blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
7eff5d0c0c1303a69b8bb751dd7c7158d79b0fd2
3417f701c2b84776b300cb827604a94f286dd048
/legacy-trunk/src/scopeclient/main.cpp
79601c612c808d77332bf2843387e3269f759027
[]
no_license
azonenberg-hk/antikernel
adbf2f69fb72e27aa0f007f117932441e7713bb0
914aff1f869f45c01b8e0eb9ecbf8cbd95025a15
refs/heads/master
2020-06-15T23:10:27.684786
2016-11-30T04:26:56
2016-11-30T04:26:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,765
cpp
/*********************************************************************************************************************** * * * ANTIKERNEL v0.1 * * * * Copyright (c) 2012-2016 Andrew D. Zonenberg * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * * following conditions are met: * * * * * Redistributions of source code must retain the above copyright notice, this list of conditions, and the * * following disclaimer. * * * * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * * following disclaimer in the documentation and/or other materials provided with the distribution. * * * * * Neither the name of the author nor the names of any contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * * THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * * POSSIBILITY OF SUCH DAMAGE. * * * ***********************************************************************************************************************/ /** @file @author Andrew D. Zonenberg @brief Program entry point */ #include "scopeclient.h" #include "MainWindow.h" #include "ScopeConnectionDialog.h" #include "../scopehal/NetworkedOscilloscope.h" #include "../scopehal/RedTinLogicAnalyzer.h" #include "../scopeprotocols/scopeprotocols.h" using namespace std; int main(int argc, char* argv[]) { int exit_code = 0; try { Gtk::Main kit(argc, argv); //Global settings unsigned short port = 0; string server = ""; string api = "redtin"; bool scripted = false; string scopename = ""; //Parse command-line arguments for(int i=1; i<argc; i++) { string s(argv[i]); if(s == "--help") { //not implemented return 0; } else if(s == "--port") port = atoi(argv[++i]); else if(s == "--server") server = argv[++i]; else if(s == "--api") api = argv[++i]; else if(s == "--scripted") scripted = true; else if(s == "--scopename") scopename = argv[++i]; else if(s == "--tty") { i++; //throw away the argument silently, for compatibility with SlurmWrapper.php } else if(s == "--version") { //not implemented //ShowVersion(); return 0; } else { printf("Unrecognized command-line argument \"%s\", use --help\n", s.c_str()); return 1; } } //Initialize the protocol decoder library ScopeProtocolStaticInit(); //Connect to the server Oscilloscope* scope = NULL; NameServer* namesrvr = NULL; if(api == "scoped") scope = new NetworkedOscilloscope(server, port); else if(api == "redtin") { //Not scripting? Normal dialog process if(!scripted) { ScopeConnectionDialog dlg(server, port); if(Gtk::RESPONSE_OK != dlg.run()) return 0; namesrvr = dlg.DetachNameServer(); scope = dlg.DetachScope(); } else { RedTinLogicAnalyzer* la = new RedTinLogicAnalyzer(server, port); namesrvr = new NameServer(&la->m_iface); la->Connect(scopename); scope = la; } } else { printf("Unrecognized API \"%s\", use --help\n", api.c_str()); return 1; } //and run the app MainWindow wnd(scope, server, port, namesrvr); kit.run(wnd); if(namesrvr) delete namesrvr; delete scope; } catch(const JtagException& ex) { printf("%s\n", ex.GetDescription().c_str()); exit_code = 1; } return exit_code; }
[ "azonenberg@drawersteak.com" ]
azonenberg@drawersteak.com
bb51085f478b4da1e87338cfe3a8611b72404e31
84f3a4a858afa1a1f494556643b29aa706292261
/OpenMoCap/src/Gui/Widgets/POIsImageWidget.h
8d262d9b53132a43682d087dd8abfb3bb7e58078
[]
no_license
jamieforth/OpenMoCap
ac44a86554983030ed0448855720084e4488d73b
45eaa1347d3160719147e52a20279937cc199837
refs/heads/master
2020-03-07T00:12:16.479130
2014-08-02T21:50:53
2014-08-02T21:50:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
535
h
#ifndef POISIMAGEWIDGET_H_ #define POISIMAGEWIDGET_H_ #include "../../Tracking/AbstractPOIFinder.h" #include "ImageWidget.h" class POIsImageWidget: public ImageWidget { Q_OBJECT public: POIsImageWidget(QWidget* parent, int width, int height); ~POIsImageWidget(); void refreshImage(IplImage* image, vector<POI> POIs); POI getPOIAtPosition(int x, int y); private: vector<POI> _POIs; void paintEvent(QPaintEvent *paintEvent); void drawPOIs(QPainter *painter); }; #endif /* POIS IMAGEWIDGET_H_ */
[ "davidflam@gmail.com@1b195e6b-c8d0-be63-1615-5224d025ebd8" ]
davidflam@gmail.com@1b195e6b-c8d0-be63-1615-5224d025ebd8
bee1e33be61b9b9a1f681931adc5749f090957b3
972e1f25b38856ee03ea966183bfa6e96d94e962
/src/globals.h
7975f05f8b8d8f94af7af161b4f25dfb5e0a0e7a
[ "Apache-2.0" ]
permissive
guoyu07/zan-thrift
0b0d58778f8096a507e9eeee98c726d310c64e0c
d6125cab364cbe72913a9aa53fce2e5cc93232c8
refs/heads/master
2021-06-21T03:33:18.118605
2017-08-18T02:40:22
2017-08-18T02:40:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,284
h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef T_GLOBALS_H #define T_GLOBALS_H #include <set> #include <queue> #include <stack> #include <vector> #include <string> #ifndef ZAN #define ZAN 1 #endif /** * This module contains all the global variables (slap on the wrist) that are * shared throughout the program. The reason for this is to facilitate simple * interaction between the parser and the rest of the program. Before calling * yyparse(), the main.cc program will make necessary adjustments to these * global variables such that the parser does the right thing and puts entries * into the right containers, etc. * */ /** * Hooray for forward declaration of types! */ class t_program; class t_scope; class t_type; /** * Parsing mode, two passes up in this gin rummy! */ enum PARSE_MODE { INCLUDES = 1, PROGRAM = 2 }; /** * Strictness level */ extern int g_strict; /** * The master program parse tree. This is accessed from within the parser code * to build up the program elements. */ extern t_program* g_program; /** * Global types for the parser to be able to reference */ extern t_type* g_type_void; extern t_type* g_type_string; extern t_type* g_type_binary; extern t_type* g_type_slist; extern t_type* g_type_bool; extern t_type* g_type_byte; extern t_type* g_type_i16; extern t_type* g_type_i32; extern t_type* g_type_i64; extern t_type* g_type_double; /** * The scope that we are currently parsing into */ extern t_scope* g_scope; /** * The parent scope to also load symbols into */ extern t_scope* g_parent_scope; /** * The prefix for the parent scope entries */ extern std::string g_parent_prefix; /** * The parsing pass that we are on. We do different things on each pass. */ extern PARSE_MODE g_parse_mode; /** * Global time string, used in formatting error messages etc. */ extern char* g_time_str; /** * The last parsed doctext comment. */ extern char* g_doctext; /** * The location of the last parsed doctext comment. */ extern int g_doctext_lineno; /** * Status of program level doctext candidate */ enum PROGDOCTEXT_STATUS { INVALID = 0, STILL_CANDIDATE = 1, // the text may or may not be the program doctext ALREADY_PROCESSED = 2, // doctext has been used and is no longer available ABSOLUTELY_SURE = 3, // this is the program doctext NO_PROGRAM_DOCTEXT = 4 // there is no program doctext }; /** * The program level doctext. Stored seperately to make parsing easier. */ extern char* g_program_doctext_candidate; extern int g_program_doctext_lineno; extern PROGDOCTEXT_STATUS g_program_doctext_status; /** * Whether or not negative field keys are accepted. * * When a field does not have a user-specified key, thrift automatically * assigns a negative value. However, this is fragile since changes to the * file may unintentionally change the key numbering, resulting in a new * protocol that is not backwards compatible. * * When g_allow_neg_field_keys is enabled, users can explicitly specify * negative keys. This way they can write a .thrift file with explicitly * specified keys that is still backwards compatible with older .thrift files * that did not specify key values. */ extern int g_allow_neg_field_keys; /** * Whether or not 64-bit constants will generate a warning. * * Some languages don't support 64-bit constants, but many do, so we can * suppress this warning for projects that don't use any non-64-bit-safe * languages. */ extern int g_allow_64bit_consts; #endif
[ "david.dai@healthbok.com" ]
david.dai@healthbok.com
7dfc3145167ecfdeadb54aa63784479fad808693
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/contrib/nrubyserver/src/ruby/nrubyrun.cc
ac6268db5006208e762eca4832e1217480b1aa8e
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
7,316
cc
#define N_IMPLEMENTS nRubyServer //-------------------------------------------------------------------- // nrubyrun.cc -- Command evaluation and passing to ruby // // (C) 2003/4 Thomas Miskiewicz tom@3d-inferno.com //-------------------------------------------------------------------- #include <stdlib.h> #include <stdio.h> #include "ruby.h" #include "ruby/nrubyserver.h" #include "kernel/nfileserver2.h" #include "kernel/narg.h" extern "C" void free_d(VALUE); extern "C" VALUE cNRoot; //-------------------------------------------------------------------- /** Prompt Pass a prompt string to the interactive shell. Will be called each frame so I omitted any fancy stuff - 02-01-04 tom created */ //-------------------------------------------------------------------- nString nRubyServer::Prompt() { // no custom prompt as Prompt will be called every frame :-( nString prompt; prompt.Append("> "); return prompt; } //-------------------------------------------------------------------- /** Run Evaluate a ruby command string Result will be empty, as any errors get printed out by ruby itself for ease of use. - 02-01-04 Tom created - 11-02-04 Tom error printing for N2 */ //-------------------------------------------------------------------- bool nRubyServer::Run(const char *cmd_str, nString& result) { result.Clear(); int ret = 0; rb_p(rb_eval_string_protect((char *)cmd_str, &ret)); if (ret) { //same as rb_p but without rb_default_rs if (this->GetFailOnError()) { n_error(RSTRING(rb_obj_as_string(rb_inspect(ruby_errinfo)))->ptr); } else { n_printf(RSTRING(rb_obj_as_string(rb_inspect(ruby_errinfo)))->ptr); //n_printf(rb_default_rs); } return false; } return true; } #ifdef __cplusplus extern "C" { #endif //-------------------------------------------------------------------- /** NArg2RubyObj Converts a nebula argument into an ruby native object. TODO implement LIST Type for nebula 2 - 02-01-04 Tom created - 11-02-04 Tom N2 args */ //-------------------------------------------------------------------- VALUE NArg2RubyObj(nArg *a) { switch (a->GetType()) { case nArg::Void: return Qnil; case nArg::Int: return INT2NUM(a->GetI()); case nArg::Float: return rb_float_new(a->GetF()); case nArg::String: return rb_str_new2(a->GetS()); case nArg::Bool: return (a->GetB()==true?Qtrue:Qfalse); case nArg::Object: { nRoot* o = (nRoot *) a->GetO(); if(o) { VALUE tst = Data_Wrap_Struct(cNRoot, 0, free_d, (void *)o); return tst; } else { return Qnil; } } //case nArg::ARGTYPE_CODE: // return rb_str_new2(a->GetC()); case nArg::List: { nArg *args; int num_args = a->GetL(args); VALUE result = rb_ary_new2(num_args); for(int i = 0; i < num_args; i++) { rb_ary_push(result, NArg2RubyObj(&args[i])); } return result; } default: return Qundef; } return Qundef; } #ifdef __cplusplus } #endif //-------------------------------------------------------------------- /** RunCommand Execute a nebula command in ruby - 02-01-04 Tom created not tested to be done - 11-02-04 Tom error printing for N2 */ //-------------------------------------------------------------------- bool nRubyServer::RunCommand(nCmd *c) { //TODO nArg *arg; int num_args = c->GetNumInArgs(); c->Rewind(); VALUE rargs = Qfalse; // handle single return args (no need to create list) if (1 == num_args) { arg = c->In(); rargs = NArg2RubyObj(arg); } else { // rargs = rb_ary_new(); // more then one in arg, create an Array int i; for (i=0; i<num_args; i++) { arg = c->In(); rb_ary_push(rargs, NArg2RubyObj(arg)); //rargs[i] = NArg2RubyObj(arg); } } //rb_str_new2(c->In()->GetS()); rb_p(rb_funcall2(rb_mKernel,rb_intern(c->In()->GetS()), num_args, &rargs)); if (NIL_P(ruby_errinfo)) { //same as rb_p but without rb_default_rs if (this->GetFailOnError()) { n_error(RSTRING(rb_obj_as_string(rb_inspect(ruby_errinfo)))->ptr); } else { n_printf(RSTRING(rb_obj_as_string(rb_inspect(ruby_errinfo)))->ptr); //n_printf(rb_default_rs); } return false; } return true; } //-------------------------------------------------------------------- /** RunScript Load and evaluate a ruby script then switches over to interactive mode Result is left empty as errors get printed out by nebula itself for ease of use. - 18-12-03 Tom created - 11-02-04 Tom error printing for N2 */ //-------------------------------------------------------------------- bool nRubyServer::RunScript(const char *fname, nString& result) { char buf[N_MAXPATH]; result.Clear(); strcpy(buf,(kernelServer->GetFileServer()->ManglePath(fname).Get())); this->print_error = true; ruby_script(buf); //rb_load_file(buf); int ret =0; rb_load_protect(rb_str_new2(buf), 0, &ret); if (ret) { //rb_p(ruby_errinfo); //same as rb_p but without rb_default_rs if (this->GetFailOnError()) { n_error(RSTRING(rb_obj_as_string(rb_inspect(ruby_errinfo)))->ptr); } else { n_printf(RSTRING(rb_obj_as_string(rb_inspect(ruby_errinfo)))->ptr); //n_printf(rb_default_rs); } return false; } return true; } //-------------------------------------------------------------------- /** @brief Invoke a Ruby function. */ bool nRubyServer::RunFunction(const char *funcName, nString& result) { nString cmdStr = funcName; cmdStr.Append("()"); return this->Run(cmdStr.Get(), result); } //-------------------------------------------------------------------- /** Trigger Check for shutdown flag - 18-12-03 Tom created - 01-05-04 Tom cleaned up */ //-------------------------------------------------------------------- bool nRubyServer::Trigger(void) { if(!GetQuitRequested() && !finished) { return true; } else { return false; } } //-------------------------------------------------------------------- // EOF //--------------------------------------------------------------------
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c
9879b56ea60860ded38f351c5831e9ddf4f3fdd5
81080d03310881ec497af7db96c8c67ac5f3a70d
/algorithms/16. 3Sum Closest/main.cpp
467dfb41547dd7d8da41099c0356e3387e2b42b1
[]
no_license
pz325/leetcode
230619b525b2cea003d581598243cd6cd4603b27
bcfa296100660ce48d58f8de8618a9157d854209
refs/heads/master
2021-09-07T23:53:12.341653
2018-03-03T17:45:53
2018-03-03T17:45:53
111,305,372
0
0
null
null
null
null
UTF-8
C++
false
false
2,914
cpp
/* Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). */ #include <vector> #include <iostream> #include <algorithm> void printV(const std::vector<int> &v) { for (auto i : v) { std::cout << i << " "; } std::cout << std::endl; } class Solution { public: int threeSumClosest(std::vector<int> &nums, int target) { std::sort(std::begin(nums), std::end(nums)); int ret = 0; int minDiff = INT_MAX; for (auto i = std::begin(nums); i < std::end(nums);) { const int valueAtI = *i; auto j = i + 1; auto k = std::end(nums) - 1; int valueAtJ = *j; int valueAtK = *k; int sum = valueAtI + valueAtJ + valueAtK; while (j < k) { const int diff = abs(sum - target); printV({valueAtI, valueAtJ, valueAtK, sum, target, diff}); if (diff < minDiff) { ret = sum; minDiff = diff; std::cout << "find new min diff at "; printV({valueAtI, valueAtJ, valueAtK, sum, target, diff}); } if (minDiff == 0) { return ret; } if ((target - sum) > 0) { std::cout << "increase j" << std::endl; ++j; // skip repeated 2nd integer while (j < k && *j == valueAtJ) { std::cout << "increase j" << std::endl; ++j; } } else { std::cout << "decrease k" << std::endl; --k; // skip repeated 3rd integer while (j < k && *k == valueAtK) { std::cout << "decrease k" << std::endl; --k; } } valueAtJ = *j; valueAtK = *k; sum = valueAtI + valueAtJ + valueAtK; } ++i; // skip repeated 1st integer while (i != std::end(nums) && *i == valueAtI) { ++i; } } return ret; } }; int main() { std::vector<int> s{1, 2, 4, 8, 16, 32, 64, 128}; const int target = 82; Solution solution; const int ret = solution.threeSumClosest(s, target); std::cout << ret << std::endl; }
[ "sg71.cherub@gmail.com" ]
sg71.cherub@gmail.com
4e9acee0ae4e885fdb2af0da510e273fe42610b0
8a9a57e3fdda2edbff4ed3d1af82e7cb7317eaa6
/sqlite/sqlite_orm/dev/operators.h
9136e6a2c19472c2a4fe4c92216495bd7d16c961
[ "BSD-3-Clause" ]
permissive
javacommons/misc5
717b4b3e3b066b2b078e13255b10cee73385e42f
a266d4d21babe0ea182264fde0c60781c79ae6dc
refs/heads/main
2023-04-06T11:18:18.696402
2021-04-28T04:05:50
2021-04-28T04:05:50
314,198,390
0
0
null
null
null
null
UTF-8
C++
false
false
7,770
h
#pragma once #include <type_traits> // std::false_type, std::true_type #include "negatable.h" namespace sqlite_orm { namespace internal { /** * Inherit this class to support arithmetic types overloading */ struct arithmetic_t {}; template<class L, class R, class... Ds> struct binary_operator : Ds... { using left_type = L; using right_type = R; left_type lhs; right_type rhs; binary_operator(left_type lhs_, right_type rhs_) : lhs(std::move(lhs_)), rhs(std::move(rhs_)) {} }; struct conc_string { operator std::string() const { return "||"; } }; /** * Result of concatenation || operator */ template<class L, class R> using conc_t = binary_operator<L, R, conc_string>; struct add_string { operator std::string() const { return "+"; } }; /** * Result of addition + operator */ template<class L, class R> using add_t = binary_operator<L, R, add_string, arithmetic_t, negatable_t>; struct sub_string { operator std::string() const { return "-"; } }; /** * Result of substitute - operator */ template<class L, class R> using sub_t = binary_operator<L, R, sub_string, arithmetic_t, negatable_t>; struct mul_string { operator std::string() const { return "*"; } }; /** * Result of multiply * operator */ template<class L, class R> using mul_t = binary_operator<L, R, mul_string, arithmetic_t, negatable_t>; struct div_string { operator std::string() const { return "/"; } }; /** * Result of divide / operator */ template<class L, class R> using div_t = binary_operator<L, R, div_string, arithmetic_t, negatable_t>; struct mod_string { operator std::string() const { return "%"; } }; /** * Result of mod % operator */ template<class L, class R> using mod_t = binary_operator<L, R, mod_string, arithmetic_t, negatable_t>; struct bitwise_shift_left_string { operator std::string() const { return "<<"; } }; /** * Result of bitwise shift left << operator */ template<class L, class R> using bitwise_shift_left_t = binary_operator<L, R, bitwise_shift_left_string, arithmetic_t, negatable_t>; struct bitwise_shift_right_string { operator std::string() const { return ">>"; } }; /** * Result of bitwise shift right >> operator */ template<class L, class R> using bitwise_shift_right_t = binary_operator<L, R, bitwise_shift_right_string, arithmetic_t, negatable_t>; struct bitwise_and_string { operator std::string() const { return "&"; } }; /** * Result of bitwise and & operator */ template<class L, class R> using bitwise_and_t = binary_operator<L, R, bitwise_and_string, arithmetic_t, negatable_t>; struct bitwise_or_string { operator std::string() const { return "|"; } }; /** * Result of bitwise or | operator */ template<class L, class R> using bitwise_or_t = binary_operator<L, R, bitwise_or_string, arithmetic_t, negatable_t>; struct bitwise_not_string { operator std::string() const { return "~"; } }; /** * Result of bitwise not ~ operator */ template<class T> struct bitwise_not_t : bitwise_not_string, arithmetic_t, negatable_t { using argument_type = T; argument_type argument; bitwise_not_t(argument_type argument_) : argument(std::move(argument_)) {} }; struct assign_string { operator std::string() const { return "="; } }; /** * Result of assign = operator */ template<class L, class R> using assign_t = binary_operator<L, R, assign_string>; /** * Assign operator traits. Common case */ template<class T> struct is_assign_t : public std::false_type {}; /** * Assign operator traits. Specialized case */ template<class L, class R> struct is_assign_t<assign_t<L, R>> : public std::true_type {}; /** * Is not an operator but a result of c(...) function. Has operator= overloaded which returns assign_t */ template<class T> struct expression_t { T t; expression_t(T t_) : t(std::move(t_)) {} template<class R> assign_t<T, R> operator=(R r) const { return {this->t, std::move(r)}; } assign_t<T, std::nullptr_t> operator=(std::nullptr_t) const { return {this->t, nullptr}; } }; } /** * Public interface for syntax sugar for columns. Example: `where(c(&User::id) == 5)` or * `storage.update(set(c(&User::name) = "Dua Lipa")); */ template<class T> internal::expression_t<T> c(T t) { return {std::move(t)}; } /** * Public interface for || concatenation operator. Example: `select(conc(&User::name, "@gmail.com"));` => SELECT * name || '@gmail.com' FROM users */ template<class L, class R> internal::conc_t<L, R> conc(L l, R r) { return {std::move(l), std::move(r)}; } /** * Public interface for + operator. Example: `select(add(&User::age, 100));` => SELECT age + 100 FROM users */ template<class L, class R> internal::add_t<L, R> add(L l, R r) { return {std::move(l), std::move(r)}; } /** * Public interface for - operator. Example: `select(add(&User::age, 1));` => SELECT age - 1 FROM users */ template<class L, class R> internal::sub_t<L, R> sub(L l, R r) { return {std::move(l), std::move(r)}; } template<class L, class R> internal::mul_t<L, R> mul(L l, R r) { return {std::move(l), std::move(r)}; } template<class L, class R> internal::div_t<L, R> div(L l, R r) { return {std::move(l), std::move(r)}; } template<class L, class R> internal::mod_t<L, R> mod(L l, R r) { return {std::move(l), std::move(r)}; } template<class L, class R> internal::bitwise_shift_left_t<L, R> bitwise_shift_left(L l, R r) { return {std::move(l), std::move(r)}; } template<class L, class R> internal::bitwise_shift_right_t<L, R> bitwise_shift_right(L l, R r) { return {std::move(l), std::move(r)}; } template<class L, class R> internal::bitwise_and_t<L, R> bitwise_and(L l, R r) { return {std::move(l), std::move(r)}; } template<class L, class R> internal::bitwise_or_t<L, R> bitwise_or(L l, R r) { return {std::move(l), std::move(r)}; } template<class T> internal::bitwise_not_t<T> bitwise_not(T t) { return {std::move(t)}; } template<class L, class R> internal::assign_t<L, R> assign(L l, R r) { return {std::move(l), std::move(r)}; } }
[ "javacommons@gmail.com" ]
javacommons@gmail.com
36cabe42bed37d41dc61cb43f357b2bac5e27de6
188dbc4be7773a160d4ae456d9822d278ed60ac4
/C++ primer plus/第二章/2.2/1.2.cpp
91c82667ea9ad7e97dd9a124fca3a57e4fef2159
[]
no_license
lyb1234567/C-plus-plus-
9ec8e66f460a158d9b7f51e0853a7019b19fcddc
11b06de5620d789d0df5be99f0800d4dd016e23b
refs/heads/master
2023-08-25T16:05:45.317462
2021-09-26T09:41:02
2021-09-26T09:41:02
386,282,954
0
0
null
null
null
null
UTF-8
C++
false
false
271
cpp
#include<iostream> using namespace std; int longmulti(int); int main() { int long_unit; cout << "Input a unit of long:"; cin >> long_unit; cout << "The output will be:" << longmulti(long_unit); return 0; } int longmulti(int long_unit) { return 220 * long_unit; }
[ "1536635817@qq.com" ]
1536635817@qq.com
e11a36841a8507cc212d327ca9aa8a0bb15e6892
a26aa08a21c299f0a5725b0c46f0321a88d2593d
/GRender/GRender/Render/Core/Image.cpp
b5ba73eb50f58c400930fd1e69201edede4fee94
[]
no_license
GavinZL/GRender
387c856ffa20cfd076111385740284574b8bbfa3
46b84801e867c446e3b8b6b7be235bc6d2f82380
refs/heads/master
2021-08-29T23:30:49.341942
2017-12-15T08:51:50
2017-12-15T08:51:50
113,120,953
0
0
null
null
null
null
UTF-8
C++
false
false
81,984
cpp
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org 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 "Image.h" #include <string> #include <ctype.h> #include <cstdint> #include "../Comm/Utils.h" //#include "base/CCData.h" //#include "base/ccConfig.h" // CC_USE_JPEG, CC_USE_TIFF, CC_USE_WEBP extern "C" { // To resolve link error when building 32bits with Xcode 6. // More information please refer to the discussion in https://github.com/cocos2d/cocos2d-x/pull/6986 #if defined (__unix) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) #ifndef __ENABLE_COMPATIBILITY_WITH_UNIX_2003__ #define __ENABLE_COMPATIBILITY_WITH_UNIX_2003__ #include <stdio.h> FILE *fopen$UNIX2003( const char *filename, const char *mode ) { return fopen(filename, mode); } size_t fwrite$UNIX2003( const void *a, size_t b, size_t c, FILE *d ) { return fwrite(a, b, c, d); } char *strerror$UNIX2003( int errnum ) { return strerror(errnum); } #endif #endif #include "png.h" #define CC_USE_JPEG 1 #define CC_USE_TIFF 1 #if CC_USE_TIFF #include "tiffio.h" #endif //CC_USE_TIFF //#include "../base/etc1.h" #if CC_USE_JPEG #include "jpeglib.h" #endif // CC_USE_JPEG } //#include "../base/s3tc.h" //#include "../base/atitc.h" //#include "../base/pvr.h" //#include "../base/TGAlib.h" //#if (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) && (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) //#if CC_USE_WEBP //#include "decode.h" //#endif // CC_USE_WEBP //#endif //#include "base/ccMacros.h" //#include "CCCommon.h" //#include "CCStdC.h" //#include "CCFileUtils.h" //#include "base/CCConfiguration.h" //#include "base/ccUtils.h" //#include "base/ZipUtils.h" //#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) //#include "android/CCFileUtils-android.h" //#endif #define CC_GL_ATC_RGB_AMD 0x8C92 #define CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93 #define CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE USING_NAMESPACE_G ////////////////////////////////////////////////////////////////////////// //struct and data for pvr structure namespace { static const int PVR_TEXTURE_FLAG_TYPE_MASK = 0xff; static bool _PVRHaveAlphaPremultiplied = false; // Values taken from PVRTexture.h from http://www.imgtec.com enum class PVR2TextureFlag { Mipmap = (1<<8), // has mip map levels Twiddle = (1<<9), // is twiddled Bumpmap = (1<<10), // has normals encoded for a bump map Tiling = (1<<11), // is bordered for tiled pvr Cubemap = (1<<12), // is a cubemap/skybox FalseMipCol = (1<<13), // are there false colored MIP levels Volume = (1<<14), // is this a volume texture Alpha = (1<<15), // v2.1 is there transparency info in the texture VerticalFlip = (1<<16), // v2.1 is the texture vertically flipped }; enum class PVR3TextureFlag { PremultipliedAlpha = (1<<1) // has premultiplied alpha }; static const char gPVRTexIdentifier[5] = "PVR!"; // v2 enum class PVR2TexturePixelFormat : unsigned char { RGBA4444 = 0x10, RGBA5551, RGBA8888, RGB565, RGB555, // unsupported RGB888, I8, AI88, PVRTC2BPP_RGBA, PVRTC4BPP_RGBA, BGRA8888, A8, }; // v3 enum class PVR3TexturePixelFormat : uint64_t { PVRTC2BPP_RGB = 0ULL, PVRTC2BPP_RGBA = 1ULL, PVRTC4BPP_RGB = 2ULL, PVRTC4BPP_RGBA = 3ULL, PVRTC2_2BPP_RGBA = 4ULL, PVRTC2_4BPP_RGBA = 5ULL, ETC1 = 6ULL, DXT1 = 7ULL, DXT2 = 8ULL, DXT3 = 9ULL, DXT4 = 10ULL, DXT5 = 11ULL, BC1 = 7ULL, BC2 = 9ULL, BC3 = 11ULL, BC4 = 12ULL, BC5 = 13ULL, BC6 = 14ULL, BC7 = 15ULL, UYVY = 16ULL, YUY2 = 17ULL, BW1bpp = 18ULL, R9G9B9E5 = 19ULL, RGBG8888 = 20ULL, GRGB8888 = 21ULL, ETC2_RGB = 22ULL, ETC2_RGBA = 23ULL, ETC2_RGBA1 = 24ULL, EAC_R11_Unsigned = 25ULL, EAC_R11_Signed = 26ULL, EAC_RG11_Unsigned = 27ULL, EAC_RG11_Signed = 28ULL, BGRA8888 = 0x0808080861726762ULL, RGBA8888 = 0x0808080861626772ULL, RGBA4444 = 0x0404040461626772ULL, RGBA5551 = 0x0105050561626772ULL, RGB565 = 0x0005060500626772ULL, RGB888 = 0x0008080800626772ULL, A8 = 0x0000000800000061ULL, L8 = 0x000000080000006cULL, LA88 = 0x000008080000616cULL, }; // v2 typedef const std::map<PVR2TexturePixelFormat, Texture2D::PixelFormat> _pixel2_formathash; static const _pixel2_formathash::value_type v2_pixel_formathash_value[] = { _pixel2_formathash::value_type(PVR2TexturePixelFormat::BGRA8888, Texture2D::PixelFormat::BGRA8888), _pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA8888, Texture2D::PixelFormat::RGBA8888), _pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA4444, Texture2D::PixelFormat::RGBA4444), _pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA5551, Texture2D::PixelFormat::RGB5A1), _pixel2_formathash::value_type(PVR2TexturePixelFormat::RGB565, Texture2D::PixelFormat::RGB565), _pixel2_formathash::value_type(PVR2TexturePixelFormat::RGB888, Texture2D::PixelFormat::RGB888), _pixel2_formathash::value_type(PVR2TexturePixelFormat::A8, Texture2D::PixelFormat::A8), _pixel2_formathash::value_type(PVR2TexturePixelFormat::I8, Texture2D::PixelFormat::I8), _pixel2_formathash::value_type(PVR2TexturePixelFormat::AI88, Texture2D::PixelFormat::AI88), _pixel2_formathash::value_type(PVR2TexturePixelFormat::PVRTC2BPP_RGBA, Texture2D::PixelFormat::PVRTC2A), _pixel2_formathash::value_type(PVR2TexturePixelFormat::PVRTC4BPP_RGBA, Texture2D::PixelFormat::PVRTC4A), }; static const int PVR2_MAX_TABLE_ELEMENTS = sizeof(v2_pixel_formathash_value) / sizeof(v2_pixel_formathash_value[0]); static const _pixel2_formathash v2_pixel_formathash(v2_pixel_formathash_value, v2_pixel_formathash_value + PVR2_MAX_TABLE_ELEMENTS); // v3 typedef const std::map<PVR3TexturePixelFormat, Texture2D::PixelFormat> _pixel3_formathash; static _pixel3_formathash::value_type v3_pixel_formathash_value[] = { _pixel3_formathash::value_type(PVR3TexturePixelFormat::BGRA8888, Texture2D::PixelFormat::BGRA8888), _pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA8888, Texture2D::PixelFormat::RGBA8888), _pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA4444, Texture2D::PixelFormat::RGBA4444), _pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA5551, Texture2D::PixelFormat::RGB5A1), _pixel3_formathash::value_type(PVR3TexturePixelFormat::RGB565, Texture2D::PixelFormat::RGB565), _pixel3_formathash::value_type(PVR3TexturePixelFormat::RGB888, Texture2D::PixelFormat::RGB888), _pixel3_formathash::value_type(PVR3TexturePixelFormat::A8, Texture2D::PixelFormat::A8), _pixel3_formathash::value_type(PVR3TexturePixelFormat::L8, Texture2D::PixelFormat::I8), _pixel3_formathash::value_type(PVR3TexturePixelFormat::LA88, Texture2D::PixelFormat::AI88), _pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC2BPP_RGB, Texture2D::PixelFormat::PVRTC2), _pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC2BPP_RGBA, Texture2D::PixelFormat::PVRTC2A), _pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC4BPP_RGB, Texture2D::PixelFormat::PVRTC4), _pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC4BPP_RGBA, Texture2D::PixelFormat::PVRTC4A), _pixel3_formathash::value_type(PVR3TexturePixelFormat::ETC1, Texture2D::PixelFormat::ETC), }; static const int PVR3_MAX_TABLE_ELEMENTS = sizeof(v3_pixel_formathash_value) / sizeof(v3_pixel_formathash_value[0]); static const _pixel3_formathash v3_pixel_formathash(v3_pixel_formathash_value, v3_pixel_formathash_value + PVR3_MAX_TABLE_ELEMENTS); typedef struct _PVRTexHeader { unsigned int headerLength; unsigned int height; unsigned int width; unsigned int numMipmaps; unsigned int flags; unsigned int dataLength; unsigned int bpp; unsigned int bitmaskRed; unsigned int bitmaskGreen; unsigned int bitmaskBlue; unsigned int bitmaskAlpha; unsigned int pvrTag; unsigned int numSurfs; } PVRv2TexHeader; #ifdef _MSC_VER #pragma pack(push,1) #endif typedef struct { uint32_t version; uint32_t flags; uint64_t pixelFormat; uint32_t colorSpace; uint32_t channelType; uint32_t height; uint32_t width; uint32_t depth; uint32_t numberOfSurfaces; uint32_t numberOfFaces; uint32_t numberOfMipmaps; uint32_t metadataLength; #ifdef _MSC_VER } PVRv3TexHeader; #pragma pack(pop) #else } __attribute__((packed)) PVRv3TexHeader; #endif } //pvr structure end ////////////////////////////////////////////////////////////////////////// //struct and data for s3tc(dds) struct namespace { struct DDColorKey { uint32_t colorSpaceLowValue; uint32_t colorSpaceHighValue; }; struct DDSCaps { uint32_t caps; uint32_t caps2; uint32_t caps3; uint32_t caps4; }; struct DDPixelFormat { uint32_t size; uint32_t flags; uint32_t fourCC; uint32_t RGBBitCount; uint32_t RBitMask; uint32_t GBitMask; uint32_t BBitMask; uint32_t ABitMask; }; struct DDSURFACEDESC2 { uint32_t size; uint32_t flags; uint32_t height; uint32_t width; union { uint32_t pitch; uint32_t linearSize; } DUMMYUNIONNAMEN1; union { uint32_t backBufferCount; uint32_t depth; } DUMMYUNIONNAMEN5; union { uint32_t mipMapCount; uint32_t refreshRate; uint32_t srcVBHandle; } DUMMYUNIONNAMEN2; uint32_t alphaBitDepth; uint32_t reserved; uint32_t surface; union { DDColorKey ddckCKDestOverlay; uint32_t emptyFaceColor; } DUMMYUNIONNAMEN3; DDColorKey ddckCKDestBlt; DDColorKey ddckCKSrcOverlay; DDColorKey ddckCKSrcBlt; union { DDPixelFormat ddpfPixelFormat; uint32_t FVF; } DUMMYUNIONNAMEN4; DDSCaps ddsCaps; uint32_t textureStage; } ; #pragma pack(push,1) struct S3TCTexHeader { char fileCode[4]; DDSURFACEDESC2 ddsd; }; #pragma pack(pop) } //s3tc struct end ////////////////////////////////////////////////////////////////////////// //struct and data for atitc(ktx) struct namespace { struct ATITCTexHeader { //HEADER char identifier[12]; uint32_t endianness; uint32_t glType; uint32_t glTypeSize; uint32_t glFormat; uint32_t glInternalFormat; uint32_t glBaseInternalFormat; uint32_t pixelWidth; uint32_t pixelHeight; uint32_t pixelDepth; uint32_t numberOfArrayElements; uint32_t numberOfFaces; uint32_t numberOfMipmapLevels; uint32_t bytesOfKeyValueData; }; } //atittc struct end ////////////////////////////////////////////////////////////////////////// namespace { typedef struct { const unsigned char * data; ssize_t size; int offset; }tImageSource; static void pngReadCallback(png_structp png_ptr, png_bytep data, png_size_t length) { tImageSource* isource = (tImageSource*)png_get_io_ptr(png_ptr); if((int)(isource->offset + length) <= isource->size) { memcpy(data, isource->data+isource->offset, length); isource->offset += length; } else { png_error(png_ptr, "pngReaderCallback failed"); } } } Texture2D::PixelFormat getDevicePixelFormat(Texture2D::PixelFormat format) { switch (format) { case Texture2D::PixelFormat::PVRTC4: case Texture2D::PixelFormat::PVRTC4A: case Texture2D::PixelFormat::PVRTC2: case Texture2D::PixelFormat::PVRTC2A: //if(Configuration::getInstance()->supportsPVRTC()) if (false) return format; else return Texture2D::PixelFormat::RGBA8888; case Texture2D::PixelFormat::ETC: //if(Configuration::getInstance()->supportsETC()) if (false) return format; else return Texture2D::PixelFormat::RGB888; default: return format; } } ////////////////////////////////////////////////////////////////////////// // Implement Image ////////////////////////////////////////////////////////////////////////// Image::Image() : _data(nullptr) , _dataLen(0) , _width(0) , _height(0) , _unpack(false) , _fileType(Format::UNKOWN) , _renderFormat(Texture2D::PixelFormat::NONE) , _numberOfMipmaps(0) , _hasPremultipliedAlpha(true) { } Image::~Image() { if (_unpack) { for (int i = 0; i < _numberOfMipmaps; ++i) delete _mipmaps[i].address; //CC_SAFE_DELETE_ARRAY(_mipmaps[i].address); } else delete _data; //CC_SAFE_FREE(_data); } unsigned char* Image::readDataFromFile(const std::string& file, unsigned int& len) { unsigned char* buffer = nullptr; size_t size = 0; size_t readsize; FILE *fp = fopen(file.c_str(), "rb"); if (!fp){ return 0; } fseek(fp, 0, SEEK_END); size = ftell(fp); fseek(fp, 0, SEEK_SET); buffer = (unsigned char*)malloc(sizeof(unsigned char) * size); readsize = fread(buffer, sizeof(unsigned char), size, fp); fclose(fp); len = readsize; return buffer; } bool Image::initWithImageFile(const std::string& path) { bool ret = false; _filePath = path;//FileUtils::getInstance()->fullPathForFilename(path); #ifdef EMSCRIPTEN // Emscripten includes a re-implementation of SDL that uses HTML5 canvas // operations underneath. Consequently, loading images via IMG_Load (an SDL // API) will be a lot faster than running libpng et al as compiled with // Emscripten. SDL_Surface *iSurf = IMG_Load(fullPath.c_str()); int size = 4 * (iSurf->w * iSurf->h); ret = initWithRawData((const unsigned char*)iSurf->pixels, size, iSurf->w, iSurf->h, 8, true); unsigned int *tmp = (unsigned int *)_data; int nrPixels = iSurf->w * iSurf->h; for(int i = 0; i < nrPixels; i++) { unsigned char *p = _data + i * 4; tmp[i] = CC_RGB_PREMULTIPLY_ALPHA( p[0], p[1], p[2], p[3] ); } SDL_FreeSurface(iSurf); #else //Data data = FileUtils::getInstance()->getDataFromFile(_filePath); unsigned char* data = nullptr; unsigned int dlen = 0; data = readDataFromFile(_filePath, dlen); if (data != nullptr) { ret = initWithImageData(data, dlen); } #endif // EMSCRIPTEN return ret; } bool Image::initWithImageFileThreadSafe(const std::string& fullpath) { bool ret = false; _filePath = fullpath; //Data data = FileUtils::getInstance()->getDataFromFile(fullpath); //if (!data.isNull()) //{ // unsigned int uSize = data.getSize(); // this->ImageDataDecode(data.getBytes(), uSize); // ret = initWithImageData(data.getBytes(), uSize); //} return ret; } bool Image::initWithImageData(const unsigned char * data, ssize_t dataLen) { bool ret = false; if (!data || dataLen <= 0){ return false; } do { unsigned char* unpackedData = nullptr; ssize_t unpackedLen = 0; ////detecgt and unzip the compress file //if (ZipUtils::isCCZBuffer(data, dataLen)) //{ // unpackedLen = ZipUtils::inflateCCZBuffer(data, dataLen, &unpackedData); //} //else if (ZipUtils::isGZipBuffer(data, dataLen)) //{ // unpackedLen = ZipUtils::inflateMemory(const_cast<unsigned char*>(data), dataLen, &unpackedData); //} //else { unpackedData = const_cast<unsigned char*>(data); unpackedLen = dataLen; } _fileType = detectFormat(unpackedData, unpackedLen); switch (_fileType) { case Format::PNG: ret = initWithPngData(unpackedData, unpackedLen); break; case Format::JPG: ret = initWithJpgData(unpackedData, unpackedLen); break; case Format::TIFF: ret = initWithTiffData(unpackedData, unpackedLen); break; case Format::WEBP: ret = initWithWebpData(unpackedData, unpackedLen); break; case Format::PVR: ret = initWithPVRData(unpackedData, unpackedLen); break; case Format::ETC: ret = initWithETCData(unpackedData, unpackedLen); break; case Format::S3TC: ret = initWithS3TCData(unpackedData, unpackedLen); break; case Format::ATITC: ret = initWithATITCData(unpackedData, unpackedLen); break; default: { //// load and detect image format //tImageTGA* tgaData = tgaLoadBuffer(unpackedData, unpackedLen); // //if (tgaData != nullptr && tgaData->status == TGA_OK) //{ // ret = initWithTGAData(tgaData); //} //else //{ // CCAssert(false, "unsupport image format!"); //} // //free(tgaData); break; } } if(unpackedData != data) { free(unpackedData); } } while (0); return ret; } bool Image::isPng(const unsigned char * data, ssize_t dataLen) { if (dataLen <= 8) { return false; } static const unsigned char PNG_SIGNATURE[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a}; return memcmp(PNG_SIGNATURE, data, sizeof(PNG_SIGNATURE)) == 0; } bool Image::isEtc(const unsigned char * data, ssize_t dataLen) { return false;//etc1_pkm_is_valid((etc1_byte*)data) ? true : false; } bool Image::isS3TC(const unsigned char * data, ssize_t dataLen) { S3TCTexHeader *header = (S3TCTexHeader *)data; if (strncmp(header->fileCode, "DDS", 3) != 0) { G::log("cocos2d: the file is not a dds file!"); return false; } return true; } bool Image::isATITC(const unsigned char *data, ssize_t dataLen) { ATITCTexHeader *header = (ATITCTexHeader *)data; if (strncmp(&header->identifier[1], "KTX", 3) != 0) { G::log("cocos3d: the file is not a ktx file!"); return false; } return true; } bool Image::isJpg(const unsigned char * data, ssize_t dataLen) { if (dataLen <= 4) { return false; } static const unsigned char JPG_SOI[] = {0xFF, 0xD8}; return memcmp(data, JPG_SOI, 2) == 0; } bool Image::isTiff(const unsigned char * data, ssize_t dataLen) { if (dataLen <= 4) { return false; } static const char* TIFF_II = "II"; static const char* TIFF_MM = "MM"; return (memcmp(data, TIFF_II, 2) == 0 && *(static_cast<const unsigned char*>(data) + 2) == 42 && *(static_cast<const unsigned char*>(data) + 3) == 0) || (memcmp(data, TIFF_MM, 2) == 0 && *(static_cast<const unsigned char*>(data) + 2) == 0 && *(static_cast<const unsigned char*>(data) + 3) == 42); } bool Image::isWebp(const unsigned char * data, ssize_t dataLen) { if (dataLen <= 12) { return false; } static const char* WEBP_RIFF = "RIFF"; static const char* WEBP_WEBP = "WEBP"; return memcmp(data, WEBP_RIFF, 4) == 0 && memcmp(static_cast<const unsigned char*>(data) + 8, WEBP_WEBP, 4) == 0; } bool Image::isPvr(const unsigned char * data, ssize_t dataLen) { if (static_cast<size_t>(dataLen) < sizeof(PVRv2TexHeader) || static_cast<size_t>(dataLen) < sizeof(PVRv3TexHeader)) { return false; } const PVRv2TexHeader* headerv2 = static_cast<const PVRv2TexHeader*>(static_cast<const void*>(data)); const PVRv3TexHeader* headerv3 = static_cast<const PVRv3TexHeader*>(static_cast<const void*>(data)); return false;//memcmp(&headerv2->pvrTag, gPVRTexIdentifier, strlen(gPVRTexIdentifier)) == 0 || CC_SWAP_INT32_BIG_TO_HOST(headerv3->version) == 0x50565203; } Image::Format Image::detectFormat(const unsigned char * data, ssize_t dataLen) { if (isPng(data, dataLen)) { return Format::PNG; } else if (isJpg(data, dataLen)) { return Format::JPG; } else if (isTiff(data, dataLen)) { return Format::TIFF; } else if (isWebp(data, dataLen)) { return Format::WEBP; } else if (isPvr(data, dataLen)) { return Format::PVR; } else if (isEtc(data, dataLen)) { return Format::ETC; } else if (isS3TC(data, dataLen)) { return Format::S3TC; } else if (isATITC(data, dataLen)) { return Format::ATITC; } else { return Format::UNKOWN; } } int Image::getBitPerPixel() { return Texture2D::getPixelFormatInfoMap().at(_renderFormat).bpp; } bool Image::hasAlpha() { return Texture2D::getPixelFormatInfoMap().at(_renderFormat).alpha; } bool Image::isCompressed() { return Texture2D::getPixelFormatInfoMap().at(_renderFormat).compressed; } namespace { /* * ERROR HANDLING: * * The JPEG library's standard error handler (jerror.c) is divided into * several "methods" which you can override individually. This lets you * adjust the behavior without duplicating a lot of code, which you might * have to update with each future release. * * We override the "error_exit" method so that control is returned to the * library's caller when a fatal error occurs, rather than calling exit() * as the standard error_exit method does. * * We use C's setjmp/longjmp facility to return control. This means that the * routine which calls the JPEG library must first execute a setjmp() call to * establish the return point. We want the replacement error_exit to do a * longjmp(). But we need to make the setjmp buffer accessible to the * error_exit routine. To do this, we make a private extension of the * standard JPEG error handler object. (If we were using C++, we'd say we * were making a subclass of the regular error handler.) * * Here's the extended error handler struct: */ #if CC_USE_JPEG struct MyErrorMgr { struct jpeg_error_mgr pub; /* "public" fields */ jmp_buf setjmp_buffer; /* for return to caller */ }; typedef struct MyErrorMgr * MyErrorPtr; /* * Here's the routine that will replace the standard error_exit method: */ METHODDEF(void) myErrorExit(j_common_ptr cinfo) { /* cinfo->err really points to a MyErrorMgr struct, so coerce pointer */ MyErrorPtr myerr = (MyErrorPtr) cinfo->err; /* Always display the message. */ /* We could postpone this until after returning, if we chose. */ /* internal message function cann't show error message in some platforms, so we rewrite it here. * edit it if has version confilict. */ //(*cinfo->err->output_message) (cinfo); char buffer[JMSG_LENGTH_MAX]; (*cinfo->err->format_message) (cinfo, buffer); G::log("jpeg error: %s", buffer); /* Return control to the setjmp point */ longjmp(myerr->setjmp_buffer, 1); } #endif // CC_USE_JPEG } bool Image::initWithJpgData(const unsigned char * data, ssize_t dataLen) { #if CC_USE_JPEG /* these are standard libjpeg structures for reading(decompression) */ struct jpeg_decompress_struct cinfo; /* We use our private extension JPEG error handler. * Note that this struct must live as long as the main JPEG parameter * struct, to avoid dangling-pointer problems. */ struct MyErrorMgr jerr; /* libjpeg data structure for storing one row, that is, scanline of an image */ JSAMPROW row_pointer[1] = {0}; unsigned long location = 0; bool ret = false; do { /* We set up the normal JPEG error routines, then override error_exit. */ cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = myErrorExit; /* Establish the setjmp return context for MyErrorExit to use. */ if (setjmp(jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. * We need to clean up the JPEG object, close the input file, and return. */ jpeg_destroy_decompress(&cinfo); break; } /* setup decompression process and source, then read JPEG header */ jpeg_create_decompress( &cinfo ); #ifndef CC_TARGET_QT5 jpeg_mem_src(&cinfo, const_cast<unsigned char*>(data), dataLen); #endif /* CC_TARGET_QT5 */ /* reading the image header which contains image information */ #if (JPEG_LIB_VERSION >= 90) // libjpeg 0.9 adds stricter types. jpeg_read_header(&cinfo, TRUE); #else jpeg_read_header(&cinfo, TRUE); #endif // we only support RGB or grayscale if (cinfo.jpeg_color_space == JCS_GRAYSCALE) { _renderFormat = Texture2D::PixelFormat::I8; }else { cinfo.out_color_space = JCS_RGB; _renderFormat = Texture2D::PixelFormat::RGB888; } /* Start decompression jpeg here */ jpeg_start_decompress( &cinfo ); /* init image info */ _width = cinfo.output_width; _height = cinfo.output_height; _hasPremultipliedAlpha = false; _dataLen = cinfo.output_width*cinfo.output_height*cinfo.output_components; _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char))); if (!_data){ break; } /* now actually read the jpeg into the raw buffer */ /* read one scan line at a time */ while (cinfo.output_scanline < cinfo.output_height) { row_pointer[0] = _data + location; location += cinfo.output_width*cinfo.output_components; jpeg_read_scanlines(&cinfo, row_pointer, 1); } /* When read image file with broken data, jpeg_finish_decompress() may cause error. * Besides, jpeg_destroy_decompress() shall deallocate and release all memory associated * with the decompression object. * So it doesn't need to call jpeg_finish_decompress(). */ //jpeg_finish_decompress( &cinfo ); jpeg_destroy_decompress( &cinfo ); /* wrap up decompression, destroy objects, free pointers and close open files */ ret = true; } while (0); return ret; #else return false; #endif // CC_USE_JPEG } bool Image::initWithPngData(const unsigned char * data, ssize_t dataLen) { // length of bytes to check if it is a valid png file #define PNGSIGSIZE 8 bool ret = false; png_byte header[PNGSIGSIZE] = {0}; png_structp png_ptr = 0; png_infop info_ptr = 0; do { // png header len is 8 bytes //CC_BREAK_IF(dataLen < PNGSIGSIZE); if (dataLen < PNGSIGSIZE){ G::log("png data len < PNGSIGSIZE(8)"); break; } // check the data is png or not memcpy(header, data, PNGSIGSIZE); if (png_sig_cmp(header, 0, PNGSIGSIZE)){ break; } // init png_struct png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0); if (!png_ptr){ break; } // init png_info info_ptr = png_create_info_struct(png_ptr); if(!info_ptr){ break; } #if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA && CC_TARGET_PLATFORM != CC_PLATFORM_NACL) CC_BREAK_IF(setjmp(png_jmpbuf(png_ptr))); #endif // set the read call back function tImageSource imageSource; imageSource.data = (unsigned char*)data; imageSource.size = dataLen; imageSource.offset = 0; png_set_read_fn(png_ptr, &imageSource, pngReadCallback); // read png header info // read png file info png_read_info(png_ptr, info_ptr); _width = png_get_image_width(png_ptr, info_ptr); _height = png_get_image_height(png_ptr, info_ptr); png_byte bit_depth = png_get_bit_depth(png_ptr, info_ptr); png_uint_32 color_type = png_get_color_type(png_ptr, info_ptr); //G::log("color type %u", color_type); // force palette images to be expanded to 24-bit RGB // it may include alpha channel if (color_type == PNG_COLOR_TYPE_PALETTE) { png_set_palette_to_rgb(png_ptr); } // low-bit-depth grayscale images are to be expanded to 8 bits if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) { bit_depth = 8; png_set_expand_gray_1_2_4_to_8(png_ptr); } // expand any tRNS chunk data into a full alpha channel if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { png_set_tRNS_to_alpha(png_ptr); } // reduce images with 16-bit samples to 8 bits if (bit_depth == 16) { png_set_strip_16(png_ptr); } // Expanded earlier for grayscale, now take care of palette and rgb if (bit_depth < 8) { png_set_packing(png_ptr); } // update info png_read_update_info(png_ptr, info_ptr); bit_depth = png_get_bit_depth(png_ptr, info_ptr); color_type = png_get_color_type(png_ptr, info_ptr); switch (color_type) { case PNG_COLOR_TYPE_GRAY: _renderFormat = Texture2D::PixelFormat::I8; break; case PNG_COLOR_TYPE_GRAY_ALPHA: _renderFormat = Texture2D::PixelFormat::AI88; break; case PNG_COLOR_TYPE_RGB: _renderFormat = Texture2D::PixelFormat::RGB888; break; case PNG_COLOR_TYPE_RGB_ALPHA: _renderFormat = Texture2D::PixelFormat::RGBA8888; break; default: break; } // read png data png_size_t rowbytes; png_bytep* row_pointers = (png_bytep*)malloc( sizeof(png_bytep) * _height ); rowbytes = png_get_rowbytes(png_ptr, info_ptr); _dataLen = rowbytes * _height; _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char))); if (!_data) { if (row_pointers != nullptr) { free(row_pointers); } break; } for (unsigned short i = 0; i < _height; ++i) { row_pointers[i] = _data + i*rowbytes; } png_read_image(png_ptr, row_pointers); png_read_end(png_ptr, nullptr); // premultiplied alpha for RGBA8888 if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) { premultipliedAlpha(); } else { _hasPremultipliedAlpha = false; } if (row_pointers != nullptr) { free(row_pointers); } ret = true; } while (0); if (png_ptr) { png_destroy_read_struct(&png_ptr, (info_ptr) ? &info_ptr : 0, 0); } return ret; } #if CC_USE_TIFF namespace { static tmsize_t tiffReadProc(thandle_t fd, void* buf, tmsize_t size) { tImageSource* isource = (tImageSource*)fd; uint8* ma; uint64 mb; unsigned long n; unsigned long o; tmsize_t p; ma=(uint8*)buf; mb=size; p=0; while (mb>0) { n=0x80000000UL; if ((uint64)n>mb) n=(unsigned long)mb; if ((int)(isource->offset + n) <= isource->size) { memcpy(ma, isource->data+isource->offset, n); isource->offset += n; o = n; } else { return 0; } ma+=o; mb-=o; p+=o; if (o!=n) { break; } } return p; } static tmsize_t tiffWriteProc(thandle_t fd, void* buf, tmsize_t size) { //CC_UNUSED_PARAM(fd); //CC_UNUSED_PARAM(buf); //CC_UNUSED_PARAM(size); fd; buf; size; return 0; } static uint64 tiffSeekProc(thandle_t fd, uint64 off, int whence) { tImageSource* isource = (tImageSource*)fd; uint64 ret = -1; do { if (whence == SEEK_SET) { if (off >= (uint64)isource->size){ break; } ret = isource->offset = (uint32)off; } else if (whence == SEEK_CUR) { if (isource->offset + off >= (uint64)isource->size){ break; } ret = isource->offset += (uint32)off; } else if (whence == SEEK_END) { if (off >= (uint64)isource->size){ break; } ret = isource->offset = (uint32)(isource->size-1 - off); } else { if (off >= (uint64)isource->size){ break; } ret = isource->offset = (uint32)off; } } while (0); return ret; } static uint64 tiffSizeProc(thandle_t fd) { tImageSource* imageSrc = (tImageSource*)fd; return imageSrc->size; } static int tiffCloseProc(thandle_t fd) { //CC_UNUSED_PARAM(fd); fd; return 0; } static int tiffMapProc(thandle_t fd, void** base, toff_t* size) { //CC_UNUSED_PARAM(fd); //CC_UNUSED_PARAM(base); //CC_UNUSED_PARAM(size); fd; base; size; return 0; } static void tiffUnmapProc(thandle_t fd, void* base, toff_t size) { //CC_UNUSED_PARAM(fd); //CC_UNUSED_PARAM(base); //CC_UNUSED_PARAM(size); fd; base; size; } } #endif // CC_USE_TIFF bool Image::initWithTiffData(const unsigned char * data, ssize_t dataLen) { #if CC_USE_TIFF bool ret = false; do { // set the read call back function tImageSource imageSource; imageSource.data = data; imageSource.size = dataLen; imageSource.offset = 0; TIFF* tif = TIFFClientOpen("file.tif", "r", (thandle_t)&imageSource, tiffReadProc, tiffWriteProc, tiffSeekProc, tiffCloseProc, tiffSizeProc, tiffMapProc, tiffUnmapProc); if (nullptr == tif){ break; } uint32 w = 0, h = 0; uint16 bitsPerSample = 0, samplePerPixel = 0, planarConfig = 0; size_t npixels = 0; TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h); TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bitsPerSample); TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samplePerPixel); TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &planarConfig); npixels = w * h; _renderFormat = Texture2D::PixelFormat::RGBA8888; _width = w; _height = h; _dataLen = npixels * sizeof (uint32); _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char))); uint32* raster = (uint32*) _TIFFmalloc(npixels * sizeof (uint32)); if (raster != nullptr) { if (TIFFReadRGBAImageOriented(tif, w, h, raster, ORIENTATION_TOPLEFT, 0)) { /* the raster data is pre-multiplied by the alpha component after invoking TIFFReadRGBAImageOriented*/ _hasPremultipliedAlpha = true; memcpy(_data, raster, npixels*sizeof (uint32)); } _TIFFfree(raster); } TIFFClose(tif); ret = true; } while (0); return ret; #else G::log("tiff is not enabled, please enalbe it in ccConfig.h"); return false; #endif } namespace { bool testFormatForPvr2TCSupport(PVR2TexturePixelFormat format) { return true; } bool testFormatForPvr3TCSupport(PVR3TexturePixelFormat format) { switch (format) { case PVR3TexturePixelFormat::DXT1: case PVR3TexturePixelFormat::DXT3: case PVR3TexturePixelFormat::DXT5: return false;//Configuration::getInstance()->supportsS3TC(); case PVR3TexturePixelFormat::BGRA8888: return true;//Configuration::getInstance()->supportsBGRA8888(); case PVR3TexturePixelFormat::PVRTC2BPP_RGB: case PVR3TexturePixelFormat::PVRTC2BPP_RGBA: case PVR3TexturePixelFormat::PVRTC4BPP_RGB: case PVR3TexturePixelFormat::PVRTC4BPP_RGBA: case PVR3TexturePixelFormat::ETC1: case PVR3TexturePixelFormat::RGBA8888: //case PVR3TexturePixelFormat::RGBA4444: //case PVR3TexturePixelFormat::RGBA5551: case PVR3TexturePixelFormat::RGB565: //case PVR3TexturePixelFormat::RGB888: case PVR3TexturePixelFormat::A8: case PVR3TexturePixelFormat::L8: case PVR3TexturePixelFormat::LA88: return true; default: return false; } } } bool Image::initWithPVRv2Data(const unsigned char * data, ssize_t dataLen) { /* int dataLength = 0, dataOffset = 0, dataSize = 0; int blockSize = 0, widthBlocks = 0, heightBlocks = 0; int width = 0, height = 0; //Cast first sizeof(PVRTexHeader) bytes of data stream as PVRTexHeader const PVRv2TexHeader *header = static_cast<const PVRv2TexHeader *>(static_cast<const void*>(data)); //Make sure that tag is in correct formatting if (memcmp(&header->pvrTag, gPVRTexIdentifier, strlen(gPVRTexIdentifier)) != 0) { return false; } Configuration *configuration = Configuration::getInstance(); //can not detect the premultiplied alpha from pvr file, use _PVRHaveAlphaPremultiplied instead. _hasPremultipliedAlpha = _PVRHaveAlphaPremultiplied; unsigned int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags); PVR2TexturePixelFormat formatFlags = static_cast<PVR2TexturePixelFormat>(flags & PVR_TEXTURE_FLAG_TYPE_MASK); bool flipped = (flags & (unsigned int)PVR2TextureFlag::VerticalFlip) ? true : false; if (flipped) { G::log("cocos2d: WARNING: Image is flipped. Regenerate it using PVRTexTool"); } if (! configuration->supportsNPOT() && (static_cast<int>(header->width) != ccNextPOT(header->width) || static_cast<int>(header->height) != ccNextPOT(header->height))) { G::log("cocos2d: ERROR: Loading an NPOT texture (%dx%d) but is not supported on this device", header->width, header->height); return false; } if (!testFormatForPvr2TCSupport(formatFlags)) { G::log("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); return false; } if (v2_pixel_formathash.find(formatFlags) == v2_pixel_formathash.end()) { G::log("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); return false; } auto it = Texture2D::getPixelFormatInfoMap().find(getDevicePixelFormat(v2_pixel_formathash.at(formatFlags))); if (it == Texture2D::getPixelFormatInfoMap().end()) { G::log("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); return false; } _renderFormat = it->first; int bpp = it->second.bpp; //Reset num of mipmaps _numberOfMipmaps = 0; //Get size of mipmap _width = width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width); _height = height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height); //Get ptr to where data starts.. dataLength = CC_SWAP_INT32_LITTLE_TO_HOST(header->dataLength); //Move by size of header _dataLen = dataLen - sizeof(PVRv2TexHeader); _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char))); memcpy(_data, (unsigned char*)data + sizeof(PVRv2TexHeader), _dataLen); // Calculate the data size for each texture level and respect the minimum number of blocks while (dataOffset < dataLength) { switch (formatFlags) { case PVR2TexturePixelFormat::PVRTC2BPP_RGBA: if (!Configuration::getInstance()->supportsPVRTC()) { G::log("cocos2d: Hardware PVR decoder not present. Using software decoder"); _unpack = true; _mipmaps[_numberOfMipmaps].len = width*height*4; _mipmaps[_numberOfMipmaps].address = new unsigned char[width*height*4]; PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[_numberOfMipmaps].address, true); bpp = 2; } blockSize = 8 * 4; // Pixel by pixel block size for 2bpp widthBlocks = width / 8; heightBlocks = height / 4; break; case PVR2TexturePixelFormat::PVRTC4BPP_RGBA: if (!Configuration::getInstance()->supportsPVRTC()) { G::log("cocos2d: Hardware PVR decoder not present. Using software decoder"); _unpack = true; _mipmaps[_numberOfMipmaps].len = width*height*4; _mipmaps[_numberOfMipmaps].address = new unsigned char[width*height*4]; PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[_numberOfMipmaps].address, false); bpp = 4; } blockSize = 4 * 4; // Pixel by pixel block size for 4bpp widthBlocks = width / 4; heightBlocks = height / 4; break; case PVR2TexturePixelFormat::BGRA8888: if (Configuration::getInstance()->supportsBGRA8888() == false) { G::log("cocos2d: Image. BGRA8888 not supported on this device"); return false; } default: blockSize = 1; widthBlocks = width; heightBlocks = height; break; } // Clamp to minimum number of blocks if (widthBlocks < 2) { widthBlocks = 2; } if (heightBlocks < 2) { heightBlocks = 2; } dataSize = widthBlocks * heightBlocks * ((blockSize * bpp) / 8); int packetLength = (dataLength - dataOffset); packetLength = packetLength > dataSize ? dataSize : packetLength; //Make record to the mipmaps array and increment counter if(!_unpack) { _mipmaps[_numberOfMipmaps].address = _data + dataOffset; _mipmaps[_numberOfMipmaps].len = packetLength; } _numberOfMipmaps++; dataOffset += packetLength; //Update width and height to the next lower power of two width = MAX(width >> 1, 1); height = MAX(height >> 1, 1); } if(_unpack) { _data = _mipmaps[0].address; _dataLen = _mipmaps[0].len; } */ return true; } bool Image::initWithPVRv3Data(const unsigned char * data, ssize_t dataLen) { /* if (static_cast<size_t>(dataLen) < sizeof(PVRv3TexHeader)) { return false; } const PVRv3TexHeader *header = static_cast<const PVRv3TexHeader *>(static_cast<const void*>(data)); // validate version if (CC_SWAP_INT32_BIG_TO_HOST(header->version) != 0x50565203) { G::log("cocos2d: WARNING: pvr file version mismatch"); return false; } // parse pixel format PVR3TexturePixelFormat pixelFormat = static_cast<PVR3TexturePixelFormat>(header->pixelFormat); if (!testFormatForPvr3TCSupport(pixelFormat)) { G::log("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant", static_cast<unsigned long long>(pixelFormat)); return false; } if (v3_pixel_formathash.find(pixelFormat) == v3_pixel_formathash.end()) { G::log("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant", static_cast<unsigned long long>(pixelFormat)); return false; } auto it = Texture2D::getPixelFormatInfoMap().find(getDevicePixelFormat(v3_pixel_formathash.at(pixelFormat))); if (it == Texture2D::getPixelFormatInfoMap().end()) { G::log("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant", static_cast<unsigned long long>(pixelFormat)); return false; } _renderFormat = it->first; int bpp = it->second.bpp; // flags int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags); // PVRv3 specifies premultiply alpha in a flag -- should always respect this in PVRv3 files if (flags & (unsigned int)PVR3TextureFlag::PremultipliedAlpha) { _hasPremultipliedAlpha = true; } // sizing int width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width); int height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height); _width = width; _height = height; int dataOffset = 0, dataSize = 0; int blockSize = 0, widthBlocks = 0, heightBlocks = 0; _dataLen = dataLen - (sizeof(PVRv3TexHeader) + header->metadataLength); _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char))); memcpy(_data, static_cast<const unsigned char*>(data) + sizeof(PVRv3TexHeader) + header->metadataLength, _dataLen); _numberOfMipmaps = header->numberOfMipmaps; CCAssert(_numberOfMipmaps < MIPMAP_MAX, "Image: Maximum number of mimpaps reached. Increate the CC_MIPMAP_MAX value"); for (int i = 0; i < _numberOfMipmaps; i++) { switch ((PVR3TexturePixelFormat)pixelFormat) { case PVR3TexturePixelFormat::PVRTC2BPP_RGB : case PVR3TexturePixelFormat::PVRTC2BPP_RGBA : if (!Configuration::getInstance()->supportsPVRTC()) { G::log("cocos2d: Hardware PVR decoder not present. Using software decoder"); _unpack = true; _mipmaps[i].len = width*height*4; _mipmaps[i].address = new unsigned char[width*height*4]; PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[i].address, true); bpp = 2; } blockSize = 8 * 4; // Pixel by pixel block size for 2bpp widthBlocks = width / 8; heightBlocks = height / 4; break; case PVR3TexturePixelFormat::PVRTC4BPP_RGB : case PVR3TexturePixelFormat::PVRTC4BPP_RGBA : if (!Configuration::getInstance()->supportsPVRTC()) { G::log("cocos2d: Hardware PVR decoder not present. Using software decoder"); _unpack = true; _mipmaps[i].len = width*height*4; _mipmaps[i].address = new unsigned char[width*height*4]; PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[i].address, false); bpp = 4; } blockSize = 4 * 4; // Pixel by pixel block size for 4bpp widthBlocks = width / 4; heightBlocks = height / 4; break; case PVR3TexturePixelFormat::ETC1: if (!Configuration::getInstance()->supportsETC()) { G::log("cocos2d: Hardware ETC1 decoder not present. Using software decoder"); int bytePerPixel = 3; unsigned int stride = width * bytePerPixel; _unpack = true; _mipmaps[i].len = width*height*bytePerPixel; _mipmaps[i].address = new unsigned char[width*height*bytePerPixel]; if (etc1_decode_image(static_cast<const unsigned char*>(_data+dataOffset), static_cast<etc1_byte*>(_mipmaps[i].address), width, height, bytePerPixel, stride) != 0) { return false; } } blockSize = 4 * 4; // Pixel by pixel block size for 4bpp widthBlocks = width / 4; heightBlocks = height / 4; break; case PVR3TexturePixelFormat::BGRA8888: if (! Configuration::getInstance()->supportsBGRA8888()) { G::log("cocos2d: Image. BGRA8888 not supported on this device"); return false; } default: blockSize = 1; widthBlocks = width; heightBlocks = height; break; } // Clamp to minimum number of blocks if (widthBlocks < 2) { widthBlocks = 2; } if (heightBlocks < 2) { heightBlocks = 2; } dataSize = widthBlocks * heightBlocks * ((blockSize * bpp) / 8); auto packetLength = _dataLen - dataOffset; packetLength = packetLength > dataSize ? dataSize : packetLength; if(!_unpack) { _mipmaps[i].address = _data + dataOffset; _mipmaps[i].len = static_cast<int>(packetLength); } dataOffset += packetLength; CCAssert(dataOffset <= _dataLen, "CCTexurePVR: Invalid lenght"); width = MAX(width >> 1, 1); height = MAX(height >> 1, 1); } if (_unpack) { _data = _mipmaps[0].address; _dataLen = _mipmaps[0].len; } */ return true; } bool Image::initWithETCData(const unsigned char * data, ssize_t dataLen) { /* const etc1_byte* header = static_cast<const etc1_byte*>(data); //check the data if (! etc1_pkm_is_valid(header)) { return false; } _width = etc1_pkm_get_width(header); _height = etc1_pkm_get_height(header); if (0 == _width || 0 == _height) { return false; } if (Configuration::getInstance()->supportsETC()) { //old opengl version has no define for GL_ETC1_RGB8_OES, add macro to make compiler happy. #ifdef GL_ETC1_RGB8_OES _renderFormat = Texture2D::PixelFormat::ETC; _dataLen = dataLen - ETC_PKM_HEADER_SIZE; _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char))); memcpy(_data, static_cast<const unsigned char*>(data) + ETC_PKM_HEADER_SIZE, _dataLen); return true; #endif } else { G::log("cocos2d: Hardware ETC1 decoder not present. Using software decoder"); //if it is not gles or device do not support ETC, decode texture by software int bytePerPixel = 3; unsigned int stride = _width * bytePerPixel; _renderFormat = Texture2D::PixelFormat::RGB888; _dataLen = _width * _height * bytePerPixel; _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char))); if (etc1_decode_image(static_cast<const unsigned char*>(data) + ETC_PKM_HEADER_SIZE, static_cast<etc1_byte*>(_data), _width, _height, bytePerPixel, stride) != 0) { _dataLen = 0; if (_data != nullptr) { free(_data); } return false; } return true; } */ return false; } bool Image::initWithTGAData(tImageTGA* tgaData) { bool ret = false; /* do { CC_BREAK_IF(tgaData == nullptr); // tgaLoadBuffer only support type 2, 3, 10 if (2 == tgaData->type || 10 == tgaData->type) { // true color // unsupport RGB555 if (tgaData->pixelDepth == 16) { _renderFormat = Texture2D::PixelFormat::RGB5A1; } else if(tgaData->pixelDepth == 24) { _renderFormat = Texture2D::PixelFormat::RGB888; } else if(tgaData->pixelDepth == 32) { _renderFormat = Texture2D::PixelFormat::RGBA8888; } else { G::log("Image WARNING: unsupport true color tga data pixel format. FILE: %s", _filePath.c_str()); break; } } else if(3 == tgaData->type) { // gray if (8 == tgaData->pixelDepth) { _renderFormat = Texture2D::PixelFormat::I8; } else { // actually this won't happen, if it happens, maybe the image file is not a tga G::log("Image WARNING: unsupport gray tga data pixel format. FILE: %s", _filePath.c_str()); break; } } _width = tgaData->width; _height = tgaData->height; _data = tgaData->imageData; _dataLen = _width * _height * tgaData->pixelDepth / 8; _fileType = Format::TGA; _hasPremultipliedAlpha = false; ret = true; }while(false); if (ret) { if (_filePath.length() > 0) { const unsigned char tgaSuffix [] = ".tga"; for (int i = 0; i < 4; ++i) { if (tolower(_filePath[_filePath.length() - i - 1]) != tgaSuffix[3 - i]) { G::log("Image WARNING: the image file suffix is not tga, but parsed as a tga image file. FILE: %s", _filePath.c_str()); break; }; } } } else { if (tgaData && tgaData->imageData != nullptr) { free(tgaData->imageData); _data = nullptr; } } */ return ret; } namespace { static const uint32_t makeFourCC(char ch0, char ch1, char ch2, char ch3) { const uint32_t fourCC = ((uint32_t)(char)(ch0) | ((uint32_t)(char)(ch1) << 8) | ((uint32_t)(char)(ch2) << 16) | ((uint32_t)(char)(ch3) << 24 )); return fourCC; } } bool Image::initWithS3TCData(const unsigned char * data, ssize_t dataLen) { /* const uint32_t FOURCC_DXT1 = makeFourCC('D', 'X', 'T', '1'); const uint32_t FOURCC_DXT3 = makeFourCC('D', 'X', 'T', '3'); const uint32_t FOURCC_DXT5 = makeFourCC('D', 'X', 'T', '5'); //* load the .dds file * S3TCTexHeader *header = (S3TCTexHeader *)data; unsigned char *pixelData = static_cast<unsigned char*>(malloc((dataLen - sizeof(S3TCTexHeader)) * sizeof(unsigned char))); memcpy((void *)pixelData, data + sizeof(S3TCTexHeader), dataLen - sizeof(S3TCTexHeader)); _width = header->ddsd.width; _height = header->ddsd.height; _numberOfMipmaps = MAX(1, header->ddsd.DUMMYUNIONNAMEN2.mipMapCount); //if dds header reports 0 mipmaps, set to 1 to force correct software decoding (if needed). _dataLen = 0; int blockSize = (FOURCC_DXT1 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC) ? 8 : 16; //* calculate the dataLen * int width = _width; int height = _height; if (Configuration::getInstance()->supportsS3TC()) //compressed data length { _dataLen = dataLen - sizeof(S3TCTexHeader); _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char))); memcpy((void *)_data,(void *)pixelData , _dataLen); } else //decompressed data length { for (int i = 0; i < _numberOfMipmaps && (width || height); ++i) { if (width == 0) width = 1; if (height == 0) height = 1; _dataLen += (height * width *4); width >>= 1; height >>= 1; } _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char))); } //* if hardware supports s3tc, set pixelformat before loading mipmaps, to support non-mipmapped textures * if (Configuration::getInstance()->supportsS3TC()) { //decode texture throught hardware if (FOURCC_DXT1 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC) { _renderFormat = Texture2D::PixelFormat::S3TC_DXT1; } else if (FOURCC_DXT3 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC) { _renderFormat = Texture2D::PixelFormat::S3TC_DXT3; } else if (FOURCC_DXT5 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC) { _renderFormat = Texture2D::PixelFormat::S3TC_DXT5; } } else { //will software decode _renderFormat = Texture2D::PixelFormat::RGBA8888; } //* load the mipmaps * int encodeOffset = 0; int decodeOffset = 0; width = _width; height = _height; for (int i = 0; i < _numberOfMipmaps && (width || height); ++i) { if (width == 0) width = 1; if (height == 0) height = 1; int size = ((width+3)/4)*((height+3)/4)*blockSize; if (Configuration::getInstance()->supportsS3TC()) { //decode texture throught hardware _mipmaps[i].address = (unsigned char *)_data + encodeOffset; _mipmaps[i].len = size; } else { //if it is not gles or device do not support S3TC, decode texture by software G::log("cocos2d: Hardware S3TC decoder not present. Using software decoder"); int bytePerPixel = 4; unsigned int stride = width * bytePerPixel; std::vector<unsigned char> decodeImageData(stride * height); if (FOURCC_DXT1 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC) { s3tc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, S3TCDecodeFlag::DXT1); } else if (FOURCC_DXT3 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC) { s3tc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, S3TCDecodeFlag::DXT3); } else if (FOURCC_DXT5 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC) { s3tc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, S3TCDecodeFlag::DXT5); } _mipmaps[i].address = (unsigned char *)_data + decodeOffset; _mipmaps[i].len = (stride * height); memcpy((void *)_mipmaps[i].address, (void *)&decodeImageData[0], _mipmaps[i].len); decodeOffset += stride * height; } encodeOffset += size; width >>= 1; height >>= 1; } //* end load the mipmaps * if (pixelData != nullptr) { free(pixelData); }; */ return true; } bool Image::initWithATITCData(const unsigned char *data, ssize_t dataLen) { ///* load the .ktx file */ //ATITCTexHeader *header = (ATITCTexHeader *)data; //_width = header->pixelWidth; //_height = header->pixelHeight; //_numberOfMipmaps = header->numberOfMipmapLevels; // //int blockSize = 0; //switch (header->glInternalFormat) //{ // case CC_GL_ATC_RGB_AMD: // blockSize = 8; // break; // case CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD: // blockSize = 16; // break; // case CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD: // blockSize = 16; // break; // default: // break; //} // ///* pixelData point to the compressed data address */ //unsigned char *pixelData = (unsigned char *)data + sizeof(ATITCTexHeader) + header->bytesOfKeyValueData + 4; // ///* caculate the dataLen */ //int width = _width; //int height = _height; // //if (Configuration::getInstance()->supportsATITC()) //compressed data length //{ // _dataLen = dataLen - sizeof(ATITCTexHeader) - header->bytesOfKeyValueData - 4; // _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char))); // memcpy((void *)_data,(void *)pixelData , _dataLen); //} //else //decompressed data length //{ // for (int i = 0; i < _numberOfMipmaps && (width || height); ++i) // { // if (width == 0) width = 1; // if (height == 0) height = 1; // // _dataLen += (height * width *4); // // width >>= 1; // height >>= 1; // } // _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char))); //} // ///* load the mipmaps */ //int encodeOffset = 0; //int decodeOffset = 0; //width = _width; height = _height; // //for (int i = 0; i < _numberOfMipmaps && (width || height); ++i) //{ // if (width == 0) width = 1; // if (height == 0) height = 1; // // int size = ((width+3)/4)*((height+3)/4)*blockSize; // // if (Configuration::getInstance()->supportsATITC()) // { // /* decode texture throught hardware */ // // G::log("this is atitc H decode"); // // switch (header->glInternalFormat) // { // case CC_GL_ATC_RGB_AMD: // _renderFormat = Texture2D::PixelFormat::ATC_RGB; // break; // case CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD: // _renderFormat = Texture2D::PixelFormat::ATC_EXPLICIT_ALPHA; // break; // case CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD: // _renderFormat = Texture2D::PixelFormat::ATC_INTERPOLATED_ALPHA; // break; // default: // break; // } // // _mipmaps[i].address = (unsigned char *)_data + encodeOffset; // _mipmaps[i].len = size; // } // else // { // /* if it is not gles or device do not support ATITC, decode texture by software */ // // G::log("cocos2d: Hardware ATITC decoder not present. Using software decoder"); // // int bytePerPixel = 4; // unsigned int stride = width * bytePerPixel; // _renderFormat = Texture2D::PixelFormat::RGBA8888; // // std::vector<unsigned char> decodeImageData(stride * height); // switch (header->glInternalFormat) // { // case CC_GL_ATC_RGB_AMD: // atitc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, ATITCDecodeFlag::ATC_RGB); // break; // case CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD: // atitc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, ATITCDecodeFlag::ATC_EXPLICIT_ALPHA); // break; // case CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD: // atitc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, ATITCDecodeFlag::ATC_INTERPOLATED_ALPHA); // break; // default: // break; // } // _mipmaps[i].address = (unsigned char *)_data + decodeOffset; // _mipmaps[i].len = (stride * height); // memcpy((void *)_mipmaps[i].address, (void *)&decodeImageData[0], _mipmaps[i].len); // decodeOffset += stride * height; // } // encodeOffset += (size + 4); // width >>= 1; // height >>= 1; //} ///* end load the mipmaps */ // return true; } bool Image::initWithPVRData(const unsigned char * data, ssize_t dataLen) { return initWithPVRv2Data(data, dataLen) || initWithPVRv3Data(data, dataLen); } bool Image::initWithWebpData(const unsigned char * data, ssize_t dataLen) { #if CC_USE_WEBP bool ret = false; #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) G::log("WEBP image format not supported on WinRT or WP8"); #else do { WebPDecoderConfig config; if (WebPInitDecoderConfig(&config) == 0) break; if (WebPGetFeatures(static_cast<const uint8_t*>(data), dataLen, &config.input) != VP8_STATUS_OK) break; if (config.input.width == 0 || config.input.height == 0) break; config.output.colorspace = MODE_RGBA; _renderFormat = Texture2D::PixelFormat::RGBA8888; _width = config.input.width; _height = config.input.height; _dataLen = _width * _height * 4; _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char))); config.output.u.RGBA.rgba = static_cast<uint8_t*>(_data); config.output.u.RGBA.stride = _width * 4; config.output.u.RGBA.size = _dataLen; config.output.is_external_memory = 1; if (WebPDecode(static_cast<const uint8_t*>(data), dataLen, &config) != VP8_STATUS_OK) { free(_data); _data = nullptr; break; } ret = true; } while (0); #endif // (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) return ret; #else G::log("webp is not enabled, please enable it in ccConfig.h"); return false; #endif // CC_USE_WEBP } bool Image::initWithRawData(const unsigned char * data, ssize_t dataLen, int width, int height, int bitsPerComponent, bool preMulti) { bool ret = false; do { if (0 == width || 0 == height){ break; } _height = height; _width = width; _hasPremultipliedAlpha = preMulti; _renderFormat = Texture2D::PixelFormat::RGBA8888; // only RGBA8888 supported int bytesPerComponent = 4; _dataLen = height * width * bytesPerComponent; _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char))); if (!_data){ break; } memcpy(_data, data, _dataLen); ret = true; } while (0); return ret; } //#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) bool Image::saveToFile(const std::string& filename, bool isToRGB) { //only support for Texture2D::PixelFormat::RGB888 or Texture2D::PixelFormat::RGBA8888 uncompressed data if (isCompressed() || (_renderFormat != Texture2D::PixelFormat::RGB888 && _renderFormat != Texture2D::PixelFormat::RGBA8888)) { G::log("cocos2d: Image: saveToFile is only support for Texture2D::PixelFormat::RGB888 or Texture2D::PixelFormat::RGBA8888 uncompressed data for now"); return false; } bool ret = false; do { if (filename.size() <= 4){ break; } std::string strLowerCasePath(filename); for (unsigned int i = 0; i < strLowerCasePath.length(); ++i) { strLowerCasePath[i] = tolower(filename[i]); } if (std::string::npos != strLowerCasePath.find(".png")) { if (!saveImageToPNG(filename, isToRGB)){ break; } } else if (std::string::npos != strLowerCasePath.find(".jpg")) { if (!saveImageToJPG(filename)){ break; } } else { break; } ret = true; } while (0); return ret; } //#endif bool Image::saveImageToPNG(const std::string& filePath, bool isToRGB) { bool ret = false; do { FILE *fp; png_structp png_ptr; png_infop info_ptr; png_colorp palette; png_bytep *row_pointers; fp = fopen(filePath.c_str(), "wb"); if (nullptr == fp){ break; } png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (nullptr == png_ptr) { fclose(fp); break; } info_ptr = png_create_info_struct(png_ptr); if (nullptr == info_ptr) { fclose(fp); png_destroy_write_struct(&png_ptr, nullptr); break; } #if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA && CC_TARGET_PLATFORM != CC_PLATFORM_NACL) if (setjmp(png_jmpbuf(png_ptr))) { fclose(fp); png_destroy_write_struct(&png_ptr, &info_ptr); break; } #endif png_init_io(png_ptr, fp); if (!isToRGB && hasAlpha()) { png_set_IHDR(png_ptr, info_ptr, _width, _height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); } else { png_set_IHDR(png_ptr, info_ptr, _width, _height, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); } palette = (png_colorp)png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH * sizeof (png_color)); png_set_PLTE(png_ptr, info_ptr, palette, PNG_MAX_PALETTE_LENGTH); png_write_info(png_ptr, info_ptr); png_set_packing(png_ptr); row_pointers = (png_bytep *)malloc(_height * sizeof(png_bytep)); if(row_pointers == nullptr) { fclose(fp); png_destroy_write_struct(&png_ptr, &info_ptr); break; } if (!hasAlpha()) { for (int i = 0; i < (int)_height; i++) { row_pointers[i] = (png_bytep)_data + i * _width * 3; } png_write_image(png_ptr, row_pointers); free(row_pointers); row_pointers = nullptr; } else { if (isToRGB) { unsigned char *tempData = static_cast<unsigned char*>(malloc(_width * _height * 3 * sizeof(unsigned char))); if (nullptr == tempData) { fclose(fp); png_destroy_write_struct(&png_ptr, &info_ptr); free(row_pointers); row_pointers = nullptr; break; } for (int i = 0; i < _height; ++i) { for (int j = 0; j < _width; ++j) { tempData[(i * _width + j) * 3] = _data[(i * _width + j) * 4]; tempData[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1]; tempData[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2]; } } for (int i = 0; i < (int)_height; i++) { row_pointers[i] = (png_bytep)tempData + i * _width * 3; } png_write_image(png_ptr, row_pointers); free(row_pointers); row_pointers = nullptr; if (tempData != nullptr) { free(tempData); } } else { for (int i = 0; i < (int)_height; i++) { row_pointers[i] = (png_bytep)_data + i * _width * 4; } png_write_image(png_ptr, row_pointers); free(row_pointers); row_pointers = nullptr; } } png_write_end(png_ptr, info_ptr); png_free(png_ptr, palette); palette = nullptr; png_destroy_write_struct(&png_ptr, &info_ptr); fclose(fp); ret = true; } while (0); return ret; } bool Image::saveImageToJPG(const std::string& filePath) { #if CC_USE_JPEG bool ret = false; do { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; FILE * outfile; /* target file */ JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */ int row_stride; /* physical row width in image buffer */ cinfo.err = jpeg_std_error(&jerr); /* Now we can initialize the JPEG compression object. */ jpeg_create_compress(&cinfo); if ((outfile = fopen(filePath.c_str(), "wb")) == nullptr){ break; } jpeg_stdio_dest(&cinfo, outfile); cinfo.image_width = _width; /* image width and height, in pixels */ cinfo.image_height = _height; cinfo.input_components = 3; /* # of color components per pixel */ cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, 90, TRUE); jpeg_start_compress(&cinfo, TRUE); row_stride = _width * 3; /* JSAMPLEs per row in image_buffer */ if (hasAlpha()) { unsigned char *tempData = static_cast<unsigned char*>(malloc(_width * _height * 3 * sizeof(unsigned char))); if (nullptr == tempData) { jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); fclose(outfile); break; } for (int i = 0; i < _height; ++i) { for (int j = 0; j < _width; ++j) { tempData[(i * _width + j) * 3] = _data[(i * _width + j) * 4]; tempData[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1]; tempData[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2]; } } while (cinfo.next_scanline < cinfo.image_height) { row_pointer[0] = & tempData[cinfo.next_scanline * row_stride]; (void) jpeg_write_scanlines(&cinfo, row_pointer, 1); } if (tempData != nullptr) { free(tempData); } } else { while (cinfo.next_scanline < cinfo.image_height) { row_pointer[0] = & _data[cinfo.next_scanline * row_stride]; (void) jpeg_write_scanlines(&cinfo, row_pointer, 1); } } jpeg_finish_compress(&cinfo); fclose(outfile); jpeg_destroy_compress(&cinfo); ret = true; } while (0); return ret; #else G::log("jpeg is not enabled, please enable it in ccConfig.h"); return false; #endif // CC_USE_JPEG } void Image::premultipliedAlpha() { //CCASSERT(_renderFormat == Texture2D::PixelFormat::RGBA8888, "The pixel format should be RGBA8888!"); // //unsigned int* fourBytes = (unsigned int*)_data; //for(int i = 0; i < _width * _height; i++) //{ // unsigned char* p = _data + i * 4; // fourBytes[i] = CC_RGB_PREMULTIPLY_ALPHA(p[0], p[1], p[2], p[3]); //} // //_hasPremultipliedAlpha = true; } void Image::setPVRImagesHavePremultipliedAlpha(bool haveAlphaPremultiplied) { _PVRHaveAlphaPremultiplied = haveAlphaPremultiplied; } bool Image::ImageDataDecode(unsigned char *pData, unsigned int &uSize) { unsigned char pHeadOld[] = { 4, 8, 15, 16, 23, 42, 0, 0 }; unsigned char pHeadNew[] = { 15, 0, 192, 22, 15, 9, 0, 0 }; unsigned int lFileLength = uSize; if ( lFileLength < sizeof(pHeadOld) || pData == NULL ) { return false; } bool bEncryptionOld = true; bool bEncryptionNew = true; for ( int i = 0 ;i < sizeof(pHeadOld) - 2; ++i) { if ( pHeadOld[i] != pData[i] ) { bEncryptionOld = false; break; } } for ( int i = 0 ;i < sizeof(pHeadNew) - 2; ++i) { if ( pHeadNew[i] != pData[i] ) { bEncryptionNew = false; break; } } if( bEncryptionOld ) { return DecryptionOld( pData, uSize ); } else if( bEncryptionNew ) { return DecryptionNew( pData, uSize ); } else { return false; } } bool Image::DecryptionOld(unsigned char *pData, unsigned int &uSize) { unsigned char pHead[] = { 4, 8, 15, 16, 23, 42, 0, 0 }; unsigned int lFileLength = uSize; pHead[6] = pData[6]; pHead[7] = pData[7]; unsigned char* pDataDec = new unsigned char[lFileLength - sizeof(pHead)]; memcpy( pDataDec, &pData[sizeof(pHead)], sizeof(unsigned char) * (lFileLength - sizeof(pHead))); for ( unsigned int i = 0; i < lFileLength - sizeof(pHead) - 20; i += 10 ) { unsigned char cbDATA[10] = { pDataDec[i + 0], pDataDec[i + 1], pDataDec[i + 2], pDataDec[i + 3], pDataDec[i + 4], pDataDec[i + 5], pDataDec[i + 6], pDataDec[i + 7], pDataDec[i + 8], pDataDec[i + 9] }; pDataDec[i + 0] = cbDATA[6]; pDataDec[i + 2] = cbDATA[9]; pDataDec[i + 4] = cbDATA[2]; pDataDec[i + 6] = cbDATA[4]; pDataDec[i + 9] = cbDATA[0]; pDataDec[i + 1] -= pHead[7]; pDataDec[i + 3] += pHead[6]; pDataDec[i + 5] += pHead[5]; pDataDec[i + 7] -= (pHead[6] + pHead[7]); pDataDec[i + 8] -= (pHead[7] + pHead[5]); } memcpy( pData, pDataDec, sizeof(unsigned char) * (lFileLength - sizeof(pHead))); uSize = (lFileLength - sizeof(pHead)); delete[] pDataDec; pDataDec = NULL; return true; } bool Image::DecryptionNew(unsigned char *pData, unsigned int &uSize) { unsigned char pHead[] = { 15, 0, 192, 22, 15, 9, 0, 0 }; unsigned int lFileLength = uSize; pHead[6] = pData[6]; pHead[7] = pData[7]; unsigned char* pDataDec = new unsigned char[lFileLength - sizeof(pHead)]; memcpy( pDataDec, &pData[sizeof(pHead)], sizeof(unsigned char) * (lFileLength - sizeof(pHead))); for ( unsigned int i = 0; i < lFileLength - sizeof(pHead) - 20; i += 17 ) { unsigned char cbDATA[17] = { pDataDec[i + 0], pDataDec[i + 1], pDataDec[i + 2], pDataDec[i + 3], pDataDec[i + 4], pDataDec[i + 5], pDataDec[i + 6], pDataDec[i + 7], pDataDec[i + 8], pDataDec[i + 9], pDataDec[i + 10], pDataDec[i + 11], pDataDec[i + 12], pDataDec[i + 13], pDataDec[i + 14], pDataDec[i + 15], pDataDec[i + 16]}; pDataDec[i + 0] = cbDATA[4]; pDataDec[i + 2] = cbDATA[6]; pDataDec[i + 4] = cbDATA[0]; pDataDec[i + 6] = cbDATA[9]; pDataDec[i + 9] = cbDATA[2]; pDataDec[i + 1] -= pHead[7]; pDataDec[i + 3] += pHead[6]; pDataDec[i + 5] -= pHead[5]; pDataDec[i + 7] += (pHead[6] + pHead[7]); pDataDec[i + 8] += (pHead[7] + pHead[5]); pDataDec[i + 10] = cbDATA[14]; pDataDec[i + 11] = cbDATA[13]; pDataDec[i + 12] = cbDATA[11]; pDataDec[i + 13] = cbDATA[12]; pDataDec[i + 14] = cbDATA[10]; pDataDec[i + 15] -= pHead[4]; pDataDec[i + 16] += pHead[2]; } memcpy( pData, pDataDec, sizeof(unsigned char) * (lFileLength - sizeof(pHead))); uSize = (lFileLength - sizeof(pHead)); delete[] pDataDec; pDataDec = NULL; return true; }
[ "junee1122@163.com" ]
junee1122@163.com
08495046c052617a602a67918e3f54f87b4ced5a
24d34ec86dec261404c65a48f1bf8150f0348ac9
/AppViewer/InputManager.h
4e1d3d2ac0471d1db696da03c9cc129aaf061f7d
[]
no_license
mbanquiero/miniengine
4c57ef534e69b699beed6a7676d8e50e08c1c257
c4a1a692a47aa0c0fd6c634edbe83748fb29207c
refs/heads/master
2021-01-10T07:31:57.632406
2014-06-12T23:04:18
2014-06-12T23:04:18
53,662,835
0
0
null
null
null
null
UTF-8
C++
false
false
4,932
h
#pragma once #include <../Include/dinput.h> #include <math/vector3.h> enum DInputKey { Key_Escape = 1, Key_D1 = 2, Key_D2 = 3, Key_D3 = 4, Key_D4 = 5, Key_D5 = 6, Key_D6 = 7, Key_D7 = 8, Key_D8 = 9, Key_D9 = 10, Key_D0 = 11, Key_Minus = 12, Key_Equals = 13, Key_Back = 14, Key_BackSpace = 14, Key_Tab = 15, Key_Q = 16, Key_W = 17, Key_E = 18, Key_R = 19, Key_T = 20, Key_Y = 21, Key_U = 22, Key_I = 23, Key_O = 24, Key_P = 25, Key_LeftBracket = 26, Key_RightBracket = 27, Key_Return = 28, Key_LeftControl = 29, Key_A = 30, Key_S = 31, Key_D = 32, Key_F = 33, Key_G = 34, Key_H = 35, Key_J = 36, Key_K = 37, Key_L = 38, Key_SemiColon = 39, Key_Apostrophe = 40, Key_Grave = 41, Key_LeftShift = 42, Key_BackSlash = 43, Key_Z = 44, Key_X = 45, Key_C = 46, Key_V = 47, Key_B = 48, Key_N = 49, Key_M = 50, Key_Comma = 51, Key_Period = 52, Key_Slash = 53, Key_RightShift = 54, Key_Multiply = 55, Key_NumPadStar = 55, Key_LeftAlt = 56, Key_LeftMenu = 56, Key_Space = 57, Key_Capital = 58, Key_CapsLock = 58, Key_F1 = 59, Key_F2 = 60, Key_F3 = 61, Key_F4 = 62, Key_F5 = 63, Key_F6 = 64, Key_F7 = 65, Key_F8 = 66, Key_F9 = 67, Key_F10 = 68, Key_Numlock = 69, Key_Scroll = 70, Key_NumPad7 = 71, Key_NumPad8 = 72, Key_NumPad9 = 73, Key_NumPadMinus = 74, Key_Subtract = 74, Key_NumPad4 = 75, Key_NumPad5 = 76, Key_NumPad6 = 77, Key_Add = 78, Key_NumPadPlus = 78, Key_NumPad1 = 79, Key_NumPad2 = 80, Key_NumPad3 = 81, Key_NumPad0 = 82, Key_Decimal = 83, Key_NumPadPeriod = 83, Key_OEM102 = 86, Key_F11 = 87, Key_F12 = 88, Key_F13 = 100, Key_F14 = 101, Key_F15 = 102, Key_Kana = 112, Key_AbntC1 = 115, Key_Convert = 121, Key_NoConvert = 123, Key_Yen = 125, Key_AbntC2 = 126, Key_NumPadEquals = 141, Key_Circumflex = 144, Key_PrevTrack = 144, Key_At = 145, Key_Colon = 146, Key_Underline = 147, Key_Kanji = 148, Key_Stop = 149, Key_AX = 150, Key_Unlabeled = 151, Key_NextTrack = 153, Key_NumPadEnter = 156, Key_RightControl = 157, Key_Mute = 160, Key_Calculator = 161, Key_PlayPause = 162, Key_MediaStop = 164, Key_VolumeDown = 174, Key_VolumeUp = 176, Key_WebHome = 178, Key_NumPadComma = 179, Key_Divide = 181, Key_NumPadSlash = 181, Key_SysRq = 183, Key_RightAlt = 184, Key_RightMenu = 184, Key_Pause = 197, Key_Home = 199, Key_Up = 200, Key_UpArrow = 200, Key_PageUp = 201, Key_Prior = 201, Key_Left = 203, Key_LeftArrow = 203, Key_Right = 205, Key_RightArrow = 205, Key_End = 207, Key_Down = 208, Key_DownArrow = 208, Key_Next = 209, Key_PageDown = 209, Key_Insert = 210, Key_Delete = 211, Key_LeftWindows = 219, Key_RightWindows = 220, Key_Apps = 221, Key_Power = 222, Key_Sleep = 223, Key_Wake = 227, Key_WebSearch = 229, Key_WebFavorites = 230, Key_WebRefresh = 231, Key_WebStop = 232, Key_WebForward = 233, Key_WebBack = 234, Key_MyComputer = 235, Key_Mail = 236, Key_MediaSelect = 237, }; struct KeyboardState { bool keys[256]; operator void*() { return (void *)&keys; } bool operator [](DInputKey key) const { return keys[(int)key]; } bool operator [](int key) const { return keys[key]; }; }; #define MOUSE_LEFT_BUTTON 0 #define MOUSE_RIGHT_BUTTON 1 #define MOUSE_WHEEL_BUTTON 2 #define MOUSE_OTHER_BUTTON 3 struct MouseState { int X; int Y; int Z; BYTE mouseButtons[4]; BYTE * GetMouseButtons(){ return mouseButtons; } operator void*() { return (void *)this; } }; class InputManager { public: static KeyboardState m_antKeyboardState; static KeyboardState m_keyboardState; static MouseState m_antMouseState; static MouseState m_mouseState; static Vector3 m_delta_mouse; static LPDIRECTINPUT8 m_dinput; static LPDIRECTINPUTDEVICE8 m_pKeyboard; static LPDIRECTINPUTDEVICE8 m_pMouse; static bool Init( void ); static void Shutdown(void); static void Update(); static bool IsDown(DInputKey key) { return m_keyboardState[key]; }; static bool IsPressed(int key) { return m_antKeyboardState[key] && !m_keyboardState[key]; }; static bool IsLButtonDown() { return m_mouseState.mouseButtons[MOUSE_LEFT_BUTTON]; }; static bool IsLButtonPressed() { return m_antMouseState.mouseButtons[MOUSE_LEFT_BUTTON] && !m_mouseState.mouseButtons[MOUSE_LEFT_BUTTON]; }; static bool IsRButtonDown() { return m_mouseState.mouseButtons[MOUSE_RIGHT_BUTTON]; }; static bool IsRButtonPressed() { return m_antMouseState.mouseButtons[MOUSE_RIGHT_BUTTON] && !m_mouseState.mouseButtons[MOUSE_RIGHT_BUTTON]; }; static bool IsWheelButtonDown() { return m_mouseState.mouseButtons[MOUSE_WHEEL_BUTTON]; }; static bool IsWheelButtonPressed() { return m_antMouseState.mouseButtons[MOUSE_WHEEL_BUTTON] && !m_mouseState.mouseButtons[MOUSE_WHEEL_BUTTON]; }; };
[ "martin.giachetti@gmail.com" ]
martin.giachetti@gmail.com
59ba5bab4c496a4a0eba7c2239cf395d4457b194
dc61ea4ccd68a64541978e7bff7b9a6b56440fb8
/src/BackPack.cpp
f51839fac2ed73fe19c1a8f184e04cc902263b84
[]
no_license
Glaz92/Shooter
b5277c2d75968e81e92b55fa41b94ef8a6adb9b8
cb49b9c536b4f7ac85d9b57d505a6fa313b0f835
refs/heads/master
2022-11-17T15:03:24.588168
2020-06-28T18:35:46
2020-06-28T18:35:46
263,388,397
0
0
null
null
null
null
UTF-8
C++
false
false
5,176
cpp
#include "BackPack.h" #include "Window.h" #include <sstream> #include <map> #include <tuple> BackPack::BackPack() : pistolAmmo(24), pistolMag(12), shotgunAmmo(0), shotgunMag(8), uziAmmo(30), uziMag(30), mgAmmo(0), mgMag(30), inHand(Weapon::Pistol), box(sf::Vector2f(230,120)), position(20, sf::VideoMode::getDesktopMode().height - 140) { box.setFillColor(sf::Color(10, 10, 10, 140)); font.loadFromFile("data/font/CodenameCoderFree4F-Bold.ttf"); txt.setFont(font); txtAmmo.setFont(font); txt.setString("Pistol\n10/15"); boxS.setTexture(GetWindow().getBoxRT().getTexture()); life.setFont(font); } BackPack::~BackPack() { } void BackPack::draw(int playerLife) { box.setPosition(GetWindow().getViewCenter().x - sf::VideoMode::getDesktopMode().width / 2 + position.x, GetWindow().getViewCenter().y - sf::VideoMode::getDesktopMode().height / 2 + position.y); txt.setPosition(box.getPosition().x + 35, box.getPosition().y + 20); boxS.setPosition(GetWindow().getViewCenter().x + sf::VideoMode::getDesktopMode().width / 2 - position.x - 240, GetWindow().getViewCenter().y - sf::VideoMode::getDesktopMode().height / 2 + position.y + 30); life.setPosition(boxS.getPosition().x + 20, boxS.getPosition().y + 25); txt.setString(getWeaponInfoString()); std::ostringstream ss; ss.str(""); ss << " " << playerLife / 2; life.setString(ss.str()); GetWindow().draw(&box); GetWindow().draw(&txt); GetWindow().draw(&boxS); GetWindow().draw(&life); ss.str(""); // ss << SCORE; txt.setString(ss.str()); txt.setPosition(GetWindow().getViewCenter().x, GetWindow().getViewCenter().y - GetWindow().getSize().y / 2); GetWindow().draw(&txt); } std::string BackPack::getWeaponInfoString() { std::ostringstream ss; using ammoInformation = std::tuple<std::string, int, int>; std::map<Weapon, ammoInformation> ammunictionMap { { Weapon::Pistol, { "Pistol", pistolMag, pistolAmmo } }, { Weapon::Shotgun, { "Shotgun", shotgunMag, shotgunAmmo } }, { Weapon::Uzi, { "Uzi", uziMag, uziAmmo } }, { Weapon::MG, { "MG", mgMag, mgAmmo } } }; ss << std::get<0>(ammunictionMap[inHand]) << std::endl << std::get<1>(ammunictionMap[inHand]) << "/" << std::get<2>(ammunictionMap[inHand]); return ss.str(); } bool BackPack::shot() { std::map<Weapon, int*> magMap { { Weapon::Pistol, &pistolMag }, { Weapon::Shotgun, &shotgunMag }, { Weapon::Uzi, &uziMag }, { Weapon::MG, &mgMag } }; if(*magMap[inHand] > 0) { (*magMap[inHand])--; return true; } return false; } int BackPack::reload() { std::map<Weapon, int> maxBulletsInMag { { Weapon::Pistol, 12 }, { Weapon::Shotgun, 8 }, { Weapon::Uzi,30 }, { Weapon::MG, 30 } }; std::map<Weapon, int*> magMap { { Weapon::Pistol, &pistolMag }, { Weapon::Shotgun, &shotgunMag }, { Weapon::Uzi, &uziMag }, { Weapon::MG, &mgMag } }; std::map<Weapon, int*> ammoMap { { Weapon::Pistol, &pistolAmmo }, { Weapon::Shotgun, &shotgunAmmo }, { Weapon::Uzi, &uziAmmo }, { Weapon::MG, &mgAmmo } }; if(*magMap[inHand] == maxBulletsInMag[inHand]) { return 0; } else { if(*ammoMap[inHand] - (maxBulletsInMag[inHand] - *magMap[inHand]) >= 0) { *ammoMap[inHand] += *magMap[inHand] - maxBulletsInMag[inHand]; *magMap[inHand] = maxBulletsInMag[inHand]; } else if(*ammoMap[inHand] == 0) { return 0; } else { *magMap[inHand] += *ammoMap[inHand]; *ammoMap[inHand] = 0; } return 120; } return 0; } void BackPack::setWeapon(Weapon weapon) { inHand = weapon; } void BackPack::nextWeapon() { std::map<Weapon, Weapon> nextWeapon { { Weapon::Pistol, Weapon::Shotgun }, { Weapon::Shotgun, Weapon::Uzi }, { Weapon::Uzi, Weapon::MG }, { Weapon::MG, Weapon::Pistol } }; inHand = nextWeapon[inHand]; } void BackPack::prevWeapon() { std::map<Weapon, Weapon> nextWeapon { { Weapon::Pistol, Weapon::MG }, { Weapon::Shotgun, Weapon::Pistol }, { Weapon::Uzi, Weapon::Shotgun }, { Weapon::MG, Weapon::Uzi } }; inHand = nextWeapon[inHand]; }
[ "epglaz@gmail.com" ]
epglaz@gmail.com
9f39e8202df5d9b79756dad8f13d1f081f489908
ee5303492ad12df0bf2ac3090d88aefa27034796
/Server/Server/stdafx.cpp
51a8613b7bfc67439f2fd4fbee39693fc44b0e4a
[]
no_license
ernie0218e/Game-Server
be57422a0227dd1f7aa6388957bb3ed623d10c27
77bad3b68aefd8be9d592d529a1f004b0ac064d7
refs/heads/master
2016-09-06T09:51:54.703756
2014-12-20T12:05:46
2014-12-20T12:05:46
28,266,065
0
0
null
null
null
null
GB18030
C++
false
false
178
cpp
// stdafx.cpp : 僅包含標準 Include 檔的原始程式檔 // Server.pch 會成為先行編譯標頭檔 // stdafx.obj 會包含先行編譯型別資訊 #include "stdafx.h"
[ "ernie0218e@gmail.com" ]
ernie0218e@gmail.com
2f8aac3005175dd3b96986fbaf4fc0206c8ede37
b924f2af695a94e26208925e3f83819e3db9616b
/blocks/mail/src/Mail.cpp
011738c753b5938e99ea28c8d84b660411f998fa
[]
no_license
saithal/BanTheRewind
8f801ce15d6880aac1b1c0840ec6b47e6a2be71d
70a8c483cfedd998251d3547b156abe874bf5a48
refs/heads/master
2021-01-16T21:30:42.673263
2011-10-27T01:16:35
2011-10-27T01:16:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,901
cpp
/* * * Copyright (c) 2011, Ban the Rewind * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of the Ban the Rewind nor the names of its * contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ // Include header #include <Mail.h> namespace cinder { namespace mail { // Constructor Message::Message(const std::string & to, const std::string & from, const std::string & subject, const std::string & message, const std::string & server, int32_t port, bool mxLookUp) { // Initialize message if (to.length() > 0 && from.length() > 0) mObj = std::shared_ptr<jwsmtp::mailer>(new jwsmtp::mailer(to.c_str(), from.c_str(), subject.c_str(), message.c_str(), server.c_str(), (uint32_t)port, mxLookUp)); } // Destructor Message::~Message() { // Reset internal object reset(); if (mObj) mObj.reset(); } // Send the message void Message::send() { if (mObj) mObj->send(); } void Message::send() const { if (mObj) mObj->send(); } // Clear message void Message::reset() { if (mObj) mObj->reset(); } // Get server response const std::string Message::getResponse() { return mObj ? mObj->response() : ""; } const std::string Message::getResponse() const { return mObj ? mObj->response() : ""; } // Recipient bool Message::addTo(const std::string & to) { return mObj ? mObj->addrecipient(to.c_str()) : false; } bool Message::addTo(const std::vector<std::string> & to) { for (std::vector<std::string>::const_iterator toIt = to.cbegin(); toIt != to.cend(); ++toIt) if (!addTo(* toIt)) return false; return true; } void Message::clearTo() { if (mObj) mObj->clearrecipients(); } bool Message::removeTo(const std::string & to) { return mObj ? mObj->removerecipient(to.c_str()) : false; } bool Message::removeTo(const std::vector<std::string> & to) { for (std::vector<std::string>::const_iterator toIt = to.cbegin(); toIt != to.cend(); ++toIt) if (!removeTo(* toIt)) return false; return true; } // Attachments bool Message::addAttachment(const std::string & path) { return mObj ? mObj->attach(path) : false; } bool Message::addAttachments(const std::vector<std::string> & paths) { for (std::vector<std::string>::const_iterator pathIt = paths.cbegin(); pathIt != paths.cend(); ++pathIt) if (!addAttachment(* pathIt)) return false; return true; } bool Message::addAttachment(const ci::fs::path & path) { return addAttachment(path.string()); } bool Message::addAttachments(const std::vector<ci::fs::path> & paths) { for (std::vector<ci::fs::path>::const_iterator pathIt = paths.cbegin(); pathIt != paths.cend(); ++pathIt) if (!addAttachment(* pathIt)) return false; return true; } void Message::clearAttachments() { if (mObj) mObj->clearattachments(); } bool Message::removeAttachment(const std::string & path) { return mObj ? mObj->removeattachment(path) : false; } bool Message::removeAttachments(const std::vector<std::string> & paths) { for (std::vector<std::string>::const_iterator pathIt = paths.cbegin(); pathIt != paths.cend(); ++pathIt) if (!removeAttachment(* pathIt)) return false; return true; } bool Message::removeAttachment(const ci::fs::path & path) { return removeAttachment(path.string()); } bool Message::removeAttachments(const std::vector<ci::fs::path> & paths) { for (std::vector<ci::fs::path>::const_iterator pathIt = paths.cbegin(); pathIt != paths.cend(); ++pathIt) if (!removeAttachment(* pathIt)) return false; return true; } // Setters void Message::setAuthentication(const AuthType & authType, const std::string & username, const std::string & password) { if (mObj) { mObj->authtype(authType); mObj->username(username); mObj->password(password); } } bool Message::setFrom(const std::string & from) { return mObj ? mObj->setsender(from) : false; } bool Message::setMessage(const std::string & message, bool html) { if (mObj) { if (html) return mObj->setmessageHTML(message); else return mObj->setmessage(message); } return false; } bool Message::setServer(const std::string & server) { return mObj ? mObj->setserver(server) : false; } bool Message::setSubject(const std::string & subject) { return mObj ? mObj->setsubject(subject) : false; } bool Message::setTo(const std::string & to) { if (mObj) { clearTo(); return addTo(to); } return false; } } }
[ "bantherewind@gmail.com" ]
bantherewind@gmail.com
75094c22c202fe090fdc4941644ff82ccbb3b7a9
4fc3e83dc068bf2281120a6495c93d55a6b20b18
/src/XLUEExtObject/Illumination/IlluminationObjectRegister.cpp
ca9aa4d2d3ac654daf9e8031b64759fe941e7c80
[]
no_license
tsukasaCJ/BXF
b77dcfa4207e2caef10ca6de2852cd9df11528b3
2f49376446f8359f132b535c6fd466c81ac21fa1
refs/heads/master
2021-01-15T14:58:50.956659
2013-11-09T08:47:35
2013-11-09T08:47:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,099
cpp
#include "stdafx.h" #include "./IlluminationObjectRegister.h" #include "./IlluminationObjectCreater.h" #include "./IlluminationObjectParser.h" #include "./LuaIlluminationObject.h" bool IlluminationObjectRegiter::RegiterIlluminationSessionObject() { return ExtObjRegisterHelper<ExtObjType_layoutObj, IlluminationSessionObject, IlluminationSessionObjectCreater, IlluminationSessionObjectParser, LuaIlluminationSessionObject>::Register(EXTCLASSNAME_ILLUMINATIONSESSIONOBJECT, 0); } bool IlluminationObjectRegiter::RegiterIlluminationLayerObject() { unsigned long attribute = ExtObjAttribute_clipsens; return ExtObjRegisterHelper<ExtObjType_renderableObj, IlluminationLayerObject, IlluminationLayerObjectCreater, IlluminationLayerObjectParser, LuaIlluminationLayerObject>::Register(EXTCLASSNAME_ILLUMINATIONLAYEROBJECT, attribute); } bool IlluminationObjectRegiter::RegiterIlluminantObject() { return ExtObjRegisterHelper<ExtObjType_layoutObj, IlluminantObject, IlluminantObjectCreater, IlluminantObjectParser, LuaIlluminantObject>::Register(EXTCLASSNAME_ILLUMINANTOBJECT, 0); }
[ "sichangjun@xunlei.com" ]
sichangjun@xunlei.com
4f966ad2cacc818cdf74e92811c821a1e868cea8
7f98f218e3eb50c7020c49bfe15d9dbb6bd70d0b
/ch10/ex10_27.cpp
237ef51b2e8922af40121fb189bd7dfb448c69c6
[]
no_license
MonstarCoder/MyCppPrimer
1917494855b01dbe12a343d4c3e08752f291c0e9
3399701bb90c45bc0ee0dc843a4e0b93e20d898a
refs/heads/master
2021-01-18T10:16:37.501209
2017-11-09T13:44:36
2017-11-09T13:44:36
84,318,673
0
0
null
null
null
null
UTF-8
C++
false
false
285
cpp
#include<iostream> #include<vector> #include<list> #include<algorithm> using namespace std; int main() { vector<int> vec{1, 1, 2, 2, 3, 3}; list<int> lst; unique_copy(vec.cbegin(), vec.cend(), back_inserter(lst)); for (auto i : lst) cout << i << " "; cout << endl; return 0; }
[ "652141046@qq.com" ]
652141046@qq.com
f593ca022eebe80abf5819d6e3b12e1016ac4626
8eeb53487472a9992233f2335815773c2a42e474
/04_04_12_EdgeWeightedCycleFinderTopological.cpp
4c0fd92352f48800a7239334197e4fdf0a5902c0
[ "MIT" ]
permissive
kanlihu/Algos_4th_Solutions
2ba29ae8d0332552063615f644568657f7322a94
049e8b2082414ac544458f211748c9b2bd95f43e
refs/heads/master
2023-05-14T15:01:03.583116
2020-01-27T03:06:24
2020-01-27T03:06:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,072
cpp
// // Created by Phong Cao on 2019-04-01. // // uncomment to disable assert() // #define NDEBUG #include <cassert> #include <iostream> #include <cstdio> #include <iomanip> #include <ios> #include <sstream> #include <fstream> #include <string> #include <cmath> #include <cstdlib> #include <ctime> #include <functional> #include <vector> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <list> #include <forward_list> #include <deque> #include <queue> #include <stack> #include <iterator> #include <utility> #include <algorithm> #include <memory> #include <cctype> #include <stdexcept> #include <limits> #include <numeric> //----<iostream>------------// using std::cout; using std::cin; using std::endl; using std::ostream; using std::istream; //----<cstdio>--------------// using std::printf; using std::fprintf; using std::sprintf; using std::snprintf; //----<iomanip>-------------// using std::setprecision; using std::setw; //----<ios>-----------------// using std::hex; using std::dec; using std::oct; using std::fixed; //----<sstream>-------------// using std::ostringstream; using std::istringstream; //----<fstream>-------------// using std::ofstream; using std::ifstream; //----<string>--------------// using std::getline; using std::string; using std::to_string; using std::stoi; using std::stol; //----<cmath>---------------// using std::sqrt; using std::pow; using std::log; // log( <arg> ) using std::exp; // e ^ <arg> using std::abs; //----<cstdlib>-------------// using std::rand; using std::srand; //----<ctime>---------------// using std::time; //----<functional>----------// using std::hash; using std::greater; // lhs > rhs. Used for MinPQ using std::less; // lhs < rhs. Used for MaxPQ. Default for priority_queue<> using std::less_equal; using std::greater_equal; //----<vector>--------------// using std::vector; // Unordered Array //----<map>-----------------// using std::map; // Ordered Map (Red-Black Tree) //----<unordered_map>-------// using std::unordered_map; // HashMap (SeparateChainingHashST) //----<set>-----------------// using std::set; // Ordered Set (Red-Black Tree) //----<unordered_set>-------// using std::unordered_set; // HashSet (SeparateChainingHashST) //----<list>----------------// using std::list; // Doubly-Linked List with size() ( O( 1 ) ) //----<forward_list>--------// using std::forward_list; // Singly-Linked List without size() function ( so O( N ) if we need to get size() ) //----<deque>---------------// using std::deque; // Vector of fixed-size Vectors: 1 fixed-size vector for each end of the deque //----<queue>---------------// using std::queue; // Non-Iterable & Use std::deque as underlying data structure using std::priority_queue; // MaxPQ (MaxHeap) & Non-Iterable. // // => Pass std::greater<> as template params to create MinPQ (MinHeap) //----<stack>---------------// using std::stack; // Non-Iterable & Use std::deque as underlying data structure //----<iterator>------------// using std::next; // Return an advanced iter without changing original iter using std::prev; // Return an decremented iter without changin original iter using std::distance; // Calculate distance between 2 iterators //----<utility>-------------// using std::pair; //----<algorithm>-----------// using std::fill; using std::max; using std::min; using std::find; using std::reverse; using std::sort; //----<memory>--------------// using std::make_shared; using std::shared_ptr; //----<cctype>--------------// using std::isalnum; using std::isalpha; using std::islower; using std::isupper; using std::isdigit; using std::isspace; // Check whether char is whitespace character (space, newline, tab, etc. ) using std::isblank; // Check whether char is blank character ( space or tab ) using std::tolower; using std::toupper; //----<stdexcept>-----------// using std::runtime_error; using std::invalid_argument; using std::out_of_range; //----<limits>--------------// using std::numeric_limits; //----<numeric>-------------// using std::iota; using std::gcd; using std::lcm; //--------------------------// class DirectedEdge { private: int v = 0; int w = 0; double weight = numeric_limits< double >::infinity(); public: DirectedEdge() { // not implemented } DirectedEdge( int v, int w, double weight ) : v( v ), w( w ), weight( weight ) { // not implemented } DirectedEdge( const DirectedEdge& e ) : v( e.v ), w( e.w ), weight( e.weight ) { // not implemented } virtual ~DirectedEdge() { // not implemented } int getFrom() const { return v; } int getTo() const { return w; } double getWeight() const { return weight; } operator bool() const { return weight != numeric_limits< double >::infinity(); } string toString() const { ostringstream oss; oss << *this; return oss.str(); } friend ostream& operator <<( ostream& out, const DirectedEdge& e ) { out << fixed << setprecision( 2 ); out << " | " << e.v << " : " << e.w << " : " << e.weight << " | "; return out; } }; class EdgeWeightedDigraph { private: int V = 0; int E = 0; vector< forward_list< DirectedEdge > > adj; public: EdgeWeightedDigraph( int V ) : V( V ), adj( V ) { // not implemented } virtual ~EdgeWeightedDigraph() { // not implemented } int getV() const { return V; } int getE() const { return E; } forward_list< DirectedEdge > getAdj( int v ) const { return adj[ v ]; } forward_list< DirectedEdge > getEdges() const { forward_list< DirectedEdge > all; for ( int v = 0; v < getV(); ++v ) { for ( DirectedEdge e : getAdj( v ) ) { all.push_front( e ); } } return all; } void addEdge( DirectedEdge e ) { adj[ e.getFrom() ].push_front( e ); ++E; } string toString() const { ostringstream oss; oss << *this; return oss.str(); } friend ostream& operator <<( ostream& out, const EdgeWeightedDigraph& G ) { out << "\n| V : " << G.getV() << " ; E : " << G.getE() << " ; adj : \n"; for ( int v = 0; v < G.getV(); ++v ) { out << "\n| v : " << v << " : "; for ( const DirectedEdge& e : G.getAdj( v ) ) { out << e << ", "; } out << " | "; } return out; } }; class DirectedCycle { private: vector< bool > marked; vector< DirectedEdge > edgeTo; vector< bool > onStack; stack< DirectedEdge > cycle; void dfs( const EdgeWeightedDigraph& G, int v ) { marked[ v ] = true; onStack[ v ] = true; for ( DirectedEdge e : G.getAdj( v ) ) { int w = e.getTo(); if ( hasCycle() ) { return; } else if ( ! marked[ w ] ) { edgeTo[ w ] = e; dfs( G, w ); } else if ( onStack[ w ] ) { // cycle detected for ( int x = v; x != w; x = edgeTo[ x ].getFrom() ) { if ( edgeTo[ x ] ) { cycle.push( edgeTo[ x ] ); } } cycle.push( e ); } } onStack[ v ] = false; } public: DirectedCycle( const EdgeWeightedDigraph& G ) : marked( G.getV(), false ), edgeTo( G.getV() ), onStack( G.getV(), false ) { for ( int v = 0; v < G.getV(); ++v ) { if ( ! marked[ v ] ) { dfs( G, v ); } } } virtual ~DirectedCycle() { // not implemented } stack< DirectedEdge > getCycle() const { return cycle; } bool hasCycle() const { return ! cycle.empty(); } string toString() const { ostringstream oss; oss << *this; return oss.str(); } friend ostream& operator <<( ostream& out, const DirectedCycle& dCycle ) { out << "\ncycle:\n"; stack< DirectedEdge > s = dCycle.getCycle(); while ( ! s.empty() ) { out << s.top() << ", "; s.pop(); } return out; } }; class DepthFirstOrder { private: vector< bool > marked; queue< int > pre; queue< int > post; stack< int > reversePost; void dfs( const EdgeWeightedDigraph& G, int v ) { marked[ v ] = true; pre.push( v ); for ( const DirectedEdge& e : G.getAdj( v ) ) { int w = e.getTo(); if ( ! marked[ w ] ) { dfs( G, w ); } } post.push( v ); reversePost.push( v ); } public: DepthFirstOrder( const EdgeWeightedDigraph& G ) : marked( G.getV(), false ) { for ( int v = 0; v < G.getV(); ++v ) { if ( ! marked[ v ] ) { dfs( G, v ); } } } virtual ~DepthFirstOrder() { // not implemented } queue< int > getPre() const { return pre; } queue< int > getPost() const { return post; } stack< int > getReversePost() const { return reversePost; } string toString() const { ostringstream oss; oss << *this; return oss.str(); } friend ostream& operator <<( ostream& out, const DepthFirstOrder& dfo ) { out << "\npre:\n"; queue< int > q = dfo.getPre(); while ( ! q.empty() ) { out << q.front() << ", "; q.pop(); } out << "\npost:\n"; q = dfo.getPost(); while ( ! q.empty() ) { out << q.front() << ", "; q.pop(); } out << "\nreversePost:\n"; stack< int > s = dfo.getReversePost(); while ( ! s.empty() ) { out << s.top() << ", "; s.pop(); } return out; } }; class Topological { private: stack< int > order; public: Topological( const EdgeWeightedDigraph& G ) { DirectedCycle cycleFinder( G ); if ( ! cycleFinder.hasCycle() ) { DepthFirstOrder dfo( G ); order = dfo.getReversePost(); } } virtual ~Topological() { // not implemented } stack< int > getOrder() const { return order; } bool isDAG() const { return ! order.empty(); } string toString() const { ostringstream oss; oss << *this; return oss.str(); } friend ostream& operator <<( ostream& out, const Topological& topo ) { out << "\ntopo:\n"; stack< int > s = topo.getOrder(); while ( ! s.empty() ) { out << s.top() << ", "; s.pop(); } return out; } }; int main( int argc, char ** argv ) { double graphArr[ 13 ][ 3 ] = { { 5, 4, 0.35 }, { 4, 7, 0.37 }, { 5, 7, 0.28 }, { 5, 1, 0.32 }, { 4, 0, 0.38 }, { 0, 2, 0.26 }, { 3, 7, 0.39 }, { 1, 3, 0.29 }, { 7, 2, 0.34 }, { 6, 2, 0.40 }, { 3, 6, 0.52 }, { 6, 0, 0.58 }, { 6, 4, 0.93 } }; EdgeWeightedDigraph ewDigraph( 8 ); for ( int i = 0; i < 13; ++i ) { DirectedEdge e( (int)graphArr[ i ][ 0 ], (int)graphArr[ i ][ 1 ], graphArr[ i ][ 2 ] ); ewDigraph.addEdge( e ); } cout << "DEBUG: ewDigraph: \n" << ewDigraph << endl; Topological topo( ewDigraph ); cout << "DEBUG: topo: \n" << topo << endl; return 0; }
[ "phongvcao@phongvcao.com" ]
phongvcao@phongvcao.com
c22cfb4b1d5aa510dbfa66f41aac631d81efef23
e217eaf05d0dab8dd339032b6c58636841aa8815
/external/Oklabi/Kern-C++/OklabiBucketStore.h
5e20593a9e9d47137ab32cd1d126ace23e78fd84
[]
no_license
bigdoods/OpenInfraPlatform
f7785ebe4cb46e24d7f636e1b4110679d78a4303
0266e86a9f25f2ea9ec837d8d340d31a58a83c8e
refs/heads/master
2021-01-21T03:41:20.124443
2016-01-26T23:20:21
2016-01-26T23:20:21
57,377,206
0
1
null
2016-04-29T10:38:19
2016-04-29T10:38:19
null
UTF-8
C++
false
false
2,099
h
/* Change-Log: * * */ #include "OklabiPackaging.h" #ifdef OKLABI_KERN #ifndef DEFOklabiBucketStore #define DEFOklabiBucketStore #ifdef OKLABI_PACK #pragma pack(push,4) #endif #include <string> #include <list> #include "OklabiMemoryChunk.h" #include "OklabiMemoryChunkStore.h" #include "OklabiKern.h" namespace Oklabi { const UINT64 topSet64(((UINT64)1) << 63); const UINT64 allSet64((UINT64)(-1)); const unsigned int topSet32(0x80000000); const unsigned int allSet32(0xFFFFFFFF); class OklabiBucketStore { public: OklabiBucketStore(size_t size); ~OklabiBucketStore(); void* getBucket() /*throw ( BadAlloc )*/; void* getBucket( size_t ) /*throw ( BadAlloc )*/; void* getBucket( double size ) /*throw ( BadAlloc )*/ { return getBucket((size_t)size); }; void freeBucket( void* ) /*throw (NotPresent)*/; void freeBucket( void* , size_t); void freeBucket( void* p, double size ) { freeBucket(p, (size_t)size); }; size_t getSize(); // Bucketsize (Byte) private: typedef unsigned char Byte; static const unsigned sizWord; static const double d; size_t m_noAdminWords; // #Words for Admin-Entries at Begin of Chunk size_t m_uSize; // Bucketsize (Byte) size_t getNoBuckets( OklabiMemoryChunk* pXMChunk); size_t getOffsStart( OklabiMemoryChunk* pXMChunk ); // Read Free-Bit at npos of Chunk bool getBit(OklabiMemoryChunk* pXMChunk, size_t npos) /*throw (OutOfBounds)*/; // Set Free-Bit at npos of Chunk void setBit(OklabiMemoryChunk* pXMChunk, size_t npos, bool bit) /*throw (OutOfBounds)*/; void* getBucket(OklabiMemoryChunk* pXMChunk, size_t npos) /*throw (OutOfBounds)*/; size_t FindFreeBucket(OklabiMemoryChunk* pChunk); void* getWordAt(OklabiMemoryChunk* pXMChunk, size_t index) /*throw (OutOfBounds)*/; std::list<OklabiMemoryChunk*> listAssociatedChunks; OklabiMemoryChunk* GetNewChunk(size_t minSiz=0) /*throw (CannotCreate)*/; // get another Chunk bool chunkIsEmpty(OklabiMemoryChunk* pXMChunk); void cleanup(); }; class OutOfBounds { public: OutOfBounds() {}; ~OutOfBounds() {}; }; }; #ifdef OKLABI_PACK #pragma pack(pop) #endif #endif #endif
[ "planung.cms.bv@tum.de" ]
planung.cms.bv@tum.de
f996ece3939714817182350a92396a84cff5c639
17cc994a886599a9f99d7d678fd965fa73f9382e
/ShimCity/Boatplane.cpp
eaf88a3f6fdafba6d6558c636c49603f06ead3c4
[]
no_license
hsshimde/justExperiments
a53ca960f14e84b1fb6e38021fcf787146a38131
6a0573fea79ddf49bbb41a09acb1fb246755f6e4
refs/heads/master
2023-04-02T20:19:13.517315
2021-03-30T11:01:58
2021-03-30T11:01:58
296,870,856
0
0
null
null
null
null
UTF-8
C++
false
false
1,525
cpp
#include <cmath> #include "Boatplane.h" namespace assignment2 { Boatplane::Boatplane(unsigned int maxPassengersCount) : Vehicle{maxPassengersCount} { } Boatplane::Boatplane(const Boatplane& rhs) : Vehicle{ rhs } { } Boatplane& Boatplane::operator=(const Boatplane& rhs) { Vehicle::operator=(rhs); return *this; } Boatplane::~Boatplane() { } size_t Boatplane::GetMaxSpeed() const { size_t sailSpeed{ GetSailSpeed() }; size_t flySpeed{ GetFlySpeed() }; return (sailSpeed > flySpeed) ? sailSpeed : flySpeed; } size_t Boatplane::GetFlySpeed() const { size_t passengersCount{ GetPassengersCount() }; size_t totalWeight{}; for (size_t i{}; i < passengersCount; ++i) { totalWeight += GetPassenger(i)->GetWeight(); } double power{ (static_cast<double>(totalWeight) * (-1) + 500) / 300 }; size_t flySpeed{ static_cast<size_t>(std::floor(std::exp(power) * 150 + 0.5)) }; //150 * e ^ ((-x + 500) / 300) return flySpeed; } size_t Boatplane::GetSailSpeed() const { size_t passengersCount{ GetPassengersCount() }; size_t totalWeight{}; for (size_t i{}; i < passengersCount; ++i) { totalWeight += GetPassenger(i)->GetWeight(); } //MAX((800 - 1.7x), 20) return static_cast<size_t>(std::max<double>(800 - 1.7 * static_cast<double>(totalWeight), 20.0)); } bool Boatplane::GoOnTravel() { size_t travelCount{ GetTravelCount() }; IncreaseTravelCount(); if (travelCount % 4 == 1) { return true; } else { return false; } } }
[ "hsshimde@outlook.com" ]
hsshimde@outlook.com
5c85ea742fddb54a4639498525642b71985940c1
73f5267f6c087c5a1c63d67229a46d0379be2335
/include/mapping_msgs/CollisionObjectOperation.h
30396290071d34f186f594094d6664bb6425d1de
[]
no_license
zphilip/handDetect
a4cc74ef3659f765b836a69dbdd061bdb64a1d10
7114f54198b748dacf64dfdcfe90e09c05f903c1
refs/heads/master
2016-09-05T15:00:14.950589
2012-10-11T06:38:22
2012-10-11T06:38:22
5,794,632
1
2
null
null
null
null
UTF-8
C++
false
false
8,139
h
/* Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Auto-generated by genmsg_cpp from file c:\work\ws\mapping_msgs\msg\CollisionObjectOperation.msg * */ #ifndef MAPPING_MSGS_MESSAGE_COLLISIONOBJECTOPERATION_H #define MAPPING_MSGS_MESSAGE_COLLISIONOBJECTOPERATION_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace mapping_msgs { template <class ContainerAllocator> struct CollisionObjectOperation_ { typedef CollisionObjectOperation_<ContainerAllocator> Type; CollisionObjectOperation_() : operation(0) { } CollisionObjectOperation_(const ContainerAllocator& _alloc) : operation(0) { } typedef int8_t _operation_type; _operation_type operation; enum { ADD = 0 }; enum { REMOVE = 1 }; enum { DETACH_AND_ADD_AS_OBJECT = 2 }; enum { ATTACH_AND_REMOVE_AS_OBJECT = 3 }; typedef boost::shared_ptr< ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator> const> ConstPtr; boost::shared_ptr<std::map<std::string, std::string> > __connection_header; }; // struct CollisionObjectOperation_ typedef ::mapping_msgs::CollisionObjectOperation_<std::allocator<void> > CollisionObjectOperation; typedef boost::shared_ptr< ::mapping_msgs::CollisionObjectOperation > CollisionObjectOperationPtr; typedef boost::shared_ptr< ::mapping_msgs::CollisionObjectOperation const> CollisionObjectOperationConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator> & v) { ros::message_operations::Printer< ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace mapping_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False} // {'geometric_shapes_msgs': ['c:/work/ws/geometric_shapes_msgs/msg'], 'geometry_msgs': ['c:/work/ws/geometry_msgs/msg'], 'mapping_msgs': ['c:/work/ws/mapping_msgs/msg', 'c:/work/ws/mapping_msgs/msg'], 'std_msgs': ['c:/work/ws/std_msgs/msg'], 'sensor_msgs': ['c:/work/ws/sensor_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator> > { static const char* value() { return "66a2b3b971d193145f8da8c3e401a474"; } static const char* value(const ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x66a2b3b971d19314ULL; static const uint64_t static_value2 = 0x5f8da8c3e401a474ULL; }; template<class ContainerAllocator> struct DataType< ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator> > { static const char* value() { return "mapping_msgs/CollisionObjectOperation"; } static const char* value(const ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator> > { static const char* value() { return "#Puts the object into the environment\n\ #or updates the object if already added\n\ byte ADD=0\n\ \n\ #Removes the object from the environment entirely\n\ byte REMOVE=1\n\ \n\ #Only valid within the context of a CollisionAttachedObject message\n\ #Will be ignored if sent with an CollisionObject message\n\ #Takes an attached object, detaches from the attached link\n\ #But adds back in as regular object\n\ byte DETACH_AND_ADD_AS_OBJECT=2\n\ \n\ #Only valid within the context of a CollisionAttachedObject message\n\ #Will be ignored if sent with an CollisionObject message\n\ #Takes current object in the environment and removes it as\n\ #a regular object\n\ byte ATTACH_AND_REMOVE_AS_OBJECT=3\n\ \n\ # Byte code for operation\n\ byte operation\n\ \n\ "; } static const char* value(const ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.operation); } ROS_DECLARE_ALLINONE_SERIALIZER; }; // struct CollisionObjectOperation_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::mapping_msgs::CollisionObjectOperation_<ContainerAllocator>& v) { s << indent << "operation: "; Printer<int8_t>::stream(s, indent + " ", v.operation); } }; } // namespace message_operations } // namespace ros #endif // MAPPING_MSGS_MESSAGE_COLLISIONOBJECTOPERATION_H
[ "zphilip2000@hotmail.com" ]
zphilip2000@hotmail.com
9225671fd42e2730e21212ed269c8bca8b7c0deb
e1694830058a721d2a6605f60a53c805d679a337
/DynamicProjectionMapping/rbf.h
5a35f81bd1780de19d0517701780200e032897aa
[]
no_license
smygw72/Dynamic-Projection-Mapping
b5074eaeef23e6c186f189129da1c2636e53ae21
62a8ccb05ed9f2be3dc4cc15bc6588ec67f992e4
refs/heads/main
2023-08-07T23:54:53.755405
2021-09-12T02:32:23
2021-09-12T02:32:23
350,939,830
2
0
null
null
null
null
SHIFT_JIS
C++
false
false
644
h
#pragma once #include "head.h" /////////////////////////////////////////////////////////////////////////////// //   マーカ部分の明度を補間するためにRBF補間を用いる     // /////////////////////////////////////////////////////////////////////////////// using namespace std; class RBF { private: int N; // データの数 vector<cv::Point2i> X; Eigen::MatrixXf Y; Eigen::MatrixXf W; Eigen::MatrixXf Phi; public: RBF(); ~RBF() {}; void SetY(const cv::Mat roi); void SetPhi(); void SetW(); int GetValue(const int x, const int y); void Exe(cv::Mat& roi); };
[ "smygw72@gmail.com" ]
smygw72@gmail.com
7cbc99ac4ebd08fbc69f2643be6d70c22c6edec7
0d74161c499ac2287b1d0ecb444aa92b220cda11
/httpserver/hostMapper.cpp
3051cf48779f5c70a06592116327238ec7059cc0
[ "MIT" ]
permissive
ondra-novak/jsonrpcserver
70e19c7d1f269c109412764e7ac18706479f98cb
878f5f7a981a326dcb39d43d0bb5c4eac213a65c
refs/heads/master
2020-04-04T07:34:52.097615
2019-12-13T08:42:59
2019-12-13T08:42:59
27,509,171
1
0
null
null
null
null
UTF-8
C++
false
false
6,321
cpp
#include "hostMapper.h" #include "lightspeed/base/text/textParser.tcc" #include "lightspeed/base/memory/smallAlloc.h" #include "lightspeed/base/containers/map.tcc" namespace BredyHttpSrv { void HostMapper::registerUrl(ConstStrA baseUrlFormat) { processUrl(baseUrlFormat, false); } void HostMapper::processUrl(ConstStrA baseUrlFormat, bool unreg) { TextParser<char, SmallAlloc<256> > parser; StringA data; ConstStrA host; ConstStrA path; ConstStrA protocol; ConstStrA targetVPath; if (parser(" %[a-zA-Z0-9]1://%[a-zA-Z0-9-._:]2%%[/](*)[*^> ]3 -> %4 ", baseUrlFormat)) { data = baseUrlFormat; protocol = ConstStrA(parser[1].str()).map(data); host = ConstStrA(parser[2].str()).map(data); path = ConstStrA(parser[3].str()).map(data); targetVPath = ConstStrA(parser[4].str()).map(data); } else if (parser(" %[a-zA-Z0-9]1://%[a-zA-Z0-9-._:]2%%[/](*)[^> ]3 ", baseUrlFormat)) { data = baseUrlFormat; protocol = ConstStrA(parser[1].str()).map(data); host = ConstStrA(parser[2].str()).map(data); path = ConstStrA(parser[3].str()).map(data); targetVPath = (path.empty() || path.tail(1) == ConstStrA("/"))?ConstStrA("/"):ConstStrA(); } else { throw MappingSyntaxError(THISLOCATION, baseUrlFormat); } if (host == "%") { if (unreg) defaultMapping = Mapping(); else defaultMapping = Mapping(data, protocol, path, targetVPath); } else { if (unreg) { mapping.erase(host); } else { mapping.replace(host, Mapping(data, protocol, path, targetVPath)); } } } void HostMapper::registerHost(ConstStrA host, ConstStrA protocol, ConstStrA path, ConstStrA targetVPath) { StringA data = host + protocol + path + targetVPath; host = data.head(host.length()); protocol = data.mid(host.length(), protocol.length()); path = data.mid(host.length() + protocol.length(), path.length()); targetVPath = data.mid(host.length() + protocol.length() + path.length(), targetVPath.length()); if (host == "%") defaultMapping = Mapping(data, protocol, path, targetVPath); else mapping.replace(host, Mapping(data, protocol, path, targetVPath)); } StringKey<StringA> HostMapper::mapRequest(ConstStrA host, ConstStrA path) { const Mapping *mp = mapping.find(host); if (mp == 0) mp = &defaultMapping; if (path.head(mp->path.length()) != mp->path) throw NoMappingException(THISLOCATION, StringA(host+path)); if (mp->targetVPath.empty()) return StringKey<StringA>(ConstStrA(path.offset(mp->path.length()))); else return StringKey<StringA>(StringA(mp->targetVPath + path.offset(mp->path.length()))); } LightSpeed::StringA HostMapper::getBaseUrl(ConstStrA host) { const Mapping *mp = mapping.find(host); if (mp == 0) mp = &defaultMapping; return StringA(mp->protocol + ConstStrA("://") + host + mp->path); } void HostMapper::unregisterUrl(ConstStrA mapLine) { processUrl(mapLine, true); } LightSpeed::StringA HostMapper::getAbsoluteUrl(ConstStrA host, ConstStrA curPath, ConstStrA relpath) { const Mapping *mp = mapping.find(host); if (mp == 0) mp = &defaultMapping; StringA tmp; if (relpath.empty()) { //if relpath is empty, we can directly create url using curent path //combine protocol://host/curpath return StringA(mp->protocol + ConstStrA("://") + host + curPath); } else if (relpath.head(2) == ConstStrA("+/")) { natural q = relpath.find('?'); natural p = curPath.find('?'); ConstStrA query; if (p != naturalNull) { query = curPath.offset(p); curPath = curPath.head(p); }; if (q != naturalNull) query.empty(); return StringA(mp->protocol + ConstStrA("://") + host + curPath + relpath.offset(1)+query); } else if (relpath[0] == '/') { //path relative to host root //path must respect current vpath mapping //so if host's root is mapped to some vpath, we need to remove that part from the relpath //check whether this is valid request //in context of host, function cannot create url to the paths outside of mapping if (relpath.head(mp->targetVPath.length()) == mp->targetVPath) { //now adjust host's relpath relpath = relpath.offset(mp->targetVPath.length()); //no add host's path from the mapping if (!mp->path.empty()) { //check path for ending slash bool endslash = mp->path.tail(1) == ConstStrA('/'); //check relpath for starting slash bool startslash = relpath.head(1) == ConstStrA('/'); //if both have slash if (endslash && startslash) { //remove starting slash and combine path tmp = mp->path + relpath.offset(1); } //neither both have slash else if (!endslash && !startslash) { //put slash between path and relpath tmp = mp->path + ConstStrA('/') + relpath; } else { //combine paths tmp = mp->path + relpath; } relpath = tmp; } //no we have path // 1. removed vpath offset from mapping // 2. added host's offset from mapping // (reversed mapping) //finally, check, whether there is slash at begging if (relpath.head(1) == ConstStrA('/')) { //if not. pretend one '/' tmp = ConstStrA("/") + relpath; relpath = tmp; } //combine protocol://host/relpath return StringA(mp->protocol + ConstStrA("://") + host + relpath); } else { throw NoMappingException(THISLOCATION,relpath); } } else { //remove query: /aa/bbb/c?x=0 -> /aa/bbb/c natural query = curPath.find('?'); if (query != naturalNull) curPath = curPath.head(query); //remove filename: /aa/bbb/c -> /aa/bbb/ natural slash = curPath.findLast('/'); curPath = curPath.head(slash + 1); //combine protocol://host/path/relpath return StringA(mp->protocol + ConstStrA("://") + host + curPath + relpath); } } void HostMapper::NoMappingException::message(ExceptionMsg &msg) const { msg("No mapping for given host and path: %1") << path; } LightSpeed::ConstStrA HostMapper::MappingExistException::getHost() const { return host; } void HostMapper::MappingExistException::message(ExceptionMsg &msg) const { msg("Mapping already exists for the host %1") << host; } void HostMapper::MappingSyntaxError::message(ExceptionMsg &msg) const { msg("Host mapping - syntax error: %1") << line; } }
[ "ondra-novak@email.cz" ]
ondra-novak@email.cz
106597b836f7295535759780b637505f33f25960
2cfd7cf75080d921dfde9c0a1842bf63be685d01
/algocoding/algocoding/CountingSort.cpp
01755869e1c19753e638317a175be25f8f176003
[]
no_license
rahulnairiit/VisualStudiocodes
26f9304e56036d97c0673195358e3e5c5acbacc3
f77c2bdbfbfb23398f8f15c710f0e7977ccf5b13
refs/heads/master
2021-01-19T09:23:46.745700
2012-04-26T01:02:48
2012-04-26T01:02:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,658
cpp
#include <iostream> using namespace std; // Input of n integers which fall in the range of 0 to k.. // we can efficiently use cout sort wen k is O(n) void countsort(int * ,int * , int , int ); void main() { int i; int inpta[10] = { 1,2,3,7,2,9,2,6,1,5 }; int outpta[10] = { 0 }; cout<< " input arr is "<<inpta<<endl; countsort(inpta,outpta,10,9); //for( i = 0 ; i < 10; i++ ) //{ // cout<<outpta[i]; //} getchar(); } void countsort(int inpta[],int outa[], int count, int range) { int n = count; int i; int * tempCounta ; tempCounta =(int*) calloc(range,sizeof(int)); //cout<<inpta<<endl; for( i = 0 ; i < 10; i++ ) { cout<<inpta[i]; } cout<<"s0000000000000"<<endl; for( i=0; i<range; i++) // initialize the count array { tempCounta[i] = 0; } for( i = 0; i<n; i++ ) // set the count of each number appearing in the input { tempCounta[inpta[i]] = tempCounta[inpta[i]] + 1; cout << " i is "<<i<< "and inpta[i] is "<<inpta[i]<<endl; } for( i = 0 ; i < 10; i++ ) { cout<<tempCounta[i]; } cout<<"s0000000000000"<<endl; //Now for each number in the tempCounta update the value to number of // elements less than or equal to that number for( i =0; i< range; i++ ) { if(i == 0 ) { tempCounta[i] = tempCounta[i] ;; } else tempCounta[i] = tempCounta[i] + tempCounta[i - 1]; } cout<<endl; for( i = 0 ; i < range; i++ ) { cout<<tempCounta[i]; } //Now start populating the output array for( i = 10; i >= 1; i--) { outa[tempCounta[inpta[i]]]= inpta[i]; tempCounta[inpta[i]] = tempCounta[inpta[i]] - 1; } for(i = 0 ; i < n; i++ ) { cout<<outa[i]; } //cout<<outa<<endl; }
[ "rahul.banglre@gmail.com" ]
rahul.banglre@gmail.com
2a41fa71d58b876c3e5c709c8ca45c400a6687b6
cd11d2e3aa7e050554cd745dcf713abb7a11e929
/XGames/Prince/Classes/TowerModule/LayerTreasure.h
c2577896b7a99fabf0cff3b4d3dd1bd2f1adcee1
[]
no_license
daxingyou/XGame
3cdc2c9ab06be55ed80aed6c99cb6aa77073b139
5fd0140bc398edc374306067bb258b323604b9cb
refs/heads/main
2023-04-16T21:23:20.368638
2021-04-20T16:35:17
2021-04-20T16:35:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,048
h
/******************************************************************* * Copyright(c) 2015 zcjoy All rights reserved. * * FileName: LayerTreasure * Description: 发现宝藏界面; * Version: 1.0 * Author: Phil * Date: 04/20/2015 * Others: * ******************************************************************/ #ifndef LayerTreasure_h__ #define LayerTreasure_h__ #include "TowerDef.h" #include "Utils/Observer.h" #include "LayerTrail.h" class TreasureNode : public Node { public: ~TreasureNode(); static TreasureNode* create(int nTemplateId, int nCount, string strName); virtual bool init(int nTemplateId, int nCount, string strName); void setOpened(bool bOpened); bool isOpend() { return m_bIsOpend; }; int getCount() { return m_nCount; }; private: TreasureNode(); void initUI(int nTemplateId, int nCount, string strName); private: UI_Treasure_Node m_ui; bool m_bIsOpend; int m_nCount; }; class LayerTrail; class LayerTreasure : public Layer, public Observer { public: ~LayerTreasure(void); static LayerTreasure* create(); virtual bool init(); virtual void onEnter(); virtual void onExit(); virtual void update(float delta); virtual void updateSelf(void* pData); void onBtnClicked( Ref* ref, Widget::TouchEventType type, int nWidgetName ); void refreshTreasure(multimap<int, int> mapInfo); void openTreasure(); void checkIsTreasureOpend(float delta); // 设置父节点; void setParent(LayerTrail* parent) { m_pParent = parent; }; private: LayerTreasure(void); void showTouchContinue(); void onLayerTouched(Ref* ref, Widget::TouchEventType type); void initUI(); void updateGold(); private: UI_Treasure m_ui; multimap<int, TreasureNode*> m_mapTreasure; // 父节点; LayerTrail* m_pParent; vector<int> m_vcOpendTreasure; bool m_bIsFirstEnter; Armature* _armatureLight; enum UI_TREASURE_WIDGET { Lab_Gold, Btn_Close, Btn_Open, Lab_Cost, Btn_Refresh, Lab_Refresh_Cost }; }; #endif // LayerTreasure_h__
[ "635459675@qq.com" ]
635459675@qq.com
2f419e18c1a8c203456bb5175ef0a560f2c2e7ed
53d4a4ed468941ace04d92da75bdac2285c377fe
/Part-III/Ch16/16.2.2/16.37.cc
665e07d4c79dabd5eb295aeb26683bf7c805f996
[ "MIT" ]
permissive
RingZEROtlf/Cpp-Primer
c937cad3342950d4f211907b7fb7044260bc09cc
bde40534eeca733350825c41f268415fdccb1cc3
refs/heads/master
2022-12-22T18:52:01.163191
2020-09-25T07:45:13
2020-09-25T07:45:13
285,617,317
1
0
null
null
null
null
UTF-8
C++
false
false
102
cc
#include <iostream> #include <algorithm> int main() { std::cout << std::max(1, 2.0) << std::endl; }
[ "RingZEROtlf@outlook.com" ]
RingZEROtlf@outlook.com
b960c8dd32401c799f46b22b8b0d930060abf570
c005bbc7525f6810d01cedcd56495482ba375f2f
/method.cc
78a31c3ac4bc423b0729bf50ed8387081f3a040a
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
Chungzuwalla/ici
a8d9ae2ad3bc4f6c1754765126c7186df442b184
8240fbe36ef8c9f67f101e9798f9d6d36dd27d27
refs/heads/master
2020-04-20T06:23:34.743227
2019-01-18T08:57:31
2019-01-18T08:57:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,802
cc
#define ICI_CORE #include "fwd.h" #include "method.h" #include "exec.h" #include "buf.h" #include "null.h" #include "primes.h" #include "str.h" #ifndef NOPROFILE #include "profile.h" #endif namespace ici { /* * Returns a new ICI method object that combines the given 'subject' object * (typically a struct) with the given 'callable' object (typically a * function). A method is also a callable object. * * Returns nullptr on error, usual conventions. * * This --func-- forms part of the --ici-api--. */ method *new_method(object *subject, object *callable) { method *m; if ((m = ici_talloc(method)) == nullptr) return nullptr; set_tfnz(m, TC_METHOD, 0, 1, 0); m->m_subject = subject; m->m_callable = callable; rego(m); return m; } size_t method_type::mark(object *o) { auto m = methodof(o); return type::mark(m) + ici_mark(m->m_subject) + ici_mark(m->m_callable); } object * method_type::fetch(object *o, object *k) { auto m = methodof(o); if (k == SS(subject)) return m->m_subject; if (k == SS(callable)) return m->m_callable; return null; } int method_type::call(object *o, object *) { auto m = methodof(o); if (!m->m_callable->can_call()) { char n1[objnamez]; char n2[objnamez]; return set_error ( "attempt to call %s:%s", ici::objname(n1, m->m_subject), ici::objname(n2, m->m_callable) ); } return m->m_callable->call(m->m_subject); } void method_type::objname(object *o, char p[objnamez]) { char n1[objnamez]; char n2[objnamez]; ici::objname(n1, methodof(o)->m_subject); ici::objname(n2, methodof(o)->m_callable); sprintf(p, "(%.13s:%.13s)", n1, n2); } } // namespace ici
[ "an@atrn.org" ]
an@atrn.org
9386112279a34ba09bfa38248c7026f03ea4a31d
b7549e543dea772774f92bb09e4af77a25cd3220
/makefile/test/make-p/sub/subd.cxx
1764932f5cf08dc133a760cb6b8d431350d462eb
[]
no_license
snoopspy/template
f6856fd24f5c39878dc4c4c8c540fd9f5fe6ebd5
f23fbea5bd177bd43dd7e9b06b44cc8c20312787
refs/heads/master
2020-04-25T15:07:16.246326
2015-04-22T06:08:29
2015-04-22T06:08:29
31,304,345
0
1
null
null
null
null
UTF-8
C++
false
false
71
cxx
#include <stdio.h> extern "C" void subd() { printf("subd.cxx\n"); }
[ "gilgil@gilgil.net" ]
gilgil@gilgil.net
74a1d205205e9d05bac1144009ea9ec65aa9e71c
0bc4186fee113a3c9e740f47a82ddb79b8dbe7ad
/Weekly Assignments/Week1/Box2D Demo/src/Game.cpp
36e5ce609bcec41c3e52a38476c954bf93624976
[]
no_license
uhhgoat/AngryBirdsPrototype
8080db3f2115eff777c9a93b81c13c47dc9934ba
4c7ba585386da70a0fe3f6f2ceb9589828f5e184
refs/heads/master
2020-12-28T14:41:41.463088
2020-02-05T05:33:51
2020-02-05T05:33:51
238,374,827
0
0
null
null
null
null
UTF-8
C++
false
false
12,591
cpp
#include <sb6.h> #include <sb6ktx.h> #include <math.h> #include <assert.h> #include "DebugOut.h" #include "GameObject.h" #include "MathEngine.h" #include "Game.h" #include "GraphicsObject.h" #include "GraphicsObject_Sprite.h" #include "GraphicsObject_Circle.h" #include "GraphicsObject_Box.h" #include "GraphicsObject_Tri.h" #include "TextureMan.h" #include "Camera.h" #include "GameObjectMan.h" #include "CameraMan.h" #include "Image.h" #include "GameObject2D.h" #include "Color.h" #include "Vect2D.h" #include "ShaderMan.h" #include "ImageMan.h" #include "DebugOut.h" #include "ModelMan.h" #include "AzulStopWatch.h" #include "TimerMan.h" #include "Keyboard.h" #include "Mouse.h" #include "RedBird.h" #include "BlueBird.h" #include "YellowBird.h" #include "GreenBird.h" #include "BlackBird.h" #include "WhiteBird.h" #include "BigRedBird.h" #include "KingPig.h" #include "QueenPig.h" #include "WoodBlockShort.h" #include "WoodBlockMed.h" #include "WoodBlockLong.h" #include "GlassBlockShort.h" #include "GlassBlockMed.h" #include "GlassBlockLong.h" Game* Game::ptrInstance = nullptr; #include "Box2D.h" #include "PixelToMeter.h" WoodBlockLong *WBL; GlassBlockLong *GBL; WoodBlockMed *WBM; GlassBlockMed *GBM; WoodBlockShort *WBS; GlassBlockShort *GBS; RedBird* rB; BlueBird* blB; YellowBird* yB; GreenBird* gB; BlackBird* bkB; WhiteBird* wB; BigRedBird* brB; GameSortBucket* pSortBkt; //----------------------------------------------------------------------------- // Game::Game() // Game Engine Constructor //----------------------------------------------------------------------------- Game::Game(const char* windowName, const int Width, const int Height) :Engine(windowName, Width, Height) { ptrInstance = this; screenWidth = static_cast<float>(Width); screenHeight = static_cast<float>(Height); } //----------------------------------------------------------------------------- // Game::Initialize() // Allows the engine to perform any initialization it needs to before // starting to run. This is where it can query for any required services // and load any non-graphic related content. //----------------------------------------------------------------------------- void Game::Initialize() { // Initialize timer AzulStopWatch::initStopWatch(); // Start timer stopWatch.tic(); totalWatch.tic(); //--------------------------------------------------------------------------------------------------------- // Box2D setup //--------------------------------------------------------------------------------------------------------- // Gravity in Y direction b2Vec2 gravity(0.0, -10.0f); pWorld = new b2World(gravity); // scale: pixels per meter UnitScale::Create(50); } //----------------------------------------------------------------------------- // Game::LoadContent() // Allows you to load all content needed for your engine, // such as objects, graphics, etc. //----------------------------------------------------------------------------- void Game::LoadContent() { //--------------------------------------------------------------------------------------------------------- // Setup the current 2D orthographic Camera //--------------------------------------------------------------------------------------------------------- Camera *pCam2D = new Camera(Camera::Type::ORTHOGRAPHIC_2D); pCam2D->setViewport(0, 0, (int)this->screenWidth, (int)this->screenHeight); pCam2D->setOrthographic(-pCam2D->getScreenWidth() / 2.0f, pCam2D->getScreenWidth() / 2.0f, -pCam2D->getScreenHeight() / 2.0f, pCam2D->getScreenHeight() / 2.0f, 1.0f, 1000.0f); pCam2D->setOrientAndPosition(Vect(0.0f, 1.0f, 0.0f), Vect(0.0f, 0.0f, -1.0f), Vect(0.0f, 0.0f, 0.0f)); // Holder for the current 2D cameras CameraMan::SetCurrentCamera(pCam2D, Camera::Type::ORTHOGRAPHIC_2D); //--------------------------------------------------------------------------------------------------------- // Load up the managers //--------------------------------------------------------------------------------------------------------- // Create/Load Shader ShaderMan::addShader(ShaderName::SPRITE, "spriteRender"); ShaderMan::addShader(ShaderName::SPRITE_LINE, "spriteLineRender"); // Textures TextureMan::addTexture("../../../../../reference/Asset/AngryBirds/unsorted.tga", TextName::Characters); TextureMan::addTexture("../../../../../reference/Asset/AngryBirds/woodBlocks.tga", TextName::WoodBlocks); TextureMan::addTexture("../../../../../reference/Asset/AngryBirds/glassBlocks.tga", TextName::GlassBlocks); TextureMan::addTexture("../../../../../reference/Asset/AngryBirds/stoneBlocks.tga", TextName::StoneBlocks); // Images ImageMan::addImage(ImageName::KingPig, TextName::Characters, Rect(40, 1, 127, 153)); ImageMan::addImage(ImageName::QueenPig, TextName::Characters, Rect(40, 466, 127, 153)); ImageMan::addImage(ImageName::RedBird, TextName::Characters, Rect(903, 798, 46, 45)); ImageMan::addImage(ImageName::BlueBird, TextName::Characters, Rect(0, 378, 32, 31)); ImageMan::addImage(ImageName::YellowBird, TextName::Characters, Rect(667, 879, 59, 55)); ImageMan::addImage(ImageName::GreenBird, TextName::Characters, Rect(932, 529, 99, 72)); ImageMan::addImage(ImageName::WhiteBird, TextName::Characters, Rect(409, 352, 81, 94)); ImageMan::addImage(ImageName::BlackBird, TextName::Characters, Rect(409, 725, 62, 80)); ImageMan::addImage(ImageName::BigRedBird, TextName::Characters, Rect(298, 752, 97, 95)); ImageMan::addImage(ImageName::WoodBlockShort, TextName::WoodBlocks, Rect(288, 344, 83, 21)); ImageMan::addImage(ImageName::WoodBlockMed, TextName::WoodBlocks, Rect(288, 257, 168, 21)); ImageMan::addImage(ImageName::WoodBlockLong, TextName::WoodBlocks, Rect(288, 169, 205, 21)); ImageMan::addImage(ImageName::GlassBlockShort, TextName::GlassBlocks, Rect(288, 346, 83, 21)); ImageMan::addImage(ImageName::GlassBlockMed, TextName::GlassBlocks, Rect(288, 259, 168, 21)); ImageMan::addImage(ImageName::GlassBlockLong, TextName::GlassBlocks, Rect(288, 215, 205, 21)); //--------------------------------------------------------------------------------------------------------- // Sort buckets (AKA sprite layers) //--------------------------------------------------------------------------------------------------------- pSortBkt = new GameSortBucket(GameObjectName::MainGroup); GameObjectMan::Add(pSortBkt); //--------------------------------------------------------------------------------------------------------- // Create Sprites //--------------------------------------------------------------------------------------------------------- // Sprite WBL = new WoodBlockLong(650, 100, 0.0f, *pWorld); GameObjectMan::Add(WBL, GameObjectName::MainGroup); GBL = new GlassBlockLong(1150, 100, 0.0f, *pWorld); GameObjectMan::Add(GBL, GameObjectName::MainGroup); WBM = new WoodBlockMed(200, 200, -0.2f, *pWorld); GameObjectMan::Add(WBM, GameObjectName::MainGroup); GBM = new GlassBlockMed(1600, 200, 0.2f, *pWorld); GameObjectMan::Add(GBM, GameObjectName::MainGroup); WBS = new WoodBlockShort(650, 500, 0.4f, *pWorld); GameObjectMan::Add(WBS, GameObjectName::MainGroup); GBS = new GlassBlockShort(1150, 500, -0.4f, *pWorld); GameObjectMan::Add(GBS, GameObjectName::MainGroup); rB = new RedBird(350, 900, 0.0f, true, *pWorld); GameObjectMan::Add(rB, GameObjectName::MainGroup); blB = new BlueBird(1300, 900, 0.0f, true, *pWorld); GameObjectMan::Add(blB, GameObjectName::MainGroup); gB = new GreenBird(1100, 900, 0.0f, true, *pWorld); GameObjectMan::Add(gB, GameObjectName::MainGroup); yB = new YellowBird(900, 900, 0.0f, true, *pWorld); GameObjectMan::Add(yB, GameObjectName::MainGroup); wB = new WhiteBird(700, 900, 0.0f, true, *pWorld); GameObjectMan::Add(wB, GameObjectName::MainGroup); bkB = new BlackBird(500, 900, 0.0f, true, *pWorld); GameObjectMan::Add(bkB, GameObjectName::MainGroup); brB = new BigRedBird(600, 900, 0.0f, true, *pWorld); GameObjectMan::Add(brB, GameObjectName::MainGroup); //---------------------------------------------------------------------------------------- // Ground box - Box2D setup //---------------------------------------------------------------------------------------- //CONSOLIDATED INTO CLASS //---------------------------------------------------------------------------------------- // Red Bird - Box2D setup //---------------------------------------------------------------------------------------- //CONSOLIDATED INTO CLASS } //----------------------------------------------------------------------------- // Game::Update() // Called once per frame, update data, tranformations, etc // Use this function to control process order // Input, AI, Physics, Animation, and Graphics //----------------------------------------------------------------------------- void Game::Update(float currentTime) { // Time update. // Get the time that has passed. // Feels backwards, but its not, need to see how much time has passed stopWatch.toc(); stopWatch.tic(); totalWatch.toc(); // Update cameras - make sure everything is consistent Camera *pCam2D = CameraMan::GetCurrent(Camera::Type::ORTHOGRAPHIC_2D); pCam2D->updateCamera(); TimerMan::Update(); // ------------- Add your update below this line: ---------------------------- // Phase 1: Physics Update - Step world---------------------------- int velocityIterations = 8; int positionIterations = 3; float timestep = 1.0f / 60; // 60 fps. Box2D does not recommend tying this to framerate pWorld->Step(timestep, velocityIterations, positionIterations); // Phase 2: Update the associated GameObjectsd -------------------- b2Body *pBody = pWorld->GetBodyList(); while (pBody != 0) // Loop through all the bodies in the Box2D { b2Fixture *pFix = pBody->GetFixtureList(); while (pFix != 0) // For each body, loop through all its fixtures { // For a given fixture, get the associated GameObject2D GameObject2D *pGObj = static_cast<GameObject2D*>(pFix->GetUserData()); b2Vec2 fixCenter; if (pBody->IsActive()) { fixCenter = pFix->GetAABB(0).GetCenter(); } else { // Must extract the center this way when body is inactive b2AABB tmpAABB; pFix->GetShape()->ComputeAABB(&tmpAABB, pBody->GetTransform(), 0); fixCenter = tmpAABB.GetCenter(); } float ang = pBody->GetAngle(); pGObj->PhysicsUpdate(fixCenter, ang); pFix = pFix->GetNext(); } pBody = pBody->GetNext(); } // Phase 3: Let the engine update all the game objects normally GameObjectMan::Update(currentTime); } //----------------------------------------------------------------------------- // Game::Draw() // This function is called once per frame // Use this for draw graphics to the screen. // Only do rendering here //----------------------------------------------------------------------------- void Game::Draw() { // draw all objects GameObjectMan::Draw(); } //----------------------------------------------------------------------------- // Game::UnLoadContent() // unload content (resources loaded above) // unload all content that was loaded before the Engine Loop started //----------------------------------------------------------------------------- void Game::UnLoadContent() { delete rB; delete blB; delete gB; delete yB; delete wB; delete bkB; delete brB; delete WBS; delete WBM; delete WBL; delete GBS; delete GBM; delete GBL; delete pSortBkt; // Engine clean-up CameraMan::Terminate(); ModelMan::Terminate(); ShaderMan::Terminate(); TextureMan::Terminate(); ImageMan::Terminate(); GameObjectMan::Terminate(); TimerMan::Terminate(); } //------------------------------------------------------------------ // Game::ClearBufferFunc() // Allows user to change the way the clear buffer function works //------------------------------------------------------------------ void Game::ClearBufferFunc() { const GLfloat blue[] = { 0.6f, 0.6f, 0.6f, 1.0f }; const GLfloat one = 1.0f; glViewport(0, 0, info.windowWidth, info.windowHeight); glClearBufferfv(GL_COLOR, 0, blue); glClearBufferfv(GL_DEPTH, 0, &one); } float Game::GetFrameTime() { return Instance().stopWatch.timeInSeconds(); } float Game::GetTotalTime() { return Instance().totalWatch.timeInSeconds(); } Game::~Game() { delete pWorld; } void Game::Run(const char* windowName, const int Width, const int Height) { ptrInstance = new Game(windowName, Width, Height); ptrInstance->run(); delete ptrInstance; }
[ "matyas@fenyves.net" ]
matyas@fenyves.net
d9d0607a1a28bc9fbd5b3882dc965b9247030d70
4df46993262e19afb957380b6ca1828e5b1fafec
/source/FileManagement.h
9b3303eec2a0a42e7f0362d374ac32b875f1b749
[ "MIT" ]
permissive
fallscameron01/List_Manager
2386ae6501670b83972fcae9954065d6db89a415
7025eff39cf1da0786d51a3b5371fdc482298d88
refs/heads/master
2022-10-20T21:14:52.717915
2020-06-02T21:25:06
2020-06-02T21:25:06
253,299,863
0
0
null
null
null
null
UTF-8
C++
false
false
899
h
/* Programmer: Cameron Falls File: FileManagement.h Purpose: This file contains the declarations for file related functions. */ #ifndef FILEMANAGEMENT_H #define FILEMANAGEMENT_H #define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING #include <experimental/filesystem> #include <string> #include <vector> #include "TaskGroup.h" namespace fs = std::experimental::filesystem; using namespace std; /* Description: Loads all lists in the directory Lists/ into groups. Parameters: groups - holds the loaded lists Returns: none. */ void loadLists(vector<TaskGroup>& groups); /* Description: Checks if a list name is valid. Parameters: groups - all the lists, to check if the name is already in use. name - the name being checked. Returns: bool - whether or not the name is valid. */ bool nameIsValid(const vector<TaskGroup>& groups, const string& name); #endif
[ "camfalls0201@gmail.com" ]
camfalls0201@gmail.com
32cc265b5a3395b08626ae2392529a82d3c7b617
7fc9ca1aa8c9281160105c7f2b3a96007630add7
/977F.cpp
55ecfec4da5955c4e19b1af82a59a05d8755508b
[]
no_license
PatelManav/Codeforces_Backup
9b2318d02c42d8402c9874ae0c570d4176348857
9671a37b9de20f0f9d9849cd74e00c18de780498
refs/heads/master
2023-01-04T03:18:14.823128
2020-10-27T12:07:22
2020-10-27T12:07:22
300,317,389
2
1
null
2020-10-27T12:07:23
2020-10-01T14:54:31
C++
UTF-8
C++
false
false
1,192
cpp
/*May The Force Be With Me*/ #include <bits/stdc++.h> #define ll long long #define MOD 1000000007 #define endl "\n" #define vll vector<long long> #define pll pair<long long, long long> #define all(c) c.begin(),c.end() #define f first #define s second #define inf INT_MAX #define size 10000000 #define size_2d 10000 #define mem(a,val) memset(a,val,sizeof(a)) //Snippets: bigint, bsearch, graph, splitstring, segtree using namespace std; ll N; ll arr[size]; map<ll, ll> dp; void Input() { cin >> N; for (ll i = 0; i < N; i++) { cin >> arr[i]; //dp[arr[i]] = 1; } } void Solve() { ll ans = 0, ed = 0; for (ll i = 0; i < N; i++) { dp[arr[i]] = max(dp[arr[i]], dp[arr[i] - 1] + 1); ans = max(ans, dp[arr[i]]); } cout << ans << endl; for (ll i = 0; i < N; i++) { if (dp[arr[i]] == ans) { ed = arr[i]; break; } } ed -= (ans - 1); for (ll i = 0; i < N; i++) { if (arr[i] == ed) { cout << i + 1 << " "; ed++; } } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ll T = 1; //cin >> T; while (T--) { Input(); Solve(); } return 0; }
[ "helewrer3@gmail.com" ]
helewrer3@gmail.com
43e057c2de4703917a61d9591b38cd3865538385
ecfdfa7b306cfa60f5f4336666c4ba8a612823f9
/GeneratedFiles/ui_opencontestwidget.h
cd932056d3883af3549526d40898420a219afbee
[]
no_license
fangjyshanghai/LemonJudger
c573d603717922ab9aadf3cec2abd2c8bb9be30b
88bc6f190a98b720116c5f62e528e2197734e479
refs/heads/master
2020-04-27T16:59:31.928442
2018-09-18T14:38:28
2018-09-18T14:38:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,022
h
/******************************************************************************** ** Form generated from reading UI file 'opencontestwidget.ui' ** ** Created by: Qt User Interface Compiler version 5.8.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_OPENCONTESTWIDGET_H #define UI_OPENCONTESTWIDGET_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QTableWidget> #include <QtWidgets/QToolButton> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_OpenContestWidget { public: QHBoxLayout *horizontalLayout; QTableWidget *recentContest; QVBoxLayout *verticalLayout; QSpacerItem *verticalSpacer; QToolButton *addButton; QToolButton *deleteButton; QSpacerItem *verticalSpacer_2; void setupUi(QWidget *OpenContestWidget) { if (OpenContestWidget->objectName().isEmpty()) OpenContestWidget->setObjectName(QStringLiteral("OpenContestWidget")); OpenContestWidget->resize(400, 300); horizontalLayout = new QHBoxLayout(OpenContestWidget); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); recentContest = new QTableWidget(OpenContestWidget); if (recentContest->columnCount() < 2) recentContest->setColumnCount(2); QFont font; font.setPointSize(9); font.setBold(true); font.setWeight(75); QTableWidgetItem *__qtablewidgetitem = new QTableWidgetItem(); __qtablewidgetitem->setFont(font); recentContest->setHorizontalHeaderItem(0, __qtablewidgetitem); QTableWidgetItem *__qtablewidgetitem1 = new QTableWidgetItem(); __qtablewidgetitem1->setFont(font); recentContest->setHorizontalHeaderItem(1, __qtablewidgetitem1); recentContest->setObjectName(QStringLiteral("recentContest")); recentContest->setStyleSheet(QStringLiteral("font-size: 9pt;")); recentContest->setEditTriggers(QAbstractItemView::NoEditTriggers); recentContest->setSelectionMode(QAbstractItemView::SingleSelection); recentContest->setSelectionBehavior(QAbstractItemView::SelectRows); recentContest->horizontalHeader()->setHighlightSections(false); recentContest->horizontalHeader()->setMinimumSectionSize(80); recentContest->horizontalHeader()->setStretchLastSection(true); recentContest->verticalHeader()->setVisible(false); recentContest->verticalHeader()->setDefaultSectionSize(25); recentContest->verticalHeader()->setMinimumSectionSize(25); horizontalLayout->addWidget(recentContest); verticalLayout = new QVBoxLayout(); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout->addItem(verticalSpacer); addButton = new QToolButton(OpenContestWidget); addButton->setObjectName(QStringLiteral("addButton")); addButton->setMinimumSize(QSize(27, 27)); QIcon icon; icon.addFile(QStringLiteral(":/icon/add.png"), QSize(), QIcon::Normal, QIcon::Off); addButton->setIcon(icon); verticalLayout->addWidget(addButton); deleteButton = new QToolButton(OpenContestWidget); deleteButton->setObjectName(QStringLiteral("deleteButton")); deleteButton->setEnabled(false); deleteButton->setMinimumSize(QSize(27, 27)); QIcon icon1; icon1.addFile(QStringLiteral(":/icon/rod.png"), QSize(), QIcon::Normal, QIcon::Off); deleteButton->setIcon(icon1); verticalLayout->addWidget(deleteButton); verticalSpacer_2 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout->addItem(verticalSpacer_2); horizontalLayout->addLayout(verticalLayout); retranslateUi(OpenContestWidget); QMetaObject::connectSlotsByName(OpenContestWidget); } // setupUi void retranslateUi(QWidget *OpenContestWidget) { OpenContestWidget->setWindowTitle(QApplication::translate("OpenContestWidget", "Form", Q_NULLPTR)); QTableWidgetItem *___qtablewidgetitem = recentContest->horizontalHeaderItem(0); ___qtablewidgetitem->setText(QApplication::translate("OpenContestWidget", "Title", Q_NULLPTR)); QTableWidgetItem *___qtablewidgetitem1 = recentContest->horizontalHeaderItem(1); ___qtablewidgetitem1->setText(QApplication::translate("OpenContestWidget", "Location", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class OpenContestWidget: public Ui_OpenContestWidget {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_OPENCONTESTWIDGET_H
[ "2470196889@qq.com" ]
2470196889@qq.com
abf51ab80dd2586acb0ff5990f6852f6f541fc8d
cb5ee802d85e40428ed556fafb31b951ff517557
/IS/Agenda/Agenda.cpp
0726a2c09b599e0d6cac89a1bab849857693667b
[]
no_license
i22safed/AsignaturasIngenier
04bbe62d23f166e65d039f7cd400b30663d9c0c4
331638f1d766e7ac8dea45643a1a7e50a62c14f2
refs/heads/master
2021-01-18T02:34:20.010445
2015-04-20T15:41:18
2015-04-20T15:41:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,109
cpp
/* * Agenda.cpp * * Created on: 13/12/2014 * Author: jose */ #include "Agenda.h" using namespace std; Agenda::Agenda() { // TODO Auto-generated constructor stub } Agenda::~Agenda() { // TODO Auto-generated destructor stub } bool Agenda::esvacia() { return agenda.empty(); } int Agenda::longitud() { return agenda.size(); } bool Agenda::pertenece(Cliente &e) { bool encontrado=false; list<Cliente>::iterator it= agenda.begin(); while(!encontrado && it!=agenda.end()){//hay que buscarlo tambien por el segundo apellido para que sea igual if((*it).getDni()==e.getDni() ){ encontrado=true; } else it++; } return encontrado; } void Agenda::insertarCliente(list<Cliente>::iterator pos, Cliente& e) { //hay que distinguir entre si el cliente existe o no bool ok=false; if(esvacia()){ agenda.push_back(e); } else if(pertenece(e)) { //Si ya esta en la agenda le preguntamos si desea modificaro cout<<"\nEl cliente ya existe"; } else{ agenda.insert(pos,e); //me da a mi que asi no es :S } } bool Agenda::eliminar(list<Cliente>::iterator it) { agenda.erase(it); } list<Cliente>::iterator Agenda::buscar(Cliente &e) { bool encontrado=false; list<Cliente>::iterator it= agenda.begin(); while(!encontrado && it!=agenda.end()){//hay que buscarlo tambien por el segundo apellido para que sea igual if((*it).getApellido1()==e.getApellido1() && (*it).getApellido2()==e.getApellido2() || (*it).getDni()==e.getDni() ){ encontrado=true; } else it++; } return it; } bool Agenda::modificar(list<Cliente>::iterator i,Cliente aux) { *i=aux; //hay que machacarlo; } bool Agenda::ordenar() { //si los vamos a insertar ordenados?? para que? } list<Cliente> Agenda::getFavoritos() { list<Cliente> aux; list<Cliente>::iterator it; for(it=agenda.begin();it!=agenda.end();it++){ if((*it).getFavorito()==1) aux.push_back((*it)); //ESTAN ORDENAOS COÑO } return aux; } void Agenda::guardar(list<Cliente> agenda) { f.guardar_agenda(agenda); } list<Cliente> Agenda::getallApellido(string apellido) { list<Cliente> aux; list<Cliente>::iterator it; for(it=agenda.begin();it!=agenda.end();it++){ if((*it).getApellido1()==apellido) aux.push_back((*it)); } return aux; } list<Cliente> Agenda::getClientes() { return agenda; } list<Cliente>::iterator Agenda::buscarpos(Cliente& e) { list<Cliente>::iterator it=agenda.begin(); bool entrado=false; while((*it).getApellido1()<=e.getApellido1() && it!=agenda.end() && entrado==false) { if((*it).getApellido1()==e.getApellido1() && !entrado) { if ((*it).getApellido2()<e.getApellido2() && !entrado) { it++; entrado=true; while((*it).getApellido2()<e.getApellido2() && it!=agenda.end()) { it++; }//si el primer apellido es igual hay que compararlo con el segundo entrado=true; } entrado=true; } it++; } return it; } Cliente Agenda::getcliente(list<Cliente>::iterator it) { return *it; } void Agenda::cargar() { f.cargar_agenda(); }
[ "ceox1992@gmail.com" ]
ceox1992@gmail.com
3972bec008579b1add6d3b3f64f2721fcb3f8b6e
3d9027550e8c9c93acbd987e9212661438fe1438
/arduino-tinywebserver-20100617/Fat16/SdCard.cpp
b13003b8e3ac6f903f9dc63a3a97c64cf4bd2243
[]
no_license
kutch2001/arduinobykutch
ff92d676172bab87b700aff9d3fc2b4f169c130a
0f5851380640b6138d072229fdf5c7277ed02dd5
refs/heads/master
2021-05-04T11:35:34.708999
2021-04-14T20:30:23
2021-04-14T20:30:23
49,112,164
0
0
null
null
null
null
UTF-8
C++
false
false
8,960
cpp
/* Arduino FAT16 Library * Copyright (C) 2008 by William Greiman * * This file is part of the Arduino FAT16 Library * * This Library is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This Library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with the Arduino Fat16 Library. If not, see * <http://www.gnu.org/licenses/>. */ #include <wiring.h> #include "Fat16Config.h" #include "SdCard.h" //------------------------------------------------------------------------------ //r1 status values #define R1_READY_STATE 0 #define R1_IDLE_STATE 1 //start data token for read or write #define DATA_START_BLOCK 0XFE //data response tokens for write block #define DATA_RES_MASK 0X1F #define DATA_RES_ACCEPTED 0X05 #define DATA_RES_CRC_ERROR 0X0B #define DATA_RES_WRITE_ERROR 0X0D // // stop compiler from inlining where speed optimization is not required #define STATIC_NOINLINE static __attribute__((noinline)) //------------------------------------------------------------------------------ // SPI static functions // // clock byte in STATIC_NOINLINE uint8_t spiRec(void) { SPDR = 0xff; while(!(SPSR & (1 << SPIF))); return SPDR; } // clock byte out STATIC_NOINLINE void spiSend(uint8_t b) { SPDR = b; while(!(SPSR & (1 << SPIF))); } // set Slave Select HIGH STATIC_NOINLINE void spiSSHigh(void) { digitalWrite(SPI_SS_PIN, HIGH); } // set Slave Select LOW STATIC_NOINLINE void spiSSLow(void) { digitalWrite(SPI_SS_PIN, LOW); } //------------------------------------------------------------------------------ // wait for card to go not busy // return false if timeout static uint8_t waitForToken(uint8_t token, uint16_t timeoutMillis) { uint16_t t0 = millis(); while (spiRec() != token) { if (((uint16_t)millis() - t0) > timeoutMillis) return false; } return true; } //------------------------------------------------------------------------------ static uint8_t cardCommand(uint8_t cmd, uint32_t arg) { uint8_t r1; // select card spiSSLow(); // wait if busy waitForToken(0XFF, SD_COMMAND_TIMEOUT); // send command spiSend(cmd | 0x40); // send argument for (int8_t s = 24; s >= 0; s -= 8) spiSend(arg >> s); // send CRC - must send valid CRC for CMD0 spiSend(cmd == CMD0 ? 0x95 : 0XFF); //wait for not busy for (uint8_t retry = 0; (0X80 & (r1 = spiRec())) && retry != 0XFF; retry++); return r1; } //============================================================================== // SdCard member functions //------------------------------------------------------------------------------ #if SD_CARD_INFO_SUPPORT /** * Determine the size of a standard SD flash memory card * \return The number of 512 byte data blocks in the card */ uint32_t SdCard::cardSize(void) { uint16_t c_size; csd_t csd; if (!readReg(CMD9, (uint8_t *)&csd)) return 0; uint8_t read_bl_len = csd.read_bl_len; c_size = (csd.c_size_high << 10) | (csd.c_size_mid << 2) | csd.c_size_low; uint8_t c_size_mult = (csd.c_size_mult_high << 1) | csd.c_size_mult_low; return (uint32_t)(c_size+1) << (c_size_mult + read_bl_len - 7); } #endif //SD_CARD_INFO_SUPPORT //------------------------------------------------------------------------------ void SdCard::error(uint8_t code, uint8_t data) { errorData = data; error(code); } //------------------------------------------------------------------------------ void SdCard::error(uint8_t code) { errorCode = code; spiSSHigh(); } //------------------------------------------------------------------------------ /** * Initialize a SD flash memory card. * * \param[in] slow Set SPI Frequency F_CPU/4 if true else F_CPU/2. * * \return The value one, true, is returned for success and * the value zero, false, is returned for failure. * */ uint8_t SdCard::init(uint8_t slow) { // 16-bit init start time allows over a minute uint16_t t0 = (uint16_t)millis(); pinMode(SPI_SS_PIN, OUTPUT); #if SPI_SS_PIN != 10 pinMode(10, OUTPUT); digitalWrite(10, HIGH); #endif spiSSHigh(); pinMode(SPI_MOSI_PIN, OUTPUT); pinMode(SPI_SCK_PIN, OUTPUT); //Enable SPI, Master, clock rate F_CPU/128 SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR1) | (1 << SPR0); //must supply min of 74 clock cycles with CS high. for (uint8_t i = 0; i < 10; i++) spiSend(0XFF); spiSSLow(); #if SD_INIT_OLD_VER // next line prevent re-init hang by some cards (not sure why this works) for (uint16_t i = 0; i <= 512; i++) spiRec(); uint8_t r = cardCommand(CMD0, 0); for (uint16_t retry = 0; r != R1_IDLE_STATE; retry++){ if (retry == 10000) { error(SD_ERROR_CMD0, r); return false; } r = spiRec(); } #else // SD_INIT_OLD_VER // command to go idle in SPI mode while (1) { uint8_t r = cardCommand(CMD0, 0); if (r == R1_IDLE_STATE) break; if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) { error(SD_ERROR_CMD0, r); return false; } } #endif // SD_INIT_OLD_VER // start initialization and wait for completed initialization while (1) { cardCommand(CMD55, 0); uint8_t r = cardCommand(ACMD41, 0); if (r == R1_READY_STATE)break; if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) { error(SD_ERROR_ACMD41, r); return false; } } // set SPI frequency SPCR &= ~((1 << SPR1) | (1 << SPR0)); // F_CPU/4 if (!slow) SPSR |= (1 << SPI2X); // Doubled Clock Frequency to F_CPU/2 spiSSHigh(); return true; } //------------------------------------------------------------------------------ /** * Reads a 512 byte block from a storage device. * * \param[in] blockNumber Logical block to be read. * \param[out] dst Pointer to the location that will receive the data. * \return The value one, true, is returned for success and * the value zero, false, is returned for failure. */ uint8_t SdCard::readBlock(uint32_t blockNumber, uint8_t *dst) { if (cardCommand(CMD17, blockNumber << 9)) { error(SD_ERROR_CMD17); return false; } return readTransfer(dst, 512); } //------------------------------------------------------------------------------ #if SD_CARD_INFO_SUPPORT uint8_t SdCard::readReg(uint8_t cmd, uint8_t *dst) { if (cardCommand(cmd, 0)) { spiSSHigh(); return false; } return readTransfer(dst, 16); } #endif //SD_CARD_INFO_SUPPORT //------------------------------------------------------------------------------ uint8_t SdCard::readTransfer(uint8_t *dst, uint16_t count) { //wait for start of data if (!waitForToken(DATA_START_BLOCK, SD_READ_TIMEOUT)) { error(SD_ERROR_READ_TIMEOUT); } //start first spi transfer SPDR = 0XFF; for (uint16_t i = 0; i < count; i++) { while(!(SPSR & (1 << SPIF))); dst[i] = SPDR; SPDR = 0XFF; } // wait for first CRC byte while(!(SPSR & (1 << SPIF))); spiRec();//second CRC byte spiSSHigh(); return true; } //------------------------------------------------------------------------------ /** * Writes a 512 byte block to a storage device. * * \param[in] blockNumber Logical block to be written. * \param[in] src Pointer to the location of the data to be written. * \return The value one, true, is returned for success and * the value zero, false, is returned for failure. */ uint8_t SdCard::writeBlock(uint32_t blockNumber, uint8_t *src) { uint32_t address = blockNumber << 9; #if SD_PROTECT_BLOCK_ZERO //don't allow write to first block if (address == 0) { error(SD_ERROR_BLOCK_ZERO_WRITE); return false; } #endif //SD_PROTECT_BLOCK_ZERO if (cardCommand(CMD24, address)) { error(SD_ERROR_CMD24); return false; } // optimize write loop SPDR = DATA_START_BLOCK; for (uint16_t i = 0; i < 512; i++) { while(!(SPSR & (1 << SPIF))); SPDR = src[i]; } while(!(SPSR & (1 << SPIF)));// wait for last data byte spiSend(0xFF);// dummy crc spiSend(0xFF);// dummy crc // get write response uint8_t r1 = spiRec(); if ((r1 & DATA_RES_MASK) != DATA_RES_ACCEPTED) { error(SD_ERROR_WRITE_RESPONSE, r1); return false; } // wait for card to complete write programming if (!waitForToken(0XFF, SD_WRITE_TIMEOUT)) { error(SD_ERROR_WRITE_TIMEOUT); } spiSSHigh(); return true; }
[ "kutch2001@localhost" ]
kutch2001@localhost
5b91e898ac6e03b79f63566b05192533b318c059
675799331c7b3812ec286ec6786a3020d9bdac3d
/CPP/AtCoder/other/CodeFestival2016TR3/a.cpp
4807b922e7669260a2ec559f2bb3ebcd43b79991
[]
no_license
kkisic/Procon
07436574c12ebb01347b92d98c7aebb31404085a
30f394c237369a7d706fe46b53dc9d0313ce053e
refs/heads/master
2021-10-24T17:29:13.390016
2021-10-04T14:03:51
2021-10-04T14:03:51
112,325,136
1
1
null
null
null
null
UTF-8
C++
false
false
1,808
cpp
#include <cmath> #include <iostream> #include <vector> #include <queue> #include <deque> #include <map> #include <set> #include <stack> #include <tuple> #include <bitset> #include <algorithm> #include <functional> #include <utility> #include <iomanip> #define int long long int #define rep(i, n) for(int i = 0; i < (n); ++i) #define ALL(x) (x).begin(), (x).end() #define SZ(x) ((int)(x).size()) #define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() ) using namespace std; typedef pair<int, int> P; const int INF = 1e15; const int MOD = 1e9+7; template <typename T> using vector2 = vector<vector<T>>; template <typename T> vector2<T> initVec2(size_t n0, size_t n1, T e = T()){ return vector2<T>(n0, vector<T>(n1, e)); } template <typename T> using vector3 = vector<vector<vector<T>>>; template <typename T> vector3<T> initVec3(size_t n0, size_t n1, size_t n2, T e = T()){ return vector3<T>(n0, vector2<T>(n1, vector<T>(n2, e))); } signed main(){ ios::sync_with_stdio(false); cin.tie(0); int n, m, k; cin >> n >> m >> k; vector<int> a(n); rep(i, n) cin >> a[i]; auto dp = initVec2<int>(n + 1, k + 1); for(int j = 0; j < k; j++){ deque<int> deq; int l = 0; for(int i = 0; i < n; i++){ while(not deq.empty() && dp[deq.back()][j] <= dp[i][j]){ deq.pop_back(); } deq.push_back(i); if(i - l >= m){ if(deq.front() == l){ deq.pop_front(); } l++; } if(i >= j){ dp[i+1][j+1] = dp[deq.front()][j] + a[i] * (j + 1); } } } int ans = 0; rep(i, n + 1){ ans = max(ans, dp[i][k]); } cout << ans << endl; return 0; }
[ "amareamo.pxhxc@gmail.com" ]
amareamo.pxhxc@gmail.com
7c4436b2a5a58359bc6c99ebcb3f3b9b642c3434
e2c48e041d2983164cf04bc49d37f3bc7324f2d3
/Cplusplus/_1049_Last_Stone_Weight_II/_1049_main.cpp
c3b2a8fb7805d0dc53015b74012827a73704bb9a
[]
no_license
ToLoveToFeel/LeetCode
17aff7f9b36615ccebe386545440f921d8fdf740
de7a893fc625ff30122899969f761ed5f8df8b12
refs/heads/master
2023-07-12T07:35:09.410016
2021-08-23T02:33:00
2021-08-23T02:33:00
230,863,299
2
0
null
null
null
null
UTF-8
C++
false
false
746
cpp
// Created by WXX on 2021/6/8 9:34 #include <iostream> #include <vector> using namespace std; /** * 执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户 * 内存消耗:8.1 MB, 在所有 C++ 提交中击败了49.56%的用户 */ class Solution { public: int lastStoneWeightII(vector<int> &stones) { int sum = 0; for (auto x : stones) sum += x; int m = sum / 2; vector<int> f(m + 1); for (auto x : stones) for (int j = m; j >= x; j--) f[j] = max(f[j], f[j - x] + x); return (sum - f[m]) - f[m]; } }; int main() { vector<int> stones = {2, 7, 4, 1, 8, 1}; cout << Solution().lastStoneWeightII(stones) << endl; // 1 return 0; }
[ "1137247975@qq.com" ]
1137247975@qq.com
d03cd7344e3f86076cd3e9f24c3c5f0247a92a76
1e006c14837be0e7b6ed9a0f5870907638dfd402
/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr/include/boost/geometry/algorithms/expand.hpp
fca638a0a49a4a508ac191bbecf30551d03094e5
[]
no_license
slowfranklin/synology-ds
b9cd512d86ffc4d61949e6d72012b8cff8d58813
5a6dc5e1cfde5be3104f412e5a368bc8d615dfa6
refs/heads/master
2021-10-24T01:38:38.120574
2019-03-20T13:01:12
2019-03-20T13:01:12
176,933,470
1
1
null
null
null
null
UTF-8
C++
false
false
9,142
hpp
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2008-2012 Bruno Lalande, Paris, France. // Copyright (c) 2009-2012 Mateusz Loskot, London, UK. // Copyright (c) 2014 Samuel Debionne, Grenoble, France. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_ALGORITHMS_EXPAND_HPP #define BOOST_GEOMETRY_ALGORITHMS_EXPAND_HPP #include <cstddef> #include <boost/numeric/conversion/cast.hpp> #include <boost/geometry/algorithms/not_implemented.hpp> #include <boost/geometry/core/coordinate_dimension.hpp> #include <boost/geometry/geometries/concepts/check.hpp> #include <boost/geometry/util/select_coordinate_type.hpp> #include <boost/geometry/strategies/compare.hpp> #include <boost/geometry/policies/compare.hpp> #include <boost/variant/static_visitor.hpp> #include <boost/variant/apply_visitor.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace expand { template < typename StrategyLess, typename StrategyGreater, std::size_t Dimension, std::size_t DimensionCount > struct point_loop { template <typename Box, typename Point> static inline void apply(Box& box, Point const& source) { typedef typename strategy::compare::detail::select_strategy < StrategyLess, 1, Point, Dimension >::type less_type; typedef typename strategy::compare::detail::select_strategy < StrategyGreater, -1, Point, Dimension >::type greater_type; typedef typename select_coordinate_type<Point, Box>::type coordinate_type; less_type less; greater_type greater; coordinate_type const coord = get<Dimension>(source); if (less(coord, get<min_corner, Dimension>(box))) { set<min_corner, Dimension>(box, coord); } if (greater(coord, get<max_corner, Dimension>(box))) { set<max_corner, Dimension>(box, coord); } point_loop < StrategyLess, StrategyGreater, Dimension + 1, DimensionCount >::apply(box, source); } }; template < typename StrategyLess, typename StrategyGreater, std::size_t DimensionCount > struct point_loop < StrategyLess, StrategyGreater, DimensionCount, DimensionCount > { template <typename Box, typename Point> static inline void apply(Box&, Point const&) {} }; template < typename StrategyLess, typename StrategyGreater, std::size_t Index, std::size_t Dimension, std::size_t DimensionCount > struct indexed_loop { template <typename Box, typename Geometry> static inline void apply(Box& box, Geometry const& source) { typedef typename strategy::compare::detail::select_strategy < StrategyLess, 1, Box, Dimension >::type less_type; typedef typename strategy::compare::detail::select_strategy < StrategyGreater, -1, Box, Dimension >::type greater_type; typedef typename select_coordinate_type < Box, Geometry >::type coordinate_type; less_type less; greater_type greater; coordinate_type const coord = get<Index, Dimension>(source); if (less(coord, get<min_corner, Dimension>(box))) { set<min_corner, Dimension>(box, coord); } if (greater(coord, get<max_corner, Dimension>(box))) { set<max_corner, Dimension>(box, coord); } indexed_loop < StrategyLess, StrategyGreater, Index, Dimension + 1, DimensionCount >::apply(box, source); } }; template < typename StrategyLess, typename StrategyGreater, std::size_t Index, std::size_t DimensionCount > struct indexed_loop < StrategyLess, StrategyGreater, Index, DimensionCount, DimensionCount > { template <typename Box, typename Geometry> static inline void apply(Box&, Geometry const&) {} }; // Changes a box such that the other box is also contained by the box template < typename StrategyLess, typename StrategyGreater > struct expand_indexed { template <typename Box, typename Geometry> static inline void apply(Box& box, Geometry const& geometry) { indexed_loop < StrategyLess, StrategyGreater, 0, 0, dimension<Geometry>::type::value >::apply(box, geometry); indexed_loop < StrategyLess, StrategyGreater, 1, 0, dimension<Geometry>::type::value >::apply(box, geometry); } }; }} // namespace detail::expand #endif // DOXYGEN_NO_DETAIL #ifndef DOXYGEN_NO_DISPATCH namespace dispatch { template < typename GeometryOut, typename Geometry, typename StrategyLess = strategy::compare::default_strategy, typename StrategyGreater = strategy::compare::default_strategy, typename TagOut = typename tag<GeometryOut>::type, typename Tag = typename tag<Geometry>::type > struct expand: not_implemented<TagOut, Tag> {}; // Box + point -> new box containing also point template < typename BoxOut, typename Point, typename StrategyLess, typename StrategyGreater > struct expand<BoxOut, Point, StrategyLess, StrategyGreater, box_tag, point_tag> : detail::expand::point_loop < StrategyLess, StrategyGreater, 0, dimension<Point>::type::value > {}; // Box + box -> new box containing two input boxes template < typename BoxOut, typename BoxIn, typename StrategyLess, typename StrategyGreater > struct expand<BoxOut, BoxIn, StrategyLess, StrategyGreater, box_tag, box_tag> : detail::expand::expand_indexed<StrategyLess, StrategyGreater> {}; template < typename Box, typename Segment, typename StrategyLess, typename StrategyGreater > struct expand<Box, Segment, StrategyLess, StrategyGreater, box_tag, segment_tag> : detail::expand::expand_indexed<StrategyLess, StrategyGreater> {}; } // namespace dispatch #endif // DOXYGEN_NO_DISPATCH namespace resolve_variant { template <typename Geometry> struct expand { template <typename Box> static inline void apply(Box& box, Geometry const& geometry) { concept::check<Box>(); concept::check<Geometry const>(); concept::check_concepts_and_equal_dimensions<Box, Geometry const>(); dispatch::expand<Box, Geometry>::apply(box, geometry); } }; template <BOOST_VARIANT_ENUM_PARAMS(typename T)> struct expand<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> > { template <typename Box> struct visitor: boost::static_visitor<void> { Box& m_box; visitor(Box& box) : m_box(box) {} template <typename Geometry> void operator()(Geometry const& geometry) const { return expand<Geometry>::apply(m_box, geometry); } }; template <class Box> static inline void apply(Box& box, boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry) { return boost::apply_visitor(visitor<Box>(box), geometry); } }; } // namespace resolve_variant /*** *! \brief Expands a box using the extend (envelope) of another geometry (box, point) \ingroup expand \tparam Box type of the box \tparam Geometry of second geometry, to be expanded with the box \param box box to expand another geometry with, might be changed \param geometry other geometry \param strategy_less \param strategy_greater \note Strategy is currently ignored * template < typename Box, typename Geometry, typename StrategyLess, typename StrategyGreater > inline void expand(Box& box, Geometry const& geometry, StrategyLess const& strategy_less, StrategyGreater const& strategy_greater) { concept::check_concepts_and_equal_dimensions<Box, Geometry const>(); dispatch::expand<Box, Geometry>::apply(box, geometry); } ***/ /*! \brief Expands a box using the bounding box (envelope) of another geometry (box, point) \ingroup expand \tparam Box type of the box \tparam Geometry \tparam_geometry \param box box to be expanded using another geometry, mutable \param geometry \param_geometry geometry which envelope (bounding box) will be added to the box \qbk{[include reference/algorithms/expand.qbk]} */ template <typename Box, typename Geometry> inline void expand(Box& box, Geometry const& geometry) { resolve_variant::expand<Geometry>::apply(box, geometry); } }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_EXPAND_HPP
[ "slow@samba.org" ]
slow@samba.org
350f086c92631211ef00a4c1fcd8455289a009d5
6157455a8627e82d77254289050bd04162d552ba
/PiFcp/pifcp/spc.cp
976f719a34bd92486905eadb776ea8c5f720de22
[]
no_license
shapirolab/Logix
f769e6ab3fec12dcf5e4b59a3d172ed667291ead
6960cb3ff7dfef9885383b62b7996ae1d7e42538
refs/heads/master
2022-11-11T07:52:49.814029
2020-06-30T07:17:08
2020-06-30T07:17:08
275,871,063
1
0
null
null
null
null
UTF-8
C++
false
false
6,457
cp
/* Precompiler for Pi Calculus procedures - Stochastic Pi Calculus Phase. Bill Silverman, February 1999. Last update by $Author: bill $ $Date: 2000/05/07 09:05:50 $ Currently locked by $Locker: $ $Revision: 2.1 $ $Source: /home/qiana/Repository/PiFcp/pifcp/spc.cp,v $ Copyright (C) 2000, Weizmann Institute of Science - Rehovot, ISRAEL */ -export(output/3). -mode(interpret). -language(compound). /* ** output/3 ** ** Input: ** ** In is a stream of Mode(Atom, RHSS, Procedure). ** ** Mode is one of {export, ** none, no_guard, ** compare, logix, ** receive, send, mixed}. ** ** Atom is an Fcp atom of a compound procedure: ** ** ProcedureName(<arguments>) ** or ** ProcedureName ** ** RHSS is the right-hand-side of the compound procedure. ** ** Procedure is [] or the compound procedure's communication part. ** ** ProcedureName.Mode(<arguments'>) :- <compound rhs> ** ** where Mode is in {send, mixed}. ** ** Delay is one of {none, stochastic}. ** ** Output: ** ** Terms is a stream of compound procedures. */ output(In, Delay, Terms) :- Delay =?= none, In ? Mode(Atom, RHSS, []), Mode =\= conflict : Terms ! (Atom :- RHSS) | self; Delay =?= none, In ? Mode(Atom, RHSS, Procedure), Procedure =\= [], Mode =\= conflict : Terms ! (Atom :- RHSS), Terms' ! Procedure | self; /* Discard conflicted code. */ In ? conflict(_Atom, _RHSS, _Procedure) | self; Delay =?= stochastic, In ? export(Atom, RHSS, _Procedure) : Terms ! (Atom :- RHSS) | self; Delay =?= stochastic, In ? Mode(Atom, RHSS, Procedure), Mode =\= export, Mode =\= conflict | add_schedule_channel, stochastic; In = [] : Delay = _, Terms = []. add_schedule_channel(Atom, LHS) :- string(Atom) : LHS = Atom(`pifcp(schedule)); tuple(Atom) | utils#tuple_to_dlist(Atom, AL, [`pifcp(schedule)]), utils#list_to_tuple(AL, LHS). stochastic(In, Delay, Terms, Mode, LHS, RHSS, Procedure) :- Procedure =?= [] : Mode = _, Terms ! (Atom? :- RHSS) | piutils#tuple_to_atom(LHS, Atom), output; Procedure =?= (Atom :- Communicate) : Procedure' = (Atom'? :- Communicate) | add_schedule_channel(Atom, Atom'), communication. communication(In, Delay, Terms, Mode, LHS, RHSS, Procedure) :- Procedure =?= (Atom :- Communicate1), arg(1, Atom, ProcName), string_to_dlist(ProcName, PNL, []) : Mode = _, Terms ! (LHS :- RHS?), Terms' ! (Atom'? :- Communicate2?) | utils#tuple_to_dlist(Atom, ADL, [`pifcp(count)]), utils#list_to_tuple(ADL?, Atom'), remake_rhs(RHSS, Prepares, RHSS'), reform_rhs(RHSS', write_channel(schedule(WaitList?), `pifcp(schedule)), RHS), piutils#untuple_predicate_list(';', Communicate1, CL1), make_reference_name, rewrite_rhss, piutils#make_predicate_list(';', CL2?, Communicate2), output. reform_rhs(RHSS, Schedule, RHS) :- RHSS =?= (Ask : Tell | Body) : RHS = (Ask : Schedule, Tell | Body); RHSS =?= (Ask | Body), Ask =\= (_ : _) : RHS = (Ask : Schedule | Body); RHSS =\= (_ | _) : RHS = (true : Schedule | RHSS). make_reference_name(PNL, RefName) :- PNL ? Dot : ascii('.', Dot) | self; otherwise, list_to_string(PNL, RefName^) | true. remake_rhs(RHS1, Prepares, RHS2) :- RHS1 =\= (_ | _) : Prepares = {[], []}, RHS2 = RHS1; RHS1 =?= (Asks : Tells | Body) : Prepares = {Asks'?, Tells'?} | piutils#untuple_predicate_list(',', Asks, Asks'), piutils#untuple_predicate_list(',', Tells, Tells'), extract_reads_and_writes, make_waits(IdWrites?, Body, Body'), complete_preparation. make_waits(IdWrites, OldBody, NewBody) :- IdWrites ? {_Identify, write_channel(PiMessage, _FcpChannel)}, PiMessage =?= _Sender(_Message, ChoiceTag, _Choice) : NewBody = (pi_wait_to_send(`spsfcp(ChoiceTag), PiMessage), NewBody'?) | self; IdWrites =?= [] : NewBody = OldBody. /* This procedure should be replaced if the monitor is enhanced to prepare the Receives.*/ complete_preparation(Reads, Body, RHS2) :- Reads =?= [] : RHS2 = Body; otherwise : RHS2 = (PrepareReceives?, Body) | piutils#make_predicate_list(',', Reads, PrepareReceives). extract_reads_and_writes(Asks, Tells, IdWrites, Reads) :- Asks ? Identify, Tells ? Write, Write = write_channel(_PiMessage, _FcpChannel) : IdWrites ! {Identify, Write} | self; Asks ? Identify, Tells ? true, Identify = (`ChannelName = _Tuple), Asks' ? Read, Read =?= read_vector(2, _FcpVector, Stream) : Reads ! pi_wait_to_receive(`sprfcp(ChannelName),`pifcp(chosen), Stream) | self; Asks ? Identify, Tells =?= [], Identify = (`ChannelName = _Tuple), Asks' ? Read, Read =?= read_vector(2, _FcpVector, Stream) : Reads ! pi_wait_to_receive(`sprfcp(ChannelName),`pifcp(chosen), Stream) | self; Asks =?= [] : Tells = _, IdWrites = [], Reads = []. rewrite_rhss(ProcName, RefName, CL1, Prepares, WaitList, CL2) :- CL1 ? Receive, Receive =?= (Ask : Tell | Body), Body =\= self, Ask = (_Stream ? _Message, Identify, _We), Identify = (`ChannelName = _Creator(_FcpVector, _Arguments)) : WaitList ! receive(`ChannelName, `sprfcp(ChannelName)), CL2 ! (Ask : write_channel(terminate(RefName-ChannelName, `pifcp(count)), `pifcp(schedule)), Tell | Body) | self; CL1 ? Send, Send =?= (Ask | Body), Ask = (`pifcp(chosen) = _Index) : CL2 ! (Ask : write_channel(terminate(RefName, `pifcp(count)), `pifcp(schedule)) | Body) | self; CL1 ? Send, Send =?= (Ask : Tell | Body), Ask = (`pifcp(chosen) = _Index) : CL2 ! (Ask : write_channel(terminate(RefName, `pifcp(count)), `pifcp(schedule)), Tell | Body) | self; CL1 ? Other, otherwise : CL2 ! Other | self; CL1 =?= [], Prepares = {Asks, Tells} : ProcName = _, CL2 = [] | extract_reads_and_writes + (Reads = _), complete_waitlist + (EndList = RefName(`pifcp(count))). complete_waitlist(EndList, IdWrites, WaitList) :- IdWrites ? {(Channel = _PiChannel), write_channel(PiMessage, _FcpChannel)}, PiMessage =?= {_Sender, _ChannelList, SendIndex, _ChoiceVariable} : WaitList ! send(Channel, `spsfcp(SendIndex)) | self; IdWrites =?= [] : WaitList = EndList.
[ "bill" ]
bill
08a84fd1d3b1e74aaad9fbbb16dce75c938832f3
ebd5c4632bb5f85c9e3311fd70f6f1bf92fae53f
/PORMain/panda/include/openalAudioManager.h
2a95aba405c98f71f6cdcc902a0ca462dfd94408
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
BrandonAlex/Pirates-Online-Retribution
7f881a64ec74e595aaf62e78a39375d2d51f4d2e
980b7448f798e255eecfb6bd2ebb67b299b27dd7
refs/heads/master
2020-04-02T14:22:28.626453
2018-10-24T15:33:17
2018-10-24T15:33:17
154,521,816
2
1
null
null
null
null
UTF-8
C++
false
false
8,322
h
// Filename: openalAudioManager.h // Created by: Ben Buchwald <bb2@alumni.cmu.edu> // // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #ifndef __OPENAL_AUDIO_MANAGER_H__ #define __OPENAL_AUDIO_MANAGER_H__ #include "pandabase.h" #ifdef HAVE_OPENAL //[ #include "audioManager.h" #include "plist.h" #include "pmap.h" #include "pset.h" #include "movieAudioCursor.h" #include "reMutex.h" // OSX uses the OpenAL framework #ifdef IS_OSX #include <OpenAL/al.h> #include <OpenAL/alc.h> #else #include <AL/al.h> #include <AL/alc.h> #endif class OpenALAudioSound; extern void al_audio_errcheck(const char *context); extern void alc_audio_errcheck(const char *context,ALCdevice* device); class EXPCL_OPENAL_AUDIO OpenALAudioManager : public AudioManager { class SoundData; friend class OpenALAudioSound; friend class OpenALSoundData; public: //Constructor and Destructor OpenALAudioManager(); virtual ~OpenALAudioManager(); virtual void shutdown(); virtual bool is_valid(); virtual PT(AudioSound) get_sound(const string&, bool positional = false, int mode=SM_heuristic); virtual PT(AudioSound) get_sound(MovieAudio *sound, bool positional = false, int mode=SM_heuristic); virtual void uncache_sound(const string&); virtual void clear_cache(); virtual void set_cache_limit(unsigned int count); virtual unsigned int get_cache_limit() const; virtual void set_volume(PN_stdfloat); virtual PN_stdfloat get_volume() const; void set_play_rate(PN_stdfloat play_rate); PN_stdfloat get_play_rate() const; virtual void set_active(bool); virtual bool get_active() const; // This controls the "set of ears" that listens to 3D spacialized sound // px, py, pz are position coordinates. Can be 0.0f to ignore. // vx, vy, vz are a velocity vector in UNITS PER SECOND. // fx, fy and fz are the respective components of a unit forward-vector // ux, uy and uz are the respective components of a unit up-vector // These changes will NOT be invoked until audio_3d_update() is called. virtual void audio_3d_set_listener_attributes(PN_stdfloat px, PN_stdfloat py, PN_stdfloat pz, PN_stdfloat vx, PN_stdfloat xy, PN_stdfloat xz, PN_stdfloat fx, PN_stdfloat fy, PN_stdfloat fz, PN_stdfloat ux, PN_stdfloat uy, PN_stdfloat uz); virtual void audio_3d_get_listener_attributes(PN_stdfloat *px, PN_stdfloat *py, PN_stdfloat *pz, PN_stdfloat *vx, PN_stdfloat *vy, PN_stdfloat *vz, PN_stdfloat *fx, PN_stdfloat *fy, PN_stdfloat *fz, PN_stdfloat *ux, PN_stdfloat *uy, PN_stdfloat *uz); // Control the "relative distance factor" for 3D spacialized audio in units-per-foot. Default is 1.0 // OpenAL has no distance factor but we use this as a scale // on the min/max distances of sounds to preserve FMOD compatibility. // Also, adjusts the speed of sound to compensate for unit difference. virtual void audio_3d_set_distance_factor(PN_stdfloat factor); virtual PN_stdfloat audio_3d_get_distance_factor() const; // Control the presence of the Doppler effect. Default is 1.0 // Exaggerated Doppler, use >1.0 // Diminshed Doppler, use <1.0 virtual void audio_3d_set_doppler_factor(PN_stdfloat factor); virtual PN_stdfloat audio_3d_get_doppler_factor() const; // Exaggerate or diminish the effect of distance on sound. Default is 1.0 // Faster drop off, use >1.0 // Slower drop off, use <1.0 virtual void audio_3d_set_drop_off_factor(PN_stdfloat factor); virtual PN_stdfloat audio_3d_get_drop_off_factor() const; virtual void set_concurrent_sound_limit(unsigned int limit = 0); virtual unsigned int get_concurrent_sound_limit() const; virtual void reduce_sounds_playing_to(unsigned int count); virtual void stop_all_sounds(); virtual void update(); private: void make_current() const; bool can_use_audio(MovieAudioCursor *source); bool should_load_audio(MovieAudioCursor *source, int mode); SoundData *get_sound_data(MovieAudio *source, int mode); // Tell the manager that the sound dtor was called. void release_sound(OpenALAudioSound* audioSound); void increment_client_count(SoundData *sd); void decrement_client_count(SoundData *sd); void discard_excess_cache(int limit); void starting_sound(OpenALAudioSound* audio); void stopping_sound(OpenALAudioSound* audio); void cleanup(); private: // This global lock protects all access to OpenAL library interfaces. static ReMutex _lock; // An expiration queue is a list of SoundData // that are no longer being used. They are kept // around for a little while, since it is common to // stop using a sound for a brief moment and then // quickly resume. typedef plist<void *> ExpirationQueue; ExpirationQueue _expiring_samples; ExpirationQueue _expiring_streams; // An AudioSound that uses a SoundData is called a "client" // of the SoundData. The SoundData keeps track of how // many clients are using it. When the number of clients // drops to zero, the SoundData is no longer in use. The // expiration queue is a list of all SoundData that aren't // in use, in least-recently-used order. If a SoundData // in the expiration queue gains a new client, it is removed // from the expiration queue. When the number of sounds // in the expiration queue exceeds the cache limit, the // first sound in the expiration queue is purged. class SoundData { public: SoundData(); ~SoundData(); OpenALAudioManager* _manager; PT(MovieAudio) _movie; ALuint _sample; PT(MovieAudioCursor) _stream; double _length; int _rate; int _channels; int _client_count; ExpirationQueue::iterator _expire; }; typedef phash_map<string, SoundData *> SampleCache; SampleCache _sample_cache; typedef phash_set<PT(OpenALAudioSound)> SoundsPlaying; SoundsPlaying _sounds_playing; typedef phash_set<OpenALAudioSound *> AllSounds; AllSounds _all_sounds; // State: int _cache_limit; PN_stdfloat _volume; PN_stdfloat _play_rate; bool _active; bool _cleanup_required; // keep a count for startup and shutdown: static int _active_managers; static bool _openal_active; unsigned int _concurrent_sound_limit; bool _is_valid; typedef pset<OpenALAudioManager *> Managers; static Managers *_managers; static ALCdevice* _device; static ALCcontext* _context; // cache of openal sources, use only for playing sounds typedef pset<ALuint > SourceCache; static SourceCache *_al_sources; PN_stdfloat _distance_factor; PN_stdfloat _doppler_factor; PN_stdfloat _drop_off_factor; ALfloat _position[3]; ALfloat _velocity[3]; ALfloat _forward_up[6]; //////////////////////////////////////////////////////////// //These are needed for Panda's Pointer System. DO NOT ERASE! //////////////////////////////////////////////////////////// public: static TypeHandle get_class_type() { return _type_handle; } static void init_type() { AudioManager::init_type(); register_type(_type_handle, "OpenALAudioManager", AudioManager::get_class_type()); } virtual TypeHandle get_type() const { return get_class_type(); } virtual TypeHandle force_init_type() { init_type(); return get_class_type(); } private: static TypeHandle _type_handle; //////////////////////////////////////////////////////////// //DONE //////////////////////////////////////////////////////////// }; EXPCL_OPENAL_AUDIO AudioManager *Create_OpenALAudioManager(); #endif //] #endif /* __OPENAL_AUDIO_MANAGER_H__ */
[ "brandoncarden12345@gmail.com" ]
brandoncarden12345@gmail.com
1a11b56527548a5aedaa4695012bdda84e33a476
ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c
/out/release/gen/third_party/blink/renderer/bindings/modules/v8/unsigned_long_or_unsigned_long_sequence.h
6446382b66f49cd04bdbd8938900e946c710eadc
[ "BSD-3-Clause" ]
permissive
xueqiya/chromium_src
5d20b4d3a2a0251c063a7fb9952195cda6d29e34
d4aa7a8f0e07cfaa448fcad8c12b29242a615103
refs/heads/main
2022-07-30T03:15:14.818330
2021-01-16T16:47:22
2021-01-16T16:47:22
330,115,551
1
0
null
null
null
null
UTF-8
C++
false
false
4,210
h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file has been auto-generated from the Jinja2 template // third_party/blink/renderer/bindings/templates/union_container.h.tmpl // by the script code_generator_v8.py. // DO NOT MODIFY! // clang-format off #ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_UNSIGNED_LONG_OR_UNSIGNED_LONG_SEQUENCE_H_ #define THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_UNSIGNED_LONG_OR_UNSIGNED_LONG_SEQUENCE_H_ #include "base/optional.h" #include "third_party/blink/renderer/bindings/core/v8/dictionary.h" #include "third_party/blink/renderer/bindings/core/v8/native_value_traits.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/heap/handle.h" namespace blink { class MODULES_EXPORT UnsignedLongOrUnsignedLongSequence final { DISALLOW_NEW(); public: UnsignedLongOrUnsignedLongSequence(); bool IsNull() const { return type_ == SpecificType::kNone; } bool IsUnsignedLong() const { return type_ == SpecificType::kUnsignedLong; } uint32_t GetAsUnsignedLong() const; void SetUnsignedLong(uint32_t); static UnsignedLongOrUnsignedLongSequence FromUnsignedLong(uint32_t); bool IsUnsignedLongSequence() const { return type_ == SpecificType::kUnsignedLongSequence; } const Vector<uint32_t>& GetAsUnsignedLongSequence() const; void SetUnsignedLongSequence(const Vector<uint32_t>&); static UnsignedLongOrUnsignedLongSequence FromUnsignedLongSequence(const Vector<uint32_t>&); UnsignedLongOrUnsignedLongSequence(const UnsignedLongOrUnsignedLongSequence&); ~UnsignedLongOrUnsignedLongSequence(); UnsignedLongOrUnsignedLongSequence& operator=(const UnsignedLongOrUnsignedLongSequence&); void Trace(blink::Visitor*); private: enum class SpecificType { kNone, kUnsignedLong, kUnsignedLongSequence, }; SpecificType type_; uint32_t unsigned_long_; Vector<uint32_t> unsigned_long_sequence_; friend MODULES_EXPORT v8::Local<v8::Value> ToV8(const UnsignedLongOrUnsignedLongSequence&, v8::Local<v8::Object>, v8::Isolate*); }; class V8UnsignedLongOrUnsignedLongSequence final { public: MODULES_EXPORT static void ToImpl(v8::Isolate*, v8::Local<v8::Value>, UnsignedLongOrUnsignedLongSequence&, UnionTypeConversionMode, ExceptionState&); }; MODULES_EXPORT v8::Local<v8::Value> ToV8(const UnsignedLongOrUnsignedLongSequence&, v8::Local<v8::Object>, v8::Isolate*); template <class CallbackInfo> inline void V8SetReturnValue(const CallbackInfo& callbackInfo, UnsignedLongOrUnsignedLongSequence& impl) { V8SetReturnValue(callbackInfo, ToV8(impl, callbackInfo.Holder(), callbackInfo.GetIsolate())); } template <class CallbackInfo> inline void V8SetReturnValue(const CallbackInfo& callbackInfo, UnsignedLongOrUnsignedLongSequence& impl, v8::Local<v8::Object> creationContext) { V8SetReturnValue(callbackInfo, ToV8(impl, creationContext, callbackInfo.GetIsolate())); } template <> struct NativeValueTraits<UnsignedLongOrUnsignedLongSequence> : public NativeValueTraitsBase<UnsignedLongOrUnsignedLongSequence> { MODULES_EXPORT static UnsignedLongOrUnsignedLongSequence NativeValue(v8::Isolate*, v8::Local<v8::Value>, ExceptionState&); MODULES_EXPORT static UnsignedLongOrUnsignedLongSequence NullValue() { return UnsignedLongOrUnsignedLongSequence(); } }; template <> struct V8TypeOf<UnsignedLongOrUnsignedLongSequence> { typedef V8UnsignedLongOrUnsignedLongSequence Type; }; } // namespace blink // We need to set canInitializeWithMemset=true because HeapVector supports // items that can initialize with memset or have a vtable. It is safe to // set canInitializeWithMemset=true for a union type object in practice. // See https://codereview.chromium.org/1118993002/#msg5 for more details. WTF_ALLOW_MOVE_AND_INIT_WITH_MEM_FUNCTIONS(blink::UnsignedLongOrUnsignedLongSequence) #endif // THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_UNSIGNED_LONG_OR_UNSIGNED_LONG_SEQUENCE_H_
[ "xueqi@zjmedia.net" ]
xueqi@zjmedia.net
546fbd84a1d4a1de6d33a6959fc8043e8246d9c2
05d5ccee626b6c2b606f3a284d9c13121c1160ff
/data_compression/L3/benchmarks/lz4_p2p_decompress/src/host.cpp
443e51d8b376807b327547c4d40e6d9e94a63f27
[ "Apache-2.0", "Zlib", "BSD-2-Clause" ]
permissive
classmate7/Vitis_Libraries
a6407508bd6aa1a92bb82db2c590e0e0c00dbcff
40b98f7a20d4f9d181642104f74d797a94315024
refs/heads/master
2021-01-02T15:45:36.347010
2019-11-12T18:05:06
2019-11-12T18:05:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,720
cpp
/* * Copyright 2019 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "lz4_p2p.hpp" #include "lz4_p2p_dec.hpp" #include <fstream> #include <iostream> #include <cassert> #include "cmdlineparser.h" int validate(std::string& inFile_name, std::string& outFile_name) { std::string command = "cmp " + inFile_name + " " + outFile_name; int ret = system(command.c_str()); return ret; } void decompress_multiple_files(const std::vector<std::string>& inFileVec, const std::vector<std::string>& outFileVec, const std::string& decompress_bin) { std::vector<char*> outVec; std::vector<uint64_t> orgSizeVec; std::vector<uint64_t> inSizeVec; std::vector<int> fd_p2p_vec; std::vector<cl_event> userEventVec; uint64_t total_size = 0; uint64_t total_in_size = 0; for (uint32_t fid = 0; fid < inFileVec.size(); fid++) { uint64_t original_size = 0; std::string inFile_name = inFileVec[fid]; std::ifstream inFile(inFile_name.c_str(), std::ifstream::binary); uint64_t input_size = xfLz4::get_file_size(inFile); inFile.close(); int fd_p2p_c_in = open(inFile_name.c_str(), O_RDONLY | O_DIRECT); if (fd_p2p_c_in <= 0) { std::cout << "P2P: Unable to open input file, fd: " << fd_p2p_c_in << std::endl; exit(1); } std::vector<uint8_t, aligned_allocator<uint8_t> > in_4kbytes(4 * KB); read(fd_p2p_c_in, (char*)in_4kbytes.data(), 4 * KB); lseek(fd_p2p_c_in, 0, SEEK_SET); fd_p2p_vec.push_back(fd_p2p_c_in); std::memcpy(&original_size, &in_4kbytes[6], 4); total_size += original_size; total_in_size += input_size; orgSizeVec.push_back(original_size); char* out = (char*)aligned_alloc(4096, original_size); outVec.push_back(out); inSizeVec.push_back(input_size); } xfLz4 xlz(decompress_bin); xlz.decompress_in_line_multiple_files(inFileVec, fd_p2p_vec, outVec, orgSizeVec, inSizeVec); for (uint32_t fid = 0; fid < inFileVec.size(); fid++) { std::string outFile_name = outFileVec[fid]; std::ofstream outFile(outFile_name.c_str(), std::ofstream::binary); outFile.write((char*)outVec[fid], orgSizeVec[fid]); close(fd_p2p_vec[fid]); outFile.close(); } } void xil_decompress_file_list(std::string& file_list, std::string& decompress_bin) { std::ifstream infilelist_dec(file_list.c_str()); std::string line_dec; std::string ext1 = ".lz4"; std::vector<std::string> inFileList; std::vector<std::string> outFileList; std::vector<std::string> orgFileList; while (std::getline(infilelist_dec, line_dec)) { std::string in_file = line_dec + ext1; std::string out_file = line_dec + ext1 + ".org"; inFileList.push_back(in_file); orgFileList.push_back(line_dec); outFileList.push_back(out_file); } decompress_multiple_files(inFileList, outFileList, decompress_bin); std::cout << std::endl; for (size_t i = 0; i < inFileList.size(); i++) { int ret = validate(orgFileList[i], outFileList[i]); if (ret) { std::cout << "FAILED: " << inFileList[i] << std::endl; } else { std::cout << "PASSED: " << inFileList[i] << std::endl; } } } int main(int argc, char* argv[]) { sda::utils::CmdLineParser parser; parser.addSwitch("--decompress_xclbin", "-dx", "Decompress XCLBIN", "decompress"); parser.addSwitch("--decompress_mode", "-d", "Decompress Mode", ""); parser.addSwitch("--single_xclbin", "-sx", "Single XCLBIN", "p2p_decompress"); parser.addSwitch("--file_list", "-l", "List of Input Files", ""); parser.parse(argc, argv); std::string decompress_xclbin = parser.value("decompress_xclbin"); std::string decompress_mod = parser.value("decompress_mode"); std::string single_bin = parser.value("single_xclbin"); std::string filelist = parser.value("file_list"); int fopt = 1; // "-l" List of Files if (!filelist.empty()) { xil_decompress_file_list(filelist, decompress_xclbin); } }
[ "tianyul@xilinx.com" ]
tianyul@xilinx.com
1268ac2c24e30d3cffa9b03a0070bfc96d0a916e
b2f17cca26922b7fc6268cca284b6cf6e85c602c
/src/Script/xtal_manager.cpp
16baec5ecac5b356018f7d5b52b8eca3bca6b5e4
[ "MIT" ]
permissive
katze7514/ManaGameFramework
e3e0e8699d95bef1258f5f0e8a5950b55e8f2eb0
f79c6032cd9b3a522a7560272801a51ced2a6b83
refs/heads/master
2020-04-28T22:42:30.208249
2017-01-31T15:11:30
2017-01-31T15:11:30
41,914,237
1
0
null
null
null
null
UTF-8
C++
false
false
2,532
cpp
#include "../mana_common.h" #include <xtal_lib/xtal_winthread.h> #include <xtal_lib/xtal_chcode.h> #include <xtal_lib/xtal_errormessage.h> #include "xtal_lib.h" #include "xtal_code.h" #include "xtal_manager.h" namespace mana{ namespace script{ xtal_manager::~xtal_manager() { fin(); } void xtal_manager::init(const shared_ptr<resource_manager>& pResource) { logger::add_out_category("XTL"); pResource_ = pResource; init_lib(); xtal::Setting setting; setting.ch_code_lib = pCodeLib_; setting.std_stream_lib = pStreamLib_; setting.filesystem_lib = pFileSystemLib_; setting.thread_lib = pThreadLib_; xtal::initialize(setting); xtal::bind_error_message(); init_bind(); bInit_ = true; } void xtal_manager::fin() { if(!bInit_) return; mapCode_.clear(); fin_bind(); xtal::uninitialize(); safe_delete(pThreadLib_); safe_delete(pFileSystemLib_); safe_delete(pStreamLib_); safe_delete(pCodeLib_); bInit_ = false; } void xtal_manager::init_lib() { pCodeLib_ = new_ xtal::SJISChCodeLib(); pStreamLib_ = new_ logger_stream_lib(); pFileSystemLib_ = nullptr; pThreadLib_ = new_ xtal::WinThreadLib(); } void xtal_manager::init_bind() { xtal::lib()->def(Xid(xtal_manager), xtal::cpp_class<xtal_manager>()); xtal::lib()->def(Xid(manager), xtal::SmartPtr<xtal_manager>(this)); } void xtal_manager::fin_bind() { xtal::cpp_class<xtal_manager>()->object_orphan(); } void xtal_manager::exec() { xtal::gc(); } ////////////////////////////////// const shared_ptr<xtal_code>& xtal_manager::create_code(const string_fw& sID) { if(sID.get().empty()) { logger::warnln("[xtal_manager]IDが空です。"); return std::move(shared_ptr<xtal_code>()); } auto code = make_shared<xtal_code>(); code->set_id(sID); code->pMgr_ = this; auto r = mapCode_.emplace(sID, code); if(!r.second) { logger::warnln("[xtal_manager]コード情報を追加することができませんでした。"); return std::move(shared_ptr<xtal_code>()); } return r.first->second; } void xtal_manager::destroy_code(const string_fw& sID) { auto it = mapCode_.find(sID); if(it==mapCode_.end()) return; it->second->call_bind(false); mapCode_.erase(it); } const shared_ptr<xtal_code>& xtal_manager::code(const string_fw& sID) { auto it = mapCode_.find(sID); if(it!=mapCode_.end()) return it->second; return std::move(shared_ptr<xtal_code>()); } } // namespace script end } // namespace mana end XTAL_PREBIND(mana::script::xtal_manager) { Xdef_ctor0(); } XTAL_BIND(mana::script::xtal_manager) { }
[ "katze.s2k@gmail.com" ]
katze.s2k@gmail.com
2614f1522f30d5eddcb4df4ae31498239029772c
7ebae5ec0378642a1d2c181184460e76c73debbd
/USACO/barn1/barn1/stdafx.cpp
83ce18922bcb1988e209fed1cb83f000fea42139
[]
no_license
tonyli00000/Competition-Code
a4352b6b6835819a0f19f7f5cc67e46d2a200906
7f5767e3cb997fd15ae6f72145bcb8394f50975f
refs/heads/master
2020-06-17T23:04:10.367762
2019-12-28T22:08:25
2019-12-28T22:08:25
196,091,038
0
0
null
null
null
null
UTF-8
C++
false
false
284
cpp
// stdafx.cpp : source file that includes just the standard includes // barn1.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "tonyli2002@live.com" ]
tonyli2002@live.com
98f6b3e89c1a4c07c2596bceeb879efb3be9ca59
4627f3e31411cd2669161c63bb7a744eb1087a7f
/catch.hpp
b8ecab4a9185405640a37b6ba7be58b0bce9a04b
[ "MIT" ]
permissive
kosta2456/Huffman_Algorithm
727cfbe77aac16dbe3c2d1ae3b1fe53c662bee90
01948f27422c6914aefe5ce021050e1d02b3eb3c
refs/heads/master
2020-05-21T12:51:49.728586
2019-05-02T19:51:38
2019-05-02T19:51:38
186,052,962
0
0
null
null
null
null
UTF-8
C++
false
false
424,346
hpp
/* * Catch v2.6.0 * Generated: 2019-01-31 22:25:55.560884 * ---------------------------------------------------------- * This file has been merged from multiple headers. Please don't edit it directly * Copyright (c) 2019 Two Blue Cubes Ltd. All rights reserved. * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED // start catch.hpp #define CATCH_VERSION_MAJOR 2 #define CATCH_VERSION_MINOR 6 #define CATCH_VERSION_PATCH 0 #ifdef __clang__ # pragma clang system_header #elif defined __GNUC__ # pragma GCC system_header #endif // start catch_suppress_warnings.h #ifdef __clang__ # ifdef __ICC // icpc defines the __clang__ macro # pragma warning(push) # pragma warning(disable: 161 1682) # else // __ICC # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wpadded" # pragma clang diagnostic ignored "-Wswitch-enum" # pragma clang diagnostic ignored "-Wcovered-switch-default" # endif #elif defined __GNUC__ // Because REQUIREs trigger GCC's -Wparentheses, and because still // supported version of g++ have only buggy support for _Pragmas, // Wparentheses have to be suppressed globally. # pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-variable" # pragma GCC diagnostic ignored "-Wpadded" #endif // end catch_suppress_warnings.h #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) # define CATCH_IMPL # define CATCH_CONFIG_ALL_PARTS #endif // In the impl file, we want to have access to all parts of the headers // Can also be used to sanely support PCHs #if defined(CATCH_CONFIG_ALL_PARTS) # define CATCH_CONFIG_EXTERNAL_INTERFACES # if defined(CATCH_CONFIG_DISABLE_MATCHERS) # undef CATCH_CONFIG_DISABLE_MATCHERS # endif # if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER # endif #endif #if !defined(CATCH_CONFIG_IMPL_ONLY) // start catch_platform.h #ifdef __APPLE__ # include <TargetConditionals.h> # if TARGET_OS_OSX == 1 # define CATCH_PLATFORM_MAC # elif TARGET_OS_IPHONE == 1 # define CATCH_PLATFORM_IPHONE # endif #elif defined(linux) || defined(__linux) || defined(__linux__) # define CATCH_PLATFORM_LINUX #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) # define CATCH_PLATFORM_WINDOWS #endif // end catch_platform.h #ifdef CATCH_IMPL # ifndef CLARA_CONFIG_MAIN # define CLARA_CONFIG_MAIN_NOT_DEFINED # define CLARA_CONFIG_MAIN # endif #endif // start catch_user_interfaces.h namespace Catch { unsigned int rngSeed(); } // end catch_user_interfaces.h // start catch_tag_alias_autoregistrar.h // start catch_common.h // start catch_compiler_capabilities.h // Detect a number of compiler features - by compiler // The following features are defined: // // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported? // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported? // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled? // **************** // Note to maintainers: if new toggles are added please document them // in configuration.md, too // **************** // In general each macro has a _NO_<feature name> form // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature. // Many features, at point of detection, define an _INTERNAL_ macro, so they // can be combined, en-mass, with the _NO_ forms later. #ifdef __cplusplus # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L) # define CATCH_CPP14_OR_GREATER # endif # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) # define CATCH_CPP17_OR_GREATER # endif #endif #if defined(CATCH_CPP17_OR_GREATER) # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS #endif #ifdef __clang__ # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ _Pragma( "clang diagnostic push" ) \ _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"") # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ _Pragma( "clang diagnostic pop" ) # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ _Pragma( "clang diagnostic push" ) \ _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \ _Pragma( "clang diagnostic pop" ) # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ _Pragma( "clang diagnostic push" ) \ _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" ) # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS \ _Pragma( "clang diagnostic pop" ) #endif // __clang__ //////////////////////////////////////////////////////////////////////////////// // Assume that non-Windows platforms support posix signals by default #if !defined(CATCH_PLATFORM_WINDOWS) #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS #endif //////////////////////////////////////////////////////////////////////////////// // We know some environments not to support full POSIX signals #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__) #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS #endif #ifdef __OS400__ # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS # define CATCH_CONFIG_COLOUR_NONE #endif //////////////////////////////////////////////////////////////////////////////// // Android somehow still does not support std::to_string #if defined(__ANDROID__) # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING #endif //////////////////////////////////////////////////////////////////////////////// // Not all Windows environments support SEH properly #if defined(__MINGW32__) # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH #endif //////////////////////////////////////////////////////////////////////////////// // PS4 #if defined(__ORBIS__) # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE #endif //////////////////////////////////////////////////////////////////////////////// // Cygwin #ifdef __CYGWIN__ // Required for some versions of Cygwin to declare gettimeofday // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin # define _BSD_SOURCE // some versions of cygwin (most) do not support std::to_string. Use the libstd check. // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813 # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \ && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF)) # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING # endif #endif // __CYGWIN__ //////////////////////////////////////////////////////////////////////////////// // Visual C++ #ifdef _MSC_VER # if _MSC_VER >= 1900 // Visual Studio 2015 or newer # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS # endif // Universal Windows platform does not support SEH // Or console colours (or console at all...) # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) # define CATCH_CONFIG_COLOUR_NONE # else # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH # endif // MSVC traditional preprocessor needs some workaround for __VA_ARGS__ // _MSVC_TRADITIONAL == 0 means new conformant preprocessor // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR # endif #endif // _MSC_VER //////////////////////////////////////////////////////////////////////////////// // Check if we are compiled with -fno-exceptions or equivalent #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND) # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED #endif //////////////////////////////////////////////////////////////////////////////// // DJGPP #ifdef __DJGPP__ # define CATCH_INTERNAL_CONFIG_NO_WCHAR #endif // __DJGPP__ //////////////////////////////////////////////////////////////////////////////// // Embarcadero C++Build #if defined(__BORLANDC__) #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN #endif //////////////////////////////////////////////////////////////////////////////// // Use of __COUNTER__ is suppressed during code analysis in // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly // handled by it. // Otherwise all supported compilers support COUNTER macro, // but user still might want to turn it off #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L ) #define CATCH_INTERNAL_CONFIG_COUNTER #endif //////////////////////////////////////////////////////////////////////////////// // Check if string_view is available and usable // The check is split apart to work around v140 (VS2015) preprocessor issue... #if defined(__has_include) #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER) # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW #endif #endif //////////////////////////////////////////////////////////////////////////////// // Check if optional is available and usable #if defined(__has_include) # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER) # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER) #endif // __has_include //////////////////////////////////////////////////////////////////////////////// // Check if variant is available and usable #if defined(__has_include) # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER) # if defined(__clang__) && (__clang_major__ < 8) // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852 // fix should be in clang 8, workaround in libstdc++ 8.2 # include <ciso646> # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) # define CATCH_CONFIG_NO_CPP17_VARIANT # else # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) # else # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT # endif // defined(__clang__) && (__clang_major__ < 8) # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER) #endif // __has_include #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) # define CATCH_CONFIG_COUNTER #endif #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH) # define CATCH_CONFIG_WINDOWS_SEH #endif // This is set by default, because we assume that unix compilers are posix-signal-compatible by default. #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS) # define CATCH_CONFIG_POSIX_SIGNALS #endif // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR) # define CATCH_CONFIG_WCHAR #endif #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING) # define CATCH_CONFIG_CPP11_TO_STRING #endif #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL) # define CATCH_CONFIG_CPP17_OPTIONAL #endif #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS #endif #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) # define CATCH_CONFIG_CPP17_STRING_VIEW #endif #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT) # define CATCH_CONFIG_CPP17_VARIANT #endif #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE #endif #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE) # define CATCH_CONFIG_NEW_CAPTURE #endif #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) # define CATCH_CONFIG_DISABLE_EXCEPTIONS #endif #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN) # define CATCH_CONFIG_POLYFILL_ISNAN #endif #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS #endif #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) #define CATCH_TRY if ((true)) #define CATCH_CATCH_ALL if ((false)) #define CATCH_CATCH_ANON(type) if ((false)) #else #define CATCH_TRY try #define CATCH_CATCH_ALL catch (...) #define CATCH_CATCH_ANON(type) catch (type) #endif #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #endif // end catch_compiler_capabilities.h #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) #ifdef CATCH_CONFIG_COUNTER # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) #else # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) #endif #include <iosfwd> #include <string> #include <cstdint> // We need a dummy global operator<< so we can bring it into Catch namespace later struct Catch_global_namespace_dummy {}; std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy); namespace Catch { struct CaseSensitive { enum Choice { Yes, No }; }; class NonCopyable { NonCopyable( NonCopyable const& ) = delete; NonCopyable( NonCopyable && ) = delete; NonCopyable& operator = ( NonCopyable const& ) = delete; NonCopyable& operator = ( NonCopyable && ) = delete; protected: NonCopyable(); virtual ~NonCopyable(); }; struct SourceLineInfo { SourceLineInfo() = delete; SourceLineInfo( char const* _file, std::size_t _line ) noexcept : file( _file ), line( _line ) {} SourceLineInfo( SourceLineInfo const& other ) = default; SourceLineInfo& operator = ( SourceLineInfo const& ) = default; SourceLineInfo( SourceLineInfo&& ) noexcept = default; SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default; bool empty() const noexcept; bool operator == ( SourceLineInfo const& other ) const noexcept; bool operator < ( SourceLineInfo const& other ) const noexcept; char const* file; std::size_t line; }; std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ); // Bring in operator<< from global namespace into Catch namespace // This is necessary because the overload of operator<< above makes // lookup stop at namespace Catch using ::operator<<; // Use this in variadic streaming macros to allow // >> +StreamEndStop // as well as // >> stuff +StreamEndStop struct StreamEndStop { std::string operator+() const; }; template<typename T> T const& operator + ( T const& value, StreamEndStop ) { return value; } } #define CATCH_INTERNAL_LINEINFO \ ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) ) // end catch_common.h namespace Catch { struct RegistrarForTagAliases { RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); }; } // end namespace Catch #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS // end catch_tag_alias_autoregistrar.h // start catch_test_registry.h // start catch_interfaces_testcase.h #include <vector> namespace Catch { class TestSpec; struct ITestInvoker { virtual void invoke () const = 0; virtual ~ITestInvoker(); }; class TestCase; struct IConfig; struct ITestCaseRegistry { virtual ~ITestCaseRegistry(); virtual std::vector<TestCase> const& getAllTests() const = 0; virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0; }; bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ); std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ); } // end catch_interfaces_testcase.h // start catch_stringref.h #include <cstddef> #include <string> #include <iosfwd> namespace Catch { /// A non-owning string class (similar to the forthcoming std::string_view) /// Note that, because a StringRef may be a substring of another string, /// it may not be null terminated. c_str() must return a null terminated /// string, however, and so the StringRef will internally take ownership /// (taking a copy), if necessary. In theory this ownership is not externally /// visible - but it does mean (substring) StringRefs should not be shared between /// threads. class StringRef { public: using size_type = std::size_t; private: friend struct StringRefTestAccess; char const* m_start; size_type m_size; char* m_data = nullptr; void takeOwnership(); static constexpr char const* const s_empty = ""; public: // construction/ assignment StringRef() noexcept : StringRef( s_empty, 0 ) {} StringRef( StringRef const& other ) noexcept : m_start( other.m_start ), m_size( other.m_size ) {} StringRef( StringRef&& other ) noexcept : m_start( other.m_start ), m_size( other.m_size ), m_data( other.m_data ) { other.m_data = nullptr; } StringRef( char const* rawChars ) noexcept; StringRef( char const* rawChars, size_type size ) noexcept : m_start( rawChars ), m_size( size ) {} StringRef( std::string const& stdString ) noexcept : m_start( stdString.c_str() ), m_size( stdString.size() ) {} ~StringRef() noexcept { delete[] m_data; } auto operator = ( StringRef const &other ) noexcept -> StringRef& { delete[] m_data; m_data = nullptr; m_start = other.m_start; m_size = other.m_size; return *this; } operator std::string() const; void swap( StringRef& other ) noexcept; public: // operators auto operator == ( StringRef const& other ) const noexcept -> bool; auto operator != ( StringRef const& other ) const noexcept -> bool; auto operator[] ( size_type index ) const noexcept -> char; public: // named queries auto empty() const noexcept -> bool { return m_size == 0; } auto size() const noexcept -> size_type { return m_size; } auto numberOfCharacters() const noexcept -> size_type; auto c_str() const -> char const*; public: // substrings and searches auto substr( size_type start, size_type size ) const noexcept -> StringRef; // Returns the current start pointer. // Note that the pointer can change when if the StringRef is a substring auto currentData() const noexcept -> char const*; private: // ownership queries - may not be consistent between calls auto isOwned() const noexcept -> bool; auto isSubstring() const noexcept -> bool; }; auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string; auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string; auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string; auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&; auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&; inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef { return StringRef( rawChars, size ); } } // namespace Catch inline auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef { return Catch::StringRef( rawChars, size ); } // end catch_stringref.h // start catch_type_traits.hpp #include <type_traits> namespace Catch{ #ifdef CATCH_CPP17_OR_GREATER template <typename...> inline constexpr auto is_unique = std::true_type{}; template <typename T, typename... Rest> inline constexpr auto is_unique<T, Rest...> = std::bool_constant< (!std::is_same_v<T, Rest> && ...) && is_unique<Rest...> >{}; #else template <typename...> struct is_unique : std::true_type{}; template <typename T0, typename T1, typename... Rest> struct is_unique<T0, T1, Rest...> : std::integral_constant <bool, !std::is_same<T0, T1>::value && is_unique<T0, Rest...>::value && is_unique<T1, Rest...>::value >{}; #endif } // end catch_type_traits.hpp // start catch_preprocessor.hpp #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__ #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__))) #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__))) #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__))) #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__))) #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__))) #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__ // MSVC needs more evaluations #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__))) #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__)) #else #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__) #endif #define CATCH_REC_END(...) #define CATCH_REC_OUT #define CATCH_EMPTY() #define CATCH_DEFER(id) id CATCH_EMPTY() #define CATCH_REC_GET_END2() 0, CATCH_REC_END #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0) #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next) #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ ) #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ ) #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results, // and passes userdata as the first parameter to each invocation, // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c) #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param) #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__ #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__ #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__) #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME2(Name, ...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME3(Name, __VA_ARGS__) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME3(Name,...) Name " - " #__VA_ARGS__ #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME(Name,...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME2(Name, INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)) #else // MSVC is adding extra space and needs more calls to properly remove () #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME3(Name,...) Name " -" #__VA_ARGS__ #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME1(Name, ...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME2(Name, __VA_ARGS__) #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME(Name, ...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME1(Name, INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))) #endif #define INTERNAL_CATCH_MAKE_TYPE_LIST(types) TypeList<INTERNAL_CATCH_REMOVE_PARENS(types)> #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(types)\ CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,INTERNAL_CATCH_REMOVE_PARENS(types)) // end catch_preprocessor.hpp // start catch_meta.hpp #include <type_traits> template< typename... > struct TypeList{}; template< typename... > struct append; template< template<typename...> class L1 , typename...E1 , template<typename...> class L2 , typename...E2 > struct append< L1<E1...>, L2<E2...> > { using type = L1<E1..., E2...>; }; template< template<typename...> class L1 , typename...E1 , template<typename...> class L2 , typename...E2 , typename...Rest > struct append< L1<E1...>, L2<E2...>, Rest...> { using type = typename append< L1<E1..., E2...>, Rest... >::type; }; template< template<typename...> class , typename... > struct rewrap; template< template<typename...> class Container , template<typename...> class List , typename...elems > struct rewrap<Container, List<elems...>> { using type = TypeList< Container< elems... > >; }; template< template<typename...> class Container , template<typename...> class List , class...Elems , typename...Elements> struct rewrap<Container, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<Container, Elements...>::type>::type; }; template< template<typename...> class...Containers > struct combine { template< typename...Types > struct with_types { template< template <typename...> class Final > struct into { using type = typename append<Final<>, typename rewrap<Containers, Types...>::type...>::type; }; }; }; template<typename T> struct always_false : std::false_type {}; // end catch_meta.hpp namespace Catch { template<typename C> class TestInvokerAsMethod : public ITestInvoker { void (C::*m_testAsMethod)(); public: TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {} void invoke() const override { C obj; (obj.*m_testAsMethod)(); } }; auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*; template<typename C> auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* { return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod ); } struct NameAndTags { NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept; StringRef name; StringRef tags; }; struct AutoReg : NonCopyable { AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept; ~AutoReg(); }; } // end namespace Catch #if defined(CATCH_CONFIG_DISABLE) #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \ static void TestName() #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \ namespace{ \ struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ void test(); \ }; \ } \ void TestName::test() #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION( TestName, ... ) \ template<typename TestType> \ static void TestName() #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \ namespace{ \ template<typename TestType> \ struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \ void test(); \ }; \ } \ template<typename TestType> \ void TestName::test() #endif /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \ static void TestName(); \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ static void TestName() #define INTERNAL_CATCH_TESTCASE( ... ) \ INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace{ \ struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ void test(); \ }; \ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \ } \ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ void TestName::test() #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \ INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, ... )\ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ template<typename TestType> \ static void TestFunc();\ namespace {\ template<typename...Types> \ struct TestName{\ template<typename...Ts> \ TestName(Ts...names){\ CATCH_INTERNAL_CHECK_UNIQUE_TYPES(CATCH_REC_LIST(INTERNAL_CATCH_REMOVE_PARENS, __VA_ARGS__)) \ using expander = int[];\ (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ names, Tags } ), 0)... };/* NOLINT */ \ }\ };\ INTERNAL_CATCH_TEMPLATE_REGISTRY_INITIATE(TestName, Name, __VA_ARGS__) \ }\ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ template<typename TestType> \ static void TestFunc() #if defined(CATCH_CPP17_OR_GREATER) #define CATCH_INTERNAL_CHECK_UNIQUE_TYPES(...) static_assert(Catch::is_unique<__VA_ARGS__>,"Duplicate type detected in declaration of template test case"); #else #define CATCH_INTERNAL_CHECK_UNIQUE_TYPES(...) static_assert(Catch::is_unique<__VA_ARGS__>::value,"Duplicate type detected in declaration of template test case"); #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, __VA_ARGS__ ) ) #endif #define INTERNAL_CATCH_TEMPLATE_REGISTRY_INITIATE(TestName, Name, ...)\ static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ TestName<CATCH_REC_LIST(INTERNAL_CATCH_REMOVE_PARENS, __VA_ARGS__)>(CATCH_REC_LIST_UD(INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME,Name, __VA_ARGS__));\ return 0;\ }(); #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, TmplTypes, TypesList) \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ template<typename TestType> static void TestFuncName(); \ namespace { \ template<typename... Types> \ struct TestName { \ TestName() { \ CATCH_INTERNAL_CHECK_UNIQUE_TYPES(Types...) \ int index = 0; \ using expander = int[]; \ (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + Catch::StringMaker<int>::convert(index++), Tags } ), 0)... };/* NOLINT */ \ } \ }; \ static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \ using TestInit = combine<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)> \ ::with_types<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(TypesList)>::into<TestName>::type; \ TestInit(); \ return 0; \ }(); \ } \ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ template<typename TestType> \ static void TestFuncName() #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ),Name,Tags,__VA_ARGS__) #else #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, __VA_ARGS__ ) ) #endif #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, ... ) \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace{ \ template<typename TestType> \ struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \ void test();\ };\ template<typename...Types> \ struct TestNameClass{\ template<typename...Ts> \ TestNameClass(Ts...names){\ CATCH_INTERNAL_CHECK_UNIQUE_TYPES(CATCH_REC_LIST(INTERNAL_CATCH_REMOVE_PARENS, __VA_ARGS__)) \ using expander = int[];\ (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ names, Tags } ), 0)... };/* NOLINT */ \ }\ };\ INTERNAL_CATCH_TEMPLATE_REGISTRY_INITIATE(TestNameClass, Name, __VA_ARGS__)\ }\ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS\ template<typename TestType> \ void TestName<TestType>::test() #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, __VA_ARGS__ ) ) #endif #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, TmplTypes, TypesList)\ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ template<typename TestType> \ struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \ void test();\ };\ namespace {\ template<typename...Types>\ struct TestNameClass{\ TestNameClass(){\ CATCH_INTERNAL_CHECK_UNIQUE_TYPES(Types...)\ int index = 0;\ using expander = int[];\ (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + Catch::StringMaker<int>::convert(index++), Tags } ), 0)... };/* NOLINT */ \ }\ };\ static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ using TestInit = combine<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>\ ::with_types<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(TypesList)>::into<TestNameClass>::type;\ TestInit();\ return 0;\ }(); \ }\ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ template<typename TestType> \ void TestName<TestType>::test() #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, __VA_ARGS__ ) ) #endif // end catch_test_registry.h // start catch_capture.hpp // start catch_assertionhandler.h // start catch_assertioninfo.h // start catch_result_type.h namespace Catch { // ResultWas::OfType enum struct ResultWas { enum OfType { Unknown = -1, Ok = 0, Info = 1, Warning = 2, FailureBit = 0x10, ExpressionFailed = FailureBit | 1, ExplicitFailure = FailureBit | 2, Exception = 0x100 | FailureBit, ThrewException = Exception | 1, DidntThrowException = Exception | 2, FatalErrorCondition = 0x200 | FailureBit }; }; bool isOk( ResultWas::OfType resultType ); bool isJustInfo( int flags ); // ResultDisposition::Flags enum struct ResultDisposition { enum Flags { Normal = 0x01, ContinueOnFailure = 0x02, // Failures fail test, but execution continues FalseTest = 0x04, // Prefix expression with ! SuppressFail = 0x08 // Failures are reported but do not fail the test }; }; ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ); bool shouldContinueOnFailure( int flags ); inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; } bool shouldSuppressFailure( int flags ); } // end namespace Catch // end catch_result_type.h namespace Catch { struct AssertionInfo { StringRef macroName; SourceLineInfo lineInfo; StringRef capturedExpression; ResultDisposition::Flags resultDisposition; // We want to delete this constructor but a compiler bug in 4.8 means // the struct is then treated as non-aggregate //AssertionInfo() = delete; }; } // end namespace Catch // end catch_assertioninfo.h // start catch_decomposer.h // start catch_tostring.h #include <vector> #include <cstddef> #include <type_traits> #include <string> // start catch_stream.h #include <iosfwd> #include <cstddef> #include <ostream> namespace Catch { std::ostream& cout(); std::ostream& cerr(); std::ostream& clog(); class StringRef; struct IStream { virtual ~IStream(); virtual std::ostream& stream() const = 0; }; auto makeStream( StringRef const &filename ) -> IStream const*; class ReusableStringStream { std::size_t m_index; std::ostream* m_oss; public: ReusableStringStream(); ~ReusableStringStream(); auto str() const -> std::string; template<typename T> auto operator << ( T const& value ) -> ReusableStringStream& { *m_oss << value; return *this; } auto get() -> std::ostream& { return *m_oss; } }; } // end catch_stream.h #ifdef CATCH_CONFIG_CPP17_STRING_VIEW #include <string_view> #endif #ifdef __OBJC__ // start catch_objc_arc.hpp #import <Foundation/Foundation.h> #ifdef __has_feature #define CATCH_ARC_ENABLED __has_feature(objc_arc) #else #define CATCH_ARC_ENABLED 0 #endif void arcSafeRelease( NSObject* obj ); id performOptionalSelector( id obj, SEL sel ); #if !CATCH_ARC_ENABLED inline void arcSafeRelease( NSObject* obj ) { [obj release]; } inline id performOptionalSelector( id obj, SEL sel ) { if( [obj respondsToSelector: sel] ) return [obj performSelector: sel]; return nil; } #define CATCH_UNSAFE_UNRETAINED #define CATCH_ARC_STRONG #else inline void arcSafeRelease( NSObject* ){} inline id performOptionalSelector( id obj, SEL sel ) { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" #endif if( [obj respondsToSelector: sel] ) return [obj performSelector: sel]; #ifdef __clang__ #pragma clang diagnostic pop #endif return nil; } #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained #define CATCH_ARC_STRONG __strong #endif // end catch_objc_arc.hpp #endif #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless #endif namespace Catch { namespace Detail { extern const std::string unprintableString; std::string rawMemoryToString( const void *object, std::size_t size ); template<typename T> std::string rawMemoryToString( const T& object ) { return rawMemoryToString( &object, sizeof(object) ); } template<typename T> class IsStreamInsertable { template<typename SS, typename TT> static auto test(int) -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type()); template<typename, typename> static auto test(...)->std::false_type; public: static const bool value = decltype(test<std::ostream, const T&>(0))::value; }; template<typename E> std::string convertUnknownEnumToString( E e ); template<typename T> typename std::enable_if< !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value, std::string>::type convertUnstreamable( T const& ) { return Detail::unprintableString; } template<typename T> typename std::enable_if< !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value, std::string>::type convertUnstreamable(T const& ex) { return ex.what(); } template<typename T> typename std::enable_if< std::is_enum<T>::value , std::string>::type convertUnstreamable( T const& value ) { return convertUnknownEnumToString( value ); } #if defined(_MANAGED) //! Convert a CLR string to a utf8 std::string template<typename T> std::string clrReferenceToString( T^ ref ) { if (ref == nullptr) return std::string("null"); auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString()); cli::pin_ptr<System::Byte> p = &bytes[0]; return std::string(reinterpret_cast<char const *>(p), bytes->Length); } #endif } // namespace Detail // If we decide for C++14, change these to enable_if_ts template <typename T, typename = void> struct StringMaker { template <typename Fake = T> static typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type convert(const Fake& value) { ReusableStringStream rss; // NB: call using the function-like syntax to avoid ambiguity with // user-defined templated operator<< under clang. rss.operator<<(value); return rss.str(); } template <typename Fake = T> static typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type convert( const Fake& value ) { #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER) return Detail::convertUnstreamable(value); #else return CATCH_CONFIG_FALLBACK_STRINGIFIER(value); #endif } }; namespace Detail { // This function dispatches all stringification requests inside of Catch. // Should be preferably called fully qualified, like ::Catch::Detail::stringify template <typename T> std::string stringify(const T& e) { return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e); } template<typename E> std::string convertUnknownEnumToString( E e ) { return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e)); } #if defined(_MANAGED) template <typename T> std::string stringify( T^ e ) { return ::Catch::StringMaker<T^>::convert(e); } #endif } // namespace Detail // Some predefined specializations template<> struct StringMaker<std::string> { static std::string convert(const std::string& str); }; #ifdef CATCH_CONFIG_CPP17_STRING_VIEW template<> struct StringMaker<std::string_view> { static std::string convert(std::string_view str); }; #endif template<> struct StringMaker<char const *> { static std::string convert(char const * str); }; template<> struct StringMaker<char *> { static std::string convert(char * str); }; #ifdef CATCH_CONFIG_WCHAR template<> struct StringMaker<std::wstring> { static std::string convert(const std::wstring& wstr); }; # ifdef CATCH_CONFIG_CPP17_STRING_VIEW template<> struct StringMaker<std::wstring_view> { static std::string convert(std::wstring_view str); }; # endif template<> struct StringMaker<wchar_t const *> { static std::string convert(wchar_t const * str); }; template<> struct StringMaker<wchar_t *> { static std::string convert(wchar_t * str); }; #endif // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer, // while keeping string semantics? template<int SZ> struct StringMaker<char[SZ]> { static std::string convert(char const* str) { return ::Catch::Detail::stringify(std::string{ str }); } }; template<int SZ> struct StringMaker<signed char[SZ]> { static std::string convert(signed char const* str) { return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) }); } }; template<int SZ> struct StringMaker<unsigned char[SZ]> { static std::string convert(unsigned char const* str) { return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) }); } }; template<> struct StringMaker<int> { static std::string convert(int value); }; template<> struct StringMaker<long> { static std::string convert(long value); }; template<> struct StringMaker<long long> { static std::string convert(long long value); }; template<> struct StringMaker<unsigned int> { static std::string convert(unsigned int value); }; template<> struct StringMaker<unsigned long> { static std::string convert(unsigned long value); }; template<> struct StringMaker<unsigned long long> { static std::string convert(unsigned long long value); }; template<> struct StringMaker<bool> { static std::string convert(bool b); }; template<> struct StringMaker<char> { static std::string convert(char c); }; template<> struct StringMaker<signed char> { static std::string convert(signed char c); }; template<> struct StringMaker<unsigned char> { static std::string convert(unsigned char c); }; template<> struct StringMaker<std::nullptr_t> { static std::string convert(std::nullptr_t); }; template<> struct StringMaker<float> { static std::string convert(float value); }; template<> struct StringMaker<double> { static std::string convert(double value); }; template <typename T> struct StringMaker<T*> { template <typename U> static std::string convert(U* p) { if (p) { return ::Catch::Detail::rawMemoryToString(p); } else { return "nullptr"; } } }; template <typename R, typename C> struct StringMaker<R C::*> { static std::string convert(R C::* p) { if (p) { return ::Catch::Detail::rawMemoryToString(p); } else { return "nullptr"; } } }; #if defined(_MANAGED) template <typename T> struct StringMaker<T^> { static std::string convert( T^ ref ) { return ::Catch::Detail::clrReferenceToString(ref); } }; #endif namespace Detail { template<typename InputIterator> std::string rangeToString(InputIterator first, InputIterator last) { ReusableStringStream rss; rss << "{ "; if (first != last) { rss << ::Catch::Detail::stringify(*first); for (++first; first != last; ++first) rss << ", " << ::Catch::Detail::stringify(*first); } rss << " }"; return rss.str(); } } #ifdef __OBJC__ template<> struct StringMaker<NSString*> { static std::string convert(NSString * nsstring) { if (!nsstring) return "nil"; return std::string("@") + [nsstring UTF8String]; } }; template<> struct StringMaker<NSObject*> { static std::string convert(NSObject* nsObject) { return ::Catch::Detail::stringify([nsObject description]); } }; namespace Detail { inline std::string stringify( NSString* nsstring ) { return StringMaker<NSString*>::convert( nsstring ); } } // namespace Detail #endif // __OBJC__ } // namespace Catch ////////////////////////////////////////////////////// // Separate std-lib types stringification, so it can be selectively enabled // This means that we do not bring in #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS) # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER #endif // Separate std::pair specialization #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER) #include <utility> namespace Catch { template<typename T1, typename T2> struct StringMaker<std::pair<T1, T2> > { static std::string convert(const std::pair<T1, T2>& pair) { ReusableStringStream rss; rss << "{ " << ::Catch::Detail::stringify(pair.first) << ", " << ::Catch::Detail::stringify(pair.second) << " }"; return rss.str(); } }; } #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL) #include <optional> namespace Catch { template<typename T> struct StringMaker<std::optional<T> > { static std::string convert(const std::optional<T>& optional) { ReusableStringStream rss; if (optional.has_value()) { rss << ::Catch::Detail::stringify(*optional); } else { rss << "{ }"; } return rss.str(); } }; } #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER // Separate std::tuple specialization #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER) #include <tuple> namespace Catch { namespace Detail { template< typename Tuple, std::size_t N = 0, bool = (N < std::tuple_size<Tuple>::value) > struct TupleElementPrinter { static void print(const Tuple& tuple, std::ostream& os) { os << (N ? ", " : " ") << ::Catch::Detail::stringify(std::get<N>(tuple)); TupleElementPrinter<Tuple, N + 1>::print(tuple, os); } }; template< typename Tuple, std::size_t N > struct TupleElementPrinter<Tuple, N, false> { static void print(const Tuple&, std::ostream&) {} }; } template<typename ...Types> struct StringMaker<std::tuple<Types...>> { static std::string convert(const std::tuple<Types...>& tuple) { ReusableStringStream rss; rss << '{'; Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get()); rss << " }"; return rss.str(); } }; } #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT) #include <variant> namespace Catch { template<> struct StringMaker<std::monostate> { static std::string convert(const std::monostate&) { return "{ }"; } }; template<typename... Elements> struct StringMaker<std::variant<Elements...>> { static std::string convert(const std::variant<Elements...>& variant) { if (variant.valueless_by_exception()) { return "{valueless variant}"; } else { return std::visit( [](const auto& value) { return ::Catch::Detail::stringify(value); }, variant ); } } }; } #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER namespace Catch { struct not_this_one {}; // Tag type for detecting which begin/ end are being selected // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace using std::begin; using std::end; not_this_one begin( ... ); not_this_one end( ... ); template <typename T> struct is_range { static const bool value = !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value && !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value; }; #if defined(_MANAGED) // Managed types are never ranges template <typename T> struct is_range<T^> { static const bool value = false; }; #endif template<typename Range> std::string rangeToString( Range const& range ) { return ::Catch::Detail::rangeToString( begin( range ), end( range ) ); } // Handle vector<bool> specially template<typename Allocator> std::string rangeToString( std::vector<bool, Allocator> const& v ) { ReusableStringStream rss; rss << "{ "; bool first = true; for( bool b : v ) { if( first ) first = false; else rss << ", "; rss << ::Catch::Detail::stringify( b ); } rss << " }"; return rss.str(); } template<typename R> struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> { static std::string convert( R const& range ) { return rangeToString( range ); } }; template <typename T, int SZ> struct StringMaker<T[SZ]> { static std::string convert(T const(&arr)[SZ]) { return rangeToString(arr); } }; } // namespace Catch // Separate std::chrono::duration specialization #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) #include <ctime> #include <ratio> #include <chrono> namespace Catch { template <class Ratio> struct ratio_string { static std::string symbol(); }; template <class Ratio> std::string ratio_string<Ratio>::symbol() { Catch::ReusableStringStream rss; rss << '[' << Ratio::num << '/' << Ratio::den << ']'; return rss.str(); } template <> struct ratio_string<std::atto> { static std::string symbol(); }; template <> struct ratio_string<std::femto> { static std::string symbol(); }; template <> struct ratio_string<std::pico> { static std::string symbol(); }; template <> struct ratio_string<std::nano> { static std::string symbol(); }; template <> struct ratio_string<std::micro> { static std::string symbol(); }; template <> struct ratio_string<std::milli> { static std::string symbol(); }; //////////// // std::chrono::duration specializations template<typename Value, typename Ratio> struct StringMaker<std::chrono::duration<Value, Ratio>> { static std::string convert(std::chrono::duration<Value, Ratio> const& duration) { ReusableStringStream rss; rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's'; return rss.str(); } }; template<typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> { static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) { ReusableStringStream rss; rss << duration.count() << " s"; return rss.str(); } }; template<typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> { static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) { ReusableStringStream rss; rss << duration.count() << " m"; return rss.str(); } }; template<typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> { static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) { ReusableStringStream rss; rss << duration.count() << " h"; return rss.str(); } }; //////////// // std::chrono::time_point specialization // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock> template<typename Clock, typename Duration> struct StringMaker<std::chrono::time_point<Clock, Duration>> { static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) { return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch"; } }; // std::chrono::time_point<system_clock> specialization template<typename Duration> struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> { static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) { auto converted = std::chrono::system_clock::to_time_t(time_point); #ifdef _MSC_VER std::tm timeInfo = {}; gmtime_s(&timeInfo, &converted); #else std::tm* timeInfo = std::gmtime(&converted); #endif auto const timeStampSize = sizeof("2017-01-16T17:06:45Z"); char timeStamp[timeStampSize]; const char * const fmt = "%Y-%m-%dT%H:%M:%SZ"; #ifdef _MSC_VER std::strftime(timeStamp, timeStampSize, fmt, &timeInfo); #else std::strftime(timeStamp, timeStampSize, fmt, timeInfo); #endif return std::string(timeStamp); } }; } #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER #ifdef _MSC_VER #pragma warning(pop) #endif // end catch_tostring.h #include <iosfwd> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4389) // '==' : signed/unsigned mismatch #pragma warning(disable:4018) // more "signed/unsigned mismatch" #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform) #pragma warning(disable:4180) // qualifier applied to function type has no meaning #pragma warning(disable:4800) // Forcing result to true or false #endif namespace Catch { struct ITransientExpression { auto isBinaryExpression() const -> bool { return m_isBinaryExpression; } auto getResult() const -> bool { return m_result; } virtual void streamReconstructedExpression( std::ostream &os ) const = 0; ITransientExpression( bool isBinaryExpression, bool result ) : m_isBinaryExpression( isBinaryExpression ), m_result( result ) {} // We don't actually need a virtual destructor, but many static analysers // complain if it's not here :-( virtual ~ITransientExpression(); bool m_isBinaryExpression; bool m_result; }; void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ); template<typename LhsT, typename RhsT> class BinaryExpr : public ITransientExpression { LhsT m_lhs; StringRef m_op; RhsT m_rhs; void streamReconstructedExpression( std::ostream &os ) const override { formatReconstructedExpression ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) ); } public: BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs ) : ITransientExpression{ true, comparisonResult }, m_lhs( lhs ), m_op( op ), m_rhs( rhs ) {} template<typename T> auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<T>::value, "chained comparisons are not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } template<typename T> auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<T>::value, "chained comparisons are not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } template<typename T> auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<T>::value, "chained comparisons are not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } template<typename T> auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<T>::value, "chained comparisons are not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } template<typename T> auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<T>::value, "chained comparisons are not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } template<typename T> auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<T>::value, "chained comparisons are not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } template<typename T> auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<T>::value, "chained comparisons are not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } template<typename T> auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<T>::value, "chained comparisons are not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } }; template<typename LhsT> class UnaryExpr : public ITransientExpression { LhsT m_lhs; void streamReconstructedExpression( std::ostream &os ) const override { os << Catch::Detail::stringify( m_lhs ); } public: explicit UnaryExpr( LhsT lhs ) : ITransientExpression{ false, static_cast<bool>(lhs) }, m_lhs( lhs ) {} }; // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int) template<typename LhsT, typename RhsT> auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); } template<typename T> auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); } template<typename T> auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); } template<typename T> auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; } template<typename T> auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; } template<typename LhsT, typename RhsT> auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); } template<typename T> auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); } template<typename T> auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); } template<typename T> auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; } template<typename T> auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; } template<typename LhsT> class ExprLhs { LhsT m_lhs; public: explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {} template<typename RhsT> auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs }; } auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const { return { m_lhs == rhs, m_lhs, "==", rhs }; } template<typename RhsT> auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs }; } auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const { return { m_lhs != rhs, m_lhs, "!=", rhs }; } template<typename RhsT> auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs }; } template<typename RhsT> auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs }; } template<typename RhsT> auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs }; } template<typename RhsT> auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs }; } template<typename RhsT> auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<RhsT>::value, "operator&& is not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } template<typename RhsT> auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<RhsT>::value, "operator|| is not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } auto makeUnaryExpr() const -> UnaryExpr<LhsT> { return UnaryExpr<LhsT>{ m_lhs }; } }; void handleExpression( ITransientExpression const& expr ); template<typename T> void handleExpression( ExprLhs<T> const& expr ) { handleExpression( expr.makeUnaryExpr() ); } struct Decomposer { template<typename T> auto operator <= ( T const& lhs ) -> ExprLhs<T const&> { return ExprLhs<T const&>{ lhs }; } auto operator <=( bool value ) -> ExprLhs<bool> { return ExprLhs<bool>{ value }; } }; } // end namespace Catch #ifdef _MSC_VER #pragma warning(pop) #endif // end catch_decomposer.h // start catch_interfaces_capture.h #include <string> namespace Catch { class AssertionResult; struct AssertionInfo; struct SectionInfo; struct SectionEndInfo; struct MessageInfo; struct Counts; struct BenchmarkInfo; struct BenchmarkStats; struct AssertionReaction; struct SourceLineInfo; struct ITransientExpression; struct IGeneratorTracker; struct IResultCapture { virtual ~IResultCapture(); virtual bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) = 0; virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0; virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0; virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0; virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0; virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0; virtual void pushScopedMessage( MessageInfo const& message ) = 0; virtual void popScopedMessage( MessageInfo const& message ) = 0; virtual void handleFatalErrorCondition( StringRef message ) = 0; virtual void handleExpr ( AssertionInfo const& info, ITransientExpression const& expr, AssertionReaction& reaction ) = 0; virtual void handleMessage ( AssertionInfo const& info, ResultWas::OfType resultType, StringRef const& message, AssertionReaction& reaction ) = 0; virtual void handleUnexpectedExceptionNotThrown ( AssertionInfo const& info, AssertionReaction& reaction ) = 0; virtual void handleUnexpectedInflightException ( AssertionInfo const& info, std::string const& message, AssertionReaction& reaction ) = 0; virtual void handleIncomplete ( AssertionInfo const& info ) = 0; virtual void handleNonExpr ( AssertionInfo const &info, ResultWas::OfType resultType, AssertionReaction &reaction ) = 0; virtual bool lastAssertionPassed() = 0; virtual void assertionPassed() = 0; // Deprecated, do not use: virtual std::string getCurrentTestName() const = 0; virtual const AssertionResult* getLastResult() const = 0; virtual void exceptionEarlyReported() = 0; }; IResultCapture& getResultCapture(); } // end catch_interfaces_capture.h namespace Catch { struct TestFailureException{}; struct AssertionResultData; struct IResultCapture; class RunContext; class LazyExpression { friend class AssertionHandler; friend struct AssertionStats; friend class RunContext; ITransientExpression const* m_transientExpression = nullptr; bool m_isNegated; public: LazyExpression( bool isNegated ); LazyExpression( LazyExpression const& other ); LazyExpression& operator = ( LazyExpression const& ) = delete; explicit operator bool() const; friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&; }; struct AssertionReaction { bool shouldDebugBreak = false; bool shouldThrow = false; }; class AssertionHandler { AssertionInfo m_assertionInfo; AssertionReaction m_reaction; bool m_completed = false; IResultCapture& m_resultCapture; public: AssertionHandler ( StringRef const& macroName, SourceLineInfo const& lineInfo, StringRef capturedExpression, ResultDisposition::Flags resultDisposition ); ~AssertionHandler() { if ( !m_completed ) { m_resultCapture.handleIncomplete( m_assertionInfo ); } } template<typename T> void handleExpr( ExprLhs<T> const& expr ) { handleExpr( expr.makeUnaryExpr() ); } void handleExpr( ITransientExpression const& expr ); void handleMessage(ResultWas::OfType resultType, StringRef const& message); void handleExceptionThrownAsExpected(); void handleUnexpectedExceptionNotThrown(); void handleExceptionNotThrownAsExpected(); void handleThrowingCallSkipped(); void handleUnexpectedInflightException(); void complete(); void setCompleted(); // query auto allowThrows() const -> bool; }; void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ); } // namespace Catch // end catch_assertionhandler.h // start catch_message.h #include <string> #include <vector> namespace Catch { struct MessageInfo { MessageInfo( StringRef const& _macroName, SourceLineInfo const& _lineInfo, ResultWas::OfType _type ); StringRef macroName; std::string message; SourceLineInfo lineInfo; ResultWas::OfType type; unsigned int sequence; bool operator == ( MessageInfo const& other ) const; bool operator < ( MessageInfo const& other ) const; private: static unsigned int globalCount; }; struct MessageStream { template<typename T> MessageStream& operator << ( T const& value ) { m_stream << value; return *this; } ReusableStringStream m_stream; }; struct MessageBuilder : MessageStream { MessageBuilder( StringRef const& macroName, SourceLineInfo const& lineInfo, ResultWas::OfType type ); template<typename T> MessageBuilder& operator << ( T const& value ) { m_stream << value; return *this; } MessageInfo m_info; }; class ScopedMessage { public: explicit ScopedMessage( MessageBuilder const& builder ); ~ScopedMessage(); MessageInfo m_info; }; class Capturer { std::vector<MessageInfo> m_messages; IResultCapture& m_resultCapture = getResultCapture(); size_t m_captured = 0; public: Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ); ~Capturer(); void captureValue( size_t index, std::string const& value ); template<typename T> void captureValues( size_t index, T const& value ) { captureValue( index, Catch::Detail::stringify( value ) ); } template<typename T, typename... Ts> void captureValues( size_t index, T const& value, Ts const&... values ) { captureValue( index, Catch::Detail::stringify(value) ); captureValues( index+1, values... ); } }; } // end namespace Catch // end catch_message.h #if !defined(CATCH_CONFIG_DISABLE) #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION) #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__ #else #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION" #endif #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) /////////////////////////////////////////////////////////////////////////////// // Another way to speed-up compilation is to omit local try-catch for REQUIRE* // macros. #define INTERNAL_CATCH_TRY #define INTERNAL_CATCH_CATCH( capturer ) #else // CATCH_CONFIG_FAST_COMPILE #define INTERNAL_CATCH_TRY try #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); } #endif #define INTERNAL_CATCH_REACT( handler ) handler.complete(); /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \ do { \ Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \ INTERNAL_CATCH_TRY { \ CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \ CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \ } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while( (void)0, false && static_cast<bool>( !!(__VA_ARGS__) ) ) // the expression here is never evaluated at runtime but it forces the compiler to give it a look // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&. /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \ INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ if( Catch::getResultCapture().lastAssertionPassed() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \ INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ if( !Catch::getResultCapture().lastAssertionPassed() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \ do { \ Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \ try { \ static_cast<void>(__VA_ARGS__); \ catchAssertionHandler.handleExceptionNotThrownAsExpected(); \ } \ catch( ... ) { \ catchAssertionHandler.handleUnexpectedInflightException(); \ } \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while( false ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \ do { \ Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \ if( catchAssertionHandler.allowThrows() ) \ try { \ static_cast<void>(__VA_ARGS__); \ catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ } \ catch( ... ) { \ catchAssertionHandler.handleExceptionThrownAsExpected(); \ } \ else \ catchAssertionHandler.handleThrowingCallSkipped(); \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while( false ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \ do { \ Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \ if( catchAssertionHandler.allowThrows() ) \ try { \ static_cast<void>(expr); \ catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ } \ catch( exceptionType const& ) { \ catchAssertionHandler.handleExceptionThrownAsExpected(); \ } \ catch( ... ) { \ catchAssertionHandler.handleUnexpectedInflightException(); \ } \ else \ catchAssertionHandler.handleThrowingCallSkipped(); \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while( false ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \ do { \ Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \ catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while( false ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \ auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \ varName.captureValues( 0, __VA_ARGS__ ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_INFO( macroName, log ) \ Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log ); /////////////////////////////////////////////////////////////////////////////// // Although this is matcher-based, it can be used with just a string #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \ do { \ Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ if( catchAssertionHandler.allowThrows() ) \ try { \ static_cast<void>(__VA_ARGS__); \ catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ } \ catch( ... ) { \ Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \ } \ else \ catchAssertionHandler.handleThrowingCallSkipped(); \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while( false ) #endif // CATCH_CONFIG_DISABLE // end catch_capture.hpp // start catch_section.h // start catch_section_info.h // start catch_totals.h #include <cstddef> namespace Catch { struct Counts { Counts operator - ( Counts const& other ) const; Counts& operator += ( Counts const& other ); std::size_t total() const; bool allPassed() const; bool allOk() const; std::size_t passed = 0; std::size_t failed = 0; std::size_t failedButOk = 0; }; struct Totals { Totals operator - ( Totals const& other ) const; Totals& operator += ( Totals const& other ); Totals delta( Totals const& prevTotals ) const; int error = 0; Counts assertions; Counts testCases; }; } // end catch_totals.h #include <string> namespace Catch { struct SectionInfo { SectionInfo ( SourceLineInfo const& _lineInfo, std::string const& _name ); // Deprecated SectionInfo ( SourceLineInfo const& _lineInfo, std::string const& _name, std::string const& ) : SectionInfo( _lineInfo, _name ) {} std::string name; std::string description; // !Deprecated: this will always be empty SourceLineInfo lineInfo; }; struct SectionEndInfo { SectionInfo sectionInfo; Counts prevAssertions; double durationInSeconds; }; } // end namespace Catch // end catch_section_info.h // start catch_timer.h #include <cstdint> namespace Catch { auto getCurrentNanosecondsSinceEpoch() -> uint64_t; auto getEstimatedClockResolution() -> uint64_t; class Timer { uint64_t m_nanoseconds = 0; public: void start(); auto getElapsedNanoseconds() const -> uint64_t; auto getElapsedMicroseconds() const -> uint64_t; auto getElapsedMilliseconds() const -> unsigned int; auto getElapsedSeconds() const -> double; }; } // namespace Catch // end catch_timer.h #include <string> namespace Catch { class Section : NonCopyable { public: Section( SectionInfo const& info ); ~Section(); // This indicates whether the section should be executed or not explicit operator bool() const; private: SectionInfo m_info; std::string m_name; Counts m_assertions; bool m_sectionIncluded; Timer m_timer; }; } // end namespace Catch #define INTERNAL_CATCH_SECTION( ... ) \ CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \ CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \ CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \ CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS // end catch_section.h // start catch_benchmark.h #include <cstdint> #include <string> namespace Catch { class BenchmarkLooper { std::string m_name; std::size_t m_count = 0; std::size_t m_iterationsToRun = 1; uint64_t m_resolution; Timer m_timer; static auto getResolution() -> uint64_t; public: // Keep most of this inline as it's on the code path that is being timed BenchmarkLooper( StringRef name ) : m_name( name ), m_resolution( getResolution() ) { reportStart(); m_timer.start(); } explicit operator bool() { if( m_count < m_iterationsToRun ) return true; return needsMoreIterations(); } void increment() { ++m_count; } void reportStart(); auto needsMoreIterations() -> bool; }; } // end namespace Catch #define BENCHMARK( name ) \ for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() ) // end catch_benchmark.h // start catch_interfaces_exception.h // start catch_interfaces_registry_hub.h #include <string> #include <memory> namespace Catch { class TestCase; struct ITestCaseRegistry; struct IExceptionTranslatorRegistry; struct IExceptionTranslator; struct IReporterRegistry; struct IReporterFactory; struct ITagAliasRegistry; class StartupExceptionRegistry; using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>; struct IRegistryHub { virtual ~IRegistryHub(); virtual IReporterRegistry const& getReporterRegistry() const = 0; virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0; virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0; virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0; virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0; }; struct IMutableRegistryHub { virtual ~IMutableRegistryHub(); virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0; virtual void registerListener( IReporterFactoryPtr const& factory ) = 0; virtual void registerTest( TestCase const& testInfo ) = 0; virtual void registerTranslator( const IExceptionTranslator* translator ) = 0; virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0; virtual void registerStartupException() noexcept = 0; }; IRegistryHub const& getRegistryHub(); IMutableRegistryHub& getMutableRegistryHub(); void cleanUp(); std::string translateActiveException(); } // end catch_interfaces_registry_hub.h #if defined(CATCH_CONFIG_DISABLE) #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \ static std::string translatorName( signature ) #endif #include <exception> #include <string> #include <vector> namespace Catch { using exceptionTranslateFunction = std::string(*)(); struct IExceptionTranslator; using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>; struct IExceptionTranslator { virtual ~IExceptionTranslator(); virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0; }; struct IExceptionTranslatorRegistry { virtual ~IExceptionTranslatorRegistry(); virtual std::string translateActiveException() const = 0; }; class ExceptionTranslatorRegistrar { template<typename T> class ExceptionTranslator : public IExceptionTranslator { public: ExceptionTranslator( std::string(*translateFunction)( T& ) ) : m_translateFunction( translateFunction ) {} std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override { try { if( it == itEnd ) std::rethrow_exception(std::current_exception()); else return (*it)->translate( it+1, itEnd ); } catch( T& ex ) { return m_translateFunction( ex ); } } protected: std::string(*m_translateFunction)( T& ); }; public: template<typename T> ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) { getMutableRegistryHub().registerTranslator ( new ExceptionTranslator<T>( translateFunction ) ); } }; } /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \ static std::string translatorName( signature ); \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ static std::string translatorName( signature ) #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) // end catch_interfaces_exception.h // start catch_approx.h #include <type_traits> namespace Catch { namespace Detail { class Approx { private: bool equalityComparisonImpl(double other) const; // Validates the new margin (margin >= 0) // out-of-line to avoid including stdexcept in the header void setMargin(double margin); // Validates the new epsilon (0 < epsilon < 1) // out-of-line to avoid including stdexcept in the header void setEpsilon(double epsilon); public: explicit Approx ( double value ); static Approx custom(); Approx operator-() const; template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> Approx operator()( T const& value ) { Approx approx( static_cast<double>(value) ); approx.m_epsilon = m_epsilon; approx.m_margin = m_margin; approx.m_scale = m_scale; return approx; } template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> explicit Approx( T const& value ): Approx(static_cast<double>(value)) {} template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> friend bool operator == ( const T& lhs, Approx const& rhs ) { auto lhs_v = static_cast<double>(lhs); return rhs.equalityComparisonImpl(lhs_v); } template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> friend bool operator == ( Approx const& lhs, const T& rhs ) { return operator==( rhs, lhs ); } template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> friend bool operator != ( T const& lhs, Approx const& rhs ) { return !operator==( lhs, rhs ); } template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> friend bool operator != ( Approx const& lhs, T const& rhs ) { return !operator==( rhs, lhs ); } template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> friend bool operator <= ( T const& lhs, Approx const& rhs ) { return static_cast<double>(lhs) < rhs.m_value || lhs == rhs; } template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> friend bool operator <= ( Approx const& lhs, T const& rhs ) { return lhs.m_value < static_cast<double>(rhs) || lhs == rhs; } template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> friend bool operator >= ( T const& lhs, Approx const& rhs ) { return static_cast<double>(lhs) > rhs.m_value || lhs == rhs; } template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> friend bool operator >= ( Approx const& lhs, T const& rhs ) { return lhs.m_value > static_cast<double>(rhs) || lhs == rhs; } template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> Approx& epsilon( T const& newEpsilon ) { double epsilonAsDouble = static_cast<double>(newEpsilon); setEpsilon(epsilonAsDouble); return *this; } template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> Approx& margin( T const& newMargin ) { double marginAsDouble = static_cast<double>(newMargin); setMargin(marginAsDouble); return *this; } template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> Approx& scale( T const& newScale ) { m_scale = static_cast<double>(newScale); return *this; } std::string toString() const; private: double m_epsilon; double m_margin; double m_scale; double m_value; }; } // end namespace Detail namespace literals { Detail::Approx operator "" _a(long double val); Detail::Approx operator "" _a(unsigned long long val); } // end namespace literals template<> struct StringMaker<Catch::Detail::Approx> { static std::string convert(Catch::Detail::Approx const& value); }; } // end namespace Catch // end catch_approx.h // start catch_string_manip.h #include <string> #include <iosfwd> namespace Catch { bool startsWith( std::string const& s, std::string const& prefix ); bool startsWith( std::string const& s, char prefix ); bool endsWith( std::string const& s, std::string const& suffix ); bool endsWith( std::string const& s, char suffix ); bool contains( std::string const& s, std::string const& infix ); void toLowerInPlace( std::string& s ); std::string toLower( std::string const& s ); std::string trim( std::string const& str ); bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ); struct pluralise { pluralise( std::size_t count, std::string const& label ); friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ); std::size_t m_count; std::string m_label; }; } // end catch_string_manip.h #ifndef CATCH_CONFIG_DISABLE_MATCHERS // start catch_capture_matchers.h // start catch_matchers.h #include <string> #include <vector> namespace Catch { namespace Matchers { namespace Impl { template<typename ArgT> struct MatchAllOf; template<typename ArgT> struct MatchAnyOf; template<typename ArgT> struct MatchNotOf; class MatcherUntypedBase { public: MatcherUntypedBase() = default; MatcherUntypedBase ( MatcherUntypedBase const& ) = default; MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete; std::string toString() const; protected: virtual ~MatcherUntypedBase(); virtual std::string describe() const = 0; mutable std::string m_cachedToString; }; #ifdef __clang__ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wnon-virtual-dtor" #endif template<typename ObjectT> struct MatcherMethod { virtual bool match( ObjectT const& arg ) const = 0; }; #ifdef __clang__ # pragma clang diagnostic pop #endif template<typename T> struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> { MatchAllOf<T> operator && ( MatcherBase const& other ) const; MatchAnyOf<T> operator || ( MatcherBase const& other ) const; MatchNotOf<T> operator ! () const; }; template<typename ArgT> struct MatchAllOf : MatcherBase<ArgT> { bool match( ArgT const& arg ) const override { for( auto matcher : m_matchers ) { if (!matcher->match(arg)) return false; } return true; } std::string describe() const override { std::string description; description.reserve( 4 + m_matchers.size()*32 ); description += "( "; bool first = true; for( auto matcher : m_matchers ) { if( first ) first = false; else description += " and "; description += matcher->toString(); } description += " )"; return description; } MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) { m_matchers.push_back( &other ); return *this; } std::vector<MatcherBase<ArgT> const*> m_matchers; }; template<typename ArgT> struct MatchAnyOf : MatcherBase<ArgT> { bool match( ArgT const& arg ) const override { for( auto matcher : m_matchers ) { if (matcher->match(arg)) return true; } return false; } std::string describe() const override { std::string description; description.reserve( 4 + m_matchers.size()*32 ); description += "( "; bool first = true; for( auto matcher : m_matchers ) { if( first ) first = false; else description += " or "; description += matcher->toString(); } description += " )"; return description; } MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) { m_matchers.push_back( &other ); return *this; } std::vector<MatcherBase<ArgT> const*> m_matchers; }; template<typename ArgT> struct MatchNotOf : MatcherBase<ArgT> { MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {} bool match( ArgT const& arg ) const override { return !m_underlyingMatcher.match( arg ); } std::string describe() const override { return "not " + m_underlyingMatcher.toString(); } MatcherBase<ArgT> const& m_underlyingMatcher; }; template<typename T> MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const { return MatchAllOf<T>() && *this && other; } template<typename T> MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const { return MatchAnyOf<T>() || *this || other; } template<typename T> MatchNotOf<T> MatcherBase<T>::operator ! () const { return MatchNotOf<T>( *this ); } } // namespace Impl } // namespace Matchers using namespace Matchers; using Matchers::Impl::MatcherBase; } // namespace Catch // end catch_matchers.h // start catch_matchers_floating.h #include <type_traits> #include <cmath> namespace Catch { namespace Matchers { namespace Floating { enum class FloatingPointKind : uint8_t; struct WithinAbsMatcher : MatcherBase<double> { WithinAbsMatcher(double target, double margin); bool match(double const& matchee) const override; std::string describe() const override; private: double m_target; double m_margin; }; struct WithinUlpsMatcher : MatcherBase<double> { WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType); bool match(double const& matchee) const override; std::string describe() const override; private: double m_target; int m_ulps; FloatingPointKind m_type; }; } // namespace Floating // The following functions create the actual matcher objects. // This allows the types to be inferred Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff); Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff); Floating::WithinAbsMatcher WithinAbs(double target, double margin); } // namespace Matchers } // namespace Catch // end catch_matchers_floating.h // start catch_matchers_generic.hpp #include <functional> #include <string> namespace Catch { namespace Matchers { namespace Generic { namespace Detail { std::string finalizeDescription(const std::string& desc); } template <typename T> class PredicateMatcher : public MatcherBase<T> { std::function<bool(T const&)> m_predicate; std::string m_description; public: PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr) :m_predicate(std::move(elem)), m_description(Detail::finalizeDescription(descr)) {} bool match( T const& item ) const override { return m_predicate(item); } std::string describe() const override { return m_description; } }; } // namespace Generic // The following functions create the actual matcher objects. // The user has to explicitly specify type to the function, because // infering std::function<bool(T const&)> is hard (but possible) and // requires a lot of TMP. template<typename T> Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") { return Generic::PredicateMatcher<T>(predicate, description); } } // namespace Matchers } // namespace Catch // end catch_matchers_generic.hpp // start catch_matchers_string.h #include <string> namespace Catch { namespace Matchers { namespace StdString { struct CasedString { CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ); std::string adjustString( std::string const& str ) const; std::string caseSensitivitySuffix() const; CaseSensitive::Choice m_caseSensitivity; std::string m_str; }; struct StringMatcherBase : MatcherBase<std::string> { StringMatcherBase( std::string const& operation, CasedString const& comparator ); std::string describe() const override; CasedString m_comparator; std::string m_operation; }; struct EqualsMatcher : StringMatcherBase { EqualsMatcher( CasedString const& comparator ); bool match( std::string const& source ) const override; }; struct ContainsMatcher : StringMatcherBase { ContainsMatcher( CasedString const& comparator ); bool match( std::string const& source ) const override; }; struct StartsWithMatcher : StringMatcherBase { StartsWithMatcher( CasedString const& comparator ); bool match( std::string const& source ) const override; }; struct EndsWithMatcher : StringMatcherBase { EndsWithMatcher( CasedString const& comparator ); bool match( std::string const& source ) const override; }; struct RegexMatcher : MatcherBase<std::string> { RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity ); bool match( std::string const& matchee ) const override; std::string describe() const override; private: std::string m_regex; CaseSensitive::Choice m_caseSensitivity; }; } // namespace StdString // The following functions create the actual matcher objects. // This allows the types to be inferred StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); } // namespace Matchers } // namespace Catch // end catch_matchers_string.h // start catch_matchers_vector.h #include <algorithm> namespace Catch { namespace Matchers { namespace Vector { namespace Detail { template <typename InputIterator, typename T> size_t count(InputIterator first, InputIterator last, T const& item) { size_t cnt = 0; for (; first != last; ++first) { if (*first == item) { ++cnt; } } return cnt; } template <typename InputIterator, typename T> bool contains(InputIterator first, InputIterator last, T const& item) { for (; first != last; ++first) { if (*first == item) { return true; } } return false; } } template<typename T> struct ContainsElementMatcher : MatcherBase<std::vector<T>> { ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {} bool match(std::vector<T> const &v) const override { for (auto const& el : v) { if (el == m_comparator) { return true; } } return false; } std::string describe() const override { return "Contains: " + ::Catch::Detail::stringify( m_comparator ); } T const& m_comparator; }; template<typename T> struct ContainsMatcher : MatcherBase<std::vector<T>> { ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {} bool match(std::vector<T> const &v) const override { // !TBD: see note in EqualsMatcher if (m_comparator.size() > v.size()) return false; for (auto const& comparator : m_comparator) { auto present = false; for (const auto& el : v) { if (el == comparator) { present = true; break; } } if (!present) { return false; } } return true; } std::string describe() const override { return "Contains: " + ::Catch::Detail::stringify( m_comparator ); } std::vector<T> const& m_comparator; }; template<typename T> struct EqualsMatcher : MatcherBase<std::vector<T>> { EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {} bool match(std::vector<T> const &v) const override { // !TBD: This currently works if all elements can be compared using != // - a more general approach would be via a cmp template that defaults // to using !=. but could be specialised for, e.g. std::vector<T> etc // - then just call that directly if (m_comparator.size() != v.size()) return false; for (std::size_t i = 0; i < v.size(); ++i) if (m_comparator[i] != v[i]) return false; return true; } std::string describe() const override { return "Equals: " + ::Catch::Detail::stringify( m_comparator ); } std::vector<T> const& m_comparator; }; template<typename T> struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> { UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {} bool match(std::vector<T> const& vec) const override { // Note: This is a reimplementation of std::is_permutation, // because I don't want to include <algorithm> inside the common path if (m_target.size() != vec.size()) { return false; } auto lfirst = m_target.begin(), llast = m_target.end(); auto rfirst = vec.begin(), rlast = vec.end(); // Cut common prefix to optimize checking of permuted parts while (lfirst != llast && *lfirst == *rfirst) { ++lfirst; ++rfirst; } if (lfirst == llast) { return true; } for (auto mid = lfirst; mid != llast; ++mid) { // Skip already counted items if (Detail::contains(lfirst, mid, *mid)) { continue; } size_t num_vec = Detail::count(rfirst, rlast, *mid); if (num_vec == 0 || Detail::count(lfirst, llast, *mid) != num_vec) { return false; } } return true; } std::string describe() const override { return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target); } private: std::vector<T> const& m_target; }; } // namespace Vector // The following functions create the actual matcher objects. // This allows the types to be inferred template<typename T> Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) { return Vector::ContainsMatcher<T>( comparator ); } template<typename T> Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) { return Vector::ContainsElementMatcher<T>( comparator ); } template<typename T> Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) { return Vector::EqualsMatcher<T>( comparator ); } template<typename T> Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) { return Vector::UnorderedEqualsMatcher<T>(target); } } // namespace Matchers } // namespace Catch // end catch_matchers_vector.h namespace Catch { template<typename ArgT, typename MatcherT> class MatchExpr : public ITransientExpression { ArgT const& m_arg; MatcherT m_matcher; StringRef m_matcherString; public: MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) : ITransientExpression{ true, matcher.match( arg ) }, m_arg( arg ), m_matcher( matcher ), m_matcherString( matcherString ) {} void streamReconstructedExpression( std::ostream &os ) const override { auto matcherAsString = m_matcher.toString(); os << Catch::Detail::stringify( m_arg ) << ' '; if( matcherAsString == Detail::unprintableString ) os << m_matcherString; else os << matcherAsString; } }; using StringMatcher = Matchers::Impl::MatcherBase<std::string>; void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ); template<typename ArgT, typename MatcherT> auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> { return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString ); } } // namespace Catch /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \ do { \ Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ INTERNAL_CATCH_TRY { \ catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \ } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while( false ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \ do { \ Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ if( catchAssertionHandler.allowThrows() ) \ try { \ static_cast<void>(__VA_ARGS__ ); \ catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ } \ catch( exceptionType const& ex ) { \ catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \ } \ catch( ... ) { \ catchAssertionHandler.handleUnexpectedInflightException(); \ } \ else \ catchAssertionHandler.handleThrowingCallSkipped(); \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while( false ) // end catch_capture_matchers.h #endif // start catch_generators.hpp // start catch_interfaces_generatortracker.h #include <memory> namespace Catch { namespace Generators { class GeneratorUntypedBase { public: GeneratorUntypedBase() = default; virtual ~GeneratorUntypedBase(); // Attempts to move the generator to the next element // // Returns true iff the move succeeded (and a valid element // can be retrieved). virtual bool next() = 0; }; using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>; } // namespace Generators struct IGeneratorTracker { virtual ~IGeneratorTracker(); virtual auto hasGenerator() const -> bool = 0; virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0; virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0; }; } // namespace Catch // end catch_interfaces_generatortracker.h // start catch_enforce.h #include <stdexcept> namespace Catch { #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) template <typename Ex> [[noreturn]] void throw_exception(Ex const& e) { throw e; } #else // ^^ Exceptions are enabled // Exceptions are disabled vv [[noreturn]] void throw_exception(std::exception const& e); #endif } // namespace Catch; #define CATCH_PREPARE_EXCEPTION( type, msg ) \ type( ( Catch::ReusableStringStream() << msg ).str() ) #define CATCH_INTERNAL_ERROR( msg ) \ Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg)) #define CATCH_ERROR( msg ) \ Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::domain_error, msg )) #define CATCH_RUNTIME_ERROR( msg ) \ Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::runtime_error, msg )) #define CATCH_ENFORCE( condition, msg ) \ do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false) // end catch_enforce.h #include <memory> #include <vector> #include <cassert> #include <utility> #include <exception> namespace Catch { class GeneratorException : public std::exception { const char* const m_msg = ""; public: GeneratorException(const char* msg): m_msg(msg) {} const char* what() const noexcept override final; }; namespace Generators { // !TBD move this into its own location? namespace pf{ template<typename T, typename... Args> std::unique_ptr<T> make_unique( Args&&... args ) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } } template<typename T> struct IGenerator : GeneratorUntypedBase { virtual ~IGenerator() = default; // Returns the current element of the generator // // \Precondition The generator is either freshly constructed, // or the last call to `next()` returned true virtual T const& get() const = 0; using type = T; }; template<typename T> class SingleValueGenerator final : public IGenerator<T> { T m_value; public: SingleValueGenerator(T const& value) : m_value( value ) {} SingleValueGenerator(T&& value) : m_value(std::move(value)) {} T const& get() const override { return m_value; } bool next() override { return false; } }; template<typename T> class FixedValuesGenerator final : public IGenerator<T> { std::vector<T> m_values; size_t m_idx = 0; public: FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {} T const& get() const override { return m_values[m_idx]; } bool next() override { ++m_idx; return m_idx < m_values.size(); } }; template <typename T> class GeneratorWrapper final { std::unique_ptr<IGenerator<T>> m_generator; public: GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator): m_generator(std::move(generator)) {} T const& get() const { return m_generator->get(); } bool next() { return m_generator->next(); } }; template <typename T> GeneratorWrapper<T> value(T&& value) { return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value))); } template <typename T> GeneratorWrapper<T> values(std::initializer_list<T> values) { return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values)); } template<typename T> class Generators : public IGenerator<T> { std::vector<GeneratorWrapper<T>> m_generators; size_t m_current = 0; void populate(GeneratorWrapper<T>&& generator) { m_generators.emplace_back(std::move(generator)); } void populate(T&& val) { m_generators.emplace_back(value(std::move(val))); } template<typename U> void populate(U&& val) { populate(T(std::move(val))); } template<typename U, typename... Gs> void populate(U&& valueOrGenerator, Gs... moreGenerators) { populate(std::forward<U>(valueOrGenerator)); populate(std::forward<Gs>(moreGenerators)...); } public: template <typename... Gs> Generators(Gs... moreGenerators) { m_generators.reserve(sizeof...(Gs)); populate(std::forward<Gs>(moreGenerators)...); } T const& get() const override { return m_generators[m_current].get(); } bool next() override { if (m_current >= m_generators.size()) { return false; } const bool current_status = m_generators[m_current].next(); if (!current_status) { ++m_current; } return m_current < m_generators.size(); } }; template<typename... Ts> GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) { return values<std::tuple<Ts...>>( tuples ); } // Tag type to signal that a generator sequence should convert arguments to a specific type template <typename T> struct as {}; template<typename T, typename... Gs> auto makeGenerators( GeneratorWrapper<T>&& generator, Gs... moreGenerators ) -> Generators<T> { return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...); } template<typename T> auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> { return Generators<T>(std::move(generator)); } template<typename T, typename... Gs> auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> { return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... ); } template<typename T, typename U, typename... Gs> auto makeGenerators( as<T>, U&& val, Gs... moreGenerators ) -> Generators<T> { return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... ); } template <typename T> class TakeGenerator : public IGenerator<T> { GeneratorWrapper<T> m_generator; size_t m_returned = 0; size_t m_target; public: TakeGenerator(size_t target, GeneratorWrapper<T>&& generator): m_generator(std::move(generator)), m_target(target) { assert(target != 0 && "Empty generators are not allowed"); } T const& get() const override { return m_generator.get(); } bool next() override { ++m_returned; if (m_returned >= m_target) { return false; } const auto success = m_generator.next(); // If the underlying generator does not contain enough values // then we cut short as well if (!success) { m_returned = m_target; } return success; } }; template <typename T> GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) { return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator))); } template <typename T, typename Predicate> class FilterGenerator : public IGenerator<T> { GeneratorWrapper<T> m_generator; Predicate m_predicate; public: template <typename P = Predicate> FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator): m_generator(std::move(generator)), m_predicate(std::forward<P>(pred)) { if (!m_predicate(m_generator.get())) { // It might happen that there are no values that pass the // filter. In that case we throw an exception. auto has_initial_value = next(); if (!has_initial_value) { Catch::throw_exception(GeneratorException("No valid value found in filtered generator")); } } } T const& get() const override { return m_generator.get(); } bool next() override { bool success = m_generator.next(); if (!success) { return false; } while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true); return success; } }; template <typename T, typename Predicate> GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) { return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator)))); } template <typename T> class RepeatGenerator : public IGenerator<T> { GeneratorWrapper<T> m_generator; mutable std::vector<T> m_returned; size_t m_target_repeats; size_t m_current_repeat = 0; size_t m_repeat_index = 0; public: RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator): m_generator(std::move(generator)), m_target_repeats(repeats) { assert(m_target_repeats > 0 && "Repeat generator must repeat at least once"); } T const& get() const override { if (m_current_repeat == 0) { m_returned.push_back(m_generator.get()); return m_returned.back(); } return m_returned[m_repeat_index]; } bool next() override { // There are 2 basic cases: // 1) We are still reading the generator // 2) We are reading our own cache // In the first case, we need to poke the underlying generator. // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache if (m_current_repeat == 0) { const auto success = m_generator.next(); if (!success) { ++m_current_repeat; } return m_current_repeat < m_target_repeats; } // In the second case, we need to move indices forward and check that we haven't run up against the end ++m_repeat_index; if (m_repeat_index == m_returned.size()) { m_repeat_index = 0; ++m_current_repeat; } return m_current_repeat < m_target_repeats; } }; template <typename T> GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) { return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator))); } template <typename T, typename U, typename Func> class MapGenerator : public IGenerator<T> { // TBD: provide static assert for mapping function, for friendly error message GeneratorWrapper<U> m_generator; Func m_function; // To avoid returning dangling reference, we have to save the values T m_cache; public: template <typename F2 = Func> MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) : m_generator(std::move(generator)), m_function(std::forward<F2>(function)), m_cache(m_function(m_generator.get())) {} T const& get() const override { return m_cache; } bool next() override { const auto success = m_generator.next(); if (success) { m_cache = m_function(m_generator.get()); } return success; } }; template <typename T, typename U, typename Func> GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) { return GeneratorWrapper<T>( pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator)) ); } template <typename T, typename Func> GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<T>&& generator) { return GeneratorWrapper<T>( pf::make_unique<MapGenerator<T, T, Func>>(std::forward<Func>(function), std::move(generator)) ); } auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&; template<typename L> // Note: The type after -> is weird, because VS2015 cannot parse // the expression used in the typedef inside, when it is in // return type. Yeah, ¯\_(ツ)_/¯ auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) { using UnderlyingType = typename decltype(generatorExpression())::type; IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo ); if (!tracker.hasGenerator()) { tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression())); } auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() ); return generator.get(); } } // namespace Generators } // namespace Catch #define GENERATE( ... ) \ Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, []{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) // end catch_generators.hpp // These files are included here so the single_include script doesn't put them // in the conditionally compiled sections // start catch_test_case_info.h #include <string> #include <vector> #include <memory> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif namespace Catch { struct ITestInvoker; struct TestCaseInfo { enum SpecialProperties{ None = 0, IsHidden = 1 << 1, ShouldFail = 1 << 2, MayFail = 1 << 3, Throws = 1 << 4, NonPortable = 1 << 5, Benchmark = 1 << 6 }; TestCaseInfo( std::string const& _name, std::string const& _className, std::string const& _description, std::vector<std::string> const& _tags, SourceLineInfo const& _lineInfo ); friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ); bool isHidden() const; bool throws() const; bool okToFail() const; bool expectedToFail() const; std::string tagsAsString() const; std::string name; std::string className; std::string description; std::vector<std::string> tags; std::vector<std::string> lcaseTags; SourceLineInfo lineInfo; SpecialProperties properties; }; class TestCase : public TestCaseInfo { public: TestCase( ITestInvoker* testCase, TestCaseInfo&& info ); TestCase withName( std::string const& _newName ) const; void invoke() const; TestCaseInfo const& getTestCaseInfo() const; bool operator == ( TestCase const& other ) const; bool operator < ( TestCase const& other ) const; private: std::shared_ptr<ITestInvoker> test; }; TestCase makeTestCase( ITestInvoker* testCase, std::string const& className, NameAndTags const& nameAndTags, SourceLineInfo const& lineInfo ); } #ifdef __clang__ #pragma clang diagnostic pop #endif // end catch_test_case_info.h // start catch_interfaces_runner.h namespace Catch { struct IRunner { virtual ~IRunner(); virtual bool aborting() const = 0; }; } // end catch_interfaces_runner.h #ifdef __OBJC__ // start catch_objc.hpp #import <objc/runtime.h> #include <string> // NB. Any general catch headers included here must be included // in catch.hpp first to make sure they are included by the single // header for non obj-usage /////////////////////////////////////////////////////////////////////////////// // This protocol is really only here for (self) documenting purposes, since // all its methods are optional. @protocol OcFixture @optional -(void) setUp; -(void) tearDown; @end namespace Catch { class OcMethod : public ITestInvoker { public: OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {} virtual void invoke() const { id obj = [[m_cls alloc] init]; performOptionalSelector( obj, @selector(setUp) ); performOptionalSelector( obj, m_sel ); performOptionalSelector( obj, @selector(tearDown) ); arcSafeRelease( obj ); } private: virtual ~OcMethod() {} Class m_cls; SEL m_sel; }; namespace Detail{ inline std::string getAnnotation( Class cls, std::string const& annotationName, std::string const& testCaseName ) { NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()]; SEL sel = NSSelectorFromString( selStr ); arcSafeRelease( selStr ); id value = performOptionalSelector( cls, sel ); if( value ) return [(NSString*)value UTF8String]; return ""; } } inline std::size_t registerTestMethods() { std::size_t noTestMethods = 0; int noClasses = objc_getClassList( nullptr, 0 ); Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses); objc_getClassList( classes, noClasses ); for( int c = 0; c < noClasses; c++ ) { Class cls = classes[c]; { u_int count; Method* methods = class_copyMethodList( cls, &count ); for( u_int m = 0; m < count ; m++ ) { SEL selector = method_getName(methods[m]); std::string methodName = sel_getName(selector); if( startsWith( methodName, "Catch_TestCase_" ) ) { std::string testCaseName = methodName.substr( 15 ); std::string name = Detail::getAnnotation( cls, "Name", testCaseName ); std::string desc = Detail::getAnnotation( cls, "Description", testCaseName ); const char* className = class_getName( cls ); getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) ); noTestMethods++; } } free(methods); } } return noTestMethods; } #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) namespace Matchers { namespace Impl { namespace NSStringMatchers { struct StringHolder : MatcherBase<NSString*>{ StringHolder( NSString* substr ) : m_substr( [substr copy] ){} StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){} StringHolder() { arcSafeRelease( m_substr ); } bool match( NSString* arg ) const override { return false; } NSString* CATCH_ARC_STRONG m_substr; }; struct Equals : StringHolder { Equals( NSString* substr ) : StringHolder( substr ){} bool match( NSString* str ) const override { return (str != nil || m_substr == nil ) && [str isEqualToString:m_substr]; } std::string describe() const override { return "equals string: " + Catch::Detail::stringify( m_substr ); } }; struct Contains : StringHolder { Contains( NSString* substr ) : StringHolder( substr ){} bool match( NSString* str ) const { return (str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location != NSNotFound; } std::string describe() const override { return "contains string: " + Catch::Detail::stringify( m_substr ); } }; struct StartsWith : StringHolder { StartsWith( NSString* substr ) : StringHolder( substr ){} bool match( NSString* str ) const override { return (str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location == 0; } std::string describe() const override { return "starts with: " + Catch::Detail::stringify( m_substr ); } }; struct EndsWith : StringHolder { EndsWith( NSString* substr ) : StringHolder( substr ){} bool match( NSString* str ) const override { return (str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location == [str length] - [m_substr length]; } std::string describe() const override { return "ends with: " + Catch::Detail::stringify( m_substr ); } }; } // namespace NSStringMatchers } // namespace Impl inline Impl::NSStringMatchers::Equals Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); } inline Impl::NSStringMatchers::Contains Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); } inline Impl::NSStringMatchers::StartsWith StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); } inline Impl::NSStringMatchers::EndsWith EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); } } // namespace Matchers using namespace Matchers; #endif // CATCH_CONFIG_DISABLE_MATCHERS } // namespace Catch /////////////////////////////////////////////////////////////////////////////// #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \ +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \ { \ return @ name; \ } \ +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \ { \ return @ desc; \ } \ -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix ) #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ ) // end catch_objc.hpp #endif #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES // start catch_external_interfaces.h // start catch_reporter_bases.hpp // start catch_interfaces_reporter.h // start catch_config.hpp // start catch_test_spec_parser.h #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif // start catch_test_spec.h #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif // start catch_wildcard_pattern.h namespace Catch { class WildcardPattern { enum WildcardPosition { NoWildcard = 0, WildcardAtStart = 1, WildcardAtEnd = 2, WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd }; public: WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity ); virtual ~WildcardPattern() = default; virtual bool matches( std::string const& str ) const; private: std::string adjustCase( std::string const& str ) const; CaseSensitive::Choice m_caseSensitivity; WildcardPosition m_wildcard = NoWildcard; std::string m_pattern; }; } // end catch_wildcard_pattern.h #include <string> #include <vector> #include <memory> namespace Catch { class TestSpec { struct Pattern { virtual ~Pattern(); virtual bool matches( TestCaseInfo const& testCase ) const = 0; }; using PatternPtr = std::shared_ptr<Pattern>; class NamePattern : public Pattern { public: NamePattern( std::string const& name ); virtual ~NamePattern(); virtual bool matches( TestCaseInfo const& testCase ) const override; private: WildcardPattern m_wildcardPattern; }; class TagPattern : public Pattern { public: TagPattern( std::string const& tag ); virtual ~TagPattern(); virtual bool matches( TestCaseInfo const& testCase ) const override; private: std::string m_tag; }; class ExcludedPattern : public Pattern { public: ExcludedPattern( PatternPtr const& underlyingPattern ); virtual ~ExcludedPattern(); virtual bool matches( TestCaseInfo const& testCase ) const override; private: PatternPtr m_underlyingPattern; }; struct Filter { std::vector<PatternPtr> m_patterns; bool matches( TestCaseInfo const& testCase ) const; }; public: bool hasFilters() const; bool matches( TestCaseInfo const& testCase ) const; private: std::vector<Filter> m_filters; friend class TestSpecParser; }; } #ifdef __clang__ #pragma clang diagnostic pop #endif // end catch_test_spec.h // start catch_interfaces_tag_alias_registry.h #include <string> namespace Catch { struct TagAlias; struct ITagAliasRegistry { virtual ~ITagAliasRegistry(); // Nullptr if not present virtual TagAlias const* find( std::string const& alias ) const = 0; virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0; static ITagAliasRegistry const& get(); }; } // end namespace Catch // end catch_interfaces_tag_alias_registry.h namespace Catch { class TestSpecParser { enum Mode{ None, Name, QuotedName, Tag, EscapedName }; Mode m_mode = None; bool m_exclusion = false; std::size_t m_start = std::string::npos, m_pos = 0; std::string m_arg; std::vector<std::size_t> m_escapeChars; TestSpec::Filter m_currentFilter; TestSpec m_testSpec; ITagAliasRegistry const* m_tagAliases = nullptr; public: TestSpecParser( ITagAliasRegistry const& tagAliases ); TestSpecParser& parse( std::string const& arg ); TestSpec testSpec(); private: void visitChar( char c ); void startNewMode( Mode mode, std::size_t start ); void escape(); std::string subString() const; template<typename T> void addPattern() { std::string token = subString(); for( std::size_t i = 0; i < m_escapeChars.size(); ++i ) token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 ); m_escapeChars.clear(); if( startsWith( token, "exclude:" ) ) { m_exclusion = true; token = token.substr( 8 ); } if( !token.empty() ) { TestSpec::PatternPtr pattern = std::make_shared<T>( token ); if( m_exclusion ) pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern ); m_currentFilter.m_patterns.push_back( pattern ); } m_exclusion = false; m_mode = None; } void addFilter(); }; TestSpec parseTestSpec( std::string const& arg ); } // namespace Catch #ifdef __clang__ #pragma clang diagnostic pop #endif // end catch_test_spec_parser.h // start catch_interfaces_config.h #include <iosfwd> #include <string> #include <vector> #include <memory> namespace Catch { enum class Verbosity { Quiet = 0, Normal, High }; struct WarnAbout { enum What { Nothing = 0x00, NoAssertions = 0x01, NoTests = 0x02 }; }; struct ShowDurations { enum OrNot { DefaultForReporter, Always, Never }; }; struct RunTests { enum InWhatOrder { InDeclarationOrder, InLexicographicalOrder, InRandomOrder }; }; struct UseColour { enum YesOrNo { Auto, Yes, No }; }; struct WaitForKeypress { enum When { Never, BeforeStart = 1, BeforeExit = 2, BeforeStartAndExit = BeforeStart | BeforeExit }; }; class TestSpec; struct IConfig : NonCopyable { virtual ~IConfig(); virtual bool allowThrows() const = 0; virtual std::ostream& stream() const = 0; virtual std::string name() const = 0; virtual bool includeSuccessfulResults() const = 0; virtual bool shouldDebugBreak() const = 0; virtual bool warnAboutMissingAssertions() const = 0; virtual bool warnAboutNoTests() const = 0; virtual int abortAfter() const = 0; virtual bool showInvisibles() const = 0; virtual ShowDurations::OrNot showDurations() const = 0; virtual TestSpec const& testSpec() const = 0; virtual bool hasTestFilters() const = 0; virtual RunTests::InWhatOrder runOrder() const = 0; virtual unsigned int rngSeed() const = 0; virtual int benchmarkResolutionMultiple() const = 0; virtual UseColour::YesOrNo useColour() const = 0; virtual std::vector<std::string> const& getSectionsToRun() const = 0; virtual Verbosity verbosity() const = 0; }; using IConfigPtr = std::shared_ptr<IConfig const>; } // end catch_interfaces_config.h // Libstdc++ doesn't like incomplete classes for unique_ptr #include <memory> #include <vector> #include <string> #ifndef CATCH_CONFIG_CONSOLE_WIDTH #define CATCH_CONFIG_CONSOLE_WIDTH 80 #endif namespace Catch { struct IStream; struct ConfigData { bool listTests = false; bool listTags = false; bool listReporters = false; bool listTestNamesOnly = false; bool showSuccessfulTests = false; bool shouldDebugBreak = false; bool noThrow = false; bool showHelp = false; bool showInvisibles = false; bool filenamesAsTags = false; bool libIdentify = false; int abortAfter = -1; unsigned int rngSeed = 0; int benchmarkResolutionMultiple = 100; Verbosity verbosity = Verbosity::Normal; WarnAbout::What warnings = WarnAbout::Nothing; ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter; RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder; UseColour::YesOrNo useColour = UseColour::Auto; WaitForKeypress::When waitForKeypress = WaitForKeypress::Never; std::string outputFilename; std::string name; std::string processName; #ifndef CATCH_CONFIG_DEFAULT_REPORTER #define CATCH_CONFIG_DEFAULT_REPORTER "console" #endif std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER; #undef CATCH_CONFIG_DEFAULT_REPORTER std::vector<std::string> testsOrTags; std::vector<std::string> sectionsToRun; }; class Config : public IConfig { public: Config() = default; Config( ConfigData const& data ); virtual ~Config() = default; std::string const& getFilename() const; bool listTests() const; bool listTestNamesOnly() const; bool listTags() const; bool listReporters() const; std::string getProcessName() const; std::string const& getReporterName() const; std::vector<std::string> const& getTestsOrTags() const; std::vector<std::string> const& getSectionsToRun() const override; virtual TestSpec const& testSpec() const override; bool hasTestFilters() const override; bool showHelp() const; // IConfig interface bool allowThrows() const override; std::ostream& stream() const override; std::string name() const override; bool includeSuccessfulResults() const override; bool warnAboutMissingAssertions() const override; bool warnAboutNoTests() const override; ShowDurations::OrNot showDurations() const override; RunTests::InWhatOrder runOrder() const override; unsigned int rngSeed() const override; int benchmarkResolutionMultiple() const override; UseColour::YesOrNo useColour() const override; bool shouldDebugBreak() const override; int abortAfter() const override; bool showInvisibles() const override; Verbosity verbosity() const override; private: IStream const* openStream(); ConfigData m_data; std::unique_ptr<IStream const> m_stream; TestSpec m_testSpec; bool m_hasTestFilters = false; }; } // end namespace Catch // end catch_config.hpp // start catch_assertionresult.h #include <string> namespace Catch { struct AssertionResultData { AssertionResultData() = delete; AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression ); std::string message; mutable std::string reconstructedExpression; LazyExpression lazyExpression; ResultWas::OfType resultType; std::string reconstructExpression() const; }; class AssertionResult { public: AssertionResult() = delete; AssertionResult( AssertionInfo const& info, AssertionResultData const& data ); bool isOk() const; bool succeeded() const; ResultWas::OfType getResultType() const; bool hasExpression() const; bool hasMessage() const; std::string getExpression() const; std::string getExpressionInMacro() const; bool hasExpandedExpression() const; std::string getExpandedExpression() const; std::string getMessage() const; SourceLineInfo getSourceInfo() const; StringRef getTestMacroName() const; //protected: AssertionInfo m_info; AssertionResultData m_resultData; }; } // end namespace Catch // end catch_assertionresult.h // start catch_option.hpp namespace Catch { // An optional type template<typename T> class Option { public: Option() : nullableValue( nullptr ) {} Option( T const& _value ) : nullableValue( new( storage ) T( _value ) ) {} Option( Option const& _other ) : nullableValue( _other ? new( storage ) T( *_other ) : nullptr ) {} ~Option() { reset(); } Option& operator= ( Option const& _other ) { if( &_other != this ) { reset(); if( _other ) nullableValue = new( storage ) T( *_other ); } return *this; } Option& operator = ( T const& _value ) { reset(); nullableValue = new( storage ) T( _value ); return *this; } void reset() { if( nullableValue ) nullableValue->~T(); nullableValue = nullptr; } T& operator*() { return *nullableValue; } T const& operator*() const { return *nullableValue; } T* operator->() { return nullableValue; } const T* operator->() const { return nullableValue; } T valueOr( T const& defaultValue ) const { return nullableValue ? *nullableValue : defaultValue; } bool some() const { return nullableValue != nullptr; } bool none() const { return nullableValue == nullptr; } bool operator !() const { return nullableValue == nullptr; } explicit operator bool() const { return some(); } private: T *nullableValue; alignas(alignof(T)) char storage[sizeof(T)]; }; } // end namespace Catch // end catch_option.hpp #include <string> #include <iosfwd> #include <map> #include <set> #include <memory> namespace Catch { struct ReporterConfig { explicit ReporterConfig( IConfigPtr const& _fullConfig ); ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream ); std::ostream& stream() const; IConfigPtr fullConfig() const; private: std::ostream* m_stream; IConfigPtr m_fullConfig; }; struct ReporterPreferences { bool shouldRedirectStdOut = false; bool shouldReportAllAssertions = false; }; template<typename T> struct LazyStat : Option<T> { LazyStat& operator=( T const& _value ) { Option<T>::operator=( _value ); used = false; return *this; } void reset() { Option<T>::reset(); used = false; } bool used = false; }; struct TestRunInfo { TestRunInfo( std::string const& _name ); std::string name; }; struct GroupInfo { GroupInfo( std::string const& _name, std::size_t _groupIndex, std::size_t _groupsCount ); std::string name; std::size_t groupIndex; std::size_t groupsCounts; }; struct AssertionStats { AssertionStats( AssertionResult const& _assertionResult, std::vector<MessageInfo> const& _infoMessages, Totals const& _totals ); AssertionStats( AssertionStats const& ) = default; AssertionStats( AssertionStats && ) = default; AssertionStats& operator = ( AssertionStats const& ) = default; AssertionStats& operator = ( AssertionStats && ) = default; virtual ~AssertionStats(); AssertionResult assertionResult; std::vector<MessageInfo> infoMessages; Totals totals; }; struct SectionStats { SectionStats( SectionInfo const& _sectionInfo, Counts const& _assertions, double _durationInSeconds, bool _missingAssertions ); SectionStats( SectionStats const& ) = default; SectionStats( SectionStats && ) = default; SectionStats& operator = ( SectionStats const& ) = default; SectionStats& operator = ( SectionStats && ) = default; virtual ~SectionStats(); SectionInfo sectionInfo; Counts assertions; double durationInSeconds; bool missingAssertions; }; struct TestCaseStats { TestCaseStats( TestCaseInfo const& _testInfo, Totals const& _totals, std::string const& _stdOut, std::string const& _stdErr, bool _aborting ); TestCaseStats( TestCaseStats const& ) = default; TestCaseStats( TestCaseStats && ) = default; TestCaseStats& operator = ( TestCaseStats const& ) = default; TestCaseStats& operator = ( TestCaseStats && ) = default; virtual ~TestCaseStats(); TestCaseInfo testInfo; Totals totals; std::string stdOut; std::string stdErr; bool aborting; }; struct TestGroupStats { TestGroupStats( GroupInfo const& _groupInfo, Totals const& _totals, bool _aborting ); TestGroupStats( GroupInfo const& _groupInfo ); TestGroupStats( TestGroupStats const& ) = default; TestGroupStats( TestGroupStats && ) = default; TestGroupStats& operator = ( TestGroupStats const& ) = default; TestGroupStats& operator = ( TestGroupStats && ) = default; virtual ~TestGroupStats(); GroupInfo groupInfo; Totals totals; bool aborting; }; struct TestRunStats { TestRunStats( TestRunInfo const& _runInfo, Totals const& _totals, bool _aborting ); TestRunStats( TestRunStats const& ) = default; TestRunStats( TestRunStats && ) = default; TestRunStats& operator = ( TestRunStats const& ) = default; TestRunStats& operator = ( TestRunStats && ) = default; virtual ~TestRunStats(); TestRunInfo runInfo; Totals totals; bool aborting; }; struct BenchmarkInfo { std::string name; }; struct BenchmarkStats { BenchmarkInfo info; std::size_t iterations; uint64_t elapsedTimeInNanoseconds; }; struct IStreamingReporter { virtual ~IStreamingReporter() = default; // Implementing class must also provide the following static methods: // static std::string getDescription(); // static std::set<Verbosity> getSupportedVerbosities() virtual ReporterPreferences getPreferences() const = 0; virtual void noMatchingTestCases( std::string const& spec ) = 0; virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0; virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0; virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0; virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0; // *** experimental *** virtual void benchmarkStarting( BenchmarkInfo const& ) {} virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0; // The return value indicates if the messages buffer should be cleared: virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0; // *** experimental *** virtual void benchmarkEnded( BenchmarkStats const& ) {} virtual void sectionEnded( SectionStats const& sectionStats ) = 0; virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0; virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0; virtual void testRunEnded( TestRunStats const& testRunStats ) = 0; virtual void skipTest( TestCaseInfo const& testInfo ) = 0; // Default empty implementation provided virtual void fatalErrorEncountered( StringRef name ); virtual bool isMulti() const; }; using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>; struct IReporterFactory { virtual ~IReporterFactory(); virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0; virtual std::string getDescription() const = 0; }; using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>; struct IReporterRegistry { using FactoryMap = std::map<std::string, IReporterFactoryPtr>; using Listeners = std::vector<IReporterFactoryPtr>; virtual ~IReporterRegistry(); virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0; virtual FactoryMap const& getFactories() const = 0; virtual Listeners const& getListeners() const = 0; }; } // end namespace Catch // end catch_interfaces_reporter.h #include <algorithm> #include <cstring> #include <cfloat> #include <cstdio> #include <cassert> #include <memory> #include <ostream> namespace Catch { void prepareExpandedExpression(AssertionResult& result); // Returns double formatted as %.3f (format expected on output) std::string getFormattedDuration( double duration ); template<typename DerivedT> struct StreamingReporterBase : IStreamingReporter { StreamingReporterBase( ReporterConfig const& _config ) : m_config( _config.fullConfig() ), stream( _config.stream() ) { m_reporterPrefs.shouldRedirectStdOut = false; if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) ) CATCH_ERROR( "Verbosity level not supported by this reporter" ); } ReporterPreferences getPreferences() const override { return m_reporterPrefs; } static std::set<Verbosity> getSupportedVerbosities() { return { Verbosity::Normal }; } ~StreamingReporterBase() override = default; void noMatchingTestCases(std::string const&) override {} void testRunStarting(TestRunInfo const& _testRunInfo) override { currentTestRunInfo = _testRunInfo; } void testGroupStarting(GroupInfo const& _groupInfo) override { currentGroupInfo = _groupInfo; } void testCaseStarting(TestCaseInfo const& _testInfo) override { currentTestCaseInfo = _testInfo; } void sectionStarting(SectionInfo const& _sectionInfo) override { m_sectionStack.push_back(_sectionInfo); } void sectionEnded(SectionStats const& /* _sectionStats */) override { m_sectionStack.pop_back(); } void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override { currentTestCaseInfo.reset(); } void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override { currentGroupInfo.reset(); } void testRunEnded(TestRunStats const& /* _testRunStats */) override { currentTestCaseInfo.reset(); currentGroupInfo.reset(); currentTestRunInfo.reset(); } void skipTest(TestCaseInfo const&) override { // Don't do anything with this by default. // It can optionally be overridden in the derived class. } IConfigPtr m_config; std::ostream& stream; LazyStat<TestRunInfo> currentTestRunInfo; LazyStat<GroupInfo> currentGroupInfo; LazyStat<TestCaseInfo> currentTestCaseInfo; std::vector<SectionInfo> m_sectionStack; ReporterPreferences m_reporterPrefs; }; template<typename DerivedT> struct CumulativeReporterBase : IStreamingReporter { template<typename T, typename ChildNodeT> struct Node { explicit Node( T const& _value ) : value( _value ) {} virtual ~Node() {} using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>; T value; ChildNodes children; }; struct SectionNode { explicit SectionNode(SectionStats const& _stats) : stats(_stats) {} virtual ~SectionNode() = default; bool operator == (SectionNode const& other) const { return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo; } bool operator == (std::shared_ptr<SectionNode> const& other) const { return operator==(*other); } SectionStats stats; using ChildSections = std::vector<std::shared_ptr<SectionNode>>; using Assertions = std::vector<AssertionStats>; ChildSections childSections; Assertions assertions; std::string stdOut; std::string stdErr; }; struct BySectionInfo { BySectionInfo( SectionInfo const& other ) : m_other( other ) {} BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {} bool operator() (std::shared_ptr<SectionNode> const& node) const { return ((node->stats.sectionInfo.name == m_other.name) && (node->stats.sectionInfo.lineInfo == m_other.lineInfo)); } void operator=(BySectionInfo const&) = delete; private: SectionInfo const& m_other; }; using TestCaseNode = Node<TestCaseStats, SectionNode>; using TestGroupNode = Node<TestGroupStats, TestCaseNode>; using TestRunNode = Node<TestRunStats, TestGroupNode>; CumulativeReporterBase( ReporterConfig const& _config ) : m_config( _config.fullConfig() ), stream( _config.stream() ) { m_reporterPrefs.shouldRedirectStdOut = false; if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) ) CATCH_ERROR( "Verbosity level not supported by this reporter" ); } ~CumulativeReporterBase() override = default; ReporterPreferences getPreferences() const override { return m_reporterPrefs; } static std::set<Verbosity> getSupportedVerbosities() { return { Verbosity::Normal }; } void testRunStarting( TestRunInfo const& ) override {} void testGroupStarting( GroupInfo const& ) override {} void testCaseStarting( TestCaseInfo const& ) override {} void sectionStarting( SectionInfo const& sectionInfo ) override { SectionStats incompleteStats( sectionInfo, Counts(), 0, false ); std::shared_ptr<SectionNode> node; if( m_sectionStack.empty() ) { if( !m_rootSection ) m_rootSection = std::make_shared<SectionNode>( incompleteStats ); node = m_rootSection; } else { SectionNode& parentNode = *m_sectionStack.back(); auto it = std::find_if( parentNode.childSections.begin(), parentNode.childSections.end(), BySectionInfo( sectionInfo ) ); if( it == parentNode.childSections.end() ) { node = std::make_shared<SectionNode>( incompleteStats ); parentNode.childSections.push_back( node ); } else node = *it; } m_sectionStack.push_back( node ); m_deepestSection = std::move(node); } void assertionStarting(AssertionInfo const&) override {} bool assertionEnded(AssertionStats const& assertionStats) override { assert(!m_sectionStack.empty()); // AssertionResult holds a pointer to a temporary DecomposedExpression, // which getExpandedExpression() calls to build the expression string. // Our section stack copy of the assertionResult will likely outlive the // temporary, so it must be expanded or discarded now to avoid calling // a destroyed object later. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) ); SectionNode& sectionNode = *m_sectionStack.back(); sectionNode.assertions.push_back(assertionStats); return true; } void sectionEnded(SectionStats const& sectionStats) override { assert(!m_sectionStack.empty()); SectionNode& node = *m_sectionStack.back(); node.stats = sectionStats; m_sectionStack.pop_back(); } void testCaseEnded(TestCaseStats const& testCaseStats) override { auto node = std::make_shared<TestCaseNode>(testCaseStats); assert(m_sectionStack.size() == 0); node->children.push_back(m_rootSection); m_testCases.push_back(node); m_rootSection.reset(); assert(m_deepestSection); m_deepestSection->stdOut = testCaseStats.stdOut; m_deepestSection->stdErr = testCaseStats.stdErr; } void testGroupEnded(TestGroupStats const& testGroupStats) override { auto node = std::make_shared<TestGroupNode>(testGroupStats); node->children.swap(m_testCases); m_testGroups.push_back(node); } void testRunEnded(TestRunStats const& testRunStats) override { auto node = std::make_shared<TestRunNode>(testRunStats); node->children.swap(m_testGroups); m_testRuns.push_back(node); testRunEndedCumulative(); } virtual void testRunEndedCumulative() = 0; void skipTest(TestCaseInfo const&) override {} IConfigPtr m_config; std::ostream& stream; std::vector<AssertionStats> m_assertions; std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections; std::vector<std::shared_ptr<TestCaseNode>> m_testCases; std::vector<std::shared_ptr<TestGroupNode>> m_testGroups; std::vector<std::shared_ptr<TestRunNode>> m_testRuns; std::shared_ptr<SectionNode> m_rootSection; std::shared_ptr<SectionNode> m_deepestSection; std::vector<std::shared_ptr<SectionNode>> m_sectionStack; ReporterPreferences m_reporterPrefs; }; template<char C> char const* getLineOfChars() { static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0}; if( !*line ) { std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 ); line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0; } return line; } struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> { TestEventListenerBase( ReporterConfig const& _config ); static std::set<Verbosity> getSupportedVerbosities(); void assertionStarting(AssertionInfo const&) override; bool assertionEnded(AssertionStats const&) override; }; } // end namespace Catch // end catch_reporter_bases.hpp // start catch_console_colour.h namespace Catch { struct Colour { enum Code { None = 0, White, Red, Green, Blue, Cyan, Yellow, Grey, Bright = 0x10, BrightRed = Bright | Red, BrightGreen = Bright | Green, LightGrey = Bright | Grey, BrightWhite = Bright | White, BrightYellow = Bright | Yellow, // By intention FileName = LightGrey, Warning = BrightYellow, ResultError = BrightRed, ResultSuccess = BrightGreen, ResultExpectedFailure = Warning, Error = BrightRed, Success = Green, OriginalExpression = Cyan, ReconstructedExpression = BrightYellow, SecondaryText = LightGrey, Headers = White }; // Use constructed object for RAII guard Colour( Code _colourCode ); Colour( Colour&& other ) noexcept; Colour& operator=( Colour&& other ) noexcept; ~Colour(); // Use static method for one-shot changes static void use( Code _colourCode ); private: bool m_moved = false; }; std::ostream& operator << ( std::ostream& os, Colour const& ); } // end namespace Catch // end catch_console_colour.h // start catch_reporter_registrars.hpp namespace Catch { template<typename T> class ReporterRegistrar { class ReporterFactory : public IReporterFactory { virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override { return std::unique_ptr<T>( new T( config ) ); } virtual std::string getDescription() const override { return T::getDescription(); } }; public: explicit ReporterRegistrar( std::string const& name ) { getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() ); } }; template<typename T> class ListenerRegistrar { class ListenerFactory : public IReporterFactory { virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override { return std::unique_ptr<T>( new T( config ) ); } virtual std::string getDescription() const override { return std::string(); } }; public: ListenerRegistrar() { getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() ); } }; } #if !defined(CATCH_CONFIG_DISABLE) #define CATCH_REGISTER_REPORTER( name, reporterType ) \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS #define CATCH_REGISTER_LISTENER( listenerType ) \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS #else // CATCH_CONFIG_DISABLE #define CATCH_REGISTER_REPORTER(name, reporterType) #define CATCH_REGISTER_LISTENER(listenerType) #endif // CATCH_CONFIG_DISABLE // end catch_reporter_registrars.hpp // Allow users to base their work off existing reporters // start catch_reporter_compact.h namespace Catch { struct CompactReporter : StreamingReporterBase<CompactReporter> { using StreamingReporterBase::StreamingReporterBase; ~CompactReporter() override; static std::string getDescription(); ReporterPreferences getPreferences() const override; void noMatchingTestCases(std::string const& spec) override; void assertionStarting(AssertionInfo const&) override; bool assertionEnded(AssertionStats const& _assertionStats) override; void sectionEnded(SectionStats const& _sectionStats) override; void testRunEnded(TestRunStats const& _testRunStats) override; }; } // end namespace Catch // end catch_reporter_compact.h // start catch_reporter_console.h #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch // Note that 4062 (not all labels are handled // and default is missing) is enabled #endif namespace Catch { // Fwd decls struct SummaryColumn; class TablePrinter; struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> { std::unique_ptr<TablePrinter> m_tablePrinter; ConsoleReporter(ReporterConfig const& config); ~ConsoleReporter() override; static std::string getDescription(); void noMatchingTestCases(std::string const& spec) override; void assertionStarting(AssertionInfo const&) override; bool assertionEnded(AssertionStats const& _assertionStats) override; void sectionStarting(SectionInfo const& _sectionInfo) override; void sectionEnded(SectionStats const& _sectionStats) override; void benchmarkStarting(BenchmarkInfo const& info) override; void benchmarkEnded(BenchmarkStats const& stats) override; void testCaseEnded(TestCaseStats const& _testCaseStats) override; void testGroupEnded(TestGroupStats const& _testGroupStats) override; void testRunEnded(TestRunStats const& _testRunStats) override; private: void lazyPrint(); void lazyPrintWithoutClosingBenchmarkTable(); void lazyPrintRunInfo(); void lazyPrintGroupInfo(); void printTestCaseAndSectionHeader(); void printClosedHeader(std::string const& _name); void printOpenHeader(std::string const& _name); // if string has a : in first line will set indent to follow it on // subsequent lines void printHeaderString(std::string const& _string, std::size_t indent = 0); void printTotals(Totals const& totals); void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row); void printTotalsDivider(Totals const& totals); void printSummaryDivider(); private: bool m_headerPrinted = false; }; } // end namespace Catch #if defined(_MSC_VER) #pragma warning(pop) #endif // end catch_reporter_console.h // start catch_reporter_junit.h // start catch_xmlwriter.h #include <vector> namespace Catch { class XmlEncode { public: enum ForWhat { ForTextNodes, ForAttributes }; XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes ); void encodeTo( std::ostream& os ) const; friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ); private: std::string m_str; ForWhat m_forWhat; }; class XmlWriter { public: class ScopedElement { public: ScopedElement( XmlWriter* writer ); ScopedElement( ScopedElement&& other ) noexcept; ScopedElement& operator=( ScopedElement&& other ) noexcept; ~ScopedElement(); ScopedElement& writeText( std::string const& text, bool indent = true ); template<typename T> ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { m_writer->writeAttribute( name, attribute ); return *this; } private: mutable XmlWriter* m_writer = nullptr; }; XmlWriter( std::ostream& os = Catch::cout() ); ~XmlWriter(); XmlWriter( XmlWriter const& ) = delete; XmlWriter& operator=( XmlWriter const& ) = delete; XmlWriter& startElement( std::string const& name ); ScopedElement scopedElement( std::string const& name ); XmlWriter& endElement(); XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ); XmlWriter& writeAttribute( std::string const& name, bool attribute ); template<typename T> XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { ReusableStringStream rss; rss << attribute; return writeAttribute( name, rss.str() ); } XmlWriter& writeText( std::string const& text, bool indent = true ); XmlWriter& writeComment( std::string const& text ); void writeStylesheetRef( std::string const& url ); XmlWriter& writeBlankLine(); void ensureTagClosed(); private: void writeDeclaration(); void newlineIfNecessary(); bool m_tagIsOpen = false; bool m_needsNewline = false; std::vector<std::string> m_tags; std::string m_indent; std::ostream& m_os; }; } // end catch_xmlwriter.h namespace Catch { class JunitReporter : public CumulativeReporterBase<JunitReporter> { public: JunitReporter(ReporterConfig const& _config); ~JunitReporter() override; static std::string getDescription(); void noMatchingTestCases(std::string const& /*spec*/) override; void testRunStarting(TestRunInfo const& runInfo) override; void testGroupStarting(GroupInfo const& groupInfo) override; void testCaseStarting(TestCaseInfo const& testCaseInfo) override; bool assertionEnded(AssertionStats const& assertionStats) override; void testCaseEnded(TestCaseStats const& testCaseStats) override; void testGroupEnded(TestGroupStats const& testGroupStats) override; void testRunEndedCumulative() override; void writeGroup(TestGroupNode const& groupNode, double suiteTime); void writeTestCase(TestCaseNode const& testCaseNode); void writeSection(std::string const& className, std::string const& rootName, SectionNode const& sectionNode); void writeAssertions(SectionNode const& sectionNode); void writeAssertion(AssertionStats const& stats); XmlWriter xml; Timer suiteTimer; std::string stdOutForSuite; std::string stdErrForSuite; unsigned int unexpectedExceptions = 0; bool m_okToFail = false; }; } // end namespace Catch // end catch_reporter_junit.h // start catch_reporter_xml.h namespace Catch { class XmlReporter : public StreamingReporterBase<XmlReporter> { public: XmlReporter(ReporterConfig const& _config); ~XmlReporter() override; static std::string getDescription(); virtual std::string getStylesheetRef() const; void writeSourceInfo(SourceLineInfo const& sourceInfo); public: // StreamingReporterBase void noMatchingTestCases(std::string const& s) override; void testRunStarting(TestRunInfo const& testInfo) override; void testGroupStarting(GroupInfo const& groupInfo) override; void testCaseStarting(TestCaseInfo const& testInfo) override; void sectionStarting(SectionInfo const& sectionInfo) override; void assertionStarting(AssertionInfo const&) override; bool assertionEnded(AssertionStats const& assertionStats) override; void sectionEnded(SectionStats const& sectionStats) override; void testCaseEnded(TestCaseStats const& testCaseStats) override; void testGroupEnded(TestGroupStats const& testGroupStats) override; void testRunEnded(TestRunStats const& testRunStats) override; private: Timer m_testCaseTimer; XmlWriter m_xml; int m_sectionDepth = 0; }; } // end namespace Catch // end catch_reporter_xml.h // end catch_external_interfaces.h #endif #endif // ! CATCH_CONFIG_IMPL_ONLY #ifdef CATCH_IMPL // start catch_impl.hpp #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wweak-vtables" #endif // Keep these here for external reporters // start catch_test_case_tracker.h #include <string> #include <vector> #include <memory> namespace Catch { namespace TestCaseTracking { struct NameAndLocation { std::string name; SourceLineInfo location; NameAndLocation( std::string const& _name, SourceLineInfo const& _location ); }; struct ITracker; using ITrackerPtr = std::shared_ptr<ITracker>; struct ITracker { virtual ~ITracker(); // static queries virtual NameAndLocation const& nameAndLocation() const = 0; // dynamic queries virtual bool isComplete() const = 0; // Successfully completed or failed virtual bool isSuccessfullyCompleted() const = 0; virtual bool isOpen() const = 0; // Started but not complete virtual bool hasChildren() const = 0; virtual ITracker& parent() = 0; // actions virtual void close() = 0; // Successfully complete virtual void fail() = 0; virtual void markAsNeedingAnotherRun() = 0; virtual void addChild( ITrackerPtr const& child ) = 0; virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0; virtual void openChild() = 0; // Debug/ checking virtual bool isSectionTracker() const = 0; virtual bool isGeneratorTracker() const = 0; }; class TrackerContext { enum RunState { NotStarted, Executing, CompletedCycle }; ITrackerPtr m_rootTracker; ITracker* m_currentTracker = nullptr; RunState m_runState = NotStarted; public: static TrackerContext& instance(); ITracker& startRun(); void endRun(); void startCycle(); void completeCycle(); bool completedCycle() const; ITracker& currentTracker(); void setCurrentTracker( ITracker* tracker ); }; class TrackerBase : public ITracker { protected: enum CycleState { NotStarted, Executing, ExecutingChildren, NeedsAnotherRun, CompletedSuccessfully, Failed }; using Children = std::vector<ITrackerPtr>; NameAndLocation m_nameAndLocation; TrackerContext& m_ctx; ITracker* m_parent; Children m_children; CycleState m_runState = NotStarted; public: TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ); NameAndLocation const& nameAndLocation() const override; bool isComplete() const override; bool isSuccessfullyCompleted() const override; bool isOpen() const override; bool hasChildren() const override; void addChild( ITrackerPtr const& child ) override; ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override; ITracker& parent() override; void openChild() override; bool isSectionTracker() const override; bool isGeneratorTracker() const override; void open(); void close() override; void fail() override; void markAsNeedingAnotherRun() override; private: void moveToParent(); void moveToThis(); }; class SectionTracker : public TrackerBase { std::vector<std::string> m_filters; public: SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ); bool isSectionTracker() const override; bool isComplete() const override; static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ); void tryOpen(); void addInitialFilters( std::vector<std::string> const& filters ); void addNextFilters( std::vector<std::string> const& filters ); }; } // namespace TestCaseTracking using TestCaseTracking::ITracker; using TestCaseTracking::TrackerContext; using TestCaseTracking::SectionTracker; } // namespace Catch // end catch_test_case_tracker.h // start catch_leak_detector.h namespace Catch { struct LeakDetector { LeakDetector(); ~LeakDetector(); }; } // end catch_leak_detector.h // Cpp files will be included in the single-header file here // start catch_approx.cpp #include <cmath> #include <limits> namespace { // Performs equivalent check of std::fabs(lhs - rhs) <= margin // But without the subtraction to allow for INFINITY in comparison bool marginComparison(double lhs, double rhs, double margin) { return (lhs + margin >= rhs) && (rhs + margin >= lhs); } } namespace Catch { namespace Detail { Approx::Approx ( double value ) : m_epsilon( std::numeric_limits<float>::epsilon()*100 ), m_margin( 0.0 ), m_scale( 0.0 ), m_value( value ) {} Approx Approx::custom() { return Approx( 0 ); } Approx Approx::operator-() const { auto temp(*this); temp.m_value = -temp.m_value; return temp; } std::string Approx::toString() const { ReusableStringStream rss; rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )"; return rss.str(); } bool Approx::equalityComparisonImpl(const double other) const { // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value // Thanks to Richard Harris for his help refining the scaled margin value return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value))); } void Approx::setMargin(double margin) { CATCH_ENFORCE(margin >= 0, "Invalid Approx::margin: " << margin << '.' << " Approx::Margin has to be non-negative."); m_margin = margin; } void Approx::setEpsilon(double epsilon) { CATCH_ENFORCE(epsilon >= 0 && epsilon <= 1.0, "Invalid Approx::epsilon: " << epsilon << '.' << " Approx::epsilon has to be in [0, 1]"); m_epsilon = epsilon; } } // end namespace Detail namespace literals { Detail::Approx operator "" _a(long double val) { return Detail::Approx(val); } Detail::Approx operator "" _a(unsigned long long val) { return Detail::Approx(val); } } // end namespace literals std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) { return value.toString(); } } // end namespace Catch // end catch_approx.cpp // start catch_assertionhandler.cpp // start catch_context.h #include <memory> namespace Catch { struct IResultCapture; struct IRunner; struct IConfig; struct IMutableContext; using IConfigPtr = std::shared_ptr<IConfig const>; struct IContext { virtual ~IContext(); virtual IResultCapture* getResultCapture() = 0; virtual IRunner* getRunner() = 0; virtual IConfigPtr const& getConfig() const = 0; }; struct IMutableContext : IContext { virtual ~IMutableContext(); virtual void setResultCapture( IResultCapture* resultCapture ) = 0; virtual void setRunner( IRunner* runner ) = 0; virtual void setConfig( IConfigPtr const& config ) = 0; private: static IMutableContext *currentContext; friend IMutableContext& getCurrentMutableContext(); friend void cleanUpContext(); static void createContext(); }; inline IMutableContext& getCurrentMutableContext() { if( !IMutableContext::currentContext ) IMutableContext::createContext(); return *IMutableContext::currentContext; } inline IContext& getCurrentContext() { return getCurrentMutableContext(); } void cleanUpContext(); } // end catch_context.h // start catch_debugger.h namespace Catch { bool isDebuggerActive(); } #ifdef CATCH_PLATFORM_MAC #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */ #elif defined(CATCH_PLATFORM_LINUX) // If we can use inline assembler, do it because this allows us to break // directly at the location of the failing check instead of breaking inside // raise() called from it, i.e. one stack frame below. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */ #else // Fall back to the generic way. #include <signal.h> #define CATCH_TRAP() raise(SIGTRAP) #endif #elif defined(_MSC_VER) #define CATCH_TRAP() __debugbreak() #elif defined(__MINGW32__) extern "C" __declspec(dllimport) void __stdcall DebugBreak(); #define CATCH_TRAP() DebugBreak() #endif #ifdef CATCH_TRAP #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }() #else #define CATCH_BREAK_INTO_DEBUGGER() []{}() #endif // end catch_debugger.h // start catch_run_context.h // start catch_fatal_condition.h // start catch_windows_h_proxy.h #if defined(CATCH_PLATFORM_WINDOWS) #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX) # define CATCH_DEFINED_NOMINMAX # define NOMINMAX #endif #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN) # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN #endif #ifdef __AFXDLL #include <AfxWin.h> #else #include <windows.h> #endif #ifdef CATCH_DEFINED_NOMINMAX # undef NOMINMAX #endif #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN # undef WIN32_LEAN_AND_MEAN #endif #endif // defined(CATCH_PLATFORM_WINDOWS) // end catch_windows_h_proxy.h #if defined( CATCH_CONFIG_WINDOWS_SEH ) namespace Catch { struct FatalConditionHandler { static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo); FatalConditionHandler(); static void reset(); ~FatalConditionHandler(); private: static bool isSet; static ULONG guaranteeSize; static PVOID exceptionHandlerHandle; }; } // namespace Catch #elif defined ( CATCH_CONFIG_POSIX_SIGNALS ) #include <signal.h> namespace Catch { struct FatalConditionHandler { static bool isSet; static struct sigaction oldSigActions[]; static stack_t oldSigStack; static char altStackMem[]; static void handleSignal( int sig ); FatalConditionHandler(); ~FatalConditionHandler(); static void reset(); }; } // namespace Catch #else namespace Catch { struct FatalConditionHandler { void reset(); }; } #endif // end catch_fatal_condition.h #include <string> namespace Catch { struct IMutableContext; /////////////////////////////////////////////////////////////////////////// class RunContext : public IResultCapture, public IRunner { public: RunContext( RunContext const& ) = delete; RunContext& operator =( RunContext const& ) = delete; explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter ); ~RunContext() override; void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ); void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ); Totals runTest(TestCase const& testCase); IConfigPtr config() const; IStreamingReporter& reporter() const; public: // IResultCapture // Assertion handlers void handleExpr ( AssertionInfo const& info, ITransientExpression const& expr, AssertionReaction& reaction ) override; void handleMessage ( AssertionInfo const& info, ResultWas::OfType resultType, StringRef const& message, AssertionReaction& reaction ) override; void handleUnexpectedExceptionNotThrown ( AssertionInfo const& info, AssertionReaction& reaction ) override; void handleUnexpectedInflightException ( AssertionInfo const& info, std::string const& message, AssertionReaction& reaction ) override; void handleIncomplete ( AssertionInfo const& info ) override; void handleNonExpr ( AssertionInfo const &info, ResultWas::OfType resultType, AssertionReaction &reaction ) override; bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override; void sectionEnded( SectionEndInfo const& endInfo ) override; void sectionEndedEarly( SectionEndInfo const& endInfo ) override; auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override; void benchmarkStarting( BenchmarkInfo const& info ) override; void benchmarkEnded( BenchmarkStats const& stats ) override; void pushScopedMessage( MessageInfo const& message ) override; void popScopedMessage( MessageInfo const& message ) override; std::string getCurrentTestName() const override; const AssertionResult* getLastResult() const override; void exceptionEarlyReported() override; void handleFatalErrorCondition( StringRef message ) override; bool lastAssertionPassed() override; void assertionPassed() override; public: // !TBD We need to do this another way! bool aborting() const final; private: void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ); void invokeActiveTestCase(); void resetAssertionInfo(); bool testForMissingAssertions( Counts& assertions ); void assertionEnded( AssertionResult const& result ); void reportExpr ( AssertionInfo const &info, ResultWas::OfType resultType, ITransientExpression const *expr, bool negated ); void populateReaction( AssertionReaction& reaction ); private: void handleUnfinishedSections(); TestRunInfo m_runInfo; IMutableContext& m_context; TestCase const* m_activeTestCase = nullptr; ITracker* m_testCaseTracker = nullptr; Option<AssertionResult> m_lastResult; IConfigPtr m_config; Totals m_totals; IStreamingReporterPtr m_reporter; std::vector<MessageInfo> m_messages; AssertionInfo m_lastAssertionInfo; std::vector<SectionEndInfo> m_unfinishedSections; std::vector<ITracker*> m_activeSections; TrackerContext m_trackerContext; bool m_lastAssertionPassed = false; bool m_shouldReportUnexpected = true; bool m_includeSuccessfulResults; }; } // end namespace Catch // end catch_run_context.h namespace Catch { namespace { auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& { expr.streamReconstructedExpression( os ); return os; } } LazyExpression::LazyExpression( bool isNegated ) : m_isNegated( isNegated ) {} LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {} LazyExpression::operator bool() const { return m_transientExpression != nullptr; } auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& { if( lazyExpr.m_isNegated ) os << "!"; if( lazyExpr ) { if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() ) os << "(" << *lazyExpr.m_transientExpression << ")"; else os << *lazyExpr.m_transientExpression; } else { os << "{** error - unchecked empty expression requested **}"; } return os; } AssertionHandler::AssertionHandler ( StringRef const& macroName, SourceLineInfo const& lineInfo, StringRef capturedExpression, ResultDisposition::Flags resultDisposition ) : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition }, m_resultCapture( getResultCapture() ) {} void AssertionHandler::handleExpr( ITransientExpression const& expr ) { m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction ); } void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) { m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction ); } auto AssertionHandler::allowThrows() const -> bool { return getCurrentContext().getConfig()->allowThrows(); } void AssertionHandler::complete() { setCompleted(); if( m_reaction.shouldDebugBreak ) { // If you find your debugger stopping you here then go one level up on the // call-stack for the code that caused it (typically a failed assertion) // (To go back to the test and change execution, jump over the throw, next) CATCH_BREAK_INTO_DEBUGGER(); } if (m_reaction.shouldThrow) { #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) throw Catch::TestFailureException(); #else CATCH_ERROR( "Test failure requires aborting test!" ); #endif } } void AssertionHandler::setCompleted() { m_completed = true; } void AssertionHandler::handleUnexpectedInflightException() { m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction ); } void AssertionHandler::handleExceptionThrownAsExpected() { m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction); } void AssertionHandler::handleExceptionNotThrownAsExpected() { m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction); } void AssertionHandler::handleUnexpectedExceptionNotThrown() { m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction ); } void AssertionHandler::handleThrowingCallSkipped() { m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction); } // This is the overload that takes a string and infers the Equals matcher from it // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) { handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString ); } } // namespace Catch // end catch_assertionhandler.cpp // start catch_assertionresult.cpp namespace Catch { AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression): lazyExpression(_lazyExpression), resultType(_resultType) {} std::string AssertionResultData::reconstructExpression() const { if( reconstructedExpression.empty() ) { if( lazyExpression ) { ReusableStringStream rss; rss << lazyExpression; reconstructedExpression = rss.str(); } } return reconstructedExpression; } AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data ) : m_info( info ), m_resultData( data ) {} // Result was a success bool AssertionResult::succeeded() const { return Catch::isOk( m_resultData.resultType ); } // Result was a success, or failure is suppressed bool AssertionResult::isOk() const { return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition ); } ResultWas::OfType AssertionResult::getResultType() const { return m_resultData.resultType; } bool AssertionResult::hasExpression() const { return m_info.capturedExpression[0] != 0; } bool AssertionResult::hasMessage() const { return !m_resultData.message.empty(); } std::string AssertionResult::getExpression() const { if( isFalseTest( m_info.resultDisposition ) ) return "!(" + m_info.capturedExpression + ")"; else return m_info.capturedExpression; } std::string AssertionResult::getExpressionInMacro() const { std::string expr; if( m_info.macroName[0] == 0 ) expr = m_info.capturedExpression; else { expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 ); expr += m_info.macroName; expr += "( "; expr += m_info.capturedExpression; expr += " )"; } return expr; } bool AssertionResult::hasExpandedExpression() const { return hasExpression() && getExpandedExpression() != getExpression(); } std::string AssertionResult::getExpandedExpression() const { std::string expr = m_resultData.reconstructExpression(); return expr.empty() ? getExpression() : expr; } std::string AssertionResult::getMessage() const { return m_resultData.message; } SourceLineInfo AssertionResult::getSourceInfo() const { return m_info.lineInfo; } StringRef AssertionResult::getTestMacroName() const { return m_info.macroName; } } // end namespace Catch // end catch_assertionresult.cpp // start catch_benchmark.cpp namespace Catch { auto BenchmarkLooper::getResolution() -> uint64_t { return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple(); } void BenchmarkLooper::reportStart() { getResultCapture().benchmarkStarting( { m_name } ); } auto BenchmarkLooper::needsMoreIterations() -> bool { auto elapsed = m_timer.getElapsedNanoseconds(); // Exponentially increasing iterations until we're confident in our timer resolution if( elapsed < m_resolution ) { m_iterationsToRun *= 10; return true; } getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } ); return false; } } // end namespace Catch // end catch_benchmark.cpp // start catch_capture_matchers.cpp namespace Catch { using StringMatcher = Matchers::Impl::MatcherBase<std::string>; // This is the general overload that takes a any string matcher // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers // the Equals matcher (so the header does not mention matchers) void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) { std::string exceptionMessage = Catch::translateActiveException(); MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString ); handler.handleExpr( expr ); } } // namespace Catch // end catch_capture_matchers.cpp // start catch_commandline.cpp // start catch_commandline.h // start catch_clara.h // Use Catch's value for console width (store Clara's off to the side, if present) #ifdef CLARA_CONFIG_CONSOLE_WIDTH #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH #endif #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1 #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wweak-vtables" #pragma clang diagnostic ignored "-Wexit-time-destructors" #pragma clang diagnostic ignored "-Wshadow" #endif // start clara.hpp // Copyright 2017 Two Blue Cubes Ltd. All rights reserved. // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See https://github.com/philsquared/Clara for more details // Clara v1.1.5 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80 #endif #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH #endif #ifndef CLARA_CONFIG_OPTIONAL_TYPE #ifdef __has_include #if __has_include(<optional>) && __cplusplus >= 201703L #include <optional> #define CLARA_CONFIG_OPTIONAL_TYPE std::optional #endif #endif #endif // ----------- #included from clara_textflow.hpp ----------- // TextFlowCpp // // A single-header library for wrapping and laying out basic text, by Phil Nash // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // This project is hosted at https://github.com/philsquared/textflowcpp #include <cassert> #include <ostream> #include <sstream> #include <vector> #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80 #endif namespace Catch { namespace clara { namespace TextFlow { inline auto isWhitespace(char c) -> bool { static std::string chars = " \t\n\r"; return chars.find(c) != std::string::npos; } inline auto isBreakableBefore(char c) -> bool { static std::string chars = "[({<|"; return chars.find(c) != std::string::npos; } inline auto isBreakableAfter(char c) -> bool { static std::string chars = "])}>.,:;*+-=&/\\"; return chars.find(c) != std::string::npos; } class Columns; class Column { std::vector<std::string> m_strings; size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH; size_t m_indent = 0; size_t m_initialIndent = std::string::npos; public: class iterator { friend Column; Column const& m_column; size_t m_stringIndex = 0; size_t m_pos = 0; size_t m_len = 0; size_t m_end = 0; bool m_suffix = false; iterator(Column const& column, size_t stringIndex) : m_column(column), m_stringIndex(stringIndex) {} auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; } auto isBoundary(size_t at) const -> bool { assert(at > 0); assert(at <= line().size()); return at == line().size() || (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) || isBreakableBefore(line()[at]) || isBreakableAfter(line()[at - 1]); } void calcLength() { assert(m_stringIndex < m_column.m_strings.size()); m_suffix = false; auto width = m_column.m_width - indent(); m_end = m_pos; while (m_end < line().size() && line()[m_end] != '\n') ++m_end; if (m_end < m_pos + width) { m_len = m_end - m_pos; } else { size_t len = width; while (len > 0 && !isBoundary(m_pos + len)) --len; while (len > 0 && isWhitespace(line()[m_pos + len - 1])) --len; if (len > 0) { m_len = len; } else { m_suffix = true; m_len = width - 1; } } } auto indent() const -> size_t { auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos; return initial == std::string::npos ? m_column.m_indent : initial; } auto addIndentAndSuffix(std::string const &plain) const -> std::string { return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain); } public: using difference_type = std::ptrdiff_t; using value_type = std::string; using pointer = value_type * ; using reference = value_type & ; using iterator_category = std::forward_iterator_tag; explicit iterator(Column const& column) : m_column(column) { assert(m_column.m_width > m_column.m_indent); assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent); calcLength(); if (m_len == 0) m_stringIndex++; // Empty string } auto operator *() const -> std::string { assert(m_stringIndex < m_column.m_strings.size()); assert(m_pos <= m_end); return addIndentAndSuffix(line().substr(m_pos, m_len)); } auto operator ++() -> iterator& { m_pos += m_len; if (m_pos < line().size() && line()[m_pos] == '\n') m_pos += 1; else while (m_pos < line().size() && isWhitespace(line()[m_pos])) ++m_pos; if (m_pos == line().size()) { m_pos = 0; ++m_stringIndex; } if (m_stringIndex < m_column.m_strings.size()) calcLength(); return *this; } auto operator ++(int) -> iterator { iterator prev(*this); operator++(); return prev; } auto operator ==(iterator const& other) const -> bool { return m_pos == other.m_pos && m_stringIndex == other.m_stringIndex && &m_column == &other.m_column; } auto operator !=(iterator const& other) const -> bool { return !operator==(other); } }; using const_iterator = iterator; explicit Column(std::string const& text) { m_strings.push_back(text); } auto width(size_t newWidth) -> Column& { assert(newWidth > 0); m_width = newWidth; return *this; } auto indent(size_t newIndent) -> Column& { m_indent = newIndent; return *this; } auto initialIndent(size_t newIndent) -> Column& { m_initialIndent = newIndent; return *this; } auto width() const -> size_t { return m_width; } auto begin() const -> iterator { return iterator(*this); } auto end() const -> iterator { return { *this, m_strings.size() }; } inline friend std::ostream& operator << (std::ostream& os, Column const& col) { bool first = true; for (auto line : col) { if (first) first = false; else os << "\n"; os << line; } return os; } auto operator + (Column const& other)->Columns; auto toString() const -> std::string { std::ostringstream oss; oss << *this; return oss.str(); } }; class Spacer : public Column { public: explicit Spacer(size_t spaceWidth) : Column("") { width(spaceWidth); } }; class Columns { std::vector<Column> m_columns; public: class iterator { friend Columns; struct EndTag {}; std::vector<Column> const& m_columns; std::vector<Column::iterator> m_iterators; size_t m_activeIterators; iterator(Columns const& columns, EndTag) : m_columns(columns.m_columns), m_activeIterators(0) { m_iterators.reserve(m_columns.size()); for (auto const& col : m_columns) m_iterators.push_back(col.end()); } public: using difference_type = std::ptrdiff_t; using value_type = std::string; using pointer = value_type * ; using reference = value_type & ; using iterator_category = std::forward_iterator_tag; explicit iterator(Columns const& columns) : m_columns(columns.m_columns), m_activeIterators(m_columns.size()) { m_iterators.reserve(m_columns.size()); for (auto const& col : m_columns) m_iterators.push_back(col.begin()); } auto operator ==(iterator const& other) const -> bool { return m_iterators == other.m_iterators; } auto operator !=(iterator const& other) const -> bool { return m_iterators != other.m_iterators; } auto operator *() const -> std::string { std::string row, padding; for (size_t i = 0; i < m_columns.size(); ++i) { auto width = m_columns[i].width(); if (m_iterators[i] != m_columns[i].end()) { std::string col = *m_iterators[i]; row += padding + col; if (col.size() < width) padding = std::string(width - col.size(), ' '); else padding = ""; } else { padding += std::string(width, ' '); } } return row; } auto operator ++() -> iterator& { for (size_t i = 0; i < m_columns.size(); ++i) { if (m_iterators[i] != m_columns[i].end()) ++m_iterators[i]; } return *this; } auto operator ++(int) -> iterator { iterator prev(*this); operator++(); return prev; } }; using const_iterator = iterator; auto begin() const -> iterator { return iterator(*this); } auto end() const -> iterator { return { *this, iterator::EndTag() }; } auto operator += (Column const& col) -> Columns& { m_columns.push_back(col); return *this; } auto operator + (Column const& col) -> Columns { Columns combined = *this; combined += col; return combined; } inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) { bool first = true; for (auto line : cols) { if (first) first = false; else os << "\n"; os << line; } return os; } auto toString() const -> std::string { std::ostringstream oss; oss << *this; return oss.str(); } }; inline auto Column::operator + (Column const& other) -> Columns { Columns cols; cols += *this; cols += other; return cols; } } } } // ----------- end of #include from clara_textflow.hpp ----------- // ........... back in clara.hpp #include <string> #include <memory> #include <set> #include <algorithm> #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) ) #define CATCH_PLATFORM_WINDOWS #endif namespace Catch { namespace clara { namespace detail { // Traits for extracting arg and return type of lambdas (for single argument lambdas) template<typename L> struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {}; template<typename ClassT, typename ReturnT, typename... Args> struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> { static const bool isValid = false; }; template<typename ClassT, typename ReturnT, typename ArgT> struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> { static const bool isValid = true; using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type; using ReturnType = ReturnT; }; class TokenStream; // Transport for raw args (copied from main args, or supplied via init list for testing) class Args { friend TokenStream; std::string m_exeName; std::vector<std::string> m_args; public: Args( int argc, char const* const* argv ) : m_exeName(argv[0]), m_args(argv + 1, argv + argc) {} Args( std::initializer_list<std::string> args ) : m_exeName( *args.begin() ), m_args( args.begin()+1, args.end() ) {} auto exeName() const -> std::string { return m_exeName; } }; // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string // may encode an option + its argument if the : or = form is used enum class TokenType { Option, Argument }; struct Token { TokenType type; std::string token; }; inline auto isOptPrefix( char c ) -> bool { return c == '-' #ifdef CATCH_PLATFORM_WINDOWS || c == '/' #endif ; } // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled class TokenStream { using Iterator = std::vector<std::string>::const_iterator; Iterator it; Iterator itEnd; std::vector<Token> m_tokenBuffer; void loadBuffer() { m_tokenBuffer.resize( 0 ); // Skip any empty strings while( it != itEnd && it->empty() ) ++it; if( it != itEnd ) { auto const &next = *it; if( isOptPrefix( next[0] ) ) { auto delimiterPos = next.find_first_of( " :=" ); if( delimiterPos != std::string::npos ) { m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } ); m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } ); } else { if( next[1] != '-' && next.size() > 2 ) { std::string opt = "- "; for( size_t i = 1; i < next.size(); ++i ) { opt[1] = next[i]; m_tokenBuffer.push_back( { TokenType::Option, opt } ); } } else { m_tokenBuffer.push_back( { TokenType::Option, next } ); } } } else { m_tokenBuffer.push_back( { TokenType::Argument, next } ); } } } public: explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {} TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) { loadBuffer(); } explicit operator bool() const { return !m_tokenBuffer.empty() || it != itEnd; } auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); } auto operator*() const -> Token { assert( !m_tokenBuffer.empty() ); return m_tokenBuffer.front(); } auto operator->() const -> Token const * { assert( !m_tokenBuffer.empty() ); return &m_tokenBuffer.front(); } auto operator++() -> TokenStream & { if( m_tokenBuffer.size() >= 2 ) { m_tokenBuffer.erase( m_tokenBuffer.begin() ); } else { if( it != itEnd ) ++it; loadBuffer(); } return *this; } }; class ResultBase { public: enum Type { Ok, LogicError, RuntimeError }; protected: ResultBase( Type type ) : m_type( type ) {} virtual ~ResultBase() = default; virtual void enforceOk() const = 0; Type m_type; }; template<typename T> class ResultValueBase : public ResultBase { public: auto value() const -> T const & { enforceOk(); return m_value; } protected: ResultValueBase( Type type ) : ResultBase( type ) {} ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) { if( m_type == ResultBase::Ok ) new( &m_value ) T( other.m_value ); } ResultValueBase( Type, T const &value ) : ResultBase( Ok ) { new( &m_value ) T( value ); } auto operator=( ResultValueBase const &other ) -> ResultValueBase & { if( m_type == ResultBase::Ok ) m_value.~T(); ResultBase::operator=(other); if( m_type == ResultBase::Ok ) new( &m_value ) T( other.m_value ); return *this; } ~ResultValueBase() override { if( m_type == Ok ) m_value.~T(); } union { T m_value; }; }; template<> class ResultValueBase<void> : public ResultBase { protected: using ResultBase::ResultBase; }; template<typename T = void> class BasicResult : public ResultValueBase<T> { public: template<typename U> explicit BasicResult( BasicResult<U> const &other ) : ResultValueBase<T>( other.type() ), m_errorMessage( other.errorMessage() ) { assert( type() != ResultBase::Ok ); } template<typename U> static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; } static auto ok() -> BasicResult { return { ResultBase::Ok }; } static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; } static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; } explicit operator bool() const { return m_type == ResultBase::Ok; } auto type() const -> ResultBase::Type { return m_type; } auto errorMessage() const -> std::string { return m_errorMessage; } protected: void enforceOk() const override { // Errors shouldn't reach this point, but if they do // the actual error message will be in m_errorMessage assert( m_type != ResultBase::LogicError ); assert( m_type != ResultBase::RuntimeError ); if( m_type != ResultBase::Ok ) std::abort(); } std::string m_errorMessage; // Only populated if resultType is an error BasicResult( ResultBase::Type type, std::string const &message ) : ResultValueBase<T>(type), m_errorMessage(message) { assert( m_type != ResultBase::Ok ); } using ResultValueBase<T>::ResultValueBase; using ResultBase::m_type; }; enum class ParseResultType { Matched, NoMatch, ShortCircuitAll, ShortCircuitSame }; class ParseState { public: ParseState( ParseResultType type, TokenStream const &remainingTokens ) : m_type(type), m_remainingTokens( remainingTokens ) {} auto type() const -> ParseResultType { return m_type; } auto remainingTokens() const -> TokenStream { return m_remainingTokens; } private: ParseResultType m_type; TokenStream m_remainingTokens; }; using Result = BasicResult<void>; using ParserResult = BasicResult<ParseResultType>; using InternalParseResult = BasicResult<ParseState>; struct HelpColumns { std::string left; std::string right; }; template<typename T> inline auto convertInto( std::string const &source, T& target ) -> ParserResult { std::stringstream ss; ss << source; ss >> target; if( ss.fail() ) return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" ); else return ParserResult::ok( ParseResultType::Matched ); } inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult { target = source; return ParserResult::ok( ParseResultType::Matched ); } inline auto convertInto( std::string const &source, bool &target ) -> ParserResult { std::string srcLC = source; std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( ::tolower(c) ); } ); if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on") target = true; else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off") target = false; else return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" ); return ParserResult::ok( ParseResultType::Matched ); } #ifdef CLARA_CONFIG_OPTIONAL_TYPE template<typename T> inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult { T temp; auto result = convertInto( source, temp ); if( result ) target = std::move(temp); return result; } #endif // CLARA_CONFIG_OPTIONAL_TYPE struct NonCopyable { NonCopyable() = default; NonCopyable( NonCopyable const & ) = delete; NonCopyable( NonCopyable && ) = delete; NonCopyable &operator=( NonCopyable const & ) = delete; NonCopyable &operator=( NonCopyable && ) = delete; }; struct BoundRef : NonCopyable { virtual ~BoundRef() = default; virtual auto isContainer() const -> bool { return false; } virtual auto isFlag() const -> bool { return false; } }; struct BoundValueRefBase : BoundRef { virtual auto setValue( std::string const &arg ) -> ParserResult = 0; }; struct BoundFlagRefBase : BoundRef { virtual auto setFlag( bool flag ) -> ParserResult = 0; virtual auto isFlag() const -> bool { return true; } }; template<typename T> struct BoundValueRef : BoundValueRefBase { T &m_ref; explicit BoundValueRef( T &ref ) : m_ref( ref ) {} auto setValue( std::string const &arg ) -> ParserResult override { return convertInto( arg, m_ref ); } }; template<typename T> struct BoundValueRef<std::vector<T>> : BoundValueRefBase { std::vector<T> &m_ref; explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {} auto isContainer() const -> bool override { return true; } auto setValue( std::string const &arg ) -> ParserResult override { T temp; auto result = convertInto( arg, temp ); if( result ) m_ref.push_back( temp ); return result; } }; struct BoundFlagRef : BoundFlagRefBase { bool &m_ref; explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {} auto setFlag( bool flag ) -> ParserResult override { m_ref = flag; return ParserResult::ok( ParseResultType::Matched ); } }; template<typename ReturnType> struct LambdaInvoker { static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" ); template<typename L, typename ArgType> static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult { return lambda( arg ); } }; template<> struct LambdaInvoker<void> { template<typename L, typename ArgType> static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult { lambda( arg ); return ParserResult::ok( ParseResultType::Matched ); } }; template<typename ArgType, typename L> inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult { ArgType temp{}; auto result = convertInto( arg, temp ); return !result ? result : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp ); } template<typename L> struct BoundLambda : BoundValueRefBase { L m_lambda; static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" ); explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {} auto setValue( std::string const &arg ) -> ParserResult override { return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg ); } }; template<typename L> struct BoundFlagLambda : BoundFlagRefBase { L m_lambda; static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" ); static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" ); explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {} auto setFlag( bool flag ) -> ParserResult override { return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag ); } }; enum class Optionality { Optional, Required }; struct Parser; class ParserBase { public: virtual ~ParserBase() = default; virtual auto validate() const -> Result { return Result::ok(); } virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0; virtual auto cardinality() const -> size_t { return 1; } auto parse( Args const &args ) const -> InternalParseResult { return parse( args.exeName(), TokenStream( args ) ); } }; template<typename DerivedT> class ComposableParserImpl : public ParserBase { public: template<typename T> auto operator|( T const &other ) const -> Parser; template<typename T> auto operator+( T const &other ) const -> Parser; }; // Common code and state for Args and Opts template<typename DerivedT> class ParserRefImpl : public ComposableParserImpl<DerivedT> { protected: Optionality m_optionality = Optionality::Optional; std::shared_ptr<BoundRef> m_ref; std::string m_hint; std::string m_description; explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {} public: template<typename T> ParserRefImpl( T &ref, std::string const &hint ) : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ), m_hint( hint ) {} template<typename LambdaT> ParserRefImpl( LambdaT const &ref, std::string const &hint ) : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ), m_hint(hint) {} auto operator()( std::string const &description ) -> DerivedT & { m_description = description; return static_cast<DerivedT &>( *this ); } auto optional() -> DerivedT & { m_optionality = Optionality::Optional; return static_cast<DerivedT &>( *this ); }; auto required() -> DerivedT & { m_optionality = Optionality::Required; return static_cast<DerivedT &>( *this ); }; auto isOptional() const -> bool { return m_optionality == Optionality::Optional; } auto cardinality() const -> size_t override { if( m_ref->isContainer() ) return 0; else return 1; } auto hint() const -> std::string { return m_hint; } }; class ExeName : public ComposableParserImpl<ExeName> { std::shared_ptr<std::string> m_name; std::shared_ptr<BoundValueRefBase> m_ref; template<typename LambdaT> static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> { return std::make_shared<BoundLambda<LambdaT>>( lambda) ; } public: ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {} explicit ExeName( std::string &ref ) : ExeName() { m_ref = std::make_shared<BoundValueRef<std::string>>( ref ); } template<typename LambdaT> explicit ExeName( LambdaT const& lambda ) : ExeName() { m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda ); } // The exe name is not parsed out of the normal tokens, but is handled specially auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override { return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) ); } auto name() const -> std::string { return *m_name; } auto set( std::string const& newName ) -> ParserResult { auto lastSlash = newName.find_last_of( "\\/" ); auto filename = ( lastSlash == std::string::npos ) ? newName : newName.substr( lastSlash+1 ); *m_name = filename; if( m_ref ) return m_ref->setValue( filename ); else return ParserResult::ok( ParseResultType::Matched ); } }; class Arg : public ParserRefImpl<Arg> { public: using ParserRefImpl::ParserRefImpl; auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override { auto validationResult = validate(); if( !validationResult ) return InternalParseResult( validationResult ); auto remainingTokens = tokens; auto const &token = *remainingTokens; if( token.type != TokenType::Argument ) return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) ); assert( !m_ref->isFlag() ); auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() ); auto result = valueRef->setValue( remainingTokens->token ); if( !result ) return InternalParseResult( result ); else return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) ); } }; inline auto normaliseOpt( std::string const &optName ) -> std::string { #ifdef CATCH_PLATFORM_WINDOWS if( optName[0] == '/' ) return "-" + optName.substr( 1 ); else #endif return optName; } class Opt : public ParserRefImpl<Opt> { protected: std::vector<std::string> m_optNames; public: template<typename LambdaT> explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {} explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {} template<typename LambdaT> Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {} template<typename T> Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {} auto operator[]( std::string const &optName ) -> Opt & { m_optNames.push_back( optName ); return *this; } auto getHelpColumns() const -> std::vector<HelpColumns> { std::ostringstream oss; bool first = true; for( auto const &opt : m_optNames ) { if (first) first = false; else oss << ", "; oss << opt; } if( !m_hint.empty() ) oss << " <" << m_hint << ">"; return { { oss.str(), m_description } }; } auto isMatch( std::string const &optToken ) const -> bool { auto normalisedToken = normaliseOpt( optToken ); for( auto const &name : m_optNames ) { if( normaliseOpt( name ) == normalisedToken ) return true; } return false; } using ParserBase::parse; auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override { auto validationResult = validate(); if( !validationResult ) return InternalParseResult( validationResult ); auto remainingTokens = tokens; if( remainingTokens && remainingTokens->type == TokenType::Option ) { auto const &token = *remainingTokens; if( isMatch(token.token ) ) { if( m_ref->isFlag() ) { auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() ); auto result = flagRef->setFlag( true ); if( !result ) return InternalParseResult( result ); if( result.value() == ParseResultType::ShortCircuitAll ) return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) ); } else { auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() ); ++remainingTokens; if( !remainingTokens ) return InternalParseResult::runtimeError( "Expected argument following " + token.token ); auto const &argToken = *remainingTokens; if( argToken.type != TokenType::Argument ) return InternalParseResult::runtimeError( "Expected argument following " + token.token ); auto result = valueRef->setValue( argToken.token ); if( !result ) return InternalParseResult( result ); if( result.value() == ParseResultType::ShortCircuitAll ) return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) ); } return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) ); } } return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) ); } auto validate() const -> Result override { if( m_optNames.empty() ) return Result::logicError( "No options supplied to Opt" ); for( auto const &name : m_optNames ) { if( name.empty() ) return Result::logicError( "Option name cannot be empty" ); #ifdef CATCH_PLATFORM_WINDOWS if( name[0] != '-' && name[0] != '/' ) return Result::logicError( "Option name must begin with '-' or '/'" ); #else if( name[0] != '-' ) return Result::logicError( "Option name must begin with '-'" ); #endif } return ParserRefImpl::validate(); } }; struct Help : Opt { Help( bool &showHelpFlag ) : Opt([&]( bool flag ) { showHelpFlag = flag; return ParserResult::ok( ParseResultType::ShortCircuitAll ); }) { static_cast<Opt &>( *this ) ("display usage information") ["-?"]["-h"]["--help"] .optional(); } }; struct Parser : ParserBase { mutable ExeName m_exeName; std::vector<Opt> m_options; std::vector<Arg> m_args; auto operator|=( ExeName const &exeName ) -> Parser & { m_exeName = exeName; return *this; } auto operator|=( Arg const &arg ) -> Parser & { m_args.push_back(arg); return *this; } auto operator|=( Opt const &opt ) -> Parser & { m_options.push_back(opt); return *this; } auto operator|=( Parser const &other ) -> Parser & { m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end()); m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end()); return *this; } template<typename T> auto operator|( T const &other ) const -> Parser { return Parser( *this ) |= other; } // Forward deprecated interface with '+' instead of '|' template<typename T> auto operator+=( T const &other ) -> Parser & { return operator|=( other ); } template<typename T> auto operator+( T const &other ) const -> Parser { return operator|( other ); } auto getHelpColumns() const -> std::vector<HelpColumns> { std::vector<HelpColumns> cols; for (auto const &o : m_options) { auto childCols = o.getHelpColumns(); cols.insert( cols.end(), childCols.begin(), childCols.end() ); } return cols; } void writeToStream( std::ostream &os ) const { if (!m_exeName.name().empty()) { os << "usage:\n" << " " << m_exeName.name() << " "; bool required = true, first = true; for( auto const &arg : m_args ) { if (first) first = false; else os << " "; if( arg.isOptional() && required ) { os << "["; required = false; } os << "<" << arg.hint() << ">"; if( arg.cardinality() == 0 ) os << " ... "; } if( !required ) os << "]"; if( !m_options.empty() ) os << " options"; os << "\n\nwhere options are:" << std::endl; } auto rows = getHelpColumns(); size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH; size_t optWidth = 0; for( auto const &cols : rows ) optWidth = (std::max)(optWidth, cols.left.size() + 2); optWidth = (std::min)(optWidth, consoleWidth/2); for( auto const &cols : rows ) { auto row = TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) + TextFlow::Spacer(4) + TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth ); os << row << std::endl; } } friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& { parser.writeToStream( os ); return os; } auto validate() const -> Result override { for( auto const &opt : m_options ) { auto result = opt.validate(); if( !result ) return result; } for( auto const &arg : m_args ) { auto result = arg.validate(); if( !result ) return result; } return Result::ok(); } using ParserBase::parse; auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override { struct ParserInfo { ParserBase const* parser = nullptr; size_t count = 0; }; const size_t totalParsers = m_options.size() + m_args.size(); assert( totalParsers < 512 ); // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do ParserInfo parseInfos[512]; { size_t i = 0; for (auto const &opt : m_options) parseInfos[i++].parser = &opt; for (auto const &arg : m_args) parseInfos[i++].parser = &arg; } m_exeName.set( exeName ); auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) ); while( result.value().remainingTokens() ) { bool tokenParsed = false; for( size_t i = 0; i < totalParsers; ++i ) { auto& parseInfo = parseInfos[i]; if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) { result = parseInfo.parser->parse(exeName, result.value().remainingTokens()); if (!result) return result; if (result.value().type() != ParseResultType::NoMatch) { tokenParsed = true; ++parseInfo.count; break; } } } if( result.value().type() == ParseResultType::ShortCircuitAll ) return result; if( !tokenParsed ) return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token ); } // !TBD Check missing required options return result; } }; template<typename DerivedT> template<typename T> auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser { return Parser() | static_cast<DerivedT const &>( *this ) | other; } } // namespace detail // A Combined parser using detail::Parser; // A parser for options using detail::Opt; // A parser for arguments using detail::Arg; // Wrapper for argc, argv from main() using detail::Args; // Specifies the name of the executable using detail::ExeName; // Convenience wrapper for option parser that specifies the help option using detail::Help; // enum of result types from a parse using detail::ParseResultType; // Result type for parser operation using detail::ParserResult; }} // namespace Catch::clara // end clara.hpp #ifdef __clang__ #pragma clang diagnostic pop #endif // Restore Clara's value for console width, if present #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #endif // end catch_clara.h namespace Catch { clara::Parser makeCommandLineParser( ConfigData& config ); } // end namespace Catch // end catch_commandline.h #include <fstream> #include <ctime> namespace Catch { clara::Parser makeCommandLineParser( ConfigData& config ) { using namespace clara; auto const setWarning = [&]( std::string const& warning ) { auto warningSet = [&]() { if( warning == "NoAssertions" ) return WarnAbout::NoAssertions; if ( warning == "NoTests" ) return WarnAbout::NoTests; return WarnAbout::Nothing; }(); if (warningSet == WarnAbout::Nothing) return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" ); config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet ); return ParserResult::ok( ParseResultType::Matched ); }; auto const loadTestNamesFromFile = [&]( std::string const& filename ) { std::ifstream f( filename.c_str() ); if( !f.is_open() ) return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" ); std::string line; while( std::getline( f, line ) ) { line = trim(line); if( !line.empty() && !startsWith( line, '#' ) ) { if( !startsWith( line, '"' ) ) line = '"' + line + '"'; config.testsOrTags.push_back( line + ',' ); } } return ParserResult::ok( ParseResultType::Matched ); }; auto const setTestOrder = [&]( std::string const& order ) { if( startsWith( "declared", order ) ) config.runOrder = RunTests::InDeclarationOrder; else if( startsWith( "lexical", order ) ) config.runOrder = RunTests::InLexicographicalOrder; else if( startsWith( "random", order ) ) config.runOrder = RunTests::InRandomOrder; else return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" ); return ParserResult::ok( ParseResultType::Matched ); }; auto const setRngSeed = [&]( std::string const& seed ) { if( seed != "time" ) return clara::detail::convertInto( seed, config.rngSeed ); config.rngSeed = static_cast<unsigned int>( std::time(nullptr) ); return ParserResult::ok( ParseResultType::Matched ); }; auto const setColourUsage = [&]( std::string const& useColour ) { auto mode = toLower( useColour ); if( mode == "yes" ) config.useColour = UseColour::Yes; else if( mode == "no" ) config.useColour = UseColour::No; else if( mode == "auto" ) config.useColour = UseColour::Auto; else return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" ); return ParserResult::ok( ParseResultType::Matched ); }; auto const setWaitForKeypress = [&]( std::string const& keypress ) { auto keypressLc = toLower( keypress ); if( keypressLc == "start" ) config.waitForKeypress = WaitForKeypress::BeforeStart; else if( keypressLc == "exit" ) config.waitForKeypress = WaitForKeypress::BeforeExit; else if( keypressLc == "both" ) config.waitForKeypress = WaitForKeypress::BeforeStartAndExit; else return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" ); return ParserResult::ok( ParseResultType::Matched ); }; auto const setVerbosity = [&]( std::string const& verbosity ) { auto lcVerbosity = toLower( verbosity ); if( lcVerbosity == "quiet" ) config.verbosity = Verbosity::Quiet; else if( lcVerbosity == "normal" ) config.verbosity = Verbosity::Normal; else if( lcVerbosity == "high" ) config.verbosity = Verbosity::High; else return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" ); return ParserResult::ok( ParseResultType::Matched ); }; auto const setReporter = [&]( std::string const& reporter ) { IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories(); auto lcReporter = toLower( reporter ); auto result = factories.find( lcReporter ); if( factories.end() != result ) config.reporterName = lcReporter; else return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" ); return ParserResult::ok( ParseResultType::Matched ); }; auto cli = ExeName( config.processName ) | Help( config.showHelp ) | Opt( config.listTests ) ["-l"]["--list-tests"] ( "list all/matching test cases" ) | Opt( config.listTags ) ["-t"]["--list-tags"] ( "list all/matching tags" ) | Opt( config.showSuccessfulTests ) ["-s"]["--success"] ( "include successful tests in output" ) | Opt( config.shouldDebugBreak ) ["-b"]["--break"] ( "break into debugger on failure" ) | Opt( config.noThrow ) ["-e"]["--nothrow"] ( "skip exception tests" ) | Opt( config.showInvisibles ) ["-i"]["--invisibles"] ( "show invisibles (tabs, newlines)" ) | Opt( config.outputFilename, "filename" ) ["-o"]["--out"] ( "output filename" ) | Opt( setReporter, "name" ) ["-r"]["--reporter"] ( "reporter to use (defaults to console)" ) | Opt( config.name, "name" ) ["-n"]["--name"] ( "suite name" ) | Opt( [&]( bool ){ config.abortAfter = 1; } ) ["-a"]["--abort"] ( "abort at first failure" ) | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" ) ["-x"]["--abortx"] ( "abort after x failures" ) | Opt( setWarning, "warning name" ) ["-w"]["--warn"] ( "enable warnings" ) | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" ) ["-d"]["--durations"] ( "show test durations" ) | Opt( loadTestNamesFromFile, "filename" ) ["-f"]["--input-file"] ( "load test names to run from a file" ) | Opt( config.filenamesAsTags ) ["-#"]["--filenames-as-tags"] ( "adds a tag for the filename" ) | Opt( config.sectionsToRun, "section name" ) ["-c"]["--section"] ( "specify section to run" ) | Opt( setVerbosity, "quiet|normal|high" ) ["-v"]["--verbosity"] ( "set output verbosity" ) | Opt( config.listTestNamesOnly ) ["--list-test-names-only"] ( "list all/matching test cases names only" ) | Opt( config.listReporters ) ["--list-reporters"] ( "list all reporters" ) | Opt( setTestOrder, "decl|lex|rand" ) ["--order"] ( "test case order (defaults to decl)" ) | Opt( setRngSeed, "'time'|number" ) ["--rng-seed"] ( "set a specific seed for random numbers" ) | Opt( setColourUsage, "yes|no" ) ["--use-colour"] ( "should output be colourised" ) | Opt( config.libIdentify ) ["--libidentify"] ( "report name and version according to libidentify standard" ) | Opt( setWaitForKeypress, "start|exit|both" ) ["--wait-for-keypress"] ( "waits for a keypress before exiting" ) | Opt( config.benchmarkResolutionMultiple, "multiplier" ) ["--benchmark-resolution-multiple"] ( "multiple of clock resolution to run benchmarks" ) | Arg( config.testsOrTags, "test name|pattern|tags" ) ( "which test or tests to use" ); return cli; } } // end namespace Catch // end catch_commandline.cpp // start catch_common.cpp #include <cstring> #include <ostream> namespace Catch { bool SourceLineInfo::empty() const noexcept { return file[0] == '\0'; } bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept { return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0); } bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept { // We can assume that the same file will usually have the same pointer. // Thus, if the pointers are the same, there is no point in calling the strcmp return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0)); } std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) { #ifndef __GNUG__ os << info.file << '(' << info.line << ')'; #else os << info.file << ':' << info.line; #endif return os; } std::string StreamEndStop::operator+() const { return std::string(); } NonCopyable::NonCopyable() = default; NonCopyable::~NonCopyable() = default; } // end catch_common.cpp // start catch_config.cpp namespace Catch { Config::Config( ConfigData const& data ) : m_data( data ), m_stream( openStream() ) { TestSpecParser parser(ITagAliasRegistry::get()); if (data.testsOrTags.empty()) { parser.parse("~[.]"); // All not hidden tests } else { m_hasTestFilters = true; for( auto const& testOrTags : data.testsOrTags ) parser.parse( testOrTags ); } m_testSpec = parser.testSpec(); } std::string const& Config::getFilename() const { return m_data.outputFilename ; } bool Config::listTests() const { return m_data.listTests; } bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; } bool Config::listTags() const { return m_data.listTags; } bool Config::listReporters() const { return m_data.listReporters; } std::string Config::getProcessName() const { return m_data.processName; } std::string const& Config::getReporterName() const { return m_data.reporterName; } std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; } std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; } TestSpec const& Config::testSpec() const { return m_testSpec; } bool Config::hasTestFilters() const { return m_hasTestFilters; } bool Config::showHelp() const { return m_data.showHelp; } // IConfig interface bool Config::allowThrows() const { return !m_data.noThrow; } std::ostream& Config::stream() const { return m_stream->stream(); } std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; } bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; } bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); } bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); } ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; } RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; } unsigned int Config::rngSeed() const { return m_data.rngSeed; } int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; } UseColour::YesOrNo Config::useColour() const { return m_data.useColour; } bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; } int Config::abortAfter() const { return m_data.abortAfter; } bool Config::showInvisibles() const { return m_data.showInvisibles; } Verbosity Config::verbosity() const { return m_data.verbosity; } IStream const* Config::openStream() { return Catch::makeStream(m_data.outputFilename); } } // end namespace Catch // end catch_config.cpp // start catch_console_colour.cpp #if defined(__clang__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wexit-time-destructors" #endif // start catch_errno_guard.h namespace Catch { class ErrnoGuard { public: ErrnoGuard(); ~ErrnoGuard(); private: int m_oldErrno; }; } // end catch_errno_guard.h #include <sstream> namespace Catch { namespace { struct IColourImpl { virtual ~IColourImpl() = default; virtual void use( Colour::Code _colourCode ) = 0; }; struct NoColourImpl : IColourImpl { void use( Colour::Code ) {} static IColourImpl* instance() { static NoColourImpl s_instance; return &s_instance; } }; } // anon namespace } // namespace Catch #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI ) # ifdef CATCH_PLATFORM_WINDOWS # define CATCH_CONFIG_COLOUR_WINDOWS # else # define CATCH_CONFIG_COLOUR_ANSI # endif #endif #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) ///////////////////////////////////////// namespace Catch { namespace { class Win32ColourImpl : public IColourImpl { public: Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) ) { CONSOLE_SCREEN_BUFFER_INFO csbiInfo; GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo ); originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY ); originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY ); } virtual void use( Colour::Code _colourCode ) override { switch( _colourCode ) { case Colour::None: return setTextAttribute( originalForegroundAttributes ); case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); case Colour::Red: return setTextAttribute( FOREGROUND_RED ); case Colour::Green: return setTextAttribute( FOREGROUND_GREEN ); case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE ); case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN ); case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN ); case Colour::Grey: return setTextAttribute( 0 ); case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY ); case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED ); case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN ); case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN ); case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" ); default: CATCH_ERROR( "Unknown colour requested" ); } } private: void setTextAttribute( WORD _textAttribute ) { SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes ); } HANDLE stdoutHandle; WORD originalForegroundAttributes; WORD originalBackgroundAttributes; }; IColourImpl* platformColourInstance() { static Win32ColourImpl s_instance; IConfigPtr config = getCurrentContext().getConfig(); UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto; if( colourMode == UseColour::Auto ) colourMode = UseColour::Yes; return colourMode == UseColour::Yes ? &s_instance : NoColourImpl::instance(); } } // end anon namespace } // end namespace Catch #elif defined( CATCH_CONFIG_COLOUR_ANSI ) ////////////////////////////////////// #include <unistd.h> namespace Catch { namespace { // use POSIX/ ANSI console terminal codes // Thanks to Adam Strzelecki for original contribution // (http://github.com/nanoant) // https://github.com/philsquared/Catch/pull/131 class PosixColourImpl : public IColourImpl { public: virtual void use( Colour::Code _colourCode ) override { switch( _colourCode ) { case Colour::None: case Colour::White: return setColour( "[0m" ); case Colour::Red: return setColour( "[0;31m" ); case Colour::Green: return setColour( "[0;32m" ); case Colour::Blue: return setColour( "[0;34m" ); case Colour::Cyan: return setColour( "[0;36m" ); case Colour::Yellow: return setColour( "[0;33m" ); case Colour::Grey: return setColour( "[1;30m" ); case Colour::LightGrey: return setColour( "[0;37m" ); case Colour::BrightRed: return setColour( "[1;31m" ); case Colour::BrightGreen: return setColour( "[1;32m" ); case Colour::BrightWhite: return setColour( "[1;37m" ); case Colour::BrightYellow: return setColour( "[1;33m" ); case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" ); default: CATCH_INTERNAL_ERROR( "Unknown colour requested" ); } } static IColourImpl* instance() { static PosixColourImpl s_instance; return &s_instance; } private: void setColour( const char* _escapeCode ) { getCurrentContext().getConfig()->stream() << '\033' << _escapeCode; } }; bool useColourOnPlatform() { return #ifdef CATCH_PLATFORM_MAC !isDebuggerActive() && #endif #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__)) isatty(STDOUT_FILENO) #else false #endif ; } IColourImpl* platformColourInstance() { ErrnoGuard guard; IConfigPtr config = getCurrentContext().getConfig(); UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto; if( colourMode == UseColour::Auto ) colourMode = useColourOnPlatform() ? UseColour::Yes : UseColour::No; return colourMode == UseColour::Yes ? PosixColourImpl::instance() : NoColourImpl::instance(); } } // end anon namespace } // end namespace Catch #else // not Windows or ANSI /////////////////////////////////////////////// namespace Catch { static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); } } // end namespace Catch #endif // Windows/ ANSI/ None namespace Catch { Colour::Colour( Code _colourCode ) { use( _colourCode ); } Colour::Colour( Colour&& rhs ) noexcept { m_moved = rhs.m_moved; rhs.m_moved = true; } Colour& Colour::operator=( Colour&& rhs ) noexcept { m_moved = rhs.m_moved; rhs.m_moved = true; return *this; } Colour::~Colour(){ if( !m_moved ) use( None ); } void Colour::use( Code _colourCode ) { static IColourImpl* impl = platformColourInstance(); impl->use( _colourCode ); } std::ostream& operator << ( std::ostream& os, Colour const& ) { return os; } } // end namespace Catch #if defined(__clang__) # pragma clang diagnostic pop #endif // end catch_console_colour.cpp // start catch_context.cpp namespace Catch { class Context : public IMutableContext, NonCopyable { public: // IContext virtual IResultCapture* getResultCapture() override { return m_resultCapture; } virtual IRunner* getRunner() override { return m_runner; } virtual IConfigPtr const& getConfig() const override { return m_config; } virtual ~Context() override; public: // IMutableContext virtual void setResultCapture( IResultCapture* resultCapture ) override { m_resultCapture = resultCapture; } virtual void setRunner( IRunner* runner ) override { m_runner = runner; } virtual void setConfig( IConfigPtr const& config ) override { m_config = config; } friend IMutableContext& getCurrentMutableContext(); private: IConfigPtr m_config; IRunner* m_runner = nullptr; IResultCapture* m_resultCapture = nullptr; }; IMutableContext *IMutableContext::currentContext = nullptr; void IMutableContext::createContext() { currentContext = new Context(); } void cleanUpContext() { delete IMutableContext::currentContext; IMutableContext::currentContext = nullptr; } IContext::~IContext() = default; IMutableContext::~IMutableContext() = default; Context::~Context() = default; } // end catch_context.cpp // start catch_debug_console.cpp // start catch_debug_console.h #include <string> namespace Catch { void writeToDebugConsole( std::string const& text ); } // end catch_debug_console.h #ifdef CATCH_PLATFORM_WINDOWS namespace Catch { void writeToDebugConsole( std::string const& text ) { ::OutputDebugStringA( text.c_str() ); } } #else namespace Catch { void writeToDebugConsole( std::string const& text ) { // !TBD: Need a version for Mac/ XCode and other IDEs Catch::cout() << text; } } #endif // Platform // end catch_debug_console.cpp // start catch_debugger.cpp #ifdef CATCH_PLATFORM_MAC # include <assert.h> # include <stdbool.h> # include <sys/types.h> # include <unistd.h> # include <sys/sysctl.h> # include <cstddef> # include <ostream> namespace Catch { // The following function is taken directly from the following technical note: // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html // Returns true if the current process is being debugged (either // running under the debugger or has a debugger attached post facto). bool isDebuggerActive(){ int mib[4]; struct kinfo_proc info; std::size_t size; // Initialize the flags so that, if sysctl fails for some bizarre // reason, we get a predictable result. info.kp_proc.p_flag = 0; // Initialize mib, which tells sysctl the info we want, in this case // we're looking for information about a specific process ID. mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); // Call sysctl. size = sizeof(info); if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) { Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl; return false; } // We're being debugged if the P_TRACED flag is set. return ( (info.kp_proc.p_flag & P_TRACED) != 0 ); } } // namespace Catch #elif defined(CATCH_PLATFORM_LINUX) #include <fstream> #include <string> namespace Catch{ // The standard POSIX way of detecting a debugger is to attempt to // ptrace() the process, but this needs to be done from a child and not // this process itself to still allow attaching to this process later // if wanted, so is rather heavy. Under Linux we have the PID of the // "debugger" (which doesn't need to be gdb, of course, it could also // be strace, for example) in /proc/$PID/status, so just get it from // there instead. bool isDebuggerActive(){ // Libstdc++ has a bug, where std::ifstream sets errno to 0 // This way our users can properly assert over errno values ErrnoGuard guard; std::ifstream in("/proc/self/status"); for( std::string line; std::getline(in, line); ) { static const int PREFIX_LEN = 11; if( line.cmp(0, PREFIX_LEN, "TracerPid:\t") == 0 ) { // We're traced if the PID is not 0 and no other PID starts // with 0 digit, so it's enough to check for just a single // character. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0'; } } return false; } } // namespace Catch #elif defined(_MSC_VER) extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); namespace Catch { bool isDebuggerActive() { return IsDebuggerPresent() != 0; } } #elif defined(__MINGW32__) extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); namespace Catch { bool isDebuggerActive() { return IsDebuggerPresent() != 0; } } #else namespace Catch { bool isDebuggerActive() { return false; } } #endif // Platform // end catch_debugger.cpp // start catch_decomposer.cpp namespace Catch { ITransientExpression::~ITransientExpression() = default; void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) { if( lhs.size() + rhs.size() < 40 && lhs.find('\n') == std::string::npos && rhs.find('\n') == std::string::npos ) os << lhs << " " << op << " " << rhs; else os << lhs << "\n" << op << "\n" << rhs; } } // end catch_decomposer.cpp // start catch_enforce.cpp namespace Catch { #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER) [[noreturn]] void throw_exception(std::exception const& e) { Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n" << "The message was: " << e.what() << '\n'; std::terminate(); } #endif } // namespace Catch; // end catch_enforce.cpp // start catch_errno_guard.cpp #include <cerrno> namespace Catch { ErrnoGuard::ErrnoGuard():m_oldErrno(errno){} ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; } } // end catch_errno_guard.cpp // start catch_exception_translator_registry.cpp // start catch_exception_translator_registry.h #include <vector> #include <string> #include <memory> namespace Catch { class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry { public: ~ExceptionTranslatorRegistry(); virtual void registerTranslator( const IExceptionTranslator* translator ); virtual std::string translateActiveException() const override; std::string tryTranslators() const; private: std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators; }; } // end catch_exception_translator_registry.h #ifdef __OBJC__ #import "Foundation/Foundation.h" #endif namespace Catch { ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() { } void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) { m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) ); } #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) std::string ExceptionTranslatorRegistry::translateActiveException() const { try { #ifdef __OBJC__ // In Objective-C try objective-c exceptions first @try { return tryTranslators(); } @catch (NSException *exception) { return Catch::Detail::stringify( [exception description] ); } #else // Compiling a mixed mode project with MSVC means that CLR // exceptions will be caught in (...) as well. However, these // do not fill-in std::current_exception and thus lead to crash // when attempting rethrow. // /EHa switch also causes structured exceptions to be caught // here, but they fill-in current_exception properly, so // at worst the output should be a little weird, instead of // causing a crash. if (std::current_exception() == nullptr) { return "Non C++ exception. Possibly a CLR exception."; } return tryTranslators(); #endif } catch( TestFailureException& ) { std::rethrow_exception(std::current_exception()); } catch( std::exception& ex ) { return ex.what(); } catch( std::string& msg ) { return msg; } catch( const char* msg ) { return msg; } catch(...) { return "Unknown exception"; } } std::string ExceptionTranslatorRegistry::tryTranslators() const { if (m_translators.empty()) { std::rethrow_exception(std::current_exception()); } else { return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end()); } } #else // ^^ Exceptions are enabled // Exceptions are disabled vv std::string ExceptionTranslatorRegistry::translateActiveException() const { CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!"); } std::string ExceptionTranslatorRegistry::tryTranslators() const { CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!"); } #endif } // end catch_exception_translator_registry.cpp // start catch_fatal_condition.cpp #if defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wmissing-field-initializers" #endif #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS ) namespace { // Report the error condition void reportFatal( char const * const message ) { Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message ); } } #endif // signals/SEH handling #if defined( CATCH_CONFIG_WINDOWS_SEH ) namespace Catch { struct SignalDefs { DWORD id; const char* name; }; // There is no 1-1 mapping between signals and windows exceptions. // Windows can easily distinguish between SO and SigSegV, // but SigInt, SigTerm, etc are handled differently. static SignalDefs signalDefs[] = { { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" }, { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" }, { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" }, { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" }, }; LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) { for (auto const& def : signalDefs) { if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) { reportFatal(def.name); } } // If its not an exception we care about, pass it along. // This stops us from eating debugger breaks etc. return EXCEPTION_CONTINUE_SEARCH; } FatalConditionHandler::FatalConditionHandler() { isSet = true; // 32k seems enough for Catch to handle stack overflow, // but the value was found experimentally, so there is no strong guarantee guaranteeSize = 32 * 1024; exceptionHandlerHandle = nullptr; // Register as first handler in current chain exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException); // Pass in guarantee size to be filled SetThreadStackGuarantee(&guaranteeSize); } void FatalConditionHandler::reset() { if (isSet) { RemoveVectoredExceptionHandler(exceptionHandlerHandle); SetThreadStackGuarantee(&guaranteeSize); exceptionHandlerHandle = nullptr; isSet = false; } } FatalConditionHandler::~FatalConditionHandler() { reset(); } bool FatalConditionHandler::isSet = false; ULONG FatalConditionHandler::guaranteeSize = 0; PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr; } // namespace Catch #elif defined( CATCH_CONFIG_POSIX_SIGNALS ) namespace Catch { struct SignalDefs { int id; const char* name; }; // 32kb for the alternate stack seems to be sufficient. However, this value // is experimentally determined, so that's not guaranteed. constexpr static std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ; static SignalDefs signalDefs[] = { { SIGINT, "SIGINT - Terminal interrupt signal" }, { SIGILL, "SIGILL - Illegal instruction signal" }, { SIGFPE, "SIGFPE - Floating point error signal" }, { SIGSEGV, "SIGSEGV - Segmentation violation signal" }, { SIGTERM, "SIGTERM - Termination request signal" }, { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" } }; void FatalConditionHandler::handleSignal( int sig ) { char const * name = "<unknown signal>"; for (auto const& def : signalDefs) { if (sig == def.id) { name = def.name; break; } } reset(); reportFatal(name); raise( sig ); } FatalConditionHandler::FatalConditionHandler() { isSet = true; stack_t sigStack; sigStack.ss_sp = altStackMem; sigStack.ss_size = sigStackSize; sigStack.ss_flags = 0; sigaltstack(&sigStack, &oldSigStack); struct sigaction sa = { }; sa.sa_handler = handleSignal; sa.sa_flags = SA_ONSTACK; for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) { sigaction(signalDefs[i].id, &sa, &oldSigActions[i]); } } FatalConditionHandler::~FatalConditionHandler() { reset(); } void FatalConditionHandler::reset() { if( isSet ) { // Set signals back to previous values -- hopefully nobody overwrote them in the meantime for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) { sigaction(signalDefs[i].id, &oldSigActions[i], nullptr); } // Return the old stack sigaltstack(&oldSigStack, nullptr); isSet = false; } } bool FatalConditionHandler::isSet = false; struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {}; stack_t FatalConditionHandler::oldSigStack = {}; char FatalConditionHandler::altStackMem[sigStackSize] = {}; } // namespace Catch #else namespace Catch { void FatalConditionHandler::reset() {} } #endif // signals/SEH handling #if defined(__GNUC__) # pragma GCC diagnostic pop #endif // end catch_fatal_condition.cpp // start catch_generators.cpp // start catch_random_number_generator.h #include <algorithm> #include <random> namespace Catch { struct IConfig; std::mt19937& rng(); void seedRng( IConfig const& config ); unsigned int rngSeed(); } // end catch_random_number_generator.h #include <limits> #include <set> namespace Catch { IGeneratorTracker::~IGeneratorTracker() {} const char* GeneratorException::what() const noexcept { return m_msg; } namespace Generators { GeneratorUntypedBase::~GeneratorUntypedBase() {} auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& { return getResultCapture().acquireGeneratorTracker( lineInfo ); } } // namespace Generators } // namespace Catch // end catch_generators.cpp // start catch_interfaces_capture.cpp namespace Catch { IResultCapture::~IResultCapture() = default; } // end catch_interfaces_capture.cpp // start catch_interfaces_config.cpp namespace Catch { IConfig::~IConfig() = default; } // end catch_interfaces_config.cpp // start catch_interfaces_exception.cpp namespace Catch { IExceptionTranslator::~IExceptionTranslator() = default; IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default; } // end catch_interfaces_exception.cpp // start catch_interfaces_registry_hub.cpp namespace Catch { IRegistryHub::~IRegistryHub() = default; IMutableRegistryHub::~IMutableRegistryHub() = default; } // end catch_interfaces_registry_hub.cpp // start catch_interfaces_reporter.cpp // start catch_reporter_listening.h namespace Catch { class ListeningReporter : public IStreamingReporter { using Reporters = std::vector<IStreamingReporterPtr>; Reporters m_listeners; IStreamingReporterPtr m_reporter = nullptr; ReporterPreferences m_preferences; public: ListeningReporter(); void addListener( IStreamingReporterPtr&& listener ); void addReporter( IStreamingReporterPtr&& reporter ); public: // IStreamingReporter ReporterPreferences getPreferences() const override; void noMatchingTestCases( std::string const& spec ) override; static std::set<Verbosity> getSupportedVerbosities(); void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override; void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override; void testRunStarting( TestRunInfo const& testRunInfo ) override; void testGroupStarting( GroupInfo const& groupInfo ) override; void testCaseStarting( TestCaseInfo const& testInfo ) override; void sectionStarting( SectionInfo const& sectionInfo ) override; void assertionStarting( AssertionInfo const& assertionInfo ) override; // The return value indicates if the messages buffer should be cleared: bool assertionEnded( AssertionStats const& assertionStats ) override; void sectionEnded( SectionStats const& sectionStats ) override; void testCaseEnded( TestCaseStats const& testCaseStats ) override; void testGroupEnded( TestGroupStats const& testGroupStats ) override; void testRunEnded( TestRunStats const& testRunStats ) override; void skipTest( TestCaseInfo const& testInfo ) override; bool isMulti() const override; }; } // end namespace Catch // end catch_reporter_listening.h namespace Catch { ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig ) : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {} ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream ) : m_stream( &_stream ), m_fullConfig( _fullConfig ) {} std::ostream& ReporterConfig::stream() const { return *m_stream; } IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; } TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {} GroupInfo::GroupInfo( std::string const& _name, std::size_t _groupIndex, std::size_t _groupsCount ) : name( _name ), groupIndex( _groupIndex ), groupsCounts( _groupsCount ) {} AssertionStats::AssertionStats( AssertionResult const& _assertionResult, std::vector<MessageInfo> const& _infoMessages, Totals const& _totals ) : assertionResult( _assertionResult ), infoMessages( _infoMessages ), totals( _totals ) { assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression; if( assertionResult.hasMessage() ) { // Copy message into messages list. // !TBD This should have been done earlier, somewhere MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() ); builder << assertionResult.getMessage(); builder.m_info.message = builder.m_stream.str(); infoMessages.push_back( builder.m_info ); } } AssertionStats::~AssertionStats() = default; SectionStats::SectionStats( SectionInfo const& _sectionInfo, Counts const& _assertions, double _durationInSeconds, bool _missingAssertions ) : sectionInfo( _sectionInfo ), assertions( _assertions ), durationInSeconds( _durationInSeconds ), missingAssertions( _missingAssertions ) {} SectionStats::~SectionStats() = default; TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo, Totals const& _totals, std::string const& _stdOut, std::string const& _stdErr, bool _aborting ) : testInfo( _testInfo ), totals( _totals ), stdOut( _stdOut ), stdErr( _stdErr ), aborting( _aborting ) {} TestCaseStats::~TestCaseStats() = default; TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo, Totals const& _totals, bool _aborting ) : groupInfo( _groupInfo ), totals( _totals ), aborting( _aborting ) {} TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo ) : groupInfo( _groupInfo ), aborting( false ) {} TestGroupStats::~TestGroupStats() = default; TestRunStats::TestRunStats( TestRunInfo const& _runInfo, Totals const& _totals, bool _aborting ) : runInfo( _runInfo ), totals( _totals ), aborting( _aborting ) {} TestRunStats::~TestRunStats() = default; void IStreamingReporter::fatalErrorEncountered( StringRef ) {} bool IStreamingReporter::isMulti() const { return false; } IReporterFactory::~IReporterFactory() = default; IReporterRegistry::~IReporterRegistry() = default; } // end namespace Catch // end catch_interfaces_reporter.cpp // start catch_interfaces_runner.cpp namespace Catch { IRunner::~IRunner() = default; } // end catch_interfaces_runner.cpp // start catch_interfaces_testcase.cpp namespace Catch { ITestInvoker::~ITestInvoker() = default; ITestCaseRegistry::~ITestCaseRegistry() = default; } // end catch_interfaces_testcase.cpp // start catch_leak_detector.cpp #ifdef CATCH_CONFIG_WINDOWS_CRTDBG #include <crtdbg.h> namespace Catch { LeakDetector::LeakDetector() { int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); flag |= _CRTDBG_LEAK_CHECK_DF; flag |= _CRTDBG_ALLOC_MEM_DF; _CrtSetDbgFlag(flag); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); // Change this to leaking allocation's number to break there _CrtSetBreakAlloc(-1); } } #else Catch::LeakDetector::LeakDetector() {} #endif Catch::LeakDetector::~LeakDetector() { Catch::cleanUp(); } // end catch_leak_detector.cpp // start catch_list.cpp // start catch_list.h #include <set> namespace Catch { std::size_t listTests( Config const& config ); std::size_t listTestsNamesOnly( Config const& config ); struct TagInfo { void add( std::string const& spelling ); std::string all() const; std::set<std::string> spellings; std::size_t count = 0; }; std::size_t listTags( Config const& config ); std::size_t listReporters(); Option<std::size_t> list( Config const& config ); } // end namespace Catch // end catch_list.h // start catch_text.h namespace Catch { using namespace clara::TextFlow; } // end catch_text.h #include <limits> #include <algorithm> #include <iomanip> namespace Catch { std::size_t listTests( Config const& config ) { TestSpec testSpec = config.testSpec(); if( config.hasTestFilters() ) Catch::cout() << "Matching test cases:\n"; else { Catch::cout() << "All available test cases:\n"; } auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); for( auto const& testCaseInfo : matchedTestCases ) { Colour::Code colour = testCaseInfo.isHidden() ? Colour::SecondaryText : Colour::None; Colour colourGuard( colour ); Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n"; if( config.verbosity() >= Verbosity::High ) { Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl; std::string description = testCaseInfo.description; if( description.empty() ) description = "(NO DESCRIPTION)"; Catch::cout() << Column( description ).indent(4) << std::endl; } if( !testCaseInfo.tags.empty() ) Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n"; } if( !config.hasTestFilters() ) Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl; else Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl; return matchedTestCases.size(); } std::size_t listTestsNamesOnly( Config const& config ) { TestSpec testSpec = config.testSpec(); std::size_t matchedTests = 0; std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); for( auto const& testCaseInfo : matchedTestCases ) { matchedTests++; if( startsWith( testCaseInfo.name, '#' ) ) Catch::cout() << '"' << testCaseInfo.name << '"'; else Catch::cout() << testCaseInfo.name; if ( config.verbosity() >= Verbosity::High ) Catch::cout() << "\t@" << testCaseInfo.lineInfo; Catch::cout() << std::endl; } return matchedTests; } void TagInfo::add( std::string const& spelling ) { ++count; spellings.insert( spelling ); } std::string TagInfo::all() const { std::string out; for( auto const& spelling : spellings ) out += "[" + spelling + "]"; return out; } std::size_t listTags( Config const& config ) { TestSpec testSpec = config.testSpec(); if( config.hasTestFilters() ) Catch::cout() << "Tags for matching test cases:\n"; else { Catch::cout() << "All available tags:\n"; } std::map<std::string, TagInfo> tagCounts; std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); for( auto const& testCase : matchedTestCases ) { for( auto const& tagName : testCase.getTestCaseInfo().tags ) { std::string lcaseTagName = toLower( tagName ); auto countIt = tagCounts.find( lcaseTagName ); if( countIt == tagCounts.end() ) countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first; countIt->second.add( tagName ); } } for( auto const& tagCount : tagCounts ) { ReusableStringStream rss; rss << " " << std::setw(2) << tagCount.second.count << " "; auto str = rss.str(); auto wrapper = Column( tagCount.second.all() ) .initialIndent( 0 ) .indent( str.size() ) .width( CATCH_CONFIG_CONSOLE_WIDTH-10 ); Catch::cout() << str << wrapper << '\n'; } Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl; return tagCounts.size(); } std::size_t listReporters() { Catch::cout() << "Available reporters:\n"; IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories(); std::size_t maxNameLen = 0; for( auto const& factoryKvp : factories ) maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() ); for( auto const& factoryKvp : factories ) { Catch::cout() << Column( factoryKvp.first + ":" ) .indent(2) .width( 5+maxNameLen ) + Column( factoryKvp.second->getDescription() ) .initialIndent(0) .indent(2) .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) << "\n"; } Catch::cout() << std::endl; return factories.size(); } Option<std::size_t> list( Config const& config ) { Option<std::size_t> listedCount; if( config.listTests() ) listedCount = listedCount.valueOr(0) + listTests( config ); if( config.listTestNamesOnly() ) listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config ); if( config.listTags() ) listedCount = listedCount.valueOr(0) + listTags( config ); if( config.listReporters() ) listedCount = listedCount.valueOr(0) + listReporters(); return listedCount; } } // end namespace Catch // end catch_list.cpp // start catch_matchers.cpp namespace Catch { namespace Matchers { namespace Impl { std::string MatcherUntypedBase::toString() const { if( m_cachedToString.empty() ) m_cachedToString = describe(); return m_cachedToString; } MatcherUntypedBase::~MatcherUntypedBase() = default; } // namespace Impl } // namespace Matchers using namespace Matchers; using Matchers::Impl::MatcherBase; } // namespace Catch // end catch_matchers.cpp // start catch_matchers_floating.cpp // start catch_polyfills.hpp namespace Catch { bool isnan(float f); bool isnan(double d); } // end catch_polyfills.hpp // start catch_to_string.hpp #include <string> namespace Catch { template <typename T> std::string to_string(T const& t) { #if defined(CATCH_CONFIG_CPP11_TO_STRING) return std::to_string(t); #else ReusableStringStream rss; rss << t; return rss.str(); #endif } } // end namespace Catch // end catch_to_string.hpp #include <cstdlib> #include <cstdint> #include <cstring> namespace Catch { namespace Matchers { namespace Floating { enum class FloatingPointKind : uint8_t { Float, Double }; } } } namespace { template <typename T> struct Converter; template <> struct Converter<float> { static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated"); Converter(float f) { std::memcpy(&i, &f, sizeof(f)); } int32_t i; }; template <> struct Converter<double> { static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated"); Converter(double d) { std::memcpy(&i, &d, sizeof(d)); } int64_t i; }; template <typename T> auto convert(T t) -> Converter<T> { return Converter<T>(t); } template <typename FP> bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) { // Comparison with NaN should always be false. // This way we can rule it out before getting into the ugly details if (Catch::isnan(lhs) || Catch::isnan(rhs)) { return false; } auto lc = convert(lhs); auto rc = convert(rhs); if ((lc.i < 0) != (rc.i < 0)) { // Potentially we can have +0 and -0 return lhs == rhs; } auto ulpDiff = std::abs(lc.i - rc.i); return ulpDiff <= maxUlpDiff; } } namespace Catch { namespace Matchers { namespace Floating { WithinAbsMatcher::WithinAbsMatcher(double target, double margin) :m_target{ target }, m_margin{ margin } { CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.' << " Margin has to be non-negative."); } // Performs equivalent check of std::fabs(lhs - rhs) <= margin // But without the subtraction to allow for INFINITY in comparison bool WithinAbsMatcher::match(double const& matchee) const { return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee); } std::string WithinAbsMatcher::describe() const { return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target); } WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType) :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } { CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.' << " ULPs have to be non-negative."); } #if defined(__clang__) #pragma clang diagnostic push // Clang <3.5 reports on the default branch in the switch below #pragma clang diagnostic ignored "-Wunreachable-code" #endif bool WithinUlpsMatcher::match(double const& matchee) const { switch (m_type) { case FloatingPointKind::Float: return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps); case FloatingPointKind::Double: return almostEqualUlps<double>(matchee, m_target, m_ulps); default: CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" ); } } #if defined(__clang__) #pragma clang diagnostic pop #endif std::string WithinUlpsMatcher::describe() const { return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : ""); } }// namespace Floating Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) { return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double); } Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) { return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float); } Floating::WithinAbsMatcher WithinAbs(double target, double margin) { return Floating::WithinAbsMatcher(target, margin); } } // namespace Matchers } // namespace Catch // end catch_matchers_floating.cpp // start catch_matchers_generic.cpp std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) { if (desc.empty()) { return "matches undescribed predicate"; } else { return "matches predicate: \"" + desc + '"'; } } // end catch_matchers_generic.cpp // start catch_matchers_string.cpp #include <regex> namespace Catch { namespace Matchers { namespace StdString { CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ) : m_caseSensitivity( caseSensitivity ), m_str( adjustString( str ) ) {} std::string CasedString::adjustString( std::string const& str ) const { return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str; } std::string CasedString::caseSensitivitySuffix() const { return m_caseSensitivity == CaseSensitive::No ? " (case insensitive)" : std::string(); } StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator ) : m_comparator( comparator ), m_operation( operation ) { } std::string StringMatcherBase::describe() const { std::string description; description.reserve(5 + m_operation.size() + m_comparator.m_str.size() + m_comparator.caseSensitivitySuffix().size()); description += m_operation; description += ": \""; description += m_comparator.m_str; description += "\""; description += m_comparator.caseSensitivitySuffix(); return description; } EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {} bool EqualsMatcher::match( std::string const& source ) const { return m_comparator.adjustString( source ) == m_comparator.m_str; } ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {} bool ContainsMatcher::match( std::string const& source ) const { return contains( m_comparator.adjustString( source ), m_comparator.m_str ); } StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {} bool StartsWithMatcher::match( std::string const& source ) const { return startsWith( m_comparator.adjustString( source ), m_comparator.m_str ); } EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {} bool EndsWithMatcher::match( std::string const& source ) const { return endsWith( m_comparator.adjustString( source ), m_comparator.m_str ); } RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {} bool RegexMatcher::match(std::string const& matchee) const { auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway if (m_caseSensitivity == CaseSensitive::Choice::No) { flags |= std::regex::icase; } auto reg = std::regex(m_regex, flags); return std::regex_match(matchee, reg); } std::string RegexMatcher::describe() const { return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively"); } } // namespace StdString StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) { return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) ); } StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) { return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) ); } StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) { return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) ); } StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) { return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) ); } StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) { return StdString::RegexMatcher(regex, caseSensitivity); } } // namespace Matchers } // namespace Catch // end catch_matchers_string.cpp // start catch_message.cpp // start catch_uncaught_exceptions.h namespace Catch { bool uncaught_exceptions(); } // end namespace Catch // end catch_uncaught_exceptions.h #include <cassert> #include <stack> namespace Catch { MessageInfo::MessageInfo( StringRef const& _macroName, SourceLineInfo const& _lineInfo, ResultWas::OfType _type ) : macroName( _macroName ), lineInfo( _lineInfo ), type( _type ), sequence( ++globalCount ) {} bool MessageInfo::operator==( MessageInfo const& other ) const { return sequence == other.sequence; } bool MessageInfo::operator<( MessageInfo const& other ) const { return sequence < other.sequence; } // This may need protecting if threading support is added unsigned int MessageInfo::globalCount = 0; //////////////////////////////////////////////////////////////////////////// Catch::MessageBuilder::MessageBuilder( StringRef const& macroName, SourceLineInfo const& lineInfo, ResultWas::OfType type ) :m_info(macroName, lineInfo, type) {} //////////////////////////////////////////////////////////////////////////// ScopedMessage::ScopedMessage( MessageBuilder const& builder ) : m_info( builder.m_info ) { m_info.message = builder.m_stream.str(); getResultCapture().pushScopedMessage( m_info ); } ScopedMessage::~ScopedMessage() { if ( !uncaught_exceptions() ){ getResultCapture().popScopedMessage(m_info); } } Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) { auto trimmed = [&] (size_t start, size_t end) { while (names[start] == ',' || isspace(names[start])) { ++start; } while (names[end] == ',' || isspace(names[end])) { --end; } return names.substr(start, end - start + 1); }; size_t start = 0; std::stack<char> openings; for (size_t pos = 0; pos < names.size(); ++pos) { char c = names[pos]; switch (c) { case '[': case '{': case '(': // It is basically impossible to disambiguate between // comparison and start of template args in this context // case '<': openings.push(c); break; case ']': case '}': case ')': // case '>': openings.pop(); break; case ',': if (start != pos && openings.size() == 0) { m_messages.emplace_back(macroName, lineInfo, resultType); m_messages.back().message = trimmed(start, pos); m_messages.back().message += " := "; start = pos; } } } assert(openings.size() == 0 && "Mismatched openings"); m_messages.emplace_back(macroName, lineInfo, resultType); m_messages.back().message = trimmed(start, names.size() - 1); m_messages.back().message += " := "; } Capturer::~Capturer() { if ( !uncaught_exceptions() ){ assert( m_captured == m_messages.size() ); for( size_t i = 0; i < m_captured; ++i ) m_resultCapture.popScopedMessage( m_messages[i] ); } } void Capturer::captureValue( size_t index, std::string const& value ) { assert( index < m_messages.size() ); m_messages[index].message += value; m_resultCapture.pushScopedMessage( m_messages[index] ); m_captured++; } } // end namespace Catch // end catch_message.cpp // start catch_output_redirect.cpp // start catch_output_redirect.h #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H #include <cstdio> #include <iosfwd> #include <string> namespace Catch { class RedirectedStream { std::ostream& m_originalStream; std::ostream& m_redirectionStream; std::streambuf* m_prevBuf; public: RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream ); ~RedirectedStream(); }; class RedirectedStdOut { ReusableStringStream m_rss; RedirectedStream m_cout; public: RedirectedStdOut(); auto str() const -> std::string; }; // StdErr has two constituent streams in C++, std::cerr and std::clog // This means that we need to redirect 2 streams into 1 to keep proper // order of writes class RedirectedStdErr { ReusableStringStream m_rss; RedirectedStream m_cerr; RedirectedStream m_clog; public: RedirectedStdErr(); auto str() const -> std::string; }; #if defined(CATCH_CONFIG_NEW_CAPTURE) // Windows's implementation of std::tmpfile is terrible (it tries // to create a file inside system folder, thus requiring elevated // privileges for the binary), so we have to use tmpnam(_s) and // create the file ourselves there. class TempFile { public: TempFile(TempFile const&) = delete; TempFile& operator=(TempFile const&) = delete; TempFile(TempFile&&) = delete; TempFile& operator=(TempFile&&) = delete; TempFile(); ~TempFile(); std::FILE* getFile(); std::string getContents(); private: std::FILE* m_file = nullptr; #if defined(_MSC_VER) char m_buffer[L_tmpnam] = { 0 }; #endif }; class OutputRedirect { public: OutputRedirect(OutputRedirect const&) = delete; OutputRedirect& operator=(OutputRedirect const&) = delete; OutputRedirect(OutputRedirect&&) = delete; OutputRedirect& operator=(OutputRedirect&&) = delete; OutputRedirect(std::string& stdout_dest, std::string& stderr_dest); ~OutputRedirect(); private: int m_originalStdout = -1; int m_originalStderr = -1; TempFile m_stdoutFile; TempFile m_stderrFile; std::string& m_stdoutDest; std::string& m_stderrDest; }; #endif } // end namespace Catch #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H // end catch_output_redirect.h #include <cstdio> #include <cstring> #include <fstream> #include <sstream> #include <stdexcept> #if defined(CATCH_CONFIG_NEW_CAPTURE) #if defined(_MSC_VER) #include <io.h> //_dup and _dup2 #define dup _dup #define dup2 _dup2 #define fileno _fileno #else #include <unistd.h> // dup and dup2 #endif #endif namespace Catch { RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream ) : m_originalStream( originalStream ), m_redirectionStream( redirectionStream ), m_prevBuf( m_originalStream.rdbuf() ) { m_originalStream.rdbuf( m_redirectionStream.rdbuf() ); } RedirectedStream::~RedirectedStream() { m_originalStream.rdbuf( m_prevBuf ); } RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {} auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); } RedirectedStdErr::RedirectedStdErr() : m_cerr( Catch::cerr(), m_rss.get() ), m_clog( Catch::clog(), m_rss.get() ) {} auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); } #if defined(CATCH_CONFIG_NEW_CAPTURE) #if defined(_MSC_VER) TempFile::TempFile() { if (tmpnam_s(m_buffer)) { CATCH_RUNTIME_ERROR("Could not get a temp filename"); } if (fopen_s(&m_file, m_buffer, "w")) { char buffer[100]; if (strerror_s(buffer, errno)) { CATCH_RUNTIME_ERROR("Could not translate errno to a string"); } CATCH_RUNTIME_ERROR("Coul dnot open the temp file: '" << m_buffer << "' because: " << buffer); } } #else TempFile::TempFile() { m_file = std::tmpfile(); if (!m_file) { CATCH_RUNTIME_ERROR("Could not create a temp file."); } } #endif TempFile::~TempFile() { // TBD: What to do about errors here? std::fclose(m_file); // We manually create the file on Windows only, on Linux // it will be autodeleted #if defined(_MSC_VER) std::remove(m_buffer); #endif } FILE* TempFile::getFile() { return m_file; } std::string TempFile::getContents() { std::stringstream sstr; char buffer[100] = {}; std::rewind(m_file); while (std::fgets(buffer, sizeof(buffer), m_file)) { sstr << buffer; } return sstr.str(); } OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) : m_originalStdout(dup(1)), m_originalStderr(dup(2)), m_stdoutDest(stdout_dest), m_stderrDest(stderr_dest) { dup2(fileno(m_stdoutFile.getFile()), 1); dup2(fileno(m_stderrFile.getFile()), 2); } OutputRedirect::~OutputRedirect() { Catch::cout() << std::flush; fflush(stdout); // Since we support overriding these streams, we flush cerr // even though std::cerr is unbuffered Catch::cerr() << std::flush; Catch::clog() << std::flush; fflush(stderr); dup2(m_originalStdout, 1); dup2(m_originalStderr, 2); m_stdoutDest += m_stdoutFile.getContents(); m_stderrDest += m_stderrFile.getContents(); } #endif // CATCH_CONFIG_NEW_CAPTURE } // namespace Catch #if defined(CATCH_CONFIG_NEW_CAPTURE) #if defined(_MSC_VER) #undef dup #undef dup2 #undef fileno #endif #endif // end catch_output_redirect.cpp // start catch_polyfills.cpp #include <cmath> namespace Catch { #if !defined(CATCH_CONFIG_POLYFILL_ISNAN) bool isnan(float f) { return std::isnan(f); } bool isnan(double d) { return std::isnan(d); } #else // For now we only use this for embarcadero bool isnan(float f) { return std::_isnan(f); } bool isnan(double d) { return std::_isnan(d); } #endif } // end namespace Catch // end catch_polyfills.cpp // start catch_random_number_generator.cpp namespace Catch { std::mt19937& rng() { static std::mt19937 s_rng; return s_rng; } void seedRng( IConfig const& config ) { if( config.rngSeed() != 0 ) { std::srand( config.rngSeed() ); rng().seed( config.rngSeed() ); } } unsigned int rngSeed() { return getCurrentContext().getConfig()->rngSeed(); } } // end catch_random_number_generator.cpp // start catch_registry_hub.cpp // start catch_test_case_registry_impl.h #include <vector> #include <set> #include <algorithm> #include <ios> namespace Catch { class TestCase; struct IConfig; std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ); bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ); std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ); std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ); class TestRegistry : public ITestCaseRegistry { public: virtual ~TestRegistry() = default; virtual void registerTest( TestCase const& testCase ); std::vector<TestCase> const& getAllTests() const override; std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override; private: std::vector<TestCase> m_functions; mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder; mutable std::vector<TestCase> m_sortedFunctions; std::size_t m_unnamedCount = 0; std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised }; /////////////////////////////////////////////////////////////////////////// class TestInvokerAsFunction : public ITestInvoker { void(*m_testAsFunction)(); public: TestInvokerAsFunction( void(*testAsFunction)() ) noexcept; void invoke() const override; }; std::string extractClassName( StringRef const& classOrQualifiedMethodName ); /////////////////////////////////////////////////////////////////////////// } // end namespace Catch // end catch_test_case_registry_impl.h // start catch_reporter_registry.h #include <map> namespace Catch { class ReporterRegistry : public IReporterRegistry { public: ~ReporterRegistry() override; IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override; void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ); void registerListener( IReporterFactoryPtr const& factory ); FactoryMap const& getFactories() const override; Listeners const& getListeners() const override; private: FactoryMap m_factories; Listeners m_listeners; }; } // end catch_reporter_registry.h // start catch_tag_alias_registry.h // start catch_tag_alias.h #include <string> namespace Catch { struct TagAlias { TagAlias(std::string const& _tag, SourceLineInfo _lineInfo); std::string tag; SourceLineInfo lineInfo; }; } // end namespace Catch // end catch_tag_alias.h #include <map> namespace Catch { class TagAliasRegistry : public ITagAliasRegistry { public: ~TagAliasRegistry() override; TagAlias const* find( std::string const& alias ) const override; std::string expandAliases( std::string const& unexpandedTestSpec ) const override; void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ); private: std::map<std::string, TagAlias> m_registry; }; } // end namespace Catch // end catch_tag_alias_registry.h // start catch_startup_exception_registry.h #include <vector> #include <exception> namespace Catch { class StartupExceptionRegistry { public: void add(std::exception_ptr const& exception) noexcept; std::vector<std::exception_ptr> const& getExceptions() const noexcept; private: std::vector<std::exception_ptr> m_exceptions; }; } // end namespace Catch // end catch_startup_exception_registry.h // start catch_singletons.hpp namespace Catch { struct ISingleton { virtual ~ISingleton(); }; void addSingleton( ISingleton* singleton ); void cleanupSingletons(); template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT> class Singleton : SingletonImplT, public ISingleton { static auto getInternal() -> Singleton* { static Singleton* s_instance = nullptr; if( !s_instance ) { s_instance = new Singleton; addSingleton( s_instance ); } return s_instance; } public: static auto get() -> InterfaceT const& { return *getInternal(); } static auto getMutable() -> MutableInterfaceT& { return *getInternal(); } }; } // namespace Catch // end catch_singletons.hpp namespace Catch { namespace { class RegistryHub : public IRegistryHub, public IMutableRegistryHub, private NonCopyable { public: // IRegistryHub RegistryHub() = default; IReporterRegistry const& getReporterRegistry() const override { return m_reporterRegistry; } ITestCaseRegistry const& getTestCaseRegistry() const override { return m_testCaseRegistry; } IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override { return m_exceptionTranslatorRegistry; } ITagAliasRegistry const& getTagAliasRegistry() const override { return m_tagAliasRegistry; } StartupExceptionRegistry const& getStartupExceptionRegistry() const override { return m_exceptionRegistry; } public: // IMutableRegistryHub void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override { m_reporterRegistry.registerReporter( name, factory ); } void registerListener( IReporterFactoryPtr const& factory ) override { m_reporterRegistry.registerListener( factory ); } void registerTest( TestCase const& testInfo ) override { m_testCaseRegistry.registerTest( testInfo ); } void registerTranslator( const IExceptionTranslator* translator ) override { m_exceptionTranslatorRegistry.registerTranslator( translator ); } void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override { m_tagAliasRegistry.add( alias, tag, lineInfo ); } void registerStartupException() noexcept override { m_exceptionRegistry.add(std::current_exception()); } private: TestRegistry m_testCaseRegistry; ReporterRegistry m_reporterRegistry; ExceptionTranslatorRegistry m_exceptionTranslatorRegistry; TagAliasRegistry m_tagAliasRegistry; StartupExceptionRegistry m_exceptionRegistry; }; } using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>; IRegistryHub const& getRegistryHub() { return RegistryHubSingleton::get(); } IMutableRegistryHub& getMutableRegistryHub() { return RegistryHubSingleton::getMutable(); } void cleanUp() { cleanupSingletons(); cleanUpContext(); } std::string translateActiveException() { return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException(); } } // end namespace Catch // end catch_registry_hub.cpp // start catch_reporter_registry.cpp namespace Catch { ReporterRegistry::~ReporterRegistry() = default; IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const { auto it = m_factories.find( name ); if( it == m_factories.end() ) return nullptr; return it->second->create( ReporterConfig( config ) ); } void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) { m_factories.emplace(name, factory); } void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) { m_listeners.push_back( factory ); } IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const { return m_factories; } IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const { return m_listeners; } } // end catch_reporter_registry.cpp // start catch_result_type.cpp namespace Catch { bool isOk( ResultWas::OfType resultType ) { return ( resultType & ResultWas::FailureBit ) == 0; } bool isJustInfo( int flags ) { return flags == ResultWas::Info; } ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) { return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) ); } bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; } bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; } } // end namespace Catch // end catch_result_type.cpp // start catch_run_context.cpp #include <cassert> #include <algorithm> #include <sstream> namespace Catch { namespace Generators { struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker { GeneratorBasePtr m_generator; GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ) : TrackerBase( nameAndLocation, ctx, parent ) {} ~GeneratorTracker(); static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) { std::shared_ptr<GeneratorTracker> tracker; ITracker& currentTracker = ctx.currentTracker(); if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) { assert( childTracker ); assert( childTracker->isGeneratorTracker() ); tracker = std::static_pointer_cast<GeneratorTracker>( childTracker ); } else { tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker ); currentTracker.addChild( tracker ); } if( !ctx.completedCycle() && !tracker->isComplete() ) { tracker->open(); } return *tracker; } // TrackerBase interface bool isGeneratorTracker() const override { return true; } auto hasGenerator() const -> bool override { return !!m_generator; } void close() override { TrackerBase::close(); // Generator interface only finds out if it has another item on atual move if (m_runState == CompletedSuccessfully && m_generator->next()) { m_children.clear(); m_runState = Executing; } } // IGeneratorTracker interface auto getGenerator() const -> GeneratorBasePtr const& override { return m_generator; } void setGenerator( GeneratorBasePtr&& generator ) override { m_generator = std::move( generator ); } }; GeneratorTracker::~GeneratorTracker() {} } RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter) : m_runInfo(_config->name()), m_context(getCurrentMutableContext()), m_config(_config), m_reporter(std::move(reporter)), m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal }, m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions ) { m_context.setRunner(this); m_context.setConfig(m_config); m_context.setResultCapture(this); m_reporter->testRunStarting(m_runInfo); } RunContext::~RunContext() { m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting())); } void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) { m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount)); } void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) { m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting())); } Totals RunContext::runTest(TestCase const& testCase) { Totals prevTotals = m_totals; std::string redirectedCout; std::string redirectedCerr; auto const& testInfo = testCase.getTestCaseInfo(); m_reporter->testCaseStarting(testInfo); m_activeTestCase = &testCase; ITracker& rootTracker = m_trackerContext.startRun(); assert(rootTracker.isSectionTracker()); static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun()); do { m_trackerContext.startCycle(); m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo)); runCurrentTest(redirectedCout, redirectedCerr); } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting()); Totals deltaTotals = m_totals.delta(prevTotals); if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) { deltaTotals.assertions.failed++; deltaTotals.testCases.passed--; deltaTotals.testCases.failed++; } m_totals.testCases += deltaTotals.testCases; m_reporter->testCaseEnded(TestCaseStats(testInfo, deltaTotals, redirectedCout, redirectedCerr, aborting())); m_activeTestCase = nullptr; m_testCaseTracker = nullptr; return deltaTotals; } IConfigPtr RunContext::config() const { return m_config; } IStreamingReporter& RunContext::reporter() const { return *m_reporter; } void RunContext::assertionEnded(AssertionResult const & result) { if (result.getResultType() == ResultWas::Ok) { m_totals.assertions.passed++; m_lastAssertionPassed = true; } else if (!result.isOk()) { m_lastAssertionPassed = false; if( m_activeTestCase->getTestCaseInfo().okToFail() ) m_totals.assertions.failedButOk++; else m_totals.assertions.failed++; } else { m_lastAssertionPassed = true; } // We have no use for the return value (whether messages should be cleared), because messages were made scoped // and should be let to clear themselves out. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals))); // Reset working state resetAssertionInfo(); m_lastResult = result; } void RunContext::resetAssertionInfo() { m_lastAssertionInfo.macroName = StringRef(); m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr; } bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) { ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo)); if (!sectionTracker.isOpen()) return false; m_activeSections.push_back(&sectionTracker); m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo; m_reporter->sectionStarting(sectionInfo); assertions = m_totals.assertions; return true; } auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& { using namespace Generators; GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) ); assert( tracker.isOpen() ); m_lastAssertionInfo.lineInfo = lineInfo; return tracker; } bool RunContext::testForMissingAssertions(Counts& assertions) { if (assertions.total() != 0) return false; if (!m_config->warnAboutMissingAssertions()) return false; if (m_trackerContext.currentTracker().hasChildren()) return false; m_totals.assertions.failed++; assertions.failed++; return true; } void RunContext::sectionEnded(SectionEndInfo const & endInfo) { Counts assertions = m_totals.assertions - endInfo.prevAssertions; bool missingAssertions = testForMissingAssertions(assertions); if (!m_activeSections.empty()) { m_activeSections.back()->close(); m_activeSections.pop_back(); } m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions)); m_messages.clear(); } void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) { if (m_unfinishedSections.empty()) m_activeSections.back()->fail(); else m_activeSections.back()->close(); m_activeSections.pop_back(); m_unfinishedSections.push_back(endInfo); } void RunContext::benchmarkStarting( BenchmarkInfo const& info ) { m_reporter->benchmarkStarting( info ); } void RunContext::benchmarkEnded( BenchmarkStats const& stats ) { m_reporter->benchmarkEnded( stats ); } void RunContext::pushScopedMessage(MessageInfo const & message) { m_messages.push_back(message); } void RunContext::popScopedMessage(MessageInfo const & message) { m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end()); } std::string RunContext::getCurrentTestName() const { return m_activeTestCase ? m_activeTestCase->getTestCaseInfo().name : std::string(); } const AssertionResult * RunContext::getLastResult() const { return &(*m_lastResult); } void RunContext::exceptionEarlyReported() { m_shouldReportUnexpected = false; } void RunContext::handleFatalErrorCondition( StringRef message ) { // First notify reporter that bad things happened m_reporter->fatalErrorEncountered(message); // Don't rebuild the result -- the stringification itself can cause more fatal errors // Instead, fake a result data. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } ); tempResult.message = message; AssertionResult result(m_lastAssertionInfo, tempResult); assertionEnded(result); handleUnfinishedSections(); // Recreate section for test case (as we will lose the one that was in scope) auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name); Counts assertions; assertions.failed = 1; SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false); m_reporter->sectionEnded(testCaseSectionStats); auto const& testInfo = m_activeTestCase->getTestCaseInfo(); Totals deltaTotals; deltaTotals.testCases.failed = 1; deltaTotals.assertions.failed = 1; m_reporter->testCaseEnded(TestCaseStats(testInfo, deltaTotals, std::string(), std::string(), false)); m_totals.testCases.failed++; testGroupEnded(std::string(), m_totals, 1, 1); m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false)); } bool RunContext::lastAssertionPassed() { return m_lastAssertionPassed; } void RunContext::assertionPassed() { m_lastAssertionPassed = true; ++m_totals.assertions.passed; resetAssertionInfo(); } bool RunContext::aborting() const { return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter()); } void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) { auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name); m_reporter->sectionStarting(testCaseSection); Counts prevAssertions = m_totals.assertions; double duration = 0; m_shouldReportUnexpected = true; m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal }; seedRng(*m_config); Timer timer; CATCH_TRY { if (m_reporter->getPreferences().shouldRedirectStdOut) { #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) RedirectedStdOut redirectedStdOut; RedirectedStdErr redirectedStdErr; timer.start(); invokeActiveTestCase(); redirectedCout += redirectedStdOut.str(); redirectedCerr += redirectedStdErr.str(); #else OutputRedirect r(redirectedCout, redirectedCerr); timer.start(); invokeActiveTestCase(); #endif } else { timer.start(); invokeActiveTestCase(); } duration = timer.getElapsedSeconds(); } CATCH_CATCH_ANON (TestFailureException&) { // This just means the test was aborted due to failure } CATCH_CATCH_ALL { // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions // are reported without translation at the point of origin. if( m_shouldReportUnexpected ) { AssertionReaction dummyReaction; handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction ); } } Counts assertions = m_totals.assertions - prevAssertions; bool missingAssertions = testForMissingAssertions(assertions); m_testCaseTracker->close(); handleUnfinishedSections(); m_messages.clear(); SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions); m_reporter->sectionEnded(testCaseSectionStats); } void RunContext::invokeActiveTestCase() { FatalConditionHandler fatalConditionHandler; // Handle signals m_activeTestCase->invoke(); fatalConditionHandler.reset(); } void RunContext::handleUnfinishedSections() { // If sections ended prematurely due to an exception we stored their // infos here so we can tear them down outside the unwind process. for (auto it = m_unfinishedSections.rbegin(), itEnd = m_unfinishedSections.rend(); it != itEnd; ++it) sectionEnded(*it); m_unfinishedSections.clear(); } void RunContext::handleExpr( AssertionInfo const& info, ITransientExpression const& expr, AssertionReaction& reaction ) { m_reporter->assertionStarting( info ); bool negated = isFalseTest( info.resultDisposition ); bool result = expr.getResult() != negated; if( result ) { if (!m_includeSuccessfulResults) { assertionPassed(); } else { reportExpr(info, ResultWas::Ok, &expr, negated); } } else { reportExpr(info, ResultWas::ExpressionFailed, &expr, negated ); populateReaction( reaction ); } } void RunContext::reportExpr( AssertionInfo const &info, ResultWas::OfType resultType, ITransientExpression const *expr, bool negated ) { m_lastAssertionInfo = info; AssertionResultData data( resultType, LazyExpression( negated ) ); AssertionResult assertionResult{ info, data }; assertionResult.m_resultData.lazyExpression.m_transientExpression = expr; assertionEnded( assertionResult ); } void RunContext::handleMessage( AssertionInfo const& info, ResultWas::OfType resultType, StringRef const& message, AssertionReaction& reaction ) { m_reporter->assertionStarting( info ); m_lastAssertionInfo = info; AssertionResultData data( resultType, LazyExpression( false ) ); data.message = message; AssertionResult assertionResult{ m_lastAssertionInfo, data }; assertionEnded( assertionResult ); if( !assertionResult.isOk() ) populateReaction( reaction ); } void RunContext::handleUnexpectedExceptionNotThrown( AssertionInfo const& info, AssertionReaction& reaction ) { handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction); } void RunContext::handleUnexpectedInflightException( AssertionInfo const& info, std::string const& message, AssertionReaction& reaction ) { m_lastAssertionInfo = info; AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) ); data.message = message; AssertionResult assertionResult{ info, data }; assertionEnded( assertionResult ); populateReaction( reaction ); } void RunContext::populateReaction( AssertionReaction& reaction ) { reaction.shouldDebugBreak = m_config->shouldDebugBreak(); reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal); } void RunContext::handleIncomplete( AssertionInfo const& info ) { m_lastAssertionInfo = info; AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) ); data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE"; AssertionResult assertionResult{ info, data }; assertionEnded( assertionResult ); } void RunContext::handleNonExpr( AssertionInfo const &info, ResultWas::OfType resultType, AssertionReaction &reaction ) { m_lastAssertionInfo = info; AssertionResultData data( resultType, LazyExpression( false ) ); AssertionResult assertionResult{ info, data }; assertionEnded( assertionResult ); if( !assertionResult.isOk() ) populateReaction( reaction ); } IResultCapture& getResultCapture() { if (auto* capture = getCurrentContext().getResultCapture()) return *capture; else CATCH_INTERNAL_ERROR("No result capture instance"); } } // end catch_run_context.cpp // start catch_section.cpp namespace Catch { Section::Section( SectionInfo const& info ) : m_info( info ), m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) ) { m_timer.start(); } Section::~Section() { if( m_sectionIncluded ) { SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() }; if( uncaught_exceptions() ) getResultCapture().sectionEndedEarly( endInfo ); else getResultCapture().sectionEnded( endInfo ); } } // This indicates whether the section should be executed or not Section::operator bool() const { return m_sectionIncluded; } } // end namespace Catch // end catch_section.cpp // start catch_section_info.cpp namespace Catch { SectionInfo::SectionInfo ( SourceLineInfo const& _lineInfo, std::string const& _name ) : name( _name ), lineInfo( _lineInfo ) {} } // end namespace Catch // end catch_section_info.cpp // start catch_session.cpp // start catch_session.h #include <memory> namespace Catch { class Session : NonCopyable { public: Session(); ~Session() override; void showHelp() const; void libIdentify(); int applyCommandLine( int argc, char const * const * argv ); #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE) int applyCommandLine( int argc, wchar_t const * const * argv ); #endif void useConfigData( ConfigData const& configData ); template<typename CharT> int run(int argc, CharT const * const argv[]) { if (m_startupExceptions) return 1; int returnCode = applyCommandLine(argc, argv); if (returnCode == 0) returnCode = run(); return returnCode; } int run(); clara::Parser const& cli() const; void cli( clara::Parser const& newParser ); ConfigData& configData(); Config& config(); private: int runInternal(); clara::Parser m_cli; ConfigData m_configData; std::shared_ptr<Config> m_config; bool m_startupExceptions = false; }; } // end namespace Catch // end catch_session.h // start catch_version.h #include <iosfwd> namespace Catch { // Versioning information struct Version { Version( Version const& ) = delete; Version& operator=( Version const& ) = delete; Version( unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber, char const * const _branchName, unsigned int _buildNumber ); unsigned int const majorVersion; unsigned int const minorVersion; unsigned int const patchNumber; // buildNumber is only used if branchName is not null char const * const branchName; unsigned int const buildNumber; friend std::ostream& operator << ( std::ostream& os, Version const& version ); }; Version const& libraryVersion(); } // end catch_version.h #include <cstdlib> #include <iomanip> namespace Catch { namespace { const int MaxExitCode = 255; IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) { auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config); CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'"); return reporter; } IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) { if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) { return createReporter(config->getReporterName(), config); } // On older platforms, returning std::unique_ptr<ListeningReporter> // when the return type is std::unique_ptr<IStreamingReporter> // doesn't compile without a std::move call. However, this causes // a warning on newer platforms. Thus, we have to work around // it a bit and downcast the pointer manually. auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter); auto& multi = static_cast<ListeningReporter&>(*ret); auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners(); for (auto const& listener : listeners) { multi.addListener(listener->create(Catch::ReporterConfig(config))); } multi.addReporter(createReporter(config->getReporterName(), config)); return ret; } Catch::Totals runTests(std::shared_ptr<Config> const& config) { auto reporter = makeReporter(config); RunContext context(config, std::move(reporter)); Totals totals; context.testGroupStarting(config->name(), 1, 1); TestSpec testSpec = config->testSpec(); auto const& allTestCases = getAllTestCasesSorted(*config); for (auto const& testCase : allTestCases) { if (!context.aborting() && matchTest(testCase, testSpec, *config)) totals += context.runTest(testCase); else context.reporter().skipTest(testCase); } if (config->warnAboutNoTests() && totals.testCases.total() == 0) { ReusableStringStream testConfig; bool first = true; for (const auto& input : config->getTestsOrTags()) { if (!first) { testConfig << ' '; } first = false; testConfig << input; } context.reporter().noMatchingTestCases(testConfig.str()); totals.error = -1; } context.testGroupEnded(config->name(), totals, 1, 1); return totals; } void applyFilenamesAsTags(Catch::IConfig const& config) { auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config)); for (auto& testCase : tests) { auto tags = testCase.tags; std::string filename = testCase.lineInfo.file; auto lastSlash = filename.find_last_of("\\/"); if (lastSlash != std::string::npos) { filename.erase(0, lastSlash); filename[0] = '#'; } auto lastDot = filename.find_last_of('.'); if (lastDot != std::string::npos) { filename.erase(lastDot); } tags.push_back(std::move(filename)); setTags(testCase, tags); } } } // anon namespace Session::Session() { static bool alreadyInstantiated = false; if( alreadyInstantiated ) { CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); } CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); } } // There cannot be exceptions at startup in no-exception mode. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions(); if ( !exceptions.empty() ) { m_startupExceptions = true; Colour colourGuard( Colour::Red ); Catch::cerr() << "Errors occurred during startup!" << '\n'; // iterate over all exceptions and notify user for ( const auto& ex_ptr : exceptions ) { try { std::rethrow_exception(ex_ptr); } catch ( std::exception const& ex ) { Catch::cerr() << Column( ex.what() ).indent(2) << '\n'; } } } #endif alreadyInstantiated = true; m_cli = makeCommandLineParser( m_configData ); } Session::~Session() { Catch::cleanUp(); } void Session::showHelp() const { Catch::cout() << "\nCatch v" << libraryVersion() << "\n" << m_cli << std::endl << "For more detailed usage please see the project docs\n" << std::endl; } void Session::libIdentify() { Catch::cout() << std::left << std::setw(16) << "description: " << "A Catch test executable\n" << std::left << std::setw(16) << "category: " << "testframework\n" << std::left << std::setw(16) << "framework: " << "Catch Test\n" << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl; } int Session::applyCommandLine( int argc, char const * const * argv ) { if( m_startupExceptions ) return 1; auto result = m_cli.parse( clara::Args( argc, argv ) ); if( !result ) { Catch::cerr() << Colour( Colour::Red ) << "\nError(s) in input:\n" << Column( result.errorMessage() ).indent( 2 ) << "\n\n"; Catch::cerr() << "Run with -? for usage\n" << std::endl; return MaxExitCode; } if( m_configData.showHelp ) showHelp(); if( m_configData.libIdentify ) libIdentify(); m_config.reset(); return 0; } #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE) int Session::applyCommandLine( int argc, wchar_t const * const * argv ) { char **utf8Argv = new char *[ argc ]; for ( int i = 0; i < argc; ++i ) { int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL ); utf8Argv[ i ] = new char[ bufSize ]; WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL ); } int returnCode = applyCommandLine( argc, utf8Argv ); for ( int i = 0; i < argc; ++i ) delete [] utf8Argv[ i ]; delete [] utf8Argv; return returnCode; } #endif void Session::useConfigData( ConfigData const& configData ) { m_configData = configData; m_config.reset(); } int Session::run() { if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) { Catch::cout() << "...waiting for enter/ return before starting" << std::endl; static_cast<void>(std::getchar()); } int exitCode = runInternal(); if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) { Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl; static_cast<void>(std::getchar()); } return exitCode; } clara::Parser const& Session::cli() const { return m_cli; } void Session::cli( clara::Parser const& newParser ) { m_cli = newParser; } ConfigData& Session::configData() { return m_configData; } Config& Session::config() { if( !m_config ) m_config = std::make_shared<Config>( m_configData ); return *m_config; } int Session::runInternal() { if( m_startupExceptions ) return 1; if (m_configData.showHelp || m_configData.libIdentify) { return 0; } CATCH_TRY { config(); // Force config to be constructed seedRng( *m_config ); if( m_configData.filenamesAsTags ) applyFilenamesAsTags( *m_config ); // Handle list request if( Option<std::size_t> listed = list( config() ) ) return static_cast<int>( *listed ); auto totals = runTests( m_config ); // Note that on unices only the lower 8 bits are usually used, clamping // the return value to 255 prevents false negative when some multiple // of 256 tests has failed return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed))); } #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) catch( std::exception& ex ) { Catch::cerr() << ex.what() << std::endl; return MaxExitCode; } #endif } } // end namespace Catch // end catch_session.cpp // start catch_singletons.cpp #include <vector> namespace Catch { namespace { static auto getSingletons() -> std::vector<ISingleton*>*& { static std::vector<ISingleton*>* g_singletons = nullptr; if( !g_singletons ) g_singletons = new std::vector<ISingleton*>(); return g_singletons; } } ISingleton::~ISingleton() {} void addSingleton(ISingleton* singleton ) { getSingletons()->push_back( singleton ); } void cleanupSingletons() { auto& singletons = getSingletons(); for( auto singleton : *singletons ) delete singleton; delete singletons; singletons = nullptr; } } // namespace Catch // end catch_singletons.cpp // start catch_startup_exception_registry.cpp namespace Catch { void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept { CATCH_TRY { m_exceptions.push_back(exception); } CATCH_CATCH_ALL { // If we run out of memory during start-up there's really not a lot more we can do about it std::terminate(); } } std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept { return m_exceptions; } } // end namespace Catch // end catch_startup_exception_registry.cpp // start catch_stream.cpp #include <cstdio> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <memory> namespace Catch { Catch::IStream::~IStream() = default; namespace detail { namespace { template<typename WriterF, std::size_t bufferSize=256> class StreamBufImpl : public std::streambuf { char data[bufferSize]; WriterF m_writer; public: StreamBufImpl() { setp( data, data + sizeof(data) ); } ~StreamBufImpl() noexcept { StreamBufImpl::sync(); } private: int overflow( int c ) override { sync(); if( c != EOF ) { if( pbase() == epptr() ) m_writer( std::string( 1, static_cast<char>( c ) ) ); else sputc( static_cast<char>( c ) ); } return 0; } int sync() override { if( pbase() != pptr() ) { m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) ); setp( pbase(), epptr() ); } return 0; } }; /////////////////////////////////////////////////////////////////////////// struct OutputDebugWriter { void operator()( std::string const&str ) { writeToDebugConsole( str ); } }; /////////////////////////////////////////////////////////////////////////// class FileStream : public IStream { mutable std::ofstream m_ofs; public: FileStream( StringRef filename ) { m_ofs.open( filename.c_str() ); CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" ); } ~FileStream() override = default; public: // IStream std::ostream& stream() const override { return m_ofs; } }; /////////////////////////////////////////////////////////////////////////// class CoutStream : public IStream { mutable std::ostream m_os; public: // Store the streambuf from cout up-front because // cout may get redirected when running tests CoutStream() : m_os( Catch::cout().rdbuf() ) {} ~CoutStream() override = default; public: // IStream std::ostream& stream() const override { return m_os; } }; /////////////////////////////////////////////////////////////////////////// class DebugOutStream : public IStream { std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf; mutable std::ostream m_os; public: DebugOutStream() : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ), m_os( m_streamBuf.get() ) {} ~DebugOutStream() override = default; public: // IStream std::ostream& stream() const override { return m_os; } }; }} // namespace anon::detail /////////////////////////////////////////////////////////////////////////// auto makeStream( StringRef const &filename ) -> IStream const* { if( filename.empty() ) return new detail::CoutStream(); else if( filename[0] == '%' ) { if( filename == "%debug" ) return new detail::DebugOutStream(); else CATCH_ERROR( "Unrecognised stream: '" << filename << "'" ); } else return new detail::FileStream( filename ); } // This class encapsulates the idea of a pool of ostringstreams that can be reused. struct StringStreams { std::vector<std::unique_ptr<std::ostringstream>> m_streams; std::vector<std::size_t> m_unused; std::ostringstream m_referenceStream; // Used for copy state/ flags from auto add() -> std::size_t { if( m_unused.empty() ) { m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) ); return m_streams.size()-1; } else { auto index = m_unused.back(); m_unused.pop_back(); return index; } } void release( std::size_t index ) { m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state m_unused.push_back(index); } }; ReusableStringStream::ReusableStringStream() : m_index( Singleton<StringStreams>::getMutable().add() ), m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() ) {} ReusableStringStream::~ReusableStringStream() { static_cast<std::ostringstream*>( m_oss )->str(""); m_oss->clear(); Singleton<StringStreams>::getMutable().release( m_index ); } auto ReusableStringStream::str() const -> std::string { return static_cast<std::ostringstream*>( m_oss )->str(); } /////////////////////////////////////////////////////////////////////////// #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions std::ostream& cout() { return std::cout; } std::ostream& cerr() { return std::cerr; } std::ostream& clog() { return std::clog; } #endif } // end catch_stream.cpp // start catch_string_manip.cpp #include <algorithm> #include <ostream> #include <cstring> #include <cctype> namespace Catch { namespace { char toLowerCh(char c) { return static_cast<char>( std::tolower( c ) ); } } bool startsWith( std::string const& s, std::string const& prefix ) { return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin()); } bool startsWith( std::string const& s, char prefix ) { return !s.empty() && s[0] == prefix; } bool endsWith( std::string const& s, std::string const& suffix ) { return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin()); } bool endsWith( std::string const& s, char suffix ) { return !s.empty() && s[s.size()-1] == suffix; } bool contains( std::string const& s, std::string const& infix ) { return s.find( infix ) != std::string::npos; } void toLowerInPlace( std::string& s ) { std::transform( s.begin(), s.end(), s.begin(), toLowerCh ); } std::string toLower( std::string const& s ) { std::string lc = s; toLowerInPlace( lc ); return lc; } std::string trim( std::string const& str ) { static char const* whitespaceChars = "\n\r\t "; std::string::size_type start = str.find_first_not_of( whitespaceChars ); std::string::size_type end = str.find_last_not_of( whitespaceChars ); return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string(); } bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) { bool replaced = false; std::size_t i = str.find( replaceThis ); while( i != std::string::npos ) { replaced = true; str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() ); if( i < str.size()-withThis.size() ) i = str.find( replaceThis, i+withThis.size() ); else i = std::string::npos; } return replaced; } pluralise::pluralise( std::size_t count, std::string const& label ) : m_count( count ), m_label( label ) {} std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) { os << pluraliser.m_count << ' ' << pluraliser.m_label; if( pluraliser.m_count != 1 ) os << 's'; return os; } } // end catch_string_manip.cpp // start catch_stringref.cpp #if defined(__clang__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wexit-time-destructors" #endif #include <ostream> #include <cstring> #include <cstdint> namespace { const uint32_t byte_2_lead = 0xC0; const uint32_t byte_3_lead = 0xE0; const uint32_t byte_4_lead = 0xF0; } namespace Catch { StringRef::StringRef( char const* rawChars ) noexcept : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) ) {} StringRef::operator std::string() const { return std::string( m_start, m_size ); } void StringRef::swap( StringRef& other ) noexcept { std::swap( m_start, other.m_start ); std::swap( m_size, other.m_size ); std::swap( m_data, other.m_data ); } auto StringRef::c_str() const -> char const* { if( isSubstring() ) const_cast<StringRef*>( this )->takeOwnership(); return m_start; } auto StringRef::currentData() const noexcept -> char const* { return m_start; } auto StringRef::isOwned() const noexcept -> bool { return m_data != nullptr; } auto StringRef::isSubstring() const noexcept -> bool { return m_start[m_size] != '\0'; } void StringRef::takeOwnership() { if( !isOwned() ) { m_data = new char[m_size+1]; memcpy( m_data, m_start, m_size ); m_data[m_size] = '\0'; m_start = m_data; } } auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef { if( start < m_size ) return StringRef( m_start+start, size ); else return StringRef(); } auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool { return size() == other.size() && (std::strncmp( m_start, other.m_start, size() ) == 0); } auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool { return !operator==( other ); } auto StringRef::operator[](size_type index) const noexcept -> char { return m_start[index]; } auto StringRef::numberOfCharacters() const noexcept -> size_type { size_type noChars = m_size; // Make adjustments for uft encodings for( size_type i=0; i < m_size; ++i ) { char c = m_start[i]; if( ( c & byte_2_lead ) == byte_2_lead ) { noChars--; if (( c & byte_3_lead ) == byte_3_lead ) noChars--; if( ( c & byte_4_lead ) == byte_4_lead ) noChars--; } } return noChars; } auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string { std::string str; str.reserve( lhs.size() + rhs.size() ); str += lhs; str += rhs; return str; } auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string { return std::string( lhs ) + std::string( rhs ); } auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string { return std::string( lhs ) + std::string( rhs ); } auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& { return os.write(str.currentData(), str.size()); } auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& { lhs.append(rhs.currentData(), rhs.size()); return lhs; } } // namespace Catch #if defined(__clang__) # pragma clang diagnostic pop #endif // end catch_stringref.cpp // start catch_tag_alias.cpp namespace Catch { TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {} } // end catch_tag_alias.cpp // start catch_tag_alias_autoregistrar.cpp namespace Catch { RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) { CATCH_TRY { getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo); } CATCH_CATCH_ALL { // Do not throw when constructing global objects, instead register the exception to be processed later getMutableRegistryHub().registerStartupException(); } } } // end catch_tag_alias_autoregistrar.cpp // start catch_tag_alias_registry.cpp #include <sstream> namespace Catch { TagAliasRegistry::~TagAliasRegistry() {} TagAlias const* TagAliasRegistry::find( std::string const& alias ) const { auto it = m_registry.find( alias ); if( it != m_registry.end() ) return &(it->second); else return nullptr; } std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const { std::string expandedTestSpec = unexpandedTestSpec; for( auto const& registryKvp : m_registry ) { std::size_t pos = expandedTestSpec.find( registryKvp.first ); if( pos != std::string::npos ) { expandedTestSpec = expandedTestSpec.substr( 0, pos ) + registryKvp.second.tag + expandedTestSpec.substr( pos + registryKvp.first.size() ); } } return expandedTestSpec; } void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) { CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'), "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo ); CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second, "error: tag alias, '" << alias << "' already registered.\n" << "\tFirst seen at: " << find(alias)->lineInfo << "\n" << "\tRedefined at: " << lineInfo ); } ITagAliasRegistry::~ITagAliasRegistry() {} ITagAliasRegistry const& ITagAliasRegistry::get() { return getRegistryHub().getTagAliasRegistry(); } } // end namespace Catch // end catch_tag_alias_registry.cpp // start catch_test_case_info.cpp #include <cctype> #include <exception> #include <algorithm> #include <sstream> namespace Catch { namespace { TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) { if( startsWith( tag, '.' ) || tag == "!hide" ) return TestCaseInfo::IsHidden; else if( tag == "!throws" ) return TestCaseInfo::Throws; else if( tag == "!shouldfail" ) return TestCaseInfo::ShouldFail; else if( tag == "!mayfail" ) return TestCaseInfo::MayFail; else if( tag == "!nonportable" ) return TestCaseInfo::NonPortable; else if( tag == "!benchmark" ) return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden ); else return TestCaseInfo::None; } bool isReservedTag( std::string const& tag ) { return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) ); } void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) { CATCH_ENFORCE( !isReservedTag(tag), "Tag name: [" << tag << "] is not allowed.\n" << "Tag names starting with non alpha-numeric characters are reserved\n" << _lineInfo ); } } TestCase makeTestCase( ITestInvoker* _testCase, std::string const& _className, NameAndTags const& nameAndTags, SourceLineInfo const& _lineInfo ) { bool isHidden = false; // Parse out tags std::vector<std::string> tags; std::string desc, tag; bool inTag = false; std::string _descOrTags = nameAndTags.tags; for (char c : _descOrTags) { if( !inTag ) { if( c == '[' ) inTag = true; else desc += c; } else { if( c == ']' ) { TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag ); if( ( prop & TestCaseInfo::IsHidden ) != 0 ) isHidden = true; else if( prop == TestCaseInfo::None ) enforceNotReservedTag( tag, _lineInfo ); tags.push_back( tag ); tag.clear(); inTag = false; } else tag += c; } } if( isHidden ) { tags.push_back( "." ); } TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo ); return TestCase( _testCase, std::move(info) ); } void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) { std::sort(begin(tags), end(tags)); tags.erase(std::unique(begin(tags), end(tags)), end(tags)); testCaseInfo.lcaseTags.clear(); for( auto const& tag : tags ) { std::string lcaseTag = toLower( tag ); testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) ); testCaseInfo.lcaseTags.push_back( lcaseTag ); } testCaseInfo.tags = std::move(tags); } TestCaseInfo::TestCaseInfo( std::string const& _name, std::string const& _className, std::string const& _description, std::vector<std::string> const& _tags, SourceLineInfo const& _lineInfo ) : name( _name ), className( _className ), description( _description ), lineInfo( _lineInfo ), properties( None ) { setTags( *this, _tags ); } bool TestCaseInfo::isHidden() const { return ( properties & IsHidden ) != 0; } bool TestCaseInfo::throws() const { return ( properties & Throws ) != 0; } bool TestCaseInfo::okToFail() const { return ( properties & (ShouldFail | MayFail ) ) != 0; } bool TestCaseInfo::expectedToFail() const { return ( properties & (ShouldFail ) ) != 0; } std::string TestCaseInfo::tagsAsString() const { std::string ret; // '[' and ']' per tag std::size_t full_size = 2 * tags.size(); for (const auto& tag : tags) { full_size += tag.size(); } ret.reserve(full_size); for (const auto& tag : tags) { ret.push_back('['); ret.append(tag); ret.push_back(']'); } return ret; } TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {} TestCase TestCase::withName( std::string const& _newName ) const { TestCase other( *this ); other.name = _newName; return other; } void TestCase::invoke() const { test->invoke(); } bool TestCase::operator == ( TestCase const& other ) const { return test.get() == other.test.get() && name == other.name && className == other.className; } bool TestCase::operator < ( TestCase const& other ) const { return name < other.name; } TestCaseInfo const& TestCase::getTestCaseInfo() const { return *this; } } // end namespace Catch // end catch_test_case_info.cpp // start catch_test_case_registry_impl.cpp #include <sstream> namespace Catch { std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) { std::vector<TestCase> sorted = unsortedTestCases; switch( config.runOrder() ) { case RunTests::InLexicographicalOrder: std::sort( sorted.begin(), sorted.end() ); break; case RunTests::InRandomOrder: seedRng( config ); std::shuffle( sorted.begin(), sorted.end(), rng() ); break; case RunTests::InDeclarationOrder: // already in declaration order break; } return sorted; } bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) { return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() ); } void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) { std::set<TestCase> seenFunctions; for( auto const& function : functions ) { auto prev = seenFunctions.insert( function ); CATCH_ENFORCE( prev.second, "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n" << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n" << "\tRedefined at " << function.getTestCaseInfo().lineInfo ); } } std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) { std::vector<TestCase> filtered; filtered.reserve( testCases.size() ); for( auto const& testCase : testCases ) if( matchTest( testCase, testSpec, config ) ) filtered.push_back( testCase ); return filtered; } std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) { return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config ); } void TestRegistry::registerTest( TestCase const& testCase ) { std::string name = testCase.getTestCaseInfo().name; if( name.empty() ) { ReusableStringStream rss; rss << "Anonymous test case " << ++m_unnamedCount; return registerTest( testCase.withName( rss.str() ) ); } m_functions.push_back( testCase ); } std::vector<TestCase> const& TestRegistry::getAllTests() const { return m_functions; } std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const { if( m_sortedFunctions.empty() ) enforceNoDuplicateTestCases( m_functions ); if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) { m_sortedFunctions = sortTests( config, m_functions ); m_currentSortOrder = config.runOrder(); } return m_sortedFunctions; } /////////////////////////////////////////////////////////////////////////// TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {} void TestInvokerAsFunction::invoke() const { m_testAsFunction(); } std::string extractClassName( StringRef const& classOrQualifiedMethodName ) { std::string className = classOrQualifiedMethodName; if( startsWith( className, '&' ) ) { std::size_t lastColons = className.rfind( "::" ); std::size_t penultimateColons = className.rfind( "::", lastColons-1 ); if( penultimateColons == std::string::npos ) penultimateColons = 1; className = className.substr( penultimateColons, lastColons-penultimateColons ); } return className; } } // end namespace Catch // end catch_test_case_registry_impl.cpp // start catch_test_case_tracker.cpp #include <algorithm> #include <cassert> #include <stdexcept> #include <memory> #include <sstream> #if defined(__clang__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wexit-time-destructors" #endif namespace Catch { namespace TestCaseTracking { NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location ) : name( _name ), location( _location ) {} ITracker::~ITracker() = default; TrackerContext& TrackerContext::instance() { static TrackerContext s_instance; return s_instance; } ITracker& TrackerContext::startRun() { m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr ); m_currentTracker = nullptr; m_runState = Executing; return *m_rootTracker; } void TrackerContext::endRun() { m_rootTracker.reset(); m_currentTracker = nullptr; m_runState = NotStarted; } void TrackerContext::startCycle() { m_currentTracker = m_rootTracker.get(); m_runState = Executing; } void TrackerContext::completeCycle() { m_runState = CompletedCycle; } bool TrackerContext::completedCycle() const { return m_runState == CompletedCycle; } ITracker& TrackerContext::currentTracker() { return *m_currentTracker; } void TrackerContext::setCurrentTracker( ITracker* tracker ) { m_currentTracker = tracker; } TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ) : m_nameAndLocation( nameAndLocation ), m_ctx( ctx ), m_parent( parent ) {} NameAndLocation const& TrackerBase::nameAndLocation() const { return m_nameAndLocation; } bool TrackerBase::isComplete() const { return m_runState == CompletedSuccessfully || m_runState == Failed; } bool TrackerBase::isSuccessfullyCompleted() const { return m_runState == CompletedSuccessfully; } bool TrackerBase::isOpen() const { return m_runState != NotStarted && !isComplete(); } bool TrackerBase::hasChildren() const { return !m_children.empty(); } void TrackerBase::addChild( ITrackerPtr const& child ) { m_children.push_back( child ); } ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) { auto it = std::find_if( m_children.begin(), m_children.end(), [&nameAndLocation]( ITrackerPtr const& tracker ){ return tracker->nameAndLocation().location == nameAndLocation.location && tracker->nameAndLocation().name == nameAndLocation.name; } ); return( it != m_children.end() ) ? *it : nullptr; } ITracker& TrackerBase::parent() { assert( m_parent ); // Should always be non-null except for root return *m_parent; } void TrackerBase::openChild() { if( m_runState != ExecutingChildren ) { m_runState = ExecutingChildren; if( m_parent ) m_parent->openChild(); } } bool TrackerBase::isSectionTracker() const { return false; } bool TrackerBase::isGeneratorTracker() const { return false; } void TrackerBase::open() { m_runState = Executing; moveToThis(); if( m_parent ) m_parent->openChild(); } void TrackerBase::close() { // Close any still open children (e.g. generators) while( &m_ctx.currentTracker() != this ) m_ctx.currentTracker().close(); switch( m_runState ) { case NeedsAnotherRun: break; case Executing: m_runState = CompletedSuccessfully; break; case ExecutingChildren: if( m_children.empty() || m_children.back()->isComplete() ) m_runState = CompletedSuccessfully; break; case NotStarted: case CompletedSuccessfully: case Failed: CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState ); default: CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState ); } moveToParent(); m_ctx.completeCycle(); } void TrackerBase::fail() { m_runState = Failed; if( m_parent ) m_parent->markAsNeedingAnotherRun(); moveToParent(); m_ctx.completeCycle(); } void TrackerBase::markAsNeedingAnotherRun() { m_runState = NeedsAnotherRun; } void TrackerBase::moveToParent() { assert( m_parent ); m_ctx.setCurrentTracker( m_parent ); } void TrackerBase::moveToThis() { m_ctx.setCurrentTracker( this ); } SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ) : TrackerBase( nameAndLocation, ctx, parent ) { if( parent ) { while( !parent->isSectionTracker() ) parent = &parent->parent(); SectionTracker& parentSection = static_cast<SectionTracker&>( *parent ); addNextFilters( parentSection.m_filters ); } } bool SectionTracker::isComplete() const { bool complete = true; if ((m_filters.empty() || m_filters[0] == "") || std::find(m_filters.begin(), m_filters.end(), m_nameAndLocation.name) != m_filters.end()) complete = TrackerBase::isComplete(); return complete; } bool SectionTracker::isSectionTracker() const { return true; } SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) { std::shared_ptr<SectionTracker> section; ITracker& currentTracker = ctx.currentTracker(); if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) { assert( childTracker ); assert( childTracker->isSectionTracker() ); section = std::static_pointer_cast<SectionTracker>( childTracker ); } else { section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker ); currentTracker.addChild( section ); } if( !ctx.completedCycle() ) section->tryOpen(); return *section; } void SectionTracker::tryOpen() { if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) ) open(); } void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) { if( !filters.empty() ) { m_filters.push_back(""); // Root - should never be consulted m_filters.push_back(""); // Test Case - not a section filter m_filters.insert( m_filters.end(), filters.begin(), filters.end() ); } } void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) { if( filters.size() > 1 ) m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() ); } } // namespace TestCaseTracking using TestCaseTracking::ITracker; using TestCaseTracking::TrackerContext; using TestCaseTracking::SectionTracker; } // namespace Catch #if defined(__clang__) # pragma clang diagnostic pop #endif // end catch_test_case_tracker.cpp // start catch_test_registry.cpp namespace Catch { auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* { return new(std::nothrow) TestInvokerAsFunction( testAsFunction ); } NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {} AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept { CATCH_TRY { getMutableRegistryHub() .registerTest( makeTestCase( invoker, extractClassName( classOrMethod ), nameAndTags, lineInfo)); } CATCH_CATCH_ALL { // Do not throw when constructing global objects, instead register the exception to be processed later getMutableRegistryHub().registerStartupException(); } } AutoReg::~AutoReg() = default; } // end catch_test_registry.cpp // start catch_test_spec.cpp #include <algorithm> #include <string> #include <vector> #include <memory> namespace Catch { TestSpec::Pattern::~Pattern() = default; TestSpec::NamePattern::~NamePattern() = default; TestSpec::TagPattern::~TagPattern() = default; TestSpec::ExcludedPattern::~ExcludedPattern() = default; TestSpec::NamePattern::NamePattern( std::string const& name ) : m_wildcardPattern( toLower( name ), CaseSensitive::No ) {} bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const { return m_wildcardPattern.matches( toLower( testCase.name ) ); } TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {} bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const { return std::find(begin(testCase.lcaseTags), end(testCase.lcaseTags), m_tag) != end(testCase.lcaseTags); } TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {} bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); } bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const { // All patterns in a filter must match for the filter to be a match for( auto const& pattern : m_patterns ) { if( !pattern->matches( testCase ) ) return false; } return true; } bool TestSpec::hasFilters() const { return !m_filters.empty(); } bool TestSpec::matches( TestCaseInfo const& testCase ) const { // A TestSpec matches if any filter matches for( auto const& filter : m_filters ) if( filter.matches( testCase ) ) return true; return false; } } // end catch_test_spec.cpp // start catch_test_spec_parser.cpp namespace Catch { TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {} TestSpecParser& TestSpecParser::parse( std::string const& arg ) { m_mode = None; m_exclusion = false; m_start = std::string::npos; m_arg = m_tagAliases->expandAliases( arg ); m_escapeChars.clear(); for( m_pos = 0; m_pos < m_arg.size(); ++m_pos ) visitChar( m_arg[m_pos] ); if( m_mode == Name ) addPattern<TestSpec::NamePattern>(); return *this; } TestSpec TestSpecParser::testSpec() { addFilter(); return m_testSpec; } void TestSpecParser::visitChar( char c ) { if( m_mode == None ) { switch( c ) { case ' ': return; case '~': m_exclusion = true; return; case '[': return startNewMode( Tag, ++m_pos ); case '"': return startNewMode( QuotedName, ++m_pos ); case '\\': return escape(); default: startNewMode( Name, m_pos ); break; } } if( m_mode == Name ) { if( c == ',' ) { addPattern<TestSpec::NamePattern>(); addFilter(); } else if( c == '[' ) { if( subString() == "exclude:" ) m_exclusion = true; else addPattern<TestSpec::NamePattern>(); startNewMode( Tag, ++m_pos ); } else if( c == '\\' ) escape(); } else if( m_mode == EscapedName ) m_mode = Name; else if( m_mode == QuotedName && c == '"' ) addPattern<TestSpec::NamePattern>(); else if( m_mode == Tag && c == ']' ) addPattern<TestSpec::TagPattern>(); } void TestSpecParser::startNewMode( Mode mode, std::size_t start ) { m_mode = mode; m_start = start; } void TestSpecParser::escape() { if( m_mode == None ) m_start = m_pos; m_mode = EscapedName; m_escapeChars.push_back( m_pos ); } std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); } void TestSpecParser::addFilter() { if( !m_currentFilter.m_patterns.empty() ) { m_testSpec.m_filters.push_back( m_currentFilter ); m_currentFilter = TestSpec::Filter(); } } TestSpec parseTestSpec( std::string const& arg ) { return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec(); } } // namespace Catch // end catch_test_spec_parser.cpp // start catch_timer.cpp #include <chrono> static const uint64_t nanosecondsInSecond = 1000000000; namespace Catch { auto getCurrentNanosecondsSinceEpoch() -> uint64_t { return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count(); } namespace { auto estimateClockResolution() -> uint64_t { uint64_t sum = 0; static const uint64_t iterations = 1000000; auto startTime = getCurrentNanosecondsSinceEpoch(); for( std::size_t i = 0; i < iterations; ++i ) { uint64_t ticks; uint64_t baseTicks = getCurrentNanosecondsSinceEpoch(); do { ticks = getCurrentNanosecondsSinceEpoch(); } while( ticks == baseTicks ); auto delta = ticks - baseTicks; sum += delta; // If we have been calibrating for over 3 seconds -- the clock // is terrible and we should move on. // TBD: How to signal that the measured resolution is probably wrong? if (ticks > startTime + 3 * nanosecondsInSecond) { return sum / ( i + 1u ); } } // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers // - and potentially do more iterations if there's a high variance. return sum/iterations; } } auto getEstimatedClockResolution() -> uint64_t { static auto s_resolution = estimateClockResolution(); return s_resolution; } void Timer::start() { m_nanoseconds = getCurrentNanosecondsSinceEpoch(); } auto Timer::getElapsedNanoseconds() const -> uint64_t { return getCurrentNanosecondsSinceEpoch() - m_nanoseconds; } auto Timer::getElapsedMicroseconds() const -> uint64_t { return getElapsedNanoseconds()/1000; } auto Timer::getElapsedMilliseconds() const -> unsigned int { return static_cast<unsigned int>(getElapsedMicroseconds()/1000); } auto Timer::getElapsedSeconds() const -> double { return getElapsedMicroseconds()/1000000.0; } } // namespace Catch // end catch_timer.cpp // start catch_tostring.cpp #if defined(__clang__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wexit-time-destructors" # pragma clang diagnostic ignored "-Wglobal-constructors" #endif // Enable specific decls locally #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER #endif #include <cmath> #include <iomanip> namespace Catch { namespace Detail { const std::string unprintableString = "{?}"; namespace { const int hexThreshold = 255; struct Endianness { enum Arch { Big, Little }; static Arch which() { union _{ int asInt; char asChar[sizeof (int)]; } u; u.asInt = 1; return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little; } }; } std::string rawMemoryToString( const void *object, std::size_t size ) { // Reverse order for little endian architectures int i = 0, end = static_cast<int>( size ), inc = 1; if( Endianness::which() == Endianness::Little ) { i = end-1; end = inc = -1; } unsigned char const *bytes = static_cast<unsigned char const *>(object); ReusableStringStream rss; rss << "0x" << std::setfill('0') << std::hex; for( ; i != end; i += inc ) rss << std::setw(2) << static_cast<unsigned>(bytes[i]); return rss.str(); } } template<typename T> std::string fpToString( T value, int precision ) { if (Catch::isnan(value)) { return "nan"; } ReusableStringStream rss; rss << std::setprecision( precision ) << std::fixed << value; std::string d = rss.str(); std::size_t i = d.find_last_not_of( '0' ); if( i != std::string::npos && i != d.size()-1 ) { if( d[i] == '.' ) i++; d = d.substr( 0, i+1 ); } return d; } //// ======================================================= //// // // Out-of-line defs for full specialization of StringMaker // //// ======================================================= //// std::string StringMaker<std::string>::convert(const std::string& str) { if (!getCurrentContext().getConfig()->showInvisibles()) { return '"' + str + '"'; } std::string s("\""); for (char c : str) { switch (c) { case '\n': s.append("\\n"); break; case '\t': s.append("\\t"); break; default: s.push_back(c); break; } } s.append("\""); return s; } #ifdef CATCH_CONFIG_CPP17_STRING_VIEW std::string StringMaker<std::string_view>::convert(std::string_view str) { return ::Catch::Detail::stringify(std::string{ str }); } #endif std::string StringMaker<char const*>::convert(char const* str) { if (str) { return ::Catch::Detail::stringify(std::string{ str }); } else { return{ "{null string}" }; } } std::string StringMaker<char*>::convert(char* str) { if (str) { return ::Catch::Detail::stringify(std::string{ str }); } else { return{ "{null string}" }; } } #ifdef CATCH_CONFIG_WCHAR std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) { std::string s; s.reserve(wstr.size()); for (auto c : wstr) { s += (c <= 0xff) ? static_cast<char>(c) : '?'; } return ::Catch::Detail::stringify(s); } # ifdef CATCH_CONFIG_CPP17_STRING_VIEW std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) { return StringMaker<std::wstring>::convert(std::wstring(str)); } # endif std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) { if (str) { return ::Catch::Detail::stringify(std::wstring{ str }); } else { return{ "{null string}" }; } } std::string StringMaker<wchar_t *>::convert(wchar_t * str) { if (str) { return ::Catch::Detail::stringify(std::wstring{ str }); } else { return{ "{null string}" }; } } #endif std::string StringMaker<int>::convert(int value) { return ::Catch::Detail::stringify(static_cast<long long>(value)); } std::string StringMaker<long>::convert(long value) { return ::Catch::Detail::stringify(static_cast<long long>(value)); } std::string StringMaker<long long>::convert(long long value) { ReusableStringStream rss; rss << value; if (value > Detail::hexThreshold) { rss << " (0x" << std::hex << value << ')'; } return rss.str(); } std::string StringMaker<unsigned int>::convert(unsigned int value) { return ::Catch::Detail::stringify(static_cast<unsigned long long>(value)); } std::string StringMaker<unsigned long>::convert(unsigned long value) { return ::Catch::Detail::stringify(static_cast<unsigned long long>(value)); } std::string StringMaker<unsigned long long>::convert(unsigned long long value) { ReusableStringStream rss; rss << value; if (value > Detail::hexThreshold) { rss << " (0x" << std::hex << value << ')'; } return rss.str(); } std::string StringMaker<bool>::convert(bool b) { return b ? "true" : "false"; } std::string StringMaker<signed char>::convert(signed char value) { if (value == '\r') { return "'\\r'"; } else if (value == '\f') { return "'\\f'"; } else if (value == '\n') { return "'\\n'"; } else if (value == '\t') { return "'\\t'"; } else if ('\0' <= value && value < ' ') { return ::Catch::Detail::stringify(static_cast<unsigned int>(value)); } else { char chstr[] = "' '"; chstr[1] = value; return chstr; } } std::string StringMaker<char>::convert(char c) { return ::Catch::Detail::stringify(static_cast<signed char>(c)); } std::string StringMaker<unsigned char>::convert(unsigned char c) { return ::Catch::Detail::stringify(static_cast<char>(c)); } std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) { return "nullptr"; } std::string StringMaker<float>::convert(float value) { return fpToString(value, 5) + 'f'; } std::string StringMaker<double>::convert(double value) { return fpToString(value, 10); } std::string ratio_string<std::atto>::symbol() { return "a"; } std::string ratio_string<std::femto>::symbol() { return "f"; } std::string ratio_string<std::pico>::symbol() { return "p"; } std::string ratio_string<std::nano>::symbol() { return "n"; } std::string ratio_string<std::micro>::symbol() { return "u"; } std::string ratio_string<std::milli>::symbol() { return "m"; } } // end namespace Catch #if defined(__clang__) # pragma clang diagnostic pop #endif // end catch_tostring.cpp // start catch_totals.cpp namespace Catch { Counts Counts::operator - ( Counts const& other ) const { Counts diff; diff.passed = passed - other.passed; diff.failed = failed - other.failed; diff.failedButOk = failedButOk - other.failedButOk; return diff; } Counts& Counts::operator += ( Counts const& other ) { passed += other.passed; failed += other.failed; failedButOk += other.failedButOk; return *this; } std::size_t Counts::total() const { return passed + failed + failedButOk; } bool Counts::allPassed() const { return failed == 0 && failedButOk == 0; } bool Counts::allOk() const { return failed == 0; } Totals Totals::operator - ( Totals const& other ) const { Totals diff; diff.assertions = assertions - other.assertions; diff.testCases = testCases - other.testCases; return diff; } Totals& Totals::operator += ( Totals const& other ) { assertions += other.assertions; testCases += other.testCases; return *this; } Totals Totals::delta( Totals const& prevTotals ) const { Totals diff = *this - prevTotals; if( diff.assertions.failed > 0 ) ++diff.testCases.failed; else if( diff.assertions.failedButOk > 0 ) ++diff.testCases.failedButOk; else ++diff.testCases.passed; return diff; } } // end catch_totals.cpp // start catch_uncaught_exceptions.cpp #include <exception> namespace Catch { bool uncaught_exceptions() { #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) return std::uncaught_exceptions() > 0; #else return std::uncaught_exception(); #endif } } // end namespace Catch // end catch_uncaught_exceptions.cpp // start catch_version.cpp #include <ostream> namespace Catch { Version::Version ( unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber, char const * const _branchName, unsigned int _buildNumber ) : majorVersion( _majorVersion ), minorVersion( _minorVersion ), patchNumber( _patchNumber ), branchName( _branchName ), buildNumber( _buildNumber ) {} std::ostream& operator << ( std::ostream& os, Version const& version ) { os << version.majorVersion << '.' << version.minorVersion << '.' << version.patchNumber; // branchName is never null -> 0th char is \0 if it is empty if (version.branchName[0]) { os << '-' << version.branchName << '.' << version.buildNumber; } return os; } Version const& libraryVersion() { static Version version( 2, 6, 0, "", 0 ); return version; } } // end catch_version.cpp // start catch_wildcard_pattern.cpp #include <sstream> namespace Catch { WildcardPattern::WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity ) : m_caseSensitivity( caseSensitivity ), m_pattern( adjustCase( pattern ) ) { if( startsWith( m_pattern, '*' ) ) { m_pattern = m_pattern.substr( 1 ); m_wildcard = WildcardAtStart; } if( endsWith( m_pattern, '*' ) ) { m_pattern = m_pattern.substr( 0, m_pattern.size()-1 ); m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd ); } } bool WildcardPattern::matches( std::string const& str ) const { switch( m_wildcard ) { case NoWildcard: return m_pattern == adjustCase( str ); case WildcardAtStart: return endsWith( adjustCase( str ), m_pattern ); case WildcardAtEnd: return startsWith( adjustCase( str ), m_pattern ); case WildcardAtBothEnds: return contains( adjustCase( str ), m_pattern ); default: CATCH_INTERNAL_ERROR( "Unknown enum" ); } } std::string WildcardPattern::adjustCase( std::string const& str ) const { return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str; } } // end catch_wildcard_pattern.cpp // start catch_xmlwriter.cpp #include <iomanip> using uchar = unsigned char; namespace Catch { namespace { size_t trailingBytes(unsigned char c) { if ((c & 0xE0) == 0xC0) { return 2; } if ((c & 0xF0) == 0xE0) { return 3; } if ((c & 0xF8) == 0xF0) { return 4; } CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); } uint32_t headerValue(unsigned char c) { if ((c & 0xE0) == 0xC0) { return c & 0x1F; } if ((c & 0xF0) == 0xE0) { return c & 0x0F; } if ((c & 0xF8) == 0xF0) { return c & 0x07; } CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); } void hexEscapeChar(std::ostream& os, unsigned char c) { std::ios_base::fmtflags f(os.flags()); os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(c); os.flags(f); } } // anonymous namespace XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat ) : m_str( str ), m_forWhat( forWhat ) {} void XmlEncode::encodeTo( std::ostream& os ) const { // Apostrophe escaping not necessary if we always use " to write attributes // (see: http://www.w3.org/TR/xml/#syntax) for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) { uchar c = m_str[idx]; switch (c) { case '<': os << "&lt;"; break; case '&': os << "&amp;"; break; case '>': // See: http://www.w3.org/TR/xml/#syntax if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']') os << "&gt;"; else os << c; break; case '\"': if (m_forWhat == ForAttributes) os << "&quot;"; else os << c; break; default: // Check for control characters and invalid utf-8 // Escape control characters in standard ascii // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { hexEscapeChar(os, c); break; } // Plain ASCII: Write it to stream if (c < 0x7F) { os << c; break; } // UTF-8 territory // Check if the encoding is valid and if it is not, hex escape bytes. // Important: We do not check the exact decoded values for validity, only the encoding format // First check that this bytes is a valid lead byte: // This means that it is not encoded as 1111 1XXX // Or as 10XX XXXX if (c < 0xC0 || c >= 0xF8) { hexEscapeChar(os, c); break; } auto encBytes = trailingBytes(c); // Are there enough bytes left to avoid accessing out-of-bounds memory? if (idx + encBytes - 1 >= m_str.size()) { hexEscapeChar(os, c); break; } // The header is valid, check data // The next encBytes bytes must together be a valid utf-8 // This means: bitpattern 10XX XXXX and the extracted value is sane (ish) bool valid = true; uint32_t value = headerValue(c); for (std::size_t n = 1; n < encBytes; ++n) { uchar nc = m_str[idx + n]; valid &= ((nc & 0xC0) == 0x80); value = (value << 6) | (nc & 0x3F); } if ( // Wrong bit pattern of following bytes (!valid) || // Overlong encodings (value < 0x80) || (0x80 <= value && value < 0x800 && encBytes > 2) || (0x800 < value && value < 0x10000 && encBytes > 3) || // Encoded value out of range (value >= 0x110000) ) { hexEscapeChar(os, c); break; } // If we got here, this is in fact a valid(ish) utf-8 sequence for (std::size_t n = 0; n < encBytes; ++n) { os << m_str[idx + n]; } idx += encBytes - 1; break; } } } std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { xmlEncode.encodeTo( os ); return os; } XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer ) : m_writer( writer ) {} XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept : m_writer( other.m_writer ){ other.m_writer = nullptr; } XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept { if ( m_writer ) { m_writer->endElement(); } m_writer = other.m_writer; other.m_writer = nullptr; return *this; } XmlWriter::ScopedElement::~ScopedElement() { if( m_writer ) m_writer->endElement(); } XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) { m_writer->writeText( text, indent ); return *this; } XmlWriter::XmlWriter( std::ostream& os ) : m_os( os ) { writeDeclaration(); } XmlWriter::~XmlWriter() { while( !m_tags.empty() ) endElement(); } XmlWriter& XmlWriter::startElement( std::string const& name ) { ensureTagClosed(); newlineIfNecessary(); m_os << m_indent << '<' << name; m_tags.push_back( name ); m_indent += " "; m_tagIsOpen = true; return *this; } XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) { ScopedElement scoped( this ); startElement( name ); return scoped; } XmlWriter& XmlWriter::endElement() { newlineIfNecessary(); m_indent = m_indent.substr( 0, m_indent.size()-2 ); if( m_tagIsOpen ) { m_os << "/>"; m_tagIsOpen = false; } else { m_os << m_indent << "</" << m_tags.back() << ">"; } m_os << std::endl; m_tags.pop_back(); return *this; } XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) { if( !name.empty() && !attribute.empty() ) m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; return *this; } XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) { m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"'; return *this; } XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) { if( !text.empty() ){ bool tagWasOpen = m_tagIsOpen; ensureTagClosed(); if( tagWasOpen && indent ) m_os << m_indent; m_os << XmlEncode( text ); m_needsNewline = true; } return *this; } XmlWriter& XmlWriter::writeComment( std::string const& text ) { ensureTagClosed(); m_os << m_indent << "<!--" << text << "-->"; m_needsNewline = true; return *this; } void XmlWriter::writeStylesheetRef( std::string const& url ) { m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n"; } XmlWriter& XmlWriter::writeBlankLine() { ensureTagClosed(); m_os << '\n'; return *this; } void XmlWriter::ensureTagClosed() { if( m_tagIsOpen ) { m_os << ">" << std::endl; m_tagIsOpen = false; } } void XmlWriter::writeDeclaration() { m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; } void XmlWriter::newlineIfNecessary() { if( m_needsNewline ) { m_os << std::endl; m_needsNewline = false; } } } // end catch_xmlwriter.cpp // start catch_reporter_bases.cpp #include <cstring> #include <cfloat> #include <cstdio> #include <cassert> #include <memory> namespace Catch { void prepareExpandedExpression(AssertionResult& result) { result.getExpandedExpression(); } // Because formatting using c++ streams is stateful, drop down to C is required // Alternatively we could use stringstream, but its performance is... not good. std::string getFormattedDuration( double duration ) { // Max exponent + 1 is required to represent the whole part // + 1 for decimal point // + 3 for the 3 decimal places // + 1 for null terminator const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1; char buffer[maxDoubleSize]; // Save previous errno, to prevent sprintf from overwriting it ErrnoGuard guard; #ifdef _MSC_VER sprintf_s(buffer, "%.3f", duration); #else sprintf(buffer, "%.3f", duration); #endif return std::string(buffer); } TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config) :StreamingReporterBase(_config) {} std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() { return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High }; } void TestEventListenerBase::assertionStarting(AssertionInfo const &) {} bool TestEventListenerBase::assertionEnded(AssertionStats const &) { return false; } } // end namespace Catch // end catch_reporter_bases.cpp // start catch_reporter_compact.cpp namespace { #ifdef CATCH_PLATFORM_MAC const char* failedString() { return "FAILED"; } const char* passedString() { return "PASSED"; } #else const char* failedString() { return "failed"; } const char* passedString() { return "passed"; } #endif // Colour::LightGrey Catch::Colour::Code dimColour() { return Catch::Colour::FileName; } std::string bothOrAll( std::size_t count ) { return count == 1 ? std::string() : count == 2 ? "both " : "all " ; } } // anon namespace namespace Catch { namespace { // Colour, message variants: // - white: No tests ran. // - red: Failed [both/all] N test cases, failed [both/all] M assertions. // - white: Passed [both/all] N test cases (no assertions). // - red: Failed N tests cases, failed M assertions. // - green: Passed [both/all] N tests cases with M assertions. void printTotals(std::ostream& out, const Totals& totals) { if (totals.testCases.total() == 0) { out << "No tests ran."; } else if (totals.testCases.failed == totals.testCases.total()) { Colour colour(Colour::ResultError); const std::string qualify_assertions_failed = totals.assertions.failed == totals.assertions.total() ? bothOrAll(totals.assertions.failed) : std::string(); out << "Failed " << bothOrAll(totals.testCases.failed) << pluralise(totals.testCases.failed, "test case") << ", " "failed " << qualify_assertions_failed << pluralise(totals.assertions.failed, "assertion") << '.'; } else if (totals.assertions.total() == 0) { out << "Passed " << bothOrAll(totals.testCases.total()) << pluralise(totals.testCases.total(), "test case") << " (no assertions)."; } else if (totals.assertions.failed) { Colour colour(Colour::ResultError); out << "Failed " << pluralise(totals.testCases.failed, "test case") << ", " "failed " << pluralise(totals.assertions.failed, "assertion") << '.'; } else { Colour colour(Colour::ResultSuccess); out << "Passed " << bothOrAll(totals.testCases.passed) << pluralise(totals.testCases.passed, "test case") << " with " << pluralise(totals.assertions.passed, "assertion") << '.'; } } // Implementation of CompactReporter formatting class AssertionPrinter { public: AssertionPrinter& operator= (AssertionPrinter const&) = delete; AssertionPrinter(AssertionPrinter const&) = delete; AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages) : stream(_stream) , result(_stats.assertionResult) , messages(_stats.infoMessages) , itMessage(_stats.infoMessages.begin()) , printInfoMessages(_printInfoMessages) {} void print() { printSourceInfo(); itMessage = messages.begin(); switch (result.getResultType()) { case ResultWas::Ok: printResultType(Colour::ResultSuccess, passedString()); printOriginalExpression(); printReconstructedExpression(); if (!result.hasExpression()) printRemainingMessages(Colour::None); else printRemainingMessages(); break; case ResultWas::ExpressionFailed: if (result.isOk()) printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok")); else printResultType(Colour::Error, failedString()); printOriginalExpression(); printReconstructedExpression(); printRemainingMessages(); break; case ResultWas::ThrewException: printResultType(Colour::Error, failedString()); printIssue("unexpected exception with message:"); printMessage(); printExpressionWas(); printRemainingMessages(); break; case ResultWas::FatalErrorCondition: printResultType(Colour::Error, failedString()); printIssue("fatal error condition with message:"); printMessage(); printExpressionWas(); printRemainingMessages(); break; case ResultWas::DidntThrowException: printResultType(Colour::Error, failedString()); printIssue("expected exception, got none"); printExpressionWas(); printRemainingMessages(); break; case ResultWas::Info: printResultType(Colour::None, "info"); printMessage(); printRemainingMessages(); break; case ResultWas::Warning: printResultType(Colour::None, "warning"); printMessage(); printRemainingMessages(); break; case ResultWas::ExplicitFailure: printResultType(Colour::Error, failedString()); printIssue("explicitly"); printRemainingMessages(Colour::None); break; // These cases are here to prevent compiler warnings case ResultWas::Unknown: case ResultWas::FailureBit: case ResultWas::Exception: printResultType(Colour::Error, "** internal error **"); break; } } private: void printSourceInfo() const { Colour colourGuard(Colour::FileName); stream << result.getSourceInfo() << ':'; } void printResultType(Colour::Code colour, std::string const& passOrFail) const { if (!passOrFail.empty()) { { Colour colourGuard(colour); stream << ' ' << passOrFail; } stream << ':'; } } void printIssue(std::string const& issue) const { stream << ' ' << issue; } void printExpressionWas() { if (result.hasExpression()) { stream << ';'; { Colour colour(dimColour()); stream << " expression was:"; } printOriginalExpression(); } } void printOriginalExpression() const { if (result.hasExpression()) { stream << ' ' << result.getExpression(); } } void printReconstructedExpression() const { if (result.hasExpandedExpression()) { { Colour colour(dimColour()); stream << " for: "; } stream << result.getExpandedExpression(); } } void printMessage() { if (itMessage != messages.end()) { stream << " '" << itMessage->message << '\''; ++itMessage; } } void printRemainingMessages(Colour::Code colour = dimColour()) { if (itMessage == messages.end()) return; // using messages.end() directly yields (or auto) compilation error: std::vector<MessageInfo>::const_iterator itEnd = messages.end(); const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd)); { Colour colourGuard(colour); stream << " with " << pluralise(N, "message") << ':'; } for (; itMessage != itEnd; ) { // If this assertion is a warning ignore any INFO messages if (printInfoMessages || itMessage->type != ResultWas::Info) { stream << " '" << itMessage->message << '\''; if (++itMessage != itEnd) { Colour colourGuard(dimColour()); stream << " and"; } } } } private: std::ostream& stream; AssertionResult const& result; std::vector<MessageInfo> messages; std::vector<MessageInfo>::const_iterator itMessage; bool printInfoMessages; }; } // anon namespace std::string CompactReporter::getDescription() { return "Reports test results on a single line, suitable for IDEs"; } ReporterPreferences CompactReporter::getPreferences() const { return m_reporterPrefs; } void CompactReporter::noMatchingTestCases( std::string const& spec ) { stream << "No test cases matched '" << spec << '\'' << std::endl; } void CompactReporter::assertionStarting( AssertionInfo const& ) {} bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) { AssertionResult const& result = _assertionStats.assertionResult; bool printInfoMessages = true; // Drop out if result was successful and we're not printing those if( !m_config->includeSuccessfulResults() && result.isOk() ) { if( result.getResultType() != ResultWas::Warning ) return false; printInfoMessages = false; } AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); printer.print(); stream << std::endl; return true; } void CompactReporter::sectionEnded(SectionStats const& _sectionStats) { if (m_config->showDurations() == ShowDurations::Always) { stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl; } } void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) { printTotals( stream, _testRunStats.totals ); stream << '\n' << std::endl; StreamingReporterBase::testRunEnded( _testRunStats ); } CompactReporter::~CompactReporter() {} CATCH_REGISTER_REPORTER( "compact", CompactReporter ) } // end namespace Catch // end catch_reporter_compact.cpp // start catch_reporter_console.cpp #include <cfloat> #include <cstdio> #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch // Note that 4062 (not all labels are handled // and default is missing) is enabled #endif namespace Catch { namespace { // Formatter impl for ConsoleReporter class ConsoleAssertionPrinter { public: ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete; ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete; ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages) : stream(_stream), stats(_stats), result(_stats.assertionResult), colour(Colour::None), message(result.getMessage()), messages(_stats.infoMessages), printInfoMessages(_printInfoMessages) { switch (result.getResultType()) { case ResultWas::Ok: colour = Colour::Success; passOrFail = "PASSED"; //if( result.hasMessage() ) if (_stats.infoMessages.size() == 1) messageLabel = "with message"; if (_stats.infoMessages.size() > 1) messageLabel = "with messages"; break; case ResultWas::ExpressionFailed: if (result.isOk()) { colour = Colour::Success; passOrFail = "FAILED - but was ok"; } else { colour = Colour::Error; passOrFail = "FAILED"; } if (_stats.infoMessages.size() == 1) messageLabel = "with message"; if (_stats.infoMessages.size() > 1) messageLabel = "with messages"; break; case ResultWas::ThrewException: colour = Colour::Error; passOrFail = "FAILED"; messageLabel = "due to unexpected exception with "; if (_stats.infoMessages.size() == 1) messageLabel += "message"; if (_stats.infoMessages.size() > 1) messageLabel += "messages"; break; case ResultWas::FatalErrorCondition: colour = Colour::Error; passOrFail = "FAILED"; messageLabel = "due to a fatal error condition"; break; case ResultWas::DidntThrowException: colour = Colour::Error; passOrFail = "FAILED"; messageLabel = "because no exception was thrown where one was expected"; break; case ResultWas::Info: messageLabel = "info"; break; case ResultWas::Warning: messageLabel = "warning"; break; case ResultWas::ExplicitFailure: passOrFail = "FAILED"; colour = Colour::Error; if (_stats.infoMessages.size() == 1) messageLabel = "explicitly with message"; if (_stats.infoMessages.size() > 1) messageLabel = "explicitly with messages"; break; // These cases are here to prevent compiler warnings case ResultWas::Unknown: case ResultWas::FailureBit: case ResultWas::Exception: passOrFail = "** internal error **"; colour = Colour::Error; break; } } void print() const { printSourceInfo(); if (stats.totals.assertions.total() > 0) { printResultType(); printOriginalExpression(); printReconstructedExpression(); } else { stream << '\n'; } printMessage(); } private: void printResultType() const { if (!passOrFail.empty()) { Colour colourGuard(colour); stream << passOrFail << ":\n"; } } void printOriginalExpression() const { if (result.hasExpression()) { Colour colourGuard(Colour::OriginalExpression); stream << " "; stream << result.getExpressionInMacro(); stream << '\n'; } } void printReconstructedExpression() const { if (result.hasExpandedExpression()) { stream << "with expansion:\n"; Colour colourGuard(Colour::ReconstructedExpression); stream << Column(result.getExpandedExpression()).indent(2) << '\n'; } } void printMessage() const { if (!messageLabel.empty()) stream << messageLabel << ':' << '\n'; for (auto const& msg : messages) { // If this assertion is a warning ignore any INFO messages if (printInfoMessages || msg.type != ResultWas::Info) stream << Column(msg.message).indent(2) << '\n'; } } void printSourceInfo() const { Colour colourGuard(Colour::FileName); stream << result.getSourceInfo() << ": "; } std::ostream& stream; AssertionStats const& stats; AssertionResult const& result; Colour::Code colour; std::string passOrFail; std::string messageLabel; std::string message; std::vector<MessageInfo> messages; bool printInfoMessages; }; std::size_t makeRatio(std::size_t number, std::size_t total) { std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0; return (ratio == 0 && number > 0) ? 1 : ratio; } std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) { if (i > j && i > k) return i; else if (j > k) return j; else return k; } struct ColumnInfo { enum Justification { Left, Right }; std::string name; int width; Justification justification; }; struct ColumnBreak {}; struct RowBreak {}; class Duration { enum class Unit { Auto, Nanoseconds, Microseconds, Milliseconds, Seconds, Minutes }; static const uint64_t s_nanosecondsInAMicrosecond = 1000; static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond; static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond; static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond; uint64_t m_inNanoseconds; Unit m_units; public: explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto) : m_inNanoseconds(inNanoseconds), m_units(units) { if (m_units == Unit::Auto) { if (m_inNanoseconds < s_nanosecondsInAMicrosecond) m_units = Unit::Nanoseconds; else if (m_inNanoseconds < s_nanosecondsInAMillisecond) m_units = Unit::Microseconds; else if (m_inNanoseconds < s_nanosecondsInASecond) m_units = Unit::Milliseconds; else if (m_inNanoseconds < s_nanosecondsInAMinute) m_units = Unit::Seconds; else m_units = Unit::Minutes; } } auto value() const -> double { switch (m_units) { case Unit::Microseconds: return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond); case Unit::Milliseconds: return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond); case Unit::Seconds: return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond); case Unit::Minutes: return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute); default: return static_cast<double>(m_inNanoseconds); } } auto unitsAsString() const -> std::string { switch (m_units) { case Unit::Nanoseconds: return "ns"; case Unit::Microseconds: return "µs"; case Unit::Milliseconds: return "ms"; case Unit::Seconds: return "s"; case Unit::Minutes: return "m"; default: return "** internal error **"; } } friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& { return os << duration.value() << " " << duration.unitsAsString(); } }; } // end anon namespace class TablePrinter { std::ostream& m_os; std::vector<ColumnInfo> m_columnInfos; std::ostringstream m_oss; int m_currentColumn = -1; bool m_isOpen = false; public: TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos ) : m_os( os ), m_columnInfos( std::move( columnInfos ) ) {} auto columnInfos() const -> std::vector<ColumnInfo> const& { return m_columnInfos; } void open() { if (!m_isOpen) { m_isOpen = true; *this << RowBreak(); for (auto const& info : m_columnInfos) *this << info.name << ColumnBreak(); *this << RowBreak(); m_os << Catch::getLineOfChars<'-'>() << "\n"; } } void close() { if (m_isOpen) { *this << RowBreak(); m_os << std::endl; m_isOpen = false; } } template<typename T> friend TablePrinter& operator << (TablePrinter& tp, T const& value) { tp.m_oss << value; return tp; } friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) { auto colStr = tp.m_oss.str(); // This takes account of utf8 encodings auto strSize = Catch::StringRef(colStr).numberOfCharacters(); tp.m_oss.str(""); tp.open(); if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) { tp.m_currentColumn = -1; tp.m_os << "\n"; } tp.m_currentColumn++; auto colInfo = tp.m_columnInfos[tp.m_currentColumn]; auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width)) ? std::string(colInfo.width - (strSize + 2), ' ') : std::string(); if (colInfo.justification == ColumnInfo::Left) tp.m_os << colStr << padding << " "; else tp.m_os << padding << colStr << " "; return tp; } friend TablePrinter& operator << (TablePrinter& tp, RowBreak) { if (tp.m_currentColumn > 0) { tp.m_os << "\n"; tp.m_currentColumn = -1; } return tp; } }; ConsoleReporter::ConsoleReporter(ReporterConfig const& config) : StreamingReporterBase(config), m_tablePrinter(new TablePrinter(config.stream(), { { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left }, { "iters", 8, ColumnInfo::Right }, { "elapsed ns", 14, ColumnInfo::Right }, { "average", 14, ColumnInfo::Right } })) {} ConsoleReporter::~ConsoleReporter() = default; std::string ConsoleReporter::getDescription() { return "Reports test results as plain lines of text"; } void ConsoleReporter::noMatchingTestCases(std::string const& spec) { stream << "No test cases matched '" << spec << '\'' << std::endl; } void ConsoleReporter::assertionStarting(AssertionInfo const&) {} bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) { AssertionResult const& result = _assertionStats.assertionResult; bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); // Drop out if result was successful but we're not printing them. if (!includeResults && result.getResultType() != ResultWas::Warning) return false; lazyPrint(); ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults); printer.print(); stream << std::endl; return true; } void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) { m_headerPrinted = false; StreamingReporterBase::sectionStarting(_sectionInfo); } void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) { m_tablePrinter->close(); if (_sectionStats.missingAssertions) { lazyPrint(); Colour colour(Colour::ResultError); if (m_sectionStack.size() > 1) stream << "\nNo assertions in section"; else stream << "\nNo assertions in test case"; stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl; } if (m_config->showDurations() == ShowDurations::Always) { stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl; } if (m_headerPrinted) { m_headerPrinted = false; } StreamingReporterBase::sectionEnded(_sectionStats); } void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) { lazyPrintWithoutClosingBenchmarkTable(); auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) ); bool firstLine = true; for (auto line : nameCol) { if (!firstLine) (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak(); else firstLine = false; (*m_tablePrinter) << line << ColumnBreak(); } } void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) { Duration average(stats.elapsedTimeInNanoseconds / stats.iterations); (*m_tablePrinter) << stats.iterations << ColumnBreak() << stats.elapsedTimeInNanoseconds << ColumnBreak() << average << ColumnBreak(); } void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) { m_tablePrinter->close(); StreamingReporterBase::testCaseEnded(_testCaseStats); m_headerPrinted = false; } void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) { if (currentGroupInfo.used) { printSummaryDivider(); stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n"; printTotals(_testGroupStats.totals); stream << '\n' << std::endl; } StreamingReporterBase::testGroupEnded(_testGroupStats); } void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) { printTotalsDivider(_testRunStats.totals); printTotals(_testRunStats.totals); stream << std::endl; StreamingReporterBase::testRunEnded(_testRunStats); } void ConsoleReporter::lazyPrint() { m_tablePrinter->close(); lazyPrintWithoutClosingBenchmarkTable(); } void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() { if (!currentTestRunInfo.used) lazyPrintRunInfo(); if (!currentGroupInfo.used) lazyPrintGroupInfo(); if (!m_headerPrinted) { printTestCaseAndSectionHeader(); m_headerPrinted = true; } } void ConsoleReporter::lazyPrintRunInfo() { stream << '\n' << getLineOfChars<'~'>() << '\n'; Colour colour(Colour::SecondaryText); stream << currentTestRunInfo->name << " is a Catch v" << libraryVersion() << " host application.\n" << "Run with -? for options\n\n"; if (m_config->rngSeed() != 0) stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n"; currentTestRunInfo.used = true; } void ConsoleReporter::lazyPrintGroupInfo() { if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) { printClosedHeader("Group: " + currentGroupInfo->name); currentGroupInfo.used = true; } } void ConsoleReporter::printTestCaseAndSectionHeader() { assert(!m_sectionStack.empty()); printOpenHeader(currentTestCaseInfo->name); if (m_sectionStack.size() > 1) { Colour colourGuard(Colour::Headers); auto it = m_sectionStack.begin() + 1, // Skip first section (test case) itEnd = m_sectionStack.end(); for (; it != itEnd; ++it) printHeaderString(it->name, 2); } SourceLineInfo lineInfo = m_sectionStack.back().lineInfo; if (!lineInfo.empty()) { stream << getLineOfChars<'-'>() << '\n'; Colour colourGuard(Colour::FileName); stream << lineInfo << '\n'; } stream << getLineOfChars<'.'>() << '\n' << std::endl; } void ConsoleReporter::printClosedHeader(std::string const& _name) { printOpenHeader(_name); stream << getLineOfChars<'.'>() << '\n'; } void ConsoleReporter::printOpenHeader(std::string const& _name) { stream << getLineOfChars<'-'>() << '\n'; { Colour colourGuard(Colour::Headers); printHeaderString(_name); } } // if string has a : in first line will set indent to follow it on // subsequent lines void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) { std::size_t i = _string.find(": "); if (i != std::string::npos) i += 2; else i = 0; stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n'; } struct SummaryColumn { SummaryColumn( std::string _label, Colour::Code _colour ) : label( std::move( _label ) ), colour( _colour ) {} SummaryColumn addRow( std::size_t count ) { ReusableStringStream rss; rss << count; std::string row = rss.str(); for (auto& oldRow : rows) { while (oldRow.size() < row.size()) oldRow = ' ' + oldRow; while (oldRow.size() > row.size()) row = ' ' + row; } rows.push_back(row); return *this; } std::string label; Colour::Code colour; std::vector<std::string> rows; }; void ConsoleReporter::printTotals( Totals const& totals ) { if (totals.testCases.total() == 0) { stream << Colour(Colour::Warning) << "No tests ran\n"; } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) { stream << Colour(Colour::ResultSuccess) << "All tests passed"; stream << " (" << pluralise(totals.assertions.passed, "assertion") << " in " << pluralise(totals.testCases.passed, "test case") << ')' << '\n'; } else { std::vector<SummaryColumn> columns; columns.push_back(SummaryColumn("", Colour::None) .addRow(totals.testCases.total()) .addRow(totals.assertions.total())); columns.push_back(SummaryColumn("passed", Colour::Success) .addRow(totals.testCases.passed) .addRow(totals.assertions.passed)); columns.push_back(SummaryColumn("failed", Colour::ResultError) .addRow(totals.testCases.failed) .addRow(totals.assertions.failed)); columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure) .addRow(totals.testCases.failedButOk) .addRow(totals.assertions.failedButOk)); printSummaryRow("test cases", columns, 0); printSummaryRow("assertions", columns, 1); } } void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) { for (auto col : cols) { std::string value = col.rows[row]; if (col.label.empty()) { stream << label << ": "; if (value != "0") stream << value; else stream << Colour(Colour::Warning) << "- none -"; } else if (value != "0") { stream << Colour(Colour::LightGrey) << " | "; stream << Colour(col.colour) << value << ' ' << col.label; } } stream << '\n'; } void ConsoleReporter::printTotalsDivider(Totals const& totals) { if (totals.testCases.total() > 0) { std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total()); std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total()); std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total()); while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1) findMax(failedRatio, failedButOkRatio, passedRatio)++; while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1) findMax(failedRatio, failedButOkRatio, passedRatio)--; stream << Colour(Colour::Error) << std::string(failedRatio, '='); stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '='); if (totals.testCases.allPassed()) stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '='); else stream << Colour(Colour::Success) << std::string(passedRatio, '='); } else { stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '='); } stream << '\n'; } void ConsoleReporter::printSummaryDivider() { stream << getLineOfChars<'-'>() << '\n'; } CATCH_REGISTER_REPORTER("console", ConsoleReporter) } // end namespace Catch #if defined(_MSC_VER) #pragma warning(pop) #endif // end catch_reporter_console.cpp // start catch_reporter_junit.cpp #include <cassert> #include <sstream> #include <ctime> #include <algorithm> namespace Catch { namespace { std::string getCurrentTimestamp() { // Beware, this is not reentrant because of backward compatibility issues // Also, UTC only, again because of backward compatibility (%z is C++11) time_t rawtime; std::time(&rawtime); auto const timeStampSize = sizeof("2017-01-16T17:06:45Z"); #ifdef _MSC_VER std::tm timeInfo = {}; gmtime_s(&timeInfo, &rawtime); #else std::tm* timeInfo; timeInfo = std::gmtime(&rawtime); #endif char timeStamp[timeStampSize]; const char * const fmt = "%Y-%m-%dT%H:%M:%SZ"; #ifdef _MSC_VER std::strftime(timeStamp, timeStampSize, fmt, &timeInfo); #else std::strftime(timeStamp, timeStampSize, fmt, timeInfo); #endif return std::string(timeStamp); } std::string fileNameTag(const std::vector<std::string> &tags) { auto it = std::find_if(begin(tags), end(tags), [] (std::string const& tag) {return tag.front() == '#'; }); if (it != tags.end()) return it->substr(1); return std::string(); } } // anonymous namespace JunitReporter::JunitReporter( ReporterConfig const& _config ) : CumulativeReporterBase( _config ), xml( _config.stream() ) { m_reporterPrefs.shouldRedirectStdOut = true; m_reporterPrefs.shouldReportAllAssertions = true; } JunitReporter::~JunitReporter() {} std::string JunitReporter::getDescription() { return "Reports test results in an XML format that looks like Ant's junitreport target"; } void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {} void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) { CumulativeReporterBase::testRunStarting( runInfo ); xml.startElement( "testsuites" ); } void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) { suiteTimer.start(); stdOutForSuite.clear(); stdErrForSuite.clear(); unexpectedExceptions = 0; CumulativeReporterBase::testGroupStarting( groupInfo ); } void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) { m_okToFail = testCaseInfo.okToFail(); } bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) { if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail ) unexpectedExceptions++; return CumulativeReporterBase::assertionEnded( assertionStats ); } void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { stdOutForSuite += testCaseStats.stdOut; stdErrForSuite += testCaseStats.stdErr; CumulativeReporterBase::testCaseEnded( testCaseStats ); } void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) { double suiteTime = suiteTimer.getElapsedSeconds(); CumulativeReporterBase::testGroupEnded( testGroupStats ); writeGroup( *m_testGroups.back(), suiteTime ); } void JunitReporter::testRunEndedCumulative() { xml.endElement(); } void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) { XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" ); TestGroupStats const& stats = groupNode.value; xml.writeAttribute( "name", stats.groupInfo.name ); xml.writeAttribute( "errors", unexpectedExceptions ); xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions ); xml.writeAttribute( "tests", stats.totals.assertions.total() ); xml.writeAttribute( "hostname", "tbd" ); // !TBD if( m_config->showDurations() == ShowDurations::Never ) xml.writeAttribute( "time", "" ); else xml.writeAttribute( "time", suiteTime ); xml.writeAttribute( "timestamp", getCurrentTimestamp() ); // Write test cases for( auto const& child : groupNode.children ) writeTestCase( *child ); xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false ); xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false ); } void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) { TestCaseStats const& stats = testCaseNode.value; // All test cases have exactly one section - which represents the // test case itself. That section may have 0-n nested sections assert( testCaseNode.children.size() == 1 ); SectionNode const& rootSection = *testCaseNode.children.front(); std::string className = stats.testInfo.className; if( className.empty() ) { className = fileNameTag(stats.testInfo.tags); if ( className.empty() ) className = "global"; } if ( !m_config->name().empty() ) className = m_config->name() + "." + className; writeSection( className, "", rootSection ); } void JunitReporter::writeSection( std::string const& className, std::string const& rootName, SectionNode const& sectionNode ) { std::string name = trim( sectionNode.stats.sectionInfo.name ); if( !rootName.empty() ) name = rootName + '/' + name; if( !sectionNode.assertions.empty() || !sectionNode.stdOut.empty() || !sectionNode.stdErr.empty() ) { XmlWriter::ScopedElement e = xml.scopedElement( "testcase" ); if( className.empty() ) { xml.writeAttribute( "classname", name ); xml.writeAttribute( "name", "root" ); } else { xml.writeAttribute( "classname", className ); xml.writeAttribute( "name", name ); } xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) ); writeAssertions( sectionNode ); if( !sectionNode.stdOut.empty() ) xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false ); if( !sectionNode.stdErr.empty() ) xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false ); } for( auto const& childNode : sectionNode.childSections ) if( className.empty() ) writeSection( name, "", *childNode ); else writeSection( className, name, *childNode ); } void JunitReporter::writeAssertions( SectionNode const& sectionNode ) { for( auto const& assertion : sectionNode.assertions ) writeAssertion( assertion ); } void JunitReporter::writeAssertion( AssertionStats const& stats ) { AssertionResult const& result = stats.assertionResult; if( !result.isOk() ) { std::string elementName; switch( result.getResultType() ) { case ResultWas::ThrewException: case ResultWas::FatalErrorCondition: elementName = "error"; break; case ResultWas::ExplicitFailure: elementName = "failure"; break; case ResultWas::ExpressionFailed: elementName = "failure"; break; case ResultWas::DidntThrowException: elementName = "failure"; break; // We should never see these here: case ResultWas::Info: case ResultWas::Warning: case ResultWas::Ok: case ResultWas::Unknown: case ResultWas::FailureBit: case ResultWas::Exception: elementName = "internalError"; break; } XmlWriter::ScopedElement e = xml.scopedElement( elementName ); xml.writeAttribute( "message", result.getExpandedExpression() ); xml.writeAttribute( "type", result.getTestMacroName() ); ReusableStringStream rss; if( !result.getMessage().empty() ) rss << result.getMessage() << '\n'; for( auto const& msg : stats.infoMessages ) if( msg.type == ResultWas::Info ) rss << msg.message << '\n'; rss << "at " << result.getSourceInfo(); xml.writeText( rss.str(), false ); } } CATCH_REGISTER_REPORTER( "junit", JunitReporter ) } // end namespace Catch // end catch_reporter_junit.cpp // start catch_reporter_listening.cpp #include <cassert> namespace Catch { ListeningReporter::ListeningReporter() { // We will assume that listeners will always want all assertions m_preferences.shouldReportAllAssertions = true; } void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) { m_listeners.push_back( std::move( listener ) ); } void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) { assert(!m_reporter && "Listening reporter can wrap only 1 real reporter"); m_reporter = std::move( reporter ); m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut; } ReporterPreferences ListeningReporter::getPreferences() const { return m_preferences; } std::set<Verbosity> ListeningReporter::getSupportedVerbosities() { return std::set<Verbosity>{ }; } void ListeningReporter::noMatchingTestCases( std::string const& spec ) { for ( auto const& listener : m_listeners ) { listener->noMatchingTestCases( spec ); } m_reporter->noMatchingTestCases( spec ); } void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) { for ( auto const& listener : m_listeners ) { listener->benchmarkStarting( benchmarkInfo ); } m_reporter->benchmarkStarting( benchmarkInfo ); } void ListeningReporter::benchmarkEnded( BenchmarkStats const& benchmarkStats ) { for ( auto const& listener : m_listeners ) { listener->benchmarkEnded( benchmarkStats ); } m_reporter->benchmarkEnded( benchmarkStats ); } void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) { for ( auto const& listener : m_listeners ) { listener->testRunStarting( testRunInfo ); } m_reporter->testRunStarting( testRunInfo ); } void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) { for ( auto const& listener : m_listeners ) { listener->testGroupStarting( groupInfo ); } m_reporter->testGroupStarting( groupInfo ); } void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) { for ( auto const& listener : m_listeners ) { listener->testCaseStarting( testInfo ); } m_reporter->testCaseStarting( testInfo ); } void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) { for ( auto const& listener : m_listeners ) { listener->sectionStarting( sectionInfo ); } m_reporter->sectionStarting( sectionInfo ); } void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) { for ( auto const& listener : m_listeners ) { listener->assertionStarting( assertionInfo ); } m_reporter->assertionStarting( assertionInfo ); } // The return value indicates if the messages buffer should be cleared: bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) { for( auto const& listener : m_listeners ) { static_cast<void>( listener->assertionEnded( assertionStats ) ); } return m_reporter->assertionEnded( assertionStats ); } void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) { for ( auto const& listener : m_listeners ) { listener->sectionEnded( sectionStats ); } m_reporter->sectionEnded( sectionStats ); } void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { for ( auto const& listener : m_listeners ) { listener->testCaseEnded( testCaseStats ); } m_reporter->testCaseEnded( testCaseStats ); } void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) { for ( auto const& listener : m_listeners ) { listener->testGroupEnded( testGroupStats ); } m_reporter->testGroupEnded( testGroupStats ); } void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) { for ( auto const& listener : m_listeners ) { listener->testRunEnded( testRunStats ); } m_reporter->testRunEnded( testRunStats ); } void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) { for ( auto const& listener : m_listeners ) { listener->skipTest( testInfo ); } m_reporter->skipTest( testInfo ); } bool ListeningReporter::isMulti() const { return true; } } // end namespace Catch // end catch_reporter_listening.cpp // start catch_reporter_xml.cpp #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch // Note that 4062 (not all labels are handled // and default is missing) is enabled #endif namespace Catch { XmlReporter::XmlReporter( ReporterConfig const& _config ) : StreamingReporterBase( _config ), m_xml(_config.stream()) { m_reporterPrefs.shouldRedirectStdOut = true; m_reporterPrefs.shouldReportAllAssertions = true; } XmlReporter::~XmlReporter() = default; std::string XmlReporter::getDescription() { return "Reports test results as an XML document"; } std::string XmlReporter::getStylesheetRef() const { return std::string(); } void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) { m_xml .writeAttribute( "filename", sourceInfo.file ) .writeAttribute( "line", sourceInfo.line ); } void XmlReporter::noMatchingTestCases( std::string const& s ) { StreamingReporterBase::noMatchingTestCases( s ); } void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) { StreamingReporterBase::testRunStarting( testInfo ); std::string stylesheetRef = getStylesheetRef(); if( !stylesheetRef.empty() ) m_xml.writeStylesheetRef( stylesheetRef ); m_xml.startElement( "Catch" ); if( !m_config->name().empty() ) m_xml.writeAttribute( "name", m_config->name() ); if( m_config->rngSeed() != 0 ) m_xml.scopedElement( "Randomness" ) .writeAttribute( "seed", m_config->rngSeed() ); } void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) { StreamingReporterBase::testGroupStarting( groupInfo ); m_xml.startElement( "Group" ) .writeAttribute( "name", groupInfo.name ); } void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) { StreamingReporterBase::testCaseStarting(testInfo); m_xml.startElement( "TestCase" ) .writeAttribute( "name", trim( testInfo.name ) ) .writeAttribute( "description", testInfo.description ) .writeAttribute( "tags", testInfo.tagsAsString() ); writeSourceInfo( testInfo.lineInfo ); if ( m_config->showDurations() == ShowDurations::Always ) m_testCaseTimer.start(); m_xml.ensureTagClosed(); } void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) { StreamingReporterBase::sectionStarting( sectionInfo ); if( m_sectionDepth++ > 0 ) { m_xml.startElement( "Section" ) .writeAttribute( "name", trim( sectionInfo.name ) ); writeSourceInfo( sectionInfo.lineInfo ); m_xml.ensureTagClosed(); } } void XmlReporter::assertionStarting( AssertionInfo const& ) { } bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) { AssertionResult const& result = assertionStats.assertionResult; bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); if( includeResults || result.getResultType() == ResultWas::Warning ) { // Print any info messages in <Info> tags. for( auto const& msg : assertionStats.infoMessages ) { if( msg.type == ResultWas::Info && includeResults ) { m_xml.scopedElement( "Info" ) .writeText( msg.message ); } else if ( msg.type == ResultWas::Warning ) { m_xml.scopedElement( "Warning" ) .writeText( msg.message ); } } } // Drop out if result was successful but we're not printing them. if( !includeResults && result.getResultType() != ResultWas::Warning ) return true; // Print the expression if there is one. if( result.hasExpression() ) { m_xml.startElement( "Expression" ) .writeAttribute( "success", result.succeeded() ) .writeAttribute( "type", result.getTestMacroName() ); writeSourceInfo( result.getSourceInfo() ); m_xml.scopedElement( "Original" ) .writeText( result.getExpression() ); m_xml.scopedElement( "Expanded" ) .writeText( result.getExpandedExpression() ); } // And... Print a result applicable to each result type. switch( result.getResultType() ) { case ResultWas::ThrewException: m_xml.startElement( "Exception" ); writeSourceInfo( result.getSourceInfo() ); m_xml.writeText( result.getMessage() ); m_xml.endElement(); break; case ResultWas::FatalErrorCondition: m_xml.startElement( "FatalErrorCondition" ); writeSourceInfo( result.getSourceInfo() ); m_xml.writeText( result.getMessage() ); m_xml.endElement(); break; case ResultWas::Info: m_xml.scopedElement( "Info" ) .writeText( result.getMessage() ); break; case ResultWas::Warning: // Warning will already have been written break; case ResultWas::ExplicitFailure: m_xml.startElement( "Failure" ); writeSourceInfo( result.getSourceInfo() ); m_xml.writeText( result.getMessage() ); m_xml.endElement(); break; default: break; } if( result.hasExpression() ) m_xml.endElement(); return true; } void XmlReporter::sectionEnded( SectionStats const& sectionStats ) { StreamingReporterBase::sectionEnded( sectionStats ); if( --m_sectionDepth > 0 ) { XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" ); e.writeAttribute( "successes", sectionStats.assertions.passed ); e.writeAttribute( "failures", sectionStats.assertions.failed ); e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk ); if ( m_config->showDurations() == ShowDurations::Always ) e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds ); m_xml.endElement(); } } void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { StreamingReporterBase::testCaseEnded( testCaseStats ); XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" ); e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() ); if ( m_config->showDurations() == ShowDurations::Always ) e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() ); if( !testCaseStats.stdOut.empty() ) m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false ); if( !testCaseStats.stdErr.empty() ) m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false ); m_xml.endElement(); } void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) { StreamingReporterBase::testGroupEnded( testGroupStats ); // TODO: Check testGroupStats.aborting and act accordingly. m_xml.scopedElement( "OverallResults" ) .writeAttribute( "successes", testGroupStats.totals.assertions.passed ) .writeAttribute( "failures", testGroupStats.totals.assertions.failed ) .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk ); m_xml.endElement(); } void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) { StreamingReporterBase::testRunEnded( testRunStats ); m_xml.scopedElement( "OverallResults" ) .writeAttribute( "successes", testRunStats.totals.assertions.passed ) .writeAttribute( "failures", testRunStats.totals.assertions.failed ) .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk ); m_xml.endElement(); } CATCH_REGISTER_REPORTER( "xml", XmlReporter ) } // end namespace Catch #if defined(_MSC_VER) #pragma warning(pop) #endif // end catch_reporter_xml.cpp namespace Catch { LeakDetector leakDetector; } #ifdef __clang__ #pragma clang diagnostic pop #endif // end catch_impl.hpp #endif #ifdef CATCH_CONFIG_MAIN // start catch_default_main.hpp #ifndef __OBJC__ #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN) // Standard C/C++ Win32 Unicode wmain entry point extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) { #else // Standard C/C++ main entry point int main (int argc, char * argv[]) { #endif return Catch::Session().run( argc, argv ); } #else // __OBJC__ // Objective-C entry point int main (int argc, char * const argv[]) { #if !CATCH_ARC_ENABLED NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; #endif Catch::registerTestMethods(); int result = Catch::Session().run( argc, (char**)argv ); #if !CATCH_ARC_ENABLED [pool drain]; #endif return result; } #endif // __OBJC__ // end catch_default_main.hpp #endif #if !defined(CATCH_CONFIG_IMPL_ONLY) #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED # undef CLARA_CONFIG_MAIN #endif #if !defined(CATCH_CONFIG_DISABLE) ////// // If this config identifier is defined then all CATCH macros are prefixed with CATCH_ #ifdef CATCH_CONFIG_PREFIX_ALL #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", __VA_ARGS__ ) #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr ) #endif// CATCH_CONFIG_DISABLE_MATCHERS #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ ) #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", __VA_ARGS__ ) #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg ) #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ ) #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ ) #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE() #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) #else #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) ) #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) #endif #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE) #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ ) #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ ) #else #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ ) #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ ) #endif // "BDD-style" convenience wrappers #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ ) #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc ) #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc ) #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc ) #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc ) #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc ) #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc ) // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required #else #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ ) #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg ) #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ ) #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ ) #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE() #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) #else #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) ) #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) ) #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) #endif #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE) #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ ) #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" ) #else #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ ) #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ ) #endif #endif #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) // "BDD-style" convenience wrappers #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ ) #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc ) #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc ) #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc ) #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc ) #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc ) #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc ) using Catch::Detail::Approx; #else // CATCH_CONFIG_DISABLE ////// // If this config identifier is defined then all CATCH macros are prefixed with CATCH_ #ifdef CATCH_CONFIG_PREFIX_ALL #define CATCH_REQUIRE( ... ) (void)(0) #define CATCH_REQUIRE_FALSE( ... ) (void)(0) #define CATCH_REQUIRE_THROWS( ... ) (void)(0) #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0) #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) #endif// CATCH_CONFIG_DISABLE_MATCHERS #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0) #define CATCH_CHECK( ... ) (void)(0) #define CATCH_CHECK_FALSE( ... ) (void)(0) #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__) #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__)) #define CATCH_CHECK_NOFAIL( ... ) (void)(0) #define CATCH_CHECK_THROWS( ... ) (void)(0) #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0) #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define CATCH_CHECK_NOTHROW( ... ) (void)(0) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) #define CATCH_CHECK_THAT( arg, matcher ) (void)(0) #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define CATCH_INFO( msg ) (void)(0) #define CATCH_WARN( msg ) (void)(0) #define CATCH_CAPTURE( msg ) (void)(0) #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) #define CATCH_METHOD_AS_TEST_CASE( method, ... ) #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0) #define CATCH_SECTION( ... ) #define CATCH_DYNAMIC_SECTION( ... ) #define CATCH_FAIL( ... ) (void)(0) #define CATCH_FAIL_CHECK( ... ) (void)(0) #define CATCH_SUCCEED( ... ) (void)(0) #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) ) #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), className ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) #else #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) ) ) #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), className ) ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) #endif // "BDD-style" convenience wrappers #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className ) #define CATCH_GIVEN( desc ) #define CATCH_AND_GIVEN( desc ) #define CATCH_WHEN( desc ) #define CATCH_AND_WHEN( desc ) #define CATCH_THEN( desc ) #define CATCH_AND_THEN( desc ) #define CATCH_STATIC_REQUIRE( ... ) (void)(0) #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0) // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required #else #define REQUIRE( ... ) (void)(0) #define REQUIRE_FALSE( ... ) (void)(0) #define REQUIRE_THROWS( ... ) (void)(0) #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0) #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define REQUIRE_NOTHROW( ... ) (void)(0) #define CHECK( ... ) (void)(0) #define CHECK_FALSE( ... ) (void)(0) #define CHECKED_IF( ... ) if (__VA_ARGS__) #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__)) #define CHECK_NOFAIL( ... ) (void)(0) #define CHECK_THROWS( ... ) (void)(0) #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0) #define CHECK_THROWS_WITH( expr, matcher ) (void)(0) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define CHECK_NOTHROW( ... ) (void)(0) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) #define CHECK_THAT( arg, matcher ) (void)(0) #define REQUIRE_THAT( arg, matcher ) (void)(0) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define INFO( msg ) (void)(0) #define WARN( msg ) (void)(0) #define CAPTURE( msg ) (void)(0) #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) #define METHOD_AS_TEST_CASE( method, ... ) #define REGISTER_TEST_CASE( Function, ... ) (void)(0) #define SECTION( ... ) #define DYNAMIC_SECTION( ... ) #define FAIL( ... ) (void)(0) #define FAIL_CHECK( ... ) (void)(0) #define SUCCEED( ... ) (void)(0) #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) ) #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), className ) #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) #else #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) ) ) #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), className ) ) #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) #endif #define STATIC_REQUIRE( ... ) (void)(0) #define STATIC_REQUIRE_FALSE( ... ) (void)(0) #endif #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) // "BDD-style" convenience wrappers #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) ) #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className ) #define GIVEN( desc ) #define AND_GIVEN( desc ) #define WHEN( desc ) #define AND_WHEN( desc ) #define THEN( desc ) #define AND_THEN( desc ) using Catch::Detail::Approx; #endif #endif // ! CATCH_CONFIG_IMPL_ONLY // start catch_reenable_warnings.h #ifdef __clang__ # ifdef __ICC // icpc defines the __clang__ macro # pragma warning(pop) # else # pragma clang diagnostic pop # endif #elif defined __GNUC__ # pragma GCC diagnostic pop #endif // end catch_reenable_warnings.h // end catch.hpp #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
[ "kevinkosta@Kevins-MacBook-Pro-2.local" ]
kevinkosta@Kevins-MacBook-Pro-2.local
661ffda6c50388e81844b52da4dda9f6d9531058
e1ba0eb26a14be38c1b2fdf0902417d2552be913
/REM/Tool/IDA 7.3/plugins/hexrays_sdk/plugins/vds14/hexrays_sample14.cpp
309510a74eca15d21c8e16174728b1eb7c9c4266
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
dodieboy/Np_class
db7fb9d4f4eb0fe4d5bb38dc05e69a9cbd485cf0
5c6e517599a20658ee23bdbdd76f197f2f4a1b63
refs/heads/master
2022-11-15T10:29:30.587639
2022-06-24T12:25:45
2022-06-24T12:25:45
181,395,891
0
2
MIT
2020-05-30T06:22:17
2019-04-15T02:07:40
C#
UTF-8
C++
false
false
11,183
cpp
/* * Hex-Rays Decompiler project * Copyright (c) 2007-2019 by Hex-Rays, support@hex-rays.com * ALL RIGHTS RESERVED. * * Sample plugin for Hex-Rays Decompiler. * It shows xrefs to the called function as the decompiler output. * All calls are displayed with the call arguments. * Usage: Shift-X or Jump, Jump to call xrefs... */ #include <hexrays.hpp> // Hex-Rays API pointer hexdsp_t *hexdsp = NULL; struct xref_info_t { qstring text; ea_t ea; char xref_type; }; DECLARE_TYPE_AS_MOVABLE(xref_info_t); typedef qvector<xref_info_t> xrefvec_t; //------------------------------------------------------------------------- // go backwards until the beginning of the basic block static ea_t find_bb_start(ea_t call_ea) { ea_t ea = call_ea; while ( true ) { flags_t F = get_flags(ea); if ( !is_flow(F) || has_xref(F) ) break; insn_t tmp; ea_t prev = decode_prev_insn(&tmp, ea); if ( prev == BADADDR ) break; ea = prev; } return ea; } //------------------------------------------------------------------------- static bool determine_decompilation_range( mba_ranges_t *mbr, ea_t call_ea, const tinfo_t &tif) { func_t *pfn = get_func(call_ea); if ( pfn != NULL && calc_func_size(pfn) <= 1024 ) { // a small function, decompile it entirely mbr->pfn = pfn; return true; } ea_t minea = call_ea; ea_t maxea = call_ea; eavec_t addrs; if ( !get_arg_addrs(&addrs, call_ea) ) { apply_callee_tinfo(call_ea, tif); if ( !get_arg_addrs(&addrs, call_ea) ) minea = find_bb_start(call_ea); } for ( size_t i=0; i < addrs.size(); i++ ) { if ( minea > addrs[i] ) minea = addrs[i]; if ( maxea < addrs[i] ) maxea = addrs[i]; } range_t &r = mbr->ranges.push_back(); r.start_ea = minea; r.end_ea = get_item_end(maxea); return true; } //------------------------------------------------------------------------- // decompile the snippet static bool generate_call_line( qstring *out, bool *canceled, ea_t call_ea, const tinfo_t &tif) { mba_ranges_t mbr; if ( !determine_decompilation_range(&mbr, call_ea, tif) ) return false; hexrays_failure_t hf; cfuncptr_t func = decompile(mbr, &hf, DECOMP_NO_WAIT); if ( func == NULL ) { if ( hf.code == MERR_CANCELED ) *canceled = true; return false; } citem_t *call = func->body.find_closest_addr(call_ea); if ( call == NULL || call->ea != call_ea ) return false; const strvec_t &sv = func->get_pseudocode(); int y; if ( !func->find_item_coords(call, NULL, &y) ) return false; *out = sv[y].line; tag_remove(out); // indentation does not convey much info, so remove the leading spaces out->ltrim(); return true; } //------------------------------------------------------------------------- struct xref_chooser_t : public chooser_t { protected: ea_t func_ea; const xrefvec_t &list; static const int widths_[]; static const char *const header_[]; enum { ICON = 55 }; public: xref_chooser_t(uint32 flags, ea_t func_ea, const xrefvec_t &list, const char *title); ea_t choose_modal(ea_t xrefpos_ea); virtual size_t idaapi get_count() const { return list.size(); } virtual void idaapi get_row( qstrvec_t *cols, int *icon_, chooser_item_attrs_t *attrs, size_t n) const; // calculate the location of the item, // item_data is a pointer to a xref position virtual ssize_t idaapi get_item_index(const void *item_data) const; protected: static const char *direction_str(ea_t ea, ea_t refea) { return ea > refea ? "Up" : ea < refea ? "Down" : ""; } static void get_xrefed_name(qstring *buf, ea_t ref); xrefvec_t::const_iterator find(const xrefpos_t &pos) const { xrefvec_t::const_iterator it = list.begin(); xrefvec_t::const_iterator end = list.end(); for ( ; it != end; ++it ) { const xref_info_t &cur = *it; if ( cur.ea == pos.ea && cur.xref_type == pos.type ) break; } return it; } }; //------------------------------------------------------------------------- const int xref_chooser_t::widths_[] = { 6, // Direction 1, // Type 15, // Address 50, // Text }; const char *const xref_chooser_t::header_[] = { "Direction", // 0 "Type", // 1 "Address", // 2 "Text", // 3 }; //------------------------------------------------------------------------- inline xref_chooser_t::xref_chooser_t( uint32 flags_, ea_t func_ea_, const xrefvec_t &list_, const char *title_) : chooser_t(flags_, qnumber(widths_), widths_, header_, title_), func_ea(func_ea_), list(list_) { CASSERT(qnumber(widths_) == qnumber(header_)); icon = ICON; deflt_col = 2; } //------------------------------------------------------------------------- inline ea_t xref_chooser_t::choose_modal(ea_t xrefpos_ea) { if ( list.empty() ) { warning("There are no %s", title); return BADADDR; } xrefpos_t defpos; get_xrefpos(&defpos, xrefpos_ea); ssize_t n = ::choose(this, &defpos); if ( n < 0 || n >= list.size() ) return BADADDR; const xref_info_t &entry = list[n]; if ( n == 0 ) { del_xrefpos(xrefpos_ea); } else { xrefpos_t xp(entry.ea, entry.xref_type); set_xrefpos(xrefpos_ea, &xp); } return entry.ea; } //------------------------------------------------------------------------- void idaapi xref_chooser_t::get_row( qstrvec_t *cols_, int *, chooser_item_attrs_t *, size_t n) const { const xref_info_t &entry = list[n]; qstrvec_t &cols = *cols_; cols[0] = direction_str(func_ea, entry.ea); cols[1].sprnt("%c", xrefchar(entry.xref_type)); get_xrefed_name(&cols[2], entry.ea); cols[3] = entry.text; } //------------------------------------------------------------------------ ssize_t idaapi xref_chooser_t::get_item_index(const void *item_data) const { if ( list.empty() ) return NO_SELECTION; // `item_data` is a pointer to a xref position xrefpos_t item_pos = *(const xrefpos_t *)item_data; if ( !item_pos.is_valid() ) return 0; // first item by default xrefvec_t::const_iterator it = find(item_pos); if ( it == list.end() ) return 0; // first item by default return it - list.begin(); } //------------------------------------------------------------------------- void xref_chooser_t::get_xrefed_name(qstring *buf, ea_t ref) { int f2 = GNCN_NOCOLOR; //-V688 if ( !inf_show_xref_fncoff() ) f2 |= GNCN_NOFUNC; if ( !inf_show_xref_seg() ) f2 |= GNCN_NOSEG; get_nice_colored_name(buf, ref, f2); } //------------------------------------------------------------------------- static bool jump_to_call(ea_t func_ea) { // Retrieve all xrefs to the function xrefblk_t xb; xrefvec_t list; for ( bool ok = xb.first_to(func_ea, 0); ok; ok=xb.next_to() ) { xref_info_t &entry = list.push_back(); entry.ea = xb.from; entry.xref_type = xb.type; } // Generate decompiler output or disassembly output for each xref tinfo_t tif; if ( get_tinfo(&tif, func_ea) ) guess_tinfo(&tif, func_ea); show_wait_box("Decompiling..."); bool canceled = false; size_t n = list.size(); for ( size_t i=0; i < n; i++ ) { xref_info_t &entry = list[i]; bool success = false; if ( entry.xref_type >= fl_CF && !canceled ) { replace_wait_box("Decompiling %a (%" FMT_Z "/%" FMT_Z ")...", entry.ea, i, n); success = generate_call_line(&entry.text, &canceled, entry.ea, tif); } if ( !success ) generate_disasm_line(&entry.text, entry.ea, GENDSM_REMOVE_TAGS); } hide_wait_box(); // Display the xref chooser qstring title; get_short_name(&title, func_ea); title.insert("xrefs to "); xref_chooser_t xrefch(CH_MODAL | CH_KEEP, func_ea, list, title.c_str()); ea_t target = xrefch.choose_modal(func_ea); if ( target == BADADDR ) return false; // Jump to the seleected target return jumpto(target); } //------------------------------------------------------------------------- struct func_xrefs_t : public action_handler_t { virtual int idaapi activate(action_activation_ctx_t *ctx) { ea_t ea = ctx->cur_value; flags_t F = get_flags(ea); if ( !is_func(F) ) { // we are not staying on a call. // check if we stay on the entry point of a function ea = ctx->cur_ea; F = get_flags(ea); if ( !is_func(F) ) ea = BADADDR; } if ( ea != BADADDR ) return jump_to_call(ea); return process_ui_action("JumpOpXref"); // fallback to the built-in action } virtual action_state_t idaapi update(action_update_ctx_t *ctx) { switch ( ctx->widget_type ) { case BWN_EXPORTS: // exports case BWN_IMPORTS: // imports case BWN_NAMES: // names case BWN_FUNCS: // functions case BWN_DISASM: // disassembly views case BWN_DUMP: // hex dumps case BWN_PSEUDOCODE: // decompiler view return AST_ENABLE_FOR_WIDGET; } return AST_DISABLE_FOR_WIDGET; } }; static func_xrefs_t func_xrefs_ah; static const char ah_name[] = "vds14:call_xrefs"; static const action_desc_t xref_desc = ACTION_DESC_LITERAL( ah_name, "Jump to call x~r~efs", &func_xrefs_ah, "Shift-X", NULL, -1); //-------------------------------------------------------------------------- int idaapi init(void) { if ( !init_hexrays_plugin() ) return PLUGIN_SKIP; // no decompiler const char *hxver = get_hexrays_version(); msg("Hex-rays version %s has been detected, %s ready to use\n", hxver, PLUGIN.wanted_name); register_action(xref_desc); attach_action_to_menu("Jump/Jump to func", ah_name, SETMENU_APP); return PLUGIN_KEEP; } //-------------------------------------------------------------------------- void idaapi term(void) { if ( hexdsp != NULL ) { unregister_action(ah_name); term_hexrays_plugin(); } } //-------------------------------------------------------------------------- bool idaapi run(size_t) { return false; } //-------------------------------------------------------------------------- static const char comment[] = "Sample14 plugin for Hex-Rays decompiler"; //-------------------------------------------------------------------------- // // PLUGIN DESCRIPTION BLOCK // //-------------------------------------------------------------------------- plugin_t PLUGIN = { IDP_INTERFACE_VERSION, PLUGIN_HIDE, // plugin flags init, // initialize term, // terminate. this pointer may be NULL. run, // invoke plugin comment, // long comment about the plugin // it could appear in the status line // or as a hint "", // multiline help about the plugin "Call xrefs", // the preferred short name of the plugin // (not visible because of PLUGIN_HIDE) "" // the preferred hotkey to run the plugin };
[ "dodieboy@users.noreply.github.com" ]
dodieboy@users.noreply.github.com
9acb242b748f9aed82609ba3d3ffce6a64b63d69
fc987ace8516d4d5dfcb5444ed7cb905008c6147
/third_party/aria2/src/ReceiverMSEHandshakeCommand.h
98857a2bcdaff5d3cfc5370eedcdd4f5c111da47
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "OpenSSL", "GPL-1.0-or-later", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "FSFAP", "GPL-2.0-only", "LicenseRef-scancode-public-domain", "MIT", "Apache-2.0" ]
permissive
nfschina/nfs-browser
3c366cedbdbe995739717d9f61e451bcf7b565ce
b6670ba13beb8ab57003f3ba2c755dc368de3967
refs/heads/master
2022-10-28T01:18:08.229807
2020-09-07T11:45:28
2020-09-07T11:45:28
145,939,440
2
4
BSD-3-Clause
2022-10-13T14:59:54
2018-08-24T03:47:46
null
UTF-8
C++
false
false
2,705
h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_RECEIVER_MSE_HANDSHAKE_COMMAND_H #define D_RECEIVER_MSE_HANDSHAKE_COMMAND_H #include "PeerAbstractCommand.h" namespace aria2 { class MSEHandshake; class SocketCore; class Peer; class ReceiverMSEHandshakeCommand:public PeerAbstractCommand { public: enum Seq { RECEIVER_IDENTIFY_HANDSHAKE, RECEIVER_WAIT_KEY, RECEIVER_SEND_KEY_PENDING, RECEIVER_FIND_HASH_MARKER, RECEIVER_RECEIVE_PAD_C_LENGTH, RECEIVER_RECEIVE_PAD_C, RECEIVER_RECEIVE_IA_LENGTH, RECEIVER_RECEIVE_IA, RECEIVER_SEND_STEP2_PENDING, }; private: Seq sequence_; std::unique_ptr<MSEHandshake> mseHandshake_; void createCommand(); protected: virtual bool executeInternal() CXX11_OVERRIDE; virtual bool exitBeforeExecute() CXX11_OVERRIDE; public: ReceiverMSEHandshakeCommand(cuid_t cuid, const std::shared_ptr<Peer>& peer, DownloadEngine* e, const std::shared_ptr<SocketCore>& s); virtual ~ReceiverMSEHandshakeCommand(); }; } // namespace aria2 #endif // D_RECEIVER_MSE_HANDSHAKE_COMMAND_H
[ "hukun@cpu-os.ac.cn" ]
hukun@cpu-os.ac.cn
be95119743225ffb5994c826d33604fea7ff3ef9
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/08_8146_40.cpp
34d9b6ecd6b609eaa58bbd910798932127c2a09a
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,074
cpp
#include<stdio.h> #include<string.h> #define maxn 3000 #define maxint 999999999 bool p[maxn][maxn]; bool output[maxn]; int q[maxn],last[maxn]; int i,j,n,m; int make(){ bool changed; int ans=0; memset(output,0,sizeof(output)); do{ changed=0; for(i=1;i<=m;i++)if(q[i]==0){ if(last[i]==0)return -1; for(j=1;j<=m;j++){ if(last[j]==last[i])q[j]=maxint; if(p[last[i]][j])q[j]--; } changed=1; ans++; output[last[i]]=1; } }while(changed); return ans; } int main(){ int nn,ii,t,x,y; scanf("%d",&nn); for(ii=1;ii<=nn;ii++){ printf("Case #%d:",ii); scanf("%d %d",&n,&m); memset(last,0,sizeof(last)); memset(q,0,sizeof(q)); memset(p,0,sizeof(p)); for(i=1;i<=m;i++){ scanf("%d",&t); while(t--){ scanf("%d %d",&x,&y); if(y==0)p[x][i]=1,q[i]++; else last[i]=x; } } int temp=make(); if(temp<0){ printf(" IMPOSSIBLE\n"); }else { for(i=1;i<=n;i++)if(output[i])printf(" 1"); else printf(" 0"); printf("\n"); } } return 0; }
[ "nikola.mrzljak@fer.hr" ]
nikola.mrzljak@fer.hr
d275c1345fc4738474a26907a8a2df7b8d2b4e96
08948ee7b7239bfc09b274082f52db4f832433cb
/src/Common/Color.h
ac46b9ac81cb130092e3c1a033b85bdfee5b18f5
[ "MIT" ]
permissive
Tobaloidee/rainbow
4d738953403c40046055409ea6df722456bfd050
7bbac9405ae9e519c6496f2a5fa957a073cce563
refs/heads/master
2020-05-02T16:51:13.265175
2019-03-27T22:09:40
2019-03-27T22:09:40
178,011,578
0
0
MIT
2019-03-27T14:29:51
2019-03-27T14:29:51
null
UTF-8
C++
false
false
1,264
h
// Copyright (c) 2010-present Bifrost Entertainment AS and Tommy Nguyen // Distributed under the MIT License. // (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) #ifndef COMMON_COLOR_H_ #define COMMON_COLOR_H_ #include <cstdint> namespace rainbow { /// <summary>Structure for storing a colour (RGBA).</summary> struct Color { uint8_t r, g, b, a; constexpr Color() : r(0xff), g(0xff), b(0xff), a(0xff) {} constexpr Color(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 0xff) : r(r), g(g), b(b), a(a) { } constexpr Color(uint32_t rgba) : r(0xff & (rgba >> 24)), g(0xff & (rgba >> 16)), b(0xff & (rgba >> 8)), a(0xff & rgba) { } auto operator=(uint32_t c) -> Color& { return *this = Color{c}; } // TODO: Having constexpr here breaks Xcode 8.3 friend bool operator!=(Color lhs, Color rhs) { return !(lhs == rhs); } friend constexpr bool operator==(Color lhs, Color rhs) { return lhs.r == rhs.r && // lhs.g == rhs.g && // lhs.b == rhs.b && // lhs.a == rhs.a; } }; } // namespace rainbow #endif
[ "tn0502@gmail.com" ]
tn0502@gmail.com
89afebb4fa545370fcf0cb4a53778e1cd625a09b
9a9d28bb2195b4cf81bc2da8265135ec079e9147
/Grid.cpp
befcf9241aeff4fcf5e4dc5e61a15547bfc8749f
[]
no_license
meghnaraswan/CPSC350Assignment2
e15e19daab32766e20ea85599adc7f419133048c
7399d21650327e3c244a6ade2ef3f81714224aea
refs/heads/main
2023-01-02T14:37:09.956385
2020-10-29T00:52:43
2020-10-29T00:52:43
302,977,727
0
0
null
null
null
null
UTF-8
C++
false
false
6,691
cpp
// // Grid.cpp // FirstCPP // // Created by iMan on 10/4/20. // Copyright © 2020 iMan. All rights reserved. // #include "Grid.hpp" #include "Cell.hpp" #include <iostream> #include <fstream> #include <string> using namespace std; //Grid //default constructor //default values of rows and columns of grid will be 5 Grid::Grid(){ rows = 5; cols = 5; } //overloaded constructor Grid::Grid(int rows, int cols){ this->rows = rows; this->cols = cols; for (int i = 0; i < this->rows; ++i){ //rows for (int j = 0; j < this->cols; ++j){ //columns pCellArray[i][j] = new Cell(); //array consists of Cell datatype } } } //overloaded constructor //array can hold up to 10 rows and 10 columns Grid::Grid(int rows, int cols, char values[10][10]) { this->rows = rows; this->cols = cols; for (int i = 0; i < this->rows; ++i){ //rows for (int j = 0; j < this->cols; ++j){ //columns pCellArray[i][j] = new Cell(values[i][j]); //array consists of Cell datatype that has char value } } } //overloaded constructor Grid::Grid(string m_filename){ //initialize rows, columns, and line count as 0 this->rows = 0; this->cols = 0; int lineCount = 0; fstream newfile; //fstream is a stream class to both read and write from/to files. newfile.open(m_filename,ios::in); //open a file to perform read operation using file object if (newfile.is_open()){ //checking to see whether the file is open string line; while(getline(newfile, line)){ //read data from file object and put it into string. if(lineCount == 0){ //the first line (or 0th index of the line) is the rows this->rows = stoi(line); //stoi converts data from a string type to an integer type } else if (lineCount == 1){ //the second line (or the 1st indext of the line) is the columns this->cols = stoi(line); } else { int i = lineCount - 2; //makes i starting from 0 since the first 2 lines were rows and columns for (int j = 0; j < sizeof(line); j++) //while going through each value in the string of 1 line, the value will be added into the array { pCellArray[i][j] = new Cell(line[j]); } } ++lineCount; //increasing line count by 1 after reading though the next file } newfile.close(); //close the file object. } countNeighborsForAllCells(); //calling the countNeighborsForAllCells() function to count the neighbors for all cells (not including doughnut or mirror modes, those will be done in their individual classes) } //destructor Grid::~Grid(){ for (int i = 0; i < this->rows; ++i){ //rows for (int j = 0; j < this->cols; ++j){ //columns delete pCellArray[i][j]; //delete each cell in array } } } //print() function prints the total rows and and columnsand then calls the toString method from Cell class to output each value of the cell in the respected rows and columns void Grid::print() { cout << "[" << this->rows << ":" << this->cols <<"]" << endl; for (int i = 0; i < this->rows; ++i){ //rows for (int j = 0; j < this->cols; ++j){ //columns cout << pCellArray[i][j]->toString(); } cout << endl; //new line for the end of each row } } //function counts the number of X's each cell's neighbors have void Grid::countNeighborsForAllCells() { for (int i = 0; i < this->rows; ++i){ //rows for (int j = 0; j < this->cols; ++j){ //columns // reset count of neighbors pCellArray[i][j]->neighborCount = 0; int pii = (i-1 < 0) ? 0 : i-1; // prev edge boundary of the row int qii = (i+1>this->rows-1) ? this->rows-1 : i+1;// next edge boundary of the row int pjj = (j-1 < 0) ? 0 : j-1; // prev edge boundary of the col int qjj = (j+1>this->cols-1) ? this->cols-1 : j+1;// next edge boundary of the col // enter the boundary for each cell for calculating the neighbor count for (int ii = pii; ii <= qii; ++ii){ //rows for (int jj = pjj; jj <= qjj; ++jj){ //column if (i == ii && j == jj) { ; // do nothing or skip } else { if(pCellArray[ii][jj]->getValue() == 'X') { //if the neighbor has X value, increase the neighbor count by 1 pCellArray[i][j]->neighborCount++; } } } } } } } //uses the function calcNextGenVal() from Cell class to calculate the cell's value in the next generation at that positions depending on the number of neighbors that have Xs void Grid::calcNextGenerationValuesForAllCells() { for (int i = 0; i < this->rows; ++i){ //rows for (int j = 0; j < this->cols; ++j){ //columns pCellArray[i][j]->calcNextGenVal(); } } } //function move the cell to the next generation by calling the calcNextGenerationValuesForAllCells() and countNeighborsForAllCells() functions void Grid::moveToNextGeneration() { this->calcNextGenerationValuesForAllCells(); this->countNeighborsForAllCells(); } //function counts the neighbors for each cell that is on the edge of the row, which is the same pattern followed for the Doughnut and Mirror modes void Grid::helpCountEdgeRowNeighbors(int curr_row, int neigh_row){ for(int j=0; j<cols; j++) { //for each column int pjj = (j-1 < 0) ? 0 : j-1; // prev edge boundary of the col int qjj = (j+1>cols-1) ? cols-1 : j+1; // next edge boundary of the col for (int jj = pjj; jj <= qjj; ++jj) { if(pCellArray[neigh_row][jj]->getValue() == 'X') { //if the neighbor has X value, increase the neighbor count by 1 pCellArray[curr_row][j]->neighborCount++; } } } } //function counts the neighbors for each cell that is on the edge of the columns, which is the same pattern followed for the Doughnut and Mirror modes void Grid::helpCountEdgeColNeighbors(int curr_col, int neigh_col){ for(int i=0; i<rows; i++) { //for each row int pii = (i-1 < 0) ? 0 : i-1; //prev edge boundary of the row int qii = (i+1>rows-1) ? rows-1 : i+1; // next edge boundary of the row for (int ii = pii; ii <= qii; ++ii) { if(pCellArray[ii][neigh_col]->getValue() == 'X') { //if the neighbor has X value, increase the neighbor count by 1 pCellArray[i][curr_col]->neighborCount++; } } } }
[ "raswan@chapman.edu" ]
raswan@chapman.edu
bea4a9598825f17d8b4df2f15de6cff71a2254b2
dca653bb975528bd1b8ab2547f6ef4f48e15b7b7
/tags/wxPy-2.8.11.0/src/gtk/window.cpp
bbedb09eece2245a8602078a15cfcad11805a12f
[]
no_license
czxxjtu/wxPython-1
51ca2f62ff6c01722e50742d1813f4be378c0517
6a7473c258ea4105f44e31d140ea5c0ae6bc46d8
refs/heads/master
2021-01-15T12:09:59.328778
2015-01-05T20:55:10
2015-01-05T20:55:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
135,666
cpp
///////////////////////////////////////////////////////////////////////////// // Name: src/gtk/window.cpp // Purpose: // Author: Robert Roebling // Id: $Id$ // Copyright: (c) 1998 Robert Roebling, Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __VMS #define XWarpPointer XWARPPOINTER #endif #include "wx/window.h" #ifndef WX_PRECOMP #include "wx/log.h" #include "wx/app.h" #include "wx/frame.h" #include "wx/dcclient.h" #include "wx/menu.h" #include "wx/settings.h" #include "wx/msgdlg.h" #include "wx/textctrl.h" #include "wx/radiobut.h" #include "wx/toolbar.h" #include "wx/combobox.h" #include "wx/layout.h" #include "wx/math.h" #endif #include "wx/dnd.h" #include "wx/tooltip.h" #include "wx/caret.h" #include "wx/fontutil.h" #include "wx/sysopt.h" #ifdef __WXDEBUG__ #include "wx/thread.h" #endif #include <ctype.h> // FIXME: Due to a hack we use GtkCombo in here, which is deprecated since gtk2.3.0 #include <gtk/gtkversion.h> #if defined(GTK_DISABLE_DEPRECATED) && GTK_CHECK_VERSION(2,3,0) #undef GTK_DISABLE_DEPRECATED #include <gtk/gtkcombo.h> #define GTK_DISABLE_DEPRECATED #endif #define USE_STYLE_SET_CALLBACK 1 #include "wx/gtk/private.h" #include "wx/gtk/win_gtk.h" #include <gdk/gdkkeysyms.h> #include <gdk/gdkx.h> #if !GTK_CHECK_VERSION(2,10,0) // GTK+ can reliably detect Meta key state only since 2.10 when // GDK_META_MASK was introduced -- there wasn't any way to detect it // in older versions. wxGTK used GDK_MOD2_MASK for this purpose, but // GDK_MOD2_MASK is documented as: // // the fifth modifier key (it depends on the modifier mapping of the X // server which key is interpreted as this modifier) // // In other words, it isn't guaranteed to map to Meta. This is a real // problem: it is common to map NumLock to it (in fact, it's an exception // if the X server _doesn't_ use it for NumLock). So the old code caused // wxKeyEvent::MetaDown() to always return true as long as NumLock was on // on many systems, which broke all applications using // wxKeyEvent::GetModifiers() to check modifiers state (see e.g. here: // http://tinyurl.com/56lsk2). // // Because of this, it's better to not detect Meta key state at all than // to detect it incorrectly. Hence the following #define, which causes // m_metaDown to be always set to false. #define GDK_META_MASK 0 #endif //----------------------------------------------------------------------------- // documentation on internals //----------------------------------------------------------------------------- /* I have been asked several times about writing some documentation about the GTK port of wxWidgets, especially its internal structures. Obviously, you cannot understand wxGTK without knowing a little about the GTK, but some more information about what the wxWindow, which is the base class for all other window classes, does seems required as well. I) What does wxWindow do? It contains the common interface for the following jobs of its descendants: 1) Define the rudimentary behaviour common to all window classes, such as resizing, intercepting user input (so as to make it possible to use these events for special purposes in a derived class), window names etc. 2) Provide the possibility to contain and manage children, if the derived class is allowed to contain children, which holds true for those window classes which do not display a native GTK widget. To name them, these classes are wxPanel, wxScrolledWindow, wxDialog, wxFrame. The MDI frame- work classes are a special case and are handled a bit differently from the rest. The same holds true for the wxNotebook class. 3) Provide the possibility to draw into a client area of a window. This, too, only holds true for classes that do not display a native GTK widget as above. 4) Provide the entire mechanism for scrolling widgets. This actual inter- face for this is usually in wxScrolledWindow, but the GTK implementation is in this class. 5) A multitude of helper or extra methods for special purposes, such as Drag'n'Drop, managing validators etc. 6) Display a border (sunken, raised, simple or none). Normally one might expect, that one wxWidgets window would always correspond to one GTK widget. Under GTK, there is no such all-round widget that has all the functionality. Moreover, the GTK defines a client area as a different widget from the actual widget you are handling. Last but not least some special classes (e.g. wxFrame) handle different categories of widgets and still have the possibility to draw something in the client area. It was therefore required to write a special purpose GTK widget, that would represent a client area in the sense of wxWidgets capable to do the jobs 2), 3) and 4). I have written this class and it resides in win_gtk.c of this directory. All windows must have a widget, with which they interact with other under- lying GTK widgets. It is this widget, e.g. that has to be resized etc and the wxWindow class has a member variable called m_widget which holds a pointer to this widget. When the window class represents a GTK native widget, this is (in most cases) the only GTK widget the class manages. E.g. the wxStaticText class handles only a GtkLabel widget a pointer to which you can find in m_widget (defined in wxWindow) When the class has a client area for drawing into and for containing children it has to handle the client area widget (of the type GtkPizza, defined in win_gtk.c), but there could be any number of widgets, handled by a class The common rule for all windows is only, that the widget that interacts with the rest of GTK must be referenced in m_widget and all other widgets must be children of this widget on the GTK level. The top-most widget, which also represents the client area, must be in the m_wxwindow field and must be of the type GtkPizza. As I said, the window classes that display a GTK native widget only have one widget, so in the case of e.g. the wxButton class m_widget holds a pointer to a GtkButton widget. But windows with client areas (for drawing and children) have a m_widget field that is a pointer to a GtkScrolled- Window and a m_wxwindow field that is pointer to a GtkPizza and this one is (in the GTK sense) a child of the GtkScrolledWindow. If the m_wxwindow field is set, then all input to this widget is inter- cepted and sent to the wxWidgets class. If not, all input to the widget that gets pointed to by m_widget gets intercepted and sent to the class. II) The design of scrolling in wxWidgets is markedly different from that offered by the GTK itself and therefore we cannot simply take it as it is. In GTK, clicking on a scrollbar belonging to scrolled window will inevitably move the window. In wxWidgets, the scrollbar will only emit an event, send this to (normally) a wxScrolledWindow and that class will call ScrollWindow() which actually moves the window and its sub-windows. Note that GtkPizza memorizes how much it has been scrolled but that wxWidgets forgets this so that the two coordinates systems have to be kept in synch. This is done in various places using the pizza->xoffset and pizza->yoffset values. III) Singularly the most broken code in GTK is the code that is supposed to inform subwindows (child windows) about new positions. Very often, duplicate events are sent without changes in size or position, equally often no events are sent at all (All this is due to a bug in the GtkContainer code which got fixed in GTK 1.2.6). For that reason, wxGTK completely ignores GTK's own system and it simply waits for size events for toplevel windows and then iterates down the respective size events to all window. This has the disadvantage that windows might get size events before the GTK widget actually has the reported size. This doesn't normally pose any problem, but the OpenGL drawing routines rely on correct behaviour. Therefore, I have added the m_nativeSizeEvents flag, which is true only for the OpenGL canvas, i.e. the wxGLCanvas will emit a size event, when (and not before) the X11 window that is used for OpenGL output really has that size (as reported by GTK). IV) If someone at some point of time feels the immense desire to have a look at, change or attempt to optimise the Refresh() logic, this person will need an intimate understanding of what "draw" and "expose" events are and what they are used for, in particular when used in connection with GTK's own windowless widgets. Beware. V) Cursors, too, have been a constant source of pleasure. The main difficulty is that a GdkWindow inherits a cursor if the programmer sets a new cursor for the parent. To prevent this from doing too much harm, I use idle time to set the cursor over and over again, starting from the toplevel windows and ending with the youngest generation (speaking of parent and child windows). Also don't forget that cursors (like much else) are connected to GdkWindows, not GtkWidgets and that the "window" field of a GtkWidget might very well point to the GdkWindow of the parent widget (-> "window-less widget") and that the two obviously have very different meanings. */ //----------------------------------------------------------------------------- // data //----------------------------------------------------------------------------- extern bool g_blockEventsOnDrag; extern bool g_blockEventsOnScroll; extern wxCursor g_globalCursor; // mouse capture state: the window which has it and if the mouse is currently // inside it static wxWindowGTK *g_captureWindow = (wxWindowGTK*) NULL; static bool g_captureWindowHasMouse = false; wxWindowGTK *g_focusWindow = (wxWindowGTK*) NULL; wxWindowGTK *g_focusWindowPending = (wxWindowGTK*) NULL; // the last window which had the focus - this is normally never NULL (except // if we never had focus at all) as even when g_focusWindow is NULL it still // keeps its previous value wxWindowGTK *g_focusWindowLast = (wxWindowGTK*) NULL; // If a window get the focus set but has not been realized // yet, defer setting the focus to idle time. wxWindowGTK *g_delayedFocus = (wxWindowGTK*) NULL; // global variables because GTK+ DnD want to have the // mouse event that caused it GdkEvent *g_lastMouseEvent = (GdkEvent*) NULL; int g_lastButtonNumber = 0; extern bool g_mainThreadLocked; //----------------------------------------------------------------------------- // debug //----------------------------------------------------------------------------- #ifdef __WXDEBUG__ #if wxUSE_THREADS # define DEBUG_MAIN_THREAD if (wxThread::IsMain() && g_mainThreadLocked) printf("gui reentrance"); #else # define DEBUG_MAIN_THREAD #endif #else #define DEBUG_MAIN_THREAD #endif // Debug // the trace mask used for the focus debugging messages #define TRACE_FOCUS _T("focus") //----------------------------------------------------------------------------- // missing gdk functions //----------------------------------------------------------------------------- void gdk_window_warp_pointer (GdkWindow *window, gint x, gint y) { if (!window) window = gdk_get_default_root_window(); if (!GDK_WINDOW_DESTROYED(window)) { XWarpPointer (GDK_WINDOW_XDISPLAY(window), None, /* not source window -> move from anywhere */ GDK_WINDOW_XID(window), /* dest window */ 0, 0, 0, 0, /* not source window -> move from anywhere */ x, y ); } } //----------------------------------------------------------------------------- // local code (see below) //----------------------------------------------------------------------------- // returns the child of win which currently has focus or NULL if not found // // Note: can't be static, needed by textctrl.cpp. wxWindow *wxFindFocusedChild(wxWindowGTK *win) { wxWindowGTK* winFocus = g_focusWindow; if ( !winFocus ) return (wxWindow *)NULL; if ( winFocus == win ) return (wxWindow *)win; for ( wxWindowList::compatibility_iterator node = win->GetChildren().GetFirst(); node; node = node->GetNext() ) { wxWindow *child = wxFindFocusedChild(node->GetData()); if ( child ) return child; } return (wxWindow *)NULL; } static void GetScrollbarWidth(GtkWidget* widget, int& w, int& h) { GtkScrolledWindow* scroll_window = GTK_SCROLLED_WINDOW(widget); GtkScrolledWindowClass* scroll_class = GTK_SCROLLED_WINDOW_CLASS(GTK_OBJECT_GET_CLASS(scroll_window)); GtkRequisition scroll_req; w = 0; if (scroll_window->vscrollbar_visible) { scroll_req.width = 2; scroll_req.height = 2; (* GTK_WIDGET_CLASS( GTK_OBJECT_GET_CLASS(scroll_window->vscrollbar) )->size_request ) (scroll_window->vscrollbar, &scroll_req ); w = scroll_req.width + scroll_class->scrollbar_spacing; } h = 0; if (scroll_window->hscrollbar_visible) { scroll_req.width = 2; scroll_req.height = 2; (* GTK_WIDGET_CLASS( GTK_OBJECT_GET_CLASS(scroll_window->hscrollbar) )->size_request ) (scroll_window->hscrollbar, &scroll_req ); h = scroll_req.height + scroll_class->scrollbar_spacing; } } static void draw_frame( GtkWidget *widget, wxWindowGTK *win ) { // wxUniversal widgets draw the borders and scrollbars themselves #ifndef __WXUNIVERSAL__ if (!win->m_hasVMT) return; int dx = 0; int dy = 0; if (GTK_WIDGET_NO_WINDOW (widget)) { dx += widget->allocation.x; dy += widget->allocation.y; } int x = dx; int y = dy; int dw = 0; int dh = 0; if (win->m_hasScrolling) { GetScrollbarWidth(widget, dw, dh); if (win->GetLayoutDirection() == wxLayout_RightToLeft) { // This is actually wrong for old GTK+ version // which do not display the scrollbar on the // left side in RTL x += dw; } } int w = widget->allocation.width-dw; int h = widget->allocation.height-dh; if (win->HasFlag(wxRAISED_BORDER)) { gtk_paint_shadow (widget->style, widget->window, GTK_STATE_NORMAL, GTK_SHADOW_OUT, NULL, NULL, NULL, // FIXME: No clipping? x, y, w, h ); return; } if (win->HasFlag(wxSUNKEN_BORDER)) { gtk_paint_shadow (widget->style, widget->window, GTK_STATE_NORMAL, GTK_SHADOW_IN, NULL, NULL, NULL, // FIXME: No clipping? x, y, w, h ); return; } if (win->HasFlag(wxSIMPLE_BORDER)) { GdkGC *gc; gc = gdk_gc_new( widget->window ); gdk_gc_set_foreground( gc, &widget->style->black ); gdk_draw_rectangle( widget->window, gc, FALSE, x, y, w-1, h-1 ); g_object_unref (gc); return; } #endif // __WXUNIVERSAL__ } //----------------------------------------------------------------------------- // "expose_event" of m_widget //----------------------------------------------------------------------------- extern "C" { static gboolean gtk_window_own_expose_callback( GtkWidget *widget, GdkEventExpose *gdk_event, wxWindowGTK *win ) { if (gdk_event->count == 0) draw_frame(widget, win); return false; } } //----------------------------------------------------------------------------- // "size_request" of m_widget //----------------------------------------------------------------------------- // make it extern because wxStaticText needs to disconnect this one extern "C" { void wxgtk_window_size_request_callback(GtkWidget *widget, GtkRequisition *requisition, wxWindow *win) { int w, h; win->GetSize( &w, &h ); if (w < 2) w = 2; if (h < 2) h = 2; requisition->height = h; requisition->width = w; } } extern "C" { static void wxgtk_combo_size_request_callback(GtkWidget *widget, GtkRequisition *requisition, wxComboBox *win) { // This callback is actually hooked into the text entry // of the combo box, not the GtkHBox. int w, h; win->GetSize( &w, &h ); if (w < 2) w = 2; if (h < 2) h = 2; GtkCombo *gcombo = GTK_COMBO(win->m_widget); GtkRequisition entry_req; entry_req.width = 2; entry_req.height = 2; (* GTK_WIDGET_CLASS( GTK_OBJECT_GET_CLASS(gcombo->entry) )->size_request ) (gcombo->entry, &entry_req ); GtkRequisition button_req; button_req.width = 2; button_req.height = 2; (* GTK_WIDGET_CLASS( GTK_OBJECT_GET_CLASS(gcombo->button) )->size_request ) (gcombo->button, &button_req ); requisition->width = w - button_req.width; requisition->height = entry_req.height; } } //----------------------------------------------------------------------------- // "expose_event" of m_wxwindow //----------------------------------------------------------------------------- extern "C" { static gboolean gtk_window_expose_callback( GtkWidget *widget, GdkEventExpose *gdk_event, wxWindow *win ) { DEBUG_MAIN_THREAD // don't need to install idle handler, its done from "event" signal // This callback gets called in drawing-idle time under // GTK 2.0, so we don't need to defer anything to idle // time anymore. GtkPizza *pizza = GTK_PIZZA( widget ); if (gdk_event->window != pizza->bin_window) { // block expose events on GTK_WIDGET(pizza)->window, // all drawing is done on pizza->bin_window return true; } #if 0 if (win->GetName()) { wxPrintf( wxT("OnExpose from ") ); if (win->GetClassInfo() && win->GetClassInfo()->GetClassName()) wxPrintf( win->GetClassInfo()->GetClassName() ); wxPrintf( wxT(" %d %d %d %d\n"), (int)gdk_event->area.x, (int)gdk_event->area.y, (int)gdk_event->area.width, (int)gdk_event->area.height ); } gtk_paint_box ( win->m_wxwindow->style, pizza->bin_window, GTK_STATE_NORMAL, GTK_SHADOW_OUT, (GdkRectangle*) NULL, win->m_wxwindow, (char *)"button", // const_cast 20,20,24,24 ); #endif win->GetUpdateRegion() = wxRegion( gdk_event->region ); win->GtkSendPaintEvents(); // Let parent window draw window-less widgets return FALSE; } } //----------------------------------------------------------------------------- // "key_press_event" from any window //----------------------------------------------------------------------------- // These are used when transforming Ctrl-alpha to ascii values 1-26 inline bool wxIsLowerChar(int code) { return (code >= 'a' && code <= 'z' ); } inline bool wxIsUpperChar(int code) { return (code >= 'A' && code <= 'Z' ); } // set WXTRACE to this to see the key event codes on the console #define TRACE_KEYS _T("keyevent") // translates an X key symbol to WXK_XXX value // // if isChar is true it means that the value returned will be used for EVT_CHAR // event and then we choose the logical WXK_XXX, i.e. '/' for GDK_KP_Divide, // for example, while if it is false it means that the value is going to be // used for KEY_DOWN/UP events and then we translate GDK_KP_Divide to // WXK_NUMPAD_DIVIDE static long wxTranslateKeySymToWXKey(KeySym keysym, bool isChar) { long key_code; switch ( keysym ) { // Shift, Control and Alt don't generate the CHAR events at all case GDK_Shift_L: case GDK_Shift_R: key_code = isChar ? 0 : WXK_SHIFT; break; case GDK_Control_L: case GDK_Control_R: key_code = isChar ? 0 : WXK_CONTROL; break; case GDK_Meta_L: case GDK_Meta_R: case GDK_Alt_L: case GDK_Alt_R: case GDK_Super_L: case GDK_Super_R: key_code = isChar ? 0 : WXK_ALT; break; // neither do the toggle modifies case GDK_Scroll_Lock: key_code = isChar ? 0 : WXK_SCROLL; break; case GDK_Caps_Lock: key_code = isChar ? 0 : WXK_CAPITAL; break; case GDK_Num_Lock: key_code = isChar ? 0 : WXK_NUMLOCK; break; // various other special keys case GDK_Menu: key_code = WXK_MENU; break; case GDK_Help: key_code = WXK_HELP; break; case GDK_BackSpace: key_code = WXK_BACK; break; case GDK_ISO_Left_Tab: case GDK_Tab: key_code = WXK_TAB; break; case GDK_Linefeed: case GDK_Return: key_code = WXK_RETURN; break; case GDK_Clear: key_code = WXK_CLEAR; break; case GDK_Pause: key_code = WXK_PAUSE; break; case GDK_Select: key_code = WXK_SELECT; break; case GDK_Print: key_code = WXK_PRINT; break; case GDK_Execute: key_code = WXK_EXECUTE; break; case GDK_Escape: key_code = WXK_ESCAPE; break; // cursor and other extended keyboard keys case GDK_Delete: key_code = WXK_DELETE; break; case GDK_Home: key_code = WXK_HOME; break; case GDK_Left: key_code = WXK_LEFT; break; case GDK_Up: key_code = WXK_UP; break; case GDK_Right: key_code = WXK_RIGHT; break; case GDK_Down: key_code = WXK_DOWN; break; case GDK_Prior: // == GDK_Page_Up key_code = WXK_PAGEUP; break; case GDK_Next: // == GDK_Page_Down key_code = WXK_PAGEDOWN; break; case GDK_End: key_code = WXK_END; break; case GDK_Begin: key_code = WXK_HOME; break; case GDK_Insert: key_code = WXK_INSERT; break; // numpad keys case GDK_KP_0: case GDK_KP_1: case GDK_KP_2: case GDK_KP_3: case GDK_KP_4: case GDK_KP_5: case GDK_KP_6: case GDK_KP_7: case GDK_KP_8: case GDK_KP_9: key_code = (isChar ? '0' : WXK_NUMPAD0) + keysym - GDK_KP_0; break; case GDK_KP_Space: key_code = isChar ? ' ' : WXK_NUMPAD_SPACE; break; case GDK_KP_Tab: key_code = isChar ? WXK_TAB : WXK_NUMPAD_TAB; break; case GDK_KP_Enter: key_code = isChar ? WXK_RETURN : WXK_NUMPAD_ENTER; break; case GDK_KP_F1: key_code = isChar ? WXK_F1 : WXK_NUMPAD_F1; break; case GDK_KP_F2: key_code = isChar ? WXK_F2 : WXK_NUMPAD_F2; break; case GDK_KP_F3: key_code = isChar ? WXK_F3 : WXK_NUMPAD_F3; break; case GDK_KP_F4: key_code = isChar ? WXK_F4 : WXK_NUMPAD_F4; break; case GDK_KP_Home: key_code = isChar ? WXK_HOME : WXK_NUMPAD_HOME; break; case GDK_KP_Left: key_code = isChar ? WXK_LEFT : WXK_NUMPAD_LEFT; break; case GDK_KP_Up: key_code = isChar ? WXK_UP : WXK_NUMPAD_UP; break; case GDK_KP_Right: key_code = isChar ? WXK_RIGHT : WXK_NUMPAD_RIGHT; break; case GDK_KP_Down: key_code = isChar ? WXK_DOWN : WXK_NUMPAD_DOWN; break; case GDK_KP_Prior: // == GDK_KP_Page_Up key_code = isChar ? WXK_PAGEUP : WXK_NUMPAD_PAGEUP; break; case GDK_KP_Next: // == GDK_KP_Page_Down key_code = isChar ? WXK_PAGEDOWN : WXK_NUMPAD_PAGEDOWN; break; case GDK_KP_End: key_code = isChar ? WXK_END : WXK_NUMPAD_END; break; case GDK_KP_Begin: key_code = isChar ? WXK_HOME : WXK_NUMPAD_BEGIN; break; case GDK_KP_Insert: key_code = isChar ? WXK_INSERT : WXK_NUMPAD_INSERT; break; case GDK_KP_Delete: key_code = isChar ? WXK_DELETE : WXK_NUMPAD_DELETE; break; case GDK_KP_Equal: key_code = isChar ? '=' : WXK_NUMPAD_EQUAL; break; case GDK_KP_Multiply: key_code = isChar ? '*' : WXK_NUMPAD_MULTIPLY; break; case GDK_KP_Add: key_code = isChar ? '+' : WXK_NUMPAD_ADD; break; case GDK_KP_Separator: // FIXME: what is this? key_code = isChar ? '.' : WXK_NUMPAD_SEPARATOR; break; case GDK_KP_Subtract: key_code = isChar ? '-' : WXK_NUMPAD_SUBTRACT; break; case GDK_KP_Decimal: key_code = isChar ? '.' : WXK_NUMPAD_DECIMAL; break; case GDK_KP_Divide: key_code = isChar ? '/' : WXK_NUMPAD_DIVIDE; break; // function keys case GDK_F1: case GDK_F2: case GDK_F3: case GDK_F4: case GDK_F5: case GDK_F6: case GDK_F7: case GDK_F8: case GDK_F9: case GDK_F10: case GDK_F11: case GDK_F12: key_code = WXK_F1 + keysym - GDK_F1; break; default: key_code = 0; } return key_code; } static inline bool wxIsAsciiKeysym(KeySym ks) { return ks < 256; } static void wxFillOtherKeyEventFields(wxKeyEvent& event, wxWindowGTK *win, GdkEventKey *gdk_event) { int x = 0; int y = 0; GdkModifierType state; if (gdk_event->window) gdk_window_get_pointer(gdk_event->window, &x, &y, &state); event.SetTimestamp( gdk_event->time ); event.SetId(win->GetId()); event.m_shiftDown = (gdk_event->state & GDK_SHIFT_MASK) != 0; event.m_controlDown = (gdk_event->state & GDK_CONTROL_MASK) != 0; event.m_altDown = (gdk_event->state & GDK_MOD1_MASK) != 0; event.m_metaDown = (gdk_event->state & GDK_META_MASK) != 0; event.m_scanCode = gdk_event->keyval; event.m_rawCode = (wxUint32) gdk_event->keyval; event.m_rawFlags = 0; #if wxUSE_UNICODE event.m_uniChar = gdk_keyval_to_unicode(gdk_event->keyval); #endif wxGetMousePosition( &x, &y ); win->ScreenToClient( &x, &y ); event.m_x = x; event.m_y = y; event.SetEventObject( win ); } static bool wxTranslateGTKKeyEventToWx(wxKeyEvent& event, wxWindowGTK *win, GdkEventKey *gdk_event) { // VZ: it seems that GDK_KEY_RELEASE event doesn't set event->string // but only event->keyval which is quite useless to us, so remember // the last character from GDK_KEY_PRESS and reuse it as last resort // // NB: should be MT-safe as we're always called from the main thread only static struct { KeySym keysym; long keycode; } s_lastKeyPress = { 0, 0 }; KeySym keysym = gdk_event->keyval; wxLogTrace(TRACE_KEYS, _T("Key %s event: keysym = %ld"), event.GetEventType() == wxEVT_KEY_UP ? _T("release") : _T("press"), keysym); long key_code = wxTranslateKeySymToWXKey(keysym, false /* !isChar */); if ( !key_code ) { // do we have the translation or is it a plain ASCII character? if ( (gdk_event->length == 1) || wxIsAsciiKeysym(keysym) ) { // we should use keysym if it is ASCII as X does some translations // like "I pressed while Control is down" => "Ctrl-I" == "TAB" // which we don't want here (but which we do use for OnChar()) if ( !wxIsAsciiKeysym(keysym) ) { keysym = (KeySym)gdk_event->string[0]; } // we want to always get the same key code when the same key is // pressed regardless of the state of the modifiers, i.e. on a // standard US keyboard pressing '5' or '%' ('5' key with // Shift) should result in the same key code in OnKeyDown(): // '5' (although OnChar() will get either '5' or '%'). // // to do it we first translate keysym to keycode (== scan code) // and then back but always using the lower register Display *dpy = (Display *)wxGetDisplay(); KeyCode keycode = XKeysymToKeycode(dpy, keysym); wxLogTrace(TRACE_KEYS, _T("\t-> keycode %d"), keycode); KeySym keysymNormalized = XKeycodeToKeysym(dpy, keycode, 0); // use the normalized, i.e. lower register, keysym if we've // got one key_code = keysymNormalized ? keysymNormalized : keysym; // as explained above, we want to have lower register key codes // normally but for the letter keys we want to have the upper ones // // NB: don't use XConvertCase() here, we want to do it for letters // only key_code = toupper(key_code); } else // non ASCII key, what to do? { // by default, ignore it key_code = 0; // but if we have cached information from the last KEY_PRESS if ( gdk_event->type == GDK_KEY_RELEASE ) { // then reuse it if ( keysym == s_lastKeyPress.keysym ) { key_code = s_lastKeyPress.keycode; } } } if ( gdk_event->type == GDK_KEY_PRESS ) { // remember it to be reused for KEY_UP event later s_lastKeyPress.keysym = keysym; s_lastKeyPress.keycode = key_code; } } wxLogTrace(TRACE_KEYS, _T("\t-> wxKeyCode %ld"), key_code); // sending unknown key events doesn't really make sense if ( !key_code ) return false; // now fill all the other fields wxFillOtherKeyEventFields(event, win, gdk_event); event.m_keyCode = key_code; #if wxUSE_UNICODE if ( gdk_event->type == GDK_KEY_PRESS || gdk_event->type == GDK_KEY_RELEASE ) { event.m_uniChar = key_code; } #endif return true; } struct wxGtkIMData { GtkIMContext *context; GdkEventKey *lastKeyEvent; wxGtkIMData() { context = gtk_im_multicontext_new(); lastKeyEvent = NULL; } ~wxGtkIMData() { g_object_unref (context); } }; extern "C" { static gboolean gtk_window_key_press_callback( GtkWidget *widget, GdkEventKey *gdk_event, wxWindow *win ) { DEBUG_MAIN_THREAD // don't need to install idle handler, its done from "event" signal if (!win->m_hasVMT) return FALSE; if (g_blockEventsOnDrag) return FALSE; // GTK+ sends keypress events to the focus widget and then // to all its parent and grandparent widget. We only want // the key events from the focus widget. if (!GTK_WIDGET_HAS_FOCUS(widget)) return FALSE; wxKeyEvent event( wxEVT_KEY_DOWN ); bool ret = false; bool return_after_IM = false; if( wxTranslateGTKKeyEventToWx(event, win, gdk_event) ) { // Emit KEY_DOWN event ret = win->GetEventHandler()->ProcessEvent( event ); } else { // Return after IM processing as we cannot do // anything with it anyhow. return_after_IM = true; } // 2005.01.26 modified by Hong Jen Yee (hzysoft@sina.com.tw): // When we get a key_press event here, it could be originate // from the current widget or its child widgets. However, only the widget // with the INPUT FOCUS can generate the INITIAL key_press event. That is, // if the CURRENT widget doesn't have the FOCUS at all, this event definitely // originated from its child widgets and shouldn't be passed to IM context. // In fact, what a GTK+ IM should do is filtering keyEvents and convert them // into text input ONLY WHEN THE WIDGET HAS INPUT FOCUS. Besides, when current // widgets has both IM context and input focus, the event should be filtered // by gtk_im_context_filter_keypress(). // Then, we should, according to GTK+ 2.0 API doc, return whatever it returns. if ((!ret) && (win->m_imData != NULL) && ( g_focusWindow == win )) { // We should let GTK+ IM filter key event first. According to GTK+ 2.0 API // docs, if IM filter returns true, no further processing should be done. // we should send the key_down event anyway. bool intercepted_by_IM = gtk_im_context_filter_keypress(win->m_imData->context, gdk_event); win->m_imData->lastKeyEvent = NULL; if (intercepted_by_IM) { wxLogTrace(TRACE_KEYS, _T("Key event intercepted by IM")); return TRUE; } } if (return_after_IM) return FALSE; #if wxUSE_ACCEL if (!ret) { wxWindowGTK *ancestor = win; while (ancestor) { int command = ancestor->GetAcceleratorTable()->GetCommand( event ); if (command != -1) { wxCommandEvent menu_event( wxEVT_COMMAND_MENU_SELECTED, command ); ret = ancestor->GetEventHandler()->ProcessEvent( menu_event ); if ( !ret ) { // if the accelerator wasn't handled as menu event, try // it as button click (for compatibility with other // platforms): wxCommandEvent button_event( wxEVT_COMMAND_BUTTON_CLICKED, command ); ret = ancestor->GetEventHandler()->ProcessEvent( button_event ); } break; } if (ancestor->IsTopLevel()) break; ancestor = ancestor->GetParent(); } } #endif // wxUSE_ACCEL // Only send wxEVT_CHAR event if not processed yet. Thus, ALT-x // will only be sent if it is not in an accelerator table. if (!ret) { long key_code; KeySym keysym = gdk_event->keyval; // Find key code for EVT_CHAR and EVT_CHAR_HOOK events key_code = wxTranslateKeySymToWXKey(keysym, true /* isChar */); if ( !key_code ) { if ( wxIsAsciiKeysym(keysym) ) { // ASCII key key_code = (unsigned char)keysym; } // gdk_event->string is actually deprecated else if ( gdk_event->length == 1 ) { key_code = (unsigned char)gdk_event->string[0]; } } if ( key_code ) { wxLogTrace(TRACE_KEYS, _T("Char event: %ld"), key_code); event.m_keyCode = key_code; // To conform to the docs we need to translate Ctrl-alpha // characters to values in the range 1-26. if ( event.ControlDown() && ( wxIsLowerChar(key_code) || wxIsUpperChar(key_code) )) { if ( wxIsLowerChar(key_code) ) event.m_keyCode = key_code - 'a' + 1; if ( wxIsUpperChar(key_code) ) event.m_keyCode = key_code - 'A' + 1; #if wxUSE_UNICODE event.m_uniChar = event.m_keyCode; #endif } // Implement OnCharHook by checking ancestor top level windows wxWindow *parent = win; while (parent && !parent->IsTopLevel()) parent = parent->GetParent(); if (parent) { event.SetEventType( wxEVT_CHAR_HOOK ); ret = parent->GetEventHandler()->ProcessEvent( event ); } if (!ret) { event.SetEventType(wxEVT_CHAR); ret = win->GetEventHandler()->ProcessEvent( event ); } } } // win is a control: tab can be propagated up if ( !ret && (gdk_event->keyval == GDK_Tab || gdk_event->keyval == GDK_ISO_Left_Tab) #if wxUSE_TEXTCTRL && !(win->HasFlag(wxTE_PROCESS_TAB) && wxDynamicCast(win, wxTextCtrl)) #endif ) { wxWindow * const parent = win->GetParent(); if ( parent && parent->HasFlag(wxTAB_TRAVERSAL) ) { wxNavigationKeyEvent new_event; new_event.SetEventObject( parent ); // GDK reports GDK_ISO_Left_Tab for SHIFT-TAB new_event.SetDirection( (gdk_event->keyval == GDK_Tab) ); // CTRL-TAB changes the (parent) window, i.e. switch notebook page new_event.SetWindowChange( (gdk_event->state & GDK_CONTROL_MASK) ); new_event.SetCurrentFocus( win ); ret = parent->GetEventHandler()->ProcessEvent( new_event ); } } return ret; } } extern "C" { static void gtk_wxwindow_commit_cb (GtkIMContext *context, const gchar *str, wxWindow *window) { wxKeyEvent event( wxEVT_KEY_DOWN ); // take modifiers, cursor position, timestamp etc. from the last // key_press_event that was fed into Input Method: if (window->m_imData->lastKeyEvent) { wxFillOtherKeyEventFields(event, window, window->m_imData->lastKeyEvent); } else { event.SetEventObject( window ); } const wxWxCharBuffer data(wxGTK_CONV_BACK(str)); if( !data ) return; bool ret = false; // Implement OnCharHook by checking ancestor top level windows wxWindow *parent = window; while (parent && !parent->IsTopLevel()) parent = parent->GetParent(); for( const wxChar* pstr = data; *pstr; pstr++ ) { #if wxUSE_UNICODE event.m_uniChar = *pstr; // Backward compatible for ISO-8859-1 event.m_keyCode = *pstr < 256 ? event.m_uniChar : 0; wxLogTrace(TRACE_KEYS, _T("IM sent character '%c'"), event.m_uniChar); #else event.m_keyCode = *pstr; #endif // wxUSE_UNICODE // To conform to the docs we need to translate Ctrl-alpha // characters to values in the range 1-26. if ( event.ControlDown() && ( wxIsLowerChar(*pstr) || wxIsUpperChar(*pstr) )) { if ( wxIsLowerChar(*pstr) ) event.m_keyCode = *pstr - 'a' + 1; if ( wxIsUpperChar(*pstr) ) event.m_keyCode = *pstr - 'A' + 1; event.m_keyCode = *pstr - 'a' + 1; #if wxUSE_UNICODE event.m_uniChar = event.m_keyCode; #endif } if (parent) { event.SetEventType( wxEVT_CHAR_HOOK ); ret = parent->GetEventHandler()->ProcessEvent( event ); } if (!ret) { event.SetEventType(wxEVT_CHAR); ret = window->GetEventHandler()->ProcessEvent( event ); } } } } //----------------------------------------------------------------------------- // "key_release_event" from any window //----------------------------------------------------------------------------- extern "C" { static gboolean gtk_window_key_release_callback( GtkWidget *widget, GdkEventKey *gdk_event, wxWindowGTK *win ) { DEBUG_MAIN_THREAD // don't need to install idle handler, its done from "event" signal if (!win->m_hasVMT) return FALSE; if (g_blockEventsOnDrag) return FALSE; wxKeyEvent event( wxEVT_KEY_UP ); if ( !wxTranslateGTKKeyEventToWx(event, win, gdk_event) ) { // unknown key pressed, ignore (the event would be useless anyhow) return FALSE; } return win->GTKProcessEvent(event); } } // ============================================================================ // the mouse events // ============================================================================ // ---------------------------------------------------------------------------- // mouse event processing helpers // ---------------------------------------------------------------------------- // init wxMouseEvent with the info from GdkEventXXX struct template<typename T> void InitMouseEvent(wxWindowGTK *win, wxMouseEvent& event, T *gdk_event) { event.SetTimestamp( gdk_event->time ); event.m_shiftDown = (gdk_event->state & GDK_SHIFT_MASK); event.m_controlDown = (gdk_event->state & GDK_CONTROL_MASK); event.m_altDown = (gdk_event->state & GDK_MOD1_MASK); event.m_metaDown = (gdk_event->state & GDK_META_MASK); event.m_leftDown = (gdk_event->state & GDK_BUTTON1_MASK); event.m_middleDown = (gdk_event->state & GDK_BUTTON2_MASK); event.m_rightDown = (gdk_event->state & GDK_BUTTON3_MASK); wxPoint pt = win->GetClientAreaOrigin(); event.m_x = (wxCoord)gdk_event->x - pt.x; event.m_y = (wxCoord)gdk_event->y - pt.y; if ((win->m_wxwindow) && (win->GetLayoutDirection() == wxLayout_RightToLeft)) { // origin in the upper right corner int window_width = gtk_pizza_get_rtl_offset( GTK_PIZZA(win->m_wxwindow) ); event.m_x = window_width - event.m_x; } event.SetEventObject( win ); event.SetId( win->GetId() ); event.SetTimestamp( gdk_event->time ); } static void AdjustEventButtonState(wxMouseEvent& event) { // GDK reports the old state of the button for a button press event, but // for compatibility with MSW and common sense we want m_leftDown be TRUE // for a LEFT_DOWN event, not FALSE, so we will invert // left/right/middleDown for the corresponding click events if ((event.GetEventType() == wxEVT_LEFT_DOWN) || (event.GetEventType() == wxEVT_LEFT_DCLICK) || (event.GetEventType() == wxEVT_LEFT_UP)) { event.m_leftDown = !event.m_leftDown; return; } if ((event.GetEventType() == wxEVT_MIDDLE_DOWN) || (event.GetEventType() == wxEVT_MIDDLE_DCLICK) || (event.GetEventType() == wxEVT_MIDDLE_UP)) { event.m_middleDown = !event.m_middleDown; return; } if ((event.GetEventType() == wxEVT_RIGHT_DOWN) || (event.GetEventType() == wxEVT_RIGHT_DCLICK) || (event.GetEventType() == wxEVT_RIGHT_UP)) { event.m_rightDown = !event.m_rightDown; return; } } // find the window to send the mouse event too static wxWindowGTK *FindWindowForMouseEvent(wxWindowGTK *win, wxCoord& x, wxCoord& y) { wxCoord xx = x; wxCoord yy = y; if (win->m_wxwindow) { GtkPizza *pizza = GTK_PIZZA(win->m_wxwindow); xx += gtk_pizza_get_xoffset( pizza ); yy += gtk_pizza_get_yoffset( pizza ); } wxWindowList::compatibility_iterator node = win->GetChildren().GetFirst(); while (node) { wxWindowGTK *child = node->GetData(); node = node->GetNext(); if (!child->IsShown()) continue; if (child->IsTransparentForMouse()) { // wxStaticBox is transparent in the box itself int xx1 = child->m_x; int yy1 = child->m_y; int xx2 = child->m_x + child->m_width; int yy2 = child->m_y + child->m_height; // left if (((xx >= xx1) && (xx <= xx1+10) && (yy >= yy1) && (yy <= yy2)) || // right ((xx >= xx2-10) && (xx <= xx2) && (yy >= yy1) && (yy <= yy2)) || // top ((xx >= xx1) && (xx <= xx2) && (yy >= yy1) && (yy <= yy1+10)) || // bottom ((xx >= xx1) && (xx <= xx2) && (yy >= yy2-1) && (yy <= yy2))) { win = child; x -= child->m_x; y -= child->m_y; break; } } else { if ((child->m_wxwindow == (GtkWidget*) NULL) && (child->m_x <= xx) && (child->m_y <= yy) && (child->m_x+child->m_width >= xx) && (child->m_y+child->m_height >= yy)) { win = child; x -= child->m_x; y -= child->m_y; break; } } } return win; } // ---------------------------------------------------------------------------- // common event handlers helpers // ---------------------------------------------------------------------------- bool wxWindowGTK::GTKProcessEvent(wxEvent& event) const { // nothing special at this level return GetEventHandler()->ProcessEvent(event); } int wxWindowGTK::GTKCallbackCommonPrologue(GdkEventAny *event) const { DEBUG_MAIN_THREAD // don't need to install idle handler, its done from "event" signal if (!m_hasVMT) return FALSE; if (g_blockEventsOnDrag) return TRUE; if (g_blockEventsOnScroll) return TRUE; if (!GTKIsOwnWindow(event->window)) return FALSE; return -1; } // overloads for all GDK event types we use here: we need to have this as // GdkEventXXX can't be implicitly cast to GdkEventAny even if it, in fact, // derives from it in the sense that the structs have the same layout #define wxDEFINE_COMMON_PROLOGUE_OVERLOAD(T) \ static int wxGtkCallbackCommonPrologue(T *event, wxWindowGTK *win) \ { \ return win->GTKCallbackCommonPrologue((GdkEventAny *)event); \ } wxDEFINE_COMMON_PROLOGUE_OVERLOAD(GdkEventButton) wxDEFINE_COMMON_PROLOGUE_OVERLOAD(GdkEventMotion) wxDEFINE_COMMON_PROLOGUE_OVERLOAD(GdkEventCrossing) #undef wxDEFINE_COMMON_PROLOGUE_OVERLOAD #define wxCOMMON_CALLBACK_PROLOGUE(event, win) \ const int rc = wxGtkCallbackCommonPrologue(event, win); \ if ( rc != -1 ) \ return rc // send the wxChildFocusEvent and wxFocusEvent, common code of // gtk_window_focus_in_callback() and SetFocus() static bool DoSendFocusEvents(wxWindow *win) { // Notify the parent keeping track of focus for the kbd navigation // purposes that we got it. wxChildFocusEvent eventChildFocus(win); (void)win->GetEventHandler()->ProcessEvent(eventChildFocus); wxFocusEvent eventFocus(wxEVT_SET_FOCUS, win->GetId()); eventFocus.SetEventObject(win); return win->GetEventHandler()->ProcessEvent(eventFocus); } // all event handlers must have C linkage as they're called from GTK+ C code extern "C" { //----------------------------------------------------------------------------- // "button_press_event" //----------------------------------------------------------------------------- static gboolean gtk_window_button_press_callback( GtkWidget *widget, GdkEventButton *gdk_event, wxWindowGTK *win ) { wxCOMMON_CALLBACK_PROLOGUE(gdk_event, win); g_lastButtonNumber = gdk_event->button; // GDK sends surplus button down events // before a double click event. We // need to filter these out. if ((gdk_event->type == GDK_BUTTON_PRESS) && (win->m_wxwindow)) { GdkEvent *peek_event = gdk_event_peek(); if (peek_event) { if ((peek_event->type == GDK_2BUTTON_PRESS) || (peek_event->type == GDK_3BUTTON_PRESS)) { gdk_event_free( peek_event ); return TRUE; } else { gdk_event_free( peek_event ); } } } wxEventType event_type = wxEVT_NULL; // GdkDisplay is a GTK+ 2.2.0 thing #if defined(__WXGTK20__) && GTK_CHECK_VERSION(2, 2, 0) if ( gdk_event->type == GDK_2BUTTON_PRESS && !gtk_check_version(2,2,0) && gdk_event->button >= 1 && gdk_event->button <= 3 ) { // Reset GDK internal timestamp variables in order to disable GDK // triple click events. GDK will then next time believe no button has // been clicked just before, and send a normal button click event. GdkDisplay* display = gtk_widget_get_display (widget); display->button_click_time[1] = 0; display->button_click_time[0] = 0; } #endif // GTK 2+ if (gdk_event->button == 1) { // note that GDK generates triple click events which are not supported // by wxWidgets but still have to be passed to the app as otherwise // clicks would simply go missing switch (gdk_event->type) { // we shouldn't get triple clicks at all for GTK2 because we // suppress them artificially using the code above but we still // should map them to something for GTK1 and not just ignore them // as this would lose clicks case GDK_3BUTTON_PRESS: // we could also map this to DCLICK... case GDK_BUTTON_PRESS: event_type = wxEVT_LEFT_DOWN; break; case GDK_2BUTTON_PRESS: event_type = wxEVT_LEFT_DCLICK; break; default: // just to silence gcc warnings ; } } else if (gdk_event->button == 2) { switch (gdk_event->type) { case GDK_3BUTTON_PRESS: case GDK_BUTTON_PRESS: event_type = wxEVT_MIDDLE_DOWN; break; case GDK_2BUTTON_PRESS: event_type = wxEVT_MIDDLE_DCLICK; break; default: ; } } else if (gdk_event->button == 3) { switch (gdk_event->type) { case GDK_3BUTTON_PRESS: case GDK_BUTTON_PRESS: event_type = wxEVT_RIGHT_DOWN; break; case GDK_2BUTTON_PRESS: event_type = wxEVT_RIGHT_DCLICK; break; default: ; } } if ( event_type == wxEVT_NULL ) { // unknown mouse button or click type return FALSE; } g_lastMouseEvent = (GdkEvent*) gdk_event; wxMouseEvent event( event_type ); InitMouseEvent( win, event, gdk_event ); AdjustEventButtonState(event); // wxListBox actually gets mouse events from the item, so we need to give it // a chance to correct this win->FixUpMouseEvent(widget, event.m_x, event.m_y); // find the correct window to send the event to: it may be a different one // from the one which got it at GTK+ level because some controls don't have // their own X window and thus cannot get any events. if ( !g_captureWindow ) win = FindWindowForMouseEvent(win, event.m_x, event.m_y); // reset the event object and id in case win changed. event.SetEventObject( win ); event.SetId( win->GetId() ); bool ret = win->GTKProcessEvent( event ); g_lastMouseEvent = NULL; if ( ret ) return TRUE; if ((event_type == wxEVT_LEFT_DOWN) && (g_focusWindow != win) && win->AcceptsFocus()) { win->SetFocus(); } if (event_type == wxEVT_RIGHT_DOWN) { // generate a "context menu" event: this is similar to right mouse // click under many GUIs except that it is generated differently // (right up under MSW, ctrl-click under Mac, right down here) and // // (a) it's a command event and so is propagated to the parent // (b) under some ports it can be generated from kbd too // (c) it uses screen coords (because of (a)) wxContextMenuEvent evtCtx( wxEVT_CONTEXT_MENU, win->GetId(), win->ClientToScreen(event.GetPosition())); evtCtx.SetEventObject(win); return win->GTKProcessEvent(evtCtx); } return FALSE; } //----------------------------------------------------------------------------- // "button_release_event" //----------------------------------------------------------------------------- static gboolean gtk_window_button_release_callback( GtkWidget *widget, GdkEventButton *gdk_event, wxWindowGTK *win ) { wxCOMMON_CALLBACK_PROLOGUE(gdk_event, win); g_lastButtonNumber = 0; wxEventType event_type = wxEVT_NULL; switch (gdk_event->button) { case 1: event_type = wxEVT_LEFT_UP; break; case 2: event_type = wxEVT_MIDDLE_UP; break; case 3: event_type = wxEVT_RIGHT_UP; break; default: // unknown button, don't process return FALSE; } g_lastMouseEvent = (GdkEvent*) gdk_event; wxMouseEvent event( event_type ); InitMouseEvent( win, event, gdk_event ); AdjustEventButtonState(event); // same wxListBox hack as above win->FixUpMouseEvent(widget, event.m_x, event.m_y); if ( !g_captureWindow ) win = FindWindowForMouseEvent(win, event.m_x, event.m_y); // reset the event object and id in case win changed. event.SetEventObject( win ); event.SetId( win->GetId() ); bool ret = win->GTKProcessEvent(event); g_lastMouseEvent = NULL; return ret; } //----------------------------------------------------------------------------- // "motion_notify_event" //----------------------------------------------------------------------------- static gboolean gtk_window_motion_notify_callback( GtkWidget *widget, GdkEventMotion *gdk_event, wxWindowGTK *win ) { wxCOMMON_CALLBACK_PROLOGUE(gdk_event, win); if (gdk_event->is_hint) { int x = 0; int y = 0; GdkModifierType state; gdk_window_get_pointer(gdk_event->window, &x, &y, &state); gdk_event->x = x; gdk_event->y = y; } g_lastMouseEvent = (GdkEvent*) gdk_event; wxMouseEvent event( wxEVT_MOTION ); InitMouseEvent(win, event, gdk_event); if ( g_captureWindow ) { // synthesise a mouse enter or leave event if needed GdkWindow *winUnderMouse = gdk_window_at_pointer(NULL, NULL); // This seems to be necessary and actually been added to // GDK itself in version 2.0.X gdk_flush(); bool hasMouse = winUnderMouse == gdk_event->window; if ( hasMouse != g_captureWindowHasMouse ) { // the mouse changed window g_captureWindowHasMouse = hasMouse; wxMouseEvent eventM(g_captureWindowHasMouse ? wxEVT_ENTER_WINDOW : wxEVT_LEAVE_WINDOW); InitMouseEvent(win, eventM, gdk_event); eventM.SetEventObject(win); win->GTKProcessEvent(eventM); } } else // no capture { win = FindWindowForMouseEvent(win, event.m_x, event.m_y); // reset the event object and id in case win changed. event.SetEventObject( win ); event.SetId( win->GetId() ); } if ( !g_captureWindow ) { wxSetCursorEvent cevent( event.m_x, event.m_y ); if (win->GTKProcessEvent( cevent )) { win->SetCursor( cevent.GetCursor() ); } } bool ret = win->GTKProcessEvent(event); g_lastMouseEvent = NULL; return ret; } //----------------------------------------------------------------------------- // "scroll_event" (mouse wheel event) //----------------------------------------------------------------------------- static gboolean window_scroll_event(GtkWidget*, GdkEventScroll* gdk_event, wxWindow* win) { DEBUG_MAIN_THREAD // don't need to install idle handler, its done from "event" signal if (gdk_event->direction != GDK_SCROLL_UP && gdk_event->direction != GDK_SCROLL_DOWN) { return false; } wxMouseEvent event(wxEVT_MOUSEWHEEL); // Can't use InitMouse macro because scroll events don't have button event.SetTimestamp( gdk_event->time ); event.m_shiftDown = (gdk_event->state & GDK_SHIFT_MASK); event.m_controlDown = (gdk_event->state & GDK_CONTROL_MASK); event.m_altDown = (gdk_event->state & GDK_MOD1_MASK); event.m_metaDown = (gdk_event->state & GDK_META_MASK); event.m_leftDown = (gdk_event->state & GDK_BUTTON1_MASK); event.m_middleDown = (gdk_event->state & GDK_BUTTON2_MASK); event.m_rightDown = (gdk_event->state & GDK_BUTTON3_MASK); // FIXME: Get these values from GTK or GDK event.m_linesPerAction = 3; event.m_wheelDelta = 120; if (gdk_event->direction == GDK_SCROLL_UP) event.m_wheelRotation = 120; else event.m_wheelRotation = -120; wxPoint pt = win->GetClientAreaOrigin(); event.m_x = (wxCoord)gdk_event->x - pt.x; event.m_y = (wxCoord)gdk_event->y - pt.y; event.SetEventObject( win ); event.SetId( win->GetId() ); event.SetTimestamp( gdk_event->time ); return win->GTKProcessEvent(event); } //----------------------------------------------------------------------------- // "popup-menu" //----------------------------------------------------------------------------- static gboolean wxgtk_window_popup_menu_callback(GtkWidget*, wxWindowGTK* win) { wxContextMenuEvent event(wxEVT_CONTEXT_MENU, win->GetId(), wxPoint(-1, -1)); event.SetEventObject(win); return win->GTKProcessEvent(event); } //----------------------------------------------------------------------------- // "focus_in_event" //----------------------------------------------------------------------------- static gboolean gtk_window_focus_in_callback( GtkWidget *widget, GdkEventFocus *WXUNUSED(event), wxWindow *win ) { DEBUG_MAIN_THREAD // don't need to install idle handler, its done from "event" signal if (win->m_imData) gtk_im_context_focus_in(win->m_imData->context); g_focusWindowLast = g_focusWindow = win; g_focusWindowPending = NULL; wxLogTrace(TRACE_FOCUS, _T("%s: focus in"), win->GetName().c_str()); #if wxUSE_CARET // caret needs to be informed about focus change wxCaret *caret = win->GetCaret(); if ( caret ) { caret->OnSetFocus(); } #endif // wxUSE_CARET gboolean ret = FALSE; // does the window itself think that it has the focus? if ( !win->m_hasFocus ) { // not yet, notify it win->m_hasFocus = true; (void)DoSendFocusEvents(win); ret = TRUE; } // Disable default focus handling for custom windows // since the default GTK+ handler issues a repaint if (win->m_wxwindow) return ret; return FALSE; } //----------------------------------------------------------------------------- // "focus_out_event" //----------------------------------------------------------------------------- static gboolean gtk_window_focus_out_callback( GtkWidget *widget, GdkEventFocus *gdk_event, wxWindowGTK *win ) { DEBUG_MAIN_THREAD // don't need to install idle handler, its done from "event" signal if (win->m_imData) gtk_im_context_focus_out(win->m_imData->context); wxLogTrace( TRACE_FOCUS, _T("%s: focus out"), win->GetName().c_str() ); wxWindowGTK *winFocus = wxFindFocusedChild(win); if ( winFocus ) win = winFocus; g_focusWindow = (wxWindowGTK *)NULL; #if wxUSE_CARET // caret needs to be informed about focus change wxCaret *caret = win->GetCaret(); if ( caret ) { caret->OnKillFocus(); } #endif // wxUSE_CARET // don't send the window a kill focus event if it thinks that it doesn't // have focus already if ( win->m_hasFocus ) { // the event handler might delete the window when it loses focus, so // check whether this is a custom window before calling it const bool has_wxwindow = win->m_wxwindow != NULL; win->m_hasFocus = false; wxFocusEvent event( wxEVT_KILL_FOCUS, win->GetId() ); event.SetEventObject( win ); (void)win->GTKProcessEvent( event ); // Disable default focus handling for custom windows // since the default GTK+ handler issues a repaint if ( has_wxwindow ) return TRUE; } // continue with normal processing return FALSE; } //----------------------------------------------------------------------------- // "enter_notify_event" //----------------------------------------------------------------------------- static gboolean gtk_window_enter_callback( GtkWidget *widget, GdkEventCrossing *gdk_event, wxWindowGTK *win ) { wxCOMMON_CALLBACK_PROLOGUE(gdk_event, win); // Event was emitted after a grab if (gdk_event->mode != GDK_CROSSING_NORMAL) return FALSE; int x = 0; int y = 0; GdkModifierType state = (GdkModifierType)0; gdk_window_get_pointer( widget->window, &x, &y, &state ); wxMouseEvent event( wxEVT_ENTER_WINDOW ); InitMouseEvent(win, event, gdk_event); wxPoint pt = win->GetClientAreaOrigin(); event.m_x = x + pt.x; event.m_y = y + pt.y; if ( !g_captureWindow ) { wxSetCursorEvent cevent( event.m_x, event.m_y ); if (win->GTKProcessEvent( cevent )) { win->SetCursor( cevent.GetCursor() ); } } return win->GTKProcessEvent(event); } //----------------------------------------------------------------------------- // "leave_notify_event" //----------------------------------------------------------------------------- static gboolean gtk_window_leave_callback( GtkWidget *widget, GdkEventCrossing *gdk_event, wxWindowGTK *win ) { wxCOMMON_CALLBACK_PROLOGUE(gdk_event, win); // Event was emitted after an ungrab if (gdk_event->mode != GDK_CROSSING_NORMAL) return FALSE; wxMouseEvent event( wxEVT_LEAVE_WINDOW ); event.SetTimestamp( gdk_event->time ); event.SetEventObject( win ); int x = 0; int y = 0; GdkModifierType state = (GdkModifierType)0; gdk_window_get_pointer( widget->window, &x, &y, &state ); event.m_shiftDown = (state & GDK_SHIFT_MASK) != 0; event.m_controlDown = (state & GDK_CONTROL_MASK) != 0; event.m_altDown = (state & GDK_MOD1_MASK) != 0; event.m_metaDown = (state & GDK_META_MASK) != 0; event.m_leftDown = (state & GDK_BUTTON1_MASK) != 0; event.m_middleDown = (state & GDK_BUTTON2_MASK) != 0; event.m_rightDown = (state & GDK_BUTTON3_MASK) != 0; wxPoint pt = win->GetClientAreaOrigin(); event.m_x = x + pt.x; event.m_y = y + pt.y; return win->GTKProcessEvent(event); } //----------------------------------------------------------------------------- // "value_changed" from scrollbar //----------------------------------------------------------------------------- static void gtk_scrollbar_value_changed(GtkRange* range, wxWindow* win) { wxEventType eventType = win->GetScrollEventType(range); if (eventType != wxEVT_NULL) { // Convert scroll event type to scrollwin event type eventType += wxEVT_SCROLLWIN_TOP - wxEVT_SCROLL_TOP; // find the scrollbar which generated the event wxWindowGTK::ScrollDir dir = win->ScrollDirFromRange(range); // generate the corresponding wx event const int orient = wxWindow::OrientFromScrollDir(dir); wxScrollWinEvent event(eventType, win->GetScrollPos(orient), orient); event.SetEventObject(win); win->GTKProcessEvent(event); } } //----------------------------------------------------------------------------- // "button_press_event" from scrollbar //----------------------------------------------------------------------------- static gboolean gtk_scrollbar_button_press_event(GtkRange*, GdkEventButton*, wxWindow* win) { DEBUG_MAIN_THREAD // don't need to install idle handler, its done from "event" signal g_blockEventsOnScroll = true; win->m_mouseButtonDown = true; return false; } //----------------------------------------------------------------------------- // "event_after" from scrollbar //----------------------------------------------------------------------------- static void gtk_scrollbar_event_after(GtkRange* range, GdkEvent* event, wxWindow* win) { if (event->type == GDK_BUTTON_RELEASE) { g_signal_handlers_block_by_func(range, (void*)gtk_scrollbar_event_after, win); const int orient = wxWindow::OrientFromScrollDir( win->ScrollDirFromRange(range)); wxScrollWinEvent event(wxEVT_SCROLLWIN_THUMBRELEASE, win->GetScrollPos(orient), orient); event.SetEventObject(win); win->GTKProcessEvent(event); } } //----------------------------------------------------------------------------- // "button_release_event" from scrollbar //----------------------------------------------------------------------------- static gboolean gtk_scrollbar_button_release_event(GtkRange* range, GdkEventButton*, wxWindow* win) { DEBUG_MAIN_THREAD g_blockEventsOnScroll = false; win->m_mouseButtonDown = false; // If thumb tracking if (win->m_isScrolling) { win->m_isScrolling = false; // Hook up handler to send thumb release event after this emission is finished. // To allow setting scroll position from event handler, sending event must // be deferred until after the GtkRange handler for this signal has run g_signal_handlers_unblock_by_func(range, (void*)gtk_scrollbar_event_after, win); } return false; } //----------------------------------------------------------------------------- // "realize" from m_widget //----------------------------------------------------------------------------- /* We cannot set colours and fonts before the widget has been realized, so we do this directly after realization. */ static void gtk_window_realized_callback( GtkWidget *m_widget, wxWindow *win ) { DEBUG_MAIN_THREAD if (g_isIdle) wxapp_install_idle_handler(); if (win->m_imData) { GtkPizza *pizza = GTK_PIZZA( m_widget ); gtk_im_context_set_client_window( win->m_imData->context, pizza->bin_window ); } wxWindowCreateEvent event( win ); event.SetEventObject( win ); win->GTKProcessEvent( event ); } //----------------------------------------------------------------------------- // "size_allocate" //----------------------------------------------------------------------------- static void gtk_window_size_callback( GtkWidget *WXUNUSED(widget), GtkAllocation *alloc, wxWindow *win ) { if (g_isIdle) wxapp_install_idle_handler(); int client_width = 0; int client_height = 0; win->GetClientSize( &client_width, &client_height ); if ((client_width == win->m_oldClientWidth) && (client_height == win->m_oldClientHeight)) return; if ( !client_width && !client_height ) { // the window is currently unmapped, don't generate size events return; } win->m_oldClientWidth = client_width; win->m_oldClientHeight = client_height; if (!win->m_nativeSizeEvent) { wxSizeEvent event( win->GetSize(), win->GetId() ); event.SetEventObject( win ); win->GTKProcessEvent( event ); } } //----------------------------------------------------------------------------- // "style_set" //----------------------------------------------------------------------------- static void gtk_window_style_set_callback( GtkWidget *widget, GtkStyle *previous_style, wxWindow* win ) { if (win && previous_style) { wxSysColourChangedEvent event; event.SetEventObject(win); win->GTKProcessEvent( event ); } } } // extern "C" // Connect/disconnect style-set void wxConnectStyleSet(wxWindow* win) { if (win->m_wxwindow) g_signal_connect (win->m_wxwindow, "style_set", G_CALLBACK (gtk_window_style_set_callback), win); } void wxDisconnectStyleSet(wxWindow* win) { if (win->m_wxwindow) g_signal_handlers_disconnect_by_func (win->m_wxwindow, (gpointer) gtk_window_style_set_callback, win); } // Helper to suspend colour change event event processing while we change a widget's style class wxSuspendStyleEvents { public: wxSuspendStyleEvents(wxWindow* win) { m_win = win; #if USE_STYLE_SET_CALLBACK if (win->IsTopLevel()) wxDisconnectStyleSet(win); #endif } ~wxSuspendStyleEvents() { #if USE_STYLE_SET_CALLBACK if (m_win->IsTopLevel()) wxConnectStyleSet(m_win); #endif } wxWindow* m_win; }; // ---------------------------------------------------------------------------- // this wxWindowBase function is implemented here (in platform-specific file) // because it is static and so couldn't be made virtual // ---------------------------------------------------------------------------- wxWindow *wxWindowBase::DoFindFocus() { // the cast is necessary when we compile in wxUniversal mode return (wxWindow *)(g_focusWindowPending ? g_focusWindowPending : g_focusWindow); } //----------------------------------------------------------------------------- // InsertChild for wxWindowGTK. //----------------------------------------------------------------------------- /* Callback for wxWindowGTK. This very strange beast has to be used because * C++ has no virtual methods in a constructor. We have to emulate a * virtual function here as wxNotebook requires a different way to insert * a child in it. I had opted for creating a wxNotebookPage window class * which would have made this superfluous (such in the MDI window system), * but no-one was listening to me... */ static void wxInsertChildInWindow( wxWindowGTK* parent, wxWindowGTK* child ) { /* the window might have been scrolled already, do we have to adapt the position */ GtkPizza *pizza = GTK_PIZZA(parent->m_wxwindow); child->m_x += gtk_pizza_get_xoffset( pizza ); child->m_y += gtk_pizza_get_yoffset( pizza ); gtk_pizza_put( GTK_PIZZA(parent->m_wxwindow), GTK_WIDGET(child->m_widget), child->m_x, child->m_y, child->m_width, child->m_height ); } //----------------------------------------------------------------------------- // global functions //----------------------------------------------------------------------------- wxWindow *wxGetActiveWindow() { return wxWindow::FindFocus(); } wxMouseState wxGetMouseState() { wxMouseState ms; gint x; gint y; GdkModifierType mask; gdk_window_get_pointer(NULL, &x, &y, &mask); ms.SetX(x); ms.SetY(y); ms.SetLeftDown(mask & GDK_BUTTON1_MASK); ms.SetMiddleDown(mask & GDK_BUTTON2_MASK); ms.SetRightDown(mask & GDK_BUTTON3_MASK); ms.SetControlDown(mask & GDK_CONTROL_MASK); ms.SetShiftDown(mask & GDK_SHIFT_MASK); ms.SetAltDown(mask & GDK_MOD1_MASK); ms.SetMetaDown(mask & GDK_META_MASK); return ms; } //----------------------------------------------------------------------------- // wxWindowGTK //----------------------------------------------------------------------------- // in wxUniv/MSW this class is abstract because it doesn't have DoPopupMenu() // method #ifdef __WXUNIVERSAL__ IMPLEMENT_ABSTRACT_CLASS(wxWindowGTK, wxWindowBase) #else // __WXGTK__ IMPLEMENT_DYNAMIC_CLASS(wxWindow, wxWindowBase) #endif // __WXUNIVERSAL__/__WXGTK__ void wxWindowGTK::Init() { // GTK specific m_widget = (GtkWidget *) NULL; m_wxwindow = (GtkWidget *) NULL; m_focusWidget = (GtkWidget *) NULL; // position/size m_x = 0; m_y = 0; m_width = 0; m_height = 0; m_sizeSet = false; m_hasVMT = false; m_needParent = true; m_isBeingDeleted = false; m_showOnIdle= false; m_noExpose = false; m_nativeSizeEvent = false; m_hasScrolling = false; m_isScrolling = false; m_mouseButtonDown = false; m_blockScrollEvent = false; // initialize scrolling stuff for ( int dir = 0; dir < ScrollDir_Max; dir++ ) { m_scrollBar[dir] = NULL; m_scrollPos[dir] = 0; m_blockValueChanged[dir] = false; } m_oldClientWidth = m_oldClientHeight = 0; m_resizing = false; m_insertCallback = (wxInsertChildFunction) NULL; m_acceptsFocus = false; m_hasFocus = false; m_clipPaintRegion = false; m_needsStyleChange = false; m_cursor = *wxSTANDARD_CURSOR; m_imData = NULL; m_dirtyTabOrder = false; } wxWindowGTK::wxWindowGTK() { Init(); } wxWindowGTK::wxWindowGTK( wxWindow *parent, wxWindowID id, const wxPoint &pos, const wxSize &size, long style, const wxString &name ) { Init(); Create( parent, id, pos, size, style, name ); } bool wxWindowGTK::Create( wxWindow *parent, wxWindowID id, const wxPoint &pos, const wxSize &size, long style, const wxString &name ) { if (!PreCreation( parent, pos, size ) || !CreateBase( parent, id, pos, size, style, wxDefaultValidator, name )) { wxFAIL_MSG( wxT("wxWindowGTK creation failed") ); return false; } m_insertCallback = wxInsertChildInWindow; m_widget = gtk_scrolled_window_new( (GtkAdjustment *) NULL, (GtkAdjustment *) NULL ); GTK_WIDGET_UNSET_FLAGS( m_widget, GTK_CAN_FOCUS ); GtkScrolledWindow *scrolledWindow = GTK_SCROLLED_WINDOW(m_widget); GtkScrolledWindowClass *scroll_class = GTK_SCROLLED_WINDOW_CLASS( GTK_OBJECT_GET_CLASS(m_widget) ); scroll_class->scrollbar_spacing = 0; if (HasFlag(wxALWAYS_SHOW_SB)) { gtk_scrolled_window_set_policy( scrolledWindow, GTK_POLICY_ALWAYS, GTK_POLICY_ALWAYS ); scrolledWindow->hscrollbar_visible = TRUE; scrolledWindow->vscrollbar_visible = TRUE; } else { gtk_scrolled_window_set_policy( scrolledWindow, GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC ); } m_scrollBar[ScrollDir_Horz] = GTK_RANGE(scrolledWindow->hscrollbar); m_scrollBar[ScrollDir_Vert] = GTK_RANGE(scrolledWindow->vscrollbar); if (GetLayoutDirection() == wxLayout_RightToLeft) gtk_range_set_inverted( m_scrollBar[ScrollDir_Horz], TRUE ); m_wxwindow = gtk_pizza_new(); #ifndef __WXUNIVERSAL__ if (HasFlag(wxSIMPLE_BORDER)) gtk_container_set_border_width((GtkContainer*)m_wxwindow, 1); else if (HasFlag(wxRAISED_BORDER) || HasFlag(wxSUNKEN_BORDER)) gtk_container_set_border_width((GtkContainer*)m_wxwindow, 2); #endif // __WXUNIVERSAL__ gtk_container_add( GTK_CONTAINER(m_widget), m_wxwindow ); GTK_WIDGET_SET_FLAGS( m_wxwindow, GTK_CAN_FOCUS ); m_acceptsFocus = true; // connect various scroll-related events for ( int dir = 0; dir < ScrollDir_Max; dir++ ) { // these handlers block mouse events to any window during scrolling // such as motion events and prevent GTK and wxWidgets from fighting // over where the slider should be g_signal_connect(m_scrollBar[dir], "button_press_event", G_CALLBACK(gtk_scrollbar_button_press_event), this); g_signal_connect(m_scrollBar[dir], "button_release_event", G_CALLBACK(gtk_scrollbar_button_release_event), this); gulong handler_id = g_signal_connect(m_scrollBar[dir], "event_after", G_CALLBACK(gtk_scrollbar_event_after), this); g_signal_handler_block(m_scrollBar[dir], handler_id); // these handlers get notified when scrollbar slider moves g_signal_connect_after(m_scrollBar[dir], "value_changed", G_CALLBACK(gtk_scrollbar_value_changed), this); } gtk_widget_show( m_wxwindow ); if (m_parent) m_parent->DoAddChild( this ); m_focusWidget = m_wxwindow; PostCreation(); return true; } wxWindowGTK::~wxWindowGTK() { SendDestroyEvent(); if (g_focusWindow == this) g_focusWindow = NULL; if (g_focusWindowPending == this) g_focusWindowPending = NULL; if ( g_delayedFocus == this ) g_delayedFocus = NULL; m_isBeingDeleted = true; m_hasVMT = false; // destroy children before destroying this window itself DestroyChildren(); // unhook focus handlers to prevent stray events being // propagated to this (soon to be) dead object if (m_focusWidget != NULL) { g_signal_handlers_disconnect_by_func (m_focusWidget, (gpointer) gtk_window_focus_in_callback, this); g_signal_handlers_disconnect_by_func (m_focusWidget, (gpointer) gtk_window_focus_out_callback, this); } if (m_widget) Show( false ); // delete before the widgets to avoid a crash on solaris delete m_imData; if (m_wxwindow) { gtk_widget_destroy( m_wxwindow ); m_wxwindow = (GtkWidget*) NULL; } if (m_widget) { gtk_widget_destroy( m_widget ); m_widget = (GtkWidget*) NULL; } } bool wxWindowGTK::PreCreation( wxWindowGTK *parent, const wxPoint &pos, const wxSize &size ) { wxCHECK_MSG( !m_needParent || parent, false, wxT("Need complete parent.") ); // Use either the given size, or the default if -1 is given. // See wxWindowBase for these functions. m_width = WidthDefault(size.x) ; m_height = HeightDefault(size.y); m_x = (int)pos.x; m_y = (int)pos.y; return true; } void wxWindowGTK::PostCreation() { wxASSERT_MSG( (m_widget != NULL), wxT("invalid window") ); if (m_wxwindow) { if (!m_noExpose) { // these get reported to wxWidgets -> wxPaintEvent g_signal_connect (m_wxwindow, "expose_event", G_CALLBACK (gtk_window_expose_callback), this); if (GetLayoutDirection() == wxLayout_LeftToRight) gtk_widget_set_redraw_on_allocate( GTK_WIDGET(m_wxwindow), HasFlag( wxFULL_REPAINT_ON_RESIZE ) ); } // Create input method handler m_imData = new wxGtkIMData; // Cannot handle drawing preedited text yet gtk_im_context_set_use_preedit( m_imData->context, FALSE ); g_signal_connect (m_imData->context, "commit", G_CALLBACK (gtk_wxwindow_commit_cb), this); // these are called when the "sunken" or "raised" borders are drawn g_signal_connect (m_widget, "expose_event", G_CALLBACK (gtk_window_own_expose_callback), this); } // focus handling if (!GTK_IS_WINDOW(m_widget)) { if (m_focusWidget == NULL) m_focusWidget = m_widget; if (m_wxwindow) { g_signal_connect (m_focusWidget, "focus_in_event", G_CALLBACK (gtk_window_focus_in_callback), this); g_signal_connect (m_focusWidget, "focus_out_event", G_CALLBACK (gtk_window_focus_out_callback), this); } else { g_signal_connect_after (m_focusWidget, "focus_in_event", G_CALLBACK (gtk_window_focus_in_callback), this); g_signal_connect_after (m_focusWidget, "focus_out_event", G_CALLBACK (gtk_window_focus_out_callback), this); } } // connect to the various key and mouse handlers GtkWidget *connect_widget = GetConnectWidget(); ConnectWidget( connect_widget ); /* We cannot set colours, fonts and cursors before the widget has been realized, so we do this directly after realization */ g_signal_connect (connect_widget, "realize", G_CALLBACK (gtk_window_realized_callback), this); if (m_wxwindow) { // Catch native resize events g_signal_connect (m_wxwindow, "size_allocate", G_CALLBACK (gtk_window_size_callback), this); } if (GTK_IS_COMBO(m_widget)) { GtkCombo *gcombo = GTK_COMBO(m_widget); g_signal_connect (gcombo->entry, "size_request", G_CALLBACK (wxgtk_combo_size_request_callback), this); } #ifdef GTK_IS_FILE_CHOOSER_BUTTON else if (!gtk_check_version(2,6,0) && GTK_IS_FILE_CHOOSER_BUTTON(m_widget)) { // If we connect to the "size_request" signal of a GtkFileChooserButton // then that control won't be sized properly when placed inside sizers // (this can be tested removing this elseif and running XRC or WIDGETS samples) // FIXME: what should be done here ? } #endif else { // This is needed if we want to add our windows into native // GTK controls, such as the toolbar. With this callback, the // toolbar gets to know the correct size (the one set by the // programmer). Sadly, it misbehaves for wxComboBox. g_signal_connect (m_widget, "size_request", G_CALLBACK (wxgtk_window_size_request_callback), this); } InheritAttributes(); m_hasVMT = true; SetLayoutDirection(wxLayout_Default); // unless the window was created initially hidden (i.e. Hide() had been // called before Create()), we should show it at GTK+ level as well if ( IsShown() ) gtk_widget_show( m_widget ); } void wxWindowGTK::ConnectWidget( GtkWidget *widget ) { g_signal_connect (widget, "key_press_event", G_CALLBACK (gtk_window_key_press_callback), this); g_signal_connect (widget, "key_release_event", G_CALLBACK (gtk_window_key_release_callback), this); g_signal_connect (widget, "button_press_event", G_CALLBACK (gtk_window_button_press_callback), this); g_signal_connect (widget, "button_release_event", G_CALLBACK (gtk_window_button_release_callback), this); g_signal_connect (widget, "motion_notify_event", G_CALLBACK (gtk_window_motion_notify_callback), this); g_signal_connect (widget, "scroll_event", G_CALLBACK (window_scroll_event), this); g_signal_connect (widget, "popup_menu", G_CALLBACK (wxgtk_window_popup_menu_callback), this); g_signal_connect (widget, "enter_notify_event", G_CALLBACK (gtk_window_enter_callback), this); g_signal_connect (widget, "leave_notify_event", G_CALLBACK (gtk_window_leave_callback), this); #if USE_STYLE_SET_CALLBACK if (IsTopLevel() && m_wxwindow) g_signal_connect (m_wxwindow, "style_set", G_CALLBACK (gtk_window_style_set_callback), this); #endif } bool wxWindowGTK::Destroy() { wxASSERT_MSG( (m_widget != NULL), wxT("invalid window") ); m_hasVMT = false; return wxWindowBase::Destroy(); } void wxWindowGTK::DoMoveWindow(int x, int y, int width, int height) { // inform the parent to perform the move gtk_pizza_set_size( GTK_PIZZA(m_parent->m_wxwindow), m_widget, x, y, width, height ); } void wxWindowGTK::DoSetSize( int x, int y, int width, int height, int sizeFlags ) { wxASSERT_MSG( (m_widget != NULL), wxT("invalid window") ); wxASSERT_MSG( (m_parent != NULL), wxT("wxWindowGTK::SetSize requires parent.\n") ); if (m_resizing) return; /* I don't like recursions */ m_resizing = true; int currentX, currentY; GetPosition(&currentX, &currentY); if (x == -1 && !(sizeFlags & wxSIZE_ALLOW_MINUS_ONE)) x = currentX; if (y == -1 && !(sizeFlags & wxSIZE_ALLOW_MINUS_ONE)) y = currentY; AdjustForParentClientOrigin(x, y, sizeFlags); // calculate the best size if we should auto size the window if ( ((sizeFlags & wxSIZE_AUTO_WIDTH) && width == -1) || ((sizeFlags & wxSIZE_AUTO_HEIGHT) && height == -1) ) { const wxSize sizeBest = GetBestSize(); if ( (sizeFlags & wxSIZE_AUTO_WIDTH) && width == -1 ) width = sizeBest.x; if ( (sizeFlags & wxSIZE_AUTO_HEIGHT) && height == -1 ) height = sizeBest.y; } if (width != -1) m_width = width; if (height != -1) m_height = height; int minWidth = GetMinWidth(), minHeight = GetMinHeight(), maxWidth = GetMaxWidth(), maxHeight = GetMaxHeight(); if ((minWidth != -1) && (m_width < minWidth )) m_width = minWidth; if ((minHeight != -1) && (m_height < minHeight)) m_height = minHeight; if ((maxWidth != -1) && (m_width > maxWidth )) m_width = maxWidth; if ((maxHeight != -1) && (m_height > maxHeight)) m_height = maxHeight; #if wxUSE_TOOLBAR_NATIVE if (wxDynamicCast(GetParent(), wxToolBar)) { // don't take the x,y values, they're wrong because toolbar sets them GtkWidget *widget = GTK_WIDGET(m_widget); gtk_widget_set_size_request (widget, m_width, m_height); } else #endif if (m_parent->m_wxwindow == NULL) // i.e. wxNotebook { // don't set the size for children of wxNotebook, just take the values. m_x = x; m_y = y; m_width = width; m_height = height; } else { GtkPizza *pizza = GTK_PIZZA(m_parent->m_wxwindow); if ((sizeFlags & wxSIZE_ALLOW_MINUS_ONE) == 0) { if (x != -1) m_x = x + gtk_pizza_get_xoffset( pizza ); if (y != -1) m_y = y + gtk_pizza_get_yoffset( pizza ); } else { m_x = x + gtk_pizza_get_xoffset( pizza ); m_y = y + gtk_pizza_get_yoffset( pizza ); } int left_border = 0; int right_border = 0; int top_border = 0; int bottom_border = 0; /* the default button has a border around it */ if (GTK_WIDGET_CAN_DEFAULT(m_widget)) { GtkBorder *default_border = NULL; gtk_widget_style_get( m_widget, "default_border", &default_border, NULL ); if (default_border) { left_border += default_border->left; right_border += default_border->right; top_border += default_border->top; bottom_border += default_border->bottom; gtk_border_free( default_border ); } } DoMoveWindow( m_x - left_border, m_y - top_border, m_width+left_border+right_border, m_height+top_border+bottom_border ); } if (m_hasScrolling) { /* Sometimes the client area changes size without the whole windows's size changing, but if the whole windows's size doesn't change, no wxSizeEvent will normally be sent. Here we add an extra test if the client test has been changed and this will be used then. */ GetClientSize( &m_oldClientWidth, &m_oldClientHeight ); } /* wxPrintf( "OnSize sent from " ); if (GetClassInfo() && GetClassInfo()->GetClassName()) wxPrintf( GetClassInfo()->GetClassName() ); wxPrintf( " %d %d %d %d\n", (int)m_x, (int)m_y, (int)m_width, (int)m_height ); */ if (!m_nativeSizeEvent) { wxSizeEvent event( wxSize(m_width,m_height), GetId() ); event.SetEventObject( this ); GetEventHandler()->ProcessEvent( event ); } m_resizing = false; } bool wxWindowGTK::GtkShowFromOnIdle() { if (IsShown() && m_showOnIdle && !GTK_WIDGET_VISIBLE (m_widget)) { GtkAllocation alloc; alloc.x = m_x; alloc.y = m_y; alloc.width = m_width; alloc.height = m_height; gtk_widget_size_allocate( m_widget, &alloc ); gtk_widget_show( m_widget ); wxShowEvent eventShow(GetId(), true); eventShow.SetEventObject(this); GetEventHandler()->ProcessEvent(eventShow); m_showOnIdle = false; return true; } return false; } void wxWindowGTK::OnInternalIdle() { // Check if we have to show window now if (GtkShowFromOnIdle()) return; if ( m_dirtyTabOrder ) { m_dirtyTabOrder = false; RealizeTabOrder(); } // Update style if the window was not yet realized // and SetBackgroundStyle(wxBG_STYLE_CUSTOM) was called if (m_needsStyleChange) { SetBackgroundStyle(GetBackgroundStyle()); m_needsStyleChange = false; } wxCursor cursor = m_cursor; if (g_globalCursor.Ok()) cursor = g_globalCursor; if (cursor.Ok()) { /* I now set the cursor anew in every OnInternalIdle call as setting the cursor in a parent window also effects the windows above so that checking for the current cursor is not possible. */ if (m_wxwindow) { GdkWindow *window = GTK_PIZZA(m_wxwindow)->bin_window; if (window) gdk_window_set_cursor( window, cursor.GetCursor() ); if (!g_globalCursor.Ok()) cursor = *wxSTANDARD_CURSOR; window = m_widget->window; if ((window) && !(GTK_WIDGET_NO_WINDOW(m_widget))) gdk_window_set_cursor( window, cursor.GetCursor() ); } else if ( m_widget ) { GdkWindow *window = m_widget->window; if ( window && !GTK_WIDGET_NO_WINDOW(m_widget) ) gdk_window_set_cursor( window, cursor.GetCursor() ); } } if (wxUpdateUIEvent::CanUpdate(this) && IsShownOnScreen()) UpdateWindowUI(wxUPDATE_UI_FROMIDLE); } void wxWindowGTK::DoGetSize( int *width, int *height ) const { wxCHECK_RET( (m_widget != NULL), wxT("invalid window") ); if (width) (*width) = m_width; if (height) (*height) = m_height; } void wxWindowGTK::DoSetClientSize( int width, int height ) { wxCHECK_RET( (m_widget != NULL), wxT("invalid window") ); if (m_wxwindow) { int dw = 0; int dh = 0; if (m_hasScrolling) { GetScrollbarWidth(m_widget, dw, dh); } const int border = GTK_CONTAINER(m_wxwindow)->border_width; dw += 2 * border; dh += 2 * border; width += dw; height += dh; } SetSize(width, height); } void wxWindowGTK::DoGetClientSize( int *width, int *height ) const { wxCHECK_RET( (m_widget != NULL), wxT("invalid window") ); int w = m_width; int h = m_height; if (m_wxwindow) { int dw = 0; int dh = 0; if (m_hasScrolling) GetScrollbarWidth(m_widget, dw, dh); const int border = GTK_CONTAINER(m_wxwindow)->border_width; dw += 2 * border; dh += 2 * border; w -= dw; h -= dh; if (w < 0) w = 0; if (h < 0) h = 0; } if (width) *width = w; if (height) *height = h; } void wxWindowGTK::DoGetPosition( int *x, int *y ) const { wxCHECK_RET( (m_widget != NULL), wxT("invalid window") ); int dx = 0; int dy = 0; if (!IsTopLevel() && m_parent && m_parent->m_wxwindow) { GtkPizza *pizza = GTK_PIZZA(m_parent->m_wxwindow); dx = gtk_pizza_get_xoffset( pizza ); dy = gtk_pizza_get_yoffset( pizza ); } if (m_x == -1 && m_y == -1) { GdkWindow *source = (GdkWindow *) NULL; if (m_wxwindow) source = GTK_PIZZA(m_wxwindow)->bin_window; else source = m_widget->window; if (source) { int org_x = 0; int org_y = 0; gdk_window_get_origin( source, &org_x, &org_y ); if (GetParent()) GetParent()->ScreenToClient(&org_x, &org_y); wx_const_cast(wxWindowGTK*, this)->m_x = org_x; wx_const_cast(wxWindowGTK*, this)->m_y = org_y; } } if (x) (*x) = m_x - dx; if (y) (*y) = m_y - dy; } void wxWindowGTK::DoClientToScreen( int *x, int *y ) const { wxCHECK_RET( (m_widget != NULL), wxT("invalid window") ); if (!m_widget->window) return; GdkWindow *source = (GdkWindow *) NULL; if (m_wxwindow) source = GTK_PIZZA(m_wxwindow)->bin_window; else source = m_widget->window; int org_x = 0; int org_y = 0; gdk_window_get_origin( source, &org_x, &org_y ); if (!m_wxwindow) { if (GTK_WIDGET_NO_WINDOW (m_widget)) { org_x += m_widget->allocation.x; org_y += m_widget->allocation.y; } } if (x) { if (GetLayoutDirection() == wxLayout_RightToLeft) *x = (GetClientSize().x - *x) + org_x; else *x += org_x; } if (y) *y += org_y; } void wxWindowGTK::DoScreenToClient( int *x, int *y ) const { wxCHECK_RET( (m_widget != NULL), wxT("invalid window") ); if (!m_widget->window) return; GdkWindow *source = (GdkWindow *) NULL; if (m_wxwindow) source = GTK_PIZZA(m_wxwindow)->bin_window; else source = m_widget->window; int org_x = 0; int org_y = 0; gdk_window_get_origin( source, &org_x, &org_y ); if (!m_wxwindow) { if (GTK_WIDGET_NO_WINDOW (m_widget)) { org_x += m_widget->allocation.x; org_y += m_widget->allocation.y; } } if (x) { if (GetLayoutDirection() == wxLayout_RightToLeft) *x = (GetClientSize().x - *x) - org_x; else *x -= org_x; } if (y) *y -= org_y; } bool wxWindowGTK::Show( bool show ) { wxCHECK_MSG( (m_widget != NULL), false, wxT("invalid window") ); if (!wxWindowBase::Show(show)) { // nothing to do return false; } if (show) { if (!m_showOnIdle) { gtk_widget_show( m_widget ); wxShowEvent eventShow(GetId(), show); eventShow.SetEventObject(this); GetEventHandler()->ProcessEvent(eventShow); } } else { gtk_widget_hide( m_widget ); wxShowEvent eventShow(GetId(), show); eventShow.SetEventObject(this); GetEventHandler()->ProcessEvent(eventShow); } return true; } static void wxWindowNotifyEnable(wxWindowGTK* win, bool enable) { win->OnParentEnable(enable); // Recurse, so that children have the opportunity to Do The Right Thing // and reset colours that have been messed up by a parent's (really ancestor's) // Enable call for ( wxWindowList::compatibility_iterator node = win->GetChildren().GetFirst(); node; node = node->GetNext() ) { wxWindow *child = node->GetData(); if (!child->IsKindOf(CLASSINFO(wxDialog)) && !child->IsKindOf(CLASSINFO(wxFrame))) wxWindowNotifyEnable(child, enable); } } bool wxWindowGTK::Enable( bool enable ) { wxCHECK_MSG( (m_widget != NULL), false, wxT("invalid window") ); if (!wxWindowBase::Enable(enable)) { // nothing to do return false; } gtk_widget_set_sensitive( m_widget, enable ); if ( m_wxwindow ) gtk_widget_set_sensitive( m_wxwindow, enable ); wxWindowNotifyEnable(this, enable); return true; } int wxWindowGTK::GetCharHeight() const { wxCHECK_MSG( (m_widget != NULL), 12, wxT("invalid window") ); wxFont font = GetFont(); wxCHECK_MSG( font.Ok(), 12, wxT("invalid font") ); PangoContext *context = NULL; if (m_widget) context = gtk_widget_get_pango_context( m_widget ); if (!context) return 0; PangoFontDescription *desc = font.GetNativeFontInfo()->description; PangoLayout *layout = pango_layout_new(context); pango_layout_set_font_description(layout, desc); pango_layout_set_text(layout, "H", 1); PangoLayoutLine *line = (PangoLayoutLine *)pango_layout_get_lines(layout)->data; PangoRectangle rect; pango_layout_line_get_extents(line, NULL, &rect); g_object_unref (layout); return (int) PANGO_PIXELS(rect.height); } int wxWindowGTK::GetCharWidth() const { wxCHECK_MSG( (m_widget != NULL), 8, wxT("invalid window") ); wxFont font = GetFont(); wxCHECK_MSG( font.Ok(), 8, wxT("invalid font") ); PangoContext *context = NULL; if (m_widget) context = gtk_widget_get_pango_context( m_widget ); if (!context) return 0; PangoFontDescription *desc = font.GetNativeFontInfo()->description; PangoLayout *layout = pango_layout_new(context); pango_layout_set_font_description(layout, desc); pango_layout_set_text(layout, "g", 1); PangoLayoutLine *line = (PangoLayoutLine *)pango_layout_get_lines(layout)->data; PangoRectangle rect; pango_layout_line_get_extents(line, NULL, &rect); g_object_unref (layout); return (int) PANGO_PIXELS(rect.width); } void wxWindowGTK::GetTextExtent( const wxString& string, int *x, int *y, int *descent, int *externalLeading, const wxFont *theFont ) const { wxFont fontToUse = theFont ? *theFont : GetFont(); wxCHECK_RET( fontToUse.Ok(), wxT("invalid font") ); if (string.empty()) { if (x) (*x) = 0; if (y) (*y) = 0; return; } PangoContext *context = NULL; if (m_widget) context = gtk_widget_get_pango_context( m_widget ); if (!context) { if (x) (*x) = 0; if (y) (*y) = 0; return; } PangoFontDescription *desc = fontToUse.GetNativeFontInfo()->description; PangoLayout *layout = pango_layout_new(context); pango_layout_set_font_description(layout, desc); { const wxCharBuffer data = wxGTK_CONV( string ); if ( data ) pango_layout_set_text(layout, data, strlen(data)); } PangoRectangle rect; pango_layout_get_extents(layout, NULL, &rect); if (x) (*x) = (wxCoord) PANGO_PIXELS(rect.width); if (y) (*y) = (wxCoord) PANGO_PIXELS(rect.height); if (descent) { PangoLayoutIter *iter = pango_layout_get_iter(layout); int baseline = pango_layout_iter_get_baseline(iter); pango_layout_iter_free(iter); *descent = *y - PANGO_PIXELS(baseline); } if (externalLeading) (*externalLeading) = 0; // ?? g_object_unref (layout); } bool wxWindowGTK::GTKSetDelayedFocusIfNeeded() { if ( g_delayedFocus == this ) { if ( GTK_WIDGET_REALIZED(m_widget) ) { gtk_widget_grab_focus(m_widget); g_delayedFocus = NULL; return true; } } return false; } void wxWindowGTK::SetFocus() { wxCHECK_RET( m_widget != NULL, wxT("invalid window") ); if ( m_hasFocus ) { // don't do anything if we already have focus return; } // Setting "physical" focus is not immediate in GTK+ and while // gtk_widget_is_focus ("determines if the widget is the focus widget // within its toplevel", i.e. returns true for one widget per TLW, not // globally) returns true immediately after grabbing focus, // GTK_WIDGET_HAS_FOCUS (which returns true only for the one widget that // has focus at the moment) takes affect only after the window is shown // (if it was hidden at the moment of the call) or at the next event loop // iteration. // // Because we want to FindFocus() call immediately following // foo->SetFocus() to return foo, we have to keep track of "pending" focus // ourselves. g_focusWindowPending = this; if (m_wxwindow) { if (!GTK_WIDGET_HAS_FOCUS (m_wxwindow)) { gtk_widget_grab_focus (m_wxwindow); } } else if (m_widget) { if (GTK_IS_CONTAINER(m_widget)) { if (IsKindOf(CLASSINFO(wxRadioButton))) { gtk_widget_grab_focus (m_widget); return; } gtk_widget_child_focus( m_widget, GTK_DIR_TAB_FORWARD ); } else if (GTK_WIDGET_CAN_FOCUS(m_widget) && !GTK_WIDGET_HAS_FOCUS (m_widget) ) { if (!GTK_WIDGET_REALIZED(m_widget)) { // we can't set the focus to the widget now so we remember that // it should be focused and will do it later, during the idle // time, as soon as we can wxLogTrace(TRACE_FOCUS, _T("Delaying setting focus to %s(%s)"), GetClassInfo()->GetClassName(), GetLabel().c_str()); g_delayedFocus = this; } else { wxLogTrace(TRACE_FOCUS, _T("Setting focus to %s(%s)"), GetClassInfo()->GetClassName(), GetLabel().c_str()); gtk_widget_grab_focus (m_widget); } } else { wxLogTrace(TRACE_FOCUS, _T("Can't set focus to %s(%s)"), GetClassInfo()->GetClassName(), GetLabel().c_str()); } } } bool wxWindowGTK::AcceptsFocus() const { return m_acceptsFocus && wxWindowBase::AcceptsFocus(); } bool wxWindowGTK::Reparent( wxWindowBase *newParentBase ) { wxCHECK_MSG( (m_widget != NULL), false, wxT("invalid window") ); wxWindowGTK *oldParent = m_parent, *newParent = (wxWindowGTK *)newParentBase; wxASSERT( GTK_IS_WIDGET(m_widget) ); if ( !wxWindowBase::Reparent(newParent) ) return false; wxASSERT( GTK_IS_WIDGET(m_widget) ); /* prevent GTK from deleting the widget arbitrarily */ gtk_widget_ref( m_widget ); if (oldParent) { gtk_container_remove( GTK_CONTAINER(m_widget->parent), m_widget ); } wxASSERT( GTK_IS_WIDGET(m_widget) ); if (newParent) { if (GTK_WIDGET_VISIBLE (newParent->m_widget)) { m_showOnIdle = true; gtk_widget_hide( m_widget ); } /* insert GTK representation */ (*(newParent->m_insertCallback))(newParent, this); } /* reverse: prevent GTK from deleting the widget arbitrarily */ gtk_widget_unref( m_widget ); SetLayoutDirection(wxLayout_Default); return true; } void wxWindowGTK::DoAddChild(wxWindowGTK *child) { wxASSERT_MSG( (m_widget != NULL), wxT("invalid window") ); wxASSERT_MSG( (child != NULL), wxT("invalid child window") ); wxASSERT_MSG( (m_insertCallback != NULL), wxT("invalid child insertion function") ); /* add to list */ AddChild( child ); /* insert GTK representation */ (*m_insertCallback)(this, child); } void wxWindowGTK::AddChild(wxWindowBase *child) { wxWindowBase::AddChild(child); m_dirtyTabOrder = true; if (g_isIdle) wxapp_install_idle_handler(); } void wxWindowGTK::RemoveChild(wxWindowBase *child) { wxWindowBase::RemoveChild(child); m_dirtyTabOrder = true; if (g_isIdle) wxapp_install_idle_handler(); } /* static */ wxLayoutDirection wxWindowGTK::GTKGetLayout(GtkWidget *widget) { return gtk_widget_get_direction(GTK_WIDGET(widget)) == GTK_TEXT_DIR_RTL ? wxLayout_RightToLeft : wxLayout_LeftToRight; } /* static */ void wxWindowGTK::GTKSetLayout(GtkWidget *widget, wxLayoutDirection dir) { wxASSERT_MSG( dir != wxLayout_Default, _T("invalid layout direction") ); gtk_widget_set_direction(GTK_WIDGET(widget), dir == wxLayout_RightToLeft ? GTK_TEXT_DIR_RTL : GTK_TEXT_DIR_LTR); } wxLayoutDirection wxWindowGTK::GetLayoutDirection() const { return GTKGetLayout(m_widget); } void wxWindowGTK::SetLayoutDirection(wxLayoutDirection dir) { if ( dir == wxLayout_Default ) { const wxWindow *const parent = GetParent(); if ( parent ) { // inherit layout from parent. dir = parent->GetLayoutDirection(); } else // no parent, use global default layout { dir = wxTheApp->GetLayoutDirection(); } } if ( dir == wxLayout_Default ) return; GTKSetLayout(m_widget, dir); if (m_wxwindow) GTKSetLayout(m_wxwindow, dir); } wxCoord wxWindowGTK::AdjustForLayoutDirection(wxCoord x, wxCoord WXUNUSED(width), wxCoord WXUNUSED(widthTotal)) const { // We now mirrors the coordinates of RTL windows in GtkPizza return x; } void wxWindowGTK::DoMoveInTabOrder(wxWindow *win, MoveKind move) { wxWindowBase::DoMoveInTabOrder(win, move); m_dirtyTabOrder = true; if (g_isIdle) wxapp_install_idle_handler(); } bool wxWindowGTK::GTKWidgetNeedsMnemonic() const { // none needed by default return false; } void wxWindowGTK::GTKWidgetDoSetMnemonic(GtkWidget* WXUNUSED(w)) { // nothing to do by default since none is needed } void wxWindowGTK::RealizeTabOrder() { if (m_wxwindow) { if ( !m_children.empty() ) { // we don't only construct the correct focus chain but also use // this opportunity to update the mnemonic widgets for the widgets // that need them GList *chain = NULL; wxWindowGTK* mnemonicWindow = NULL; for ( wxWindowList::const_iterator i = m_children.begin(); i != m_children.end(); ++i ) { wxWindowGTK *win = *i; if ( mnemonicWindow ) { if ( win->AcceptsFocusFromKeyboard() ) { // wxComboBox et al. needs to focus on on a different // widget than m_widget, so if the main widget isn't // focusable try the connect widget GtkWidget* w = win->m_widget; if ( !GTK_WIDGET_CAN_FOCUS(w) ) { w = win->GetConnectWidget(); if ( !GTK_WIDGET_CAN_FOCUS(w) ) w = NULL; } if ( w ) { mnemonicWindow->GTKWidgetDoSetMnemonic(w); mnemonicWindow = NULL; } } } else if ( win->GTKWidgetNeedsMnemonic() ) { mnemonicWindow = win; } chain = g_list_prepend(chain, win->m_widget); } chain = g_list_reverse(chain); gtk_container_set_focus_chain(GTK_CONTAINER(m_wxwindow), chain); g_list_free(chain); } else // no children { gtk_container_unset_focus_chain(GTK_CONTAINER(m_wxwindow)); } } } void wxWindowGTK::Raise() { wxCHECK_RET( (m_widget != NULL), wxT("invalid window") ); if (m_wxwindow && m_wxwindow->window) { gdk_window_raise( m_wxwindow->window ); } else if (m_widget->window) { gdk_window_raise( m_widget->window ); } } void wxWindowGTK::Lower() { wxCHECK_RET( (m_widget != NULL), wxT("invalid window") ); if (m_wxwindow && m_wxwindow->window) { gdk_window_lower( m_wxwindow->window ); } else if (m_widget->window) { gdk_window_lower( m_widget->window ); } } bool wxWindowGTK::SetCursor( const wxCursor &cursor ) { if ( !wxWindowBase::SetCursor(cursor.Ok() ? cursor : *wxSTANDARD_CURSOR) ) return false; GTKUpdateCursor(); return true; } void wxWindowGTK::GTKUpdateCursor() { wxCursor cursor(g_globalCursor.Ok() ? g_globalCursor : GetCursor()); if ( cursor.Ok() ) { wxArrayGdkWindows windowsThis; GdkWindow * const winThis = GTKGetWindow(windowsThis); if ( winThis ) { gdk_window_set_cursor(winThis, cursor.GetCursor()); } else { const size_t count = windowsThis.size(); for ( size_t n = 0; n < count; n++ ) { GdkWindow *win = windowsThis[n]; if ( !win ) { wxFAIL_MSG(_T("NULL window returned by GTKGetWindow()?")); continue; } gdk_window_set_cursor(win, cursor.GetCursor()); } } } } void wxWindowGTK::WarpPointer( int x, int y ) { wxCHECK_RET( (m_widget != NULL), wxT("invalid window") ); // We provide this function ourselves as it is // missing in GDK (top of this file). GdkWindow *window = (GdkWindow*) NULL; if (m_wxwindow) window = GTK_PIZZA(m_wxwindow)->bin_window; else window = GetConnectWidget()->window; if (window) gdk_window_warp_pointer( window, x, y ); } wxWindowGTK::ScrollDir wxWindowGTK::ScrollDirFromRange(GtkRange *range) const { // find the scrollbar which generated the event for ( int dir = 0; dir < ScrollDir_Max; dir++ ) { if ( range == m_scrollBar[dir] ) return (ScrollDir)dir; } wxFAIL_MSG( _T("event from unknown scrollbar received") ); return ScrollDir_Max; } bool wxWindowGTK::DoScrollByUnits(ScrollDir dir, ScrollUnit unit, int units) { bool changed = false; GtkRange* range = m_scrollBar[dir]; if ( range && units ) { GtkAdjustment* adj = range->adjustment; gdouble inc = unit == ScrollUnit_Line ? adj->step_increment : adj->page_increment; const int posOld = int(adj->value + 0.5); gtk_range_set_value(range, posOld + units*inc); changed = int(adj->value + 0.5) != posOld; } return changed; } bool wxWindowGTK::ScrollLines(int lines) { return DoScrollByUnits(ScrollDir_Vert, ScrollUnit_Line, lines); } bool wxWindowGTK::ScrollPages(int pages) { return DoScrollByUnits(ScrollDir_Vert, ScrollUnit_Page, pages); } void wxWindowGTK::Refresh( bool eraseBackground, const wxRect *rect ) { if (!m_widget) return; if (!m_widget->window) return; if (m_wxwindow) { if (!GTK_PIZZA(m_wxwindow)->bin_window) return; GdkRectangle gdk_rect, *p; if (rect) { gdk_rect.x = rect->x; gdk_rect.y = rect->y; gdk_rect.width = rect->width; gdk_rect.height = rect->height; if (GetLayoutDirection() == wxLayout_RightToLeft) gdk_rect.x = GetClientSize().x - gdk_rect.x - gdk_rect.width; p = &gdk_rect; } else // invalidate everything { p = NULL; } gdk_window_invalidate_rect( GTK_PIZZA(m_wxwindow)->bin_window, p, TRUE ); } } void wxWindowGTK::Update() { GtkUpdate(); // when we call Update() we really want to update the window immediately on // screen, even if it means flushing the entire queue and hence slowing down // everything -- but it should still be done, it's just that Update() should // be called very rarely gdk_flush(); } void wxWindowGTK::GtkUpdate() { if (m_wxwindow && GTK_PIZZA(m_wxwindow)->bin_window) gdk_window_process_updates( GTK_PIZZA(m_wxwindow)->bin_window, FALSE ); if (m_widget && m_widget->window) gdk_window_process_updates( m_widget->window, FALSE ); // for consistency with other platforms (and also because it's convenient // to be able to update an entire TLW by calling Update() only once), we // should also update all our children here for ( wxWindowList::compatibility_iterator node = GetChildren().GetFirst(); node; node = node->GetNext() ) { node->GetData()->GtkUpdate(); } } bool wxWindowGTK::DoIsExposed( int x, int y ) const { return m_updateRegion.Contains(x, y) != wxOutRegion; } bool wxWindowGTK::DoIsExposed( int x, int y, int w, int h ) const { if (GetLayoutDirection() == wxLayout_RightToLeft) return m_updateRegion.Contains(x-w, y, w, h) != wxOutRegion; else return m_updateRegion.Contains(x, y, w, h) != wxOutRegion; } void wxWindowGTK::GtkSendPaintEvents() { if (!m_wxwindow) { m_updateRegion.Clear(); return; } // Clip to paint region in wxClientDC m_clipPaintRegion = true; m_nativeUpdateRegion = m_updateRegion; if (GetLayoutDirection() == wxLayout_RightToLeft) { // Transform m_updateRegion under RTL m_updateRegion.Clear(); gint width; gdk_window_get_geometry( GTK_PIZZA(m_wxwindow)->bin_window, NULL, NULL, &width, NULL, NULL ); wxRegionIterator upd( m_nativeUpdateRegion ); while (upd) { wxRect rect; rect.x = upd.GetX(); rect.y = upd.GetY(); rect.width = upd.GetWidth(); rect.height = upd.GetHeight(); rect.x = width - rect.x - rect.width; m_updateRegion.Union( rect ); ++upd; } } // widget to draw on GtkPizza *pizza = GTK_PIZZA (m_wxwindow); if (GetThemeEnabled() && (GetBackgroundStyle() == wxBG_STYLE_SYSTEM)) { // find ancestor from which to steal background wxWindow *parent = wxGetTopLevelParent((wxWindow *)this); if (!parent) parent = (wxWindow*)this; if (GTK_WIDGET_MAPPED(parent->m_widget)) { wxRegionIterator upd( m_nativeUpdateRegion ); while (upd) { GdkRectangle rect; rect.x = upd.GetX(); rect.y = upd.GetY(); rect.width = upd.GetWidth(); rect.height = upd.GetHeight(); gtk_paint_flat_box( parent->m_widget->style, pizza->bin_window, (GtkStateType)GTK_WIDGET_STATE(m_wxwindow), GTK_SHADOW_NONE, &rect, parent->m_widget, (char *)"base", 0, 0, -1, -1 ); ++upd; } } } else { wxWindowDC dc( (wxWindow*)this ); dc.SetClippingRegion( m_updateRegion ); // Work around gtk-qt <= 0.60 bug whereby the window colour // remains grey if (GetBackgroundStyle() == wxBG_STYLE_COLOUR && GetBackgroundColour().Ok() && wxSystemOptions::GetOptionInt(wxT("gtk.window.force-background-colour")) == 1) { dc.SetBackground(wxBrush(GetBackgroundColour())); dc.Clear(); } wxEraseEvent erase_event( GetId(), &dc ); erase_event.SetEventObject( this ); GetEventHandler()->ProcessEvent(erase_event); } wxNcPaintEvent nc_paint_event( GetId() ); nc_paint_event.SetEventObject( this ); GetEventHandler()->ProcessEvent( nc_paint_event ); wxPaintEvent paint_event( GetId() ); paint_event.SetEventObject( this ); GetEventHandler()->ProcessEvent( paint_event ); m_clipPaintRegion = false; m_updateRegion.Clear(); m_nativeUpdateRegion.Clear(); } void wxWindowGTK::SetDoubleBuffered( bool on ) { wxCHECK_RET( (m_widget != NULL), wxT("invalid window") ); if ( m_wxwindow ) gtk_widget_set_double_buffered( m_wxwindow, on ); } bool wxWindowGTK::IsDoubleBuffered() const { return GTK_WIDGET_DOUBLE_BUFFERED( m_wxwindow ); } void wxWindowGTK::ClearBackground() { wxCHECK_RET( m_widget != NULL, wxT("invalid window") ); } #if wxUSE_TOOLTIPS void wxWindowGTK::DoSetToolTip( wxToolTip *tip ) { wxWindowBase::DoSetToolTip(tip); if (m_tooltip) { m_tooltip->Apply( (wxWindow *)this ); } else { GtkWidget *w = GetConnectWidget(); wxToolTip::Apply(w, wxCharBuffer()); #if GTK_CHECK_VERSION(2, 12, 0) // Just applying NULL doesn't work on 2.12.0, so also use // gtk_widget_set_has_tooltip. It is part of the new GtkTooltip API // but seems also to work with the old GtkTooltips. if (gtk_check_version(2, 12, 0) == NULL) gtk_widget_set_has_tooltip(w, FALSE); #endif } } void wxWindowGTK::ApplyToolTip( GtkTooltips *tips, const wxChar *tip ) { if (tip) { wxString tmp( tip ); gtk_tooltips_set_tip( tips, GetConnectWidget(), wxGTK_CONV(tmp), (gchar*) NULL ); } else { gtk_tooltips_set_tip( tips, GetConnectWidget(), NULL, NULL); } } #endif // wxUSE_TOOLTIPS bool wxWindowGTK::SetBackgroundColour( const wxColour &colour ) { wxCHECK_MSG( m_widget != NULL, false, wxT("invalid window") ); if (!wxWindowBase::SetBackgroundColour(colour)) return false; if (colour.Ok()) { // We need the pixel value e.g. for background clearing. m_backgroundColour.CalcPixel(gtk_widget_get_colormap(m_widget)); } // apply style change (forceStyle=true so that new style is applied // even if the bg colour changed from valid to wxNullColour) if (GetBackgroundStyle() != wxBG_STYLE_CUSTOM) ApplyWidgetStyle(true); return true; } bool wxWindowGTK::SetForegroundColour( const wxColour &colour ) { wxCHECK_MSG( m_widget != NULL, false, wxT("invalid window") ); if (!wxWindowBase::SetForegroundColour(colour)) { return false; } if (colour.Ok()) { // We need the pixel value e.g. for background clearing. m_foregroundColour.CalcPixel(gtk_widget_get_colormap(m_widget)); } // apply style change (forceStyle=true so that new style is applied // even if the bg colour changed from valid to wxNullColour): ApplyWidgetStyle(true); return true; } PangoContext *wxWindowGTK::GtkGetPangoDefaultContext() { return gtk_widget_get_pango_context( m_widget ); } GtkRcStyle *wxWindowGTK::CreateWidgetStyle(bool forceStyle) { // do we need to apply any changes at all? if ( !forceStyle && !m_font.Ok() && !m_foregroundColour.Ok() && !m_backgroundColour.Ok() ) { return NULL; } GtkRcStyle *style = gtk_rc_style_new(); if ( m_font.Ok() ) { style->font_desc = pango_font_description_copy( m_font.GetNativeFontInfo()->description ); } int flagsNormal = 0, flagsPrelight = 0, flagsActive = 0, flagsInsensitive = 0; if ( m_foregroundColour.Ok() ) { const GdkColor *fg = m_foregroundColour.GetColor(); style->fg[GTK_STATE_NORMAL] = style->text[GTK_STATE_NORMAL] = *fg; flagsNormal |= GTK_RC_FG | GTK_RC_TEXT; style->fg[GTK_STATE_PRELIGHT] = style->text[GTK_STATE_PRELIGHT] = *fg; flagsPrelight |= GTK_RC_FG | GTK_RC_TEXT; style->fg[GTK_STATE_ACTIVE] = style->text[GTK_STATE_ACTIVE] = *fg; flagsActive |= GTK_RC_FG | GTK_RC_TEXT; } if ( m_backgroundColour.Ok() ) { const GdkColor *bg = m_backgroundColour.GetColor(); style->bg[GTK_STATE_NORMAL] = style->base[GTK_STATE_NORMAL] = *bg; flagsNormal |= GTK_RC_BG | GTK_RC_BASE; style->bg[GTK_STATE_PRELIGHT] = style->base[GTK_STATE_PRELIGHT] = *bg; flagsPrelight |= GTK_RC_BG | GTK_RC_BASE; style->bg[GTK_STATE_ACTIVE] = style->base[GTK_STATE_ACTIVE] = *bg; flagsActive |= GTK_RC_BG | GTK_RC_BASE; style->bg[GTK_STATE_INSENSITIVE] = style->base[GTK_STATE_INSENSITIVE] = *bg; flagsInsensitive |= GTK_RC_BG | GTK_RC_BASE; } style->color_flags[GTK_STATE_NORMAL] = (GtkRcFlags)flagsNormal; style->color_flags[GTK_STATE_PRELIGHT] = (GtkRcFlags)flagsPrelight; style->color_flags[GTK_STATE_ACTIVE] = (GtkRcFlags)flagsActive; style->color_flags[GTK_STATE_INSENSITIVE] = (GtkRcFlags)flagsInsensitive; return style; } void wxWindowGTK::ApplyWidgetStyle(bool forceStyle) { GtkRcStyle *style = CreateWidgetStyle(forceStyle); if ( style ) { DoApplyWidgetStyle(style); gtk_rc_style_unref(style); } // Style change may affect GTK+'s size calculation: InvalidateBestSize(); } void wxWindowGTK::DoApplyWidgetStyle(GtkRcStyle *style) { wxSuspendStyleEvents s((wxWindow *)this); if (m_wxwindow) gtk_widget_modify_style(m_wxwindow, style); else gtk_widget_modify_style(m_widget, style); } bool wxWindowGTK::SetBackgroundStyle(wxBackgroundStyle style) { wxWindowBase::SetBackgroundStyle(style); if (style == wxBG_STYLE_CUSTOM) { GdkWindow *window = (GdkWindow*) NULL; if (m_wxwindow) window = GTK_PIZZA(m_wxwindow)->bin_window; else window = GetConnectWidget()->window; if (window) { // Make sure GDK/X11 doesn't refresh the window // automatically. gdk_window_set_back_pixmap( window, None, False ); #ifdef __X__ Display* display = GDK_WINDOW_DISPLAY(window); XFlush(display); #endif m_needsStyleChange = false; } else // Do in OnIdle, because the window is not yet available m_needsStyleChange = true; // Don't apply widget style, or we get a grey background } else { // apply style change (forceStyle=true so that new style is applied // even if the bg colour changed from valid to wxNullColour): ApplyWidgetStyle(true); } return true; } #if wxUSE_DRAG_AND_DROP void wxWindowGTK::SetDropTarget( wxDropTarget *dropTarget ) { wxCHECK_RET( m_widget != NULL, wxT("invalid window") ); GtkWidget *dnd_widget = GetConnectWidget(); if (m_dropTarget) m_dropTarget->UnregisterWidget( dnd_widget ); if (m_dropTarget) delete m_dropTarget; m_dropTarget = dropTarget; if (m_dropTarget) m_dropTarget->RegisterWidget( dnd_widget ); } #endif // wxUSE_DRAG_AND_DROP GtkWidget* wxWindowGTK::GetConnectWidget() { GtkWidget *connect_widget = m_widget; if (m_wxwindow) connect_widget = m_wxwindow; return connect_widget; } bool wxWindowGTK::GTKIsOwnWindow(GdkWindow *window) const { wxArrayGdkWindows windowsThis; GdkWindow * const winThis = GTKGetWindow(windowsThis); return winThis ? window == winThis : windowsThis.Index(window) != wxNOT_FOUND; } GdkWindow *wxWindowGTK::GTKGetWindow(wxArrayGdkWindows& WXUNUSED(windows)) const { return m_wxwindow ? GTK_PIZZA(m_wxwindow)->bin_window : m_widget->window; } bool wxWindowGTK::SetFont( const wxFont &font ) { wxCHECK_MSG( m_widget != NULL, false, wxT("invalid window") ); if (!wxWindowBase::SetFont(font)) return false; // apply style change (forceStyle=true so that new style is applied // even if the font changed from valid to wxNullFont): ApplyWidgetStyle(true); return true; } void wxWindowGTK::DoCaptureMouse() { wxCHECK_RET( m_widget != NULL, wxT("invalid window") ); GdkWindow *window = (GdkWindow*) NULL; if (m_wxwindow) window = GTK_PIZZA(m_wxwindow)->bin_window; else window = GetConnectWidget()->window; wxCHECK_RET( window, _T("CaptureMouse() failed") ); const wxCursor* cursor = &m_cursor; if (!cursor->Ok()) cursor = wxSTANDARD_CURSOR; gdk_pointer_grab( window, FALSE, (GdkEventMask) (GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_POINTER_MOTION_MASK), (GdkWindow *) NULL, cursor->GetCursor(), (guint32)GDK_CURRENT_TIME ); g_captureWindow = this; g_captureWindowHasMouse = true; } void wxWindowGTK::DoReleaseMouse() { wxCHECK_RET( m_widget != NULL, wxT("invalid window") ); wxCHECK_RET( g_captureWindow, wxT("can't release mouse - not captured") ); g_captureWindow = (wxWindowGTK*) NULL; GdkWindow *window = (GdkWindow*) NULL; if (m_wxwindow) window = GTK_PIZZA(m_wxwindow)->bin_window; else window = GetConnectWidget()->window; if (!window) return; gdk_pointer_ungrab ( (guint32)GDK_CURRENT_TIME ); } /* static */ wxWindow *wxWindowBase::GetCapture() { return (wxWindow *)g_captureWindow; } bool wxWindowGTK::IsRetained() const { return false; } void wxWindowGTK::BlockScrollEvent() { wxASSERT(!m_blockScrollEvent); m_blockScrollEvent = true; } void wxWindowGTK::UnblockScrollEvent() { wxASSERT(m_blockScrollEvent); m_blockScrollEvent = false; } void wxWindowGTK::SetScrollbar(int orient, int pos, int thumbVisible, int range, bool WXUNUSED(update)) { GtkRange * const sb = m_scrollBar[ScrollDirFromOrient(orient)]; wxCHECK_RET( sb, _T("this window is not scrollable") ); if (range > 0) { m_hasScrolling = true; } else { // GtkRange requires upper > lower range = thumbVisible = 1; } if (pos > range - thumbVisible) pos = range - thumbVisible; if (pos < 0) pos = 0; GtkAdjustment * const adj = sb->adjustment; adj->step_increment = 1; adj->page_increment = adj->page_size = thumbVisible; adj->upper = range; SetScrollPos(orient, pos); gtk_adjustment_changed(adj); } void wxWindowGTK::SetScrollPos(int orient, int pos, bool WXUNUSED(refresh)) { const int dir = ScrollDirFromOrient(orient); GtkRange * const sb = m_scrollBar[dir]; wxCHECK_RET( sb, _T("this window is not scrollable") ); // This check is more than an optimization. Without it, the slider // will not move smoothly while tracking when using wxScrollHelper. if (GetScrollPos(orient) != pos) { GtkAdjustment* adj = sb->adjustment; const int max = int(adj->upper - adj->page_size); if (pos > max) pos = max; if (pos < 0) pos = 0; m_scrollPos[dir] = adj->value = pos; g_signal_handlers_disconnect_by_func( m_scrollBar[dir], (gpointer)gtk_scrollbar_value_changed, this); gtk_adjustment_value_changed(adj); g_signal_connect_after(m_scrollBar[dir], "value_changed", G_CALLBACK(gtk_scrollbar_value_changed), this); } } int wxWindowGTK::GetScrollThumb(int orient) const { GtkRange * const sb = m_scrollBar[ScrollDirFromOrient(orient)]; wxCHECK_MSG( sb, 0, _T("this window is not scrollable") ); return int(sb->adjustment->page_size); } int wxWindowGTK::GetScrollPos( int orient ) const { GtkRange * const sb = m_scrollBar[ScrollDirFromOrient(orient)]; wxCHECK_MSG( sb, 0, _T("this window is not scrollable") ); return int(sb->adjustment->value + 0.5); } int wxWindowGTK::GetScrollRange( int orient ) const { GtkRange * const sb = m_scrollBar[ScrollDirFromOrient(orient)]; wxCHECK_MSG( sb, 0, _T("this window is not scrollable") ); return int(sb->adjustment->upper); } // Determine if increment is the same as +/-x, allowing for some small // difference due to possible inexactness in floating point arithmetic static inline bool IsScrollIncrement(double increment, double x) { wxASSERT(increment > 0); const double tolerance = 1.0 / 1024; return fabs(increment - fabs(x)) < tolerance; } wxEventType wxWindowGTK::GetScrollEventType(GtkRange* range) { DEBUG_MAIN_THREAD if (g_isIdle) wxapp_install_idle_handler(); wxASSERT(range == m_scrollBar[0] || range == m_scrollBar[1]); const int barIndex = range == m_scrollBar[1]; GtkAdjustment* adj = range->adjustment; const int value = int(adj->value + 0.5); // save previous position const double oldPos = m_scrollPos[barIndex]; // update current position m_scrollPos[barIndex] = adj->value; // If event should be ignored, or integral position has not changed if (!m_hasVMT || g_blockEventsOnDrag || value == int(oldPos + 0.5)) { return wxEVT_NULL; } wxEventType eventType = wxEVT_SCROLL_THUMBTRACK; if (!m_isScrolling) { // Difference from last change event const double diff = adj->value - oldPos; const bool isDown = diff > 0; if (IsScrollIncrement(adj->step_increment, diff)) { eventType = isDown ? wxEVT_SCROLL_LINEDOWN : wxEVT_SCROLL_LINEUP; } else if (IsScrollIncrement(adj->page_increment, diff)) { eventType = isDown ? wxEVT_SCROLL_PAGEDOWN : wxEVT_SCROLL_PAGEUP; } else if (m_mouseButtonDown) { // Assume track event m_isScrolling = true; } } return eventType; } void wxWindowGTK::ScrollWindow( int dx, int dy, const wxRect* WXUNUSED(rect) ) { wxCHECK_RET( m_widget != NULL, wxT("invalid window") ); wxCHECK_RET( m_wxwindow != NULL, wxT("window needs client area for scrolling") ); // No scrolling requested. if ((dx == 0) && (dy == 0)) return; m_clipPaintRegion = true; if (GetLayoutDirection() == wxLayout_RightToLeft) gtk_pizza_scroll( GTK_PIZZA(m_wxwindow), dx, -dy ); else gtk_pizza_scroll( GTK_PIZZA(m_wxwindow), -dx, -dy ); m_clipPaintRegion = false; #if wxUSE_CARET bool restoreCaret = (GetCaret() != NULL && GetCaret()->IsVisible()); if (restoreCaret) { wxRect caretRect(GetCaret()->GetPosition(), GetCaret()->GetSize()); if (dx > 0) caretRect.width += dx; else { caretRect.x += dx; caretRect.width -= dx; } if (dy > 0) caretRect.height += dy; else { caretRect.y += dy; caretRect.height -= dy; } RefreshRect(caretRect); } #endif // wxUSE_CARET } void wxWindowGTK::GtkScrolledWindowSetBorder(GtkWidget* w, int wxstyle) { //RN: Note that static controls usually have no border on gtk, so maybe //it makes sense to treat that as simply no border at the wx level //as well... if (!(wxstyle & wxNO_BORDER) && !(wxstyle & wxBORDER_STATIC)) { GtkShadowType gtkstyle; if(wxstyle & wxBORDER_RAISED) gtkstyle = GTK_SHADOW_OUT; else if (wxstyle & wxBORDER_SUNKEN) gtkstyle = GTK_SHADOW_IN; // wxBORDER_DOUBLE is no longer supported since wxBORDER_THEME takes on the same value #if 0 else if (wxstyle & wxBORDER_DOUBLE) gtkstyle = GTK_SHADOW_ETCHED_IN; #endif else //default gtkstyle = GTK_SHADOW_IN; gtk_scrolled_window_set_shadow_type( GTK_SCROLLED_WINDOW(w), gtkstyle ); } } void wxWindowGTK::SetWindowStyleFlag( long style ) { // Updates the internal variable. NB: Now m_windowStyle bits carry the _new_ style values already wxWindowBase::SetWindowStyleFlag(style); } // Find the wxWindow at the current mouse position, also returning the mouse // position. wxWindow* wxFindWindowAtPointer(wxPoint& pt) { pt = wxGetMousePosition(); wxWindow* found = wxFindWindowAtPoint(pt); return found; } // Get the current mouse position. wxPoint wxGetMousePosition() { /* This crashes when used within wxHelpContext, so we have to use the X-specific implementation below. gint x, y; GdkModifierType *mask; (void) gdk_window_get_pointer(NULL, &x, &y, mask); return wxPoint(x, y); */ int x, y; GdkWindow* windowAtPtr = gdk_window_at_pointer(& x, & y); Display *display = windowAtPtr ? GDK_WINDOW_XDISPLAY(windowAtPtr) : GDK_DISPLAY(); Window rootWindow = RootWindowOfScreen (DefaultScreenOfDisplay(display)); Window rootReturn, childReturn; int rootX, rootY, winX, winY; unsigned int maskReturn; XQueryPointer (display, rootWindow, &rootReturn, &childReturn, &rootX, &rootY, &winX, &winY, &maskReturn); return wxPoint(rootX, rootY); } // Needed for implementing e.g. combobox on wxGTK within a modal dialog. void wxAddGrab(wxWindow* window) { gtk_grab_add( (GtkWidget*) window->GetHandle() ); } void wxRemoveGrab(wxWindow* window) { gtk_grab_remove( (GtkWidget*) window->GetHandle() ); }
[ "RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775" ]
RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775
2c74d2ceccf63b588480926d80c55bef57f168a8
b945071e088837d70ce8bf8c57ec59be6fadca0b
/compiler/model.cc
cb768d53df0ae0b4bd8afd187f708d46fc7e7a3c
[ "MIT" ]
permissive
vermashresth/chainer-compiler
8649ed4c6e4b8325bef2456ef5a484260f834291
5f5ad365d14398d6ae0214fa012eb10360db8e7e
refs/heads/master
2020-05-04T13:05:19.621839
2019-10-17T13:03:14
2019-10-17T13:03:14
179,147,105
0
0
MIT
2019-10-17T13:03:16
2019-04-02T19:43:25
Python
UTF-8
C++
false
false
2,030
cc
#include "compiler/model.h" #include <compiler/onnx.h> #include <common/log.h> #include <compiler/graph.h> #include <compiler/serializer_util.h> namespace chainer_compiler { Model::Model(const onnx::ModelProto& xmodel) : ir_version_(xmodel.ir_version()), opset_import_(xmodel.opset_import().begin(), xmodel.opset_import().end()), producer_name_(xmodel.producer_name()), producer_version_(xmodel.producer_version()), domain_(xmodel.domain()), model_version_(xmodel.model_version()), doc_string_(xmodel.doc_string()), graph_(new Graph(xmodel.graph())) { for (const onnx::StringStringEntryProto& metadata : xmodel.metadata_props()) { CHECK(metadata_props_.emplace(metadata.key(), metadata.value()).second) << "Duplicated metadata key: " << metadata.key(); } } Model::Model(const Model& model, const std::string& graph_name) : ir_version_(model.ir_version_), opset_import_(model.opset_import_), producer_name_(model.producer_name_), producer_version_(model.producer_version_), domain_(model.domain_), model_version_(model.model_version_), doc_string_(model.doc_string_), metadata_props_(model.metadata_props_), graph_(new Graph(graph_name)) { } Model::~Model() { } void Model::ToONNX(onnx::ModelProto* xmodel) const { DUMP_PRIM(xmodel, ir_version); for (const onnx::OperatorSetIdProto& opset : opset_import_) { *xmodel->add_opset_import() = opset; } DUMP_STRING(xmodel, producer_name); DUMP_STRING(xmodel, producer_version); DUMP_STRING(xmodel, domain); DUMP_PRIM(xmodel, model_version); DUMP_STRING(xmodel, doc_string); graph_->ToONNX(xmodel->mutable_graph()); for (const auto& p : metadata_props_) { onnx::StringStringEntryProto* metadata = xmodel->add_metadata_props(); metadata->set_key(p.first); metadata->set_value(p.second); } } void Model::ResetGraph(Graph* graph) { graph_.reset(graph); } } // namespace chainer_compiler
[ "shinichiro.hamaji@gmail.com" ]
shinichiro.hamaji@gmail.com
88477193d17f8360a0db28c0aa0fa18c446a79e7
f784bdbd0d342a2287a4fc6dabf25d7143c2edde
/include/EmpericalStrategy.h
f999a68977eca6bd34d7ac796308eef6b191570f
[]
no_license
LeonardLi/vNAMS
d6b9893b11e98c1fc9f9c83b7d255043d772e29a
933a0ba40d719b44e1d9a295d60f03ab4aa80140
refs/heads/master
2021-01-12T07:48:49.583680
2017-04-26T16:04:45
2017-04-26T16:04:45
77,027,268
0
0
null
2016-12-21T07:06:39
2016-12-21T07:06:39
null
UTF-8
C++
false
false
946
h
#ifndef _EMPERICAL_STRATEGY_ #define _EMPERICAL_STRATEGY_ #include "ScheduleStrategy.h" #include "VirtualFunction.h" #include <vector> #include <utility> #include <fstream> #include <sstream> #include <iostream> #include <string> class EmpericalStrategy :public ScheduleStrategy{ public: EmpericalStrategy(){}; virtual ~EmpericalStrategy(){}; std::vector<Decision> schedule(const std::map<int, VM_info> &vmInfoMap, const std::vector<double> &physicalCpuUsage, const Numa_node* nodeInfos, const int numOfNode, const int NIC_NODE_ID); public: //read the infomation from file bool initFromFile(); //or from system bool initDefault(const Numa_node* nodeInfos, const int numOfNode); //the basic infomation std::vector<std::vector<double> > lantencyMatrix; std::vector<std::vector<double> > bandwidthMatrix; std::vector<VirtualFunction> serviceFunctionChain; void calculateAffinity(std::vector<Decision>&); }; #endif
[ "liyangde66@gmail.com" ]
liyangde66@gmail.com
0b154a7477aba8cce10dbe49485ccd9ae5b8b30b
cf6868b214e6a2c380f2b2e2d8a14a70cc1d8b0c
/Player/KIB_Player/Kiblet.cpp
290276eb807604b9b7b9a66c610678764dd2a418
[]
no_license
kyzyx/KIB
5d5304a73c5a91733d62946d9b5eb68e4cdd49f1
1cc51d3597d73e953c55becd018cf4677b961a3c
refs/heads/master
2021-01-10T18:26:48.697281
2013-04-26T22:49:12
2013-04-26T22:49:12
7,301,329
0
1
null
null
null
null
UTF-8
C++
false
false
1,846
cpp
#include "Kiblet.h" #include "ArcKidget.h" #include "BackgroundKidget.h" #include "BallKidget.h" #include "BodyKidget.h" #include "ClapKidget.h" #include "HandsKidget.h" #include "KibletKidget.h" #include "PunchKidget.h" #include "WaveKidget.h" using namespace std; Kiblet::Kiblet(void) { } Kiblet::~Kiblet(void) { for (unsigned int i = 0; i < kidgets.size(); ++i) { delete kidgets[i]; } } Kidget* Kiblet::makeKidget(string type, Json::Value& v) { if (type == "arc") return new ArcKidget(&v); else if (type == "background") return new BackgroundKidget(&v); else if (type == "ball") return new BallKidget(&v); else if (type == "body") return new BodyKidget(&v); else if (type == "clap") return new ClapKidget(&v); else if (type == "hands") return new HandsKidget(&v); else if (type == "kiblet") return new KibletKidget(&v); else if (type == "punch") return new PunchKidget(&v); else if (type == "wave") return new WaveKidget(&v); else return NULL; } Kiblet::Kiblet(Json::Value& v) { Json::Value::Members& members = v.getMemberNames(); for (unsigned int i = 0; i < members.size(); ++i) { Kidget* k = makeKidget(members[i], v[members[i]]); kidgets.push_back(k); } } void Kiblet::sendOscMessages(UdpTransmitSocket* transmitSocket, const Vector4* skeletonPositions) { osc::OutboundPacketStream p(buffer, OUTPUT_BUFFER_SIZE); p << osc::BeginBundleImmediate; for (unsigned int i = 0; i < kidgets.size(); ++i) { kidgets[i]->sendOSC(p, skeletonPositions); } p << osc::EndBundle; transmitSocket->Send(p.Data(), p.Size()); } bool Kiblet::checkTriggerCondition() { // Check time // Check OSC Messages return false; } void Kiblet::draw(const Vector4* skel, unsigned char* rgb, float* depth, char* pid, int w, int h) { for (unsigned int i = 0; i < kidgets.size(); ++i) { kidgets[i]->draw(skel, rgb, depth, pid); } }
[ "edward64@gmail.com" ]
edward64@gmail.com
b7dca72e37f114c8484e2f39f9bf486755addd7f
39d592f89bdc0383b58996c224d40b464297d478
/158a.cpp
ad1471d9f5a25cbc8a3bdba544c37922af60c35c
[]
no_license
NoshinTahsin/Codeforces
c276776c8d819846a24efaa04a16c567836f97e9
fd4f770ad9eb36c841aa191609c87c2eb8142891
refs/heads/master
2020-12-14T10:09:39.499288
2020-07-24T13:40:49
2020-07-24T13:40:49
234,705,053
0
0
null
null
null
null
UTF-8
C++
false
false
374
cpp
#include<iostream> using namespace std; int main() { int n,k; cin>>n>>k; int arr[n]; for(int i=0;i<n;i++) { cin>>arr[i]; } int st=arr[k-1]; int cnt=0; for(int i=0;i<n;i++) { if(arr[i]>0 && arr[i]>=st) cnt++; } cout<<cnt<<endl; return 0; }
[ "noreply@github.com" ]
NoshinTahsin.noreply@github.com
2343fb05cff6fb4c450c6e099be8ada33bd4b9d8
38d297718d0252a595e2954243c5a7026b54f844
/proj6/static_lib2/src/sublib2.cpp
64f22a157cb6383744a065cb459093cc4476791b
[]
no_license
deltavoid/cmake_examples
16bfdc2791fdde13681e2b754877742fee0ca2b9
8dac6cfbf2a07dd4dcbdbb44d504029f64ccbbef
refs/heads/master
2023-04-07T07:48:24.983060
2021-04-20T13:47:35
2021-04-20T13:47:35
277,831,884
0
0
null
null
null
null
UTF-8
C++
false
false
131
cpp
#include <iostream> #include "sublib2/sublib2.h" void sublib2::print() { std::cout << "Hello sub-library 2!" << std::endl; }
[ "zhangqianyu.sys@bytedance.com" ]
zhangqianyu.sys@bytedance.com
bdae8b10336b432a75b0b506447c9d697e8a8314
ef98d98431ff8a324863cc26302f16ac1f1e9151
/SINRGE2 Core/sin_kconv.h
1fc7cd652236ba2da45812f39cae9b10d97a785d
[ "Zlib" ]
permissive
orochi2k/SINRGE2
41542dc295a8ef475160a45bfa81d9cf401270ec
66ca171f21c042ad4c978c2965b06ed918af5f24
refs/heads/master
2023-03-18T00:41:19.460037
2018-09-01T03:35:23
2018-09-01T03:35:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
554
h
#ifndef __K_CONV_H__ #define __K_CONV_H__ class CAutoBuffer; namespace Kconv { wchar_t * AnsiToUnicode(const char * str, CAutoBuffer * pAutoBuffer = 0); wchar_t * UTF8ToUnicode(const char * str, CAutoBuffer * pAutoBuffer = 0); char * UnicodeToAnsi(const wchar_t * str, CAutoBuffer * pAutoBuffer = 0); char * UnicodeToUTF8(const wchar_t * str, CAutoBuffer * pAutoBuffer = 0); char * UTF8ToAnsi(const char * str, CAutoBuffer * pAutoBuffer = 0); char * AnsiToUTF8(const char * str, CAutoBuffer * pAutoBuffer = 0); }; #endif // __K_CONV_H__
[ "Gernischt@gmail.com" ]
Gernischt@gmail.com
f4091d54b549689022183ab1192140b3df88b2b2
d002ed401cba924074e021d22347b84334a02b0f
/export/windows/obj/src/lime/net/_HTTPRequest_Bytes.cpp
36c46feec0f11403511087f6e9bdf9970227c889
[]
no_license
IADenner/LD47
63f6beda87424ba7e0e129848ee190c1eb1da54d
340856f1d77983da0e7f331b467609c45587f5d1
refs/heads/master
2022-12-29T13:01:46.789276
2020-10-05T22:04:42
2020-10-05T22:04:42
301,550,551
1
0
null
null
null
null
UTF-8
C++
false
true
6,034
cpp
// Generated by Haxe 4.1.2 #include <hxcpp.h> #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_lime__internal_backend_native_NativeHTTPRequest #include <lime/_internal/backend/native/NativeHTTPRequest.h> #endif #ifndef INCLUDED_lime_app_Future #include <lime/app/Future.h> #endif #ifndef INCLUDED_lime_app_Promise #include <lime/app/Promise.h> #endif #ifndef INCLUDED_lime_net__HTTPRequest_AbstractHTTPRequest #include <lime/net/_HTTPRequest/AbstractHTTPRequest.h> #endif #ifndef INCLUDED_lime_net__HTTPRequest_Bytes #include <lime/net/_HTTPRequest_Bytes.h> #endif #ifndef INCLUDED_lime_net__IHTTPRequest #include <lime/net/_IHTTPRequest.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_d0a88ab7a13f72d7_88_new,"lime.net._HTTPRequest_Bytes","new",0xc45547d0,"lime.net._HTTPRequest_Bytes.new","lime/net/HTTPRequest.hx",88,0x339db723) HX_LOCAL_STACK_FRAME(_hx_pos_d0a88ab7a13f72d7_93_fromBytes,"lime.net._HTTPRequest_Bytes","fromBytes",0x58799e11,"lime.net._HTTPRequest_Bytes.fromBytes","lime/net/HTTPRequest.hx",93,0x339db723) HX_LOCAL_STACK_FRAME(_hx_pos_d0a88ab7a13f72d7_110_load,"lime.net._HTTPRequest_Bytes","load",0x04fea4b6,"lime.net._HTTPRequest_Bytes.load","lime/net/HTTPRequest.hx",110,0x339db723) HX_LOCAL_STACK_FRAME(_hx_pos_d0a88ab7a13f72d7_97_load,"lime.net._HTTPRequest_Bytes","load",0x04fea4b6,"lime.net._HTTPRequest_Bytes.load","lime/net/HTTPRequest.hx",97,0x339db723) namespace lime{ namespace net{ void _HTTPRequest_Bytes_obj::__construct(::String uri){ HX_STACKFRAME(&_hx_pos_d0a88ab7a13f72d7_88_new) HXDLIN( 88) super::__construct(uri); } Dynamic _HTTPRequest_Bytes_obj::__CreateEmpty() { return new _HTTPRequest_Bytes_obj; } void *_HTTPRequest_Bytes_obj::_hx_vtable = 0; Dynamic _HTTPRequest_Bytes_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< _HTTPRequest_Bytes_obj > _hx_result = new _HTTPRequest_Bytes_obj(); _hx_result->__construct(inArgs[0]); return _hx_result; } bool _HTTPRequest_Bytes_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x09b24b15) { return inClassId==(int)0x00000001 || inClassId==(int)0x09b24b15; } else { return inClassId==(int)0x7f4deb50; } } ::Dynamic _HTTPRequest_Bytes_obj::fromBytes( ::haxe::io::Bytes bytes){ HX_STACKFRAME(&_hx_pos_d0a88ab7a13f72d7_93_fromBytes) HXDLIN( 93) return bytes; } HX_DEFINE_DYNAMIC_FUNC1(_HTTPRequest_Bytes_obj,fromBytes,return ) ::lime::app::Future _HTTPRequest_Bytes_obj::load(::String uri){ HX_BEGIN_LOCAL_FUNC_S2(::hx::LocalFunc,_hx_Closure_0, ::lime::net::_HTTPRequest_Bytes,_gthis, ::lime::app::Promise,promise) HXARGC(1) void _hx_run( ::haxe::io::Bytes bytes){ HX_GC_STACKFRAME(&_hx_pos_d0a88ab7a13f72d7_110_load) HXLINE( 111) _gthis->responseData = _gthis->fromBytes(bytes); HXLINE( 112) promise->complete(_gthis->responseData); } HX_END_LOCAL_FUNC1((void)) HX_GC_STACKFRAME(&_hx_pos_d0a88ab7a13f72d7_97_load) HXLINE( 96) ::lime::net::_HTTPRequest_Bytes _gthis = ::hx::ObjectPtr<OBJ_>(this); HXLINE( 98) if (::hx::IsNotNull( uri )) { HXLINE( 100) this->uri = uri; } HXLINE( 103) ::lime::app::Promise promise = ::lime::app::Promise_obj::__alloc( HX_CTX ); HXLINE( 104) ::lime::app::Future future = this->_hx___backend->loadData(this->uri,null()); HXLINE( 106) future->onProgress(promise->progress_dyn()); HXLINE( 107) future->onError(promise->error_dyn()); HXLINE( 109) future->onComplete( ::Dynamic(new _hx_Closure_0(_gthis,promise))); HXLINE( 115) return promise->future; } ::hx::ObjectPtr< _HTTPRequest_Bytes_obj > _HTTPRequest_Bytes_obj::__new(::String uri) { ::hx::ObjectPtr< _HTTPRequest_Bytes_obj > __this = new _HTTPRequest_Bytes_obj(); __this->__construct(uri); return __this; } ::hx::ObjectPtr< _HTTPRequest_Bytes_obj > _HTTPRequest_Bytes_obj::__alloc(::hx::Ctx *_hx_ctx,::String uri) { _HTTPRequest_Bytes_obj *__this = (_HTTPRequest_Bytes_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(_HTTPRequest_Bytes_obj), true, "lime.net._HTTPRequest_Bytes")); *(void **)__this = _HTTPRequest_Bytes_obj::_hx_vtable; __this->__construct(uri); return __this; } _HTTPRequest_Bytes_obj::_HTTPRequest_Bytes_obj() { } ::hx::Val _HTTPRequest_Bytes_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"load") ) { return ::hx::Val( load_dyn() ); } break; case 9: if (HX_FIELD_EQ(inName,"fromBytes") ) { return ::hx::Val( fromBytes_dyn() ); } } return super::__Field(inName,inCallProp); } #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo *_HTTPRequest_Bytes_obj_sMemberStorageInfo = 0; static ::hx::StaticInfo *_HTTPRequest_Bytes_obj_sStaticStorageInfo = 0; #endif static ::String _HTTPRequest_Bytes_obj_sMemberFields[] = { HX_("fromBytes",a1,f2,20,72), HX_("load",26,9a,b7,47), ::String(null()) }; ::hx::Class _HTTPRequest_Bytes_obj::__mClass; void _HTTPRequest_Bytes_obj::__register() { _HTTPRequest_Bytes_obj _hx_dummy; _HTTPRequest_Bytes_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("lime.net._HTTPRequest_Bytes",de,5f,09,09); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(_HTTPRequest_Bytes_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< _HTTPRequest_Bytes_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = _HTTPRequest_Bytes_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = _HTTPRequest_Bytes_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace lime } // end namespace net
[ "theiadstudios@gmail.com" ]
theiadstudios@gmail.com
1c4ff16ab7918c891ff75d7c398d7e3197391108
90047daeb462598a924d76ddf4288e832e86417c
/base/task_scheduler/task_unittest.cc
fb076d761bea261f68d378bc428aa373c7290bc8
[ "BSD-3-Clause" ]
permissive
massbrowser/android
99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080
a9c4371682c9443d6e1d66005d4db61a24a9617c
refs/heads/master
2022-11-04T21:15:50.656802
2017-06-08T12:31:39
2017-06-08T12:31:39
93,747,579
2
2
BSD-3-Clause
2022-10-31T10:34:25
2017-06-08T12:36:07
null
UTF-8
C++
false
false
2,692
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/task_scheduler/task.h" #include "base/bind.h" #include "base/location.h" #include "base/task_scheduler/task_traits.h" #include "base/time/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { namespace internal { // Verify that the shutdown behavior of a BLOCK_SHUTDOWN delayed task is // adjusted to SKIP_ON_SHUTDOWN. The shutown behavior of other delayed tasks // should not change. TEST(TaskSchedulerTaskTest, ShutdownBehaviorChangeWithDelay) { Task continue_on_shutdown(FROM_HERE, BindOnce(&DoNothing), TaskTraits().WithShutdownBehavior( TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN), TimeDelta::FromSeconds(1)); EXPECT_EQ(TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN, continue_on_shutdown.traits.shutdown_behavior()); Task skip_on_shutdown( FROM_HERE, BindOnce(&DoNothing), TaskTraits().WithShutdownBehavior(TaskShutdownBehavior::SKIP_ON_SHUTDOWN), TimeDelta::FromSeconds(1)); EXPECT_EQ(TaskShutdownBehavior::SKIP_ON_SHUTDOWN, skip_on_shutdown.traits.shutdown_behavior()); Task block_shutdown( FROM_HERE, BindOnce(&DoNothing), TaskTraits().WithShutdownBehavior(TaskShutdownBehavior::BLOCK_SHUTDOWN), TimeDelta::FromSeconds(1)); EXPECT_EQ(TaskShutdownBehavior::SKIP_ON_SHUTDOWN, block_shutdown.traits.shutdown_behavior()); } // Verify that the shutdown behavior of undelayed tasks is not adjusted. TEST(TaskSchedulerTaskTest, NoShutdownBehaviorChangeNoDelay) { Task continue_on_shutdown(FROM_HERE, BindOnce(&DoNothing), TaskTraits().WithShutdownBehavior( TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN), TimeDelta()); EXPECT_EQ(TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN, continue_on_shutdown.traits.shutdown_behavior()); Task skip_on_shutdown( FROM_HERE, BindOnce(&DoNothing), TaskTraits().WithShutdownBehavior(TaskShutdownBehavior::SKIP_ON_SHUTDOWN), TimeDelta()); EXPECT_EQ(TaskShutdownBehavior::SKIP_ON_SHUTDOWN, skip_on_shutdown.traits.shutdown_behavior()); Task block_shutdown( FROM_HERE, BindOnce(&DoNothing), TaskTraits().WithShutdownBehavior(TaskShutdownBehavior::BLOCK_SHUTDOWN), TimeDelta()); EXPECT_EQ(TaskShutdownBehavior::BLOCK_SHUTDOWN, block_shutdown.traits.shutdown_behavior()); } } // namespace internal } // namespace base
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
7508fbed7e64d2afdb563f07d9255f0ec8f844d2
5c74203db583750843c70142f1a9d7166e942d63
/boost/memory/memory.cpp
35d228c7eb35a1785436015d1fe1b86334b7bb88
[]
no_license
shiqi-lu/Learn-CPP
fd49704192c3983dd81ba5d690f909ba0968e116
169a383a9078b3fc1e6fffa5be79f068f10f9b0e
refs/heads/master
2021-05-30T10:18:24.371296
2015-11-30T23:27:51
2015-11-30T23:27:51
25,058,280
1
0
null
null
null
null
UTF-8
C++
false
false
3,456
cpp
#include <iostream> #include <vector> #include <string> #include <boost/smart_ptr.hpp> using namespace boost; using namespace std; struct posix_file { posix_file(const char * file_name) { cout << "open file: " << file_name << endl; } ~posix_file() { cout << "close file" << endl; } }; void boost_scoped_ptr() { cout << "============== scoped_ptr: =============" << endl; scoped_ptr<string> sp(new string("text")); cout << *sp << endl; cout << sp->size() << endl; scoped_ptr<int> p(new int); if (p) { *p = 100; cout << *p << endl; } p.reset(); assert(p == 0); if (!p) { cout << "scoped_ptr == null" << endl; } scoped_ptr<posix_file> fp (new posix_file("/tmp/a.txt")); /* output: ============== scoped_ptr: ============= text 4 100 scoped_ptr == null open file: /tmp/a.txt close file */ } // not recommend to use void boost_scoped_array() { scoped_array<int> sap(new int [100]); sap[0] = 10; int * arr = new int [100]; scoped_array<int> sa(arr); fill_n(&sa[0], 100, 5); sa[10] = sa[20] + sa[30]; } void boost_shared_ptr() { shared_ptr<int> spi(new int); assert(spi); *spi = 253; shared_ptr<string> sps(new string("smart")); assert(sps->size() == 5); shared_ptr<int> sp(new int(10)); assert(sp.unique()); shared_ptr<int> sp2 = sp; assert(sp == sp2 && sp.use_count() == 2); *sp2 = 100; assert(*sp == 100); sp.reset(); assert(!sp); } class shared { private: shared_ptr<int> p; public: shared(shared_ptr<int> p_):p(p_) {} void print() { cout << "count:" << p.use_count() << ",v =" << *p << endl; } }; void print_func(shared_ptr<int> p) { cout << "count:" << p.use_count() << ", v=" << *p << endl; } void boost_shared_ptr_class() { cout << "======= shared_ptr_class: ========" << endl; shared_ptr<int> p (new int(100)); shared s1(p), s2(p); s1.print(); s2.print(); *p = 20; print_func(p); s1.print(); /* output: ======= shared_ptr_class: ======== count:3,v =100 count:3,v =100 count:4, v=20 count:3,v =20 */ } void boost_stl_shared_ptr() { cout << "========= stl_shared_ptr: =============" << endl; typedef vector<shared_ptr<int> > vs; vs v(10); int i = 0; for (vs::iterator pos = v.begin(); pos != v.end(); ++pos) { (*pos) = make_shared<int>(++i); cout << *(*pos) << ", "; } cout << endl; shared_ptr<int> p = v[9]; *p = 100; cout << *v[9] << endl; /* output: ========= stl_shared_ptr: ============= 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 */ } void boost_shared_array() { int * p = new int[100]; shared_array<int> sa(p); shared_array<int> sa2 = sa; sa[0] = 10; assert(sa2[0] == 10); } void boost_weak_ptr() { shared_ptr<int> sp(new int(10)); assert(sp.use_count() == 1); weak_ptr<int> wp(sp); assert(wp.use_count() == 1); if (!wp.expired()) { shared_ptr<int> sp2 = wp.lock(); *sp2 = 100; assert(wp.use_count() == 2); } assert(wp.use_count() == 1); sp.reset(); assert(wp.expired()); assert(!wp.lock()); } int main() { boost_scoped_ptr(); boost_scoped_array(); boost_shared_ptr(); boost_shared_ptr_class(); boost_stl_shared_ptr(); boost_shared_array(); boost_weak_ptr(); return 0; }
[ "traumlou@gmail.com" ]
traumlou@gmail.com
9cdb8357ac8fb471092cf387f6fc6ab6ef18e401
1fea1b1bcb283931afea6aa3103795236f12fb6d
/rta-dq-lib/execution_strategies/include/HDF5ReadingCompoundScalarFieldStrategy.hpp
12033e5265ad86cdf593f928aa0a2e8a0df88980
[]
no_license
LeoBaro/rtadqlibcpp_proto
09b3ec479117fec37ce5a5dd6441a16316a3bc8f
9802c180e29a3aecc9bfbee4735ec51c8328f755
refs/heads/master
2022-12-06T13:10:59.449412
2020-08-22T09:21:49
2020-08-22T09:21:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,337
hpp
#ifndef HDF5_READING_COMPOUND_SCALAR_FIELD_STRATEGY_HPP #define HDF5_READING_COMPOUND_SCALAR_FIELD_STRATEGY_HPP #include "H5Cpp.h" using namespace H5; #include "HDF5ReadingCompoundFieldStrategy.hpp" template <class T> class HDF5ReadingCompoundScalarFieldStrategy: public HDF5ReadingCompoundFieldStrategy<T> { public: HDF5ReadingCompoundScalarFieldStrategy(ParamsForHDF5CompoundFieldReading & params); ~HDF5ReadingCompoundScalarFieldStrategy(); T* exec(ExecutionParams & params); }; /** * Constructor for class HDF5ReadingCompoundScalarFieldStrategy. * * @param params an object of class ParamsForHDF5CompoundFieldReading */ template <class T> HDF5ReadingCompoundScalarFieldStrategy<T>::HDF5ReadingCompoundScalarFieldStrategy(ParamsForHDF5CompoundFieldReading & params) { this->compound_field_data = new float[ params.how_many ]; } /** * Destructor for class HDF5ReadingCompoundScalarFieldStrategy. */ template <class T> HDF5ReadingCompoundScalarFieldStrategy<T>::~HDF5ReadingCompoundScalarFieldStrategy() { //delete this->compound_field_data; this delete will cause a segmentation fault } /** * This method opens an HDF5 file and reads a scalar field of a compound dataset element. * * This output array is allocated by the class' constructor. * * @param params an object of class ParamsForHDF5CompoundFieldReading */ template <class T> T* HDF5ReadingCompoundScalarFieldStrategy<T>::exec(ExecutionParams & params) { ParamsForHDF5CompoundFieldReading & cf_params = (ParamsForHDF5CompoundFieldReading &) params; this->file = new H5File (cf_params.file_name, H5F_ACC_RDONLY); this->group = new Group (this->file->openGroup(cf_params.group_name)); this->dataset = new DataSet (this->group->openDataSet(cf_params.dataset_name)); CompType field_type( sizeof(T) ); field_type.insertMember( cf_params.field_name, 0, PredType::NATIVE_FLOAT); Exception::dontPrint(); // should be centralized try { this->dataset->read(this->compound_field_data, field_type); } // catch failure caused by the H5File operations catch( Exception error ) { error.printErrorStack(); } delete this->dataset; delete this->group; delete this->file; return this->compound_field_data; } #endif
[ "leonardo.baroncelli@inaf.it" ]
leonardo.baroncelli@inaf.it
a3cbf53db181b2f87bded32893d2c93bbb24a633
c377b266f74f9c835cf3534728e38ab17116c650
/src/StockAverager.cpp
2b0f256cd47ca97e8907a29c80b92f20b522dee3
[ "MIT" ]
permissive
gigs94/qlft
68abb41cb93938d9b08fa7965e51dcf738bf3106
738c35e9dd9230375370bba4f9cf7ccf5f85c7f3
refs/heads/master
2021-01-20T17:02:35.867226
2016-07-14T22:45:28
2016-07-14T22:45:28
63,359,371
0
0
null
null
null
null
UTF-8
C++
false
false
924
cpp
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <unordered_map> #include <StockAverager.h> #include <StocksProcessor.h> int main() { std::ifstream infile{"input.csv"}; std::ofstream outfile{"output.csv"}; StocksProcessor processor{}; while (infile) { std::string line; std::string stockName; long timestamp; int volume; int price; if (!std::getline( infile, line )) break; std::istringstream ss( line ); std::string d; if (!getline( ss, d, ',' )) break; timestamp = std::stol(d); if (!getline( ss, stockName, ',' )) break; if (!getline( ss, d, ',' )) break; volume = std::stoi(d); if (!getline( ss, d, '\n' )) break; price = std::stoi(d); processor.add(timestamp,stockName,volume,price); }; outfile << processor; };
[ "dagregor@us.ibm.com" ]
dagregor@us.ibm.com
ca9c086027352c6712602de83ae27ef556e62ed7
bd1a8d3157793f97ac0e4340cf51e09412b8717d
/src/config/file/filebasedconfig.h
314ea0cdc51c3fe103b5809f6f0a115f794248be
[]
no_license
zaic/cavis
198e070c32fe48d238680450a408cbb2c90eb3a7
d8d91fe34d7fba83ef3eb2b80413bb9aae6c03d4
refs/heads/master
2020-04-08T12:12:40.880402
2013-06-06T01:55:15
2013-06-06T01:55:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,160
h
#pragma once #include <cstddef> #include <fstream> #include <iostream> #include <sstream> #include <cassert> #include <cstdlib> #include "../config.h" using std::ifstream; using std::cerr; using std::endl; using std::stringstream; using std::string; class FileBasedConfig : public Config { FileBasedConfig(); FileBasedConfig(const FileBasedConfig& ); FileBasedConfig& operator=(const FileBasedConfig& ); int real_x, real_y, element_size; int logic_x, logic_y; int iterations_count; int current_iteration; char* data; public: FileBasedConfig(const char *filename, int x = 0, int y = 0); virtual ~FileBasedConfig(); virtual int prev(); virtual int next(); virtual int setIteration(int iteration); virtual int getIterationsCount() { return iterations_count; } virtual void* getData(void* = NULL) { return data; } virtual int getDimSize(int dim) const; virtual int getDimSizeX() const { return real_x; } virtual int getDimSizeY() const { return real_y; } virtual int getDimSizeZ() const { return 1; } virtual void setLogicSize(int x, int y) { logic_x = x; logic_y = y; } };
[ "zaic101@gmail.com" ]
zaic101@gmail.com
620e8d7f0809dd7044efad7772103a50ce5cc41c
0fba517f10d2179a8aa838b9da9b789d4e203598
/Codeforces/CF 166/D.cpp
42df798894fe4eec6de5301cea17d8a7e550d95c
[]
no_license
hdi-superuser/Codes
e7923975b4656a09b211710d659cd2ea7859bcbb
2ca9d777d6ecce59c0ed26e8db83b475b73b192a
refs/heads/master
2021-01-21T00:36:34.855984
2016-06-15T20:27:28
2016-06-15T20:27:28
61,238,394
0
0
null
2016-06-15T20:22:04
2016-06-15T20:22:04
null
UTF-8
C++
false
false
1,601
cpp
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <vector> #include <cstring> #include <string> #include <cmath> #include <ctime> #include <utility> #include <map> #include <set> #include <queue> #include <stack> #include <sstream> #define FOR(a,b,c) for (int a=b,_c=c;a<=_c;a++) #define FORD(a,b,c) for (int a=b;a>=c;a--) #define REP(i,a) for(int i=0,_a=(a); i<_a; ++i) #define REPD(i,a) for(int i=(a)-1; i>=0; --i) #define pb push_back #define mp make_pair #define fi first #define se second #define sz(a) int(a.size()) #define reset(a,b) memset(a,b,sizeof(a)) #define oo 1000000007 using namespace std; typedef long long ll; typedef pair<ll, ll> pll; const int maxn=1507; const ll base=73471; const ll base2=100007; char s[maxn],buf[30]; int n,k,res,sum[maxn]; ll val[maxn],hashpw[maxn],val2[maxn],hashpw2[maxn]; vector<pll> list; #include <conio.h> int main(){ //freopen("test.txt","r",stdin); scanf("%s",s+1); n=strlen(s+1); scanf("%s",buf); scanf("%d",&k); hashpw[0]=hashpw2[0]=1; val[0]=val2[0]=0; sum[0]=0; FOR(i,1,n){ val[i]=val[i-1]*base+s[i]; hashpw[i]=hashpw[i-1]*base; val2[i]=val2[i-1]*base2+s[i]; hashpw2[i]=hashpw2[i-1]*base2; sum[i]=sum[i-1]+(buf[s[i]-'a']=='0'); } FOR(i,1,n) FOR(j,i,n) if(sum[j]-sum[i-1]<=k) list.pb(pll(val[j]-val[i-1]*hashpw[j-i+1], val2[j]-val2[i-1]*hashpw2[j-i+1])); sort(list.begin(),list.end()); list.resize(unique(list.begin(),list.end())-list.begin()); printf("%d\n",sz(list)); //getch(); return 0; }
[ "yenthanh.t7@gmail.com" ]
yenthanh.t7@gmail.com
8fd2096354f5669460ad43455052aa9db76d9f87
c164deecf14db1b3f09e9e89dcaf45c993a35897
/include/lwiot/ipaddress.h
39fff4add5764d0bb51cec12012e3ebd3e02191e
[ "Apache-2.0" ]
permissive
michelmegens/lwIoT
16135aadc53079b03b49cef002daf5df19f94cd2
345d7d7705b1c2f639c4b19fe608ae54e3b7cde1
refs/heads/master
2021-10-15T23:19:00.065109
2018-10-02T13:17:20
2018-10-02T13:17:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,077
h
/* * IP address object definition. * * @author Michel Megens * @email dev@bietje.net */ #pragma once #include <lwiot/types.h> #include <lwiot/string.h> namespace lwiot { class IPAddress { public: explicit IPAddress(); explicit IPAddress(uint8_t first, uint8_t second, uint8_t third, uint8_t forth); explicit IPAddress(const uint8_t *address); IPAddress(uint32_t address); virtual ~IPAddress() = default; virtual String toString() const; static IPAddress fromString(const String& str); static IPAddress fromString(const char *str); /* Operators */ operator uint32_t () const; bool operator ==(const IPAddress& other) const; bool operator ==(const uint32_t& other) const; bool operator ==(const uint8_t* other) const; uint8_t operator [](int idx) const; uint8_t& operator [](int idx); IPAddress& operator =(const uint8_t *address); IPAddress& operator =(uint32_t addr); IPAddress& operator =(const IPAddress& addr); private: union { uint8_t bytes[4]; uint32_t dword; } _address; const uint8_t *raw() const; }; }
[ "dev@bietje.net" ]
dev@bietje.net
46388f2039a1bf63c355098e4e528281be71a454
92468dc69a005e9b640093c9be2db2465130a57d
/Sources/Log.cpp
e6099ea0ecee10a3fc9af5518e633d5655c7b029
[]
no_license
wingrime/ShaderTestPlatform
8bf32922d16b95d8f57bbd53942b0a2080cbda5a
d531b90415946a4c0608d2eb3eb37317a9739ecd
refs/heads/master
2021-01-10T02:18:49.350009
2017-01-05T19:01:11
2017-01-05T19:01:11
47,027,076
1
0
null
null
null
null
UTF-8
C++
false
false
1,720
cpp
#include "Log.h" #include <iostream> #include <stdarg.h> #include "MAssert.h" #include "ErrorCodes.h" #include "string_format.h" Log::~Log() { d_logfile_stream.flush(); d_logfile_stream.close(); } Log::Log(Log::Verbosity _v, const std::string &s) :d_logfile_stream(s), v(_v) { } int Log::LogW(const std::string &s) { d_logfile_stream << "[W]" << s << std::endl; if (d_callback) d_callback(Log::L_WARNING,std::string("[WARN] ")+s+'\n'); return ESUCCESS; } int Log::LogFmtW(const char * fmt_str, ...) { va_list args; va_start(args, fmt_str); int r = LogW(vastring_format(fmt_str,args)); va_end(args); return r; } int Log::LogFmtE(const char * fmt_str, ...) { va_list args; va_start(args, fmt_str); int r = LogE(vastring_format(fmt_str,args)); va_end(args); return r; } int Log::LogFmtV(const char * fmt_str, ...) { va_list args; va_start(args, fmt_str); int r = LogV(vastring_format(fmt_str,args)); va_end(args); return r; } int Log::LogE(const std::string &s) { d_logfile_stream << "[E]" << s << std::endl; if (d_callback) d_callback(Log::L_ERROR,std::string("[ERR] ")+s+'\n'); /*log to std console -- remove me*/ std::cout << s << std::endl; std::cout.flush(); d_logfile_stream.flush(); return ESUCCESS; } int Log::LogV(const std::string &s) { if (d_callback) d_callback(Log::L_VERBOSE,std::string("[VERB] ")+s+'\n'); d_logfile_stream << "[V]" << s << std::endl; return ESUCCESS; } void Log::SetCallback(std::function<void (Log::Verbosity, const std::string &)> callback) { MASSERT(!callback); d_callback = callback; }
[ "wingrime@gmail.com" ]
wingrime@gmail.com
78095d438f3ba8ffccfb37c4fcda643fe886a4a8
642630fc1f6747663f08c6357e3b2c3ecaa994a5
/libraries/SmartRC-CC1101-Driver-Lib/examples/CC1101 default examples/cc1101_Receive/cc1101_Receive.ino
d91f0c585e29034f8bb0faed2b9168e199093e28
[ "CC-BY-4.0" ]
permissive
whid-injector/EvilCrow-RF
e099644a4248484c8d4276e496f2e4d6f8025e7f
d47ac1204fcd2fea070a1d9e80f12f9e15c3a64a
refs/heads/main
2023-04-09T16:09:40.864399
2021-04-20T09:04:22
2021-04-20T09:04:22
359,750,025
3
1
CC-BY-4.0
2021-04-20T08:59:59
2021-04-20T08:59:59
null
UTF-8
C++
false
false
1,548
ino
// These examples are from the Electronics Cookbook by Simon Monk //https://github.com/LSatan/SmartRC-CC1101-Driver-Lib // mod by Little_S@tan #include <ELECHOUSE_CC1101_SRC_DRV.h> const int n = 61; void setup(){ Serial.begin(9600); Serial.println("Rx"); ELECHOUSE_cc1101.setGDO(6,2); // set lib internal gdo pins (gdo0,gdo2). ELECHOUSE_cc1101.setCCMode(1); // set config for internal transmission mode. ELECHOUSE_cc1101.setModulation(0); // set modulation mode. 0 = 2-FSK, 1 = GFSK, 2 = ASK/OOK, 3 = 4-FSK, 4 = MSK. ELECHOUSE_cc1101.setMHZ(433.92); // Here you can set your basic frequency. The lib calculates the frequency automatically (default = 433.92).The cc1101 can: 300-348 MHZ, 387-464MHZ and 779-928MHZ. Read More info from datasheet. // ELECHOUSE_cc1101.setPA(10); // set TxPower. The following settings are possible depending on the frequency band. (-30 -20 -15 -10 -6 0 5 7 10 11 12) Default is max! ELECHOUSE_cc1101.Init(); // must be set to initialize the cc1101! ELECHOUSE_cc1101.SetRx(); // set Receive on. } byte buffer[61] = {0}; void loop(){ if (ELECHOUSE_cc1101.CheckReceiveFlag()) { Serial.print("Rssi: "); Serial.println(ELECHOUSE_cc1101.getRssi()); Serial.print("LQI: "); Serial.println(ELECHOUSE_cc1101.getLqi()); int len = ELECHOUSE_cc1101.ReceiveData(buffer); buffer[len] = '\0'; Serial.println((char *) buffer); ELECHOUSE_cc1101.SetRx(); } }
[ "jserna@phoenixintelligencesecurity.com" ]
jserna@phoenixintelligencesecurity.com
5d86b1013fd9c4e4a17b0806e4ccb097926cfdeb
414af5807da676c87967d47132654c08238b9b2e
/part-3/09-priority-queues-heapsort/program_09_06.cpp
44beddbff2ce042b0f72457ea49443c3e42ebae6
[]
no_license
jthommen/algorithms-cpp
bfcd77ba90af1df1dfac00d8ceeb3239e8a11db3
c20149ac0e7c4ea8452c39b975f757e05e3438c8
refs/heads/master
2020-04-15T01:57:18.051712
2019-12-22T12:55:22
2019-12-22T12:55:22
164,297,665
0
0
null
null
null
null
UTF-8
C++
false
false
1,791
cpp
/* ### Program 9.6: Heapsort ### Description: Using fixDown directly gives the classical heapsort algorithm. The for loop constructs the heap, then the while loop exchanges the largest element with the final element in the array and repairs the heap, continuing until the heap is empty. The pointer pq to a[l-1] allows the code to treat the subarray passed to it as an array with the first element at index 1, for the array representation of the complete tree. Some programming environments may disallow this usage. Properties: - Heapsort uses fewer than 2N lg N comparisons to sort N elements. - Heap-based selection allows the kth largest of N items to be found in time proportional to N when k is small or close to N, and in time proportional to N log N otherwise. */ #include<iostream> #include<cstdlib> #include "pq.cpp" template<typename Item> void heapsort(Item a[], int l, int r) { int k, N = r-l+1; Item* pq = a+l-1; // constructing heap tree for(k = N/2; k >= 1; k--) fixDown(pq, k, N); // performing sort (sortdown) while(N > 1) { exch(pq[1], pq[N]); fixDown(pq, 1, --N); } } int main(int argc, char* argv[]) { // Getting command line arguments // N = amount of numbers to sort // sw = generate numbers randomly or take from std input int i, N = atoi(argv[1]), sw = atoi(argv[2]); int* a = new int[N]; // Random number generation or command line input if(sw) for(i=0; i<N; i++) a[i] = 1000*(1.0*rand()/RAND_MAX); else { N = 0; while(std::cin >> a[N]) N++; } // Sorting numbers heapsort(a, 0, N-1); // Printing sorted numbers for(i=0; i<N; i++) std::cout << a[i] << " "; std::cout << std::endl; }
[ "23640912+jthommen@users.noreply.github.com" ]
23640912+jthommen@users.noreply.github.com
eaa1ac8e8532257ebc955bc7754a230c2b5c1f2f
0a1d33de260573d68b8d02926a92a52530ec7d74
/tile.cpp
cf09389a4eac5c984069eb139bf79effb6ce87b2
[]
no_license
Chuvvie/Final-Project
9a2598f8ef9fe74a936c88c7ea952447bae9a207
960b168327dcd0a55dc11ca6e74f6b68c7d96789
refs/heads/master
2021-01-21T16:48:43.616845
2016-05-06T06:49:32
2016-05-06T06:49:32
58,185,767
0
0
null
2016-05-06T06:26:46
2016-05-06T06:26:46
null
UTF-8
C++
false
false
1,462
cpp
#include "Tile.h" #include "SFML/System/Vector2.hpp" #include "SFML/Graphics/Color.hpp" Tile::Tile(float cx, float cy, int type, bool passability) { this->cx = cx; this->cy = cy; this->type = type; this->passability = passability; this->shape = sf::RectangleShape(sf::Vector2f(Tile::tileSize, Tile::tileSize)); this->shape.setPosition(sf::Vector2f((cx - (Tile::tileSize / 2)), (cy - (Tile::tileSize / 2)))); this->shape.setFillColor((type == 0)?(sf::Color::White):(sf::Color::Black)); } int Tile::getType() { return this->type; } void Tile::setColor(sf::Color color) { this->shape.setFillColor(color); } // 0 is free tile, 1 is wall, 2 is object, 3 is hall, 4 is triggeredobject void Tile::setType(int type) { this->type = type; if(type == 0) { this->passability = true; this->shape.setFillColor(sf::Color::White); } else if (type == 1) { this->passability = false; this->shape.setFillColor(sf::Color::Black); } else if (type == 2) { this->passability = false; this->shape.setFillColor(sf::Color::Yellow); } else if (type == 3) { this->passability = true; this->shape.setFillColor(sf::Color::White); } else if (type == 4) { this->passability = false; this->shape.setFillColor(sf::Color::Red); } } bool Tile::isPassable() { return this->passability; } void Tile::draw(sf::RenderWindow* window) { window->draw(this->shape); } float Tile::getX(){ return cx; } float Tile::getY(){ return cx; }
[ "giansalay@yahoo.com" ]
giansalay@yahoo.com
70f52cde87541f0d1c88c0a92d555d6e9a3629c5
cd5610dd6fcb7803d1ea1883dec3d8b36a8c7c7e
/src/primitives/block.h
e0a0ce225f4adb3a019daad9af53fe4c9a13bf9e
[ "MIT" ]
permissive
malandante/Commercium-TESTNET
39f62f83bd61c9206a6ebafe77d354c61081ffd5
91ad12511d89b8357540c8208093098419f5e9ff
refs/heads/master
2020-04-04T18:51:48.191375
2018-07-21T01:03:40
2018-07-21T01:03:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,811
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_PRIMITIVES_BLOCK_H #define BITCOIN_PRIMITIVES_BLOCK_H #include "primitives/transaction.h" #include "serialize.h" #include "uint256.h" /** Nodes collect new transactions into a block, hash them into a hash tree, * and scan through nonce values to make the block's hash satisfy proof-of-work * requirements. When they solve the proof-of-work, they broadcast the block * to everyone and the block is added to the block chain. The first transaction * in the block is a special one that creates a new coin owned by the creator * of the block. */ class CBlockHeader { public: // header static const size_t HEADER_SIZE=4+32+32+32+4+4+32; // excluding Equihash solution int32_t nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; uint256 hashReserved; uint32_t nTime; uint32_t nBits; uint256 nNonce; std::vector<unsigned char> nSolution; CBlockHeader() { SetNull(); } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(this->nVersion); READWRITE(hashPrevBlock); READWRITE(hashMerkleRoot); READWRITE(hashReserved); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); READWRITE(nSolution); } void SetNull() { nVersion = 0; hashPrevBlock.SetNull(); hashMerkleRoot.SetNull(); hashReserved.SetNull(); nTime = 0; nBits = 0; nNonce = uint256(); nSolution.clear();; } bool IsNull() const { return (nBits == 0); } uint256 GetHash() const; int64_t GetBlockTime() const { return (int64_t)nTime; } }; class CBlock : public CBlockHeader { public: // network and disk std::vector<CTransactionRef> vtx; // memory only mutable CTxOut txoutMasternode; // masternode payment mutable std::vector<CTxOut> voutSuperblock; // superblock payment mutable bool fChecked; CBlock() { SetNull(); } CBlock(const CBlockHeader &header) { SetNull(); *((CBlockHeader*)this) = header; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(*(CBlockHeader*)this); READWRITE(vtx); } void SetNull() { CBlockHeader::SetNull(); vtx.clear(); txoutMasternode = CTxOut(); voutSuperblock.clear(); fChecked = false; } CBlockHeader GetBlockHeader() const { CBlockHeader block; block.nVersion = nVersion; block.hashPrevBlock = hashPrevBlock; block.hashMerkleRoot = hashMerkleRoot; block.hashReserved = hashReserved; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; block.nSolution = nSolution; return block; } std::string ToString() const; }; /** * Custom serializer for CBlockHeader that omits the nonce and solution, for use * as input to Equihash. */ class CEquihashInput : private CBlockHeader { public: CEquihashInput(const CBlockHeader &header) { CBlockHeader::SetNull(); *((CBlockHeader*)this) = header; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(this->nVersion); READWRITE(hashPrevBlock); READWRITE(hashMerkleRoot); READWRITE(hashReserved); READWRITE(nTime); READWRITE(nBits); } }; /** Describes a place in the block chain to another node such that if the * other node doesn't have the same branch, it can find a recent common trunk. * The further back it is, the further before the fork it may be. */ struct CBlockLocator { std::vector<uint256> vHave; CBlockLocator() {} CBlockLocator(const std::vector<uint256>& vHaveIn) { vHave = vHaveIn; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { int nVersion = s.GetVersion(); if (!(s.GetType() & SER_GETHASH)) READWRITE(nVersion); READWRITE(vHave); } void SetNull() { vHave.clear(); } bool IsNull() const { return vHave.empty(); } }; #endif // BITCOIN_PRIMITIVES_BLOCK_H
[ "anthony19114@gmail.com" ]
anthony19114@gmail.com
61c8e314a1cf9d70e70a1b46be5c4808a1c5f633
19ee8a8f3ca7c378ee3b463721f494b23991cce7
/1_spring/code.cpp
9eeebe4f2a1d593f2605bbf4aa83b2e3ea944f4a
[]
no_license
sahsinevgen/MIPT_algorithms
1fb2694f161ff6da2f349e426cdbea363bf755d4
642db51d15f4a7479925c776af6705ddedb1b066
refs/heads/master
2023-02-02T10:16:35.477866
2020-12-20T18:13:12
2020-12-20T18:13:12
320,849,527
0
0
null
null
null
null
UTF-8
C++
false
false
702
cpp
#include <list> #include <vector> #include <iostream> using namespace std; int last_digit(list<int> array, int Mod = 10) { if (array.size() == 0) return 1; vector<int> anss; int x = array.front(); int x_ = x; while (true) { x_ = (x * x_) % Mod; anss.push_back(x_); if (x == x_) break; } array.pop_front(); return (anss[last_digit(array, anss.size())] + 1) % Mod; // Write your code here } int main() { while(true) { int n; cin >> n; list<int> ar; for (int i = 0; i < n; i++) { int a; cin >> a; ar.push_back(a); } cout << last_digit(ar) << endl; } }
[ "sasha@darkmastersin.net" ]
sasha@darkmastersin.net
f01765970cd0b13a8a88bafbd4ba60d039e33a89
44d4d6c1049685d2ce103edd72e5885f79ea6988
/练习2/7.cpp
b9cd97c407785405083f04c0d007ece4de676c5f
[]
no_license
ClaraShar/LANQIAO
f269e33570ac7fd60c090158533079eece972281
2b09d9ed8058a07eda360ce2bbe4ce6342faef82
refs/heads/master
2020-04-08T17:59:41.696027
2019-02-26T11:20:25
2019-02-26T11:20:25
159,307,832
0
0
null
null
null
null
UTF-8
C++
false
false
717
cpp
#include <iostream> #include <string> #include <map> #include <queue> using namespace std; map<string,queue<string>> m; map<string,int> death; void DFS(string s) { while(!m[s].empty()) { string name=m[s].front(); if(death[name]!=1) cout<<name<<endl; DFS(name); m[s].pop(); } } int main() { int n; string king,tag,father,son,dead; cin>>n; cin>>king; death[king]=1; for(int i=0;i<n;++i) { cin>>tag; if(tag=="birth") { cin>>father>>son; m[father].push(son); } else if(tag=="death") { cin>>dead; death[dead]=1; } } DFS(king); cin>>n; return 0; } /* https://blog.csdn.net/July_xunle/article/details/79822510 */
[ "179800587@qq.com" ]
179800587@qq.com
9a18b4bf77a8c0140e5095ea4ce872e8c9ae1b72
64b487be42dbc38f1915fca72e338f158506598b
/hw10/cleaner.cpp
4447eaac7454f08063f340800bcf849fdf7b6cd7
[]
no_license
DLobosky/CS53-Intro-to-Programming-C-Plus-Plus
250ad090178587e0a906feb7d66d2d39162e6fad
08b8a3b28e958ea10b5e95df417ded2187005af7
refs/heads/master
2021-01-10T18:44:02.222047
2016-12-01T21:40:20
2016-12-01T21:40:20
75,326,900
0
0
null
null
null
null
UTF-8
C++
false
false
4,848
cpp
//Programmers: Jason Beard, Dalton Lobosky, Carl Garrett Herrmann //Date: 05/07/2013 //File: cleaner.cpp //Class: CS 53 //Purpose: class definition for cleaner object. #include "cleaner.h" #include "house.h" #include <cstdlib> #include <ctime> cleaner::cleaner(string obj_name, int x_coor, int y_coor) { name = obj_name; location.x = x_coor; location.y = y_coor; stress = 0; alive = true; aneurism = false; } void cleaner::calc_stress(house house1, const bool alive[]) { int trash_n = 0; int people_n = 0; int h_size = 0; char floor_space; h_size = house1.getSize(); for(int x = 0; x < h_size; x++) { for(int y = 0; y < h_size; y++) { floor_space = house1.getFloorSpace(x,y); switch (floor_space) { case 'H': case 'B': case 'L': case 'm': people_n++; break; case 't': trash_n++; break; } } } if (alive[0]==false) { people_n--; } if (alive[1]==false) { people_n--; } if (alive[2]==false) { people_n--; } if (alive[3]==false) { people_n--; } stress = (int)((trash_n * 100.0)/(h_size * h_size)) + (2 * people_n); if(stress >= 100) { aneurism = true; stress = 100; cout<<"STRESS TOO HEIGH!!!!!!!!!!!!!!!!" <<endl; } return; } string cleaner::getName() { return name; } void cleaner::setLocation(const int x, const int y) { location.x = x; location.y = y; } ostream& operator << (ostream& os, const cleaner cl) { os<< cl.name.c_str() << " is at (" << cl.location.x << "," << cl.location.y << "), and has a stress level of " << cl.stress << " out of 100." <<endl; return os; } int cleaner::getStress() { return stress; } bool cleaner::getAlive() { return alive; } void cleaner::step(house & h1) { int way; bool can = false; char item; trash mytrash; do { way = rand() % 4; switch (way) { case 0: item = h1.getFloorSpace(location.x, location.y - 1); break; case 1: item = h1.getFloorSpace(location.x, location.y + 1); break; case 2: item = h1.getFloorSpace(location.x - 1, location.y); break; case 3: item = h1.getFloorSpace(location.x + 1, location.y); break; default: item = '\0'; } switch (item) { case 'C': dyson.empty(); can = false; break; case 't': dyson.vac(mytrash); h1.trash_dec(); can = true; break; case 'b': can = false; break; case 'W': can = true; alive = false; cout<<"FELL OUT WINDOW!!!!!!!!!!!" <<endl; break; case 'H': can = false; break; case 'B': can = false; break; case 'L': can = false; break; case 'm': can = false; break; case '\0': can = true; break; } }while(can == false); if(can == true) { switch (way) { case 0: h1.setFloorSpace(location.x, location.y, '\0'); location.y --; h1.setFloorSpace(location.x, location.y, 'M'); break; case 1: h1.setFloorSpace(location.x, location.y, '\0'); location.y ++; h1.setFloorSpace(location.x, location.y, 'M'); break; case 2: h1.setFloorSpace(location.x, location.y, '\0'); location.x --; h1.setFloorSpace(location.x, location.y, 'M'); break; case 3: h1.setFloorSpace(location.x, location.y, '\0'); location.x ++; h1.setFloorSpace(location.x, location.y, 'M'); break; } } if(stress >= 100 || dyson.isExploded() || dyson.isSparky()) { alive = false; } return; }
[ "d.lobosky@gmail.com" ]
d.lobosky@gmail.com
ddb9478162a6a635c9663b7f6204670a2b578aa7
8489aae0a1b1f546a14c1719717c5184feb8e36c
/MotorbikeArduino/ino/Gps_TinyGps.ino
f88e5afb3947329892e495b2b8ab0a77c66cfc1a
[]
no_license
lentzlive/MotorbikeArduino
16df093b368fd4114d15b52e8396bcc830d5e085
425a9e3ba88b70edabfeb00b38cc9124289e9f93
refs/heads/master
2021-01-17T17:59:53.052448
2016-07-30T11:14:33
2016-07-30T11:14:33
61,470,971
9
0
null
null
null
null
UTF-8
C++
false
false
4,581
ino
#include <TinyGPS++.h> #include <SoftwareSerial.h> #include <Wire.h> #include <ADXL345.h> const float alpha = 0.5; double fXg = 0; double fYg = 0; double fZg = 0; double refXg = 0; double refYg = 0; double refZg = 0; int i = 0; ADXL345 acc; /* This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object. It requires the use of SoftwareSerial, and assumes that you have a 4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx). */ static const int RXPin = 12, TXPin = 13; static const int GPSBaud = 9600; // The TinyGPS++ object TinyGPSPlus gps; SoftwareSerial BTSerial(10, 11); // RX | TX // The serial connection to the GPS device SoftwareSerial ss(RXPin, TXPin); void setup() { pinMode(9, OUTPUT); // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode digitalWrite(9, HIGH); Serial.begin(9600); //Serial.println("Enter AT commands:"); BTSerial.begin(9600); // HC-05 default speed in AT command more Serial.println("Setup End"); delay(500); // Serial.begin(115200); ss.begin(GPSBaud); Serial.println(F("DeviceExample.ino")); Serial.println(F("A simple demonstration of TinyGPS++ with an attached GPS module")); Serial.print(F("Testing TinyGPS++ library v. ")); Serial.println(TinyGPSPlus::libraryVersion()); Serial.println(F("by Mikal Hart")); Serial.println(); acc.begin(); } void loop() { // This sketch displays information every time a new sentence is correctly encoded. while (ss.available() > 0) { if (gps.encode(ss.read())) { displayInfo(); } /* else { String strMessage = "STOP|0|N|0|E|0|0|0|0|0|0|0|"; Serial.println(strMessage); // Message // BTSerial.print(strMessage); delay(1000); }*/ } if (millis() > 5000 && gps.charsProcessed() < 10) { Serial.println(F("No GPS detected: check wiring.")); while (true); } } void displayInfo() { /* ARRAY DEFINITION: 0 - START 1 - Latitude 2 - N (Nord) 3 - Longitude 4 - E (East) 5 - month 6 - day 7 - year 8 - speed (Km/h) 9 - altitude (m) 10 - satellites (number of satellites) 11 - hdop (number of satellites in use) 12 - roll 13 - pitch */ String strMessage = ""; // Serial.print(F("Location: ")); if (gps.location.isValid()) { strMessage = "START|"; // Serial.print(gps.location.lat(), 6); // Serial.print(F(",")); // Serial.print(gps.location.lng(), 6); strMessage += gps.location.lat(), 6; strMessage += "|N|"; strMessage += gps.location.lng(), 6; strMessage += "|E|"; } else { // Serial.print(F("INVALID")); strMessage = "START|"; strMessage += "INVALID"; strMessage += "|N|"; strMessage += "INVALID"; strMessage += "|E|"; } // Serial.print(F(" Date/Time: ")); if (gps.date.isValid()) { // Serial.print(gps.date.month()); // Serial.print(F("/")); // Serial.print(gps.date.day()); // Serial.print(F("/")); // Serial.print(gps.date.year()); strMessage += gps.date.month(); strMessage += "|"; strMessage += gps.date.day(); strMessage += "|"; strMessage += gps.date.year(); strMessage += "|"; } else { // Serial.print(F("INVALID")); strMessage += "INVALID"; strMessage += "|"; strMessage += "INVALID"; strMessage += "|"; strMessage += "INVALID"; strMessage += "|"; } strMessage += gps.speed.kmph(); strMessage += "|"; strMessage += gps.altitude.meters(); strMessage += "|"; // Serial.println(gps.satellites.value()); // Number of satellites in use (u32) strMessage += gps.satellites.value(); strMessage += "|"; // Serial.println(gps.hdop.value()); // Number of satellites in use (u32) strMessage += gps.hdop.value(); strMessage += "|"; double pitch, roll, Xg, Yg, Zg; acc.read(&Xg, &Yg, &Zg); // Calibrazione if (i == 0) { refXg = Xg; refYg = Yg; refZg = Zg; i = 1; } Xg = Xg - refXg; Yg = Yg - refYg; Zg = Zg - refZg + 1; fXg = Xg * alpha + (fXg * (1.0 - alpha)); fYg = Yg * alpha + (fYg * (1.0 - alpha)); fZg = Zg * alpha + (fZg * (1.0 - alpha)); // Roll & Pitch Equations roll = (atan2(-fYg, fZg) * 180.0) / M_PI; pitch = (atan2(fXg, sqrt(fYg * fYg + fZg * fZg)) * 180.0) / M_PI; strMessage += roll; strMessage += "|"; strMessage += pitch; strMessage += "|"; Serial.println(strMessage); // Message // BTSerial.print(strMessage); // Serial.println(); delay(400); }
[ "Davide@DAVIDE-PC" ]
Davide@DAVIDE-PC
ee409057a329511267903b5149eabec557ecc878
1cb28e7f237ff6ca9c3ce7e4cc530185aa98e3de
/DepthSkin.cpp
57ab1707afb179d3cbb44151601d0c2d44b16295
[]
no_license
jonathanvdc/computer-graphics
1aa40c7b90ff7dbe5aa2185953eb67f28daa189c
62b9f518026b4e75b7fcaac6f7048617369c816f
refs/heads/master
2021-05-06T04:22:43.616582
2017-12-21T10:37:27
2017-12-21T10:37:27
114,994,232
0
0
null
null
null
null
UTF-8
C++
false
false
424
cpp
#include "DepthSkin.h" #include <memory> #include "DepthSkinBase.h" #include "ITexture.h" #include "ProjectedPolygonTexture.h" using namespace Engine; DepthSkin::DepthSkin() { } /// \brief Creates a texture based on the given projected polygon /// depth texture. std::shared_ptr<ITexture> DepthSkin::CreateTexture(std::shared_ptr<ProjectedPolygonTexture> DepthTexture) const { return DepthTexture; }
[ "jonathan.vdc@outlook.com" ]
jonathan.vdc@outlook.com
79b2d2c02cd6a5478a788d4fe91af92f95b51698
f0da2d7171782433b308348d62a0ce510aa87a66
/main.cpp
2b6da7dc8fc825f2393b74f27c4754e6daddef89
[]
no_license
AhsanSN/Paint-Graphic-Editor
4f4aa4375659ddd8ec42a4a80fe2b1f6e1f29d0e
19cc8af22e001b422a343e465ace3a8ee130b33b
refs/heads/master
2020-03-07T18:55:34.637027
2019-06-25T08:43:19
2019-06-25T08:43:19
127,656,813
1
0
null
null
null
null
UTF-8
C++
false
false
32,896
cpp
#include <SDL.h> #include <stdio.h> #include <string> #include <windows.h> #include <time.h> #include <cstdlib> #include <unistd.h> #include <cmath> #include <iostream> #include"Rect.h" #include"Line.h" #include"Stack.h" #include"Stack_redo.h" #define fps 60 /* Important notes: - the whole main program (main.cpp)is divided into three parts. these three parts are 90% same,except the shape that they are creating. - a linked list is used to store shapes - a linked list (stack_redo) is used to store the redo and the undo elements - you may find me adding and subtracting some constants to variables, such as length of stack. this is to adjust so that the program can run properly */ //Screen dimension constants const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; //Key press surfaces constants enum KeyPressSurfaces { KEY_PRESS_SURFACE_DEFAULT, KEY_PRESS_SURFACE_UP, KEY_PRESS_SURFACE_DOWN, KEY_PRESS_SURFACE_LEFT, KEY_PRESS_SURFACE_RIGHT, KEY_PRESS_SURFACE_TOTAL }; // bool init(); bool loadMedia(); void close(); void redoArrayFunction(); SDL_Window* gWindow = NULL; SDL_Renderer* gRenderer = NULL; bool init() //same code as given { bool success = true; if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Set texture filtering to linear if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "0" ) ) { printf( "Warning: Linear texture filtering not enabled!" ); } //Create window gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if( gWindow == NULL ) { printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Create renderer for window gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED ); if( gRenderer == NULL ) { printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Initialize renderer color SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); } } } return success; } bool loadMedia() //same code as given { bool success = true; return success; } void close() //same code as given //both stacks have been deallocated int he main function in the end { //Destroy window SDL_DestroyRenderer( gRenderer ); SDL_DestroyWindow( gWindow ); gWindow = NULL; gRenderer = NULL; //Quit SDL subsystems SDL_Quit(); } int main( int argc, char* args[] ) { Shapes* swapUpDown[100]; //used to store the shapes that are sent up and down srand (time(NULL)); Uint32 starting_tick; Stack stk; Stack_redo stkRedo; int shapesInStack=0; int redoArrayLength=0; int redoNumber=0; //Start linePermission SDL and create window if( !init() ) { printf( "Failed to initialize!\n" ); } else { if( !loadMedia() ) //Load media { printf( "Failed to load media!\n" ); } else { bool quit = false; //Main loop controller int swapIndex=0; // int swapInitialIndex=0; // position of last element in swapstack Shapes* swapIndexShape; SDL_Event e; //Event handler that takes care of all events bool mouseClicked = false; bool allowUp = false; SDL_Rect fillRect; bool rectanglePermission=false; //rectangle bool linePermission = false; //line bool swapPermission = true; bool pointPermission = false; //point //for coordinates int oldx ; int oldy ; int x, y ; int lineoldx, lineoldy; int linex, liney; //creating objects Shapes* rect = NULL; Line* line = NULL; Point* point = NULL; rectanglePermission = true; rect = new Rect(fillRect); line = new Line(); point = new Point(); point->giveCoods(0,0); //creates the first point stk.Push(point); stk.Show(gRenderer); shapesInStack++; while( !quit ) { while( SDL_PollEvent( &e ) != 0 ) { if( e.type == SDL_QUIT ) { quit = true; } else { SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); rectanglePermission = true; while(!quit) { starting_tick = SDL_GetTicks(); // used to decrease the frame rate to ensure smooth running of program //Handle events on queue while (rectanglePermission ==true) // loop for rectangle. same is done for line and point { starting_tick = SDL_GetTicks(); while( SDL_PollEvent( &e ) != 0 ) { //User requests quit if( e.type == SDL_QUIT ) { quit = true; rectanglePermission = false; } if( e.type == SDL_MOUSEMOTION || e.type == SDL_MOUSEBUTTONDOWN || e.type == SDL_MOUSEBUTTONUP ) { SDL_GetMouseState( &x, &y ); if(e.type == SDL_MOUSEMOTION) { if(mouseClicked == true) fillRect = { oldx, oldy, x - oldx, y - oldy }; rect->inFillrect(&fillRect); //send the coordinates } if(e.type == SDL_MOUSEBUTTONDOWN) { if (e.button.button == SDL_BUTTON_LEFT) { if(mouseClicked == false) { mouseClicked = true; oldx = x; oldy = y; } } } if(e.type == SDL_MOUSEBUTTONUP) { if (e.button.button == SDL_BUTTON_LEFT) //draws { rect = new Rect(fillRect); mouseClicked = false; stk.Push(rect); shapesInStack++; SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); stk.Show(gRenderer); //draws all the shapes } if (e.button.button == SDL_BUTTON_RIGHT) //undo { if (shapesInStack > 1) { shapesInStack--; SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); stkRedo.Push_redo(stk.Pop()); redoArrayLength ++; SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); stk.Show(gRenderer); } } if (e.button.button == SDL_BUTTON_MIDDLE) //redo { if (redoNumber-1 <= redoArrayLength+1) { (stkRedo.Pop_redo())->draw(gRenderer); redoNumber = redoNumber+1; redoArrayLength = redoArrayLength -1; } } } } } SDL_RenderPresent( gRenderer ); switch( e.key.keysym.sym ) // get the keyboard inputs { case SDLK_p: { rectanglePermission = false; pointPermission = true; break; } case SDLK_l: { rectanglePermission = false; linePermission = true; break; } case SDLK_DOWN: { if (e.type == SDL_KEYUP) { allowUp = true; swapPermission = true; } if (e.type == SDL_KEYDOWN) { if (swapPermission ==true) { if (swapIndex==0) { swapInitialIndex=stk.length()-1; } if ((stk.length())-2>swapIndex) { stk.swap(swapInitialIndex-1,swapInitialIndex); swapIndex++; swapInitialIndex--; } SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); stk.Show(gRenderer); swapPermission = false; break; } } } case SDLK_UP: { if (allowUp == true) { if (e.type == SDL_KEYUP) { swapPermission = true; } if (e.type == SDL_KEYDOWN) { if (swapPermission ==true) { if (swapIndex==0) { swapInitialIndex=stk.length()-1; } if ((stk.length()-1)>swapIndex) { stk.swap(swapInitialIndex+1,swapInitialIndex); swapIndex--; swapInitialIndex++; } SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); stk.Show(gRenderer); swapPermission = false; break; } } } } } if((500/fps)> SDL_GetTicks() - starting_tick) //decreasing frame rate { SDL_Delay(500/fps - (SDL_GetTicks() - starting_tick )); } } while (linePermission ==true) { starting_tick = SDL_GetTicks(); while( SDL_PollEvent( &e ) != 0 ) { //User requests quit if( e.type == SDL_QUIT ) { quit = true; linePermission = false; } if( e.type == SDL_MOUSEMOTION || e.type == SDL_MOUSEBUTTONDOWN || e.type == SDL_MOUSEBUTTONUP ) { SDL_GetMouseState( &linex, &liney ); if(e.type == SDL_MOUSEMOTION) { swapPermission = true; if(mouseClicked == true) line->giveCoordinates2(linex, liney); } if(e.type == SDL_MOUSEBUTTONDOWN) { if (e.button.button == SDL_BUTTON_LEFT) { if(mouseClicked == false) { mouseClicked = true; lineoldx = linex; lineoldy = liney; line->giveCoordinates1(lineoldx,lineoldy); } } } if(e.type == SDL_MOUSEBUTTONUP) { if (e.button.button == SDL_BUTTON_LEFT) { mouseClicked = false; line = new Line(); line->draw(gRenderer); stk.Push(line); shapesInStack++; stk.Show(gRenderer); } if (e.button.button == SDL_BUTTON_RIGHT) { if (shapesInStack > 1) { shapesInStack--; SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear(gRenderer ); stkRedo.Push_redo(stk.Pop()); redoArrayLength++; stk.Show(gRenderer); } } if (e.button.button == SDL_BUTTON_MIDDLE) { if (redoNumber-1 <= redoArrayLength+1) { (stkRedo.Pop_redo())->draw(gRenderer); redoNumber = redoNumber+1; redoArrayLength = redoArrayLength -1; } } } } } SDL_RenderPresent( gRenderer ); switch( e.key.keysym.sym ) { if (e.type == SDL_KEYDOWN) { case SDLK_p: linePermission = false; pointPermission = true; break; case SDLK_r: linePermission = false; rectanglePermission = true; break; case SDLK_DOWN: { if (e.type == SDL_KEYUP) { allowUp = true; swapPermission = true; } if (e.type == SDL_KEYDOWN) { if (swapPermission ==true) { if (swapIndex==0) { swapInitialIndex=stk.length()-1; } if ((stk.length())-2>swapIndex) { stk.swap(swapInitialIndex-1,swapInitialIndex); //stk.swap(stk.length()-1,stk.length()); swapIndex++; swapInitialIndex--; } SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); stk.Show(gRenderer); swapPermission = false; break; } } } case SDLK_UP: { if (allowUp == true) { if (e.type == SDL_KEYUP) { swapPermission = true; } if (e.type == SDL_KEYDOWN) { if (swapPermission ==true) { if (swapIndex==0) { swapInitialIndex=stk.length()-1; } if ((stk.length()-1)>swapIndex) { stk.swap(swapInitialIndex+1,swapInitialIndex); swapIndex--; swapInitialIndex++; } SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); stk.Show(gRenderer); swapPermission = false; break; } } } } } } SDL_RenderPresent( gRenderer ); //tempor if((500/fps)> SDL_GetTicks() - starting_tick) //decreasing frame rate { SDL_Delay(500/fps - (SDL_GetTicks() - starting_tick )); } } while (pointPermission ==true) { while( SDL_PollEvent( &e ) != 0 ) { //User requests quit if( e.type == SDL_QUIT ) { quit = true; pointPermission = false; } if( e.type == SDL_MOUSEMOTION || e.type == SDL_MOUSEBUTTONDOWN || e.type == SDL_MOUSEBUTTONUP ) { SDL_GetMouseState( &x, &y ); if(e.type == SDL_MOUSEBUTTONDOWN) { if (e.button.button == SDL_BUTTON_LEFT) { if(mouseClicked == false) { mouseClicked = true; oldx = x; oldy = y; } } } if(e.type == SDL_MOUSEBUTTONUP) { if (e.button.button == SDL_BUTTON_LEFT) { mouseClicked = false; point = new Point(); point->giveCoods(oldx,oldy); stk.Push(point); stk.Show(gRenderer); shapesInStack++; SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); point->draw(gRenderer); } if (e.button.button == SDL_BUTTON_RIGHT) { if (shapesInStack > 1) { shapesInStack--; SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); redoArrayLength++; stkRedo.Push_redo(stk.Pop()); stk.Show(gRenderer); } } if (e.button.button == SDL_BUTTON_MIDDLE) { if (redoNumber-1 <= redoArrayLength+1) { (stkRedo.Pop_redo())->draw(gRenderer); redoNumber = redoNumber+1; redoArrayLength = redoArrayLength -1; } } } } } SDL_RenderPresent( gRenderer ); switch( e.key.keysym.sym ) { if (e.type == SDL_KEYDOWN) { case SDLK_l: pointPermission = false; linePermission = true; break; case SDLK_r: pointPermission = false; rectanglePermission = true; break; case SDLK_DOWN: { if (e.type == SDL_KEYUP) { allowUp = true; swapPermission = true; } if (e.type == SDL_KEYDOWN) { if (swapPermission ==true) { if (swapIndex==0) { swapInitialIndex=stk.length()-1; } if ((stk.length())-2>swapIndex) { stk.swap(swapInitialIndex-1,swapInitialIndex); swapIndex++; swapInitialIndex--; } SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); stk.Show(gRenderer); swapPermission = false; break; } } } case SDLK_UP: { if (allowUp == true) { if (e.type == SDL_KEYUP) { swapPermission = true; } if (e.type == SDL_KEYDOWN) { if (swapPermission ==true) { if (swapIndex==0) { swapInitialIndex=stk.length()-1; } if ((stk.length()-1)>swapIndex) { stk.swap(swapInitialIndex+1,swapInitialIndex); swapIndex--; swapInitialIndex++; } SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); stk.Show(gRenderer); swapPermission = false; break; } } } } } } if((500/fps)> SDL_GetTicks() - starting_tick) //decreasing frame rate { SDL_Delay(500/fps - (SDL_GetTicks() - starting_tick )); } } if((500/fps)> SDL_GetTicks() - starting_tick) //decreasing frame rate { SDL_Delay(500/fps - (SDL_GetTicks() - starting_tick )); } } } } } } } stk.clearAll(); stk.~Stack(); //destructor /deallocates stack stkRedo.~Stack_redo();//destructor /deallocates stack close(); return 0; }
[ "sa02908@st.habib.edu.pk" ]
sa02908@st.habib.edu.pk
3f9aebca05ac0ed9fe43f7226283f7d254cab2e6
1e9c38783db1e2b7e9d96cccec3e38d0dff497ad
/IronManRing/IronManRing.ino
251e3cd6275d27c11311bde7cf0eb9a2e0495636
[ "MIT" ]
permissive
simonemarra/IronManRing_Arduino
6f6293a7b268ecf3900c8d4e2c1d30227af3df61
3126aca2e80d3511edd583bfeff3b861cd9f59a4
refs/heads/master
2020-12-30T08:38:11.594374
2020-02-07T13:51:54
2020-02-07T13:51:54
238,933,008
0
0
null
null
null
null
UTF-8
C++
false
false
1,950
ino
#include <Adafruit_NeoPixel.h> #define RING_PIN 2//6 // How many NeoPixels are attached to the Arduino? #define LED_COUNT 36//16//60 Adafruit_NeoPixel strip(LED_COUNT, RING_PIN, NEO_GRB + NEO_KHZ800); // Argument 1 = Number of pixels in NeoPixel strip // Argument 2 = Arduino pin number (most are valid) // Argument 3 = Pixel type flags, add together as needed: // NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs) // NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers) // NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products) // NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2) // NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products) int16_t blueVal = 0; #define BLUE_MIN 105 #define RED_MIN 15 #define GREEN_MIN 15 #define BRIGHTNESS_DEFAULT 125//50 void setup() { strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED) strip.show(); // Turn OFF all pixels ASAP strip.setBrightness(BRIGHTNESS_DEFAULT); // Set BRIGHTNESS to about 1/5 (max = 255) /* for(int b = 0; b < 10; b++) { colorWipe(strip.Color(RED_MIN, GREEN_MIN, 255), 5); // Blue colorWipe(strip.Color(RED_MIN, GREEN_MIN, BLUE_MIN), 5); // Blue } */ } void loop() { // put your main code here, to run repeatedly: for(blueVal = BLUE_MIN; blueVal <= 255; blueVal+=10) { colorWipe(strip.Color(RED_MIN, GREEN_MIN, (uint8_t)blueVal),0); } for(blueVal = 255; blueVal >= BLUE_MIN; blueVal-=10) { colorWipe(strip.Color(RED_MIN, GREEN_MIN, (uint8_t)blueVal),0); } } void colorWipe(uint32_t color, int wait) { for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip... strip.setPixelColor(i, color); // Set pixel's color (in RAM) strip.show(); // Update strip to match delay(wait); // Pause for a moment } }
[ "simone.marra.electronics@gmail.com" ]
simone.marra.electronics@gmail.com
97bbaa709661277e41808d4f9db04febbd1d6dd8
33ac633b566c21f00a6073fba2f896020cd7f62c
/WA/BackStageMgrDef.h
d801e44e97dc856954dcc2f04ca0f90182a8e259
[]
no_license
orichisonic/GMServer_20091221
ef4d454d4b78d01b49b8752eed2170c3419af22a
19847f86a45a2706ddf645a2ca9e98f80affb198
refs/heads/master
2020-03-13T04:33:08.253747
2018-04-25T07:29:55
2018-04-25T07:29:55
130,965,261
0
0
null
null
null
null
GB18030
C++
false
false
440
h
#pragma once // // 服务器后台管理相关定义 // #pragma pack(push, 1) namespace BACKSTAGEMGR { const int MSG_BASE_BSTRS = 25000; const int MSG_BASE_RSTBS = 26000; const int MAX_ID_LENGTH = 20; const int MAX_PASSWORD_LENGTH = 21; const int MAX_CHARACTER_NAME_LENGTH = 13; struct TCP_MSG_BASE { unsigned short header; TCP_MSG_BASE(unsigned short id) :header(id) { } }; }; // #pragma pack(pop)
[ "wanglin36@CENTALINE.COM.CN" ]
wanglin36@CENTALINE.COM.CN
e89f0a7dfc8e1af5d2fa8190e5fb6ebe755c5b4d
6b6e7606ea14bd3ee22f5fbfab90bf86220d36a2
/appseed/axis/axis/node/_node.cpp
ee4ee3198a47cf1675634a815e7d0eb8ba0123e9
[]
no_license
mediabuff/app
b51e1d21e8b244af09e3d3f78ab38d8e80cd4bba
12f8aeacce1b2649977d4c7ce61a4415c636fa6c
refs/heads/master
2021-08-06T15:57:12.573775
2017-11-06T12:24:35
2017-11-06T12:24:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
151
cpp
#include "framework.h" #ifdef ANDROID #include "android/_node_android.cpp" #elif defined(WINDOWSEX) #include "windows/_windows_node.cpp" #endif
[ "camilo@ca2.email" ]
camilo@ca2.email
cae5a64397dc6248eeaac0a059c6f49981f372bc
f0a2b390fac20afa243e46a9f73d4e754ae713fa
/msquare/msquare.cpp
226ab3aac19152289ae6a0a4f6e6d43235fd2f38
[]
no_license
OneStig/usaco
647b0df1830563a0d4df46f57a27b135acb1eb54
bbbeedc5836a15cd3239ab47091baa58cae236b4
refs/heads/master
2023-07-13T06:15:35.660474
2021-08-26T04:17:37
2021-08-26T04:17:37
256,059,713
3
2
null
null
null
null
UTF-8
C++
false
false
1,943
cpp
/* ID: stevenh6 TASK: msquare LANG: C++ */ #include <fstream> #include <string> #include <map> #include <vector> #include <algorithm> #include <queue> #include <set> using namespace std; ofstream fout("msquare.out"); ifstream fin("msquare.in"); struct Magic { string tran, str; int sh; Magic(string tr, string st, int s) { tran = tr; str = st; sh = s; } }; string full = ""; set<string> all; queue<Magic> Q; const string tot = "12345678"; Magic search() { if (full == tot) { return Magic("", "", 0); } Q.push(Magic("12345678", "", 0)); all.insert("12345678"); while (true) { if (Q.empty()) { break; } Magic cur = Q.front(); string A(cur.tran.rbegin(), cur.tran.rend()); string B(cur.tran[3] + cur.tran.substr(0, 3) + cur.tran.substr(5) + cur.tran[4]); string C = cur.tran; Q.pop(); if (A == full) { return Magic(A, cur.str + "A", cur.sh + 1); } if (!all.count(A)) { all.insert(A); Q.push(Magic(A, cur.str + "A", cur.sh + 1)); } if (B == full) { return Magic(B, cur.str + "B", cur.sh + 1); } if (!all.count(B)) { all.insert(B); Q.push(Magic(B, cur.str + "B", cur.sh + 1)); } swap(C[1], C[2]); swap(C[1], C[5]); swap(C[1], C[6]); if (C == full) { return Magic(C, cur.str + "C", cur.sh + 1); } if (!all.count(C)) { all.insert(C); Q.push(Magic(C, cur.str + "C", cur.sh + 1)); } } } int main() { for (int i = 0; i < 8; i++) { char in; fin >> in; full += in; } Magic n = search(); fout << n.sh << endl << n.str << endl; }
[ "therealonestig@gmail.com" ]
therealonestig@gmail.com
63561ba48482888dad5f075b063409f52bd3e352
9030ce2789a58888904d0c50c21591632eddffd7
/SDK/ARKSurvivalEvolved_HoverSkiffHudWidget_functions.cpp
1686a36aebcd541322c02cd534f34e0f2ec0d879
[ "MIT" ]
permissive
2bite/ARK-SDK
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
refs/heads/master
2022-09-19T06:28:20.076298
2022-09-03T17:21:00
2022-09-03T17:21:00
232,411,353
14
5
null
null
null
null
UTF-8
C++
false
false
28,114
cpp
// ARKSurvivalEvolved (332.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_HoverSkiffHudWidget_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_RepairPanel_BrushColor_1 // () // Parameters: // struct FLinearColor ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FLinearColor UHoverSkiffHudWidget_C::Get_RepairPanel_BrushColor_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_RepairPanel_BrushColor_1"); UHoverSkiffHudWidget_C_Get_RepairPanel_BrushColor_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_SkiffModeSubStatusTextBlock_Text_1 // (Exec, Native, Event, NetResponse, Static, NetMulticast, Private, NetServer, HasOutParms, NetClient, BlueprintEvent) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UHoverSkiffHudWidget_C::STATIC_Get_SkiffModeSubStatusTextBlock_Text_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_SkiffModeSubStatusTextBlock_Text_1"); UHoverSkiffHudWidget_C_Get_SkiffModeSubStatusTextBlock_Text_1_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_RepairLabelTextBlock_Text_1 // (NetRequest, Exec, Native, Private, NetServer, HasOutParms, NetClient, BlueprintEvent) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UHoverSkiffHudWidget_C::Get_RepairLabelTextBlock_Text_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_RepairLabelTextBlock_Text_1"); UHoverSkiffHudWidget_C_Get_RepairLabelTextBlock_Text_1_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.WidgetBoolToVisibilty // () // Parameters: // class UObject* TargetWidget (Parm, ZeroConstructor, IsPlainOldData) // bool IsVisible (Parm, ZeroConstructor, IsPlainOldData) // bool UseHiddenInsteadOfCollapsed (Parm, ZeroConstructor, IsPlainOldData) void UHoverSkiffHudWidget_C::WidgetBoolToVisibilty(class UObject* TargetWidget, bool IsVisible, bool UseHiddenInsteadOfCollapsed) { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.WidgetBoolToVisibilty"); UHoverSkiffHudWidget_C_WidgetBoolToVisibilty_Params params; params.TargetWidget = TargetWidget; params.IsVisible = IsVisible; params.UseHiddenInsteadOfCollapsed = UseHiddenInsteadOfCollapsed; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.UpdateRepairProgressBarsPercentAndForegroundColor // (NetRequest, Native, Event, NetResponse, MulticastDelegate, Public, Protected, HasOutParms, NetClient, BlueprintEvent) void UHoverSkiffHudWidget_C::UpdateRepairProgressBarsPercentAndForegroundColor() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.UpdateRepairProgressBarsPercentAndForegroundColor"); UHoverSkiffHudWidget_C_UpdateRepairProgressBarsPercentAndForegroundColor_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.UpdateRepairPanelVisibility // () void UHoverSkiffHudWidget_C::UpdateRepairPanelVisibility() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.UpdateRepairPanelVisibility"); UHoverSkiffHudWidget_C_UpdateRepairPanelVisibility_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.UpdateAllFuelGaugesPanelVisibility // () void UHoverSkiffHudWidget_C::UpdateAllFuelGaugesPanelVisibility() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.UpdateAllFuelGaugesPanelVisibility"); UHoverSkiffHudWidget_C_UpdateAllFuelGaugesPanelVisibility_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_AltFuelLabelTextBlock_Text_1 // (Net, NetReliable, Native, Event, Private, NetServer, HasOutParms, NetClient, BlueprintEvent) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UHoverSkiffHudWidget_C::Get_AltFuelLabelTextBlock_Text_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_AltFuelLabelTextBlock_Text_1"); UHoverSkiffHudWidget_C_Get_AltFuelLabelTextBlock_Text_1_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Update Status Visibilities // () void UHoverSkiffHudWidget_C::Update_Status_Visibilities() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Update Status Visibilities"); UHoverSkiffHudWidget_C_Update_Status_Visibilities_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.UpdateNeedleRotation // () void UHoverSkiffHudWidget_C::UpdateNeedleRotation() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.UpdateNeedleRotation"); UHoverSkiffHudWidget_C_UpdateNeedleRotation_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Update Tractor Beam Crosshair Visuals // (NetRequest, NetResponse, Static, MulticastDelegate, Public, Protected, HasOutParms, NetClient, BlueprintEvent) void UHoverSkiffHudWidget_C::STATIC_Update_Tractor_Beam_Crosshair_Visuals() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Update Tractor Beam Crosshair Visuals"); UHoverSkiffHudWidget_C_Update_Tractor_Beam_Crosshair_Visuals_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_FuelUsageNeedleImage_ColorAndOpacity_1 // () // Parameters: // struct FLinearColor ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FLinearColor UHoverSkiffHudWidget_C::Get_FuelUsageNeedleImage_ColorAndOpacity_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_FuelUsageNeedleImage_ColorAndOpacity_1"); UHoverSkiffHudWidget_C_Get_FuelUsageNeedleImage_ColorAndOpacity_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_FuelReserveNeedleImage_ColorAndOpacity_1 // () // Parameters: // struct FLinearColor ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FLinearColor UHoverSkiffHudWidget_C::Get_FuelReserveNeedleImage_ColorAndOpacity_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_FuelReserveNeedleImage_ColorAndOpacity_1"); UHoverSkiffHudWidget_C_Get_FuelReserveNeedleImage_ColorAndOpacity_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_FuelTankNeedleImage_ColorAndOpacity_1 // () // Parameters: // struct FLinearColor ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FLinearColor UHoverSkiffHudWidget_C::Get_FuelTankNeedleImage_ColorAndOpacity_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_FuelTankNeedleImage_ColorAndOpacity_1"); UHoverSkiffHudWidget_C_Get_FuelTankNeedleImage_ColorAndOpacity_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_FuelTankGaugeImage_ColorAndOpacity_1 // () // Parameters: // struct FLinearColor ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FLinearColor UHoverSkiffHudWidget_C::Get_FuelTankGaugeImage_ColorAndOpacity_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_FuelTankGaugeImage_ColorAndOpacity_1"); UHoverSkiffHudWidget_C_Get_FuelTankGaugeImage_ColorAndOpacity_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_FuelReserveGaugeImage_ColorAndOpacity_1 // () // Parameters: // struct FLinearColor ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FLinearColor UHoverSkiffHudWidget_C::Get_FuelReserveGaugeImage_ColorAndOpacity_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_FuelReserveGaugeImage_ColorAndOpacity_1"); UHoverSkiffHudWidget_C_Get_FuelReserveGaugeImage_ColorAndOpacity_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.IsExtendedInfoKeyPressed // () // Parameters: // bool bShowExtendedInfoKey (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UHoverSkiffHudWidget_C::IsExtendedInfoKeyPressed(bool* bShowExtendedInfoKey) { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.IsExtendedInfoKeyPressed"); UHoverSkiffHudWidget_C_IsExtendedInfoKeyPressed_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (bShowExtendedInfoKey != nullptr) *bShowExtendedInfoKey = params.bShowExtendedInfoKey; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_FuelUsageGaugeImage_ColorAndOpacity_1 // () // Parameters: // struct FLinearColor ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FLinearColor UHoverSkiffHudWidget_C::Get_FuelUsageGaugeImage_ColorAndOpacity_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_FuelUsageGaugeImage_ColorAndOpacity_1"); UHoverSkiffHudWidget_C_Get_FuelUsageGaugeImage_ColorAndOpacity_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.DimGaugesAndNeedlesOnBool // () // Parameters: // bool Bool (Parm, ZeroConstructor, IsPlainOldData) void UHoverSkiffHudWidget_C::DimGaugesAndNeedlesOnBool(bool Bool) { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.DimGaugesAndNeedlesOnBool"); UHoverSkiffHudWidget_C_DimGaugesAndNeedlesOnBool_Params params; params.Bool = Bool; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.OnShowExtendedInfoKeyPressed // () void UHoverSkiffHudWidget_C::OnShowExtendedInfoKeyPressed() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.OnShowExtendedInfoKeyPressed"); UHoverSkiffHudWidget_C_OnShowExtendedInfoKeyPressed_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_RepairValueTextBlock_Text_1 // (NetRequest, Exec, Event, Static, Private, NetServer, HasOutParms, NetClient, BlueprintEvent) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UHoverSkiffHudWidget_C::STATIC_Get_RepairValueTextBlock_Text_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_RepairValueTextBlock_Text_1"); UHoverSkiffHudWidget_C_Get_RepairValueTextBlock_Text_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_AltFuelValueTextBlock_Text_1 // (Net, NetReliable, NetRequest, Exec, Native, Event, Static, Private, NetServer, HasOutParms, NetClient, BlueprintEvent) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UHoverSkiffHudWidget_C::STATIC_Get_AltFuelValueTextBlock_Text_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_AltFuelValueTextBlock_Text_1"); UHoverSkiffHudWidget_C_Get_AltFuelValueTextBlock_Text_1_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_AltFuelIcon_Brush_1 // (NetRequest, Exec, Native, NetResponse, NetMulticast, MulticastDelegate, Public, Protected, HasOutParms, NetClient, BlueprintEvent) // Parameters: // struct FSlateBrush ReturnValue (Parm, OutParm, ReturnParm) struct FSlateBrush UHoverSkiffHudWidget_C::Get_AltFuelIcon_Brush_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_AltFuelIcon_Brush_1"); UHoverSkiffHudWidget_C_Get_AltFuelIcon_Brush_1_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_SkiffModeValueTextBlock_Text_1 // (NetRequest, NetResponse, Static, Private, NetServer, HasOutParms, NetClient, BlueprintEvent) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UHoverSkiffHudWidget_C::STATIC_Get_SkiffModeValueTextBlock_Text_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_SkiffModeValueTextBlock_Text_1"); UHoverSkiffHudWidget_C_Get_SkiffModeValueTextBlock_Text_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_AltitudeValueTextBlock_Text_1 // (NetReliable, Event, NetResponse, Static, Private, NetServer, HasOutParms, NetClient, BlueprintEvent) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UHoverSkiffHudWidget_C::STATIC_Get_AltitudeValueTextBlock_Text_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_AltitudeValueTextBlock_Text_1"); UHoverSkiffHudWidget_C_Get_AltitudeValueTextBlock_Text_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_AltitudeLabelTextBlock_Text_1 // (Net, Exec, Native, Event, NetResponse, Static, Private, NetServer, HasOutParms, NetClient, BlueprintEvent) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UHoverSkiffHudWidget_C::STATIC_Get_AltitudeLabelTextBlock_Text_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_AltitudeLabelTextBlock_Text_1"); UHoverSkiffHudWidget_C_Get_AltitudeLabelTextBlock_Text_1_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get Debug Text 0 // (NetReliable, NetRequest, Exec, Native, Event, NetResponse, Static, Private, NetServer, HasOutParms, NetClient, BlueprintEvent) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UHoverSkiffHudWidget_C::STATIC_Get_Debug_Text_0() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get Debug Text 0"); UHoverSkiffHudWidget_C_Get_Debug_Text_0_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_FuelReserveTextBlock_Text_1 // (Net, NetReliable, NetMulticast, Private, NetServer, HasOutParms, NetClient, BlueprintEvent) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UHoverSkiffHudWidget_C::Get_FuelReserveTextBlock_Text_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_FuelReserveTextBlock_Text_1"); UHoverSkiffHudWidget_C_Get_FuelReserveTextBlock_Text_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Set Progress Bar Fill And Background Colors // (NetReliable, Exec, NetResponse, Static, NetMulticast, MulticastDelegate, Public, Protected, HasOutParms, NetClient, BlueprintEvent) // Parameters: // class UProgressBar* ProgressBar (Parm, ZeroConstructor, IsPlainOldData) // struct FLinearColor LinearColor (Parm, ZeroConstructor, IsPlainOldData) // struct FProgressBarStyle ProgressBarStyle (Parm, OutParm) void UHoverSkiffHudWidget_C::STATIC_Set_Progress_Bar_Fill_And_Background_Colors(class UProgressBar* ProgressBar, const struct FLinearColor& LinearColor, struct FProgressBarStyle* ProgressBarStyle) { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Set Progress Bar Fill And Background Colors"); UHoverSkiffHudWidget_C_Set_Progress_Bar_Fill_And_Background_Colors_Params params; params.ProgressBar = ProgressBar; params.LinearColor = LinearColor; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (ProgressBarStyle != nullptr) *ProgressBarStyle = params.ProgressBarStyle; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_CurrentElementValueTextBlock_Text_1 // (NetReliable, NetRequest, Exec, NetMulticast, Private, NetServer, HasOutParms, NetClient, BlueprintEvent) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UHoverSkiffHudWidget_C::Get_CurrentElementValueTextBlock_Text_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_CurrentElementValueTextBlock_Text_1"); UHoverSkiffHudWidget_C_Get_CurrentElementValueTextBlock_Text_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get Tractor Progress Bar Percent // () // Parameters: // float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) float UHoverSkiffHudWidget_C::Get_Tractor_Progress_Bar_Percent_() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get Tractor Progress Bar Percent "); UHoverSkiffHudWidget_C_Get_Tractor_Progress_Bar_Percent__Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_Crosshair_ColorAndOpacity_1 // () // Parameters: // struct FLinearColor ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FLinearColor UHoverSkiffHudWidget_C::Get_Crosshair_ColorAndOpacity_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_Crosshair_ColorAndOpacity_1"); UHoverSkiffHudWidget_C_Get_Crosshair_ColorAndOpacity_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_CameraLockIcon_ColorAndOpacity_1 // () // Parameters: // struct FLinearColor ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FLinearColor UHoverSkiffHudWidget_C::Get_CameraLockIcon_ColorAndOpacity_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_CameraLockIcon_ColorAndOpacity_1"); UHoverSkiffHudWidget_C_Get_CameraLockIcon_ColorAndOpacity_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_FuelConsumptionRateValueTextBlock_Text_1 // (Exec, Native, NetMulticast, Private, NetServer, HasOutParms, NetClient, BlueprintEvent) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UHoverSkiffHudWidget_C::Get_FuelConsumptionRateValueTextBlock_Text_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_FuelConsumptionRateValueTextBlock_Text_1"); UHoverSkiffHudWidget_C_Get_FuelConsumptionRateValueTextBlock_Text_1_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_ElementFuelValueTextBlock_Text_1 // (NetReliable, NetRequest, Native, Static, MulticastDelegate, Protected, NetServer, NetClient, BlueprintEvent) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UHoverSkiffHudWidget_C::STATIC_Get_ElementFuelValueTextBlock_Text_1() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Get_ElementFuelValueTextBlock_Text_1"); UHoverSkiffHudWidget_C_Get_ElementFuelValueTextBlock_Text_1_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.InitFromSkiff // () // Parameters: // class ATekHoverSkiff_Character_BP_C* FromSkiff (Parm, ZeroConstructor, IsPlainOldData) void UHoverSkiffHudWidget_C::InitFromSkiff(class ATekHoverSkiff_Character_BP_C* FromSkiff) { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.InitFromSkiff"); UHoverSkiffHudWidget_C_InitFromSkiff_Params params; params.FromSkiff = FromSkiff; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.StartClosingWidget // () // Parameters: // float NewLifeSpan (Parm, ZeroConstructor, IsPlainOldData) void UHoverSkiffHudWidget_C::StartClosingWidget(float NewLifeSpan) { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.StartClosingWidget"); UHoverSkiffHudWidget_C_StartClosingWidget_Params params; params.NewLifeSpan = NewLifeSpan; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.DestroySkiffHudWidget // () void UHoverSkiffHudWidget_C::DestroySkiffHudWidget() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.DestroySkiffHudWidget"); UHoverSkiffHudWidget_C_DestroySkiffHudWidget_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.ResetSkiffHudWidget // () void UHoverSkiffHudWidget_C::ResetSkiffHudWidget() { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.ResetSkiffHudWidget"); UHoverSkiffHudWidget_C_ResetSkiffHudWidget_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Tick // () // Parameters: // struct FGeometry* MyGeometry (Parm, IsPlainOldData) // float* InDeltaTime (Parm, ZeroConstructor, IsPlainOldData) void UHoverSkiffHudWidget_C::Tick(struct FGeometry* MyGeometry, float* InDeltaTime) { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.Tick"); UHoverSkiffHudWidget_C_Tick_Params params; params.MyGeometry = MyGeometry; params.InDeltaTime = InDeltaTime; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.ExecuteUbergraph_HoverSkiffHudWidget // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UHoverSkiffHudWidget_C::ExecuteUbergraph_HoverSkiffHudWidget(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function HoverSkiffHudWidget.HoverSkiffHudWidget_C.ExecuteUbergraph_HoverSkiffHudWidget"); UHoverSkiffHudWidget_C_ExecuteUbergraph_HoverSkiffHudWidget_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
7ecaf59537605026de714a5a1bb94bcc900272fa
a9e308c81c27a80c53c899ce806d6d7b4a9bbbf3
/engine/xray/editor/world/sources/particle_links_manager.h
ec147d0c01c54167c47f09f2a9dffd42f87f6b27
[]
no_license
NikitaNikson/xray-2_0
00d8e78112d7b3d5ec1cb790c90f614dc732f633
82b049d2d177aac15e1317cbe281e8c167b8f8d1
refs/heads/master
2023-06-25T16:51:26.243019
2020-09-29T15:49:23
2020-09-29T15:49:23
390,966,305
1
0
null
null
null
null
UTF-8
C++
false
false
1,639
h
//////////////////////////////////////////////////////////////////////////// // Created : 26.01.2010 // Author : // Copyright (C) GSC Game World - 2010 //////////////////////////////////////////////////////////////////////////// #ifndef PARTICLE_LINKS_MANAGER_H_INCLUDED #define PARTICLE_LINKS_MANAGER_H_INCLUDED using namespace System::Collections; namespace xray { namespace editor { ref class particle_links_manager : public xray::editor::controls::hypergraph::links_manager { typedef controls::hypergraph::node node; typedef controls::hypergraph::link link; typedef controls::hypergraph::connection_point connection_point; typedef Generic::List<link^> links; typedef Generic::List<node^> nodes; private: links^ m_links; controls::hypergraph::hypergraph_control^ m_hypergraph; public: particle_links_manager (controls::hypergraph::hypergraph_control^ h); virtual void on_node_added (node^ node); virtual void on_node_removed (node^ node); virtual void on_node_destroyed (node^ node); virtual void create_link (controls::hypergraph::connection_point^ pt_src, controls::hypergraph::connection_point^ pt_dst); void create_link (node^ src_node, node^ dst_node); virtual void destroy_link (controls::hypergraph::link^ link); void destroy_link (node^ src_node, node^ dst_node); virtual links^ visible_links (); virtual void clear (); }; // ref class particle_links_manager } // namespace editor } // namespace xray #endif //PARTICLE_LINKS_MANAGER_H_INCLUDED
[ "loxotron@bk.ru" ]
loxotron@bk.ru
fc3ad073b9f6bf2876203c42952c26bb67b091c8
9795b3fdc47ce0aa91c9f2443168f4cbbe8d9c3c
/simulation/extern_include/mex.hpp
54a9ce7107daf360cfc9ae63f8d3dcf65d7517a7
[ "MIT" ]
permissive
seanny1986/gym-aero
badf540a230adab0c85ef2f9c6f76fcc189e8aff
bb8e7f299ca83029c300fa85e423be90fc9c11e1
refs/heads/master
2021-06-18T13:01:44.804786
2021-01-06T11:24:52
2021-01-06T11:24:52
143,800,401
5
4
MIT
2018-10-26T07:59:00
2018-08-07T01:04:18
Python
UTF-8
C++
false
false
1,721
hpp
/** * Published header for C++ MEX * * Copyright 2017-2018 The MathWorks, Inc. */ #if defined(_MSC_VER) # pragma once #endif #if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 3)) # pragma once #endif #ifndef mex_hpp #define mex_hpp #endif #ifndef __MEX_CPP_PUBLISHED_API_HPP__ #define __MEX_CPP_PUBLISHED_API_HPP__ #define __MEX_CPP_API__ #ifndef EXTERN_C # ifdef __cplusplus # define EXTERN_C extern "C" # else # define EXTERN_C extern # endif #endif #if defined(BUILDING_LIBMEX) # include "mex/mex_typedefs.hpp" # include "mex/libmwmex_util.hpp" #else # ifndef LIBMWMEX_API # define LIBMWMEX_API # endif # ifndef LIBMWMEX_API_EXTERN_C # define LIBMWMEX_API_EXTERN_C EXTERN_C LIBMWMEX_API # endif #endif #ifdef _WIN32 # define DLL_EXPORT_SYM __declspec(dllexport) # define SUPPORTS_PRAGMA_ONCE #elif __GNUC__ >= 4 # define DLL_EXPORT_SYM __attribute__ ((visibility("default"))) # define SUPPORTS_PRAGMA_ONCE #else # define DLL_EXPORT_SYM #endif #ifdef DLL_EXPORT_SYM # define MEXFUNCTION_LINKAGE EXTERN_C DLL_EXPORT_SYM #else # ifdef MW_NEEDS_VERSION_H # include "version.h" # define MEXFUNCTION_LINKAGE EXTERN_C DLL_EXPORT_SYM # else # define MEXFUNCTION_LINKAGE EXTERN_C # endif #endif #if defined(_WIN32 ) #define NOEXCEPT throw() #else #define NOEXCEPT noexcept #endif #if defined(_MSC_VER) && _MSC_VER==1800 #define NOEXCEPT_FALSE throw(...) #else #define NOEXCEPT_FALSE noexcept(false) #endif #include "cppmex/mexMatlabEngine.hpp" #include "cppmex/mexFunction.hpp" #include "cppmex/mexException.hpp" #include "cppmex/mexFuture.hpp" #include "cppmex/mexTaskReference.hpp" #endif //__MEX_CPP_PUBLISHED_API_HPP__
[ "s3251350@student.rmit.edu.au" ]
s3251350@student.rmit.edu.au
911923642e3dc4fe52fca389503b191d3359aa05
9634f7e331592b99fc98e0665e3b915105e3b56c
/ödevvvv.cpp
1762072893b21d76dd71d10c34c8735a3b341d36
[]
no_license
betulayyb/Continuation_of_C_codes
2af2bafdc9176a8807f7aa983cc22938a9c7857c
70b45d0175803657706bcb0485ba151028882994
refs/heads/main
2023-03-31T02:01:30.180129
2021-04-09T12:27:52
2021-04-09T12:27:52
356,262,208
0
0
null
null
null
null
ISO-8859-9
C++
false
false
2,086
cpp
#include<stdio.h> int main() { int dizi[4]={119,121,45,140}; // 4*1 lik değerleri belirli bir dizi tanımladık int esiklenmis_dizi[4]; //4*1 lik değerleri belirsiz bir dizi tanımladık printf(" \n\t ***DIZI*** \n\n"); int i; // i karakterini int kullanarak atadık for ( i=0;i<4;i++) // i değerini for döngüsüyle 0'dan 3'e kadar artırdık { printf(" \t %d ",dizi[i]); // printf kullanarak diziyi ekrana yazdırdık } printf(" \n\t ***ESIKLENMIS DIZI*** \n\n"); // printf kullanarak ekrana ***ESIKLENMIS DIZI*** yazdırdık { for (i=0;i<4;i++){ if (dizi[i]>120) // if komutu kullanarak dizi içinde ki sayıları sırasıyla 120 den büyük mü diye kontrol ettik printf("\t225 ",esiklenmis_dizi[i]); // 120 den büyük çıkınca o sayı yerine 225 yazdırdık else printf("\t 0 ",esiklenmis_dizi[i]); // 120 den küçük çıkınca sayı yerine 0 yazdırdık } } int matris[4][4]={124,89,45,785,121,112,85,100,145,100,45,485,134,100,75,130}; //4*4 lük değerleri belirli olan bir matris tanımladık int esiklenmis_matris[4][4]; //4*4 lük değerleri belli olmayan bir matris tanımladık printf(" \n\t ***MATRIS*** \n\n"); //printf kullanarak ekrana ***MATRIS*** yazdırdık int j;// j değerini tanımladık for ( i=0;i<4;i++) { // i değerini for döngüsüyle 0'dan 3'e kadar artırdık for ( j=0;j<4;j++){ // j değerini for döngüsüyle 0'dan 3'e kadar artırdık printf(" \t %d ",matris[i][j]); // printf kullanarak matrisi ekrana yazdırdık } printf("\n"); } printf(" \n\t ***ESIKLENMIS MATRIS*** \n\n"); //printf kullanarak ekrana *** ESIKLENMIS MATRIS*** yazdırdık { for (i=0;i<4;i++){ for ( j=0;j<4;j++){ if (matris[i][j]>120) // if komutu kullanarak matris içinde ki sayıları sırasıyla 120 den büyük mü diye kontrol ettik printf("\t225 ",esiklenmis_matris[i][j]); //120 den büyük çıkınca o sayı yerine 225 yazdırdık else printf("\t 0 ",esiklenmis_matris[i][j]); //120 den küçük çıkınca sayı yerine 0 yazdırdık } printf("\n"); } } }
[ "noreply@github.com" ]
betulayyb.noreply@github.com
f19fd447cce1fdac00226e25af66221ed7a28805
5a2349399fa9d57c6e8cc6e0f7226d683391a362
/src/qt/qtwebkit/Source/WebCore/platform/sql/SQLiteDatabase.cpp
2418fc12c458544a79ea5888e2e00f0a6d3c033c
[ "BSD-2-Clause", "LGPL-2.1-only", "LGPL-2.0-only", "BSD-3-Clause" ]
permissive
aharthcock/phantomjs
e70f3c379dcada720ec8abde3f7c09a24808154c
7d7f2c862347fbc7215c849e790290b2e07bab7c
refs/heads/master
2023-03-18T04:58:32.428562
2023-03-14T05:52:52
2023-03-14T05:52:52
24,828,890
0
0
BSD-3-Clause
2023-03-14T05:52:53
2014-10-05T23:38:56
C++
UTF-8
C++
false
false
15,350
cpp
/* * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved. * Copyright (C) 2007 Justin Haygood (jhaygood@reaktix.com) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "SQLiteDatabase.h" #include "DatabaseAuthorizer.h" #include "Logging.h" #include "SQLiteFileSystem.h" #include "SQLiteStatement.h" #include <sqlite3.h> #include <wtf/Threading.h> #include <wtf/text/CString.h> #include <wtf/text/WTFString.h> namespace WebCore { const int SQLResultDone = SQLITE_DONE; const int SQLResultError = SQLITE_ERROR; const int SQLResultOk = SQLITE_OK; const int SQLResultRow = SQLITE_ROW; const int SQLResultSchema = SQLITE_SCHEMA; const int SQLResultFull = SQLITE_FULL; const int SQLResultInterrupt = SQLITE_INTERRUPT; const int SQLResultConstraint = SQLITE_CONSTRAINT; static const char notOpenErrorMessage[] = "database is not open"; SQLiteDatabase::SQLiteDatabase() : m_db(0) , m_pageSize(-1) , m_transactionInProgress(false) , m_sharable(false) , m_openingThread(0) , m_interrupted(false) , m_openError(SQLITE_ERROR) , m_openErrorMessage() , m_lastChangesCount(0) { } SQLiteDatabase::~SQLiteDatabase() { close(); } bool SQLiteDatabase::open(const String& filename, bool forWebSQLDatabase) { close(); m_openError = SQLiteFileSystem::openDatabase(filename, &m_db, forWebSQLDatabase); if (m_openError != SQLITE_OK) { m_openErrorMessage = m_db ? sqlite3_errmsg(m_db) : "sqlite_open returned null"; LOG_ERROR("SQLite database failed to load from %s\nCause - %s", filename.ascii().data(), m_openErrorMessage.data()); sqlite3_close(m_db); m_db = 0; return false; } m_openError = sqlite3_extended_result_codes(m_db, 1); if (m_openError != SQLITE_OK) { m_openErrorMessage = sqlite3_errmsg(m_db); LOG_ERROR("SQLite database error when enabling extended errors - %s", m_openErrorMessage.data()); sqlite3_close(m_db); m_db = 0; return false; } if (isOpen()) m_openingThread = currentThread(); else m_openErrorMessage = "sqlite_open returned null"; if (!SQLiteStatement(*this, ASCIILiteral("PRAGMA temp_store = MEMORY;")).executeCommand()) LOG_ERROR("SQLite database could not set temp_store to memory"); return isOpen(); } void SQLiteDatabase::close() { if (m_db) { // FIXME: This is being called on the main thread during JS GC. <rdar://problem/5739818> // ASSERT(currentThread() == m_openingThread); sqlite3* db = m_db; { MutexLocker locker(m_databaseClosingMutex); m_db = 0; } sqlite3_close(db); } m_openingThread = 0; m_openError = SQLITE_ERROR; m_openErrorMessage = CString(); } void SQLiteDatabase::interrupt() { m_interrupted = true; while (!m_lockingMutex.tryLock()) { MutexLocker locker(m_databaseClosingMutex); if (!m_db) return; sqlite3_interrupt(m_db); yield(); } m_lockingMutex.unlock(); } bool SQLiteDatabase::isInterrupted() { ASSERT(!m_lockingMutex.tryLock()); return m_interrupted; } void SQLiteDatabase::setFullsync(bool fsync) { if (fsync) executeCommand(ASCIILiteral("PRAGMA fullfsync = 1;")); else executeCommand(ASCIILiteral("PRAGMA fullfsync = 0;")); } int64_t SQLiteDatabase::maximumSize() { int64_t maxPageCount = 0; { MutexLocker locker(m_authorizerLock); enableAuthorizer(false); SQLiteStatement statement(*this, ASCIILiteral("PRAGMA max_page_count")); maxPageCount = statement.getColumnInt64(0); enableAuthorizer(true); } return maxPageCount * pageSize(); } void SQLiteDatabase::setMaximumSize(int64_t size) { if (size < 0) size = 0; int currentPageSize = pageSize(); ASSERT(currentPageSize || !m_db); int64_t newMaxPageCount = currentPageSize ? size / currentPageSize : 0; MutexLocker locker(m_authorizerLock); enableAuthorizer(false); SQLiteStatement statement(*this, "PRAGMA max_page_count = " + String::number(newMaxPageCount)); statement.prepare(); if (statement.step() != SQLResultRow) #if OS(WINDOWS) LOG_ERROR("Failed to set maximum size of database to %I64i bytes", static_cast<long long>(size)); #else LOG_ERROR("Failed to set maximum size of database to %lli bytes", static_cast<long long>(size)); #endif enableAuthorizer(true); } int SQLiteDatabase::pageSize() { // Since the page size of a database is locked in at creation and therefore cannot be dynamic, // we can cache the value for future use if (m_pageSize == -1) { MutexLocker locker(m_authorizerLock); enableAuthorizer(false); SQLiteStatement statement(*this, ASCIILiteral("PRAGMA page_size")); m_pageSize = statement.getColumnInt(0); enableAuthorizer(true); } return m_pageSize; } int64_t SQLiteDatabase::freeSpaceSize() { int64_t freelistCount = 0; { MutexLocker locker(m_authorizerLock); enableAuthorizer(false); // Note: freelist_count was added in SQLite 3.4.1. SQLiteStatement statement(*this, ASCIILiteral("PRAGMA freelist_count")); freelistCount = statement.getColumnInt64(0); enableAuthorizer(true); } return freelistCount * pageSize(); } int64_t SQLiteDatabase::totalSize() { int64_t pageCount = 0; { MutexLocker locker(m_authorizerLock); enableAuthorizer(false); SQLiteStatement statement(*this, ASCIILiteral("PRAGMA page_count")); pageCount = statement.getColumnInt64(0); enableAuthorizer(true); } return pageCount * pageSize(); } void SQLiteDatabase::setSynchronous(SynchronousPragma sync) { executeCommand("PRAGMA synchronous = " + String::number(sync)); } void SQLiteDatabase::setBusyTimeout(int ms) { if (m_db) sqlite3_busy_timeout(m_db, ms); else LOG(SQLDatabase, "BusyTimeout set on non-open database"); } void SQLiteDatabase::setBusyHandler(int(*handler)(void*, int)) { if (m_db) sqlite3_busy_handler(m_db, handler, NULL); else LOG(SQLDatabase, "Busy handler set on non-open database"); } bool SQLiteDatabase::executeCommand(const String& sql) { return SQLiteStatement(*this, sql).executeCommand(); } bool SQLiteDatabase::returnsAtLeastOneResult(const String& sql) { return SQLiteStatement(*this, sql).returnsAtLeastOneResult(); } bool SQLiteDatabase::tableExists(const String& tablename) { if (!isOpen()) return false; String statement = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = '" + tablename + "';"; SQLiteStatement sql(*this, statement); sql.prepare(); return sql.step() == SQLITE_ROW; } void SQLiteDatabase::clearAllTables() { String query = ASCIILiteral("SELECT name FROM sqlite_master WHERE type='table';"); Vector<String> tables; if (!SQLiteStatement(*this, query).returnTextResults(0, tables)) { LOG(SQLDatabase, "Unable to retrieve list of tables from database"); return; } for (Vector<String>::iterator table = tables.begin(); table != tables.end(); ++table ) { if (*table == "sqlite_sequence") continue; if (!executeCommand("DROP TABLE " + *table)) LOG(SQLDatabase, "Unable to drop table %s", (*table).ascii().data()); } } int SQLiteDatabase::runVacuumCommand() { if (!executeCommand(ASCIILiteral("VACUUM;"))) LOG(SQLDatabase, "Unable to vacuum database - %s", lastErrorMsg()); return lastError(); } int SQLiteDatabase::runIncrementalVacuumCommand() { MutexLocker locker(m_authorizerLock); enableAuthorizer(false); if (!executeCommand(ASCIILiteral("PRAGMA incremental_vacuum"))) LOG(SQLDatabase, "Unable to run incremental vacuum - %s", lastErrorMsg()); enableAuthorizer(true); return lastError(); } int64_t SQLiteDatabase::lastInsertRowID() { if (!m_db) return 0; return sqlite3_last_insert_rowid(m_db); } void SQLiteDatabase::updateLastChangesCount() { if (!m_db) return; m_lastChangesCount = sqlite3_total_changes(m_db); } int SQLiteDatabase::lastChanges() { if (!m_db) return 0; return sqlite3_total_changes(m_db) - m_lastChangesCount; } int SQLiteDatabase::lastError() { return m_db ? sqlite3_errcode(m_db) : m_openError; } const char* SQLiteDatabase::lastErrorMsg() { if (m_db) return sqlite3_errmsg(m_db); return m_openErrorMessage.isNull() ? notOpenErrorMessage : m_openErrorMessage.data(); } #ifndef NDEBUG void SQLiteDatabase::disableThreadingChecks() { // This doesn't guarantee that SQList was compiled with -DTHREADSAFE, or that you haven't turned off the mutexes. #if SQLITE_VERSION_NUMBER >= 3003001 m_sharable = true; #else ASSERT(0); // Your SQLite doesn't support sharing handles across threads. #endif } #endif int SQLiteDatabase::authorizerFunction(void* userData, int actionCode, const char* parameter1, const char* parameter2, const char* /*databaseName*/, const char* /*trigger_or_view*/) { DatabaseAuthorizer* auth = static_cast<DatabaseAuthorizer*>(userData); ASSERT(auth); switch (actionCode) { case SQLITE_CREATE_INDEX: return auth->createIndex(parameter1, parameter2); case SQLITE_CREATE_TABLE: return auth->createTable(parameter1); case SQLITE_CREATE_TEMP_INDEX: return auth->createTempIndex(parameter1, parameter2); case SQLITE_CREATE_TEMP_TABLE: return auth->createTempTable(parameter1); case SQLITE_CREATE_TEMP_TRIGGER: return auth->createTempTrigger(parameter1, parameter2); case SQLITE_CREATE_TEMP_VIEW: return auth->createTempView(parameter1); case SQLITE_CREATE_TRIGGER: return auth->createTrigger(parameter1, parameter2); case SQLITE_CREATE_VIEW: return auth->createView(parameter1); case SQLITE_DELETE: return auth->allowDelete(parameter1); case SQLITE_DROP_INDEX: return auth->dropIndex(parameter1, parameter2); case SQLITE_DROP_TABLE: return auth->dropTable(parameter1); case SQLITE_DROP_TEMP_INDEX: return auth->dropTempIndex(parameter1, parameter2); case SQLITE_DROP_TEMP_TABLE: return auth->dropTempTable(parameter1); case SQLITE_DROP_TEMP_TRIGGER: return auth->dropTempTrigger(parameter1, parameter2); case SQLITE_DROP_TEMP_VIEW: return auth->dropTempView(parameter1); case SQLITE_DROP_TRIGGER: return auth->dropTrigger(parameter1, parameter2); case SQLITE_DROP_VIEW: return auth->dropView(parameter1); case SQLITE_INSERT: return auth->allowInsert(parameter1); case SQLITE_PRAGMA: return auth->allowPragma(parameter1, parameter2); case SQLITE_READ: return auth->allowRead(parameter1, parameter2); case SQLITE_SELECT: return auth->allowSelect(); case SQLITE_TRANSACTION: return auth->allowTransaction(); case SQLITE_UPDATE: return auth->allowUpdate(parameter1, parameter2); case SQLITE_ATTACH: return auth->allowAttach(parameter1); case SQLITE_DETACH: return auth->allowDetach(parameter1); case SQLITE_ALTER_TABLE: return auth->allowAlterTable(parameter1, parameter2); case SQLITE_REINDEX: return auth->allowReindex(parameter1); #if SQLITE_VERSION_NUMBER >= 3003013 case SQLITE_ANALYZE: return auth->allowAnalyze(parameter1); case SQLITE_CREATE_VTABLE: return auth->createVTable(parameter1, parameter2); case SQLITE_DROP_VTABLE: return auth->dropVTable(parameter1, parameter2); case SQLITE_FUNCTION: return auth->allowFunction(parameter2); #endif default: ASSERT_NOT_REACHED(); return SQLAuthDeny; } } void SQLiteDatabase::setAuthorizer(PassRefPtr<DatabaseAuthorizer> auth) { if (!m_db) { LOG_ERROR("Attempt to set an authorizer on a non-open SQL database"); ASSERT_NOT_REACHED(); return; } MutexLocker locker(m_authorizerLock); m_authorizer = auth; enableAuthorizer(true); } void SQLiteDatabase::enableAuthorizer(bool enable) { if (m_authorizer && enable) sqlite3_set_authorizer(m_db, SQLiteDatabase::authorizerFunction, m_authorizer.get()); else sqlite3_set_authorizer(m_db, NULL, 0); } bool SQLiteDatabase::isAutoCommitOn() const { return sqlite3_get_autocommit(m_db); } bool SQLiteDatabase::turnOnIncrementalAutoVacuum() { SQLiteStatement statement(*this, ASCIILiteral("PRAGMA auto_vacuum")); int autoVacuumMode = statement.getColumnInt(0); int error = lastError(); // Check if we got an error while trying to get the value of the auto_vacuum flag. // If we got a SQLITE_BUSY error, then there's probably another transaction in // progress on this database. In this case, keep the current value of the // auto_vacuum flag and try to set it to INCREMENTAL the next time we open this // database. If the error is not SQLITE_BUSY, then we probably ran into a more // serious problem and should return false (to log an error message). if (error != SQLITE_ROW) return false; switch (autoVacuumMode) { case AutoVacuumIncremental: return true; case AutoVacuumFull: return executeCommand(ASCIILiteral("PRAGMA auto_vacuum = 2")); case AutoVacuumNone: default: if (!executeCommand(ASCIILiteral("PRAGMA auto_vacuum = 2"))) return false; runVacuumCommand(); error = lastError(); return (error == SQLITE_OK); } } } // namespace WebCore
[ "ariya.hidayat@gmail.com" ]
ariya.hidayat@gmail.com
c69bbb914d82072687a805c65971399163f06097
df2b251a2d00fff294270ebb3fa5ff4e8f82a23a
/WebSocketAPIPlugin/MessageHandling.cpp
711b1e7c9b567ede3a4484405297abc9af87f0af
[]
no_license
sKeLeTr0n/OBSRemote
93ca4ba79e37000225ae85cbe61f61f8739c56e3
031df3ad70b3b379eeb8399c0b7d4ed42ebf35ac
refs/heads/master
2021-01-17T22:29:31.172773
2013-03-10T19:34:44
2013-03-10T19:34:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,028
cpp
/******************************************************************************** Copyright (C) 2013 Hugh Bailey <obs.jim@gmail.com> Copyright (C) 2013 William Hamilton <bill@ecologylab.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. ********************************************************************************/ #include "MessageHandling.h" void OBSAPIMessageHandler::initializeMessageMap() { messageMap[REQ_GET_VERSION] = OBSAPIMessageHandler::HandleGetVersion; messageMap[REQ_GET_CURRENT_SCENE] = OBSAPIMessageHandler::HandleGetCurrentScene; messageMap[REQ_GET_SCENE_LIST] = OBSAPIMessageHandler::HandleGetSceneList; messageMap[REQ_SET_CURRENT_SCENE] = OBSAPIMessageHandler::HandleSetCurrentScene; messageMap[REQ_SET_SOURCES_ORDER] = OBSAPIMessageHandler::HandleSetSourcesOrder; messageMap[REQ_SET_SOURCE_RENDER] = OBSAPIMessageHandler::HandleSetSourceRender; messageMap[REQ_SET_SCENEITEM_POSITION_AND_SIZE] = OBSAPIMessageHandler::HandleSetSceneItemPositionAndSize; messageMap[REQ_GET_STREAMING_STATUS] = OBSAPIMessageHandler::HandleGetStreamingStatus; messageMap[REQ_STARTSTOP_STREAMING] = OBSAPIMessageHandler::HandleStartStopStreaming; messageMap[REQ_TOGGLE_MUTE] = OBSAPIMessageHandler::HandleToggleMute; messageMap[REQ_GET_VOLUMES] = OBSAPIMessageHandler::HandleGetVolumes; messageMap[REQ_SET_VOLUME] = OBSAPIMessageHandler::HandleSetVolume; mapInitialized = true; } OBSAPIMessageHandler::OBSAPIMessageHandler(struct libwebsocket *ws):wsi(ws), mapInitialized(FALSE) { if(!mapInitialized) { initializeMessageMap(); } } json_t* GetOkResponse(json_t* id = NULL) { json_t* ret = json_object(); json_object_set_new(ret, "status", json_string("ok")); if(id != NULL && json_is_string(id)) { json_object_set(ret, "message-id", id); } return ret; } json_t* GetErrorResponse(const char * error, json_t *id = NULL) { json_t* ret = json_object(); json_object_set_new(ret, "status", json_string("error")); json_object_set_new(ret, "error", json_string(error)); if(id != NULL && json_is_string(id)) { json_object_set(ret, "message-id", id); } return ret; } bool OBSAPIMessageHandler::HandleReceivedMessage(void *in, size_t len) { json_error_t err; json_t* message = json_loads((char *) in, JSON_DISABLE_EOF_CHECK, &err); if(message == NULL) { /* failed to parse the message */ return false; } json_t* type = json_object_get(message, "request-type"); json_t* id = json_object_get(message, "message-id"); if(!json_is_string(type)) { this->messagesToSend.push_back(GetErrorResponse("message type not specified", id)); json_decref(message); return true; } const char* requestType = json_string_value(type); MessageFunction messageFunc = messageMap[requestType]; json_t* ret = NULL; if(messageFunc != NULL) { ret = messageFunc(this, message); } else { this->messagesToSend.push_back(GetErrorResponse("message type not recognized", id)); json_decref(message); return true; } if(ret != NULL) { if(json_is_string(id)) { json_object_set(ret, "message-id", id); } json_decref(message); this->messagesToSend.push_back(ret); return true; } else { this->messagesToSend.push_back(GetErrorResponse("no response given", id)); json_decref(message); return true; } return false; } json_t* json_string_wchar(CTSTR str) { if(!str) { return NULL; } size_t wcharLen = slen(str); size_t curLength = (UINT)wchar_to_utf8_len(str, wcharLen, 0); if(curLength) { char *out = (char *) malloc((curLength+1)); wchar_to_utf8(str,wcharLen, out, curLength + 1, 0); out[curLength] = 0; json_t* ret = json_string(out); free(out); return ret; } else { return NULL; } } json_t* getSourceJson(XElement* source) { json_t* ret = json_object(); CTSTR name = source->GetName(); float x = source->GetFloat(TEXT("x")); float y = source->GetFloat(TEXT("y")); float cx = source->GetFloat(TEXT("cx")); float cy = source->GetFloat(TEXT("cy")); bool render = source->GetInt(TEXT("render")) > 0; json_object_set_new(ret, "name", json_string_wchar(name)); json_object_set_new(ret, "x", json_real(x)); json_object_set_new(ret, "y", json_real(y)); json_object_set_new(ret, "cx", json_real(cx)); json_object_set_new(ret, "cy", json_real(cy)); json_object_set_new(ret, "render", json_boolean(render)); return ret; } json_t* getSceneJson(XElement* scene) { XElement* sources = scene->GetElement(TEXT("sources")); json_t* ret = json_object(); json_t* scene_items = json_array(); json_object_set_new(ret, "name", json_string_wchar(scene->GetName())); if(sources != NULL) { for(UINT i = 0; i < sources->NumElements(); i++) { XElement* source = sources->GetElementByID(i); json_array_append(scene_items, getSourceJson(source)); } } json_object_set_new(ret, "sources", scene_items); return ret; } /* Message Handlers */ json_t* OBSAPIMessageHandler::HandleGetVersion(OBSAPIMessageHandler* handler, json_t* message) { json_t* ret = GetOkResponse(); json_object_set_new(ret, "version", json_real(OBS_REMOTE_VERSION)); return ret; } json_t* OBSAPIMessageHandler::HandleGetCurrentScene(OBSAPIMessageHandler* handler, json_t* message) { OBSEnterSceneMutex(); json_t* ret = GetOkResponse(); XElement* scene = OBSGetSceneElement(); json_object_set_new(ret, "name", json_string_wchar(scene->GetName())); XElement* sources = scene->GetElement(TEXT("sources")); json_t* scene_items = json_array(); if(sources != NULL) { for(UINT i = 0; i < sources->NumElements(); i++) { XElement* source = sources->GetElementByID(i); json_array_append_new(scene_items, getSourceJson(source)); } } json_object_set_new(ret, "sources", scene_items); OBSLeaveSceneMutex(); return ret; } json_t* OBSAPIMessageHandler::HandleGetSceneList(OBSAPIMessageHandler* handler, json_t* message) { OBSEnterSceneMutex(); json_t* ret = GetOkResponse(); XElement* xscenes = OBSGetSceneListElement(); XElement* currentScene = OBSGetSceneElement(); json_object_set_new(ret, "current-scene", json_string_wchar(currentScene->GetName())); json_t* scenes = json_array(); if(scenes != NULL) { int numScenes = xscenes->NumElements(); for(int i = 0; i < numScenes; i++) { XElement* scene = xscenes->GetElementByID(i); json_array_append_new(scenes, getSceneJson(scene)); } } json_object_set_new(ret,"scenes", scenes); OBSLeaveSceneMutex(); return ret; } json_t* OBSAPIMessageHandler::HandleSetCurrentScene(OBSAPIMessageHandler* handler, json_t* message) { json_t* newScene = json_object_get(message, "scene-name"); if(newScene != NULL && json_typeof(newScene) == JSON_STRING) { String name = json_string_value(newScene); OBSSetScene(name.Array(), true); } return GetOkResponse(); } json_t* OBSAPIMessageHandler::HandleSetSourcesOrder(OBSAPIMessageHandler* handler, json_t* message) { StringList sceneNames; json_t* arry = json_object_get(message, "scene-names"); if(arry != NULL && json_typeof(arry) == JSON_ARRAY) { for(size_t i = 0; i < json_array_size(arry); i++) { json_t* sceneName = json_array_get(arry, i); String name = json_string_value(sceneName); sceneNames.Add(name); } OBSSetSourceOrder(sceneNames); } return GetOkResponse(); } json_t* OBSAPIMessageHandler::HandleSetSourceRender(OBSAPIMessageHandler *handler, json_t* message) { StringList sceneNames; json_t* source = json_object_get(message, "source"); if(source == NULL || json_typeof(source) != JSON_STRING) { return GetErrorResponse("No source specified"); } json_t* sourceRender = json_object_get(message, "render"); if(source == NULL || !json_is_boolean(sourceRender)) { return GetErrorResponse("No render specified"); } json_t* ret = GetOkResponse(); String sourceName = json_string_value(source); OBSSetSourceRender(sourceName.Array(), json_typeof(sourceRender) == JSON_TRUE); return ret; } json_t* OBSAPIMessageHandler::HandleSetSceneItemPositionAndSize(OBSAPIMessageHandler* handler, json_t* message) { return GetOkResponse(); } json_t* OBSAPIMessageHandler::HandleGetStreamingStatus(OBSAPIMessageHandler* handler, json_t* message) { json_t* ret = GetOkResponse(); json_object_set_new(ret, "streaming", json_boolean(OBSGetStreaming())); json_object_set_new(ret, "preview-only", json_boolean(OBSGetPreviewOnly())); return ret; } json_t* OBSAPIMessageHandler::HandleStartStopStreaming(OBSAPIMessageHandler* handler, json_t* message) { json_t* previewOnly = json_object_get(message, "preview-only"); if(previewOnly != NULL && json_typeof(previewOnly) == JSON_TRUE) { OBSStartStopPreview(); } else { OBSStartStopStream(); } return GetOkResponse(); } json_t* OBSAPIMessageHandler::HandleToggleMute(OBSAPIMessageHandler* handler, json_t* message) { json_t* channel = json_object_get(message, "channel"); if(channel != NULL && json_typeof(channel) == JSON_STRING) { const char* channelVal = json_string_value(channel); if(stricmp(channelVal, "desktop") == 0) { OBSToggleDesktopMute(); } else if(stricmp(channelVal, "microphone") == 0) { OBSToggleMicMute(); } else { return GetErrorResponse("Invalid channel specified."); } } else { return GetErrorResponse("Channel not specified."); } return GetOkResponse(); } json_t* OBSAPIMessageHandler::HandleGetVolumes(OBSAPIMessageHandler* handler, json_t* message) { json_t* ret = GetOkResponse(); json_object_set_new(ret, "mic-volume", json_real(OBSGetMicVolume())); json_object_set_new(ret, "mic-muted", json_boolean(OBSGetMicMuted())); json_object_set_new(ret, "desktop-volume", json_real(OBSGetDesktopVolume())); json_object_set_new(ret, "desktop-muted", json_boolean(OBSGetDesktopMuted())); return ret; } json_t* OBSAPIMessageHandler::HandleSetVolume(OBSAPIMessageHandler* handler, json_t* message) { json_t* channel = json_object_get(message, "channel"); json_t* volume = json_object_get(message, "volume"); json_t* finalValue = json_object_get(message, "final"); if(volume == NULL) { return GetErrorResponse("Volume not specified."); } if(!json_is_number(volume)) { return GetErrorResponse("Volume not number."); } float val = (float) json_number_value(volume); val = min(1.0f, max(0.0f, val)); if(finalValue == NULL) { return GetErrorResponse("Final not specified."); } if(!json_is_boolean(finalValue)) { return GetErrorResponse("Final is not a boolean."); } if(channel != NULL && json_typeof(channel) == JSON_STRING) { const char* channelVal = json_string_value(channel); if(stricmp(channelVal, "desktop") == 0) { OBSSetDesktopVolume(val, json_is_true(finalValue)); } else if(stricmp(channelVal, "microphone") == 0) { OBSSetMicVolume(val, json_is_true(finalValue)); } else { return GetErrorResponse("Invalid channel specified."); } } else { return GetErrorResponse("Channel not specified."); } return GetOkResponse(); } /* OBS Trigger Handler */ WebSocketOBSTriggerHandler::WebSocketOBSTriggerHandler() { updateQueueMutex = OSCreateMutex(); } WebSocketOBSTriggerHandler::~WebSocketOBSTriggerHandler() { OSCloseMutex(updateQueueMutex); } void WebSocketOBSTriggerHandler::StreamStarting(bool previewOnly) { json_t* update = json_object(); json_object_set_new(update, "update-type", json_string("StreamStarting")); json_object_set_new(update, "preview-only", json_boolean(previewOnly)); OSEnterMutex(this->updateQueueMutex); this->updates.Add(update); OSLeaveMutex(this->updateQueueMutex); } void WebSocketOBSTriggerHandler::StreamStopping(bool previewOnly) { json_t* update = json_object(); json_object_set_new(update, "update-type", json_string("StreamStopping")); json_object_set_new(update, "preview-only", json_boolean(previewOnly)); OSEnterMutex(this->updateQueueMutex); this->updates.Add(update); OSLeaveMutex(this->updateQueueMutex); } void WebSocketOBSTriggerHandler::StreamStatus(bool streaming, bool previewOnly, UINT bytesPerSec, double strain, UINT totalStreamtime, UINT numTotalFrames, UINT numDroppedFrames, UINT fps) { json_t* update = json_object(); json_object_set_new(update, "update-type", json_string("StreamStatus")); json_object_set_new(update, "streaming", json_boolean(streaming)); json_object_set_new(update, "preview-only", json_boolean(previewOnly)); json_object_set_new(update, "bytes-per-sec", json_integer(bytesPerSec)); json_object_set_new(update, "strain", json_real(strain)); json_object_set_new(update, "total-stream-time", json_integer(totalStreamtime)); json_object_set_new(update, "num-total-frames", json_integer(numTotalFrames)); json_object_set_new(update, "num-dropped-frames", json_integer(numDroppedFrames)); json_object_set_new(update, "fps", json_integer(fps)); OSEnterMutex(this->updateQueueMutex); this->updates.Add(update); OSLeaveMutex(this->updateQueueMutex); } void WebSocketOBSTriggerHandler::ScenesSwitching(CTSTR scene) { json_t* update = json_object(); json_object_set_new(update, "update-type", json_string("SwitchScenes")); json_object_set_new(update, "scene-name", json_string_wchar(scene)); OSEnterMutex(this->updateQueueMutex); this->updates.Add(update); OSLeaveMutex(this->updateQueueMutex); } void WebSocketOBSTriggerHandler::ScenesChanged() { json_t* update = json_object(); json_object_set_new(update, "update-type", json_string("ScenesChanged")); OSEnterMutex(this->updateQueueMutex); this->updates.Add(update); OSLeaveMutex(this->updateQueueMutex); } void WebSocketOBSTriggerHandler::SourceOrderChanged() { json_t* update = json_object(); json_object_set_new(update, "update-type", json_string("SourceOrderChanged")); XElement* xsources = OBSGetSceneElement()->GetElement(TEXT("sources")); json_t* sources = json_array(); for(UINT i = 0; i < xsources->NumElements(); i++) { XElement* source = xsources->GetElementByID(i); json_array_append_new(sources, json_string_wchar(source->GetName())); } json_object_set_new(update, "sources", sources); OSEnterMutex(this->updateQueueMutex); this->updates.Add(update); OSLeaveMutex(this->updateQueueMutex); } void WebSocketOBSTriggerHandler::SourcesAddedOrRemoved() { json_t* update = json_object(); json_object_set_new(update, "update-type", json_string("RepopulateSources")); XElement* xsources = OBSGetSceneElement()->GetElement(TEXT("sources")); json_t* sources = json_array(); for(UINT i = 0; i < xsources->NumElements(); i++) { XElement* source = xsources->GetElementByID(i); json_array_append_new(sources, getSourceJson(source)); } json_object_set_new(update, "sources", sources); OSEnterMutex(this->updateQueueMutex); this->updates.Add(update); OSLeaveMutex(this->updateQueueMutex); } void WebSocketOBSTriggerHandler::SourceChanged(CTSTR sourceName, XElement* source) { json_t* update = json_object(); json_object_set_new(update, "update-type", json_string("SourceChanged")); XElement* xsources = OBSGetSceneElement()->GetElement(TEXT("sources")); json_object_set_new(update, "source-name", json_string_wchar(sourceName)); json_object_set_new(update, "source", getSourceJson(source)); OSEnterMutex(this->updateQueueMutex); this->updates.Add(update); OSLeaveMutex(this->updateQueueMutex); } void WebSocketOBSTriggerHandler::MicVolumeChanged(float level, bool muted, bool finalValue) { json_t* update = json_object(); json_object_set_new(update, "update-type", json_string("VolumeChanged")); json_object_set_new(update, "channel", json_string("microphone")); json_object_set_new(update, "volume", json_real(level)); json_object_set_new(update, "muted", json_boolean(muted)); json_object_set_new(update, "finalValue", json_boolean(finalValue)); OSEnterMutex(this->updateQueueMutex); this->updates.Add(update); OSLeaveMutex(this->updateQueueMutex); } void WebSocketOBSTriggerHandler::DesktopVolumeChanged(float level, bool muted, bool finalValue) { json_t* update = json_object(); json_object_set_new(update, "update-type", json_string("VolumeChanged")); json_object_set_new(update, "channel", json_string("desktop")); json_object_set_new(update, "volume", json_real(level)); json_object_set_new(update, "muted", json_boolean(muted)); json_object_set_new(update, "finalValue", json_boolean(finalValue)); OSEnterMutex(this->updateQueueMutex); this->updates.Add(update); OSLeaveMutex(this->updateQueueMutex); } json_t* WebSocketOBSTriggerHandler::popUpdate() { OSEnterMutex(this->updateQueueMutex); json_t* ret = NULL; if(this->updates.Num() > 0) { ret = this->updates.GetElement(0); this->updates.Remove(0); } OSLeaveMutex(this->updateQueueMutex); return ret; }
[ "luin.uial@gmail.com" ]
luin.uial@gmail.com
c1fa0e8cd45d9d837e55570cb75b796d9f104535
627d4d432c86ad98f669214d9966ae2db1600b31
/src/script/bridge/qscriptdeclarativeclass_p.h
8c7328685365f9c0a7ee344c4f16e5a9f0d9fc4d
[]
no_license
fluxer/copperspice
6dbab905f71843b8a3f52c844b841cef17f71f3f
07e7d1315d212a4568589b0ab1bd6c29c06d70a1
refs/heads/cs-1.1
2021-01-17T21:21:54.176319
2015-08-26T15:25:29
2015-08-26T15:25:29
39,802,091
6
0
null
2015-07-27T23:04:01
2015-07-27T23:04:00
null
UTF-8
C++
false
false
5,045
h
/*********************************************************************** * * Copyright (c) 2012-2015 Barbara Geller * Copyright (c) 2012-2015 Ansel Sermersheim * Copyright (c) 2012-2014 Digia Plc and/or its subsidiary(-ies). * Copyright (c) 2008-2012 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * * This file is part of CopperSpice. * * CopperSpice is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * CopperSpice is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with CopperSpice. If not, see * <http://www.gnu.org/licenses/>. * ***********************************************************************/ #ifndef QSCRIPTDECLARATIVECLASS_P_H #define QSCRIPTDECLARATIVECLASS_P_H #include <QtScript/qscriptvalue.h> #include <QtScript/qscriptclass.h> QT_BEGIN_NAMESPACE class QScriptDeclarativeClassPrivate; class PersistentIdentifierPrivate; class QScriptContext; class Q_SCRIPT_EXPORT QScriptDeclarativeClass { public: #define QT_HAVE_QSCRIPTDECLARATIVECLASS_VALUE class Q_SCRIPT_EXPORT Value { public: Value(); Value(const Value &); Value(QScriptContext *, int); Value(QScriptContext *, uint); Value(QScriptContext *, bool); Value(QScriptContext *, double); Value(QScriptContext *, float); Value(QScriptContext *, const QString &); Value(QScriptContext *, const QScriptValue &); Value(QScriptEngine *, int); Value(QScriptEngine *, uint); Value(QScriptEngine *, bool); Value(QScriptEngine *, double); Value(QScriptEngine *, float); Value(QScriptEngine *, const QString &); Value(QScriptEngine *, const QScriptValue &); ~Value(); QScriptValue toScriptValue(QScriptEngine *) const; private: char dummy[8]; }; typedef void *Identifier; struct Object { virtual ~Object() {} }; static QScriptValue newObject(QScriptEngine *, QScriptDeclarativeClass *, Object *); static Value newObjectValue(QScriptEngine *, QScriptDeclarativeClass *, Object *); static QScriptDeclarativeClass *scriptClass(const QScriptValue &); static Object *object(const QScriptValue &); static QScriptValue function(const QScriptValue &, const Identifier &); static QScriptValue property(const QScriptValue &, const Identifier &); static Value functionValue(const QScriptValue &, const Identifier &); static Value propertyValue(const QScriptValue &, const Identifier &); static QScriptValue scopeChainValue(QScriptContext *, int index); static QScriptContext *pushCleanContext(QScriptEngine *); static QScriptValue newStaticScopeObject( QScriptEngine *, int propertyCount, const QString *names, const QScriptValue *values, const QScriptValue::PropertyFlags *flags); static QScriptValue newStaticScopeObject(QScriptEngine *); class Q_SCRIPT_EXPORT PersistentIdentifier { public: Identifier identifier; PersistentIdentifier(); ~PersistentIdentifier(); PersistentIdentifier(const PersistentIdentifier &other); PersistentIdentifier &operator=(const PersistentIdentifier &other); QString toString() const; private: friend class QScriptDeclarativeClass; PersistentIdentifier(QScriptEnginePrivate *e) : identifier(0), engine(e), d(0) {} QScriptEnginePrivate *engine; void *d; }; QScriptDeclarativeClass(QScriptEngine *engine); virtual ~QScriptDeclarativeClass(); QScriptEngine *engine() const; bool supportsCall() const; void setSupportsCall(bool); PersistentIdentifier createPersistentIdentifier(const QString &); PersistentIdentifier createPersistentIdentifier(const Identifier &); QString toString(const Identifier &); bool startsWithUpper(const Identifier &); quint32 toArrayIndex(const Identifier &, bool *ok); virtual QScriptClass::QueryFlags queryProperty(Object *, const Identifier &, QScriptClass::QueryFlags flags); virtual Value property(Object *, const Identifier &); virtual void setProperty(Object *, const Identifier &name, const QScriptValue &); virtual QScriptValue::PropertyFlags propertyFlags(Object *, const Identifier &); virtual Value call(Object *, QScriptContext *); virtual bool compare(Object *, Object *); virtual QStringList propertyNames(Object *); virtual bool isQObject() const; virtual QObject *toQObject(Object *, bool *ok = 0); virtual QVariant toVariant(Object *, bool *ok = 0); QScriptContext *context() const; protected: friend class QScriptDeclarativeClassPrivate; QScopedPointer<QScriptDeclarativeClassPrivate> d_ptr; }; QT_END_NAMESPACE #endif
[ "ansel@copperspice.com" ]
ansel@copperspice.com
f8c3231a602cc458b78b358f7071cd937c7ce6ee
47924dd44a8e071aa113f0f2b9e8700e21a5d934
/Marlin/Marlin_main.cpp
12ae360d66e22665a5349ff03a75a53687abc1e3
[]
no_license
masterzion/Marlin1.4
4cf585b0b47811517a12296c43e2c1db7b72e1b0
fd079a5d81484bb66699937bfe6dfb9d4ebc2531
refs/heads/main
2023-04-18T23:59:31.678600
2021-05-03T14:56:49
2021-05-03T14:56:49
363,965,174
0
0
null
null
null
null
UTF-8
C++
false
false
537,086
cpp
/** * Marlin 3D Printer Firmware * Copyright (C) 2016, 2017 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /** * About Marlin * * This firmware is a mashup between Sprinter and grbl. * - https://github.com/kliment/Sprinter * - https://github.com/grbl/grbl */ /** * ----------------- * G-Codes in Marlin * ----------------- * * Helpful G-code references: * - http://linuxcnc.org/handbook/gcode/g-code.html * - http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes * * Help to document Marlin's G-codes online: * - http://reprap.org/wiki/G-code * - https://github.com/MarlinFirmware/MarlinDocumentation * * ----------------- * * "G" Codes * * G0 -> G1 * G1 - Coordinated Movement X Y Z E * G2 - CW ARC * G3 - CCW ARC * G4 - Dwell S<seconds> or P<milliseconds> * G5 - Cubic B-spline with XYZE destination and IJPQ offsets * G6 - Direct stepper move (Requires UNREGISTERED_MOVE_SUPPORT). Hangprinter defaults to relative moves. Others default to absolute moves. * G10 - Retract filament according to settings of M207 (Requires FWRETRACT) * G11 - Retract recover filament according to settings of M208 (Requires FWRETRACT) * G12 - Clean tool (Requires NOZZLE_CLEAN_FEATURE) * G17 - Select Plane XY (Requires CNC_WORKSPACE_PLANES) * G18 - Select Plane ZX (Requires CNC_WORKSPACE_PLANES) * G19 - Select Plane YZ (Requires CNC_WORKSPACE_PLANES) * G20 - Set input units to inches (Requires INCH_MODE_SUPPORT) * G21 - Set input units to millimeters (Requires INCH_MODE_SUPPORT) * G26 - Mesh Validation Pattern (Requires G26_MESH_VALIDATION) * G27 - Park Nozzle (Requires NOZZLE_PARK_FEATURE) * G28 - Home one or more axes * G29 - Start or continue the bed leveling probe procedure (Requires bed leveling) * G30 - Single Z probe, probes bed at X Y location (defaults to current XY location) * G31 - Dock sled (Z_PROBE_SLED only) * G32 - Undock sled (Z_PROBE_SLED only) * G33 - Delta Auto-Calibration (Requires DELTA_AUTO_CALIBRATION) * G38 - Probe in any direction using the Z_MIN_PROBE (Requires G38_PROBE_TARGET) * G42 - Coordinated move to a mesh point (Requires MESH_BED_LEVELING, AUTO_BED_LEVELING_BLINEAR, or AUTO_BED_LEVELING_UBL) * G90 - Use Absolute Coordinates * G91 - Use Relative Coordinates * G92 - Set current position to coordinates given * G95 - Set torque mode (Requires MECHADUINO_I2C_COMMANDS enabled) * G96 - Set encoder reference point (Requires MECHADUINO_I2C_COMMANDS enabled) * * "M" Codes * * M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled) * M1 -> M0 * M3 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to clockwise * M4 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to counter-clockwise * M5 - Turn laser/spindle off * M17 - Enable/Power all stepper motors * M18 - Disable all stepper motors; same as M84 * M20 - List SD card. (Requires SDSUPPORT) * M21 - Init SD card. (Requires SDSUPPORT) * M22 - Release SD card. (Requires SDSUPPORT) * M23 - Select SD file: "M23 /path/file.gco". (Requires SDSUPPORT) * M24 - Start/resume SD print. (Requires SDSUPPORT) * M25 - Pause SD print. (Requires SDSUPPORT) * M26 - Set SD position in bytes: "M26 S12345". (Requires SDSUPPORT) * M27 - Report SD print status. (Requires SDSUPPORT) * OR, with 'S<seconds>' set the SD status auto-report interval. (Requires AUTO_REPORT_SD_STATUS) * OR, with 'C' get the current filename. * M28 - Start SD write: "M28 /path/file.gco". (Requires SDSUPPORT) * M29 - Stop SD write. (Requires SDSUPPORT) * M30 - Delete file from SD: "M30 /path/file.gco" * M31 - Report time since last M109 or SD card start to serial. * M32 - Select file and start SD print: "M32 [S<bytepos>] !/path/file.gco#". (Requires SDSUPPORT) * Use P to run other files as sub-programs: "M32 P !filename#" * The '#' is necessary when calling from within sd files, as it stops buffer prereading * M33 - Get the longname version of a path. (Requires LONG_FILENAME_HOST_SUPPORT) * M34 - Set SD Card sorting options. (Requires SDCARD_SORT_ALPHA) * M42 - Change pin status via gcode: M42 P<pin> S<value>. LED pin assumed if P is omitted. * M43 - Display pin status, watch pins for changes, watch endstops & toggle LED, Z servo probe test, toggle pins * M48 - Measure Z Probe repeatability: M48 P<points> X<pos> Y<pos> V<level> E<engage> L<legs> S<chizoid>. (Requires Z_MIN_PROBE_REPEATABILITY_TEST) * M75 - Start the print job timer. * M76 - Pause the print job timer. * M77 - Stop the print job timer. * M78 - Show statistical information about the print jobs. (Requires PRINTCOUNTER) * M80 - Turn on Power Supply. (Requires POWER_SUPPLY > 0) * M81 - Turn off Power Supply. (Requires POWER_SUPPLY > 0) * M82 - Set E codes absolute (default). * M83 - Set E codes relative while in Absolute (G90) mode. * M84 - Disable steppers until next move, or use S<seconds> to specify an idle * duration after which steppers should turn off. S0 disables the timeout. * M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default) * M92 - Set planner.axis_steps_per_mm for one or more axes. * M100 - Watch Free Memory (for debugging) (Requires M100_FREE_MEMORY_WATCHER) * M104 - Set extruder target temp. * M105 - Report current temperatures. * M106 - Set print fan speed. * M107 - Print fan off. * M108 - Break out of heating loops (M109, M190, M303). With no controller, breaks out of M0/M1. (Requires EMERGENCY_PARSER) * M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating * Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling * If AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F * M110 - Set the current line number. (Used by host printing) * M111 - Set debug flags: "M111 S<flagbits>". See flag bits defined in enum.h. * M112 - Emergency stop. * M113 - Get or set the timeout interval for Host Keepalive "busy" messages. (Requires HOST_KEEPALIVE_FEATURE) * M114 - Report current position. * - S1 Compute length traveled since last G96 using encoder position data (Requires MECHADUINO_I2C_COMMANDS, only kinematic axes) * M115 - Report capabilities. (Extended capabilities requires EXTENDED_CAPABILITIES_REPORT) * M117 - Display a message on the controller screen. (Requires an LCD) * M118 - Display a message in the host console. * M119 - Report endstops status. * M120 - Enable endstops detection. * M121 - Disable endstops detection. * M122 - Debug stepper (Requires at least one _DRIVER_TYPE defined as TMC2130/TMC2208/TMC2660) * M125 - Save current position and move to filament change position. (Requires PARK_HEAD_ON_PAUSE) * M126 - Solenoid Air Valve Open. (Requires BARICUDA) * M127 - Solenoid Air Valve Closed. (Requires BARICUDA) * M128 - EtoP Open. (Requires BARICUDA) * M129 - EtoP Closed. (Requires BARICUDA) * M140 - Set bed target temp. S<temp> * M145 - Set heatup values for materials on the LCD. H<hotend> B<bed> F<fan speed> for S<material> (0=PLA, 1=ABS) * M149 - Set temperature units. (Requires TEMPERATURE_UNITS_SUPPORT) * M150 - Set Status LED Color as R<red> U<green> B<blue> P<bright>. Values 0-255. (Requires BLINKM, RGB_LED, RGBW_LED, NEOPIXEL_LED, or PCA9632). * M155 - Auto-report temperatures with interval of S<seconds>. (Requires AUTO_REPORT_TEMPERATURES) * M163 - Set a single proportion for a mixing extruder. (Requires MIXING_EXTRUDER) * M164 - Commit the mix (Req. MIXING_EXTRUDER) and optionally save as a virtual tool (Req. MIXING_VIRTUAL_TOOLS > 1) * M165 - Set the mix for a mixing extruder wuth parameters ABCDHI. (Requires MIXING_EXTRUDER and DIRECT_MIXING_IN_G1) * M190 - Sxxx Wait for bed current temp to reach target temp. ** Waits only when heating! ** * Rxxx Wait for bed current temp to reach target temp. ** Waits for heating or cooling. ** * M200 - Set filament diameter, D<diameter>, setting E axis units to cubic. (Use S0 to revert to linear units.) * M201 - Set max acceleration in units/s^2 for print moves: "M201 X<accel> Y<accel> Z<accel> E<accel>" * M202 - Set max acceleration in units/s^2 for travel moves: "M202 X<accel> Y<accel> Z<accel> E<accel>" ** UNUSED IN MARLIN! ** * M203 - Set maximum feedrate: "M203 X<fr> Y<fr> Z<fr> E<fr>" in units/sec. * M204 - Set default acceleration in units/sec^2: P<printing> R<extruder_only> T<travel> * M205 - Set advanced settings. Current units apply: S<print> T<travel> minimum speeds Q<minimum segment time> X<max X jerk>, Y<max Y jerk>, Z<max Z jerk>, E<max E jerk> * M206 - Set additional homing offset. (Disabled by NO_WORKSPACE_OFFSETS or DELTA) * M207 - Set Retract Length: S<length>, Feedrate: F<units/min>, and Z lift: Z<distance>. (Requires FWRETRACT) * M208 - Set Recover (unretract) Additional (!) Length: S<length> and Feedrate: F<units/min>. (Requires FWRETRACT) * M209 - Turn Automatic Retract Detection on/off: S<0|1> (For slicers that don't support G10/11). (Requires FWRETRACT) Every normal extrude-only move will be classified as retract depending on the direction. * M211 - Enable, Disable, and/or Report software endstops: S<0|1> (Requires MIN_SOFTWARE_ENDSTOPS or MAX_SOFTWARE_ENDSTOPS) * M218 - Set/get a tool offset: "M218 T<index> X<offset> Y<offset>". (Requires 2 or more extruders) * M220 - Set Feedrate Percentage: "M220 S<percent>" (i.e., "FR" on the LCD) * M221 - Set Flow Percentage: "M221 S<percent>" * M226 - Wait until a pin is in a given state: "M226 P<pin> S<state>" * M240 - Trigger a camera to take a photograph. (Requires CHDK or PHOTOGRAPH_PIN) * M250 - Set LCD contrast: "M250 C<contrast>" (0-63). (Requires LCD support) * M260 - i2c Send Data (Requires EXPERIMENTAL_I2CBUS) * M261 - i2c Request Data (Requires EXPERIMENTAL_I2CBUS) * M280 - Set servo position absolute: "M280 P<index> S<angle|µs>". (Requires servos) * M290 - Babystepping (Requires BABYSTEPPING) * M300 - Play beep sound S<frequency Hz> P<duration ms> * M301 - Set PID parameters P I and D. (Requires PIDTEMP) * M302 - Allow cold extrudes, or set the minimum extrude S<temperature>. (Requires PREVENT_COLD_EXTRUSION) * M303 - PID relay autotune S<temperature> sets the target temperature. Default 150C. (Requires PIDTEMP) * M304 - Set bed PID parameters P I and D. (Requires PIDTEMPBED) * M350 - Set microstepping mode. (Requires digital microstepping pins.) * M351 - Toggle MS1 MS2 pins directly. (Requires digital microstepping pins.) * M355 - Set Case Light on/off and set brightness. (Requires CASE_LIGHT_PIN) * M380 - Activate solenoid on active extruder. (Requires EXT_SOLENOID) * M381 - Disable all solenoids. (Requires EXT_SOLENOID) * M400 - Finish all moves. * M401 - Deploy and activate Z probe. (Requires a probe) * M402 - Deactivate and stow Z probe. (Requires a probe) * M404 - Display or set the Nominal Filament Width: "W<diameter>". (Requires FILAMENT_WIDTH_SENSOR) * M405 - Enable Filament Sensor flow control. "M405 D<delay_cm>". (Requires FILAMENT_WIDTH_SENSOR) * M406 - Disable Filament Sensor flow control. (Requires FILAMENT_WIDTH_SENSOR) * M407 - Display measured filament diameter in millimeters. (Requires FILAMENT_WIDTH_SENSOR) * M410 - Quickstop. Abort all planned moves. * M420 - Enable/Disable Leveling (with current values) S1=enable S0=disable (Requires MESH_BED_LEVELING or ABL) * M421 - Set a single Z coordinate in the Mesh Leveling grid. X<units> Y<units> Z<units> (Requires MESH_BED_LEVELING, AUTO_BED_LEVELING_BILINEAR, or AUTO_BED_LEVELING_UBL) * M428 - Set the home_offset based on the current_position. Nearest edge applies. (Disabled by NO_WORKSPACE_OFFSETS or DELTA) * M500 - Store parameters in EEPROM. (Requires EEPROM_SETTINGS) * M501 - Restore parameters from EEPROM. (Requires EEPROM_SETTINGS) * M502 - Revert to the default "factory settings". ** Does not write them to EEPROM! ** * M503 - Print the current settings (in memory): "M503 S<verbose>". S0 specifies compact output. * M524 - Abort SD card print job started with M24 (Requires SDSUPPORT) * M540 - Enable/disable SD card abort on endstop hit: "M540 S<state>". (Requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED) * M600 - Pause for filament change: "M600 X<pos> Y<pos> Z<raise> E<first_retract> L<later_retract>". (Requires ADVANCED_PAUSE_FEATURE) * M603 - Configure filament change: "M603 T<tool> U<unload_length> L<load_length>". (Requires ADVANCED_PAUSE_FEATURE) * M605 - Set Dual X-Carriage movement mode: "M605 S<mode> [X<x_offset>] [R<temp_offset>]". (Requires DUAL_X_CARRIAGE) * M665 - Set Delta configurations: "M665 H<delta height> L<diagonal rod> R<delta radius> S<segments/s> B<calibration radius> X<Alpha angle trim> Y<Beta angle trim> Z<Gamma angle trim> (Requires DELTA) * M665 - Set Hangprinter configurations: "M665 W<Ay> E<Az> R<Bx> T<By> Y<Bz> U<Cx> I<Cy> O<Cz> P<Dz> S<segments/s>" (Requires HANGPRINTER) * M666 - Set/get endstop offsets for delta (Requires DELTA) or dual endstops (Requires [XYZ]_DUAL_ENDSTOPS). * M701 - Load filament (requires FILAMENT_LOAD_UNLOAD_GCODES) * M702 - Unload filament (requires FILAMENT_LOAD_UNLOAD_GCODES) * M851 - Set Z probe's Z offset in current units. (Negative = below the nozzle.) * M852 - Set skew factors: "M852 [I<xy>] [J<xz>] [K<yz>]". (Requires SKEW_CORRECTION_GCODE, and SKEW_CORRECTION_FOR_Z for IJ) * M860 - Report the position of position encoder modules. * M861 - Report the status of position encoder modules. * M862 - Perform an axis continuity test for position encoder modules. * M863 - Perform steps-per-mm calibration for position encoder modules. * M864 - Change position encoder module I2C address. * M865 - Check position encoder module firmware version. * M866 - Report or reset position encoder module error count. * M867 - Enable/disable or toggle error correction for position encoder modules. * M868 - Report or set position encoder module error correction threshold. * M869 - Report position encoder module error. * M888 - Ultrabase cooldown: Let the parts cooling fan hover above the finished print to cool down the bed. EXPERIMENTAL FEATURE! * M900 - Get or Set Linear Advance K-factor. (Requires LIN_ADVANCE) * M906 - Set or get motor current in milliamps using axis codes X, Y, Z, E. Report values if no axis codes given. (Requires at least one _DRIVER_TYPE defined as TMC2130/TMC2208/TMC2660) * M907 - Set digital trimpot motor current using axis codes. (Requires a board with digital trimpots) * M908 - Control digital trimpot directly. (Requires DAC_STEPPER_CURRENT or DIGIPOTSS_PIN) * M909 - Print digipot/DAC current value. (Requires DAC_STEPPER_CURRENT) * M910 - Commit digipot/DAC value to external EEPROM via I2C. (Requires DAC_STEPPER_CURRENT) * M911 - Report stepper driver overtemperature pre-warn condition. (Requires at least one _DRIVER_TYPE defined as TMC2130/TMC2208/TMC2660) * M912 - Clear stepper driver overtemperature pre-warn condition flag. (Requires at least one _DRIVER_TYPE defined as TMC2130/TMC2208/TMC2660) * M913 - Set HYBRID_THRESHOLD speed. (Requires HYBRID_THRESHOLD) * M914 - Set SENSORLESS_HOMING sensitivity. (Requires SENSORLESS_HOMING) * * M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration) * M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree) * M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration) * M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree) * M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position) * * ************ Custom codes - This can change to suit future G-code regulations * M928 - Start SD logging: "M928 filename.gco". Stop with M29. (Requires SDSUPPORT) * M999 - Restart after being stopped by error * * "T" Codes * * T0-T3 - Select an extruder (tool) by index: "T<n> F<units/min>" * */ #include "Marlin.h" // #include "MyHardwareSerial.h" #include "ultralcd.h" #include "planner.h" #include "stepper.h" #include "endstops.h" #include "temperature.h" #include "cardreader.h" #include "configuration_store.h" #include "language.h" #include "pins_arduino.h" #include "math.h" #include "nozzle.h" #include "printcounter.h" #include "duration_t.h" #include "types.h" #include "parser.h" #if ENABLED(AUTO_POWER_CONTROL) #include "power.h" #endif #if ABL_PLANAR #include "vector_3.h" #if ENABLED(AUTO_BED_LEVELING_LINEAR) #include "least_squares_fit.h" #endif #elif ENABLED(MESH_BED_LEVELING) #include "mesh_bed_leveling.h" #endif #if ENABLED(BEZIER_CURVE_SUPPORT) #include "planner_bezier.h" #endif #if ENABLED(FWRETRACT) #include "fwretract.h" #endif #if ENABLED(POWER_LOSS_RECOVERY) #include "power_loss_recovery.h" #endif #if ENABLED(FILAMENT_RUNOUT_SENSOR) #include "runout.h" #endif #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER) #include "buzzer.h" #endif #if ENABLED(USE_WATCHDOG) #include "watchdog.h" #endif #if ENABLED(MAX7219_DEBUG) #include "Max7219_Debug_LEDs.h" #endif #if HAS_COLOR_LEDS #include "leds.h" #endif #if HAS_SERVOS #include "servo.h" #endif #if HAS_DIGIPOTSS #include <SPI.h> #endif #if HAS_TRINAMIC #include "tmc_util.h" #endif #if ENABLED(DAC_STEPPER_CURRENT) #include "stepper_dac.h" #endif #if ENABLED(EXPERIMENTAL_I2CBUS) #include "twibus.h" #endif #if ENABLED(I2C_POSITION_ENCODERS) #include "I2CPositionEncoder.h" #endif #if ENABLED(M100_FREE_MEMORY_WATCHER) void gcode_M100(); void M100_dump_routine(const char * const title, const char *start, const char *end); #endif #if ENABLED(G26_MESH_VALIDATION) bool g26_debug_flag; // =false void gcode_G26(); #endif #if ENABLED(SDSUPPORT) CardReader card; #endif #if ENABLED(EXPERIMENTAL_I2CBUS) TWIBus i2c; #endif #if ENABLED(G38_PROBE_TARGET) bool G38_move = false, G38_endstop_hit = false; #endif #if ENABLED(AUTO_BED_LEVELING_UBL) #include "ubl.h" #endif #if ENABLED(CNC_COORDINATE_SYSTEMS) int8_t active_coordinate_system = -1; // machine space float coordinate_system[MAX_COORDINATE_SYSTEMS][XYZ]; #endif #ifdef ANYCUBIC_TFT_MODEL #include "AnycubicTFT.h" #endif bool Running = true; uint8_t marlin_debug_flags = DEBUG_NONE; /** * Cartesian Current Position * Used to track the native machine position as moves are queued. * Used by 'buffer_line_to_current_position' to do a move after changing it. * Used by 'SYNC_PLAN_POSITION_KINEMATIC' to update 'planner.position'. */ float current_position[XYZE] = { 0 }; /** * Cartesian Destination * The destination for a move, filled in by G-code movement commands, * and expected by functions like 'prepare_move_to_destination'. * Set with 'gcode_get_destination' or 'set_destination_from_current'. */ float destination[XYZE] = { 0 }; /** * axis_homed * Flags that each linear axis was homed. * XYZ on cartesian, ABC on delta, ABZ on SCARA. * * axis_known_position * Flags that the position is known in each linear axis. Set when homed. * Cleared whenever a stepper powers off, potentially losing its position. */ uint8_t axis_homed, axis_known_position; // = 0 /** * GCode line number handling. Hosts may opt to include line numbers when * sending commands to Marlin, and lines will be checked for sequentiality. * M110 N<int> sets the current line number. */ static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0; /** * GCode Command Queue * A simple ring buffer of BUFSIZE command strings. * * Commands are copied into this buffer by the command injectors * (immediate, serial, sd card) and they are processed sequentially by * the main loop. The process_next_command function parses the next * command and hands off execution to individual handler functions. */ uint8_t commands_in_queue = 0, // Count of commands in the queue cmd_queue_index_r = 0, // Ring buffer read (out) position cmd_queue_index_w = 0; // Ring buffer write (in) position char command_queue[BUFSIZE][MAX_CMD_SIZE]; /** * Next Injected Command pointer. NULL if no commands are being injected. * Used by Marlin internally to ensure that commands initiated from within * are enqueued ahead of any pending serial or sd card commands. */ static const char *injected_commands_P = NULL; #if ENABLED(TEMPERATURE_UNITS_SUPPORT) TempUnit input_temp_units = TEMPUNIT_C; #endif /** * Feed rates are often configured with mm/m * but the planner and stepper like mm/s units. */ static const float homing_feedrate_mm_s[] PROGMEM = { #if ENABLED(HANGPRINTER) MMM_TO_MMS(DUMMY_HOMING_FEEDRATE), MMM_TO_MMS(DUMMY_HOMING_FEEDRATE), MMM_TO_MMS(DUMMY_HOMING_FEEDRATE), MMM_TO_MMS(DUMMY_HOMING_FEEDRATE), 0 #else #if ENABLED(DELTA) MMM_TO_MMS(HOMING_FEEDRATE_Z), MMM_TO_MMS(HOMING_FEEDRATE_Z), #else MMM_TO_MMS(HOMING_FEEDRATE_XY), MMM_TO_MMS(HOMING_FEEDRATE_XY), #endif MMM_TO_MMS(HOMING_FEEDRATE_Z), 0 #endif }; FORCE_INLINE float homing_feedrate(const AxisEnum a) { return pgm_read_float(&homing_feedrate_mm_s[a]); } float feedrate_mm_s = MMM_TO_MMS(1500.0f); static float saved_feedrate_mm_s; int16_t feedrate_percentage = 100, saved_feedrate_percentage; // Initialized by settings.load() bool axis_relative_modes[XYZE] = AXIS_RELATIVE_MODES; #if HAS_WORKSPACE_OFFSET #if HAS_POSITION_SHIFT // The distance that XYZ has been offset by G92. Reset by G28. float position_shift[XYZ] = { 0 }; #endif #if HAS_HOME_OFFSET // This offset is added to the configured home position. // Set by M206, M428, or menu item. Saved to EEPROM. float home_offset[XYZ] = { 0 }; #endif #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT // The above two are combined to save on computes float workspace_offset[XYZ] = { 0 }; #endif #endif // Software Endstops are based on the configured limits. float soft_endstop_min[XYZ] = { X_MIN_BED, Y_MIN_BED, Z_MIN_POS }, soft_endstop_max[XYZ] = { X_MAX_BED, Y_MAX_BED, Z_MAX_POS }; #if HAS_SOFTWARE_ENDSTOPS bool soft_endstops_enabled = true; #if IS_KINEMATIC float soft_endstop_radius, soft_endstop_radius_2; #endif #endif #if FAN_COUNT > 0 int16_t fanSpeeds[FAN_COUNT] = { 0 }; #if ENABLED(EXTRA_FAN_SPEED) int16_t old_fanSpeeds[FAN_COUNT], new_fanSpeeds[FAN_COUNT]; #endif #if ENABLED(PROBING_FANS_OFF) bool fans_paused; // = false; int16_t paused_fanSpeeds[FAN_COUNT] = { 0 }; #endif #endif #if ENABLED(USE_CONTROLLER_FAN) int controllerFanSpeed; // = 0; #endif // The active extruder (tool). Set with T<extruder> command. uint8_t active_extruder; // = 0; // Relative Mode. Enable with G91, disable with G90. static bool relative_mode; // = false; // For M109 and M190, this flag may be cleared (by M108) to exit the wait loop volatile bool wait_for_heatup = true; // Making sure this flag can be cleared by the Anycubic display volatile bool nozzle_timed_out = false; // For M0/M1, this flag may be cleared (by M108) to exit the wait-for-user loop #if HAS_RESUME_CONTINUE volatile bool wait_for_user; // = false; #endif #if HAS_AUTO_REPORTING || ENABLED(HOST_KEEPALIVE_FEATURE) bool suspend_auto_report; // = false #endif const char axis_codes[XYZE] = { 'X', 'Y', 'Z', 'E' }; #if ENABLED(HANGPRINTER) const char axis_codes_hangprinter[ABCDE] = { 'A', 'B', 'C', 'D', 'E' }; #define RAW_AXIS_CODES(I) axis_codes_hangprinter[I] #else #define RAW_AXIS_CODES(I) axis_codes[I] #endif // Number of characters read in the current line of serial input static int serial_count; // = 0; // Inactivity shutdown millis_t previous_move_ms; // = 0; static millis_t max_inactive_time; // = 0; static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000UL; // Buzzer - I2C on the LCD or a BEEPER_PIN #if ENABLED(LCD_USE_I2C_BUZZER) #define BUZZ(d,f) lcd_buzz(d, f) #elif PIN_EXISTS(BEEPER) Buzzer buzzer; #define BUZZ(d,f) buzzer.tone(d, f) #else #define BUZZ(d,f) NOOP #endif uint8_t target_extruder; #if HAS_BED_PROBE float zprobe_zoffset; // Initialized by settings.load() #endif #if HAS_ABL float xy_probe_feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED); #define XY_PROBE_FEEDRATE_MM_S xy_probe_feedrate_mm_s #elif defined(XY_PROBE_SPEED) #define XY_PROBE_FEEDRATE_MM_S MMM_TO_MMS(XY_PROBE_SPEED) #else #define XY_PROBE_FEEDRATE_MM_S PLANNER_XY_FEEDRATE() #endif #if ENABLED(AUTO_BED_LEVELING_BILINEAR) #if ENABLED(DELTA) #define ADJUST_DELTA(V) \ if (planner.leveling_active) { \ const float zadj = bilinear_z_offset(V); \ delta[A_AXIS] += zadj; \ delta[B_AXIS] += zadj; \ delta[C_AXIS] += zadj; \ } #else #define ADJUST_DELTA(V) if (planner.leveling_active) { delta[Z_AXIS] += bilinear_z_offset(V); } #endif #elif IS_KINEMATIC #define ADJUST_DELTA(V) NOOP #endif #if HAS_HEATED_BED && ENABLED(WAIT_FOR_BED_HEATER) const static char msg_wait_for_bed_heating[] PROGMEM = "Wait for bed heating...\n"; #endif // Extruder offsets #if HOTENDS > 1 float hotend_offset[XYZ][HOTENDS]; // Initialized by settings.load() #endif #if HAS_Z_SERVO_PROBE const int z_servo_angle[2] = Z_SERVO_ANGLES; #endif #if ENABLED(BARICUDA) uint8_t baricuda_valve_pressure = 0, baricuda_e_to_p_pressure = 0; #endif #if HAS_POWER_SWITCH bool powersupply_on; #if ENABLED(AUTO_POWER_CONTROL) #define PSU_ON() powerManager.power_on() #define PSU_OFF() powerManager.power_off() #else #define PSU_ON() PSU_PIN_ON() #define PSU_OFF() PSU_PIN_OFF() #endif #endif #if ENABLED(DELTA) float delta[ABC]; // Initialized by settings.load() float delta_height, delta_endstop_adj[ABC] = { 0 }, delta_radius, delta_tower_angle_trim[ABC], delta_tower[ABC][2], delta_diagonal_rod, delta_calibration_radius, delta_diagonal_rod_2_tower[ABC], delta_segments_per_second, delta_clip_start_height = Z_MAX_POS; float delta_safe_distance_from_top(); #elif ENABLED(HANGPRINTER) float anchor_A_y, anchor_A_z, anchor_B_x, anchor_B_y, anchor_B_z, anchor_C_x, anchor_C_y, anchor_C_z, anchor_D_z, line_lengths[ABCD], line_lengths_origin[ABCD], delta_segments_per_second; #endif #if ENABLED(AUTO_BED_LEVELING_BILINEAR) int bilinear_grid_spacing[2], bilinear_start[2]; float bilinear_grid_factor[2], z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y]; #if ENABLED(ABL_BILINEAR_SUBDIVISION) #define ABL_BG_SPACING(A) bilinear_grid_spacing_virt[A] #define ABL_BG_FACTOR(A) bilinear_grid_factor_virt[A] #define ABL_BG_POINTS_X ABL_GRID_POINTS_VIRT_X #define ABL_BG_POINTS_Y ABL_GRID_POINTS_VIRT_Y #define ABL_BG_GRID(X,Y) z_values_virt[X][Y] #else #define ABL_BG_SPACING(A) bilinear_grid_spacing[A] #define ABL_BG_FACTOR(A) bilinear_grid_factor[A] #define ABL_BG_POINTS_X GRID_MAX_POINTS_X #define ABL_BG_POINTS_Y GRID_MAX_POINTS_Y #define ABL_BG_GRID(X,Y) z_values[X][Y] #endif #endif #if IS_SCARA // Float constants for SCARA calculations const float L1 = SCARA_LINKAGE_1, L2 = SCARA_LINKAGE_2, L1_2 = sq(float(L1)), L1_2_2 = 2.0 * L1_2, L2_2 = sq(float(L2)); float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND, delta[ABC]; #endif float cartes[XYZ] = { 0 }; #if ENABLED(FILAMENT_WIDTH_SENSOR) bool filament_sensor; // = false; // M405 turns on filament sensor control. M406 turns it off. float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA, // Nominal filament width. Change with M404. filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; // Measured filament diameter uint8_t meas_delay_cm = MEASUREMENT_DELAY_CM; // Distance delay setting int8_t measurement_delay[MAX_MEASUREMENT_DELAY + 1], // Ring buffer to delayed measurement. Store extruder factor after subtracting 100 filwidth_delay_index[2] = { 0, -1 }; // Indexes into ring buffer #endif #if ENABLED(ADVANCED_PAUSE_FEATURE) AdvancedPauseMenuResponse advanced_pause_menu_response; float filament_change_unload_length[EXTRUDERS], filament_change_load_length[EXTRUDERS]; #endif #if ENABLED(MIXING_EXTRUDER) float mixing_factor[MIXING_STEPPERS]; // Reciprocal of mix proportion. 0.0 = off, otherwise >= 1.0. #if MIXING_VIRTUAL_TOOLS > 1 float mixing_virtual_tool_mix[MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS]; #endif #endif static bool send_ok[BUFSIZE]; #if HAS_SERVOS Servo servo[NUM_SERVOS]; #define MOVE_SERVO(I, P) servo[I].move(P) #if HAS_Z_SERVO_PROBE #define DEPLOY_Z_SERVO() MOVE_SERVO(Z_PROBE_SERVO_NR, z_servo_angle[0]) #define STOW_Z_SERVO() MOVE_SERVO(Z_PROBE_SERVO_NR, z_servo_angle[1]) #endif #endif #ifdef CHDK millis_t chdkHigh = 0; bool chdkActive = false; #endif #if ENABLED(HOST_KEEPALIVE_FEATURE) MarlinBusyState busy_state = NOT_BUSY; static millis_t next_busy_signal_ms = 0; uint8_t host_keepalive_interval = DEFAULT_KEEPALIVE_INTERVAL; #else #define host_keepalive() NOOP #endif #if ENABLED(I2C_POSITION_ENCODERS) I2CPositionEncodersMgr I2CPEM; #endif #if ENABLED(CNC_WORKSPACE_PLANES) static WorkspacePlane workspace_plane = PLANE_XY; #endif FORCE_INLINE float pgm_read_any(const float *p) { return pgm_read_float_near(p); } FORCE_INLINE signed char pgm_read_any(const signed char *p) { return pgm_read_byte_near(p); } #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \ static const PROGMEM type array##_P[XYZ] = { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \ static inline type array(const AxisEnum axis) { return pgm_read_any(&array##_P[axis]); } \ typedef void __void_##CONFIG##__ XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS); XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS); XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS); XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH); XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM); XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR); /** * *************************************************************************** * ******************************** FUNCTIONS ******************************** * *************************************************************************** */ void stop(); void get_available_commands(); void process_next_command(); void process_parsed_command(); void get_cartesian_from_steppers(); void set_current_from_steppers_for_axis(const AxisEnum axis); #if ENABLED(ARC_SUPPORT) void plan_arc(const float (&cart)[XYZE], const float (&offset)[2], const bool clockwise); #endif #if ENABLED(BEZIER_CURVE_SUPPORT) void plan_cubic_move(const float (&cart)[XYZE], const float (&offset)[4]); #endif void report_current_position(); void report_current_position_detail(); #if ENABLED(DEBUG_LEVELING_FEATURE) void print_xyz(const char* prefix, const char* suffix, const float x, const float y, const float z) { serialprintPGM(prefix); SERIAL_CHAR('('); SERIAL_ECHO(x); SERIAL_ECHOPAIR(", ", y); SERIAL_ECHOPAIR(", ", z); SERIAL_CHAR(')'); if (suffix) serialprintPGM(suffix); else SERIAL_EOL(); } void print_xyz(const char* prefix, const char* suffix, const float xyz[]) { print_xyz(prefix, suffix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]); } #define DEBUG_POS(SUFFIX,VAR) do { \ print_xyz(PSTR(" " STRINGIFY(VAR) "="), PSTR(" : " SUFFIX "\n"), VAR); }while(0) #endif /** * sync_plan_position * * Set the planner/stepper positions directly from current_position with * no kinematic translation. Used for homing axes and cartesian/core syncing. * * This is not possible for Hangprinter because current_position and position are different sizes */ void sync_plan_position() { #if DISABLED(HANGPRINTER) #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position", current_position); #endif planner.set_position_mm(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART]); #endif } void sync_plan_position_e() { planner.set_e_position_mm(current_position[E_CART]); } #if IS_KINEMATIC inline void sync_plan_position_kinematic() { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position_kinematic", current_position); #endif planner.set_position_mm_kinematic(current_position); } #endif #if ENABLED(SDSUPPORT) #include "SdFatUtil.h" int freeMemory() { return SdFatUtil::FreeRam(); } #else extern "C" { extern char __bss_end; extern char __heap_start; extern void* __brkval; int freeMemory() { int free_memory; if (int(__brkval) == 0) free_memory = (int(&free_memory)) - (int(&__bss_end)); else free_memory = (int(&free_memory)) - (int(__brkval)); return free_memory; } } #endif // !SDSUPPORT #if ENABLED(DIGIPOT_I2C) extern void digipot_i2c_set_current(uint8_t channel, float current); extern void digipot_i2c_init(); #endif /** * Inject the next "immediate" command, when possible, onto the front of the queue. * Return true if any immediate commands remain to inject. */ static bool drain_injected_commands_P() { if (injected_commands_P != NULL) { size_t i = 0; char c, cmd[30]; strncpy_P(cmd, injected_commands_P, sizeof(cmd) - 1); cmd[sizeof(cmd) - 1] = '\0'; while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command cmd[i] = '\0'; if (enqueue_and_echo_command(cmd)) // success? injected_commands_P = c ? injected_commands_P + i + 1 : NULL; // next command or done } return (injected_commands_P != NULL); // return whether any more remain } /** * Record one or many commands to run from program memory. * Aborts the current queue, if any. * Note: drain_injected_commands_P() must be called repeatedly to drain the commands afterwards */ void enqueue_and_echo_commands_P(const char * const pgcode) { injected_commands_P = pgcode; (void)drain_injected_commands_P(); // first command executed asap (when possible) } /** * Clear the Marlin command queue */ void clear_command_queue() { cmd_queue_index_r = cmd_queue_index_w = commands_in_queue = 0; } /** * Once a new command is in the ring buffer, call this to commit it */ inline void _commit_command(bool say_ok) { send_ok[cmd_queue_index_w] = say_ok; if (++cmd_queue_index_w >= BUFSIZE) cmd_queue_index_w = 0; commands_in_queue++; } /** * Copy a command from RAM into the main command buffer. * Return true if the command was successfully added. * Return false for a full buffer, or if the 'command' is a comment. */ inline bool _enqueuecommand(const char* cmd, bool say_ok=false) { if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false; strcpy(command_queue[cmd_queue_index_w], cmd); _commit_command(say_ok); return true; } /** * Enqueue with Serial Echo */ bool enqueue_and_echo_command(const char* cmd) { if (_enqueuecommand(cmd)) { SERIAL_ECHO_START(); SERIAL_ECHOPAIR(MSG_ENQUEUEING, cmd); SERIAL_CHAR('"'); SERIAL_EOL(); return true; } return false; } #if HAS_QUEUE_NOW void enqueue_and_echo_command_now(const char* cmd) { while (!enqueue_and_echo_command(cmd)) idle(); } #if HAS_LCD_QUEUE_NOW void enqueue_and_echo_commands_now_P(const char * const pgcode) { enqueue_and_echo_commands_P(pgcode); while (drain_injected_commands_P()) idle(); } #endif #endif void setup_killpin() { #if HAS_KILL SET_INPUT_PULLUP(KILL_PIN); #endif } void setup_powerhold() { #if HAS_SUICIDE OUT_WRITE(SUICIDE_PIN, HIGH); #endif #if HAS_POWER_SWITCH #if ENABLED(PS_DEFAULT_OFF) powersupply_on = true; PSU_OFF(); #else powersupply_on = false; PSU_ON(); #endif #endif } void suicide() { #if HAS_SUICIDE OUT_WRITE(SUICIDE_PIN, LOW); #endif } void servo_init() { #if NUM_SERVOS >= 1 && HAS_SERVO_0 servo[0].attach(SERVO0_PIN); servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position. #endif #if NUM_SERVOS >= 2 && HAS_SERVO_1 servo[1].attach(SERVO1_PIN); servo[1].detach(); #endif #if NUM_SERVOS >= 3 && HAS_SERVO_2 servo[2].attach(SERVO2_PIN); servo[2].detach(); #endif #if NUM_SERVOS >= 4 && HAS_SERVO_3 servo[3].attach(SERVO3_PIN); servo[3].detach(); #endif #if HAS_Z_SERVO_PROBE /** * Set position of Z Servo Endstop * * The servo might be deployed and positioned too low to stow * when starting up the machine or rebooting the board. * There's no way to know where the nozzle is positioned until * homing has been done - no homing with z-probe without init! * */ STOW_Z_SERVO(); #endif } /** * Stepper Reset (RigidBoard, et.al.) */ #if HAS_STEPPER_RESET void disableStepperDrivers() { OUT_WRITE(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips } void enableStepperDrivers() { SET_INPUT(STEPPER_RESET_PIN); } // set to input, which allows it to be pulled high by pullups #endif #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0 void i2c_on_receive(int bytes) { // just echo all bytes received to serial i2c.receive(bytes); } void i2c_on_request() { // just send dummy data for now i2c.reply("Hello World!\n"); } #endif void gcode_line_error(const char* err, bool doFlush = true) { SERIAL_ERROR_START(); serialprintPGM(err); SERIAL_ERRORLN(gcode_LastN); //Serial.println(gcode_N); if (doFlush) flush_and_request_resend(); serial_count = 0; } /** * Get all commands waiting on the serial port and queue them. * Exit when the buffer is full or when no more characters are * left on the serial port. */ inline void get_serial_commands() { static char serial_line_buffer[MAX_CMD_SIZE]; static bool serial_comment_mode = false; // If the command buffer is empty for too long, // send "wait" to indicate Marlin is still waiting. #if NO_TIMEOUTS > 0 static millis_t last_command_time = 0; const millis_t ms = millis(); if (commands_in_queue == 0 && !MYSERIAL0.available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) { SERIAL_ECHOLNPGM(MSG_WAIT); last_command_time = ms; } #endif /** * Loop while serial characters are incoming and the queue is not full */ int c; while (commands_in_queue < BUFSIZE && (c = MYSERIAL0.read()) >= 0) { char serial_char = c; /** * If the character ends the line */ if (serial_char == '\n' || serial_char == '\r') { serial_comment_mode = false; // end of line == end of comment // Skip empty lines and comments if (!serial_count) { thermalManager.manage_heater(); continue; } serial_line_buffer[serial_count] = 0; // Terminate string serial_count = 0; // Reset buffer char* command = serial_line_buffer; while (*command == ' ') command++; // Skip leading spaces char *npos = (*command == 'N') ? command : NULL; // Require the N parameter to start the line if (npos) { bool M110 = strstr_P(command, PSTR("M110")) != NULL; if (M110) { char* n2pos = strchr(command + 4, 'N'); if (n2pos) npos = n2pos; } gcode_N = strtol(npos + 1, NULL, 10); if (gcode_N != gcode_LastN + 1 && !M110) return gcode_line_error(PSTR(MSG_ERR_LINE_NO)); char *apos = strrchr(command, '*'); if (apos) { uint8_t checksum = 0, count = uint8_t(apos - command); while (count) checksum ^= command[--count]; if (strtol(apos + 1, NULL, 10) != checksum) return gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH)); } else return gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM)); gcode_LastN = gcode_N; } #if ENABLED(SDSUPPORT) else if (card.saving && strcmp(command, "M29") != 0) // No line number with M29 in Pronterface return gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM)); #endif // Movement commands alert when stopped if (IsStopped()) { char* gpos = strchr(command, 'G'); if (gpos) { switch (strtol(gpos + 1, NULL, 10)) { case 0: case 1: #if ENABLED(ARC_SUPPORT) case 2: case 3: #endif #if ENABLED(BEZIER_CURVE_SUPPORT) case 5: #endif SERIAL_ERRORLNPGM(MSG_ERR_STOPPED); LCD_MESSAGEPGM(MSG_STOPPED); break; } } } #if DISABLED(EMERGENCY_PARSER) // Process critical commands early if (strcmp(command, "M108") == 0) { wait_for_heatup = false; #if ENABLED(NEWPANEL) wait_for_user = false; #endif } if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED)); if (strcmp(command, "M410") == 0) quickstop_stepper(); #endif #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0 last_command_time = ms; #endif // Add the command to the queue _enqueuecommand(serial_line_buffer, true); } else if (serial_count >= MAX_CMD_SIZE - 1) { // Keep fetching, but ignore normal characters beyond the max length // The command will be injected when EOL is reached } else if (serial_char == '\\') { // Handle escapes if ((c = MYSERIAL0.read()) >= 0 && !serial_comment_mode) // if we have one more character, copy it over serial_line_buffer[serial_count++] = (char)c; // otherwise do nothing } else { // it's not a newline, carriage return or escape char if (serial_char == ';') serial_comment_mode = true; if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char; } } // queue has space, serial has data } #if ENABLED(SDSUPPORT) #if ENABLED(PRINTER_EVENT_LEDS) && HAS_RESUME_CONTINUE static bool lights_off_after_print; // = false #endif /** * Get commands from the SD Card until the command buffer is full * or until the end of the file is reached. The special character '#' * can also interrupt buffering. */ inline void get_sdcard_commands() { static bool stop_buffering = false, sd_comment_mode = false; if (!card.sdprinting) return; /** * '#' stops reading from SD to the buffer prematurely, so procedural * macro calls are possible. If it occurs, stop_buffering is triggered * and the buffer is run dry; this character _can_ occur in serial com * due to checksums, however, no checksums are used in SD printing. */ if (commands_in_queue == 0) stop_buffering = false; uint16_t sd_count = 0; bool card_eof = card.eof(); while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) { const int16_t n = card.get(); char sd_char = (char)n; card_eof = card.eof(); if (card_eof || n == -1 || sd_char == '\n' || sd_char == '\r' || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode) ) { if (card_eof) { card.printingHasFinished(); if (card.sdprinting) sd_count = 0; // If a sub-file was printing, continue from call point else { SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED); #if ENABLED(PRINTER_EVENT_LEDS) LCD_MESSAGEPGM(MSG_INFO_COMPLETED_PRINTS); leds.set_green(); #if HAS_RESUME_CONTINUE lights_off_after_print = true; enqueue_and_echo_commands_P(PSTR("M0 S" #if ENABLED(NEWPANEL) "1800" #else "60" #endif )); #else safe_delay(2000); leds.set_off(); #endif #endif // PRINTER_EVENT_LEDS } } else if (n == -1) { SERIAL_ERROR_START(); SERIAL_ECHOLNPGM(MSG_SD_ERR_READ); } if (sd_char == '#') stop_buffering = true; sd_comment_mode = false; // for new command // Skip empty lines and comments if (!sd_count) { thermalManager.manage_heater(); continue; } command_queue[cmd_queue_index_w][sd_count] = '\0'; // terminate string sd_count = 0; // clear sd line buffer _commit_command(false); } else if (sd_count >= MAX_CMD_SIZE - 1) { /** * Keep fetching, but ignore normal characters beyond the max length * The command will be injected when EOL is reached */ } else { if (sd_char == ';') sd_comment_mode = true; if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char; } } } #if ENABLED(POWER_LOSS_RECOVERY) inline bool drain_job_recovery_commands() { static uint8_t job_recovery_commands_index = 0; // Resets on reboot if (job_recovery_commands_count) { if (_enqueuecommand(job_recovery_commands[job_recovery_commands_index])) { ++job_recovery_commands_index; if (!--job_recovery_commands_count) job_recovery_phase = JOB_RECOVERY_DONE; } return true; } return false; } #endif #endif // SDSUPPORT /** * Add to the circular command queue the next command from: * - The command-injection queue (injected_commands_P) * - The active serial input (usually USB) * - Commands left in the queue after power-loss * - The SD card file being actively printed */ void get_available_commands() { // Immediate commands block the other queues if (drain_injected_commands_P()) return; get_serial_commands(); #if ENABLED(POWER_LOSS_RECOVERY) // Commands for power-loss recovery take precedence if (job_recovery_phase == JOB_RECOVERY_YES && drain_job_recovery_commands()) return; #endif #if ENABLED(SDSUPPORT) get_sdcard_commands(); #endif } /** * Set target_extruder from the T parameter or the active_extruder * * Returns TRUE if the target is invalid */ bool get_target_extruder_from_command(const uint16_t code) { if (parser.seenval('T')) { const int8_t e = parser.value_byte(); if (e >= EXTRUDERS) { SERIAL_ECHO_START(); SERIAL_CHAR('M'); SERIAL_ECHO(code); SERIAL_ECHOLNPAIR(" " MSG_INVALID_EXTRUDER " ", e); return true; } target_extruder = e; } else target_extruder = active_extruder; return false; } #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE) bool extruder_duplication_enabled = false; // Used in Dual X mode 2 #endif #if ENABLED(DUAL_X_CARRIAGE) static DualXMode dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE; static float x_home_pos(const int extruder) { if (extruder == 0) return base_home_pos(X_AXIS); else /** * In dual carriage mode the extruder offset provides an override of the * second X-carriage position when homed - otherwise X2_HOME_POS is used. * This allows soft recalibration of the second extruder home position * without firmware reflash (through the M218 command). */ return hotend_offset[X_AXIS][1] > 0 ? hotend_offset[X_AXIS][1] : X2_HOME_POS; } static int x_home_dir(const int extruder) { return extruder ? X2_HOME_DIR : X_HOME_DIR; } static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1 static bool active_extruder_parked = false; // used in mode 1 & 2 static float raised_parked_position[XYZE]; // used in mode 1 static millis_t delayed_move_time = 0; // used in mode 1 static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2 static int16_t duplicate_extruder_temp_offset = 0; // used in mode 2 #endif // DUAL_X_CARRIAGE #if HAS_WORKSPACE_OFFSET || ENABLED(DUAL_X_CARRIAGE) || ENABLED(DELTA) /** * Software endstops can be used to monitor the open end of * an axis that has a hardware endstop on the other end. Or * they can prevent axes from moving past endstops and grinding. * * To keep doing their job as the coordinate system changes, * the software endstop positions must be refreshed to remain * at the same positions relative to the machine. */ void update_software_endstops(const AxisEnum axis) { #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT workspace_offset[axis] = home_offset[axis] + position_shift[axis]; #endif #if ENABLED(DUAL_X_CARRIAGE) if (axis == X_AXIS) { // In Dual X mode hotend_offset[X] is T1's home position const float dual_max_x = MAX(hotend_offset[X_AXIS][1], X2_MAX_POS); if (active_extruder != 0) { // T1 can move from X2_MIN_POS to X2_MAX_POS or X2 home position (whichever is larger) soft_endstop_min[X_AXIS] = X2_MIN_POS; soft_endstop_max[X_AXIS] = dual_max_x; } else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) { // In Duplication Mode, T0 can move as far left as X_MIN_POS // but not so far to the right that T1 would move past the end soft_endstop_min[X_AXIS] = base_min_pos(X_AXIS); soft_endstop_max[X_AXIS] = MIN(base_max_pos(X_AXIS), dual_max_x - duplicate_extruder_x_offset); } else { // In other modes, T0 can move from X_MIN_POS to X_MAX_POS soft_endstop_min[axis] = base_min_pos(axis); soft_endstop_max[axis] = base_max_pos(axis); } } #elif ENABLED(DELTA) soft_endstop_min[axis] = base_min_pos(axis); soft_endstop_max[axis] = axis == Z_AXIS ? delta_height #if HAS_BED_PROBE - zprobe_zoffset #endif : base_max_pos(axis); #else soft_endstop_min[axis] = base_min_pos(axis); soft_endstop_max[axis] = base_max_pos(axis); #endif #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("For ", axis_codes[axis]); #if HAS_HOME_OFFSET SERIAL_ECHOPAIR(" axis:\n home_offset = ", home_offset[axis]); #endif #if HAS_POSITION_SHIFT SERIAL_ECHOPAIR("\n position_shift = ", position_shift[axis]); #endif SERIAL_ECHOPAIR("\n soft_endstop_min = ", soft_endstop_min[axis]); SERIAL_ECHOLNPAIR("\n soft_endstop_max = ", soft_endstop_max[axis]); } #endif #if ENABLED(DELTA) switch (axis) { #if HAS_SOFTWARE_ENDSTOPS case X_AXIS: case Y_AXIS: // Get a minimum radius for clamping soft_endstop_radius = MIN3(ABS(MAX(soft_endstop_min[X_AXIS], soft_endstop_min[Y_AXIS])), soft_endstop_max[X_AXIS], soft_endstop_max[Y_AXIS]); soft_endstop_radius_2 = sq(soft_endstop_radius); break; #endif case Z_AXIS: delta_clip_start_height = soft_endstop_max[axis] - delta_safe_distance_from_top(); default: break; } #endif } #endif // HAS_WORKSPACE_OFFSET || DUAL_X_CARRIAGE || DELTA #if HAS_M206_COMMAND /** * Change the home offset for an axis. * Also refreshes the workspace offset. */ static void set_home_offset(const AxisEnum axis, const float v) { home_offset[axis] = v; update_software_endstops(axis); } #endif // HAS_M206_COMMAND /** * Set an axis' current position to its home position (after homing). * * For Core and Cartesian robots this applies one-to-one when an * individual axis has been homed. * * DELTA should wait until all homing is done before setting the XYZ * current_position to home, because homing is a single operation. * In the case where the axis positions are already known and previously * homed, DELTA could home to X or Y individually by moving either one * to the center. However, homing Z always homes XY and Z. * * SCARA should wait until all XY homing is done before setting the XY * current_position to home, because neither X nor Y is at home until * both are at home. Z can however be homed individually. * * Callers must sync the planner position after calling this! */ static void set_axis_is_at_home(const AxisEnum axis) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR(">>> set_axis_is_at_home(", axis_codes[axis]); SERIAL_CHAR(')'); SERIAL_EOL(); } #endif SBI(axis_known_position, axis); SBI(axis_homed, axis); #if HAS_POSITION_SHIFT position_shift[axis] = 0; update_software_endstops(axis); #endif #if ENABLED(DUAL_X_CARRIAGE) if (axis == X_AXIS && (active_extruder == 1 || dual_x_carriage_mode == DXC_DUPLICATION_MODE)) { current_position[X_AXIS] = x_home_pos(active_extruder); return; } #endif #if ENABLED(MORGAN_SCARA) /** * Morgan SCARA homes XY at the same time */ if (axis == X_AXIS || axis == Y_AXIS) { float homeposition[XYZ] = { base_home_pos(X_AXIS), base_home_pos(Y_AXIS), base_home_pos(Z_AXIS) }; // SERIAL_ECHOPAIR("homeposition X:", homeposition[X_AXIS]); // SERIAL_ECHOLNPAIR(" Y:", homeposition[Y_AXIS]); /** * Get Home position SCARA arm angles using inverse kinematics, * and calculate homing offset using forward kinematics */ inverse_kinematics(homeposition); forward_kinematics_SCARA(delta[A_AXIS], delta[B_AXIS]); // SERIAL_ECHOPAIR("Cartesian X:", cartes[X_AXIS]); // SERIAL_ECHOLNPAIR(" Y:", cartes[Y_AXIS]); current_position[axis] = cartes[axis]; /** * SCARA home positions are based on configuration since the actual * limits are determined by the inverse kinematic transform. */ soft_endstop_min[axis] = base_min_pos(axis); // + (cartes[axis] - base_home_pos(axis)); soft_endstop_max[axis] = base_max_pos(axis); // + (cartes[axis] - base_home_pos(axis)); } else #elif ENABLED(DELTA) current_position[axis] = (axis == Z_AXIS ? delta_height #if HAS_BED_PROBE - zprobe_zoffset #endif : base_home_pos(axis)); #else current_position[axis] = base_home_pos(axis); #endif /** * Z Probe Z Homing? Account for the probe's Z offset. */ #if HAS_BED_PROBE && Z_HOME_DIR < 0 if (axis == Z_AXIS) { #if HOMING_Z_WITH_PROBE current_position[Z_AXIS] -= zprobe_zoffset; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOLNPGM("*** Z HOMED WITH PROBE (Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) ***"); SERIAL_ECHOLNPAIR("> zprobe_zoffset = ", zprobe_zoffset); } #endif #elif ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("*** Z HOMED TO ENDSTOP (Z_MIN_PROBE_ENDSTOP) ***"); #endif } #endif #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { #if HAS_HOME_OFFSET SERIAL_ECHOPAIR("> home_offset[", axis_codes[axis]); SERIAL_ECHOLNPAIR("] = ", home_offset[axis]); #endif DEBUG_POS("", current_position); SERIAL_ECHOPAIR("<<< set_axis_is_at_home(", axis_codes[axis]); SERIAL_CHAR(')'); SERIAL_EOL(); } #endif #if ENABLED(I2C_POSITION_ENCODERS) I2CPEM.homed(axis); #endif } /** * Homing bump feedrate (mm/s) */ inline float get_homing_bump_feedrate(const AxisEnum axis) { #if HOMING_Z_WITH_PROBE if (axis == Z_AXIS) return MMM_TO_MMS(Z_PROBE_SPEED_SLOW); #endif static const uint8_t homing_bump_divisor[] PROGMEM = HOMING_BUMP_DIVISOR; uint8_t hbd = pgm_read_byte(&homing_bump_divisor[axis]); if (hbd < 1) { hbd = 10; SERIAL_ECHO_START(); SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1"); } return homing_feedrate(axis) / hbd; } /** * Some planner shorthand inline functions */ /** * Move the planner to the current position from wherever it last moved * (or from wherever it has been told it is located). * * Impossible on Hangprinter because current_position and position are of different sizes */ inline void buffer_line_to_current_position() { #if DISABLED(HANGPRINTER) // emptying this function probably breaks do_blocking_move_to() planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART], feedrate_mm_s, active_extruder); #endif } /** * Move the planner to the position stored in the destination array, which is * used by G0/G1/G2/G3/G5 and many other functions to set a destination. */ inline void buffer_line_to_destination(const float &fr_mm_s) { #if ENABLED(HANGPRINTER) UNUSED(fr_mm_s); #else planner.buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_CART], fr_mm_s, active_extruder); #endif } #if IS_KINEMATIC /** * Calculate delta, start a line, and set current_position to destination */ void prepare_uninterpolated_move_to_destination(const float fr_mm_s=0) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("prepare_uninterpolated_move_to_destination", destination); #endif #if UBL_SEGMENTED // ubl segmented line will do z-only moves in single segment ubl.prepare_segmented_line_to(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s)); #else if ( current_position[X_AXIS] == destination[X_AXIS] && current_position[Y_AXIS] == destination[Y_AXIS] && current_position[Z_AXIS] == destination[Z_AXIS] && current_position[E_CART] == destination[E_CART] ) return; planner.buffer_line_kinematic(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s), active_extruder); #endif set_current_from_destination(); } #endif // IS_KINEMATIC /** * Plan a move to (X, Y, Z) and set the current_position. * The final current_position may not be the one that was requested * Caution: 'destination' is modified by this function. */ void do_blocking_move_to(const float rx, const float ry, const float rz, const float &fr_mm_s/*=0.0*/) { const float old_feedrate_mm_s = feedrate_mm_s; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) print_xyz(PSTR(">>> do_blocking_move_to"), NULL, LOGICAL_X_POSITION(rx), LOGICAL_Y_POSITION(ry), LOGICAL_Z_POSITION(rz)); #endif const float z_feedrate = fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS); #if ENABLED(DELTA) if (!position_is_reachable(rx, ry)) return; feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S; set_destination_from_current(); // sync destination at the start #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("set_destination_from_current", destination); #endif // when in the danger zone if (current_position[Z_AXIS] > delta_clip_start_height) { if (rz > delta_clip_start_height) { // staying in the danger zone destination[X_AXIS] = rx; // move directly (uninterpolated) destination[Y_AXIS] = ry; destination[Z_AXIS] = rz; prepare_uninterpolated_move_to_destination(); // set_current_from_destination #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("danger zone move", current_position); #endif return; } destination[Z_AXIS] = delta_clip_start_height; prepare_uninterpolated_move_to_destination(); // set_current_from_destination #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("zone border move", current_position); #endif } if (rz > current_position[Z_AXIS]) { // raising? destination[Z_AXIS] = rz; prepare_uninterpolated_move_to_destination(z_feedrate); // set_current_from_destination #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("z raise move", current_position); #endif } destination[X_AXIS] = rx; destination[Y_AXIS] = ry; prepare_move_to_destination(); // set_current_from_destination #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("xy move", current_position); #endif if (rz < current_position[Z_AXIS]) { // lowering? destination[Z_AXIS] = rz; prepare_uninterpolated_move_to_destination(z_feedrate); // set_current_from_destination #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("z lower move", current_position); #endif } #elif IS_SCARA if (!position_is_reachable(rx, ry)) return; set_destination_from_current(); // If Z needs to raise, do it before moving XY if (destination[Z_AXIS] < rz) { destination[Z_AXIS] = rz; prepare_uninterpolated_move_to_destination(z_feedrate); } destination[X_AXIS] = rx; destination[Y_AXIS] = ry; prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S); // If Z needs to lower, do it after moving XY if (destination[Z_AXIS] > rz) { destination[Z_AXIS] = rz; prepare_uninterpolated_move_to_destination(z_feedrate); } #else // If Z needs to raise, do it before moving XY if (current_position[Z_AXIS] < rz) { feedrate_mm_s = z_feedrate; current_position[Z_AXIS] = rz; buffer_line_to_current_position(); } feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S; current_position[X_AXIS] = rx; current_position[Y_AXIS] = ry; buffer_line_to_current_position(); // If Z needs to lower, do it after moving XY if (current_position[Z_AXIS] > rz) { feedrate_mm_s = z_feedrate; current_position[Z_AXIS] = rz; buffer_line_to_current_position(); } #endif planner.synchronize(); feedrate_mm_s = old_feedrate_mm_s; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< do_blocking_move_to"); #endif } void do_blocking_move_to_x(const float &rx, const float &fr_mm_s/*=0.0*/) { do_blocking_move_to(rx, current_position[Y_AXIS], current_position[Z_AXIS], fr_mm_s); } void do_blocking_move_to_z(const float &rz, const float &fr_mm_s/*=0.0*/) { do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], rz, fr_mm_s); } void do_blocking_move_to_xy(const float &rx, const float &ry, const float &fr_mm_s/*=0.0*/) { do_blocking_move_to(rx, ry, current_position[Z_AXIS], fr_mm_s); } // // Prepare to do endstop or probe moves // with custom feedrates. // // - Save current feedrates // - Reset the rate multiplier // - Reset the command timeout // - Enable the endstops (for endstop moves) // void setup_for_endstop_or_probe_move() { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("setup_for_endstop_or_probe_move", current_position); #endif saved_feedrate_mm_s = feedrate_mm_s; saved_feedrate_percentage = feedrate_percentage; feedrate_percentage = 100; } void clean_up_after_endstop_or_probe_move() { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("clean_up_after_endstop_or_probe_move", current_position); #endif feedrate_mm_s = saved_feedrate_mm_s; feedrate_percentage = saved_feedrate_percentage; } #if HAS_AXIS_UNHOMED_ERR bool axis_unhomed_error(const bool x/*=true*/, const bool y/*=true*/, const bool z/*=true*/) { #if ENABLED(HOME_AFTER_DEACTIVATE) const bool xx = x && !TEST(axis_known_position, X_AXIS), yy = y && !TEST(axis_known_position, Y_AXIS), zz = z && !TEST(axis_known_position, Z_AXIS); #else const bool xx = x && !TEST(axis_homed, X_AXIS), yy = y && !TEST(axis_homed, Y_AXIS), zz = z && !TEST(axis_homed, Z_AXIS); #endif if (xx || yy || zz) { SERIAL_ECHO_START(); SERIAL_ECHOPGM(MSG_HOME " "); if (xx) SERIAL_ECHOPGM(MSG_X); if (yy) SERIAL_ECHOPGM(MSG_Y); if (zz) SERIAL_ECHOPGM(MSG_Z); SERIAL_ECHOLNPGM(" " MSG_FIRST); #if ENABLED(ULTRA_LCD) lcd_status_printf_P(0, PSTR(MSG_HOME " %s%s%s " MSG_FIRST), xx ? MSG_X : "", yy ? MSG_Y : "", zz ? MSG_Z : ""); #endif return true; } return false; } #endif // HAS_AXIS_UNHOMED_ERR #if ENABLED(Z_PROBE_SLED) #ifndef SLED_DOCKING_OFFSET #define SLED_DOCKING_OFFSET 0 #endif /** * Method to dock/undock a sled designed by Charles Bell. * * stow[in] If false, move to MAX_X and engage the solenoid * If true, move to MAX_X and release the solenoid */ static void dock_sled(bool stow) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("dock_sled(", stow); SERIAL_CHAR(')'); SERIAL_EOL(); } #endif // Dock sled a bit closer to ensure proper capturing do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET - ((stow) ? 1 : 0)); #if HAS_SOLENOID_1 && DISABLED(EXT_SOLENOID) WRITE(SOL1_PIN, !stow); // switch solenoid #endif } #elif ENABLED(Z_PROBE_ALLEN_KEY) FORCE_INLINE void do_blocking_move_to(const float (&raw)[XYZ], const float &fr_mm_s) { do_blocking_move_to(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS], fr_mm_s); } void run_deploy_moves_script() { #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_Z) #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_X #define Z_PROBE_ALLEN_KEY_DEPLOY_1_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Y #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Z #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE #define Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE 0.0 #endif const float deploy_1[] = { Z_PROBE_ALLEN_KEY_DEPLOY_1_X, Z_PROBE_ALLEN_KEY_DEPLOY_1_Y, Z_PROBE_ALLEN_KEY_DEPLOY_1_Z }; do_blocking_move_to(deploy_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE)); #endif #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_Z) #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_X #define Z_PROBE_ALLEN_KEY_DEPLOY_2_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Y #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Z #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE #define Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE 0.0 #endif const float deploy_2[] = { Z_PROBE_ALLEN_KEY_DEPLOY_2_X, Z_PROBE_ALLEN_KEY_DEPLOY_2_Y, Z_PROBE_ALLEN_KEY_DEPLOY_2_Z }; do_blocking_move_to(deploy_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE)); #endif #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_Z) #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_X #define Z_PROBE_ALLEN_KEY_DEPLOY_3_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Y #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Z #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE #define Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE 0.0 #endif const float deploy_3[] = { Z_PROBE_ALLEN_KEY_DEPLOY_3_X, Z_PROBE_ALLEN_KEY_DEPLOY_3_Y, Z_PROBE_ALLEN_KEY_DEPLOY_3_Z }; do_blocking_move_to(deploy_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE)); #endif #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_Z) #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_X #define Z_PROBE_ALLEN_KEY_DEPLOY_4_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Y #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Z #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE #define Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE 0.0 #endif const float deploy_4[] = { Z_PROBE_ALLEN_KEY_DEPLOY_4_X, Z_PROBE_ALLEN_KEY_DEPLOY_4_Y, Z_PROBE_ALLEN_KEY_DEPLOY_4_Z }; do_blocking_move_to(deploy_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE)); #endif #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_Z) #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_X #define Z_PROBE_ALLEN_KEY_DEPLOY_5_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Y #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Z #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE #define Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE 0.0 #endif const float deploy_5[] = { Z_PROBE_ALLEN_KEY_DEPLOY_5_X, Z_PROBE_ALLEN_KEY_DEPLOY_5_Y, Z_PROBE_ALLEN_KEY_DEPLOY_5_Z }; do_blocking_move_to(deploy_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE)); #endif } void run_stow_moves_script() { #if defined(Z_PROBE_ALLEN_KEY_STOW_1_X) || defined(Z_PROBE_ALLEN_KEY_STOW_1_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_1_Z) #ifndef Z_PROBE_ALLEN_KEY_STOW_1_X #define Z_PROBE_ALLEN_KEY_STOW_1_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Y #define Z_PROBE_ALLEN_KEY_STOW_1_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Z #define Z_PROBE_ALLEN_KEY_STOW_1_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE #define Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE 0.0 #endif const float stow_1[] = { Z_PROBE_ALLEN_KEY_STOW_1_X, Z_PROBE_ALLEN_KEY_STOW_1_Y, Z_PROBE_ALLEN_KEY_STOW_1_Z }; do_blocking_move_to(stow_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE)); #endif #if defined(Z_PROBE_ALLEN_KEY_STOW_2_X) || defined(Z_PROBE_ALLEN_KEY_STOW_2_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_2_Z) #ifndef Z_PROBE_ALLEN_KEY_STOW_2_X #define Z_PROBE_ALLEN_KEY_STOW_2_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Y #define Z_PROBE_ALLEN_KEY_STOW_2_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Z #define Z_PROBE_ALLEN_KEY_STOW_2_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE #define Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE 0.0 #endif const float stow_2[] = { Z_PROBE_ALLEN_KEY_STOW_2_X, Z_PROBE_ALLEN_KEY_STOW_2_Y, Z_PROBE_ALLEN_KEY_STOW_2_Z }; do_blocking_move_to(stow_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE)); #endif #if defined(Z_PROBE_ALLEN_KEY_STOW_3_X) || defined(Z_PROBE_ALLEN_KEY_STOW_3_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_3_Z) #ifndef Z_PROBE_ALLEN_KEY_STOW_3_X #define Z_PROBE_ALLEN_KEY_STOW_3_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Y #define Z_PROBE_ALLEN_KEY_STOW_3_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Z #define Z_PROBE_ALLEN_KEY_STOW_3_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE #define Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE 0.0 #endif const float stow_3[] = { Z_PROBE_ALLEN_KEY_STOW_3_X, Z_PROBE_ALLEN_KEY_STOW_3_Y, Z_PROBE_ALLEN_KEY_STOW_3_Z }; do_blocking_move_to(stow_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE)); #endif #if defined(Z_PROBE_ALLEN_KEY_STOW_4_X) || defined(Z_PROBE_ALLEN_KEY_STOW_4_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_4_Z) #ifndef Z_PROBE_ALLEN_KEY_STOW_4_X #define Z_PROBE_ALLEN_KEY_STOW_4_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Y #define Z_PROBE_ALLEN_KEY_STOW_4_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Z #define Z_PROBE_ALLEN_KEY_STOW_4_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE #define Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE 0.0 #endif const float stow_4[] = { Z_PROBE_ALLEN_KEY_STOW_4_X, Z_PROBE_ALLEN_KEY_STOW_4_Y, Z_PROBE_ALLEN_KEY_STOW_4_Z }; do_blocking_move_to(stow_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE)); #endif #if defined(Z_PROBE_ALLEN_KEY_STOW_5_X) || defined(Z_PROBE_ALLEN_KEY_STOW_5_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_5_Z) #ifndef Z_PROBE_ALLEN_KEY_STOW_5_X #define Z_PROBE_ALLEN_KEY_STOW_5_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Y #define Z_PROBE_ALLEN_KEY_STOW_5_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Z #define Z_PROBE_ALLEN_KEY_STOW_5_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE #define Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE 0.0 #endif const float stow_5[] = { Z_PROBE_ALLEN_KEY_STOW_5_X, Z_PROBE_ALLEN_KEY_STOW_5_Y, Z_PROBE_ALLEN_KEY_STOW_5_Z }; do_blocking_move_to(stow_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE)); #endif } #endif // Z_PROBE_ALLEN_KEY #if ENABLED(PROBING_FANS_OFF) void fans_pause(const bool p) { if (p != fans_paused) { fans_paused = p; if (p) for (uint8_t x = 0; x < FAN_COUNT; x++) { paused_fanSpeeds[x] = fanSpeeds[x]; fanSpeeds[x] = 0; } else for (uint8_t x = 0; x < FAN_COUNT; x++) fanSpeeds[x] = paused_fanSpeeds[x]; } } #endif // PROBING_FANS_OFF #if HAS_BED_PROBE // TRIGGERED_WHEN_STOWED_TEST can easily be extended to servo probes, ... if needed. #if ENABLED(PROBE_IS_TRIGGERED_WHEN_STOWED_TEST) #if ENABLED(Z_MIN_PROBE_ENDSTOP) #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING) #else #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING) #endif #endif #if QUIET_PROBING void probing_pause(const bool p) { #if ENABLED(PROBING_HEATERS_OFF) thermalManager.pause(p); #endif #if ENABLED(PROBING_FANS_OFF) fans_pause(p); #endif if (p) safe_delay( #if DELAY_BEFORE_PROBING > 25 DELAY_BEFORE_PROBING #else 25 #endif ); } #endif // QUIET_PROBING #if ENABLED(BLTOUCH) void bltouch_command(int angle) { MOVE_SERVO(Z_PROBE_SERVO_NR, angle); // Give the BL-Touch the command and wait safe_delay(BLTOUCH_DELAY); } bool set_bltouch_deployed(const bool deploy) { if (deploy && TEST_BLTOUCH()) { // If BL-Touch says it's triggered bltouch_command(BLTOUCH_RESET); // try to reset it. bltouch_command(BLTOUCH_DEPLOY); // Also needs to deploy and stow to bltouch_command(BLTOUCH_STOW); // clear the triggered condition. safe_delay(1500); // Wait for internal self-test to complete. // (Measured completion time was 0.65 seconds // after reset, deploy, and stow sequence) if (TEST_BLTOUCH()) { // If it still claims to be triggered... SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_STOP_BLTOUCH); stop(); // punt! return true; } } bltouch_command(deploy ? BLTOUCH_DEPLOY : BLTOUCH_STOW); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("set_bltouch_deployed(", deploy); SERIAL_CHAR(')'); SERIAL_EOL(); } #endif return false; } #endif // BLTOUCH /** * Raise Z to a minimum height to make room for a probe to move */ inline void do_probe_raise(const float z_raise) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("do_probe_raise(", z_raise); SERIAL_CHAR(')'); SERIAL_EOL(); } #endif float z_dest = z_raise; if (zprobe_zoffset < 0) z_dest -= zprobe_zoffset; NOMORE(z_dest, Z_MAX_POS); if (z_dest > current_position[Z_AXIS]) do_blocking_move_to_z(z_dest); } // returns false for ok and true for failure bool set_probe_deployed(const bool deploy) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { DEBUG_POS("set_probe_deployed", current_position); SERIAL_ECHOLNPAIR("deploy: ", deploy); } #endif if (endstops.z_probe_enabled == deploy) return false; // Make room for probe to deploy (or stow) // Fix-mounted probe should only raise for deploy #if ENABLED(FIX_MOUNTED_PROBE) const bool deploy_stow_condition = deploy; #else constexpr bool deploy_stow_condition = true; #endif // For beds that fall when Z is powered off only raise for trusted Z #if ENABLED(UNKNOWN_Z_NO_RAISE) const bool unknown_condition = TEST(axis_known_position, Z_AXIS); #else constexpr float unknown_condition = true; #endif if (deploy_stow_condition && unknown_condition) do_probe_raise(MAX(Z_CLEARANCE_BETWEEN_PROBES, Z_CLEARANCE_DEPLOY_PROBE)); #if ENABLED(Z_PROBE_SLED) || ENABLED(Z_PROBE_ALLEN_KEY) #if ENABLED(Z_PROBE_SLED) #define _AUE_ARGS true, false, false #else #define _AUE_ARGS #endif if (axis_unhomed_error(_AUE_ARGS)) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_STOP_UNHOMED); stop(); return true; } #endif const float oldXpos = current_position[X_AXIS], oldYpos = current_position[Y_AXIS]; #ifdef _TRIGGERED_WHEN_STOWED_TEST // If endstop is already false, the Z probe is deployed if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // closed after the probe specific actions. // Would a goto be less ugly? //while (!_TRIGGERED_WHEN_STOWED_TEST) idle(); // would offer the opportunity // for a triggered when stowed manual probe. if (!deploy) endstops.enable_z_probe(false); // Switch off triggered when stowed probes early // otherwise an Allen-Key probe can't be stowed. #endif #if ENABLED(SOLENOID_PROBE) #if HAS_SOLENOID_1 WRITE(SOL1_PIN, deploy); #endif #elif ENABLED(Z_PROBE_SLED) dock_sled(!deploy); #elif HAS_Z_SERVO_PROBE && DISABLED(BLTOUCH) MOVE_SERVO(Z_PROBE_SERVO_NR, z_servo_angle[deploy ? 0 : 1]); #elif ENABLED(Z_PROBE_ALLEN_KEY) deploy ? run_deploy_moves_script() : run_stow_moves_script(); #endif #ifdef _TRIGGERED_WHEN_STOWED_TEST } // _TRIGGERED_WHEN_STOWED_TEST == deploy if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // State hasn't changed? if (IsRunning()) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM("Z-Probe failed"); LCD_ALERTMESSAGEPGM("Err: ZPROBE"); } stop(); return true; } // _TRIGGERED_WHEN_STOWED_TEST == deploy #endif do_blocking_move_to(oldXpos, oldYpos, current_position[Z_AXIS]); // return to position before deploy endstops.enable_z_probe(deploy); return false; } /** * @brief Used by run_z_probe to do a single Z probe move. * * @param z Z destination * @param fr_mm_s Feedrate in mm/s * @return true to indicate an error */ static bool do_probe_move(const float z, const float fr_mm_s) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS(">>> do_probe_move", current_position); #endif #if HAS_HEATED_BED && ENABLED(WAIT_FOR_BED_HEATER) // Wait for bed to heat back up between probing points if (thermalManager.isHeatingBed()) { serialprintPGM(msg_wait_for_bed_heating); LCD_MESSAGEPGM(MSG_BED_HEATING); while (thermalManager.isHeatingBed()) safe_delay(200); lcd_reset_status(); } #endif // Deploy BLTouch at the start of any probe #if ENABLED(BLTOUCH) if (set_bltouch_deployed(true)) return true; #endif #if QUIET_PROBING probing_pause(true); #endif // Move down until probe triggered do_blocking_move_to_z(z, fr_mm_s); // Check to see if the probe was triggered const bool probe_triggered = TEST(endstops.trigger_state(), #if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) Z_MIN #else Z_MIN_PROBE #endif ); #if QUIET_PROBING probing_pause(false); #endif // Retract BLTouch immediately after a probe if it was triggered #if ENABLED(BLTOUCH) if (probe_triggered && set_bltouch_deployed(false)) return true; #endif endstops.hit_on_purpose(); // Get Z where the steppers were interrupted set_current_from_steppers_for_axis(Z_AXIS); // Tell the planner where we actually are SYNC_PLAN_POSITION_KINEMATIC(); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("<<< do_probe_move", current_position); #endif return !probe_triggered; } /** * @details Used by probe_pt to do a single Z probe at the current position. * Leaves current_position[Z_AXIS] at the height where the probe triggered. * * @return The raw Z position where the probe was triggered */ static float run_z_probe() { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS(">>> run_z_probe", current_position); #endif // Stop the probe before it goes too low to prevent damage. // If Z isn't known then probe to -10mm. const float z_probe_low_point = TEST(axis_known_position, Z_AXIS) ? -zprobe_zoffset + Z_PROBE_LOW_POINT : -10.0; // Double-probing does a fast probe followed by a slow probe #if MULTIPLE_PROBING == 2 // Do a first probe at the fast speed if (do_probe_move(z_probe_low_point, MMM_TO_MMS(Z_PROBE_SPEED_FAST))) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOLNPGM("FAST Probe fail!"); DEBUG_POS("<<< run_z_probe", current_position); } #endif return NAN; } float first_probe_z = current_position[Z_AXIS]; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("1st Probe Z:", first_probe_z); #endif // move up to make clearance for the probe do_blocking_move_to_z(current_position[Z_AXIS] + Z_CLEARANCE_MULTI_PROBE, MMM_TO_MMS(Z_PROBE_SPEED_FAST)); #else // If the nozzle is well over the travel height then // move down quickly before doing the slow probe float z = Z_CLEARANCE_DEPLOY_PROBE + 5.0; if (zprobe_zoffset < 0) z -= zprobe_zoffset; if (current_position[Z_AXIS] > z) { // If we don't make it to the z position (i.e. the probe triggered), move up to make clearance for the probe if (!do_probe_move(z, MMM_TO_MMS(Z_PROBE_SPEED_FAST))) do_blocking_move_to_z(current_position[Z_AXIS] + Z_CLEARANCE_BETWEEN_PROBES, MMM_TO_MMS(Z_PROBE_SPEED_FAST)); } #endif #if MULTIPLE_PROBING > 2 float probes_total = 0; for (uint8_t p = MULTIPLE_PROBING + 1; --p;) { #endif // move down slowly to find bed if (do_probe_move(z_probe_low_point, MMM_TO_MMS(Z_PROBE_SPEED_SLOW))) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOLNPGM("SLOW Probe fail!"); DEBUG_POS("<<< run_z_probe", current_position); } #endif return NAN; } #if MULTIPLE_PROBING > 2 probes_total += current_position[Z_AXIS]; if (p > 1) do_blocking_move_to_z(current_position[Z_AXIS] + Z_CLEARANCE_MULTI_PROBE, MMM_TO_MMS(Z_PROBE_SPEED_FAST)); } #endif #if MULTIPLE_PROBING > 2 // Return the average value of all probes const float measured_z = probes_total * (1.0f / (MULTIPLE_PROBING)); #elif MULTIPLE_PROBING == 2 const float z2 = current_position[Z_AXIS]; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("2nd Probe Z:", z2); SERIAL_ECHOLNPAIR(" Discrepancy:", first_probe_z - z2); } #endif // Return a weighted average of the fast and slow probes const float measured_z = (z2 * 3.0 + first_probe_z * 2.0) * 0.2; #else // Return the single probe result const float measured_z = current_position[Z_AXIS]; #endif #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("<<< run_z_probe", current_position); #endif return measured_z; } /** * - Move to the given XY * - Deploy the probe, if not already deployed * - Probe the bed, get the Z position * - Depending on the 'stow' flag * - Stow the probe, or * - Raise to the BETWEEN height * - Return the probed Z position */ float probe_pt(const float &rx, const float &ry, const ProbePtRaise raise_after/*=PROBE_PT_NONE*/, const uint8_t verbose_level/*=0*/, const bool probe_relative/*=true*/) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR(">>> probe_pt(", LOGICAL_X_POSITION(rx)); SERIAL_ECHOPAIR(", ", LOGICAL_Y_POSITION(ry)); SERIAL_ECHOPAIR(", ", raise_after == PROBE_PT_RAISE ? "raise" : raise_after == PROBE_PT_STOW ? "stow" : "none"); SERIAL_ECHOPAIR(", ", int(verbose_level)); SERIAL_ECHOPAIR(", ", probe_relative ? "probe" : "nozzle"); SERIAL_ECHOLNPGM("_relative)"); DEBUG_POS("", current_position); } #endif // TODO: Adapt for SCARA, where the offset rotates float nx = rx, ny = ry; if (probe_relative) { if (!position_is_reachable_by_probe(rx, ry)) return NAN; // The given position is in terms of the probe nx -= (X_PROBE_OFFSET_FROM_EXTRUDER); // Get the nozzle position ny -= (Y_PROBE_OFFSET_FROM_EXTRUDER); } else if (!position_is_reachable(nx, ny)) return NAN; // The given position is in terms of the nozzle const float nz = #if ENABLED(DELTA) // Move below clip height or xy move will be aborted by do_blocking_move_to MIN(current_position[Z_AXIS], delta_clip_start_height) #else current_position[Z_AXIS] #endif ; const float old_feedrate_mm_s = feedrate_mm_s; feedrate_mm_s = XY_PROBE_FEEDRATE_MM_S; // Move the probe to the starting XYZ do_blocking_move_to(nx, ny, nz); float measured_z = NAN; if (!DEPLOY_PROBE()) { measured_z = run_z_probe() + zprobe_zoffset; const bool big_raise = raise_after == PROBE_PT_BIG_RAISE; if (big_raise || raise_after == PROBE_PT_RAISE) do_blocking_move_to_z(current_position[Z_AXIS] + (big_raise ? 25 : Z_CLEARANCE_BETWEEN_PROBES), MMM_TO_MMS(Z_PROBE_SPEED_FAST)); else if (raise_after == PROBE_PT_STOW) if (STOW_PROBE()) measured_z = NAN; } if (verbose_level > 2) { SERIAL_PROTOCOLPGM("Bed X: "); SERIAL_PROTOCOL_F(LOGICAL_X_POSITION(rx), 3); SERIAL_PROTOCOLPGM(" Y: "); SERIAL_PROTOCOL_F(LOGICAL_Y_POSITION(ry), 3); SERIAL_PROTOCOLPGM(" Z: "); SERIAL_PROTOCOL_F(measured_z, 3); SERIAL_EOL(); } feedrate_mm_s = old_feedrate_mm_s; if (isnan(measured_z)) { LCD_MESSAGEPGM(MSG_ERR_PROBING_FAILED); SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_PROBING_FAILED); } #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< probe_pt"); #endif return measured_z; } #endif // HAS_BED_PROBE #if HAS_LEVELING bool leveling_is_valid() { return #if ENABLED(MESH_BED_LEVELING) mbl.has_mesh() #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) !!bilinear_grid_spacing[X_AXIS] #elif ENABLED(AUTO_BED_LEVELING_UBL) ubl.mesh_is_valid() #else // 3POINT, LINEAR true #endif ; } /** * Turn bed leveling on or off, fixing the current * position as-needed. * * Disable: Current position = physical position * Enable: Current position = "unleveled" physical position */ void set_bed_leveling_enabled(const bool enable/*=true*/) { #if ENABLED(AUTO_BED_LEVELING_BILINEAR) const bool can_change = (!enable || leveling_is_valid()); #else constexpr bool can_change = true; #endif if (can_change && enable != planner.leveling_active) { planner.synchronize(); #if ENABLED(MESH_BED_LEVELING) if (!enable) planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]); const bool enabling = enable && leveling_is_valid(); planner.leveling_active = enabling; if (enabling) planner.unapply_leveling(current_position); #elif ENABLED(AUTO_BED_LEVELING_UBL) #if PLANNER_LEVELING if (planner.leveling_active) { // leveling from on to off // change unleveled current_position to physical current_position without moving steppers. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]); planner.leveling_active = false; // disable only AFTER calling apply_leveling } else { // leveling from off to on planner.leveling_active = true; // enable BEFORE calling unapply_leveling, otherwise ignored // change physical current_position to unleveled current_position without moving steppers. planner.unapply_leveling(current_position); } #else // UBL equivalents for apply/unapply_leveling #if ENABLED(SKEW_CORRECTION) float pos[XYZ] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] }; planner.skew(pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS]); #else const float (&pos)[XYZE] = current_position; #endif if (planner.leveling_active) { current_position[Z_AXIS] += ubl.get_z_correction(pos[X_AXIS], pos[Y_AXIS]); planner.leveling_active = false; } else { planner.leveling_active = true; current_position[Z_AXIS] -= ubl.get_z_correction(pos[X_AXIS], pos[Y_AXIS]); } #endif #else // ABL #if ENABLED(AUTO_BED_LEVELING_BILINEAR) // Force bilinear_z_offset to re-calculate next time const float reset[XYZ] = { -9999.999, -9999.999, 0 }; (void)bilinear_z_offset(reset); #endif // Enable or disable leveling compensation in the planner planner.leveling_active = enable; if (!enable) // When disabling just get the current position from the steppers. // This will yield the smallest error when first converted back to steps. set_current_from_steppers_for_axis( #if ABL_PLANAR ALL_AXES #else Z_AXIS #endif ); else // When enabling, remove compensation from the current position, // so compensation will give the right stepper counts. planner.unapply_leveling(current_position); SYNC_PLAN_POSITION_KINEMATIC(); #endif // ABL } } #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) void set_z_fade_height(const float zfh, const bool do_report/*=true*/) { if (planner.z_fade_height == zfh) return; const bool leveling_was_active = planner.leveling_active; set_bed_leveling_enabled(false); planner.set_z_fade_height(zfh); if (leveling_was_active) { const float oldpos[] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] }; set_bed_leveling_enabled(true); if (do_report && memcmp(oldpos, current_position, sizeof(oldpos))) report_current_position(); } } #endif // LEVELING_FADE_HEIGHT /** * Reset calibration results to zero. */ void reset_bed_level() { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("reset_bed_level"); #endif set_bed_leveling_enabled(false); #if ENABLED(MESH_BED_LEVELING) mbl.reset(); #elif ENABLED(AUTO_BED_LEVELING_UBL) ubl.reset(); #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) bilinear_start[X_AXIS] = bilinear_start[Y_AXIS] = bilinear_grid_spacing[X_AXIS] = bilinear_grid_spacing[Y_AXIS] = 0; for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++) for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++) z_values[x][y] = NAN; #elif ABL_PLANAR planner.bed_level_matrix.set_to_identity(); #endif } #endif // HAS_LEVELING #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(MESH_BED_LEVELING) /** * Enable to produce output in JSON format suitable * for SCAD or JavaScript mesh visualizers. * * Visualize meshes in OpenSCAD using the included script. * * buildroot/shared/scripts/MarlinMesh.scad */ //#define SCAD_MESH_OUTPUT /** * Print calibration results for plotting or manual frame adjustment. */ void print_2d_array(const uint8_t sx, const uint8_t sy, const uint8_t precision, const element_2d_fn fn) { #ifndef SCAD_MESH_OUTPUT for (uint8_t x = 0; x < sx; x++) { for (uint8_t i = 0; i < precision + 2 + (x < 10 ? 1 : 0); i++) SERIAL_PROTOCOLCHAR(' '); SERIAL_PROTOCOL(int(x)); } SERIAL_EOL(); #endif #ifdef SCAD_MESH_OUTPUT SERIAL_PROTOCOLLNPGM("measured_z = ["); // open 2D array #endif for (uint8_t y = 0; y < sy; y++) { #ifdef SCAD_MESH_OUTPUT SERIAL_PROTOCOLPGM(" ["); // open sub-array #else if (y < 10) SERIAL_PROTOCOLCHAR(' '); SERIAL_PROTOCOL(int(y)); #endif for (uint8_t x = 0; x < sx; x++) { SERIAL_PROTOCOLCHAR(' '); const float offset = fn(x, y); if (!isnan(offset)) { if (offset >= 0) SERIAL_PROTOCOLCHAR('+'); SERIAL_PROTOCOL_F(offset, int(precision)); } else { #ifdef SCAD_MESH_OUTPUT for (uint8_t i = 3; i < precision + 3; i++) SERIAL_PROTOCOLCHAR(' '); SERIAL_PROTOCOLPGM("NAN"); #else for (uint8_t i = 0; i < precision + 3; i++) SERIAL_PROTOCOLCHAR(i ? '=' : ' '); #endif } #ifdef SCAD_MESH_OUTPUT if (x < sx - 1) SERIAL_PROTOCOLCHAR(','); #endif } #ifdef SCAD_MESH_OUTPUT SERIAL_PROTOCOLCHAR(' '); SERIAL_PROTOCOLCHAR(']'); // close sub-array if (y < sy - 1) SERIAL_PROTOCOLCHAR(','); #endif SERIAL_EOL(); } #ifdef SCAD_MESH_OUTPUT SERIAL_PROTOCOLPGM("];"); // close 2D array #endif SERIAL_EOL(); } #endif #if ENABLED(AUTO_BED_LEVELING_BILINEAR) /** * Extrapolate a single point from its neighbors */ static void extrapolate_one_point(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPGM("Extrapolate ["); if (x < 10) SERIAL_CHAR(' '); SERIAL_ECHO(int(x)); SERIAL_CHAR(xdir ? (xdir > 0 ? '+' : '-') : ' '); SERIAL_CHAR(' '); if (y < 10) SERIAL_CHAR(' '); SERIAL_ECHO(int(y)); SERIAL_CHAR(ydir ? (ydir > 0 ? '+' : '-') : ' '); SERIAL_CHAR(']'); } #endif if (!isnan(z_values[x][y])) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM(" (done)"); #endif return; // Don't overwrite good values. } SERIAL_EOL(); // Get X neighbors, Y neighbors, and XY neighbors const uint8_t x1 = x + xdir, y1 = y + ydir, x2 = x1 + xdir, y2 = y1 + ydir; float a1 = z_values[x1][y ], a2 = z_values[x2][y ], b1 = z_values[x ][y1], b2 = z_values[x ][y2], c1 = z_values[x1][y1], c2 = z_values[x2][y2]; // Treat far unprobed points as zero, near as equal to far if (isnan(a2)) a2 = 0.0; if (isnan(a1)) a1 = a2; if (isnan(b2)) b2 = 0.0; if (isnan(b1)) b1 = b2; if (isnan(c2)) c2 = 0.0; if (isnan(c1)) c1 = c2; const float a = 2 * a1 - a2, b = 2 * b1 - b2, c = 2 * c1 - c2; // Take the average instead of the median z_values[x][y] = (a + b + c) / 3.0; // Median is robust (ignores outliers). // z_values[x][y] = (a < b) ? ((b < c) ? b : (c < a) ? a : c) // : ((c < b) ? b : (a < c) ? a : c); } //Enable this if your SCARA uses 180° of total area //#define EXTRAPOLATE_FROM_EDGE #if ENABLED(EXTRAPOLATE_FROM_EDGE) #if GRID_MAX_POINTS_X < GRID_MAX_POINTS_Y #define HALF_IN_X #elif GRID_MAX_POINTS_Y < GRID_MAX_POINTS_X #define HALF_IN_Y #endif #endif /** * Fill in the unprobed points (corners of circular print surface) * using linear extrapolation, away from the center. */ static void extrapolate_unprobed_bed_level() { #ifdef HALF_IN_X constexpr uint8_t ctrx2 = 0, xlen = GRID_MAX_POINTS_X - 1; #else constexpr uint8_t ctrx1 = (GRID_MAX_POINTS_X - 1) / 2, // left-of-center ctrx2 = (GRID_MAX_POINTS_X) / 2, // right-of-center xlen = ctrx1; #endif #ifdef HALF_IN_Y constexpr uint8_t ctry2 = 0, ylen = GRID_MAX_POINTS_Y - 1; #else constexpr uint8_t ctry1 = (GRID_MAX_POINTS_Y - 1) / 2, // top-of-center ctry2 = (GRID_MAX_POINTS_Y) / 2, // bottom-of-center ylen = ctry1; #endif for (uint8_t xo = 0; xo <= xlen; xo++) for (uint8_t yo = 0; yo <= ylen; yo++) { uint8_t x2 = ctrx2 + xo, y2 = ctry2 + yo; #ifndef HALF_IN_X const uint8_t x1 = ctrx1 - xo; #endif #ifndef HALF_IN_Y const uint8_t y1 = ctry1 - yo; #ifndef HALF_IN_X extrapolate_one_point(x1, y1, +1, +1); // left-below + + #endif extrapolate_one_point(x2, y1, -1, +1); // right-below - + #endif #ifndef HALF_IN_X extrapolate_one_point(x1, y2, +1, -1); // left-above + - #endif extrapolate_one_point(x2, y2, -1, -1); // right-above - - } } static void print_bilinear_leveling_grid() { SERIAL_ECHOLNPGM("Bilinear Leveling Grid:"); print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 3, [](const uint8_t ix, const uint8_t iy) { return z_values[ix][iy]; } ); } #if ENABLED(ABL_BILINEAR_SUBDIVISION) #define ABL_GRID_POINTS_VIRT_X (GRID_MAX_POINTS_X - 1) * (BILINEAR_SUBDIVISIONS) + 1 #define ABL_GRID_POINTS_VIRT_Y (GRID_MAX_POINTS_Y - 1) * (BILINEAR_SUBDIVISIONS) + 1 #define ABL_TEMP_POINTS_X (GRID_MAX_POINTS_X + 2) #define ABL_TEMP_POINTS_Y (GRID_MAX_POINTS_Y + 2) float z_values_virt[ABL_GRID_POINTS_VIRT_X][ABL_GRID_POINTS_VIRT_Y]; int bilinear_grid_spacing_virt[2] = { 0 }; float bilinear_grid_factor_virt[2] = { 0 }; static void print_bilinear_leveling_grid_virt() { SERIAL_ECHOLNPGM("Subdivided with CATMULL ROM Leveling Grid:"); print_2d_array(ABL_GRID_POINTS_VIRT_X, ABL_GRID_POINTS_VIRT_Y, 5, [](const uint8_t ix, const uint8_t iy) { return z_values_virt[ix][iy]; } ); } #define LINEAR_EXTRAPOLATION(E, I) ((E) * 2 - (I)) float bed_level_virt_coord(const uint8_t x, const uint8_t y) { uint8_t ep = 0, ip = 1; if (!x || x == ABL_TEMP_POINTS_X - 1) { if (x) { ep = GRID_MAX_POINTS_X - 1; ip = GRID_MAX_POINTS_X - 2; } if (WITHIN(y, 1, ABL_TEMP_POINTS_Y - 2)) return LINEAR_EXTRAPOLATION( z_values[ep][y - 1], z_values[ip][y - 1] ); else return LINEAR_EXTRAPOLATION( bed_level_virt_coord(ep + 1, y), bed_level_virt_coord(ip + 1, y) ); } if (!y || y == ABL_TEMP_POINTS_Y - 1) { if (y) { ep = GRID_MAX_POINTS_Y - 1; ip = GRID_MAX_POINTS_Y - 2; } if (WITHIN(x, 1, ABL_TEMP_POINTS_X - 2)) return LINEAR_EXTRAPOLATION( z_values[x - 1][ep], z_values[x - 1][ip] ); else return LINEAR_EXTRAPOLATION( bed_level_virt_coord(x, ep + 1), bed_level_virt_coord(x, ip + 1) ); } return z_values[x - 1][y - 1]; } static float bed_level_virt_cmr(const float p[4], const uint8_t i, const float t) { return ( p[i-1] * -t * sq(1 - t) + p[i] * (2 - 5 * sq(t) + 3 * t * sq(t)) + p[i+1] * t * (1 + 4 * t - 3 * sq(t)) - p[i+2] * sq(t) * (1 - t) ) * 0.5; } static float bed_level_virt_2cmr(const uint8_t x, const uint8_t y, const float &tx, const float &ty) { float row[4], column[4]; for (uint8_t i = 0; i < 4; i++) { for (uint8_t j = 0; j < 4; j++) { column[j] = bed_level_virt_coord(i + x - 1, j + y - 1); } row[i] = bed_level_virt_cmr(column, 1, ty); } return bed_level_virt_cmr(row, 1, tx); } void bed_level_virt_interpolate() { bilinear_grid_spacing_virt[X_AXIS] = bilinear_grid_spacing[X_AXIS] / (BILINEAR_SUBDIVISIONS); bilinear_grid_spacing_virt[Y_AXIS] = bilinear_grid_spacing[Y_AXIS] / (BILINEAR_SUBDIVISIONS); bilinear_grid_factor_virt[X_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[X_AXIS]); bilinear_grid_factor_virt[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[Y_AXIS]); for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++) for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++) for (uint8_t ty = 0; ty < BILINEAR_SUBDIVISIONS; ty++) for (uint8_t tx = 0; tx < BILINEAR_SUBDIVISIONS; tx++) { if ((ty && y == GRID_MAX_POINTS_Y - 1) || (tx && x == GRID_MAX_POINTS_X - 1)) continue; z_values_virt[x * (BILINEAR_SUBDIVISIONS) + tx][y * (BILINEAR_SUBDIVISIONS) + ty] = bed_level_virt_2cmr( x + 1, y + 1, (float)tx / (BILINEAR_SUBDIVISIONS), (float)ty / (BILINEAR_SUBDIVISIONS) ); } } #endif // ABL_BILINEAR_SUBDIVISION // Refresh after other values have been updated void refresh_bed_level() { bilinear_grid_factor[X_AXIS] = RECIPROCAL(bilinear_grid_spacing[X_AXIS]); bilinear_grid_factor[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing[Y_AXIS]); #if ENABLED(ABL_BILINEAR_SUBDIVISION) bed_level_virt_interpolate(); #endif } #endif // AUTO_BED_LEVELING_BILINEAR #if ENABLED(SENSORLESS_HOMING) /** * Set sensorless homing if the axis has it, accounting for Core Kinematics. */ void sensorless_homing_per_axis(const AxisEnum axis, const bool enable=true) { switch (axis) { #if X_SENSORLESS case X_AXIS: tmc_sensorless_homing(stepperX, enable); #if CORE_IS_XY && Y_SENSORLESS tmc_sensorless_homing(stepperY, enable); #elif CORE_IS_XZ && Z_SENSORLESS tmc_sensorless_homing(stepperZ, enable); #endif break; #endif #if Y_SENSORLESS case Y_AXIS: tmc_sensorless_homing(stepperY, enable); #if CORE_IS_XY && X_SENSORLESS tmc_sensorless_homing(stepperX, enable); #elif CORE_IS_YZ && Z_SENSORLESS tmc_sensorless_homing(stepperZ, enable); #endif break; #endif #if Z_SENSORLESS case Z_AXIS: tmc_sensorless_homing(stepperZ, enable); #if CORE_IS_XZ && X_SENSORLESS tmc_sensorless_homing(stepperX, enable); #elif CORE_IS_YZ && Y_SENSORLESS tmc_sensorless_homing(stepperY, enable); #endif break; #endif default: break; } } #endif // SENSORLESS_HOMING /** * Home an individual linear axis */ static void do_homing_move(const AxisEnum axis, const float distance, const float fr_mm_s=0) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR(">>> do_homing_move(", axis_codes[axis]); SERIAL_ECHOPAIR(", ", distance); SERIAL_ECHOPGM(", "); if (fr_mm_s) SERIAL_ECHO(fr_mm_s); else { SERIAL_ECHOPAIR("[", homing_feedrate(axis)); SERIAL_CHAR(']'); } SERIAL_ECHOLNPGM(")"); } #endif #if HOMING_Z_WITH_PROBE && HAS_HEATED_BED && ENABLED(WAIT_FOR_BED_HEATER) // Wait for bed to heat back up between probing points if (axis == Z_AXIS && distance < 0 && thermalManager.isHeatingBed()) { serialprintPGM(msg_wait_for_bed_heating); LCD_MESSAGEPGM(MSG_BED_HEATING); while (thermalManager.isHeatingBed()) safe_delay(200); lcd_reset_status(); } #endif // Only do some things when moving towards an endstop const int8_t axis_home_dir = #if ENABLED(DUAL_X_CARRIAGE) (axis == X_AXIS) ? x_home_dir(active_extruder) : #endif home_dir(axis); const bool is_home_dir = (axis_home_dir > 0) == (distance > 0); if (is_home_dir) { #if HOMING_Z_WITH_PROBE && QUIET_PROBING if (axis == Z_AXIS) probing_pause(true); #endif // Disable stealthChop if used. Enable diag1 pin on driver. #if ENABLED(SENSORLESS_HOMING) sensorless_homing_per_axis(axis); #endif } // Tell the planner the axis is at 0 current_position[axis] = 0; // Do the move, which is required to hit an endstop #if IS_SCARA SYNC_PLAN_POSITION_KINEMATIC(); current_position[axis] = distance; inverse_kinematics(current_position); planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], current_position[E_CART], fr_mm_s ? fr_mm_s : homing_feedrate(axis), active_extruder); #elif ENABLED(HANGPRINTER) // TODO: Hangprinter homing is not finished (Jan 7, 2018) SYNC_PLAN_POSITION_KINEMATIC(); current_position[axis] = distance; inverse_kinematics(current_position); planner.buffer_line(line_lengths[A_AXIS], line_lengths[B_AXIS], line_lengths[C_AXIS], line_lengths[D_AXIS], current_position[E_CART], fr_mm_s ? fr_mm_s : homing_feedrate(axis), active_extruder); #else sync_plan_position(); current_position[axis] = distance; // Set delta/cartesian axes directly planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART], fr_mm_s ? fr_mm_s : homing_feedrate(axis), active_extruder); #endif planner.synchronize(); if (is_home_dir) { #if HOMING_Z_WITH_PROBE && QUIET_PROBING if (axis == Z_AXIS) probing_pause(false); #endif endstops.validate_homing_move(); // Re-enable stealthChop if used. Disable diag1 pin on driver. #if ENABLED(SENSORLESS_HOMING) sensorless_homing_per_axis(axis, false); #endif } #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("<<< do_homing_move(", axis_codes[axis]); SERIAL_CHAR(')'); SERIAL_EOL(); } #endif } /** * Home an individual "raw axis" to its endstop. * This applies to XYZ on Cartesian and Core robots, and * to the individual ABC steppers on DELTA and SCARA. * * At the end of the procedure the axis is marked as * homed and the current position of that axis is updated. * Kinematic robots should wait till all axes are homed * before updating the current position. */ static void homeaxis(const AxisEnum axis) { #if IS_SCARA // Only Z homing (with probe) is permitted if (axis != Z_AXIS) { BUZZ(100, 880); return; } #else #define CAN_HOME(A) \ (axis == _AXIS(A) && ((A##_MIN_PIN > -1 && A##_HOME_DIR < 0) || (A##_MAX_PIN > -1 && A##_HOME_DIR > 0))) if (!CAN_HOME(X) && !CAN_HOME(Y) && !CAN_HOME(Z)) return; #endif #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR(">>> homeaxis(", axis_codes[axis]); SERIAL_CHAR(')'); SERIAL_EOL(); } #endif const int axis_home_dir = ( #if ENABLED(DUAL_X_CARRIAGE) axis == X_AXIS ? x_home_dir(active_extruder) : #endif home_dir(axis) ); // Homing Z towards the bed? Deploy the Z probe or endstop. #if HOMING_Z_WITH_PROBE if (axis == Z_AXIS && DEPLOY_PROBE()) return; #endif // Set flags for X, Y, Z motor locking #if ENABLED(X_DUAL_ENDSTOPS) || ENABLED(Y_DUAL_ENDSTOPS) || ENABLED(Z_DUAL_ENDSTOPS) switch (axis) { #if ENABLED(X_DUAL_ENDSTOPS) case X_AXIS: #endif #if ENABLED(Y_DUAL_ENDSTOPS) case Y_AXIS: #endif #if ENABLED(Z_DUAL_ENDSTOPS) case Z_AXIS: #endif stepper.set_homing_dual_axis(true); default: break; } #endif // Fast move towards endstop until triggered #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 1 Fast:"); #endif #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH) // BLTOUCH needs to be deployed every time if (axis == Z_AXIS && set_bltouch_deployed(true)) return; #endif do_homing_move(axis, 1.5f * max_length(axis) * axis_home_dir); #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH) // BLTOUCH needs to be stowed after trigger to rearm itself if (axis == Z_AXIS) set_bltouch_deployed(false); #endif // When homing Z with probe respect probe clearance const float bump = axis_home_dir * ( #if HOMING_Z_WITH_PROBE (axis == Z_AXIS && (Z_HOME_BUMP_MM)) ? MAX(Z_CLEARANCE_BETWEEN_PROBES, Z_HOME_BUMP_MM) : #endif home_bump_mm(axis) ); // If a second homing move is configured... if (bump) { // Move away from the endstop by the axis HOME_BUMP_MM #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Move Away:"); #endif do_homing_move(axis, -bump #if HOMING_Z_WITH_PROBE , axis == Z_AXIS ? MMM_TO_MMS(Z_PROBE_SPEED_FAST) : 0.00 #endif ); // Slow move towards endstop until triggered #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 2 Slow:"); #endif #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH) // BLTOUCH needs to be deployed every time if (axis == Z_AXIS && set_bltouch_deployed(true)) return; #endif do_homing_move(axis, 2 * bump, get_homing_bump_feedrate(axis)); #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH) // BLTOUCH needs to be stowed after trigger to rearm itself if (axis == Z_AXIS) set_bltouch_deployed(false); #endif } /** * Home axes that have dual endstops... differently */ #if ENABLED(X_DUAL_ENDSTOPS) || ENABLED(Y_DUAL_ENDSTOPS) || ENABLED(Z_DUAL_ENDSTOPS) const bool pos_dir = axis_home_dir > 0; #if ENABLED(X_DUAL_ENDSTOPS) if (axis == X_AXIS) { const float adj = ABS(endstops.x_endstop_adj); if (adj) { if (pos_dir ? (endstops.x_endstop_adj > 0) : (endstops.x_endstop_adj < 0)) stepper.set_x_lock(true); else stepper.set_x2_lock(true); do_homing_move(axis, pos_dir ? -adj : adj); stepper.set_x_lock(false); stepper.set_x2_lock(false); } } #endif #if ENABLED(Y_DUAL_ENDSTOPS) if (axis == Y_AXIS) { const float adj = ABS(endstops.y_endstop_adj); if (adj) { if (pos_dir ? (endstops.y_endstop_adj > 0) : (endstops.y_endstop_adj < 0)) stepper.set_y_lock(true); else stepper.set_y2_lock(true); do_homing_move(axis, pos_dir ? -adj : adj); stepper.set_y_lock(false); stepper.set_y2_lock(false); } } #endif #if ENABLED(Z_DUAL_ENDSTOPS) if (axis == Z_AXIS) { const float adj = ABS(endstops.z_endstop_adj); if (adj) { if (pos_dir ? (endstops.z_endstop_adj > 0) : (endstops.z_endstop_adj < 0)) stepper.set_z_lock(true); else stepper.set_z2_lock(true); do_homing_move(axis, pos_dir ? -adj : adj); stepper.set_z_lock(false); stepper.set_z2_lock(false); } } #endif stepper.set_homing_dual_axis(false); #endif #if IS_SCARA set_axis_is_at_home(axis); SYNC_PLAN_POSITION_KINEMATIC(); #elif ENABLED(DELTA) // Delta has already moved all three towers up in G28 // so here it re-homes each tower in turn. // Delta homing treats the axes as normal linear axes. // retrace by the amount specified in delta_endstop_adj + additional dist in order to have minimum steps if (delta_endstop_adj[axis] * Z_HOME_DIR <= 0) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("delta_endstop_adj:"); #endif do_homing_move(axis, delta_endstop_adj[axis] - (MIN_STEPS_PER_SEGMENT + 1) * planner.steps_to_mm[axis] * Z_HOME_DIR); } #else // For cartesian/core machines, // set the axis to its home position set_axis_is_at_home(axis); sync_plan_position(); destination[axis] = current_position[axis]; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("> AFTER set_axis_is_at_home", current_position); #endif #endif // Put away the Z probe #if HOMING_Z_WITH_PROBE if (axis == Z_AXIS && STOW_PROBE()) return; #endif // Clear retracted status if homing the Z axis #if ENABLED(FWRETRACT) if (axis == Z_AXIS) fwretract.hop_amount = 0.0; #endif #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("<<< homeaxis(", axis_codes[axis]); SERIAL_CHAR(')'); SERIAL_EOL(); } #endif } // homeaxis() #if ENABLED(MIXING_EXTRUDER) void normalize_mix() { float mix_total = 0.0; for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mix_total += mixing_factor[i]; // Scale all values if they don't add up to ~1.0 if (!NEAR(mix_total, 1.0)) { SERIAL_PROTOCOLLNPGM("Warning: Mix factors must add up to 1.0. Scaling."); const float inverse_sum = RECIPROCAL(mix_total); for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mixing_factor[i] *= inverse_sum; } } #if ENABLED(DIRECT_MIXING_IN_G1) // Get mixing parameters from the GCode // The total "must" be 1.0 (but it will be normalized) // If no mix factors are given, the old mix is preserved void gcode_get_mix() { const char mixing_codes[] = { 'A', 'B' #if MIXING_STEPPERS > 2 , 'C' #if MIXING_STEPPERS > 3 , 'D' #if MIXING_STEPPERS > 4 , 'H' #if MIXING_STEPPERS > 5 , 'I' #endif // MIXING_STEPPERS > 5 #endif // MIXING_STEPPERS > 4 #endif // MIXING_STEPPERS > 3 #endif // MIXING_STEPPERS > 2 }; byte mix_bits = 0; for (uint8_t i = 0; i < MIXING_STEPPERS; i++) { if (parser.seenval(mixing_codes[i])) { SBI(mix_bits, i); mixing_factor[i] = MAX(parser.value_float(), 0.0); } } // If any mixing factors were included, clear the rest // If none were included, preserve the last mix if (mix_bits) { for (uint8_t i = 0; i < MIXING_STEPPERS; i++) if (!TEST(mix_bits, i)) mixing_factor[i] = 0.0; normalize_mix(); } } #endif #endif /** * *************************************************************************** * ***************************** G-CODE HANDLING ***************************** * *************************************************************************** */ /** * Set XYZE destination and feedrate from the current GCode command * * - Set destination from included axis codes * - Set to current for missing axis codes * - Set the feedrate, if included */ void gcode_get_destination() { LOOP_XYZE(i) { if (parser.seen(axis_codes[i])) { const float v = parser.value_axis_units((AxisEnum)i); destination[i] = (axis_relative_modes[i] || relative_mode) ? current_position[i] + v : (i == E_CART) ? v : LOGICAL_TO_NATIVE(v, i); } else destination[i] = current_position[i]; } if (parser.linearval('F') > 0) feedrate_mm_s = MMM_TO_MMS(parser.value_feedrate()); #if ENABLED(PRINTCOUNTER) if (!DEBUGGING(DRYRUN)) print_job_timer.incFilamentUsed(destination[E_CART] - current_position[E_CART]); #endif // Get ABCDHI mixing factors #if ENABLED(MIXING_EXTRUDER) && ENABLED(DIRECT_MIXING_IN_G1) gcode_get_mix(); #endif } #if ENABLED(HOST_KEEPALIVE_FEATURE) /** * Output a "busy" message at regular intervals * while the machine is not accepting commands. */ void host_keepalive() { const millis_t ms = millis(); if (!suspend_auto_report && host_keepalive_interval && busy_state != NOT_BUSY) { if (PENDING(ms, next_busy_signal_ms)) return; switch (busy_state) { case IN_HANDLER: case IN_PROCESS: SERIAL_ECHO_START(); SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING); break; case PAUSED_FOR_USER: SERIAL_ECHO_START(); SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER); break; case PAUSED_FOR_INPUT: SERIAL_ECHO_START(); SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT); break; default: break; } } next_busy_signal_ms = ms + host_keepalive_interval * 1000UL; } #endif // HOST_KEEPALIVE_FEATURE /************************************************** ***************** GCode Handlers ***************** **************************************************/ #if ENABLED(NO_MOTION_BEFORE_HOMING) #define G0_G1_CONDITION !axis_unhomed_error(parser.seen('X'), parser.seen('Y'), parser.seen('Z')) #else #define G0_G1_CONDITION true #endif /** * G0, G1: Coordinated movement of X Y Z E axes */ inline void gcode_G0_G1( #if IS_SCARA bool fast_move=false #endif ) { if (IsRunning() && G0_G1_CONDITION) { gcode_get_destination(); // For X Y Z E F #if ENABLED(FWRETRACT) if (MIN_AUTORETRACT <= MAX_AUTORETRACT) { // When M209 Autoretract is enabled, convert E-only moves to firmware retract/prime moves if (fwretract.autoretract_enabled && parser.seen('E') && !(parser.seen('X') || parser.seen('Y') || parser.seen('Z'))) { const float echange = destination[E_CART] - current_position[E_CART]; // Is this a retract or prime move? if (WITHIN(ABS(echange), MIN_AUTORETRACT, MAX_AUTORETRACT) && fwretract.retracted[active_extruder] == (echange > 0.0)) { current_position[E_CART] = destination[E_CART]; // Hide a G1-based retract/prime from calculations sync_plan_position_e(); // AND from the planner return fwretract.retract(echange < 0.0); // Firmware-based retract/prime (double-retract ignored) } } } #endif // FWRETRACT #if IS_SCARA fast_move ? prepare_uninterpolated_move_to_destination() : prepare_move_to_destination(); #else prepare_move_to_destination(); #endif #if ENABLED(NANODLP_Z_SYNC) #if ENABLED(NANODLP_ALL_AXIS) #define _MOVE_SYNC parser.seenval('X') || parser.seenval('Y') || parser.seenval('Z') // For any move wait and output sync message #else #define _MOVE_SYNC parser.seenval('Z') // Only for Z move #endif if (_MOVE_SYNC) { planner.synchronize(); SERIAL_ECHOLNPGM(MSG_Z_MOVE_COMP); } #endif } } /** * G2: Clockwise Arc * G3: Counterclockwise Arc * * This command has two forms: IJ-form and R-form. * * - I specifies an X offset. J specifies a Y offset. * At least one of the IJ parameters is required. * X and Y can be omitted to do a complete circle. * The given XY is not error-checked. The arc ends * based on the angle of the destination. * Mixing I or J with R will throw an error. * * - R specifies the radius. X or Y is required. * Omitting both X and Y will throw an error. * X or Y must differ from the current XY. * Mixing R with I or J will throw an error. * * - P specifies the number of full circles to do * before the specified arc move. * * Examples: * * G2 I10 ; CW circle centered at X+10 * G3 X20 Y12 R14 ; CCW circle with r=14 ending at X20 Y12 */ #if ENABLED(ARC_SUPPORT) inline void gcode_G2_G3(const bool clockwise) { #if ENABLED(NO_MOTION_BEFORE_HOMING) if (axis_unhomed_error()) return; #endif if (IsRunning()) { #if ENABLED(SF_ARC_FIX) const bool relative_mode_backup = relative_mode; relative_mode = true; #endif gcode_get_destination(); #if ENABLED(SF_ARC_FIX) relative_mode = relative_mode_backup; #endif float arc_offset[2] = { 0, 0 }; if (parser.seenval('R')) { const float r = parser.value_linear_units(), p1 = current_position[X_AXIS], q1 = current_position[Y_AXIS], p2 = destination[X_AXIS], q2 = destination[Y_AXIS]; if (r && (p2 != p1 || q2 != q1)) { const float e = clockwise ^ (r < 0) ? -1 : 1, // clockwise -1/1, counterclockwise 1/-1 dx = p2 - p1, dy = q2 - q1, // X and Y differences d = HYPOT(dx, dy), // Linear distance between the points h = SQRT(sq(r) - sq(d * 0.5f)), // Distance to the arc pivot-point mx = (p1 + p2) * 0.5f, my = (q1 + q2) * 0.5f, // Point between the two points sx = -dy / d, sy = dx / d, // Slope of the perpendicular bisector cx = mx + e * h * sx, cy = my + e * h * sy; // Pivot-point of the arc arc_offset[0] = cx - p1; arc_offset[1] = cy - q1; } } else { if (parser.seenval('I')) arc_offset[0] = parser.value_linear_units(); if (parser.seenval('J')) arc_offset[1] = parser.value_linear_units(); } if (arc_offset[0] || arc_offset[1]) { #if ENABLED(ARC_P_CIRCLES) // P indicates number of circles to do int8_t circles_to_do = parser.byteval('P'); if (!WITHIN(circles_to_do, 0, 100)) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS); } while (circles_to_do--) plan_arc(current_position, arc_offset, clockwise); #endif // Send the arc to the planner plan_arc(destination, arc_offset, clockwise); } else { // Bad arguments SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS); } } } #endif // ARC_SUPPORT void dwell(millis_t time) { time += millis(); while (PENDING(millis(), time)) idle(); } /** * G4: Dwell S<seconds> or P<milliseconds> */ inline void gcode_G4() { millis_t dwell_ms = 0; if (parser.seenval('P')) dwell_ms = parser.value_millis(); // milliseconds to wait if (parser.seenval('S')) dwell_ms = parser.value_millis_from_seconds(); // seconds to wait planner.synchronize(); #if ENABLED(NANODLP_Z_SYNC) SERIAL_ECHOLNPGM(MSG_Z_MOVE_COMP); #endif if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL); dwell(dwell_ms); } #if ENABLED(BEZIER_CURVE_SUPPORT) /** * Parameters interpreted according to: * http://linuxcnc.org/docs/2.6/html/gcode/gcode.html#sec:G5-Cubic-Spline * However I, J omission is not supported at this point; all * parameters can be omitted and default to zero. */ /** * G5: Cubic B-spline */ inline void gcode_G5() { #if ENABLED(NO_MOTION_BEFORE_HOMING) if (axis_unhomed_error()) return; #endif if (IsRunning()) { #if ENABLED(CNC_WORKSPACE_PLANES) if (workspace_plane != PLANE_XY) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_BAD_PLANE_MODE); return; } #endif gcode_get_destination(); const float offset[] = { parser.linearval('I'), parser.linearval('J'), parser.linearval('P'), parser.linearval('Q') }; plan_cubic_move(destination, offset); } } #endif // BEZIER_CURVE_SUPPORT #if ENABLED(UNREGISTERED_MOVE_SUPPORT) /** * G6 implementation for Hangprinter based on * http://reprap.org/wiki/GCodes#G6:_Direct_Stepper_Move * Accessed Jan 8, 2018 * * G6 is used frequently to tighten lines with Hangprinter, so Hangprinter default is relative moves. * Hangprinter uses switches * S1 for absolute moves * S2 for saving recording new line length after unregistered move * (typically used while tuning LINE_BUILDUP_COMPENSATION_FEATURE parameters) */ /** * G6: Direct Stepper Move */ inline void gcode_G6() { bool count_it = false; #if ENABLED(NO_MOTION_BEFORE_HOMING) if (axis_unhomed_error()) return; #endif if (IsRunning()) { float go[MOV_AXIS] = { 0.0 }, tmp_fr_mm_s = 0.0; LOOP_MOV_AXIS(i) if (parser.seen(RAW_AXIS_CODES(i))) go[i] = parser.value_axis_units((AxisEnum)i); #if ENABLED(HANGPRINTER) #define GO_SRC line_lengths #elif ENABLED(DELTA) #define GO_SRC delta #else #define GO_SRC current_position #endif if ( #if ENABLED(HANGPRINTER) // Sending R to another machine is the same as not sending S1 to Hangprinter parser.byteval('S') != 2 #else parser.seen('R') #endif ) LOOP_MOV_AXIS(i) go[i] += GO_SRC[i]; else LOOP_MOV_AXIS(i) if (!parser.seen(RAW_AXIS_CODES(i))) go[i] += GO_SRC[i]; tmp_fr_mm_s = parser.linearval('F') > 0.0 ? MMM_TO_MMS(parser.value_feedrate()) : feedrate_mm_s; #if ENABLED(HANGPRINTER) if (parser.byteval('S') == 2) { LOOP_MOV_AXIS(i) line_lengths[i] = go[i]; count_it = true; } #endif planner.buffer_segment(go[A_AXIS], go[B_AXIS], go[C_AXIS] #if ENABLED(HANGPRINTER) , go[D_AXIS] #endif , current_position[E_CART], tmp_fr_mm_s, active_extruder, 0.0, count_it ); } } #endif #if ENABLED(FWRETRACT) /** * G10 - Retract filament according to settings of M207 */ inline void gcode_G10() { #if EXTRUDERS > 1 const bool rs = parser.boolval('S'); #endif fwretract.retract(true #if EXTRUDERS > 1 , rs #endif ); } /** * G11 - Recover filament according to settings of M208 */ inline void gcode_G11() { fwretract.retract(false); } #endif // FWRETRACT #if ENABLED(NOZZLE_CLEAN_FEATURE) /** * G12: Clean the nozzle */ inline void gcode_G12() { // Don't allow nozzle cleaning without homing first if (axis_unhomed_error()) return; const uint8_t pattern = parser.ushortval('P', 0), strokes = parser.ushortval('S', NOZZLE_CLEAN_STROKES), objects = parser.ushortval('T', NOZZLE_CLEAN_TRIANGLES); const float radius = parser.floatval('R', NOZZLE_CLEAN_CIRCLE_RADIUS); Nozzle::clean(pattern, strokes, radius, objects); } #endif #if ENABLED(CNC_WORKSPACE_PLANES) inline void report_workspace_plane() { SERIAL_ECHO_START(); SERIAL_ECHOPGM("Workspace Plane "); serialprintPGM( workspace_plane == PLANE_YZ ? PSTR("YZ\n") : workspace_plane == PLANE_ZX ? PSTR("ZX\n") : PSTR("XY\n") ); } inline void set_workspace_plane(const WorkspacePlane plane) { workspace_plane = plane; if (DEBUGGING(INFO)) report_workspace_plane(); } /** * G17: Select Plane XY * G18: Select Plane ZX * G19: Select Plane YZ */ inline void gcode_G17() { set_workspace_plane(PLANE_XY); } inline void gcode_G18() { set_workspace_plane(PLANE_ZX); } inline void gcode_G19() { set_workspace_plane(PLANE_YZ); } #endif // CNC_WORKSPACE_PLANES #if ENABLED(CNC_COORDINATE_SYSTEMS) /** * Select a coordinate system and update the workspace offset. * System index -1 is used to specify machine-native. */ bool select_coordinate_system(const int8_t _new) { if (active_coordinate_system == _new) return false; float old_offset[XYZ] = { 0 }, new_offset[XYZ] = { 0 }; if (WITHIN(active_coordinate_system, 0, MAX_COORDINATE_SYSTEMS - 1)) COPY(old_offset, coordinate_system[active_coordinate_system]); if (WITHIN(_new, 0, MAX_COORDINATE_SYSTEMS - 1)) COPY(new_offset, coordinate_system[_new]); active_coordinate_system = _new; LOOP_XYZ(i) { const float diff = new_offset[i] - old_offset[i]; if (diff) { position_shift[i] += diff; update_software_endstops((AxisEnum)i); } } return true; } /** * G53: Apply native workspace to the current move * * In CNC G-code G53 is a modifier. * It precedes a movement command (or other modifiers) on the same line. * This is the first command to use parser.chain() to make this possible. * * Marlin also uses G53 on a line by itself to go back to native space. */ inline void gcode_G53() { const int8_t _system = active_coordinate_system; active_coordinate_system = -1; if (parser.chain()) { // If this command has more following... process_parsed_command(); active_coordinate_system = _system; } } /** * G54-G59.3: Select a new workspace * * A workspace is an XYZ offset to the machine native space. * All workspaces default to 0,0,0 at start, or with EEPROM * support they may be restored from a previous session. * * G92 is used to set the current workspace's offset. */ inline void gcode_G54_59(uint8_t subcode=0) { const int8_t _space = parser.codenum - 54 + subcode; if (select_coordinate_system(_space)) { SERIAL_PROTOCOLLNPAIR("Select workspace ", _space); report_current_position(); } } FORCE_INLINE void gcode_G54() { gcode_G54_59(); } FORCE_INLINE void gcode_G55() { gcode_G54_59(); } FORCE_INLINE void gcode_G56() { gcode_G54_59(); } FORCE_INLINE void gcode_G57() { gcode_G54_59(); } FORCE_INLINE void gcode_G58() { gcode_G54_59(); } FORCE_INLINE void gcode_G59() { gcode_G54_59(parser.subcode); } #endif #if ENABLED(INCH_MODE_SUPPORT) /** * G20: Set input mode to inches */ inline void gcode_G20() { parser.set_input_linear_units(LINEARUNIT_INCH); } /** * G21: Set input mode to millimeters */ inline void gcode_G21() { parser.set_input_linear_units(LINEARUNIT_MM); } #endif #if ENABLED(NOZZLE_PARK_FEATURE) /** * G27: Park the nozzle */ inline void gcode_G27() { // Don't allow nozzle parking without homing first if (axis_unhomed_error()) return; Nozzle::park(parser.ushortval('P')); } #endif // NOZZLE_PARK_FEATURE #if ENABLED(QUICK_HOME) static void quick_home_xy() { // Pretend the current position is 0,0 current_position[X_AXIS] = current_position[Y_AXIS] = 0.0; sync_plan_position(); const int x_axis_home_dir = #if ENABLED(DUAL_X_CARRIAGE) x_home_dir(active_extruder) #else home_dir(X_AXIS) #endif ; const float mlx = max_length(X_AXIS), mly = max_length(Y_AXIS), mlratio = mlx > mly ? mly / mlx : mlx / mly, fr_mm_s = MIN(homing_feedrate(X_AXIS), homing_feedrate(Y_AXIS)) * SQRT(sq(mlratio) + 1.0); #if ENABLED(SENSORLESS_HOMING) sensorless_homing_per_axis(X_AXIS); sensorless_homing_per_axis(Y_AXIS); #endif do_blocking_move_to_xy(1.5 * mlx * x_axis_home_dir, 1.5 * mly * home_dir(Y_AXIS), fr_mm_s); endstops.validate_homing_move(); current_position[X_AXIS] = current_position[Y_AXIS] = 0.0; #if ENABLED(SENSORLESS_HOMING) sensorless_homing_per_axis(X_AXIS, false); sensorless_homing_per_axis(Y_AXIS, false); #endif } #endif // QUICK_HOME #if ENABLED(DEBUG_LEVELING_FEATURE) void log_machine_info() { SERIAL_ECHOPGM("Machine Type: "); #if ENABLED(DELTA) SERIAL_ECHOLNPGM("Delta"); #elif IS_SCARA SERIAL_ECHOLNPGM("SCARA"); #elif IS_CORE SERIAL_ECHOLNPGM("Core"); #else SERIAL_ECHOLNPGM("Cartesian"); #endif SERIAL_ECHOPGM("Probe: "); #if ENABLED(PROBE_MANUALLY) SERIAL_ECHOLNPGM("PROBE_MANUALLY"); #elif ENABLED(FIX_MOUNTED_PROBE) SERIAL_ECHOLNPGM("FIX_MOUNTED_PROBE"); #elif ENABLED(BLTOUCH) SERIAL_ECHOLNPGM("BLTOUCH"); #elif HAS_Z_SERVO_PROBE SERIAL_ECHOLNPGM("SERVO PROBE"); #elif ENABLED(Z_PROBE_SLED) SERIAL_ECHOLNPGM("Z_PROBE_SLED"); #elif ENABLED(Z_PROBE_ALLEN_KEY) SERIAL_ECHOLNPGM("Z_PROBE_ALLEN_KEY"); #else SERIAL_ECHOLNPGM("NONE"); #endif #if HAS_BED_PROBE SERIAL_ECHOPAIR("Probe Offset X:", X_PROBE_OFFSET_FROM_EXTRUDER); SERIAL_ECHOPAIR(" Y:", Y_PROBE_OFFSET_FROM_EXTRUDER); SERIAL_ECHOPAIR(" Z:", zprobe_zoffset); #if X_PROBE_OFFSET_FROM_EXTRUDER > 0 SERIAL_ECHOPGM(" (Right"); #elif X_PROBE_OFFSET_FROM_EXTRUDER < 0 SERIAL_ECHOPGM(" (Left"); #elif Y_PROBE_OFFSET_FROM_EXTRUDER != 0 SERIAL_ECHOPGM(" (Middle"); #else SERIAL_ECHOPGM(" (Aligned With"); #endif #if Y_PROBE_OFFSET_FROM_EXTRUDER > 0 #if IS_SCARA SERIAL_ECHOPGM("-Distal"); #else SERIAL_ECHOPGM("-Back"); #endif #elif Y_PROBE_OFFSET_FROM_EXTRUDER < 0 #if IS_SCARA SERIAL_ECHOPGM("-Proximal"); #else SERIAL_ECHOPGM("-Front"); #endif #elif X_PROBE_OFFSET_FROM_EXTRUDER != 0 SERIAL_ECHOPGM("-Center"); #endif if (zprobe_zoffset < 0) SERIAL_ECHOPGM(" & Below"); else if (zprobe_zoffset > 0) SERIAL_ECHOPGM(" & Above"); else SERIAL_ECHOPGM(" & Same Z as"); SERIAL_ECHOLNPGM(" Nozzle)"); #endif #if HAS_ABL SERIAL_ECHOPGM("Auto Bed Leveling: "); #if ENABLED(AUTO_BED_LEVELING_LINEAR) SERIAL_ECHOPGM("LINEAR"); #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) SERIAL_ECHOPGM("BILINEAR"); #elif ENABLED(AUTO_BED_LEVELING_3POINT) SERIAL_ECHOPGM("3POINT"); #elif ENABLED(AUTO_BED_LEVELING_UBL) SERIAL_ECHOPGM("UBL"); #endif if (planner.leveling_active) { SERIAL_ECHOLNPGM(" (enabled)"); #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) if (planner.z_fade_height) SERIAL_ECHOLNPAIR("Z Fade: ", planner.z_fade_height); #endif #if ABL_PLANAR const float diff[XYZ] = { planner.get_axis_position_mm(X_AXIS) - current_position[X_AXIS], planner.get_axis_position_mm(Y_AXIS) - current_position[Y_AXIS], planner.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS] }; SERIAL_ECHOPGM("ABL Adjustment X"); if (diff[X_AXIS] > 0) SERIAL_CHAR('+'); SERIAL_ECHO(diff[X_AXIS]); SERIAL_ECHOPGM(" Y"); if (diff[Y_AXIS] > 0) SERIAL_CHAR('+'); SERIAL_ECHO(diff[Y_AXIS]); SERIAL_ECHOPGM(" Z"); if (diff[Z_AXIS] > 0) SERIAL_CHAR('+'); SERIAL_ECHO(diff[Z_AXIS]); #else #if ENABLED(AUTO_BED_LEVELING_UBL) SERIAL_ECHOPGM("UBL Adjustment Z"); const float rz = ubl.get_z_correction(current_position[X_AXIS], current_position[Y_AXIS]); #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) SERIAL_ECHOPAIR("Bilinear Grid X", bilinear_start[X_AXIS]); SERIAL_ECHOPAIR(" Y", bilinear_start[Y_AXIS]); SERIAL_ECHOPAIR(" W", ABL_BG_SPACING(X_AXIS)); SERIAL_ECHOLNPAIR(" H", ABL_BG_SPACING(Y_AXIS)); SERIAL_ECHOPGM("ABL Adjustment Z"); const float rz = bilinear_z_offset(current_position); #endif SERIAL_ECHO(ftostr43sign(rz, '+')); #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) if (planner.z_fade_height) { SERIAL_ECHOPAIR(" (", ftostr43sign(rz * planner.fade_scaling_factor_for_z(current_position[Z_AXIS]), '+')); SERIAL_CHAR(')'); } #endif #endif } else SERIAL_ECHOLNPGM(" (disabled)"); SERIAL_EOL(); #elif ENABLED(MESH_BED_LEVELING) SERIAL_ECHOPGM("Mesh Bed Leveling"); if (planner.leveling_active) { SERIAL_ECHOLNPGM(" (enabled)"); SERIAL_ECHOPAIR("MBL Adjustment Z", ftostr43sign(mbl.get_z(current_position[X_AXIS], current_position[Y_AXIS] #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) , 1.0 #endif ), '+')); #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) if (planner.z_fade_height) { SERIAL_ECHOPAIR(" (", ftostr43sign( mbl.get_z(current_position[X_AXIS], current_position[Y_AXIS], planner.fade_scaling_factor_for_z(current_position[Z_AXIS])), '+' )); SERIAL_CHAR(')'); } #endif } else SERIAL_ECHOPGM(" (disabled)"); SERIAL_EOL(); #endif // MESH_BED_LEVELING } #endif // DEBUG_LEVELING_FEATURE #if ENABLED(DELTA) #if ENABLED(SENSORLESS_HOMING) inline void delta_sensorless_homing(const bool on=true) { sensorless_homing_per_axis(A_AXIS, on); sensorless_homing_per_axis(B_AXIS, on); sensorless_homing_per_axis(C_AXIS, on); } #endif /** * A delta can only safely home all axes at the same time * This is like quick_home_xy() but for 3 towers. */ inline void home_delta() { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS(">>> home_delta", current_position); #endif // Init the current position of all carriages to 0,0,0 ZERO(current_position); sync_plan_position(); // Disable stealthChop if used. Enable diag1 pin on driver. #if ENABLED(SENSORLESS_HOMING) delta_sensorless_homing(); #endif // Move all carriages together linearly until an endstop is hit. current_position[X_AXIS] = current_position[Y_AXIS] = current_position[Z_AXIS] = (delta_height + 10 #if HAS_BED_PROBE - zprobe_zoffset #endif ); feedrate_mm_s = homing_feedrate(X_AXIS); buffer_line_to_current_position(); planner.synchronize(); // Re-enable stealthChop if used. Disable diag1 pin on driver. #if ENABLED(SENSORLESS_HOMING) delta_sensorless_homing(false); #endif endstops.validate_homing_move(); // At least one carriage has reached the top. // Now re-home each carriage separately. homeaxis(A_AXIS); homeaxis(B_AXIS); homeaxis(C_AXIS); // Set all carriages to their home positions // Do this here all at once for Delta, because // XYZ isn't ABC. Applying this per-tower would // give the impression that they are the same. LOOP_XYZ(i) set_axis_is_at_home((AxisEnum)i); SYNC_PLAN_POSITION_KINEMATIC(); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("<<< home_delta", current_position); #endif } #elif ENABLED(HANGPRINTER) /** * A hangprinter cannot home itself */ inline void home_hangprinter() { SERIAL_ECHOLNPGM("Warning: G28 is not implemented for Hangprinter."); } #endif #ifdef Z_AFTER_PROBING void move_z_after_probing() { if (current_position[Z_AXIS] != Z_AFTER_PROBING) { do_blocking_move_to_z(Z_AFTER_PROBING); current_position[Z_AXIS] = Z_AFTER_PROBING; } } #endif #if ENABLED(Z_SAFE_HOMING) inline void home_z_safely() { // Disallow Z homing if X or Y are unknown if (!TEST(axis_known_position, X_AXIS) || !TEST(axis_known_position, Y_AXIS)) { LCD_MESSAGEPGM(MSG_ERR_Z_HOMING); SERIAL_ECHO_START(); SERIAL_ECHOLNPGM(MSG_ERR_Z_HOMING); return; } #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Z_SAFE_HOMING >>>"); #endif SYNC_PLAN_POSITION_KINEMATIC(); /** * Move the Z probe (or just the nozzle) to the safe homing point */ destination[X_AXIS] = Z_SAFE_HOMING_X_POINT; destination[Y_AXIS] = Z_SAFE_HOMING_Y_POINT; destination[Z_AXIS] = current_position[Z_AXIS]; // Z is already at the right height #if HOMING_Z_WITH_PROBE destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER; destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER; #endif if (position_is_reachable(destination[X_AXIS], destination[Y_AXIS])) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("Z_SAFE_HOMING", destination); #endif // This causes the carriage on Dual X to unpark #if ENABLED(DUAL_X_CARRIAGE) active_extruder_parked = false; #endif #if ENABLED(SENSORLESS_HOMING) safe_delay(500); // Short delay needed to settle #endif do_blocking_move_to_xy(destination[X_AXIS], destination[Y_AXIS]); homeaxis(Z_AXIS); } else { LCD_MESSAGEPGM(MSG_ZPROBE_OUT); SERIAL_ECHO_START(); SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT); } #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING"); #endif } #endif // Z_SAFE_HOMING #if ENABLED(PROBE_MANUALLY) bool g29_in_progress = false; #else constexpr bool g29_in_progress = false; #endif /** * G28: Home all axes according to settings * * Parameters * * None Home to all axes with no parameters. * With QUICK_HOME enabled XY will home together, then Z. * * O Home only if position is unknown * * Rn Raise by n mm/inches before homing * * Cartesian parameters * * X Home to the X endstop * Y Home to the Y endstop * Z Home to the Z endstop * */ inline void gcode_G28(const bool always_home_all) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOLNPGM(">>> G28"); log_machine_info(); } #endif #if ENABLED(MARLIN_DEV_MODE) if (parser.seen('S')) { LOOP_XYZ(a) set_axis_is_at_home((AxisEnum)a); SYNC_PLAN_POSITION_KINEMATIC(); SERIAL_ECHOLNPGM("Simulated Homing"); report_current_position(); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< G28"); #endif return; } #endif if (all_axes_known() && parser.boolval('O')) { // home only if needed #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOLNPGM("> homing not needed, skip"); SERIAL_ECHOLNPGM("<<< G28"); } #endif return; } // Wait for planner moves to finish! planner.synchronize(); // Cancel the active G29 session #if ENABLED(PROBE_MANUALLY) g29_in_progress = false; #endif // Disable the leveling matrix before homing #if HAS_LEVELING #if ENABLED(RESTORE_LEVELING_AFTER_G28) const bool leveling_was_active = planner.leveling_active; #endif set_bed_leveling_enabled(false); #endif #if ENABLED(CNC_WORKSPACE_PLANES) workspace_plane = PLANE_XY; #endif #if ENABLED(BLTOUCH) // Make sure any BLTouch error condition is cleared bltouch_command(BLTOUCH_RESET); set_bltouch_deployed(false); #endif // Always home with tool 0 active #if HOTENDS > 1 #if DISABLED(DELTA) || ENABLED(DELTA_HOME_TO_SAFE_ZONE) const uint8_t old_tool_index = active_extruder; #endif tool_change(0, 0, true); #endif #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE) extruder_duplication_enabled = false; #endif setup_for_endstop_or_probe_move(); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> endstops.enable(true)"); #endif endstops.enable(true); // Enable endstops for next homing move #if ENABLED(DELTA) home_delta(); UNUSED(always_home_all); #elif ENABLED(HANGPRINTER) home_hangprinter(); UNUSED(always_home_all); #else // NOT Delta or Hangprinter const bool homeX = always_home_all || parser.seen('X'), homeY = always_home_all || parser.seen('Y'), homeZ = always_home_all || parser.seen('Z'), home_all = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ); set_destination_from_current(); #if Z_HOME_DIR > 0 // If homing away from BED do Z first if (home_all || homeZ) homeaxis(Z_AXIS); #endif const float z_homing_height = ( #if ENABLED(UNKNOWN_Z_NO_RAISE) !TEST(axis_known_position, Z_AXIS) ? 0 : #endif (parser.seenval('R') ? parser.value_linear_units() : Z_HOMING_HEIGHT) ); if (z_homing_height && (home_all || homeX || homeY)) { // Raise Z before homing any other axes and z is not already high enough (never lower z) destination[Z_AXIS] = z_homing_height; if (destination[Z_AXIS] > current_position[Z_AXIS]) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("Raise Z (before homing) to ", destination[Z_AXIS]); #endif do_blocking_move_to_z(destination[Z_AXIS]); } } #if ENABLED(QUICK_HOME) if (home_all || (homeX && homeY)) quick_home_xy(); #endif // Home Y (before X) #if ENABLED(HOME_Y_BEFORE_X) if (home_all || homeY #if ENABLED(CODEPENDENT_XY_HOMING) || homeX #endif ) homeaxis(Y_AXIS); #endif // Home X if (home_all || homeX #if ENABLED(CODEPENDENT_XY_HOMING) && DISABLED(HOME_Y_BEFORE_X) || homeY #endif ) { #if ENABLED(DUAL_X_CARRIAGE) // Always home the 2nd (right) extruder first active_extruder = 1; homeaxis(X_AXIS); // Remember this extruder's position for later tool change inactive_extruder_x_pos = current_position[X_AXIS]; // Home the 1st (left) extruder active_extruder = 0; homeaxis(X_AXIS); // Consider the active extruder to be parked COPY(raised_parked_position, current_position); delayed_move_time = 0; active_extruder_parked = true; #else homeaxis(X_AXIS); #endif } // Home Y (after X) #if DISABLED(HOME_Y_BEFORE_X) if (home_all || homeY) homeaxis(Y_AXIS); #endif // Home Z last if homing towards the bed #if Z_HOME_DIR < 0 if (home_all || homeZ) { #if ENABLED(Z_SAFE_HOMING) home_z_safely(); #else homeaxis(Z_AXIS); #endif #if HOMING_Z_WITH_PROBE && defined(Z_AFTER_PROBING) move_z_after_probing(); #endif } // home_all || homeZ #endif // Z_HOME_DIR < 0 SYNC_PLAN_POSITION_KINEMATIC(); #endif // !DELTA (gcode_G28) endstops.not_homing(); #if ENABLED(DELTA) && ENABLED(DELTA_HOME_TO_SAFE_ZONE) // move to a height where we can use the full xy-area do_blocking_move_to_z(delta_clip_start_height); #endif #if ENABLED(RESTORE_LEVELING_AFTER_G28) set_bed_leveling_enabled(leveling_was_active); #endif clean_up_after_endstop_or_probe_move(); // Restore the active tool after homing #if HOTENDS > 1 && (DISABLED(DELTA) || ENABLED(DELTA_HOME_TO_SAFE_ZONE)) #if ENABLED(PARKING_EXTRUDER) #define NO_FETCH false // fetch the previous toolhead #else #define NO_FETCH true #endif tool_change(old_tool_index, 0, NO_FETCH); #endif lcd_refresh(); report_current_position(); #if ENABLED(NANODLP_Z_SYNC) #if ENABLED(NANODLP_ALL_AXIS) #define _HOME_SYNC true // For any axis, output sync text. #else #define _HOME_SYNC (home_all || homeZ) // Only for Z-axis #endif if (_HOME_SYNC) SERIAL_ECHOLNPGM(MSG_Z_MOVE_COMP); #endif #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< G28"); #endif } // G28 void home_all_axes() { gcode_G28(true); } #if ENABLED(MESH_BED_LEVELING) || ENABLED(PROBE_MANUALLY) inline void _manual_goto_xy(const float &rx, const float &ry) { #ifdef MANUAL_PROBE_START_Z #if MANUAL_PROBE_HEIGHT > 0 do_blocking_move_to(rx, ry, MANUAL_PROBE_HEIGHT); do_blocking_move_to_z(MAX(0,MANUAL_PROBE_START_Z)); #else do_blocking_move_to(rx, ry, MAX(0,MANUAL_PROBE_START_Z)); #endif #elif MANUAL_PROBE_HEIGHT > 0 const float prev_z = current_position[Z_AXIS]; do_blocking_move_to(rx, ry, MANUAL_PROBE_HEIGHT); do_blocking_move_to_z(prev_z); #else do_blocking_move_to_xy(rx, ry); #endif current_position[X_AXIS] = rx; current_position[Y_AXIS] = ry; #if ENABLED(LCD_BED_LEVELING) lcd_wait_for_move = false; #endif } #endif #if ENABLED(MESH_BED_LEVELING) // Save 130 bytes with non-duplication of PSTR void echo_not_entered() { SERIAL_PROTOCOLLNPGM(" not entered."); } /** * G29: Mesh-based Z probe, probes a grid and produces a * mesh to compensate for variable bed height * * Parameters With MESH_BED_LEVELING: * * S0 Produce a mesh report * S1 Start probing mesh points * S2 Probe the next mesh point * S3 Xn Yn Zn.nn Manually modify a single point * S4 Zn.nn Set z offset. Positive away from bed, negative closer to bed. * S5 Reset and disable mesh * * The S0 report the points as below * * +----> X-axis 1-n * | * | * v Y-axis 1-n * */ inline void gcode_G29() { static int mbl_probe_index = -1; #if HAS_SOFTWARE_ENDSTOPS static bool enable_soft_endstops; #endif MeshLevelingState state = (MeshLevelingState)parser.byteval('S', (int8_t)MeshReport); if (!WITHIN(state, 0, 5)) { SERIAL_PROTOCOLLNPGM("S out of range (0-5)."); return; } int8_t px, py; switch (state) { case MeshReport: if (leveling_is_valid()) { SERIAL_PROTOCOLLNPAIR("State: ", planner.leveling_active ? MSG_ON : MSG_OFF); mbl.report_mesh(); } else SERIAL_PROTOCOLLNPGM("Mesh bed leveling has no data."); break; case MeshStart: mbl.reset(); mbl_probe_index = 0; if (!lcd_wait_for_move) { enqueue_and_echo_commands_P(PSTR("G28\nG29 S2")); return; } state = MeshNext; case MeshNext: if (mbl_probe_index < 0) { SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first."); return; } // For each G29 S2... if (mbl_probe_index == 0) { #if HAS_SOFTWARE_ENDSTOPS // For the initial G29 S2 save software endstop state enable_soft_endstops = soft_endstops_enabled; #endif // Move close to the bed before the first point do_blocking_move_to_z(0); } else { // Save Z for the previous mesh position mbl.set_zigzag_z(mbl_probe_index - 1, current_position[Z_AXIS]); #if HAS_SOFTWARE_ENDSTOPS soft_endstops_enabled = enable_soft_endstops; #endif } // If there's another point to sample, move there with optional lift. if (mbl_probe_index < GRID_MAX_POINTS) { #if HAS_SOFTWARE_ENDSTOPS // Disable software endstops to allow manual adjustment // If G29 is not completed, they will not be re-enabled soft_endstops_enabled = false; #endif mbl.zigzag(mbl_probe_index++, px, py); _manual_goto_xy(mbl.index_to_xpos[px], mbl.index_to_ypos[py]); } else { // One last "return to the bed" (as originally coded) at completion current_position[Z_AXIS] = MANUAL_PROBE_HEIGHT; buffer_line_to_current_position(); planner.synchronize(); // After recording the last point, activate home and activate mbl_probe_index = -1; SERIAL_PROTOCOLLNPGM("Mesh probing done."); BUZZ(100, 659); BUZZ(100, 698); home_all_axes(); set_bed_leveling_enabled(true); #if ENABLED(MESH_G28_REST_ORIGIN) current_position[Z_AXIS] = 0; set_destination_from_current(); buffer_line_to_destination(homing_feedrate(Z_AXIS)); planner.synchronize(); #endif #if ENABLED(LCD_BED_LEVELING) lcd_wait_for_move = false; #endif } break; case MeshSet: if (parser.seenval('X')) { px = parser.value_int() - 1; if (!WITHIN(px, 0, GRID_MAX_POINTS_X - 1)) { SERIAL_PROTOCOLPAIR("X out of range (1-", int(GRID_MAX_POINTS_X)); SERIAL_PROTOCOLLNPGM(")"); return; } } else { SERIAL_CHAR('X'); echo_not_entered(); return; } if (parser.seenval('Y')) { py = parser.value_int() - 1; if (!WITHIN(py, 0, GRID_MAX_POINTS_Y - 1)) { SERIAL_PROTOCOLPAIR("Y out of range (1-", int(GRID_MAX_POINTS_Y)); SERIAL_PROTOCOLLNPGM(")"); return; } } else { SERIAL_CHAR('Y'); echo_not_entered(); return; } if (parser.seenval('Z')) mbl.z_values[px][py] = parser.value_linear_units(); else { SERIAL_CHAR('Z'); echo_not_entered(); return; } break; case MeshSetZOffset: if (parser.seenval('Z')) mbl.z_offset = parser.value_linear_units(); else { SERIAL_CHAR('Z'); echo_not_entered(); return; } break; case MeshReset: reset_bed_level(); break; } // switch (state) if (state == MeshNext) { SERIAL_PROTOCOLPAIR("MBL G29 point ", MIN(mbl_probe_index, GRID_MAX_POINTS)); SERIAL_PROTOCOLLNPAIR(" of ", int(GRID_MAX_POINTS)); } report_current_position(); } #elif OLDSCHOOL_ABL #if ABL_GRID #if ENABLED(PROBE_Y_FIRST) #define PR_OUTER_VAR xCount #define PR_OUTER_END abl_grid_points_x #define PR_INNER_VAR yCount #define PR_INNER_END abl_grid_points_y #else #define PR_OUTER_VAR yCount #define PR_OUTER_END abl_grid_points_y #define PR_INNER_VAR xCount #define PR_INNER_END abl_grid_points_x #endif #endif /** * G29: Detailed Z probe, probes the bed at 3 or more points. * Will fail if the printer has not been homed with G28. * * Enhanced G29 Auto Bed Leveling Probe Routine * * O Auto-level only if needed * * D Dry-Run mode. Just evaluate the bed Topology - Don't apply * or alter the bed level data. Useful to check the topology * after a first run of G29. * * J Jettison current bed leveling data * * V Set the verbose level (0-4). Example: "G29 V3" * * Parameters With LINEAR leveling only: * * P Set the size of the grid that will be probed (P x P points). * Example: "G29 P4" * * X Set the X size of the grid that will be probed (X x Y points). * Example: "G29 X7 Y5" * * Y Set the Y size of the grid that will be probed (X x Y points). * * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report. * This is useful for manual bed leveling and finding flaws in the bed (to * assist with part placement). * Not supported by non-linear delta printer bed leveling. * * Parameters With LINEAR and BILINEAR leveling only: * * S Set the XY travel speed between probe points (in units/min) * * F Set the Front limit of the probing grid * B Set the Back limit of the probing grid * L Set the Left limit of the probing grid * R Set the Right limit of the probing grid * * Parameters with DEBUG_LEVELING_FEATURE only: * * C Make a totally fake grid with no actual probing. * For use in testing when no probing is possible. * * Parameters with BILINEAR leveling only: * * Z Supply an additional Z probe offset * * Extra parameters with PROBE_MANUALLY: * * To do manual probing simply repeat G29 until the procedure is complete. * The first G29 accepts parameters. 'G29 Q' for status, 'G29 A' to abort. * * Q Query leveling and G29 state * * A Abort current leveling procedure * * Extra parameters with BILINEAR only: * * W Write a mesh point. (If G29 is idle.) * I X index for mesh point * J Y index for mesh point * X X for mesh point, overrides I * Y Y for mesh point, overrides J * Z Z for mesh point. Otherwise, raw current Z. * * Without PROBE_MANUALLY: * * E By default G29 will engage the Z probe, test the bed, then disengage. * Include "E" to engage/disengage the Z probe for each sample. * There's no extra effect if you have a fixed Z probe. * */ inline void gcode_G29() { #if ENABLED(DEBUG_LEVELING_FEATURE) || ENABLED(PROBE_MANUALLY) const bool seenQ = parser.seen('Q'); #else constexpr bool seenQ = false; #endif // G29 Q is also available if debugging #if ENABLED(DEBUG_LEVELING_FEATURE) const uint8_t old_debug_flags = marlin_debug_flags; if (seenQ) marlin_debug_flags |= DEBUG_LEVELING; if (DEBUGGING(LEVELING)) { DEBUG_POS(">>> G29", current_position); log_machine_info(); } marlin_debug_flags = old_debug_flags; #if DISABLED(PROBE_MANUALLY) if (seenQ) return; #endif #endif #if ENABLED(PROBE_MANUALLY) const bool seenA = parser.seen('A'); #else constexpr bool seenA = false; #endif const bool no_action = seenA || seenQ, faux = #if ENABLED(DEBUG_LEVELING_FEATURE) && DISABLED(PROBE_MANUALLY) parser.boolval('C') #else no_action #endif ; // Don't allow auto-leveling without homing first if (axis_unhomed_error()) return; if (!no_action && planner.leveling_active && parser.boolval('O')) { // Auto-level only if needed #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOLNPGM("> Auto-level not needed, skip"); SERIAL_ECHOLNPGM("<<< G29"); } #endif return; } // Define local vars 'static' for manual probing, 'auto' otherwise #if ENABLED(PROBE_MANUALLY) #define ABL_VAR static #else #define ABL_VAR #endif ABL_VAR int verbose_level; ABL_VAR float xProbe, yProbe, measured_z; ABL_VAR bool dryrun, abl_should_enable; #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR) ABL_VAR int16_t abl_probe_index; #endif #if HAS_SOFTWARE_ENDSTOPS && ENABLED(PROBE_MANUALLY) ABL_VAR bool enable_soft_endstops = true; #endif #if ABL_GRID #if ENABLED(PROBE_MANUALLY) ABL_VAR uint8_t PR_OUTER_VAR; ABL_VAR int8_t PR_INNER_VAR; #endif ABL_VAR int left_probe_bed_position, right_probe_bed_position, front_probe_bed_position, back_probe_bed_position; ABL_VAR float xGridSpacing = 0, yGridSpacing = 0; #if ENABLED(AUTO_BED_LEVELING_LINEAR) ABL_VAR uint8_t abl_grid_points_x = GRID_MAX_POINTS_X, abl_grid_points_y = GRID_MAX_POINTS_Y; ABL_VAR bool do_topography_map; #else // Bilinear uint8_t constexpr abl_grid_points_x = GRID_MAX_POINTS_X, abl_grid_points_y = GRID_MAX_POINTS_Y; #endif #if ENABLED(AUTO_BED_LEVELING_LINEAR) ABL_VAR int16_t abl_points; #elif ENABLED(PROBE_MANUALLY) // Bilinear int16_t constexpr abl_points = GRID_MAX_POINTS; #endif #if ENABLED(AUTO_BED_LEVELING_BILINEAR) ABL_VAR float zoffset; #elif ENABLED(AUTO_BED_LEVELING_LINEAR) ABL_VAR int indexIntoAB[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y]; ABL_VAR float eqnAMatrix[GRID_MAX_POINTS * 3], // "A" matrix of the linear system of equations eqnBVector[GRID_MAX_POINTS], // "B" vector of Z points mean; #endif #elif ENABLED(AUTO_BED_LEVELING_3POINT) #if ENABLED(PROBE_MANUALLY) int8_t constexpr abl_points = 3; // used to show total points #endif // Probe at 3 arbitrary points ABL_VAR vector_3 points[3] = { vector_3(PROBE_PT_1_X, PROBE_PT_1_Y, 0), vector_3(PROBE_PT_2_X, PROBE_PT_2_Y, 0), vector_3(PROBE_PT_3_X, PROBE_PT_3_Y, 0) }; #endif // AUTO_BED_LEVELING_3POINT #if ENABLED(AUTO_BED_LEVELING_LINEAR) struct linear_fit_data lsf_results; incremental_LSF_reset(&lsf_results); #endif /** * On the initial G29 fetch command parameters. */ if (!g29_in_progress) { #if ENABLED(DUAL_X_CARRIAGE) if (active_extruder != 0) tool_change(0); #endif #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR) abl_probe_index = -1; #endif abl_should_enable = planner.leveling_active; #if ENABLED(AUTO_BED_LEVELING_BILINEAR) const bool seen_w = parser.seen('W'); if (seen_w) { if (!leveling_is_valid()) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM("No bilinear grid"); return; } const float rz = parser.seenval('Z') ? RAW_Z_POSITION(parser.value_linear_units()) : current_position[Z_AXIS]; if (!WITHIN(rz, -10, 10)) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM("Bad Z value"); return; } const float rx = RAW_X_POSITION(parser.linearval('X', NAN)), ry = RAW_Y_POSITION(parser.linearval('Y', NAN)); int8_t i = parser.byteval('I', -1), j = parser.byteval('J', -1); if (!isnan(rx) && !isnan(ry)) { // Get nearest i / j from rx / ry i = (rx - bilinear_start[X_AXIS] + 0.5f * xGridSpacing) / xGridSpacing; j = (ry - bilinear_start[Y_AXIS] + 0.5f * yGridSpacing) / yGridSpacing; i = constrain(i, 0, GRID_MAX_POINTS_X - 1); j = constrain(j, 0, GRID_MAX_POINTS_Y - 1); } if (WITHIN(i, 0, GRID_MAX_POINTS_X - 1) && WITHIN(j, 0, GRID_MAX_POINTS_Y)) { set_bed_leveling_enabled(false); z_values[i][j] = rz; #if ENABLED(ABL_BILINEAR_SUBDIVISION) bed_level_virt_interpolate(); #endif set_bed_leveling_enabled(abl_should_enable); if (abl_should_enable) report_current_position(); } return; } // parser.seen('W') #else constexpr bool seen_w = false; #endif // Jettison bed leveling data if (!seen_w && parser.seen('J')) { reset_bed_level(); return; } verbose_level = parser.intval('V'); if (!WITHIN(verbose_level, 0, 4)) { SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4)."); return; } dryrun = parser.boolval('D') #if ENABLED(PROBE_MANUALLY) || no_action #endif ; #if ENABLED(AUTO_BED_LEVELING_LINEAR) do_topography_map = verbose_level > 2 || parser.boolval('T'); // X and Y specify points in each direction, overriding the default // These values may be saved with the completed mesh abl_grid_points_x = parser.intval('X', GRID_MAX_POINTS_X); abl_grid_points_y = parser.intval('Y', GRID_MAX_POINTS_Y); if (parser.seenval('P')) abl_grid_points_x = abl_grid_points_y = parser.value_int(); if (!WITHIN(abl_grid_points_x, 2, GRID_MAX_POINTS_X)) { SERIAL_PROTOCOLLNPGM("?Probe points (X) is implausible (2-" STRINGIFY(GRID_MAX_POINTS_X) ")."); return; } if (!WITHIN(abl_grid_points_y, 2, GRID_MAX_POINTS_Y)) { SERIAL_PROTOCOLLNPGM("?Probe points (Y) is implausible (2-" STRINGIFY(GRID_MAX_POINTS_Y) ")."); return; } abl_points = abl_grid_points_x * abl_grid_points_y; mean = 0; #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) zoffset = parser.linearval('Z'); #endif #if ABL_GRID xy_probe_feedrate_mm_s = MMM_TO_MMS(parser.linearval('S', XY_PROBE_SPEED)); left_probe_bed_position = parser.seenval('L') ? int(RAW_X_POSITION(parser.value_linear_units())) : LEFT_PROBE_BED_POSITION; right_probe_bed_position = parser.seenval('R') ? int(RAW_X_POSITION(parser.value_linear_units())) : RIGHT_PROBE_BED_POSITION; front_probe_bed_position = parser.seenval('F') ? int(RAW_Y_POSITION(parser.value_linear_units())) : FRONT_PROBE_BED_POSITION; back_probe_bed_position = parser.seenval('B') ? int(RAW_Y_POSITION(parser.value_linear_units())) : BACK_PROBE_BED_POSITION; if ( #if IS_SCARA || ENABLED(DELTA) !position_is_reachable_by_probe(left_probe_bed_position, 0) || !position_is_reachable_by_probe(right_probe_bed_position, 0) || !position_is_reachable_by_probe(0, front_probe_bed_position) || !position_is_reachable_by_probe(0, back_probe_bed_position) #else !position_is_reachable_by_probe(left_probe_bed_position, front_probe_bed_position) || !position_is_reachable_by_probe(right_probe_bed_position, back_probe_bed_position) #endif ) { SERIAL_PROTOCOLLNPGM("? (L,R,F,B) out of bounds."); return; } // probe at the points of a lattice grid xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (abl_grid_points_x - 1); yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (abl_grid_points_y - 1); #endif // ABL_GRID if (verbose_level > 0) { SERIAL_PROTOCOLPGM("G29 Auto Bed Leveling"); if (dryrun) SERIAL_PROTOCOLPGM(" (DRYRUN)"); SERIAL_EOL(); } planner.synchronize(); // Disable auto bed leveling during G29. // Be formal so G29 can be done successively without G28. if (!no_action) set_bed_leveling_enabled(false); #if HAS_BED_PROBE // Deploy the probe. Probe will raise if needed. if (DEPLOY_PROBE()) { set_bed_leveling_enabled(abl_should_enable); return; } #endif if (!faux) setup_for_endstop_or_probe_move(); #if ENABLED(AUTO_BED_LEVELING_BILINEAR) #if ENABLED(PROBE_MANUALLY) if (!no_action) #endif if ( xGridSpacing != bilinear_grid_spacing[X_AXIS] || yGridSpacing != bilinear_grid_spacing[Y_AXIS] || left_probe_bed_position != bilinear_start[X_AXIS] || front_probe_bed_position != bilinear_start[Y_AXIS] ) { // Reset grid to 0.0 or "not probed". (Also disables ABL) reset_bed_level(); // Initialize a grid with the given dimensions bilinear_grid_spacing[X_AXIS] = xGridSpacing; bilinear_grid_spacing[Y_AXIS] = yGridSpacing; bilinear_start[X_AXIS] = left_probe_bed_position; bilinear_start[Y_AXIS] = front_probe_bed_position; // Can't re-enable (on error) until the new grid is written abl_should_enable = false; } #endif // AUTO_BED_LEVELING_BILINEAR #if ENABLED(AUTO_BED_LEVELING_3POINT) #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> 3-point Leveling"); #endif // Probe at 3 arbitrary points points[0].z = points[1].z = points[2].z = 0; #endif // AUTO_BED_LEVELING_3POINT } // !g29_in_progress #if ENABLED(PROBE_MANUALLY) // For manual probing, get the next index to probe now. // On the first probe this will be incremented to 0. if (!no_action) { ++abl_probe_index; g29_in_progress = true; } // Abort current G29 procedure, go back to idle state if (seenA && g29_in_progress) { SERIAL_PROTOCOLLNPGM("Manual G29 aborted"); #if HAS_SOFTWARE_ENDSTOPS soft_endstops_enabled = enable_soft_endstops; #endif set_bed_leveling_enabled(abl_should_enable); g29_in_progress = false; #if ENABLED(LCD_BED_LEVELING) lcd_wait_for_move = false; #endif } // Query G29 status if (verbose_level || seenQ) { SERIAL_PROTOCOLPGM("Manual G29 "); if (g29_in_progress) { SERIAL_PROTOCOLPAIR("point ", MIN(abl_probe_index + 1, abl_points)); SERIAL_PROTOCOLLNPAIR(" of ", abl_points); } else SERIAL_PROTOCOLLNPGM("idle"); } if (no_action) return; if (abl_probe_index == 0) { // For the initial G29 save software endstop state #if HAS_SOFTWARE_ENDSTOPS enable_soft_endstops = soft_endstops_enabled; #endif // Move close to the bed before the first point do_blocking_move_to_z(0); } else { #if ENABLED(AUTO_BED_LEVELING_LINEAR) || ENABLED(AUTO_BED_LEVELING_3POINT) const uint16_t index = abl_probe_index - 1; #endif // For G29 after adjusting Z. // Save the previous Z before going to the next point measured_z = current_position[Z_AXIS]; #if ENABLED(AUTO_BED_LEVELING_LINEAR) mean += measured_z; eqnBVector[index] = measured_z; eqnAMatrix[index + 0 * abl_points] = xProbe; eqnAMatrix[index + 1 * abl_points] = yProbe; eqnAMatrix[index + 2 * abl_points] = 1; incremental_LSF(&lsf_results, xProbe, yProbe, measured_z); #elif ENABLED(AUTO_BED_LEVELING_3POINT) points[index].z = measured_z; #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) z_values[xCount][yCount] = measured_z + zoffset; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_PROTOCOLPAIR("Save X", xCount); SERIAL_PROTOCOLPAIR(" Y", yCount); SERIAL_PROTOCOLLNPAIR(" Z", measured_z + zoffset); } #endif #endif } // // If there's another point to sample, move there with optional lift. // #if ABL_GRID // Skip any unreachable points while (abl_probe_index < abl_points) { // Set xCount, yCount based on abl_probe_index, with zig-zag PR_OUTER_VAR = abl_probe_index / PR_INNER_END; PR_INNER_VAR = abl_probe_index - (PR_OUTER_VAR * PR_INNER_END); // Probe in reverse order for every other row/column bool zig = (PR_OUTER_VAR & 1); // != ((PR_OUTER_END) & 1); if (zig) PR_INNER_VAR = (PR_INNER_END - 1) - PR_INNER_VAR; const float xBase = xCount * xGridSpacing + left_probe_bed_position, yBase = yCount * yGridSpacing + front_probe_bed_position; xProbe = FLOOR(xBase + (xBase < 0 ? 0 : 0.5)); yProbe = FLOOR(yBase + (yBase < 0 ? 0 : 0.5)); #if ENABLED(AUTO_BED_LEVELING_LINEAR) indexIntoAB[xCount][yCount] = abl_probe_index; #endif // Keep looping till a reachable point is found if (position_is_reachable(xProbe, yProbe)) break; ++abl_probe_index; } // Is there a next point to move to? if (abl_probe_index < abl_points) { _manual_goto_xy(xProbe, yProbe); // Can be used here too! #if HAS_SOFTWARE_ENDSTOPS // Disable software endstops to allow manual adjustment // If G29 is not completed, they will not be re-enabled soft_endstops_enabled = false; #endif return; } else { // Leveling done! Fall through to G29 finishing code below SERIAL_PROTOCOLLNPGM("Grid probing done."); // Re-enable software endstops, if needed #if HAS_SOFTWARE_ENDSTOPS soft_endstops_enabled = enable_soft_endstops; #endif } #elif ENABLED(AUTO_BED_LEVELING_3POINT) // Probe at 3 arbitrary points if (abl_probe_index < abl_points) { xProbe = points[abl_probe_index].x; yProbe = points[abl_probe_index].y; _manual_goto_xy(xProbe, yProbe); #if HAS_SOFTWARE_ENDSTOPS // Disable software endstops to allow manual adjustment // If G29 is not completed, they will not be re-enabled soft_endstops_enabled = false; #endif return; } else { SERIAL_PROTOCOLLNPGM("3-point probing done."); // Re-enable software endstops, if needed #if HAS_SOFTWARE_ENDSTOPS soft_endstops_enabled = enable_soft_endstops; #endif if (!dryrun) { vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal(); if (planeNormal.z < 0) { planeNormal.x *= -1; planeNormal.y *= -1; planeNormal.z *= -1; } planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal); // Can't re-enable (on error) until the new grid is written abl_should_enable = false; } } #endif // AUTO_BED_LEVELING_3POINT #else // !PROBE_MANUALLY { const ProbePtRaise raise_after = parser.boolval('E') ? PROBE_PT_STOW : PROBE_PT_RAISE; measured_z = 0; #if ABL_GRID bool zig = PR_OUTER_END & 1; // Always end at RIGHT and BACK_PROBE_BED_POSITION measured_z = 0; // Outer loop is Y with PROBE_Y_FIRST disabled for (uint8_t PR_OUTER_VAR = 0; PR_OUTER_VAR < PR_OUTER_END && !isnan(measured_z); PR_OUTER_VAR++) { int8_t inStart, inStop, inInc; if (zig) { // away from origin inStart = 0; inStop = PR_INNER_END; inInc = 1; } else { // towards origin inStart = PR_INNER_END - 1; inStop = -1; inInc = -1; } zig ^= true; // zag // Inner loop is Y with PROBE_Y_FIRST enabled for (int8_t PR_INNER_VAR = inStart; PR_INNER_VAR != inStop; PR_INNER_VAR += inInc) { float xBase = left_probe_bed_position + xGridSpacing * xCount, yBase = front_probe_bed_position + yGridSpacing * yCount; xProbe = FLOOR(xBase + (xBase < 0 ? 0 : 0.5)); yProbe = FLOOR(yBase + (yBase < 0 ? 0 : 0.5)); #if ENABLED(AUTO_BED_LEVELING_LINEAR) indexIntoAB[xCount][yCount] = ++abl_probe_index; // 0... #endif #if IS_KINEMATIC // Avoid probing outside the round or hexagonal area if (!position_is_reachable_by_probe(xProbe, yProbe)) continue; #endif measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, raise_after, verbose_level); if (isnan(measured_z)) { set_bed_leveling_enabled(abl_should_enable); break; } #if ENABLED(AUTO_BED_LEVELING_LINEAR) mean += measured_z; eqnBVector[abl_probe_index] = measured_z; eqnAMatrix[abl_probe_index + 0 * abl_points] = xProbe; eqnAMatrix[abl_probe_index + 1 * abl_points] = yProbe; eqnAMatrix[abl_probe_index + 2 * abl_points] = 1; incremental_LSF(&lsf_results, xProbe, yProbe, measured_z); #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) z_values[xCount][yCount] = measured_z + zoffset; #endif abl_should_enable = false; idle(); } // inner } // outer #elif ENABLED(AUTO_BED_LEVELING_3POINT) // Probe at 3 arbitrary points for (uint8_t i = 0; i < 3; ++i) { // Retain the last probe position xProbe = points[i].x; yProbe = points[i].y; measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, raise_after, verbose_level); if (isnan(measured_z)) { set_bed_leveling_enabled(abl_should_enable); break; } points[i].z = measured_z; } if (!dryrun && !isnan(measured_z)) { vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal(); if (planeNormal.z < 0) { planeNormal.x *= -1; planeNormal.y *= -1; planeNormal.z *= -1; } planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal); // Can't re-enable (on error) until the new grid is written abl_should_enable = false; } #endif // AUTO_BED_LEVELING_3POINT // Stow the probe. No raise for FIX_MOUNTED_PROBE. if (STOW_PROBE()) { set_bed_leveling_enabled(abl_should_enable); measured_z = NAN; } } #endif // !PROBE_MANUALLY // // G29 Finishing Code // // Unless this is a dry run, auto bed leveling will // definitely be enabled after this point. // // If code above wants to continue leveling, it should // return or loop before this point. // #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("> probing complete", current_position); #endif #if ENABLED(PROBE_MANUALLY) g29_in_progress = false; #if ENABLED(LCD_BED_LEVELING) lcd_wait_for_move = false; #endif #endif // Calculate leveling, print reports, correct the position if (!isnan(measured_z)) { #if ENABLED(AUTO_BED_LEVELING_BILINEAR) if (!dryrun) extrapolate_unprobed_bed_level(); print_bilinear_leveling_grid(); refresh_bed_level(); #if ENABLED(ABL_BILINEAR_SUBDIVISION) print_bilinear_leveling_grid_virt(); #endif #elif ENABLED(AUTO_BED_LEVELING_LINEAR) // For LINEAR leveling calculate matrix, print reports, correct the position /** * solve the plane equation ax + by + d = z * A is the matrix with rows [x y 1] for all the probed points * B is the vector of the Z positions * the normal vector to the plane is formed by the coefficients of the * plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0 * so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z */ float plane_equation_coefficients[3]; finish_incremental_LSF(&lsf_results); plane_equation_coefficients[0] = -lsf_results.A; // We should be able to eliminate the '-' on these three lines and down below plane_equation_coefficients[1] = -lsf_results.B; // but that is not yet tested. plane_equation_coefficients[2] = -lsf_results.D; mean /= abl_points; if (verbose_level) { SERIAL_PROTOCOLPGM("Eqn coefficients: a: "); SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8); SERIAL_PROTOCOLPGM(" b: "); SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8); SERIAL_PROTOCOLPGM(" d: "); SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8); SERIAL_EOL(); if (verbose_level > 2) { SERIAL_PROTOCOLPGM("Mean of sampled points: "); SERIAL_PROTOCOL_F(mean, 8); SERIAL_EOL(); } } // Create the matrix but don't correct the position yet if (!dryrun) planner.bed_level_matrix = matrix_3x3::create_look_at( vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1) // We can eliminate the '-' here and up above ); // Show the Topography map if enabled if (do_topography_map) { SERIAL_PROTOCOLLNPGM("\nBed Height Topography:\n" " +--- BACK --+\n" " | |\n" " L | (+) | R\n" " E | | I\n" " F | (-) N (+) | G\n" " T | | H\n" " | (-) | T\n" " | |\n" " O-- FRONT --+\n" " (0,0)"); float min_diff = 999; for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) { for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) { int ind = indexIntoAB[xx][yy]; float diff = eqnBVector[ind] - mean, x_tmp = eqnAMatrix[ind + 0 * abl_points], y_tmp = eqnAMatrix[ind + 1 * abl_points], z_tmp = 0; apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp); NOMORE(min_diff, eqnBVector[ind] - z_tmp); if (diff >= 0.0) SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment else SERIAL_PROTOCOLCHAR(' '); SERIAL_PROTOCOL_F(diff, 5); } // xx SERIAL_EOL(); } // yy SERIAL_EOL(); if (verbose_level > 3) { SERIAL_PROTOCOLLNPGM("\nCorrected Bed Height vs. Bed Topology:"); for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) { for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) { int ind = indexIntoAB[xx][yy]; float x_tmp = eqnAMatrix[ind + 0 * abl_points], y_tmp = eqnAMatrix[ind + 1 * abl_points], z_tmp = 0; apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp); float diff = eqnBVector[ind] - z_tmp - min_diff; if (diff >= 0.0) SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment else SERIAL_PROTOCOLCHAR(' '); SERIAL_PROTOCOL_F(diff, 5); } // xx SERIAL_EOL(); } // yy SERIAL_EOL(); } } //do_topography_map #endif // AUTO_BED_LEVELING_LINEAR #if ABL_PLANAR // For LINEAR and 3POINT leveling correct the current position if (verbose_level > 0) planner.bed_level_matrix.debug(PSTR("\n\nBed Level Correction Matrix:")); if (!dryrun) { // // Correct the current XYZ position based on the tilted plane. // #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("G29 uncorrected XYZ", current_position); #endif float converted[XYZ]; COPY(converted, current_position); planner.leveling_active = true; planner.unapply_leveling(converted); // use conversion machinery planner.leveling_active = false; // Use the last measured distance to the bed, if possible if ( NEAR(current_position[X_AXIS], xProbe - (X_PROBE_OFFSET_FROM_EXTRUDER)) && NEAR(current_position[Y_AXIS], yProbe - (Y_PROBE_OFFSET_FROM_EXTRUDER)) ) { const float simple_z = current_position[Z_AXIS] - measured_z; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("Z from Probe:", simple_z); SERIAL_ECHOPAIR(" Matrix:", converted[Z_AXIS]); SERIAL_ECHOLNPAIR(" Discrepancy:", simple_z - converted[Z_AXIS]); } #endif converted[Z_AXIS] = simple_z; } // The rotated XY and corrected Z are now current_position COPY(current_position, converted); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("G29 corrected XYZ", current_position); #endif } #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) if (!dryrun) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("G29 uncorrected Z:", current_position[Z_AXIS]); #endif // Unapply the offset because it is going to be immediately applied // and cause compensation movement in Z current_position[Z_AXIS] -= bilinear_z_offset(current_position); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR(" corrected Z:", current_position[Z_AXIS]); #endif } #endif // ABL_PLANAR #ifdef Z_PROBE_END_SCRIPT #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("Z Probe End Script: ", Z_PROBE_END_SCRIPT); #endif planner.synchronize(); enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT)); #endif // Auto Bed Leveling is complete! Enable if possible. planner.leveling_active = dryrun ? abl_should_enable : true; } // !isnan(measured_z) // Restore state after probing if (!faux) clean_up_after_endstop_or_probe_move(); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< G29"); #endif KEEPALIVE_STATE(IN_HANDLER); if (planner.leveling_active) SYNC_PLAN_POSITION_KINEMATIC(); #if HAS_BED_PROBE && defined(Z_AFTER_PROBING) move_z_after_probing(); #endif report_current_position(); } #endif // OLDSCHOOL_ABL #if HAS_BED_PROBE /** * G30: Do a single Z probe at the current XY * * Parameters: * * X Probe X position (default current X) * Y Probe Y position (default current Y) * E Engage the probe for each probe (default 1) */ inline void gcode_G30() { const float xpos = parser.linearval('X', current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER), ypos = parser.linearval('Y', current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER); if (!position_is_reachable_by_probe(xpos, ypos)) return; // Disable leveling so the planner won't mess with us #if HAS_LEVELING set_bed_leveling_enabled(false); #endif setup_for_endstop_or_probe_move(); const ProbePtRaise raise_after = parser.boolval('E', true) ? PROBE_PT_STOW : PROBE_PT_NONE; const float measured_z = probe_pt(xpos, ypos, raise_after, parser.intval('V', 1)); if (!isnan(measured_z)) { SERIAL_PROTOCOLPAIR_F("Bed X: ", xpos); SERIAL_PROTOCOLPAIR_F(" Y: ", ypos); SERIAL_PROTOCOLLNPAIR_F(" Z: ", measured_z); } clean_up_after_endstop_or_probe_move(); #ifdef Z_AFTER_PROBING if (raise_after == PROBE_PT_STOW) move_z_after_probing(); #endif report_current_position(); } #if ENABLED(Z_PROBE_SLED) /** * G31: Deploy the Z probe */ inline void gcode_G31() { DEPLOY_PROBE(); } /** * G32: Stow the Z probe */ inline void gcode_G32() { STOW_PROBE(); } #endif // Z_PROBE_SLED #endif // HAS_BED_PROBE #if ENABLED(DELTA_AUTO_CALIBRATION) constexpr uint8_t _7P_STEP = 1, // 7-point step - to change number of calibration points _4P_STEP = _7P_STEP * 2, // 4-point step NPP = _7P_STEP * 6; // number of calibration points on the radius enum CalEnum : char { // the 7 main calibration points - add definitions if needed CEN = 0, __A = 1, _AB = __A + _7P_STEP, __B = _AB + _7P_STEP, _BC = __B + _7P_STEP, __C = _BC + _7P_STEP, _CA = __C + _7P_STEP, }; #define LOOP_CAL_PT(VAR, S, N) for (uint8_t VAR=S; VAR<=NPP; VAR+=N) #define F_LOOP_CAL_PT(VAR, S, N) for (float VAR=S; VAR<NPP+0.9999; VAR+=N) #define I_LOOP_CAL_PT(VAR, S, N) for (float VAR=S; VAR>CEN+0.9999; VAR-=N) #define LOOP_CAL_ALL(VAR) LOOP_CAL_PT(VAR, CEN, 1) #define LOOP_CAL_RAD(VAR) LOOP_CAL_PT(VAR, __A, _7P_STEP) #define LOOP_CAL_ACT(VAR, _4P, _OP) LOOP_CAL_PT(VAR, _OP ? _AB : __A, _4P ? _4P_STEP : _7P_STEP) #if HOTENDS > 1 const uint8_t old_tool_index = active_extruder; #define AC_CLEANUP() ac_cleanup(old_tool_index) #else #define AC_CLEANUP() ac_cleanup() #endif float lcd_probe_pt(const float &rx, const float &ry); void ac_home() { endstops.enable(true); home_delta(); endstops.not_homing(); } void ac_setup(const bool reset_bed) { #if HOTENDS > 1 tool_change(0, 0, true); #endif planner.synchronize(); setup_for_endstop_or_probe_move(); #if HAS_LEVELING if (reset_bed) reset_bed_level(); // After full calibration bed-level data is no longer valid #endif } void ac_cleanup( #if HOTENDS > 1 const uint8_t old_tool_index #endif ) { #if ENABLED(DELTA_HOME_TO_SAFE_ZONE) do_blocking_move_to_z(delta_clip_start_height); #endif #if HAS_BED_PROBE STOW_PROBE(); #endif clean_up_after_endstop_or_probe_move(); #if HOTENDS > 1 tool_change(old_tool_index, 0, true); #endif } void print_signed_float(const char * const prefix, const float &f) { SERIAL_PROTOCOLPGM(" "); serialprintPGM(prefix); SERIAL_PROTOCOLCHAR(':'); if (f >= 0) SERIAL_CHAR('+'); SERIAL_PROTOCOL_F(f, 2); } /** * - Print the delta settings */ static void print_calibration_settings(const bool end_stops, const bool tower_angles) { SERIAL_PROTOCOLPAIR(".Height:", delta_height); if (end_stops) { print_signed_float(PSTR("Ex"), delta_endstop_adj[A_AXIS]); print_signed_float(PSTR("Ey"), delta_endstop_adj[B_AXIS]); print_signed_float(PSTR("Ez"), delta_endstop_adj[C_AXIS]); } if (end_stops && tower_angles) { SERIAL_PROTOCOLPAIR(" Radius:", delta_radius); SERIAL_EOL(); SERIAL_CHAR('.'); SERIAL_PROTOCOL_SP(13); } if (tower_angles) { print_signed_float(PSTR("Tx"), delta_tower_angle_trim[A_AXIS]); print_signed_float(PSTR("Ty"), delta_tower_angle_trim[B_AXIS]); print_signed_float(PSTR("Tz"), delta_tower_angle_trim[C_AXIS]); } if ((!end_stops && tower_angles) || (end_stops && !tower_angles)) { // XOR SERIAL_PROTOCOLPAIR(" Radius:", delta_radius); } SERIAL_EOL(); } /** * - Print the probe results */ static void print_calibration_results(const float z_pt[NPP + 1], const bool tower_points, const bool opposite_points) { SERIAL_PROTOCOLPGM(". "); print_signed_float(PSTR("c"), z_pt[CEN]); if (tower_points) { print_signed_float(PSTR(" x"), z_pt[__A]); print_signed_float(PSTR(" y"), z_pt[__B]); print_signed_float(PSTR(" z"), z_pt[__C]); } if (tower_points && opposite_points) { SERIAL_EOL(); SERIAL_CHAR('.'); SERIAL_PROTOCOL_SP(13); } if (opposite_points) { print_signed_float(PSTR("yz"), z_pt[_BC]); print_signed_float(PSTR("zx"), z_pt[_CA]); print_signed_float(PSTR("xy"), z_pt[_AB]); } SERIAL_EOL(); } /** * - Calculate the standard deviation from the zero plane */ static float std_dev_points(float z_pt[NPP + 1], const bool _0p_cal, const bool _1p_cal, const bool _4p_cal, const bool _4p_opp) { if (!_0p_cal) { float S2 = sq(z_pt[CEN]); int16_t N = 1; if (!_1p_cal) { // std dev from zero plane LOOP_CAL_ACT(rad, _4p_cal, _4p_opp) { S2 += sq(z_pt[rad]); N++; } return LROUND(SQRT(S2 / N) * 1000.0) / 1000.0 + 0.00001; } } return 0.00001; } /** * - Probe a point */ static float calibration_probe(const float &nx, const float &ny, const bool stow) { #if HAS_BED_PROBE return probe_pt(nx, ny, stow ? PROBE_PT_STOW : PROBE_PT_RAISE, 0, false); #else UNUSED(stow); return lcd_probe_pt(nx, ny); #endif } /** * - Probe a grid */ static bool probe_calibration_points(float z_pt[NPP + 1], const int8_t probe_points, const bool towers_set, const bool stow_after_each) { const bool _0p_calibration = probe_points == 0, _1p_calibration = probe_points == 1 || probe_points == -1, _4p_calibration = probe_points == 2, _4p_opposite_points = _4p_calibration && !towers_set, _7p_calibration = probe_points >= 3, _7p_no_intermediates = probe_points == 3, _7p_1_intermediates = probe_points == 4, _7p_2_intermediates = probe_points == 5, _7p_4_intermediates = probe_points == 6, _7p_6_intermediates = probe_points == 7, _7p_8_intermediates = probe_points == 8, _7p_11_intermediates = probe_points == 9, _7p_14_intermediates = probe_points == 10, _7p_intermed_points = probe_points >= 4, _7p_6_center = probe_points >= 5 && probe_points <= 7, _7p_9_center = probe_points >= 8; LOOP_CAL_ALL(rad) z_pt[rad] = 0.0; if (!_0p_calibration) { if (!_7p_no_intermediates && !_7p_4_intermediates && !_7p_11_intermediates) { // probe the center z_pt[CEN] += calibration_probe(0, 0, stow_after_each); if (isnan(z_pt[CEN])) return false; } if (_7p_calibration) { // probe extra center points const float start = _7p_9_center ? float(_CA) + _7P_STEP / 3.0 : _7p_6_center ? float(_CA) : float(__C), steps = _7p_9_center ? _4P_STEP / 3.0 : _7p_6_center ? _7P_STEP : _4P_STEP; I_LOOP_CAL_PT(rad, start, steps) { const float a = RADIANS(210 + (360 / NPP) * (rad - 1)), r = delta_calibration_radius * 0.1; z_pt[CEN] += calibration_probe(cos(a) * r, sin(a) * r, stow_after_each); if (isnan(z_pt[CEN])) return false; } z_pt[CEN] /= float(_7p_2_intermediates ? 7 : probe_points); } if (!_1p_calibration) { // probe the radius const CalEnum start = _4p_opposite_points ? _AB : __A; const float steps = _7p_14_intermediates ? _7P_STEP / 15.0 : // 15r * 6 + 10c = 100 _7p_11_intermediates ? _7P_STEP / 12.0 : // 12r * 6 + 9c = 81 _7p_8_intermediates ? _7P_STEP / 9.0 : // 9r * 6 + 10c = 64 _7p_6_intermediates ? _7P_STEP / 7.0 : // 7r * 6 + 7c = 49 _7p_4_intermediates ? _7P_STEP / 5.0 : // 5r * 6 + 6c = 36 _7p_2_intermediates ? _7P_STEP / 3.0 : // 3r * 6 + 7c = 25 _7p_1_intermediates ? _7P_STEP / 2.0 : // 2r * 6 + 4c = 16 _7p_no_intermediates ? _7P_STEP : // 1r * 6 + 3c = 9 _4P_STEP; // .5r * 6 + 1c = 4 bool zig_zag = true; F_LOOP_CAL_PT(rad, start, _7p_9_center ? steps * 3 : steps) { const int8_t offset = _7p_9_center ? 2 : 0; for (int8_t circle = 0; circle <= offset; circle++) { const float a = RADIANS(210 + (360 / NPP) * (rad - 1)), r = delta_calibration_radius * (1 - 0.1 * (zig_zag ? offset - circle : circle)), interpol = fmod(rad, 1); const float z_temp = calibration_probe(cos(a) * r, sin(a) * r, stow_after_each); if (isnan(z_temp)) return false; // split probe point to neighbouring calibration points z_pt[uint8_t(LROUND(rad - interpol + NPP - 1)) % NPP + 1] += z_temp * sq(cos(RADIANS(interpol * 90))); z_pt[uint8_t(LROUND(rad - interpol)) % NPP + 1] += z_temp * sq(sin(RADIANS(interpol * 90))); } zig_zag = !zig_zag; } if (_7p_intermed_points) LOOP_CAL_RAD(rad) z_pt[rad] /= _7P_STEP / steps; do_blocking_move_to_xy(0.0, 0.0); } } return true; } /** * kinematics routines and auto tune matrix scaling parameters: * see https://github.com/LVD-AC/Marlin-AC/tree/1.1.x-AC/documentation for * - formulae for approximative forward kinematics in the end-stop displacement matrix * - definition of the matrix scaling parameters */ static void reverse_kinematics_probe_points(float z_pt[NPP + 1], float mm_at_pt_axis[NPP + 1][ABC]) { float pos[XYZ] = { 0.0 }; LOOP_CAL_ALL(rad) { const float a = RADIANS(210 + (360 / NPP) * (rad - 1)), r = (rad == CEN ? 0.0 : delta_calibration_radius); pos[X_AXIS] = cos(a) * r; pos[Y_AXIS] = sin(a) * r; pos[Z_AXIS] = z_pt[rad]; inverse_kinematics(pos); LOOP_XYZ(axis) mm_at_pt_axis[rad][axis] = delta[axis]; } } static void forward_kinematics_probe_points(float mm_at_pt_axis[NPP + 1][ABC], float z_pt[NPP + 1]) { const float r_quot = delta_calibration_radius / delta_radius; #define ZPP(N,I,A) ((1 / 3.0 + r_quot * (N) / 3.0 ) * mm_at_pt_axis[I][A]) #define Z00(I, A) ZPP( 0, I, A) #define Zp1(I, A) ZPP(+1, I, A) #define Zm1(I, A) ZPP(-1, I, A) #define Zp2(I, A) ZPP(+2, I, A) #define Zm2(I, A) ZPP(-2, I, A) z_pt[CEN] = Z00(CEN, A_AXIS) + Z00(CEN, B_AXIS) + Z00(CEN, C_AXIS); z_pt[__A] = Zp2(__A, A_AXIS) + Zm1(__A, B_AXIS) + Zm1(__A, C_AXIS); z_pt[__B] = Zm1(__B, A_AXIS) + Zp2(__B, B_AXIS) + Zm1(__B, C_AXIS); z_pt[__C] = Zm1(__C, A_AXIS) + Zm1(__C, B_AXIS) + Zp2(__C, C_AXIS); z_pt[_BC] = Zm2(_BC, A_AXIS) + Zp1(_BC, B_AXIS) + Zp1(_BC, C_AXIS); z_pt[_CA] = Zp1(_CA, A_AXIS) + Zm2(_CA, B_AXIS) + Zp1(_CA, C_AXIS); z_pt[_AB] = Zp1(_AB, A_AXIS) + Zp1(_AB, B_AXIS) + Zm2(_AB, C_AXIS); } static void calc_kinematics_diff_probe_points(float z_pt[NPP + 1], float delta_e[ABC], float delta_r, float delta_t[ABC]) { const float z_center = z_pt[CEN]; float diff_mm_at_pt_axis[NPP + 1][ABC], new_mm_at_pt_axis[NPP + 1][ABC]; reverse_kinematics_probe_points(z_pt, diff_mm_at_pt_axis); delta_radius += delta_r; LOOP_XYZ(axis) delta_tower_angle_trim[axis] += delta_t[axis]; recalc_delta_settings(); reverse_kinematics_probe_points(z_pt, new_mm_at_pt_axis); LOOP_XYZ(axis) LOOP_CAL_ALL(rad) diff_mm_at_pt_axis[rad][axis] -= new_mm_at_pt_axis[rad][axis] + delta_e[axis]; forward_kinematics_probe_points(diff_mm_at_pt_axis, z_pt); LOOP_CAL_RAD(rad) z_pt[rad] -= z_pt[CEN] - z_center; z_pt[CEN] = z_center; delta_radius -= delta_r; LOOP_XYZ(axis) delta_tower_angle_trim[axis] -= delta_t[axis]; recalc_delta_settings(); } static float auto_tune_h() { const float r_quot = delta_calibration_radius / delta_radius; float h_fac = 0.0; h_fac = r_quot / (2.0 / 3.0); h_fac = 1.0f / h_fac; // (2/3)/CR return h_fac; } static float auto_tune_r() { const float diff = 0.01; float r_fac = 0.0, z_pt[NPP + 1] = { 0.0 }, delta_e[ABC] = {0.0}, delta_r = {0.0}, delta_t[ABC] = {0.0}; delta_r = diff; calc_kinematics_diff_probe_points(z_pt, delta_e, delta_r, delta_t); r_fac = -(z_pt[__A] + z_pt[__B] + z_pt[__C] + z_pt[_BC] + z_pt[_CA] + z_pt[_AB]) / 6.0; r_fac = diff / r_fac / 3.0; // 1/(3*delta_Z) return r_fac; } static float auto_tune_a() { const float diff = 0.01; float a_fac = 0.0, z_pt[NPP + 1] = { 0.0 }, delta_e[ABC] = {0.0}, delta_r = {0.0}, delta_t[ABC] = {0.0}; LOOP_XYZ(axis) { LOOP_XYZ(axis_2) delta_t[axis_2] = 0.0; delta_t[axis] = diff; calc_kinematics_diff_probe_points(z_pt, delta_e, delta_r, delta_t); a_fac += z_pt[uint8_t((axis * _4P_STEP) - _7P_STEP + NPP) % NPP + 1] / 6.0; a_fac -= z_pt[uint8_t((axis * _4P_STEP) + 1 + _7P_STEP)] / 6.0; } a_fac = diff / a_fac / 3.0; // 1/(3*delta_Z) return a_fac; } /** * G33 - Delta '1-4-7-point' Auto-Calibration * Calibrate height, z_offset, endstops, delta radius, and tower angles. * * Parameters: * * Pn Number of probe points: * P0 Normalizes calibration. * P1 Calibrates height only with center probe. * P2 Probe center and towers. Calibrate height, endstops and delta radius. * P3 Probe all positions: center, towers and opposite towers. Calibrate all. * P4-P10 Probe all positions at different intermediate locations and average them. * * T Don't calibrate tower angle corrections * * Cn.nn Calibration precision; when omitted calibrates to maximum precision * * Fn Force to run at least n iterations and take the best result * * Vn Verbose level: * V0 Dry-run mode. Report settings and probe results. No calibration. * V1 Report start and end settings only * V2 Report settings at each iteration * V3 Report settings and probe results * * E Engage the probe for each point */ inline void gcode_G33() { const int8_t probe_points = parser.intval('P', DELTA_CALIBRATION_DEFAULT_POINTS); if (!WITHIN(probe_points, 0, 10)) { SERIAL_PROTOCOLLNPGM("?(P)oints is implausible (0-10)."); return; } const bool towers_set = !parser.seen('T'); const float calibration_precision = parser.floatval('C', 0.0); if (calibration_precision < 0) { SERIAL_PROTOCOLLNPGM("?(C)alibration precision is implausible (>=0)."); return; } const int8_t force_iterations = parser.intval('F', 0); if (!WITHIN(force_iterations, 0, 30)) { SERIAL_PROTOCOLLNPGM("?(F)orce iteration is implausible (0-30)."); return; } const int8_t verbose_level = parser.byteval('V', 1); if (!WITHIN(verbose_level, 0, 3)) { SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-3)."); return; } const bool stow_after_each = parser.seen('E'); const bool _0p_calibration = probe_points == 0, _1p_calibration = probe_points == 1 || probe_points == -1, _4p_calibration = probe_points == 2, _4p_opposite_points = _4p_calibration && !towers_set, _7p_9_center = probe_points >= 8, _tower_results = (_4p_calibration && towers_set) || probe_points >= 3, _opposite_results = (_4p_calibration && !towers_set) || probe_points >= 3, _endstop_results = probe_points != 1 && probe_points != -1 && probe_points != 0, _angle_results = probe_points >= 3 && towers_set; static const char save_message[] PROGMEM = "Save with M500 and/or copy to Configuration.h"; int8_t iterations = 0; float test_precision, zero_std_dev = (verbose_level ? 999.0 : 0.0), // 0.0 in dry-run mode : forced end zero_std_dev_min = zero_std_dev, zero_std_dev_old = zero_std_dev, h_factor, r_factor, a_factor, e_old[ABC] = { delta_endstop_adj[A_AXIS], delta_endstop_adj[B_AXIS], delta_endstop_adj[C_AXIS] }, r_old = delta_radius, h_old = delta_height, a_old[ABC] = { delta_tower_angle_trim[A_AXIS], delta_tower_angle_trim[B_AXIS], delta_tower_angle_trim[C_AXIS] }; SERIAL_PROTOCOLLNPGM("G33 Auto Calibrate"); if (!_1p_calibration && !_0p_calibration) { // test if the outer radius is reachable LOOP_CAL_RAD(axis) { const float a = RADIANS(210 + (360 / NPP) * (axis - 1)), r = delta_calibration_radius; if (!position_is_reachable(cos(a) * r, sin(a) * r)) { SERIAL_PROTOCOLLNPGM("?(M665 B)ed radius is implausible."); return; } } } // Report settings const char *checkingac = PSTR("Checking... AC"); serialprintPGM(checkingac); if (verbose_level == 0) SERIAL_PROTOCOLPGM(" (DRY-RUN)"); SERIAL_EOL(); lcd_setstatusPGM(checkingac); print_calibration_settings(_endstop_results, _angle_results); ac_setup(!_0p_calibration && !_1p_calibration); if (!_0p_calibration) ac_home(); do { // start iterations float z_at_pt[NPP + 1] = { 0.0 }; test_precision = zero_std_dev_old != 999.0 ? (zero_std_dev + zero_std_dev_old) / 2 : zero_std_dev; iterations++; // Probe the points zero_std_dev_old = zero_std_dev; if (!probe_calibration_points(z_at_pt, probe_points, towers_set, stow_after_each)) { SERIAL_PROTOCOLLNPGM("Correct delta settings with M665 and M666"); return AC_CLEANUP(); } zero_std_dev = std_dev_points(z_at_pt, _0p_calibration, _1p_calibration, _4p_calibration, _4p_opposite_points); // Solve matrices if ((zero_std_dev < test_precision || iterations <= force_iterations) && zero_std_dev > calibration_precision) { #if !HAS_BED_PROBE test_precision = 0.00; // forced end #endif if (zero_std_dev < zero_std_dev_min) { // set roll-back point COPY(e_old, delta_endstop_adj); r_old = delta_radius; h_old = delta_height; COPY(a_old, delta_tower_angle_trim); } float e_delta[ABC] = { 0.0 }, r_delta = 0.0, t_delta[ABC] = { 0.0 }; /** * convergence matrices: * see https://github.com/LVD-AC/Marlin-AC/tree/1.1.x-AC/documentation for * - definition of the matrix scaling parameters * - matrices for 4 and 7 point calibration */ #define ZP(N,I) ((N) * z_at_pt[I] / 4.0) // 4.0 = divider to normalize to integers #define Z12(I) ZP(12, I) #define Z4(I) ZP(4, I) #define Z2(I) ZP(2, I) #define Z1(I) ZP(1, I) #define Z0(I) ZP(0, I) // calculate factors const float cr_old = delta_calibration_radius; if (_7p_9_center) delta_calibration_radius *= 0.9; h_factor = auto_tune_h(); r_factor = auto_tune_r(); a_factor = auto_tune_a(); delta_calibration_radius = cr_old; switch (probe_points) { case 0: test_precision = 0.00; // forced end break; case 1: test_precision = 0.00; // forced end LOOP_XYZ(axis) e_delta[axis] = +Z4(CEN); break; case 2: if (towers_set) { // see 4 point calibration (towers) matrix e_delta[A_AXIS] = (+Z4(__A) -Z2(__B) -Z2(__C)) * h_factor +Z4(CEN); e_delta[B_AXIS] = (-Z2(__A) +Z4(__B) -Z2(__C)) * h_factor +Z4(CEN); e_delta[C_AXIS] = (-Z2(__A) -Z2(__B) +Z4(__C)) * h_factor +Z4(CEN); r_delta = (+Z4(__A) +Z4(__B) +Z4(__C) -Z12(CEN)) * r_factor; } else { // see 4 point calibration (opposites) matrix e_delta[A_AXIS] = (-Z4(_BC) +Z2(_CA) +Z2(_AB)) * h_factor +Z4(CEN); e_delta[B_AXIS] = (+Z2(_BC) -Z4(_CA) +Z2(_AB)) * h_factor +Z4(CEN); e_delta[C_AXIS] = (+Z2(_BC) +Z2(_CA) -Z4(_AB)) * h_factor +Z4(CEN); r_delta = (+Z4(_BC) +Z4(_CA) +Z4(_AB) -Z12(CEN)) * r_factor; } break; default: // see 7 point calibration (towers & opposites) matrix e_delta[A_AXIS] = (+Z2(__A) -Z1(__B) -Z1(__C) -Z2(_BC) +Z1(_CA) +Z1(_AB)) * h_factor +Z4(CEN); e_delta[B_AXIS] = (-Z1(__A) +Z2(__B) -Z1(__C) +Z1(_BC) -Z2(_CA) +Z1(_AB)) * h_factor +Z4(CEN); e_delta[C_AXIS] = (-Z1(__A) -Z1(__B) +Z2(__C) +Z1(_BC) +Z1(_CA) -Z2(_AB)) * h_factor +Z4(CEN); r_delta = (+Z2(__A) +Z2(__B) +Z2(__C) +Z2(_BC) +Z2(_CA) +Z2(_AB) -Z12(CEN)) * r_factor; if (towers_set) { // see 7 point tower angle calibration (towers & opposites) matrix t_delta[A_AXIS] = (+Z0(__A) -Z4(__B) +Z4(__C) +Z0(_BC) -Z4(_CA) +Z4(_AB) +Z0(CEN)) * a_factor; t_delta[B_AXIS] = (+Z4(__A) +Z0(__B) -Z4(__C) +Z4(_BC) +Z0(_CA) -Z4(_AB) +Z0(CEN)) * a_factor; t_delta[C_AXIS] = (-Z4(__A) +Z4(__B) +Z0(__C) -Z4(_BC) +Z4(_CA) +Z0(_AB) +Z0(CEN)) * a_factor; } break; } LOOP_XYZ(axis) delta_endstop_adj[axis] += e_delta[axis]; delta_radius += r_delta; LOOP_XYZ(axis) delta_tower_angle_trim[axis] += t_delta[axis]; } else if (zero_std_dev >= test_precision) { // roll back COPY(delta_endstop_adj, e_old); delta_radius = r_old; delta_height = h_old; COPY(delta_tower_angle_trim, a_old); } if (verbose_level != 0) { // !dry run // normalise angles to least squares if (_angle_results) { float a_sum = 0.0; LOOP_XYZ(axis) a_sum += delta_tower_angle_trim[axis]; LOOP_XYZ(axis) delta_tower_angle_trim[axis] -= a_sum / 3.0; } // adjust delta_height and endstops by the max amount const float z_temp = MAX3(delta_endstop_adj[A_AXIS], delta_endstop_adj[B_AXIS], delta_endstop_adj[C_AXIS]); delta_height -= z_temp; LOOP_XYZ(axis) delta_endstop_adj[axis] -= z_temp; } recalc_delta_settings(); NOMORE(zero_std_dev_min, zero_std_dev); // print report if (verbose_level == 3) print_calibration_results(z_at_pt, _tower_results, _opposite_results); if (verbose_level != 0) { // !dry run if ((zero_std_dev >= test_precision && iterations > force_iterations) || zero_std_dev <= calibration_precision) { // end iterations SERIAL_PROTOCOLPGM("Calibration OK"); SERIAL_PROTOCOL_SP(32); #if HAS_BED_PROBE if (zero_std_dev >= test_precision && !_1p_calibration && !_0p_calibration) SERIAL_PROTOCOLPGM("rolling back."); else #endif { SERIAL_PROTOCOLPGM("std dev:"); SERIAL_PROTOCOL_F(zero_std_dev_min, 3); } SERIAL_EOL(); char mess[21]; strcpy_P(mess, PSTR("Calibration sd:")); if (zero_std_dev_min < 1) sprintf_P(&mess[15], PSTR("0.%03i"), int(LROUND(zero_std_dev_min * 1000.0))); else sprintf_P(&mess[15], PSTR("%03i.x"), int(LROUND(zero_std_dev_min))); lcd_setstatus(mess); print_calibration_settings(_endstop_results, _angle_results); serialprintPGM(save_message); SERIAL_EOL(); } else { // !end iterations char mess[15]; if (iterations < 31) sprintf_P(mess, PSTR("Iteration : %02i"), int(iterations)); else strcpy_P(mess, PSTR("No convergence")); SERIAL_PROTOCOL(mess); SERIAL_PROTOCOL_SP(32); SERIAL_PROTOCOLPGM("std dev:"); SERIAL_PROTOCOL_F(zero_std_dev, 3); SERIAL_EOL(); lcd_setstatus(mess); if (verbose_level > 1) print_calibration_settings(_endstop_results, _angle_results); } } else { // dry run const char *enddryrun = PSTR("End DRY-RUN"); serialprintPGM(enddryrun); SERIAL_PROTOCOL_SP(35); SERIAL_PROTOCOLPGM("std dev:"); SERIAL_PROTOCOL_F(zero_std_dev, 3); SERIAL_EOL(); char mess[21]; strcpy_P(mess, enddryrun); strcpy_P(&mess[11], PSTR(" sd:")); if (zero_std_dev < 1) sprintf_P(&mess[15], PSTR("0.%03i"), int(LROUND(zero_std_dev * 1000.0))); else sprintf_P(&mess[15], PSTR("%03i.x"), int(LROUND(zero_std_dev))); lcd_setstatus(mess); } ac_home(); } while (((zero_std_dev < test_precision && iterations < 31) || iterations <= force_iterations) && zero_std_dev > calibration_precision); AC_CLEANUP(); } #endif // DELTA_AUTO_CALIBRATION #if ENABLED(G38_PROBE_TARGET) static bool G38_run_probe() { bool G38_pass_fail = false; #if MULTIPLE_PROBING > 1 // Get direction of move and retract float retract_mm[XYZ]; LOOP_XYZ(i) { float dist = destination[i] - current_position[i]; retract_mm[i] = ABS(dist) < G38_MINIMUM_MOVE ? 0 : home_bump_mm((AxisEnum)i) * (dist > 0 ? -1 : 1); } #endif // Move until destination reached or target hit planner.synchronize(); endstops.enable(true); G38_move = true; G38_endstop_hit = false; prepare_move_to_destination(); planner.synchronize(); G38_move = false; endstops.hit_on_purpose(); set_current_from_steppers_for_axis(ALL_AXES); SYNC_PLAN_POSITION_KINEMATIC(); if (G38_endstop_hit) { G38_pass_fail = true; #if MULTIPLE_PROBING > 1 // Move away by the retract distance set_destination_from_current(); LOOP_XYZ(i) destination[i] += retract_mm[i]; endstops.enable(false); prepare_move_to_destination(); feedrate_mm_s /= 4; // Bump the target more slowly LOOP_XYZ(i) destination[i] -= retract_mm[i] * 2; planner.synchronize(); endstops.enable(true); G38_move = true; prepare_move_to_destination(); planner.synchronize(); G38_move = false; set_current_from_steppers_for_axis(ALL_AXES); SYNC_PLAN_POSITION_KINEMATIC(); #endif } endstops.hit_on_purpose(); endstops.not_homing(); return G38_pass_fail; } /** * G38.2 - probe toward workpiece, stop on contact, signal error if failure * G38.3 - probe toward workpiece, stop on contact * * Like G28 except uses Z min probe for all axes */ inline void gcode_G38(bool is_38_2) { // Get X Y Z E F gcode_get_destination(); setup_for_endstop_or_probe_move(); // If any axis has enough movement, do the move LOOP_XYZ(i) if (ABS(destination[i] - current_position[i]) >= G38_MINIMUM_MOVE) { if (!parser.seenval('F')) feedrate_mm_s = homing_feedrate((AxisEnum)i); // If G38.2 fails throw an error if (!G38_run_probe() && is_38_2) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM("Failed to reach target"); } break; } clean_up_after_endstop_or_probe_move(); } #endif // G38_PROBE_TARGET #if HAS_MESH /** * G42: Move X & Y axes to mesh coordinates (I & J) */ inline void gcode_G42() { #if ENABLED(NO_MOTION_BEFORE_HOMING) if (axis_unhomed_error()) return; #endif if (IsRunning()) { const bool hasI = parser.seenval('I'); const int8_t ix = hasI ? parser.value_int() : 0; const bool hasJ = parser.seenval('J'); const int8_t iy = hasJ ? parser.value_int() : 0; if ((hasI && !WITHIN(ix, 0, GRID_MAX_POINTS_X - 1)) || (hasJ && !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1))) { SERIAL_ECHOLNPGM(MSG_ERR_MESH_XY); return; } set_destination_from_current(); if (hasI) destination[X_AXIS] = _GET_MESH_X(ix); if (hasJ) destination[Y_AXIS] = _GET_MESH_Y(iy); if (parser.boolval('P')) { if (hasI) destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER; if (hasJ) destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER; } const float fval = parser.linearval('F'); if (fval > 0.0) feedrate_mm_s = MMM_TO_MMS(fval); // SCARA kinematic has "safe" XY raw moves #if IS_SCARA prepare_uninterpolated_move_to_destination(); #else prepare_move_to_destination(); #endif } } #endif // HAS_MESH /** * G92: Set current position to given X Y Z E */ inline void gcode_G92() { #if ENABLED(CNC_COORDINATE_SYSTEMS) switch (parser.subcode) { case 1: // Zero the G92 values and restore current position #if !IS_SCARA LOOP_XYZ(i) { const float v = position_shift[i]; if (v) { position_shift[i] = 0; update_software_endstops((AxisEnum)i); } } #endif // Not SCARA return; } #endif #if ENABLED(CNC_COORDINATE_SYSTEMS) #define IS_G92_0 (parser.subcode == 0) #else #define IS_G92_0 true #endif bool didE = false; #if IS_SCARA || !HAS_POSITION_SHIFT || ENABLED(HANGPRINTER) bool didXYZ = false; #else constexpr bool didXYZ = false; #endif if (IS_G92_0) LOOP_XYZE(i) { if (parser.seenval(axis_codes[i])) { const float l = parser.value_axis_units((AxisEnum)i), v = i == E_CART ? l : LOGICAL_TO_NATIVE(l, i), d = v - current_position[i]; if (!NEAR_ZERO(d) #if ENABLED(HANGPRINTER) || true // Hangprinter needs to update its line lengths whether current_position changed or not #endif ) { #if IS_SCARA || !HAS_POSITION_SHIFT || ENABLED(HANGPRINTER) if (i == E_CART) didE = true; else didXYZ = true; current_position[i] = v; // Without workspaces revert to Marlin 1.0 behavior #elif HAS_POSITION_SHIFT if (i == E_CART) { didE = true; current_position[E_CART] = v; // When using coordinate spaces, only E is set directly } else { position_shift[i] += d; // Other axes simply offset the coordinate space update_software_endstops((AxisEnum)i); } #endif } } } #if ENABLED(CNC_COORDINATE_SYSTEMS) // Apply workspace offset to the active coordinate system if (WITHIN(active_coordinate_system, 0, MAX_COORDINATE_SYSTEMS - 1)) COPY(coordinate_system[active_coordinate_system], position_shift); #endif // Update planner/steppers only if the native coordinates changed if (didXYZ) SYNC_PLAN_POSITION_KINEMATIC(); else if (didE) sync_plan_position_e(); report_current_position(); } #if ENABLED(MECHADUINO_I2C_COMMANDS) /** * G95: Set torque mode */ inline void gcode_G95() { i2cFloat torques[NUM_AXIS]; // Assumes 4-byte floats here and in Mechaduino firmware LOOP_NUM_AXIS(i) torques[i].fval = parser.floatval(RAW_AXIS_CODES(i), 999.9); // 999.9 chosen to satisfy fabs(999.9) > 255.0 // 0x5f == 95 #define G95_SEND(LETTER) do { \ if (fabs(torques[_AXIS(LETTER)].fval) < 255.0){ \ torques[_AXIS(LETTER)].fval = -fabs(torques[_AXIS(LETTER)].fval); \ if(!INVERT_##LETTER##_DIR) torques[_AXIS(LETTER)].fval = -torques[_AXIS(LETTER)].fval; \ i2c.address(LETTER##_MOTOR_I2C_ADDR); \ i2c.reset(); \ i2c.addbyte(0x5f); \ i2c.addbytes(torques[_AXIS(LETTER)].bval, sizeof(float)); \ i2c.send(); \ }} while(0) #if ENABLED(HANGPRINTER) #if ENABLED(A_IS_MECHADUINO) G95_SEND(A); #endif #if ENABLED(B_IS_MECHADUINO) G95_SEND(B); #endif #if ENABLED(C_IS_MECHADUINO) G95_SEND(C); #endif #if ENABLED(D_IS_MECHADUINO) G95_SEND(D); #endif #else #if ENABLED(X_IS_MECHADUINO) G95_SEND(X); #endif #if ENABLED(Y_IS_MECHADUINO) G95_SEND(Y); #endif #if ENABLED(Z_IS_MECHADUINO) G95_SEND(Z); #endif #endif #if ENABLED(E_IS_MECHADUINO) G95_SEND(E); #endif } /** * G96: Mark encoder reference point */ inline void gcode_G96() { bool mark[NUM_AXIS] = { false }; if (!parser.seen_any()) LOOP_NUM_AXIS(i) mark[i] = true; else LOOP_NUM_AXIS(i) if (parser.seen(RAW_AXIS_CODES(i))) mark[i] = true; // 0x60 == 96 #define G96_SEND(LETTER) do {\ if (mark[LETTER##_AXIS]){ \ i2c.address(LETTER##_MOTOR_I2C_ADDR); \ i2c.reset(); \ i2c.addbyte(0x60); \ i2c.send(); \ }} while(0) #if ENABLED(HANGPRINTER) #if ENABLED(A_IS_MECHADUINO) G96_SEND(A); #endif #if ENABLED(B_IS_MECHADUINO) G96_SEND(B); #endif #if ENABLED(C_IS_MECHADUINO) G96_SEND(C); #endif #if ENABLED(D_IS_MECHADUINO) G96_SEND(D); #endif #else #if ENABLED(X_IS_MECHADUINO) G96_SEND(X); #endif #if ENABLED(Y_IS_MECHADUINO) G96_SEND(Y); #endif #if ENABLED(Z_IS_MECHADUINO) G96_SEND(Z); #endif #endif #if ENABLED(E_IS_MECHADUINO) G96_SEND(E); // E ref point not used by any other commands (Feb 7, 2018) #endif } float ang_to_mm(float ang, const AxisEnum axis) { const float abs_step_in_origin = #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE) planner.k0[axis] * (SQRT(planner.k1[axis] + planner.k2[axis] * line_lengths_origin[axis]) - planner.sqrtk1[axis]) #else line_lengths_origin[axis] * planner.axis_steps_per_mm[axis] #endif ; const float c = abs_step_in_origin + ang * float(STEPS_PER_MOTOR_REVOLUTION) / 360.0; // current step count return #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE) // Inverse function found in planner.cpp, where target[AXIS_A] is calculated ((c / planner.k0[axis] + planner.sqrtk1[axis]) * (c / planner.k0[axis] + planner.sqrtk1[axis]) - planner.k1[axis]) / planner.k2[axis] - line_lengths_origin[axis] #else c / planner.axis_steps_per_mm[axis] - line_lengths_origin[axis] #endif ; } void report_axis_position_from_encoder_data() { i2cFloat ang; #define M114_S1_RECEIVE(LETTER) do { \ i2c.address(LETTER##_MOTOR_I2C_ADDR); \ i2c.request(sizeof(float)); \ i2c.capture(ang.bval, sizeof(float)); \ if(LETTER##_INVERT_REPORTED_ANGLE == INVERT_##LETTER##_DIR) ang.fval = -ang.fval; \ SERIAL_PROTOCOL(ang_to_mm(ang.fval, LETTER##_AXIS)); \ } while(0) SERIAL_CHAR('['); #if ENABLED(HANGPRINTER) #if ENABLED(A_IS_MECHADUINO) M114_S1_RECEIVE(A); #endif #if ENABLED(B_IS_MECHADUINO) SERIAL_PROTOCOLPGM(", "); M114_S1_RECEIVE(B); #endif #if ENABLED(C_IS_MECHADUINO) SERIAL_PROTOCOLPGM(", "); M114_S1_RECEIVE(C); #endif #if ENABLED(D_IS_MECHADUINO) SERIAL_PROTOCOLPGM(", "); M114_S1_RECEIVE(D); #endif #else #if ENABLED(X_IS_MECHADUINO) M114_S1_RECEIVE(X); #endif #if ENABLED(Y_IS_MECHADUINO) SERIAL_PROTOCOLPGM(", "); M114_S1_RECEIVE(Y); #endif #if ENABLED(Z_IS_MECHADUINO) SERIAL_PROTOCOLPGM(", "); M114_S1_RECEIVE(Z); #endif #endif SERIAL_CHAR(']'); SERIAL_EOL(); } #endif // MECHADUINO_I2C_COMMANDS void report_xyz_from_stepper_position() { get_cartesian_from_steppers(); // writes to cartes[XYZ] SERIAL_CHAR('['); SERIAL_PROTOCOL(cartes[X_AXIS]); SERIAL_PROTOCOLPAIR(", ", cartes[Y_AXIS]); SERIAL_PROTOCOLPAIR(", ", cartes[Z_AXIS]); SERIAL_CHAR(']'); SERIAL_EOL(); } #if HAS_RESUME_CONTINUE /** * M0: Unconditional stop - Wait for user button press on LCD * M1: Conditional stop - Wait for user button press on LCD */ inline void gcode_M0_M1() { const char * const args = parser.string_arg; millis_t ms = 0; bool hasP = false, hasS = false; if (parser.seenval('P')) { ms = parser.value_millis(); // milliseconds to wait hasP = ms > 0; } if (parser.seenval('S')) { ms = parser.value_millis_from_seconds(); // seconds to wait hasS = ms > 0; } const bool has_message = !hasP && !hasS && args && *args; planner.synchronize(); #if ENABLED(ULTIPANEL) if (has_message) lcd_setstatus(args, true); else { LCD_MESSAGEPGM(MSG_USERWAIT); #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0 dontExpireStatus(); #endif } #else if (has_message) { SERIAL_ECHO_START(); SERIAL_ECHOLN(args); } #endif KEEPALIVE_STATE(PAUSED_FOR_USER); wait_for_user = true; if (ms > 0) { ms += millis(); // wait until this time for a click while (PENDING(millis(), ms) && wait_for_user) idle(); } else while (wait_for_user) idle(); #if ENABLED(PRINTER_EVENT_LEDS) && ENABLED(SDSUPPORT) if (lights_off_after_print) { leds.set_off(); lights_off_after_print = false; } #endif lcd_reset_status(); wait_for_user = false; KEEPALIVE_STATE(IN_HANDLER); } #endif // HAS_RESUME_CONTINUE #if ENABLED(SPINDLE_LASER_ENABLE) /** * M3: Spindle Clockwise * M4: Spindle Counter-clockwise * * S0 turns off spindle. * * If no speed PWM output is defined then M3/M4 just turns it on. * * At least 12.8KHz (50Hz * 256) is needed for spindle PWM. * Hardware PWM is required. ISRs are too slow. * * NOTE: WGM for timers 3, 4, and 5 must be either Mode 1 or Mode 5. * No other settings give a PWM signal that goes from 0 to 5 volts. * * The system automatically sets WGM to Mode 1, so no special * initialization is needed. * * WGM bits for timer 2 are automatically set by the system to * Mode 1. This produces an acceptable 0 to 5 volt signal. * No special initialization is needed. * * NOTE: A minimum PWM frequency of 50 Hz is needed. All prescaler * factors for timers 2, 3, 4, and 5 are acceptable. * * SPINDLE_LASER_ENABLE_PIN needs an external pullup or it may power on * the spindle/laser during power-up or when connecting to the host * (usually goes through a reset which sets all I/O pins to tri-state) * * PWM duty cycle goes from 0 (off) to 255 (always on). */ // Wait for spindle to come up to speed inline void delay_for_power_up() { dwell(SPINDLE_LASER_POWERUP_DELAY); } // Wait for spindle to stop turning inline void delay_for_power_down() { dwell(SPINDLE_LASER_POWERDOWN_DELAY); } /** * ocr_val_mode() is used for debugging and to get the points needed to compute the RPM vs ocr_val line * * it accepts inputs of 0-255 */ inline void ocr_val_mode() { uint8_t spindle_laser_power = parser.value_byte(); WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low) if (SPINDLE_LASER_PWM_INVERT) spindle_laser_power = 255 - spindle_laser_power; analogWrite(SPINDLE_LASER_PWM_PIN, spindle_laser_power); } inline void gcode_M3_M4(bool is_M3) { planner.synchronize(); // wait until previous movement commands (G0/G0/G2/G3) have completed before playing with the spindle #if SPINDLE_DIR_CHANGE const bool rotation_dir = (is_M3 && !SPINDLE_INVERT_DIR || !is_M3 && SPINDLE_INVERT_DIR) ? HIGH : LOW; if (SPINDLE_STOP_ON_DIR_CHANGE \ && READ(SPINDLE_LASER_ENABLE_PIN) == SPINDLE_LASER_ENABLE_INVERT \ && READ(SPINDLE_DIR_PIN) != rotation_dir ) { WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off delay_for_power_down(); } WRITE(SPINDLE_DIR_PIN, rotation_dir); #endif /** * Our final value for ocr_val is an unsigned 8 bit value between 0 and 255 which usually means uint8_t. * Went to uint16_t because some of the uint8_t calculations would sometimes give 1000 0000 rather than 1111 1111. * Then needed to AND the uint16_t result with 0x00FF to make sure we only wrote the byte of interest. */ #if ENABLED(SPINDLE_LASER_PWM) if (parser.seen('O')) ocr_val_mode(); else { const float spindle_laser_power = parser.floatval('S'); if (spindle_laser_power == 0) { WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off (active low) analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0); // only write low byte delay_for_power_down(); } else { int16_t ocr_val = (spindle_laser_power - (SPEED_POWER_INTERCEPT)) * (1.0f / (SPEED_POWER_SLOPE)); // convert RPM to PWM duty cycle NOMORE(ocr_val, 255); // limit to max the Atmel PWM will support if (spindle_laser_power <= SPEED_POWER_MIN) ocr_val = (SPEED_POWER_MIN - (SPEED_POWER_INTERCEPT)) * (1.0f / (SPEED_POWER_SLOPE)); // minimum setting if (spindle_laser_power >= SPEED_POWER_MAX) ocr_val = (SPEED_POWER_MAX - (SPEED_POWER_INTERCEPT)) * (1.0f / (SPEED_POWER_SLOPE)); // limit to max RPM if (SPINDLE_LASER_PWM_INVERT) ocr_val = 255 - ocr_val; WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low) analogWrite(SPINDLE_LASER_PWM_PIN, ocr_val & 0xFF); // only write low byte delay_for_power_up(); } } #else WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low) if spindle speed option not enabled delay_for_power_up(); #endif } /** * M5 turn off spindle */ inline void gcode_M5() { planner.synchronize(); WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); #if ENABLED(SPINDLE_LASER_PWM) analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0); #endif delay_for_power_down(); } #endif // SPINDLE_LASER_ENABLE /** * M17: Enable power on all stepper motors */ inline void gcode_M17() { LCD_MESSAGEPGM(MSG_NO_MOVE); enable_all_steppers(); } #if ENABLED(ADVANCED_PAUSE_FEATURE) void do_pause_e_move(const float &length, const float &fr) { set_destination_from_current(); destination[E_CART] += length / planner.e_factor[active_extruder]; planner.buffer_line_kinematic(destination, fr, active_extruder); set_current_from_destination(); planner.synchronize(); } static float resume_position[XYZE]; int8_t did_pause_print = 0; #if HAS_BUZZER static void filament_change_beep(const int8_t max_beep_count, const bool init=false) { static millis_t next_buzz = 0; static int8_t runout_beep = 0; if (init) next_buzz = runout_beep = 0; const millis_t ms = millis(); if (ELAPSED(ms, next_buzz)) { if (max_beep_count < 0 || runout_beep < max_beep_count + 5) { // Only beep as long as we're supposed to next_buzz = ms + ((max_beep_count < 0 || runout_beep < max_beep_count) ? 1000 : 500); BUZZ(50, 880 - (runout_beep & 1) * 220); runout_beep++; } } } #endif /** * Ensure a safe temperature for extrusion * * - Fail if the TARGET temperature is too low * - Display LCD placard with temperature status * - Return when heating is done or aborted * * Returns 'true' if heating was completed, 'false' for abort */ static bool ensure_safe_temperature(const AdvancedPauseMode mode=ADVANCED_PAUSE_MODE_PAUSE_PRINT) { #if ENABLED(PREVENT_COLD_EXTRUSION) if (!DEBUGGING(DRYRUN) && thermalManager.targetTooColdToExtrude(active_extruder)) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_HOTEND_TOO_COLD); return false; } #endif #if ENABLED(ULTIPANEL) lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_WAIT_FOR_NOZZLES_TO_HEAT, mode); #else UNUSED(mode); #endif wait_for_heatup = true; // M108 will clear this while (wait_for_heatup && thermalManager.wait_for_heating(active_extruder)) idle(); const bool status = wait_for_heatup; wait_for_heatup = false; return status; } /** * Load filament into the hotend * * - Fail if the a safe temperature was not reached * - If pausing for confirmation, wait for a click or M108 * - Show "wait for load" placard * - Load and purge filament * - Show "Purge more" / "Continue" menu * - Return when "Continue" is selected * * Returns 'true' if load was completed, 'false' for abort */ static bool load_filament(const float &slow_load_length=0, const float &fast_load_length=0, const float &purge_length=0, const int8_t max_beep_count=0, const bool show_lcd=false, const bool pause_for_user=false, const AdvancedPauseMode mode=ADVANCED_PAUSE_MODE_PAUSE_PRINT ) { #if DISABLED(ULTIPANEL) UNUSED(show_lcd); #endif if (!ensure_safe_temperature(mode)) { #if ENABLED(ULTIPANEL) if (show_lcd) // Show status screen lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS); #endif return false; } if (pause_for_user) { #if ENABLED(ULTIPANEL) if (show_lcd) // Show "insert filament" lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT, mode); #endif SERIAL_ECHO_START(); SERIAL_ECHOLNPGM(MSG_FILAMENT_CHANGE_INSERT); #if HAS_BUZZER filament_change_beep(max_beep_count, true); #else UNUSED(max_beep_count); #endif KEEPALIVE_STATE(PAUSED_FOR_USER); wait_for_user = true; // LCD click or M108 will clear this while (wait_for_user) { #if HAS_BUZZER filament_change_beep(max_beep_count); #endif idle(true); } KEEPALIVE_STATE(IN_HANDLER); } #if ENABLED(ULTIPANEL) if (show_lcd) // Show "wait for load" message lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_LOAD, mode); #endif // Slow Load filament if (slow_load_length) do_pause_e_move(slow_load_length, FILAMENT_CHANGE_SLOW_LOAD_FEEDRATE); // Fast Load Filament if (fast_load_length) { #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0 const float saved_acceleration = planner.retract_acceleration; planner.retract_acceleration = FILAMENT_CHANGE_FAST_LOAD_ACCEL; #endif do_pause_e_move(fast_load_length, FILAMENT_CHANGE_FAST_LOAD_FEEDRATE); #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0 planner.retract_acceleration = saved_acceleration; #endif } #if ENABLED(ADVANCED_PAUSE_CONTINUOUS_PURGE) #if ENABLED(ULTIPANEL) if (show_lcd) lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_CONTINUOUS_PURGE); #endif wait_for_user = true; for (float purge_count = purge_length; purge_count > 0 && wait_for_user; --purge_count) do_pause_e_move(1, ADVANCED_PAUSE_PURGE_FEEDRATE); wait_for_user = false; #else do { if (purge_length > 0) { // "Wait for filament purge" #if ENABLED(ULTIPANEL) if (show_lcd) lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_PURGE, mode); #endif // Extrude filament to get into hotend do_pause_e_move(purge_length, ADVANCED_PAUSE_PURGE_FEEDRATE); } // Show "Purge More" / "Resume" menu and wait for reply #if ENABLED(ULTIPANEL) if (show_lcd) { KEEPALIVE_STATE(PAUSED_FOR_USER); wait_for_user = false; lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_OPTION, mode); while (advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_WAIT_FOR) idle(true); KEEPALIVE_STATE(IN_HANDLER); } #endif // Keep looping if "Purge More" was selected } while ( #if ENABLED(ULTIPANEL) show_lcd && advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_EXTRUDE_MORE #else 0 #endif ); #endif return true; } /** * Unload filament from the hotend * * - Fail if the a safe temperature was not reached * - Show "wait for unload" placard * - Retract, pause, then unload filament * - Disable E stepper (on most machines) * * Returns 'true' if unload was completed, 'false' for abort */ static bool unload_filament(const float &unload_length, const bool show_lcd=false, const AdvancedPauseMode mode=ADVANCED_PAUSE_MODE_PAUSE_PRINT ) { if (!ensure_safe_temperature(mode)) { #if ENABLED(ULTIPANEL) if (show_lcd) // Show status screen lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS); #endif return false; } #if DISABLED(ULTIPANEL) UNUSED(show_lcd); #else if (show_lcd) lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_UNLOAD, mode); #endif // Retract filament do_pause_e_move(-FILAMENT_UNLOAD_RETRACT_LENGTH, PAUSE_PARK_RETRACT_FEEDRATE); // Wait for filament to cool safe_delay(FILAMENT_UNLOAD_DELAY); // Quickly purge do_pause_e_move(FILAMENT_UNLOAD_RETRACT_LENGTH + FILAMENT_UNLOAD_PURGE_LENGTH, planner.max_feedrate_mm_s[E_AXIS]); // Unload filament #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0 const float saved_acceleration = planner.retract_acceleration; planner.retract_acceleration = FILAMENT_CHANGE_UNLOAD_ACCEL; #endif do_pause_e_move(unload_length, FILAMENT_CHANGE_UNLOAD_FEEDRATE); #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0 planner.retract_acceleration = saved_acceleration; #endif // Disable extruders steppers for manual filament changing (only on boards that have separate ENABLE_PINS) #if E0_ENABLE_PIN != X_ENABLE_PIN && E1_ENABLE_PIN != Y_ENABLE_PIN disable_e_stepper(active_extruder); safe_delay(100); #endif return true; } /** * Pause procedure * * - Abort if already paused * - Send host action for pause, if configured * - Abort if TARGET temperature is too low * - Display "wait for start of filament change" (if a length was specified) * - Initial retract, if current temperature is hot enough * - Park the nozzle at the given position * - Call unload_filament (if a length was specified) * * Returns 'true' if pause was completed, 'false' for abort */ static bool pause_print(const float &retract, const point_t &park_point, const float &unload_length=0, const bool show_lcd=false) { if (did_pause_print) return false; // already paused #ifdef ACTION_ON_PAUSE SERIAL_ECHOLNPGM("//action:" ACTION_ON_PAUSE); #endif if (!DEBUGGING(DRYRUN) && unload_length && thermalManager.targetTooColdToExtrude(active_extruder)) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_HOTEND_TOO_COLD); #if ENABLED(ULTIPANEL) if (show_lcd) // Show status screen lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS); LCD_MESSAGEPGM(MSG_M600_TOO_COLD); #endif return false; // unable to reach safe temperature } // Indicate that the printer is paused ++did_pause_print; // Pause the print job and timer #if ENABLED(SDSUPPORT) if (card.sdprinting) { card.pauseSDPrint(); ++did_pause_print; // Indicate SD pause also } #endif print_job_timer.pause(); // Save current position COPY(resume_position, current_position); // Wait for synchronize steppers planner.synchronize(); // Initial retract before move to filament change position if (retract && thermalManager.hotEnoughToExtrude(active_extruder)) do_pause_e_move(retract, PAUSE_PARK_RETRACT_FEEDRATE); // Park the nozzle by moving up by z_lift and then moving to (x_pos, y_pos) if (!axis_unhomed_error()) Nozzle::park(2, park_point); // Unload the filament if (unload_length) unload_filament(unload_length, show_lcd); return true; } /** * - Show "Insert filament and press button to continue" * - Wait for a click before returning * - Heaters can time out, reheated before accepting a click * * Used by M125 and M600 */ static void wait_for_filament_reload(const int8_t max_beep_count=0) { nozzle_timed_out = false; #if ENABLED(ULTIPANEL) lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT); #endif SERIAL_ECHO_START(); SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_INSERT); #if HAS_BUZZER filament_change_beep(max_beep_count, true); #endif // Start the heater idle timers const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL; HOTEND_LOOP() thermalManager.start_heater_idle_timer(e, nozzle_timeout); // Wait for filament insert by user and press button KEEPALIVE_STATE(PAUSED_FOR_USER); wait_for_user = true; // LCD click or M108 will clear this while (wait_for_user) { #if HAS_BUZZER filament_change_beep(max_beep_count); #endif // If the nozzle has timed out, wait for the user to press the button to re-heat the nozzle, then // re-heat the nozzle, re-show the insert screen, restart the idle timers, and start over if (!nozzle_timed_out) HOTEND_LOOP() nozzle_timed_out |= thermalManager.is_heater_idle(e); if (nozzle_timed_out) { #ifdef ANYCUBIC_TFT_MODEL if (AnycubicTFT.ai3m_pause_state < 3) { AnycubicTFT.ai3m_pause_state += 2; #ifdef ANYCUBIC_TFT_DEBUG SERIAL_ECHOPAIR(" DEBUG: NTO - AI3M Pause State set to: ", AnycubicTFT.ai3m_pause_state); SERIAL_EOL(); #endif } #ifdef ANYCUBIC_TFT_DEBUG SERIAL_ECHOLNPGM("DEBUG: Nozzle timeout flag set"); #endif #endif #if ENABLED(ULTIPANEL) lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_CLICK_TO_HEAT_NOZZLE); #endif SERIAL_ECHO_START(); #if ENABLED(ULTIPANEL) && ENABLED(EMERGENCY_PARSER) SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_HEAT); #elif ENABLED(EMERGENCY_PARSER) SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_HEAT_M108); #else SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_HEAT_LCD); #endif // Wait for LCD click or M108 while (wait_for_user) idle(true); // Re-enable the heaters if they timed out HOTEND_LOOP() thermalManager.reset_heater_idle_timer(e); // Wait for the heaters to reach the target temperatures ensure_safe_temperature(); #if ENABLED(ULTIPANEL) lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT); #endif SERIAL_ECHO_START(); #if ENABLED(ULTIPANEL) && ENABLED(EMERGENCY_PARSER) SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_INSERT); #elif ENABLED(EMERGENCY_PARSER) SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_INSERT_M108); #else SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_INSERT_LCD); #endif // Start the heater idle timers const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL; HOTEND_LOOP() thermalManager.start_heater_idle_timer(e, nozzle_timeout); wait_for_user = true; // Wait for user to load filament nozzle_timed_out = false; #ifdef ANYCUBIC_TFT_MODEL if (AnycubicTFT.ai3m_pause_state > 3) { AnycubicTFT.ai3m_pause_state -= 2; #ifdef ANYCUBIC_TFT_DEBUG SERIAL_ECHOPAIR(" DEBUG: NTO - AI3M Pause State set to: ", AnycubicTFT.ai3m_pause_state); SERIAL_EOL(); #endif } #endif #if HAS_BUZZER filament_change_beep(max_beep_count, true); #endif } idle(true); } KEEPALIVE_STATE(IN_HANDLER); } /** * Resume or Start print procedure * * - Abort if not paused * - Reset heater idle timers * - Load filament if specified, but only if: * - a nozzle timed out, or * - the nozzle is already heated. * - Display "wait for print to resume" * - Re-prime the nozzle... * - FWRETRACT: Recover/prime from the prior G10. * - !FWRETRACT: Retract by resume_position[E], if negative. * Not sure how this logic comes into use. * - Move the nozzle back to resume_position * - Sync the planner E to resume_position[E] * - Send host action for resume, if configured * - Resume the current SD print job, if any */ static void resume_print(const float &slow_load_length=0, const float &fast_load_length=0, const float &purge_length=ADVANCED_PAUSE_PURGE_LENGTH, const int8_t max_beep_count=0) { if (!did_pause_print) return; // Re-enable the heaters if they timed out nozzle_timed_out = false; #ifdef ANYCUBIC_TFT_MODEL if (AnycubicTFT.ai3m_pause_state > 3) { AnycubicTFT.ai3m_pause_state -= 2; #ifdef ANYCUBIC_TFT_DEBUG SERIAL_ECHOPAIR(" DEBUG: NTO - AI3M Pause State set to: ", AnycubicTFT.ai3m_pause_state); SERIAL_EOL(); #endif } #endif HOTEND_LOOP() { nozzle_timed_out |= thermalManager.is_heater_idle(e); thermalManager.reset_heater_idle_timer(e); } if (nozzle_timed_out || thermalManager.hotEnoughToExtrude(active_extruder)) { // Load the new filament load_filament(slow_load_length, fast_load_length, purge_length, max_beep_count, true, nozzle_timed_out); } #if ENABLED(ULTIPANEL) // "Wait for print to resume" lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_RESUME); #endif // Intelligent resuming #if ENABLED(FWRETRACT) // If retracted before goto pause if (fwretract.retracted[active_extruder]) do_pause_e_move(-fwretract.retract_length, fwretract.retract_feedrate_mm_s); #endif // If resume_position is negative if (resume_position[E_CART] < 0) do_pause_e_move(resume_position[E_CART], PAUSE_PARK_RETRACT_FEEDRATE); // Move XY to starting position, then Z do_blocking_move_to_xy(resume_position[X_AXIS], resume_position[Y_AXIS], NOZZLE_PARK_XY_FEEDRATE); // Set Z_AXIS to saved position do_blocking_move_to_z(resume_position[Z_AXIS], NOZZLE_PARK_Z_FEEDRATE); // Now all extrusion positions are resumed and ready to be confirmed // Set extruder to saved position planner.set_e_position_mm((destination[E_CART] = current_position[E_CART] = resume_position[E_CART])); #if ENABLED(FILAMENT_RUNOUT_SENSOR) runout.reset(); #endif #if ENABLED(ULTIPANEL) // Show status screen lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS); #endif #ifdef ACTION_ON_RESUME SERIAL_ECHOLNPGM("//action:" ACTION_ON_RESUME); #endif --did_pause_print; #if ENABLED(SDSUPPORT) if (did_pause_print) { card.startFileprint(); --did_pause_print; } #endif } #endif // ADVANCED_PAUSE_FEATURE #if ENABLED(SDSUPPORT) /** * M20: List SD card to serial output */ inline void gcode_M20() { SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST); card.ls(); SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST); } /** * M21: Init SD Card */ inline void gcode_M21() { card.initsd(); } /** * M22: Release SD Card */ inline void gcode_M22() { card.release(); } /** * M23: Open a file */ inline void gcode_M23() { #if ENABLED(POWER_LOSS_RECOVERY) card.removeJobRecoveryFile(); #endif // Simplify3D includes the size, so zero out all spaces (#7227) for (char *fn = parser.string_arg; *fn; ++fn) if (*fn == ' ') *fn = '\0'; card.openFile(parser.string_arg, true); } /** * M24: Start or Resume SD Print */ inline void gcode_M24() { #if ENABLED(PARK_HEAD_ON_PAUSE) resume_print(); #endif #if ENABLED(POWER_LOSS_RECOVERY) if (parser.seenval('S')) card.setIndex(parser.value_long()); #endif card.startFileprint(); #if ENABLED(POWER_LOSS_RECOVERY) if (parser.seenval('T')) print_job_timer.resume(parser.value_long()); else #endif print_job_timer.start(); } /** * M25: Pause SD Print */ inline void gcode_M25() { card.pauseSDPrint(); print_job_timer.pause(); #if ENABLED(PARK_HEAD_ON_PAUSE) enqueue_and_echo_commands_P(PSTR("M125")); // Must be enqueued with pauseSDPrint set to be last in the buffer #endif } /** * M26: Set SD Card file index */ inline void gcode_M26() { if (card.cardOK && parser.seenval('S')) card.setIndex(parser.value_long()); } /** * M27: Get SD Card status * OR, with 'S<seconds>' set the SD status auto-report interval. (Requires AUTO_REPORT_SD_STATUS) * OR, with 'C' get the current filename. */ inline void gcode_M27() { if (parser.seen('C')) { SERIAL_ECHOPGM("Current file: "); card.printFilename(); } #if ENABLED(AUTO_REPORT_SD_STATUS) else if (parser.seenval('S')) card.set_auto_report_interval(parser.value_byte()); #endif else card.getStatus(); } /** * M28: Start SD Write */ inline void gcode_M28() { card.openFile(parser.string_arg, false); } /** * M29: Stop SD Write * Processed in write to file routine above */ inline void gcode_M29() { // card.saving = false; } /** * M30 <filename>: Delete SD Card file */ inline void gcode_M30() { if (card.cardOK) { card.closefile(); card.removeFile(parser.string_arg); } } #endif // SDSUPPORT /** * M31: Get the time since the start of SD Print (or last M109) */ inline void gcode_M31() { char buffer[21]; duration_t elapsed = print_job_timer.duration(); elapsed.toString(buffer); lcd_setstatus(buffer); SERIAL_ECHO_START(); SERIAL_ECHOLNPAIR("Print time: ", buffer); } #if ENABLED(SDSUPPORT) /** * M32: Select file and start SD Print * * Examples: * * M32 !PATH/TO/FILE.GCO# ; Start FILE.GCO * M32 P !PATH/TO/FILE.GCO# ; Start FILE.GCO as a procedure * M32 S60 !PATH/TO/FILE.GCO# ; Start FILE.GCO at byte 60 * */ inline void gcode_M32() { if (card.sdprinting) planner.synchronize(); if (card.cardOK) { const bool call_procedure = parser.boolval('P'); card.openFile(parser.string_arg, true, call_procedure); if (parser.seenval('S')) card.setIndex(parser.value_long()); card.startFileprint(); // Procedure calls count as normal print time. if (!call_procedure) print_job_timer.start(); } } #if ENABLED(LONG_FILENAME_HOST_SUPPORT) /** * M33: Get the long full path of a file or folder * * Parameters: * <dospath> Case-insensitive DOS-style path to a file or folder * * Example: * M33 miscel~1/armchair/armcha~1.gco * * Output: * /Miscellaneous/Armchair/Armchair.gcode */ inline void gcode_M33() { card.printLongPath(parser.string_arg); } #endif #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE) /** * M34: Set SD Card Sorting Options */ inline void gcode_M34() { if (parser.seen('S')) card.setSortOn(parser.value_bool()); if (parser.seenval('F')) { const int v = parser.value_long(); card.setSortFolders(v < 0 ? -1 : v > 0 ? 1 : 0); } //if (parser.seen('R')) card.setSortReverse(parser.value_bool()); } #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE /** * M928: Start SD Write */ inline void gcode_M928() { card.openLogFile(parser.string_arg); } #endif // SDSUPPORT /** * Sensitive pin test for M42, M226 */ static bool pin_is_protected(const pin_t pin) { static const pin_t sensitive_pins[] PROGMEM = SENSITIVE_PINS; for (uint8_t i = 0; i < COUNT(sensitive_pins); i++) if (pin == (pin_t)pgm_read_byte(&sensitive_pins[i])) return true; return false; } inline void protected_pin_err() { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_PROTECTED_PIN); } /** * M42: Change pin status via GCode * * P<pin> Pin number (LED if omitted) * S<byte> Pin status from 0 - 255 * I Flag to ignore Marlin's pin protection */ inline void gcode_M42() { if (!parser.seenval('S')) return; const byte pin_status = parser.value_byte(); const pin_t pin_number = parser.byteval('P', LED_PIN); if (pin_number < 0) return; if (!parser.boolval('I') && pin_is_protected(pin_number)) return protected_pin_err(); pinMode(pin_number, OUTPUT); digitalWrite(pin_number, pin_status); analogWrite(pin_number, pin_status); #if FAN_COUNT > 0 switch (pin_number) { #if HAS_FAN0 case FAN_PIN: fanSpeeds[0] = pin_status; break; #endif #if HAS_FAN1 case FAN1_PIN: fanSpeeds[1] = pin_status; break; #endif #if HAS_FAN2 case FAN2_PIN: fanSpeeds[2] = pin_status; break; #endif } #endif } #if ENABLED(PINS_DEBUGGING) #include "pinsDebug.h" inline void toggle_pins() { const bool ignore_protection = parser.boolval('I'); const int repeat = parser.intval('R', 1), start = parser.intval('S'), end = parser.intval('L', NUM_DIGITAL_PINS - 1), wait = parser.intval('W', 500); for (uint8_t pin = start; pin <= end; pin++) { //report_pin_state_extended(pin, ignore_protection, false); if (!ignore_protection && pin_is_protected(pin)) { report_pin_state_extended(pin, ignore_protection, true, "Untouched "); SERIAL_EOL(); } else { report_pin_state_extended(pin, ignore_protection, true, "Pulsing "); #if AVR_AT90USB1286_FAMILY // Teensy IDEs don't know about these pins so must use FASTIO if (pin == TEENSY_E2) { SET_OUTPUT(TEENSY_E2); for (int16_t j = 0; j < repeat; j++) { WRITE(TEENSY_E2, LOW); safe_delay(wait); WRITE(TEENSY_E2, HIGH); safe_delay(wait); WRITE(TEENSY_E2, LOW); safe_delay(wait); } } else if (pin == TEENSY_E3) { SET_OUTPUT(TEENSY_E3); for (int16_t j = 0; j < repeat; j++) { WRITE(TEENSY_E3, LOW); safe_delay(wait); WRITE(TEENSY_E3, HIGH); safe_delay(wait); WRITE(TEENSY_E3, LOW); safe_delay(wait); } } else #endif { pinMode(pin, OUTPUT); for (int16_t j = 0; j < repeat; j++) { digitalWrite(pin, 0); safe_delay(wait); digitalWrite(pin, 1); safe_delay(wait); digitalWrite(pin, 0); safe_delay(wait); } } } SERIAL_EOL(); } SERIAL_ECHOLNPGM("Done."); } // toggle_pins inline void servo_probe_test() { #if !(NUM_SERVOS > 0 && HAS_SERVO_0) SERIAL_ERROR_START(); SERIAL_ERRORLNPGM("SERVO not setup"); #elif !HAS_Z_SERVO_PROBE SERIAL_ERROR_START(); SERIAL_ERRORLNPGM("Z_PROBE_SERVO_NR not setup"); #else // HAS_Z_SERVO_PROBE const uint8_t probe_index = parser.byteval('P', Z_PROBE_SERVO_NR); SERIAL_PROTOCOLLNPGM("Servo probe test"); SERIAL_PROTOCOLLNPAIR(". using index: ", probe_index); SERIAL_PROTOCOLLNPAIR(". deploy angle: ", z_servo_angle[0]); SERIAL_PROTOCOLLNPAIR(". stow angle: ", z_servo_angle[1]); bool probe_inverting; #if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) #define PROBE_TEST_PIN Z_MIN_PIN SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN pin: ", PROBE_TEST_PIN); SERIAL_PROTOCOLLNPGM(". uses Z_MIN_ENDSTOP_INVERTING (ignores Z_MIN_PROBE_ENDSTOP_INVERTING)"); SERIAL_PROTOCOLPGM(". Z_MIN_ENDSTOP_INVERTING: "); #if Z_MIN_ENDSTOP_INVERTING SERIAL_PROTOCOLLNPGM("true"); #else SERIAL_PROTOCOLLNPGM("false"); #endif probe_inverting = Z_MIN_ENDSTOP_INVERTING; #elif ENABLED(Z_MIN_PROBE_ENDSTOP) #define PROBE_TEST_PIN Z_MIN_PROBE_PIN SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN_PROBE_PIN: ", PROBE_TEST_PIN); SERIAL_PROTOCOLLNPGM(". uses Z_MIN_PROBE_ENDSTOP_INVERTING (ignores Z_MIN_ENDSTOP_INVERTING)"); SERIAL_PROTOCOLPGM(". Z_MIN_PROBE_ENDSTOP_INVERTING: "); #if Z_MIN_PROBE_ENDSTOP_INVERTING SERIAL_PROTOCOLLNPGM("true"); #else SERIAL_PROTOCOLLNPGM("false"); #endif probe_inverting = Z_MIN_PROBE_ENDSTOP_INVERTING; #endif SERIAL_PROTOCOLLNPGM(". deploy & stow 4 times"); SET_INPUT_PULLUP(PROBE_TEST_PIN); bool deploy_state, stow_state; for (uint8_t i = 0; i < 4; i++) { MOVE_SERVO(probe_index, z_servo_angle[0]); //deploy safe_delay(500); deploy_state = READ(PROBE_TEST_PIN); MOVE_SERVO(probe_index, z_servo_angle[1]); //stow safe_delay(500); stow_state = READ(PROBE_TEST_PIN); } if (probe_inverting != deploy_state) SERIAL_PROTOCOLLNPGM("WARNING - INVERTING setting probably backwards"); if (deploy_state != stow_state) { SERIAL_PROTOCOLLNPGM("BLTouch clone detected"); if (deploy_state) { SERIAL_PROTOCOLLNPGM(". DEPLOYED state: HIGH (logic 1)"); SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: LOW (logic 0)"); } else { SERIAL_PROTOCOLLNPGM(". DEPLOYED state: LOW (logic 0)"); SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: HIGH (logic 1)"); } #if ENABLED(BLTOUCH) SERIAL_PROTOCOLLNPGM("ERROR: BLTOUCH enabled - set this device up as a Z Servo Probe with inverting as true."); #endif } else { // measure active signal length MOVE_SERVO(probe_index, z_servo_angle[0]); // deploy safe_delay(500); SERIAL_PROTOCOLLNPGM("please trigger probe"); uint16_t probe_counter = 0; // Allow 30 seconds max for operator to trigger probe for (uint16_t j = 0; j < 500 * 30 && probe_counter == 0 ; j++) { safe_delay(2); if (0 == j % (500 * 1)) reset_stepper_timeout(); // Keep steppers powered if (deploy_state != READ(PROBE_TEST_PIN)) { // probe triggered for (probe_counter = 1; probe_counter < 50 && deploy_state != READ(PROBE_TEST_PIN); ++probe_counter) safe_delay(2); if (probe_counter == 50) SERIAL_PROTOCOLLNPGM("Z Servo Probe detected"); // >= 100mS active time else if (probe_counter >= 2) SERIAL_PROTOCOLLNPAIR("BLTouch compatible probe detected - pulse width (+/- 4mS): ", probe_counter * 2); // allow 4 - 100mS pulse else SERIAL_PROTOCOLLNPGM("noise detected - please re-run test"); // less than 2mS pulse MOVE_SERVO(probe_index, z_servo_angle[1]); //stow } // pulse detected } // for loop waiting for trigger if (probe_counter == 0) SERIAL_PROTOCOLLNPGM("trigger not detected"); } // measure active signal length #endif } // servo_probe_test /** * M43: Pin debug - report pin state, watch pins, toggle pins and servo probe test/report * * M43 - report name and state of pin(s) * P<pin> Pin to read or watch. If omitted, reads all pins. * I Flag to ignore Marlin's pin protection. * * M43 W - Watch pins -reporting changes- until reset, click, or M108. * P<pin> Pin to read or watch. If omitted, read/watch all pins. * I Flag to ignore Marlin's pin protection. * * M43 E<bool> - Enable / disable background endstop monitoring * - Machine continues to operate * - Reports changes to endstops * - Toggles LED_PIN when an endstop changes * - Can not reliably catch the 5mS pulse from BLTouch type probes * * M43 T - Toggle pin(s) and report which pin is being toggled * S<pin> - Start Pin number. If not given, will default to 0 * L<pin> - End Pin number. If not given, will default to last pin defined for this board * I<bool> - Flag to ignore Marlin's pin protection. Use with caution!!!! * R - Repeat pulses on each pin this number of times before continueing to next pin * W - Wait time (in miliseconds) between pulses. If not given will default to 500 * * M43 S - Servo probe test * P<index> - Probe index (optional - defaults to 0 */ inline void gcode_M43() { if (parser.seen('T')) { // must be first or else its "S" and "E" parameters will execute endstop or servo test toggle_pins(); return; } // Enable or disable endstop monitoring if (parser.seen('E')) { endstops.monitor_flag = parser.value_bool(); SERIAL_PROTOCOLPGM("endstop monitor "); serialprintPGM(endstops.monitor_flag ? PSTR("en") : PSTR("dis")); SERIAL_PROTOCOLLNPGM("abled"); return; } if (parser.seen('S')) { servo_probe_test(); return; } // Get the range of pins to test or watch const pin_t first_pin = parser.byteval('P'), last_pin = parser.seenval('P') ? first_pin : NUM_DIGITAL_PINS - 1; if (first_pin > last_pin) return; const bool ignore_protection = parser.boolval('I'); // Watch until click, M108, or reset if (parser.boolval('W')) { SERIAL_PROTOCOLLNPGM("Watching pins"); byte pin_state[last_pin - first_pin + 1]; for (pin_t pin = first_pin; pin <= last_pin; pin++) { if (!ignore_protection && pin_is_protected(pin)) continue; pinMode(pin, INPUT_PULLUP); delay(1); /* if (IS_ANALOG(pin)) pin_state[pin - first_pin] = analogRead(pin - analogInputToDigitalPin(0)); // int16_t pin_state[...] else //*/ pin_state[pin - first_pin] = digitalRead(pin); } #if HAS_RESUME_CONTINUE wait_for_user = true; KEEPALIVE_STATE(PAUSED_FOR_USER); #endif for (;;) { for (pin_t pin = first_pin; pin <= last_pin; pin++) { if (!ignore_protection && pin_is_protected(pin)) continue; const byte val = /* IS_ANALOG(pin) ? analogRead(pin - analogInputToDigitalPin(0)) : // int16_t val : //*/ digitalRead(pin); if (val != pin_state[pin - first_pin]) { report_pin_state_extended(pin, ignore_protection, false); pin_state[pin - first_pin] = val; } } #if HAS_RESUME_CONTINUE if (!wait_for_user) { KEEPALIVE_STATE(IN_HANDLER); break; } #endif safe_delay(200); } return; } // Report current state of selected pin(s) for (pin_t pin = first_pin; pin <= last_pin; pin++) report_pin_state_extended(pin, ignore_protection, true); } #endif // PINS_DEBUGGING #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST) /** * M48: Z probe repeatability measurement function. * * Usage: * M48 <P#> <X#> <Y#> <V#> <E> <L#> <S> * P = Number of sampled points (4-50, default 10) * X = Sample X position * Y = Sample Y position * V = Verbose level (0-4, default=1) * E = Engage Z probe for each reading * L = Number of legs of movement before probe * S = Schizoid (Or Star if you prefer) * * This function requires the machine to be homed before invocation. */ inline void gcode_M48() { if (axis_unhomed_error()) return; const int8_t verbose_level = parser.byteval('V', 1); if (!WITHIN(verbose_level, 0, 4)) { SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4)."); return; } if (verbose_level > 0) SERIAL_PROTOCOLLNPGM("M48 Z-Probe Repeatability Test"); const int8_t n_samples = parser.byteval('P', 10); if (!WITHIN(n_samples, 4, 50)) { SERIAL_PROTOCOLLNPGM("?Sample size not plausible (4-50)."); return; } const ProbePtRaise raise_after = parser.boolval('E') ? PROBE_PT_STOW : PROBE_PT_RAISE; float X_current = current_position[X_AXIS], Y_current = current_position[Y_AXIS]; const float X_probe_location = parser.linearval('X', X_current + X_PROBE_OFFSET_FROM_EXTRUDER), Y_probe_location = parser.linearval('Y', Y_current + Y_PROBE_OFFSET_FROM_EXTRUDER); if (!position_is_reachable_by_probe(X_probe_location, Y_probe_location)) { SERIAL_PROTOCOLLNPGM("? (X,Y) out of bounds."); return; } bool seen_L = parser.seen('L'); uint8_t n_legs = seen_L ? parser.value_byte() : 0; if (n_legs > 15) { SERIAL_PROTOCOLLNPGM("?Number of legs in movement not plausible (0-15)."); return; } if (n_legs == 1) n_legs = 2; const bool schizoid_flag = parser.boolval('S'); if (schizoid_flag && !seen_L) n_legs = 7; /** * Now get everything to the specified probe point So we can safely do a * probe to get us close to the bed. If the Z-Axis is far from the bed, * we don't want to use that as a starting point for each probe. */ if (verbose_level > 2) SERIAL_PROTOCOLLNPGM("Positioning the probe..."); // Disable bed level correction in M48 because we want the raw data when we probe #if HAS_LEVELING const bool was_enabled = planner.leveling_active; set_bed_leveling_enabled(false); #endif setup_for_endstop_or_probe_move(); float mean = 0.0, sigma = 0.0, min = 99999.9, max = -99999.9, sample_set[n_samples]; // Move to the first point, deploy, and probe const float t = probe_pt(X_probe_location, Y_probe_location, raise_after, verbose_level); bool probing_good = !isnan(t); if (probing_good) { randomSeed(millis()); for (uint8_t n = 0; n < n_samples; n++) { if (n_legs) { const int dir = (random(0, 10) > 5.0) ? -1 : 1; // clockwise or counter clockwise float angle = random(0.0, 360.0); const float radius = random( #if ENABLED(DELTA) 0.1250000000 * (DELTA_PRINTABLE_RADIUS), 0.3333333333 * (DELTA_PRINTABLE_RADIUS) #else 5.0, 0.125 * MIN(X_BED_SIZE, Y_BED_SIZE) #endif ); if (verbose_level > 3) { SERIAL_ECHOPAIR("Starting radius: ", radius); SERIAL_ECHOPAIR(" angle: ", angle); SERIAL_ECHOPGM(" Direction: "); if (dir > 0) SERIAL_ECHOPGM("Counter-"); SERIAL_ECHOLNPGM("Clockwise"); } for (uint8_t l = 0; l < n_legs - 1; l++) { float delta_angle; if (schizoid_flag) // The points of a 5 point star are 72 degrees apart. We need to // skip a point and go to the next one on the star. delta_angle = dir * 2.0 * 72.0; else // If we do this line, we are just trying to move further // around the circle. delta_angle = dir * (float) random(25, 45); angle += delta_angle; while (angle > 360.0) // We probably do not need to keep the angle between 0 and 2*PI, but the angle -= 360.0; // Arduino documentation says the trig functions should not be given values while (angle < 0.0) // outside of this range. It looks like they behave correctly with angle += 360.0; // numbers outside of the range, but just to be safe we clamp them. X_current = X_probe_location - (X_PROBE_OFFSET_FROM_EXTRUDER) + cos(RADIANS(angle)) * radius; Y_current = Y_probe_location - (Y_PROBE_OFFSET_FROM_EXTRUDER) + sin(RADIANS(angle)) * radius; #if DISABLED(DELTA) X_current = constrain(X_current, X_MIN_POS, X_MAX_POS); Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS); #else // If we have gone out too far, we can do a simple fix and scale the numbers // back in closer to the origin. while (!position_is_reachable_by_probe(X_current, Y_current)) { X_current *= 0.8; Y_current *= 0.8; if (verbose_level > 3) { SERIAL_ECHOPAIR("Pulling point towards center:", X_current); SERIAL_ECHOLNPAIR(", ", Y_current); } } #endif if (verbose_level > 3) { SERIAL_PROTOCOLPGM("Going to:"); SERIAL_ECHOPAIR(" X", X_current); SERIAL_ECHOPAIR(" Y", Y_current); SERIAL_ECHOLNPAIR(" Z", current_position[Z_AXIS]); } do_blocking_move_to_xy(X_current, Y_current); } // n_legs loop } // n_legs // Probe a single point sample_set[n] = probe_pt(X_probe_location, Y_probe_location, raise_after); // Break the loop if the probe fails probing_good = !isnan(sample_set[n]); if (!probing_good) break; /** * Get the current mean for the data points we have so far */ float sum = 0.0; for (uint8_t j = 0; j <= n; j++) sum += sample_set[j]; mean = sum / (n + 1); NOMORE(min, sample_set[n]); NOLESS(max, sample_set[n]); /** * Now, use that mean to calculate the standard deviation for the * data points we have so far */ sum = 0.0; for (uint8_t j = 0; j <= n; j++) sum += sq(sample_set[j] - mean); sigma = SQRT(sum / (n + 1)); if (verbose_level > 0) { if (verbose_level > 1) { SERIAL_PROTOCOL(n + 1); SERIAL_PROTOCOLPGM(" of "); SERIAL_PROTOCOL(int(n_samples)); SERIAL_PROTOCOLPGM(": z: "); SERIAL_PROTOCOL_F(sample_set[n], 3); if (verbose_level > 2) { SERIAL_PROTOCOLPGM(" mean: "); SERIAL_PROTOCOL_F(mean, 4); SERIAL_PROTOCOLPGM(" sigma: "); SERIAL_PROTOCOL_F(sigma, 6); SERIAL_PROTOCOLPGM(" min: "); SERIAL_PROTOCOL_F(min, 3); SERIAL_PROTOCOLPGM(" max: "); SERIAL_PROTOCOL_F(max, 3); SERIAL_PROTOCOLPGM(" range: "); SERIAL_PROTOCOL_F(max-min, 3); } SERIAL_EOL(); } } } // n_samples loop } STOW_PROBE(); if (probing_good) { SERIAL_PROTOCOLLNPGM("Finished!"); if (verbose_level > 0) { SERIAL_PROTOCOLPGM("Mean: "); SERIAL_PROTOCOL_F(mean, 6); SERIAL_PROTOCOLPGM(" Min: "); SERIAL_PROTOCOL_F(min, 3); SERIAL_PROTOCOLPGM(" Max: "); SERIAL_PROTOCOL_F(max, 3); SERIAL_PROTOCOLPGM(" Range: "); SERIAL_PROTOCOL_F(max-min, 3); SERIAL_EOL(); } SERIAL_PROTOCOLPGM("Standard Deviation: "); SERIAL_PROTOCOL_F(sigma, 6); SERIAL_EOL(); SERIAL_EOL(); } clean_up_after_endstop_or_probe_move(); // Re-enable bed level correction if it had been on #if HAS_LEVELING set_bed_leveling_enabled(was_enabled); #endif #ifdef Z_AFTER_PROBING move_z_after_probing(); #endif report_current_position(); } #endif // Z_MIN_PROBE_REPEATABILITY_TEST #if ENABLED(G26_MESH_VALIDATION) inline void gcode_M49() { g26_debug_flag ^= true; SERIAL_PROTOCOLPGM("G26 Debug "); serialprintPGM(g26_debug_flag ? PSTR("on.\n") : PSTR("off.\n")); } #endif // G26_MESH_VALIDATION #if ENABLED(ULTRA_LCD) && ENABLED(LCD_SET_PROGRESS_MANUALLY) /** * M73: Set percentage complete (for display on LCD) * * Example: * M73 P25 ; Set progress to 25% * * Notes: * This has no effect during an SD print job */ inline void gcode_M73() { if (!IS_SD_PRINTING() && parser.seen('P')) { progress_bar_percent = parser.value_byte(); NOMORE(progress_bar_percent, 100); } } #endif // ULTRA_LCD && LCD_SET_PROGRESS_MANUALLY /** * M75: Start print timer */ inline void gcode_M75() { print_job_timer.start(); } /** * M76: Pause print timer */ inline void gcode_M76() { print_job_timer.pause(); } /** * M77: Stop print timer */ inline void gcode_M77() { print_job_timer.stop(); } #if ENABLED(PRINTCOUNTER) /** * M78: Show print statistics */ inline void gcode_M78() { // "M78 S78" will reset the statistics if (parser.intval('S') == 78) print_job_timer.initStats(); else print_job_timer.showStats(); } #endif /** * M104: Set hot end temperature */ inline void gcode_M104() { if (get_target_extruder_from_command(104)) return; if (DEBUGGING(DRYRUN)) return; #if ENABLED(SINGLENOZZLE) if (target_extruder != active_extruder) return; #endif if (parser.seenval('S')) { const int16_t temp = parser.value_celsius(); thermalManager.setTargetHotend(temp, target_extruder); #if ENABLED(DUAL_X_CARRIAGE) if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0) thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1); #endif #if ENABLED(PRINTJOB_TIMER_AUTOSTART) /** * Stop the timer at the end of print. Start is managed by 'heat and wait' M109. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot * standby mode, for instance in a dual extruder setup, without affecting * the running print timer. */ if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) { print_job_timer.stop(); lcd_reset_status(); } #endif } #if ENABLED(AUTOTEMP) planner.autotemp_M104_M109(); #endif } /** * M105: Read hot end and bed temperature */ inline void gcode_M105() { if (get_target_extruder_from_command(105)) return; #if HAS_TEMP_SENSOR SERIAL_PROTOCOLPGM(MSG_OK); thermalManager.print_heaterstates(); #else // !HAS_TEMP_SENSOR SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS); #endif SERIAL_EOL(); } #if ENABLED(AUTO_REPORT_TEMPERATURES) /** * M155: Set temperature auto-report interval. M155 S<seconds> */ inline void gcode_M155() { if (parser.seenval('S')) thermalManager.set_auto_report_interval(parser.value_byte()); } #endif // AUTO_REPORT_TEMPERATURES #if FAN_COUNT > 0 /** * M106: Set Fan Speed * * S<int> Speed between 0-255 * P<index> Fan index, if more than one fan * * With EXTRA_FAN_SPEED enabled: * * T<int> Restore/Use/Set Temporary Speed: * 1 = Restore previous speed after T2 * 2 = Use temporary speed set with T3-255 * 3-255 = Set the speed for use with T2 */ inline void gcode_M106() { const uint8_t p = parser.byteval('P'); if (p < FAN_COUNT) { #if ENABLED(EXTRA_FAN_SPEED) const int16_t t = parser.intval('T'); if (t > 0) { switch (t) { case 1: fanSpeeds[p] = old_fanSpeeds[p]; break; case 2: old_fanSpeeds[p] = fanSpeeds[p]; fanSpeeds[p] = new_fanSpeeds[p]; break; default: new_fanSpeeds[p] = MIN(t, 255); break; } return; } #endif // EXTRA_FAN_SPEED const uint16_t s = parser.ushortval('S', 255); fanSpeeds[p] = MIN(s, 255U); } } /** * M107: Fan Off */ inline void gcode_M107() { const uint16_t p = parser.ushortval('P'); if (p < FAN_COUNT) fanSpeeds[p] = 0; } #endif // FAN_COUNT > 0 #if DISABLED(EMERGENCY_PARSER) /** * M108: Stop the waiting for heaters in M109, M190, M303. Does not affect the target temperature. */ inline void gcode_M108() { wait_for_heatup = false; } /** * M112: Emergency Stop */ inline void gcode_M112() { kill(PSTR(MSG_KILLED)); } /** * M410: Quickstop - Abort all planned moves * * This will stop the carriages mid-move, so most likely they * will be out of sync with the stepper position after this. */ inline void gcode_M410() { quickstop_stepper(); } #endif /** * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling. */ #ifndef MIN_COOLING_SLOPE_DEG #define MIN_COOLING_SLOPE_DEG 1.50 #endif #ifndef MIN_COOLING_SLOPE_TIME #define MIN_COOLING_SLOPE_TIME 60 #endif inline void gcode_M109() { if (get_target_extruder_from_command(109)) return; if (DEBUGGING(DRYRUN)) return; #if ENABLED(SINGLENOZZLE) if (target_extruder != active_extruder) return; #endif const bool no_wait_for_cooling = parser.seenval('S'), set_temp = no_wait_for_cooling || parser.seenval('R'); if (set_temp) { const int16_t temp = parser.value_celsius(); thermalManager.setTargetHotend(temp, target_extruder); #if ENABLED(DUAL_X_CARRIAGE) if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0) thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1); #endif #if ENABLED(PRINTJOB_TIMER_AUTOSTART) /** * Use half EXTRUDE_MINTEMP to allow nozzles to be put into hot * standby mode, (e.g., in a dual extruder setup) without affecting * the running print timer. */ if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) { print_job_timer.stop(); lcd_reset_status(); } else print_job_timer.start(); #endif #if ENABLED(ULTRA_LCD) const bool heating = thermalManager.isHeatingHotend(target_extruder); if (heating || !no_wait_for_cooling) #if HOTENDS > 1 lcd_status_printf_P(0, heating ? PSTR("E%i " MSG_HEATING) : PSTR("E%i " MSG_COOLING), target_extruder + 1); #else lcd_setstatusPGM(heating ? PSTR("E " MSG_HEATING) : PSTR("E " MSG_COOLING)); #endif #endif } #ifdef ANYCUBIC_TFT_MODEL AnycubicTFT.HeatingStart(); #endif #if ENABLED(AUTOTEMP) planner.autotemp_M104_M109(); #endif if (!set_temp) return; #if TEMP_RESIDENCY_TIME > 0 millis_t residency_start_ms = 0; // Loop until the temperature has stabilized #define TEMP_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL)) #else // Loop until the temperature is very close target #define TEMP_CONDITIONS (wants_to_cool ? thermalManager.isCoolingHotend(target_extruder) : thermalManager.isHeatingHotend(target_extruder)) #endif float target_temp = -1, old_temp = 9999; bool wants_to_cool = false; wait_for_heatup = true; millis_t now, next_temp_ms = 0, next_cool_check_ms = 0; #if DISABLED(BUSY_WHILE_HEATING) KEEPALIVE_STATE(NOT_BUSY); #endif #if ENABLED(PRINTER_EVENT_LEDS) const float start_temp = thermalManager.degHotend(target_extruder); uint8_t old_blue = 0; #endif do { // Target temperature might be changed during the loop if (target_temp != thermalManager.degTargetHotend(target_extruder)) { wants_to_cool = thermalManager.isCoolingHotend(target_extruder); target_temp = thermalManager.degTargetHotend(target_extruder); // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher> if (no_wait_for_cooling && wants_to_cool) break; } now = millis(); if (ELAPSED(now, next_temp_ms)) { //Print temp & remaining time every 1s while waiting next_temp_ms = now + 1000UL; thermalManager.print_heaterstates(); #if TEMP_RESIDENCY_TIME > 0 SERIAL_PROTOCOLPGM(" W:"); if (residency_start_ms) SERIAL_PROTOCOL(long((((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL)); else SERIAL_PROTOCOLCHAR('?'); #endif SERIAL_EOL(); } idle(); reset_stepper_timeout(); // Keep steppers powered const float temp = thermalManager.degHotend(target_extruder); #if ENABLED(PRINTER_EVENT_LEDS) // Gradually change LED strip from violet to red as nozzle heats up if (!wants_to_cool) { const uint8_t blue = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 255, 0); if (blue != old_blue) { old_blue = blue; leds.set_color( MakeLEDColor(255, 0, blue, 0, pixels.getBrightness()) #if ENABLED(NEOPIXEL_IS_SEQUENTIAL) , true #endif ); } } #endif #ifdef ANYCUBIC_TFT_MODEL AnycubicTFT.CommandScan(); #endif #if TEMP_RESIDENCY_TIME > 0 const float temp_diff = ABS(target_temp - temp); if (!residency_start_ms) { // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time. if (temp_diff < TEMP_WINDOW) residency_start_ms = now; } else if (temp_diff > TEMP_HYSTERESIS) { // Restart the timer whenever the temperature falls outside the hysteresis. residency_start_ms = now; } #endif // Prevent a wait-forever situation if R is misused i.e. M109 R0 if (wants_to_cool) { // break after MIN_COOLING_SLOPE_TIME seconds // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) { if (old_temp - temp < float(MIN_COOLING_SLOPE_DEG)) break; next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME; old_temp = temp; } } } while (wait_for_heatup && TEMP_CONDITIONS); if (wait_for_heatup) { lcd_reset_status(); #if ENABLED(PRINTER_EVENT_LEDS) leds.set_white(); #endif } #ifdef ANYCUBIC_TFT_MODEL AnycubicTFT.HeatingDone(); #endif #if DISABLED(BUSY_WHILE_HEATING) KEEPALIVE_STATE(IN_HANDLER); #endif // flush the serial buffer after heating to prevent lockup by m105 //SERIAL_FLUSH(); } #if HAS_HEATED_BED /** * M140: Set bed temperature */ inline void gcode_M140() { if (DEBUGGING(DRYRUN)) return; if (parser.seenval('S')) thermalManager.setTargetBed(parser.value_celsius()); } #ifndef MIN_COOLING_SLOPE_DEG_BED #define MIN_COOLING_SLOPE_DEG_BED 1.50 #endif #ifndef MIN_COOLING_SLOPE_TIME_BED #define MIN_COOLING_SLOPE_TIME_BED 60 #endif /** * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling */ inline void gcode_M190() { if (DEBUGGING(DRYRUN)) return; const bool no_wait_for_cooling = parser.seenval('S'); if (no_wait_for_cooling || parser.seenval('R')) { thermalManager.setTargetBed(parser.value_celsius()); #if ENABLED(PRINTJOB_TIMER_AUTOSTART) if (parser.value_celsius() > BED_MINTEMP) print_job_timer.start(); #endif } else return; #ifdef ANYCUBIC_TFT_MODEL AnycubicTFT.BedHeatingStart(); #endif lcd_setstatusPGM(thermalManager.isHeatingBed() ? PSTR(MSG_BED_HEATING) : PSTR(MSG_BED_COOLING)); #if TEMP_BED_RESIDENCY_TIME > 0 millis_t residency_start_ms = 0; // Loop until the temperature has stabilized #define TEMP_BED_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_BED_RESIDENCY_TIME) * 1000UL)) #else // Loop until the temperature is very close target #define TEMP_BED_CONDITIONS (wants_to_cool ? thermalManager.isCoolingBed() : thermalManager.isHeatingBed()) #endif float target_temp = -1.0, old_temp = 9999.0; bool wants_to_cool = false; wait_for_heatup = true; millis_t now, next_temp_ms = 0, next_cool_check_ms = 0; #if DISABLED(BUSY_WHILE_HEATING) KEEPALIVE_STATE(NOT_BUSY); #endif target_extruder = active_extruder; // for print_heaterstates #if ENABLED(PRINTER_EVENT_LEDS) const float start_temp = thermalManager.degBed(); uint8_t old_red = 127; #endif do { // Target temperature might be changed during the loop if (target_temp != thermalManager.degTargetBed()) { wants_to_cool = thermalManager.isCoolingBed(); target_temp = thermalManager.degTargetBed(); // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher> if (no_wait_for_cooling && wants_to_cool) break; } now = millis(); if (ELAPSED(now, next_temp_ms)) { //Print Temp Reading every 1 second while heating up. next_temp_ms = now + 1000UL; thermalManager.print_heaterstates(); #if TEMP_BED_RESIDENCY_TIME > 0 SERIAL_PROTOCOLPGM(" W:"); if (residency_start_ms) SERIAL_PROTOCOL(long((((TEMP_BED_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL)); else SERIAL_PROTOCOLCHAR('?'); #endif SERIAL_EOL(); } idle(); reset_stepper_timeout(); // Keep steppers powered const float temp = thermalManager.degBed(); #if ENABLED(PRINTER_EVENT_LEDS) // Gradually change LED strip from blue to violet as bed heats up if (!wants_to_cool) { const uint8_t red = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 0, 255); if (red != old_red) { old_red = red; leds.set_color( MakeLEDColor(red, 0, 255, 0, pixels.getBrightness()) #if ENABLED(NEOPIXEL_IS_SEQUENTIAL) , true #endif ); } } #endif #ifdef ANYCUBIC_TFT_MODEL AnycubicTFT.CommandScan(); #endif #if TEMP_BED_RESIDENCY_TIME > 0 const float temp_diff = ABS(target_temp - temp); if (!residency_start_ms) { // Start the TEMP_BED_RESIDENCY_TIME timer when we reach target temp for the first time. if (temp_diff < TEMP_BED_WINDOW) residency_start_ms = now; } else if (temp_diff > TEMP_BED_HYSTERESIS) { // Restart the timer whenever the temperature falls outside the hysteresis. residency_start_ms = now; } #endif // TEMP_BED_RESIDENCY_TIME > 0 // Prevent a wait-forever situation if R is misused i.e. M190 R0 if (wants_to_cool) { // Break after MIN_COOLING_SLOPE_TIME_BED seconds // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_BED if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) { if (old_temp - temp < float(MIN_COOLING_SLOPE_DEG_BED)) break; next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME_BED; old_temp = temp; } } } while (wait_for_heatup && TEMP_BED_CONDITIONS); #ifdef ANYCUBIC_TFT_MODEL AnycubicTFT.BedHeatingDone(); #endif if (wait_for_heatup) lcd_reset_status(); #if DISABLED(BUSY_WHILE_HEATING) KEEPALIVE_STATE(IN_HANDLER); #endif // flush the serial buffer after heating to prevent lockup by m105 //SERIAL_FLUSH(); } #endif // HAS_HEATED_BED /** * M110: Set Current Line Number */ inline void gcode_M110() { if (parser.seenval('N')) gcode_LastN = parser.value_long(); } /** * M111: Set the debug level */ inline void gcode_M111() { if (parser.seen('S')) marlin_debug_flags = parser.byteval('S'); static const char str_debug_1[] PROGMEM = MSG_DEBUG_ECHO, str_debug_2[] PROGMEM = MSG_DEBUG_INFO, str_debug_4[] PROGMEM = MSG_DEBUG_ERRORS, str_debug_8[] PROGMEM = MSG_DEBUG_DRYRUN, str_debug_16[] PROGMEM = MSG_DEBUG_COMMUNICATION #if ENABLED(DEBUG_LEVELING_FEATURE) , str_debug_32[] PROGMEM = MSG_DEBUG_LEVELING #endif ; static const char* const debug_strings[] PROGMEM = { str_debug_1, str_debug_2, str_debug_4, str_debug_8, str_debug_16 #if ENABLED(DEBUG_LEVELING_FEATURE) , str_debug_32 #endif }; SERIAL_ECHO_START(); SERIAL_ECHOPGM(MSG_DEBUG_PREFIX); if (marlin_debug_flags) { uint8_t comma = 0; for (uint8_t i = 0; i < COUNT(debug_strings); i++) { if (TEST(marlin_debug_flags, i)) { if (comma++) SERIAL_CHAR(','); serialprintPGM((char*)pgm_read_ptr(&debug_strings[i])); } } } else { SERIAL_ECHOPGM(MSG_DEBUG_OFF); #if !defined(__AVR__) || !defined(USBCON) #if ENABLED(SERIAL_STATS_RX_BUFFER_OVERRUNS) SERIAL_ECHOPAIR("\nBuffer Overruns: ", customizedSerial.buffer_overruns()); #endif #if ENABLED(SERIAL_STATS_RX_FRAMING_ERRORS) SERIAL_ECHOPAIR("\nFraming Errors: ", customizedSerial.framing_errors()); #endif #if ENABLED(SERIAL_STATS_DROPPED_RX) SERIAL_ECHOPAIR("\nDropped bytes: ", customizedSerial.dropped()); #endif #if ENABLED(SERIAL_STATS_MAX_RX_QUEUED) SERIAL_ECHOPAIR("\nMax RX Queue Size: ", customizedSerial.rxMaxEnqueued()); #endif #endif // !__AVR__ || !USBCON } SERIAL_EOL(); } #if ENABLED(HOST_KEEPALIVE_FEATURE) /** * M113: Get or set Host Keepalive interval (0 to disable) * * S<seconds> Optional. Set the keepalive interval. */ inline void gcode_M113() { if (parser.seenval('S')) { host_keepalive_interval = parser.value_byte(); NOMORE(host_keepalive_interval, 60); } else { SERIAL_ECHO_START(); SERIAL_ECHOLNPAIR("M113 S", (unsigned long)host_keepalive_interval); } } #endif #if ENABLED(BARICUDA) #if HAS_HEATER_1 /** * M126: Heater 1 valve open */ inline void gcode_M126() { baricuda_valve_pressure = parser.byteval('S', 255); } /** * M127: Heater 1 valve close */ inline void gcode_M127() { baricuda_valve_pressure = 0; } #endif #if HAS_HEATER_2 /** * M128: Heater 2 valve open */ inline void gcode_M128() { baricuda_e_to_p_pressure = parser.byteval('S', 255); } /** * M129: Heater 2 valve close */ inline void gcode_M129() { baricuda_e_to_p_pressure = 0; } #endif #endif // BARICUDA #if ENABLED(ULTIPANEL) /** * M145: Set the heatup state for a material in the LCD menu * * S<material> (0=PLA, 1=ABS) * H<hotend temp> * B<bed temp> * F<fan speed> */ inline void gcode_M145() { const uint8_t material = (uint8_t)parser.intval('S'); if (material >= COUNT(lcd_preheat_hotend_temp)) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX); } else { int v; if (parser.seenval('H')) { v = parser.value_int(); lcd_preheat_hotend_temp[material] = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15); } if (parser.seenval('F')) { v = parser.value_int(); lcd_preheat_fan_speed[material] = constrain(v, 0, 255); } #if TEMP_SENSOR_BED != 0 if (parser.seenval('B')) { v = parser.value_int(); lcd_preheat_bed_temp[material] = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15); } #endif } } #endif // ULTIPANEL #if ENABLED(TEMPERATURE_UNITS_SUPPORT) /** * M149: Set temperature units */ inline void gcode_M149() { if (parser.seenval('C')) parser.set_input_temp_units(TEMPUNIT_C); else if (parser.seenval('K')) parser.set_input_temp_units(TEMPUNIT_K); else if (parser.seenval('F')) parser.set_input_temp_units(TEMPUNIT_F); } #endif #if HAS_POWER_SWITCH /** * M80 : Turn on the Power Supply * M80 S : Report the current state and exit */ inline void gcode_M80() { // S: Report the current power supply state and exit if (parser.seen('S')) { serialprintPGM(powersupply_on ? PSTR("PS:1\n") : PSTR("PS:0\n")); return; } PSU_ON(); /** * If you have a switch on suicide pin, this is useful * if you want to start another print with suicide feature after * a print without suicide... */ #if HAS_SUICIDE OUT_WRITE(SUICIDE_PIN, HIGH); #endif #if DISABLED(AUTO_POWER_CONTROL) delay(100); // Wait for power to settle restore_stepper_drivers(); #endif #if ENABLED(ULTIPANEL) lcd_reset_status(); #endif #ifdef ANYCUBIC_TFT_MODEL AnycubicTFT.CommandScan(); #endif } #endif // HAS_POWER_SWITCH /** * M81: Turn off Power, including Power Supply, if there is one. * * This code should ALWAYS be available for EMERGENCY SHUTDOWN! */ inline void gcode_M81() { thermalManager.disable_all_heaters(); planner.finish_and_disable(); #if FAN_COUNT > 0 for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0; #if ENABLED(PROBING_FANS_OFF) fans_paused = false; ZERO(paused_fanSpeeds); #endif #endif safe_delay(1000); // Wait 1 second before switching off #if HAS_SUICIDE suicide(); #elif HAS_POWER_SWITCH PSU_OFF(); #endif #if ENABLED(ULTIPANEL) LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF "."); #endif #ifdef ANYCUBIC_TFT_MODEL AnycubicTFT.CommandScan(); #endif } /** * M82: Set E codes absolute (default) */ inline void gcode_M82() { axis_relative_modes[E_CART] = false; } /** * M83: Set E codes relative while in Absolute Coordinates (G90) mode */ inline void gcode_M83() { axis_relative_modes[E_CART] = true; } /** * M18, M84: Disable stepper motors */ inline void gcode_M18_M84() { if (parser.seenval('S')) { stepper_inactive_time = parser.value_millis_from_seconds(); } else { bool all_axis = !(parser.seen('X') || parser.seen('Y') || parser.seen('Z') || parser.seen('E')); if (all_axis) { planner.finish_and_disable(); } else { planner.synchronize(); if (parser.seen('X')) disable_X(); if (parser.seen('Y')) disable_Y(); if (parser.seen('Z')) disable_Z(); #if E0_ENABLE_PIN != X_ENABLE_PIN && E1_ENABLE_PIN != Y_ENABLE_PIN // Only disable on boards that have separate ENABLE_PINS if (parser.seen('E')) disable_e_steppers(); #endif } #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(ULTIPANEL) // Only needed with an LCD if (ubl.lcd_map_control) ubl.lcd_map_control = defer_return_to_status = false; #endif } } /** * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default) */ inline void gcode_M85() { if (parser.seen('S')) max_inactive_time = parser.value_millis_from_seconds(); } /** * Multi-stepper support for M92, M201, M203 */ #if ENABLED(DISTINCT_E_FACTORS) #define GET_TARGET_EXTRUDER(CMD) if (get_target_extruder_from_command(CMD)) return #define TARGET_EXTRUDER target_extruder #else #define GET_TARGET_EXTRUDER(CMD) NOOP #define TARGET_EXTRUDER 0 #endif /** * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E. * (for Hangprinter: A, B, C, D, and E) * (Follows the same syntax as G92) * * With multiple extruders use T to specify which one. */ inline void gcode_M92() { GET_TARGET_EXTRUDER(92); LOOP_NUM_AXIS(i) { if (parser.seen(RAW_AXIS_CODES(i))) { if (i == E_AXIS) { const float value = parser.value_per_axis_unit((AxisEnum)(E_AXIS + TARGET_EXTRUDER)); if (value < 20) { const float factor = planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] / value; // increase e constants if M92 E14 is given for netfab. #if DISABLED(JUNCTION_DEVIATION) planner.max_jerk[E_AXIS] *= factor; #endif planner.max_feedrate_mm_s[E_AXIS + TARGET_EXTRUDER] *= factor; planner.max_acceleration_steps_per_s2[E_AXIS + TARGET_EXTRUDER] *= factor; } planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] = value; } else { #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE) SERIAL_ECHOLNPGM("Warning: " "M92 A, B, C, and D only affect acceleration planning " "when BUILDUP_COMPENSATION_FEATURE is enabled."); #endif planner.axis_steps_per_mm[i] = parser.value_per_axis_unit((AxisEnum)i); } } } planner.refresh_positioning(); } /** * Output the current position to serial */ void report_current_position() { SERIAL_PROTOCOLPAIR("X:", LOGICAL_X_POSITION(current_position[X_AXIS])); SERIAL_PROTOCOLPAIR(" Y:", LOGICAL_Y_POSITION(current_position[Y_AXIS])); SERIAL_PROTOCOLPAIR(" Z:", LOGICAL_Z_POSITION(current_position[Z_AXIS])); SERIAL_PROTOCOLPAIR(" E:", current_position[E_CART]); #if ENABLED(HANGPRINTER) SERIAL_EOL(); SERIAL_PROTOCOLPAIR("A:", line_lengths[A_AXIS]); SERIAL_PROTOCOLPAIR(" B:", line_lengths[B_AXIS]); SERIAL_PROTOCOLPAIR(" C:", line_lengths[C_AXIS]); SERIAL_PROTOCOLLNPAIR(" D:", line_lengths[D_AXIS]); #endif stepper.report_positions(); #if IS_SCARA SERIAL_PROTOCOLPAIR("SCARA Theta:", planner.get_axis_position_degrees(A_AXIS)); SERIAL_PROTOCOLLNPAIR(" Psi+Theta:", planner.get_axis_position_degrees(B_AXIS)); SERIAL_EOL(); #endif } #ifdef M114_DETAIL void report_xyze(const float pos[], const uint8_t n = 4, const uint8_t precision = 3) { char str[12]; for (uint8_t i = 0; i < n; i++) { SERIAL_CHAR(' '); SERIAL_CHAR(axis_codes[i]); SERIAL_CHAR(':'); SERIAL_PROTOCOL(dtostrf(pos[i], 8, precision, str)); } SERIAL_EOL(); } inline void report_xyz(const float pos[]) { report_xyze(pos, 3); } void report_current_position_detail() { SERIAL_PROTOCOLPGM("\nLogical:"); const float logical[XYZ] = { LOGICAL_X_POSITION(current_position[X_AXIS]), LOGICAL_Y_POSITION(current_position[Y_AXIS]), LOGICAL_Z_POSITION(current_position[Z_AXIS]) }; report_xyz(logical); SERIAL_PROTOCOLPGM("Raw: "); report_xyz(current_position); float leveled[XYZ] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] }; #if PLANNER_LEVELING SERIAL_PROTOCOLPGM("Leveled:"); planner.apply_leveling(leveled); report_xyz(leveled); SERIAL_PROTOCOLPGM("UnLevel:"); float unleveled[XYZ] = { leveled[X_AXIS], leveled[Y_AXIS], leveled[Z_AXIS] }; planner.unapply_leveling(unleveled); report_xyz(unleveled); #endif #if IS_KINEMATIC #if IS_SCARA SERIAL_PROTOCOLPGM("ScaraK: "); #else SERIAL_PROTOCOLPGM("DeltaK: "); #endif inverse_kinematics(leveled); // writes delta[] report_xyz(delta); #endif planner.synchronize(); SERIAL_PROTOCOLPGM("Stepper:"); LOOP_NUM_AXIS(i) { SERIAL_CHAR(' '); SERIAL_CHAR(RAW_AXIS_CODES(i)); SERIAL_CHAR(':'); SERIAL_PROTOCOL(stepper.position((AxisEnum)i)); } SERIAL_EOL(); #if IS_SCARA const float deg[XYZ] = { planner.get_axis_position_degrees(A_AXIS), planner.get_axis_position_degrees(B_AXIS) }; SERIAL_PROTOCOLPGM("Degrees:"); report_xyze(deg, 2); #endif SERIAL_PROTOCOLPGM("FromStp:"); get_cartesian_from_steppers(); // writes cartes[XYZ] (with forward kinematics) const float from_steppers[XYZE] = { cartes[X_AXIS], cartes[Y_AXIS], cartes[Z_AXIS], planner.get_axis_position_mm(E_AXIS) }; report_xyze(from_steppers); const float diff[XYZE] = { from_steppers[X_AXIS] - leveled[X_AXIS], from_steppers[Y_AXIS] - leveled[Y_AXIS], from_steppers[Z_AXIS] - leveled[Z_AXIS], from_steppers[E_CART] - current_position[E_CART] }; SERIAL_PROTOCOLPGM("Differ: "); report_xyze(diff); } #endif // M114_DETAIL /** * M114: Report current position to host */ inline void gcode_M114() { #ifdef M114_DETAIL if (parser.seen('D')) return report_current_position_detail(); #endif planner.synchronize(); const uint16_t sval = parser.ushortval('S'); #if ENABLED(MECHADUINO_I2C_COMMANDS) if (sval == 1) return report_axis_position_from_encoder_data(); #endif if (sval == 2) return report_xyz_from_stepper_position(); report_current_position(); } /** * M115: Capabilities string */ #if ENABLED(EXTENDED_CAPABILITIES_REPORT) static void cap_line(const char * const name, bool ena=false) { SERIAL_PROTOCOLPGM("Cap:"); serialprintPGM(name); SERIAL_PROTOCOLPGM(":"); SERIAL_PROTOCOLLN(int(ena ? 1 : 0)); } #endif inline void gcode_M115() { SERIAL_PROTOCOLLNPGM(MSG_M115_REPORT); #if ENABLED(EXTENDED_CAPABILITIES_REPORT) // SERIAL_XON_XOFF cap_line(PSTR("SERIAL_XON_XOFF") #if ENABLED(SERIAL_XON_XOFF) , true #endif ); // EEPROM (M500, M501) cap_line(PSTR("EEPROM") #if ENABLED(EEPROM_SETTINGS) , true #endif ); // Volumetric Extrusion (M200) cap_line(PSTR("VOLUMETRIC") #if DISABLED(NO_VOLUMETRICS) , true #endif ); // AUTOREPORT_TEMP (M155) cap_line(PSTR("AUTOREPORT_TEMP") #if ENABLED(AUTO_REPORT_TEMPERATURES) , true #endif ); // PROGRESS (M530 S L, M531 <file>, M532 X L) cap_line(PSTR("PROGRESS")); // Print Job timer M75, M76, M77 cap_line(PSTR("PRINT_JOB"), true); // AUTOLEVEL (G29) cap_line(PSTR("AUTOLEVEL") #if HAS_AUTOLEVEL , true #endif ); // Z_PROBE (G30) cap_line(PSTR("Z_PROBE") #if HAS_BED_PROBE , true #endif ); // MESH_REPORT (M420 V) cap_line(PSTR("LEVELING_DATA") #if HAS_LEVELING , true #endif ); // BUILD_PERCENT (M73) cap_line(PSTR("BUILD_PERCENT") #if ENABLED(LCD_SET_PROGRESS_MANUALLY) , true #endif ); // SOFTWARE_POWER (M80, M81) cap_line(PSTR("SOFTWARE_POWER") #if HAS_POWER_SWITCH , true #endif ); // CASE LIGHTS (M355) cap_line(PSTR("TOGGLE_LIGHTS") #if HAS_CASE_LIGHT , true #endif ); cap_line(PSTR("CASE_LIGHT_BRIGHTNESS") #if HAS_CASE_LIGHT , USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN) #endif ); // EMERGENCY_PARSER (M108, M112, M410) cap_line(PSTR("EMERGENCY_PARSER") #if ENABLED(EMERGENCY_PARSER) , true #endif ); // AUTOREPORT_SD_STATUS (M27 extension) cap_line(PSTR("AUTOREPORT_SD_STATUS") #if ENABLED(AUTO_REPORT_SD_STATUS) , true #endif ); // THERMAL_PROTECTION cap_line(PSTR("THERMAL_PROTECTION") #if ENABLED(THERMAL_PROTECTION_HOTENDS) && ENABLED(THERMAL_PROTECTION_BED) , true #endif ); #endif // EXTENDED_CAPABILITIES_REPORT } /** * M117: Set LCD Status Message */ inline void gcode_M117() { if (parser.string_arg[0]) lcd_setstatus(parser.string_arg); else lcd_reset_status(); } /** * M118: Display a message in the host console. * * A1 Prepend '// ' for an action command, as in OctoPrint * E1 Have the host 'echo:' the text */ inline void gcode_M118() { bool hasE = false, hasA = false; char *p = parser.string_arg; for (uint8_t i = 2; i--;) if ((p[0] == 'A' || p[0] == 'E') && p[1] == '1') { if (p[0] == 'A') hasA = true; if (p[0] == 'E') hasE = true; p += 2; while (*p == ' ') ++p; } if (hasE) SERIAL_ECHO_START(); if (hasA) SERIAL_ECHOPGM("// "); SERIAL_ECHOLN(p); } /** * M119: Output endstop states to serial output */ inline void gcode_M119() { endstops.M119(); } /** * M120: Enable endstops and set non-homing endstop state to "enabled" */ inline void gcode_M120() { endstops.enable_globally(true); } /** * M121: Disable endstops and set non-homing endstop state to "disabled" */ inline void gcode_M121() { endstops.enable_globally(false); } #if ENABLED(PARK_HEAD_ON_PAUSE) /** * M125: Store current position and move to filament change position. * Called on pause (by M25) to prevent material leaking onto the * object. On resume (M24) the head will be moved back and the * print will resume. * * If Marlin is compiled without SD Card support, M125 can be * used directly to pause the print and move to park position, * resuming with a button click or M108. * * L = override retract length * X = override X * Y = override Y * Z = override Z raise */ inline void gcode_M125() { // Initial retract before move to filament change position const float retract = -ABS(parser.seen('L') ? parser.value_axis_units(E_AXIS) : 0 #ifdef PAUSE_PARK_RETRACT_LENGTH + (PAUSE_PARK_RETRACT_LENGTH) #endif ); point_t park_point = NOZZLE_PARK_POINT; // Move XY axes to filament change position or given position if (parser.seenval('X')) park_point.x = parser.linearval('X'); if (parser.seenval('Y')) park_point.y = parser.linearval('Y'); // Lift Z axis if (parser.seenval('Z')) park_point.z = parser.linearval('Z'); #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE) && DISABLED(DELTA) park_point.x += (active_extruder ? hotend_offset[X_AXIS][active_extruder] : 0); park_point.y += (active_extruder ? hotend_offset[Y_AXIS][active_extruder] : 0); #endif #if DISABLED(SDSUPPORT) const bool job_running = print_job_timer.isRunning(); #endif if (pause_print(retract, park_point)) { #if DISABLED(SDSUPPORT) // Wait for lcd click or M108 wait_for_filament_reload(); // Return to print position and continue resume_print(); if (job_running) print_job_timer.start(); #endif } } #endif // PARK_HEAD_ON_PAUSE #if HAS_COLOR_LEDS /** * M150: Set Status LED Color - Use R-U-B-W for R-G-B-W * and Brightness - Use P (for NEOPIXEL only) * * Always sets all 3 or 4 components. If a component is left out, set to 0. * If brightness is left out, no value changed * * Examples: * * M150 R255 ; Turn LED red * M150 R255 U127 ; Turn LED orange (PWM only) * M150 ; Turn LED off * M150 R U B ; Turn LED white * M150 W ; Turn LED white using a white LED * M150 P127 ; Set LED 50% brightness * M150 P ; Set LED full brightness */ inline void gcode_M150() { leds.set_color(MakeLEDColor( parser.seen('R') ? (parser.has_value() ? parser.value_byte() : 255) : 0, parser.seen('U') ? (parser.has_value() ? parser.value_byte() : 255) : 0, parser.seen('B') ? (parser.has_value() ? parser.value_byte() : 255) : 0, parser.seen('W') ? (parser.has_value() ? parser.value_byte() : 255) : 0, parser.seen('P') ? (parser.has_value() ? parser.value_byte() : 255) : pixels.getBrightness() )); } #endif // HAS_COLOR_LEDS #if DISABLED(NO_VOLUMETRICS) /** * M200: Set filament diameter and set E axis units to cubic units * * T<extruder> - Optional extruder number. Current extruder if omitted. * D<linear> - Diameter of the filament. Use "D0" to switch back to linear units on the E axis. */ inline void gcode_M200() { if (get_target_extruder_from_command(200)) return; if (parser.seen('D')) { // setting any extruder filament size disables volumetric on the assumption that // slicers either generate in extruder values as cubic mm or as as filament feeds // for all extruders if ( (parser.volumetric_enabled = (parser.value_linear_units() != 0)) ) planner.set_filament_size(target_extruder, parser.value_linear_units()); } planner.calculate_volumetric_multipliers(); } #endif // !NO_VOLUMETRICS /** * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000) * * With multiple extruders use T to specify which one. */ inline void gcode_M201() { GET_TARGET_EXTRUDER(201); LOOP_NUM_AXIS(i) { if (parser.seen(RAW_AXIS_CODES(i))) { const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0); planner.max_acceleration_mm_per_s2[a] = parser.value_axis_units((AxisEnum)a); } } // steps per sq second need to be updated to agree with the units per sq second (as they are what is used in the planner) planner.reset_acceleration_rates(); } #if 0 // Not used for Sprinter/grbl gen6 inline void gcode_M202() { LOOP_XYZE(i) { if (parser.seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = parser.value_axis_units((AxisEnum)i) * planner.axis_steps_per_mm[i]; } } #endif /** * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in units/sec * * With multiple extruders use T to specify which one. */ inline void gcode_M203() { GET_TARGET_EXTRUDER(203); LOOP_NUM_AXIS(i) if (parser.seen(RAW_AXIS_CODES(i))) { const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0); planner.max_feedrate_mm_s[a] = parser.value_axis_units((AxisEnum)a); } } /** * M204: Set Accelerations in units/sec^2 (M204 P1200 R3000 T3000) * * P = Printing moves * R = Retract only (no X, Y, Z) moves * T = Travel (non printing) moves */ inline void gcode_M204() { bool report = true; if (parser.seenval('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments. planner.travel_acceleration = planner.acceleration = parser.value_linear_units(); report = false; } if (parser.seenval('P')) { planner.acceleration = parser.value_linear_units(); report = false; } if (parser.seenval('R')) { planner.retract_acceleration = parser.value_linear_units(); report = false; } if (parser.seenval('T')) { planner.travel_acceleration = parser.value_linear_units(); report = false; } if (report) { SERIAL_ECHOPAIR("Acceleration: P", planner.acceleration); SERIAL_ECHOPAIR(" R", planner.retract_acceleration); SERIAL_ECHOLNPAIR(" T", planner.travel_acceleration); } } /** * M205: Set Advanced Settings * * Q = Min Segment Time (µs) * S = Min Feed Rate (units/s) * T = Min Travel Feed Rate (units/s) * X = Max X Jerk (units/sec^2) * Y = Max Y Jerk (units/sec^2) * Z = Max Z Jerk (units/sec^2) * E = Max E Jerk (units/sec^2) * J = Junction Deviation (mm) (Requires JUNCTION_DEVIATION) */ inline void gcode_M205() { if (parser.seen('Q')) planner.min_segment_time_us = parser.value_ulong(); if (parser.seen('S')) planner.min_feedrate_mm_s = parser.value_linear_units(); if (parser.seen('T')) planner.min_travel_feedrate_mm_s = parser.value_linear_units(); #if ENABLED(JUNCTION_DEVIATION) if (parser.seen('J')) { const float junc_dev = parser.value_linear_units(); if (WITHIN(junc_dev, 0.01f, 0.3f)) { planner.junction_deviation_mm = junc_dev; planner.recalculate_max_e_jerk(); } else { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM("?J out of range (0.01 to 0.3)"); } } #else #if ENABLED(HANGPRINTER) if (parser.seen('A')) planner.max_jerk[A_AXIS] = parser.value_linear_units(); if (parser.seen('B')) planner.max_jerk[B_AXIS] = parser.value_linear_units(); if (parser.seen('C')) planner.max_jerk[C_AXIS] = parser.value_linear_units(); if (parser.seen('D')) planner.max_jerk[D_AXIS] = parser.value_linear_units(); #else if (parser.seen('X')) planner.max_jerk[X_AXIS] = parser.value_linear_units(); if (parser.seen('Y')) planner.max_jerk[Y_AXIS] = parser.value_linear_units(); if (parser.seen('Z')) { planner.max_jerk[Z_AXIS] = parser.value_linear_units(); #if HAS_MESH if (planner.max_jerk[Z_AXIS] <= 0.1f) SERIAL_ECHOLNPGM("WARNING! Low Z Jerk may lead to unwanted pauses."); #endif } #endif if (parser.seen('E')) planner.max_jerk[E_AXIS] = parser.value_linear_units(); #endif } #if HAS_M206_COMMAND /** * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y * * *** @thinkyhead: I recommend deprecating M206 for SCARA in favor of M665. * *** M206 for SCARA will remain enabled in 1.1.x for compatibility. * *** In the next 1.2 release, it will simply be disabled by default. */ inline void gcode_M206() { LOOP_XYZ(i) if (parser.seen(axis_codes[i])) set_home_offset((AxisEnum)i, parser.value_linear_units()); #if ENABLED(MORGAN_SCARA) if (parser.seen('T')) set_home_offset(A_AXIS, parser.value_float()); // Theta if (parser.seen('P')) set_home_offset(B_AXIS, parser.value_float()); // Psi #endif report_current_position(); } #endif // HAS_M206_COMMAND #if ENABLED(DELTA) /** * M665: Set delta configurations * * H = delta height * L = diagonal rod * R = delta radius * S = segments per second * B = delta calibration radius * X = Alpha (Tower 1) angle trim * Y = Beta (Tower 2) angle trim * Z = Gamma (Tower 3) angle trim */ inline void gcode_M665() { if (parser.seen('H')) delta_height = parser.value_linear_units(); if (parser.seen('L')) delta_diagonal_rod = parser.value_linear_units(); if (parser.seen('R')) delta_radius = parser.value_linear_units(); if (parser.seen('S')) delta_segments_per_second = parser.value_float(); if (parser.seen('B')) delta_calibration_radius = parser.value_float(); if (parser.seen('X')) delta_tower_angle_trim[A_AXIS] = parser.value_float(); if (parser.seen('Y')) delta_tower_angle_trim[B_AXIS] = parser.value_float(); if (parser.seen('Z')) delta_tower_angle_trim[C_AXIS] = parser.value_float(); recalc_delta_settings(); } /** * M666: Set delta endstop adjustment */ inline void gcode_M666() { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOLNPGM(">>> gcode_M666"); } #endif LOOP_XYZ(i) { if (parser.seen(axis_codes[i])) { if (parser.value_linear_units() * Z_HOME_DIR <= 0) delta_endstop_adj[i] = parser.value_linear_units(); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("delta_endstop_adj[", axis_codes[i]); SERIAL_ECHOLNPAIR("] = ", delta_endstop_adj[i]); } #endif } } #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOLNPGM("<<< gcode_M666"); } #endif } #elif IS_SCARA /** * M665: Set SCARA settings * * Parameters: * * S[segments-per-second] - Segments-per-second * P[theta-psi-offset] - Theta-Psi offset, added to the shoulder (A/X) angle * T[theta-offset] - Theta offset, added to the elbow (B/Y) angle * * A, P, and X are all aliases for the shoulder angle * B, T, and Y are all aliases for the elbow angle */ inline void gcode_M665() { if (parser.seen('S')) delta_segments_per_second = parser.value_float(); const bool hasA = parser.seen('A'), hasP = parser.seen('P'), hasX = parser.seen('X'); const uint8_t sumAPX = hasA + hasP + hasX; if (sumAPX == 1) home_offset[A_AXIS] = parser.value_float(); else if (sumAPX > 1) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM("Only one of A, P, or X is allowed."); return; } const bool hasB = parser.seen('B'), hasT = parser.seen('T'), hasY = parser.seen('Y'); const uint8_t sumBTY = hasB + hasT + hasY; if (sumBTY == 1) home_offset[B_AXIS] = parser.value_float(); else if (sumBTY > 1) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM("Only one of B, T, or Y is allowed."); return; } } #elif ENABLED(HANGPRINTER) /** * M665: Set HANGPRINTER settings * * Parameters: * * W[anchor_A_y] - A-anchor's y coordinate (see note) * E[anchor_A_z] - A-anchor's z coordinate (see note) * R[anchor_B_x] - B-anchor's x coordinate (see note) * T[anchor_B_y] - B-anchor's y coordinate (see note) * Y[anchor_B_z] - B-anchor's z coordinate (see note) * U[anchor_C_x] - C-anchor's x coordinate (see note) * I[anchor_C_y] - C-anchor's y coordinate (see note) * O[anchor_C_z] - C-anchor's z coordinate (see note) * P[anchor_D_z] - D-anchor's z coordinate (see note) * S[segments-per-second] - Segments-per-second * * Note: All xyz coordinates are measured relative to the line's pivot point in the mover, * when it is at its home position (nozzle in (0,0,0), and lines tight). * The y-axis is defined to be horizontal right above/below the A-lines when mover is at home. * The z-axis is along the vertical direction. */ inline void gcode_M665() { if (parser.seen('W')) anchor_A_y = parser.value_float(); if (parser.seen('E')) anchor_A_z = parser.value_float(); if (parser.seen('R')) anchor_B_x = parser.value_float(); if (parser.seen('T')) anchor_B_y = parser.value_float(); if (parser.seen('Y')) anchor_B_z = parser.value_float(); if (parser.seen('U')) anchor_C_x = parser.value_float(); if (parser.seen('I')) anchor_C_y = parser.value_float(); if (parser.seen('O')) anchor_C_z = parser.value_float(); if (parser.seen('P')) anchor_D_z = parser.value_float(); if (parser.seen('S')) delta_segments_per_second = parser.value_float(); recalc_hangprinter_settings(); } #elif ENABLED(X_DUAL_ENDSTOPS) || ENABLED(Y_DUAL_ENDSTOPS) || ENABLED(Z_DUAL_ENDSTOPS) /** * M666: Set Dual Endstops offsets for X, Y, and/or Z. * With no parameters report current offsets. */ inline void gcode_M666() { bool report = true; #if ENABLED(X_DUAL_ENDSTOPS) if (parser.seenval('X')) { endstops.x_endstop_adj = parser.value_linear_units(); report = false; } #endif #if ENABLED(Y_DUAL_ENDSTOPS) if (parser.seenval('Y')) { endstops.y_endstop_adj = parser.value_linear_units(); report = false; } #endif #if ENABLED(Z_DUAL_ENDSTOPS) if (parser.seenval('Z')) { endstops.z_endstop_adj = parser.value_linear_units(); report = false; } #endif if (report) { SERIAL_ECHOPGM("Dual Endstop Adjustment (mm): "); #if ENABLED(X_DUAL_ENDSTOPS) SERIAL_ECHOPAIR(" X", endstops.x_endstop_adj); #endif #if ENABLED(Y_DUAL_ENDSTOPS) SERIAL_ECHOPAIR(" Y", endstops.y_endstop_adj); #endif #if ENABLED(Z_DUAL_ENDSTOPS) SERIAL_ECHOPAIR(" Z", endstops.z_endstop_adj); #endif SERIAL_EOL(); } } #endif // X_DUAL_ENDSTOPS || Y_DUAL_ENDSTOPS || Z_DUAL_ENDSTOPS #if ENABLED(FWRETRACT) /** * M207: Set firmware retraction values * * S[+units] retract_length * W[+units] swap_retract_length (multi-extruder) * F[units/min] retract_feedrate_mm_s * Z[units] retract_zlift */ inline void gcode_M207() { if (parser.seen('S')) fwretract.retract_length = parser.value_axis_units(E_AXIS); if (parser.seen('F')) fwretract.retract_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS)); if (parser.seen('Z')) fwretract.retract_zlift = parser.value_linear_units(); if (parser.seen('W')) fwretract.swap_retract_length = parser.value_axis_units(E_AXIS); } /** * M208: Set firmware un-retraction values * * S[+units] retract_recover_length (in addition to M207 S*) * W[+units] swap_retract_recover_length (multi-extruder) * F[units/min] retract_recover_feedrate_mm_s * R[units/min] swap_retract_recover_feedrate_mm_s */ inline void gcode_M208() { if (parser.seen('S')) fwretract.retract_recover_length = parser.value_axis_units(E_AXIS); if (parser.seen('F')) fwretract.retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS)); if (parser.seen('R')) fwretract.swap_retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS)); if (parser.seen('W')) fwretract.swap_retract_recover_length = parser.value_axis_units(E_AXIS); } /** * M209: Enable automatic retract (M209 S1) * For slicers that don't support G10/11, reversed extrude-only * moves will be classified as retraction. */ inline void gcode_M209() { if (MIN_AUTORETRACT <= MAX_AUTORETRACT) { if (parser.seen('S')) { fwretract.autoretract_enabled = parser.value_bool(); for (uint8_t i = 0; i < EXTRUDERS; i++) fwretract.retracted[i] = false; } } } #endif // FWRETRACT /** * M211: Enable, Disable, and/or Report software endstops * * Usage: M211 S1 to enable, M211 S0 to disable, M211 alone for report */ inline void gcode_M211() { SERIAL_ECHO_START(); #if HAS_SOFTWARE_ENDSTOPS if (parser.seen('S')) soft_endstops_enabled = parser.value_bool(); SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS); serialprintPGM(soft_endstops_enabled ? PSTR(MSG_ON) : PSTR(MSG_OFF)); #else SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS); SERIAL_ECHOPGM(MSG_OFF); #endif SERIAL_ECHOPGM(MSG_SOFT_MIN); SERIAL_ECHOPAIR( MSG_X, LOGICAL_X_POSITION(soft_endstop_min[X_AXIS])); SERIAL_ECHOPAIR(" " MSG_Y, LOGICAL_Y_POSITION(soft_endstop_min[Y_AXIS])); SERIAL_ECHOPAIR(" " MSG_Z, LOGICAL_Z_POSITION(soft_endstop_min[Z_AXIS])); SERIAL_ECHOPGM(MSG_SOFT_MAX); SERIAL_ECHOPAIR( MSG_X, LOGICAL_X_POSITION(soft_endstop_max[X_AXIS])); SERIAL_ECHOPAIR(" " MSG_Y, LOGICAL_Y_POSITION(soft_endstop_max[Y_AXIS])); SERIAL_ECHOLNPAIR(" " MSG_Z, LOGICAL_Z_POSITION(soft_endstop_max[Z_AXIS])); } #if HOTENDS > 1 /** * M218 - Set/get hotend offset (in linear units) * * T<tool> * X<xoffset> * Y<yoffset> * Z<zoffset> - Available with DUAL_X_CARRIAGE, SWITCHING_NOZZLE, and PARKING_EXTRUDER */ inline void gcode_M218() { if (get_target_extruder_from_command(218) || target_extruder == 0) return; bool report = true; if (parser.seenval('X')) { hotend_offset[X_AXIS][target_extruder] = parser.value_linear_units(); report = false; } if (parser.seenval('Y')) { hotend_offset[Y_AXIS][target_extruder] = parser.value_linear_units(); report = false; } #if HAS_HOTEND_OFFSET_Z if (parser.seenval('Z')) { hotend_offset[Z_AXIS][target_extruder] = parser.value_linear_units(); report = false; } #endif if (report) { SERIAL_ECHO_START(); SERIAL_ECHOPGM(MSG_HOTEND_OFFSET); HOTEND_LOOP() { SERIAL_CHAR(' '); SERIAL_ECHO(hotend_offset[X_AXIS][e]); SERIAL_CHAR(','); SERIAL_ECHO(hotend_offset[Y_AXIS][e]); #if HAS_HOTEND_OFFSET_Z SERIAL_CHAR(','); SERIAL_ECHO(hotend_offset[Z_AXIS][e]); #endif } SERIAL_EOL(); } #if ENABLED(DELTA) if (target_extruder == active_extruder) do_blocking_move_to_xy(current_position[X_AXIS], current_position[Y_AXIS], planner.max_feedrate_mm_s[X_AXIS]); #endif } #endif // HOTENDS > 1 /** * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95) */ inline void gcode_M220() { if (parser.seenval('S')) feedrate_percentage = parser.value_int(); } /** * M221: Set extrusion percentage (M221 T0 S95) */ inline void gcode_M221() { if (get_target_extruder_from_command(221)) return; if (parser.seenval('S')) { planner.flow_percentage[target_extruder] = parser.value_int(); planner.refresh_e_factor(target_extruder); } else { SERIAL_ECHO_START(); SERIAL_CHAR('E'); SERIAL_CHAR('0' + target_extruder); SERIAL_ECHOPAIR(" Flow: ", planner.flow_percentage[target_extruder]); SERIAL_CHAR('%'); SERIAL_EOL(); } } /** * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>) */ inline void gcode_M226() { if (parser.seen('P')) { const int pin = parser.value_int(), pin_state = parser.intval('S', -1); if (WITHIN(pin_state, -1, 1) && pin > -1) { if (pin_is_protected(pin)) protected_pin_err(); else { int target = LOW; planner.synchronize(); pinMode(pin, INPUT); switch (pin_state) { case 1: target = HIGH; break; case 0: target = LOW; break; case -1: target = !digitalRead(pin); break; } while (digitalRead(pin) != target) idle(); } } // pin_state -1 0 1 && pin > -1 } // parser.seen('P') } #if ENABLED(EXPERIMENTAL_I2CBUS) /** * M260: Send data to a I2C slave device * * This is a PoC, the formating and arguments for the GCODE will * change to be more compatible, the current proposal is: * * M260 A<slave device address base 10> ; Sets the I2C slave address the data will be sent to * * M260 B<byte-1 value in base 10> * M260 B<byte-2 value in base 10> * M260 B<byte-3 value in base 10> * * M260 S1 ; Send the buffered data and reset the buffer * M260 R1 ; Reset the buffer without sending data * */ inline void gcode_M260() { // Set the target address if (parser.seen('A')) i2c.address(parser.value_byte()); // Add a new byte to the buffer if (parser.seen('B')) i2c.addbyte(parser.value_byte()); // Flush the buffer to the bus if (parser.seen('S')) i2c.send(); // Reset and rewind the buffer else if (parser.seen('R')) i2c.reset(); } /** * M261: Request X bytes from I2C slave device * * Usage: M261 A<slave device address base 10> B<number of bytes> */ inline void gcode_M261() { if (parser.seen('A')) i2c.address(parser.value_byte()); uint8_t bytes = parser.byteval('B', 1); if (i2c.addr && bytes && bytes <= TWIBUS_BUFFER_SIZE) { i2c.relay(bytes); } else { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM("Bad i2c request"); } } #endif // EXPERIMENTAL_I2CBUS #if HAS_SERVOS /** * M280: Get or set servo position. P<index> [S<angle>] */ inline void gcode_M280() { if (!parser.seen('P')) return; const int servo_index = parser.value_int(); if (WITHIN(servo_index, 0, NUM_SERVOS - 1)) { if (parser.seen('S')) MOVE_SERVO(servo_index, parser.value_int()); else { SERIAL_ECHO_START(); SERIAL_ECHOPAIR(" Servo ", servo_index); SERIAL_ECHOLNPAIR(": ", servo[servo_index].read()); } } else { SERIAL_ERROR_START(); SERIAL_ECHOPAIR("Servo ", servo_index); SERIAL_ECHOLNPGM(" out of range"); } } #endif // HAS_SERVOS #if ENABLED(BABYSTEPPING) #if ENABLED(BABYSTEP_ZPROBE_OFFSET) FORCE_INLINE void mod_zprobe_zoffset(const float &offs) { zprobe_zoffset += offs; SERIAL_ECHO_START(); SERIAL_ECHOLNPAIR(MSG_PROBE_Z_OFFSET ": ", zprobe_zoffset); } #endif /** * M290: Babystepping */ inline void gcode_M290() { #if ENABLED(BABYSTEP_XY) for (uint8_t a = X_AXIS; a <= Z_AXIS; a++) if (parser.seenval(axis_codes[a]) || (a == Z_AXIS && parser.seenval('S'))) { const float offs = constrain(parser.value_axis_units((AxisEnum)a), -2, 2); thermalManager.babystep_axis((AxisEnum)a, offs * planner.axis_steps_per_mm[a]); #if ENABLED(BABYSTEP_ZPROBE_OFFSET) if (a == Z_AXIS && (!parser.seen('P') || parser.value_bool())) mod_zprobe_zoffset(offs); #endif } #else if (parser.seenval('Z') || parser.seenval('S')) { const float offs = constrain(parser.value_axis_units(Z_AXIS), -2, 2); thermalManager.babystep_axis(Z_AXIS, offs * planner.axis_steps_per_mm[Z_AXIS]); #if ENABLED(BABYSTEP_ZPROBE_OFFSET) if (!parser.seen('P') || parser.value_bool()) mod_zprobe_zoffset(offs); #endif } #endif } #endif // BABYSTEPPING #if HAS_BUZZER /** * M300: Play beep sound S<frequency Hz> P<duration ms> */ inline void gcode_M300() { uint16_t const frequency = parser.ushortval('S', 260); uint16_t duration = parser.ushortval('P', 1000); // Limits the tone duration to 0-5 seconds. NOMORE(duration, 5000); BUZZ(duration, frequency); } #endif // HAS_BUZZER #if ENABLED(PIDTEMP) /** * M301: Set PID parameters P I D (and optionally C, L) * * P[float] Kp term * I[float] Ki term (unscaled) * D[float] Kd term (unscaled) * * With PID_EXTRUSION_SCALING: * * C[float] Kc term * L[int] LPQ length */ inline void gcode_M301() { // multi-extruder PID patch: M301 updates or prints a single extruder's PID values // default behaviour (omitting E parameter) is to update for extruder 0 only const uint8_t e = parser.byteval('E'); // extruder being updated if (e < HOTENDS) { // catch bad input value if (parser.seen('P')) PID_PARAM(Kp, e) = parser.value_float(); if (parser.seen('I')) PID_PARAM(Ki, e) = scalePID_i(parser.value_float()); if (parser.seen('D')) PID_PARAM(Kd, e) = scalePID_d(parser.value_float()); #if ENABLED(PID_EXTRUSION_SCALING) if (parser.seen('C')) PID_PARAM(Kc, e) = parser.value_float(); if (parser.seen('L')) thermalManager.lpq_len = parser.value_float(); NOMORE(thermalManager.lpq_len, LPQ_MAX_LEN); NOLESS(thermalManager.lpq_len, 0); #endif thermalManager.update_pid(); SERIAL_ECHO_START(); #if ENABLED(PID_PARAMS_PER_HOTEND) SERIAL_ECHOPAIR(" e:", e); // specify extruder in serial output #endif // PID_PARAMS_PER_HOTEND SERIAL_ECHOPAIR(" p:", PID_PARAM(Kp, e)); SERIAL_ECHOPAIR(" i:", unscalePID_i(PID_PARAM(Ki, e))); SERIAL_ECHOPAIR(" d:", unscalePID_d(PID_PARAM(Kd, e))); #if ENABLED(PID_EXTRUSION_SCALING) //Kc does not have scaling applied above, or in resetting defaults SERIAL_ECHOPAIR(" c:", PID_PARAM(Kc, e)); #endif SERIAL_EOL(); } else { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_INVALID_EXTRUDER); } } #endif // PIDTEMP #if ENABLED(PIDTEMPBED) inline void gcode_M304() { if (parser.seen('P')) thermalManager.bedKp = parser.value_float(); if (parser.seen('I')) thermalManager.bedKi = scalePID_i(parser.value_float()); if (parser.seen('D')) thermalManager.bedKd = scalePID_d(parser.value_float()); SERIAL_ECHO_START(); SERIAL_ECHOPAIR(" p:", thermalManager.bedKp); SERIAL_ECHOPAIR(" i:", unscalePID_i(thermalManager.bedKi)); SERIAL_ECHOLNPAIR(" d:", unscalePID_d(thermalManager.bedKd)); } #endif // PIDTEMPBED #if defined(CHDK) || HAS_PHOTOGRAPH /** * M240: Trigger a camera by emulating a Canon RC-1 * See http://www.doc-diy.net/photo/rc-1_hacked/ */ inline void gcode_M240() { #ifdef CHDK OUT_WRITE(CHDK, HIGH); chdkHigh = millis(); chdkActive = true; #elif HAS_PHOTOGRAPH const uint8_t NUM_PULSES = 16; const float PULSE_LENGTH = 0.01524; for (int i = 0; i < NUM_PULSES; i++) { WRITE(PHOTOGRAPH_PIN, HIGH); _delay_ms(PULSE_LENGTH); WRITE(PHOTOGRAPH_PIN, LOW); _delay_ms(PULSE_LENGTH); } delay(7.33); for (int i = 0; i < NUM_PULSES; i++) { WRITE(PHOTOGRAPH_PIN, HIGH); _delay_ms(PULSE_LENGTH); WRITE(PHOTOGRAPH_PIN, LOW); _delay_ms(PULSE_LENGTH); } #endif // !CHDK && HAS_PHOTOGRAPH } #endif // CHDK || PHOTOGRAPH_PIN #if HAS_LCD_CONTRAST /** * M250: Read and optionally set the LCD contrast */ inline void gcode_M250() { if (parser.seen('C')) set_lcd_contrast(parser.value_int()); SERIAL_PROTOCOLPGM("lcd contrast value: "); SERIAL_PROTOCOL(lcd_contrast); SERIAL_EOL(); } #endif // HAS_LCD_CONTRAST #if ENABLED(PREVENT_COLD_EXTRUSION) /** * M302: Allow cold extrudes, or set the minimum extrude temperature * * S<temperature> sets the minimum extrude temperature * P<bool> enables (1) or disables (0) cold extrusion * * Examples: * * M302 ; report current cold extrusion state * M302 P0 ; enable cold extrusion checking * M302 P1 ; disables cold extrusion checking * M302 S0 ; always allow extrusion (disables checking) * M302 S170 ; only allow extrusion above 170 * M302 S170 P1 ; set min extrude temp to 170 but leave disabled */ inline void gcode_M302() { const bool seen_S = parser.seen('S'); if (seen_S) { thermalManager.extrude_min_temp = parser.value_celsius(); thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0); } if (parser.seen('P')) thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0) || parser.value_bool(); else if (!seen_S) { // Report current state SERIAL_ECHO_START(); SERIAL_ECHOPAIR("Cold extrudes are ", (thermalManager.allow_cold_extrude ? "en" : "dis")); SERIAL_ECHOPAIR("abled (min temp ", thermalManager.extrude_min_temp); SERIAL_ECHOLNPGM("C)"); } } #endif // PREVENT_COLD_EXTRUSION /** * M303: PID relay autotune * * S<temperature> sets the target temperature. (default 150C / 70C) * E<extruder> (-1 for the bed) (default 0) * C<cycles> * U<bool> with a non-zero value will apply the result to current settings */ inline void gcode_M303() { #if HAS_PID_HEATING const int e = parser.intval('E'), c = parser.intval('C', 5); const bool u = parser.boolval('U'); int16_t temp = parser.celsiusval('S', e < 0 ? 70 : 150); if (WITHIN(e, 0, HOTENDS - 1)) target_extruder = e; #if DISABLED(BUSY_WHILE_HEATING) KEEPALIVE_STATE(NOT_BUSY); #endif thermalManager.pid_autotune(temp, e, c, u); #if DISABLED(BUSY_WHILE_HEATING) KEEPALIVE_STATE(IN_HANDLER); #endif #else SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_M303_DISABLED); #endif } #if ENABLED(MORGAN_SCARA) bool SCARA_move_to_cal(const uint8_t delta_a, const uint8_t delta_b) { if (IsRunning()) { forward_kinematics_SCARA(delta_a, delta_b); destination[X_AXIS] = cartes[X_AXIS]; destination[Y_AXIS] = cartes[Y_AXIS]; destination[Z_AXIS] = current_position[Z_AXIS]; prepare_move_to_destination(); return true; } return false; } /** * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration) */ inline bool gcode_M360() { SERIAL_ECHOLNPGM(" Cal: Theta 0"); return SCARA_move_to_cal(0, 120); } /** * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree) */ inline bool gcode_M361() { SERIAL_ECHOLNPGM(" Cal: Theta 90"); return SCARA_move_to_cal(90, 130); } /** * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration) */ inline bool gcode_M362() { SERIAL_ECHOLNPGM(" Cal: Psi 0"); return SCARA_move_to_cal(60, 180); } /** * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree) */ inline bool gcode_M363() { SERIAL_ECHOLNPGM(" Cal: Psi 90"); return SCARA_move_to_cal(50, 90); } /** * M364: SCARA calibration: Move to cal-position PsiC (90 deg to Theta calibration position) */ inline bool gcode_M364() { SERIAL_ECHOLNPGM(" Cal: Theta-Psi 90"); return SCARA_move_to_cal(45, 135); } #endif // SCARA #if ENABLED(EXT_SOLENOID) void enable_solenoid(const uint8_t num) { switch (num) { case 0: OUT_WRITE(SOL0_PIN, HIGH); break; #if HAS_SOLENOID_1 && EXTRUDERS > 1 case 1: OUT_WRITE(SOL1_PIN, HIGH); break; #endif #if HAS_SOLENOID_2 && EXTRUDERS > 2 case 2: OUT_WRITE(SOL2_PIN, HIGH); break; #endif #if HAS_SOLENOID_3 && EXTRUDERS > 3 case 3: OUT_WRITE(SOL3_PIN, HIGH); break; #endif #if HAS_SOLENOID_4 && EXTRUDERS > 4 case 4: OUT_WRITE(SOL4_PIN, HIGH); break; #endif default: SERIAL_ECHO_START(); SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID); break; } } void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); } void disable_all_solenoids() { OUT_WRITE(SOL0_PIN, LOW); #if HAS_SOLENOID_1 && EXTRUDERS > 1 OUT_WRITE(SOL1_PIN, LOW); #endif #if HAS_SOLENOID_2 && EXTRUDERS > 2 OUT_WRITE(SOL2_PIN, LOW); #endif #if HAS_SOLENOID_3 && EXTRUDERS > 3 OUT_WRITE(SOL3_PIN, LOW); #endif #if HAS_SOLENOID_4 && EXTRUDERS > 4 OUT_WRITE(SOL4_PIN, LOW); #endif } /** * M380: Enable solenoid on the active extruder */ inline void gcode_M380() { enable_solenoid_on_active_extruder(); } /** * M381: Disable all solenoids */ inline void gcode_M381() { disable_all_solenoids(); } #endif // EXT_SOLENOID /** * M400: Finish all moves */ inline void gcode_M400() { planner.synchronize(); } #if HAS_BED_PROBE /** * M401: Deploy and activate the Z probe */ inline void gcode_M401() { DEPLOY_PROBE(); report_current_position(); } /** * M402: Deactivate and stow the Z probe */ inline void gcode_M402() { STOW_PROBE(); #ifdef Z_AFTER_PROBING move_z_after_probing(); #endif report_current_position(); } #endif // HAS_BED_PROBE #if ENABLED(FILAMENT_WIDTH_SENSOR) /** * M404: Display or set (in current units) the nominal filament width (3mm, 1.75mm ) W<3.0> */ inline void gcode_M404() { if (parser.seen('W')) { filament_width_nominal = parser.value_linear_units(); planner.volumetric_area_nominal = CIRCLE_AREA(filament_width_nominal * 0.5); } else { SERIAL_PROTOCOLPGM("Filament dia (nominal mm):"); SERIAL_PROTOCOLLN(filament_width_nominal); } } /** * M405: Turn on filament sensor for control */ inline void gcode_M405() { // This is technically a linear measurement, but since it's quantized to centimeters and is a different // unit than everything else, it uses parser.value_byte() instead of parser.value_linear_units(). if (parser.seen('D')) { meas_delay_cm = parser.value_byte(); NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY); } if (filwidth_delay_index[1] == -1) { // Initialize the ring buffer if not done since startup const int8_t temp_ratio = thermalManager.widthFil_to_size_ratio(); for (uint8_t i = 0; i < COUNT(measurement_delay); ++i) measurement_delay[i] = temp_ratio; filwidth_delay_index[0] = filwidth_delay_index[1] = 0; } filament_sensor = true; } /** * M406: Turn off filament sensor for control */ inline void gcode_M406() { filament_sensor = false; planner.calculate_volumetric_multipliers(); // Restore correct 'volumetric_multiplier' value } /** * M407: Get measured filament diameter on serial output */ inline void gcode_M407() { SERIAL_PROTOCOLPGM("Filament dia (measured mm):"); SERIAL_PROTOCOLLN(filament_width_meas); } #endif // FILAMENT_WIDTH_SENSOR void quickstop_stepper() { planner.quick_stop(); planner.synchronize(); set_current_from_steppers_for_axis(ALL_AXES); SYNC_PLAN_POSITION_KINEMATIC(); } #if HAS_LEVELING //#define M420_C_USE_MEAN /** * M420: Enable/Disable Bed Leveling and/or set the Z fade height. * * S[bool] Turns leveling on or off * Z[height] Sets the Z fade height (0 or none to disable) * V[bool] Verbose - Print the leveling grid * * With AUTO_BED_LEVELING_UBL only: * * L[index] Load UBL mesh from index (0 is default) * T[map] 0:Human-readable 1:CSV 2:"LCD" 4:Compact * * With mesh-based leveling only: * * C Center mesh on the mean of the lowest and highest */ inline void gcode_M420() { const bool seen_S = parser.seen('S'); bool to_enable = seen_S ? parser.value_bool() : planner.leveling_active; // If disabling leveling do it right away // (Don't disable for just M420 or M420 V) if (seen_S && !to_enable) set_bed_leveling_enabled(false); const float oldpos[] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] }; #if ENABLED(AUTO_BED_LEVELING_UBL) // L to load a mesh from the EEPROM if (parser.seen('L')) { set_bed_leveling_enabled(false); #if ENABLED(EEPROM_SETTINGS) const int8_t storage_slot = parser.has_value() ? parser.value_int() : ubl.storage_slot; const int16_t a = settings.calc_num_meshes(); if (!a) { SERIAL_PROTOCOLLNPGM("?EEPROM storage not available."); return; } if (!WITHIN(storage_slot, 0, a - 1)) { SERIAL_PROTOCOLLNPGM("?Invalid storage slot."); SERIAL_PROTOCOLLNPAIR("?Use 0 to ", a - 1); return; } settings.load_mesh(storage_slot); ubl.storage_slot = storage_slot; #else SERIAL_PROTOCOLLNPGM("?EEPROM storage not available."); return; #endif } // L or V display the map info if (parser.seen('L') || parser.seen('V')) { ubl.display_map(parser.byteval('T')); SERIAL_ECHOPGM("Mesh is "); if (!ubl.mesh_is_valid()) SERIAL_ECHOPGM("in"); SERIAL_ECHOLNPAIR("valid\nStorage slot: ", ubl.storage_slot); } #endif // AUTO_BED_LEVELING_UBL #if HAS_MESH #if ENABLED(MESH_BED_LEVELING) #define Z_VALUES(X,Y) mbl.z_values[X][Y] #else #define Z_VALUES(X,Y) z_values[X][Y] #endif // Subtract the given value or the mean from all mesh values if (leveling_is_valid() && parser.seen('C')) { const float cval = parser.value_float(); #if ENABLED(AUTO_BED_LEVELING_UBL) set_bed_leveling_enabled(false); ubl.adjust_mesh_to_mean(true, cval); #else #if ENABLED(M420_C_USE_MEAN) // Get the sum and average of all mesh values float mesh_sum = 0; for (uint8_t x = GRID_MAX_POINTS_X; x--;) for (uint8_t y = GRID_MAX_POINTS_Y; y--;) mesh_sum += Z_VALUES(x, y); const float zmean = mesh_sum / float(GRID_MAX_POINTS); #else // Find the low and high mesh values float lo_val = 100, hi_val = -100; for (uint8_t x = GRID_MAX_POINTS_X; x--;) for (uint8_t y = GRID_MAX_POINTS_Y; y--;) { const float z = Z_VALUES(x, y); NOMORE(lo_val, z); NOLESS(hi_val, z); } // Take the mean of the lowest and highest const float zmean = (lo_val + hi_val) / 2.0 + cval; #endif // If not very close to 0, adjust the mesh if (!NEAR_ZERO(zmean)) { set_bed_leveling_enabled(false); // Subtract the mean from all values for (uint8_t x = GRID_MAX_POINTS_X; x--;) for (uint8_t y = GRID_MAX_POINTS_Y; y--;) Z_VALUES(x, y) -= zmean; #if ENABLED(ABL_BILINEAR_SUBDIVISION) bed_level_virt_interpolate(); #endif } #endif } #endif // HAS_MESH // V to print the matrix or mesh if (parser.seen('V')) { #if ABL_PLANAR planner.bed_level_matrix.debug(PSTR("Bed Level Correction Matrix:")); #else if (leveling_is_valid()) { #if ENABLED(AUTO_BED_LEVELING_BILINEAR) print_bilinear_leveling_grid(); #if ENABLED(ABL_BILINEAR_SUBDIVISION) print_bilinear_leveling_grid_virt(); #endif #elif ENABLED(MESH_BED_LEVELING) SERIAL_ECHOLNPGM("Mesh Bed Level data:"); mbl.report_mesh(); #endif } #endif } #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) if (parser.seen('Z')) set_z_fade_height(parser.value_linear_units(), false); #endif // Enable leveling if specified, or if previously active set_bed_leveling_enabled(to_enable); // Error if leveling failed to enable or reenable if (to_enable && !planner.leveling_active) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_M420_FAILED); } SERIAL_ECHO_START(); SERIAL_ECHOLNPAIR("Bed Leveling ", planner.leveling_active ? MSG_ON : MSG_OFF); #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) SERIAL_ECHO_START(); SERIAL_ECHOPGM("Fade Height "); if (planner.z_fade_height > 0.0) SERIAL_ECHOLN(planner.z_fade_height); else SERIAL_ECHOLNPGM(MSG_OFF); #endif // Report change in position if (memcmp(oldpos, current_position, sizeof(oldpos))) report_current_position(); } #endif // HAS_LEVELING #if ENABLED(MESH_BED_LEVELING) /** * M421: Set a single Mesh Bed Leveling Z coordinate * * Usage: * M421 X<linear> Y<linear> Z<linear> * M421 X<linear> Y<linear> Q<offset> * M421 I<xindex> J<yindex> Z<linear> * M421 I<xindex> J<yindex> Q<offset> */ inline void gcode_M421() { const bool hasX = parser.seen('X'), hasI = parser.seen('I'); const int8_t ix = hasI ? parser.value_int() : hasX ? mbl.probe_index_x(parser.value_linear_units()) : -1; const bool hasY = parser.seen('Y'), hasJ = parser.seen('J'); const int8_t iy = hasJ ? parser.value_int() : hasY ? mbl.probe_index_y(parser.value_linear_units()) : -1; const bool hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q'); if (int(hasI && hasJ) + int(hasX && hasY) != 1 || !(hasZ || hasQ)) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS); } else if (ix < 0 || iy < 0) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY); } else mbl.set_z(ix, iy, parser.value_linear_units() + (hasQ ? mbl.z_values[ix][iy] : 0)); } #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) /** * M421: Set a single Mesh Bed Leveling Z coordinate * * Usage: * M421 I<xindex> J<yindex> Z<linear> * M421 I<xindex> J<yindex> Q<offset> */ inline void gcode_M421() { int8_t ix = parser.intval('I', -1), iy = parser.intval('J', -1); const bool hasI = ix >= 0, hasJ = iy >= 0, hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q'); if (!hasI || !hasJ || !(hasZ || hasQ)) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS); } else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY); } else { z_values[ix][iy] = parser.value_linear_units() + (hasQ ? z_values[ix][iy] : 0); #if ENABLED(ABL_BILINEAR_SUBDIVISION) bed_level_virt_interpolate(); #endif } } #elif ENABLED(AUTO_BED_LEVELING_UBL) /** * M421: Set a single Mesh Bed Leveling Z coordinate * * Usage: * M421 I<xindex> J<yindex> Z<linear> * M421 I<xindex> J<yindex> Q<offset> * M421 I<xindex> J<yindex> N * M421 C Z<linear> * M421 C Q<offset> */ inline void gcode_M421() { int8_t ix = parser.intval('I', -1), iy = parser.intval('J', -1); const bool hasI = ix >= 0, hasJ = iy >= 0, hasC = parser.seen('C'), hasN = parser.seen('N'), hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q'); if (hasC) { const mesh_index_pair location = ubl.find_closest_mesh_point_of_type(REAL, current_position[X_AXIS], current_position[Y_AXIS], USE_NOZZLE_AS_REFERENCE, NULL); ix = location.x_index; iy = location.y_index; } if (int(hasC) + int(hasI && hasJ) != 1 || !(hasZ || hasQ || hasN)) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS); } else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY); } else ubl.z_values[ix][iy] = hasN ? NAN : parser.value_linear_units() + (hasQ ? ubl.z_values[ix][iy] : 0); } #endif // AUTO_BED_LEVELING_UBL #if HAS_M206_COMMAND /** * M428: Set home_offset based on the distance between the * current_position and the nearest "reference point." * If an axis is past center its endstop position * is the reference-point. Otherwise it uses 0. This allows * the Z offset to be set near the bed when using a max endstop. * * M428 can't be used more than 2cm away from 0 or an endstop. * * Use M206 to set these values directly. */ inline void gcode_M428() { if (axis_unhomed_error()) return; float diff[XYZ]; LOOP_XYZ(i) { diff[i] = base_home_pos((AxisEnum)i) - current_position[i]; if (!WITHIN(diff[i], -20, 20) && home_dir((AxisEnum)i) > 0) diff[i] = -current_position[i]; if (!WITHIN(diff[i], -20, 20)) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR); LCD_ALERTMESSAGEPGM("Err: Too far!"); BUZZ(200, 40); return; } } LOOP_XYZ(i) set_home_offset((AxisEnum)i, diff[i]); report_current_position(); LCD_MESSAGEPGM(MSG_HOME_OFFSETS_APPLIED); BUZZ(100, 659); BUZZ(100, 698); } #endif // HAS_M206_COMMAND /** * M500: Store settings in EEPROM */ inline void gcode_M500() { (void)settings.save(); } /** * M501: Read settings from EEPROM */ inline void gcode_M501() { (void)settings.load(); } /** * M502: Revert to default settings */ inline void gcode_M502() { (void)settings.reset(); } #if DISABLED(DISABLE_M503) /** * M503: print settings currently in memory */ inline void gcode_M503() { (void)settings.report(parser.seen('S') && !parser.value_bool()); } #endif #if ENABLED(EEPROM_SETTINGS) /** * M504: Validate EEPROM Contents */ inline void gcode_M504() { if (settings.validate()) { SERIAL_ECHO_START(); SERIAL_ECHOLNPGM("EEPROM OK"); } } #endif #if ENABLED(SDSUPPORT) /** * M524: Abort the current SD print job (started with M24) */ inline void gcode_M524() { if (IS_SD_PRINTING()) card.abort_sd_printing = true; } #endif // SDSUPPORT #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED) /** * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>) */ inline void gcode_M540() { if (parser.seen('S')) planner.abort_on_endstop_hit = parser.value_bool(); } #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED #if HAS_BED_PROBE inline void gcode_M851() { if (parser.seenval('Z')) { const float value = parser.value_linear_units(); if (WITHIN(value, Z_PROBE_OFFSET_RANGE_MIN, Z_PROBE_OFFSET_RANGE_MAX)) zprobe_zoffset = value; else { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM("?Z out of range (" STRINGIFY(Z_PROBE_OFFSET_RANGE_MIN) " to " STRINGIFY(Z_PROBE_OFFSET_RANGE_MAX) ")"); } return; } SERIAL_ECHO_START(); SERIAL_ECHOPGM(MSG_PROBE_Z_OFFSET); SERIAL_ECHOLNPAIR(": ", zprobe_zoffset); } #endif // HAS_BED_PROBE #if ENABLED(SKEW_CORRECTION_GCODE) /** * M852: Get or set the machine skew factors. Reports current values with no arguments. * * S[xy_factor] - Alias for 'I' * I[xy_factor] - New XY skew factor * J[xz_factor] - New XZ skew factor * K[yz_factor] - New YZ skew factor */ inline void gcode_M852() { uint8_t ijk = 0, badval = 0, setval = 0; if (parser.seen('I') || parser.seen('S')) { ++ijk; const float value = parser.value_linear_units(); if (WITHIN(value, SKEW_FACTOR_MIN, SKEW_FACTOR_MAX)) { if (planner.xy_skew_factor != value) { planner.xy_skew_factor = value; ++setval; } } else ++badval; } #if ENABLED(SKEW_CORRECTION_FOR_Z) if (parser.seen('J')) { ++ijk; const float value = parser.value_linear_units(); if (WITHIN(value, SKEW_FACTOR_MIN, SKEW_FACTOR_MAX)) { if (planner.xz_skew_factor != value) { planner.xz_skew_factor = value; ++setval; } } else ++badval; } if (parser.seen('K')) { ++ijk; const float value = parser.value_linear_units(); if (WITHIN(value, SKEW_FACTOR_MIN, SKEW_FACTOR_MAX)) { if (planner.yz_skew_factor != value) { planner.yz_skew_factor = value; ++setval; } } else ++badval; } #endif if (badval) SERIAL_ECHOLNPGM(MSG_SKEW_MIN " " STRINGIFY(SKEW_FACTOR_MIN) " " MSG_SKEW_MAX " " STRINGIFY(SKEW_FACTOR_MAX)); // When skew is changed the current position changes if (setval) { set_current_from_steppers_for_axis(ALL_AXES); SYNC_PLAN_POSITION_KINEMATIC(); report_current_position(); } if (!ijk) { SERIAL_ECHO_START(); SERIAL_ECHOPGM(MSG_SKEW_FACTOR " XY: "); SERIAL_ECHO_F(planner.xy_skew_factor, 6); SERIAL_EOL(); #if ENABLED(SKEW_CORRECTION_FOR_Z) SERIAL_ECHOPAIR(" XZ: ", planner.xz_skew_factor); SERIAL_ECHOLNPAIR(" YZ: ", planner.yz_skew_factor); #else SERIAL_EOL(); #endif } } #endif // SKEW_CORRECTION_GCODE #if ENABLED(ADVANCED_PAUSE_FEATURE) /** * M600: Pause for filament change * * E[distance] - Retract the filament this far * Z[distance] - Move the Z axis by this distance * X[position] - Move to this X position, with Y * Y[position] - Move to this Y position, with X * U[distance] - Retract distance for removal (manual reload) * L[distance] - Extrude distance for insertion (manual reload) * B[count] - Number of times to beep, -1 for indefinite (if equipped with a buzzer) * T[toolhead] - Select extruder for filament change * * Default values are used for omitted arguments. */ inline void gcode_M600() { #ifdef ANYCUBIC_TFT_MODEL #ifdef SDSUPPORT if (card.sdprinting) { // are we printing from sd? if (AnycubicTFT.ai3m_pause_state < 2) { AnycubicTFT.ai3m_pause_state = 2; #ifdef ANYCUBIC_TFT_DEBUG SERIAL_ECHOPAIR(" DEBUG: M600 - AI3M Pause State set to: ", AnycubicTFT.ai3m_pause_state); SERIAL_EOL(); #endif } #ifdef ANYCUBIC_TFT_DEBUG SERIAL_ECHOLNPGM("DEBUG: Enter M600 TFTstate routine"); #endif AnycubicTFT.TFTstate=ANYCUBIC_TFT_STATE_SDPAUSE_REQ; // enter correct display state to show resume button #ifdef ANYCUBIC_TFT_DEBUG SERIAL_ECHOLNPGM("DEBUG: Set TFTstate to SDPAUSE_REQ"); #endif // set flag to ensure correct resume routine gets executed } #endif #endif point_t park_point = NOZZLE_PARK_POINT; if (get_target_extruder_from_command(600)) return; // Show initial message #if ENABLED(ULTIPANEL) lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INIT, ADVANCED_PAUSE_MODE_PAUSE_PRINT, target_extruder); #endif #if ENABLED(HOME_BEFORE_FILAMENT_CHANGE) // Don't allow filament change without homing first if (axis_unhomed_error()) home_all_axes(); #endif #if EXTRUDERS > 1 // Change toolhead if specified uint8_t active_extruder_before_filament_change = active_extruder; if (active_extruder != target_extruder) tool_change(target_extruder, 0, true); #endif // Initial retract before move to filament change position const float retract = -ABS(parser.seen('E') ? parser.value_axis_units(E_AXIS) : 0 #ifdef PAUSE_PARK_RETRACT_LENGTH + (PAUSE_PARK_RETRACT_LENGTH) #endif ); // Lift Z axis if (parser.seenval('Z')) park_point.z = parser.linearval('Z'); // Move XY axes to filament change position or given position if (parser.seenval('X')) park_point.x = parser.linearval('X'); if (parser.seenval('Y')) park_point.y = parser.linearval('Y'); #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE) && DISABLED(DELTA) park_point.x += (active_extruder ? hotend_offset[X_AXIS][active_extruder] : 0); park_point.y += (active_extruder ? hotend_offset[Y_AXIS][active_extruder] : 0); #endif // Unload filament const float unload_length = -ABS(parser.seen('U') ? parser.value_axis_units(E_AXIS) : filament_change_unload_length[active_extruder]); // Slow load filament constexpr float slow_load_length = FILAMENT_CHANGE_SLOW_LOAD_LENGTH; // Fast load filament const float fast_load_length = ABS(parser.seen('L') ? parser.value_axis_units(E_AXIS) : filament_change_load_length[active_extruder]); const int beep_count = parser.intval('B', #ifdef FILAMENT_CHANGE_ALERT_BEEPS FILAMENT_CHANGE_ALERT_BEEPS #else -1 #endif ); const bool job_running = print_job_timer.isRunning(); if (pause_print(retract, park_point, unload_length, true)) { wait_for_filament_reload(beep_count); resume_print(slow_load_length, fast_load_length, ADVANCED_PAUSE_PURGE_LENGTH, beep_count); } #if EXTRUDERS > 1 // Restore toolhead if it was changed if (active_extruder_before_filament_change != active_extruder) tool_change(active_extruder_before_filament_change, 0, true); #endif // Resume the print job timer if it was running if (job_running) print_job_timer.start(); } /** * M603: Configure filament change * * T[toolhead] - Select extruder to configure, active extruder if not specified * U[distance] - Retract distance for removal, for the specified extruder * L[distance] - Extrude distance for insertion, for the specified extruder * */ inline void gcode_M603() { if (get_target_extruder_from_command(603)) return; // Unload length if (parser.seen('U')) { filament_change_unload_length[target_extruder] = ABS(parser.value_axis_units(E_AXIS)); #if ENABLED(PREVENT_LENGTHY_EXTRUDE) NOMORE(filament_change_unload_length[target_extruder], EXTRUDE_MAXLENGTH); #endif } // Load length if (parser.seen('L')) { filament_change_load_length[target_extruder] = ABS(parser.value_axis_units(E_AXIS)); #if ENABLED(PREVENT_LENGTHY_EXTRUDE) NOMORE(filament_change_load_length[target_extruder], EXTRUDE_MAXLENGTH); #endif } } #endif // ADVANCED_PAUSE_FEATURE #if ENABLED(MK2_MULTIPLEXER) inline void select_multiplexed_stepper(const uint8_t e) { planner.synchronize(); disable_e_steppers(); WRITE(E_MUX0_PIN, TEST(e, 0) ? HIGH : LOW); WRITE(E_MUX1_PIN, TEST(e, 1) ? HIGH : LOW); WRITE(E_MUX2_PIN, TEST(e, 2) ? HIGH : LOW); safe_delay(100); } #endif // MK2_MULTIPLEXER #if ENABLED(DUAL_X_CARRIAGE) /** * M605: Set dual x-carriage movement mode * * M605 S0: Full control mode. The slicer has full control over x-carriage movement * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn * units x-offset and an optional differential hotend temperature of * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate * the first with a spacing of 100mm in the x direction and 2 degrees hotter. * * Note: the X axis should be homed after changing dual x-carriage mode. */ inline void gcode_M605() { planner.synchronize(); if (parser.seen('S')) dual_x_carriage_mode = (DualXMode)parser.value_byte(); switch (dual_x_carriage_mode) { case DXC_FULL_CONTROL_MODE: case DXC_AUTO_PARK_MODE: break; case DXC_DUPLICATION_MODE: if (parser.seen('X')) duplicate_extruder_x_offset = MAX(parser.value_linear_units(), X2_MIN_POS - x_home_pos(0)); if (parser.seen('R')) duplicate_extruder_temp_offset = parser.value_celsius_diff(); SERIAL_ECHO_START(); SERIAL_ECHOPGM(MSG_HOTEND_OFFSET); SERIAL_CHAR(' '); SERIAL_ECHO(hotend_offset[X_AXIS][0]); SERIAL_CHAR(','); SERIAL_ECHO(hotend_offset[Y_AXIS][0]); SERIAL_CHAR(' '); SERIAL_ECHO(duplicate_extruder_x_offset); SERIAL_CHAR(','); SERIAL_ECHOLN(hotend_offset[Y_AXIS][1]); break; default: dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE; break; } active_extruder_parked = false; extruder_duplication_enabled = false; delayed_move_time = 0; } #elif ENABLED(DUAL_NOZZLE_DUPLICATION_MODE) inline void gcode_M605() { planner.synchronize(); extruder_duplication_enabled = parser.intval('S') == int(DXC_DUPLICATION_MODE); SERIAL_ECHO_START(); SERIAL_ECHOLNPAIR(MSG_DUPLICATION_MODE, extruder_duplication_enabled ? MSG_ON : MSG_OFF); } #endif // DUAL_NOZZLE_DUPLICATION_MODE #if ENABLED(FILAMENT_LOAD_UNLOAD_GCODES) /** * M701: Load filament * * T<extruder> - Optional extruder number. Current extruder if omitted. * Z<distance> - Move the Z axis by this distance * L<distance> - Extrude distance for insertion (positive value) (manual reload) * * Default values are used for omitted arguments. */ inline void gcode_M701() { point_t park_point = NOZZLE_PARK_POINT; #if ENABLED(NO_MOTION_BEFORE_HOMING) // Only raise Z if the machine is homed if (axis_unhomed_error()) park_point.z = 0; #endif if (get_target_extruder_from_command(701)) return; // Z axis lift if (parser.seenval('Z')) park_point.z = parser.linearval('Z'); // Show initial "wait for load" message #if ENABLED(ULTIPANEL) lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_LOAD, ADVANCED_PAUSE_MODE_LOAD_FILAMENT, target_extruder); #endif #if EXTRUDERS > 1 // Change toolhead if specified uint8_t active_extruder_before_filament_change = active_extruder; if (active_extruder != target_extruder) tool_change(target_extruder, 0, true); #endif // Lift Z axis if (park_point.z > 0) do_blocking_move_to_z(MIN(current_position[Z_AXIS] + park_point.z, Z_MAX_POS), NOZZLE_PARK_Z_FEEDRATE); constexpr float slow_load_length = FILAMENT_CHANGE_SLOW_LOAD_LENGTH; const float fast_load_length = ABS(parser.seen('L') ? parser.value_axis_units(E_AXIS) : filament_change_load_length[active_extruder]); load_filament(slow_load_length, fast_load_length, ADVANCED_PAUSE_PURGE_LENGTH, FILAMENT_CHANGE_ALERT_BEEPS, true, thermalManager.wait_for_heating(target_extruder), ADVANCED_PAUSE_MODE_LOAD_FILAMENT); // Restore Z axis if (park_point.z > 0) do_blocking_move_to_z(MAX(current_position[Z_AXIS] - park_point.z, 0), NOZZLE_PARK_Z_FEEDRATE); #if EXTRUDERS > 1 // Restore toolhead if it was changed if (active_extruder_before_filament_change != active_extruder) tool_change(active_extruder_before_filament_change, 0, true); #endif // Show status screen #if ENABLED(ULTIPANEL) lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS); #endif } /** * M702: Unload filament * * T<extruder> - Optional extruder number. If omitted, current extruder * (or ALL extruders with FILAMENT_UNLOAD_ALL_EXTRUDERS). * Z<distance> - Move the Z axis by this distance * U<distance> - Retract distance for removal (manual reload) * * Default values are used for omitted arguments. */ inline void gcode_M702() { point_t park_point = NOZZLE_PARK_POINT; #if ENABLED(NO_MOTION_BEFORE_HOMING) // Only raise Z if the machine is homed if (axis_unhomed_error()) park_point.z = 0; #endif if (get_target_extruder_from_command(702)) return; // Z axis lift if (parser.seenval('Z')) park_point.z = parser.linearval('Z'); // Show initial message #if ENABLED(ULTIPANEL) lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_UNLOAD, ADVANCED_PAUSE_MODE_UNLOAD_FILAMENT, target_extruder); #endif #if EXTRUDERS > 1 // Change toolhead if specified uint8_t active_extruder_before_filament_change = active_extruder; if (active_extruder != target_extruder) tool_change(target_extruder, 0, true); #endif // Lift Z axis if (park_point.z > 0) do_blocking_move_to_z(MIN(current_position[Z_AXIS] + park_point.z, Z_MAX_POS), NOZZLE_PARK_Z_FEEDRATE); // Unload filament #if EXTRUDERS > 1 && ENABLED(FILAMENT_UNLOAD_ALL_EXTRUDERS) if (!parser.seenval('T')) { HOTEND_LOOP() { if (e != active_extruder) tool_change(e, 0, true); unload_filament(-filament_change_unload_length[e], true, ADVANCED_PAUSE_MODE_UNLOAD_FILAMENT); } } else #endif { // Unload length const float unload_length = -ABS(parser.seen('U') ? parser.value_axis_units(E_AXIS) : filament_change_unload_length[target_extruder]); unload_filament(unload_length, true, ADVANCED_PAUSE_MODE_UNLOAD_FILAMENT); } // Restore Z axis if (park_point.z > 0) do_blocking_move_to_z(MAX(current_position[Z_AXIS] - park_point.z, 0), NOZZLE_PARK_Z_FEEDRATE); #if EXTRUDERS > 1 // Restore toolhead if it was changed if (active_extruder_before_filament_change != active_extruder) tool_change(active_extruder_before_filament_change, 0, true); #endif // Show status screen #if ENABLED(ULTIPANEL) lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS); #endif } #endif // FILAMENT_LOAD_UNLOAD_GCODES #if ENABLED(MAX7219_GCODE) /** * M7219: Control the Max7219 LED matrix * * I - Initialize (clear) the matrix * F - Fill the matrix (set all bits) * P - Dump the LEDs[] array values * C<column> - Set a column to the 8-bit value V * R<row> - Set a row to the 8-bit value V * X<pos> - X position of an LED to set or toggle * Y<pos> - Y position of an LED to set or toggle * V<value> - The potentially 32-bit value or on/off state to set * (for example: a chain of 4 Max7219 devices can have 32 bit * rows or columns depending upon rotation) */ inline void gcode_M7219() { if (parser.seen('I')) { max7219.register_setup(); max7219.clear(); } if (parser.seen('F')) max7219.fill(); const uint32_t v = parser.ulongval('V'); if (parser.seenval('R')) { const uint8_t r = parser.value_byte(); max7219.set_row(r, v); } else if (parser.seenval('C')) { const uint8_t c = parser.value_byte(); max7219.set_column(c, v); } else if (parser.seenval('X') || parser.seenval('Y')) { const uint8_t x = parser.byteval('X'), y = parser.byteval('Y'); if (parser.seenval('V')) max7219.led_set(x, y, parser.boolval('V')); else max7219.led_toggle(x, y); } else if (parser.seen('D')) { const uint8_t line = parser.byteval('D') + (parser.byteval('U') << 3); if (line < MAX7219_LINES) { max7219.led_line[line] = v; return max7219.refresh_line(line); } } if (parser.seen('P')) { for (uint8_t r = 0; r < MAX7219_LINES; r++) { SERIAL_ECHOPGM("led_line["); if (r < 10) SERIAL_CHAR(' '); SERIAL_ECHO(int(r)); SERIAL_ECHOPGM("]="); for (uint8_t b = 8; b--;) SERIAL_CHAR('0' + TEST(max7219.led_line[r], b)); SERIAL_EOL(); } } } #endif // MAX7219_GCODE /** * M888: Cooldown routine for the Anycubic Ultrabase (EXPERIMENTAL): * This is meant to be placed at the end Gcode of your slicer. * It hovers over the print bed and does circular movements while * running the fan. Works best with custom fan ducts. * * T<int> Target bed temperature (min 15°C), 30°C if not specified * S<int> Fan speed between 0 and 255, full speed if not specified */ inline void gcode_M888() { // don't do this if the machine is not homed if (axis_unhomed_error()) return; const float cooldown_arc[2] = { 50, 50 }; const uint8_t cooldown_target = MAX((parser.ushortval('T', 30)), 15); // set hotbed temperate to zero thermalManager.setTargetBed(0); SERIAL_PROTOCOLLNPGM("Ultrabase cooldown started"); // set fan to speed <S>, if undefined blast at full speed uint8_t cooldown_fanspeed = parser.ushortval('S', 255); fanSpeeds[0] = MIN(cooldown_fanspeed, 255U); // raise z by 2mm and move to X50, Y50 do_blocking_move_to_z(MIN(current_position[Z_AXIS] + 2, Z_MAX_POS), 5); do_blocking_move_to_xy(50, 50, 100); while ((thermalManager.degBed() > cooldown_target)) { // queue arc movement gcode_get_destination(); plan_arc(destination, cooldown_arc, true); SERIAL_PROTOCOLLNPGM("Target not reached, queued an arc"); // delay while arc is in progress while (planner.movesplanned()) { idle(); } idle(); } // the bed should be under <T> now fanSpeeds[0]=0; do_blocking_move_to_xy(MAX(X_MIN_POS, 10), MIN(Y_MAX_POS, 190), 100); BUZZ(100, 659); BUZZ(150, 1318); enqueue_and_echo_commands_P(PSTR("M84")); SERIAL_PROTOCOLLNPGM("M888 cooldown routine done"); } #if ENABLED(LIN_ADVANCE) /** * M900: Get or Set Linear Advance K-factor * * K<factor> Set advance K factor */ inline void gcode_M900() { if (parser.seenval('K')) { const float newK = parser.floatval('K'); if (WITHIN(newK, 0, 10)) { planner.synchronize(); planner.extruder_advance_K = newK; } else SERIAL_PROTOCOLLNPGM("?K value out of range (0-10)."); } else { SERIAL_ECHO_START(); SERIAL_ECHOLNPAIR("Advance K=", planner.extruder_advance_K); } } #endif // LIN_ADVANCE #if HAS_TRINAMIC #if ENABLED(TMC_DEBUG) inline void gcode_M122() { if (parser.seen('S')) tmc_set_report_status(parser.value_bool()); else tmc_report_all(); } #endif // TMC_DEBUG /** * M906: Set motor current in milliamps using axis codes X, Y, Z, E * Uses axis codes A, B, C, D, E for Hangprinter * Report driver currents when no axis specified */ inline void gcode_M906() { #define TMC_SAY_CURRENT(Q) tmc_get_current(stepper##Q, TMC_##Q) #define TMC_SET_CURRENT(Q) tmc_set_current(stepper##Q, value) bool report = true; const uint8_t index = parser.byteval('I'); LOOP_NUM_AXIS(i) if (uint16_t value = parser.intval(RAW_AXIS_CODES(i))) { report = false; switch (i) { // Assumes {A_AXIS, B_AXIS, C_AXIS} == {X_AXIS, Y_AXIS, Z_AXIS} case X_AXIS: #if AXIS_IS_TMC(X) if (index < 2) TMC_SET_CURRENT(X); #endif #if AXIS_IS_TMC(X2) if (!(index & 1)) TMC_SET_CURRENT(X2); #endif break; case Y_AXIS: #if AXIS_IS_TMC(Y) if (index < 2) TMC_SET_CURRENT(Y); #endif #if AXIS_IS_TMC(Y2) if (!(index & 1)) TMC_SET_CURRENT(Y2); #endif break; case Z_AXIS: #if AXIS_IS_TMC(Z) if (index < 2) TMC_SET_CURRENT(Z); #endif #if AXIS_IS_TMC(Z2) if (!(index & 1)) TMC_SET_CURRENT(Z2); #endif break; case E_AXIS: { if (get_target_extruder_from_command(906)) return; switch (target_extruder) { #if AXIS_IS_TMC(E0) case 0: TMC_SET_CURRENT(E0); break; #endif #if ENABLED(HANGPRINTER) // Avoid setting the D-current #if AXIS_IS_TMC(E1) && EXTRUDERS > 1 case 1: TMC_SET_CURRENT(E1); break; #endif #if AXIS_IS_TMC(E2) && EXTRUDERS > 2 case 2: TMC_SET_CURRENT(E2); break; #endif #if AXIS_IS_TMC(E3) && EXTRUDERS > 3 case 3: TMC_SET_CURRENT(E3); break; #endif #if AXIS_IS_TMC(E4) && EXTRUDERS > 4 case 4: TMC_SET_CURRENT(E4); break; #endif #else #if AXIS_IS_TMC(E1) case 1: TMC_SET_CURRENT(E1); break; #endif #if AXIS_IS_TMC(E2) case 2: TMC_SET_CURRENT(E2); break; #endif #if AXIS_IS_TMC(E3) case 3: TMC_SET_CURRENT(E3); break; #endif #if AXIS_IS_TMC(E4) case 4: TMC_SET_CURRENT(E4); break; #endif #endif } } break; #if ENABLED(HANGPRINTER) case D_AXIS: // D is connected on the first of E1, E2, E3, E4 output that is not an extruder #if AXIS_IS_TMC(E1) && EXTRUDERS == 1 TMC_SET_CURRENT(E1); break; #endif #if AXIS_IS_TMC(E2) && EXTRUDERS == 2 TMC_SET_CURRENT(E2); break; #endif #if AXIS_IS_TMC(E3) && EXTRUDERS == 3 TMC_SET_CURRENT(E3); break; #endif #if AXIS_IS_TMC(E4) && EXTRUDERS == 4 TMC_SET_CURRENT(E4); break; #endif #endif } } if (report) { #if AXIS_IS_TMC(X) TMC_SAY_CURRENT(X); #endif #if AXIS_IS_TMC(X2) TMC_SAY_CURRENT(X2); #endif #if AXIS_IS_TMC(Y) TMC_SAY_CURRENT(Y); #endif #if AXIS_IS_TMC(Y2) TMC_SAY_CURRENT(Y2); #endif #if AXIS_IS_TMC(Z) TMC_SAY_CURRENT(Z); #endif #if AXIS_IS_TMC(Z2) TMC_SAY_CURRENT(Z2); #endif #if AXIS_IS_TMC(E0) TMC_SAY_CURRENT(E0); #endif #if ENABLED(HANGPRINTER) // D is connected on the first of E1, E2, E3, E4 output that is not an extruder #if AXIS_IS_TMC(E1) && EXTRUDERS == 1 TMC_SAY_CURRENT(E1); #endif #if AXIS_IS_TMC(E2) && EXTRUDERS == 2 TMC_SAY_CURRENT(E2); #endif #if AXIS_IS_TMC(E3) && EXTRUDERS == 3 TMC_SAY_CURRENT(E3); #endif #if AXIS_IS_TMC(E4) && EXTRUDERS == 4 TMC_SAY_CURRENT(E4); #endif #else #if AXIS_IS_TMC(E1) TMC_SAY_CURRENT(E1); #endif #if AXIS_IS_TMC(E2) TMC_SAY_CURRENT(E2); #endif #if AXIS_IS_TMC(E3) TMC_SAY_CURRENT(E3); #endif #if AXIS_IS_TMC(E4) TMC_SAY_CURRENT(E4); #endif #endif } } #define M91x_USE(ST) (AXIS_DRIVER_TYPE(ST, TMC2130) || (AXIS_DRIVER_TYPE(ST, TMC2208) && PIN_EXISTS(ST##_SERIAL_RX))) #define M91x_USE_E(N) (E_STEPPERS > N && M91x_USE(E##N)) /** * M911: Report TMC stepper driver overtemperature pre-warn flag * This flag is held by the library, persisting until cleared by M912 */ inline void gcode_M911() { #if M91x_USE(X) tmc_report_otpw(stepperX, TMC_X); #endif #if M91x_USE(X2) tmc_report_otpw(stepperX2, TMC_X2); #endif #if M91x_USE(Y) tmc_report_otpw(stepperY, TMC_Y); #endif #if M91x_USE(Y2) tmc_report_otpw(stepperY2, TMC_Y2); #endif #if M91x_USE(Z) tmc_report_otpw(stepperZ, TMC_Z); #endif #if M91x_USE(Z2) tmc_report_otpw(stepperZ2, TMC_Z2); #endif #if M91x_USE_E(0) tmc_report_otpw(stepperE0, TMC_E0); #endif #if M91x_USE_E(1) tmc_report_otpw(stepperE1, TMC_E1); #endif #if M91x_USE_E(2) tmc_report_otpw(stepperE2, TMC_E2); #endif #if M91x_USE_E(3) tmc_report_otpw(stepperE3, TMC_E3); #endif #if M91x_USE_E(4) tmc_report_otpw(stepperE4, TMC_E4); #endif } /** * M912: Clear TMC stepper driver overtemperature pre-warn flag held by the library * Specify one or more axes with X, Y, Z, X1, Y1, Z1, X2, Y2, Z2, and E[index]. * If no axes are given, clear all. * * Examples: * M912 X ; clear X and X2 * M912 X1 ; clear X1 only * M912 X2 ; clear X2 only * M912 X E ; clear X, X2, and all E * M912 E1 ; clear E1 only */ inline void gcode_M912() { const bool hasX = parser.seen(axis_codes[X_AXIS]), hasY = parser.seen(axis_codes[Y_AXIS]), hasZ = parser.seen(axis_codes[Z_AXIS]), hasE = parser.seen(axis_codes[E_CART]), hasNone = !hasX && !hasY && !hasZ && !hasE; #if M91x_USE(X) || M91x_USE(X2) const uint8_t xval = parser.byteval(axis_codes[X_AXIS], 10); #if M91x_USE(X) if (hasNone || xval == 1 || (hasX && xval == 10)) tmc_clear_otpw(stepperX, TMC_X); #endif #if M91x_USE(X2) if (hasNone || xval == 2 || (hasX && xval == 10)) tmc_clear_otpw(stepperX2, TMC_X2); #endif #endif #if M91x_USE(Y) || M91x_USE(Y2) const uint8_t yval = parser.byteval(axis_codes[Y_AXIS], 10); #if M91x_USE(Y) if (hasNone || yval == 1 || (hasY && yval == 10)) tmc_clear_otpw(stepperY, TMC_Y); #endif #if M91x_USE(Y2) if (hasNone || yval == 2 || (hasY && yval == 10)) tmc_clear_otpw(stepperY2, TMC_Y2); #endif #endif #if M91x_USE(Z) || M91x_USE(Z2) const uint8_t zval = parser.byteval(axis_codes[Z_AXIS], 10); #if M91x_USE(Z) if (hasNone || zval == 1 || (hasZ && zval == 10)) tmc_clear_otpw(stepperZ, TMC_Z); #endif #if M91x_USE(Z2) if (hasNone || zval == 2 || (hasZ && zval == 10)) tmc_clear_otpw(stepperZ2, TMC_Z2); #endif #endif // TODO: If this is a Hangprinter, E_AXIS will not correspond to E0, E1, etc in this way #if M91x_USE_E(0) || M91x_USE_E(1) || M91x_USE_E(2) || M91x_USE_E(3) || M91x_USE_E(4) const uint8_t eval = parser.byteval(axis_codes[E_AXIS], 10); #if M91x_USE_E(0) if (hasNone || eval == 0 || (hasE && eval == 10)) tmc_clear_otpw(stepperE0, TMC_E0); #endif #if M91x_USE_E(1) if (hasNone || eval == 1 || (hasE && eval == 10)) tmc_clear_otpw(stepperE1, TMC_E1); #endif #if M91x_USE_E(2) if (hasNone || eval == 2 || (hasE && eval == 10)) tmc_clear_otpw(stepperE2, TMC_E2); #endif #if M91x_USE_E(3) if (hasNone || eval == 3 || (hasE && eval == 10)) tmc_clear_otpw(stepperE3, TMC_E3); #endif #if M91x_USE_E(4) if (hasNone || eval == 4 || (hasE && eval == 10)) tmc_clear_otpw(stepperE4, TMC_E4); #endif #endif } /** * M913: Set HYBRID_THRESHOLD speed. */ #if ENABLED(HYBRID_THRESHOLD) inline void gcode_M913() { #define TMC_SAY_PWMTHRS(A,Q) tmc_get_pwmthrs(stepper##Q, TMC_##Q, planner.axis_steps_per_mm[_AXIS(A)]) #define TMC_SET_PWMTHRS(A,Q) tmc_set_pwmthrs(stepper##Q, value, planner.axis_steps_per_mm[_AXIS(A)]) #define TMC_SAY_PWMTHRS_E(E) do{ const uint8_t extruder = E; tmc_get_pwmthrs(stepperE##E, TMC_E##E, planner.axis_steps_per_mm[E_AXIS_N]); }while(0) #define TMC_SET_PWMTHRS_E(E) do{ const uint8_t extruder = E; tmc_set_pwmthrs(stepperE##E, value, planner.axis_steps_per_mm[E_AXIS_N]); }while(0) bool report = true; const uint8_t index = parser.byteval('I'); LOOP_XYZE(i) if (int32_t value = parser.longval(axis_codes[i])) { report = false; switch (i) { case X_AXIS: #if AXIS_HAS_STEALTHCHOP(X) if (index < 2) TMC_SET_PWMTHRS(X,X); #endif #if AXIS_HAS_STEALTHCHOP(X2) if (!(index & 1)) TMC_SET_PWMTHRS(X,X2); #endif break; case Y_AXIS: #if AXIS_HAS_STEALTHCHOP(Y) if (index < 2) TMC_SET_PWMTHRS(Y,Y); #endif #if AXIS_HAS_STEALTHCHOP(Y2) if (!(index & 1)) TMC_SET_PWMTHRS(Y,Y2); #endif break; case Z_AXIS: #if AXIS_HAS_STEALTHCHOP(Z) if (index < 2) TMC_SET_PWMTHRS(Z,Z); #endif #if AXIS_HAS_STEALTHCHOP(Z2) if (!(index & 1)) TMC_SET_PWMTHRS(Z,Z2); #endif break; case E_CART: { if (get_target_extruder_from_command(913)) return; switch (target_extruder) { #if AXIS_HAS_STEALTHCHOP(E0) case 0: TMC_SET_PWMTHRS_E(0); break; #endif #if E_STEPPERS > 1 && AXIS_HAS_STEALTHCHOP(E1) case 1: TMC_SET_PWMTHRS_E(1); break; #endif #if E_STEPPERS > 2 && AXIS_HAS_STEALTHCHOP(E2) case 2: TMC_SET_PWMTHRS_E(2); break; #endif #if E_STEPPERS > 3 && AXIS_HAS_STEALTHCHOP(E3) case 3: TMC_SET_PWMTHRS_E(3); break; #endif #if E_STEPPERS > 4 && AXIS_HAS_STEALTHCHOP(E4) case 4: TMC_SET_PWMTHRS_E(4); break; #endif } } break; } } if (report) { #if AXIS_HAS_STEALTHCHOP(X) TMC_SAY_PWMTHRS(X,X); #endif #if AXIS_HAS_STEALTHCHOP(X2) TMC_SAY_PWMTHRS(X,X2); #endif #if AXIS_HAS_STEALTHCHOP(Y) TMC_SAY_PWMTHRS(Y,Y); #endif #if AXIS_HAS_STEALTHCHOP(Y2) TMC_SAY_PWMTHRS(Y,Y2); #endif #if AXIS_HAS_STEALTHCHOP(Z) TMC_SAY_PWMTHRS(Z,Z); #endif #if AXIS_HAS_STEALTHCHOP(Z2) TMC_SAY_PWMTHRS(Z,Z2); #endif #if AXIS_HAS_STEALTHCHOP(E0) TMC_SAY_PWMTHRS_E(0); #endif #if E_STEPPERS > 1 && AXIS_HAS_STEALTHCHOP(E1) TMC_SAY_PWMTHRS_E(1); #endif #if E_STEPPERS > 2 && AXIS_HAS_STEALTHCHOP(E2) TMC_SAY_PWMTHRS_E(2); #endif #if E_STEPPERS > 3 && AXIS_HAS_STEALTHCHOP(E3) TMC_SAY_PWMTHRS_E(3); #endif #if E_STEPPERS > 4 && AXIS_HAS_STEALTHCHOP(E4) TMC_SAY_PWMTHRS_E(4); #endif } } #endif // HYBRID_THRESHOLD /** * M914: Set SENSORLESS_HOMING sensitivity. */ #if ENABLED(SENSORLESS_HOMING) inline void gcode_M914() { #define TMC_SAY_SGT(Q) tmc_get_sgt(stepper##Q, TMC_##Q) #define TMC_SET_SGT(Q) tmc_set_sgt(stepper##Q, value) bool report = true; const uint8_t index = parser.byteval('I'); LOOP_XYZ(i) if (parser.seen(axis_codes[i])) { const int8_t value = (int8_t)constrain(parser.value_int(), -64, 63); report = false; switch (i) { #if X_SENSORLESS case X_AXIS: #if AXIS_HAS_STALLGUARD(X) if (index < 2) TMC_SET_SGT(X); #endif #if AXIS_HAS_STALLGUARD(X2) if (!(index & 1)) TMC_SET_SGT(X2); #endif break; #endif #if Y_SENSORLESS case Y_AXIS: #if AXIS_HAS_STALLGUARD(Y) if (index < 2) TMC_SET_SGT(Y); #endif #if AXIS_HAS_STALLGUARD(Y2) if (!(index & 1)) TMC_SET_SGT(Y2); #endif break; #endif #if Z_SENSORLESS case Z_AXIS: #if AXIS_HAS_STALLGUARD(Z) if (index < 2) TMC_SET_SGT(Z); #endif #if AXIS_HAS_STALLGUARD(Z2) if (!(index & 1)) TMC_SET_SGT(Z2); #endif break; #endif } } if (report) { #if X_SENSORLESS #if AXIS_HAS_STALLGUARD(X) TMC_SAY_SGT(X); #endif #if AXIS_HAS_STALLGUARD(X2) TMC_SAY_SGT(X2); #endif #endif #if Y_SENSORLESS #if AXIS_HAS_STALLGUARD(Y) TMC_SAY_SGT(Y); #endif #if AXIS_HAS_STALLGUARD(Y2) TMC_SAY_SGT(Y2); #endif #endif #if Z_SENSORLESS #if AXIS_HAS_STALLGUARD(Z) TMC_SAY_SGT(Z); #endif #if AXIS_HAS_STALLGUARD(Z2) TMC_SAY_SGT(Z2); #endif #endif } } #endif // SENSORLESS_HOMING /** * TMC Z axis calibration routine */ #if ENABLED(TMC_Z_CALIBRATION) inline void gcode_M915() { const uint16_t _rms = parser.seenval('S') ? parser.value_int() : CALIBRATION_CURRENT, _z = parser.seenval('Z') ? parser.value_linear_units() : CALIBRATION_EXTRA_HEIGHT; if (!TEST(axis_known_position, Z_AXIS)) { SERIAL_ECHOLNPGM("\nPlease home Z axis first"); return; } #if AXIS_IS_TMC(Z) const uint16_t Z_current_1 = stepperZ.getCurrent(); stepperZ.setCurrent(_rms, R_SENSE, HOLD_MULTIPLIER); #endif #if AXIS_IS_TMC(Z2) const uint16_t Z2_current_1 = stepperZ2.getCurrent(); stepperZ2.setCurrent(_rms, R_SENSE, HOLD_MULTIPLIER); #endif SERIAL_ECHOPAIR("\nCalibration current: Z", _rms); soft_endstops_enabled = false; do_blocking_move_to_z(Z_MAX_POS+_z); #if AXIS_IS_TMC(Z) stepperZ.setCurrent(Z_current_1, R_SENSE, HOLD_MULTIPLIER); #endif #if AXIS_IS_TMC(Z2) stepperZ2.setCurrent(Z2_current_1, R_SENSE, HOLD_MULTIPLIER); #endif do_blocking_move_to_z(Z_MAX_POS); soft_endstops_enabled = true; SERIAL_ECHOLNPGM("\nHoming Z due to lost steps"); enqueue_and_echo_commands_P(PSTR("G28 Z")); } #endif #endif // HAS_TRINAMIC /** * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S */ inline void gcode_M907() { #if HAS_DIGIPOTSS LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.digipot_current(i, parser.value_int()); if (parser.seen('B')) stepper.digipot_current(4, parser.value_int()); if (parser.seen('S')) for (uint8_t i = 0; i <= 4; i++) stepper.digipot_current(i, parser.value_int()); #elif HAS_MOTOR_CURRENT_PWM #if PIN_EXISTS(MOTOR_CURRENT_PWM_XY) if (parser.seen('X')) stepper.digipot_current(0, parser.value_int()); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z) if (parser.seen('Z')) stepper.digipot_current(1, parser.value_int()); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_E) if (parser.seen('E')) stepper.digipot_current(2, parser.value_int()); #endif #endif #if ENABLED(DIGIPOT_I2C) // this one uses actual amps in floating point LOOP_XYZE(i) if (parser.seen(axis_codes[i])) digipot_i2c_set_current(i, parser.value_float()); // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...) for (uint8_t i = NUM_AXIS; i < DIGIPOT_I2C_NUM_CHANNELS; i++) if (parser.seen('B' + i - (NUM_AXIS))) digipot_i2c_set_current(i, parser.value_float()); #endif #if ENABLED(DAC_STEPPER_CURRENT) if (parser.seen('S')) { const float dac_percent = parser.value_float(); for (uint8_t i = 0; i <= 4; i++) dac_current_percent(i, dac_percent); } LOOP_XYZE(i) if (parser.seen(axis_codes[i])) dac_current_percent(i, parser.value_float()); #endif } #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT) /** * M908: Control digital trimpot directly (M908 P<pin> S<current>) */ inline void gcode_M908() { #if HAS_DIGIPOTSS stepper.digitalPotWrite( parser.intval('P'), parser.intval('S') ); #endif #ifdef DAC_STEPPER_CURRENT dac_current_raw( parser.byteval('P', -1), parser.ushortval('S', 0) ); #endif } #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF inline void gcode_M909() { dac_print_values(); } inline void gcode_M910() { dac_commit_eeprom(); } #endif #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT #if HAS_MICROSTEPS // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers. inline void gcode_M350() { if (parser.seen('S')) for (int i = 0; i <= 4; i++) stepper.microstep_mode(i, parser.value_byte()); LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.microstep_mode(i, parser.value_byte()); if (parser.seen('B')) stepper.microstep_mode(4, parser.value_byte()); stepper.microstep_readings(); } /** * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B * S# determines MS1 or MS2, X# sets the pin high/low. */ inline void gcode_M351() { if (parser.seenval('S')) switch (parser.value_byte()) { case 1: LOOP_XYZE(i) if (parser.seenval(axis_codes[i])) stepper.microstep_ms(i, parser.value_byte(), -1); if (parser.seenval('B')) stepper.microstep_ms(4, parser.value_byte(), -1); break; case 2: LOOP_XYZE(i) if (parser.seenval(axis_codes[i])) stepper.microstep_ms(i, -1, parser.value_byte()); if (parser.seenval('B')) stepper.microstep_ms(4, -1, parser.value_byte()); break; } stepper.microstep_readings(); } #endif // HAS_MICROSTEPS #if HAS_CASE_LIGHT #ifndef INVERT_CASE_LIGHT #define INVERT_CASE_LIGHT false #endif uint8_t case_light_brightness; // LCD routine wants INT bool case_light_on; #if ENABLED(CASE_LIGHT_USE_NEOPIXEL) LEDColor case_light_color = #ifdef CASE_LIGHT_NEOPIXEL_COLOR CASE_LIGHT_NEOPIXEL_COLOR #else { 255, 255, 255, 255 } #endif ; #endif void update_case_light() { const uint8_t i = case_light_on ? case_light_brightness : 0, n10ct = INVERT_CASE_LIGHT ? 255 - i : i; #if ENABLED(CASE_LIGHT_USE_NEOPIXEL) leds.set_color( MakeLEDColor(case_light_color.r, case_light_color.g, case_light_color.b, case_light_color.w, n10ct), false ); #else // !CASE_LIGHT_USE_NEOPIXEL SET_OUTPUT(CASE_LIGHT_PIN); if (USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) analogWrite(CASE_LIGHT_PIN, n10ct); else { const bool s = case_light_on ? !INVERT_CASE_LIGHT : INVERT_CASE_LIGHT; WRITE(CASE_LIGHT_PIN, s ? HIGH : LOW); } #endif // !CASE_LIGHT_USE_NEOPIXEL } #endif // HAS_CASE_LIGHT /** * M355: Turn case light on/off and set brightness * * P<byte> Set case light brightness (PWM pin required - ignored otherwise) * * S<bool> Set case light on/off * * When S turns on the light on a PWM pin then the current brightness level is used/restored * * M355 P200 S0 turns off the light & sets the brightness level * M355 S1 turns on the light with a brightness of 200 (assuming a PWM pin) */ inline void gcode_M355() { #if HAS_CASE_LIGHT uint8_t args = 0; if (parser.seenval('P')) ++args, case_light_brightness = parser.value_byte(); if (parser.seenval('S')) ++args, case_light_on = parser.value_bool(); if (args) update_case_light(); // always report case light status SERIAL_ECHO_START(); if (!case_light_on) { SERIAL_ECHOLNPGM("Case light: off"); } else { if (!USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) SERIAL_ECHOLNPGM("Case light: on"); else SERIAL_ECHOLNPAIR("Case light: ", int(case_light_brightness)); } #else SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_M355_NONE); #endif // HAS_CASE_LIGHT } #if ENABLED(MIXING_EXTRUDER) /** * M163: Set a single mix factor for a mixing extruder * This is called "weight" by some systems. * The 'P' values must sum to 1.0 or must be followed by M164 to normalize them. * * S[index] The channel index to set * P[float] The mix value */ inline void gcode_M163() { const int mix_index = parser.intval('S'); if (mix_index < MIXING_STEPPERS) mixing_factor[mix_index] = MAX(parser.floatval('P'), 0.0); } /** * M164: Normalize and commit the mix. * If 'S' is given store as a virtual tool. (Requires MIXING_VIRTUAL_TOOLS > 1) * * S[index] The virtual tool to store */ inline void gcode_M164() { normalize_mix(); #if MIXING_VIRTUAL_TOOLS > 1 const int tool_index = parser.intval('S', -1); if (WITHIN(tool_index, 0, MIXING_VIRTUAL_TOOLS - 1)) { for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mixing_virtual_tool_mix[tool_index][i] = mixing_factor[i]; } #endif } #if ENABLED(DIRECT_MIXING_IN_G1) /** * M165: Set multiple mix factors for a mixing extruder. * Factors that are left out will be set to 0. * All factors should sum to 1.0, but they will be normalized regardless. * * A[factor] Mix factor for extruder stepper 1 * B[factor] Mix factor for extruder stepper 2 * C[factor] Mix factor for extruder stepper 3 * D[factor] Mix factor for extruder stepper 4 * H[factor] Mix factor for extruder stepper 5 * I[factor] Mix factor for extruder stepper 6 */ inline void gcode_M165() { gcode_get_mix(); } #endif #endif // MIXING_EXTRUDER /** * M999: Restart after being stopped * * Default behaviour is to flush the serial buffer and request * a resend to the host starting on the last N line received. * * Sending "M999 S1" will resume printing without flushing the * existing command buffer. * */ inline void gcode_M999() { Running = true; lcd_reset_alert_level(); if (parser.boolval('S')) return; // gcode_LastN = Stopped_gcode_LastN; flush_and_request_resend(); } #if DO_SWITCH_EXTRUDER #if EXTRUDERS > 3 #define REQ_ANGLES 4 #define _SERVO_NR (e < 2 ? SWITCHING_EXTRUDER_SERVO_NR : SWITCHING_EXTRUDER_E23_SERVO_NR) #else #define REQ_ANGLES 2 #define _SERVO_NR SWITCHING_EXTRUDER_SERVO_NR #endif inline void move_extruder_servo(const uint8_t e) { constexpr int16_t angles[] = SWITCHING_EXTRUDER_SERVO_ANGLES; static_assert(COUNT(angles) == REQ_ANGLES, "SWITCHING_EXTRUDER_SERVO_ANGLES needs " STRINGIFY(REQ_ANGLES) " angles."); planner.synchronize(); #if EXTRUDERS & 1 if (e < EXTRUDERS - 1) #endif { MOVE_SERVO(_SERVO_NR, angles[e]); safe_delay(500); } } #endif // DO_SWITCH_EXTRUDER #if ENABLED(SWITCHING_NOZZLE) inline void move_nozzle_servo(const uint8_t e) { const int16_t angles[2] = SWITCHING_NOZZLE_SERVO_ANGLES; planner.synchronize(); MOVE_SERVO(SWITCHING_NOZZLE_SERVO_NR, angles[e]); safe_delay(500); } #endif inline void invalid_extruder_error(const uint8_t e) { SERIAL_ECHO_START(); SERIAL_CHAR('T'); SERIAL_ECHO_F(e, DEC); SERIAL_CHAR(' '); SERIAL_ECHOLNPGM(MSG_INVALID_EXTRUDER); } #if ENABLED(PARKING_EXTRUDER) #if ENABLED(PARKING_EXTRUDER_SOLENOIDS_INVERT) #define PE_MAGNET_ON_STATE !PARKING_EXTRUDER_SOLENOIDS_PINS_ACTIVE #else #define PE_MAGNET_ON_STATE PARKING_EXTRUDER_SOLENOIDS_PINS_ACTIVE #endif void pe_set_magnet(const uint8_t extruder_num, const uint8_t state) { switch (extruder_num) { case 1: OUT_WRITE(SOL1_PIN, state); break; default: OUT_WRITE(SOL0_PIN, state); break; } #if PARKING_EXTRUDER_SOLENOIDS_DELAY > 0 dwell(PARKING_EXTRUDER_SOLENOIDS_DELAY); #endif } inline void pe_activate_magnet(const uint8_t extruder_num) { pe_set_magnet(extruder_num, PE_MAGNET_ON_STATE); } inline void pe_deactivate_magnet(const uint8_t extruder_num) { pe_set_magnet(extruder_num, !PE_MAGNET_ON_STATE); } #endif // PARKING_EXTRUDER #if HAS_FANMUX void fanmux_switch(const uint8_t e) { WRITE(FANMUX0_PIN, TEST(e, 0) ? HIGH : LOW); #if PIN_EXISTS(FANMUX1) WRITE(FANMUX1_PIN, TEST(e, 1) ? HIGH : LOW); #if PIN_EXISTS(FANMUX2) WRITE(FANMUX2, TEST(e, 2) ? HIGH : LOW); #endif #endif } FORCE_INLINE void fanmux_init(void) { SET_OUTPUT(FANMUX0_PIN); #if PIN_EXISTS(FANMUX1) SET_OUTPUT(FANMUX1_PIN); #if PIN_EXISTS(FANMUX2) SET_OUTPUT(FANMUX2_PIN); #endif #endif fanmux_switch(0); } #endif // HAS_FANMUX /** * Tool Change functions */ #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1 inline void mixing_tool_change(const uint8_t tmp_extruder) { if (tmp_extruder >= MIXING_VIRTUAL_TOOLS) return invalid_extruder_error(tmp_extruder); // T0-Tnnn: Switch virtual tool by changing the mix for (uint8_t j = 0; j < MIXING_STEPPERS; j++) mixing_factor[j] = mixing_virtual_tool_mix[tmp_extruder][j]; } #endif // MIXING_EXTRUDER && MIXING_VIRTUAL_TOOLS > 1 #if ENABLED(DUAL_X_CARRIAGE) inline void dualx_tool_change(const uint8_t tmp_extruder, bool &no_move) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPGM("Dual X Carriage Mode "); switch (dual_x_carriage_mode) { case DXC_FULL_CONTROL_MODE: SERIAL_ECHOLNPGM("DXC_FULL_CONTROL_MODE"); break; case DXC_AUTO_PARK_MODE: SERIAL_ECHOLNPGM("DXC_AUTO_PARK_MODE"); break; case DXC_DUPLICATION_MODE: SERIAL_ECHOLNPGM("DXC_DUPLICATION_MODE"); break; } } #endif const float xhome = x_home_pos(active_extruder); if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE && IsRunning() && (delayed_move_time || current_position[X_AXIS] != xhome) ) { float raised_z = current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT; #if ENABLED(MAX_SOFTWARE_ENDSTOPS) NOMORE(raised_z, soft_endstop_max[Z_AXIS]); #endif #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOLNPAIR("Raise to ", raised_z); SERIAL_ECHOLNPAIR("MoveX to ", xhome); SERIAL_ECHOLNPAIR("Lower to ", current_position[Z_AXIS]); } #endif // Park old head: 1) raise 2) move to park position 3) lower for (uint8_t i = 0; i < 3; i++) planner.buffer_line( i == 0 ? current_position[X_AXIS] : xhome, current_position[Y_AXIS], i == 2 ? current_position[Z_AXIS] : raised_z, current_position[E_CART], planner.max_feedrate_mm_s[i == 1 ? X_AXIS : Z_AXIS], active_extruder ); planner.synchronize(); } // Apply Y & Z extruder offset (X offset is used as home pos with Dual X) current_position[Y_AXIS] -= hotend_offset[Y_AXIS][active_extruder] - hotend_offset[Y_AXIS][tmp_extruder]; current_position[Z_AXIS] -= hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder]; // Activate the new extruder ahead of calling set_axis_is_at_home! active_extruder = tmp_extruder; // This function resets the max/min values - the current position may be overwritten below. set_axis_is_at_home(X_AXIS); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("New Extruder", current_position); #endif // Only when auto-parking are carriages safe to move if (dual_x_carriage_mode != DXC_AUTO_PARK_MODE) no_move = true; switch (dual_x_carriage_mode) { case DXC_FULL_CONTROL_MODE: // New current position is the position of the activated extruder current_position[X_AXIS] = inactive_extruder_x_pos; // Save the inactive extruder's position (from the old current_position) inactive_extruder_x_pos = destination[X_AXIS]; break; case DXC_AUTO_PARK_MODE: // record raised toolhead position for use by unpark COPY(raised_parked_position, current_position); raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT; #if ENABLED(MAX_SOFTWARE_ENDSTOPS) NOMORE(raised_parked_position[Z_AXIS], soft_endstop_max[Z_AXIS]); #endif active_extruder_parked = true; delayed_move_time = 0; break; case DXC_DUPLICATION_MODE: // If the new extruder is the left one, set it "parked" // This triggers the second extruder to move into the duplication position active_extruder_parked = (active_extruder == 0); current_position[X_AXIS] = active_extruder_parked ? inactive_extruder_x_pos : destination[X_AXIS] + duplicate_extruder_x_offset; inactive_extruder_x_pos = destination[X_AXIS]; extruder_duplication_enabled = false; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOLNPAIR("Set inactive_extruder_x_pos=", inactive_extruder_x_pos); SERIAL_ECHOLNPGM("Clear extruder_duplication_enabled"); } #endif break; } #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOLNPAIR("Active extruder parked: ", active_extruder_parked ? "yes" : "no"); DEBUG_POS("New extruder (parked)", current_position); } #endif // No extra case for HAS_ABL in DUAL_X_CARRIAGE. Does that mean they don't work together? } #endif // DUAL_X_CARRIAGE #if ENABLED(PARKING_EXTRUDER) inline void parking_extruder_tool_change(const uint8_t tmp_extruder, bool no_move) { constexpr float z_raise = PARKING_EXTRUDER_SECURITY_RAISE; if (!no_move) { const float parkingposx[] = PARKING_EXTRUDER_PARKING_X, midpos = (parkingposx[0] + parkingposx[1]) * 0.5 + hotend_offset[X_AXIS][active_extruder], grabpos = parkingposx[tmp_extruder] + hotend_offset[X_AXIS][active_extruder] + (tmp_extruder == 0 ? -(PARKING_EXTRUDER_GRAB_DISTANCE) : PARKING_EXTRUDER_GRAB_DISTANCE); /** * Steps: * 1. Raise Z-Axis to give enough clearance * 2. Move to park position of old extruder * 3. Disengage magnetic field, wait for delay * 4. Move near new extruder * 5. Engage magnetic field for new extruder * 6. Move to parking incl. offset of new extruder * 7. Lower Z-Axis */ // STEP 1 #if ENABLED(DEBUG_LEVELING_FEATURE) SERIAL_ECHOLNPGM("Starting Autopark"); if (DEBUGGING(LEVELING)) DEBUG_POS("current position:", current_position); #endif current_position[Z_AXIS] += z_raise; #if ENABLED(DEBUG_LEVELING_FEATURE) SERIAL_ECHOLNPGM("(1) Raise Z-Axis "); if (DEBUGGING(LEVELING)) DEBUG_POS("Moving to Raised Z-Position", current_position); #endif planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder); planner.synchronize(); // STEP 2 current_position[X_AXIS] = parkingposx[active_extruder] + hotend_offset[X_AXIS][active_extruder]; #if ENABLED(DEBUG_LEVELING_FEATURE) SERIAL_ECHOLNPAIR("(2) Park extruder ", active_extruder); if (DEBUGGING(LEVELING)) DEBUG_POS("Moving ParkPos", current_position); #endif planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS], active_extruder); planner.synchronize(); // STEP 3 #if ENABLED(DEBUG_LEVELING_FEATURE) SERIAL_ECHOLNPGM("(3) Disengage magnet "); #endif pe_deactivate_magnet(active_extruder); // STEP 4 #if ENABLED(DEBUG_LEVELING_FEATURE) SERIAL_ECHOLNPGM("(4) Move to position near new extruder"); #endif current_position[X_AXIS] += (active_extruder == 0 ? 10 : -10); // move 10mm away from parked extruder #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("Moving away from parked extruder", current_position); #endif planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS], active_extruder); planner.synchronize(); // STEP 5 #if ENABLED(DEBUG_LEVELING_FEATURE) SERIAL_ECHOLNPGM("(5) Engage magnetic field"); #endif #if ENABLED(PARKING_EXTRUDER_SOLENOIDS_INVERT) pe_activate_magnet(active_extruder); //just save power for inverted magnets #endif pe_activate_magnet(tmp_extruder); // STEP 6 current_position[X_AXIS] = grabpos + (tmp_extruder == 0 ? (+10) : (-10)); planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS], active_extruder); current_position[X_AXIS] = grabpos; #if ENABLED(DEBUG_LEVELING_FEATURE) SERIAL_ECHOLNPAIR("(6) Unpark extruder ", tmp_extruder); if (DEBUGGING(LEVELING)) DEBUG_POS("Move UnparkPos", current_position); #endif planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS]/2, active_extruder); planner.synchronize(); // Step 7 current_position[X_AXIS] = midpos - hotend_offset[X_AXIS][tmp_extruder]; #if ENABLED(DEBUG_LEVELING_FEATURE) SERIAL_ECHOLNPGM("(7) Move midway between hotends"); if (DEBUGGING(LEVELING)) DEBUG_POS("Move midway to new extruder", current_position); #endif planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS], active_extruder); planner.synchronize(); #if ENABLED(DEBUG_LEVELING_FEATURE) SERIAL_ECHOLNPGM("Autopark done."); #endif } else { // nomove == true // Only engage magnetic field for new extruder pe_activate_magnet(tmp_extruder); #if ENABLED(PARKING_EXTRUDER_SOLENOIDS_INVERT) pe_activate_magnet(active_extruder); // Just save power for inverted magnets #endif } current_position[Z_AXIS] += hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder]; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("Applying Z-offset", current_position); #endif } #endif // PARKING_EXTRUDER /** * Perform a tool-change, which may result in moving the * previous tool out of the way and the new tool into place. */ void tool_change(const uint8_t tmp_extruder, const float fr_mm_s/*=0.0*/, bool no_move/*=false*/) { planner.synchronize(); #if HAS_LEVELING // Set current position to the physical position const bool leveling_was_active = planner.leveling_active; set_bed_leveling_enabled(false); #endif #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1 mixing_tool_change(tmp_extruder); #else // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1 if (tmp_extruder >= EXTRUDERS) return invalid_extruder_error(tmp_extruder); #if HOTENDS > 1 const float old_feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : feedrate_mm_s; feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S; if (tmp_extruder != active_extruder) { if (!no_move && axis_unhomed_error()) { no_move = true; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("No move on toolchange"); #endif } #if ENABLED(DUAL_X_CARRIAGE) #if HAS_SOFTWARE_ENDSTOPS // Update the X software endstops early active_extruder = tmp_extruder; update_software_endstops(X_AXIS); active_extruder = !tmp_extruder; #endif // Don't move the new extruder out of bounds if (!WITHIN(current_position[X_AXIS], soft_endstop_min[X_AXIS], soft_endstop_max[X_AXIS])) no_move = true; if (!no_move) set_destination_from_current(); dualx_tool_change(tmp_extruder, no_move); // Can modify no_move #else // !DUAL_X_CARRIAGE set_destination_from_current(); #if ENABLED(PARKING_EXTRUDER) parking_extruder_tool_change(tmp_extruder, no_move); #endif #if ENABLED(SWITCHING_NOZZLE) // Always raise by at least 1 to avoid workpiece const float zdiff = hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder]; current_position[Z_AXIS] += (zdiff > 0.0 ? zdiff : 0.0) + 1; planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder); move_nozzle_servo(tmp_extruder); #endif const float xdiff = hotend_offset[X_AXIS][tmp_extruder] - hotend_offset[X_AXIS][active_extruder], ydiff = hotend_offset[Y_AXIS][tmp_extruder] - hotend_offset[Y_AXIS][active_extruder]; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("Offset Tool XY by { ", xdiff); SERIAL_ECHOPAIR(", ", ydiff); SERIAL_ECHOLNPGM(" }"); } #endif // The newly-selected extruder XY is actually at... current_position[X_AXIS] += xdiff; current_position[Y_AXIS] += ydiff; // Set the new active extruder active_extruder = tmp_extruder; #endif // !DUAL_X_CARRIAGE #if ENABLED(SWITCHING_NOZZLE) // The newly-selected extruder Z is actually at... current_position[Z_AXIS] -= zdiff; #endif // Tell the planner the new "current position" SYNC_PLAN_POSITION_KINEMATIC(); #if ENABLED(DELTA) //LOOP_XYZ(i) update_software_endstops(i); // or modify the constrain function const bool safe_to_move = current_position[Z_AXIS] < delta_clip_start_height - 1; #else constexpr bool safe_to_move = true; #endif // Raise, move, and lower again if (safe_to_move && !no_move && IsRunning()) { #if DISABLED(SWITCHING_NOZZLE) // Do a small lift to avoid the workpiece in the move back (below) current_position[Z_AXIS] += 1.0; planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder); #endif #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("Move back", destination); #endif // Move back to the original (or tweaked) position do_blocking_move_to(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS]); #if ENABLED(DUAL_X_CARRIAGE) active_extruder_parked = false; #endif } #if ENABLED(SWITCHING_NOZZLE) else { // Move back down. (Including when the new tool is higher.) do_blocking_move_to_z(destination[Z_AXIS], planner.max_feedrate_mm_s[Z_AXIS]); } #endif } // (tmp_extruder != active_extruder) planner.synchronize(); #if ENABLED(EXT_SOLENOID) && !ENABLED(PARKING_EXTRUDER) disable_all_solenoids(); enable_solenoid_on_active_extruder(); #endif feedrate_mm_s = old_feedrate_mm_s; #if HAS_SOFTWARE_ENDSTOPS && ENABLED(DUAL_X_CARRIAGE) update_software_endstops(X_AXIS); #endif #else // HOTENDS <= 1 UNUSED(fr_mm_s); UNUSED(no_move); #if ENABLED(MK2_MULTIPLEXER) if (tmp_extruder >= E_STEPPERS) return invalid_extruder_error(tmp_extruder); select_multiplexed_stepper(tmp_extruder); #endif // Set the new active extruder active_extruder = tmp_extruder; #endif // HOTENDS <= 1 #if DO_SWITCH_EXTRUDER planner.synchronize(); move_extruder_servo(active_extruder); #endif #if HAS_FANMUX fanmux_switch(active_extruder); #endif #if HAS_LEVELING // Restore leveling to re-establish the logical position set_bed_leveling_enabled(leveling_was_active); #endif SERIAL_ECHO_START(); SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, int(active_extruder)); #endif // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1 } /** * T0-T3: Switch tool, usually switching extruders * * F[units/min] Set the movement feedrate * S1 Don't move the tool in XY after change */ inline void gcode_T(const uint8_t tmp_extruder) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR(">>> gcode_T(", tmp_extruder); SERIAL_CHAR(')'); SERIAL_EOL(); DEBUG_POS("BEFORE", current_position); } #endif #if HOTENDS == 1 || (ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1) tool_change(tmp_extruder); #elif HOTENDS > 1 tool_change( tmp_extruder, MMM_TO_MMS(parser.linearval('F')), (tmp_extruder == active_extruder) || parser.boolval('S') ); #endif #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { DEBUG_POS("AFTER", current_position); SERIAL_ECHOLNPGM("<<< gcode_T"); } #endif } /** * Process the parsed command and dispatch it to its handler */ void process_parsed_command() { KEEPALIVE_STATE(IN_HANDLER); // Handle a known G, M, or T switch (parser.command_letter) { case 'G': switch (parser.codenum) { case 0: case 1: gcode_G0_G1( // G0: Fast Move, G1: Linear Move #if IS_SCARA parser.codenum == 0 #endif ); break; #if ENABLED(ARC_SUPPORT) && DISABLED(SCARA) case 2: case 3: gcode_G2_G3(parser.codenum == 2); break; // G2: CW ARC, G3: CCW ARC #endif case 4: gcode_G4(); break; // G4: Dwell #if ENABLED(BEZIER_CURVE_SUPPORT) case 5: gcode_G5(); break; // G5: Cubic B_spline #endif #if ENABLED(UNREGISTERED_MOVE_SUPPORT) case 6: gcode_G6(); break; // G6: Direct stepper move #endif #if ENABLED(FWRETRACT) case 10: gcode_G10(); break; // G10: Retract case 11: gcode_G11(); break; // G11: Prime #endif #if ENABLED(NOZZLE_CLEAN_FEATURE) case 12: gcode_G12(); break; // G12: Clean Nozzle #endif #if ENABLED(CNC_WORKSPACE_PLANES) case 17: gcode_G17(); break; // G17: Select Plane XY case 18: gcode_G18(); break; // G18: Select Plane ZX case 19: gcode_G19(); break; // G19: Select Plane YZ #endif #if ENABLED(INCH_MODE_SUPPORT) case 20: gcode_G20(); break; // G20: Inch Units case 21: gcode_G21(); break; // G21: Millimeter Units #endif #if ENABLED(G26_MESH_VALIDATION) case 26: gcode_G26(); break; // G26: Mesh Validation Pattern #endif #if ENABLED(NOZZLE_PARK_FEATURE) case 27: gcode_G27(); break; // G27: Park Nozzle #endif case 28: gcode_G28(false); break; // G28: Home one or more axes #if HAS_LEVELING case 29: gcode_G29(); break; // G29: Detailed Z probe #endif #if HAS_BED_PROBE case 30: gcode_G30(); break; // G30: Single Z probe #endif #if ENABLED(Z_PROBE_SLED) case 31: gcode_G31(); break; // G31: Dock sled case 32: gcode_G32(); break; // G32: Undock sled #endif #if ENABLED(DELTA_AUTO_CALIBRATION) case 33: gcode_G33(); break; // G33: Delta Auto-Calibration #endif #if ENABLED(G38_PROBE_TARGET) case 38: if (parser.subcode == 2 || parser.subcode == 3) gcode_G38(parser.subcode == 2); // G38.2, G38.3: Probe towards object break; #endif #if HAS_MESH case 42: gcode_G42(); break; // G42: Move to mesh point #endif case 90: relative_mode = false; break; // G90: Absolute coordinates case 91: relative_mode = true; break; // G91: Relative coordinates case 92: gcode_G92(); break; // G92: Set Position #if ENABLED(MECHADUINO_I2C_COMMANDS) case 95: gcode_G95(); break; // G95: Set torque mode case 96: gcode_G96(); break; // G96: Mark encoder reference point #endif #if ENABLED(DEBUG_GCODE_PARSER) case 800: parser.debug(); break; // G800: GCode Parser Test for G #endif default: parser.unknown_command_error(); } break; case 'M': switch (parser.codenum) { #if HAS_RESUME_CONTINUE case 0: case 1: gcode_M0_M1(); break; // M0: Unconditional stop, M1: Conditional stop #endif #if ENABLED(SPINDLE_LASER_ENABLE) case 3: gcode_M3_M4(true); break; // M3: Laser/CW-Spindle Power case 4: gcode_M3_M4(false); break; // M4: Laser/CCW-Spindle Power case 5: gcode_M5(); break; // M5: Laser/Spindle OFF #endif case 17: gcode_M17(); break; // M17: Enable all steppers #if ENABLED(SDSUPPORT) case 20: gcode_M20(); break; // M20: List SD Card case 21: gcode_M21(); break; // M21: Init SD Card case 22: gcode_M22(); break; // M22: Release SD Card case 23: gcode_M23(); break; // M23: Select File case 24: gcode_M24(); break; // M24: Start SD Print case 25: gcode_M25(); break; // M25: Pause SD Print case 26: gcode_M26(); break; // M26: Set SD Index case 27: gcode_M27(); break; // M27: Get SD Status case 28: gcode_M28(); break; // M28: Start SD Write case 29: gcode_M29(); break; // M29: Stop SD Write case 30: gcode_M30(); break; // M30: Delete File case 32: gcode_M32(); break; // M32: Select file, Start SD Print #if ENABLED(LONG_FILENAME_HOST_SUPPORT) case 33: gcode_M33(); break; // M33: Report longname path #endif #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE) case 34: gcode_M34(); break; // M34: Set SD card sorting options #endif case 928: gcode_M928(); break; // M928: Start SD write #endif // SDSUPPORT case 31: gcode_M31(); break; // M31: Report print job elapsed time case 42: gcode_M42(); break; // M42: Change pin state #if ENABLED(PINS_DEBUGGING) case 43: gcode_M43(); break; // M43: Read/monitor pin and endstop states #endif #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST) case 48: gcode_M48(); break; // M48: Z probe repeatability test #endif #if ENABLED(G26_MESH_VALIDATION) case 49: gcode_M49(); break; // M49: Toggle the G26 Debug Flag #endif #if ENABLED(ULTRA_LCD) && ENABLED(LCD_SET_PROGRESS_MANUALLY) case 73: gcode_M73(); break; // M73: Set Print Progress % #endif case 75: gcode_M75(); break; // M75: Start Print Job Timer case 76: gcode_M76(); break; // M76: Pause Print Job Timer case 77: gcode_M77(); break; // M77: Stop Print Job Timer #if ENABLED(PRINTCOUNTER) case 78: gcode_M78(); break; // M78: Report Print Statistics #endif #if ENABLED(M100_FREE_MEMORY_WATCHER) case 100: gcode_M100(); break; // M100: Free Memory Report #endif case 104: gcode_M104(); break; // M104: Set Hotend Temperature case 110: gcode_M110(); break; // M110: Set Current Line Number case 111: gcode_M111(); break; // M111: Set Debug Flags #if DISABLED(EMERGENCY_PARSER) case 108: gcode_M108(); break; // M108: Cancel Waiting case 112: gcode_M112(); break; // M112: Emergency Stop case 410: gcode_M410(); break; // M410: Quickstop. Abort all planned moves #else case 108: case 112: case 410: break; // Silently drop as handled by emergency parser #endif #if ENABLED(HOST_KEEPALIVE_FEATURE) case 113: gcode_M113(); break; // M113: Set Host Keepalive Interval #endif case 105: gcode_M105(); KEEPALIVE_STATE(NOT_BUSY); return; // M105: Report Temperatures (and say "ok") #if ENABLED(AUTO_REPORT_TEMPERATURES) case 155: gcode_M155(); break; // M155: Set Temperature Auto-report Interval #endif case 109: gcode_M109(); break; // M109: Set Hotend Temperature. Wait for target. #if HAS_HEATED_BED case 140: gcode_M140(); break; // M140: Set Bed Temperature case 190: gcode_M190(); break; // M190: Set Bed Temperature. Wait for target. #endif #if FAN_COUNT > 0 case 106: gcode_M106(); break; // M106: Set Fan Speed case 107: gcode_M107(); break; // M107: Fan Off #endif #if ENABLED(PARK_HEAD_ON_PAUSE) case 125: gcode_M125(); break; // M125: Park (for Filament Change) #endif #if ENABLED(BARICUDA) #if HAS_HEATER_1 case 126: gcode_M126(); break; // M126: Valve 1 Open case 127: gcode_M127(); break; // M127: Valve 1 Closed #endif #if HAS_HEATER_2 case 128: gcode_M128(); break; // M128: Valve 2 Open case 129: gcode_M129(); break; // M129: Valve 2 Closed #endif #endif #if HAS_POWER_SWITCH case 80: gcode_M80(); break; // M80: Turn on Power Supply #endif case 81: gcode_M81(); break; // M81: Turn off Power and Power Supply case 82: gcode_M82(); break; // M82: Disable Relative E-Axis case 83: gcode_M83(); break; // M83: Set Relative E-Axis case 18: case 84: gcode_M18_M84(); break; // M18/M84: Disable Steppers / Set Timeout case 85: gcode_M85(); break; // M85: Set inactivity stepper shutdown timeout case 92: gcode_M92(); break; // M92: Set steps-per-unit case 114: gcode_M114(); break; // M114: Report Current Position case 115: gcode_M115(); break; // M115: Capabilities Report case 117: gcode_M117(); break; // M117: Set LCD message text case 118: gcode_M118(); break; // M118: Print a message in the host console case 119: gcode_M119(); break; // M119: Report Endstop states case 120: gcode_M120(); break; // M120: Enable Endstops case 121: gcode_M121(); break; // M121: Disable Endstops #if ENABLED(ULTIPANEL) case 145: gcode_M145(); break; // M145: Set material heatup parameters #endif #if ENABLED(TEMPERATURE_UNITS_SUPPORT) case 149: gcode_M149(); break; // M149: Set Temperature Units, C F K #endif #if HAS_COLOR_LEDS case 150: gcode_M150(); break; // M150: Set Status LED Color #endif #if ENABLED(MIXING_EXTRUDER) case 163: gcode_M163(); break; // M163: Set Mixing Component #if MIXING_VIRTUAL_TOOLS > 1 case 164: gcode_M164(); break; // M164: Save Current Mix #endif #if ENABLED(DIRECT_MIXING_IN_G1) case 165: gcode_M165(); break; // M165: Set Multiple Mixing Components #endif #endif #if DISABLED(NO_VOLUMETRICS) case 200: gcode_M200(); break; // M200: Set Filament Diameter, Volumetric Extrusion #endif case 201: gcode_M201(); break; // M201: Set Max Printing Acceleration (units/sec^2) #if 0 case 202: gcode_M202(); break; // M202: Not used for Sprinter/grbl gen6 #endif case 203: gcode_M203(); break; // M203: Set Max Feedrate (units/sec) case 204: gcode_M204(); break; // M204: Set Acceleration case 205: gcode_M205(); break; // M205: Set Advanced settings #if HAS_M206_COMMAND case 206: gcode_M206(); break; // M206: Set Home Offsets case 428: gcode_M428(); break; // M428: Set Home Offsets based on current position #endif #if ENABLED(FWRETRACT) case 207: gcode_M207(); break; // M207: Set Retract Length, Feedrate, Z lift case 208: gcode_M208(); break; // M208: Set Additional Prime Length and Feedrate case 209: if (MIN_AUTORETRACT <= MAX_AUTORETRACT) gcode_M209(); // M209: Turn Auto-Retract on/off break; #endif case 211: gcode_M211(); break; // M211: Enable/Disable/Report Software Endstops #if HOTENDS > 1 case 218: gcode_M218(); break; // M218: Set Tool Offset #endif case 220: gcode_M220(); break; // M220: Set Feedrate Percentage case 221: gcode_M221(); break; // M221: Set Flow Percentage case 226: gcode_M226(); break; // M226: Wait for Pin State #if defined(CHDK) || HAS_PHOTOGRAPH case 240: gcode_M240(); break; // M240: Trigger Camera #endif #if HAS_LCD_CONTRAST case 250: gcode_M250(); break; // M250: Set LCD Contrast #endif #if ENABLED(EXPERIMENTAL_I2CBUS) case 260: gcode_M260(); break; // M260: Send Data to i2c slave case 261: gcode_M261(); break; // M261: Request Data from i2c slave #endif #if HAS_SERVOS case 280: gcode_M280(); break; // M280: Set Servo Position #endif #if ENABLED(BABYSTEPPING) case 290: gcode_M290(); break; // M290: Babystepping #endif #if HAS_BUZZER case 300: gcode_M300(); break; // M300: Add Tone/Buzz to Queue #endif #if ENABLED(PIDTEMP) case 301: gcode_M301(); break; // M301: Set Hotend PID parameters #endif #if ENABLED(PREVENT_COLD_EXTRUSION) case 302: gcode_M302(); break; // M302: Set Minimum Extrusion Temp #endif case 303: gcode_M303(); break; // M303: PID Autotune #if ENABLED(PIDTEMPBED) case 304: gcode_M304(); break; // M304: Set Bed PID parameters #endif #if HAS_MICROSTEPS case 350: gcode_M350(); break; // M350: Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers. case 351: gcode_M351(); break; // M351: Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low. #endif case 355: gcode_M355(); break; // M355: Set Case Light brightness #if ENABLED(MORGAN_SCARA) case 360: if (gcode_M360()) return; break; // M360: SCARA Theta pos1 case 361: if (gcode_M361()) return; break; // M361: SCARA Theta pos2 case 362: if (gcode_M362()) return; break; // M362: SCARA Psi pos1 case 363: if (gcode_M363()) return; break; // M363: SCARA Psi pos2 case 364: if (gcode_M364()) return; break; // M364: SCARA Psi pos3 (90 deg to Theta) #endif case 400: gcode_M400(); break; // M400: Synchronize. Wait for moves to finish. #if HAS_BED_PROBE case 401: gcode_M401(); break; // M401: Deploy Probe case 402: gcode_M402(); break; // M402: Stow Probe #endif #if ENABLED(FILAMENT_WIDTH_SENSOR) case 404: gcode_M404(); break; // M404: Set/Report Nominal Filament Width case 405: gcode_M405(); break; // M405: Enable Filament Width Sensor case 406: gcode_M406(); break; // M406: Disable Filament Width Sensor case 407: gcode_M407(); break; // M407: Report Measured Filament Width #endif #if HAS_LEVELING case 420: gcode_M420(); break; // M420: Set Bed Leveling Enabled / Fade #endif #if HAS_MESH case 421: gcode_M421(); break; // M421: Set a Mesh Z value #endif case 500: gcode_M500(); break; // M500: Store Settings in EEPROM case 501: gcode_M501(); break; // M501: Read Settings from EEPROM case 502: gcode_M502(); break; // M502: Revert Settings to defaults #if DISABLED(DISABLE_M503) case 503: gcode_M503(); break; // M503: Report Settings (in SRAM) #endif #if ENABLED(EEPROM_SETTINGS) case 504: gcode_M504(); break; // M504: Validate EEPROM #endif #if ENABLED(SDSUPPORT) case 524: gcode_M524(); break; // M524: Abort SD print job #endif #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED) case 540: gcode_M540(); break; // M540: Set Abort on Endstop Hit for SD Printing #endif #if ENABLED(ADVANCED_PAUSE_FEATURE) case 600: gcode_M600(); break; // M600: Pause for Filament Change case 603: gcode_M603(); break; // M603: Configure Filament Change #endif #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE) case 605: gcode_M605(); break; // M605: Set Dual X Carriage movement mode #endif #if ENABLED(DELTA) || ENABLED(HANGPRINTER) case 665: gcode_M665(); break; // M665: Delta / Hangprinter Configuration #endif #if ENABLED(DELTA) || ENABLED(X_DUAL_ENDSTOPS) || ENABLED(Y_DUAL_ENDSTOPS) || ENABLED(Z_DUAL_ENDSTOPS) case 666: gcode_M666(); break; // M666: DELTA/Dual Endstop Adjustment #endif #if ENABLED(FILAMENT_LOAD_UNLOAD_GCODES) case 701: gcode_M701(); break; // M701: Load Filament case 702: gcode_M702(); break; // M702: Unload Filament #endif #if ENABLED(MAX7219_GCODE) case 7219: gcode_M7219(); break; // M7219: Set LEDs, columns, and rows #endif #if ENABLED(DEBUG_GCODE_PARSER) case 800: parser.debug(); break; // M800: GCode Parser Test for M #endif #if HAS_BED_PROBE case 851: gcode_M851(); break; // M851: Set Z Probe Z Offset #endif #if ENABLED(SKEW_CORRECTION_GCODE) case 852: gcode_M852(); break; // M852: Set Skew factors #endif #if ENABLED(I2C_POSITION_ENCODERS) case 860: gcode_M860(); break; // M860: Report encoder module position case 861: gcode_M861(); break; // M861: Report encoder module status case 862: gcode_M862(); break; // M862: Perform axis test case 863: gcode_M863(); break; // M863: Calibrate steps/mm case 864: gcode_M864(); break; // M864: Change module address case 865: gcode_M865(); break; // M865: Check module firmware version case 866: gcode_M866(); break; // M866: Report axis error count case 867: gcode_M867(); break; // M867: Toggle error correction case 868: gcode_M868(); break; // M868: Set error correction threshold case 869: gcode_M869(); break; // M869: Report axis error #endif case 888: gcode_M888(); break; // M888: Ultrabase cooldown (EXPERIMENTAL) #if ENABLED(LIN_ADVANCE) case 900: gcode_M900(); break; // M900: Set Linear Advance K factor #endif case 907: gcode_M907(); break; // M907: Set Digital Trimpot Motor Current using axis codes. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT) case 908: gcode_M908(); break; // M908: Direct Control Digital Trimpot #if ENABLED(DAC_STEPPER_CURRENT) case 909: gcode_M909(); break; // M909: Print Digipot/DAC current value (As with Printrbot RevF) case 910: gcode_M910(); break; // M910: Commit Digipot/DAC value to External EEPROM (As with Printrbot RevF) #endif #endif #if HAS_DRIVER(TMC2130) || HAS_DRIVER(TMC2208) #if ENABLED(TMC_DEBUG) case 122: gcode_M122(); break; // M122: Debug TMC steppers #endif case 906: gcode_M906(); break; // M906: Set motor current in milliamps using axis codes X, Y, Z, E case 911: gcode_M911(); break; // M911: Report TMC prewarn triggered flags case 912: gcode_M912(); break; // M911: Clear TMC prewarn triggered flags #if ENABLED(HYBRID_THRESHOLD) case 913: gcode_M913(); break; // M913: Set HYBRID_THRESHOLD speed. #endif #if ENABLED(SENSORLESS_HOMING) case 914: gcode_M914(); break; // M914: Set SENSORLESS_HOMING sensitivity. #endif #if ENABLED(TMC_Z_CALIBRATION) case 915: gcode_M915(); break; // M915: TMC Z axis calibration routine #endif #endif case 999: gcode_M999(); break; // M999: Restart after being Stopped default: parser.unknown_command_error(); } break; case 'T': gcode_T(parser.codenum); break; // T: Tool Select default: parser.unknown_command_error(); } KEEPALIVE_STATE(NOT_BUSY); ok_to_send(); } void process_next_command() { char * const current_command = command_queue[cmd_queue_index_r]; if (DEBUGGING(ECHO)) { SERIAL_ECHO_START(); SERIAL_ECHOLN(current_command); #if ENABLED(M100_FREE_MEMORY_WATCHER) SERIAL_ECHOPAIR("slot:", cmd_queue_index_r); M100_dump_routine(" Command Queue:", (const char*)command_queue, (const char*)(command_queue + sizeof(command_queue))); #endif } // Parse the next command in the queue parser.parse(current_command); process_parsed_command(); } /** * Send a "Resend: nnn" message to the host to * indicate that a command needs to be re-sent. */ void flush_and_request_resend() { //char command_queue[cmd_queue_index_r][100]="Resend:"; SERIAL_FLUSH(); SERIAL_PROTOCOLPGM(MSG_RESEND); SERIAL_PROTOCOLLN(gcode_LastN + 1); ok_to_send(); } /** * Send an "ok" message to the host, indicating * that a command was successfully processed. * * If ADVANCED_OK is enabled also include: * N<int> Line number of the command, if any * P<int> Planner space remaining * B<int> Block queue space remaining */ void ok_to_send() { if (!send_ok[cmd_queue_index_r]) return; SERIAL_PROTOCOLPGM(MSG_OK); #if ENABLED(ADVANCED_OK) char* p = command_queue[cmd_queue_index_r]; if (*p == 'N') { SERIAL_PROTOCOL(' '); SERIAL_ECHO(*p++); while (NUMERIC_SIGNED(*p)) SERIAL_ECHO(*p++); } SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1)); SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue); #endif SERIAL_EOL(); } #if HAS_SOFTWARE_ENDSTOPS /** * Constrain the given coordinates to the software endstops. * * For DELTA/SCARA the XY constraint is based on the smallest * radius within the set software endstops. */ void clamp_to_software_endstops(float target[XYZ]) { if (!soft_endstops_enabled) return; #if IS_KINEMATIC const float dist_2 = HYPOT2(target[X_AXIS], target[Y_AXIS]); if (dist_2 > soft_endstop_radius_2) { const float ratio = soft_endstop_radius / SQRT(dist_2); // 200 / 300 = 0.66 target[X_AXIS] *= ratio; target[Y_AXIS] *= ratio; } #else #if ENABLED(MIN_SOFTWARE_ENDSTOP_X) NOLESS(target[X_AXIS], soft_endstop_min[X_AXIS]); #endif #if ENABLED(MIN_SOFTWARE_ENDSTOP_Y) NOLESS(target[Y_AXIS], soft_endstop_min[Y_AXIS]); #endif #if ENABLED(MAX_SOFTWARE_ENDSTOP_X) NOMORE(target[X_AXIS], soft_endstop_max[X_AXIS]); #endif #if ENABLED(MAX_SOFTWARE_ENDSTOP_Y) NOMORE(target[Y_AXIS], soft_endstop_max[Y_AXIS]); #endif #endif #if ENABLED(MIN_SOFTWARE_ENDSTOP_Z) NOLESS(target[Z_AXIS], soft_endstop_min[Z_AXIS]); #endif #if ENABLED(MAX_SOFTWARE_ENDSTOP_Z) NOMORE(target[Z_AXIS], soft_endstop_max[Z_AXIS]); #endif } #endif #if ENABLED(AUTO_BED_LEVELING_BILINEAR) // Get the Z adjustment for non-linear bed leveling float bilinear_z_offset(const float raw[XYZ]) { static float z1, d2, z3, d4, L, D, ratio_x, ratio_y, last_x = -999.999, last_y = -999.999; // Whole units for the grid line indices. Constrained within bounds. static int8_t gridx, gridy, nextx, nexty, last_gridx = -99, last_gridy = -99; // XY relative to the probed area const float rx = raw[X_AXIS] - bilinear_start[X_AXIS], ry = raw[Y_AXIS] - bilinear_start[Y_AXIS]; #if ENABLED(EXTRAPOLATE_BEYOND_GRID) // Keep using the last grid box #define FAR_EDGE_OR_BOX 2 #else // Just use the grid far edge #define FAR_EDGE_OR_BOX 1 #endif if (last_x != rx) { last_x = rx; ratio_x = rx * ABL_BG_FACTOR(X_AXIS); const float gx = constrain(FLOOR(ratio_x), 0, ABL_BG_POINTS_X - FAR_EDGE_OR_BOX); ratio_x -= gx; // Subtract whole to get the ratio within the grid box #if DISABLED(EXTRAPOLATE_BEYOND_GRID) // Beyond the grid maintain height at grid edges NOLESS(ratio_x, 0); // Never < 0.0. (> 1.0 is ok when nextx==gridx.) #endif gridx = gx; nextx = MIN(gridx + 1, ABL_BG_POINTS_X - 1); } if (last_y != ry || last_gridx != gridx) { if (last_y != ry) { last_y = ry; ratio_y = ry * ABL_BG_FACTOR(Y_AXIS); const float gy = constrain(FLOOR(ratio_y), 0, ABL_BG_POINTS_Y - FAR_EDGE_OR_BOX); ratio_y -= gy; #if DISABLED(EXTRAPOLATE_BEYOND_GRID) // Beyond the grid maintain height at grid edges NOLESS(ratio_y, 0); // Never < 0.0. (> 1.0 is ok when nexty==gridy.) #endif gridy = gy; nexty = MIN(gridy + 1, ABL_BG_POINTS_Y - 1); } if (last_gridx != gridx || last_gridy != gridy) { last_gridx = gridx; last_gridy = gridy; // Z at the box corners z1 = ABL_BG_GRID(gridx, gridy); // left-front d2 = ABL_BG_GRID(gridx, nexty) - z1; // left-back (delta) z3 = ABL_BG_GRID(nextx, gridy); // right-front d4 = ABL_BG_GRID(nextx, nexty) - z3; // right-back (delta) } // Bilinear interpolate. Needed since ry or gridx has changed. L = z1 + d2 * ratio_y; // Linear interp. LF -> LB const float R = z3 + d4 * ratio_y; // Linear interp. RF -> RB D = R - L; } const float offset = L + ratio_x * D; // the offset almost always changes /* static float last_offset = 0; if (ABS(last_offset - offset) > 0.2) { SERIAL_ECHOPGM("Sudden Shift at "); SERIAL_ECHOPAIR("x=", rx); SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[X_AXIS]); SERIAL_ECHOLNPAIR(" -> gridx=", gridx); SERIAL_ECHOPAIR(" y=", ry); SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[Y_AXIS]); SERIAL_ECHOLNPAIR(" -> gridy=", gridy); SERIAL_ECHOPAIR(" ratio_x=", ratio_x); SERIAL_ECHOLNPAIR(" ratio_y=", ratio_y); SERIAL_ECHOPAIR(" z1=", z1); SERIAL_ECHOPAIR(" z2=", z2); SERIAL_ECHOPAIR(" z3=", z3); SERIAL_ECHOLNPAIR(" z4=", z4); SERIAL_ECHOPAIR(" L=", L); SERIAL_ECHOPAIR(" R=", R); SERIAL_ECHOLNPAIR(" offset=", offset); } last_offset = offset; //*/ return offset; } #endif // AUTO_BED_LEVELING_BILINEAR #if ENABLED(DELTA) /** * Recalculate factors used for delta kinematics whenever * settings have been changed (e.g., by M665). */ void recalc_delta_settings() { const float trt[ABC] = DELTA_RADIUS_TRIM_TOWER, drt[ABC] = DELTA_DIAGONAL_ROD_TRIM_TOWER; delta_tower[A_AXIS][X_AXIS] = cos(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (delta_radius + trt[A_AXIS]); // front left tower delta_tower[A_AXIS][Y_AXIS] = sin(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (delta_radius + trt[A_AXIS]); delta_tower[B_AXIS][X_AXIS] = cos(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (delta_radius + trt[B_AXIS]); // front right tower delta_tower[B_AXIS][Y_AXIS] = sin(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (delta_radius + trt[B_AXIS]); delta_tower[C_AXIS][X_AXIS] = cos(RADIANS( 90 + delta_tower_angle_trim[C_AXIS])) * (delta_radius + trt[C_AXIS]); // back middle tower delta_tower[C_AXIS][Y_AXIS] = sin(RADIANS( 90 + delta_tower_angle_trim[C_AXIS])) * (delta_radius + trt[C_AXIS]); delta_diagonal_rod_2_tower[A_AXIS] = sq(delta_diagonal_rod + drt[A_AXIS]); delta_diagonal_rod_2_tower[B_AXIS] = sq(delta_diagonal_rod + drt[B_AXIS]); delta_diagonal_rod_2_tower[C_AXIS] = sq(delta_diagonal_rod + drt[C_AXIS]); update_software_endstops(Z_AXIS); axis_homed = 0; } /** * Delta Inverse Kinematics * * Calculate the tower positions for a given machine * position, storing the result in the delta[] array. * * This is an expensive calculation, requiring 3 square * roots per segmented linear move, and strains the limits * of a Mega2560 with a Graphical Display. * * Suggested optimizations include: * * - Disable the home_offset (M206) and/or position_shift (G92) * features to remove up to 12 float additions. */ #define DELTA_DEBUG(VAR) do { \ SERIAL_ECHOPAIR("cartesian X:", VAR[X_AXIS]); \ SERIAL_ECHOPAIR(" Y:", VAR[Y_AXIS]); \ SERIAL_ECHOLNPAIR(" Z:", VAR[Z_AXIS]); \ SERIAL_ECHOPAIR("delta A:", delta[A_AXIS]); \ SERIAL_ECHOPAIR(" B:", delta[B_AXIS]); \ SERIAL_ECHOLNPAIR(" C:", delta[C_AXIS]); \ }while(0) void inverse_kinematics(const float raw[XYZ]) { #if HOTENDS > 1 // Delta hotend offsets must be applied in Cartesian space with no "spoofing" const float pos[XYZ] = { raw[X_AXIS] - hotend_offset[X_AXIS][active_extruder], raw[Y_AXIS] - hotend_offset[Y_AXIS][active_extruder], raw[Z_AXIS] }; DELTA_IK(pos); //DELTA_DEBUG(pos); #else DELTA_IK(raw); //DELTA_DEBUG(raw); #endif } /** * Calculate the highest Z position where the * effector has the full range of XY motion. */ float delta_safe_distance_from_top() { float cartesian[XYZ] = { 0, 0, 0 }; inverse_kinematics(cartesian); const float centered_extent = delta[A_AXIS]; cartesian[Y_AXIS] = DELTA_PRINTABLE_RADIUS; inverse_kinematics(cartesian); return ABS(centered_extent - delta[A_AXIS]); } /** * Delta Forward Kinematics * * See the Wikipedia article "Trilateration" * https://en.wikipedia.org/wiki/Trilateration * * Establish a new coordinate system in the plane of the * three carriage points. This system has its origin at * tower1, with tower2 on the X axis. Tower3 is in the X-Y * plane with a Z component of zero. * We will define unit vectors in this coordinate system * in our original coordinate system. Then when we calculate * the Xnew, Ynew and Znew values, we can translate back into * the original system by moving along those unit vectors * by the corresponding values. * * Variable names matched to Marlin, c-version, and avoid the * use of any vector library. * * by Andreas Hardtung 2016-06-07 * based on a Java function from "Delta Robot Kinematics V3" * by Steve Graves * * The result is stored in the cartes[] array. */ void forward_kinematics_DELTA(const float &z1, const float &z2, const float &z3) { // Create a vector in old coordinates along x axis of new coordinate const float p12[] = { delta_tower[B_AXIS][X_AXIS] - delta_tower[A_AXIS][X_AXIS], delta_tower[B_AXIS][Y_AXIS] - delta_tower[A_AXIS][Y_AXIS], z2 - z1 }, // Get the reciprocal of Magnitude of vector. d2 = sq(p12[0]) + sq(p12[1]) + sq(p12[2]), inv_d = RSQRT(d2), // Create unit vector by multiplying by the inverse of the magnitude. ex[3] = { p12[0] * inv_d, p12[1] * inv_d, p12[2] * inv_d }, // Get the vector from the origin of the new system to the third point. p13[3] = { delta_tower[C_AXIS][X_AXIS] - delta_tower[A_AXIS][X_AXIS], delta_tower[C_AXIS][Y_AXIS] - delta_tower[A_AXIS][Y_AXIS], z3 - z1 }, // Use the dot product to find the component of this vector on the X axis. i = ex[0] * p13[0] + ex[1] * p13[1] + ex[2] * p13[2], // Create a vector along the x axis that represents the x component of p13. iex[] = { ex[0] * i, ex[1] * i, ex[2] * i }; // Subtract the X component from the original vector leaving only Y. We use the // variable that will be the unit vector after we scale it. float ey[3] = { p13[0] - iex[0], p13[1] - iex[1], p13[2] - iex[2] }; // The magnitude and the inverse of the magnitude of Y component const float j2 = sq(ey[0]) + sq(ey[1]) + sq(ey[2]), inv_j = RSQRT(j2); // Convert to a unit vector ey[0] *= inv_j; ey[1] *= inv_j; ey[2] *= inv_j; // The cross product of the unit x and y is the unit z // float[] ez = vectorCrossProd(ex, ey); const float ez[3] = { ex[1] * ey[2] - ex[2] * ey[1], ex[2] * ey[0] - ex[0] * ey[2], ex[0] * ey[1] - ex[1] * ey[0] }, // We now have the d, i and j values defined in Wikipedia. // Plug them into the equations defined in Wikipedia for Xnew, Ynew and Znew Xnew = (delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[B_AXIS] + d2) * inv_d * 0.5, Ynew = ((delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[C_AXIS] + sq(i) + j2) * 0.5 - i * Xnew) * inv_j, Znew = SQRT(delta_diagonal_rod_2_tower[A_AXIS] - HYPOT2(Xnew, Ynew)); // Start from the origin of the old coordinates and add vectors in the // old coords that represent the Xnew, Ynew and Znew to find the point // in the old system. cartes[X_AXIS] = delta_tower[A_AXIS][X_AXIS] + ex[0] * Xnew + ey[0] * Ynew - ez[0] * Znew; cartes[Y_AXIS] = delta_tower[A_AXIS][Y_AXIS] + ex[1] * Xnew + ey[1] * Ynew - ez[1] * Znew; cartes[Z_AXIS] = z1 + ex[2] * Xnew + ey[2] * Ynew - ez[2] * Znew; } void forward_kinematics_DELTA(const float (&point)[ABC]) { forward_kinematics_DELTA(point[A_AXIS], point[B_AXIS], point[C_AXIS]); } #endif // DELTA #if ENABLED(HANGPRINTER) /** * Recalculate factors used for hangprinter kinematics whenever * settings have been changed (e.g., by M665). */ void recalc_hangprinter_settings(){ HANGPRINTER_IK_ORIGIN(line_lengths_origin); #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE) const uint8_t mech_adv_tmp[MOV_AXIS] = MECHANICAL_ADVANTAGE, actn_pts_tmp[MOV_AXIS] = ACTION_POINTS; const uint16_t m_g_t_tmp[MOV_AXIS] = MOTOR_GEAR_TEETH, s_g_t_tmp[MOV_AXIS] = SPOOL_GEAR_TEETH; const float mnt_l_tmp[MOV_AXIS] = MOUNTED_LINE; float s_r2_tmp[MOV_AXIS] = SPOOL_RADII, steps_per_unit_times_r_tmp[MOV_AXIS]; uint8_t nr_lines_dir_tmp[MOV_AXIS]; LOOP_MOV_AXIS(i){ steps_per_unit_times_r_tmp[i] = (float(mech_adv_tmp[i])*STEPS_PER_MOTOR_REVOLUTION*s_g_t_tmp[i])/(2*M_PI*m_g_t_tmp[i]); nr_lines_dir_tmp[i] = mech_adv_tmp[i]*actn_pts_tmp[i]; s_r2_tmp[i] *= s_r2_tmp[i]; planner.k2[i] = -(float)nr_lines_dir_tmp[i]*SPOOL_BUILDUP_FACTOR; planner.k0[i] = 2.0*steps_per_unit_times_r_tmp[i]/planner.k2[i]; } // Assumes spools are mounted near D-anchor in ceiling #define HYP3D(x,y,z) SQRT(sq(x) + sq(y) + sq(z)) float line_on_spool_origin_tmp[MOV_AXIS]; line_on_spool_origin_tmp[A_AXIS] = actn_pts_tmp[A_AXIS] * mnt_l_tmp[A_AXIS] - actn_pts_tmp[A_AXIS] * HYPOT(anchor_A_y, anchor_D_z - anchor_A_z) - nr_lines_dir_tmp[A_AXIS] * line_lengths_origin[A_AXIS]; line_on_spool_origin_tmp[B_AXIS] = actn_pts_tmp[B_AXIS] * mnt_l_tmp[B_AXIS] - actn_pts_tmp[B_AXIS] * HYP3D(anchor_B_x, anchor_B_y, anchor_D_z - anchor_B_z) - nr_lines_dir_tmp[B_AXIS] * line_lengths_origin[B_AXIS]; line_on_spool_origin_tmp[C_AXIS] = actn_pts_tmp[C_AXIS] * mnt_l_tmp[C_AXIS] - actn_pts_tmp[C_AXIS] * HYP3D(anchor_C_x, anchor_C_y, anchor_D_z - anchor_C_z) - nr_lines_dir_tmp[C_AXIS] * line_lengths_origin[C_AXIS]; line_on_spool_origin_tmp[D_AXIS] = actn_pts_tmp[D_AXIS] * mnt_l_tmp[D_AXIS] - nr_lines_dir_tmp[D_AXIS] * line_lengths_origin[D_AXIS]; LOOP_MOV_AXIS(i) { planner.axis_steps_per_mm[i] = steps_per_unit_times_r_tmp[i] / SQRT((SPOOL_BUILDUP_FACTOR) * line_on_spool_origin_tmp[i] + s_r2_tmp[i]); planner.k1[i] = (SPOOL_BUILDUP_FACTOR) * (line_on_spool_origin_tmp[i] + nr_lines_dir_tmp[i] * line_lengths_origin[i]) + s_r2_tmp[i]; planner.sqrtk1[i] = SQRT(planner.k1[i]); } planner.axis_steps_per_mm[E_AXIS] = DEFAULT_E_AXIS_STEPS_PER_UNIT; #endif // LINE_BUILDUP_COMPENSATION_FEATURE SYNC_PLAN_POSITION_KINEMATIC(); // recalcs line lengths in case anchor was moved } /** * Hangprinter inverse kinematics */ void inverse_kinematics(const float raw[XYZ]) { HANGPRINTER_IK(raw); } /** * Hangprinter forward kinematics * Basic idea is to subtract squared line lengths to get linear equations. * Subtracting d*d from a*a, b*b, and c*c gives the cleanest derivation: * * a*a - d*d = k1 + k2*y + k3*z <---- a line (I) * b*b - d*d = k4 + k5*x + k6*y + k7*z <---- a plane (II) * c*c - d*d = k8 + k9*x + k10*y + k11*z <---- a plane (III) * * Use (I) to reduce (II) and (III) into lines. Eliminate y, keep z. * * (II): b*b - d*d = k12 + k13*x + k14*z * <=> x = k0b + k1b*z, <---- a line (IV) * * (III): c*c - d*d = k15 + k16*x + k17*z * <=> x = k0c + k1c*z, <---- a line (V) * * where k1, k2, ..., k17, k0b, k0c, k1b, and k1c are known constants. * * These two straight lines are not parallel, so they will cross in exactly one point. * Find z by setting (IV) = (V) * Find x by inserting z into (V) * Find y by inserting z into (I) * * Warning: truncation errors will typically be in the order of a few tens of microns. */ void forward_kinematics_HANGPRINTER(float a, float b, float c, float d){ const float Asq = sq(anchor_A_y) + sq(anchor_A_z), Bsq = sq(anchor_B_x) + sq(anchor_B_y) + sq(anchor_B_z), Csq = sq(anchor_C_x) + sq(anchor_C_y) + sq(anchor_C_z), Dsq = sq(anchor_D_z), aa = sq(a), dd = sq(d), k0b = (-sq(b) + Bsq - Dsq + dd) / (2.0 * anchor_B_x) + (anchor_B_y / (2.0 * anchor_A_y * anchor_B_x)) * (Dsq - Asq + aa - dd), k0c = (-sq(c) + Csq - Dsq + dd) / (2.0 * anchor_C_x) + (anchor_C_y / (2.0 * anchor_A_y * anchor_C_x)) * (Dsq - Asq + aa - dd), k1b = (anchor_B_y * (anchor_A_z - anchor_D_z)) / (anchor_A_y * anchor_B_x) + (anchor_D_z - anchor_B_z) / anchor_B_x, k1c = (anchor_C_y * (anchor_A_z - anchor_D_z)) / (anchor_A_y * anchor_C_x) + (anchor_D_z - anchor_C_z) / anchor_C_x; cartes[Z_AXIS] = (k0b - k0c) / (k1c - k1b); cartes[X_AXIS] = k0c + k1c * cartes[Z_AXIS]; cartes[Y_AXIS] = (Asq - Dsq - aa + dd) / (2.0 * anchor_A_y) + ((anchor_D_z - anchor_A_z) / anchor_A_y) * cartes[Z_AXIS]; } #endif // HANGPRINTER /** * Get the stepper positions in the cartes[] array. * Forward kinematics are applied for DELTA and SCARA. * * The result is in the current coordinate space with * leveling applied. The coordinates need to be run through * unapply_leveling to obtain machine coordinates suitable * for current_position, etc. */ void get_cartesian_from_steppers() { #if ENABLED(DELTA) forward_kinematics_DELTA( planner.get_axis_position_mm(A_AXIS), planner.get_axis_position_mm(B_AXIS), planner.get_axis_position_mm(C_AXIS) ); #elif ENABLED(HANGPRINTER) forward_kinematics_HANGPRINTER( planner.get_axis_position_mm(A_AXIS), planner.get_axis_position_mm(B_AXIS), planner.get_axis_position_mm(C_AXIS), planner.get_axis_position_mm(D_AXIS) ); #else #if IS_SCARA forward_kinematics_SCARA( planner.get_axis_position_degrees(A_AXIS), planner.get_axis_position_degrees(B_AXIS) ); #else cartes[X_AXIS] = planner.get_axis_position_mm(X_AXIS); cartes[Y_AXIS] = planner.get_axis_position_mm(Y_AXIS); #endif cartes[Z_AXIS] = planner.get_axis_position_mm(Z_AXIS); #endif } /** * Set the current_position for an axis based on * the stepper positions, removing any leveling that * may have been applied. * * To prevent small shifts in axis position always call * SYNC_PLAN_POSITION_KINEMATIC after updating axes with this. * * To keep hosts in sync, always call report_current_position * after updating the current_position. */ void set_current_from_steppers_for_axis(const AxisEnum axis) { get_cartesian_from_steppers(); #if PLANNER_LEVELING planner.unapply_leveling(cartes); #endif if (axis == ALL_AXES) COPY(current_position, cartes); else current_position[axis] = cartes[axis]; } #if IS_CARTESIAN #if ENABLED(SEGMENT_LEVELED_MOVES) /** * Prepare a segmented move on a CARTESIAN setup. * * This calls planner.buffer_line several times, adding * small incremental moves. This allows the planner to * apply more detailed bed leveling to the full move. */ inline void segmented_line_to_destination(const float &fr_mm_s, const float segment_size=LEVELED_SEGMENT_LENGTH) { const float xdiff = destination[X_AXIS] - current_position[X_AXIS], ydiff = destination[Y_AXIS] - current_position[Y_AXIS]; // If the move is only in Z/E don't split up the move if (!xdiff && !ydiff) { planner.buffer_line_kinematic(destination, fr_mm_s, active_extruder); return; } // Remaining cartesian distances const float zdiff = destination[Z_AXIS] - current_position[Z_AXIS], ediff = destination[E_CART] - current_position[E_CART]; // Get the linear distance in XYZ // If the move is very short, check the E move distance // No E move either? Game over. float cartesian_mm = SQRT(sq(xdiff) + sq(ydiff) + sq(zdiff)); if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = ABS(ediff); if (UNEAR_ZERO(cartesian_mm)) return; // The length divided by the segment size // At least one segment is required uint16_t segments = cartesian_mm / segment_size; NOLESS(segments, 1); // The approximate length of each segment const float inv_segments = 1.0f / float(segments), cartesian_segment_mm = cartesian_mm * inv_segments, segment_distance[XYZE] = { xdiff * inv_segments, ydiff * inv_segments, zdiff * inv_segments, ediff * inv_segments }; // SERIAL_ECHOPAIR("mm=", cartesian_mm); // SERIAL_ECHOLNPAIR(" segments=", segments); // SERIAL_ECHOLNPAIR(" segment_mm=", cartesian_segment_mm); // Get the raw current position as starting point float raw[XYZE]; COPY(raw, current_position); // Calculate and execute the segments while (--segments) { static millis_t next_idle_ms = millis() + 200UL; thermalManager.manage_heater(); // This returns immediately if not really needed. if (ELAPSED(millis(), next_idle_ms)) { next_idle_ms = millis() + 200UL; idle(); } LOOP_XYZE(i) raw[i] += segment_distance[i]; if (!planner.buffer_line_kinematic(raw, fr_mm_s, active_extruder, cartesian_segment_mm)) break; } // Since segment_distance is only approximate, // the final move must be to the exact destination. planner.buffer_line_kinematic(destination, fr_mm_s, active_extruder, cartesian_segment_mm); } #elif ENABLED(MESH_BED_LEVELING) /** * Prepare a mesh-leveled linear move in a Cartesian setup, * splitting the move where it crosses mesh borders. */ void mesh_line_to_destination(const float fr_mm_s, uint8_t x_splits=0xFF, uint8_t y_splits=0xFF) { // Get current and destination cells for this line int cx1 = mbl.cell_index_x(current_position[X_AXIS]), cy1 = mbl.cell_index_y(current_position[Y_AXIS]), cx2 = mbl.cell_index_x(destination[X_AXIS]), cy2 = mbl.cell_index_y(destination[Y_AXIS]); NOMORE(cx1, GRID_MAX_POINTS_X - 2); NOMORE(cy1, GRID_MAX_POINTS_Y - 2); NOMORE(cx2, GRID_MAX_POINTS_X - 2); NOMORE(cy2, GRID_MAX_POINTS_Y - 2); // Start and end in the same cell? No split needed. if (cx1 == cx2 && cy1 == cy2) { buffer_line_to_destination(fr_mm_s); set_current_from_destination(); return; } #define MBL_SEGMENT_END(A) (current_position[_AXIS(A)] + (destination[_AXIS(A)] - current_position[_AXIS(A)]) * normalized_dist) #define MBL_SEGMENT_END_E (current_position[E_CART] + (destination[E_CART] - current_position[E_CART]) * normalized_dist) float normalized_dist, end[XYZE]; const int8_t gcx = MAX(cx1, cx2), gcy = MAX(cy1, cy2); // Crosses on the X and not already split on this X? // The x_splits flags are insurance against rounding errors. if (cx2 != cx1 && TEST(x_splits, gcx)) { // Split on the X grid line CBI(x_splits, gcx); COPY(end, destination); destination[X_AXIS] = mbl.index_to_xpos[gcx]; normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]); destination[Y_AXIS] = MBL_SEGMENT_END(Y); } // Crosses on the Y and not already split on this Y? else if (cy2 != cy1 && TEST(y_splits, gcy)) { // Split on the Y grid line CBI(y_splits, gcy); COPY(end, destination); destination[Y_AXIS] = mbl.index_to_ypos[gcy]; normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]); destination[X_AXIS] = MBL_SEGMENT_END(X); } else { // Must already have been split on these border(s) buffer_line_to_destination(fr_mm_s); set_current_from_destination(); return; } destination[Z_AXIS] = MBL_SEGMENT_END(Z); destination[E_CART] = MBL_SEGMENT_END_E; // Do the split and look for more borders mesh_line_to_destination(fr_mm_s, x_splits, y_splits); // Restore destination from stack COPY(destination, end); mesh_line_to_destination(fr_mm_s, x_splits, y_splits); } #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) #define CELL_INDEX(A,V) ((V - bilinear_start[_AXIS(A)]) * ABL_BG_FACTOR(_AXIS(A))) /** * Prepare a bilinear-leveled linear move on Cartesian, * splitting the move where it crosses grid borders. */ void bilinear_line_to_destination(const float fr_mm_s, uint16_t x_splits=0xFFFF, uint16_t y_splits=0xFFFF) { // Get current and destination cells for this line int cx1 = CELL_INDEX(X, current_position[X_AXIS]), cy1 = CELL_INDEX(Y, current_position[Y_AXIS]), cx2 = CELL_INDEX(X, destination[X_AXIS]), cy2 = CELL_INDEX(Y, destination[Y_AXIS]); cx1 = constrain(cx1, 0, ABL_BG_POINTS_X - 2); cy1 = constrain(cy1, 0, ABL_BG_POINTS_Y - 2); cx2 = constrain(cx2, 0, ABL_BG_POINTS_X - 2); cy2 = constrain(cy2, 0, ABL_BG_POINTS_Y - 2); // Start and end in the same cell? No split needed. if (cx1 == cx2 && cy1 == cy2) { buffer_line_to_destination(fr_mm_s); set_current_from_destination(); return; } #define LINE_SEGMENT_END(A) (current_position[_AXIS(A)] + (destination[_AXIS(A)] - current_position[_AXIS(A)]) * normalized_dist) #define LINE_SEGMENT_END_E (current_position[E_CART] + (destination[E_CART] - current_position[E_CART]) * normalized_dist) float normalized_dist, end[XYZE]; const int8_t gcx = MAX(cx1, cx2), gcy = MAX(cy1, cy2); // Crosses on the X and not already split on this X? // The x_splits flags are insurance against rounding errors. if (cx2 != cx1 && TEST(x_splits, gcx)) { // Split on the X grid line CBI(x_splits, gcx); COPY(end, destination); destination[X_AXIS] = bilinear_start[X_AXIS] + ABL_BG_SPACING(X_AXIS) * gcx; normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]); destination[Y_AXIS] = LINE_SEGMENT_END(Y); } // Crosses on the Y and not already split on this Y? else if (cy2 != cy1 && TEST(y_splits, gcy)) { // Split on the Y grid line CBI(y_splits, gcy); COPY(end, destination); destination[Y_AXIS] = bilinear_start[Y_AXIS] + ABL_BG_SPACING(Y_AXIS) * gcy; normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]); destination[X_AXIS] = LINE_SEGMENT_END(X); } else { // Must already have been split on these border(s) buffer_line_to_destination(fr_mm_s); set_current_from_destination(); return; } destination[Z_AXIS] = LINE_SEGMENT_END(Z); destination[E_CART] = LINE_SEGMENT_END_E; // Do the split and look for more borders bilinear_line_to_destination(fr_mm_s, x_splits, y_splits); // Restore destination from stack COPY(destination, end); bilinear_line_to_destination(fr_mm_s, x_splits, y_splits); } #endif // AUTO_BED_LEVELING_BILINEAR #endif // IS_CARTESIAN #if !UBL_SEGMENTED #if IS_KINEMATIC #if IS_SCARA /** * Before raising this value, use M665 S[seg_per_sec] to decrease * the number of segments-per-second. Default is 200. Some deltas * do better with 160 or lower. It would be good to know how many * segments-per-second are actually possible for SCARA on AVR. * * Longer segments result in less kinematic overhead * but may produce jagged lines. Try 0.5mm, 1.0mm, and 2.0mm * and compare the difference. */ #define SCARA_MIN_SEGMENT_LENGTH 0.5f #endif /** * Prepare a linear move in a DELTA, SCARA or HANGPRINTER setup. * * This calls planner.buffer_line several times, adding * small incremental moves for DELTA, SCARA or HANGPRINTER. * * For Unified Bed Leveling (Delta or Segmented Cartesian) * the ubl.prepare_segmented_line_to method replaces this. */ inline bool prepare_kinematic_move_to(const float (&rtarget)[XYZE]) { // Get the top feedrate of the move in the XY plane const float _feedrate_mm_s = MMS_SCALED(feedrate_mm_s); const float xdiff = rtarget[X_AXIS] - current_position[X_AXIS], ydiff = rtarget[Y_AXIS] - current_position[Y_AXIS] #if ENABLED(HANGPRINTER) , zdiff = rtarget[Z_AXIS] - current_position[Z_AXIS] #endif ; // If the move is only in Z/E (for Hangprinter only in E) don't split up the move if (!xdiff && !ydiff #if ENABLED(HANGPRINTER) && !zdiff #endif ) { planner.buffer_line_kinematic(rtarget, _feedrate_mm_s, active_extruder); return false; // caller will update current_position } // Fail if attempting move outside printable radius if (!position_is_reachable(rtarget[X_AXIS], rtarget[Y_AXIS])) return true; // Remaining cartesian distances const float #if DISABLED(HANGPRINTER) zdiff = rtarget[Z_AXIS] - current_position[Z_AXIS], #endif ediff = rtarget[E_CART] - current_position[E_CART]; // Get the linear distance in XYZ // If the move is very short, check the E move distance // No E move either? Game over. float cartesian_mm = SQRT(sq(xdiff) + sq(ydiff) + sq(zdiff)); if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = ABS(ediff); if (UNEAR_ZERO(cartesian_mm)) return true; // Minimum number of seconds to move the given distance const float seconds = cartesian_mm / _feedrate_mm_s; // The number of segments-per-second times the duration // gives the number of segments uint16_t segments = delta_segments_per_second * seconds; // For SCARA enforce a minimum segment size #if IS_SCARA NOMORE(segments, cartesian_mm * (1.0f / float(SCARA_MIN_SEGMENT_LENGTH))); #endif // At least one segment is required NOLESS(segments, 1); // The approximate length of each segment const float inv_segments = 1.0f / float(segments), segment_distance[XYZE] = { xdiff * inv_segments, ydiff * inv_segments, zdiff * inv_segments, ediff * inv_segments }; #if !HAS_FEEDRATE_SCALING const float cartesian_segment_mm = cartesian_mm * inv_segments; #endif /* SERIAL_ECHOPAIR("mm=", cartesian_mm); SERIAL_ECHOPAIR(" seconds=", seconds); SERIAL_ECHOPAIR(" segments=", segments); #if !HAS_FEEDRATE_SCALING SERIAL_ECHOPAIR(" segment_mm=", cartesian_segment_mm); #endif SERIAL_EOL(); //*/ #if HAS_FEEDRATE_SCALING // SCARA needs to scale the feed rate from mm/s to degrees/s // i.e., Complete the angular vector in the given time. const float segment_length = cartesian_mm * inv_segments, inv_segment_length = 1.0f / segment_length, // 1/mm/segs inverse_secs = inv_segment_length * _feedrate_mm_s; float oldA = planner.position_float[A_AXIS], oldB = planner.position_float[B_AXIS] #if ENABLED(DELTA_FEEDRATE_SCALING) , oldC = planner.position_float[C_AXIS] #endif ; /* SERIAL_ECHOPGM("Scaled kinematic move: "); SERIAL_ECHOPAIR(" segment_length (inv)=", segment_length); SERIAL_ECHOPAIR(" (", inv_segment_length); SERIAL_ECHOPAIR(") _feedrate_mm_s=", _feedrate_mm_s); SERIAL_ECHOPAIR(" inverse_secs=", inverse_secs); SERIAL_ECHOPAIR(" oldA=", oldA); SERIAL_ECHOPAIR(" oldB=", oldB); #if ENABLED(DELTA_FEEDRATE_SCALING) SERIAL_ECHOPAIR(" oldC=", oldC); #endif SERIAL_EOL(); safe_delay(5); //*/ #endif // Get the current position as starting point float raw[XYZE]; COPY(raw, current_position); // Calculate and execute the segments while (--segments) { static millis_t next_idle_ms = millis() + 200UL; thermalManager.manage_heater(); // This returns immediately if not really needed. if (ELAPSED(millis(), next_idle_ms)) { next_idle_ms = millis() + 200UL; idle(); } LOOP_XYZE(i) raw[i] += segment_distance[i]; #if ENABLED(DELTA) && HOTENDS < 2 DELTA_IK(raw); // Delta can inline its kinematics #elif ENABLED(HANGPRINTER) HANGPRINTER_IK(raw); // Modifies line_lengths[ABCD] #else inverse_kinematics(raw); #endif ADJUST_DELTA(raw); // Adjust Z if bed leveling is enabled #if ENABLED(SCARA_FEEDRATE_SCALING) // For SCARA scale the feed rate from mm/s to degrees/s // i.e., Complete the angular vector in the given time. if (!planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], raw[Z_AXIS], raw[E_CART], HYPOT(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB) * inverse_secs, active_extruder, segment_length)) break; /* SERIAL_ECHO(segments); SERIAL_ECHOPAIR(": X=", raw[X_AXIS]); SERIAL_ECHOPAIR(" Y=", raw[Y_AXIS]); SERIAL_ECHOPAIR(" A=", delta[A_AXIS]); SERIAL_ECHOPAIR(" B=", delta[B_AXIS]); SERIAL_ECHOLNPAIR(" F", HYPOT(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB) * inverse_secs * 60); safe_delay(5); //*/ oldA = delta[A_AXIS]; oldB = delta[B_AXIS]; #elif ENABLED(DELTA_FEEDRATE_SCALING) // For DELTA scale the feed rate from Effector mm/s to Carriage mm/s // i.e., Complete the linear vector in the given time. if (!planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_AXIS], SQRT(sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC)) * inverse_secs, active_extruder, segment_length)) break; /* SERIAL_ECHO(segments); SERIAL_ECHOPAIR(": X=", raw[X_AXIS]); SERIAL_ECHOPAIR(" Y=", raw[Y_AXIS]); SERIAL_ECHOPAIR(" A=", delta[A_AXIS]); SERIAL_ECHOPAIR(" B=", delta[B_AXIS]); SERIAL_ECHOPAIR(" C=", delta[C_AXIS]); SERIAL_ECHOLNPAIR(" F", SQRT(sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC)) * inverse_secs * 60); safe_delay(5); //*/ oldA = delta[A_AXIS]; oldB = delta[B_AXIS]; oldC = delta[C_AXIS]; #elif ENABLED(HANGPRINTER) if (!planner.buffer_line(line_lengths[A_AXIS], line_lengths[B_AXIS], line_lengths[C_AXIS], line_lengths[D_AXIS], raw[E_CART], _feedrate_mm_s, active_extruder, cartesian_segment_mm)) break; #else if (!planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_CART], _feedrate_mm_s, active_extruder, cartesian_segment_mm)) break; #endif } // Ensure last segment arrives at target location. #if HAS_FEEDRATE_SCALING inverse_kinematics(rtarget); ADJUST_DELTA(rtarget); #endif #if ENABLED(SCARA_FEEDRATE_SCALING) const float diff2 = HYPOT2(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB); if (diff2) { planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], rtarget[Z_AXIS], rtarget[E_CART], SQRT(diff2) * inverse_secs, active_extruder, segment_length); /* SERIAL_ECHOPAIR("final: A=", delta[A_AXIS]); SERIAL_ECHOPAIR(" B=", delta[B_AXIS]); SERIAL_ECHOPAIR(" adiff=", delta[A_AXIS] - oldA); SERIAL_ECHOPAIR(" bdiff=", delta[B_AXIS] - oldB); SERIAL_ECHOLNPAIR(" F", SQRT(diff2) * inverse_secs * 60); SERIAL_EOL(); safe_delay(5); //*/ } #elif ENABLED(DELTA_FEEDRATE_SCALING) const float diff2 = sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC); if (diff2) { planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], rtarget[E_AXIS], SQRT(diff2) * inverse_secs, active_extruder, segment_length); /* SERIAL_ECHOPAIR("final: A=", delta[A_AXIS]); SERIAL_ECHOPAIR(" B=", delta[B_AXIS]); SERIAL_ECHOPAIR(" C=", delta[C_AXIS]); SERIAL_ECHOPAIR(" adiff=", delta[A_AXIS] - oldA); SERIAL_ECHOPAIR(" bdiff=", delta[B_AXIS] - oldB); SERIAL_ECHOPAIR(" cdiff=", delta[C_AXIS] - oldC); SERIAL_ECHOLNPAIR(" F", SQRT(diff2) * inverse_secs * 60); SERIAL_EOL(); safe_delay(5); //*/ } #else planner.buffer_line_kinematic(rtarget, _feedrate_mm_s, active_extruder, cartesian_segment_mm); #endif return false; // caller will update current_position } #else // !IS_KINEMATIC /** * Prepare a linear move in a Cartesian setup. * * When a mesh-based leveling system is active, moves are segmented * according to the configuration of the leveling system. * * Returns true if current_position[] was set to destination[] */ inline bool prepare_move_to_destination_cartesian() { #if HAS_MESH if (planner.leveling_active && planner.leveling_active_at_z(destination[Z_AXIS])) { #if ENABLED(AUTO_BED_LEVELING_UBL) ubl.line_to_destination_cartesian(MMS_SCALED(feedrate_mm_s), active_extruder); // UBL's motion routine needs to know about return true; // all moves, including Z-only moves. #elif ENABLED(SEGMENT_LEVELED_MOVES) segmented_line_to_destination(MMS_SCALED(feedrate_mm_s)); return false; // caller will update current_position #else /** * For MBL and ABL-BILINEAR only segment moves when X or Y are involved. * Otherwise fall through to do a direct single move. */ if (current_position[X_AXIS] != destination[X_AXIS] || current_position[Y_AXIS] != destination[Y_AXIS]) { #if ENABLED(MESH_BED_LEVELING) mesh_line_to_destination(MMS_SCALED(feedrate_mm_s)); #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) bilinear_line_to_destination(MMS_SCALED(feedrate_mm_s)); #endif return true; } #endif } #endif // HAS_MESH buffer_line_to_destination(MMS_SCALED(feedrate_mm_s)); return false; // caller will update current_position } #endif // !IS_KINEMATIC #endif // !UBL_SEGMENTED #if ENABLED(DUAL_X_CARRIAGE) /** * Unpark the carriage, if needed */ inline bool dual_x_carriage_unpark() { if (active_extruder_parked) switch (dual_x_carriage_mode) { case DXC_FULL_CONTROL_MODE: break; case DXC_AUTO_PARK_MODE: if (current_position[E_CART] == destination[E_CART]) { // This is a travel move (with no extrusion) // Skip it, but keep track of the current position // (so it can be used as the start of the next non-travel move) if (delayed_move_time != 0xFFFFFFFFUL) { set_current_from_destination(); NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]); delayed_move_time = millis(); return true; } } // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower for (uint8_t i = 0; i < 3; i++) if (!planner.buffer_line( i == 0 ? raised_parked_position[X_AXIS] : current_position[X_AXIS], i == 0 ? raised_parked_position[Y_AXIS] : current_position[Y_AXIS], i == 2 ? current_position[Z_AXIS] : raised_parked_position[Z_AXIS], current_position[E_CART], i == 1 ? PLANNER_XY_FEEDRATE() : planner.max_feedrate_mm_s[Z_AXIS], active_extruder) ) break; delayed_move_time = 0; active_extruder_parked = false; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Clear active_extruder_parked"); #endif break; case DXC_DUPLICATION_MODE: if (active_extruder == 0) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("Set planner X", inactive_extruder_x_pos); SERIAL_ECHOLNPAIR(" ... Line to X", current_position[X_AXIS] + duplicate_extruder_x_offset); } #endif // move duplicate extruder into correct duplication position. planner.set_position_mm(inactive_extruder_x_pos, current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART]); if (!planner.buffer_line( current_position[X_AXIS] + duplicate_extruder_x_offset, current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART], planner.max_feedrate_mm_s[X_AXIS], 1) ) break; planner.synchronize(); SYNC_PLAN_POSITION_KINEMATIC(); extruder_duplication_enabled = true; active_extruder_parked = false; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Set extruder_duplication_enabled\nClear active_extruder_parked"); #endif } else { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Active extruder not 0"); #endif } break; } return false; } #endif // DUAL_X_CARRIAGE /** * Prepare a single move and get ready for the next one * * This may result in several calls to planner.buffer_line to * do smaller moves for DELTA, SCARA, HANGPRINTER, mesh moves, etc. * * Make sure current_position[E] and destination[E] are good * before calling or cold/lengthy extrusion may get missed. */ void prepare_move_to_destination() { clamp_to_software_endstops(destination); #if ENABLED(PREVENT_COLD_EXTRUSION) || ENABLED(PREVENT_LENGTHY_EXTRUDE) if (!DEBUGGING(DRYRUN)) { if (destination[E_CART] != current_position[E_CART]) { #if ENABLED(PREVENT_COLD_EXTRUSION) if (thermalManager.tooColdToExtrude(active_extruder)) { current_position[E_CART] = destination[E_CART]; // Behave as if the move really took place, but ignore E part SERIAL_ECHO_START(); SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP); } #endif // PREVENT_COLD_EXTRUSION #if ENABLED(PREVENT_LENGTHY_EXTRUDE) if (ABS(destination[E_CART] - current_position[E_CART]) * planner.e_factor[active_extruder] > (EXTRUDE_MAXLENGTH)) { current_position[E_CART] = destination[E_CART]; // Behave as if the move really took place, but ignore E part SERIAL_ECHO_START(); SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP); } #endif // PREVENT_LENGTHY_EXTRUDE } } #endif #if ENABLED(DUAL_X_CARRIAGE) if (dual_x_carriage_unpark()) return; #endif if ( #if UBL_SEGMENTED ubl.prepare_segmented_line_to(destination, MMS_SCALED(feedrate_mm_s)) #elif IS_KINEMATIC prepare_kinematic_move_to(destination) #else prepare_move_to_destination_cartesian() #endif ) return; set_current_from_destination(); } #if ENABLED(ARC_SUPPORT) #if N_ARC_CORRECTION < 1 #undef N_ARC_CORRECTION #define N_ARC_CORRECTION 1 #endif /** * Plan an arc in 2 dimensions * * The arc is approximated by generating many small linear segments. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm) * Arcs should only be made relatively large (over 5mm), as larger arcs with * larger segments will tend to be more efficient. Your slicer should have * options for G2/G3 arc generation. In future these options may be GCode tunable. */ void plan_arc( const float (&cart)[XYZE], // Destination position const float (&offset)[2], // Center of rotation relative to current_position const bool clockwise // Clockwise? ) { #if ENABLED(CNC_WORKSPACE_PLANES) AxisEnum p_axis, q_axis, l_axis; switch (workspace_plane) { default: case PLANE_XY: p_axis = X_AXIS; q_axis = Y_AXIS; l_axis = Z_AXIS; break; case PLANE_ZX: p_axis = Z_AXIS; q_axis = X_AXIS; l_axis = Y_AXIS; break; case PLANE_YZ: p_axis = Y_AXIS; q_axis = Z_AXIS; l_axis = X_AXIS; break; } #else constexpr AxisEnum p_axis = X_AXIS, q_axis = Y_AXIS, l_axis = Z_AXIS; #endif // Radius vector from center to current location float r_P = -offset[0], r_Q = -offset[1]; const float radius = HYPOT(r_P, r_Q), center_P = current_position[p_axis] - r_P, center_Q = current_position[q_axis] - r_Q, rt_X = cart[p_axis] - center_P, rt_Y = cart[q_axis] - center_Q, linear_travel = cart[l_axis] - current_position[l_axis], extruder_travel = cart[E_CART] - current_position[E_CART]; // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required. float angular_travel = ATAN2(r_P * rt_Y - r_Q * rt_X, r_P * rt_X + r_Q * rt_Y); if (angular_travel < 0) angular_travel += RADIANS(360); if (clockwise) angular_travel -= RADIANS(360); // Make a circle if the angular rotation is 0 and the target is current position if (angular_travel == 0 && current_position[p_axis] == cart[p_axis] && current_position[q_axis] == cart[q_axis]) angular_travel = RADIANS(360); const float flat_mm = radius * angular_travel, mm_of_travel = linear_travel ? HYPOT(flat_mm, linear_travel) : ABS(flat_mm); if (mm_of_travel < 0.001f) return; uint16_t segments = FLOOR(mm_of_travel / (MM_PER_ARC_SEGMENT)); NOLESS(segments, 1); /** * Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector, * and phi is the angle of rotation. Based on the solution approach by Jens Geisler. * r_T = [cos(phi) -sin(phi); * sin(phi) cos(phi)] * r ; * * For arc generation, the center of the circle is the axis of rotation and the radius vector is * defined from the circle center to the initial position. Each line segment is formed by successive * vector rotations. This requires only two cos() and sin() computations to form the rotation * matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since * all double numbers are single precision on the Arduino. (True double precision will not have * round off issues for CNC applications.) Single precision error can accumulate to be greater than * tool precision in some cases. Therefore, arc path correction is implemented. * * Small angle approximation may be used to reduce computation overhead further. This approximation * holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words, * theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large * to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for * numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an * issue for CNC machines with the single precision Arduino calculations. * * This approximation also allows plan_arc to immediately insert a line segment into the planner * without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied * a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead. * This is important when there are successive arc motions. */ // Vector rotation matrix values float raw[XYZE]; const float theta_per_segment = angular_travel / segments, linear_per_segment = linear_travel / segments, extruder_per_segment = extruder_travel / segments, sin_T = theta_per_segment, cos_T = 1 - 0.5f * sq(theta_per_segment); // Small angle approximation // Initialize the linear axis raw[l_axis] = current_position[l_axis]; // Initialize the extruder axis raw[E_CART] = current_position[E_CART]; const float fr_mm_s = MMS_SCALED(feedrate_mm_s); millis_t next_idle_ms = millis() + 200UL; #if HAS_FEEDRATE_SCALING // SCARA needs to scale the feed rate from mm/s to degrees/s const float inv_segment_length = 1.0f / (MM_PER_ARC_SEGMENT), inverse_secs = inv_segment_length * fr_mm_s; float oldA = planner.position_float[A_AXIS], oldB = planner.position_float[B_AXIS] #if ENABLED(DELTA_FEEDRATE_SCALING) , oldC = planner.position_float[C_AXIS] #endif ; #endif #if N_ARC_CORRECTION > 1 int8_t arc_recalc_count = N_ARC_CORRECTION; #endif for (uint16_t i = 1; i < segments; i++) { // Iterate (segments-1) times thermalManager.manage_heater(); if (ELAPSED(millis(), next_idle_ms)) { next_idle_ms = millis() + 200UL; idle(); } #if N_ARC_CORRECTION > 1 if (--arc_recalc_count) { // Apply vector rotation matrix to previous r_P / 1 const float r_new_Y = r_P * sin_T + r_Q * cos_T; r_P = r_P * cos_T - r_Q * sin_T; r_Q = r_new_Y; } else #endif { #if N_ARC_CORRECTION > 1 arc_recalc_count = N_ARC_CORRECTION; #endif // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments. // Compute exact location by applying transformation matrix from initial radius vector(=-offset). // To reduce stuttering, the sin and cos could be computed at different times. // For now, compute both at the same time. const float cos_Ti = cos(i * theta_per_segment), sin_Ti = sin(i * theta_per_segment); r_P = -offset[0] * cos_Ti + offset[1] * sin_Ti; r_Q = -offset[0] * sin_Ti - offset[1] * cos_Ti; } // Update raw location raw[p_axis] = center_P + r_P; raw[q_axis] = center_Q + r_Q; raw[l_axis] += linear_per_segment; raw[E_CART] += extruder_per_segment; clamp_to_software_endstops(raw); #if HAS_FEEDRATE_SCALING inverse_kinematics(raw); ADJUST_DELTA(raw); #endif #if ENABLED(SCARA_FEEDRATE_SCALING) // For SCARA scale the feed rate from mm/s to degrees/s // i.e., Complete the angular vector in the given time. if (!planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], raw[Z_AXIS], raw[E_CART], HYPOT(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB) * inverse_secs, active_extruder, MM_PER_ARC_SEGMENT)) break; oldA = delta[A_AXIS]; oldB = delta[B_AXIS]; #elif ENABLED(DELTA_FEEDRATE_SCALING) // For DELTA scale the feed rate from Effector mm/s to Carriage mm/s // i.e., Complete the linear vector in the given time. if (!planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_AXIS], SQRT(sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC)) * inverse_secs, active_extruder, MM_PER_ARC_SEGMENT)) break; oldA = delta[A_AXIS]; oldB = delta[B_AXIS]; oldC = delta[C_AXIS]; #elif HAS_UBL_AND_CURVES float pos[XYZ] = { raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS] }; planner.apply_leveling(pos); if (!planner.buffer_segment(pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS], raw[E_CART], fr_mm_s, active_extruder, MM_PER_ARC_SEGMENT)) break; #else if (!planner.buffer_line_kinematic(raw, fr_mm_s, active_extruder)) break; #endif } // Ensure last segment arrives at target location. #if HAS_FEEDRATE_SCALING inverse_kinematics(cart); ADJUST_DELTA(cart); #endif #if ENABLED(SCARA_FEEDRATE_SCALING) const float diff2 = HYPOT2(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB); if (diff2) planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], cart[Z_AXIS], cart[E_CART], SQRT(diff2) * inverse_secs, active_extruder, MM_PER_ARC_SEGMENT); #elif ENABLED(DELTA_FEEDRATE_SCALING) const float diff2 = sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC); if (diff2) planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], cart[E_CART], SQRT(diff2) * inverse_secs, active_extruder, MM_PER_ARC_SEGMENT); #elif HAS_UBL_AND_CURVES float pos[XYZ] = { cart[X_AXIS], cart[Y_AXIS], cart[Z_AXIS] }; planner.apply_leveling(pos); planner.buffer_segment(pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS], cart[E_CART], fr_mm_s, active_extruder, MM_PER_ARC_SEGMENT); #else planner.buffer_line_kinematic(cart, fr_mm_s, active_extruder); #endif COPY(current_position, cart); } // plan_arc #endif // ARC_SUPPORT #if ENABLED(BEZIER_CURVE_SUPPORT) void plan_cubic_move(const float (&cart)[XYZE], const float (&offset)[4]) { cubic_b_spline(current_position, cart, offset, MMS_SCALED(feedrate_mm_s), active_extruder); COPY(current_position, cart); } #endif // BEZIER_CURVE_SUPPORT #if ENABLED(USE_CONTROLLER_FAN) void controllerFan() { static millis_t lastMotorOn = 0, // Last time a motor was turned on nextMotorCheck = 0; // Last time the state was checked const millis_t ms = millis(); if (ELAPSED(ms, nextMotorCheck)) { nextMotorCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s // If any of the drivers or the bed are enabled... if (X_ENABLE_READ == X_ENABLE_ON || Y_ENABLE_READ == Y_ENABLE_ON || Z_ENABLE_READ == Z_ENABLE_ON #if HAS_HEATED_BED || thermalManager.soft_pwm_amount_bed > 0 #endif #if HAS_X2_ENABLE || X2_ENABLE_READ == X_ENABLE_ON #endif #if HAS_Y2_ENABLE || Y2_ENABLE_READ == Y_ENABLE_ON #endif #if HAS_Z2_ENABLE || Z2_ENABLE_READ == Z_ENABLE_ON #endif || E0_ENABLE_READ == E_ENABLE_ON #if E_STEPPERS > 1 || E1_ENABLE_READ == E_ENABLE_ON #if E_STEPPERS > 2 || E2_ENABLE_READ == E_ENABLE_ON #if E_STEPPERS > 3 || E3_ENABLE_READ == E_ENABLE_ON #if E_STEPPERS > 4 || E4_ENABLE_READ == E_ENABLE_ON #endif #endif #endif #endif ) { lastMotorOn = ms; //... set time to NOW so the fan will turn on } // Fan off if no steppers have been enabled for CONTROLLERFAN_SECS seconds const uint8_t speed = (lastMotorOn && PENDING(ms, lastMotorOn + (CONTROLLERFAN_SECS) * 1000UL)) ? CONTROLLERFAN_SPEED : 0; controllerFanSpeed = speed; // allows digital or PWM fan output to be used (see M42 handling) WRITE(CONTROLLER_FAN_PIN, speed); analogWrite(CONTROLLER_FAN_PIN, speed); } } #endif // USE_CONTROLLER_FAN #if ENABLED(MORGAN_SCARA) /** * Morgan SCARA Forward Kinematics. Results in cartes[]. * Maths and first version by QHARLEY. * Integrated into Marlin and slightly restructured by Joachim Cerny. */ void forward_kinematics_SCARA(const float &a, const float &b) { float a_sin = sin(RADIANS(a)) * L1, a_cos = cos(RADIANS(a)) * L1, b_sin = sin(RADIANS(b)) * L2, b_cos = cos(RADIANS(b)) * L2; cartes[X_AXIS] = a_cos + b_cos + SCARA_OFFSET_X; //theta cartes[Y_AXIS] = a_sin + b_sin + SCARA_OFFSET_Y; //theta+phi /* SERIAL_ECHOPAIR("SCARA FK Angle a=", a); SERIAL_ECHOPAIR(" b=", b); SERIAL_ECHOPAIR(" a_sin=", a_sin); SERIAL_ECHOPAIR(" a_cos=", a_cos); SERIAL_ECHOPAIR(" b_sin=", b_sin); SERIAL_ECHOLNPAIR(" b_cos=", b_cos); SERIAL_ECHOPAIR(" cartes[X_AXIS]=", cartes[X_AXIS]); SERIAL_ECHOLNPAIR(" cartes[Y_AXIS]=", cartes[Y_AXIS]); //*/ } /** * Morgan SCARA Inverse Kinematics. Results in delta[]. * * See http://forums.reprap.org/read.php?185,283327 * * Maths and first version by QHARLEY. * Integrated into Marlin and slightly restructured by Joachim Cerny. */ void inverse_kinematics(const float raw[XYZ]) { static float C2, S2, SK1, SK2, THETA, PSI; float sx = raw[X_AXIS] - SCARA_OFFSET_X, // Translate SCARA to standard X Y sy = raw[Y_AXIS] - SCARA_OFFSET_Y; // With scaling factor. if (L1 == L2) C2 = HYPOT2(sx, sy) / L1_2_2 - 1; else C2 = (HYPOT2(sx, sy) - (L1_2 + L2_2)) / (2.0 * L1 * L2); S2 = SQRT(1 - sq(C2)); // Unrotated Arm1 plus rotated Arm2 gives the distance from Center to End SK1 = L1 + L2 * C2; // Rotated Arm2 gives the distance from Arm1 to Arm2 SK2 = L2 * S2; // Angle of Arm1 is the difference between Center-to-End angle and the Center-to-Elbow THETA = ATAN2(SK1, SK2) - ATAN2(sx, sy); // Angle of Arm2 PSI = ATAN2(S2, C2); delta[A_AXIS] = DEGREES(THETA); // theta is support arm angle delta[B_AXIS] = DEGREES(THETA + PSI); // equal to sub arm angle (inverted motor) delta[C_AXIS] = raw[Z_AXIS]; /* DEBUG_POS("SCARA IK", raw); DEBUG_POS("SCARA IK", delta); SERIAL_ECHOPAIR(" SCARA (x,y) ", sx); SERIAL_ECHOPAIR(",", sy); SERIAL_ECHOPAIR(" C2=", C2); SERIAL_ECHOPAIR(" S2=", S2); SERIAL_ECHOPAIR(" Theta=", THETA); SERIAL_ECHOLNPAIR(" Phi=", PHI); //*/ } #endif // MORGAN_SCARA #if ENABLED(TEMP_STAT_LEDS) static uint8_t red_led = -1; // Invalid value to force leds initializzation on startup static millis_t next_status_led_update_ms = 0; void handle_status_leds(void) { if (ELAPSED(millis(), next_status_led_update_ms)) { next_status_led_update_ms += 500; // Update every 0.5s float max_temp = 0.0; #if HAS_HEATED_BED max_temp = MAX(thermalManager.degTargetBed(), thermalManager.degBed()); #endif HOTEND_LOOP() max_temp = MAX3(max_temp, thermalManager.degHotend(e), thermalManager.degTargetHotend(e)); const uint8_t new_led = (max_temp > 55.0) ? HIGH : (max_temp < 54.0 || red_led == -1) ? LOW : red_led; if (new_led != red_led) { red_led = new_led; #if PIN_EXISTS(STAT_LED_RED) WRITE(STAT_LED_RED_PIN, new_led); #endif #if PIN_EXISTS(STAT_LED_BLUE) WRITE(STAT_LED_BLUE_PIN, !new_led); #endif } } } #endif void enable_all_steppers() { #if ENABLED(AUTO_POWER_CONTROL) powerManager.power_on(); #endif #if ENABLED(HANGPRINTER) enable_A(); enable_B(); enable_C(); enable_D(); #else enable_X(); enable_Y(); enable_Z(); enable_E4(); #endif enable_E0(); enable_E1(); enable_E2(); enable_E3(); } void disable_e_stepper(const uint8_t e) { switch (e) { case 0: disable_E0(); break; case 1: disable_E1(); break; case 2: disable_E2(); break; case 3: disable_E3(); break; case 4: disable_E4(); break; } } void disable_e_steppers() { disable_E0(); disable_E1(); disable_E2(); disable_E3(); disable_E4(); } void disable_all_steppers() { disable_X(); disable_Y(); disable_Z(); disable_e_steppers(); } #ifdef ENDSTOP_BEEP void EndstopBeep() { static char last_status=((READ(X_MIN_PIN)<<2)|(READ(Y_MIN_PIN)<<1)|READ(X_MAX_PIN)); static unsigned char now_status; now_status=((READ(X_MIN_PIN)<<2)|(READ(Y_MIN_PIN)<<1)|READ(X_MAX_PIN))&0xff; if(now_status<last_status) { static millis_t endstop_ms = millis() + 300UL; if (ELAPSED(millis(), endstop_ms)) { buzzer.tone(60, 2000); } last_status=now_status; } else if(now_status!=last_status) { last_status=now_status; } } #endif /** * Manage several activities: * - Check for Filament Runout * - Keep the command buffer full * - Check for maximum inactive time between commands * - Check for maximum inactive time between stepper commands * - Check if pin CHDK needs to go LOW * - Check for KILL button held down * - Check for HOME button held down * - Check if cooling fan needs to be switched on * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT) */ void manage_inactivity(const bool ignore_stepper_queue/*=false*/) { #if ENABLED(FILAMENT_RUNOUT_SENSOR) runout.run(); #endif #if ENABLED(ANYCUBIC_TFT_MODEL) && ENABLED(ANYCUBIC_FILAMENT_RUNOUT_SENSOR) AnycubicTFT.FilamentRunout(); #endif if (commands_in_queue < BUFSIZE) get_available_commands(); const millis_t ms = millis(); if (max_inactive_time && ELAPSED(ms, previous_move_ms + max_inactive_time)) { SERIAL_ERROR_START(); SERIAL_ECHOLNPAIR(MSG_KILL_INACTIVE_TIME, parser.command_ptr); kill(PSTR(MSG_KILLED)); } // Prevent steppers timing-out in the middle of M600 #if ENABLED(ADVANCED_PAUSE_FEATURE) && ENABLED(PAUSE_PARK_NO_STEPPER_TIMEOUT) #define MOVE_AWAY_TEST !did_pause_print #else #define MOVE_AWAY_TEST true #endif if (stepper_inactive_time) { if (planner.has_blocks_queued()) previous_move_ms = ms; // reset_stepper_timeout to keep steppers powered else if (MOVE_AWAY_TEST && !ignore_stepper_queue && ELAPSED(ms, previous_move_ms + stepper_inactive_time)) { #if ENABLED(DISABLE_INACTIVE_X) disable_X(); #endif #if ENABLED(DISABLE_INACTIVE_Y) disable_Y(); #endif #if ENABLED(DISABLE_INACTIVE_Z) disable_Z(); #endif #if ENABLED(DISABLE_INACTIVE_E) disable_e_steppers(); #endif #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(ULTIPANEL) // Only needed with an LCD if (ubl.lcd_map_control) ubl.lcd_map_control = defer_return_to_status = false; #endif } } #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH if (chdkActive && ELAPSED(ms, chdkHigh + CHDK_DELAY)) { chdkActive = false; WRITE(CHDK, LOW); } #endif #if HAS_KILL // Check if the kill button was pressed and wait just in case it was an accidental // key kill key press // ------------------------------------------------------------------------------- static int killCount = 0; // make the inactivity button a bit less responsive const int KILL_DELAY = 750; if (!READ(KILL_PIN)) killCount++; else if (killCount > 0) killCount--; // Exceeded threshold and we can confirm that it was not accidental // KILL the machine // ---------------------------------------------------------------- if (killCount >= KILL_DELAY) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_KILL_BUTTON); kill(PSTR(MSG_KILLED)); } #endif #if HAS_HOME // Check to see if we have to home, use poor man's debouncer // --------------------------------------------------------- static int homeDebounceCount = 0; // poor man's debouncing count const int HOME_DEBOUNCE_DELAY = 2500; if (!IS_SD_PRINTING() && !READ(HOME_PIN)) { if (!homeDebounceCount) { enqueue_and_echo_commands_P(PSTR("G28")); LCD_MESSAGEPGM(MSG_AUTO_HOME); } if (homeDebounceCount < HOME_DEBOUNCE_DELAY) homeDebounceCount++; else homeDebounceCount = 0; } #endif #if ENABLED(USE_CONTROLLER_FAN) controllerFan(); // Check if fan should be turned on to cool stepper drivers down #endif #if ENABLED(AUTO_POWER_CONTROL) powerManager.check(); #endif #if ENABLED(EXTRUDER_RUNOUT_PREVENT) if (thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP && ELAPSED(ms, previous_move_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000UL) && !planner.has_blocks_queued() ) { #if ENABLED(SWITCHING_EXTRUDER) bool oldstatus; switch (active_extruder) { default: oldstatus = E0_ENABLE_READ; enable_E0(); break; #if E_STEPPERS > 1 case 2: case 3: oldstatus = E1_ENABLE_READ; enable_E1(); break; #if E_STEPPERS > 2 case 4: oldstatus = E2_ENABLE_READ; enable_E2(); break; #endif // E_STEPPERS > 2 #endif // E_STEPPERS > 1 } #else // !SWITCHING_EXTRUDER bool oldstatus; switch (active_extruder) { default: oldstatus = E0_ENABLE_READ; enable_E0(); break; #if E_STEPPERS > 1 case 1: oldstatus = E1_ENABLE_READ; enable_E1(); break; #if E_STEPPERS > 2 case 2: oldstatus = E2_ENABLE_READ; enable_E2(); break; #if E_STEPPERS > 3 case 3: oldstatus = E3_ENABLE_READ; enable_E3(); break; #if E_STEPPERS > 4 case 4: oldstatus = E4_ENABLE_READ; enable_E4(); break; #endif // E_STEPPERS > 4 #endif // E_STEPPERS > 3 #endif // E_STEPPERS > 2 #endif // E_STEPPERS > 1 } #endif // !SWITCHING_EXTRUDER const float olde = current_position[E_CART]; current_position[E_CART] += EXTRUDER_RUNOUT_EXTRUDE; planner.buffer_line_kinematic(current_position, MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED), active_extruder); current_position[E_CART] = olde; planner.set_e_position_mm(olde); planner.synchronize(); #if ENABLED(SWITCHING_EXTRUDER) switch (active_extruder) { default: oldstatus = E0_ENABLE_WRITE(oldstatus); break; #if E_STEPPERS > 1 case 2: case 3: oldstatus = E1_ENABLE_WRITE(oldstatus); break; #if E_STEPPERS > 2 case 4: oldstatus = E2_ENABLE_WRITE(oldstatus); break; #endif // E_STEPPERS > 2 #endif // E_STEPPERS > 1 } #else // !SWITCHING_EXTRUDER switch (active_extruder) { case 0: E0_ENABLE_WRITE(oldstatus); break; #if E_STEPPERS > 1 case 1: E1_ENABLE_WRITE(oldstatus); break; #if E_STEPPERS > 2 case 2: E2_ENABLE_WRITE(oldstatus); break; #if E_STEPPERS > 3 case 3: E3_ENABLE_WRITE(oldstatus); break; #if E_STEPPERS > 4 case 4: E4_ENABLE_WRITE(oldstatus); break; #endif // E_STEPPERS > 4 #endif // E_STEPPERS > 3 #endif // E_STEPPERS > 2 #endif // E_STEPPERS > 1 } #endif // !SWITCHING_EXTRUDER previous_move_ms = ms; // reset_stepper_timeout to keep steppers powered } #endif // EXTRUDER_RUNOUT_PREVENT #if ENABLED(DUAL_X_CARRIAGE) // handle delayed move timeout if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) { // travel moves have been received so enact them delayed_move_time = 0xFFFFFFFFUL; // force moves to be done set_destination_from_current(); prepare_move_to_destination(); } #endif #if ENABLED(TEMP_STAT_LEDS) handle_status_leds(); #endif #if ENABLED(MONITOR_DRIVER_STATUS) monitor_tmc_driver(); #endif planner.check_axes_activity(); } /** * Standard idle routine keeps the machine alive */ void idle( #if ENABLED(ADVANCED_PAUSE_FEATURE) bool no_stepper_sleep/*=false*/ #endif ) { #if ENABLED(MAX7219_DEBUG) max7219.idle_tasks(); #endif #ifdef ANYCUBIC_TFT_MODEL AnycubicTFT.CommandScan(); #endif #ifdef ENDSTOP_BEEP EndstopBeep(); #endif lcd_update(); host_keepalive(); manage_inactivity( #if ENABLED(ADVANCED_PAUSE_FEATURE) no_stepper_sleep #endif ); thermalManager.manage_heater(); #if ENABLED(PRINTCOUNTER) print_job_timer.tick(); #endif #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER) buzzer.tick(); #endif #if ENABLED(I2C_POSITION_ENCODERS) static millis_t i2cpem_next_update_ms; if (planner.has_blocks_queued() && ELAPSED(millis(), i2cpem_next_update_ms)) { I2CPEM.update(); i2cpem_next_update_ms = millis() + I2CPE_MIN_UPD_TIME_MS; } #endif #if HAS_AUTO_REPORTING if (!suspend_auto_report) { #if ENABLED(AUTO_REPORT_TEMPERATURES) thermalManager.auto_report_temperatures(); #endif #if ENABLED(AUTO_REPORT_SD_STATUS) card.auto_report_sd_status(); #endif } #endif } /** * Kill all activity and lock the machine. * After this the machine will need to be reset. */ void kill(const char* lcd_msg) { SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_KILLED); thermalManager.disable_all_heaters(); disable_all_steppers(); #if ENABLED(ULTRA_LCD) kill_screen(lcd_msg); #else UNUSED(lcd_msg); #endif #ifdef ANYCUBIC_TFT_MODEL // Kill AnycubicTFT AnycubicTFT.KillTFT(); #endif _delay_ms(600); // Wait a short time (allows messages to get out before shutting down. cli(); // Stop interrupts _delay_ms(250); //Wait to ensure all interrupts routines stopped thermalManager.disable_all_heaters(); //turn off heaters again #ifdef ACTION_ON_KILL SERIAL_ECHOLNPGM("//action:" ACTION_ON_KILL); #endif #if HAS_POWER_SWITCH PSU_OFF(); #endif suicide(); while (1) { #if ENABLED(USE_WATCHDOG) watchdog_reset(); #endif } // Wait for reset } /** * Turn off heaters and stop the print in progress * After a stop the machine may be resumed with M999 */ void stop() { thermalManager.disable_all_heaters(); // 'unpause' taken care of in here #if ENABLED(PROBING_FANS_OFF) if (fans_paused) fans_pause(false); // put things back the way they were #endif if (IsRunning()) { Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart SERIAL_ERROR_START(); SERIAL_ERRORLNPGM(MSG_ERR_STOPPED); LCD_MESSAGEPGM(MSG_STOPPED); safe_delay(350); // allow enough time for messages to get out before stopping Running = false; } } /** * Marlin entry-point: Set up before the program loop * - Set up the kill pin, filament runout, power hold * - Start the serial port * - Print startup messages and diagnostics * - Get EEPROM or default settings * - Initialize managers for: * • temperature * • planner * • watchdog * • stepper * • photo pin * • servos * • LCD controller * • Digipot I2C * • Z probe sled * • status LEDs */ void setup() { #if ENABLED(MAX7219_DEBUG) max7219.init(); #endif #if ENABLED(DISABLE_JTAG) // Disable JTAG on AT90USB chips to free up pins for IO MCUCR = 0x80; MCUCR = 0x80; #endif #if ENABLED(FILAMENT_RUNOUT_SENSOR) runout.setup(); #endif setup_killpin(); setup_powerhold(); #if HAS_STEPPER_RESET disableStepperDrivers(); #endif MYSERIAL0.begin(BAUDRATE); SERIAL_PROTOCOLLNPGM("start"); SERIAL_ECHO_START(); #ifdef ANYCUBIC_TFT_MODEL // Setup AnycubicTFT AnycubicTFT.Setup(); #endif // Prepare communication for TMC drivers #if HAS_DRIVER(TMC2130) tmc_init_cs_pins(); #endif #if HAS_DRIVER(TMC2208) tmc2208_serial_begin(); #endif // Check startup - does nothing if bootloader sets MCUSR to 0 byte mcu = MCUSR; if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP); if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET); if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET); if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET); if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET); MCUSR = 0; SERIAL_ECHOPGM(MSG_MARLIN); SERIAL_CHAR(' '); SERIAL_ECHOLNPGM(SHORT_BUILD_VERSION); SERIAL_ECHOPGM(MSG_MARLIN_AI3M); SERIAL_CHAR(' '); SERIAL_ECHOLNPGM(CUSTOM_BUILD_VERSION); SERIAL_EOL(); #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR) SERIAL_ECHO_START(); SERIAL_ECHOPGM(MSG_CONFIGURATION_VER); SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE); SERIAL_ECHOLNPGM(MSG_AUTHOR STRING_CONFIG_H_AUTHOR); SERIAL_ECHO_START(); SERIAL_ECHOLNPGM("Compiled: " __DATE__); #endif SERIAL_ECHO_START(); SERIAL_ECHOPAIR(MSG_FREE_MEMORY, freeMemory()); SERIAL_ECHOLNPAIR(MSG_PLANNER_BUFFER_BYTES, int(sizeof(block_t))*(BLOCK_BUFFER_SIZE)); // Send "ok" after commands by default for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true; // Load data from EEPROM if available (or use defaults) // This also updates variables in the planner, elsewhere (void)settings.load(); #if HAS_M206_COMMAND // Initialize current position based on home_offset COPY(current_position, home_offset); #else ZERO(current_position); #endif // Vital to init stepper/planner equivalent for current_position SYNC_PLAN_POSITION_KINEMATIC(); thermalManager.init(); // Initialize temperature loop print_job_timer.init(); // Initial setup of print job timer endstops.init(); // Init endstops and pullups stepper.init(); // Init stepper. This enables interrupts! servo_init(); // Initialize all servos, stow servo probe #if HAS_PHOTOGRAPH OUT_WRITE(PHOTOGRAPH_PIN, LOW); #endif #if HAS_CASE_LIGHT case_light_on = CASE_LIGHT_DEFAULT_ON; case_light_brightness = CASE_LIGHT_DEFAULT_BRIGHTNESS; update_case_light(); #endif #if ENABLED(SPINDLE_LASER_ENABLE) OUT_WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // init spindle to off #if SPINDLE_DIR_CHANGE OUT_WRITE(SPINDLE_DIR_PIN, SPINDLE_INVERT_DIR ? 255 : 0); // init rotation to clockwise (M3) #endif #if ENABLED(SPINDLE_LASER_PWM) SET_OUTPUT(SPINDLE_LASER_PWM_PIN); analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0); // set to lowest speed #endif #endif #if HAS_BED_PROBE endstops.enable_z_probe(false); #endif #if ENABLED(USE_CONTROLLER_FAN) SET_OUTPUT(CONTROLLER_FAN_PIN); //Set pin used for driver cooling fan #endif #if HAS_STEPPER_RESET enableStepperDrivers(); #endif #if ENABLED(DIGIPOT_I2C) digipot_i2c_init(); #endif #if ENABLED(DAC_STEPPER_CURRENT) dac_init(); #endif #if (ENABLED(Z_PROBE_SLED) || ENABLED(SOLENOID_PROBE)) && HAS_SOLENOID_1 OUT_WRITE(SOL1_PIN, LOW); // turn it off #endif #if HAS_HOME SET_INPUT_PULLUP(HOME_PIN); #endif #if PIN_EXISTS(STAT_LED_RED) OUT_WRITE(STAT_LED_RED_PIN, LOW); // turn it off #endif #if PIN_EXISTS(STAT_LED_BLUE) OUT_WRITE(STAT_LED_BLUE_PIN, LOW); // turn it off #endif #if HAS_COLOR_LEDS leds.setup(); #endif #if ENABLED(RGB_LED) || ENABLED(RGBW_LED) SET_OUTPUT(RGB_LED_R_PIN); SET_OUTPUT(RGB_LED_G_PIN); SET_OUTPUT(RGB_LED_B_PIN); #if ENABLED(RGBW_LED) SET_OUTPUT(RGB_LED_W_PIN); #endif #endif #if ENABLED(MK2_MULTIPLEXER) SET_OUTPUT(E_MUX0_PIN); SET_OUTPUT(E_MUX1_PIN); SET_OUTPUT(E_MUX2_PIN); #endif #if HAS_FANMUX fanmux_init(); #endif lcd_init(); lcd_reset_status(); #if ENABLED(SHOW_BOOTSCREEN) lcd_bootscreen(); #endif #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1 // Virtual Tools 0, 1, 2, 3 = Filament 1, 2, 3, 4, etc. for (uint8_t t = 0; t < MIXING_VIRTUAL_TOOLS && t < MIXING_STEPPERS; t++) for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mixing_virtual_tool_mix[t][i] = (t == i) ? 1.0 : 0.0; // Remaining virtual tools are 100% filament 1 #if MIXING_STEPPERS < MIXING_VIRTUAL_TOOLS for (uint8_t t = MIXING_STEPPERS; t < MIXING_VIRTUAL_TOOLS; t++) for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mixing_virtual_tool_mix[t][i] = (i == 0) ? 1.0 : 0.0; #endif // Initialize mixing to tool 0 color for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mixing_factor[i] = mixing_virtual_tool_mix[0][i]; #endif #if ENABLED(BLTOUCH) // Make sure any BLTouch error condition is cleared bltouch_command(BLTOUCH_RESET); set_bltouch_deployed(false); #endif #if ENABLED(I2C_POSITION_ENCODERS) I2CPEM.init(); #endif #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0 i2c.onReceive(i2c_on_receive); i2c.onRequest(i2c_on_request); #endif #if DO_SWITCH_EXTRUDER move_extruder_servo(0); // Initialize extruder servo #endif #if ENABLED(SWITCHING_NOZZLE) move_nozzle_servo(0); // Initialize nozzle servo #endif #if ENABLED(PARKING_EXTRUDER) #if ENABLED(PARKING_EXTRUDER_SOLENOIDS_INVERT) pe_activate_magnet(0); pe_activate_magnet(1); #else pe_deactivate_magnet(0); pe_deactivate_magnet(1); #endif #endif #if ENABLED(POWER_LOSS_RECOVERY) check_print_job_recovery(); #endif #if ENABLED(USE_WATCHDOG) watchdog_init(); #endif #if ENABLED(HANGPRINTER) enable_A(); enable_B(); enable_C(); enable_D(); #endif #if ENABLED(SDSUPPORT) && DISABLED(ULTRA_LCD) card.beginautostart(); #endif } /** * The main Marlin program loop * * - Abort SD printing if flagged * - Save or log commands to SD * - Process available commands (if not saving) * - Call heater manager * - Call inactivity manager * - Call endstop manager * - Call LCD update */ void loop() { #if ENABLED(SDSUPPORT) card.checkautostart(); if (card.abort_sd_printing) { card.stopSDPrint( #if SD_RESORT true #endif ); clear_command_queue(); quickstop_stepper(); print_job_timer.stop(); thermalManager.disable_all_heaters(); #if FAN_COUNT > 0 for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0; #endif wait_for_heatup = false; #if ENABLED(POWER_LOSS_RECOVERY) card.removeJobRecoveryFile(); #endif } #endif // SDSUPPORT if (commands_in_queue < BUFSIZE) get_available_commands(); if (commands_in_queue) { #if ENABLED(SDSUPPORT) if (card.saving) { char* command = command_queue[cmd_queue_index_r]; if (strstr_P(command, PSTR("M29"))) { // M29 closes the file card.closefile(); SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED); #if USE_MARLINSERIAL #if ENABLED(SERIAL_STATS_DROPPED_RX) SERIAL_ECHOLNPAIR("Dropped bytes: ", customizedSerial.dropped()); #endif #if ENABLED(SERIAL_STATS_MAX_RX_QUEUED) SERIAL_ECHOLNPAIR("Max RX Queue Size: ", customizedSerial.rxMaxEnqueued()); #endif #endif ok_to_send(); } else { // Write the string from the read buffer to SD card.write_command(command); if (card.logging) process_next_command(); // The card is saving because it's logging else ok_to_send(); } } else { process_next_command(); #if ENABLED(POWER_LOSS_RECOVERY) if (card.cardOK && card.sdprinting) save_job_recovery_info(); #endif } #else process_next_command(); #endif // SDSUPPORT // The queue may be reset by a command handler or by code invoked by idle() within a handler if (commands_in_queue) { --commands_in_queue; if (++cmd_queue_index_r >= BUFSIZE) cmd_queue_index_r = 0; } } endstops.event_handler(); idle(); #ifdef ANYCUBIC_TFT_MODEL AnycubicTFT.CommandScan(); #endif }
[ "master.zion@gmail.com" ]
master.zion@gmail.com
e294a7391cdd3b9404ae9192be99939b65fcd67b
8d9b42dfc3bdae1bc6e47c07326db3e4e3ab3ccb
/Src/Global/monsters.cpp
c1df0c6e0d0058d36ec4c62647056b153e474197
[]
no_license
Zacktamondo/HeartOfDarkness-SDL
bfd49a443a0d947b34f8772168710f3ddd7bb763
8df295e56bcea14d8923fc68735844b79d40d7cb
refs/heads/master
2022-11-26T01:50:12.988709
2020-08-03T08:17:59
2020-08-03T08:17:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
203,072
cpp
/* * Heart of Darkness engine rewrite * Copyright (C) 2009-2011 Gregory Montoir (cyx@users.sourceforge.net) */ #include "game.h" #include "level.h" #include "resource.h" #include "util.h" // (lut[x] & 1) indicates a diagonal direction static const uint8_t _mstLut1[] = { // 0 0x08, 0x00, // kDirectionKeyMaskUp 0x02, // kDirectionKeyMaskRight 0x01, // kDirectionKeyMaskUp | kDirectionKeyMaskRight // 4 0x04, // kDirectionKeyMaskDown 0x00, // kDirectionKeyMaskDown | kDirectionKeyMaskUp 0x03, // kDirectionKeyMaskDown | kDirectionKeyMaskRight 0x01, // kDirectionKeyMaskDown | kDirectionKeyMaskUp | kDirectionKeyMaskRight // 8 0x06, // kDirectionKeyMaskLeft 0x07, // kDirectionKeyMaskLeft | kDirectionKeyMaskUp 0x02, // kDirectionKeyMaskLeft | kDirectionKeyMaskRight 0x01, // kDirectionKeyMaskLeft | kDirectionKeyMaskUp | kDirectionKeyMaskRight // 12 0x05, // kDirectionKeyMaskLeft | kDirectionKeyMaskDown 0x07, // kDirectionKeyMaskLeft | kDirectionKeyMaskDown | kDirectionKeyMaskRight 0x03, // kDirectionKeyMaskLeft | kDirectionKeyMaskDown | kDirectionKeyMaskRight 0x01 // kDirectionKeyMaskLeft | kDirectionKeyMaskDown | kDirectionKeyMaskUp | kDirectionKeyMaskRight }; // indexes _mstLut1 static const uint8_t _mstLut3[8 * 5] = { 0x01, 0x03, 0x09, 0x02, 0x08, 0x03, 0x02, 0x01, 0x06, 0x09, 0x02, 0x06, 0x03, 0x04, 0x01, 0x06, 0x04, 0x02, 0x0C, 0x03, 0x04, 0x0C, 0x06, 0x08, 0x02, 0x0C, 0x08, 0x04, 0x09, 0x06, 0x08, 0x09, 0x0C, 0x01, 0x04, 0x09, 0x01, 0x08, 0x03, 0x0C }; // monster frames animation (minus #0, #4, #8, #12, #16, #20, eg. every 4th is skipped) static const uint8_t _mstLut4[] = { 0x01, 0x02, 0x03, 0x05, 0x06, 0x07, 0x09, 0x0A, 0x0B, 0x0D, 0x0E, 0x0F, 0x11, 0x12, 0x13, 0x15, 0x16, 0x17 }; // indexes _mstLut4 clipped to [0,17], repeat the frame preceding the skipped ones static const uint8_t _mstLut5[] = { 0x00, 0x00, 0x01, 0x02, 0x03, 0x03, 0x04, 0x05, 0x06, 0x06, 0x07, 0x08, 0x09, 0x09, 0x0A, 0x0B, 0x0C, 0x0C, 0x0D, 0x0E, 0x0F, 0x0F, 0x10, 0x11, 0x12, 0x12, 0x13, 0x14, 0x15, 0x15, 0x16, 0x17 }; static const uint8_t _fireflyPosData[] = { 0, 1, 2, 3, 4, 4, 4, 0xFF, 0, 1, 2, 2, 4, 4, 3, 0xFF, 0, 1, 1, 2, 3, 2, 3, 0xFF, 0, 1, 1, 2, 3, 3, 3, 0xFF, 0, 0, 1, 2, 2, 2, 2, 0xFF, 4, 4, 4, 3, 2, 1, 0, 0xFF, 3, 4, 4, 2, 2, 1, 0, 0xFF, 3, 2, 3, 2, 1, 1, 0, 0xFF, 3, 3, 3, 2, 1, 1, 0, 0xFF, 2, 2, 2, 2, 1, 0, 0, 0xFF }; static const uint8_t kUndefinedMonsterByteCode[] = { 0x12, 0x34 }; static uint8_t mstGetFacingDirectionMask(uint8_t a) { uint8_t r = 0; if (a & kDirectionKeyMaskLeft) { // Andy left facing monster r |= 1; } if (a & kDirectionKeyMaskDown) { // Andy below the monster r |= 2; } return r; } void Game::mstMonster1ResetData(MonsterObject1 *m) { m->m46 = 0; LvlObject *o = m->o16; if (o) { o->dataPtr = 0; } for (int i = 0; i < kMaxMonsterObjects2; ++i) { MonsterObject2 *mo = &_monsterObjects2Table[i]; if (mo->monster2Info && mo->monster1 == m) { mo->monster1 = 0; } } } void Game::mstMonster2InitFirefly(MonsterObject2 *m) { LvlObject *o = m->o; m->x1 = _res->_mstPointOffsets[o->screenNum].xOffset; m->y1 = _res->_mstPointOffsets[o->screenNum].yOffset; m->x2 = m->x1 + 255; m->y2 = m->y1 + 191; const uint32_t num = _rnd.update(); m->hPosIndex = num % 40; if (_fireflyPosData[m->hPosIndex] != 0xFF) { m->hPosIndex &= ~7; } m->vPosIndex = m->hPosIndex; if (num & 0x80) { m->hPosIndex += 40; } else { m->vPosIndex += 40; } m->hDir = (num >> 16) & 1; m->vDir = (num >> 17) & 1; } void Game::mstMonster2ResetData(MonsterObject2 *m) { m->monster2Info = 0; LvlObject *o = m->o; if (o) { o->dataPtr = 0; } } void Game::mstTaskSetMonster2ScreenPosition(Task *t) { MonsterObject2 *m = t->monster2; LvlObject *o = m->o; m->xPos = o->xPos + o->posTable[7].x; m->yPos = o->yPos + o->posTable[7].y; m->xMstPos = m->xPos + _res->_mstPointOffsets[o->screenNum].xOffset; m->yMstPos = m->yPos + _res->_mstPointOffsets[o->screenNum].yOffset; } void Game::mstMonster1ResetWalkPath(MonsterObject1 *m) { _rnd.resetMst(m->rnd_m35); _rnd.resetMst(m->rnd_m49); const uint8_t *ptr = m->monsterInfos; const int num = (~m->flagsA5) & 1; m->levelPosBounds_x2 = m->walkNode->coords[0][num] - (int32_t)READ_LE_UINT32(ptr + 904); m->levelPosBounds_x1 = m->walkNode->coords[1][num] + (int32_t)READ_LE_UINT32(ptr + 904); m->levelPosBounds_y2 = m->walkNode->coords[2][num] - (int32_t)READ_LE_UINT32(ptr + 908); m->levelPosBounds_y1 = m->walkNode->coords[3][num] + (int32_t)READ_LE_UINT32(ptr + 908); const uint32_t indexWalkCode = m->walkNode->walkCodeReset[num]; m->walkCode = (indexWalkCode == kNone) ? 0 : &_res->_mstWalkCodeData[indexWalkCode]; } bool Game::mstUpdateInRange(MstMonsterAction *m) { if (m->unk4 == 0) { if (mstHasMonsterInRange(m, 0) && addChasingMonster(m, 0)) { return true; } } else { int direction = _rnd.update() & 1; if (mstHasMonsterInRange(m, direction) && addChasingMonster(m, direction)) { return true; } direction ^= 1; if (mstHasMonsterInRange(m, direction) && addChasingMonster(m, direction)) { return true; } } return false; } bool Game::addChasingMonster(MstMonsterAction *m48, uint8_t direction) { debug(kDebug_MONSTER, "addChasingMonster %d", direction); m48->direction = direction; if (m48->codeData != kNone) { Task *t = createTask(_res->_mstCodeData + m48->codeData * 4); if (!t) { return false; } while ((this->*(t->run))(t) == 0); } _mstActionNum = m48 - &_res->_mstMonsterActionData[0]; _mstChasingMonstersCount = 0; for (int i = 0; i < m48->areaCount; ++i) { MstMonsterAreaAction *unk4 = m48->area[i].data; const uint8_t num = unk4->monster1Index; if (num != 0xFF) { assert(num < kMaxMonsterObjects1); unk4->direction = direction; MonsterObject1 *m = &_monsterObjects1Table[num]; m->action = unk4; m->flags48 |= 0x40; m->flagsA5 = (m->flagsA5 & ~0x75) | 0xA; mstMonster1ResetWalkPath(m); Task *current = _monsterObjects1TasksList; Task *t = m->task; assert(t); while (current) { Task *next = current->nextPtr; if (current == t) { removeTask(&_monsterObjects1TasksList, t); appendTask(&_monsterObjects1TasksList, t); break; } current = next; } const uint32_t codeData = unk4->codeData; assert(codeData != kNone); resetTask(t, _res->_mstCodeData + codeData * 4); ++_mstChasingMonstersCount; } } debug(kDebug_MONSTER, "_mstChasingMonstersCount %d", _mstChasingMonstersCount); return true; } void Game::mstMonster1ClearChasingMonster(MonsterObject1 *m) { m->flags48 &= ~0x50; m->action->monster1Index = 0xFF; m->action = 0; --_mstChasingMonstersCount; if (_mstChasingMonstersCount <= 0) { _mstActionNum = -1; } } void Game::mstTaskSetMonster1BehaviorState(Task *t, MonsterObject1 *m, int num) { MstBehaviorState *behaviorState = &m->m46->data[num]; m->behaviorState = behaviorState; m->monsterInfos = _res->_mstMonsterInfos + behaviorState->indexMonsterInfo * kMonsterInfoDataSize; if (behaviorState->indexUnk51 == kNone) { m->flags48 &= ~4; } const uint32_t indexWalkPath = behaviorState->walkPath; m->walkNode = _res->_mstWalkPathData[indexWalkPath].data; mstTaskUpdateScreenPosition(t); if (!mstMonster1UpdateWalkPath(m)) { mstMonster1ResetWalkPath(m); } if (t->run == &Game::mstTask_monsterWait4) { t->run = &Game::mstTask_main; } if ((m->flagsA5 & 8) == 0 && t->run == &Game::mstTask_idle) { mstTaskSetNextWalkCode(t); } } int Game::mstTaskStopMonsterObject1(Task *t) { if (_mstActionNum == -1) { return 0; } MonsterObject1 *m = t->monster1; // bugfix: original code meant to check bit 3 directly ? // const uint8_t r = (m->flagsA5 == 0) ? 1 : 0; // if ((r & 8) != 0) { // return 0; // } const MstMonsterAreaAction *m48 = m->action; if (!m48) { return 0; } const uint32_t codeData = m48->codeData2; if (codeData != kNone) { resetTask(t, _res->_mstCodeData + codeData * 4); mstMonster1ClearChasingMonster(m); return 0; } mstMonster1ClearChasingMonster(m); if (m->flagsA5 & 0x80) { m->flagsA5 &= ~8; const uint32_t codeData = m->behaviorState->codeData; if (codeData != kNone) { resetTask(t, _res->_mstCodeData + codeData * 4); return 0; } m->o16->actionKeyMask = 7; m->o16->directionKeyMask = 0; t->run = &Game::mstTask_idle; return 0; } m->flagsA5 = (m->flagsA5 & ~9) | 6; if (m->flagsA6 & 2) { return 0; } return mstTaskInitMonster1Type2(t, 1); } void Game::mstMonster1SetScreenPosition(MonsterObject1 *m) { LvlObject *o = m->o16; o->xPos = m->xPos - o->posTable[7].x; o->yPos = m->yPos - o->posTable[7].y; m->xMstPos = m->xPos + _res->_mstPointOffsets[o->screenNum].xOffset; m->yMstPos = m->yPos + _res->_mstPointOffsets[o->screenNum].yOffset; } bool Game::mstMonster1SetWalkingBounds(MonsterObject1 *m) { MstBehaviorState *behaviorState = m->behaviorState; const uint32_t indexWalkPath = behaviorState->walkPath; MstWalkPath *walkPath = &_res->_mstWalkPathData[indexWalkPath]; MstWalkNode *walkNode = walkPath->data; int x = m->xMstPos; int y = m->yMstPos; if (m->levelPosBounds_x1 >= 0) { if (x < m->levelPosBounds_x1) { x = m->levelPosBounds_x1; } else if (x > m->levelPosBounds_x2) { x = m->levelPosBounds_x2; } if (y < m->levelPosBounds_y1) { y = m->levelPosBounds_y1; } else if (y > m->levelPosBounds_y2) { y = m->levelPosBounds_y2; } } const uint32_t indexWalkBox = walkPath->data[0].walkBox; const MstWalkBox *m34 = &_res->_mstWalkBoxData[indexWalkBox]; int xWalkBox = (m34->right - m34->left) / 2 + m34->left; int minDistance = 0x1000000; int yWalkBox = y; uint32_t i = 0; for (; i < walkPath->count; ++i) { const uint32_t indexWalkBox = walkPath->data[i].walkBox; const MstWalkBox *m34 = &_res->_mstWalkBoxData[indexWalkBox]; if (!rect_contains(m34->left, m34->top, m34->right, m34->bottom, x, y)) { // find the closest box const int d1 = ABS(x - m34->left); if (d1 < minDistance) { minDistance = d1; walkNode = &walkPath->data[i]; xWalkBox = m34->left; } const int d2 = ABS(x - m34->right); if (d2 < minDistance) { minDistance = d2; walkNode = &walkPath->data[i]; xWalkBox = m34->right; } } else { // find match, point is in the box xWalkBox = x; yWalkBox = y; walkNode = &walkPath->data[i]; break; } } if (i == walkPath->count) { // calculate the yPos for the walkBox const uint32_t indexWalkBox = walkNode->walkBox; const MstWalkBox *m34 = &_res->_mstWalkBoxData[indexWalkBox]; if (y <= m34->bottom) { y = (m34->bottom - m34->top) / 2 + m34->top; } yWalkBox = y; } // find screenNum for level position int screenNum = -1; int xLevelPos; int yLevelPos; for (int i = 0; i < _res->_mstHdr.screensCount; ++i) { xLevelPos = _res->_mstPointOffsets[i].xOffset; yLevelPos = _res->_mstPointOffsets[i].yOffset; if (rect_contains(xLevelPos, yLevelPos, xLevelPos + 255, yLevelPos + 191, xWalkBox, yWalkBox)) { screenNum = i; break; } } if (screenNum == -1) { screenNum = 0; xLevelPos = _res->_mstPointOffsets[0].xOffset + 256 / 2; yLevelPos = _res->_mstPointOffsets[0].yOffset + 192 / 2; } LvlObject *o = m->o16; o->screenNum = screenNum; m->xPos = xWalkBox - xLevelPos; m->yPos = yWalkBox - yLevelPos; mstMonster1SetScreenPosition(m); m->walkNode = walkNode; mstMonster1ResetWalkPath(m); return true; } bool Game::mstMonster1UpdateWalkPath(MonsterObject1 *m) { debug(kDebug_MONSTER, "mstMonster1UpdateWalkPath m %p", m); const uint8_t screenNum = m->o16->screenNum; MstBehaviorState *behaviorState = m->behaviorState; const uint32_t indexWalkPath = behaviorState->walkPath; MstWalkPath *walkPath = &_res->_mstWalkPathData[indexWalkPath]; // start from screen number uint32_t indexWalkNode = walkPath->walkNodeData[screenNum]; if (indexWalkNode != kNone) { MstWalkNode *walkNode = &walkPath->data[indexWalkNode]; uint32_t indexWalkBox = walkNode->walkBox; const MstWalkBox *m34 = &_res->_mstWalkBoxData[indexWalkBox]; while (m34->left <= m->xMstPos) { if (m34->right >= m->xMstPos && m34->top <= m->yMstPos && m34->bottom >= m->yMstPos) { if (m->walkNode == walkNode) { return false; } m->walkNode = walkNode; mstMonster1ResetWalkPath(m); return true; } indexWalkNode = walkNode->nextWalkNode; if (indexWalkNode == kNone) { break; } walkNode = &walkPath->data[indexWalkNode]; indexWalkBox = walkNode->walkBox; m34 = &_res->_mstWalkBoxData[indexWalkBox]; } } return mstMonster1SetWalkingBounds(m); } uint32_t Game::mstMonster1GetNextWalkCode(MonsterObject1 *m) { MstWalkCode *walkCode = m->walkCode; int num = 0; if (walkCode->indexDataCount != 0) { num = _rnd.getMstNextNumber(m->rnd_m35); num = walkCode->indexData[num]; } const uint32_t codeData = walkCode->codeData[num]; return codeData; } int Game::mstTaskSetNextWalkCode(Task *t) { MonsterObject1 *m = t->monster1; assert(m); const uint32_t codeData = mstMonster1GetNextWalkCode(m); assert(codeData != kNone); resetTask(t, _res->_mstCodeData + codeData * 4); const int counter = m->executeCounter; m->executeCounter = _executeMstLogicCounter; return m->executeCounter - counter; } void Game::mstBoundingBoxClear(MonsterObject1 *m, int dir) { assert(dir == 0 || dir == 1); uint8_t num = m->bboxNum[dir]; if (num < _mstBoundingBoxesCount && _mstBoundingBoxesTable[num].monster1Index == m->monster1Index) { _mstBoundingBoxesTable[num].monster1Index = 0xFF; int i = num; for (; i < _mstBoundingBoxesCount; ++i) { if (_mstBoundingBoxesTable[i].monster1Index != 0xFF) { break; } } if (i == _mstBoundingBoxesCount) { _mstBoundingBoxesCount = num; } } m->bboxNum[dir] = 0xFF; } int Game::mstBoundingBoxCollides1(int num, int x1, int y1, int x2, int y2) const { for (int i = 0; i < _mstBoundingBoxesCount; ++i) { const MstBoundingBox *p = &_mstBoundingBoxesTable[i]; if (p->monster1Index == 0xFF || num == p->monster1Index) { continue; } if (rect_intersects(x1, y1, x2, y2, p->x1, p->y1, p->x2, p->y2)) { return i + 1; } } return 0; } int Game::mstBoundingBoxUpdate(int num, int monster1Index, int x1, int y1, int x2, int y2) { if (num == 0xFF) { for (num = 0; num < _mstBoundingBoxesCount; ++num) { if (_mstBoundingBoxesTable[num].monster1Index == 0xFF) { break; } } assert(num < kMaxBoundingBoxes); MstBoundingBox *p = &_mstBoundingBoxesTable[num]; p->x1 = x1; p->y1 = y1; p->x2 = x2; p->y2 = y2; p->monster1Index = monster1Index; if (num == _mstBoundingBoxesCount) { ++_mstBoundingBoxesCount; } } else if (num < _mstBoundingBoxesCount) { MstBoundingBox *p = &_mstBoundingBoxesTable[num]; if (p->monster1Index == monster1Index) { p->x1 = x1; p->y1 = y1; p->x2 = x2; p->y2 = y2; } } return num; } int Game::mstBoundingBoxCollides2(int monster1Index, int x1, int y1, int x2, int y2) const { for (int i = 0; i < _mstBoundingBoxesCount; ++i) { const MstBoundingBox *p = &_mstBoundingBoxesTable[i]; if (p->monster1Index == 0xFF || p->monster1Index == monster1Index) { continue; } if (p->monster1Index == 0xFE) { // Andy if (_monsterObjects1Table[monster1Index].monsterInfos[944] != 15) { continue; } } if (rect_intersects(x1, y1, x2, y2, p->x1, p->y1, p->x2, p->y2)) { return i + 1; } } return 0; } int Game::getMstDistance(int y, const AndyShootData *p) const { switch (p->directionMask) { case 0: if (p->boundingBox.x1 <= _mstTemp_x2 && p->boundingBox.y2 >= _mstTemp_y1 && p->boundingBox.y1 <= _mstTemp_y2) { const int dx = _mstTemp_x1 - p->boundingBox.x2; if (dx <= 0) { return 0; } return (p->type == 3) ? 0 : dx / p->width; } break; case 1: { const int dx = p->boundingBox.x2 - _mstTemp_x1; if (dx >= 0) { const int dy = p->boundingBox.y1 - dx * 2 / 3; if (dy <= _mstTemp_y2) { const int dx2 = p->boundingBox.x1 - _mstTemp_x2; if (dx2 <= 0) { return (p->boundingBox.y2 >= _mstTemp_y1) ? 0 : -1; } const int dy2 = p->boundingBox.y2 + dx2 * 2 / 3; if (dy2 > _mstTemp_y1) { return (p->type == 3) ? 0 : dx2 / p->width; } } } } break; case 2: { const int dx = _mstTemp_x1 - p->boundingBox.x2; if (dx >= 0) { const int dy = p->boundingBox.y2 + dx * 2 / 3; if (dy >= _mstTemp_x1) { const int dx2 = p->boundingBox.x1 - _mstTemp_x2; if (dx2 <= 0) { return (p->boundingBox.y1 <= _mstTemp_y2) ? 0 : -1; } const int dy2 = p->boundingBox.y1 + dx2 * 2 / 3; if (dy2 <= _mstTemp_y2) { return (p->type == 3) ? 0 : dx2 / p->width; } } } } break; case 3: { const int dx = _mstTemp_x2 - p->boundingBox.x1; if (dx >= 0) { const int dy = p->boundingBox.y1 - dx * 2 / 3; if (dy <= _mstTemp_y2) { const int dx2 = _mstTemp_x1 - p->boundingBox.x2; if (dx2 <= 0) { return (p->boundingBox.y2 >= _mstTemp_y1) ? 0 : -1; } const int dy2 = p->boundingBox.y2 - dx2 * 2 / 3; if (dy2 >= _mstTemp_y1) { return (p->type == 3) ? 0 : dx2 / p->width; } } } } break; case 4: { const int dx = _mstTemp_x2 - p->boundingBox.x1; if (dx >= 0) { const int dy = dx * 2 / 3 + p->boundingBox.y2; if (dy >= _mstTemp_y1) { const int dx2 = _mstTemp_x1 - p->boundingBox.x2; if (dx2 <= 0) { return (p->boundingBox.y1 <= _mstTemp_y2) ? 0 : -1; } const int dy2 = dx2 * 2 / 3 + + p->boundingBox.y1; if (dy2 <= _mstTemp_y2) { return (p->type == 3) ? 0 : dx2 / p->width; } } } } break; case 5: if (p->boundingBox.x2 >= _mstTemp_x1 && p->boundingBox.y2 >= _mstTemp_y1 && p->boundingBox.y1 <= _mstTemp_y2) { const int dx = p->boundingBox.x1 - _mstTemp_x2; if (dx <= 0) { return 0; } return (p->type == 3) ? 0 : dx / p->width; } break; case 6: if (p->boundingBox.y2 >= _mstTemp_y1 && p->boundingBox.x2 >= _mstTemp_x1 && p->boundingBox.x1 <= _mstTemp_x2) { const int dy = p->boundingBox.y1 - _mstTemp_y2; if (dy <= 0) { return 0; } return (p->type == 3) ? 0 : dy / p->height; } break; case 7: if (p->boundingBox.y1 <= _mstTemp_y2 && p->boundingBox.x2 >= _mstTemp_x1 && p->boundingBox.x1 <= _mstTemp_x2) { const int dy = _mstTemp_y1 - p->boundingBox.y2; if (dy <= 0) { return 0; } return (p->type == 3) ? 0 : dy / p->height; } break; case 128: // 8 if (p->boundingBox.x1 <= _mstTemp_x2 && y >= _mstTemp_y1 && y - _mstTemp_y2 <= 9) { const int dx = _mstTemp_x1 - p->boundingBox.x2; if (dx <= 0) { return 0; } return dx / p->width; } break; case 133: // 9 if (p->boundingBox.x2 >= _mstTemp_x1 && y >= _mstTemp_y1 && y - _mstTemp_y2 <= 9) { const int dx = _mstTemp_x2 - p->boundingBox.x1; if (dx <= 0) { return 0; } return dx / p->width; } break; } return -1; } void Game::mstTaskUpdateScreenPosition(Task *t) { MonsterObject1 *m = t->monster1; assert(m); LvlObject *o = m->o20; if (!o) { o = m->o16; } assert(o); m->xPos = o->xPos + o->posTable[7].x; m->yPos = o->yPos + o->posTable[7].y; m->xMstPos = m->xPos + _res->_mstPointOffsets[o->screenNum].xOffset; m->yMstPos = m->yPos + _res->_mstPointOffsets[o->screenNum].yOffset; const uint8_t *ptr = m->monsterInfos; if (ptr[946] & 4) { const uint8_t *ptr1 = ptr + (o->flags0 & 0xFF) * 28; if (ptr1[0xE] != 0) { _mstTemp_x1 = m->xMstPos + (int8_t)ptr1[0xC]; _mstTemp_y1 = m->yMstPos + (int8_t)ptr1[0xD]; _mstTemp_x2 = _mstTemp_x1 + ptr1[0xE] - 1; _mstTemp_y2 = _mstTemp_y1 + ptr1[0xF] - 1; m->bboxNum[0] = mstBoundingBoxUpdate(m->bboxNum[0], m->monster1Index, _mstTemp_x1, _mstTemp_y1, _mstTemp_x2, _mstTemp_y2); } else { mstBoundingBoxClear(m, 0); } } m->xDelta = _mstAndyLevelPosX - m->xMstPos; if (m->xDelta < 0) { m->xDelta = -m->xDelta; m->facingDirectionMask = kDirectionKeyMaskLeft; } else { m->facingDirectionMask = kDirectionKeyMaskRight; } m->yDelta = _mstAndyLevelPosY - m->yMstPos; if (m->yDelta < 0) { m->yDelta = -m->yDelta; m->facingDirectionMask |= kDirectionKeyMaskUp; } else { m->facingDirectionMask |= kDirectionKeyMaskDown; } m->collideDistance = -1; m->shootData = 0; if (_andyShootsCount != 0 && !_specialAnimFlag && (o->flags1 & 6) != 6 && (m->localVars[7] > 0 || m->localVars[7] < -1) && (m->flagsA5 & 0x80) == 0) { for (int i = 0; i < _andyShootsCount; ++i) { AndyShootData *p = &_andyShootsTable[i]; if (m->xDelta > 256 || m->yDelta > 192) { continue; } _mstTemp_x1 = o->xPos; _mstTemp_y1 = o->yPos; _mstTemp_x2 = o->xPos + o->width - 1; _mstTemp_y2 = o->yPos + o->height - 1; const uint8_t _al = p->type; if (_al == 1 || _al == 2) { if (p->monsterDistance >= m->xDelta + m->yDelta) { if (o->screenNum != _currentScreen) { const int dx = _res->_mstPointOffsets[o->screenNum].xOffset - _res->_mstPointOffsets[_currentScreen].xOffset; const int dy = _res->_mstPointOffsets[o->screenNum].yOffset - _res->_mstPointOffsets[_currentScreen].yOffset; _mstTemp_x1 += dx; _mstTemp_x2 += dx; _mstTemp_y1 += dy; _mstTemp_y2 += dy; } if (rect_intersects(0, 0, 255, 191, _mstTemp_x1, _mstTemp_y1, _mstTemp_x2, _mstTemp_y2)) { const uint8_t type = m->monsterInfos[944]; if ((type == 9 && clipLvlObjectsSmall(p->o, o, 132)) || (type != 9 && clipLvlObjectsSmall(p->o, o, 20))) { p->m = m; p->monsterDistance = m->xDelta + m->yDelta; p->clipX = _clipBoxOffsetX; p->clipY = _clipBoxOffsetY; } } if (o->screenNum != _currentScreen) { const int dx = _res->_mstPointOffsets[_currentScreen].xOffset - _res->_mstPointOffsets[o->screenNum].xOffset; const int dy = _res->_mstPointOffsets[_currentScreen].yOffset - _res->_mstPointOffsets[o->screenNum].yOffset; _mstTemp_x1 += dx; _mstTemp_x2 += dx; _mstTemp_y1 += dy; _mstTemp_y2 += dy; } } } else if (_al == 3 && p->monsterDistance > m->xDelta + m->yDelta) { if (o->screenNum != _currentScreen) { const int dx = _res->_mstPointOffsets[o->screenNum].xOffset - _res->_mstPointOffsets[_currentScreen].xOffset; const int dy = _res->_mstPointOffsets[o->screenNum].yOffset - _res->_mstPointOffsets[_currentScreen].yOffset; _mstTemp_x1 += dx; _mstTemp_x2 += dx; _mstTemp_y1 += dy; _mstTemp_y2 += dy; } if (rect_intersects(0, 0, 255, 191, _mstTemp_x1, _mstTemp_y1, _mstTemp_x2, _mstTemp_y2)) { if (testPlasmaCannonPointsDirection(_mstTemp_x1, _mstTemp_y1, _mstTemp_x2, _mstTemp_y2)) { p->monsterDistance = m->xDelta + m->yDelta; p->m = m; p->plasmaCannonPointsCount = _plasmaCannonLastIndex1; } } const int dx = _res->_mstPointOffsets[_currentScreen].xOffset - _res->_mstPointOffsets[o->screenNum].xOffset; const int dy = _res->_mstPointOffsets[_currentScreen].yOffset - _res->_mstPointOffsets[o->screenNum].yOffset; _mstTemp_x1 += dx; _mstTemp_x2 += dx; _mstTemp_y1 += dy; _mstTemp_y2 += dy; } _mstTemp_x1 += _res->_mstPointOffsets[o->screenNum].xOffset; _mstTemp_y1 += _res->_mstPointOffsets[o->screenNum].yOffset; _mstTemp_x2 += _res->_mstPointOffsets[o->screenNum].xOffset; _mstTemp_y2 += _res->_mstPointOffsets[o->screenNum].yOffset; int res = getMstDistance((m->monsterInfos[946] & 2) != 0 ? p->boundingBox.y2 : m->yMstPos, p); if (res < 0) { continue; } if (m->collideDistance == -1 || m->collideDistance > res || (m->collideDistance == 0 && res == 0 && (m->shootData->type & 1) == 0 && p->type == 2)) { m->shootData = p; m->collideDistance = res; } } } if (m->facingDirectionMask & kDirectionKeyMaskLeft) { m->goalPosBounds_x1 = READ_LE_UINT32(ptr + 920); m->goalPosBounds_x2 = READ_LE_UINT32(ptr + 924); } else { m->goalPosBounds_x1 = READ_LE_UINT32(ptr + 912); m->goalPosBounds_x2 = READ_LE_UINT32(ptr + 916); } // m->unk90 = // m->unk8C = if (_andyShootsTable[0].type == 3 && m->shootSource != 0 && _andyShootsTable[0].directionMask == m->shootDirection && m->directionKeyMask == _andyObject->directionKeyMask) { m->flags48 |= 0x80; } else { m->shootDirection = -1; m->flags48 &= ~0x80; } } void Game::shuffleMstMonsterActionIndex(MstMonsterActionIndex *p) { for (uint32_t i = 0; i < p->dataCount; ++i) { p->data[i] &= 0x7F; } shuffleArray(p->data, p->dataCount); } void Game::initMstCode() { memset(_mstVars, 0, sizeof(_mstVars)); if (_mstDisabled) { return; } // _mstLut initialization resetMstCode(); } void Game::resetMstCode() { if (_mstDisabled) { return; } _mstFlags = 0; for (int i = 0; i < kMaxMonsterObjects1; ++i) { mstMonster1ResetData(&_monsterObjects1Table[i]); } for (int i = 0; i < kMaxMonsterObjects2; ++i) { mstMonster2ResetData(&_monsterObjects2Table[i]); } clearLvlObjectsList1(); for (int i = 0; i < _res->_mstHdr.screenAreaDataCount; ++i) { _res->_mstScreenAreaData[i].unk0x1D = 1; } _rnd.initMstTable(); _rnd.initTable(); for (int i = 0; i < _res->_mstHdr.movingBoundsDataCount; ++i) { const int count = _res->_mstMovingBoundsData[i].indexDataCount; if (count != 0) { shuffleArray(_res->_mstMovingBoundsData[i].indexData, count); } } for (int i = 0; i < _res->_mstHdr.walkCodeDataCount; ++i) { const int count = _res->_mstWalkCodeData[i].indexDataCount; if (count != 0) { shuffleArray(_res->_mstWalkCodeData[i].indexData, count); } } for (int i = 0; i < _res->_mstHdr.monsterActionIndexDataCount; ++i) { shuffleMstMonsterActionIndex(&_res->_mstMonsterActionIndexData[i]); } _mstOp67_x1 = -256; _mstOp67_x2 = -256; memset(_monsterObjects1Table, 0, sizeof(_monsterObjects1Table)); memset(_monsterObjects2Table, 0, sizeof(_monsterObjects2Table)); memset(_mstVars, 0, sizeof(_mstVars)); memset(_tasksTable, 0, sizeof(_tasksTable)); _m43Num3 = _m43Num1 = _m43Num2 = _mstActionNum = -1; _mstOp54Counter = 0; // bugfix: not reset in the original, causes uninitialized reads at the beginning of 'fort' _executeMstLogicPrevCounter = _executeMstLogicCounter = 0; // _mstUnk8 = 0; _specialAnimFlag = false; _mstAndyRectNum = 0xFF; _mstBoundingBoxesCount = 0; _mstOp67_y1 = 0; _mstOp67_y2 = 0; _mstOp67_screenNum = -1; _mstOp68_x1 = 256; _mstOp68_x2 = 256; _mstOp68_y1 = 0; _mstOp68_y2 = 0; _mstOp68_screenNum = -1; _mstLevelGatesMask = 0; // _mstLevelGatesTestMask = 0xFFFFFFFF; _mstAndyVarMask = 0; _tasksList = 0; _monsterObjects1TasksList = 0; _monsterObjects2TasksList = 0; // _mstTasksList3 = 0; // _mstTasksList4 = 0; if (_res->_mstTickCodeData != kNone) { _mstVars[31] = _mstTickDelay = _res->_mstTickDelay; } else { _mstVars[31] = -1; } _mstVars[30] = 0x20; for (int i = 0; i < kMaxMonsterObjects1; ++i) { _monsterObjects1Table[i].monster1Index = i; } for (int i = 0; i < kMaxMonsterObjects2; ++i) { _monsterObjects2Table[i].monster2Index = i; } mstUpdateRefPos(); _mstAndyLevelPrevPosX = _mstAndyLevelPosX; _mstAndyLevelPrevPosY = _mstAndyLevelPosY; } void Game::startMstCode() { mstUpdateRefPos(); _mstAndyLevelPrevPosX = _mstAndyLevelPosX; _mstAndyLevelPrevPosY = _mstAndyLevelPosY; int offset = 0; for (int i = 0; i < _res->_mstHdr.infoMonster1Count; ++i) { offset += kMonsterInfoDataSize; const uint32_t unk30 = READ_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x30]); // 900 const uint32_t unk34 = READ_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x34]); // 896 const uint32_t unk20 = _mstAndyLevelPosX - unk30; const uint32_t unk1C = _mstAndyLevelPosX + unk30; WRITE_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x20], unk20); WRITE_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x1C], unk1C); WRITE_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x24], unk20 - unk34); WRITE_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x18], unk1C + unk34); const uint32_t unk10 = _mstAndyLevelPosY - unk30; const uint32_t unk0C = _mstAndyLevelPosY + unk30; WRITE_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x10], unk10); WRITE_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x0C], unk0C); WRITE_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x14], unk10 - unk34); WRITE_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x08], unk0C + unk34); } if (_level->_checkpoint < _res->_mstHdr.levelCheckpointCodeDataCount) { const uint32_t codeData = _res->_mstLevelCheckpointCodeData[_level->_checkpoint]; if (codeData != kNone) { Task *t = createTask(_res->_mstCodeData + codeData * 4); if (t) { _runTaskOpcodesCount = 0; while ((this->*(t->run))(t) == 0); } } } } static bool compareOp(int op, int num1, int num2) { switch (op) { case 0: return num1 != num2; case 1: return num1 == num2; case 2: return num1 >= num2; case 3: return num1 > num2; case 4: return num1 <= num2; case 5: return num1 < num2; case 6: return (num1 & num2) == 0; case 7: return (num1 | num2) == 0; case 8: return (num1 ^ num2) == 0; default: error("compareOp unhandled op %d", op); break; } return false; } static void arithOp(int op, int *p, int num) { switch (op) { case 0: *p = num; break; case 1: *p += num; break; case 2: *p -= num; break; case 3: *p *= num; break; case 4: if (num != 0) { *p /= num; } break; case 5: *p <<= num; break; case 6: *p >>= num; break; case 7: *p &= num; break; case 8: *p |= num; break; case 9: *p ^= num; break; default: error("arithOp unhandled op %d", op); break; } } void Game::executeMstCode() { _andyActionKeyMaskAnd = 0xFF; _andyDirectionKeyMaskAnd = 0xFF; _andyActionKeyMaskOr = 0; _andyDirectionKeyMaskOr = 0; if (_mstDisabled) { return; } ++_executeMstLogicCounter; if (_mstLevelGatesMask != 0) { _mstHelper1Count = 0; executeMstCodeHelper1(); _mstLevelGatesMask = 0; } for (int i = 0; i < kMaxAndyShoots; ++i) { _andyShootsTable[i].shootObjectData = 0; _andyShootsTable[i].m = 0; _andyShootsTable[i].monsterDistance = 0x1000000; } mstUpdateMonster1ObjectsPosition(); if (_mstVars[31] > 0) { --_mstVars[31]; if (_mstVars[31] == 0) { uint32_t codeData = _res->_mstTickCodeData; assert(codeData != kNone); Task *t = createTask(_res->_mstCodeData + codeData * 4); if (t) { t->state = 1; } } } const MstScreenArea *msac; while ((msac = _res->findMstCodeForPos(_currentScreen, _mstAndyLevelPosX, _mstAndyLevelPosY)) != 0) { debug(kDebug_MONSTER, "trigger for %d,%d", _mstAndyLevelPosX, _mstAndyLevelPosY); _res->flagMstCodeForPos(msac->unk0x1C, 0); assert(msac->codeData != kNone); createTask(_res->_mstCodeData + msac->codeData * 4); } if (_mstAndyCurrentScreenNum != _currentScreen) { _mstAndyCurrentScreenNum = _currentScreen; } for (Task *t = _tasksList; t; t = t->nextPtr) { _runTaskOpcodesCount = 0; while ((this->*(t->run))(t) == 0); } for (int i = 0; i < _andyShootsCount; ++i) { AndyShootData *p = &_andyShootsTable[i]; MonsterObject1 *m = p->m; if (!m) { continue; } const int energy = m->localVars[7]; ShootLvlObjectData *dat = p->shootObjectData; if (dat) { if (energy > 0) { if (_cheats & kCheatOneHitSpecialPowers) { m->localVars[7] = 0; } else if (p->type == 2) { m->localVars[7] -= 4; if (m->localVars[7] < 0) { m->localVars[7] = 0; } } else { --m->localVars[7]; } dat->unk3 = 0x80; dat->xPosShoot = p->clipX; dat->yPosShoot = p->clipY; dat->o = m->o16; } else if (energy == -2) { dat->unk3 = 0x80; dat->xPosShoot = p->clipX; dat->yPosShoot = p->clipY; } continue; } if (energy > 0) { if (_cheats & kCheatOneHitPlasmaCannon) { m->localVars[7] = 0; } else { m->localVars[7] = energy - 1; } _plasmaCannonLastIndex1 = p->plasmaCannonPointsCount; } else if (energy == -2) { _plasmaCannonLastIndex1 = p->plasmaCannonPointsCount; } else { _plasmaCannonLastIndex1 = 0; } } for (Task *t = _monsterObjects1TasksList; t; t = t->nextPtr) { _runTaskOpcodesCount = 0; if (mstUpdateTaskMonsterObject1(t) == 0) { while ((this->*(t->run))(t) == 0); } } for (Task *t = _monsterObjects2TasksList; t; t = t->nextPtr) { _runTaskOpcodesCount = 0; if (mstUpdateTaskMonsterObject2(t) == 0) { while ((this->*(t->run))(t) == 0); } } } void Game::mstWalkPathUpdateIndex(MstWalkPath *walkPath, int index) { uint32_t _walkNodesTable[32]; int _walkNodesFirstIndex, _walkNodesLastIndex; int32_t buffer[64]; for (uint32_t i = 0; i < walkPath->count; ++i) { MstWalkNode *walkNode = &walkPath->data[i]; memset(buffer, 0xFF, sizeof(buffer)); memset(walkNode->unk60[index], 0, walkPath->count); _walkNodesTable[0] = i; _walkNodesLastIndex = 1; buffer[i] = 0; _walkNodesFirstIndex = 0; while (_walkNodesFirstIndex != _walkNodesLastIndex) { uint32_t vf = _walkNodesTable[_walkNodesFirstIndex]; ++_walkNodesFirstIndex; if (_walkNodesFirstIndex >= 32) { _walkNodesFirstIndex = 0; } const uint32_t indexWalkBox = walkPath->data[vf].walkBox; const MstWalkBox *m34 = &_res->_mstWalkBoxData[indexWalkBox]; for (int j = 0; j < 4; ++j) { const uint32_t indexWalkNode = walkPath->data[vf].neighborWalkNode[j]; if (indexWalkNode == kNone) { continue; } assert(indexWalkNode < walkPath->count); uint32_t mask; const uint8_t flags = m34->flags[j]; if (flags & 0x80) { mask = _mstAndyVarMask & (1 << (flags & 0x7F)); } else { mask = flags & (1 << index); } if (mask != 0) { continue; } int delta; if (j == 0 || j == 1) { delta = m34->right - m34->left + buffer[vf]; } else { delta = m34->bottom - m34->top + buffer[vf]; } if (delta >= buffer[i]) { continue; } if (buffer[indexWalkNode] == -1) { _walkNodesTable[_walkNodesLastIndex] = indexWalkNode; ++_walkNodesLastIndex; if (_walkNodesLastIndex >= 32) { _walkNodesLastIndex = 0; } } buffer[i] = delta; uint8_t value; if (vf == i) { static const uint8_t directions[] = { 2, 8, 4, 1 }; value = directions[j]; } else { value = walkNode->unk60[index][vf]; } walkNode->unk60[index][i] = value; } } } } int Game::mstWalkPathUpdateWalkNode(MstWalkPath *walkPath, MstWalkNode *walkNode, int num, int index) { if (walkNode->coords[num][index] < 0) { const uint32_t indexWalkBox = walkNode->walkBox; const MstWalkBox *m34 = &_res->_mstWalkBoxData[indexWalkBox]; uint32_t mask; const uint8_t flags = m34->flags[num]; if (flags & 0x80) { mask = _mstAndyVarMask & (1 << (flags & 0x7F)); } else { mask = flags & (1 << index); } if (mask) { switch (num) { // ((int *)&m34)[num] case 0: walkNode->coords[num][index] = m34->right; break; case 1: walkNode->coords[num][index] = m34->left; break; case 2: walkNode->coords[num][index] = m34->bottom; break; case 3: walkNode->coords[num][index] = m34->top; break; } } else { const uint32_t indexWalkNode = walkNode->neighborWalkNode[num]; assert(indexWalkNode != kNone && indexWalkNode < walkPath->count); walkNode->coords[num][index] = mstWalkPathUpdateWalkNode(walkPath, &walkPath->data[indexWalkNode], num, index); } } return walkNode->coords[num][index]; } void Game::executeMstCodeHelper1() { for (int i = 0; i < _res->_mstHdr.walkPathDataCount; ++i) { MstWalkPath *walkPath = &_res->_mstWalkPathData[i]; if (walkPath->mask & _mstLevelGatesMask) { ++_mstHelper1Count; for (uint32_t j = 0; j < walkPath->count; ++j) { for (int k = 0; k < 2; ++k) { walkPath->data[j].coords[0][k] = -1; walkPath->data[j].coords[1][k] = -1; walkPath->data[j].coords[2][k] = -1; walkPath->data[j].coords[3][k] = -1; } } for (uint32_t j = 0; j < walkPath->count; ++j) { MstWalkNode *walkNode = &walkPath->data[j]; for (int k = 0; k < 4; ++k) { mstWalkPathUpdateWalkNode(walkPath, walkNode, k, 0); mstWalkPathUpdateWalkNode(walkPath, walkNode, k, 1); } } mstWalkPathUpdateIndex(walkPath, 0); mstWalkPathUpdateIndex(walkPath, 1); } } if (_mstHelper1Count != 0) { for (int i = 0; i < kMaxMonsterObjects1; ++i) { MonsterObject1 *m = &_monsterObjects1Table[i]; if (!m->m46) { continue; } MstWalkNode *walkNode = m->walkNode; const int num = (~m->flagsA5) & 1; m->levelPosBounds_x2 = walkNode->coords[0][num] - (int32_t)READ_LE_UINT32(m->monsterInfos + 904); m->levelPosBounds_x1 = walkNode->coords[1][num] + (int32_t)READ_LE_UINT32(m->monsterInfos + 904); m->levelPosBounds_y2 = walkNode->coords[2][num] - (int32_t)READ_LE_UINT32(m->monsterInfos + 908); m->levelPosBounds_y1 = walkNode->coords[3][num] + (int32_t)READ_LE_UINT32(m->monsterInfos + 908); } } } void Game::mstUpdateMonster1ObjectsPosition() { mstUpdateRefPos(); mstUpdateMonstersRect(); for (Task *t = _monsterObjects1TasksList; t; t = t->nextPtr) { mstTaskUpdateScreenPosition(t); } } void Game::mstLvlObjectSetActionDirection(LvlObject *o, const uint8_t *ptr, uint8_t mask1, uint8_t dirMask2) { o->actionKeyMask = ptr[1]; o->directionKeyMask = mask1 & 15; MonsterObject1 *m = (MonsterObject1 *)getLvlObjectDataPtr(o, kObjectDataTypeMonster1); if ((mask1 & 0x10) == 0) { const int vf = mask1 & 0xE0; switch (vf) { case 32: case 96: case 160: case 192: if (vf == 192) { o->directionKeyMask |= (m->facingDirectionMask & ~kDirectionKeyMaskVertical); } else { o->directionKeyMask |= m->facingDirectionMask; if (m->monsterInfos[946] & 2) { if (vf == 160 && (_mstLut1[o->directionKeyMask] & 1) != 0) { if (m->xDelta >= m->yDelta) { o->directionKeyMask &= ~kDirectionKeyMaskVertical; } else { o->directionKeyMask &= ~kDirectionKeyMaskHorizontal; } } else { if (m->xDelta >= m->yDelta * 2) { o->directionKeyMask &= ~kDirectionKeyMaskVertical; } else if (m->yDelta >= m->xDelta * 2) { o->directionKeyMask &= ~kDirectionKeyMaskHorizontal; } } } } break; case 128: o->directionKeyMask |= dirMask2; if ((m->monsterInfos[946] & 2) != 0 && (_mstLut1[o->directionKeyMask] & 1) != 0) { if (m->xDelta >= m->yDelta) { o->directionKeyMask &= ~kDirectionKeyMaskVertical; } else { o->directionKeyMask &= ~kDirectionKeyMaskHorizontal; } } break; case 224: o->directionKeyMask |= m->unkF8; break; default: o->directionKeyMask |= dirMask2; break; } } o->directionKeyMask &= ptr[2]; if ((mask1 & 0xE0) == 0x40) { o->directionKeyMask ^= kDirectionKeyMaskHorizontal; } } void Game::mstMonster1UpdateGoalPosition(MonsterObject1 *m) { int var1C = 0; int var18 = 0; debug(kDebug_MONSTER, "mstMonster1UpdateGoalPosition m %p goalScreen %d levelBounds [%d,%d,%d,%d]", m, m->goalScreenNum, m->levelPosBounds_x1, m->levelPosBounds_y1, m->levelPosBounds_x2, m->levelPosBounds_y2); if (m->goalScreenNum == 0xFD) { int ve, vf, vg, va; const MstMovingBounds *m49 = m->m49; const int xPos_1 = _mstAndyLevelPosX + m49->unk14 - m->goalDistance_x2; const int xPos_2 = _mstAndyLevelPosX - m49->unk14 + m->goalDistance_x2; const int yPos_1 = _mstAndyLevelPosY + m49->unk15 - m->goalDistance_y2; const int yPos_2 = _mstAndyLevelPosY + m49->unk15 + m->goalDistance_y2; if (m->levelPosBounds_x2 > xPos_1 && m->levelPosBounds_x1 < xPos_2 && m->levelPosBounds_y2 > yPos_1 && m->levelPosBounds_y1 < yPos_2) { const int xPos_3 = _mstAndyLevelPosX + m49->unk14 + m->goalDistance_x1; const int xPos_4 = _mstAndyLevelPosX - m49->unk14 - m->goalDistance_x1; const int yPos_3 = _mstAndyLevelPosY + m49->unk15 + m->goalDistance_y1; const int yPos_4 = _mstAndyLevelPosY - m49->unk15 - m->goalDistance_y1; if (m->levelPosBounds_x2 < xPos_3) { if (m->levelPosBounds_x1 > xPos_4 && m->levelPosBounds_y2 < yPos_3 && m->levelPosBounds_y1 > yPos_4) { goto l41B2DC; } } var18 = 0; ve = 0x40000000; if (m->levelPosBounds_x2 >= _mstAndyLevelPosX + m->goalDistance_x1 + m49->unk14) { if (m->xMstPos > _mstAndyLevelPosX + m->goalDistance_x2) { ve = m->xMstPos - m->goalDistance_x1 - _mstAndyLevelPosX; if (ve >= 0 && ve < m49->unk14) { ve = 0x40000000; } else { var18 = 1; } } else if (m->xMstPos >= _mstAndyLevelPosX + m->goalDistance_x1) { ve = -1; var18 = 1; } else { ve = m->goalDistance_x2 - m->xMstPos + _mstAndyLevelPosX; if (ve >= 0 && ve < m49->unk14) { ve = 0x40000000; } else { var18 = 1; } } } vf = 0x40000000; if (m->levelPosBounds_x1 <= _mstAndyLevelPosX - m->goalDistance_x1 - m49->unk14) { if (m->xMstPos > _mstAndyLevelPosX - m->goalDistance_x1) { vf = m->xMstPos - _mstAndyLevelPosX + m->goalDistance_x2; if (vf >= 0 && vf < m49->unk14) { vf = 0x40000000; } else { var18 |= 2; } } else if (m->xMstPos >= _mstAndyLevelPosX - m->goalDistance_x2) { vf = -1; var18 |= 2; } else { vf = _mstAndyLevelPosX - m->goalDistance_x1 - m->xMstPos; if (vf >= 0 && vf < m49->unk14) { vf = 0x40000000; } else { var18 |= 2; } } } vg = 0x40000000; if (m->levelPosBounds_y2 >= _mstAndyLevelPosY + m->goalDistance_y1 + m49->unk15) { if (m->yMstPos > _mstAndyLevelPosY + m->goalDistance_y2) { vg = m->yMstPos - m->goalDistance_y1 - _mstAndyLevelPosY; if (vg >= 0 && vg < m49->unk15) { vg = 0x40000000; } else { var18 |= 4; } } else if (m->yMstPos >= _mstAndyLevelPosY + m->goalDistance_y1) { vg = -1; var18 |= 4; } else { vg = m->goalDistance_y2 - m->yMstPos + _mstAndyLevelPosY; if (vg >= 0 && vg < m49->unk15) { vg = 0x40000000; } else { var18 |= 4; } } } va = 0x40000000; if (m->levelPosBounds_y1 <= _mstAndyLevelPosY - m->goalDistance_y1 - m49->unk15) { if (m->yMstPos > _mstAndyLevelPosY - m->goalDistance_y1) { va = m->yMstPos - _mstAndyLevelPosY + m->goalDistance_y2; if (va >= 0 && va < m49->unk15) { va = 0x40000000; } else { var18 |= 8; } } else if (m->yMstPos >= _mstAndyLevelPosY - m->goalDistance_y2) { va = -1; var18 |= 8; } else { va = _mstAndyLevelPosY - m->goalDistance_y1 - m->yMstPos; if (va >= 0 && va < m49->unk15) { va = 0x40000000; } else { var18 |= 8; } } } if (var18 == 0) { var18 = 15; } } else { l41B2DC: ve = ABS(m->xMstPos - _mstAndyLevelPosX + m49->unk14 - m->goalDistance_x2); vf = ABS(m->xMstPos - _mstAndyLevelPosX - m49->unk14 + m->goalDistance_x2); vg = ABS(m->yMstPos - _mstAndyLevelPosY + m49->unk15 - m->goalDistance_y2); va = ABS(m->yMstPos - _mstAndyLevelPosY - m49->unk15 + m->goalDistance_y2); var18 = 15; } if (var18 == m->unkE4) { var1C = m->unkE5; } else { switch (var18 & 3) { case 0: var1C = (vg > va) ? 0x21 : 0x20; break; case 2: if (vf <= va && vf <= vg) { var1C = 0x12; } else { var1C = (vg >= va) ? 0x21 : 0x20; } break; case 3: if (ve > vf) { if (vf <= va && vf <= vg) { var1C = 0x12; } else { var1C = (vg >= va) ? 0x21 : 0x20; } break; } // fall-through case 1: if (ve <= va && ve <= vg) { var1C = 0x02; } else { var1C = (vg >= va) ? 0x21 : 0x20; } break; } m->unkE4 = var18; m->unkE5 = var1C; } } else { var1C = 0; } switch (var1C & 0xF0) { case 0x00: m->goalPos_x1 = m->goalDistance_x1; m->goalPos_x2 = m->goalDistance_x2; break; case 0x10: m->goalPos_x1 = -m->goalDistance_x2; m->goalPos_x2 = -m->goalDistance_x1; break; case 0x20: m->goalPos_x1 = -m->goalDistance_x2; m->goalPos_x2 = m->goalDistance_x2; break; } switch (var1C & 0xF) { case 0: m->goalPos_y1 = m->goalDistance_y1; m->goalPos_y2 = m->goalDistance_y2; break; case 1: m->goalPos_y1 = -m->goalDistance_y2; m->goalPos_y2 = -m->goalDistance_y1; break; case 2: m->goalPos_y1 = -m->goalDistance_y2; m->goalPos_y2 = m->goalDistance_y2; break; } m->goalPos_x1 += _mstAndyLevelPosX; m->goalPos_x2 += _mstAndyLevelPosX; m->goalPos_y1 += _mstAndyLevelPosY; m->goalPos_y2 += _mstAndyLevelPosY; const uint8_t *ptr = _res->_mstMonsterInfos + m->m49Unk1->offsetMonsterInfo; if ((ptr[2] & kDirectionKeyMaskVertical) == 0) { m->goalDistance_y1 = m->goalPos_y1 = m->goalDistance_y2 = m->goalPos_y2 = m->yMstPos; } if ((ptr[2] & kDirectionKeyMaskHorizontal) == 0) { m->goalDistance_x1 = m->goalPos_x1 = m->goalDistance_x2 = m->goalPos_x2 = m->xMstPos; } debug(kDebug_MONSTER, "mstMonster1UpdateGoalPosition m %p mask 0x%x goal [%d,%d,%d,%d]", m, var1C, m->goalPos_x1, m->goalPos_y1, m->goalPos_x2, m->goalPos_y2); } void Game::mstMonster1MoveTowardsGoal1(MonsterObject1 *m) { MstWalkNode *walkNode = m->walkNode; const uint8_t *p = m->monsterInfos; const uint32_t indexWalkBox = walkNode->walkBox; const MstWalkBox *m34 = &_res->_mstWalkBoxData[indexWalkBox]; const int w = (int32_t)READ_LE_UINT32(p + 904); const int h = (int32_t)READ_LE_UINT32(p + 908); debug(kDebug_MONSTER, "mstMonster1MoveTowardsGoal1 m %p pos %d,%d [%d,%d,%d,%d]", m, m->xMstPos, m->yMstPos, m34->left, m34->top, m34->right, m34->bottom); if (!rect_contains(m34->left - w, m34->top - h, m34->right + w, m34->bottom + h, m->xMstPos, m->yMstPos)) { mstMonster1UpdateWalkPath(m); m->unkC0 = -1; m->unkBC = -1; } m->task->flags &= ~0x80; if (m->xMstPos < m->goalPos_x1) { int x = m->goalPos_x2; _xMstPos1 = x; if (x > m->levelPosBounds_x2) { x = m->levelPosBounds_x2; m->task->flags |= 0x80; } m->goalDirectionMask = kDirectionKeyMaskRight; _xMstPos2 = x - m->xMstPos; } else if (m->xMstPos > m->goalPos_x2) { int x = m->goalPos_x1; _xMstPos1 = x; if (x < m->levelPosBounds_x1) { x = m->levelPosBounds_x1; m->task->flags |= 0x80; } m->goalDirectionMask = kDirectionKeyMaskLeft; _xMstPos2 = m->xMstPos - x; } else { _xMstPos1 = m->xMstPos; m->goalDirectionMask = 0; _xMstPos2 = 0; } if (m->yMstPos < m->goalPos_y1) { int y = m->goalPos_y2; _yMstPos1 = y; if (y > m->levelPosBounds_y2) { y = m->levelPosBounds_y2; m->task->flags |= 0x80; } _yMstPos2 = y - m->yMstPos; m->goalDirectionMask |= kDirectionKeyMaskDown; } else if (m->yMstPos > m->goalPos_y2) { int y = m->goalPos_y1; _yMstPos1 = y; if (y < m->levelPosBounds_y1) { y = m->levelPosBounds_y1; m->task->flags |= 0x80; } _yMstPos2 = m->yMstPos - y; m->goalDirectionMask |= kDirectionKeyMaskUp; } else { _yMstPos1 = m->yMstPos; _yMstPos2 = 0; } debug(kDebug_MONSTER, "mstMonster1MoveTowardsGoal1 m %p pos %d,%d dist %d,%d direction 0x%x", m, _xMstPos1, _yMstPos1, _xMstPos2, _yMstPos2, m->goalDirectionMask); if (m->goalDirectionMask == 0) { return; } MstBehaviorState *behaviorState = m->behaviorState; MstWalkPath *walkPath = &_res->_mstWalkPathData[behaviorState->walkPath]; uint8_t _cl = m->walkBoxNum; if (m->unkBC != _xMstPos1 || m->unkC0 != _yMstPos1) { bool inWalkBox = false; if (_cl < walkPath->count) { MstWalkNode *walkNode = &walkPath->data[_cl]; const MstWalkBox *m34 = &_res->_mstWalkBoxData[walkNode->walkBox]; if (rect_contains(m34->left, m34->top, m34->right, m34->bottom, _xMstPos1, _yMstPos1)) { inWalkBox = true; } } if (!inWalkBox) { const int _al = mstMonster1FindWalkPathRect(m, walkPath, _xMstPos1, _yMstPos1); if (_al < 0) { _xMstPos1 = _xMstPos3; _yMstPos1 = _yMstPos3; _cl = -1 - _al; m->goalPos_x1 = m->goalPos_x2 = _xMstPos1; m->goalPos_y1 = m->goalPos_y2 = _yMstPos1; _xMstPos2 = ABS(m->xMstPos - _xMstPos1); _yMstPos2 = ABS(m->yMstPos - _yMstPos1); if (m->xMstPos < m->goalPos_x1) { m->goalDirectionMask = kDirectionKeyMaskRight; } else if (m->xMstPos > m->goalPos_x2) { m->goalDirectionMask = kDirectionKeyMaskLeft; } if (m->yMstPos < m->goalPos_y1) { m->goalDirectionMask |= kDirectionKeyMaskDown; } else if (m->yMstPos > m->goalPos_y2) { m->goalDirectionMask |= kDirectionKeyMaskUp; } } else { _cl = _al; } m->walkBoxNum = _cl; m->unkBC = -1; m->unkC0 = -1; } } if (_cl >= walkPath->count || m->walkNode == &walkPath->data[_cl]) { m->targetDirectionMask = 0xFF; return; } const int vf = (~m->flagsA5) & 1; if (m->unkBC == _xMstPos1 && m->unkC0 == _yMstPos1) { if (m->targetDirectionMask == 0xFF) { return; } m->goalDirectionMask = m->targetDirectionMask; } else { m->unkBC = _xMstPos1; m->unkC0 = _yMstPos1; const uint32_t indexWalkPath = m->behaviorState->walkPath; MstWalkPath *walkPath = &_res->_mstWalkPathData[indexWalkPath]; const MstWalkNode *walkNode = m->walkNode; const uint8_t dirMask = walkNode->unk60[vf][_cl]; if (dirMask != 0) { const uint8_t *p = m->monsterInfos; const int w = (int32_t)READ_LE_UINT32(p + 904); const int h = (int32_t)READ_LE_UINT32(p + 908); while (1) { const int x1 = walkNode->coords[1][vf] + w; // left const int x2 = walkNode->coords[0][vf] - w; // right const int y1 = walkNode->coords[3][vf] + h; // top const int y2 = walkNode->coords[2][vf] - h; // bottom if (!rect_contains(x1, y1, x2, y2, _xMstPos1, _yMstPos1)) { break; } int var1C; switch (walkNode->unk60[vf][_cl]) { case 2: var1C = 0; break; case 4: var1C = 2; break; case 8: var1C = 1; break; default: // 1 var1C = 3; break; } const uint32_t indexWalkNode = walkNode->neighborWalkNode[var1C]; assert(indexWalkNode != kNone && indexWalkNode < walkPath->count); walkNode = &walkPath->data[indexWalkNode]; if (walkNode == &walkPath->data[_cl]) { m->targetDirectionMask = 0xFF; return; } } m->goalDirectionMask = dirMask; } m->targetDirectionMask = m->goalDirectionMask; } if (m->goalDirectionMask & kDirectionKeyMaskLeft) { _xMstPos2 = m->xMstPos - m->walkNode->coords[1][vf] - (int32_t)READ_LE_UINT32(m->monsterInfos + 904); } else if (m->goalDirectionMask & kDirectionKeyMaskRight) { _xMstPos2 = m->walkNode->coords[0][vf] - (int32_t)READ_LE_UINT32(m->monsterInfos + 904) - m->xMstPos; } else { _xMstPos2 = 0; } if (m->goalDirectionMask & kDirectionKeyMaskUp) { _yMstPos2 = m->yMstPos - m->walkNode->coords[3][vf] - (int32_t)READ_LE_UINT32(m->monsterInfos + 908); } else if (m->goalDirectionMask & kDirectionKeyMaskDown) { _yMstPos2 = m->walkNode->coords[2][vf] - (int32_t)READ_LE_UINT32(m->monsterInfos + 908) - m->yMstPos; } else { _yMstPos2 = 0; } debug(kDebug_MONSTER, "mstMonster1MoveTowardsGoal1 m %p dist %d,%d", m, _xMstPos2, _yMstPos2); } bool Game::mstMonster1TestGoalDirection(MonsterObject1 *m) { if (_mstLut1[m->goalDirectionMask] & 1) { if (_xMstPos2 < m->m49->unk14) { m->goalDirectionMask &= ~kDirectionKeyMaskHorizontal; } if (_yMstPos2 < m->m49->unk15) { m->goalDirectionMask &= ~kDirectionKeyMaskVertical; } } if (_mstLut1[m->goalDirectionMask] & 1) { while (--m->indexUnk49Unk1 >= 0) { m->m49Unk1 = &m->m49->data1[m->indexUnk49Unk1]; if (_xMstPos2 >= m->m49Unk1->unkE && _yMstPos2 >= m->m49Unk1->unkF) { return true; } } } else { while (--m->indexUnk49Unk1 >= 0) { m->m49Unk1 = &m->m49->data1[m->indexUnk49Unk1]; if (((m->goalDirectionMask & kDirectionKeyMaskHorizontal) == 0 || _xMstPos2 >= m->m49Unk1->unkC) && ((m->goalDirectionMask & kDirectionKeyMaskVertical) == 0 || _yMstPos2 >= m->m49Unk1->unkD)) { return true; } } } return false; } void Game::mstMonster1MoveTowardsGoal2(MonsterObject1 *m) { if (m->targetLevelPos_x != -1) { if (m->xMstPos != m->targetLevelPos_x || m->yMstPos != m->targetLevelPos_y) { _xMstPos2 = m->previousDxPos; _yMstPos2 = m->previousDyPos; return; } mstBoundingBoxClear(m, 1); } mstMonster1MoveTowardsGoal1(m); if (m->goalDirectionMask == 0) { return; } m->previousDxPos = _xMstPos2; m->previousDyPos = _yMstPos2; const MstMovingBoundsUnk1 *m49Unk1 = m->m49Unk1; uint8_t xDist, yDist; if (_mstLut1[m->goalDirectionMask] & 1) { xDist = m49Unk1->unkA; yDist = m49Unk1->unkB; } else { xDist = m49Unk1->unk8; yDist = m49Unk1->unk9; } if (_xMstPos2 < xDist && _yMstPos2 < yDist) { if ((_xMstPos2 <= 0 && _yMstPos2 <= 0) || !mstMonster1TestGoalDirection(m)) { return; } } if (_mstLut1[m->goalDirectionMask] & 1) { if (_xMstPos2 < _yMstPos2) { if (_xMstPos2 < m->m49Unk1->unkA) { m->goalDirectionMask &= ~kDirectionKeyMaskHorizontal; if (m->targetDirectionMask != 0xFF) { _xMstPos2 = 0; } } } else { if (_yMstPos2 < m->m49Unk1->unkB) { m->goalDirectionMask &= ~kDirectionKeyMaskVertical; if (m->targetDirectionMask != 0xFF) { _yMstPos2 = 0; } } } } int var10 = (~m->flagsA5) & 1; const uint32_t indexWalkBox = m->walkNode->walkBox; const MstWalkBox *m34 = &_res->_mstWalkBoxData[indexWalkBox]; int bboxIndex = 0; int var8 = _mstLut1[m->goalDirectionMask]; for (int var20 = 0; var20 < 5; ++var20) { const uint8_t *p = _res->_mstMonsterInfos + m->m49Unk1->offsetMonsterInfo; if (var20 != 0) { if (p[0xE] == 0 || bboxIndex == 0) { break; } } const int num = var20 + var8 * 5; const int dirMask = _mstLut3[num]; if (_mstLut1[dirMask] == m->unkAB) { continue; } int vc, va; if (_mstLut1[dirMask] & 1) { vc = (int8_t)p[0xA]; va = (int8_t)p[0xB]; } else { vc = (int8_t)p[0x8]; va = (int8_t)p[0x9]; } int xPos = m->xMstPos; if (dirMask & kDirectionKeyMaskLeft) { xPos -= vc; if (xPos < m->levelPosBounds_x1) { continue; } } else if (dirMask & kDirectionKeyMaskRight) { xPos += vc; if (xPos > m->levelPosBounds_x2) { continue; } } int yPos = m->yMstPos; if (dirMask & kDirectionKeyMaskUp) { yPos -= va; if (yPos < m->levelPosBounds_y1) { continue; } } else if (dirMask & kDirectionKeyMaskDown) { yPos += va; if (yPos > m->levelPosBounds_y2) { continue; } } if (var10 == 1 && (m->flagsA5 & 4) == 0 && (m->flags48 & 8) != 0) { if (!mstSetCurrentPos(m, xPos, yPos)) { continue; } } const int w = (int32_t)READ_LE_UINT32(m->monsterInfos + 904); const int h = (int32_t)READ_LE_UINT32(m->monsterInfos + 908); if (!rect_contains(m34->left - w, m34->top - h, m34->right + w, m34->bottom + h, xPos, yPos)) { const uint32_t indexWalkPath = m->behaviorState->walkPath; MstWalkPath *walkPath = &_res->_mstWalkPathData[indexWalkPath]; const int num = mstMonster1FindWalkPathRect(m, walkPath, xPos, yPos); if (num < 0) { continue; } if (m->walkNode->unk60[var10][num] == 0) { continue; } } m->targetLevelPos_x = xPos; m->targetLevelPos_y = yPos; p = _res->_mstMonsterInfos + m->m49Unk1->offsetMonsterInfo; if (p[0xE] != 0) { const int x1 = m->xMstPos + (int8_t)p[0xC]; const int y1 = m->yMstPos + (int8_t)p[0xD]; const int x2 = x1 + p[0xE] - 1; const int y2 = y1 + p[0xF] - 1; const int r = mstBoundingBoxCollides2(m->monster1Index, x1, y1, x2, y2); if (r != 0) { bboxIndex = r - 1; const MstBoundingBox *b = &_mstBoundingBoxesTable[bboxIndex]; if (rect_intersects(b->x1, b->y1, b->x2, b->y2, m->goalPos_x1, m->goalPos_y1, m->goalPos_x2, m->goalPos_y2)) { break; } continue; } m->bboxNum[1] = mstBoundingBoxUpdate(m->bboxNum[1], m->monster1Index, x1, y1, x2, y2); } else { // (p[0xE] == 0) mstBoundingBoxClear(m, 1); } m->goalDirectionMask = dirMask; if (var20 == 0) { m->unkAB = 0xFF; } else { const uint8_t n = _mstLut1[dirMask]; m->unkAB = (n < 4) ? n + 4 : n - 4; } return; } m->task->flags |= 0x80; m->goalDirectionMask = 0; _yMstPos2 = 0; _xMstPos2 = 0; } int Game::mstTaskStopMonster1(Task *t, MonsterObject1 *m) { if (m->monsterInfos[946] & 4) { mstBoundingBoxClear(m, 1); } if (m->goalScreenNum != 0xFC && (m->flagsA5 & 8) != 0 && (t->flags & 0x20) != 0 && m->action) { LvlObject *o = m->o16; const int xPosScreen = _res->_mstPointOffsets[_currentScreen].xOffset; const int yPosScreen = _res->_mstPointOffsets[_currentScreen].yOffset; const int xPosObj = o->xPos + _res->_mstPointOffsets[o->screenNum].xOffset; const int yPosObj = o->yPos + _res->_mstPointOffsets[o->screenNum].yOffset; // this matches the original code but rect_intersects() could probably be used if (xPosObj < xPosScreen || xPosObj + o->width - 1 > xPosScreen + 255 || yPosObj < yPosScreen || yPosObj + o->height - 1 > yPosScreen + 191) { return mstTaskStopMonsterObject1(t); } } mstTaskResetMonster1WalkPath(t); return 0; } int Game::mstTaskUpdatePositionActionDirection(Task *t, MonsterObject1 *m) { if ((m->monsterInfos[946] & 4) == 0 && (_mstLut1[m->goalDirectionMask] & 1) != 0) { if (_xMstPos2 < m->m49->unk14) { m->goalDirectionMask &= ~kDirectionKeyMaskHorizontal; } if (_yMstPos2 < m->m49->unk15) { m->goalDirectionMask &= ~kDirectionKeyMaskVertical; } } const uint8_t *ptr = _res->_mstMonsterInfos + m->m49Unk1->offsetMonsterInfo; if ((m->monsterInfos[946] & 4) == 0 && (m->flagsA5 & 4) == 0 && (m->flagsA5 & 2) != 0 && (m->flags48 & 8) != 0) { int vf, ve; if (_mstLut1[m->goalDirectionMask] & 1) { vf = (int8_t)ptr[0xA]; ve = (int8_t)ptr[0xB]; } else { vf = (int8_t)ptr[0x8]; ve = (int8_t)ptr[0x9]; } int x = m->xMstPos; int y = m->yMstPos; if (m->goalDirectionMask & kDirectionKeyMaskLeft) { x -= vf; } else if (m->goalDirectionMask & kDirectionKeyMaskRight) { x += vf; } if (m->goalDirectionMask & kDirectionKeyMaskUp) { y -= ve; } else if (m->goalDirectionMask & kDirectionKeyMaskDown) { y += ve; } if (!mstSetCurrentPos(m, x, y)) { _xMstPos2 = ABS(m->xMstPos - _mstCurrentPosX); _yMstPos2 = ABS(m->yMstPos - _mstCurrentPosY); } } const MstMovingBoundsUnk1 *m49Unk1 = m->m49Unk1; uint8_t xDist, yDist; if (_mstLut1[m->goalDirectionMask] & 1) { xDist = m49Unk1->unkA; yDist = m49Unk1->unkB; } else { xDist = m49Unk1->unk8; yDist = m49Unk1->unk9; } if (m->goalDirectionMask == 0) { return mstTaskStopMonster1(t, m); } if (_xMstPos2 < xDist && _yMstPos2 < yDist) { if ((_xMstPos2 <= 0 && _yMstPos2 <= 0) || !mstMonster1TestGoalDirection(m)) { return mstTaskStopMonster1(t, m); } } if ((m->monsterInfos[946] & 4) == 0 && (_mstLut1[m->goalDirectionMask] & 1) != 0) { if (_xMstPos2 < _yMstPos2) { if (_xMstPos2 < m->m49Unk1->unkA) { m->goalDirectionMask &= ~kDirectionKeyMaskHorizontal; if (m->targetDirectionMask != 0xFF) { _xMstPos2 = 0; } } } else { if (_yMstPos2 < m->m49Unk1->unkB) { m->goalDirectionMask &= ~kDirectionKeyMaskVertical; if (m->targetDirectionMask != 0xFF) { _yMstPos2 = 0; } } } } ptr = _res->_mstMonsterInfos + m->m49Unk1->offsetMonsterInfo; mstLvlObjectSetActionDirection(m->o16, ptr, ptr[3], m->goalDirectionMask); return 1; } // ret >0: found a rect matching // ret <0: return the closest match (setting _xMstPos3 and _yMstPos3) int Game::mstMonster1FindWalkPathRect(MonsterObject1 *m, MstWalkPath *walkPath, int x, int y) { _xMstPos3 = x; _yMstPos3 = y; const int num = (~m->flagsA5) & 1; int minDistance = 0x40000000; int ret = -1; int currentIndex = -1; int xDist = 0; int yDist = 0; for (uint32_t i = 0; i < walkPath->count; ++i, --currentIndex) { MstWalkNode *walkNode = &walkPath->data[i]; if (m->walkNode->unk60[num][i] == 0 && m->walkNode != walkNode) { continue; } const uint32_t indexWalkBox = walkNode->walkBox; const MstWalkBox *m34 = &_res->_mstWalkBoxData[indexWalkBox]; if (rect_contains(m34->left, m34->top, m34->right, m34->bottom, x, y)) { return i; } int dist, curX = x, curY = y; if (x >= m34->left && x <= m34->right) { const int dy1 = ABS(y - m34->bottom); const int dy2 = ABS(y - m34->top); curY = (dy2 >= dy1) ? m34->bottom : m34->top; yDist = y - curY; yDist *= yDist; dist = yDist; if (minDistance >= dist) { minDistance = dist; _xMstPos3 = curX; _yMstPos3 = curY; ret = currentIndex; } } else if (y >= m34->top && y <= m34->bottom) { const int dx1 = ABS(x - m34->right); const int dx2 = ABS(x - m34->left); curX = (dx2 >= dx1) ? m34->right : m34->left; xDist = x - curX; xDist *= xDist; dist = xDist; if (minDistance >= dist) { minDistance = dist; _xMstPos3 = curX; _yMstPos3 = curY; ret = currentIndex; } } else { curX = m34->left; xDist = x - curX; xDist *= xDist; curY = m34->top; yDist = y - curY; yDist *= yDist; dist = xDist + yDist; if (minDistance >= dist) { minDistance = dist; _xMstPos3 = curX; _yMstPos3 = curY; ret = currentIndex; } curX = m34->right; xDist = x - curX; xDist *= xDist; dist = xDist + yDist; if (minDistance >= dist) { minDistance = dist; _xMstPos3 = curX; _yMstPos3 = curY; ret = currentIndex; } curY = m34->bottom; yDist = y - curY; yDist *= yDist; dist = xDist + yDist; if (minDistance >= dist) { minDistance = dist; _xMstPos3 = curX; _yMstPos3 = curY; ret = currentIndex; } curX = m34->left; xDist = x - curX; xDist *= xDist; dist = xDist + yDist; if (minDistance >= dist) { minDistance = dist; _xMstPos3 = curX; _yMstPos3 = curY; ret = currentIndex; } } dist = xDist + yDist; if (minDistance >= dist) { minDistance = dist; _xMstPos3 = curX; _yMstPos3 = curY; ret = currentIndex; } } return ret; } bool Game::mstTestActionDirection(MonsterObject1 *m, int num) { LvlObject *o = m->o16; const uint8_t _al = _res->_mstActionDirectionData[num].unk0; const uint8_t _bl = _res->_mstActionDirectionData[num].unk2; const uint8_t *var4 = m->monsterInfos + _al * 28; const uint8_t _dl = (o->flags1 >> 4) & 3; uint8_t var8 = ((_dl & 1) != 0) ? 8 : 2; if (_dl & 2) { var8 |= 4; } else { var8 |= 1; } uint8_t directionKeyMask = _bl & 15; if ((_bl & 0x10) == 0) { const uint32_t ve = _bl & 0xE0; switch (ve) { case 32: case 96: case 160: case 192: // 0 if (ve == 192) { directionKeyMask |= m->facingDirectionMask & ~kDirectionKeyMaskVertical; } else { directionKeyMask |= m->facingDirectionMask; if (m->monsterInfos[946] & 2) { if (ve == 160 && (_mstLut1[directionKeyMask] & 1) != 0) { if (m->xDelta >= m->yDelta) { directionKeyMask &= ~kDirectionKeyMaskVertical; } else { directionKeyMask &= ~kDirectionKeyMaskHorizontal; } } else { if (m->xDelta >= 2 * m->yDelta) { directionKeyMask &= ~kDirectionKeyMaskVertical; } else if (m->yDelta >= 2 * m->xDelta) { directionKeyMask &= ~kDirectionKeyMaskHorizontal; } } } } break; case 128: // 1 directionKeyMask |= var8; if ((m->monsterInfos[946] & 2) != 0 && (_mstLut1[directionKeyMask] & 1) != 0) { if (m->xDelta >= m->yDelta) { directionKeyMask &= ~kDirectionKeyMaskVertical; } else { directionKeyMask &= ~kDirectionKeyMaskHorizontal; } } break; default: // 2 directionKeyMask |= var8; break; } } directionKeyMask &= var4[2]; if ((_bl & 0xE0) == 0x40) { directionKeyMask ^= kDirectionKeyMaskHorizontal; } return ((var8 & directionKeyMask) != 0) ? 0 : 1; } bool Game::lvlObjectCollidesAndy1(LvlObject *o, int flags) const { int x1, y1, x2, y2; if (flags != 1 && flags != 0x4000) { x1 = o->xPos; y1 = o->yPos; x2 = x1 + o->width - 1; y2 = y1 + o->height - 1; } else { x1 = o->xPos + o->posTable[0].x; x2 = o->xPos + o->posTable[1].x; y1 = o->yPos + o->posTable[0].y; y2 = o->yPos + o->posTable[1].y; if (x1 > x2) { SWAP(x1, x2); } if (y1 > y2) { SWAP(y1, y2); } if (flags == 0x4000 && _andyObject->screenNum != o->screenNum) { const int dx = _res->_mstPointOffsets[o->screenNum].xOffset - _res->_mstPointOffsets[_andyObject->screenNum].xOffset; x1 += dx; x2 += dx; const int dy = _res->_mstPointOffsets[o->screenNum].yOffset - _res->_mstPointOffsets[_andyObject->screenNum].yOffset; y1 += dy; y2 += dy; } } const int x = _andyObject->xPos + _andyObject->width / 2; const int y = _andyObject->yPos + _andyObject->height / 2; return rect_contains(x1, y1, x2, y2, x, y); } bool Game::lvlObjectCollidesAndy2(LvlObject *o, int type) const { int x1, y1, x2, y2; if (type != 1 && type != 0x1000) { x1 = o->xPos; y1 = o->yPos; x2 = x1 + o->width - 1; y2 = y1 + o->height - 1; } else { x1 = o->xPos + o->posTable[0].x; x2 = o->xPos + o->posTable[1].x; y1 = o->yPos + o->posTable[0].y; y2 = o->yPos + o->posTable[1].y; if (x1 > x2) { SWAP(x1, x2); } if (y1 > y2) { SWAP(y1, y2); } if (type == 0x1000 && _andyObject->screenNum != o->screenNum) { const int dx = _res->_mstPointOffsets[_andyObject->screenNum].xOffset - _res->_mstPointOffsets[o->screenNum].xOffset; x1 += dx; x2 += dx; const int dy = _res->_mstPointOffsets[_andyObject->screenNum].yOffset - _res->_mstPointOffsets[o->screenNum].yOffset; y1 += dy; y2 += dy; } } return rect_intersects(x1, y1, x2, y2, _andyObject->xPos, _andyObject->yPos, _andyObject->xPos + _andyObject->width - 1, _andyObject->yPos + _andyObject->height - 1); } bool Game::lvlObjectCollidesAndy3(LvlObject *o, int type) const { int x1, y1, x2, y2; if (type != 1) { x1 = o->xPos; y1 = o->yPos; x2 = o->xPos + o->width - 1; y2 = o->yPos + o->height - 1; } else { x1 = o->xPos + o->posTable[0].x; y1 = o->yPos + o->posTable[0].y; x2 = o->xPos + o->posTable[1].x; y2 = o->yPos + o->posTable[1].y; if (x1 > x2) { SWAP(x1, x2); } if (y1 > y2) { SWAP(y1, y2); } } const int xPos = _andyObject->xPos + _andyObject->posTable[3].x; const int yPos = _andyObject->yPos + _andyObject->posTable[3].y; return rect_contains(x1, y1, x2, y2, xPos, yPos); } bool Game::lvlObjectCollidesAndy4(LvlObject *o, int type) const { int x1, y1, x2, y2; if (type != 1) { x1 = o->xPos; y1 = o->yPos; x2 = o->xPos + o->width - 1; y2 = o->yPos + o->height - 1; } else { x1 = o->xPos + o->posTable[0].x; y1 = o->yPos + o->posTable[0].y; x2 = o->xPos + o->posTable[1].x; y2 = o->yPos + o->posTable[1].y; if (x1 > x2) { SWAP(x1, x2); } if (y1 > y2) { SWAP(y1, y2); } } static const uint8_t indexes[] = { 1, 2, 4, 5 }; for (int i = 0; i < 4; ++i) { const int xPos = _andyObject->xPos + _andyObject->posTable[indexes[i]].x; const int yPos = _andyObject->yPos + _andyObject->posTable[indexes[i]].y; if (rect_contains(x1, y1, x2, y2, xPos, yPos)) { return true; } } return false; } bool Game::mstCollidesByFlags(MonsterObject1 *m, uint32_t flags) { if ((flags & 1) != 0 && (m->o16->flags0 & 0x200) == 0) { return false; } else if ((flags & 8) != 0 && (m->flags48 & 0x20) == 0) { return false; } else if ((flags & 0x100) != 0 && (_mstFlags & 0x80000000) != 0) { return false; } else if ((flags & 0x200) != 0 && (_mstFlags & 0x40000000) != 0) { return false; } else if ((flags & 0x40) != 0 && (mstGetFacingDirectionMask(m->facingDirectionMask) & 1) != ((m->o16->flags1 >> 4) & 1) && (m->monsterInfos[946] & 4) == 0) { return false; } else if ((flags & 0x80) != 0 && (mstGetFacingDirectionMask(m->facingDirectionMask) & 1) != ((m->o16->flags1 >> 4) & 1) && (m->monsterInfos[946] & 4) != 0) { return false; } else if ((flags & 0x400) != 0 && (m->o16->screenNum != _andyObject->screenNum || !lvlObjectCollidesAndy1(m->o16, 0))) { return false; } else if ((flags & 0x800) != 0 && (m->o16->screenNum != _andyObject->screenNum || !lvlObjectCollidesAndy1(m->o16, 1))) { return false; } else if ((flags & 0x100000) != 0 && (m->o16->screenNum != _andyObject->screenNum || !lvlObjectCollidesAndy3(m->o16, 0))) { return false; } else if ((flags & 0x200000) != 0 && (m->o16->screenNum != _andyObject->screenNum || !lvlObjectCollidesAndy3(m->o16, 1))) { return false; } else if ((flags & 4) != 0 && (m->o16->screenNum != _andyObject->screenNum || !lvlObjectCollidesAndy2(m->o16, 0))) { return false; } else if ((flags & 2) != 0 && (m->o16->screenNum != _andyObject->screenNum || !lvlObjectCollidesAndy2(m->o16, 1))) { return false; } else if ((flags & 0x4000) != 0 && !lvlObjectCollidesAndy1(m->o16, 0x4000)) { return false; } else if ((flags & 0x1000) != 0 && !lvlObjectCollidesAndy2(m->o16, 0x1000)) { return false; } else if ((flags & 0x20) != 0 && (m->o16->flags0 & 0x100) == 0) { return false; } else if ((flags & 0x10000) != 0 && (m->o16->screenNum != _andyObject->screenNum || !lvlObjectCollidesAndy4(m->o16, 1))) { return false; } else if ((flags & 0x20000) != 0 && (m->o16->screenNum != _andyObject->screenNum || !lvlObjectCollidesAndy4(m->o16, 0))) { return false; } else if ((flags & 0x40000) != 0 && (m->o16->screenNum != _andyObject->screenNum || !clipLvlObjectsBoundingBox(_andyObject, m->o16, 36))) { return false; } else if ((flags & 0x80000) != 0 && (m->o16->screenNum != _andyObject->screenNum || !clipLvlObjectsBoundingBox(_andyObject, m->o16, 20))) { return false; } return true; } bool Game::mstMonster1Collide(MonsterObject1 *m, const uint8_t *p) { const uint32_t a = READ_LE_UINT32(p + 0x10); debug(kDebug_MONSTER, "mstMonster1Collide mask 0x%x flagsA6 0x%x", a, m->flagsA6); if (a == 0 || !mstCollidesByFlags(m, a)) { return false; } if ((a & 0x8000) != 0 && (m->flagsA6 & 4) == 0) { Task t; memcpy(&t, _mstCurrentTask, sizeof(Task)); _mstCurrentTask->child = 0; const uint32_t codeData = READ_LE_UINT32(p + 0x18); assert(codeData != kNone); _mstCurrentTask->codeData = _res->_mstCodeData + codeData * 4; _mstCurrentTask->run = &Game::mstTask_main; _mstCurrentTask->monster1->flagsA6 |= 4; Task *currentTask = _mstCurrentTask; mstTask_main(_mstCurrentTask); _mstCurrentTask = currentTask; _mstCurrentTask->monster1->flagsA6 &= ~4; t.nextPtr = _mstCurrentTask->nextPtr; t.prevPtr = _mstCurrentTask->prevPtr; memcpy(_mstCurrentTask, &t, sizeof(Task)); if (_mstCurrentTask->run == &Game::mstTask_idle && (_mstCurrentTask->monster1->flagsA6 & 2) == 0) { _mstCurrentTask->run = &Game::mstTask_main; } return false; } else { mstTaskAttack(_mstCurrentTask, READ_LE_UINT32(p + 0x18), 0x10); return true; } } int Game::mstUpdateTaskMonsterObject1(Task *t) { debug(kDebug_MONSTER, "mstUpdateTaskMonsterObject1 t %p", t); _mstCurrentTask = t; MonsterObject1 *m = t->monster1; MonsterObject1 *_mstCurrentMonster1 = m; LvlObject *o = m->o16; const int num = o->flags0 & 0xFF; const uint8_t *ptr = m->monsterInfos + num * 28; int8_t a = ptr[6]; if (a != 0) { const int num = CLIP(m->lut4Index + a, 0, 17); o->flags2 = (o->flags2 & ~0x1F) | _mstLut4[num]; } else { o->flags2 = m->o_flags2; } if (num == 0x1F) { mstRemoveMonsterObject1(_mstCurrentTask, &_monsterObjects1TasksList); return 1; } const uint32_t vf = READ_LE_UINT32(ptr + 20); if (vf != kNone) { MstBehavior *m46 = _mstCurrentMonster1->m46; for (uint32_t i = 0; i < m46->count; ++i) { if (m46->data[i].indexMonsterInfo == vf) { mstTaskSetMonster1BehaviorState(_mstCurrentTask, _mstCurrentMonster1, i); return 0; } } } if ((m->flagsA5 & 0x80) != 0) { return 0; } if (m->localVars[7] == 0 && !_specialAnimFlag) { // monster is dead m->flagsA5 |= 0x80; if (m->monsterInfos[946] & 4) { mstBoundingBoxClear(m, 1); } if (t->child) { t->child->codeData = 0; t->child = 0; } if ((m->flagsA5 & 8) != 0 && m->action && _mstActionNum != -1) { mstTaskStopMonsterObject1(_mstCurrentTask); return 0; } const uint32_t codeData = m->behaviorState->codeData; if (codeData != kNone) { resetTask(t, _res->_mstCodeData + codeData * 4); return 0; } o->actionKeyMask = 7; o->directionKeyMask = 0; t->run = &Game::mstTask_idle; return 0; } if (t->run == &Game::mstTask_monsterWait4) { return 0; } if (ptr[0] != 0) { mstMonster1Collide(_mstCurrentMonster1, ptr); return 0; } if ((m->flagsA5 & 0x40) != 0) { return 0; } assert(_mstCurrentMonster1 == m); int dir = 0; for (int i = 0; i < _andyShootsCount; ++i) { AndyShootData *p = &_andyShootsTable[i]; if (p->m && p->m != m) { continue; } if (m->collideDistance < 0) { continue; } if ((m->flags48 & 4) == 0) { continue; } if (m->behaviorState->indexUnk51 == kNone) { continue; } if (_rnd.getNextNumber() > m->behaviorState->unk10) { continue; } m->shootActionIndex = 8; int var28 = 0; AndyShootData *var14 = m->shootData; if (t->run != &Game::mstTask_monsterWait5 && t->run != &Game::mstTask_monsterWait6 && t->run != &Game::mstTask_monsterWait7 && t->run != &Game::mstTask_monsterWait8 && t->run != &Game::mstTask_monsterWait9 && t->run != &Game::mstTask_monsterWait10) { if (m->monsterInfos[946] & 2) { _mstCurrentMonster1->goalPos_x1 = _mstCurrentMonster1->goalPos_y1 = INT32_MIN; _mstCurrentMonster1->goalPos_x2 = _mstCurrentMonster1->goalPos_y2 = INT32_MAX; switch (var14->directionMask) { case 0: var28 = 2; break; case 1: case 133: var28 = 9; break; case 2: var28 = 12; break; case 3: case 128: var28 = 3; break; case 4: var28 = 6; break; case 5: var28 = 8; break; case 6: var28 = 1; break; case 7: var28 = 4; break; } _mstCurrentMonster1->shootActionIndex = _mstLut1[var28]; } } else { m->shootActionIndex = _mstLut1[m->goalDirectionMask]; var28 = 0; } uint32_t var24 = 0; MstBehaviorState *vg = m->behaviorState; if (vg->count != 0) { var24 = _rnd.update() % (vg->count + 1); } int var20 = -1; int indexUnk51; if ((m->flagsA5 & 8) != 0 && m->action && m->action->indexUnk51 != kNone && m->monsterInfos == &_res->_mstMonsterInfos[m->action->unk0 * 948]) { indexUnk51 = m->action->indexUnk51; } else { indexUnk51 = vg->indexUnk51; } int vb = -1; const MstShootIndex *var18 = &_res->_mstShootIndexData[indexUnk51]; for (; var24 < var18->count; ++var24) { assert(m->shootActionIndex >= 0 && m->shootActionIndex < 9); const uint32_t indexUnk50Unk1 = var18->indexUnk50Unk1[var24 * 9 + m->shootActionIndex]; const MstShootAction *m50Unk1 = &_res->_mstShootData[var18->indexUnk50].data[indexUnk50Unk1]; const int32_t hSize = m50Unk1->hSize; const int32_t vSize = m50Unk1->vSize; if (hSize != 0 || vSize != 0) { int dirMask = 0; int ve = 0; if ((m50Unk1->unk4 & kDirectionKeyMaskHorizontal) != kDirectionKeyMaskHorizontal && (m->o16->flags1 & 0x10) != 0) { _mstTemp_x1 = m->xMstPos - hSize; } else { _mstTemp_x1 = m->xMstPos + hSize; } if (_mstTemp_x1 < m->xMstPos) { if (_mstTemp_x1 < m->goalPos_x1) { dirMask = kDirectionKeyMaskLeft; } ve = kDirectionKeyMaskLeft; } else if (_mstTemp_x1 > m->xMstPos) { if (_mstTemp_x1 > m->goalPos_x2) { dirMask = kDirectionKeyMaskRight; } ve = kDirectionKeyMaskRight; } else { ve = 0; } _mstTemp_y1 = m->yMstPos + vSize; if (_mstTemp_y1 < m->yMstPos) { if (_mstTemp_y1 < m->goalPos_y1 && (m->monsterInfos[946] & 2) != 0) { dirMask |= kDirectionKeyMaskUp; } ve |= kDirectionKeyMaskUp; } else if (_mstTemp_y1 > m->yMstPos) { if (_mstTemp_y1 > m->goalPos_y2 && (m->monsterInfos[946] & 2) != 0) { dirMask |= kDirectionKeyMaskDown; } ve |= kDirectionKeyMaskDown; } if (var28 == dirMask) { continue; } if (mstMonster1CheckLevelBounds(m, _mstTemp_x1, _mstTemp_y1, ve)) { continue; } } _mstTemp_x1 = m->xMstPos; if ((m50Unk1->unk4 & kDirectionKeyMaskHorizontal) != kDirectionKeyMaskHorizontal && (m->o16->flags1 & 0x10) != 0) { _mstTemp_x1 -= m50Unk1->width; _mstTemp_x1 -= m50Unk1->xPos; } else { _mstTemp_x1 += m50Unk1->xPos; } _mstTemp_y1 = m->yMstPos + m50Unk1->yPos; _mstTemp_x2 = _mstTemp_x1 + m50Unk1->width - 1; _mstTemp_y2 = _mstTemp_y1 + m50Unk1->height - 1; if ((m->monsterInfos[946] & 4) != 0 && mstBoundingBoxCollides1(m->monster1Index, _mstTemp_x1, _mstTemp_y1, _mstTemp_x2, _mstTemp_y2) != 0) { continue; } if (m50Unk1->width != 0 && getMstDistance((m->monsterInfos[946] & 2) != 0 ? var14->boundingBox.y2 : m->yMstPos, var14) >= 0) { continue; } if (m->collideDistance >= m50Unk1->unk24) { MstBehaviorState *behaviorState = m->behaviorState; vb = var24; int vf = m50Unk1->unk24; if (behaviorState->unk18 != 0) { vf += (_rnd.update() % (behaviorState->unk18 * 2 + 1)) - behaviorState->unk18; if (vf < 0) { vf = 0; } } dir = vf; break; } if (var20 == -1) { dir = m50Unk1->unk24; var20 = var24; } vb = var20; } if (vb >= 0) { const uint32_t indexUnk50Unk1 = var18->indexUnk50Unk1[vb * 9 + m->shootActionIndex]; MstShootAction *m50Unk1 = &_res->_mstShootData[var18->indexUnk50].data[indexUnk50Unk1]; mstTaskAttack(_mstCurrentTask, m50Unk1->codeData, 0x40); _mstCurrentMonster1->unkF8 = m50Unk1->unk8; _mstCurrentMonster1->shootSource = dir; _mstCurrentMonster1->shootDirection = var14->directionMask; _mstCurrentMonster1->directionKeyMask = _andyObject->directionKeyMask; return 0; } } if (o->screenNum == _currentScreen && (m->flagsA5 & 0x20) == 0 && (m->flags48 & 0x10) != 0) { MstBehaviorState *behaviorState = m->behaviorState; if (behaviorState->attackBox != kNone) { const MstAttackBox *m47 = &_res->_mstAttackBoxData[behaviorState->attackBox]; if (m47->count > 0) { const uint8_t dir = (o->flags1 >> 4) & 3; const uint8_t *p = m47->data; for (uint32_t i = 0; i < m47->count; ++i) { int32_t a = READ_LE_UINT32(p); // x1 int32_t b = READ_LE_UINT32(p + 4); // y1 int32_t c = READ_LE_UINT32(p + 8); // x2 int32_t d = READ_LE_UINT32(p + 12); // y2 int x1, x2, y1, y2; switch (dir) { case 1: x1 = m->xMstPos - c; x2 = m->xMstPos - a; y1 = m->yMstPos + b; y2 = m->yMstPos + d; break; case 2: x1 = m->xMstPos + a; x2 = m->xMstPos + c; y1 = m->yMstPos - d; y2 = m->yMstPos - b; break; case 3: x1 = m->xMstPos - c; x2 = m->xMstPos - a; y1 = m->yMstPos - d; y2 = m->yMstPos - b; break; default: x1 = m->xMstPos + a; x2 = m->xMstPos + c; y1 = m->yMstPos + b; y2 = m->yMstPos + d; break; } if (rect_contains(x1, y1, x2, y2, _mstAndyLevelPosX, _mstAndyLevelPosY)) { mstTaskAttack(_mstCurrentTask, READ_LE_UINT32(p + 16), 0x20); mstMonster1Collide(_mstCurrentMonster1, ptr); return 0; } p += 20; } } } } if (mstMonster1Collide(_mstCurrentMonster1, ptr)) { return 0; } uint8_t _al = _mstCurrentMonster1->flagsA6; if (_al & 2) { return 0; } uint8_t _dl = _mstCurrentMonster1->flagsA5; if (_dl & 0x30) { return 0; } dir = _dl & 3; if (dir == 1) { MstWalkNode *walkNode = _mstCurrentMonster1->walkNode; if (walkNode->walkCodeStage2 == kNone) { return 0; } int ve = 0; if (_mstAndyLevelPosY >= m->yMstPos - walkNode->y1 && _mstAndyLevelPosY < m->yMstPos + walkNode->y2) { if (walkNode->x1 != -2 || walkNode->x1 != walkNode->x2) { if (m->xDelta <= walkNode->x1) { if (_al & 1) { ve = 1; } else { _al = mstGetFacingDirectionMask(_mstCurrentMonster1->facingDirectionMask) & 1; _dl = (_mstCurrentMonster1->o16->flags1 >> 4) & 1; if (_dl == _al || (_mstCurrentMonster1->monsterInfos[946] & 4) != 0) { ve = 1; } else if (m->xDelta <= walkNode->x2) { ve = 2; } } } } else if (o->screenNum == _currentScreen) { if (_al & 1) { ve = 1; } else { _al = mstGetFacingDirectionMask(_mstCurrentMonster1->facingDirectionMask) & 1; _dl = (_mstCurrentMonster1->o16->flags1 >> 4) & 1; if (_al != _dl && (_mstCurrentMonster1->monsterInfos[946] & 4) == 0) { ve = 2; } else { ve = 1; } } } } if (ve == 0) { m->flagsA6 &= ~1; if ((m->flagsA5 & 4) == 0) { const uint32_t indexWalkCode = m->walkNode->walkCodeReset[0]; m->walkCode = &_res->_mstWalkCodeData[indexWalkCode]; } return 0; } else if (ve == 1) { m->flagsA6 |= 1; assert(_mstCurrentMonster1 == m); if (!mstSetCurrentPos(m, m->xMstPos, m->yMstPos) && (m->monsterInfos[946] & 2) == 0) { if ((_mstCurrentPosX > m->xMstPos && _mstCurrentPosX > m->walkNode->coords[0][1]) || (_mstCurrentPosX < m->xMstPos && _mstCurrentPosX < m->walkNode->coords[1][1])) { uint32_t indexWalkCode = m->walkNode->walkCodeStage1; if (indexWalkCode != kNone) { m->walkCode = &_res->_mstWalkCodeData[indexWalkCode]; } if (m->flagsA5 & 4) { m->flagsA5 &= ~4; if (!mstMonster1UpdateWalkPath(m)) { mstMonster1ResetWalkPath(m); } indexWalkCode = m->walkNode->walkCodeStage1; if (indexWalkCode != kNone) { m->walkCode = &_res->_mstWalkCodeData[indexWalkCode]; } mstTaskSetNextWalkCode(_mstCurrentTask); } return 0; } } if ((m->monsterInfos[946] & 2) == 0) { MstWalkNode *walkPath = m->walkNode; int vf = (int32_t)READ_LE_UINT32(m->monsterInfos + 904); int vb = MAX(m->goalPosBounds_x1, walkPath->coords[1][1] + vf); int va = MIN(m->goalPosBounds_x2, walkPath->coords[0][1] - vf); const uint32_t indexUnk36 = walkPath->movingBoundsIndex2; const uint32_t indexUnk49 = _res->_mstMovingBoundsIndexData[indexUnk36].indexUnk49; uint8_t _bl = _res->_mstMovingBoundsData[indexUnk49].unk14; if (ABS(va - vb) <= _bl) { uint32_t indexWalkCode = walkPath->walkCodeStage1; if (indexWalkCode != kNone) { m->walkCode = &_res->_mstWalkCodeData[indexWalkCode]; } if (m->flagsA5 & 4) { m->flagsA5 &= ~4; if (!mstMonster1UpdateWalkPath(m)) { mstMonster1ResetWalkPath(m); } indexWalkCode = m->walkNode->walkCodeStage1; if (indexWalkCode != kNone) { m->walkCode = &_res->_mstWalkCodeData[indexWalkCode]; } mstTaskSetNextWalkCode(_mstCurrentTask); } return 0; } } mstTaskInitMonster1Type2(_mstCurrentTask, 0); return 0; } assert(ve == 2); if (m->flagsA6 & 1) { return 0; } const uint32_t indexWalkCode = m->walkNode->walkCodeStage2; MstWalkCode *m35 = &_res->_mstWalkCodeData[indexWalkCode]; if (m->walkCode != m35) { _mstCurrentMonster1->walkCode = m35; _rnd.resetMst(_mstCurrentMonster1->rnd_m35); mstTaskSetNextWalkCode(_mstCurrentTask); return 0; } if (m->flagsA5 & 4) { m->flagsA5 &= ~4; if (!mstMonster1UpdateWalkPath(_mstCurrentMonster1)) { mstMonster1ResetWalkPath(_mstCurrentMonster1); } const uint32_t indexWalkCode = m->walkNode->walkCodeStage2; _mstCurrentMonster1->walkCode = &_res->_mstWalkCodeData[indexWalkCode]; mstTaskSetNextWalkCode(_mstCurrentTask); } return 0; } else if (dir != 2) { return 0; } if ((m->flagsA5 & 4) != 0 || (m->flags48 & 8) == 0) { return 0; } if ((m->flagsA5 & 8) == 0 && (m->monsterInfos[946] & 2) == 0) { const uint8_t _dl = m->facingDirectionMask; if (_dl & kDirectionKeyMaskRight) { if ((int32_t)READ_LE_UINT32(m->monsterInfos + 916) <= m->walkNode->coords[1][1] || (int32_t)READ_LE_UINT32(m->monsterInfos + 912) >= m->walkNode->coords[0][1]) { m->flagsA6 |= 1; assert(m == _mstCurrentMonster1); m->flagsA5 = 1; mstMonster1ResetWalkPath(m); const uint32_t indexWalkCode = m->walkNode->walkCodeStage1; if (indexWalkCode != kNone) { m->walkCode = &_res->_mstWalkCodeData[indexWalkCode]; } return 0; } } else if (_dl & kDirectionKeyMaskLeft) { if ((int32_t)READ_LE_UINT32(m->monsterInfos + 920) >= m->walkNode->coords[0][1] || (int32_t)READ_LE_UINT32(m->monsterInfos + 924) <= m->walkNode->coords[1][1]) { m->flagsA6 |= 1; assert(m == _mstCurrentMonster1); m->flagsA5 = 1; mstMonster1ResetWalkPath(m); const uint32_t indexWalkCode = m->walkNode->walkCodeStage1; if (indexWalkCode != kNone) { m->walkCode = &_res->_mstWalkCodeData[indexWalkCode]; } return 0; } } } if (!mstSetCurrentPos(m, m->xMstPos, m->yMstPos)) { mstTaskInitMonster1Type2(t, 1); } return 0; } int Game::mstUpdateTaskMonsterObject2(Task *t) { debug(kDebug_MONSTER, "mstUpdateTaskMonsterObject2 t %p", t); mstTaskSetMonster2ScreenPosition(t); MonsterObject2 *m = t->monster2; if (_currentLevel == kLvl_fort && m->monster2Info->type == 27) { if (_fireflyPosData[m->hPosIndex] == 0xFF) { uint32_t r = _rnd.update(); uint8_t _dl = (r % 5) << 3; m->vPosIndex = _dl; if (m->hPosIndex >= 40) { m->hPosIndex = _dl; m->vPosIndex = _dl + 40; m->hDir = (r >> 16) & 1; } else { m->hPosIndex = m->vPosIndex + 40; m->vDir = (r >> 16) & 1; } } int dx = _fireflyPosData[m->hPosIndex]; if (m->hDir == 0) { dx = -dx; } int dy = _fireflyPosData[m->vPosIndex]; if (m->vDir == 0) { dy = -dy; } ++m->vPosIndex; ++m->hPosIndex; m->o->xPos += dx; m->o->yPos += dy; m->xMstPos += dx; m->yMstPos += dy; if (m->xMstPos > m->x2) { m->hDir = 0; } else if (m->xMstPos < m->x1) { m->hDir = 1; } if (m->yMstPos > m->y2) { m->vDir = 0; } else if (m->yMstPos < m->y1) { m->vDir = 1; } } uint8_t _dl = 0; for (int i = 0; i < _andyShootsCount; ++i) { AndyShootData *p = &_andyShootsTable[i]; if (p->type == 2) { _dl |= 1; } else if (p->type == 1) { _dl |= 2; } } LvlObject *o = m->o; MstInfoMonster2 *monster2Info = m->monster2Info; const uint8_t _bl = monster2Info->shootMask; if ((_bl & _dl) != 0) { for (int i = 0; i < _andyShootsCount; ++i) { AndyShootData *p = &_andyShootsTable[i]; if (p->type == 2 && (_bl & 1) == 0) { continue; } else if (p->type == 1 && (_bl & 2) == 0) { continue; } if (o->screenNum != _currentScreen || p->o->screenNum != _currentScreen) { continue; } if (!clipLvlObjectsBoundingBox(p->o, o, 20)) { continue; } ShootLvlObjectData *s = p->shootObjectData; s->unk3 = 0x80; s->xPosShoot = o->xPos + o->width / 2; s->yPosShoot = o->yPos + o->height / 2; if (p->type != 2 || (_bl & 4) != 0) { continue; } const uint32_t codeData = monster2Info->codeData2; if (codeData != kNone) { resetTask(t, _res->_mstCodeData + codeData * 4); } else { o->actionKeyMask = 7; o->directionKeyMask = 0; t->run = &Game::mstTask_idle; } } } if ((m->o->flags0 & 0xFF) == 0x1F) { mstRemoveMonsterObject2(t, &_monsterObjects2TasksList); return 1; } return 0; } void Game::mstUpdateRefPos() { if (_andyObject) { _mstAndyScreenPosX = _andyObject->xPos; _mstAndyScreenPosY = _andyObject->yPos; _mstAndyLevelPosX = _mstAndyScreenPosX + _res->_mstPointOffsets[_currentScreen].xOffset; _mstAndyLevelPosY = _mstAndyScreenPosY + _res->_mstPointOffsets[_currentScreen].yOffset; if (!_specialAnimFlag) { _mstAndyRectNum = mstBoundingBoxUpdate(_mstAndyRectNum, 0xFE, _mstAndyLevelPosX, _mstAndyLevelPosY, _mstAndyLevelPosX + _andyObject->width - 1, _mstAndyLevelPosY + _andyObject->height - 1) & 0xFF; } _mstAndyScreenPosX += _andyObject->posTable[3].x; _mstAndyScreenPosY += _andyObject->posTable[3].y; _mstAndyLevelPosX += _andyObject->posTable[3].x; _mstAndyLevelPosY += _andyObject->posTable[3].y; } else { _mstAndyScreenPosX = 128; _mstAndyScreenPosY = 96; _mstAndyLevelPosX = _mstAndyScreenPosX + _res->_mstPointOffsets[0].xOffset; _mstAndyLevelPosY = _mstAndyScreenPosY + _res->_mstPointOffsets[0].yOffset; } _andyShootsCount = 0; _andyShootsTable[0].type = 0; if (!_lvlObjectsList0) { if (_plasmaCannonDirection == 0) { _executeMstLogicPrevCounter = _executeMstLogicCounter; return; } _andyShootsTable[0].width = 512; _andyShootsTable[0].height = 512; _andyShootsTable[0].shootObjectData = 0; _andyShootsTable[0].type = 3; _andyShootsTable[0].size = 4; _andyShootsTable[0].xPos = _plasmaCannonPosX[_plasmaCannonFirstIndex] + _res->_mstPointOffsets[_currentScreen].xOffset; _andyShootsTable[0].yPos = _plasmaCannonPosY[_plasmaCannonFirstIndex] + _res->_mstPointOffsets[_currentScreen].yOffset; switch (_plasmaCannonDirection - 1) { case 0: _andyShootsTable[0].directionMask = 6; _andyShootsCount = 1; break; case 2: _andyShootsTable[0].directionMask = 3; _andyShootsCount = 1; break; case 1: _andyShootsTable[0].directionMask = 0; _andyShootsCount = 1; break; case 5: _andyShootsTable[0].directionMask = 4; _andyShootsCount = 1; break; case 3: _andyShootsTable[0].directionMask = 7; _andyShootsCount = 1; break; case 11: _andyShootsTable[0].directionMask = 2; _andyShootsCount = 1; break; case 7: _andyShootsTable[0].directionMask = 5; _andyShootsCount = 1; break; case 8: _andyShootsTable[0].directionMask = 1; _andyShootsCount = 1; break; default: _andyShootsCount = 1; break; } } else { AndyShootData *p = _andyShootsTable; for (LvlObject *o = _lvlObjectsList0; o; o = o->nextPtr) { p->o = o; if (!o->dataPtr) { continue; } ShootLvlObjectData *ptr = (ShootLvlObjectData *)getLvlObjectDataPtr(o, kObjectDataTypeShoot); p->shootObjectData = ptr; if (ptr->unk3 == 0x80) { continue; } if (ptr->dxPos == 0 && ptr->dyPos == 0) { continue; } p->width = ptr->dxPos; p->height = ptr->dyPos; p->directionMask = ptr->state; switch (ptr->type) { case 0: p->type = 1; p->xPos = o->xPos + _res->_mstPointOffsets[o->screenNum].xOffset + o->posTable[7].x; p->size = 3; p->yPos = o->yPos + _res->_mstPointOffsets[o->screenNum].yOffset + o->posTable[7].y; break; case 5: p->directionMask |= 0x80; // fall-through case 4: p->type = 2; p->xPos = o->xPos + _res->_mstPointOffsets[o->screenNum].xOffset + o->posTable[7].x; p->size = 7; p->yPos = o->yPos + _res->_mstPointOffsets[o->screenNum].yOffset + o->posTable[7].y; break; default: --p; --_andyShootsCount; break; } ++p; ++_andyShootsCount; if (_andyShootsCount >= kMaxAndyShoots) { break; } } if (_andyShootsCount == 0) { _executeMstLogicPrevCounter = _executeMstLogicCounter; return; } } for (int i = 0; i < _andyShootsCount; ++i) { AndyShootData *p = &_andyShootsTable[i]; p->boundingBox.x2 = p->xPos + p->size; p->boundingBox.x1 = p->xPos - p->size; p->boundingBox.y2 = p->yPos + p->size; p->boundingBox.y1 = p->yPos - p->size; } } void Game::mstUpdateMonstersRect() { const int _mstAndyLevelPosDx = _mstAndyLevelPosX - _mstAndyLevelPrevPosX; const int _mstAndyLevelPosDy = _mstAndyLevelPosY - _mstAndyLevelPrevPosY; _mstAndyLevelPrevPosX = _mstAndyLevelPosX; _mstAndyLevelPrevPosY = _mstAndyLevelPosY; if (_mstAndyLevelPosDx == 0 && _mstAndyLevelPosDy == 0) { return; } int offset = 0; for (int i = 0; i < _res->_mstHdr.infoMonster1Count; ++i) { offset += kMonsterInfoDataSize; const uint32_t unk30 = READ_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x30]); // 900 const uint32_t unk34 = READ_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x34]); // 896 const uint32_t unk20 = _mstAndyLevelPosX - unk30; const uint32_t unk1C = _mstAndyLevelPosX + unk30; WRITE_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x20], unk20); WRITE_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x1C], unk1C); WRITE_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x24], unk20 - unk34); WRITE_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x18], unk1C + unk34); const uint32_t unk10 = _mstAndyLevelPosY - unk30; const uint32_t unk0C = _mstAndyLevelPosY + unk30; WRITE_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x10], unk10); WRITE_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x0C], unk0C); WRITE_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x14], unk10 - unk34); WRITE_LE_UINT32(&_res->_mstMonsterInfos[offset - 0x08], unk0C + unk34); } } void Game::mstRemoveMonsterObject2(Task *t, Task **tasksList) { MonsterObject2 *m = t->monster2; m->monster2Info = 0; LvlObject *o = m->o; if (o) { o->dataPtr = 0; removeLvlObject2(o); } removeTask(tasksList, t); } void Game::mstRemoveMonsterObject1(Task *t, Task **tasksList) { MonsterObject1 *m = t->monster1; if (_mstActionNum != -1) { if ((m->flagsA5 & 8) != 0 && m->action) { mstMonster1ClearChasingMonster(m); } } if (m->monsterInfos[946] & 4) { mstBoundingBoxClear(m, 0); mstBoundingBoxClear(m, 1); } m->m46 = 0; LvlObject *o = m->o16; if (o) { o->dataPtr = 0; } for (int i = 0; i < kMaxMonsterObjects2; ++i) { if (_monsterObjects2Table[i].monster2Info != 0 && _monsterObjects2Table[i].monster1 == m) { _monsterObjects2Table[i].monster1 = 0; } } removeLvlObject2(o); removeTask(tasksList, t); } void Game::mstTaskAttack(Task *t, uint32_t codeData, uint8_t flags) { MonsterObject1 *m = t->monster1; m->flagsA5 = (m->flagsA5 & ~0x70) | flags; Task *c = t->child; if (c) { t->child = 0; c->codeData = 0; } if (m->flagsA5 & 8) { Task *n = findFreeTask(); if (n) { memcpy(n, t, sizeof(Task)); t->child = n; if (t->run != &Game::mstTask_wait2) { const uint8_t *p = n->codeData - 4; if ((t->flags & 0x40) != 0 || p[0] == 203 || ((flags & 0x10) != 0 && (t->run == &Game::mstTask_monsterWait1 || t->run == &Game::mstTask_monsterWait2 || t->run == &Game::mstTask_monsterWait3 || t->run == &Game::mstTask_monsterWait4))) { p += 4; } n->codeData = p; n->run = &Game::mstTask_main; } } } assert(codeData != kNone); resetTask(t, _res->_mstCodeData + codeData * 4); } int Game::mstTaskSetActionDirection(Task *t, int num, int delay) { MonsterObject1 *m = t->monster1; LvlObject *o = m->o16; uint8_t var4 = _res->_mstActionDirectionData[num].unk0; uint8_t var8 = _res->_mstActionDirectionData[num].unk2; const uint8_t *p = m->monsterInfos + var4 * 28; uint8_t _al = (o->flags1 >> 4) & 3; uint8_t _cl = ((_al & 1) != 0) ? 8 : 2; if (_al & 2) { _cl |= 4; } else { _cl |= 1; } mstLvlObjectSetActionDirection(o, p, var8, _cl); const uint8_t am = _res->_mstActionDirectionData[num].unk1; o->actionKeyMask |= am; t->flags &= ~0x80; int vf = (int8_t)p[4]; int ve = (int8_t)p[5]; debug(kDebug_MONSTER, "mstTaskSetActionDirection m %p action 0x%x direction 0x%x (%d,%d)", m, o->actionKeyMask, o->directionKeyMask, vf, ve); int va = 0; if (vf != 0 || ve != 0) { int dirMask = 0; uint8_t var11 = p[2]; if (((var11 & kDirectionKeyMaskHorizontal) == kDirectionKeyMaskHorizontal && (o->directionKeyMask & 8) != 0) || ((var11 & kDirectionKeyMaskHorizontal) != kDirectionKeyMaskHorizontal && (o->flags1 & 0x10) != 0)) { vf = m->xMstPos - vf; } else { vf = m->xMstPos + vf; } if (vf < m->xMstPos) { dirMask = kDirectionKeyMaskLeft; } else if (vf > m->xMstPos) { dirMask = kDirectionKeyMaskRight; } if ((var11 & kDirectionKeyMaskVertical) == kDirectionKeyMaskVertical && (o->directionKeyMask & 1) != 0) { ve = m->yMstPos - ve; } else { ve = m->yMstPos + ve; } if (ve < m->yMstPos) { dirMask |= kDirectionKeyMaskUp; } else if (ve > m->yMstPos) { dirMask |= kDirectionKeyMaskDown; } if (mstMonster1CheckLevelBounds(m, vf, ve, dirMask)) { t->flags |= 0x80; return 0; } va = dirMask; } if ((m->monsterInfos[946] & 4) != 0 && p[0xE] != 0) { if (va == 0) { ve = 0; } else if (_mstLut1[va] & 1) { ve = (int8_t)p[0xA]; va = (int8_t)p[0xB]; } else { ve = (int8_t)p[0x8]; va = (int8_t)p[0x9]; } if (o->directionKeyMask & kDirectionKeyMaskLeft) { ve = -ve; } else if ((o->directionKeyMask & kDirectionKeyMaskRight) == 0) { ve = 0; } if (o->directionKeyMask & kDirectionKeyMaskUp) { va = -va; } else if ((o->directionKeyMask & kDirectionKeyMaskDown) == 0) { va = 0; } const int x1 = m->xMstPos + (int8_t)p[0xC] + ve; const int y1 = m->yMstPos + (int8_t)p[0xD] + va; const int x2 = x1 + p[0xE] - 1; const int y2 = y1 + p[0xF] - 1; if ((var8 & 0xE0) != 0x60 && mstBoundingBoxCollides2(m->monster1Index, x1, y1, x2, y2) != 0) { t->flags |= 0x80; return 0; } m->bboxNum[0] = mstBoundingBoxUpdate(m->bboxNum[0], m->monster1Index, x1, y1, x2, y2); } m->o_flags0 = var4; if (delay == -1) { const uint32_t offset = m->monsterInfos - _res->_mstMonsterInfos; assert((offset % kMonsterInfoDataSize) == 0); t->arg2 = offset / kMonsterInfoDataSize; t->run = &Game::mstTask_monsterWait4; debug(kDebug_MONSTER, "mstTaskSetActionDirection arg2 %d", t->arg2); } else { t->arg1 = delay; t->run = &Game::mstTask_monsterWait3; debug(kDebug_MONSTER, "mstTaskSetActionDirection arg1 %d", t->arg1); } return 1; } Task *Game::findFreeTask() { for (int i = 0; i < kMaxTasks; ++i) { Task *t = &_tasksTable[i]; if (!t->codeData) { memset(t, 0, sizeof(Task)); return t; } } warning("findFreeTask() no free task"); return 0; } Task *Game::createTask(const uint8_t *codeData) { Task *t = findFreeTask(); if (t) { resetTask(t, codeData); t->prevPtr = 0; t->nextPtr = _tasksList; if (_tasksList) { _tasksList->prevPtr = t; } _tasksList = t; return t; } return 0; } void Game::updateTask(Task *t, int num, const uint8_t *codeData) { debug(kDebug_MONSTER, "updateTask t %p offset 0x%04x", t, codeData - _res->_mstCodeData); Task *current = _tasksList; bool found = false; while (current) { Task *nextPtr = current->nextPtr; if (current->localVars[7] == num) { found = true; if (current != t) { if (!codeData) { if (current->child) { current->child->codeData = 0; current->child = 0; } Task *prev = current->prevPtr; current->codeData = 0; Task *next = current->nextPtr; if (next) { next->prevPtr = prev; } if (prev) { prev->nextPtr = next; } else { _tasksList = next; } } else { t->codeData = codeData; t->run = &Game::mstTask_main; } } } current = nextPtr; } if (found) { return; } if (codeData) { t = findFreeTask(); if (t) { resetTask(t, codeData); t->prevPtr = 0; t->nextPtr = _tasksList; if (_tasksList) { _tasksList->prevPtr = t; } _tasksList = t; t->localVars[7] = num; } } } void Game::resetTask(Task *t, const uint8_t *codeData) { debug(kDebug_MONSTER, "resetTask t %p offset 0x%04x monster1 %p monster2 %p", t, codeData - _res->_mstCodeData, t->monster1, t->monster2); assert(codeData); t->state |= 2; t->codeData = codeData; t->run = &Game::mstTask_main; t->localVars[7] = 0; MonsterObject1 *m = t->monster1; if (m) { const uint8_t mask = m->flagsA5; if ((mask & 0x88) == 0 || (mask & 0xF0) == 0) { if ((mask & 8) != 0) { t->flags = (t->flags & ~0x40) | 0x20; m->flags48 &= ~0x1C; } else if ((mask & 2) != 0) { m->flags48 |= 8; const MstBehaviorState *behaviorState = m->behaviorState; if (behaviorState->indexUnk51 != kNone) { m->flags48 |= 4; } if (behaviorState->attackBox != kNone) { m->flags48 |= 0x10; } } } } } void Game::removeTask(Task **tasksList, Task *t) { Task *c = t->child; if (c) { c->codeData = 0; t->child = 0; } Task *prev = t->prevPtr; t->codeData = 0; Task *next = t->nextPtr; if (next) { next->prevPtr = prev; } if (prev) { prev->nextPtr = next; } else { *tasksList = next; } } void Game::appendTask(Task **tasksList, Task *t) { Task *current = *tasksList; if (!current) { *tasksList = t; t->nextPtr = t->prevPtr = 0; } else { // go to last element Task *next = current->nextPtr; while (next) { current = next; next = current->nextPtr; } assert(!current->nextPtr); current->nextPtr = t; t->nextPtr = 0; t->prevPtr = current; } } int Game::getTaskVar(Task *t, int index, int type) const { switch (type) { case 1: return index; case 2: assert(index < kMaxLocals); return t->localVars[index]; case 3: assert(index < kMaxVars); return _mstVars[index]; case 4: return getTaskOtherVar(index, t); case 5: { MonsterObject1 *m = 0; if (t->monster2) { m = t->monster2->monster1; } else { m = t->monster1; } if (m) { assert(index < kMaxLocals); return m->localVars[index]; } } break; default: warning("getTaskVar unhandled index %d type %d", index, type); break; } return 0; } void Game::setTaskVar(Task *t, int index, int type, int value) { switch (type) { case 2: assert(index < kMaxLocals); t->localVars[index] = value; break; case 3: assert(index < kMaxVars); _mstVars[index] = value; break; case 5: { MonsterObject1 *m = 0; if (t->monster2) { m = t->monster2->monster1; } else { m = t->monster1; } if (m) { assert(index < kMaxLocals); m->localVars[index] = value; } } break; default: warning("setTaskVar unhandled index %d type %d", index, type); break; } } int Game::getTaskAndyVar(int index, Task *t) const { if (index & 0x80) { const int mask = 1 << (index & 0x7F); return ((mask & _mstAndyVarMask) != 0) ? 1 : 0; } switch (index) { case 0: return (_andyObject->flags1 >> 4) & 1; case 1: return (_andyObject->flags1 >> 5) & 1; case 2: { MonsterObject1 *m = t->monster1; if (m) { return ((m->o16->flags1 & 0x10) != 0) ? 1 : 0; } else if (t->monster2) { return ((t->monster2->o->flags1 & 0x10) != 0) ? 1 : 0; } } break; case 3: { MonsterObject1 *m = t->monster1; if (m) { return ((m->o16->flags1 & 0x20) != 0) ? 1 : 0; } else if (t->monster2) { return ((t->monster2->o->flags1 & 0x20) != 0) ? 1 : 0; } } break; case 4: { MonsterObject1 *m = t->monster1; if (m) { return ((m->o16->flags0 & 0x200) != 0) ? 1 : 0; } else if (t->monster2) { return ((t->monster2->o->flags0 & 0x200) != 0) ? 1 : 0; } } break; case 5: return ((_andyObject->flags0 & 0x1F) == 7) ? 1 : 0; case 6: return (_andyObject->spriteNum == 0) ? 1 : 0; case 7: if ((_andyObject->flags0 & 0x1F) == 7) { AndyLvlObjectData *andyData = (AndyLvlObjectData *)getLvlObjectDataPtr(_andyObject, kObjectDataTypeAndy); if (andyData) { LvlObject *o = andyData->shootLvlObject; if (o && o->dataPtr) { ShootLvlObjectData *data = (ShootLvlObjectData *)getLvlObjectDataPtr(o, kObjectDataTypeShoot); return (data->type == 4) ? 1 : 0; } } } break; case 8: if ((_andyObject->flags0 & 0x1F) == 7) { AndyLvlObjectData *andyData = (AndyLvlObjectData *)getLvlObjectDataPtr(_andyObject, kObjectDataTypeAndy); if (andyData) { LvlObject *o = andyData->shootLvlObject; if (o && o->dataPtr) { ShootLvlObjectData *data = (ShootLvlObjectData *)getLvlObjectDataPtr(o, kObjectDataTypeShoot); return (data->type == 0) ? 1 : 0; } } } default: warning("getTaskAndyVar unhandled index %d", index); break; } return 0; } int Game::getTaskOtherVar(int index, Task *t) const { switch (index) { case 0: return _mstAndyScreenPosX; case 1: return _mstAndyScreenPosY; case 2: return _mstAndyLevelPosX; case 3: return _mstAndyLevelPosY; case 4: return _currentScreen; case 5: return _res->_screensState[_currentScreen].s0; case 6: return _difficulty; case 7: if (t->monster1 && t->monster1->shootData) { return t->monster1->shootData->type; } return _andyShootsTable[0].type; case 8: if (t->monster1 && t->monster1->shootData) { return t->monster1->shootData->directionMask & 0x7F; } return _andyShootsTable[0].directionMask & 0x7F; case 9: if (t->monster1 && t->monster1->action) { return t->monster1->action->xPos; } break; case 10: if (t->monster1 && t->monster1->action) { return t->monster1->action->yPos; } break; case 11: if (t->monster1) { return t->monster1->shootSource; } break; case 12: if (t->monster1) { return t->monster1->xPos; } else if (t->monster2) { return t->monster2->xPos; } break; case 13: if (t->monster1) { return t->monster1->yPos; } else if (t->monster2) { return t->monster2->yPos; } break; case 14: if (t->monster1) { return t->monster1->o16->screenNum; } else if (t->monster2) { return t->monster2->o->screenNum; } break; case 15: if (t->monster1) { return t->monster1->xDelta; } else if (t->monster2) { return ABS(_mstAndyLevelPosX - t->monster2->xMstPos); } break; case 16: if (t->monster1) { return t->monster1->yDelta; } else if (t->monster2) { return ABS(_mstAndyLevelPosY - t->monster2->yMstPos); } break; case 17: if (t->monster1) { return t->monster1->collideDistance; } break; case 18: if (t->monster1) { return ABS(t->monster1->levelPosBounds_x1 - t->monster1->xMstPos); } break; case 19: if (t->monster1) { return ABS(t->monster1->levelPosBounds_x2 - t->monster1->xMstPos); } break; case 20: if (t->monster1) { return ABS(t->monster1->levelPosBounds_y1 - t->monster1->yMstPos); } break; case 21: if (t->monster1) { return ABS(t->monster1->levelPosBounds_y2 - t->monster1->yMstPos); } break; case 22: return _mstOp54Counter; case 23: return _andyObject->actionKeyMask; case 24: return _andyObject->directionKeyMask; case 25: if (t->monster1) { return t->monster1->xMstPos; } else if (t->monster2) { return t->monster2->xMstPos; } break; case 26: if (t->monster1) { return t->monster1->yMstPos; } else if (t->monster2) { return t->monster2->yMstPos; } break; case 27: if (t->monster1) { return t->monster1->o16->flags0 & 0xFF; } else if (t->monster2) { return t->monster2->o->flags0 & 0xFF; } break; case 28: if (t->monster1) { return t->monster1->o16->anim; } else if (t->monster2) { return t->monster2->o->anim; } break; case 29: if (t->monster1) { return t->monster1->o16->frame; } else if (t->monster2) { return t->monster2->o->frame; } break; case 30: return _mstOp56Counter; case 31: return _executeMstLogicCounter; case 32: return _executeMstLogicCounter - _executeMstLogicPrevCounter; case 33: { LvlObject *o = 0; if (t->monster1) { o = t->monster1->o16; } else if (t->monster2) { o = t->monster2->o; } if (o) { return _res->_screensState[o->screenNum].s0; } } break; case 34: return _level->_checkpoint; case 35: return _mstAndyCurrentScreenNum; default: warning("getTaskOtherVar unhandled index %d", index); break; } return 0; } int Game::getTaskFlag(Task *t, int num, int type) const { switch (type) { case 1: return num; case 2: return ((t->flags & (1 << num)) != 0) ? 1 : 0; case 3: return ((_mstFlags & (1 << num)) != 0) ? 1 : 0; case 4: return getTaskAndyVar(num, t); case 5: { MonsterObject1 *m = 0; if (t->monster2) { m = t->monster2->monster1; } else { m = t->monster1; } if (m) { return ((m->flags48 & (1 << num)) != 0) ? 1 : 0; } } default: warning("getTaskFlag unhandled type %d num %d", type, num); break; } return 0; } int Game::mstTask_main(Task *t) { assert(t->codeData); const int taskNum = t - _tasksTable; int ret = 0; t->state &= ~2; const uint8_t *p = t->codeData; do { assert(p >= _res->_mstCodeData && p < _res->_mstCodeData + _res->_mstHdr.codeSize * 4); assert(((p - t->codeData) & 3) == 0); const uint32_t codeOffset = p - _res->_mstCodeData; debug(kDebug_MONSTER, "executeMstCode task %d %p code %d offset 0x%04x", taskNum, t, p[0], codeOffset); assert(p[0] <= 242); switch (p[0]) { case 0: { // 0 LvlObject *o = 0; if (t->monster1) { if ((t->monster1->flagsA6 & 2) == 0) { o = t->monster1->o16; } } else if (t->monster2) { o = t->monster2->o; } if (o) { o->actionKeyMask = 0; o->directionKeyMask = 0; } } // fall-through case 1: { // 1 const int num = READ_LE_UINT16(p + 2); const int delay = getTaskVar(t, num, p[1]); t->arg1 = delay; if (delay > 0) { if (p[0] == 0) { t->run = &Game::mstTask_wait2; ret = 1; } else { t->run = &Game::mstTask_wait1; ret = 1; } } } break; case 2: { // 2 - set_var_random_range const int num = READ_LE_UINT16(p + 2); MstOp2Data *m = &_res->_mstOp2Data[num]; int a = getTaskVar(t, m->indexVar1, m->maskVars >> 4); int b = getTaskVar(t, m->indexVar2, m->maskVars & 15); if (a > b) { SWAP(a, b); } a += _rnd.update() % (b - a + 1); setTaskVar(t, m->unkA, m->unk9, a); } break; case 3: case 8: // 3 - set_monster_action_direction_imm if (t->monster1) { const int num = READ_LE_UINT16(p + 2); const int arg = _res->_mstActionDirectionData[num].unk3; t->codeData = p; ret = mstTaskSetActionDirection(t, num, (arg == 0xFF) ? -1 : arg); } break; case 4: // 4 - set_monster_action_direction_task_var if (t->monster1) { const int num = READ_LE_UINT16(p + 2); const int arg = _res->_mstActionDirectionData[num].unk3; t->codeData = p; assert(arg < kMaxLocals); ret = mstTaskSetActionDirection(t, num, t->localVars[arg]); } break; case 13: // 8 if (t->monster1) { const int num = READ_LE_UINT16(p + 2); if (mstTestActionDirection(t->monster1, num)) { const int arg = _res->_mstActionDirectionData[num].unk3; t->codeData = p; ret = mstTaskSetActionDirection(t, num, (arg == 0xFF) ? -1 : arg); } } break; case 23: // 13 - set_flag_global _mstFlags |= (1 << p[1]); break; case 24: // 14 - set_flag_task t->flags |= (1 << p[1]); break; case 25: { // 15 - set_flag_mst MonsterObject1 *m = 0; if (t->monster2) { m = t->monster2->monster1; } else { m = t->monster1; } if (m) { m->flags48 |= (1 << p[1]); } } break; case 26: // 16 - clear_flag_global _mstFlags &= ~(1 << p[1]); break; case 27: // 17 - clear_flag_task t->flags &= ~(1 << p[1]); break; case 28: { // 18 - clear_flag_mst MonsterObject1 *m = 0; if (t->monster2) { m = t->monster2->monster1; } else { m = t->monster1; } if (m) { m->flags48 &= ~(1 << p[1]); } } break; case 30: { // 20 t->arg1 = 3; t->arg2 = p[1]; if (((1 << p[1]) & _mstFlags) == 0) { LvlObject *o = 0; if (t->monster1) { if ((t->monster1->flagsA6 & 2) == 0) { o = t->monster1->o16; } } else if (t->monster2) { o = t->monster2->o; } if (o) { o->actionKeyMask = 0; o->directionKeyMask = 0; } t->run = &Game::mstTask_wait3; ret = 1; } } break; case 32: { // 22 MonsterObject1 *m = 0; if (t->monster2) { m = t->monster2->monster1; } else { m = t->monster1; } if (m) { t->arg1 = 5; t->arg2 = p[1]; if (((1 << p[1]) & m->flags48) == 0) { LvlObject *o = 0; if (t->monster1) { if ((t->monster1->flagsA6 & 2) == 0) { o = t->monster1->o16; } } else if (t->monster2) { o = t->monster2->o; } if (o) { o->actionKeyMask = 0; o->directionKeyMask = 0; } t->run = &Game::mstTask_wait3; ret = 1; } } } break; case 33: case 229: { // 23 - jmp_imm const int num = READ_LE_UINT16(p + 2); p = _res->_mstCodeData + num * 4 - 4; } break; case 34: // no-op break; case 35: { // 24 - enable_trigger const int num = READ_LE_UINT16(p + 2); _res->flagMstCodeForPos(num, 1); } break; case 36: { // 25 - disable_trigger const int num = READ_LE_UINT16(p + 2); _res->flagMstCodeForPos(num, 0); } break; case 39: // 26 - remove_monsters_screen if (p[1] < _res->_mstHdr.screensCount) { mstOp26_removeMstTaskScreen(&_monsterObjects1TasksList, p[1]); mstOp26_removeMstTaskScreen(&_monsterObjects2TasksList, p[1]); // mstOp26_removeMstTaskScreen(&_mstTasksList3, p[1]); // mstOp26_removeMstTaskScreen(&_mstTasksList4, p[1]); } break; case 40: // 27 - remove_monsters_screen_type if (p[1] < _res->_mstHdr.screensCount) { mstOp27_removeMstTaskScreenType(&_monsterObjects1TasksList, p[1], p[2]); mstOp27_removeMstTaskScreenType(&_monsterObjects2TasksList, p[1], p[2]); // mstOp27_removeMstTaskScreenType(&_mstTasksList3, p[1], p[2]); // mstOp27_removeMstTaskScreenType(&_mstTasksList4, p[1], p[2]); } break; case 41: { // 28 - increment_task_var assert(p[1] < kMaxLocals); ++t->localVars[p[1]]; } break; case 42: { // 29 - increment_global_var const int num = p[1]; assert(num < kMaxVars); ++_mstVars[num]; } break; case 43: { // 30 - increment_monster_var MonsterObject1 *m = 0; if (t->monster2) { m = t->monster2->monster1; } else { m = t->monster1; } if (m) { const int num = p[1]; assert(num < kMaxLocals); ++m->localVars[num]; } } break; case 44: { // 31 - decrement_task_var const int num = p[1]; assert(num < kMaxLocals); --t->localVars[num]; } break; case 45: { // 32 - decrement_global_var const int num = p[1]; assert(num < kMaxVars); --_mstVars[num]; } break; case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: { // 34 - arith_task_var_task_var assert(p[1] < kMaxLocals); assert(p[2] < kMaxLocals); arithOp(p[0] - 47, &t->localVars[p[1]], t->localVars[p[2]]); } break; case 57: case 58: case 59: case 60: case 61: case 62: case 63: case 64: case 65: case 66: { // 35 - arith_global_var_task_var assert(p[1] < kMaxVars); assert(p[2] < kMaxLocals); arithOp(p[0] - 57, &_mstVars[p[1]], t->localVars[p[2]]); if (p[1] == 31 && _mstVars[31] > 0) { _mstTickDelay = _mstVars[31]; } } break; case 67: case 68: case 69: case 70: case 71: case 72: case 73: case 74: case 75: case 76: { // 36 MonsterObject1 *m = 0; if (t->monster2) { m = t->monster2->monster1; } else { m = t->monster1; } if (m) { assert(p[1] < kMaxLocals); assert(p[2] < kMaxLocals); arithOp(p[0] - 67, &m->localVars[p[1]], t->localVars[p[2]]); } } break; case 77: case 78: case 79: case 80: case 81: case 82: case 83: case 84: case 85: case 86: { // 37 MonsterObject1 *m = 0; if (t->monster2) { m = t->monster2->monster1; } else { m = t->monster1; } if (m) { assert(p[1] < kMaxLocals); assert(p[2] < kMaxLocals); arithOp(p[0] - 77, &t->localVars[p[1]], m->localVars[p[2]]); } } break; case 87: case 88: case 89: case 90: case 91: case 92: case 93: case 94: case 95: case 96: { // 38 MonsterObject1 *m = 0; if (t->monster2) { m = t->monster2->monster1; } else { m = t->monster1; } if (m) { assert(p[1] < kMaxVars); assert(p[2] < kMaxLocals); arithOp(p[0] - 87, &_mstVars[p[1]], m->localVars[p[2]]); if (p[1] == 31 && _mstVars[31] > 0) { _mstTickDelay = _mstVars[31]; } } } break; case 97: case 98: case 99: case 100: case 101: case 102: case 103: case 104: case 105: case 106: { // 39 MonsterObject1 *m = 0; if (t->monster2) { m = t->monster2->monster1; } else { m = t->monster1; } if (m) { assert(p[1] < kMaxLocals); assert(p[2] < kMaxLocals); arithOp(p[0] - 97, &m->localVars[p[1]], m->localVars[p[2]]); } } break; case 107: case 108: case 109: case 110: case 111: case 112: case 113: case 114: case 115: case 116: { // 40 assert(p[1] < kMaxLocals); assert(p[2] < kMaxVars); arithOp(p[0] - 107, &t->localVars[p[1]], _mstVars[p[2]]); } break; case 117: case 118: case 119: case 120: case 121: case 122: case 123: case 124: case 125: case 126: { // 41 assert(p[1] < kMaxVars); assert(p[2] < kMaxVars); arithOp(p[0] - 117, &_mstVars[p[1]], _mstVars[p[2]]); if (p[1] == 31 && _mstVars[31] > 0) { _mstTickDelay = _mstVars[31]; } } break; case 127: case 128: case 129: case 130: case 131: case 132: case 133: case 134: case 135: case 136: { // 42 MonsterObject1 *m = 0; if (t->monster2) { m = t->monster2->monster1; } else { m = t->monster1; } if (m) { assert(p[1] < kMaxLocals); assert(p[2] < kMaxVars); arithOp(p[0] - 127, &m->localVars[p[1]], _mstVars[p[2]]); } } break; case 137: case 138: case 139: case 140: case 141: case 142: case 143: case 144: case 145: case 146: { // 43 const int num = p[2]; assert(p[1] < kMaxLocals); arithOp(p[0] - 137, &t->localVars[p[1]], getTaskOtherVar(num, t)); } break; case 147: case 148: case 149: case 150: case 151: case 152: case 153: case 154: case 155: case 156: { // 44 const int num = p[2]; assert(p[1] < kMaxVars); arithOp(p[0] - 147, &_mstVars[p[1]], getTaskOtherVar(num, t)); if (p[1] == 31 && _mstVars[31] > 0) { _mstTickDelay = _mstVars[31]; } } break; case 157: case 158: case 159: case 160: case 161: case 162: case 163: case 164: case 165: case 166: { // 45 MonsterObject1 *m = 0; if (t->monster2) { m = t->monster2->monster1; } else { m = t->monster1; } if (m) { const int num = p[2]; assert(p[1] < kMaxLocals); arithOp(p[0] - 157, &m->localVars[p[1]], getTaskOtherVar(num, t)); } } break; case 167: case 168: case 169: case 170: case 171: case 172: case 173: case 174: case 175: case 176: { // 46 const int16_t num = READ_LE_UINT16(p + 2); assert(p[1] < kMaxLocals); arithOp(p[0] - 167, &t->localVars[p[1]], num); } break; case 177: case 178: case 179: case 180: case 181: case 182: case 183: case 184: case 185: case 186: { // 47 const int16_t num = READ_LE_UINT16(p + 2); assert(p[1] < kMaxVars); arithOp(p[0] - 177, &_mstVars[p[1]], num); if (p[1] == 31 && _mstVars[31] > 0) { _mstTickDelay = _mstVars[31]; } } break; case 187: case 188: case 189: case 190: case 191: case 192: case 193: case 194: case 195: case 196: { // 48 - arith_monster_var_imm MonsterObject1 *m = 0; if (t->monster2) { m = t->monster2->monster1; } else { m = t->monster1; } if (m) { const int16_t num = READ_LE_UINT16(p + 2); assert(p[1] < kMaxLocals); arithOp(p[0] - 187, &m->localVars[p[1]], num); } } break; case 197: // 49 if (t->monster1) { const int num = READ_LE_UINT16(p + 2); const MstOp197Data *op197Data = &_res->_mstOp197Data[num]; const uint32_t mask = op197Data->maskVars; int a = getTaskVar(t, op197Data->unk0, (mask >> 16) & 15); // var1C int b = getTaskVar(t, op197Data->unk2, (mask >> 12) & 15); // x2 int c = getTaskVar(t, op197Data->unk4, (mask >> 8) & 15); // var14 int d = getTaskVar(t, op197Data->unk6, (mask >> 4) & 15); int e = getTaskVar(t, op197Data->unkE, mask & 15); const int screenNum = CLIP(e, -4, _res->_mstHdr.screensCount - 1); ret = mstOp49_setMovingBounds(a, b, c, d, screenNum, t, num); } break; case 198: { // 50 - call_task Task *child = findFreeTask(); if (child) { t->codeData = p + 4; memcpy(child, t, sizeof(Task)); t->child = child; const uint16_t num = READ_LE_UINT16(p + 2); const uint32_t codeData = _res->_mstUnk60[num]; assert(codeData != kNone); p = _res->_mstCodeData + codeData * 4; t->codeData = p; t->state &= ~2; p -= 4; } } break; case 199: // 51 - stop_monster mstTaskStopMonsterObject1(t); return 0; case 200: // 52 - stop_monster_action if (t->monster1 && t->monster1->action) { mstOp52(); return 1; } mstOp52(); break; case 201: { // 53 - start_monster_action const int num = READ_LE_UINT16(p + 2); mstOp53(&_res->_mstMonsterActionData[num]); } break; case 202: // 54 - continue_monster_action mstOp54(); break; case 203: // 55 - monster_attack // _mstCurrentMonster1 = t->monster1; if (t->monster1) { const int num = READ_LE_UINT16(p + 2); if (mstCollidesByFlags(t->monster1, _res->_mstOp240Data[num].flags)) { t->codeData = p + 4; mstTaskAttack(t, _res->_mstOp240Data[num].codeData, 0x10); t->state &= ~2; p = t->codeData - 4; } } break; case 204: // 56 - special_action ret = mstOp56_specialAction(t, p[1], READ_LE_UINT16(p + 2)); break; case 207: case 208: case 209: // 79 break; case 210: // 57 - add_worm { MonsterObject1 *m = t->monster1; mstOp57_addWormHoleSprite(m->xPos + (int8_t)p[2], m->yPos + (int8_t)p[3], m->o16->screenNum); } break; case 211: // 58 - add_lvl_object mstOp58_addLvlObject(t, READ_LE_UINT16(p + 2)); break; case 212: { // 59 LvlObject *o = 0; if (t->monster2) { o = t->monster2->o; } else if (t->monster1) { o = t->monster1->o16; } else { break; } assert(o); int xPos = o->xPos + o->posTable[6].x; int yPos = o->yPos + o->posTable[6].y; const uint16_t flags1 = o->flags1; if (flags1 & 0x10) { xPos -= (int8_t)p[2]; } else { xPos += (int8_t)p[2]; } if (flags1 & 0x20) { yPos -= (int8_t)p[3]; } else { yPos += (int8_t)p[3]; } int dirMask = 0; if ((t->monster1 && (t->monster1->monsterInfos[944] == 10 || t->monster1->monsterInfos[944] == 25)) || (t->monster2 && (t->monster2->monster2Info->type == 10 || t->monster2->monster2Info->type == 25))) { int dx = o->posTable[6].x - o->posTable[7].x; int dy = o->posTable[6].y - o->posTable[7].y; if (dx >= 8) { dirMask = 2; } else if (dx < -8) { dirMask = 8; } if (dy >= 8) { dirMask |= 4; } else if (dy < -8) { dirMask |= 1; } } else { dirMask = ((flags1 & 0x10) != 0) ? 8 : 0; } if (p[1] == 255) { int type = 0; switch (dirMask) { case 1: type = 6; break; case 3: type = 3; break; case 4: type = 7; break; case 6: type = 4; break; case 8: type = 5; break; case 9: type = 1; break; case 12: type = 2; break; } mstOp59_addShootSpecialPowers(xPos, yPos, o->screenNum, type, (o->flags2 + 1) & 0xDFFF); } else { int type = 0; switch (dirMask) { case 1: type = 6; break; case 3: type = 3; break; case 4: type = 7; break; case 6: type = 4; break; case 8: type = 5; break; case 9: type = 1; break; case 12: type = 2; break; } mstOp59_addShootFireball(xPos, yPos, o->screenNum, p[1], type, (o->flags2 + 1) & 0xDFFF); } } break; case 213: { // 60 - monster_set_action_direction LvlObject *o = 0; if (t->monster2) { o = t->monster2->o; } else if (t->monster1) { o = t->monster1->o16; } if (o) { o->actionKeyMask = getTaskVar(t, p[2], p[1] >> 4); o->directionKeyMask = getTaskVar(t, p[3], p[1] & 15); } } break; case 214: { // 61 - reset_monster_energy MonsterObject1 *m = t->monster1; if (m) { m->flagsA5 &= ~0xC0; m->localVars[7] = m->behaviorState->energy; } } break; case 215: { // 62 if (_m43Num3 != -1) { assert(_m43Num3 < _res->_mstHdr.monsterActionIndexDataCount); shuffleMstMonsterActionIndex(&_res->_mstMonsterActionIndexData[_m43Num3]); } _mstOp54Counter = 0; } break; case 217: { // 64 const int16_t num = READ_LE_UINT16(p + 2); if (_m43Num3 != num) { _m43Num3 = num; assert(num >= 0 && num < _res->_mstHdr.monsterActionIndexDataCount); shuffleMstMonsterActionIndex(&_res->_mstMonsterActionIndexData[num]); _mstOp54Counter = 0; } } break; case 218: { // 65 const int16_t num = READ_LE_UINT16(p + 2); if (num != _m43Num1) { _m43Num1 = num; _m43Num2 = num; assert(num >= 0 && num < _res->_mstHdr.monsterActionIndexDataCount); shuffleMstMonsterActionIndex(&_res->_mstMonsterActionIndexData[num]); } } break; case 220: case 221: case 222: case 223: case 224: case 225: { // 67 - add_monster const int num = READ_LE_UINT16(p + 2); MstOp223Data *m = &_res->_mstOp223Data[num]; const int mask = m->maskVars; // var8 int a = getTaskVar(t, m->indexVar1, (mask >> 16) & 15); // var1C int b = getTaskVar(t, m->indexVar2, (mask >> 12) & 15); // var20 int c = getTaskVar(t, m->indexVar3, (mask >> 8) & 15); // var14, vb int d = getTaskVar(t, m->indexVar4, (mask >> 4) & 15); int e = getTaskVar(t, m->indexVar5, mask & 15); if (a > b) { SWAP(a, b); } if (c > d) { SWAP(c, d); } LvlObject *o = 0; if (t->monster2) { o = t->monster2->o; } else if (t->monster1) { o = t->monster1->o16; } if (e <= -2 && o) { if (o->flags1 & 0x10) { const int x1 = a; const int x2 = b; a = o->xPos - x2; b = o->xPos - x1; } else { a += o->xPos; b += o->xPos; } c += o->yPos; d += o->yPos; if (e < -2) { a += o->posTable[6].x; b += o->posTable[6].x; c += o->posTable[6].y; d += o->posTable[6].y; } else { a += o->posTable[7].x; b += o->posTable[7].x; c += o->posTable[7].y; d += o->posTable[7].y; } e = o->screenNum; } e = CLIP(e, -1, _res->_mstHdr.screensCount - 1); if (p[0] == 224) { _mstOp67_type = m->unk8; _mstOp67_flags1 = m->unk9; _mstOp67_unk = m->unkC; _mstOp67_x1 = a; _mstOp67_x2 = b; _mstOp67_y1 = c; _mstOp67_y2 = d; _mstOp67_screenNum = e; break; } else if (p[0] == 225) { _mstOp68_type = m->unk8; _mstOp68_arg9 = m->unk9; _mstOp68_flags1 = m->unkC; _mstOp68_x1 = a; _mstOp68_x2 = b; _mstOp68_y1 = c; _mstOp68_y2 = d; _mstOp68_screenNum = e; break; } else { t->flags |= 0x80; if (p[0] == 222 || p[0] == 220) { if (e == -1) { if (a >= -_mstAndyScreenPosX && a <= 255 - _mstAndyScreenPosX) { break; } } else if (e == _currentScreen) { break; } } } mstOp67_addMonster(t, a, b, c, d, e, m->unk8, m->unk9, m->unkC, m->unkB, 0, m->unkE); } break; case 226: { // 68 - add_monster_group const int num = READ_LE_UINT16(p + 2); const MstOp226Data *m226Data = &_res->_mstOp226Data[num]; int xPos = _res->_mstPointOffsets[_currentScreen].xOffset; int yPos = _res->_mstPointOffsets[_currentScreen].yOffset; int countRight = 0; // var1C int countLeft = 0; // var8 int xOffset = m226Data->unk4 * 256; for (int i = 0; i < kMaxMonsterObjects1; ++i) { MonsterObject1 *m = &_monsterObjects1Table[i]; if (!m->m46) { continue; } if (m->monsterInfos[944] != _res->_mstMonsterInfos[m226Data->unk0 * kMonsterInfoDataSize + 944]) { continue; } if (!rect_contains(xPos - xOffset, yPos, xPos + xOffset + 256, yPos + 192, m->xMstPos, m->yMstPos)) { continue; } if (_mstAndyLevelPosX > m->xMstPos) { ++countLeft; } else { ++countRight; } } t->flags |= 0x80; const int total = countRight + countLeft; if (total >= m226Data->unk3) { break; } int vc = m226Data->unk3 - total; int countType1 = m226Data->unk1; if (countLeft >= countType1) { countType1 = 0; } else { countType1 -= countLeft; } int countType2 = m226Data->unk2; if (countRight >= countType2) { countType2 = 0; } else { countType2 -= countRight; } if (countType1 != 0) { if (_mstOp67_screenNum < 0) { if (_mstOp67_x2 >= -_mstAndyScreenPosX && _mstOp67_x1 <= 255 - _mstAndyScreenPosX) { countType1 = 0; } } else if (_mstOp67_screenNum == _currentScreen) { countType1 = 0; } } if (countType2 != 0) { if (_mstOp68_screenNum < 0) { if (_mstOp68_x2 >= -_mstAndyScreenPosX && _mstOp68_x1 <= 255 -_mstAndyScreenPosX) { countType2 = 0; } } else if (_mstOp68_screenNum == _currentScreen) { countType2 = 0; } } if (countType1 != 0 || countType2 != 0) { mstOp68_addMonsterGroup(t, _res->_mstMonsterInfos + m226Data->unk0 * kMonsterInfoDataSize, countType1, countType2, vc, m226Data->unk6); } } break; case 227: { // 69 - compare_vars const int num = READ_LE_UINT16(p + 2); assert(num < _res->_mstHdr.op227DataCount); const MstOp227Data *m = &_res->_mstOp227Data[num]; const int a = getTaskVar(t, m->indexVar1, m->maskVars & 15); const int b = getTaskVar(t, m->indexVar2, m->maskVars >> 4); if (compareOp(m->compare, a, b)) { assert(m->codeData < _res->_mstHdr.codeSize); p = _res->_mstCodeData + m->codeData * 4 - 4; } } break; case 228: { // 70 - compare_flags const int num = READ_LE_UINT16(p + 2); assert(num < _res->_mstHdr.op227DataCount); const MstOp227Data *m = &_res->_mstOp227Data[num]; const int a = getTaskFlag(t, m->indexVar1, m->maskVars & 15); const int b = getTaskFlag(t, m->indexVar2, m->maskVars >> 4); if (compareOp(m->compare, a, b)) { assert(m->codeData < _res->_mstHdr.codeSize); p = _res->_mstCodeData + m->codeData * 4 - 4; } } break; case 231: case 232: { // 71 - compare_flags_monster const int num = READ_LE_UINT16(p + 2); const MstOp234Data *m = &_res->_mstOp234Data[num]; const int a = getTaskFlag(t, m->indexVar1, m->maskVars & 15); const int b = getTaskFlag(t, m->indexVar2, m->maskVars >> 4); if (compareOp(m->compare, a, b)) { if (p[0] == 231) { LvlObject *o = 0; if (t->monster1) { if ((t->monster1->flagsA6 & 2) == 0) { o = t->monster1->o16; } } else if (t->monster2) { o = t->monster2->o; } if (o) { o->actionKeyMask = 0; o->directionKeyMask = 0; } t->arg2 = num; t->run = &Game::mstTask_mstOp231; ret = 1; } } else { if (p[0] == 232) { LvlObject *o = 0; if (t->monster1) { if ((t->monster1->flagsA6 & 2) == 0) { o = t->monster1->o16; } } else if (t->monster2) { o = t->monster2->o; } if (o) { o->actionKeyMask = 0; o->directionKeyMask = 0; } t->arg2 = num; t->run = &Game::mstTask_mstOp232; ret = 1; } } } break; case 233: case 234: { // 72 - compare_vars_monster const int num = READ_LE_UINT16(p + 2); const MstOp234Data *m = &_res->_mstOp234Data[num]; const int a = getTaskVar(t, m->indexVar1, m->maskVars & 15); const int b = getTaskVar(t, m->indexVar2, m->maskVars >> 4); if (compareOp(m->compare, a, b)) { if (p[0] == 233) { LvlObject *o = 0; if (t->monster1) { if ((t->monster1->flagsA6 & 2) == 0) { o = t->monster1->o16; } } else if (t->monster2) { o = t->monster2->o; } if (o) { o->actionKeyMask = 0; o->directionKeyMask = 0; } t->arg2 = num; t->run = &Game::mstTask_mstOp233; ret = 1; } } else { if (p[0] == 234) { LvlObject *o = 0; if (t->monster1) { if ((t->monster1->flagsA6 & 2) == 0) { o = t->monster1->o16; } } else if (t->monster2) { o = t->monster2->o; } if (o) { o->actionKeyMask = 0; o->directionKeyMask = 0; } t->arg2 = num; t->run = &Game::mstTask_mstOp234; ret = 1; } } } break; case 237: // 74 - remove_monster_task if (t->monster1) { if (!t->monster2) { mstRemoveMonsterObject1(t, &_monsterObjects1TasksList); return 1; } mstRemoveMonsterObject2(t, &_monsterObjects2TasksList); return 1; } else { if (t->monster2) { mstRemoveMonsterObject2(t, &_monsterObjects2TasksList); return 1; } } break; case 238: { // 75 - jmp const int i = READ_LE_UINT16(p + 2); const uint32_t codeData = _res->_mstUnk60[i]; assert(codeData != kNone); p = _res->_mstCodeData + codeData * 4; t->codeData = p; p -= 4; } break; case 239: { // 76 - create_task const int i = READ_LE_UINT16(p + 2); const uint32_t codeData = _res->_mstUnk60[i]; assert(codeData != kNone); createTask(_res->_mstCodeData + codeData * 4); } break; case 240: { // 77 - update_task const int num = READ_LE_UINT16(p + 2); MstOp240Data *m = &_res->_mstOp240Data[num]; const uint8_t *codeData = (m->codeData == kNone) ? 0 : (_res->_mstCodeData + m->codeData * 4); updateTask(t, m->flags, codeData); } break; case 242: // 78 - terminate debug(kDebug_MONSTER, "child %p monster1 %p monster2 %p", t->child, t->monster1, t->monster2); if (t->child) { Task *child = t->child; child->prevPtr = t->prevPtr; child->nextPtr = t->nextPtr; memcpy(t, child, sizeof(Task)); t->child = 0; t->state &= ~2; child->codeData = 0; MonsterObject1 *m = t->monster1; if (m) { m->flagsA5 &= ~0x70; if ((m->flagsA5 & 8) != 0 && !m->action) { mstTaskResetMonster1Direction(t); return 1; } } return 0; } else if (t->monster1) { MonsterObject1 *m = t->monster1; if (m->flagsA6 & 4) { return 1; } if ((m->flagsA5 & 0x80) == 0) { if ((m->flagsA5 & 8) == 0) { m->flags48 |= 8; if ((m->flagsA5 & 0x70) != 0) { m->flagsA5 &= ~0x70; switch (m->flagsA5 & 7) { case 1: case 2: { const uint32_t codeData = mstMonster1GetNextWalkCode(m); assert(codeData != kNone); resetTask(t, _res->_mstCodeData + codeData * 4); t->state &= ~2; p = t->codeData - 4; } break; case 5: return mstTaskInitMonster1Type1(t); case 6: return mstTaskInitMonster1Type2(t, 1); } } else { const uint32_t codeData = mstMonster1GetNextWalkCode(m); assert(codeData != kNone); resetTask(t, _res->_mstCodeData + codeData * 4); t->state &= ~2; const int counter = m->executeCounter; m->executeCounter = _executeMstLogicCounter; p = t->codeData - 4; if (m->executeCounter == counter) { if ((m->flagsA6 & 2) == 0) { if (m->o16) { m->o16->actionKeyMask = 0; m->o16->directionKeyMask = 0; } } ret = 1; } } } else { if (m->action) { mstMonster1ClearChasingMonster(m); } m->flagsA5 = (m->flagsA5 & ~0xF) | 6; return mstTaskInitMonster1Type2(t, 1); } } else if ((m->flagsA5 & 8) != 0) { m->flagsA5 &= ~8; const uint32_t codeData = m->behaviorState->codeData; if (codeData != kNone) { resetTask(t, _res->_mstCodeData + codeData * 4); return 0; } else { m->o16->actionKeyMask = 7; m->o16->directionKeyMask = 0; t->run = &Game::mstTask_idle; return 1; } } else { t->run = &Game::mstTask_idle; return 1; } } else if (t->monster2) { mstRemoveMonsterObject2(t, &_monsterObjects2TasksList); ret = 1; } else { if ((t->state & 1) != 0 && _mstVars[31] == 0) { _mstVars[31] = _mstTickDelay; } removeTask(&_tasksList, t); ret = 1; } break; default: warning("Unhandled opcode %d in mstTask_main", *p); break; } p += 4; if ((t->state & 2) != 0) { t->state &= ~2; p = t->codeData; } ++_runTaskOpcodesCount; if (_runTaskOpcodesCount >= 128) { // prevent infinite loop warning("Stopping task %p, counter %d", t, _runTaskOpcodesCount); break; } } while (ret == 0); if (t->codeData) { t->codeData = p; } return 1; } void Game::mstOp26_removeMstTaskScreen(Task **tasksList, int screenNum) { Task *current = *tasksList; while (current) { MonsterObject1 *m = current->monster1; Task *next = current->nextPtr; if (m && m->o16->screenNum == screenNum) { if (_mstActionNum != -1 && (m->flagsA5 & 8) != 0 && m->action) { mstMonster1ClearChasingMonster(m); } if (m->monsterInfos[946] & 4) { mstBoundingBoxClear(m, 0); mstBoundingBoxClear(m, 1); } mstMonster1ResetData(m); removeLvlObject2(m->o16); removeTask(tasksList, current); } else { MonsterObject2 *mo = current->monster2; if (mo && mo->o->screenNum == screenNum) { mo->monster2Info = 0; mo->o->dataPtr = 0; removeLvlObject2(mo->o); removeTask(tasksList, current); } } current = next; } } void Game::mstOp27_removeMstTaskScreenType(Task **tasksList, int screenNum, int type) { Task *current = *tasksList; while (current) { MonsterObject1 *m = current->monster1; Task *next = current->nextPtr; if (m && m->o16->screenNum == screenNum && (m->monsterInfos[944] & 0x7F) == type) { if (_mstActionNum != -1 && (m->flagsA5 & 8) != 0 && m->action) { mstMonster1ClearChasingMonster(m); } if (m->monsterInfos[946] & 4) { mstBoundingBoxClear(m, 0); mstBoundingBoxClear(m, 1); } mstMonster1ResetData(m); removeLvlObject2(m->o16); removeTask(tasksList, current); } else { MonsterObject2 *mo = current->monster2; if (mo && mo->o->screenNum == screenNum && (mo->monster2Info->type & 0x7F) == type) { mo->monster2Info = 0; mo->o->dataPtr = 0; removeLvlObject2(mo->o); removeTask(tasksList, current); } } current = next; } } int Game::mstOp49_setMovingBounds(int a, int b, int c, int d, int screen, Task *t, int num) { debug(kDebug_MONSTER, "mstOp49 %d %d %d %d %d %d", a, b, c, d, screen, num); MonsterObject1 *m = t->monster1; const MstOp197Data *op197Data = &_res->_mstOp197Data[num]; MstMovingBounds *m49 = &_res->_mstMovingBoundsData[op197Data->indexUnk49]; m->m49 = m49; m->indexUnk49Unk1 = op197Data->unkF; if (m->indexUnk49Unk1 < 0) { if (m49->indexDataCount == 0) { m->indexUnk49Unk1 = 0; } else { m->indexUnk49Unk1 = m49->indexData[_rnd.getMstNextNumber(m->rnd_m49)]; } } assert((uint32_t)m->indexUnk49Unk1 < m49->count1); m->m49Unk1 = &m49->data1[m->indexUnk49Unk1]; m->goalScreenNum = screen; if (a > b) { m->goalDistance_x1 = b; m->goalDistance_x2 = a; } else { m->goalDistance_x1 = a; m->goalDistance_x2 = b; } if (c > d) { m->goalDistance_y1 = d; m->goalDistance_y2 = c; } else { m->goalDistance_y1 = c; m->goalDistance_y2 = d; } switch (screen + 4) { case 1: { // 0xFD m->unkE4 = 255; const uint8_t _al = m->monsterInfos[946]; if (_al & 4) { t->run = &Game::mstTask_monsterWait10; } else if (_al & 2) { t->run = &Game::mstTask_monsterWait8; } else { t->run = &Game::mstTask_monsterWait6; } if (m->goalDistance_x2 <= 0) { m->goalScreenNum = kNoScreen; if (m->xMstPos < _mstAndyLevelPosX) { m->goalDistance_x1 = -m->goalDistance_x2; m->goalDistance_x2 = -m->goalDistance_x1; } } if ((_al & 2) != 0 && m->goalDistance_y2 <= 0) { m->goalScreenNum = kNoScreen; if (m->yMstPos < _mstAndyLevelPosY) { m->goalDistance_y1 = -m->goalDistance_y2; m->goalDistance_y2 = -m->goalDistance_y1; } } } break; case 0: { // 0xFC const uint8_t _al = m->unkF8; if (_al & 8) { m->goalDistance_x1 = -b; m->goalDistance_x2 = -a; } else if (_al & 2) { m->goalDistance_x1 = a; m->goalDistance_x2 = b; } else { m->goalDistance_x1 = 0; m->goalDistance_x2 = 0; } if (_al & 1) { m->goalDistance_y1 = -d; m->goalDistance_y2 = -c; } else if (_al & 4) { m->goalDistance_y1 = c; m->goalDistance_y2 = d; } else { m->goalDistance_y1 = 0; m->goalDistance_y2 = 0; } } // fall-through case 2: // 0xFE if (m->monsterInfos[946] & 4) { t->run = &Game::mstTask_monsterWait9; } else if (m->monsterInfos[946] & 2) { t->run = &Game::mstTask_monsterWait7; } else { t->run = &Game::mstTask_monsterWait5; } m->goalDistance_x1 += m->xMstPos; m->goalDistance_x2 += m->xMstPos; m->goalDistance_y1 += m->yMstPos; m->goalDistance_y2 += m->yMstPos; break; case 3: // 0xFF if (m->monsterInfos[946] & 4) { t->run = &Game::mstTask_monsterWait10; } else if (m->monsterInfos[946] & 2) { t->run = &Game::mstTask_monsterWait8; } else { t->run = &Game::mstTask_monsterWait6; } break; default: if (m->monsterInfos[946] & 4) { t->run = &Game::mstTask_monsterWait9; } else if (m->monsterInfos[946] & 2) { t->run = &Game::mstTask_monsterWait7; } else { t->run = &Game::mstTask_monsterWait5; } m->goalDistance_x1 += _res->_mstPointOffsets[screen].xOffset; m->goalDistance_x2 += _res->_mstPointOffsets[screen].xOffset; m->goalDistance_y1 += _res->_mstPointOffsets[screen].yOffset; m->goalDistance_y2 += _res->_mstPointOffsets[screen].yOffset; break; } m->goalPos_x1 = m->goalDistance_x1; m->goalPos_x2 = m->goalDistance_x2; m->goalPos_y1 = m->goalDistance_y1; m->goalPos_y2 = m->goalDistance_y2; m->walkBoxNum = 0xFF; m->unkC0 = -1; m->unkBC = -1; m->targetDirectionMask = 0xFF; const uint8_t *ptr = _res->_mstMonsterInfos + m->m49Unk1->offsetMonsterInfo; if ((ptr[2] & kDirectionKeyMaskVertical) == 0) { m->goalDistance_y1 = m->goalPos_y1 = m->goalDistance_y2 = m->goalPos_y2 = m->yMstPos; } if ((ptr[2] & kDirectionKeyMaskHorizontal) == 0) { m->goalDistance_x1 = m->goalPos_x1 = m->goalDistance_x2 = m->goalPos_x2 = m->xMstPos; } if (m->monsterInfos[946] & 4) { m->unkAB = 0xFF; m->targetLevelPos_x = -1; m->targetLevelPos_y = -1; mstBoundingBoxClear(m, 1); } uint8_t _dl = m->goalScreenNum; if (_dl != 0xFC && (m->flagsA5 & 8) != 0 && (t->flags & 0x20) != 0 && m->action) { if (t->run != &Game::mstTask_monsterWait6 && t->run != &Game::mstTask_monsterWait8 && t->run != &Game::mstTask_monsterWait10) { if ((_dl == 0xFE && m->o16->screenNum != _currentScreen) || (_dl != 0xFE && _dl != _currentScreen)) { if (m->monsterInfos[946] & 4) { mstBoundingBoxClear(m, 1); } return mstTaskStopMonsterObject1(t); } } else { int x1, x2; const int x = MIN(_mstAndyScreenPosX, 255); if (_mstAndyScreenPosX < 0) { x1 = x; x2 = x + 255; } else { x1 = -x; x2 = 255 - x; } const int y = MIN(_mstAndyScreenPosY, 191); int y1, y2; if (_mstAndyScreenPosY < 0) { y1 = y; y2 = y + 191; } else { y1 = -y; y2 = 191 - y; } int vd, vf; if (_dl == 0xFD && m->xMstPos < _mstAndyLevelPosX) { vd = -m->goalDistance_x2; vf = -m->goalDistance_x1; } else { vd = m->goalDistance_x1; vf = m->goalDistance_x2; } uint8_t _bl = m->monsterInfos[946] & 2; int va, vc; if (_bl != 0 && _dl == 0xFD && m->yMstPos < _mstAndyLevelPosY) { va = -m->goalDistance_y2; vc = -m->goalDistance_y1; } else { va = m->goalDistance_y1; vc = m->goalDistance_y2; } if (vd < x1 || vf > x2 || (_bl != 0 && (va < y1 || vc > y2))) { if ((m->monsterInfos[946] & 4) != 0) { mstBoundingBoxClear(m, 1); } return mstTaskStopMonsterObject1(t); } } } const uint8_t *p = _res->_mstMonsterInfos + m->m49Unk1->offsetMonsterInfo; if ((m->monsterInfos[946] & 4) != 0 && p[0xE] != 0 && m->bboxNum[0] == 0xFF) { const int x1 = m->xMstPos + (int8_t)p[0xC]; const int y1 = m->yMstPos + (int8_t)p[0xD]; const int x2 = x1 + p[0xE] - 1; const int y2 = y1 + p[0xF] - 1; if (mstBoundingBoxCollides2(m->monster1Index, x1, y1, x2, y2) != 0) { m->indexUnk49Unk1 = 0; m->m49Unk1 = &m->m49->data1[0]; m->unkAB = 0xFF; m->targetLevelPos_x = -1; m->targetLevelPos_y = -1; mstBoundingBoxClear(m, 1); if (p[0xE] != 0) { t->flags |= 0x80; mstTaskResetMonster1WalkPath(t); return 0; } } else { m->bboxNum[0] = mstBoundingBoxUpdate(0xFF, m->monster1Index, x1, y1, x2, y2); } } t->flags &= ~0x80; if (m->monsterInfos[946] & 2) { if (t->run == &Game::mstTask_monsterWait10) { mstMonster1UpdateGoalPosition(m); mstMonster1MoveTowardsGoal2(m); } else if (t->run == &Game::mstTask_monsterWait8) { mstMonster1UpdateGoalPosition(m); mstMonster1MoveTowardsGoal1(m); } else if (t->run == &Game::mstTask_monsterWait9) { mstMonster1MoveTowardsGoal2(m); } else { // &Game::mstTask_monsterWait7 mstMonster1MoveTowardsGoal1(m); } const MstMovingBoundsUnk1 *m49Unk1 = m->m49Unk1; uint8_t xDist, yDist; if (_mstLut1[m->goalDirectionMask] & 1) { xDist = m49Unk1->unkE; yDist = m49Unk1->unkF; } else { xDist = m49Unk1->unkC; yDist = m49Unk1->unkD; } if (_xMstPos2 < xDist && _yMstPos2 < yDist && !mstMonster1TestGoalDirection(m)) { } else { if (m->goalDirectionMask) { return (this->*(t->run))(t); } } } else { if (t->run == &Game::mstTask_monsterWait6) { if (m->goalScreenNum == 0xFD && m->xMstPos < _mstAndyLevelPosX) { m->goalPos_x1 = _mstAndyLevelPosX - m->goalDistance_x2; m->goalPos_x2 = _mstAndyLevelPosX - m->goalDistance_x1; } else { m->goalPos_x1 = _mstAndyLevelPosX + m->goalDistance_x1; m->goalPos_x2 = _mstAndyLevelPosX + m->goalDistance_x2; } } mstMonster1SetGoalHorizontal(m); bool flag = false; while (_xMstPos2 < m->m49Unk1->unkC) { if (--m->indexUnk49Unk1 >= 0) { m->m49Unk1 = &m->m49->data1[m->indexUnk49Unk1]; } else { flag = true; break; } } if (!flag) { if (m->goalDirectionMask) { return (this->*(t->run))(t); } } } if (m->monsterInfos[946] & 4) { mstBoundingBoxClear(m, 1); } t->flags |= 0x80; mstTaskResetMonster1WalkPath(t); return 0; } void Game::mstOp52() { if (_mstActionNum == -1) { return; } MstMonsterAction *m48 = &_res->_mstMonsterActionData[_mstActionNum]; for (int i = 0; i < m48->areaCount; ++i) { MstMonsterArea *m48Area = &m48->area[i]; const uint8_t num = m48Area->data->monster1Index; if (num != 0xFF) { assert(num < kMaxMonsterObjects1); MonsterObject1 *m = &_monsterObjects1Table[num]; mstMonster1ClearChasingMonster(m); if ((m->flagsA5 & 0x70) == 0) { assert(m->task->monster1 == m); Task *t = m->task; const int num = m->o16->flags0 & 0xFF; if (m->monsterInfos[num * 28] != 0) { if (t->run != &Game::mstTask_monsterWait1 && t->run != &Game::mstTask_monsterWait4 && t->run != &Game::mstTask_monsterWait2 && t->run != &Game::mstTask_monsterWait3 && t->run != &Game::mstTask_monsterWait5 && t->run != &Game::mstTask_monsterWait6 && t->run != &Game::mstTask_monsterWait7 && t->run != &Game::mstTask_monsterWait8 && t->run != &Game::mstTask_monsterWait9 && t->run != &Game::mstTask_monsterWait10) { m->flagsA5 = (m->flagsA5 & ~0xF) | 6; mstTaskInitMonster1Type2(m->task, 1); } else { m->o16->actionKeyMask = 0; m->o16->directionKeyMask = 0; t->run = &Game::mstTask_monsterWait11; } } else { m->flagsA5 = (m->flagsA5 & ~0xF) | 6; mstTaskInitMonster1Type2(m->task, 1); } } } } _mstActionNum = -1; } bool Game::mstHasMonsterInRange(const MstMonsterAction *m48, uint8_t flag) { for (int i = 0; i < 2; ++i) { for (uint32_t j = 0; j < m48->count[i]; ++j) { uint32_t a = (i ^ flag); // * 32; uint32_t n = m48->data1[i][j]; if (_mstCollisionTable[a][n].count < m48->data2[i][j]) { return false; } } } uint8_t _op54Data[kMaxMonsterObjects1]; memset(_op54Data, 0, sizeof(_op54Data)); int var24 = 0; //int var28 = 0; int vf = 0; for (int i = 0; i < m48->areaCount; ++i) { const MstMonsterArea *m12 = &m48->area[i]; assert(m12->count == 1); MstMonsterAreaAction *m12u4 = m12->data; if (m12->unk0 != 0) { uint8_t var1C = m12u4->unk18; if (var1C != 2) { vf = var1C; } l1: int var4C = vf; int var8 = m12u4->xPos; int vb = var8; // xPos int var4 = m12u4->yPos; int vg = var4; // yPos int va = vf ^ flag; if (va == 1) { vb = -vb; } debug(kDebug_MONSTER, "mstHasMonsterInRange (unk0!=0) count:%d %d %d [%d,%d] screen:%d", m12->count, vb, vg, _mstPosXmin, _mstPosXmax, m12u4->screenNum); if (vb >= _mstPosXmin && vb <= _mstPosXmax) { uint8_t var4D = _res->_mstMonsterInfos[m12u4->unk0 * kMonsterInfoDataSize + 946] & 2; if (var4D == 0 || (vg >= _mstPosYmin && vg <= _mstPosYmax)) { MstCollision *varC = &_mstCollisionTable[va][m12u4->unk0]; vb += _mstAndyLevelPosX; const int xLevelPos = vb; vg += _mstAndyLevelPosY; const int yLevelPos = vg; int minDistY = 0x1000000; int minDistX = 0x1000000; int var34 = -1; int var10 = varC->count; //MstCollision *var20 = varC; for (int j = 0; j < var10; ++j) { MonsterObject1 *m = varC->monster1[j]; if (_op54Data[m->monster1Index] == 0 && (m12u4->screenNum < 0 || m->o16->screenNum == m12u4->screenNum)) { int ve = yLevelPos - m->yMstPos; int va = ABS(ve); int vg = xLevelPos - m->xMstPos; int vc = ABS(vg); if (vc > m48->unk0 || va > m48->unk2) { continue; } if ((var8 || var4) && m->monsterInfos[944] != 10 && m->monsterInfos[944] != 16 && m->monsterInfos[944] != 9) { if (vg <= 0) { if (m->levelPosBounds_x1 > xLevelPos) { continue; } } else { if (m->levelPosBounds_x2 < xLevelPos) { continue; } } if (var4D != 0) { // vertical move if (ve <= 0) { if (m->levelPosBounds_y1 > yLevelPos) { continue; } } else { if (m->levelPosBounds_y2 < yLevelPos) { continue; } } } } if (vc <= minDistX && va <= minDistY) { minDistY = va; minDistX = vc; var34 = j; } } } if (var34 != -1) { const uint8_t num = varC->monster1[var34]->monster1Index; m12u4->monster1Index = num; _op54Data[num] = 1; debug(kDebug_MONSTER, "monster %d in range", num); ++var24; continue; } } } if (var1C != 2 || var4C == 1) { return false; } vf = 1; var4C = vf; goto l1; } //++var28; } //var28 = vf; for (int i = vf; i < m48->areaCount; ++i) { MstMonsterArea *m12 = &m48->area[i]; assert(m12->count == 1); MstMonsterAreaAction *m12u4 = m12->data; if (m12->unk0 == 0) { uint8_t var1C = m12u4->unk18; m12u4->monster1Index = 0xFF; int var4C = (var1C == 2) ? 0 : var1C; int vd = var4C; l2: int var4 = m12u4->xPos; int vb = var4; int var8 = m12u4->yPos; int vg = var8; int va = vd ^ flag; if (va == 1) { vb = -vb; } debug(kDebug_MONSTER, "mstHasMonsterInRange (unk0==0) count:%d %d %d [%d,%d] screen:%d", m12->count, vb, vg, _mstPosXmin, _mstPosXmax, m12u4->screenNum); if (vb >= _mstPosXmin && vb <= _mstPosXmax) { uint8_t var4D = _res->_mstMonsterInfos[m12u4->unk0 * kMonsterInfoDataSize + 946] & 2; if (var4D == 0 || (vg >= _mstPosYmin && vg <= _mstPosYmax)) { MstCollision *varC = &_mstCollisionTable[va][m12u4->unk0]; vb += _mstAndyLevelPosX; const int xLevelPos = vb; vg += _mstAndyLevelPosY; const int yLevelPos = vg; int minDistY = 0x1000000; int minDistX = 0x1000000; int var34 = -1; int var10 = varC->count; for (int j = 0; j < var10; ++j) { MonsterObject1 *m = varC->monster1[j]; if (_op54Data[m->monster1Index] == 0 && (m12u4->screenNum < 0 || m->o16->screenNum == m12u4->screenNum)) { int ve = yLevelPos - m->yMstPos; int va = ABS(ve); int vg = xLevelPos - m->xMstPos; int vc = ABS(vg); if (vc > m48->unk0 || va > m48->unk2) { continue; } if ((var8 || var4) && m->monsterInfos[944] != 10 && m->monsterInfos[944] != 16 && m->monsterInfos[944] != 9) { if (vg <= 0) { if (m->levelPosBounds_x1 > xLevelPos) { continue; } } else { if (m->levelPosBounds_x2 < xLevelPos) { continue; } } if (var4D != 0) { // vertical move if (ve <= 0) { if (m->levelPosBounds_y1 > yLevelPos) { continue; } } else { if (m->levelPosBounds_y2 < yLevelPos) { continue; } } } } if (vc <= minDistX && va <= minDistY) { minDistY = va; minDistX = vc; var34 = j; } } } if (var34 != -1) { const uint8_t num = varC->monster1[var34]->monster1Index; m12u4->monster1Index = num; _op54Data[num] = 1; debug(kDebug_MONSTER, "monster %d in range", num); ++var24; continue; } } } if (var1C == 2 && var4C != 1) { vd = 1; var4C = 1; goto l2; } } //++var28; } return var24 != 0; } void Game::mstOp53(MstMonsterAction *m) { if (_mstActionNum != -1) { return; } const int x = MIN(_mstAndyScreenPosX, 255); if (_mstAndyScreenPosX < 0) { _mstPosXmin = x; _mstPosXmax = 255 + x; } else { _mstPosXmin = -x; _mstPosXmax = 255 - x; } const int y = MIN(_mstAndyScreenPosY, 191); if (_mstAndyScreenPosY < 0) { _mstPosYmin = y; _mstPosYmax = 191 + y; } else { _mstPosYmin = -y; _mstPosYmax = 191 - y; } mstResetCollisionTable(); mstUpdateInRange(m); } void Game::mstOp54() { debug(kDebug_MONSTER, "mstOp54 %d %d %d", _mstActionNum, _m43Num2, _m43Num3); if (_mstActionNum != -1) { return; } MstMonsterActionIndex *m43 = 0; if (_mstFlags & 0x20000000) { if (_m43Num2 == -1) { return; } m43 = &_res->_mstMonsterActionIndexData[_m43Num2]; } else { if (_m43Num3 == -1) { return; } m43 = &_res->_mstMonsterActionIndexData[_m43Num3]; _m43Num2 = _m43Num1; } const int x = MIN(_mstAndyScreenPosX, 255); if (_mstAndyScreenPosX < 0) { _mstPosXmin = x; _mstPosXmax = 255 + x; } else { _mstPosXmin = -x; _mstPosXmax = 255 - x; } const int y = MIN(_mstAndyScreenPosY, 191); if (_mstAndyScreenPosY < 0) { _mstPosYmin = y; _mstPosYmax = 191 + y; } else { _mstPosYmin = -y; _mstPosYmax = 191 - y; } mstResetCollisionTable(); if (m43->dataCount == 0) { const uint32_t indexUnk48 = m43->indexUnk48[0]; MstMonsterAction *m48 = &_res->_mstMonsterActionData[indexUnk48]; mstUpdateInRange(m48); if (_mstActionNum == -1) { ++_mstOp54Counter; } if (_mstOp54Counter <= 16) { return; } _mstOp54Counter = 0; shuffleMstMonsterActionIndex(m43); } else { memset(_mstOp54Table, 0, sizeof(_mstOp54Table)); bool var4 = false; uint32_t i = 0; for (; i < m43->dataCount; ++i) { uint8_t num = m43->data[i]; if ((num & 0x80) == 0) { var4 = true; if (_mstOp54Table[num] == 0) { _mstOp54Table[num] = 1; const uint32_t indexUnk48 = m43->indexUnk48[num]; MstMonsterAction *m48 = &_res->_mstMonsterActionData[indexUnk48]; if (mstUpdateInRange(m48)) { break; } } } } if (_mstActionNum != -1) { assert(i < m43->dataCount); m43->data[i] |= 0x80; } else { if (var4) { ++_mstOp54Counter; if (_mstOp54Counter <= 16) { return; } } _mstOp54Counter = 0; if (m43->dataCount != 0) { shuffleMstMonsterActionIndex(m43); } } } } static uint8_t getLvlObjectFlag(uint8_t type, const LvlObject *o, const LvlObject *andyObject) { switch (type) { case 0: return 0; case 1: return 1; case 2: return (o->flags1 >> 4) & 1; case 3: return ~(o->flags1 >> 4) & 1; case 4: return (andyObject->flags1 >> 4) & 1; case 5: return ~(andyObject->flags1 >> 4) & 1; default: warning("getLvlObjectFlag unhandled type %d", type); break; } return 0; } int Game::mstOp56_specialAction(Task *t, int code, int num) { assert(num < _res->_mstHdr.op204DataCount); const MstOp204Data *op204Data = &_res->_mstOp204Data[num]; debug(kDebug_MONSTER, "mstOp56_specialAction code %d", code); switch (code) { case 0: if (!_specialAnimFlag && setAndySpecialAnimation(0x71) != 0) { _plasmaCannonFlags |= 1; if (_andyObject->spriteNum == 0) { _mstCurrentAnim = op204Data->arg0 & 0xFFFF; } else { _mstCurrentAnim = op204Data->arg0 >> 16; } LvlObject *o = 0; if (t->monster2) { o = t->monster2->o; } else if (t->monster1) { o = t->monster1->o16; } if (op204Data->arg3 != 6 && o) { LvlObject *tmpObject = t->monster1->o16; const uint8_t flags = getLvlObjectFlag(op204Data->arg3 & 255, tmpObject, _andyObject); _specialAnimMask = ((flags & 3) << 4) | (_specialAnimMask & ~0x30); // _specialAnimScreenNum = tmpObject->screenNum; _specialAnimLvlObject = tmpObject; _mstOriginPosX = op204Data->arg1 & 0xFFFF; _mstOriginPosY = op204Data->arg2 & 0xFFFF; } else { _specialAnimMask = merge_bits(_specialAnimMask, _andyObject->flags1, 0x30); // _specialAnimMask ^= (_specialAnimMask ^ _andyObject->flags1) & 0x30; // _specialAnimScreenNum = _andyObject->screenNum; _specialAnimLvlObject = _andyObject; _mstOriginPosX = _andyObject->posTable[3].x - _andyObject->posTable[6].x; _mstOriginPosY = _andyObject->posTable[3].y - _andyObject->posTable[6].y; } _specialAnimFlag = true; } if (_mstAndyRectNum != 0xFF) { _mstBoundingBoxesTable[_mstAndyRectNum].monster1Index = 0xFF; } break; case 1: if (!_specialAnimFlag) { break; } if (setAndySpecialAnimation(0x61) != 0) { _plasmaCannonFlags &= ~1; if (_andyObject->spriteNum == 0) { _mstCurrentAnim = op204Data->arg0 & 0xFFFF; } else { _mstCurrentAnim = op204Data->arg0 >> 16; } LvlObject *o = 0; if (t->monster2) { o = t->monster2->o; } else if (t->monster1) { o = t->monster1->o16; } if (op204Data->arg3 != 6 && o) { LvlObject *tmpObject = t->monster1->o16; const uint8_t flags = getLvlObjectFlag(op204Data->arg3 & 255, tmpObject, _andyObject); _specialAnimMask = ((flags & 3) << 4) | (_specialAnimMask & ~0x30); // _specialAnimScreenNum = tmpObject->screenNum; _specialAnimLvlObject = tmpObject; _mstOriginPosX = op204Data->arg1 & 0xFFFF; _mstOriginPosY = op204Data->arg2 & 0xFFFF; } else { _specialAnimMask = merge_bits(_specialAnimMask, _andyObject->flags1, 0x30); // _specialAnimMask ^= (_specialAnimMask ^ _andyObject->flags1) & 0x30; // _specialAnimScreenNum = _andyObject->screenNum; _specialAnimLvlObject = _andyObject; _mstOriginPosX = _andyObject->posTable[3].x - _andyObject->posTable[6].x; _mstOriginPosY = _andyObject->posTable[3].y - _andyObject->posTable[6].y; } _specialAnimFlag = false; } _mstAndyRectNum = mstBoundingBoxUpdate(_mstAndyRectNum, 0xFE, _mstAndyLevelPosX, _mstAndyLevelPosY, _mstAndyLevelPosX + _andyObject->width - 1, _mstAndyLevelPosY + _andyObject->height - 1) & 0xFF; break; case 2: { LvlObject *o = t->monster1->o16; const uint8_t flags = getLvlObjectFlag(op204Data->arg0 & 255, o, _andyObject); setAndySpecialAnimation(flags | 0x10); } break; case 3: setAndySpecialAnimation(0x12); break; case 4: setAndySpecialAnimation(0x80); break; case 5: // game over, restart level setAndySpecialAnimation(0xA4); break; case 6: setAndySpecialAnimation(0xA3); break; case 7: setAndySpecialAnimation(0x05); break; case 8: setAndySpecialAnimation(0xA1); break; case 9: setAndySpecialAnimation(0xA2); break; case 10: if (op204Data->arg0 == 1) { setShakeScreen(2, op204Data->arg1 & 255); } else if (op204Data->arg0 == 2) { setShakeScreen(1, op204Data->arg1 & 255); } else { setShakeScreen(3, op204Data->arg1 & 255); } break; case 11: { MonsterObject2 *m = t->monster2; const int type = op204Data->arg3; m->x1 = getTaskVar(t, op204Data->arg0, (type >> 0xC) & 15); m->y1 = getTaskVar(t, op204Data->arg1, (type >> 0x8) & 15); m->x2 = getTaskVar(t, op204Data->arg2, (type >> 0x4) & 15); m->y2 = getTaskVar(t, type >> 16 , type & 15); } break; case 12: { const int type1 = ((op204Data->arg3 >> 4) & 15); const int hint = getTaskVar(t, op204Data->arg0, type1); const int type2 = (op204Data->arg3 & 15); const int pause = getTaskVar(t, op204Data->arg1, type2); displayHintScreen(hint, pause); } break; case 13: case 14: case 22: case 23: case 24: case 25: { const int mask = op204Data->arg3; int xPos = getTaskVar(t, op204Data->arg0, (mask >> 8) & 15); int yPos = getTaskVar(t, op204Data->arg1, (mask >> 4) & 15); int screenNum = getTaskVar(t, op204Data->arg2, mask & 15); LvlObject *o = 0; if (t->monster2) { o = t->monster2->o; } else if (t->monster1) { o = t->monster1->o16; } if (screenNum < 0) { if (screenNum == -2) { if (!o) { break; } screenNum = o->screenNum; if (t->monster2) { xPos += t->monster2->xMstPos; yPos += t->monster2->yMstPos; } else if (t->monster1) { xPos += t->monster1->xMstPos; yPos += t->monster1->yMstPos; } else { break; } } else if (screenNum == -1) { xPos += _mstAndyLevelPosX; yPos += _mstAndyLevelPosY; screenNum = _currentScreen; } else { if (!o) { break; } xPos += o->posTable[6].x - o->posTable[7].x; yPos += o->posTable[6].y - o->posTable[7].y; if (t->monster2) { xPos += t->monster2->xMstPos; yPos += t->monster2->yMstPos; } else { assert(t->monster1); xPos += t->monster1->xMstPos; yPos += t->monster1->yMstPos; } } } else { if (screenNum >= _res->_mstHdr.screensCount) { screenNum = _res->_mstHdr.screensCount - 1; } xPos += _res->_mstPointOffsets[screenNum].xOffset; yPos += _res->_mstPointOffsets[screenNum].yOffset; } if (code == 13) { assert(o); xPos -= _res->_mstPointOffsets[screenNum].xOffset; xPos -= o->posTable[7].x; yPos -= _res->_mstPointOffsets[screenNum].yOffset; yPos -= o->posTable[7].y; o->screenNum = screenNum; o->xPos = xPos; o->yPos = yPos; setLvlObjectPosInScreenGrid(o, 7); if (t->monster2) { mstTaskSetMonster2ScreenPosition(t); } else { assert(t->monster1); mstTaskUpdateScreenPosition(t); } } else if (code == 14) { const int pos = mask >> 16; assert(pos < 8); xPos -= _res->_mstPointOffsets[screenNum].xOffset; xPos -= _andyObject->posTable[pos].x; yPos -= _res->_mstPointOffsets[screenNum].yOffset; yPos -= _andyObject->posTable[pos].y; _andyObject->screenNum = screenNum; _andyObject->xPos = xPos; _andyObject->yPos = yPos; updateLvlObjectScreen(_andyObject); mstUpdateRefPos(); mstUpdateMonstersRect(); } else if (code == 22) { updateScreenMaskBuffer(xPos, yPos, 1); } else if (code == 24) { updateScreenMaskBuffer(xPos, yPos, 2); } else if (code == 25) { updateScreenMaskBuffer(xPos, yPos, 3); } else { assert(code == 23); updateScreenMaskBuffer(xPos, yPos, 0); } } break; case 15: { _andyObject->anim = op204Data->arg0; _andyObject->frame = op204Data->arg1; LvlObject *o = 0; if (t->monster2) { o = t->monster2->o; } else if (t->monster1) { o = t->monster1->o16; } else { o = _andyObject; } const uint8_t flags = getLvlObjectFlag(op204Data->arg2 & 255, o, _andyObject); _andyObject->flags1 = ((flags & 3) << 4) | (_andyObject->flags1 & ~0x30); const int x3 = _andyObject->posTable[3].x; const int y3 = _andyObject->posTable[3].y; setupLvlObjectBitmap(_andyObject); _andyObject->xPos += (x3 - _andyObject->posTable[3].x); _andyObject->yPos += (y3 - _andyObject->posTable[3].y); updateLvlObjectScreen(o); mstUpdateRefPos(); mstUpdateMonstersRect(); } break; case 16: case 17: { LvlObject *o = _andyObject; if (code == 16) { if (t->monster2) { o = t->monster2->o; } else if (t->monster1) { o = t->monster1->o16; } } const int pos = op204Data->arg2; assert(pos < 8); const int xPos = o->xPos + o->posTable[pos].x; const int yPos = o->yPos + o->posTable[pos].y; const int type1 = (op204Data->arg3 >> 4) & 15; const int index1 = op204Data->arg0; setTaskVar(t, index1, type1, xPos); const int type2 = op204Data->arg3 & 15; const int index2 = op204Data->arg1; setTaskVar(t, index2, type2, yPos); } break; case 18: { _mstCurrentActionKeyMask = op204Data->arg0 & 255; } break; case 19: { _andyActionKeyMaskAnd = op204Data->arg0 & 255; _andyActionKeyMaskOr = op204Data->arg1 & 255; _andyDirectionKeyMaskAnd = op204Data->arg2 & 255; _andyDirectionKeyMaskOr = op204Data->arg3 & 255; } break; case 20: { _mstCurrentActionKeyMask = 0; t->monster1->flagsA6 |= 2; t->run = &Game::mstTask_idle; t->monster1->o16->actionKeyMask = _mstCurrentActionKeyMask; t->monster1->o16->directionKeyMask = _andyObject->directionKeyMask; return 1; } break; case 21: { t->monster1->flagsA6 &= ~2; t->monster1->o16->actionKeyMask = 0; t->monster1->o16->directionKeyMask = 0; } break; case 26: { int screenNum = op204Data->arg2; if (screenNum < -1 && !t->monster1) { break; } if (screenNum == -1) { screenNum = _currentScreen; } else if (screenNum < -1) { screenNum = t->monster1->o16->screenNum; } if (screenNum >= _res->_mstHdr.screensCount) { screenNum = _res->_mstHdr.screensCount - 1; } const int x = _res->_mstPointOffsets[screenNum].xOffset; const int y = _res->_mstPointOffsets[screenNum].yOffset; const int xOffset = op204Data->arg3 * 256; int count = 0; for (int i = 0; i < kMaxMonsterObjects1; ++i) { const MonsterObject1 *m = &_monsterObjects1Table[i]; if (!m->m46) { continue; } if (!rect_contains(x - xOffset, y, x + xOffset + 256, y + 192, m->xMstPos, m->yMstPos)) { continue; } const int num = op204Data->arg1; switch (op204Data->arg0) { case 0: if (m->m46 == &_res->_mstBehaviorData[num]) { ++count; } break; case 1: if (m->monsterInfos == &_res->_mstMonsterInfos[num * kMonsterInfoDataSize]) { ++count; } break; case 2: if (m->monsterInfos[944] == num) { ++count; } break; } } _mstOp56Counter = count; } break; case 27: { const int type = op204Data->arg3; int a = getTaskVar(t, op204Data->arg0, (type >> 0xC) & 15); int b = getTaskVar(t, op204Data->arg1, (type >> 0x8) & 15); int c = getTaskVar(t, op204Data->arg2, (type >> 0x4) & 15); int d = getTaskVar(t, type >> 16, type & 15); setScreenMaskRect(a - 16, b, a + 16, c, d); } break; case 28: // no-op break; case 29: { const uint8_t state = op204Data->arg1 & 255; const uint8_t screen = op204Data->arg0 & 255; _res->_screensState[screen].s0 = state; } break; case 30: ++_level->_checkpoint; break; default: warning("Unhandled opcode %d in mstOp56_specialAction", code); break; } return 0; } static void initWormHoleSprite(WormHoleSprite *s, const uint8_t *p) { s->screenNum = p[0]; s->initData1 = p[1]; s->xPos = p[2]; s->yPos = p[3]; s->initData4 = READ_LE_UINT32(p + 4); s->rect1_x1 = p[8]; s->rect1_y1 = p[9]; s->rect1_x2 = p[0xA]; s->rect1_y2 = p[0xB]; s->rect2_x1 = p[0xC]; s->rect2_y1 = p[0xD]; s->rect2_x2 = p[0xE]; s->rect2_y2 = p[0xF]; } void Game::mstOp57_addWormHoleSprite(int x, int y, int screenNum) { bool found = false; int spriteNum = 0; for (int i = 0; i < 6; ++i) { if (_wormHoleSpritesTable[i].screenNum == screenNum) { found = true; break; } if (_wormHoleSpritesTable[i].screenNum == 0xFF) { break; } ++spriteNum; } if (!found) { if (spriteNum == 6) { ++_wormHoleSpritesCount; if (_wormHoleSpritesCount >= spriteNum) { _wormHoleSpritesCount = 0; spriteNum = 0; } else { spriteNum = _wormHoleSpritesCount - 1; } } else { spriteNum = _wormHoleSpritesCount; } switch (_currentLevel) { case 2: initWormHoleSprite(&_wormHoleSpritesTable[spriteNum], _pwr1_spritesData + screenNum * 16); break; case 3: initWormHoleSprite(&_wormHoleSpritesTable[spriteNum], _isld_spritesData + screenNum * 16); break; case 4: initWormHoleSprite(&_wormHoleSpritesTable[spriteNum], _lava_spritesData + screenNum * 16); break; case 6: initWormHoleSprite(&_wormHoleSpritesTable[spriteNum], _lar1_spritesData + screenNum * 16); break; default: warning("mstOp57 unhandled level %d", _currentLevel); return; } } WormHoleSprite *boulderWormSprite = &_wormHoleSpritesTable[spriteNum]; const int dx = x - boulderWormSprite->xPos; const int dy = y + 15 - boulderWormSprite->yPos; spriteNum = _rnd._rndSeed & 3; if (spriteNum == 0) { spriteNum = 1; } static const uint8_t data[32] = { 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x04, 0x04, 0x04, 0x06, 0x06, 0x06, 0x08, 0x08, 0x08, 0x0A, 0x0A, 0x0A, 0x0C, 0x0C, 0x0C, 0x0E, 0x0E, 0x0E, 0x10, 0x10, 0x10, 0x12, 0x12, 0x12, 0x14, 0x14, }; const int pos = data[(dx >> 3) & 31]; const int num = dy >> 5; if ((boulderWormSprite->flags[num] & (3 << pos)) == 0) { if (addLvlObjectToList3(20)) { LvlObject *o = _lvlObjectsList3; o->flags0 = _andyObject->flags0; o->flags1 = _andyObject->flags1; o->screenNum = screenNum; o->flags2 = 0x1007; o->anim = 0; o->frame = 0; setupLvlObjectBitmap(o); setLvlObjectPosRelativeToPoint(o, 7, x, y); } boulderWormSprite->flags[num] |= (spriteNum << pos); } } void Game::mstOp58_addLvlObject(Task *t, int num) { const MstOp211Data *dat = &_res->_mstOp211Data[num]; const int mask = dat->maskVars; int xPos = getTaskVar(t, dat->indexVar1, (mask >> 8) & 15); int yPos = getTaskVar(t, dat->indexVar2, (mask >> 4) & 15); const uint8_t type = getTaskVar(t, dat->indexVar3, mask & 15); LvlObject *o = 0; if (t->monster2) { o = t->monster2->o; } else if (t->monster1) { o = t->monster1->o16; } uint8_t screen = type; if (type == 0xFB) { // -5 if (!o) { return; } xPos += o->xPos + o->posTable[6].x; yPos += o->yPos + o->posTable[6].y; screen = o->screenNum; } else if (type == 0xFE) { // -2 if (!o) { return; } xPos += o->xPos + o->posTable[7].x; yPos += o->yPos + o->posTable[7].y; screen = o->screenNum; } else if (type == 0xFF) { // -1 xPos += _mstAndyScreenPosX; yPos += _mstAndyScreenPosY; screen = _currentScreen; } const uint16_t flags = (dat->unk6 == -1 && o) ? o->flags2 : 0x3001; o = addLvlObject(2, xPos, yPos, screen, dat->unk8, dat->unk4, dat->unkB, flags, dat->unk9, dat->unkA); if (o) { o->dataPtr = 0; } } void Game::mstOp59_addShootSpecialPowers(int x, int y, int screenNum, int state, uint16_t flags) { LvlObject *o = addLvlObjectToList0(3); if (o) { o->dataPtr = _shootLvlObjectDataNextPtr; if (_shootLvlObjectDataNextPtr) { _shootLvlObjectDataNextPtr = _shootLvlObjectDataNextPtr->nextPtr; memset(o->dataPtr, 0, sizeof(ShootLvlObjectData)); } ShootLvlObjectData *s = (ShootLvlObjectData *)o->dataPtr; assert(s); o->callbackFuncPtr = &Game::lvlObjectSpecialPowersCallback; s->state = state; s->type = 0; s->counter = 17; s->dxPos = (int8_t)_specialPowersDxDyTable[state * 2]; s->dyPos = (int8_t)_specialPowersDxDyTable[state * 2 + 1]; static const uint8_t data[16] = { 0x0D, 0x00, 0x0C, 0x01, 0x0C, 0x03, 0x0C, 0x00, 0x0C, 0x02, 0x0D, 0x01, 0x0B, 0x00, 0x0B, 0x02, }; assert(state < 8); o->anim = data[state * 2]; o->flags1 = ((data[state * 2 + 1] & 3) << 4) | (o->flags1 & ~0x0030); o->frame = 0; o->flags2 = flags; o->screenNum = screenNum; setupLvlObjectBitmap(o); setLvlObjectPosRelativeToPoint(o, 6, x, y); } } void Game::mstOp59_addShootFireball(int x, int y, int screenNum, int type, int state, uint16_t flags) { LvlObject *o = addLvlObjectToList2(7); if (o) { o->dataPtr = _shootLvlObjectDataNextPtr; if (_shootLvlObjectDataNextPtr) { _shootLvlObjectDataNextPtr = _shootLvlObjectDataNextPtr->nextPtr; memset(o->dataPtr, 0, sizeof(ShootLvlObjectData)); } ShootLvlObjectData *s = (ShootLvlObjectData *)o->dataPtr; assert(s); s->state = state; static const uint8_t fireballDxDy1[16] = { 0x0A, 0x00, 0xF7, 0xFA, 0xF7, 0x06, 0x09, 0xFA, 0x09, 0x06, 0xF6, 0x00, 0x00, 0xF6, 0x00, 0x0A }; static const uint8_t fireballDxDy2[16] = { 0x0D, 0x00, 0xF5, 0xF9, 0xF5, 0x07, 0x0B, 0xF9, 0x0B, 0x07, 0xF3, 0x00, 0x00, 0xF3, 0x00, 0x0D }; static const uint8_t data1[16] = { 0x02, 0x00, 0x01, 0x01, 0x01, 0x03, 0x01, 0x00, 0x01, 0x02, 0x02, 0x01, 0x00, 0x00, 0x00, 0x02 }; static const uint8_t data2[16] = { 0x0D, 0x00, 0x0D, 0x01, 0x0D, 0x03, 0x0D, 0x00, 0x0D, 0x02, 0x0D, 0x01, 0x0D, 0x00, 0x0D, 0x02 }; assert(state < 8); const uint8_t *anim; if (type >= 7) { s->dxPos = (int8_t)fireballDxDy2[state * 2]; s->dyPos = (int8_t)fireballDxDy2[state * 2 + 1]; s->counter = 33; anim = &data2[state * 2]; } else { s->dxPos = (int8_t)fireballDxDy1[state * 2]; s->dyPos = (int8_t)fireballDxDy1[state * 2 + 1]; s->counter = 39; anim = &data1[state * 2]; } s->type = type; o->anim = anim[0]; o->screenNum = screenNum; o->flags1 = ((anim[1] & 3) << 4) | (o->flags1 & ~0x0030); o->flags2 = flags; o->frame = 0; setupLvlObjectBitmap(o); setLvlObjectPosRelativeToPoint(o, 6, x - s->dxPos, y - s->dyPos); } } void Game::mstTaskResetMonster1WalkPath(Task *t) { MonsterObject1 *m = t->monster1; t->run = &Game::mstTask_main; m->o16->actionKeyMask = 0; m->o16->directionKeyMask = 0; if ((m->flagsA5 & 4) != 0 && (m->flagsA5 & 0x28) == 0) { switch (m->flagsA5 & 7) { case 5: m->flagsA5 = (m->flagsA5 & ~6) | 1; if (!mstMonster1UpdateWalkPath(m)) { mstMonster1ResetWalkPath(m); } mstTaskSetNextWalkCode(t); break; case 6: m->flagsA5 &= ~7; if (!mstSetCurrentPos(m, m->xMstPos, m->yMstPos)) { m->flagsA5 |= 1; if (!mstMonster1UpdateWalkPath(m)) { mstMonster1ResetWalkPath(m); } const uint32_t indexWalkCode = m->walkNode->walkCodeStage1; if (indexWalkCode != kNone) { m->walkCode = &_res->_mstWalkCodeData[indexWalkCode]; } } else { m->flagsA5 |= 2; if (!mstMonster1UpdateWalkPath(m)) { mstMonster1ResetWalkPath(m); } } mstTaskSetNextWalkCode(t); break; } } else { m->flagsA5 &= ~4; mstMonster1UpdateWalkPath(m); } } bool Game::mstSetCurrentPos(MonsterObject1 *m, int x, int y) { _mstCurrentPosX = x; _mstCurrentPosY = y; const uint8_t *ptr = m->monsterInfos; const int32_t a = READ_LE_UINT32(ptr + 900); int x1 = _mstAndyLevelPosX - a; int x2 = _mstAndyLevelPosX + a; if (ptr[946] & 2) { // horizontal and vertical int y1 = _mstAndyLevelPosY - a; int y2 = _mstAndyLevelPosY + a; if (x > x1 && x < x2 && y > y1 && y < y2) { if (ABS(x - _mstAndyLevelPosX) > ABS(y - _mstAndyLevelPosY)) { if (x >= _mstAndyLevelPosX) { _mstCurrentPosX = x2; } else { _mstCurrentPosX = x1; } } else { if (y >= _mstAndyLevelPosY) { _mstCurrentPosY = y2; } else { _mstCurrentPosY = y1; } } return false; } const int32_t b = READ_LE_UINT32(ptr + 896); x1 -= b; x2 += b; y1 -= b; y2 += b; if (x < x1) { _mstCurrentPosX = x1; } else if (x > x2) { _mstCurrentPosX = x2; } if (y < y1) { _mstCurrentPosY = y1; } else if (y > y2) { _mstCurrentPosY = y2; } return (_mstCurrentPosX == x && _mstCurrentPosY == y); } // horizontal only if (x > x1 && x < x2) { if (x >= _mstAndyLevelPosX) { _mstCurrentPosX = x2; } else { _mstCurrentPosX = x1; } return false; } const int32_t b = READ_LE_UINT32(ptr + 896); x1 -= b; x2 += b; if (x < x1) { _mstCurrentPosX = x1; return false; } else if (x > x2) { _mstCurrentPosX = x2; return false; } return true; } void Game::mstMonster1SetGoalHorizontal(MonsterObject1 *m) { Task *t = m->task; t->flags &= ~0x80; int x = m->xMstPos; if (x < m->goalPos_x1) { _xMstPos1 = x = m->goalPos_x2; if ((m->flagsA5 & 2) != 0 && (m->flags48 & 8) != 0 && x > m->goalPosBounds_x2) { t->flags |= 0x80; x = m->goalPosBounds_x2; } if (x > m->levelPosBounds_x2) { t->flags |= 0x80; x = m->levelPosBounds_x2; } _xMstPos2 = x - m->xMstPos; m->goalDirectionMask = kDirectionKeyMaskRight; } else if (x > m->goalPos_x2) { _xMstPos1 = x = m->goalPos_x1; if ((m->flagsA5 & 2) != 0 && (m->flags48 & 8) != 0 && x < m->goalPosBounds_x1) { t->flags |= 0x80; x = m->goalPosBounds_x1; } if (x < m->levelPosBounds_x1) { t->flags |= 0x80; x = m->levelPosBounds_x1; } _xMstPos2 = m->xMstPos - x; m->goalDirectionMask = kDirectionKeyMaskLeft; } else { _xMstPos1 = x; _xMstPos2 = 0; m->goalDirectionMask = 0; } } void Game::mstResetCollisionTable() { const int count = MIN(_res->_mstHdr.infoMonster1Count, 32); for (int i = 0; i < 2; ++i) { for (int j = 0; j < count; ++j) { _mstCollisionTable[i][j].count = 0; } } for (int i = 0; i < kMaxMonsterObjects1; ++i) { MonsterObject1 *m = &_monsterObjects1Table[i]; if (!m->m46) { continue; } const uint8_t _bl = m->flagsA5; if ((_bl & 2) != 0 || ((_bl & 1) != 0 && ((m->walkNode->walkCodeStage1 == kNone && !m->walkCode) || (m->walkNode->walkCodeStage1 != kNone && m->walkCode == &_res->_mstWalkCodeData[m->walkNode->walkCodeStage1])))) { if ((_bl & 0xB0) != 0) { continue; } const int num = m->o16->flags0 & 0xFF; if (m->monsterInfos[num * 28] != 0) { continue; } if (m->task->run == &Game::mstTask_monsterWait4) { continue; } uint8_t _al = m->flagsA6; if (_al & 2) { continue; } assert(m->task->monster1 == m); if ((_al & 8) == 0 || m->monsterInfos[945] != 0) { const uint32_t offset = m->monsterInfos - _res->_mstMonsterInfos; assert(offset % kMonsterInfoDataSize == 0); const uint32_t num = offset / kMonsterInfoDataSize; assert(num < 32); const int dir = (m->xMstPos < _mstAndyLevelPosX) ? 1 : 0; const int count = _mstCollisionTable[dir][num].count; _mstCollisionTable[dir][num].monster1[count] = m; ++_mstCollisionTable[dir][num].count; } } } } // resume bytecode execution void Game::mstTaskRestart(Task *t) { t->run = &Game::mstTask_main; LvlObject *o = 0; if (t->monster1) { o = t->monster1->o16; } else if (t->monster2) { o = t->monster2->o; } if (o) { o->actionKeyMask = 0; o->directionKeyMask = 0; } } bool Game::mstMonster1CheckLevelBounds(MonsterObject1 *m, int x, int y, uint8_t dir) { if ((m->flagsA5 & 2) != 0 && (m->flags48 & 8) != 0 && !mstSetCurrentPos(m, x, y)) { return true; } if ((dir & kDirectionKeyMaskLeft) != 0 && x < m->levelPosBounds_x1) { return true; } if ((dir & kDirectionKeyMaskRight) != 0 && x > m->levelPosBounds_x2) { return true; } if ((dir & kDirectionKeyMaskUp) != 0 && y < m->levelPosBounds_y1) { return true; } if ((dir & kDirectionKeyMaskDown) != 0 && y > m->levelPosBounds_y2) { return true; } return false; } int Game::mstTaskResetMonster1Direction(Task *t) { MonsterObject1 *m = t->monster1; m->flagsA5 = (m->flagsA5 & ~0xF) | 6; return mstTaskInitMonster1Type2(t, 1); } int Game::mstTaskInitMonster1Type1(Task *t) { t->flags &= ~0x80; MonsterObject1 *m = t->monster1; m->flagsA5 = (m->flagsA5 & ~2) | 5; mstMonster1ResetWalkPath(m); const uint32_t indexWalkBox = m->walkNode->walkBox; const MstWalkBox *m34 = &_res->_mstWalkBoxData[indexWalkBox]; int y = 0; int x = 0; bool flag = false; if (m->monsterInfos[946] & 2) { m->unkC0 = -1; m->unkBC = -1; m->walkBoxNum = 0xFF; m->targetDirectionMask = 0xFF; y = m34->top; if (m->yMstPos < m34->top || m->yMstPos > m34->bottom) { flag = true; } } x = m34->left; if (m->monsterInfos[946] & 4) { m->unkAB = 0xFF; m->targetLevelPos_x = -1; m->targetLevelPos_y = -1; mstBoundingBoxClear(m, 1); } if (!flag && m->xMstPos >= x && m->xMstPos <= m34->right) { mstTaskResetMonster1WalkPath(t); return 0; } const uint32_t indexUnk36 = m->walkNode->movingBoundsIndex1; MstMovingBoundsIndex *m36 = &_res->_mstMovingBoundsIndexData[indexUnk36]; MstMovingBounds *m49 = &_res->_mstMovingBoundsData[m36->indexUnk49]; m->m49 = m49; m->indexUnk49Unk1 = m36->unk4; if (m->indexUnk49Unk1 < 0) { if (m49->indexDataCount == 0) { m->indexUnk49Unk1 = 0; } else { m->indexUnk49Unk1 = m49->indexData[_rnd.getMstNextNumber(m->rnd_m49)]; } } assert((uint32_t)m->indexUnk49Unk1 < m49->count1); m->m49Unk1 = &m49->data1[m->indexUnk49Unk1]; int xDelta = (m34->right - x) / 4; m->goalDistance_x1 = x + xDelta; m->goalDistance_x2 = m34->right - xDelta; if (xDelta != 0) { xDelta = _rnd.update() % xDelta; } m->goalDistance_x1 += xDelta; m->goalDistance_x2 -= xDelta; m->goalPos_x1 = m->goalDistance_x1; m->goalPos_x2 = m->goalDistance_x2; const uint8_t *ptr = _res->_mstMonsterInfos + m->m49Unk1->offsetMonsterInfo; if ((ptr[2] & kDirectionKeyMaskHorizontal) == 0) { m->goalDistance_x1 = m->goalPos_x1 = m->goalDistance_x2 = m->goalPos_x2 = m->xMstPos; } int vf; if (m->monsterInfos[946] & 2) { int yDelta = (m34->bottom - y) / 4; m->goalDistance_y1 = y + yDelta; m->goalDistance_y2 = m34->bottom - yDelta; if (yDelta != 0) { yDelta = _rnd.update() % yDelta; } m->goalDistance_y1 += yDelta; m->goalDistance_y2 -= yDelta; m->goalPos_y1 = m->goalDistance_y1; m->goalPos_y2 = m->goalDistance_y2; if ((ptr[2] & kDirectionKeyMaskVertical) == 0) { m->goalDistance_y1 = m->goalPos_y1 = m->goalDistance_y2 = m->goalPos_y2 = m->yMstPos; } if (m->monsterInfos[946] & 4) { mstMonster1MoveTowardsGoal2(m); } else { mstMonster1MoveTowardsGoal1(m); } vf = 1; const MstMovingBoundsUnk1 *m49Unk1 = m->m49Unk1; uint8_t xDist, yDist; if (_mstLut1[m->goalDirectionMask] & 1) { xDist = m49Unk1->unkE; yDist = m49Unk1->unkF; } else { xDist = m49Unk1->unkC; yDist = m49Unk1->unkD; } if (_xMstPos2 < xDist && _yMstPos2 < yDist && !mstMonster1TestGoalDirection(m)) { vf = 0; } } else { mstMonster1SetGoalHorizontal(m); vf = 1; while (_xMstPos2 < m->m49Unk1->unkC) { if (--m->indexUnk49Unk1 >= 0) { m->m49Unk1 = &m->m49->data1[m->indexUnk49Unk1]; } else { vf = 0; break; } } } if (_xMstPos2 <= 0 && ((m->monsterInfos[946] & 2) == 0 || _yMstPos2 <= 0)) { if (m->monsterInfos[946] & 4) { mstBoundingBoxClear(m, 1); } mstTaskResetMonster1WalkPath(t); return 0; } if (vf != 0 && ((_xMstPos2 >= m->m49->unk14 || ((m->monsterInfos[946] & 2) != 0 && _yMstPos2 >= m->m49->unk15)))) { const uint8_t *p = _res->_mstMonsterInfos + m->m49Unk1->offsetMonsterInfo; if ((m->monsterInfos[946] & 4) != 0 && p[0xE] != 0 && m->bboxNum[0] == 0xFF) { const int x1 = m->xMstPos + (int8_t)p[0xC]; const int y1 = m->yMstPos + (int8_t)p[0xD]; const int x2 = x1 + p[0xE] - 1; const int y2 = y1 + p[0xF] - 1; if (mstBoundingBoxCollides2(m->monster1Index, x1, y1, x2, y2) != 0) { m->indexUnk49Unk1 = 0; m->m49Unk1 = &m->m49->data1[0]; m->unkAB = 0xFF; m->targetLevelPos_x = -1; m->targetLevelPos_y = -1; mstBoundingBoxClear(m, 1); if (p[0xE] != 0) { t->flags |= 0x80; mstTaskResetMonster1WalkPath(t); return 0; } } else { m->bboxNum[0] = mstBoundingBoxUpdate(0xFF, m->monster1Index, x1, y1, x2, y2); } } if (_xMstPos2 >= m36->unk8 || ((m->monsterInfos[946] & 2) != 0 && _yMstPos2 >= m36->unk8)) { m->indexUnk49Unk1 = m->m49->count1 - 1; m->m49Unk1 = &m->m49->data1[m->indexUnk49Unk1]; if (m->monsterInfos[946] & 4) { m->unkAB = 0xFF; m->targetLevelPos_x = -1; m->targetLevelPos_y = -1; mstBoundingBoxClear(m, 1); } } if (m->monsterInfos[946] & 4) { t->run = &Game::mstTask_monsterWait9; } else if (m->monsterInfos[946] & 2) { t->run = &Game::mstTask_monsterWait7; } else { t->run = &Game::mstTask_monsterWait5; } return (this->*(t->run))(t); } else if (m->monsterInfos[946] & 4) { mstBoundingBoxClear(m, 1); } t->flags |= 0x80; mstTaskResetMonster1WalkPath(t); return -1; } int Game::mstTaskInitMonster1Type2(Task *t, int flag) { debug(kDebug_MONSTER, "mstTaskInitMonster1Type2 t %p flag %d", t, flag); t->flags &= ~0x80; MonsterObject1 *m = t->monster1; m->flagsA5 = (m->flagsA5 & ~1) | 6; mstMonster1ResetWalkPath(m); const uint32_t indexUnk36 = m->walkNode->movingBoundsIndex2; MstMovingBoundsIndex *m36 = &_res->_mstMovingBoundsIndexData[indexUnk36]; MstMovingBounds *m49 = &_res->_mstMovingBoundsData[m36->indexUnk49]; m->m49 = m49; if (flag != 0) { m->indexUnk49Unk1 = m49->count1 - 1; } else { m->indexUnk49Unk1 = m36->unk4; } if (m->indexUnk49Unk1 < 0) { if (m49->indexDataCount == 0) { m->indexUnk49Unk1 = 0; } else { m->indexUnk49Unk1 = m49->indexData[_rnd.getMstNextNumber(m->rnd_m49)]; } } assert((uint32_t)m->indexUnk49Unk1 < m49->count1); m->m49Unk1 = &m49->data1[m->indexUnk49Unk1]; m->goalScreenNum = 0xFD; m->unkC0 = -1; m->unkBC = -1; m->walkBoxNum = 0xFF; m->targetDirectionMask = 0xFF; if (mstSetCurrentPos(m, m->xMstPos, m->yMstPos)) { mstTaskResetMonster1WalkPath(t); return 0; } int vf; const uint8_t *p = m->monsterInfos; if (p[946] & 2) { m->unkE4 = 255; if (p[946] & 4) { m->unkAB = 0xFF; m->targetLevelPos_x = -1; m->targetLevelPos_y = -1; mstBoundingBoxClear(m, 1); } m->goalDistance_x1 = READ_LE_UINT32(m->monsterInfos + 900); m->goalDistance_x2 = m->goalDistance_x1 + READ_LE_UINT32(m->monsterInfos + 896); m->goalDistance_y1 = READ_LE_UINT32(m->monsterInfos + 900); m->goalDistance_y2 = m->goalDistance_y1 + READ_LE_UINT32(m->monsterInfos + 896); m->goalPos_x1 = m->goalDistance_x1; m->goalPos_x2 = m->goalDistance_x2; m->goalPos_y1 = m->goalDistance_y1; m->goalPos_y2 = m->goalDistance_y2; const uint8_t *ptr1 = _res->_mstMonsterInfos + m->m49Unk1->offsetMonsterInfo; if ((ptr1[2] & kDirectionKeyMaskVertical) == 0) { m->goalDistance_y1 = m->goalPos_y1 = m->goalDistance_y2 = m->goalPos_y2 = m->yMstPos; } if ((ptr1[2] & kDirectionKeyMaskHorizontal) == 0) { m->goalDistance_x1 = m->goalPos_x1 = m->goalDistance_x2 = m->goalPos_x2 = m->xMstPos; } if (p[946] & 4) { mstMonster1UpdateGoalPosition(m); mstMonster1MoveTowardsGoal2(m); } else { mstMonster1UpdateGoalPosition(m); mstMonster1MoveTowardsGoal1(m); } vf = 1; const MstMovingBoundsUnk1 *m49Unk1 = m->m49Unk1; uint8_t xDist, yDist; if (_mstLut1[m->goalDirectionMask] & 1) { xDist = m49Unk1->unkE; yDist = m49Unk1->unkF; } else { xDist = m49Unk1->unkC; yDist = m49Unk1->unkD; } if (_xMstPos2 < xDist && _yMstPos2 < yDist && !mstMonster1TestGoalDirection(m)) { vf = 0; } } else { int32_t ve = READ_LE_UINT32(p + 900); int32_t vc = READ_LE_UINT32(p + 896); int r = vc / 4; m->goalDistance_x1 = ve + r; m->goalDistance_x2 = vc + ve - r; if (r != 0) { r = _rnd.update() % r; } m->goalDistance_x1 += r; m->goalDistance_x2 -= r; if (m->goalScreenNum == 0xFD && m->xMstPos < _mstAndyLevelPosX) { m->goalPos_x1 = _mstAndyLevelPosX - m->goalDistance_x2; m->goalPos_x2 = _mstAndyLevelPosX - m->goalDistance_x1; } else { m->goalPos_x1 = _mstAndyLevelPosX + m->goalDistance_x1; m->goalPos_x2 = _mstAndyLevelPosX + m->goalDistance_x2; } mstMonster1SetGoalHorizontal(m); vf = 1; while (_xMstPos2 < m->m49Unk1->unkC) { if (--m->indexUnk49Unk1 >= 0) { m->m49Unk1 = &m->m49->data1[m->indexUnk49Unk1]; } else { vf = 0; break; } } } if (_xMstPos2 <= 0 && ((m->monsterInfos[946] & 2) == 0 || _yMstPos2 <= 0)) { if (m->monsterInfos[946] & 4) { mstBoundingBoxClear(m, 1); } mstTaskResetMonster1WalkPath(t); return 0; } if (vf) { if (_xMstPos2 >= m->m49->unk14 || ((m->monsterInfos[946] & 2) != 0 && _yMstPos2 >= m->m49->unk15)) { const uint8_t *p = _res->_mstMonsterInfos + m->m49Unk1->offsetMonsterInfo; if ((m->monsterInfos[946] & 4) != 0 && p[0xE] != 0 && m->bboxNum[0] == 0xFF) { const int x1 = m->xMstPos + (int8_t)p[0xC]; const int y1 = m->yMstPos + (int8_t)p[0xD]; const int x2 = x1 + p[0xE] - 1; const int y2 = y1 + p[0xF] - 1; if (mstBoundingBoxCollides2(m->monster1Index, x1, y1, x2, y2) != 0) { m->indexUnk49Unk1 = 0; m->m49Unk1 = &m->m49->data1[0]; m->unkAB = 0xFF; m->targetLevelPos_x = -1; m->targetLevelPos_y = -1; mstBoundingBoxClear(m, 1); if (p[0xE] != 0) { t->flags |= 0x80; mstTaskResetMonster1WalkPath(t); return 0; } } else { m->bboxNum[0] = mstBoundingBoxUpdate(0xFF, m->monster1Index, x1, y1, x2, y2); } } if (_xMstPos2 >= m36->unk8 || ((m->monsterInfos[946] & 2) != 0 && _yMstPos2 >= m36->unk8)) { m->indexUnk49Unk1 = m->m49->count1 - 1; m->m49Unk1 = &m->m49->data1[m->indexUnk49Unk1]; if (m->monsterInfos[946] & 4) { m->unkAB = 0xFF; m->targetLevelPos_x = -1; m->targetLevelPos_y = -1; mstBoundingBoxClear(m, 1); } } if (m->monsterInfos[946] & 4) { t->run = &Game::mstTask_monsterWait10; } else if (m->monsterInfos[946] & 2) { t->run = &Game::mstTask_monsterWait8; } else { t->run = &Game::mstTask_monsterWait6; } return (this->*(t->run))(t); } } if (m->monsterInfos[946] & 4) { mstBoundingBoxClear(m, 1); } t->flags |= 0x80; mstTaskResetMonster1WalkPath(t); return -1; } void Game::mstOp67_addMonster(Task *currentTask, int x1, int x2, int y1, int y2, int screen, int type, int o_flags1, int o_flags2, int arg1C, int arg20, int arg24) { debug(kDebug_MONSTER, "mstOp67_addMonster pos %d,%d,%d,%d %d %d 0x%x 0x%x %d %d %d", y1, x1, y2, x2, screen, type, o_flags1, o_flags2, arg1C, arg20, arg24); if (o_flags2 == 0xFFFF) { LvlObject *o = 0; if (currentTask->monster1) { o = currentTask->monster1->o16; } else if (currentTask->monster2) { o = currentTask->monster2->o; } o_flags2 = o ? o->flags2 : 0x3001; } if (y1 != y2) { y1 += _rnd.update() % ABS(y2 - y1 + 1); } if (x1 != x2) { x1 += _rnd.update() % ABS(x2 - x1 + 1); } int objScreen = (screen < 0) ? _currentScreen : screen; LvlObject *o = 0; MonsterObject2 *mo = 0; MonsterObject1 *m = 0; if (arg1C != -128) { if (_mstVars[30] > kMaxMonsterObjects1) { _mstVars[30] = kMaxMonsterObjects1; } int count = 0; for (int i = 0; i < kMaxMonsterObjects1; ++i) { if (_monsterObjects1Table[i].m46) { ++count; } } if (count >= _mstVars[30]) { return; } if (arg1C < 0) { const MstBehaviorIndex *m42 = &_res->_mstBehaviorIndexData[arg24]; if (m42->dataCount == 0) { arg1C = m42->data[0]; } else { arg1C = m42->data[_rnd.update() % m42->dataCount]; } } for (int i = 0; i < kMaxMonsterObjects1; ++i) { if (!_monsterObjects1Table[i].m46) { m = &_monsterObjects1Table[i]; break; } } if (!m) { warning("mstOp67 unable to find a free MonsterObject1"); return; } memset(m->localVars, 0, sizeof(m->localVars)); m->flags48 = 0x1C; m->flagsA5 = 0; m->collideDistance = -1; m->walkCode = 0; m->flagsA6 = 0; assert((uint32_t)arg1C < _res->_mstBehaviorIndexData[arg24].count1); const uint32_t indexBehavior = _res->_mstBehaviorIndexData[arg24].behavior[arg1C]; MstBehavior *m46 = &_res->_mstBehaviorData[indexBehavior]; m->m46 = m46; assert((uint32_t)arg20 < m46->count); MstBehaviorState *behaviorState = &m46->data[arg20]; m->behaviorState = behaviorState; m->monsterInfos = _res->_mstMonsterInfos + behaviorState->indexMonsterInfo * kMonsterInfoDataSize; m->localVars[7] = behaviorState->energy; if (behaviorState->indexUnk51 == kNone) { m->flags48 &= ~4; } const uint8_t *ptr = m->monsterInfos; o = addLvlObject(ptr[945], x1, y1, objScreen, ptr[944], behaviorState->anim, o_flags1, o_flags2, 0, 0); if (!o) { mstMonster1ResetData(m); return; } m->o16 = o; if (_currentLevel == kLvl_lar2 && m->monsterInfos[944] == 26) { // Master of Darkness m->o20 = addLvlObject(ptr[945], x1, y1, objScreen, ptr[944], behaviorState->anim + 1, o_flags1, 0x3001, 0, 0); if (!m->o20) { warning("mstOp67 failed to addLvlObject in kLvl_lar2"); mstMonster1ResetData(m); return; } if (screen < 0) { m->o20->xPos += _mstAndyScreenPosX; m->o20->yPos += _mstAndyScreenPosY; } m->o20->dataPtr = 0; setLvlObjectPosRelativeToObject(m->o16, 6, m->o20, 6); } m->o_flags2 = o_flags2 & 0xFFFF; m->lut4Index = _mstLut5[o_flags2 & 0x1F]; o->dataPtr = m; } else { for (int i = 0; i < kMaxMonsterObjects2; ++i) { if (!_monsterObjects2Table[i].monster2Info) { mo = &_monsterObjects2Table[i]; break; } } if (!mo) { warning("mstOp67 no free monster2"); return; } assert(arg24 >= 0 && arg24 < _res->_mstHdr.infoMonster2Count); mo->monster2Info = &_res->_mstInfoMonster2Data[arg24]; if (currentTask->monster1) { mo->monster1 = currentTask->monster1; } else if (currentTask->monster2) { mo->monster1 = currentTask->monster2->monster1; } else { mo->monster1 = 0; } mo->flags24 = 0; uint8_t _cl = mo->monster2Info->type; uint16_t anim = mo->monster2Info->anim; o = addLvlObject((_cl >> 7) & 1, x1, y1, objScreen, (_cl & 0x7F), anim, o_flags1, o_flags2, 0, 0); if (!o) { mo->monster2Info = 0; if (mo->o) { mo->o->dataPtr = 0; } return; } mo->o = o; o->dataPtr = mo; } if (screen < 0) { o->xPos += _mstAndyScreenPosX; o->yPos += _mstAndyScreenPosY; } setLvlObjectPosInScreenGrid(o, 7); if (mo) { Task *t = findFreeTask(); if (!t) { mo->monster2Info = 0; if (mo->o) { mo->o->dataPtr = 0; } removeLvlObject2(o); return; } resetTask(t, kUndefinedMonsterByteCode); t->monster2 = mo; t->monster1 = 0; mo->task = t; t->codeData = 0; appendTask(&_monsterObjects2TasksList, t); t->codeData = kUndefinedMonsterByteCode; mstTaskSetMonster2ScreenPosition(t); const uint32_t codeData = mo->monster2Info->codeData; assert(codeData != kNone); resetTask(t, _res->_mstCodeData + codeData * 4); if (_currentLevel == kLvl_fort && mo->monster2Info->type == 27) { mstMonster2InitFirefly(mo); } } else { Task *t = findFreeTask(); if (!t) { mstMonster1ResetData(m); removeLvlObject2(o); return; } resetTask(t, kUndefinedMonsterByteCode); t->monster1 = m; t->monster2 = 0; m->task = t; t->codeData = 0; appendTask(&_monsterObjects1TasksList, t); t->codeData = kUndefinedMonsterByteCode; _rnd.resetMst(m->rnd_m35); _rnd.resetMst(m->rnd_m49); m->levelPosBounds_x1 = -1; MstBehaviorState *behaviorState = m->behaviorState; m->walkNode = _res->_mstWalkPathData[behaviorState->walkPath].data; if (m->monsterInfos[946] & 4) { m->bboxNum[0] = 0xFF; m->bboxNum[1] = 0xFF; } mstTaskUpdateScreenPosition(t); switch (type) { case 1: mstTaskInitMonster1Type1(t); assert(t->run != &Game::mstTask_main || (t->codeData && t->codeData != kUndefinedMonsterByteCode)); break; case 2: if (m) { m->flagsA6 |= 1; } mstTaskInitMonster1Type2(t, 0); assert(t->run != &Game::mstTask_main || (t->codeData && t->codeData != kUndefinedMonsterByteCode)); break; default: m->flagsA5 = 1; if (!mstMonster1UpdateWalkPath(m)) { mstMonster1ResetWalkPath(m); } mstTaskSetNextWalkCode(t); break; } } currentTask->flags &= ~0x80; } void Game::mstOp68_addMonsterGroup(Task *t, const uint8_t *p, int a, int b, int c, int d) { const MstBehaviorIndex *m42 = &_res->_mstBehaviorIndexData[d]; struct { int m42Index; int m46Index; } data[16]; int count = 0; for (uint32_t i = 0; i < m42->count1; ++i) { MstBehavior *m46 = &_res->_mstBehaviorData[m42->behavior[i]]; for (uint32_t j = 0; j < m46->count; ++j) { MstBehaviorState *behaviorState = &m46->data[j]; uint32_t indexMonsterInfo = p - _res->_mstMonsterInfos; assert((indexMonsterInfo % kMonsterInfoDataSize) == 0); indexMonsterInfo /= kMonsterInfoDataSize; if (behaviorState->indexMonsterInfo == indexMonsterInfo) { assert(count < 16); data[count].m42Index = i; data[count].m46Index = j; ++count; } } } if (count == 0) { return; } int j = 0; for (int i = 0; i < a; ++i) { mstOp67_addMonster(t, _mstOp67_x1, _mstOp67_x2, _mstOp67_y1, _mstOp67_y2, _mstOp67_screenNum, _mstOp67_type, _mstOp67_flags1, _mstOp68_flags1, data[j].m42Index, data[j].m46Index, d); if (--c == 0) { return; } if (++j >= count) { j = 0; } } for (int i = 0; i < b; ++i) { mstOp67_addMonster(t, _mstOp68_x1, _mstOp68_x2, _mstOp68_y1, _mstOp68_y2, _mstOp68_screenNum, _mstOp68_type, _mstOp68_arg9, _mstOp68_flags1, data[j].m42Index, data[j].m46Index, d); if (--c == 0) { return; } if (++j >= count) { j = 0; } } } int Game::mstTask_wait1(Task *t) { debug(kDebug_MONSTER, "mstTask_wait1 t %p count %d", t, t->arg1); --t->arg1; if (t->arg1 == 0) { t->run = &Game::mstTask_main; return 0; } return 1; } int Game::mstTask_wait2(Task *t) { debug(kDebug_MONSTER, "mstTask_wait2 t %p count %d", t, t->arg1); --t->arg1; if (t->arg1 == 0) { mstTaskRestart(t); return 0; } return 1; } int Game::mstTask_wait3(Task *t) { debug(kDebug_MONSTER, "mstTask_wait3 t %p type %d flag %d", t, t->arg1, t->arg2); if (getTaskFlag(t, t->arg2, t->arg1) == 0) { return 1; } mstTaskRestart(t); return 0; } int Game::mstTask_idle(Task *t) { debug(kDebug_MONSTER, "mstTask_idle t %p", t); return 1; } int Game::mstTask_mstOp231(Task *t) { debug(kDebug_MONSTER, "mstTask_mstOp231 t %p", t); const MstOp234Data *m = &_res->_mstOp234Data[t->arg2]; const int a = getTaskFlag(t, m->indexVar1, m->maskVars & 15); const int b = getTaskFlag(t, m->indexVar2, m->maskVars >> 4); if (!compareOp(m->compare, a, b)) { mstTaskRestart(t); return 0; } return 1; } int Game::mstTask_mstOp232(Task *t) { warning("mstTask_mstOp232 unimplemented"); t->run = &Game::mstTask_main; return 0; } int Game::mstTask_mstOp233(Task *t) { debug(kDebug_MONSTER, "mstTask_mstOp233 t %p", t); const MstOp234Data *m = &_res->_mstOp234Data[t->arg2]; const int a = getTaskVar(t, m->indexVar1, m->maskVars & 15); const int b = getTaskVar(t, m->indexVar2, m->maskVars >> 4); if (!compareOp(m->compare, a, b)) { mstTaskRestart(t); return 0; } return 1; } int Game::mstTask_mstOp234(Task *t) { debug(kDebug_MONSTER, "mstTask_mstOp234 t %p", t); const MstOp234Data *m = &_res->_mstOp234Data[t->arg2]; const int a = getTaskVar(t, m->indexVar1, m->maskVars & 15); const int b = getTaskVar(t, m->indexVar2, m->maskVars >> 4); if (compareOp(m->compare, a, b)) { mstTaskRestart(t); return 0; } return 1; } int Game::mstTask_monsterWait1(Task *t) { debug(kDebug_MONSTER, "mstTask_monsterWait1 t %p", t); if (t->arg1 == 0) { mstMonster1UpdateWalkPath(t->monster1); mstTaskRestart(t); return 0; } --t->arg1; return 1; } int Game::mstTask_monsterWait2(Task *t) { debug(kDebug_MONSTER, "mstTask_monsterWait2 t %p", t); MonsterObject1 *m = t->monster1; const uint16_t flags0 = m->o16->flags0; if ((flags0 & 0x100) != 0 && (flags0 & 0xFF) == m->o_flags0) { mstMonster1UpdateWalkPath(t->monster1); mstTaskRestart(t); return 0; } return 1; } int Game::mstTask_monsterWait3(Task *t) { debug(kDebug_MONSTER, "mstTask_monsterWait3 t %p", t); MonsterObject1 *m = t->monster1; const uint16_t flags0 = m->o16->flags0; if ((flags0 & 0xFF) == m->o_flags0) { if (t->arg1 > 0) { t->run = &Game::mstTask_monsterWait1; } else { t->run = &Game::mstTask_monsterWait2; } return (this->*(t->run))(t); } return 1; } int Game::mstTask_monsterWait4(Task *t) { debug(kDebug_MONSTER, "mstTask_monsterWait4 t %p", t); MonsterObject1 *m = t->monster1; const uint32_t offset = m->monsterInfos - _res->_mstMonsterInfos; assert(offset % kMonsterInfoDataSize == 0); const uint32_t num = offset / kMonsterInfoDataSize; if (t->arg2 != num) { mstMonster1UpdateWalkPath(m); mstTaskRestart(t); return 0; } return 1; } int Game::mstTask_monsterWait5(Task *t) { debug(kDebug_MONSTER, "mstTask_monsterWait5 t %p", t); // horizontal move MonsterObject1 *m = t->monster1; mstMonster1SetGoalHorizontal(m); if (_xMstPos2 < m->m49Unk1->unk8) { if (_xMstPos2 > 0) { while (--m->indexUnk49Unk1 >= 0) { m->m49Unk1 = &m->m49->data1[m->indexUnk49Unk1]; if (_xMstPos2 >= m->m49Unk1->unkC) { goto set_am; } } } return mstTaskStopMonster1(t, m); } set_am: const uint8_t *ptr = _res->_mstMonsterInfos + m->m49Unk1->offsetMonsterInfo; mstLvlObjectSetActionDirection(m->o16, ptr, ptr[3], m->goalDirectionMask); return 1; } int Game::mstTask_monsterWait6(Task *t) { debug(kDebug_MONSTER, "mstTask_monsterWait6 t %p", t); MonsterObject1 *m = t->monster1; // horizontal move with goal if (m->goalScreenNum == 0xFD && m->xMstPos < _mstAndyLevelPosX) { m->goalPos_x1 = _mstAndyLevelPosX - m->goalDistance_x2; m->goalPos_x2 = _mstAndyLevelPosX - m->goalDistance_x1; } else { m->goalPos_x1 = _mstAndyLevelPosX + m->goalDistance_x1; m->goalPos_x2 = _mstAndyLevelPosX + m->goalDistance_x2; } mstMonster1SetGoalHorizontal(m); if (_xMstPos2 < m->m49Unk1->unk8) { if (_xMstPos2 > 0) { while (--m->indexUnk49Unk1 >= 0) { m->m49Unk1 = &m->m49->data1[m->indexUnk49Unk1]; if (_xMstPos2 >= m->m49Unk1->unkC) { goto set_am; } } } return mstTaskStopMonster1(t, m); } set_am: const uint8_t *ptr = _res->_mstMonsterInfos + m->m49Unk1->offsetMonsterInfo; mstLvlObjectSetActionDirection(m->o16, ptr, ptr[3], m->goalDirectionMask); return 1; } int Game::mstTask_monsterWait7(Task *t) { debug(kDebug_MONSTER, "mstTask_monsterWait7 t %p", t); MonsterObject1 *m = t->monster1; mstMonster1MoveTowardsGoal1(m); return mstTaskUpdatePositionActionDirection(t, m); } int Game::mstTask_monsterWait8(Task *t) { debug(kDebug_MONSTER, "mstTask_monsterWait8 t %p", t); MonsterObject1 *m = t->monster1; mstMonster1UpdateGoalPosition(m); mstMonster1MoveTowardsGoal1(m); return mstTaskUpdatePositionActionDirection(t, m); } int Game::mstTask_monsterWait9(Task *t) { debug(kDebug_MONSTER, "mstTask_monsterWait9 t %p", t); MonsterObject1 *m = t->monster1; mstMonster1MoveTowardsGoal2(m); return mstTaskUpdatePositionActionDirection(t, m); } int Game::mstTask_monsterWait10(Task *t) { debug(kDebug_MONSTER, "mstTask_monsterWait10 t %p", t); MonsterObject1 *m = t->monster1; mstMonster1UpdateGoalPosition(m); mstMonster1MoveTowardsGoal2(m); return mstTaskUpdatePositionActionDirection(t, m); } int Game::mstTask_monsterWait11(Task *t) { debug(kDebug_MONSTER, "mstTask_monsterWait11 t %p", t); MonsterObject1 *m = t->monster1; const int num = m->o16->flags0 & 0xFF; if (m->monsterInfos[num * 28] == 0) { mstTaskResetMonster1Direction(t); } return 1; }
[ "maxim.lopez.02@gmail.com" ]
maxim.lopez.02@gmail.com
44147b89c9cee4d1d6642e62ce54bcf4971ffd3c
7e5aae473ced56a9cff5cb9cda8527d1c5b0ce79
/Module_3/dragons/src/main.cpp
df75d08c5bc34f7d940d4a9f2ebe9ced025369cb
[]
no_license
linroad123/AaltoCpp2021
985f37951ecb7ff7117bdd5a3aacab30ab9d9437
1ddff42b00c3c148d6514096357eac2852d477d5
refs/heads/master
2023-08-29T14:22:31.513281
2021-10-08T12:13:25
2021-10-08T12:13:25
414,680,160
0
0
null
null
null
null
UTF-8
C++
false
false
3,631
cpp
#include <vector> #include <list> #include <iostream> #include <cstdlib> #include "dragon.hpp" #include "fantasy_dragon.hpp" #include "magic_dragon.hpp" #include "dragon_cave.hpp" std::list<Treasure> CreateRandomTreasures(size_t count) { std::list<Treasure> treasures; // Jewellery std::vector<std::string> j_names = {"Ruby", "Gold bar"}; // Wisdom std::vector<std::string> w_names = {"Scroll of infinite wisdom", "Sun Tzu's Art of War"}; // Potions std::vector<std::string> p_names = {"Cough syrup", "Liquid luck", "Stoneskin potion"}; std::vector<std::vector<std::string>> names = {j_names, w_names, p_names}; for(size_t i = 0; i < count; i++) { size_t type = rand()%3; Treasure t = {((TreasureType)type), names[type][rand()%(names[type].size())]}; treasures.push_back(t); } return treasures; } std::list<Food> CreateRandomFood(size_t count) { std::list<Food> food; // PeopleFood std::vector<std::string> pf_names = {"Tenderloin steak", "Carnivore pizza"}; // People std::vector<std::string> p_names = {"Raimo", "Petteri"}; // Herbs std::vector<std::string> h_names = {"Arrowroot", "Bay leaves"}; std::vector<std::vector<std::string>> names = {pf_names, p_names, h_names}; for(size_t i = 0; i < count; i++) { size_t type = rand()%3; Food f = {((FoodType)type), names[type][rand()%(names[type].size())]}; food.push_back(f); } return food; } int main() { using namespace std; // Seed the random srand(time(NULL)); // Random treasures list<Treasure> treasures = CreateRandomTreasures(rand()%10); // Random food list<Food> food = CreateRandomFood(rand()%10); cout << "*** Creating a set of different Dragons.." << endl; MagicDragon* mdragon = new MagicDragon("Puff", 976, 20); mdragon->Hoard(treasures); FantasyDragon* fdragon = new FantasyDragon("Bahamut", (rand()%10000)+900, (rand()%10)+1); fdragon->Hoard(treasures); cout << "*** END OF READ ***" << endl; cout << "*** The dragons need beachside housing, creating a new DragonCave.." << endl; DragonCave* cave = new DragonCave(); cout << "*** Accommodating the different Dragons to the cave.." << endl; cave->Accommodate(mdragon); cave->Accommodate(fdragon); cout << "*** Printing out the cave dwellers.." << endl; cout << *cave; cout << "*** END OF READ ***" << endl; cout << "*** Evicting a few dragons for various reasons.." << endl; size_t m_evicted = 0; if(rand()%2) { m_evicted = 1; cout << mdragon->GetName() << " the MagicDragon broke the cave's rules and was evicted.." << endl; cave->Evict(mdragon->GetName()); delete mdragon; } if(rand()%2) { m_evicted = 1; cout << fdragon->GetName() << " the FantasyDragon broke the cave's rules and was evicted.." << endl; cave->Evict(fdragon->GetName()); delete fdragon; } if(rand()%2 && !m_evicted) { cout << fdragon->GetName() << " the FantasyDragon framed " << mdragon->GetName() << " and the MagicDragon who was evicted.." << endl; cave->Evict(mdragon->GetName()); delete mdragon; } cout << "*** END OF READ ***" << endl; cout << "*** Printing out the new list of cave dwellers.." << endl; cout << *cave; cout << "*** END OF READ ***" << endl; cout << "*** The cave spontaneously collapsed, killing all the remaining cave dwellers (deleted).." << endl; delete cave; cout << "*** Test complete, exiting.." << endl; return 0; }
[ "linroad@hotmail.com" ]
linroad@hotmail.com
df059699b9e9ec764308e615ee2eb9948a0638b5
328d2b96ad70e360f49c49e7e8399d0c1ad5d96c
/src/systems/StateSwitchButtonSystem.h
b38c237ebd89da588629c005691090f369000543
[]
no_license
vasylbo/ecs_lemmings
b60096927e4673d2b6852ee7c383aaabc66592fb
15b81f86bf911f466d24f44b550fbd0e2c17196a
refs/heads/master
2021-01-19T03:02:02.391392
2017-04-01T21:51:20
2017-04-01T21:51:20
51,010,782
2
2
null
2017-04-01T21:21:11
2016-02-03T15:55:26
C++
UTF-8
C++
false
false
823
h
// // Created by Vasyl. // #ifndef LEMMINGS_BUTTONSYSTEM_H #define LEMMINGS_BUTTONSYSTEM_H #include <entityx/System.h> #include "../components/StateSwitchButtonC.h" class StateSwitchButtonSystem : public entityx::System<StateSwitchButtonSystem>, public entityx::Receiver<StateSwitchButtonSystem> { public: StateSwitchButtonSystem(){}; virtual void configure(entityx::EntityManager &entities, entityx::EventManager &events) override; virtual void update(entityx::EntityManager &entities, entityx::EventManager &events, entityx::TimeDelta dt) override; virtual ~StateSwitchButtonSystem(); private: entityx::EventManager *_events; entityx::EntityManager *_entities; }; #endif //LEMMINGS_BUTTONSYSTEM_H
[ "vasylbo@gmail.com" ]
vasylbo@gmail.com
c3c80d49da67557e4f30808f39bf80c4dbef722e
359741b841c2bdee997891b36363128bb8522964
/win9x/subwnd/skbdwnd.h
9f36f8c62dfac652c1bfb0b8a839980560a4d8b2
[ "BSD-3-Clause" ]
permissive
libretro/xmil-libretro
4686acb22c521b2414eb9524748d58f2fa5e7f5c
4cb1e4eaab37321904144d1f1a23b2830268e8df
refs/heads/master
2022-05-01T12:04:23.292954
2022-04-14T16:39:02
2022-04-14T16:39:02
244,228,236
3
9
BSD-3-Clause
2022-04-14T06:05:46
2020-03-01T21:42:20
C
SHIFT_JIS
C++
false
false
1,696
h
/** * @file skbdwnd.h * @brief ソフトウェア キーボード クラスの宣言およびインターフェイスの定義をします */ #pragma once #if defined(SUPPORT_SOFTKBD) #include "dd2.h" #include "subwnd.h" /** * @brief ソフトウェア キーボード */ class CSoftKeyboardWnd : public CSubWndBase { public: static CSoftKeyboardWnd* GetInstance(); static void Initialize(); static void Deinitialize(); CSoftKeyboardWnd(); virtual ~CSoftKeyboardWnd(); void Create(); void OnIdle(); protected: virtual LRESULT WindowProc(UINT nMsg, WPARAM wParam, LPARAM lParam); void OnDestroy(); void OnPaint(); private: static CSoftKeyboardWnd sm_instance; //!< インスタンス DD2Surface m_dd2; int m_nWidth; int m_nHeight; void OnDraw(BOOL redraw); static void skpalcnv(CMNPAL *dst, const RGB32 *src, UINT pals, UINT bpp); }; /** * インスタンスを返す * @return インスタンス */ inline CSoftKeyboardWnd* CSoftKeyboardWnd::GetInstance() { return &sm_instance; } #define skbdwin_initialize CSoftKeyboardWnd::Initialize #define skbdwin_deinitialize CSoftKeyboardWnd::Deinitialize #define skbdwin_create CSoftKeyboardWnd::GetInstance()->Create #define skbdwin_destroy CSoftKeyboardWnd::GetInstance()->DestroyWindow #define skbdwin_gethwnd CSoftKeyboardWnd::GetInstance()->GetSafeHwnd #define skbdwin_process CSoftKeyboardWnd::GetInstance()->OnIdle void skbdwin_readini(); void skbdwin_writeini(); #else #define skbdwin_initialize() #define skbdwin_deinitialize() #define skbdwin_create() #define skbdwin_destroy() #define skbdwin_gethwnd() (NULL) #define skbdwin_process() #define skbdwin_readini() #define skbdwin_writeini() #endif
[ "yui@afe8d728-ceca-4c4c-a723-f8cfeda826dd" ]
yui@afe8d728-ceca-4c4c-a723-f8cfeda826dd
f2ac358a2f8fe7761eeea8b19e847c6f577be315
6cffc6e9f6b4c434262a096a6847e315f76c0bc9
/atcoder/abc214/C.cpp
25430213b441bbf8a45d21f70127342a1d7de491
[]
no_license
nishgpt/competitive_programming
c0cd15663d36dec6132bd615cdd3e0b4ba0c64cd
38535bb57081f2065dfe4170c9c87a981163fb0f
refs/heads/master
2023-08-16T14:19:42.746680
2021-10-22T04:29:33
2021-10-22T04:29:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,826
cpp
/* Author : Nishant Gupta 2.0 */ #include<bits/stdc++.h> using namespace std; #define LL long long int #define getcx getchar_unlocked #define X first #define Y second #define PB push_back #define MP make_pair #define MAX 100005 #define LOG_MAX 20 #define MOD 1000000007 #define INF 0x3f3f3f3f #define INFL (LL(1e18)) #define chk(a) cerr << endl << #a << " : " << a << endl #define chk2(a,b) cerr << endl << #a << " : " << a << "\t" << #b << " : " << b << endl #define chk3(a,b,c) cerr << endl << #a << " : " << a << "\t" << #b << " : " << b << "\t" << #c << " : " << c << endl #define chk4(a,b,c,d) cerr << endl << #a << " : " << a << "\t" << #b << " : " << b << "\t" << #c << " : " << c << "\t" << #d << " : " << d << endl #define rep(i, a, n) for(i=a;i<n;i++) #define rev(i, a, n) for(i=a;i>=n;i--) #define in(x) scanf("%d", &x) #define inl(x) scanf("%lld", &x) #define in2(x, y) scanf("%d %d", &x, &y) #define inl2(x, y) scanf("%lld %lld", &x, &y) #define MSV(A,a) memset(A, a, sizeof(A)) #define rep_itr(itr, c) for(itr = (c).begin(); itr != (c).end(); itr++) #define finish(x) {cout<<x<<'\n'; return;} typedef pair<int, int> pi; typedef pair<LL, LL> pl; const char en = '\n'; void solve() { int n; in(n); vector<int> s(n), t(n); int i, j; rep(i, 0, n) in(s[i]); rep(i, 0, n) in(t[i]); rep(i, 0, n) { int curr = t[i]; if (i == 0) { curr = min(curr, t[n - 1] + s[n - 1]); } else curr = min(curr, t[i - 1] + s[i - 1]); t[i] = curr; } rep(i, 0, n) { int curr = t[i]; if (i == 0) { curr = min(curr, t[n - 1] + s[n - 1]); } else curr = min(curr, t[i - 1] + s[i - 1]); t[i] = curr; cout << curr << en; } } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int t = 1; // cin>>t; while (t--) { solve(); } return 0; }
[ "nishant141077@gmail.com" ]
nishant141077@gmail.com
f58273eebab81f61cb853ccfe7316810375a60a2
1f6578736dac2b14aee2b790867c09980a72f697
/src/ClientPatch/HookMgr.cpp
b2a9957bf3a8e4b811f00b4567c81e412cc5e3f7
[]
no_license
gabrielbsx/wyd-spirit-destiny
c1899c76f55a10595b9c9ce8333d210e9b8c7654
ba0fb01cf511c7a54ae302c5dc9d8456f6b44ca4
refs/heads/master
2023-09-06T05:38:59.671009
2021-03-28T22:29:38
2021-03-28T22:29:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,400
cpp
#include "pch.h" #include "HookMgr.h" #include <exception> #include "pe_Hook.h" #include "Naked.h" void HookMgr::ChangeWindowName() { const char* windowName = "Spirit Destiny - https://spirit-destiny.com/"; PEHook::SETDWORD((int)windowName, 0x05494FC + 1); } void HookMgr::FixAutoTradeName() { PEHook::SETDWORD(0xE4 + 1, 0x0483C0C + 2); PEHook::SETDWORD(0xE4 + 1, 0x0483BF8 + 2); PEHook::SETDWORD(0xE4 + 1, 0x048544A + 2); PEHook::SETDWORD(0xE4 + 1, 0x0483EBE + 4); } void HookMgr::SetVersion(int version) { PEHook::SETDWORD(version, 0x04864D2 + 6); PEHook::SETDWORD(version, 0x04B38BC + 6); } void HookMgr::SmallPatches() { // Remove strdef checksum PEHook::SETBYTE(0xEB, 0x053A8D2); } bool HookMgr::InitializeConstants() { try { HookMgr::ChangeWindowName(); HookMgr::SmallPatches(); HookMgr::FixAutoTradeName(); HookMgr::SetVersion(778); return true; } catch (const std::exception&) { return false; } } bool HookMgr::InitializeNakeds() { try { PEHook::JMP_NEAR(0x0421356, Naked::NKD_ItemPrice_FormatDecimal); //Fix mage macro PEHook::JMP_NEAR(0x0497286, Naked::NKD_ChangeMacroRoute, 3); PEHook::JMP_NEAR(0x05165C5, Naked::NKD_MAutoAttackVerifyIsMage, 1); // Item Description Hook PEHook::JMP_NEAR(0x0419576, &Naked::NKD_ItemDescription, 4); // Fix macro mage PEHook::JE_NEAR(0x04974C7, &Naked::NKD_FixMageMacro); PEHook::JE_NEAR(0x04974D7, &Naked::NKD_FixMageMacro); // Add new commands PEHook::JMP_NEAR(0x04675F4, &Naked::NKD_NewCommands); // Minor hooks PEHook::JMP_NEAR(0x0417751, &Naked::NKD_ItemDesc_ChangePriceString_01, 1); PEHook::JMP_NEAR(0x041CDC7, &Naked::NKD_ItemDesc_ChangePriceString_02, 5); // Get packet class ptr PEHook::JMP_NEAR(0x0495AEE, &Naked::NKD_GetPacketClassPtr, 1); // Hook to intercept add/read message PEHook::JGE_NEAR(0x04252D6, &Naked::NKD_ReadMessage); PEHook::JMP_NEAR(0x0425887, &Naked::NKD_AddMessage, 2); /* Separar Item no Shift + Click*/ PEHook::JMP_NEAR(0x4205FC, Naked::NKD_AddAmountItem, 4); // Fix Serverlist online users PEHook::FillWithNop(0x04B2D05, 8); PEHook::FillWithNop(0x046DDC6, 11); //teste height PEHook::FillWithNop(0x054DA76, 5); PEHook::SETBYTE( 0, 0x054DAE9 + 1); return true; } catch (const std::exception&) { return false; } }
[ "patrikveloso@gmail.com" ]
patrikveloso@gmail.com
db14a84cf3819da14d03c362537e7efb7e9da5f0
a1ffe4ed85bfaa2f67325ed324b119ed9a1b93c1
/CookieSync.cpp
4c948c020fd44bb7b5152b84e10aa5c77e2d84e4
[ "Apache-2.0" ]
permissive
lhn200835/watchman
ff621b1b95f5e127a2970e19daf4cc3921d6216b
ce4f339e15a7aa13d37b6128835db19d7a6d85a2
refs/heads/master
2020-06-11T03:04:21.997001
2016-12-08T20:43:49
2016-12-08T20:48:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,823
cpp
/* Copyright 2012-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "watchman.h" namespace watchman { CookieSync::CookieSync(const w_string& dir) { setCookieDir(dir); } void CookieSync::setCookieDir(const w_string& dir) { cookieDir_ = dir; char hostname[256]; gethostname(hostname, sizeof(hostname)); hostname[sizeof(hostname) - 1] = '\0'; cookiePrefix_ = w_string::printf( "%.*s%c" WATCHMAN_COOKIE_PREFIX "%s-%d-", int(cookieDir_.size()), cookieDir_.data(), WATCHMAN_DIR_SEP, hostname, int(getpid())); } bool CookieSync::syncToNow(std::chrono::milliseconds timeout) { Cookie cookie; int errcode = 0; auto cookie_lock = std::unique_lock<std::mutex>(cookie.mutex); /* generate a cookie name: cookie prefix + id */ auto path_str = w_string::printf( "%.*s%" PRIu32, int(cookiePrefix_.size()), cookiePrefix_.data(), serial_++); /* insert our cookie in the map */ { auto wlock = cookies_.wlock(); auto& map = *wlock; map[path_str] = &cookie; } /* compute deadline */ auto deadline = std::chrono::system_clock::now() + timeout; /* touch the file */ auto file = w_stm_open( path_str.c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC, 0700); if (!file) { errcode = errno; w_log( W_LOG_ERR, "sync_to_now: creat(%s) failed: %s\n", path_str.c_str(), strerror(errcode)); goto out; } file.reset(); w_log(W_LOG_DBG, "sync_to_now [%s] waiting\n", path_str.c_str()); /* timed cond wait (unlocks cookie lock, reacquires) */ if (!cookie.cond.wait_until( cookie_lock, deadline, [&] { return cookie.seen; })) { w_log( W_LOG_ERR, "sync_to_now: %s timedwait failed: %d: istimeout=%d %s\n", path_str.c_str(), errcode, errcode == ETIMEDOUT, strerror(errcode)); goto out; } w_log(W_LOG_DBG, "sync_to_now [%s] done\n", path_str.c_str()); out: cookie_lock.unlock(); // can't unlink the file until after the cookie has been observed because // we don't know which file got changed until we look in the cookie dir unlink(path_str.c_str()); { auto map = cookies_.wlock(); map->erase(path_str); } if (!cookie.seen) { errno = errcode; return false; } return true; } void CookieSync::notifyCookie(const w_string& path) const { auto map = cookies_.rlock(); auto cookie_iter = map->find(path); w_log( W_LOG_DBG, "cookie for %s? %s\n", path.c_str(), cookie_iter != map->end() ? "yes" : "no"); if (cookie_iter != map->end()) { auto cookie = cookie_iter->second; auto cookie_lock = std::unique_lock<std::mutex>(cookie->mutex); cookie->seen = true; cookie->cond.notify_one(); } } }
[ "facebook-github-bot-bot@fb.com" ]
facebook-github-bot-bot@fb.com
e0ccb701f2f9bf1550bb8d7bc1339c91c15b303c
3051d1fe583be3d2b89b9ebf3694790d54db24df
/tarjan/cut-vertex.cpp
3321b892e55c8a426680d0775e955cc9546b88df
[]
no_license
zzzcd0x/Data-Structres
9c6bdda6d14c0e61d6da910ed8a5516cab33ec70
f4128e218e3925f8e718381ad1a999a95458869c
refs/heads/master
2022-12-27T07:44:16.146204
2020-10-04T04:00:35
2020-10-04T04:00:35
293,036,020
0
0
null
null
null
null
UTF-8
C++
false
false
1,648
cpp
#include<cstdio> #include<string.h> #include<algorithm> using namespace std; struct Edge{ int from; int to; int next; }edge[200005]; int sum; int tot; int head[20005]; int n, m; int dfscnt; int dfn[20005]; int low[20005]; bool cut[20005]; inline int read(){ int x = 0; char c = getchar(); while(c < '0' || c > '9') c = getchar(); while(c >= '0' && c <= '9') { x = x*10 + c-'0'; c = getchar(); } return x; } void tarjan(int now,int fa){ int chi = 0; low[now] = dfn[now] = ++dfscnt; for(int i = head[now]; i ; i = edge[i].next) { int to = edge[i].to; if(!dfn[to]) { tarjan(to,fa); low[now] = min(low[to],low[now]); if(low[to] >= dfn[now] && now != fa && !cut[now]) { cut[now] = true; sum++; } if(now == fa) chi++; } low[now] = min(low[now],dfn[to]);//后向边 } if(now == fa && chi >= 2 && !cut[now]) { sum++; cut[now] = true; } } void add(int x,int y){ edge[++tot].next = head[x]; head[x] = tot; edge[tot].from = x; edge[tot].to = y; } void inp(){ n = read(); m = read(); for(int i = 1; i <= m; i++) { int x,y; x = read(); y = read(); add(x,y); add(y,x); } } int main(){ inp(); for(int i = 1; i <= n; i++) if(!dfn[i]) tarjan(i,i); printf("%d\n",sum); for(int i = 1; i <= n; i++) if(cut[i]) printf("%d ",i); return 0; }
[ "1055820620@qq.com" ]
1055820620@qq.com
7ccb1c01ee84d1cb9de985605b21f28629dc17bf
30584da3a22b076c463d3363811543202db8d63a
/leetcode-problems/medium/91-decode-ways.cpp
6dad01884bf33941426c3fc3e62a19be8f2a6d27
[ "Unlicense" ]
permissive
formatkaka/dsalgo
30ad7521ea68f9b43f29ba54cd6aa0f0c00e1959
a7c7386c5c161e23bc94456f93cadd0f91f102fa
refs/heads/master
2020-07-13T19:59:45.617443
2019-12-04T12:35:46
2019-12-04T12:35:46
205,143,874
0
0
null
null
null
null
UTF-8
C++
false
false
763
cpp
// // Created by Siddhant on 2019-11-17. // #include "iostream" #include "vector" #include "string" using namespace std; int find(string &s, int i, vector<int>& memo) { if (i <= 0) { return 1; } int l1 = 0, l2 = 0; if(memo[i] != -1){ return memo[i]; } if (s[i] != '0') { l1 = find(s, i - 1, memo); } if (i > 0) { int n = stoi(s.substr(i - 1, 2)); if (n >= 10 && n <= 26) { l2 = find(s, i - 2, memo) ; } } memo[i] = l1 + l2; return l1 + l2; } int numDecodings(string s) { if (s.empty()) return 0; vector<int> memo(s.length(), -1); return find(s, s.length() - 1, memo); } int main() { cout << numDecodings("10"); return 0; }
[ "formatkaka@gmail.com" ]
formatkaka@gmail.com
ec87cd25bff562aaa71e23b8a14d22753513c05c
f1fd5b8854f5c43424f524e4326cec664a943262
/charm/Mesytec.config.hpp
c92e445ab70c2e03816e50c458d5df717f338bac
[]
no_license
zweistein22/CHARMing
771fd89fcfb2926ae2fe220eff0b80cc4a5ab082
1c19002db7f18e729e050dcec969c23b6e404745
refs/heads/master
2023-07-30T23:23:12.315525
2021-10-07T08:20:51
2021-10-07T08:20:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,147
hpp
/* _ _ _ ___ __ __ __ ___ (_) ___ | |_ ___ (_) _ _ |_ / \ V V / / -_) | | (_-< | _| / -_) | | | ' \ _/__| \_/\_/ \___| _|_|_ /__/_ _\__| \___| _|_|_ |_||_| _|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""| "`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-' Copyright (C) 2019 - 2020 by Andreas Langhoff <andreas.langhoff@frm2.tum.de> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation;*/ #pragma once #ifndef BOOST_BIND_GLOBAL_PLACEHOLDERS #define BOOST_BIND_GLOBAL_PLACEHOLDERS #endif #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/filesystem.hpp> #include "Mcpd8.Parameters.hpp" #include "Zweistein.enums.Generator.hpp" #include "Zweistein.GetLocalInterfaces.hpp" #include "Zweistein.HomePath.hpp" #include "Zweistein.Logger.hpp" #include "Zweistein.GetConfigDir.hpp" namespace Mesytec { namespace Config { extern boost::filesystem::path DATAHOME; extern boost::filesystem::path BINNINGFILE; extern boost::property_tree::ptree root; extern bool bcharmdefaults; inline bool get(std::list<Mcpd8::Parameters>& _devlist, boost::filesystem::path inidirectory,bool checknetwork=true) { bool rv = true; try { std::string oursystem = "MsmtSystem"; std::string mesytecdevice = "MesytecDevice"; std::string charmdevice = "CharmDevice"; std::string punkt = "."; std::string mcpd_ip = "mcpd_ip"; std::string mcpd_port = "mcpd_port"; std::string mcpd_id = "mcpd_id"; std::string data_host = "data_host"; std::string datahome = "DataHome"; std::string binningfile = "BinningFile"; std::string counteradc="CounterADC"; std::string modulethresgains = "Threshold_and_Gains"; std::string n_charm_units = "n_charm_units"; const int maxModule = 8; const int maxCounter = 8; const int MaxDevices = 4; int maxdevices = MaxDevices; if (root.empty()) { maxdevices = 1; } DATAHOME = root.get<std::string>(oursystem + punkt + datahome, Zweistein::GetHomePath().string()); root.put<std::string>(oursystem + punkt + datahome, DATAHOME.string()); BINNINGFILE = root.get<std::string>(oursystem + punkt + binningfile, inidirectory.empty()?"": (inidirectory /= "binning.json").string()); root.put<std::string>(oursystem + punkt + binningfile, BINNINGFILE.string()); for (int n = 0; n < maxdevices; n++) { Mcpd8::Parameters p1; std::stringstream ss; ss << oursystem << punkt << mesytecdevice << n << punkt; std::string s2 = ss.str(); if (n == 0) p1.mcpd_ip = root.get<std::string>(s2 + mcpd_ip, Mcpd8::Parameters::defaultIpAddress); else p1.mcpd_ip = root.get<std::string>(s2 + mcpd_ip); root.put<std::string>(s2 + mcpd_ip, p1.mcpd_ip); if (n == 0) p1.mcpd_port = root.get<unsigned short>(s2 + mcpd_port, Mcpd8::Parameters::defaultUdpPort); else p1.mcpd_port = root.get<unsigned short>(s2 + mcpd_port); root.put<unsigned short>(s2 + mcpd_port, p1.mcpd_port); if (n == 0) p1.mcpd_id = root.get<unsigned char>(s2 + mcpd_id, Mcpd8::Parameters::defaultmcpd_id); else p1.mcpd_id = root.get<unsigned char>(s2 + mcpd_id); root.put<unsigned char>(s2 + mcpd_id, p1.mcpd_id); if (n == 0) p1.data_host = root.get<std::string>(s2 + data_host, "0.0.0.0"); else p1.data_host = root.get<std::string>(s2 + data_host); root.put<std::string>(s2 + data_host, p1.data_host); std::string savednetworkcard; if (n == 0) { savednetworkcard = root.get<std::string>(s2 + "networkcard", "192.168.168.100"); root.put<std::string>(s2 + "networkcard", savednetworkcard); p1.networkcard = savednetworkcard; } else p1.networkcard = root.get<std::string>(s2 + "networkcard"); if (checknetwork && !Zweistein::InterfaceExists(p1.networkcard)) { LOG_ERROR << s2 + "networkcard=" << p1.networkcard << " not found." << std::endl; rv = false; //continue; } if (n == 0) { auto a3 = magic_enum::enum_name(bcharmdefaults? Zweistein::Format::EventData::Mdll :Zweistein::Format::EventData::Mpsd8); std::string m3 = std::string(a3.data(), a3.size()); std::string enum_tmp = root.get<std::string>(s2 + "eventdataformat", m3); auto a = magic_enum::enum_cast<Zweistein::Format::EventData>(enum_tmp); std::cout << "eventdataformat" << " : "; if (!a) { std::cout << "option not found : "; rv = false; } else p1.eventdataformat = a.value(); { std::cout <<"possible values are "; constexpr auto & names = magic_enum::enum_names<Zweistein::Format::EventData>(); for (const auto& n : names) std::cout << " " << n; std::cout << std::endl; //continue; } } else { std::string enum_tmp = root.get<std::string>(s2 + "eventdataformat"); auto a = magic_enum::enum_cast<Zweistein::Format::EventData>(enum_tmp); if (!a) { std::cout << "option not found : possible values are "; constexpr auto& names = magic_enum::enum_names<Zweistein::Format::EventData>(); for (const auto& n : names) std::cout << " " << n; std::cout << std::endl; rv = false; //continue; } else p1.eventdataformat = a.value(); } auto a4 = magic_enum::enum_name(p1.eventdataformat); std::string m4 = std::string(a4.data(), a4.size()); root.put<std::string>(s2 + "eventdataformat", m4); if (n == 0) { auto a5 = magic_enum::enum_name(bcharmdefaults? Zweistein::DataGenerator::CharmSimulator : Zweistein::DataGenerator::NucleoSimulator); std::string m5 = std::string(a5.data(), a5.size()); std::string enum_tmp = root.get<std::string>(s2 + "datagenerator", m5); auto a = magic_enum::enum_cast<Zweistein::DataGenerator>(enum_tmp); std::cout << "datagenerator" << " : "; if (!a) { std::cout << "option not found : "; rv = false; //continue; } else p1.datagenerator = a.value(); { std::cout << "possible values are :"; constexpr auto& names = magic_enum::enum_names<Zweistein::DataGenerator>(); for (const auto& n : names) std::cout << " " << n; std::cout << std::endl; } } else { std::string enum_tmp = root.get<std::string>(s2 + "datagenerator"); auto a = magic_enum::enum_cast<Zweistein::DataGenerator>(enum_tmp); if (!a) { std::cout << "option not found : possible values are "; constexpr auto& names = magic_enum::enum_names<Zweistein::DataGenerator>(); for (const auto& n : names) std::cout << " " << n; std::cout << std::endl; rv = false; //continue; } else p1.datagenerator = a.value(); } auto a6 = magic_enum::enum_name(p1.datagenerator); std::string m6 = std::string(a6.data(), a6.size()); root.put<std::string>(s2 + "datagenerator", m6); for (int c = 0; c < maxCounter; c++) { std::string countercell = s2+ counteradc + std::to_string(c); std::string r=root.get<std::string>(countercell, ""); root.put<std::string>(countercell, r); p1.counterADC[c] = r; } for (int m = 0; m < maxModule; m++) { std::string currmodule = s2 + modulethresgains + std::to_string(m); std::string r = root.get<std::string>(currmodule, ""); root.put<std::string>(currmodule, r); p1.moduleparam[m] = r; } std::stringstream ss2; ss2 << oursystem << punkt << charmdevice << n << punkt; std::string s3 = ss2.str(); if (n == 0) p1.n_charm_units = root.get<unsigned short>(s3 + "n_charm_units", bcharmdefaults ? Charm::Parameters::default_n_charm_units : 0); else p1.n_charm_units = root.get<unsigned short>(s3 + "n_charm_units", Charm::Parameters::default_n_charm_units); root.put<unsigned short>(s3 + "n_charm_units", p1.n_charm_units); bool bcanpushback = true; for (auto& d : _devlist) { if (d.networkcard == p1.networkcard && d.mcpd_ip == p1.mcpd_ip) { bcanpushback = false; LOG_ERROR << "CONFIGURATION ERROR:" << s2 + mcpd_ip + "(" << p1.mcpd_ip << ") already in use =>skipped" << std::endl; rv = false; } if (d.mcpd_id == p1.mcpd_id) { bcanpushback = false; LOG_ERROR << "CONFIGURATION ERROR:" << s2 + "mcpd_id(" << p1.mcpd_id << ") already in use =>skipped" << std::endl; rv = false; } } // for devices on same network interface ip addresses must be distinct // for all devices devid must be distinct if (bcanpushback) _devlist.push_back(p1); } } catch (boost::exception& ) { //LOG_DEBUG<< boost::diagnostic_information(e)<<std::endl; } return rv; } static bool AddRoi(std::string roi, std::string key) { try { for (boost::property_tree::ptree::value_type& row : root.get_child(key)) { if (row.second.data() == roi) return false; } } catch (std::exception& ) {} boost::property_tree::ptree cell; cell.put_value(roi); try { boost::property_tree::ptree node_rois = root.get_child(key); boost::property_tree::ptree::value_type row = std::make_pair("", cell); node_rois.push_back(row); root.erase(key); root.add_child(key, node_rois); } catch (std::exception& ) { boost::property_tree::ptree node_rois; node_rois.push_back(std::make_pair("", cell)); root.add_child(key, node_rois); } try { boost::property_tree::write_json(Zweistein::Config::inipath.string(), root); std::stringstream ss_1; boost::property_tree::write_json(ss_1, root); std::cout << ss_1.str() << std::endl; } catch (std::exception& e) { // exception expected, //std::cout << boost::diagnostic_information(e); std::cout << e.what() << " for writing." << std::endl; } return true; } } }
[ "andreas.langhoff@frm2.tum.de" ]
andreas.langhoff@frm2.tum.de
ecc849a7a6ca2ffca86cc49eeca1d59722aeff86
75f9da31883b36375475f86dddf4a72750d3b2ee
/src/chem/energyChiralRestraint.cc
d9f3ae9f7aec52fbd69de478fab68e9364604f24
[]
no_license
salewski/cando
b5a4e7ef94260c29771dcabec80854e0495ca88f
118320d70c5fab2c5fba7692f3d684ebda903520
refs/heads/master
2020-06-09T13:13:57.069065
2019-03-29T20:07:02
2019-03-29T20:07:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,510
cc
/* File: energyChiralRestraint.cc */ /* Open Source License Copyright (c) 2016, Christian E. Schafmeister 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. This is an open source license for the CANDO software from Temple University, but it is not the only one. Contact Temple University at mailto:techtransfer@temple.edu if you would like a different license. */ /* -^- */ #define DEBUG_LEVEL_NONE #include <cando/chem/energyChiralRestraint.h> #include <cando/chem/energyAtomTable.h> #include <cando/chem/energyFunction.h> #include <cando/chem/bond.h> #include <cando/chem/matter.h> #include <cando/chem/atom.h> #include <cando/chem/residue.h> #include <cando/chem/aggregate.h> #include <cando/chem/nVector.h> #include <cando/chem/ffBaseDb.h> #include <cando/chem/ffTypesDb.h> #include <cando/chem/largeSquareMatrix.h> #include <clasp/core/wrappers.h> //#define CHIRAL_RESTRAINT_WEIGHT 1000000.0 // 10000.0 is used in MOE namespace chem { #ifdef XML_ARCHIVE void EnergyChiralRestraint::archive(core::ArchiveP node) { node->attribute("K",this->term.K); node->attribute("CO",this->term.CO); node->attribute("I1",this->term.I1); node->attribute("I2",this->term.I2); node->attribute("I3",this->term.I3); node->attribute("I4",this->term.I4); node->attribute("a1",this->_Atom1); node->attribute("a2",this->_Atom2); node->attribute("a3",this->_Atom3); node->attribute("a4",this->_Atom4); #if TURN_ENERGY_FUNCTION_DEBUG_ON //[ node->attributeIfDefined("calcForce",this->_calcForce,this->_calcForce); node->attributeIfDefined("calcDiagonalHessian",this->_calcDiagonalHessian,this->_calcDiagonalHessian); node->attributeIfDefined("calcOffDiagonalHessian",this->_calcOffDiagonalHessian,this->_calcOffDiagonalHessian); #include <cando/chem/energy_functions/_ChiralRestraint_debugEvalSerialize.cc> #endif //] } #endif string EnergyChiralRestraint::description() { stringstream ss; ss << "EnergyChiralRestraint["; ss << "atoms: "; ss << this->_Atom1->description() << "-"; ss << this->_Atom2->description() << "-"; ss << this->_Atom3->description() << "-"; ss << this->_Atom4->description() ; #if TURN_ENERGY_FUNCTION_DEBUG_ON ss << " eval.Energy=" << this->eval.Energy; #endif return ss.str(); } #if 0 adapt::QDomNode_sp EnergyChiralRestraint::asXml() { adapt::QDomNode_sp node,child; Vector3 vdiff; node = adapt::QDomNode_O::create(env,"EnergyChiralRestraint"); node->addAttributeString("atom1Name",this->_Atom1->getName()); node->addAttributeString("atom2Name",this->_Atom2->getName()); node->addAttributeString("atom3Name",this->_Atom3->getName()); node->addAttributeString("atom4Name",this->_Atom4->getName()); node->addAttributeInt("I1",this->term.I1); node->addAttributeInt("I2",this->term.I2); node->addAttributeInt("I3",this->term.I3); node->addAttributeInt("I4",this->term.I4); node->addAttributeDoubleScientific("K",this->term.K); #if TURN_ENERGY_FUNCTION_DEBUG_ON adapt::QDomNode_sp xml = adapt::QDomNode_O::create(env,"Evaluated"); xml->addAttributeBool("calcForce",this->_calcForce ); xml->addAttributeBool("calcDiagonalHessian",this->_calcDiagonalHessian ); xml->addAttributeBool("calcOffDiagonalHessian",this->_calcOffDiagonalHessian ); #include <_ChiralRestraint_debugEvalXml.cc> node->addChild(xml); #endif return node; } void EnergyChiralRestraint::parseFromXmlUsingAtomTable(adapt::QDomNode_sp xml, AtomTable_sp at ) { this->term.K = xml->getAttributeDouble("K"); this->term.I1 = xml->getAttributeInt("I1"); this->term.I2 = xml->getAttributeInt("I2"); this->term.I3 = xml->getAttributeInt("I3"); this->term.I4 = xml->getAttributeInt("I4"); this->_Atom1 = at->findEnergyAtomWithCoordinateIndex(this->term.I1)->atom(); this->_Atom2 = at->findEnergyAtomWithCoordinateIndex(this->term.I2)->atom(); this->_Atom3 = at->findEnergyAtomWithCoordinateIndex(this->term.I3)->atom(); this->_Atom4 = at->findEnergyAtomWithCoordinateIndex(this->term.I4)->atom(); } #endif // // Copy this from implementAmberFunction.cc // double _evaluateEnergyOnly_ChiralRestraint( double x1, double y1, double z1, double x2, double y2, double z2, double x3, double y3, double z3, double x4, double y4, double z4, double K, double CO ) { #undef CHIRAL_RESTRAINT_SET_PARAMETER #define CHIRAL_RESTRAINT_SET_PARAMETER(x) {} #undef CHIRAL_RESTRAINT_SET_POSITION #define CHIRAL_RESTRAINT_SET_POSITION(x,ii,of) {} #undef CHIRAL_RESTRAINT_ENERGY_ACCUMULATE #define CHIRAL_RESTRAINT_ENERGY_ACCUMULATE(e) {} #undef CHIRAL_RESTRAINT_FORCE_ACCUMULATE #define CHIRAL_RESTRAINT_FORCE_ACCUMULATE(i,o,v) {} #undef CHIRAL_RESTRAINT_DIAGONAL_HESSIAN_ACCUMULATE #define CHIRAL_RESTRAINT_DIAGONAL_HESSIAN_ACCUMULATE(i1,o1,i2,o2,v) {} #undef CHIRAL_RESTRAINT_OFF_DIAGONAL_HESSIAN_ACCUMULATE #define CHIRAL_RESTRAINT_OFF_DIAGONAL_HESSIAN_ACCUMULATE(i1,o1,i2,o2,v) {} #undef CHIRAL_RESTRAINT_CALC_FORCE // Don't calculate FORCE or HESSIAN #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wunused-variable" #include <cando/chem/energy_functions/_ChiralRestraint_termDeclares.cc> #pragma clang diagnostic pop #include <cando/chem/energy_functions/_ChiralRestraint_termCode.cc> return Energy; } void EnergyChiralRestraint_O::addTerm(const EnergyChiralRestraint& e) { this->_Terms.push_back(e); } void EnergyChiralRestraint_O::dumpTerms() { gctools::Vec0<EnergyChiralRestraint>::iterator cri; int i; string as1, as2, as3, as4; for ( i=0,cri=this->_Terms.begin(); cri!=this->_Terms.end(); cri++,i++ ) { as1 = atomLabel(cri->_Atom1); as2 = atomLabel(cri->_Atom2); as3 = atomLabel(cri->_Atom3); as4 = atomLabel(cri->_Atom4); _lisp->print(BF("TERM 7CHIRAL %-9s %-9s %-9s %-9s %8.2lf %8.2lf ; I1=%d I2=%d I3=%d I4=%d") % as1 % as2 % as3 % as4 % cri->term.K % cri->term.CO % cri->term.I1 % cri->term.I2 % cri->term.I3 % cri->term.I4 ); } } string EnergyChiralRestraint_O::beyondThresholdInteractionsAsString() { return component_beyondThresholdInteractionsAsString<EnergyChiralRestraint_O,EnergyChiralRestraint>(*this); } void EnergyChiralRestraint_O::setupHessianPreconditioner( chem::NVector_sp nvPosition, chem::AbstractLargeSquareMatrix_sp m ) { bool calcForce = true; bool calcDiagonalHessian = true; bool calcOffDiagonalHessian = true; // // Copy from implementAmberFunction::setupHessianPreconditioner // // ----------------------- #undef CHIRAL_RESTRAINT_SET_PARAMETER #define CHIRAL_RESTRAINT_SET_PARAMETER(x) {x=cri->term.x;} #undef CHIRAL_RESTRAINT_SET_POSITION #define CHIRAL_RESTRAINT_SET_POSITION(x,ii,of) {x=nvPosition->element(ii+of);} #undef CHIRAL_RESTRAINT_PHI_SET #define CHIRAL_RESTRAINT_PHI_SET(x) {} #undef CHIRAL_RESTRAINT_ENERGY_ACCUMULATE #define CHIRAL_RESTRAINT_ENERGY_ACCUMULATE(e) {} #undef CHIRAL_RESTRAINT_FORCE_ACCUMULATE #define CHIRAL_RESTRAINT_FORCE_ACCUMULATE(i,o,v) {} #undef CHIRAL_RESTRAINT_DIAGONAL_HESSIAN_ACCUMULATE #define CHIRAL_RESTRAINT_DIAGONAL_HESSIAN_ACCUMULATE(i1,o1,i2,o2,v) {\ m->addToElement((i1)+(o1),(i2)+(o2),v);\ } #undef CHIRAL_RESTRAINT_OFF_DIAGONAL_HESSIAN_ACCUMULATE #define CHIRAL_RESTRAINT_OFF_DIAGONAL_HESSIAN_ACCUMULATE(i1,o1,i2,o2,v) {\ m->addToElement((i1)+(o1),(i2)+(o2),v);\ } #define CHIRAL_RESTRAINT_CALC_FORCE #define CHIRAL_RESTRAINT_CALC_DIAGONAL_HESSIAN #define CHIRAL_RESTRAINT_CALC_OFF_DIAGONAL_HESSIAN if ( this->isEnabled() ) { #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wunused-variable" #include <cando/chem/energy_functions/_ChiralRestraint_termDeclares.cc> #pragma clang diagnostic pop double x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4,K, CO; int I1, I2, I3, I4, i; for ( gctools::Vec0<EnergyChiralRestraint>::iterator cri=this->_Terms.begin(); cri!=this->_Terms.end(); cri++ ) { #include <cando/chem/energy_functions/_ChiralRestraint_termCode.cc> } } } double EnergyChiralRestraint_O::evaluateAll(chem::NVector_sp pos, bool calcForce, gc::Nilable<chem::NVector_sp> force, bool calcDiagonalHessian, bool calcOffDiagonalHessian, gc::Nilable<chem::AbstractLargeSquareMatrix_sp> hessian, gc::Nilable<chem::NVector_sp> hdvec, gc::Nilable<chem::NVector_sp> dvec) { if ( this->_DebugEnergy ) { LOG_ENERGY_CLEAR(); LOG_ENERGY(BF("%s {\n")% this->className()); } ANN(force); ANN(hessian); ANN(hdvec); ANN(dvec); bool hasForce = force.notnilp(); bool hasHessian = hessian.notnilp(); bool hasHdAndD = (hdvec.notnilp())&&(dvec.notnilp()); // // Copy from implementAmberFunction::evaluateAll // // ----------------------- #define CHIRAL_RESTRAINT_CALC_FORCE #define CHIRAL_RESTRAINT_CALC_DIAGONAL_HESSIAN #define CHIRAL_RESTRAINT_CALC_OFF_DIAGONAL_HESSIAN #undef CHIRAL_RESTRAINT_SET_PARAMETER #define CHIRAL_RESTRAINT_SET_PARAMETER(x) {x = cri->term.x;} #undef CHIRAL_RESTRAINT_SET_POSITION #define CHIRAL_RESTRAINT_SET_POSITION(x,ii,of) {x = pos->element(ii+of);} #undef CHIRAL_RESTRAINT_PHI_SET #define CHIRAL_RESTRAINT_PHI_SET(x) {} #undef CHIRAL_RESTRAINT_ENERGY_ACCUMULATE #define CHIRAL_RESTRAINT_ENERGY_ACCUMULATE(e) this->_TotalEnergy += (e); #undef CHIRAL_RESTRAINT_FORCE_ACCUMULATE #undef CHIRAL_RESTRAINT_DIAGONAL_HESSIAN_ACCUMULATE #undef CHIRAL_RESTRAINT_OFF_DIAGONAL_HESSIAN_ACCUMULATE #define CHIRAL_RESTRAINT_FORCE_ACCUMULATE ForceAcc #define CHIRAL_RESTRAINT_DIAGONAL_HESSIAN_ACCUMULATE DiagHessAcc #define CHIRAL_RESTRAINT_OFF_DIAGONAL_HESSIAN_ACCUMULATE OffDiagHessAcc if ( this->isEnabled() ) { #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wunused-variable" #include <cando/chem/energy_functions/_ChiralRestraint_termDeclares.cc> #pragma clang diagnostic pop double x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4,K, CO; int I1, I2, I3, I4, i; gctools::Vec0<EnergyChiralRestraint>::iterator cri; for ( i=0,cri=this->_Terms.begin(); cri!=this->_Terms.end(); cri++,i++ ) { #ifdef DEBUG_CONTROL_THE_NUMBER_OF_TERMS_EVALAUTED if ( this->_Debug_NumberOfChiralRestraintTermsToCalculate > 0 ) { if ( i>= this->_Debug_NumberOfChiralRestraintTermsToCalculate ) { break; } } #endif /* Obtain all the parameters necessary to calculate */ /* the amber and forces */ #include <cando/chem/energy_functions/_ChiralRestraint_termCode.cc> #if TURN_ENERGY_FUNCTION_DEBUG_ON //[ cri->_calcForce = calcForce; cri->_calcDiagonalHessian = calcDiagonalHessian; cri ->_calcOffDiagonalHessian = calcOffDiagonalHessian; // Now write all of the calculated values into the eval structure #undef EVAL_SET #define EVAL_SET(var,val) { cri->eval.var=val;}; #include <cando/chem/energy_functions/_ChiralRestraint_debugEvalSet.cc> #endif //] if ( this->_DebugEnergy ) { LOG_ENERGY(BF( "MEISTER chiralRestraint %d args cando\n")% (i+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d K %lf\n")% (i+1) % K ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d x1 %5.3lf %d\n")%(i+1) % x1 % (I1/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d y1 %5.3lf %d\n")%(i+1) % y1 % (I1/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d z1 %5.3lf %d\n")%(i+1) % z1 % (I1/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d x2 %5.3lf %d\n")%(i+1) % x2 % (I2/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d y2 %5.3lf %d\n")%(i+1) % y2 % (I2/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d z2 %5.3lf %d\n")%(i+1) % z2 % (I2/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d x3 %5.3lf %d\n")%(i+1) % x3 % (I3/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d y3 %5.3lf %d\n")%(i+1) % y3 % (I3/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d z3 %5.3lf %d\n")%(i+1) % z3 % (I3/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d x4 %5.3lf %d\n")%(i+1) % x4 % (I4/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d y4 %5.3lf %d\n")%(i+1) % y4 % (I4/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d z4 %5.3lf %d\n")%(i+1) % z4 % (I4/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d results\n")% (i+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d Energy %lf\n")% (i+1) % Energy); if ( calcForce ) { // LOG_ENERGY(BF( "MEISTER chiralRestraint %d DePhi %lf\n")% (i+1) % DePhi); LOG_ENERGY(BF( "MEISTER chiralRestraint %d fx1 %8.5lf %d\n")%(i+1) % fx1 % (I1/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d fy1 %8.5lf %d\n")%(i+1) % fy1 % (I1/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d fz1 %8.5lf %d\n")%(i+1) % fz1 % (I1/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d fx2 %8.5lf %d\n")%(i+1) % fx2 % (I2/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d fy2 %8.5lf %d\n")%(i+1) % fy2 % (I2/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d fz2 %8.5lf %d\n")%(i+1) % fz2 % (I2/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d fx3 %8.5lf %d\n")%(i+1) % fx3 % (I3/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d fy3 %8.5lf %d\n")%(i+1) % fy3 % (I3/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d fz3 %8.5lf %d\n")%(i+1) % fz3 % (I3/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d fx4 %8.5lf %d\n")%(i+1) % fx4 % (I4/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d fy4 %8.5lf %d\n")%(i+1) % fy4 % (I4/3+1) ); LOG_ENERGY(BF( "MEISTER chiralRestraint %d fz4 %8.5lf %d\n")%(i+1) % fz4 % (I4/3+1) ); } LOG_ENERGY(BF( "MEISTER chiralRestraint %d stop\n")% (i+1) ); } /* Add the forces */ if ( calcForce ) { // _lisp->profiler().eventCounter(core::forcesGreaterThan10000).recordCallAndProblem(fx1>10000.0); // _lisp->profiler().eventCounter(core::forcesGreaterThan10000).recordCallAndProblem(fy1>10000.0); // _lisp->profiler().eventCounter(core::forcesGreaterThan10000).recordCallAndProblem(fz1>10000.0); // _lisp->profiler().eventCounter(core::forcesGreaterThan10000).recordCallAndProblem(fx2>10000.0); // _lisp->profiler().eventCounter(core::forcesGreaterThan10000).recordCallAndProblem(fy2>10000.0); // _lisp->profiler().eventCounter(core::forcesGreaterThan10000).recordCallAndProblem(fz2>10000.0); // _lisp->profiler().eventCounter(core::forcesGreaterThan10000).recordCallAndProblem(fx3>10000.0); // _lisp->profiler().eventCounter(core::forcesGreaterThan10000).recordCallAndProblem(fy3>10000.0); // _lisp->profiler().eventCounter(core::forcesGreaterThan10000).recordCallAndProblem(fz3>10000.0); // _lisp->profiler().eventCounter(core::forcesGreaterThan10000).recordCallAndProblem(fx4>10000.0); // _lisp->profiler().eventCounter(core::forcesGreaterThan10000).recordCallAndProblem(fy4>10000.0); // _lisp->profiler().eventCounter(core::forcesGreaterThan10000).recordCallAndProblem(fz4>10000.0); } } } if ( this->_DebugEnergy ) { LOG_ENERGY(BF("%s }\n")% this->className()); } return this->_TotalEnergy; } void EnergyChiralRestraint_O::compareAnalyticalAndNumericalForceAndHessianTermByTerm( chem::NVector_sp pos) { int fails = 0; bool calcForce = true; bool calcDiagonalHessian = true; bool calcOffDiagonalHessian = true; // // copy from implementAmberFunction::compareAnalyticalAndNumericalForceAndHessianTermByTerm( // //------------------ #define CHIRAL_RESTRAINT_CALC_FORCE #define CHIRAL_RESTRAINT_CALC_DIAGONAL_HESSIAN #define CHIRAL_RESTRAINT_CALC_OFF_DIAGONAL_HESSIAN #undef CHIRAL_RESTRAINT_SET_PARAMETER #define CHIRAL_RESTRAINT_SET_PARAMETER(x) {x = cri->term.x;} #undef CHIRAL_RESTRAINT_SET_POSITION #define CHIRAL_RESTRAINT_SET_POSITION(x,ii,of) {x = pos->element(ii+of);} #undef CHIRAL_RESTRAINT_PHI_SET #define CHIRAL_RESTRAINT_PHI_SET(x) {} #undef CHIRAL_RESTRAINT_ENERGY_ACCUMULATE #define CHIRAL_RESTRAINT_ENERGY_ACCUMULATE(e) {} #undef CHIRAL_RESTRAINT_FORCE_ACCUMULATE #define CHIRAL_RESTRAINT_FORCE_ACCUMULATE(i,o,v) {} #undef CHIRAL_RESTRAINT_DIAGONAL_HESSIAN_ACCUMULATE #define CHIRAL_RESTRAINT_DIAGONAL_HESSIAN_ACCUMULATE(i1,o1,i2,o2,v) {} #undef CHIRAL_RESTRAINT_OFF_DIAGONAL_HESSIAN_ACCUMULATE #define CHIRAL_RESTRAINT_OFF_DIAGONAL_HESSIAN_ACCUMULATE(i1,o1,i2,o2,v) {} if ( this->isEnabled() ) { _BLOCK_TRACE("ChiralRestraintEnergy finiteDifference comparison"); #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wunused-variable" #include <cando/chem/energy_functions/_ChiralRestraint_termDeclares.cc> #pragma clang diagnostic pop double x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4,K, CO; int I1, I2, I3, I4, i; gctools::Vec0<EnergyChiralRestraint>::iterator cri; for ( i=0,cri=this->_Terms.begin(); cri!=this->_Terms.end(); cri++,i++ ) { /* Obtain all the parameters necessary to calculate */ /* the amber and forces */ #include <cando/chem/energy_functions/_ChiralRestraint_termCode.cc> LOG(BF("fx1 = %le") % fx1 ); LOG(BF("fy1 = %le") % fy1 ); LOG(BF("fz1 = %le") % fz1 ); LOG(BF("fx2 = %le") % fx2 ); LOG(BF("fy2 = %le") % fy2 ); LOG(BF("fz2 = %le") % fz2 ); LOG(BF("fx3 = %le") % fx3 ); LOG(BF("fy3 = %le") % fy3 ); LOG(BF("fz3 = %le") % fz3 ); LOG(BF("fx4 = %le") % fx4 ); LOG(BF("fy4 = %le") % fy4 ); LOG(BF("fz4 = %le") % fz4 ); int index = i; #include <cando/chem/energy_functions/_ChiralRestraint_debugFiniteDifference.cc> } } } int EnergyChiralRestraint_O::checkForBeyondThresholdInteractions( stringstream& info, chem::NVector_sp pos ) { int fails = 0; this->_BeyondThresholdTerms.clear(); // // Copy from implementAmberFunction::checkForBeyondThresholdInteractions // //------------------ #undef CHIRAL_RESTRAINT_CALC_FORCE #undef CHIRAL_RESTRAINT_CALC_DIAGONAL_HESSIAN #undef CHIRAL_RESTRAINT_CALC_OFF_DIAGONAL_HESSIAN #undef CHIRAL_RESTRAINT_SET_PARAMETER #define CHIRAL_RESTRAINT_SET_PARAMETER(x) {x = cri->term.x;} #undef CHIRAL_RESTRAINT_SET_POSITION #define CHIRAL_RESTRAINT_SET_POSITION(x,ii,of) {x = pos->element(ii+of);} #undef CHIRAL_RESTRAINT_PHI_SET #define CHIRAL_RESTRAINT_PHI_SET(x) {} #undef CHIRAL_RESTRAINT_ENERGY_ACCUMULATE #define CHIRAL_RESTRAINT_ENERGY_ACCUMULATE(e) {} #undef CHIRAL_RESTRAINT_FORCE_ACCUMULATE #define CHIRAL_RESTRAINT_FORCE_ACCUMULATE(i,o,v) {} #undef CHIRAL_RESTRAINT_DIAGONAL_HESSIAN_ACCUMULATE #define CHIRAL_RESTRAINT_DIAGONAL_HESSIAN_ACCUMULATE(i1,o1,i2,o2,v) {} #undef CHIRAL_RESTRAINT_OFF_DIAGONAL_HESSIAN_ACCUMULATE #define CHIRAL_RESTRAINT_OFF_DIAGONAL_HESSIAN_ACCUMULATE(i1,o1,i2,o2,v) {} if ( this->isEnabled() ) { _BLOCK_TRACE("ChiralRestraintEnergy finiteDifference comparison"); #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wunused-variable" #include <cando/chem/energy_functions/_ChiralRestraint_termDeclares.cc> #pragma clang diagnostic pop double x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4,K, CO; int I1, I2, I3, I4, i; gctools::Vec0<EnergyChiralRestraint>::iterator cri; LOG(BF("Entering checking loop, there are %d terms") % this->_Terms.end()-this->_Terms.begin() ); for ( i=0,cri=this->_Terms.begin(); cri!=this->_Terms.end(); cri++,i++ ) { /* Obtain all the parameters necessary to calculate */ /* the amber and forces */ LOG(BF("Checking term# %d") % i ); #include <cando/chem/energy_functions/_ChiralRestraint_termCode.cc> LOG(BF("Status") ); if ( ChiralTest>0.0 ) { chem::Atom_sp a1, a2, a3, a4; a1 = (*cri)._Atom1; a2 = (*cri)._Atom2; a3 = (*cri)._Atom3; a4 = (*cri)._Atom4; LOG(BF("Status") ); info<< "ChiralRestraintDeviation "; info << "value " << ChiralTest << " Atoms("; info << a1->getName() << " "; info << a2->getName() << " "; info << a3->getName() << " "; info << a4->getName() << ")"; info << std::endl; LOG(BF("Info: %s") % info.str().c_str() ); this->_BeyondThresholdTerms.push_back(*cri); LOG(BF("Status") ); fails++; } LOG(BF("Status") ); } LOG(BF("Status") ); } return fails; } void EnergyChiralRestraint_O::initialize() { this->Base::initialize(); this->setErrorThreshold(0.2); } #ifdef XML_ARCHIVE void EnergyChiralRestraint_O::archiveBase(core::ArchiveP node) { this->Base::archiveBase(node); IMPLEMENT_ME(); } #endif };
[ "chris.schaf@verizon.net" ]
chris.schaf@verizon.net
cbc177da949f030601cb44cfcbe853d5bfbd554e
7f32af244fe223aeb25dd3416419da6475c4b20d
/stdafx.cpp
92662b150c86092b0d586608ccedb06a6a1ff1d1
[]
no_license
ashishgithubbce/Speech-Based-Vowel-Recognition-System
49f21721413b5b19fc2f88e13a6d69bb16eeb6cc
70f0659e7f3dfdd5cf3b22d7fa82b58a66942b42
refs/heads/main
2023-07-28T14:40:41.609121
2021-09-12T09:45:07
2021-09-12T09:45:07
405,602,264
0
0
null
null
null
null
UTF-8
C++
false
false
303
cpp
// stdafx.cpp : source file that includes just the standard includes // VowelRecognition.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "noreply@github.com" ]
ashishgithubbce.noreply@github.com
bb8d2289dff1c8e735fb5a11c13df57e4c92ac53
a4171fa29f00b405ce8b9954ea8e67a0c35cdb05
/ConsoleApplication5/ConsoleApplication5/Utility.h
12871fb052ec9f3ed01f89daaa4586af9f8da461
[]
no_license
CyanogenMod13/PracticeWorks
5cfc0cd31a8f3f258f07785988478e389878db0c
d51d04517265355c3895cdd9c751080f114f76fb
refs/heads/master
2023-03-20T02:49:38.385107
2021-03-15T21:05:46
2021-03-15T21:05:46
316,980,307
0
0
null
null
null
null
UTF-8
C++
false
false
937
h
#ifndef _Utility_ #define _Utility_ #include <iostream> #include <cmath> inline long random(long start, long end) { return start + (rand() + 1) % (end - start + 1); } inline long min(long a, long b) { return a > b ? b : a; } inline void print(long** arr, long N, long M) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { std::cout << arr[i][j] << " "; } std::cout << std::endl; } } inline void print(long* arr, long N) { for (int i = 0; i < N; i++) { std::cout << arr[i] << " "; } } inline void swap(long& a, long& b) { long c = b; b = a; a = c; } void bubble_sort(long* arr, long size, bool oder = 0) { for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) { if (i == j) continue; if (arr[i] < arr[j] && oder || arr[i] > arr[j] && !oder) { swap(arr[i], arr[j]); continue; } } } #endif // !_Utility_
[ "noreply@github.com" ]
CyanogenMod13.noreply@github.com
dc8f539c94db1d1ffc3deda08aaa44dc3f4b1942
9da899bf6541c6a0514219377fea97df9907f0ae
/Runtime/Engine/Private/Components/BillboardComponent.cpp
8e819a4a1c60c44a1784abeedaf4e1732fe7d9d2
[]
no_license
peichangliang123/UE4
1aa4df3418c077dd8f82439ecc808cd2e6de4551
20e38f42edc251ee96905ed8e96e1be667bc14a5
refs/heads/master
2023-08-17T11:31:53.304431
2021-09-15T00:31:03
2021-09-15T00:31:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,785
cpp
// Copyright Epic Games, Inc. All Rights Reserved. #include "Components/BillboardComponent.h" #include "UObject/ConstructorHelpers.h" #include "EngineGlobals.h" #include "PrimitiveViewRelevance.h" #include "PrimitiveSceneProxy.h" #include "Components/LightComponent.h" #include "Engine/CollisionProfile.h" #include "UObject/UObjectHash.h" #include "UObject/UObjectIterator.h" #include "Engine/Texture2D.h" #include "SceneManagement.h" #include "Engine/Light.h" #include "Engine/Engine.h" #include "Engine/LevelStreaming.h" #include "LevelUtils.h" #include "TextureCompiler.h" namespace BillboardConstants { static const float DefaultScreenSize = 0.0025f; } #if WITH_EDITORONLY_DATA float UBillboardComponent::EditorScale = 1.0f; #endif /** Represents a billboard sprite to the scene manager. */ class FSpriteSceneProxy final : public FPrimitiveSceneProxy { public: SIZE_T GetTypeHash() const override { static size_t UniquePointer; return reinterpret_cast<size_t>(&UniquePointer); } /** Initialization constructor. */ FSpriteSceneProxy(const UBillboardComponent* InComponent, float SpriteScale) : FPrimitiveSceneProxy(InComponent) , ScreenSize(InComponent->ScreenSize) , U(InComponent->U) , V(InComponent->V) , Color(FLinearColor::White) , bIsScreenSizeScaled(InComponent->bIsScreenSizeScaled) #if WITH_EDITORONLY_DATA , bUseInEditorScaling(InComponent->bUseInEditorScaling) , EditorScale(InComponent->EditorScale) #endif { #if WITH_EDITOR // Extract the sprite category from the component if in the editor if ( GIsEditor ) { SpriteCategoryIndex = GEngine->GetSpriteCategoryIndex( InComponent->SpriteInfo.Category ); } #endif //WITH_EDITOR bWillEverBeLit = false; // Calculate the scale factor for the sprite. Scale = InComponent->GetComponentTransform().GetMaximumAxisScale() * SpriteScale * 0.25f; OpacityMaskRefVal = InComponent->OpacityMaskRefVal; if(InComponent->Sprite) { Texture = InComponent->Sprite; // Set UL and VL to the size of the texture if they are set to 0.0, otherwise use the given value ComponentUL = InComponent->UL; ComponentVL = InComponent->VL; } else { Texture = NULL; ComponentUL = ComponentVL = 0; } if (AActor* Owner = InComponent->GetOwner()) { // If the owner of this sprite component is an ALight, tint the sprite // to match the lights color. if (ALight* Light = Cast<ALight>(Owner)) { if (Light->GetLightComponent()) { Color = Light->GetLightComponent()->LightColor.ReinterpretAsLinear(); Color.A = 255; } } #if WITH_EDITORONLY_DATA else if (GIsEditor) { Color = FLinearColor::White; } #endif // WITH_EDITORONLY_DATA //save off override states #if WITH_EDITORONLY_DATA bIsActorLocked = Owner->IsLockLocation(); #else // WITH_EDITORONLY_DATA bIsActorLocked = false; #endif // WITH_EDITORONLY_DATA // Level colorization ULevel* Level = Owner->GetLevel(); if (ULevelStreaming* LevelStreaming = FLevelUtils::FindStreamingLevel(Level)) { // Selection takes priority over level coloration. SetLevelColor(LevelStreaming->LevelColor); } } FColor NewPropertyColor; if (GEngine->GetPropertyColorationColor( (UObject*)InComponent, NewPropertyColor )) { SetPropertyColor(NewPropertyColor); } } // FPrimitiveSceneProxy interface. virtual void GetDynamicMeshElements(const TArray<const FSceneView*>& Views, const FSceneViewFamily& ViewFamily, uint32 VisibilityMap, FMeshElementCollector& Collector) const override { QUICK_SCOPE_CYCLE_COUNTER( STAT_SpriteSceneProxy_GetDynamicMeshElements ); FTexture* TextureResource = Texture ? Texture->Resource : nullptr; if (TextureResource) { const float UL = ComponentUL == 0.0f ? TextureResource->GetSizeX() : ComponentUL; const float VL = ComponentVL == 0.0f ? TextureResource->GetSizeY() : ComponentVL; for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++) { if (VisibilityMap & (1 << ViewIndex)) { const FSceneView* View = Views[ViewIndex]; // Calculate the view-dependent scaling factor. float ViewedSizeX = Scale * UL; float ViewedSizeY = Scale * VL; if (bIsScreenSizeScaled && (View->ViewMatrices.GetProjectionMatrix().M[3][3] != 1.0f)) { const float ZoomFactor = FMath::Min<float>(View->ViewMatrices.GetProjectionMatrix().M[0][0], View->ViewMatrices.GetProjectionMatrix().M[1][1]); if(ZoomFactor != 0.0f) { const float Radius = View->WorldToScreen(Origin).W * (ScreenSize / ZoomFactor); if (Radius < 1.0f) { ViewedSizeX *= Radius; ViewedSizeY *= Radius; } } } #if WITH_EDITORONLY_DATA ViewedSizeX *= EditorScale; ViewedSizeY *= EditorScale; #endif FLinearColor ColorToUse = Color; // Set the selection/hover color from the current engine setting. // The color is multiplied by 10 because this value is normally expected to be blended // additively, this is not how the sprites work and therefore need an extra boost // to appear the same color as previously #if WITH_EDITOR if( View->bHasSelectedComponents && !IsIndividuallySelected() ) { ColorToUse = FLinearColor::White + (GEngine->GetSubduedSelectionOutlineColor() * GEngine->SelectionHighlightIntensityBillboards * 10); } else #endif if (IsSelected()) { ColorToUse = FLinearColor::White + (GEngine->GetSelectedMaterialColor() * GEngine->SelectionHighlightIntensityBillboards * 10); } else if (IsHovered()) { ColorToUse = FLinearColor::White + (GEngine->GetHoveredMaterialColor() * GEngine->SelectionHighlightIntensityBillboards * 10); } // Sprites of locked actors draw in red. if (bIsActorLocked) { ColorToUse = FColor::Red; } FLinearColor LevelColorToUse = IsSelected() ? ColorToUse : (FLinearColor)GetLevelColor(); FLinearColor PropertyColorToUse = GetPropertyColor(); ColorToUse.A = 1.0f; const FLinearColor& SpriteColor = View->Family->EngineShowFlags.LevelColoration ? LevelColorToUse : ( (View->Family->EngineShowFlags.PropertyColoration) ? PropertyColorToUse : ColorToUse ); Collector.GetPDI(ViewIndex)->DrawSprite( Origin, ViewedSizeX, ViewedSizeY, TextureResource, SpriteColor, GetDepthPriorityGroup(View), U,UL,V,VL, SE_BLEND_Masked, OpacityMaskRefVal ); } } #if !(UE_BUILD_SHIPPING || UE_BUILD_TEST) for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++) { if (VisibilityMap & (1 << ViewIndex)) { const FSceneView* View = Views[ViewIndex]; RenderBounds(Collector.GetPDI(ViewIndex), View->Family->EngineShowFlags, GetBounds(), IsSelected()); } } #endif } } virtual FPrimitiveViewRelevance GetViewRelevance(const FSceneView* View) const override { bool bVisible = View->Family->EngineShowFlags.BillboardSprites; #if WITH_EDITOR if ( GIsEditor && bVisible && SpriteCategoryIndex != INDEX_NONE && SpriteCategoryIndex < View->SpriteCategoryVisibility.Num() ) { bVisible = View->SpriteCategoryVisibility[ SpriteCategoryIndex ]; } #endif FPrimitiveViewRelevance Result; Result.bDrawRelevance = IsShown(View) && bVisible; Result.bOpaque = true; Result.bDynamicRelevance = true; Result.bShadowRelevance = IsShadowCast(View); Result.bEditorPrimitiveRelevance = UseEditorCompositing(View); return Result; } virtual void OnTransformChanged() override { Origin = GetLocalToWorld().GetOrigin(); } virtual uint32 GetMemoryFootprint(void) const override { return(sizeof(*this) + GetAllocatedSize()); } uint32 GetAllocatedSize(void) const { return( FPrimitiveSceneProxy::GetAllocatedSize() ); } private: FVector Origin; const float ScreenSize; const UTexture2D* Texture; float Scale; const float U; float ComponentUL; const float V; float ComponentVL; float OpacityMaskRefVal; FLinearColor Color; const uint32 bIsScreenSizeScaled : 1; uint32 bIsActorLocked : 1; #if WITH_EDITORONLY_DATA int32 SpriteCategoryIndex; bool bUseInEditorScaling; float EditorScale; #endif // #if WITH_EDITORONLY_DATA }; UBillboardComponent::UBillboardComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { #if WITH_EDITORONLY_DATA // Structure to hold one-time initialization struct FConstructorStatics { ConstructorHelpers::FObjectFinder<UTexture2D> SpriteTexture; FName ID_Misc; FText NAME_Misc; FConstructorStatics() : SpriteTexture(TEXT("/Engine/EditorResources/S_Actor")) , ID_Misc(TEXT("Misc")) , NAME_Misc(NSLOCTEXT( "SpriteCategory", "Misc", "Misc" )) { } }; static FConstructorStatics ConstructorStatics; Sprite = ConstructorStatics.SpriteTexture.Object; #endif SetCollisionProfileName(UCollisionProfile::NoCollision_ProfileName); SetUsingAbsoluteScale(true); bIsScreenSizeScaled = false; ScreenSize = BillboardConstants::DefaultScreenSize; U = 0; V = 0; UL = 0; VL = 0; OpacityMaskRefVal = .5f; bHiddenInGame = true; SetGenerateOverlapEvents(false); bUseEditorCompositing = true; bExcludeFromLightAttachmentGroup = true; #if WITH_EDITORONLY_DATA SpriteInfo.Category = ConstructorStatics.ID_Misc; SpriteInfo.DisplayName = ConstructorStatics.NAME_Misc; bUseInEditorScaling = true; #endif // WITH_EDITORONLY_DATA } FPrimitiveSceneProxy* UBillboardComponent::CreateSceneProxy() { float SpriteScale = 1.0f; #if WITH_EDITOR if (GetOwner()) { SpriteScale = GetOwner()->SpriteScale; } #endif return new FSpriteSceneProxy(this, SpriteScale); } FBoxSphereBounds UBillboardComponent::CalcBounds(const FTransform& LocalToWorld) const { const float NewScale = LocalToWorld.GetScale3D().GetMax() * (Sprite ? (float)FMath::Max(Sprite->GetSizeX(),Sprite->GetSizeY()) : 1.0f); return FBoxSphereBounds(LocalToWorld.GetLocation(),FVector(NewScale,NewScale,NewScale),FMath::Sqrt(3.0f * FMath::Square(NewScale))); } #if WITH_EDITOR bool UBillboardComponent::ComponentIsTouchingSelectionBox(const FBox& InSelBBox, const FEngineShowFlags& ShowFlags, const bool bConsiderOnlyBSP, const bool bMustEncompassEntireComponent) const { AActor* Actor = GetOwner(); if (!bConsiderOnlyBSP && ShowFlags.BillboardSprites && Sprite != nullptr && Actor != nullptr) { const float Scale = GetComponentTransform().GetMaximumAxisScale(); // Construct a box representing the sprite const FBox SpriteBox( Actor->GetActorLocation() - Scale * FMath::Max(Sprite->GetSizeX(), Sprite->GetSizeY()) * FVector(0.5f, 0.5f, 0.5f), Actor->GetActorLocation() + Scale * FMath::Max(Sprite->GetSizeX(), Sprite->GetSizeY()) * FVector(0.5f, 0.5f, 0.5f)); // If the selection box doesn't have to encompass the entire component and it intersects with the box constructed for the sprite, then it is valid. // Additionally, if the selection box does have to encompass the entire component and both the min and max vectors of the sprite box are inside the selection box, // then it is valid. if ((!bMustEncompassEntireComponent && InSelBBox.Intersect(SpriteBox)) || (bMustEncompassEntireComponent && InSelBBox.IsInside(SpriteBox))) { return true; } } return false; } bool UBillboardComponent::ComponentIsTouchingSelectionFrustum(const FConvexVolume& InFrustum, const FEngineShowFlags& ShowFlags, const bool bConsiderOnlyBSP, const bool bMustEncompassEntireComponent) const { AActor* Actor = GetOwner(); if (!bConsiderOnlyBSP && ShowFlags.BillboardSprites && Sprite != nullptr && Actor != nullptr) { const float Scale = GetComponentTransform().GetMaximumAxisScale(); const float MaxExtent = FMath::Max(Sprite->GetSizeX(), Sprite->GetSizeY()); const FVector Extent = Scale * MaxExtent * FVector(0.5f, 0.5f, 0.0f); bool bIsFullyContained; if (InFrustum.IntersectBox(Actor->GetActorLocation(), Extent, bIsFullyContained)) { return !bMustEncompassEntireComponent || bIsFullyContained; } } return false; } #endif void UBillboardComponent::SetSprite(UTexture2D* NewSprite) { Sprite = NewSprite; MarkRenderStateDirty(); } void UBillboardComponent::SetUV(int32 NewU, int32 NewUL, int32 NewV, int32 NewVL) { U = NewU; UL = NewUL; V = NewV; VL = NewVL; MarkRenderStateDirty(); } void UBillboardComponent::SetSpriteAndUV(UTexture2D* NewSprite, int32 NewU, int32 NewUL, int32 NewV, int32 NewVL) { U = NewU; UL = NewUL; V = NewV; VL = NewVL; SetSprite(NewSprite); } void UBillboardComponent::SetOpacityMaskRefVal(float RefVal) { OpacityMaskRefVal = RefVal; MarkRenderStateDirty(); } #if WITH_EDITORONLY_DATA void UBillboardComponent::SetEditorScale(float InEditorScale) { EditorScale = InEditorScale; for(TObjectIterator<UBillboardComponent> It; It; ++It) { It->MarkRenderStateDirty(); } } #endif
[ "ouczbs@qq.com" ]
ouczbs@qq.com
7ca67e2e5f3b841a8b8aa8673118bc2de24031a9
6b57df76567fc391ba3f7e9f741a742d792b606b
/fundcomp/lab10/board.h
a6d16cb6356ff34a33bc1ff2572d803b1f1b9fb1
[]
no_license
nolan-downey/SchoolCodingWork
66393a9839c807a1a7ba5f1de6fe4a4fe8562da0
4592791d67a7191b9bfc2cb78232fef230b36c39
refs/heads/master
2022-04-13T12:30:24.494405
2020-04-06T00:22:30
2020-04-06T00:22:30
253,351,666
0
0
null
null
null
null
UTF-8
C++
false
false
870
h
//Nolan Downey //board.h #include <vector> #include <string> using namespace std; const bool ACROSS = 1; const bool DOWN = 0; const int SZ = 15; const string END = "."; struct Word { string a_word; string s_word; int down; int across; bool orientation; bool placed; }; class Board { public: Board(); ~Board(); ostream & printClues(ostream &); ostream & printBoard(ostream &); ostream & printPuzzle(ostream &); void setWord(string); string toUpper(string); string scramble(string); void placeFirst(); void displayClue(); void display(); void followingWord(); bool placeWord(); bool checkPlace(int, int, int); int wordsLeft(); private: bool bboard[SZ][SZ]; char mainboard[SZ][SZ]; int oboard[SZ][SZ]; vector<Word> words; Word nextWord; int nextWordPos; vector<string> awords; vector<string> swords; };
[ "ndowney@student12.cse.nd.edu" ]
ndowney@student12.cse.nd.edu
221e74256591a93e0bb9aaed4e9e3d6bb1eadbe3
9a9e511d4881edaa293b6378e3f81ab853fa8b31
/src/libs/gui/swfruntime/utils.cpp
a28730ceae422f2d74ea69b22bdf544339a68c64
[]
no_license
DeanoC/old_yolk
d14a4c02da1841f83e919915bd62bfd51d6a309b
3d413320c2a0e53e3ddc9c76a801b5b91abe2028
refs/heads/master
2021-07-14T02:17:44.062551
2017-08-01T16:17:31
2017-08-01T16:17:31
208,746,200
0
0
null
2020-10-13T16:04:18
2019-09-16T08:15:54
C++
UTF-8
C++
false
false
1,145
cpp
// // SwfRuntimeUtils.cpp // Projects // // Created by Deano on 2008-09-27. // Copyright 2012 Cloud Pixies Ltd. All rights reserved. // #include "swfruntime.h" #include "gui/swfparser/SwfMatrix.h" #include "gui/swfparser/SwfColourTransform.h" #include "utils.h" namespace Swf { Math::Matrix4x4 Convert(const SwfMatrix* _matrix) { return Math::Matrix4x4( _matrix->scaleX, _matrix->rotateSkew0, 0, 0, _matrix->rotateSkew1, _matrix->scaleY, 0, 0, 0, 0, 1, 0, _matrix->translateX, _matrix->translateY, 0, 1 ); } Math::Matrix4x4 Convert(const SwfColourTransform* _ct) { return Math::Matrix4x4( _ct->mul[0], _ct->mul[1], _ct->mul[2], _ct->mul[3], _ct->add[0], _ct->add[1], _ct->add[2], _ct->add[3], 0, 0, 0, 0, 0, 0, 0, 0 ); } std::string ToLowerIfReq( const std::string& _name, bool _isCaseSensitive ) { if( _isCaseSensitive == false ) { std::string str = _name; std::transform(str.begin(), str.end(), str.begin(), tolower); return str; } else { return _name; } } } /* Swf */
[ "deano@cloudpixies.com" ]
deano@cloudpixies.com