text
stringlengths
1
1.05M
#include "HandleImageProcessing.h" namespace AI::ImageProcessing { template <typename T> void HandleImageProcessing<T>::processImage(T& args) { processEvent(this, args); } }
; A317365: Expansion of e.g.f. x*exp(x/(1 + x))/(1 + x). ; Submitted by Jon Maiga ; 0,1,0,-3,16,-75,336,-1295,1632,55881,-1124000,16722981,-229985040,3089923837,-41225160144,545880027225,-7069180940864,86130735547665,-882387869940288,3847692639294541,171852333163131600,-8392137456287472699,276055495385982856720,-8067943451470397940543,224666536903711496226336,-6126204075374030378366375,165628188414755622842815776,-4464737416811763757595054475,120187778051758944757778237872,-3226041332245478531041669507059,85930178097639863374156099906800,-2249870849629863945484628034234839 mov $2,18 mov $3,$0 lpb $3 mul $1,$4 mul $2,$3 add $1,$2 sub $4,1 add $5,1 div $2,$5 sub $3,1 lpe mov $0,$1 div $0,18
; A195013: Multiples of 2 and of 3 interleaved: a(2n-1) = 2n, a(2n) = 3n. ; 2,3,4,6,6,9,8,12,10,15,12,18,14,21,16,24,18,27,20,30,22,33,24,36,26,39,28,42,30,45,32,48,34,51,36,54,38,57,40,60,42,63,44,66,46,69,48,72,50,75,52,78,54,81,56,84,58,87,60,90,62,93,64,96,66,99,68,102,70,105,72,108,74,111,76,114,78,117,80,120,82,123,84,126,86,129,88,132,90,135,92,138,94,141,96,144,98,147,100,150,102,153,104,156,106,159,108,162,110,165,112,168,114,171,116,174,118,177,120,180,122,183,124,186,126,189,128,192,130,195,132,198,134,201,136,204,138,207,140,210,142,213,144,216,146,219,148,222,150,225,152,228,154,231,156,234,158,237,160,240,162,243,164,246,166,249,168,252,170,255,172,258,174,261,176,264,178,267,180,270,182,273,184,276,186,279,188,282,190,285,192,288,194,291,196,294,198,297,200,300,202,303,204,306,206,309,208,312,210,315,212,318,214,321,216,324,218,327,220,330,222,333,224,336,226,339,228,342,230,345,232,348,234,351,236,354,238,357,240,360,242,363,244,366,246,369,248,372,250,375 mov $1,$0 dif $0,2 div $1,2 add $1,$0 add $1,2
// Copyright (C) 2000-2017 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ 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, 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 this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 27.8.1.10 ofstream member functions // @require@ %-*.tst // @diff@ %-*.tst %-*.txt // { dg-require-fileio "" } #include <ostream> #include <fstream> #include <testsuite_hooks.h> const char name_01[] = "ofstream_members-1.tst"; const char name_02[] = "ofstream_members-1.txt"; // http://gcc.gnu.org/ml/libstdc++/2000-06/msg00136.html void test01() { std::ofstream ofs1; ofs1.close(); // false as expected: VERIFY( !ofs1.is_open() ); // this is now true: VERIFY( !(ofs1) ); ofs1.open(name_02); VERIFY( ofs1.is_open() ); // As per the resolution of DR 409. VERIFY( (ofs1) ); VERIFY( ofs1.rdstate() == std::ios_base::goodbit ); ofs1.close(); } int main() { test01(); return 0; }
/* * Timer_counter_0.inc * * Date: 09.01.2016 15:58:11 * Author: Borko Rajkovic */ ; Timer/Counter0 Init TC0_INIT: ldi tmpReg, (1<<WGM01)|(5<<CS00) ; Setup existing clock prescaler to 1024 (CS02:00) and Waveform Generation Mode to WGM01 - CTC out TCCR0, tmpReg ; (Clear Timer on Compare), so counter will reset to 0 on interrupt in tmpReg, TIMSK ; Take existing TIMSK ori tmpReg, (1<<OCIE0) ; Logical or with OCIE0 out TIMSK, tmpReg ; Turn on Output Compare Interrupt Enable ldi tmpReg, 0x08 ; We want to count 1ms out OCR0, tmpReg ; 8MHz/1024(prescaler)=7812 ticks per second ; 1ms = 7812/1000 = 7.8 ~ 8 ticks ldi tmpReg, 0x00 ; We reset counter manually (this is not critical, since it shouldn't count much up to here) out TCNT0, tmpReg ret
#include <graphene/chain/contract_object.hpp> #include <graphene/chain/contract_function_register_scheduler.hpp> namespace graphene { namespace chain { bool register_scheduler::is_owner() { return caller == contract.owner; } void register_scheduler::set_permissions_flag(bool flag) { try { FC_ASSERT(is_owner(), "You`re not the contract`s owner"); contract_id_type db_index = contract.id; db.modify(db_index(db), [&](contract_object &co) { co.check_contract_authority = flag; }); } catch (fc::exception e) { LUA_C_ERR_THROW(this->context.mState,e.to_string()); } }; void register_scheduler::set_invoke_percent(double percent) { try { FC_ASSERT(is_owner(), "You`re not the contract`s owner"); contract_id_type db_index = contract.id; db.modify(db_index(db), [&](contract_object &co) { co.user_invoke_share_percent = percent; }); } catch (fc::exception e) { LUA_C_ERR_THROW(this->context.mState,e.to_string()); } }; void register_scheduler::set_invoke_share_percent(double percent) { try { bool not_in_range = false; if((percent>=0)&&(percent<=100)) not_in_range=true; FC_ASSERT(not_in_range,"percent should be in range 0-100 "); FC_ASSERT(is_owner(), "You`re not the contract`s owner"); contract_id_type db_index = contract.id; db.modify(db_index(db), [&](contract_object &co) { co.user_invoke_share_percent = percent; }); } catch (fc::exception e) { LUA_C_ERR_THROW(this->context.mState,e.to_string()); } }; void register_scheduler::change_contract_authority(string authority) { try { FC_ASSERT(is_owner(), "You`re not the contract`s owner"); auto new_authority= public_key_type(authority); contract_id_type db_index = contract.id; db.modify(db_index(db), [&](contract_object &co) { co.contract_authority = new_authority; }); } catch (fc::exception e) { LUA_C_ERR_THROW(this->context.mState,e.to_string()); } } } // namespace chain } // namespace graphene
#include "pyhelp.h" // include first to avoid annoying redef warning #include "history.h" namespace py = pybind11; PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>) namespace neml { PYBIND11_MODULE(history, m) { m.doc() = "Internal variable tracking system."; py::class_<History, std::shared_ptr<History>>(m, "History", py::buffer_protocol()) .def(py::init<>()) .def(py::init<bool>(), py::arg("store")) .def_buffer( [](History & m) -> py::buffer_info { return py::buffer_info( m.rawptr(), sizeof(double), py::format_descriptor<double>::format(), 1, {m.size()}, {sizeof(double)}); }) .def("deepcopy", &History::deepcopy) .def("set_data", [](History & m, py::array_t<double> arr) { m.set_data(arr2ptr<double>(arr)); }, "Set data as a numpy array") .def("copy_data", [](History & m, py::array_t<double> arr) { m.copy_data(arr2ptr<double>(arr)); }, "Copy data in from an array") .def_property_readonly("size", &History::size) .def_property_readonly("store", &History::store) .def_property_readonly("items", &History::items) .def("add_scalar", [](History & m, std::string name) { m.add<double>(name); }, "Add a scalar") .def("get_scalar", [](History & m, std::string name) -> double { return m.get<double>(name); }, "Get a scalar") .def("set_scalar", [](History & m, std::string name, double value) { m.get<double>(name) = value; }, "Set a scalar") .def("add_vector", [](History & m, std::string name) { m.add<Vector>(name); }, "Add a vector") .def("get_vector", [](History & m, std::string name) -> Vector { return m.get<Vector>(name); }, "Get a vector") .def("set_vector", [](History & m, std::string name, Vector v) { m.get<Vector>(name) = v; }, "Set a vector") .def("add_ranktwo", [](History & m, std::string name) { m.add<RankTwo>(name); }, "Add a vector") .def("get_ranktwo", [](History & m, std::string name) -> RankTwo { return m.get<RankTwo>(name); }, "Get a general tensor") .def("set_ranktwo", [](History & m, std::string name, RankTwo v) { m.get<RankTwo>(name) = v; }, "Set a general tensor") .def("add_symmetric", [](History & m, std::string name) { m.add<Symmetric>(name); }, "Add a vector") .def("get_symmetric", [](History & m, std::string name) -> Symmetric { return m.get<Symmetric>(name); }, "Get a symmetric tensor") .def("set_symmetric", [](History & m, std::string name, Symmetric v) { m.get<Symmetric>(name) = v; }, "Set a symmetric tensor") .def("add_skew", [](History & m, std::string name) { m.add<Skew>(name); }, "Add a skew") .def("get_skew", [](History & m, std::string name) -> Skew { return m.get<Skew>(name); }, "Get a skew tensor") .def("set_skew", [](History & m, std::string name, Skew v) { m.get<Skew>(name) = v; }, "Set a skew") .def("add_orientation", [](History & m, std::string name) { m.add<Orientation>(name); }, "Add an orientation") .def("get_orientation", [](History & m, std::string name) -> Orientation { return m.get<Orientation>(name); }, "Get an orientation") .def("set_orientation", [](History & m, std::string name, Orientation v) { m.get<Orientation>(name) = v; }, "Set an orientation") .def("scalar_multiply", &History::scalar_multiply) .def(py::self += py::self) .def("zero", &History::zero) .def("split", &History::split, py::arg("group"), py::arg("after") = true) .def("add_union", &History::add_union) .def("contains", &History::contains) ; } } // namespace neml
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you mPrimitiveFields.may not use this file except in compliance with the License. * You mPrimitiveFields.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 "RenderProperties.h" #include <utils/Trace.h> #include <SkColorFilter.h> #include <SkMatrix.h> #include <SkPath.h> #include <SkPathOps.h> #include "Matrix.h" #include "hwui/Canvas.h" #include "utils/MathUtils.h" namespace android { namespace uirenderer { LayerProperties::LayerProperties() { reset(); } LayerProperties::~LayerProperties() { setType(LayerType::None); } void LayerProperties::reset() { mOpaque = false; setFromPaint(nullptr); } bool LayerProperties::setColorFilter(SkColorFilter* filter) { if (mColorFilter.get() == filter) return false; mColorFilter = sk_ref_sp(filter); return true; } bool LayerProperties::setFromPaint(const SkPaint* paint) { bool changed = false; changed |= setAlpha(static_cast<uint8_t>(PaintUtils::getAlphaDirect(paint))); changed |= setXferMode(PaintUtils::getBlendModeDirect(paint)); changed |= setColorFilter(paint ? paint->getColorFilter() : nullptr); return changed; } LayerProperties& LayerProperties::operator=(const LayerProperties& other) { setType(other.type()); setOpaque(other.opaque()); setAlpha(other.alpha()); setXferMode(other.xferMode()); setColorFilter(other.getColorFilter()); return *this; } RenderProperties::ComputedFields::ComputedFields() : mTransformMatrix(nullptr) {} RenderProperties::ComputedFields::~ComputedFields() { delete mTransformMatrix; } RenderProperties::RenderProperties() : mStaticMatrix(nullptr), mAnimationMatrix(nullptr) {} RenderProperties::~RenderProperties() { delete mStaticMatrix; delete mAnimationMatrix; } RenderProperties& RenderProperties::operator=(const RenderProperties& other) { if (this != &other) { mPrimitiveFields = other.mPrimitiveFields; setStaticMatrix(other.getStaticMatrix()); setAnimationMatrix(other.getAnimationMatrix()); setCameraDistance(other.getCameraDistance()); mLayerProperties = other.layerProperties(); // Force recalculation of the matrix, since other's dirty bit may be clear mPrimitiveFields.mMatrixOrPivotDirty = true; updateMatrix(); } return *this; } static void dumpMatrix(std::ostream& output, std::string& indent, const char* label, SkMatrix* matrix) { if (matrix) { output << indent << "(" << label << " " << matrix << ": "; output << std::fixed << std::setprecision(2); output << "[" << matrix->get(0) << " " << matrix->get(1) << " " << matrix->get(2) << "]"; output << " [" << matrix->get(3) << " " << matrix->get(4) << " " << matrix->get(5) << "]"; output << " [" << matrix->get(6) << " " << matrix->get(7) << " " << matrix->get(8) << "]"; output << ")" << std::endl; } } void RenderProperties::debugOutputProperties(std::ostream& output, const int level) const { auto indent = std::string(level * 2, ' '); if (mPrimitiveFields.mLeft != 0 || mPrimitiveFields.mTop != 0) { output << indent << "(Translate (left, top) " << mPrimitiveFields.mLeft << ", " << mPrimitiveFields.mTop << ")" << std::endl; } dumpMatrix(output, indent, "ConcatMatrix (static)", mStaticMatrix); dumpMatrix(output, indent, "ConcatMatrix (animation)", mAnimationMatrix); output << std::fixed << std::setprecision(2); if (hasTransformMatrix()) { if (isTransformTranslateOnly()) { output << indent << "(Translate " << getTranslationX() << ", " << getTranslationY() << ", " << getZ() << ")" << std::endl; } else { dumpMatrix(output, indent, "ConcatMatrix ", mComputedFields.mTransformMatrix); } } const bool isLayer = effectiveLayerType() != LayerType::None; int clipFlags = getClippingFlags(); if (mPrimitiveFields.mAlpha < 1 && !MathUtils::isZero(mPrimitiveFields.mAlpha)) { if (isLayer) { clipFlags &= ~CLIP_TO_BOUNDS; // bounds clipping done by layer } if (CC_LIKELY(isLayer || !getHasOverlappingRendering())) { // simply scale rendering content's alpha output << indent << "(ScaleAlpha " << mPrimitiveFields.mAlpha << ")" << std::endl; } else { // savelayeralpha to create an offscreen buffer to apply alpha Rect layerBounds(0, 0, getWidth(), getHeight()); if (clipFlags) { getClippingRectForFlags(clipFlags, &layerBounds); clipFlags = 0; // all clipping done by savelayer } output << indent << "(SaveLayerAlpha " << (int)layerBounds.left << ", " << (int)layerBounds.top << ", " << (int)layerBounds.right << ", " << (int)layerBounds.bottom << ", " << (int)(mPrimitiveFields.mAlpha * 255) << ", 0x" << std::hex << (SaveFlags::HasAlphaLayer | SaveFlags::ClipToLayer) << ")" << std::dec << std::endl; } } if (clipFlags) { Rect clipRect; getClippingRectForFlags(clipFlags, &clipRect); output << indent << "(ClipRect " << (int)clipRect.left << ", " << (int)clipRect.top << ", " << (int)clipRect.right << ", " << (int)clipRect.bottom << ")" << std::endl; } if (getRevealClip().willClip()) { Rect bounds; getRevealClip().getBounds(&bounds); output << indent << "(Clip to reveal clip with bounds " << bounds.left << ", " << bounds.top << ", " << bounds.right << ", " << bounds.bottom << ")" << std::endl; } auto& outline = mPrimitiveFields.mOutline; if (outline.getShouldClip()) { if (outline.isEmpty()) { output << indent << "(Clip to empty outline)"; } else if (outline.willClip()) { const Rect& bounds = outline.getBounds(); output << indent << "(Clip to outline with bounds " << bounds.left << ", " << bounds.top << ", " << bounds.right << ", " << bounds.bottom << ")" << std::endl; } } } void RenderProperties::updateMatrix() { if (mPrimitiveFields.mMatrixOrPivotDirty) { if (!mComputedFields.mTransformMatrix) { // only allocate a mPrimitiveFields.matrix if we have a complex transform mComputedFields.mTransformMatrix = new SkMatrix(); } if (!mPrimitiveFields.mPivotExplicitlySet) { mPrimitiveFields.mPivotX = mPrimitiveFields.mWidth / 2.0f; mPrimitiveFields.mPivotY = mPrimitiveFields.mHeight / 2.0f; } SkMatrix* transform = mComputedFields.mTransformMatrix; transform->reset(); if (MathUtils::isZero(getRotationX()) && MathUtils::isZero(getRotationY())) { transform->setTranslate(getTranslationX(), getTranslationY()); transform->preRotate(getRotation(), getPivotX(), getPivotY()); transform->preScale(getScaleX(), getScaleY(), getPivotX(), getPivotY()); } else { SkMatrix transform3D; mComputedFields.mTransformCamera.save(); transform->preScale(getScaleX(), getScaleY(), getPivotX(), getPivotY()); mComputedFields.mTransformCamera.rotateX(mPrimitiveFields.mRotationX); mComputedFields.mTransformCamera.rotateY(mPrimitiveFields.mRotationY); mComputedFields.mTransformCamera.rotateZ(-mPrimitiveFields.mRotation); mComputedFields.mTransformCamera.getMatrix(&transform3D); transform3D.preTranslate(-getPivotX(), -getPivotY()); transform3D.postTranslate(getPivotX() + getTranslationX(), getPivotY() + getTranslationY()); transform->postConcat(transform3D); mComputedFields.mTransformCamera.restore(); } mPrimitiveFields.mMatrixOrPivotDirty = false; } } } /* namespace uirenderer */ } /* namespace android */
; A007334: Number of spanning trees in the graph K_{n}/e, which results from contracting an edge e in the complete graph K_{n} on n vertices (for n>=2). ; 1,2,8,50,432,4802,65536,1062882,20000000,428717762,10319560704,275716983698,8099130339328,259492675781250,9007199254740992,336755653118801858,13493281232954916864,576882827135242335362,26214400000000000000000 mov $2,$0 add $0,2 sub $2,1 pow $0,$2 mul $0,2 trn $0,1 add $0,1
// license:BSD-3-Clause // copyright-holders:Mike Balfour /************************************************************************* audio\bsktball.c *************************************************************************/ #include "emu.h" #include "includes/bsktball.h" #include "sound/discrete.h" /*************************************************************************** Sound handlers ***************************************************************************/ void bsktball_state::bsktball_bounce_w(uint8_t data) { m_discrete->write(BSKTBALL_CROWD_DATA, data & 0x0f); // Crowd m_discrete->write(BSKTBALL_BOUNCE_EN, data & 0x10); // Bounce } void bsktball_state::bsktball_note_w(uint8_t data) { m_discrete->write(BSKTBALL_NOTE_DATA, data); // Note } /************************************************************************/ /* bsktball Sound System Analog emulation */ /************************************************************************/ static const discrete_lfsr_desc bsktball_lfsr = { DISC_CLK_IS_FREQ, 16, /* Bit Length */ 0, /* Reset Value */ 0, /* Use Bit 0 as XOR input 0 */ 14, /* Use Bit 14 as XOR input 1 */ DISC_LFSR_XNOR, /* Feedback stage1 is XNOR */ DISC_LFSR_OR, /* Feedback stage2 is just stage 1 output OR with external feed */ DISC_LFSR_REPLACE, /* Feedback stage3 replaces the shifted register contents */ 0x000001, /* Everything is shifted into the first bit only */ 0, /* Output is already inverted by XNOR */ 15 /* Output bit */ }; static const discrete_dac_r1_ladder bsktball_crowd_r1_ladder = { 4, {RES_K(390), RES_K(220), RES_K(100), RES_K(56)}, // r55, r54, r53, r52 0, 0, // no bias RES_K(1), // r21 CAP_U(0.1) // c32 }; static const discrete_op_amp_filt_info bsktball_crowd_filt = { 1.0/(1.0/RES_K(390) + 1.0/RES_K(220) + 1.0/RES_K(100) + 1.0/RES_K(56) + 1.0/RES_K(1)), // r55, r54, r53, r52, r21 0, 0, 0, RES_K(330), // r58 CAP_U(.01), // c55 CAP_U(.022), // c56 0, 5, 12, 0 }; static const discrete_mixer_desc bsktball_mixer = { DISC_MIXER_IS_OP_AMP, {RES_K(47), RES_K(47), RES_K(220)}, // r56, r57, r60 {0}, // no rNodes {CAP_U(.01), CAP_U(.01), CAP_U(.01)}, // c53, c54, c57 0, RES_K(47), // r61 CAP_U(.001), // c58 CAP_U(1), 5, 7500 }; #define BSKTBALL_32H 12096000.0/4/32 #define BSKTBALL_256H 12096000.0/768 /* Nodes - Sounds */ #define BSKTBALL_NOISE NODE_10 #define BSKTBALL_BOUNCE_SND BSKTBALL_BOUNCE_EN #define BSKTBALL_NOTE_SND NODE_12 #define BSKTBALL_CROWD_SND NODE_13 DISCRETE_SOUND_START(bsktball_discrete) /************************************************/ /* Input register mapping for bsktball */ /************************************************/ /* NODE GAIN OFFSET INIT */ DISCRETE_INPUT_DATA (BSKTBALL_NOTE_DATA) DISCRETE_INPUT_DATA (BSKTBALL_CROWD_DATA) /* Bounce is a trigger fed directly to the amp */ DISCRETE_INPUTX_LOGIC(BSKTBALL_BOUNCE_EN, DEFAULT_TTL_V_LOGIC_1, 0, 0.0) DISCRETE_INPUT_NOT (BSKTBALL_NOISE_EN) /************************************************/ /* Crowd effect is variable amplitude, filtered */ /* random noise. */ /* LFSR clk = 256H = 15750.0Hz */ /************************************************/ DISCRETE_LFSR_NOISE(BSKTBALL_NOISE, BSKTBALL_NOISE_EN, BSKTBALL_NOISE_EN, BSKTBALL_256H, 1, 0, .5, &bsktball_lfsr) DISCRETE_SWITCH(NODE_20, 1, BSKTBALL_NOISE, 0, BSKTBALL_CROWD_DATA) // enable data, gate D11 DISCRETE_DAC_R1(NODE_21, NODE_20, DEFAULT_TTL_V_LOGIC_1, &bsktball_crowd_r1_ladder) DISCRETE_OP_AMP_FILTER(BSKTBALL_CROWD_SND, 1, NODE_21, 0, DISC_OP_AMP_FILTER_IS_BAND_PASS_1M, &bsktball_crowd_filt) /************************************************/ /* Note sound is created by a divider circuit. */ /* The master clock is the 32H signal, which is */ /* 12.096MHz/128. This is then sent to a */ /* preloadable 8 bit counter, which loads the */ /* value from OUT30 when overflowing from 0xFF */ /* to 0x00. Therefore it divides by 2 (OUT30 */ /* = FE) to 256 (OUT30 = 00). */ /* There is also a final /2 stage. */ /* Note that there is no music disable line. */ /* When there is no music, the game sets the */ /* oscillator to 0Hz. (OUT30 = FF) */ /************************************************/ DISCRETE_NOTE(NODE_30, 1, BSKTBALL_32H, BSKTBALL_NOTE_DATA, 255, 1, DISC_CLK_IS_FREQ | DISC_OUT_IS_ENERGY) DISCRETE_GAIN(BSKTBALL_NOTE_SND, NODE_30, DEFAULT_TTL_V_LOGIC_1) /************************************************/ /* Mixing stage - B11 */ /************************************************/ DISCRETE_MIXER3(NODE_90, 1, BSKTBALL_NOTE_SND, BSKTBALL_BOUNCE_SND, BSKTBALL_CROWD_SND, &bsktball_mixer) DISCRETE_OUTPUT(NODE_90, 1) DISCRETE_SOUND_END
# # Test for instructions XTR, NTR, RТЕ, UZA, U1A, УТА. # org 1 lbl start vtm ws+1,15 ita 0 vtm 0o77,2 vtm -63,3 # 1-64 lbl loop ntr 0,2 rte 0o77 atx ws its 2 asn 23 # 64-41 aex 0,15 uia fail uia fail xtr 0 rte 0o77 # С некоторых пор команда RTE уставливает логическую группу. # uza fail # aox uia fail xtr ws rte 0o77 its 2 asn 23 # 64-41 aex 0,15 uia fail uia fail # vtm ws+1,15 xtr 0,15 vtm mst,15 rte 0o77 its 2 asn 23 # 64-41 aex 0,15 uia fail utm -1,2 vlm loop,3 # ntr 0o77 rte 0o41 aex b2040000000000000 uia fail ntr 0 uza fail lbl a uia ok uj fail lbl ok ntr 7 # логическая группа uia fail ntr 11 # группа умножения uza fail aox 0 uia fail ntr 19 # группа сложения uia fail xta cful uza fail ntr 11 uia fail ntr 19 uza fail # ntr 24 # гс+гу = гс uza fail ntr 12 # гу+гл = гу uia fail xta b1 # =b'1' ntr 20 # гс+гл = гс uia fail xta cful aex 0 xta 0 yta 0 aex cful uia fail arx 0 # должна uza fail # получиться arx cful # группа умножения uia fail aax cful # логическая группа uza fail # lbl align xta 0 ntr 0o77 # ставим R = 077 atx ws # не меняет R rte 0o77 # читаем R aex b3740000000000000 # =b'3740000000000000' uia fail # ждём единицы в порядке # lbl align2 xta cful ntr 0 # нет группы xta 0 # левая команда uza align3 # проверяем логическую группу uj fail # lbl align3 ntr 0 # нет группы xta 0 # правая команда uza pass # проверяем логическую группу # lbl fail stop 0o76543,2 lbl pass stop 0o12345,6 #------------------------- dorg 0o2000 # данные с адреса 2000 arr b3740000000000000 0o3740000000000000 arr b1 0o1 arr b2040000000000000 0o2040000000000000 arr cful 0o7777777777777777 mem mst 40 mem ws 1030
; $Id: bit_close.asm,v 1.3 2016-06-16 19:33:59 dom Exp $ ; ; VG-5000 1 bit sound functions ; ; void bit_click(); ; ; Stefano Bodrato - 2014 ; SECTION code_clib PUBLIC bit_close PUBLIC _bit_close .bit_close ._bit_close ret
Name: zel_ram.asm Type: file Size: 65428 Last-Modified: '2016-05-13T04:36:32Z' SHA-1: A398140B1961450E04B70E7B2C9DFDA113D0CD6C Description: null
; A158638: a(n) = 48*n^2 + 1. ; 1,49,193,433,769,1201,1729,2353,3073,3889,4801,5809,6913,8113,9409,10801,12289,13873,15553,17329,19201,21169,23233,25393,27649,30001,32449,34993,37633,40369,43201,46129,49153,52273,55489,58801,62209,65713,69313,73009,76801,80689,84673,88753,92929,97201,101569,106033,110593,115249,120001,124849,129793,134833,139969,145201,150529,155953,161473,167089,172801,178609,184513,190513,196609,202801,209089,215473,221953,228529,235201,241969,248833,255793,262849,270001,277249,284593,292033,299569,307201,314929,322753,330673,338689,346801,355009,363313,371713,380209,388801,397489,406273,415153,424129,433201,442369,451633,460993,470449,480001,489649,499393,509233,519169,529201,539329,549553,559873,570289,580801,591409,602113,612913,623809,634801,645889,657073,668353,679729,691201,702769,714433,726193,738049,750001,762049,774193,786433,798769,811201,823729,836353,849073,861889,874801,887809,900913,914113,927409,940801,954289,967873,981553,995329,1009201,1023169,1037233,1051393,1065649,1080001,1094449,1108993,1123633,1138369,1153201,1168129,1183153,1198273,1213489,1228801,1244209,1259713,1275313,1291009,1306801,1322689,1338673,1354753,1370929,1387201,1403569,1420033,1436593,1453249,1470001,1486849,1503793,1520833,1537969,1555201,1572529,1589953,1607473,1625089,1642801,1660609,1678513,1696513,1714609,1732801,1751089,1769473,1787953,1806529,1825201,1843969,1862833,1881793,1900849,1920001,1939249,1958593,1978033,1997569,2017201,2036929,2056753,2076673,2096689,2116801,2137009,2157313,2177713,2198209,2218801,2239489,2260273,2281153,2302129,2323201,2344369,2365633,2386993,2408449,2430001,2451649,2473393,2495233,2517169,2539201,2561329,2583553,2605873,2628289,2650801,2673409,2696113,2718913,2741809,2764801,2787889,2811073,2834353,2857729,2881201,2904769,2928433,2952193,2976049 mov $1,$0 pow $1,2 mul $1,48 add $1,1
; =============================================================== ; Mar 2014 ; =============================================================== ; ; ba_stack_t *ba_stack_init(void *p, void *data, size_t capacity) ; ; Initialize a byte array stack structure at address p and set the ; stack's initial data and capacity members. stack.size = 0 ; ; =============================================================== SECTION code_adt_ba_stack PUBLIC asm_ba_stack_init EXTERN asm_b_array_init defc asm_ba_stack_init = asm_b_array_init ; enter : hl = p ; de = data ; bc = capacity ; ; exit : hl = stack * = p ; ; uses : af
/*++ Copyright (c) 2013 Microsoft Corporation Module Name: opt_context.cpp Abstract: Facility for running optimization problem. Author: Anh-Dung Phan (t-anphan) 2013-10-16 Notes: --*/ #include "util/gparams.h" #include "ast/for_each_expr.h" #include "ast/ast_pp.h" #include "ast/bv_decl_plugin.h" #include "ast/pb_decl_plugin.h" #include "ast/ast_smt_pp.h" #include "ast/ast_pp_util.h" #include "ast/display_dimacs.h" #include "model/model_smt2_pp.h" #include "tactic/goal.h" #include "tactic/tactic.h" #include "tactic/arith/lia2card_tactic.h" #include "tactic/core/solve_eqs_tactic.h" #include "tactic/core/simplify_tactic.h" #include "tactic/core/propagate_values_tactic.h" #include "tactic/core/solve_eqs_tactic.h" #include "tactic/core/elim_uncnstr_tactic.h" #include "tactic/tactical.h" #include "tactic/arith/card2bv_tactic.h" #include "tactic/arith/eq2bv_tactic.h" #include "tactic/bv/dt2bv_tactic.h" #include "tactic/generic_model_converter.h" #include "ackermannization/ackermannize_bv_tactic.h" #include "sat/sat_solver/inc_sat_solver.h" #include "sat/sat_params.hpp" #include "opt/opt_context.h" #include "opt/opt_solver.h" #include "opt/opt_params.hpp" namespace opt { void context::scoped_state::push() { m_asms_lim.push_back(m_asms.size()); m_hard_lim.push_back(m_hard.size()); m_objectives_lim.push_back(m_objectives.size()); m_objectives_term_trail_lim.push_back(m_objectives_term_trail.size()); } void context::scoped_state::pop() { m_hard.resize(m_hard_lim.back()); m_asms.resize(m_asms_lim.back()); unsigned k = m_objectives_term_trail_lim.back(); while (m_objectives_term_trail.size() > k) { unsigned idx = m_objectives_term_trail.back(); m_objectives[idx].m_terms.pop_back(); m_objectives[idx].m_weights.pop_back(); m_objectives_term_trail.pop_back(); } m_objectives_term_trail_lim.pop_back(); k = m_objectives_lim.back(); while (m_objectives.size() > k) { objective& obj = m_objectives.back(); if (obj.m_type == O_MAXSMT) { m_indices.erase(obj.m_id); } m_objectives.pop_back(); } m_objectives_lim.pop_back(); m_hard_lim.pop_back(); m_asms_lim.pop_back(); } void context::scoped_state::add(expr* hard) { m_hard.push_back(hard); } bool context::scoped_state::set(expr_ref_vector const & hard) { bool eq = hard.size() == m_hard.size(); for (unsigned i = 0; eq && i < hard.size(); ++i) { eq = hard.get(i) == m_hard.get(i); } m_hard.reset(); m_hard.append(hard); return !eq; } unsigned context::scoped_state::add(expr* f, rational const& w, symbol const& id) { if (!m.is_bool(f)) { throw default_exception("Soft constraint should be Boolean"); } if (!m_indices.contains(id)) { m_objectives.push_back(objective(m, id)); m_indices.insert(id, m_objectives.size() - 1); } SASSERT(m_indices.contains(id)); unsigned idx = m_indices[id]; if (!w.is_zero()) { m_objectives[idx].m_terms.push_back(f); m_objectives[idx].m_weights.push_back(w); m_objectives_term_trail.push_back(idx); } return idx; } unsigned context::scoped_state::add(app* t, bool is_max) { app_ref tr(t, m); if (!m_bv.is_bv(t) && !m_arith.is_int_real(t)) { throw default_exception("Objective must be bit-vector, integer or real"); } unsigned index = m_objectives.size(); m_objectives.push_back(objective(is_max, tr, index)); return index; } context::context(ast_manager& m): m(m), m_arith(m), m_bv(m), m_hard_constraints(m), m_solver(nullptr), m_pareto1(false), m_box_index(UINT_MAX), m_optsmt(m, *this), m_scoped_state(m), m_fm(alloc(generic_model_converter, m, "opt")), m_model_fixed(), m_objective_refs(m), m_core(m), m_enable_sat(false), m_is_clausal(false), m_pp_neat(false), m_unknown("unknown") { params_ref p; p.set_bool("model", true); p.set_bool("unsat_core", true); p.set_bool("elim_to_real", true); updt_params(p); m_model_counter = 0; } context::~context() { reset_maxsmts(); } void context::reset_maxsmts() { for (auto& kv : m_maxsmts) { dealloc(kv.m_value); } m_maxsmts.reset(); } void context::push() { m_scoped_state.push(); } void context::pop(unsigned n) { n = std::min(n, m_scoped_state.num_scopes()); for (unsigned i = 0; i < n; ++i) { m_scoped_state.pop(); } clear_state(); reset_maxsmts(); m_optsmt.reset(); m_hard_constraints.reset(); } void context::get_labels(svector<symbol> & r) { r.append(m_labels); } void context::get_unsat_core(expr_ref_vector & r) { r.append(m_core); } void context::set_hard_constraints(expr_ref_vector const& fmls) { if (m_scoped_state.set(fmls)) { clear_state(); } } void context::add_hard_constraint(expr* f) { m_scoped_state.add(f); clear_state(); } void context::add_hard_constraint(expr* f, expr* t) { m_scoped_state.m_asms.push_back(t); m_scoped_state.add(m.mk_implies(t, f)); clear_state(); } void context::get_hard_constraints(expr_ref_vector& hard) { hard.append(m_scoped_state.m_hard); } expr_ref context::get_objective(unsigned i) { SASSERT(i < num_objectives()); objective const& o = m_scoped_state.m_objectives[i]; expr_ref result(m), zero(m); expr_ref_vector args(m); switch (o.m_type) { case O_MAXSMT: zero = m_arith.mk_numeral(rational(0), false); for (unsigned i = 0; i < o.m_terms.size(); ++i) { args.push_back(m.mk_ite(o.m_terms[i], zero, m_arith.mk_numeral(o.m_weights[i], false))); } result = m_arith.mk_add(args.size(), args.c_ptr()); break; case O_MAXIMIZE: result = o.m_term; if (m_arith.is_int_real(result)) { result = m_arith.mk_uminus(result); } else if (m_bv.is_bv(result)) { result = m_bv.mk_bv_neg(result); } else { UNREACHABLE(); } break; case O_MINIMIZE: result = o.m_term; break; } return result; } unsigned context::add_soft_constraint(expr* f, rational const& w, symbol const& id) { clear_state(); return m_scoped_state.add(f, w, id); } unsigned context::add_objective(app* t, bool is_max) { clear_state(); return m_scoped_state.add(t, is_max); } void context::import_scoped_state() { m_optsmt.reset(); reset_maxsmts(); m_objectives.reset(); m_hard_constraints.reset(); scoped_state& s = m_scoped_state; for (unsigned i = 0; i < s.m_objectives.size(); ++i) { objective& obj = s.m_objectives[i]; m_objectives.push_back(obj); if (obj.m_type == O_MAXSMT) { add_maxsmt(obj.m_id, i); } } m_hard_constraints.append(s.m_hard); } lbool context::optimize(expr_ref_vector const& _asms) { if (m_pareto) { return execute_pareto(); } if (m_box_index != UINT_MAX) { return execute_box(); } clear_state(); init_solver(); import_scoped_state(); expr_ref_vector asms(_asms); asms.append(m_scoped_state.m_asms); normalize(asms); if (m_hard_constraints.size() == 1 && m.is_false(m_hard_constraints.get(0))) { return l_false; } internalize(); update_solver(); if (contains_quantifiers()) { warning_msg("optimization with quantified constraints is not supported"); } #if 0 if (is_qsat_opt()) { return run_qsat_opt(); } #endif solver& s = get_solver(); s.assert_expr(m_hard_constraints); opt_params optp(m_params); symbol pri = optp.priority(); IF_VERBOSE(1, verbose_stream() << "(optimize:check-sat)\n"); lbool is_sat = s.check_sat(asms.size(),asms.c_ptr()); TRACE("opt", s.display(tout << "initial search result: " << is_sat << "\n");); if (is_sat != l_false) { s.get_model(m_model); s.get_labels(m_labels); model_updated(m_model.get()); if (!m_model) { is_sat = l_undef; } } if (is_sat != l_true) { TRACE("opt", tout << m_hard_constraints << " " << asms << "\n";); if (!asms.empty()) { s.get_unsat_core(m_core); } return is_sat; } s.assert_expr(asms); IF_VERBOSE(1, verbose_stream() << "(optimize:sat)\n"); TRACE("opt", model_smt2_pp(tout, m, *m_model, 0);); m_optsmt.setup(*m_opt_solver.get()); update_lower(); switch (m_objectives.size()) { case 0: break; case 1: if (m_pareto1) { is_sat = l_false; m_pareto1 = false; } else { m_pareto1 = (pri == symbol("pareto")); is_sat = execute(m_objectives[0], true, false); } break; default: { opt_params optp(m_params); symbol pri = optp.priority(); if (pri == symbol("pareto")) { is_sat = execute_pareto(); } else if (pri == symbol("box")) { is_sat = execute_box(); } else { is_sat = execute_lex(); } } } if (is_sat == l_true) validate_model(); return adjust_unknown(is_sat); } lbool context::adjust_unknown(lbool r) { if (r == l_true && m_opt_solver.get() && m_opt_solver->was_unknown()) { r = l_undef; } return r; } void context::get_base_model(model_ref& mdl) { mdl = m_model; } void context::fix_model(model_ref& mdl) { if (mdl && !m_model_fixed.contains(mdl.get())) { TRACE("opt", m_fm->display(tout << "fix-model\n"); tout << *mdl << "\n"; if (m_model_converter) m_model_converter->display(tout);); (*m_fm)(mdl); apply(m_model_converter, mdl); m_model_fixed.push_back(mdl.get()); } } void context::set_model(model_ref& m) { m_model = m; opt_params optp(m_params); if (optp.dump_models() && m) { model_ref md = m->copy(); fix_model(md); } if (m_on_model_eh && m) { model_ref md = m->copy(); if (!m_model_fixed.contains(md.get())) fix_model(md); m_on_model_eh(m_on_model_ctx, md); m_model_fixed.pop_back(); } } void context::get_model_core(model_ref& mdl) { mdl = m_model; CTRACE("opt", mdl, tout << *mdl;); fix_model(mdl); if (mdl) mdl->set_model_completion(true); CTRACE("opt", mdl, tout << *mdl;); } void context::get_box_model(model_ref& mdl, unsigned index) { if (index >= m_box_models.size()) { throw default_exception("index into models is out of bounds"); } mdl = m_box_models[index]; fix_model(mdl); } bool context::contains_quantifiers() const { for (expr* f : m_hard_constraints) { if (has_quantifiers(f)) return true; } return false; } lbool context::execute_min_max(unsigned index, bool committed, bool scoped, bool is_max) { if (scoped) get_solver().push(); lbool result = m_optsmt.lex(index, is_max); if (result == l_true) { m_optsmt.get_model(m_model, m_labels); SASSERT(m_model); } if (scoped) get_solver().pop(1); if (result == l_true && committed) m_optsmt.commit_assignment(index); if (result == l_true && m_optsmt.is_unbounded(index, is_max) && contains_quantifiers()) { throw default_exception("unbounded objectives on quantified constraints is not supported"); } return result; } lbool context::execute_maxsat(symbol const& id, bool committed, bool scoped) { model_ref tmp; maxsmt& ms = *m_maxsmts.find(id); if (scoped) get_solver().push(); lbool result = ms(); if (result != l_false && (ms.get_model(tmp, m_labels), tmp.get())) { ms.get_model(m_model, m_labels); } if (scoped) get_solver().pop(1); if (result == l_true && committed) ms.commit_assignment(); DEBUG_CODE(if (result == l_true) validate_maxsat(id);); return result; } lbool context::execute(objective const& obj, bool committed, bool scoped) { switch(obj.m_type) { case O_MAXIMIZE: return execute_min_max(obj.m_index, committed, scoped, true); case O_MINIMIZE: return execute_min_max(obj.m_index, committed, scoped, false); case O_MAXSMT: return execute_maxsat(obj.m_id, committed, scoped); default: UNREACHABLE(); return l_undef; } } /** \brief there is no need to use push/pop when all objectives are maxsat and engine is maxres. */ bool context::scoped_lex() { if (m_maxsat_engine == symbol("maxres")) { for (auto const& o : m_objectives) { if (o.m_type != O_MAXSMT) return true; } return false; } return true; } lbool context::execute_lex() { lbool r = l_true; bool sc = scoped_lex(); IF_VERBOSE(1, verbose_stream() << "(opt :lex)\n";); unsigned sz = m_objectives.size(); for (unsigned i = 0; r == l_true && i < sz; ++i) { objective const& o = m_objectives[i]; bool is_last = i + 1 == sz; r = execute(o, i + 1 < sz, sc && !is_last); if (r == l_true && o.m_type == O_MINIMIZE && !get_lower_as_num(i).is_finite()) { return r; } if (r == l_true && o.m_type == O_MAXIMIZE && !get_upper_as_num(i).is_finite()) { return r; } if (r == l_true && i + 1 < sz) { update_lower(); } } DEBUG_CODE(if (r == l_true) validate_lex();); return r; } lbool context::execute_box() { if (m_box_index < m_box_models.size()) { m_model = m_box_models[m_box_index]; CTRACE("opt", m_model, tout << *m_model << "\n";); ++m_box_index; return l_true; } if (m_box_index < m_objectives.size()) { m_model = nullptr; ++m_box_index; return l_undef; } if (m_box_index != UINT_MAX && m_box_index >= m_objectives.size()) { m_box_index = UINT_MAX; return l_false; } m_box_index = 1; m_box_models.reset(); lbool r = m_optsmt.box(); for (unsigned i = 0, j = 0; r == l_true && i < m_objectives.size(); ++i) { objective const& obj = m_objectives[i]; if (obj.m_type == O_MAXSMT) { solver::scoped_push _sp(get_solver()); r = execute(obj, false, false); m_box_models.push_back(m_model.get()); } else { model* mdl = m_optsmt.get_model(j); if (!mdl) mdl = m_model.get(); m_box_models.push_back(mdl); ++j; } } if (r == l_true && !m_box_models.empty()) { m_model = m_box_models[0]; CTRACE("opt", m_model, tout << *m_model << "\n";); } return r; } expr_ref context::mk_le(unsigned i, model_ref& mdl) { objective const& obj = m_objectives[i]; return mk_cmp(false, mdl, obj); } expr_ref context::mk_ge(unsigned i, model_ref& mdl) { objective const& obj = m_objectives[i]; return mk_cmp(true, mdl, obj); } expr_ref context::mk_gt(unsigned i, model_ref& mdl) { expr_ref result = mk_le(i, mdl); result = mk_not(m, result); return result; } expr_ref context::mk_cmp(bool is_ge, model_ref& mdl, objective const& obj) { rational k(0); expr_ref val(m), result(m); switch (obj.m_type) { case O_MINIMIZE: is_ge = !is_ge; case O_MAXIMIZE: val = (*mdl)(obj.m_term); if (is_numeral(val, k)) { if (is_ge) { result = mk_ge(obj.m_term, val); } else { result = mk_ge(val, obj.m_term); } } else { result = m.mk_true(); } break; case O_MAXSMT: { pb_util pb(m); unsigned sz = obj.m_terms.size(); ptr_vector<expr> terms; vector<rational> coeffs; for (unsigned i = 0; i < sz; ++i) { terms.push_back(obj.m_terms[i]); coeffs.push_back(obj.m_weights[i]); if (mdl->is_true(obj.m_terms[i])) { k += obj.m_weights[i]; } else { TRACE("opt", tout << (*mdl)(obj.m_terms[i]) << "\n";); } } if (is_ge) { result = pb.mk_ge(sz, coeffs.c_ptr(), terms.c_ptr(), k); } else { result = pb.mk_le(sz, coeffs.c_ptr(), terms.c_ptr(), k); } break; } } TRACE("opt", tout << (is_ge?">= ":"<= ") << k << "\n"; display_objective(tout, obj); tout << "\n"; tout << result << "\n";); return result; } expr_ref context::mk_ge(expr* t, expr* s) { expr_ref result(m); if (m_bv.is_bv(t)) { result = m_bv.mk_ule(s, t); } else { result = m_arith.mk_ge(t, s); } return result; } void context::yield() { SASSERT (m_pareto); m_pareto->get_model(m_model, m_labels); update_bound(true); update_bound(false); TRACE("opt", model_smt2_pp(tout, m, *m_model.get(), 0);); } lbool context::execute_pareto() { if (!m_pareto) { set_pareto(alloc(gia_pareto, m, *this, m_solver.get(), m_params)); } lbool is_sat = (*(m_pareto.get()))(); if (is_sat != l_true) { set_pareto(nullptr); } if (is_sat == l_true) { yield(); } return is_sat; } std::string context::reason_unknown() const { if (!m.inc()) { return Z3_CANCELED_MSG; } if (m_solver.get()) { return m_solver->reason_unknown(); } return m_unknown; } void context::display_bounds(std::ostream& out, bounds_t const& b) const { for (unsigned i = 0; i < m_objectives.size(); ++i) { objective const& obj = m_objectives[i]; display_objective(out, obj); if (obj.m_type == O_MAXIMIZE) { out << " |-> [" << b[i].first << ":" << b[i].second << "]\n"; } else { out << " |-> [" << -b[i].second << ":" << -b[i].first << "]\n"; } } } solver& context::get_solver() { return *m_solver.get(); } void context::init_solver() { setup_arith_solver(); m_opt_solver = alloc(opt_solver, m, m_params, *m_fm); m_opt_solver->set_logic(m_logic); m_solver = m_opt_solver.get(); m_opt_solver->ensure_pb(); //if (opt_params(m_params).priority() == symbol("pareto") || // (opt_params(m_params).priority() == symbol("lex") && m_objectives.size() > 1)) { //} } void context::setup_arith_solver() { opt_params p(m_params); if (p.optsmt_engine() == symbol("symba") || p.optsmt_engine() == symbol("farkas")) { auto str = std::to_string((unsigned)(arith_solver_id::AS_OPTINF)); gparams::set("smt.arith.solver", str.c_str()); } } void context::update_solver() { sat_params p(m_params); if (!p.euf()) { if (!m_enable_sat || !probe_fd()) { return; } if (m_maxsat_engine != symbol("maxres") && m_maxsat_engine != symbol("pd-maxres") && m_maxsat_engine != symbol("bcd2") && m_maxsat_engine != symbol("sls")) { return; } if (opt_params(m_params).priority() == symbol("pareto")) { return; } if (m.proofs_enabled()) { return; } } m_params.set_bool("minimize_core_partial", true); m_params.set_bool("minimize_core", true); m_sat_solver = mk_inc_sat_solver(m, m_params); expr_ref_vector fmls(m); get_solver().get_assertions(fmls); m_sat_solver->assert_expr(fmls); m_solver = m_sat_solver.get(); } void context::enable_sls(bool force) { if ((force || m_enable_sls) && m_sat_solver.get()) { m_params.set_bool("optimize_model", true); m_sat_solver->updt_params(m_params); } } struct context::is_fd { struct found_fd {}; ast_manager& m; pb_util pb; bv_util bv; is_fd(ast_manager& m): m(m), pb(m), bv(m) {} void operator()(var *) { throw found_fd(); } void operator()(quantifier *) { throw found_fd(); } void operator()(app *n) { family_id fid = n->get_family_id(); if (fid != m.get_basic_family_id() && fid != pb.get_family_id() && fid != bv.get_family_id() && (!is_uninterp_const(n) || (!m.is_bool(n) && !bv.is_bv(n)))) { throw found_fd(); } } }; bool context::probe_fd() { expr_fast_mark1 visited; is_fd proc(m); try { for (objective& obj : m_objectives) { if (obj.m_type != O_MAXSMT) return false; maxsmt& ms = *m_maxsmts.find(obj.m_id); for (unsigned j = 0; j < ms.size(); ++j) { quick_for_each_expr(proc, visited, ms[j]); } } unsigned sz = get_solver().get_num_assertions(); for (unsigned i = 0; i < sz; i++) { quick_for_each_expr(proc, visited, get_solver().get_assertion(i)); } for (expr* f : m_hard_constraints) { quick_for_each_expr(proc, visited, f); } } catch (const is_fd::found_fd &) { return false; } return true; } struct context::is_propositional_fn { struct found {}; ast_manager& m; is_propositional_fn(ast_manager& m): m(m) {} void operator()(var *) { throw found(); } void operator()(quantifier *) { throw found(); } void operator()(app *n) { family_id fid = n->get_family_id(); if (fid != m.get_basic_family_id() && !is_uninterp_const(n)) { throw found(); } } }; bool context::is_propositional(expr* p) { expr* np; if (is_uninterp_const(p) || (m.is_not(p, np) && is_uninterp_const(np))) { return true; } is_propositional_fn proc(m); expr_fast_mark1 visited; try { quick_for_each_expr(proc, visited, p); } catch (const is_propositional_fn::found &) { return false; } return true; } void context::add_maxsmt(symbol const& id, unsigned index) { maxsmt* ms = alloc(maxsmt, *this, index); ms->updt_params(m_params); m_maxsmts.insert(id, ms); } bool context::is_numeral(expr* e, rational & n) const { unsigned sz; return m_arith.is_numeral(e, n) || m_bv.is_numeral(e, n, sz); } void context::normalize(expr_ref_vector const& asms) { expr_ref_vector fmls(m); m_model_converter = nullptr; to_fmls(fmls); simplify_fmls(fmls, asms); from_fmls(fmls); } void context::simplify_fmls(expr_ref_vector& fmls, expr_ref_vector const& asms) { if (m_is_clausal) { return; } goal_ref g(alloc(goal, m, true, !asms.empty())); for (expr* fml : fmls) { g->assert_expr(fml); } for (expr * a : asms) { g->assert_expr(a, a); } tactic_ref tac0 = and_then(mk_simplify_tactic(m, m_params), mk_propagate_values_tactic(m), mk_solve_eqs_tactic(m), // NB: cannot ackermannize because max/min objectives would disappear // mk_ackermannize_bv_tactic(m, m_params), // NB: mk_elim_uncstr_tactic(m) is not sound with soft constraints mk_simplify_tactic(m)); opt_params optp(m_params); tactic_ref tac1, tac2, tac3, tac4; bool has_dep = false; for (unsigned i = 0; !has_dep && i < g->size(); ++i) { ptr_vector<expr> deps; expr_dependency_ref core(g->dep(i), m); m.linearize(core, deps); has_dep |= !deps.empty(); } if (optp.elim_01() && m_logic.is_null() && !has_dep) { tac1 = mk_dt2bv_tactic(m); tac2 = mk_lia2card_tactic(m); tac3 = mk_eq2bv_tactic(m); params_ref lia_p; lia_p.set_bool("compile_equality", optp.pb_compile_equality()); tac2->updt_params(lia_p); set_simplify(and_then(tac0.get(), tac1.get(), tac2.get(), tac3.get(), mk_simplify_tactic(m))); } else { set_simplify(tac0.get()); } goal_ref_buffer result; TRACE("opt", g->display(tout);); (*m_simplify)(g, result); SASSERT(result.size() == 1); goal* r = result[0]; m_model_converter = r->mc(); CTRACE("opt", r->mc(), r->mc()->display(tout);); fmls.reset(); expr_ref tmp(m); for (unsigned i = 0; i < r->size(); ++i) { if (asms.empty()) { fmls.push_back(r->form(i)); continue; } ptr_vector<expr> deps; expr_dependency_ref core(r->dep(i), m); m.linearize(core, deps); if (!deps.empty()) { fmls.push_back(m.mk_implies(m.mk_and(deps.size(), deps.c_ptr()), r->form(i))); } else { fmls.push_back(r->form(i)); } } if (r->inconsistent()) { ptr_vector<expr> core_elems; expr_dependency_ref core(r->dep(0), m); m.linearize(core, core_elems); m_core.append(core_elems.size(), core_elems.c_ptr()); } } bool context::is_maximize(expr* fml, app_ref& term, expr_ref& orig_term, unsigned& index) { if (is_app(fml) && m_objective_fns.find(to_app(fml)->get_decl(), index) && m_objectives[index].m_type == O_MAXIMIZE) { term = to_app(to_app(fml)->get_arg(0)); orig_term = m_objective_orig.find(to_app(fml)->get_decl()); return true; } return false; } bool context::is_minimize(expr* fml, app_ref& term, expr_ref& orig_term, unsigned& index) { if (is_app(fml) && m_objective_fns.find(to_app(fml)->get_decl(), index) && m_objectives[index].m_type == O_MINIMIZE) { term = to_app(to_app(fml)->get_arg(0)); orig_term = m_objective_orig.find(to_app(fml)->get_decl()); return true; } return false; } bool context::is_maxsat(expr* fml, expr_ref_vector& terms, vector<rational>& weights, rational& offset, bool& neg, symbol& id, expr_ref& orig_term, unsigned& index) { if (!is_app(fml)) return false; neg = false; orig_term = nullptr; index = 0; app* a = to_app(fml); if (m_objective_fns.find(a->get_decl(), index) && m_objectives[index].m_type == O_MAXSMT) { for (unsigned i = 0; i < a->get_num_args(); ++i) { expr_ref arg(a->get_arg(i), m); rational weight = m_objectives[index].m_weights[i]; if (weight.is_neg()) { weight.neg(); arg = mk_not(m, arg); offset -= weight; } if (m.is_true(arg)) { IF_VERBOSE(5, verbose_stream() << weight << ": " << mk_pp(m_objectives[index].m_terms[i].get(), m) << " |-> true\n";); } else if (weight.is_zero()) { // skip } else if (m.is_false(arg)) { IF_VERBOSE(5, verbose_stream() << weight << ": " << mk_pp(m_objectives[index].m_terms[i].get(), m) << " |-> false\n";); offset += weight; } else { terms.push_back(arg); weights.push_back(weight); } } id = m_objectives[index].m_id; return true; } app_ref term(m); offset = rational::zero(); bool is_max = is_maximize(fml, term, orig_term, index); bool is_min = !is_max && is_minimize(fml, term, orig_term, index); if (is_min && get_pb_sum(term, terms, weights, offset)) { TRACE("opt", tout << "try to convert minimization\n" << mk_pp(term, m) << "\n";); // minimize 2*x + 3*y // <=> // (assert-soft (not x) 2) // (assert-soft (not y) 3) // for (unsigned i = 0; i < weights.size(); ++i) { if (weights[i].is_neg()) { offset += weights[i]; weights[i].neg(); } else { terms[i] = mk_not(m, terms[i].get()); } } TRACE("opt", tout << "Convert minimization " << orig_term << "\n"; tout << "to maxsat: " << term << "\n"; for (unsigned i = 0; i < weights.size(); ++i) { tout << mk_pp(terms[i].get(), m) << ": " << weights[i] << "\n"; } tout << "offset: " << offset << "\n"; ); std::ostringstream out; out << orig_term << ':' << index; id = symbol(out.str()); return true; } if (is_max && get_pb_sum(term, terms, weights, offset)) { TRACE("opt", tout << "try to convert maximization " << mk_pp(term, m) << "\n";); // maximize 2*x + 3*y - z // <=> // (assert-soft x 2) // (assert-soft y 3) // (assert-soft (not z) 1) // offset := 6 // maximize = offset - penalty // for (unsigned i = 0; i < weights.size(); ++i) { if (weights[i].is_neg()) { weights[i].neg(); terms[i] = mk_not(m, terms[i].get()); } offset += weights[i]; } neg = true; std::ostringstream out; out << orig_term << ':' << index; id = symbol(out.str()); return true; } if ((is_max || is_min) && m_bv.is_bv(term)) { offset.reset(); unsigned bv_size = m_bv.get_bv_size(term); expr_ref val(m); val = m_bv.mk_numeral(is_max, 1); for (unsigned i = 0; i < bv_size; ++i) { rational w = power(rational(2),i); weights.push_back(w); terms.push_back(m.mk_eq(val, m_bv.mk_extract(i, i, term))); if (is_max) { offset += w; } } neg = is_max; std::ostringstream out; out << orig_term << ':' << index; id = symbol(out.str()); return true; } return false; } expr* context::mk_objective_fn(unsigned index, objective_t ty, unsigned sz, expr*const* args) { ptr_vector<sort> domain; for (unsigned i = 0; i < sz; ++i) { domain.push_back(args[i]->get_sort()); } char const* name = ""; switch(ty) { case O_MAXIMIZE: name = "maximize"; break; case O_MINIMIZE: name = "minimize"; break; case O_MAXSMT: name = "maxsat"; break; default: break; } func_decl* f = m.mk_fresh_func_decl(name,"", domain.size(), domain.c_ptr(), m.mk_bool_sort()); m_objective_fns.insert(f, index); m_objective_refs.push_back(f); m_objective_orig.insert(f, sz > 0 ? args[0] : nullptr); return m.mk_app(f, sz, args); } expr* context::mk_maximize(unsigned index, app* t) { expr* t_ = t; return mk_objective_fn(index, O_MAXIMIZE, 1, &t_); } expr* context::mk_minimize(unsigned index, app* t) { expr* t_ = t; return mk_objective_fn(index, O_MINIMIZE, 1, &t_); } expr* context::mk_maxsat(unsigned index, unsigned num_fmls, expr* const* fmls) { return mk_objective_fn(index, O_MAXSMT, num_fmls, fmls); } void context::from_fmls(expr_ref_vector const& fmls) { TRACE("opt", tout << fmls << "\n";); m_hard_constraints.reset(); for (expr * fml : fmls) { app_ref tr(m); expr_ref orig_term(m); expr_ref_vector terms(m); vector<rational> weights; rational offset(0); unsigned index = 0; symbol id; bool neg; if (is_maxsat(fml, terms, weights, offset, neg, id, orig_term, index)) { objective& obj = m_objectives[index]; if (obj.m_type != O_MAXSMT) { // change from maximize/minimize. obj.m_id = id; obj.m_type = O_MAXSMT; SASSERT(!m_maxsmts.contains(id)); add_maxsmt(id, index); } mk_atomic(terms); SASSERT(obj.m_id == id); obj.m_term = orig_term?to_app(orig_term):nullptr; obj.m_terms.reset(); obj.m_terms.append(terms); obj.m_weights.reset(); obj.m_weights.append(weights); obj.m_adjust_value.set_offset(offset); obj.m_adjust_value.set_negate(neg); m_maxsmts.find(id)->set_adjust_value(obj.m_adjust_value); TRACE("opt", tout << "maxsat: " << id << " offset:" << offset << "\n"; tout << terms << "\n";); } else if (is_maximize(fml, tr, orig_term, index)) { purify(tr); m_objectives[index].m_term = tr; } else if (is_minimize(fml, tr, orig_term, index)) { purify(tr); m_objectives[index].m_term = tr; m_objectives[index].m_adjust_value.set_negate(true); } else { m_hard_constraints.push_back(fml); } } // fix types of objectives: for (objective & obj : m_objectives) { expr* t = obj.m_term; switch(obj.m_type) { case O_MINIMIZE: case O_MAXIMIZE: if (!m_arith.is_int(t) && !m_arith.is_real(t)) { obj.m_term = m_arith.mk_numeral(rational(0), true); } break; default: break; } } } void context::model_updated(model* md) { model_ref mdl = md; set_model(mdl); #if 0 opt_params optp(m_params); symbol prefix = optp.solution_prefix(); if (prefix == symbol::null || prefix == symbol("")) return; model_ref mdl = md->copy(); fix_model(mdl); std::ostringstream buffer; buffer << prefix << (m_model_counter++) << ".smt2"; std::ofstream out(buffer.str()); if (out) { out << *mdl; out.close(); } #endif } bool context::verify_model(unsigned index, model* md, rational const& _v) { rational r; app_ref term = m_objectives[index].m_term; if (!term) { return true; } rational v = m_objectives[index].m_adjust_value(_v); expr_ref val(m); model_ref mdl = md->copy(); fix_model(mdl); val = (*mdl)(term); unsigned bvsz; if (!m_arith.is_numeral(val, r) && !m_bv.is_numeral(val, r, bvsz)) { TRACE("opt", tout << "model does not evaluate objective to a value but instead " << val << "\n"; tout << *mdl << "\n"; ); return false; } if (r != v) { TRACE("opt", tout << "Out of bounds: " << term << " " << val << " != " << v << "\n";); return false; } else { TRACE("opt", tout << "validated: " << term << " = " << val << "\n";); } return true; } void context::purify(app_ref& term) { generic_model_converter_ref fm; if (m_arith.is_add(term)) { expr_ref_vector args(m); for (expr* arg : *term) { if (is_mul_const(arg)) { args.push_back(arg); } else { args.push_back(purify(fm, arg)); } } term = m_arith.mk_add(args.size(), args.c_ptr()); } else if (m.is_ite(term) || !is_mul_const(term)) { TRACE("opt", tout << "Purifying " << term << "\n";); term = purify(fm, term); } if (fm) { m_model_converter = concat(m_model_converter.get(), fm.get()); } } bool context::is_mul_const(expr* e) { expr* e1, *e2; return is_uninterp_const(e) || m_arith.is_numeral(e) || (m_arith.is_mul(e, e1, e2) && m_arith.is_numeral(e1) && is_uninterp_const(e2)) || (m_arith.is_mul(e, e2, e1) && m_arith.is_numeral(e1) && is_uninterp_const(e2)); } app* context::purify(generic_model_converter_ref& fm, expr* term) { std::ostringstream out; out << mk_pp(term, m); app* q = m.mk_fresh_const(out.str(), term->get_sort()); if (!fm) fm = alloc(generic_model_converter, m, "opt"); if (m_arith.is_int_real(term)) { m_hard_constraints.push_back(m_arith.mk_ge(q, term)); m_hard_constraints.push_back(m_arith.mk_le(q, term)); } else { m_hard_constraints.push_back(m.mk_eq(q, term)); } fm->hide(q); return q; } /** To select the proper theory solver we have to ensure that all theory symbols from soft constraints are reflected in the hard constraints. - filter "obj" from generated model. */ void context::mk_atomic(expr_ref_vector& terms) { generic_model_converter_ref fm; for (unsigned i = 0; i < terms.size(); ++i) { expr_ref p(terms[i].get(), m); app_ref q(m); if (is_propositional(p)) { terms[i] = p; } else { terms[i] = purify(fm, p); } } if (fm) { m_model_converter = concat(m_model_converter.get(), fm.get()); } } void context::to_fmls(expr_ref_vector& fmls) { m_objective_fns.reset(); fmls.append(m_hard_constraints); for (unsigned i = 0; i < m_objectives.size(); ++i) { objective const& obj = m_objectives[i]; switch(obj.m_type) { case O_MINIMIZE: fmls.push_back(mk_minimize(i, obj.m_term)); break; case O_MAXIMIZE: fmls.push_back(mk_maximize(i, obj.m_term)); break; case O_MAXSMT: fmls.push_back(mk_maxsat(i, obj.m_terms.size(), obj.m_terms.c_ptr())); break; } } TRACE("opt", tout << fmls << "\n";); } void context::internalize() { for (objective & obj : m_objectives) { switch(obj.m_type) { case O_MINIMIZE: { app_ref tmp(m); tmp = obj.m_term; if (m_arith.is_int(tmp) || m_arith.is_real(tmp)) { tmp = m_arith.mk_uminus(obj.m_term); } obj.m_index = m_optsmt.add(tmp); break; } case O_MAXIMIZE: obj.m_index = m_optsmt.add(obj.m_term); break; case O_MAXSMT: { maxsmt& ms = *m_maxsmts.find(obj.m_id); for (unsigned j = 0; j < obj.m_terms.size(); ++j) { ms.add(obj.m_terms.get(j), obj.m_weights[j]); } break; } } } } void context::update_bound(bool is_lower) { expr_ref val(m); if (!m_model.get()) return; for (objective const& obj : m_objectives) { rational r; switch(obj.m_type) { case O_MINIMIZE: { val = (*m_model)(obj.m_term); TRACE("opt", tout << obj.m_term << " " << val << "\n";); if (is_numeral(val, r)) { inf_eps val = inf_eps(obj.m_adjust_value(r)); TRACE("opt", tout << "adjusted value: " << val << "\n";); if (is_lower) { m_optsmt.update_lower(obj.m_index, val); } else { m_optsmt.update_upper(obj.m_index, val); } } break; } case O_MAXIMIZE: { val = (*m_model)(obj.m_term); TRACE("opt", tout << obj.m_term << " " << val << "\n";); if (is_numeral(val, r)) { inf_eps val = inf_eps(obj.m_adjust_value(r)); TRACE("opt", tout << "adjusted value: " << val << "\n";); if (is_lower) { m_optsmt.update_lower(obj.m_index, val); } else { m_optsmt.update_upper(obj.m_index, val); } } break; } case O_MAXSMT: { bool ok = true; for (unsigned j = 0; ok && j < obj.m_terms.size(); ++j) { val = (*m_model)(obj.m_terms[j]); TRACE("opt", tout << mk_pp(obj.m_terms[j], m) << " " << val << "\n";); if (!m.is_true(val)) { r += obj.m_weights[j]; } } if (ok) { maxsmt& ms = *m_maxsmts.find(obj.m_id); if (is_lower) { ms.update_upper(r); TRACE("opt", tout << "update upper from " << r << " to " << ms.get_upper() << "\n";); } else { ms.update_lower(r); TRACE("opt", tout << "update lower from " << r << " to " << ms.get_lower() << "\n";); } } break; } } } } void context::display_benchmark() { display(verbose_stream()); return; if (opt_params(m_params).dump_benchmarks() && sat_enabled() && m_objectives.size() == 1 && m_objectives[0].m_type == O_MAXSMT ) { objective& o = m_objectives[0]; unsigned sz = o.m_terms.size(); inc_sat_display(verbose_stream(), get_solver(), sz, o.m_terms.c_ptr(), o.m_weights.c_ptr()); } } void context::display(std::ostream& out) { display_assignment(out); } void context::display_assignment(std::ostream& out) { if (m_scoped_state.m_objectives.size() != m_objectives.size()) { throw default_exception("check-sat has not been called with latest objectives"); } out << "(objectives\n"; for (unsigned i = 0; i < m_scoped_state.m_objectives.size(); ++i) { objective const& obj = m_scoped_state.m_objectives[i]; out << " ("; display_objective(out, obj); if (get_lower_as_num(i) != get_upper_as_num(i)) { out << " (interval " << get_lower(i) << " " << get_upper(i) << ")"; } else { out << " " << get_lower(i); } out << ")\n"; } out << ")\n"; } void context::display_objective(std::ostream& out, objective const& obj) const { switch(obj.m_type) { case O_MAXSMT: { symbol s = obj.m_id; if (s != symbol::null) { out << s; } break; } default: out << obj.m_term; break; } } inf_eps context::get_lower_as_num(unsigned idx) { if (idx >= m_objectives.size()) { throw default_exception("index out of bounds"); } objective const& obj = m_objectives[idx]; switch(obj.m_type) { case O_MAXSMT: return inf_eps(m_maxsmts.find(obj.m_id)->get_lower()); case O_MINIMIZE: return obj.m_adjust_value(m_optsmt.get_upper(obj.m_index)); case O_MAXIMIZE: return obj.m_adjust_value(m_optsmt.get_lower(obj.m_index)); default: UNREACHABLE(); return inf_eps(); } } inf_eps context::get_upper_as_num(unsigned idx) { if (idx >= m_objectives.size()) { throw default_exception("index out of bounds"); } objective const& obj = m_objectives[idx]; switch(obj.m_type) { case O_MAXSMT: return inf_eps(m_maxsmts.find(obj.m_id)->get_upper()); case O_MINIMIZE: return obj.m_adjust_value(m_optsmt.get_lower(obj.m_index)); case O_MAXIMIZE: return obj.m_adjust_value(m_optsmt.get_upper(obj.m_index)); default: UNREACHABLE(); return inf_eps(); } } expr_ref context::get_lower(unsigned idx) { return to_expr(get_lower_as_num(idx)); } expr_ref context::get_upper(unsigned idx) { return to_expr(get_upper_as_num(idx)); } void context::to_exprs(inf_eps const& n, expr_ref_vector& es) { rational inf = n.get_infinity(); rational r = n.get_rational(); rational eps = n.get_infinitesimal(); es.push_back(m_arith.mk_numeral(inf, inf.is_int())); es.push_back(m_arith.mk_numeral(r, r.is_int())); es.push_back(m_arith.mk_numeral(eps, eps.is_int())); } expr_ref context::to_expr(inf_eps const& n) { rational inf = n.get_infinity(); rational r = n.get_rational(); rational eps = n.get_infinitesimal(); expr_ref_vector args(m); bool is_int = eps.is_zero() && r.is_int(); if (!inf.is_zero()) { expr* oo = m.mk_const(symbol("oo"), is_int ? m_arith.mk_int() : m_arith.mk_real()); if (inf.is_one()) { args.push_back(oo); } else { args.push_back(m_arith.mk_mul(m_arith.mk_numeral(inf, is_int), oo)); } } if (!r.is_zero()) { args.push_back(m_arith.mk_numeral(r, is_int)); } if (!eps.is_zero()) { expr* ep = m.mk_const(symbol("epsilon"), m_arith.mk_real()); if (eps.is_one()) { args.push_back(ep); } else { args.push_back(m_arith.mk_mul(m_arith.mk_numeral(eps, is_int), ep)); } } switch(args.size()) { case 0: return expr_ref(m_arith.mk_numeral(rational(0), true), m); case 1: return expr_ref(args[0].get(), m); default: return expr_ref(m_arith.mk_add(args.size(), args.c_ptr()), m); } } void context::set_simplify(tactic* tac) { m_simplify = tac; } void context::clear_state() { m_pareto = nullptr; m_pareto1 = false; m_box_index = UINT_MAX; m_box_models.reset(); m_model.reset(); m_model_fixed.reset(); m_core.reset(); } void context::set_pareto(pareto_base* p) { m_pareto = p; m_pareto1 = p != nullptr; } void context::collect_statistics(statistics& stats) const { if (m_solver) { m_solver->collect_statistics(stats); } if (m_simplify) { m_simplify->collect_statistics(stats); } for (auto const& kv : m_maxsmts) { kv.m_value->collect_statistics(stats); } get_memory_statistics(stats); get_rlimit_statistics(m.limit(), stats); if (m_qmax) { m_qmax->collect_statistics(stats); } } void context::collect_param_descrs(param_descrs & r) { opt_params::collect_param_descrs(r); insert_timeout(r); insert_ctrl_c(r); } void context::updt_params(params_ref const& p) { m_params.append(p); if (m_solver) { m_solver->updt_params(m_params); } if (m_sat_solver) { m_sat_solver->updt_params(m_params); } m_optsmt.updt_params(m_params); for (auto & kv : m_maxsmts) { kv.m_value->updt_params(m_params); } opt_params _p(p); m_enable_sat = _p.enable_sat(); m_enable_sls = _p.enable_sls(); m_maxsat_engine = _p.maxsat_engine(); m_pp_neat = _p.pp_neat(); m_pp_wcnf = _p.pp_wcnf(); } std::string context::to_string() { if (m_pp_wcnf) return to_wcnf(); return to_string(false, m_scoped_state.m_hard, m_scoped_state.m_objectives); } std::string context::to_string_internal() const { return to_string(true, m_hard_constraints, m_objectives); } std::string context::to_wcnf() { import_scoped_state(); expr_ref_vector asms(m); normalize(asms); auto const& objectives = m_objectives; if (objectives.size() > 1) throw default_exception("only single objective weighted MaxSAT wcnf output is supported"); ptr_vector<expr> soft_f; vector<rational> soft_w; svector<std::pair<expr*, unsigned>> soft; if (objectives.size() == 1) { auto const& obj = objectives[0]; if (obj.m_type != O_MAXSMT) throw default_exception("only single objective weighted MaxSAT wcnf output is supported"); for (unsigned j = 0; j < obj.m_terms.size(); ++j) { rational w = obj.m_weights[j]; if (!w.is_unsigned()) throw default_exception("only single objective weighted MaxSAT wcnf output is supported"); soft_f.push_back(obj.m_terms[j]); soft_w.push_back(w); } } std::ostringstream strm; m_sat_solver = mk_inc_sat_solver(m, m_params); m_sat_solver->assert_expr(m_hard_constraints); inc_sat_display(strm, *m_sat_solver.get(), soft_f.size(), soft_f.c_ptr(), soft_w.c_ptr()); return strm.str(); } std::string context::to_string(bool is_internal, expr_ref_vector const& hard, vector<objective> const& objectives) const { smt2_pp_environment_dbg env(m); ast_pp_util visitor(m); std::ostringstream out; visitor.collect(hard); model_converter_ref mc = concat(m_model_converter.get(), m_fm.get()); for (objective const& obj : objectives) { switch(obj.m_type) { case O_MAXIMIZE: case O_MINIMIZE: visitor.collect(obj.m_term); break; case O_MAXSMT: visitor.collect(obj.m_terms); break; default: UNREACHABLE(); break; } } if (is_internal && mc) { mc->set_env(&visitor); } param_descrs descrs; collect_param_descrs(descrs); m_params.display_smt2(out, "opt", descrs); visitor.display_decls(out); visitor.display_asserts(out, hard, m_pp_neat); for (objective const& obj : objectives) { switch(obj.m_type) { case O_MAXIMIZE: out << "(maximize "; ast_smt2_pp(out, obj.m_term, env); out << ")\n"; break; case O_MINIMIZE: out << "(minimize "; ast_smt2_pp(out, obj.m_term, env); out << ")\n"; break; case O_MAXSMT: for (unsigned j = 0; j < obj.m_terms.size(); ++j) { out << "(assert-soft "; ast_smt2_pp(out, obj.m_terms[j], env); rational w = obj.m_weights[j]; w.display_decimal(out << " :weight ", 3, true); if (obj.m_id != symbol::null) { if (is_smt2_quoted_symbol(obj.m_id)) { out << " :id " << mk_smt2_quoted_symbol(obj.m_id); } else { out << " :id " << obj.m_id; } } out << ")\n"; } break; default: UNREACHABLE(); break; } } if (is_internal && mc) { mc->display(out); } if (is_internal && mc) { mc->set_env(nullptr); } out << "(check-sat)\n"; return out.str(); } void context::validate_model() { return; if (!gparams::get_ref().get_bool("model_validate", false)) return; expr_ref_vector fmls(m); get_hard_constraints(fmls); expr_ref tmp(m); model_ref mdl; get_model(mdl); mdl->set_model_completion(true); for (expr * f : fmls) { if (!mdl->is_true(f)) { IF_VERBOSE(0, verbose_stream() << "Failed to validate " << mk_pp(f, m) << "\n" << tmp << "\n"; m_fm->display(verbose_stream() << "fm\n"); m_model_converter->display(verbose_stream() << "mc\n"); model_smt2_pp(verbose_stream(), m, *mdl, 0); verbose_stream() << to_string_internal() << "\n"); } } } void context::validate_maxsat(symbol const& id) { maxsmt& ms = *m_maxsmts.find(id); TRACE("opt", tout << "Validate: " << id << "\n";); for (objective const& obj : m_objectives) { if (obj.m_id == id && obj.m_type == O_MAXSMT) { SASSERT(obj.m_type == O_MAXSMT); rational value(0); expr_ref val(m); for (unsigned i = 0; i < obj.m_terms.size(); ++i) { auto const& t = obj.m_terms[i]; if (!m_model->is_true(t)) { value += obj.m_weights[i]; } // TBD: check that optimal was not changed. } value = obj.m_adjust_value(value); rational value0 = ms.get_lower(); TRACE("opt", tout << "value " << value << " " << value0 << "\n";); // TBD is this correct? SASSERT(value == value0); } } } void context::validate_lex() { rational r1; expr_ref val(m); SASSERT(m_model); for (unsigned i = 0; i < m_objectives.size(); ++i) { objective const& obj = m_objectives[i]; switch(obj.m_type) { case O_MINIMIZE: case O_MAXIMIZE: { inf_eps n = m_optsmt.get_lower(obj.m_index); if (false && // theory_lra doesn't produce infinitesimals m_optsmt.objective_is_model_valid(obj.m_index) && n.get_infinity().is_zero() && n.get_infinitesimal().is_zero() && is_numeral((*m_model)(obj.m_term), r1)) { rational r2 = n.get_rational(); if (obj.m_type == O_MINIMIZE) { r1.neg(); } CTRACE("opt", r1 != r2, tout << obj.m_term << " evaluates to " << r1 << " but has objective " << r2 << "\n";); CTRACE("opt", r1 != r2, tout << *m_model;); SASSERT(r1 == r2); } break; } case O_MAXSMT: { rational value(0); for (unsigned i = 0; i < obj.m_terms.size(); ++i) { if (!m_model->is_true(obj.m_terms[i])) { value += obj.m_weights[i]; } // TBD: check that optimal was not changed. } maxsmt& ms = *m_maxsmts.find(obj.m_id); rational value0 = ms.get_lower(); TRACE("opt", tout << "value " << value << " other " << value0 << "\n";); // TBD SASSERT(value0 == value); break; } } } } bool context::is_qsat_opt() { if (m_objectives.size() != 1) { return false; } if (m_objectives[0].m_type != O_MAXIMIZE && m_objectives[0].m_type != O_MINIMIZE) { return false; } if (!m_arith.is_real(m_objectives[0].m_term)) { return false; } for (expr* fml : m_hard_constraints) { if (has_quantifiers(fml)) { return true; } } return false; } lbool context::run_qsat_opt() { SASSERT(is_qsat_opt()); objective const& obj = m_objectives[0]; app_ref term(obj.m_term); if (obj.m_type == O_MINIMIZE) { term = m_arith.mk_uminus(term); } inf_eps value; m_qmax = alloc(qe::qmax, m, m_params); lbool result = (*m_qmax)(m_hard_constraints, term, value, m_model); if (result != l_undef && obj.m_type == O_MINIMIZE) { value.neg(); } m_optsmt.setup(*m_opt_solver.get()); if (result == l_undef) { if (obj.m_type == O_MINIMIZE) { m_optsmt.update_upper(obj.m_index, value); } else { m_optsmt.update_lower(obj.m_index, value); } } else { m_optsmt.update_lower(obj.m_index, value); m_optsmt.update_upper(obj.m_index, value); } return result; } }
; A198410: ((3^(n-1) + 1)^3 -1)/3^n. ; 7,37,271,2269,19927,177877,1596511,14355469,129159847,1162320517,10460530351,94143710269,847290203767,7625602267957,68630391713791,617673439330669,5559060695695687,50031545486420197,450283907053258831,4052555156505760669,36472996387631139607,328256967425918137237,2954312706644976877471,26588814359239932824269,239299329231464818199527,2153693963078099632139077,19383245667687645494281711,174449211009143055863625469,1570042899082150242017899447,14130386091738940395896905717,127173474825649228216279583551,1144561273430839347906138548269,10301051460877543013034113823367,92709463147897853762943625077157,834385168331080583803402427694991,7509466514979724954041351255256669,67585198634817523685804349515315287,608266787713357710470535710291853397 mov $1,3 pow $1,$0 mov $2,9 pow $2,$0 add $1,$2 mov $0,$1 sub $0,2 mul $0,3 add $0,7
; A001547: a(n) = (7*n+1)*(7*n+2)*(7*n+4). ; 8,792,4320,12650,27840,51948,87032,135150,198360,278720,378288,499122,643280,812820,1009800,1236278,1494312,1785960,2113280,2478330,2883168,3329852,3820440,4356990,4941560,5576208,6262992,7003970,7801200,8656740,9572648,10550982,11593800,12703160,13881120,15129738,16451072,17847180,19320120,20871950,22504728,24220512,26021360,27909330,29886480,31954868,34116552,36373590,38728040,41181960,43737408,46396442,49161120,52033500,55015640,58109598,61317432,64641200,68082960,71644770,75328688,79136772,83071080,87133670,91326600,95651928,100111712,104708010,109442880,114318380,119336568,124499502,129809240,135267840,140877360,146639858,152557392,158632020,164865800,171260790,177819048,184542632,191433600,198494010,205725920,213131388,220712472,228471230,236409720,244530000,252834128,261324162,270002160,278870180,287930280,297184518,306634952,316283640,326132640,336184010,346439808,356902092,367572920,378454350,389548440,400857248,412382832,424127250,436092560,448280820,460694088,473334422,486203880,499304520,512638400,526207578,540014112,554060060,568347480,582878430,597654968,612679152,627953040,643478690,659258160,675293508,691586792,708140070,724955400,742034840,759380448,776994282,794878400,813034860,831465720,850173038,869158872,888425280,907974320,927808050,947928528,968337812,989037960,1010031030,1031319080,1052904168,1074788352,1096973690,1119462240,1142256060,1165357208,1188767742,1212489720,1236525200,1260876240,1285544898,1310533232,1335843300,1361477160,1387436870,1413724488,1440342072,1467291680,1494575370,1522195200,1550153228,1578451512,1607092110,1636077080,1665408480,1695088368,1725118802,1755501840,1786239540,1817333960,1848787158,1880601192,1912778120,1945320000,1978228890,2011506848,2045155932,2079178200,2113575710,2148350520,2183504688,2219040272,2254959330,2291263920,2327956100,2365037928,2402511462,2440378760,2478641880,2517302880,2556363818,2595826752,2635693740,2675966840,2716648110,2757739608,2799243392,2841161520,2883496050,2926249040,2969422548,3013018632,3057039350,3101486760,3146362920,3191669888,3237409722,3283584480,3330196220,3377247000,3424738878,3472673912,3521054160,3569881680,3619158530,3668886768,3719068452,3769705640,3820800390,3872354760,3924370808,3976850592,4029796170,4083209600,4137092940,4191448248,4246277582,4301583000,4357366560,4413630320,4470376338,4527606672,4585323380,4643528520,4702224150,4761412328,4821095112,4881274560,4941952730,5003131680,5064813468,5127000152,5189693790,5252896440,5316610160 mov $2,$0 mov $6,$0 lpb $0,1 mul $0,$3 mul $2,7 add $2,1 mov $1,$2 add $2,1 mov $4,$2 sub $4,2 mul $1,$4 add $1,$4 lpe mul $1,7 add $1,8 mov $7,$6 mov $9,$6 lpb $9,1 add $8,$7 sub $9,1 lpe mov $7,$8 mov $8,0 mov $9,$6 lpb $9,1 add $8,$7 sub $9,1 lpe mov $5,343 mov $7,$8 lpb $5,1 add $1,$7 sub $5,1 lpe
copyright zengfr site:http://github.com/zengfr/romhack 00042A move.l D1, (A0)+ 00042C dbra D0, $42a 004D94 move.l D1, (A1)+ 004D96 dbra D0, $4d94 012D0A add.w ($56,A6), D0 [123p+ 54, enemy+54, item+54] 012D0E move.w ($c,A6), D1 [123p+ 56, enemy+56, item+56] 012D32 add.w ($56,A6), D0 [123p+ 54, enemy+54, item+54] 012D36 cmp.w ($c,A6), D0 [123p+ 56, enemy+56, item+56] 012D68 add.w ($56,A6), D0 012D6C move.w ($c,A6), D1 012D90 add.w ($56,A6), D0 [123p+ 54] 012D94 cmp.w ($c,A6), D0 012FD8 move.w D1, ($56,A6) 012FDC move.w ($54,A1), ($54,A6) [123p+ 56] 0130A8 clr.w ($56,A6) [123p+ 54, enemy+54, item+54] 0130AC tst.b ($4dc,A5) [123p+ 56, enemy+56, etc+56, item+56] 013446 move.w D2, ($56,A6) 01344A bra $13134 [123p+ 56, enemy+56] 013468 move.w ($6b0,A5), ($56,A6) 01346E bra $13134 [123p+ 56, enemy+56, item+56] 0134A0 move.w D3, ($56,A6) 0134A4 bra $13134 [123p+ 56, enemy+56, item+56] 013502 move.w D3, ($56,A6) 013506 bra $13134 [123p+ 56, item+56] 014EE4 add.w ($56,A0), D1 [123p+ 54, enemy+54, item+54] 014EE8 tst.b ($53,A0) [123p+ 56, enemy+56, item+56] 018B8A add.w ($56,A6), D0 [123p+ 54] 018B8E addi.w #$180, D0 01A662 sub.w ($56,A6), D0 [123p+ 54] 01A666 cmpi.w #$30, D0 [123p+ 56] 01A720 sub.w ($56,A6), D0 [123p+ 54] 01A724 cmp.w (A0)+, D0 01CFFA add.w ($56,A6), D0 01CFFE cmp.w ($c,A6), D0 0AAACA move.l (A0), D2 0AAACC move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAACE move.w D0, ($2,A0) 0AAAD2 cmp.l (A0), D0 0AAAD4 bne $aaafc 0AAAD8 move.l D2, (A0)+ 0AAADA cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAAE6 move.l (A0), D2 0AAAE8 move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAAF4 move.l D2, (A0)+ 0AAAF6 cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] copyright zengfr site:http://github.com/zengfr/romhack
/*- * Copyright (c) 2003 Hidetoshi Shimokawa * Copyright (c) 1998-2002 Katsushi Kobayashi and Hidetoshi Shimokawa * All rights reserved. * * 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. * 3. All advertising materials mentioning features or use of this software * must display the acknowledgement as bellow: * * This product includes software developed by K. Kobayashi and H. SHimokawa * * 4. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * $FreeBSD: src/sys/dev/firewire/fwohci_pci.c,v 1.60 2007/06/06 14:31:36 simokawa Exp $ */ #include <OS.h> #include <KernelExport.h> #include <lock.h> #include <SupportDefs.h> #include <PCI.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <malloc.h> #include "util.h" #include "fwdebug.h" #include "fwglue.h" #include "queue.h" #include "firewire.h" #include "iec13213.h" #include "firewirereg.h" #include "fwdma.h" #include "fwohcireg.h" #include "fwohcivar.h" #define PCIM_CMD_IOS 0x0001 #define PCIM_CMD_MEMEN 0x0002 #define PCIM_CMD_BUSMASTEREN 0x0004 #define PCIM_CMD_MWRICEN 0x0010 #define PCIM_CMD_PERRESPEN 0x0040 #define PCIM_CMD_SERRESPEN 0x0100 extern pci_module_info *gPci; extern pci_info *pciInfo[MAX_CARDS]; extern fwohci_softc_t *gFwohci_softc[MAX_CARDS]; extern struct firewire_softc *gFirewire_softc[MAX_CARDS]; status_t fwohci_pci_detach(int index) { fwohci_softc_t *sc = gFwohci_softc[index]; int s; s = splfw(); fwohci_stop(sc); // bus_generic_detach(self); firewire_detach(gFirewire_softc[index]); /* if (sc->fc.bdev) { device_delete_child(self, sc->fc.bdev); sc->fc.bdev = NULL; }*/ /* disable interrupts that might have been switched on */ OWRITE(sc, FWOHCI_INTMASKCLR, OHCI_INT_EN); remove_io_interrupt_handler (sc->irq, fwohci_intr, sc); delete_area(sc->regArea); fwohci_detach(sc); mtx_destroy(FW_GMTX(&sc->fc)); splx(s); return B_OK; } static void fwohci_pci_add_child(int index) { struct fwohci_softc *sc; int err = 0; sc = gFwohci_softc[index]; /* child = device_add_child(dev, name, unit); if (child == NULL) return (child); sc->fc.bdev = child; device_set_ivars(child, (void *)&sc->fc);*/ // err = device_probe_and_attach(child); err = firewire_attach(&sc->fc, gFirewire_softc[index]); if (err) { device_printf(dev, "firewire_attach failed with err=%d\n", err); fwohci_pci_detach(index); // device_delete_child(dev, child); return; } /* XXX * Clear the bus reset event flag to start transactions even when * interrupt is disabled during the boot process. */ // if (cold) { // int s; // DELAY(250); /* 2 cycles */ // s = splfw(); // fwohci_poll((void *)sc, 0, -1); // splx(s); // } } status_t fwohci_pci_attach(int index) { fwohci_softc_t *sc = gFwohci_softc[index]; pci_info *info = pciInfo[index]; uint32 olatency, latency, ocache_line, cache_line; uint32 val; mtx_init(FW_GMTX(&sc->fc), "firewire", NULL, MTX_DEF); val = gPci->read_pci_config(info->bus, info->device, info->function, PCI_command, 2); val |= PCIM_CMD_MEMEN | PCIM_CMD_BUSMASTEREN | PCIM_CMD_MWRICEN; #if 1 /* for broken hardware */ val &= ~PCIM_CMD_MWRICEN; val &= ~(PCIM_CMD_SERRESPEN | PCIM_CMD_PERRESPEN); #endif gPci->write_pci_config(info->bus, info->device, info->function, PCI_command, 2, val); /* * Some Sun PCIO-2 FireWire controllers have their intpin register * bogusly set to 0, although it should be 3. Correct that. */ if (info->vendor_id == FW_VENDORID_SUN && info->device_id == (FW_DEVICE_PCIO2FW >> 16) && info->u.h0.interrupt_pin == 0) info->u.h0.interrupt_pin = 3; latency = olatency = gPci->read_pci_config(info->bus, info->device, info->function, PCI_latency, 1); #define DEF_LATENCY 0x20 if (olatency < DEF_LATENCY) { latency = DEF_LATENCY; gPci->write_pci_config(info->bus, info->device, info->function, PCI_latency, 1, latency); } cache_line = ocache_line = gPci->read_pci_config(info->bus, info->device, info->function, PCI_line_size, 1); #define DEF_CACHE_LINE 8 if (ocache_line < DEF_CACHE_LINE) { cache_line = DEF_CACHE_LINE; gPci->write_pci_config(info->bus, info->device, info->function, PCI_line_size, 1, cache_line); } TRACE("latency timer %lx -> %lx.\n", olatency, latency); TRACE("cache size %lx -> %lx.\n", ocache_line, cache_line); // get IRQ sc->irq = gPci->read_pci_config(info->bus, info->device, info->function, PCI_interrupt_line, 1); if (sc->irq == 0 || sc->irq == 0xff) { ERROR("no IRQ assigned\n"); goto err; } TRACE("IRQ %d\n", sc->irq); // map registers into memory // val = gPci->read_pci_config(info->bus, info->device, info->function, 0x14, 4); // val &= PCI_address_memory_32_mask; // TRACE("hardware register address %p\n", (void *) val); TRACE("hardware register address %lx\n", info->u.h0.base_registers[0]); sc->regArea = map_mem(&sc->regAddr, (void *)info->u.h0.base_registers[0], 0x800, B_READ_AREA | B_WRITE_AREA, "fw ohci register"); if (sc->regArea < B_OK) { ERROR("can't map hardware registers\n"); goto err; } TRACE("mapped registers to %p\n", sc->regAddr); // setup interrupt handler if (install_io_interrupt_handler(sc->irq, fwohci_intr, sc, 0) < B_OK) { ERROR("can't install interrupt handler\n"); goto err; } if (fwohci_init(sc) < B_OK){ ERROR("fwohci_init failed"); goto err; } fwohci_pci_add_child(index); return B_OK; err: delete_area(sc->regArea); mtx_destroy(FW_GMTX(&sc->fc)); return B_ERROR; }
;------------------------------------------------------------------------------ ; ; Copyright (c) 2013, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php. ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; IntHandler.asm ; ; Abstract: ; ; Assembly interrupt handler function. ; ;------------------------------------------------------------------------------ public AsmInterruptHandle .code AsmInterruptHandle: cli mov al, 1 iretq END
/* * All Video Processing kernels * Copyright © <2010>, Intel Corporation. * * 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, sub license, 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 (including the * next paragraph) 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 NON-INFRINGEMENT. * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS 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 file was originally licensed under the following license * * 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. * */ // Module name: PL8x4_Save_NV12.asm // // Save entire current planar frame data block of size 16x8 //--------------------------------------------------------------- // Symbols needed to be defined before including this module // // DWORD_ALIGNED_DEST: only if DEST_Y, DEST_U, DEST_V data are DWord aligned // ORIX: //--------------------------------------------------------------- #include "PL8x4_Save_NV12.inc" mov (8) mMSGHDR<1>:ud rMSGSRC<8;8,1>:ud #if !defined(SAVE_UV_ONLY) // Save current planar frame Y block data (16x8) ------------------------------- mov (2) mMSGHDR.0<1>:d wORIX<2;2,1>:w // Block origin mov (1) mMSGHDR.2<1>:ud nDPW_BLOCK_SIZE_Y:ud // Block width and height (16x8) #endif //Use the mask to determine which pixels shouldn't be over-written and (1) acc0<1>:ud udBLOCK_MASK<0;1,0>:ud 0x00FFFFFF:ud cmp.ge.f0.0 (1) dNULLREG acc0<0;1,0>:ud 0x00FFFFFF:ud //Check if all pixels in the block need to be modified (f0.0) jmpi WritePlanarToDataPort //If mask is not all 1's, then load the entire 16x8 block //so that only those bytes may be modified that need to be (using the mask) send (8) udSRC_Y(0)<1> mMSGHDR udDUMMY_NULL nDATAPORT_READ nDPMR_MSGDSC+nDPR_MSG_SIZE_Y+nBI_DESTINATION_Y:ud //16x8 asr (1) rMSGSRC.1<1>:ud wORIY<0;1,0>:w 1:w { NoDDClr } // U/V block origin should be half of Y's mov (1) rMSGSRC.2<1>:ud nDPW_BLOCK_SIZE_UV:ud { NoDDChk } // Block width and height (16x4) mov (8) mMSGHDR<1>:ud rMSGSRC<8;8,1>:ud //move message desrcptor to the message header send (8) udSRC_U(0)<1> mMSGHDR udDUMMY_NULL nDATAPORT_READ nDPMR_MSGDSC+nDPR_MSG_SIZE_UV+nBI_DESTINATION_UV:ud //Restore the origin information mov (2) rMSGSRC.0<1>:ud wORIX<2;2,1>:w // Block origin mov (1) rMSGSRC.2<1>:ud nDPW_BLOCK_SIZE_Y:ud // Block width and height (16x8) mov (8) mMSGHDR<1>:ud rMSGSRC<8;8,1>:ud //move message desrcptor to the message header //Merge the data mov (1) f0.1:uw ubBLOCK_MASK_V:ub //Load the mask on flag reg (f0.1) mov (8) rMASK_TEMP<1>:uw uwBLOCK_MASK_H:uw (-f0.1) mov (8) rMASK_TEMP<1>:uw 0:uw //convert the mask from 16bits to 8bits by selecting every other bit mov (1) udMASK_TEMP1(0,0)<1> 0x00040001:ud mov (1) udMASK_TEMP1(0,1)<1> 0x00400010:ud mov (1) udMASK_TEMP1(0,2)<1> 0x04000100:ud mov (1) udMASK_TEMP1(0,3)<1> 0x40001000:ud //merge the loaded block with the current block $for(0,0; <nY_NUM_OF_ROWS; 2,1) { mov (1) f0.1:uw uwMASK_TEMP(0, %1)<0;1,0> (-f0.1) mov (16) ubDEST_Y(0,%1*32)<2> ubSRC_Y(0,%1*16) and.nz.f0.1 (8) wNULLREG uwMASK_TEMP(0,%1)<0;1,0> uwMASK_TEMP1(0,0) //change the mask by selecting every other bit (-f0.1) mov (8) ubDEST_U(0, %2*16)<2> ub2SRC_U(0, %1*8)<16;8,2> (-f0.1) mov (8) ubDEST_V(0, %2*16)<2> ub2SRC_U(0, %1*8+1)<16;8,2> mov (1) f0.1:uw uwMASK_TEMP(0,1+%1)<0;1,0> (-f0.1) mov (16) ubDEST_Y(0, (1+%1)*32)<2> ubSRC_Y(0, (1+%1)*16) } WritePlanarToDataPort: #if !defined(SAVE_UV_ONLY) $for(0,0; <nY_NUM_OF_ROWS; 2,1) { mov (16) mubMSGPAYLOAD(%2,0)<1> ub2DEST_Y(%1)REGION(16,2) mov (16) mubMSGPAYLOAD(%2,16)<1> ub2DEST_Y(%1+1)REGION(16,2) } send (8) dNULLREG mMSGHDR udDUMMY_NULL nDATAPORT_WRITE nDPMW_MSGDSC+nDPW_MSG_SIZE_Y+nBI_DESTINATION_Y:ud #endif //** Save 8x4 packed U and V ----------------------------------------------------- // we could write directly wORIX to mMSGHDR and then execute asr on it, that way we could // avoid using rMSGSRC as a buffer and have one command less in code, but it is unknown whether //it is possible to do asr on mMSGHDR so we use rMSGSRC. mov (2) rMSGSRC.0<1>:d wORIX<2;2,1>:w // Block origin asr (1) rMSGSRC.1<1>:d rMSGSRC.1<0;1,0>:d 1:w // U/V block origin should be half of Y's mov (1) rMSGSRC.2<1>:ud nDPW_BLOCK_SIZE_UV:ud // U/V block width and height (16x4) mov (8) mMSGHDR<1>:ud rMSGSRC<8;8,1>:ud $for(0,0; <nY_NUM_OF_ROWS;4,1) { mov (16) mubMSGPAYLOAD(%2,0)<2> ub2DEST_U(%2)REGION(16,2) mov (16) mubMSGPAYLOAD(%2,1)<2> ub2DEST_V(%2)REGION(16,2) } send (8) dNULLREG mMSGHDR udDUMMY_NULL nDATAPORT_WRITE nDPMW_MSGDSC+nDPW_MSG_SIZE_UV+nBI_DESTINATION_UV:ud // End of PL8x4_Save_NV12
; Internal routine to write long at far pointer ; 31/3/00 GWL ; Entry: E'H'L'=far pointer ; DEHL=long ; ; $Id: lp_plong.asm,v 1.4 2016-06-10 22:42:22 dom Exp $ ; SECTION code_clib PUBLIC lp_plong EXTERN farseg1,incfar .lp_plong ld a,($04d1) ex af,af' push hl pop ix push de pop iy exx ld b,h ld c,l call farseg1 ld a,ixl ld (hl),a call incfar ld a,ixh ld (hl),a call incfar ld a,iyl ld (hl),a call incfar ld a,iyh ld (hl),a ex af,af' ld ($04d1),a out ($d1),a ret
// Copyright (c) 2011-2016 The vhkdCoin Core vhkd // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/vhkd-config.h" #endif #include "utilitydialog.h" #include "ui_helpmessagedialog.h" #include "vhkdgui.h" #include "clientmodel.h" #include "guiconstants.h" #include "intro.h" #include "paymentrequestplus.h" #include "guiutil.h" #include "clientversion.h" #include "init.h" #include "util.h" #include <stdio.h> #include <QCloseEvent> #include <QLabel> #include <QRegExp> #include <QTextTable> #include <QTextCursor> #include <QVBoxLayout> /** "Help message" or "About" dialog box */ HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) : QDialog(parent), ui(new Ui::HelpMessageDialog) { ui->setupUi(this); QString version = tr(PACKAGE_NAME) + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()); /* On x86 add a bit specifier to the version so that users can distinguish between * 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambiguous. */ #if defined(__x86_64__) version += " " + tr("(%1-bit)").arg(64); #elif defined(__i386__ ) version += " " + tr("(%1-bit)").arg(32); #endif if (about) { setWindowTitle(tr("About %1").arg(tr(PACKAGE_NAME))); /// HTML-format the license message from the core QString licenseInfo = QString::fromStdString(LicenseInfo()); QString licenseInfoHTML = licenseInfo; // Make URLs clickable QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2); uri.setMinimal(true); // use non-greedy matching licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>"); // Replace newlines with HTML breaks licenseInfoHTML.replace("\n", "<br>"); ui->aboutMessage->setTextFormat(Qt::RichText); ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); text = version + "\n" + licenseInfo; ui->aboutMessage->setText(version + "<br><br>" + licenseInfoHTML); ui->aboutMessage->setWordWrap(true); ui->helpMessage->setVisible(false); } else { setWindowTitle(tr("Command-line options")); QString header = tr("Usage:") + "\n" + " vhkd-qt [" + tr("command-line options") + "] " + "\n"; QTextCursor cursor(ui->helpMessage->document()); cursor.insertText(version); cursor.insertBlock(); cursor.insertText(header); cursor.insertBlock(); std::string strUsage = HelpMessage(HMM_BITCOIN_QT); const bool showDebug = gArgs.GetBoolArg("-help-debug", false); strUsage += HelpMessageGroup(tr("UI Options:").toStdString()); if (showDebug) { strUsage += HelpMessageOpt("-allowselfsignedrootcertificates", strprintf("Allow self signed root certificates (default: %u)", DEFAULT_SELFSIGNED_ROOTCERTS)); } strUsage += HelpMessageOpt("-choosedatadir", strprintf(tr("Choose data directory on startup (default: %u)").toStdString(), DEFAULT_CHOOSE_DATADIR)); strUsage += HelpMessageOpt("-lang=<lang>", tr("Set language, for example \"de_DE\" (default: system locale)").toStdString()); strUsage += HelpMessageOpt("-min", tr("Start minimized").toStdString()); strUsage += HelpMessageOpt("-rootcertificates=<file>", tr("Set SSL root certificates for payment request (default: -system-)").toStdString()); strUsage += HelpMessageOpt("-splash", strprintf(tr("Show splash screen on startup (default: %u)").toStdString(), DEFAULT_SPLASHSCREEN)); strUsage += HelpMessageOpt("-resetguisettings", tr("Reset all settings changed in the GUI").toStdString()); if (showDebug) { strUsage += HelpMessageOpt("-uiplatform", strprintf("Select platform to customize UI for (one of windows, macosx, other; default: %s)", vhkdCoinGUI::DEFAULT_UIPLATFORM)); } QString coreOptions = QString::fromStdString(strUsage); text = version + "\n" + header + "\n" + coreOptions; QTextTableFormat tf; tf.setBorderStyle(QTextFrameFormat::BorderStyle_None); tf.setCellPadding(2); QVector<QTextLength> widths; widths << QTextLength(QTextLength::PercentageLength, 35); widths << QTextLength(QTextLength::PercentageLength, 65); tf.setColumnWidthConstraints(widths); QTextCharFormat bold; bold.setFontWeight(QFont::Bold); for (const QString &line : coreOptions.split("\n")) { if (line.startsWith(" -")) { cursor.currentTable()->appendRows(1); cursor.movePosition(QTextCursor::PreviousCell); cursor.movePosition(QTextCursor::NextRow); cursor.insertText(line.trimmed()); cursor.movePosition(QTextCursor::NextCell); } else if (line.startsWith(" ")) { cursor.insertText(line.trimmed()+' '); } else if (line.size() > 0) { //Title of a group if (cursor.currentTable()) cursor.currentTable()->appendRows(1); cursor.movePosition(QTextCursor::Down); cursor.insertText(line.trimmed(), bold); cursor.insertTable(1, 2, tf); } } ui->helpMessage->moveCursor(QTextCursor::Start); ui->scrollArea->setVisible(false); ui->aboutLogo->setVisible(false); } } HelpMessageDialog::~HelpMessageDialog() { delete ui; } void HelpMessageDialog::printToConsole() { // On other operating systems, the expected action is to print the message to the console. fprintf(stdout, "%s\n", qPrintable(text)); } void HelpMessageDialog::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } void HelpMessageDialog::on_okButton_accepted() { close(); } /** "Shutdown" window */ ShutdownWindow::ShutdownWindow(QWidget *parent, Qt::WindowFlags f): QWidget(parent, f) { QVBoxLayout *layout = new QVBoxLayout(); layout->addWidget(new QLabel( tr("%1 is shutting down...").arg(tr(PACKAGE_NAME)) + "<br /><br />" + tr("Do not shut down the computer until this window disappears."))); setLayout(layout); } QWidget *ShutdownWindow::showShutdownWindow(vhkdCoinGUI *window) { if (!window) return nullptr; // Show a simple window indicating shutdown status QWidget *shutdownWindow = new ShutdownWindow(); shutdownWindow->setWindowTitle(window->windowTitle()); // Center shutdown window at where main window was const QPoint global = window->mapToGlobal(window->rect().center()); shutdownWindow->move(global.x() - shutdownWindow->width() / 2, global.y() - shutdownWindow->height() / 2); shutdownWindow->show(); return shutdownWindow; } void ShutdownWindow::closeEvent(QCloseEvent *event) { event->ignore(); }
//================================================================================================= /*! // \file src/mathtest/operations/smatdmatschur/LCbLDb.cpp // \brief Source file for the LCbLDb sparse matrix/dense matrix Schur product math test // // Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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. // 3. Neither the names of the Blaze development group 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/LowerMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/operations/smatdmatschur/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'LCbLDb'..." << std::endl; using blazetest::mathtest::TypeB; try { // Matrix type definitions using LCb = blaze::LowerMatrix< blaze::CompressedMatrix<TypeB> >; using LDb = blaze::LowerMatrix< blaze::DynamicMatrix<TypeB> >; // Creator type definitions using CLCb = blazetest::Creator<LCb>; using CLDb = blazetest::Creator<LDb>; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=LCb::maxNonZeros( i ); ++j ) { RUN_SMATDMATSCHUR_OPERATION_TEST( CLCb( i, j ), CLDb( i ) ); } } // Running tests with large matrices RUN_SMATDMATSCHUR_OPERATION_TEST( CLCb( 67UL, 7UL ), CLDb( 67UL ) ); RUN_SMATDMATSCHUR_OPERATION_TEST( CLCb( 128UL, 16UL ), CLDb( 128UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix Schur product:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
#include "AiGameObject.h" AiGameObject::AiGameObject(const std::string& name_, MATH::Vec3 position_) { name = name_; SetPos(position_); mRenderer = AddComponent<MeshRenderer>(); mRenderer->LoadModel("Plane.fbx"); mRenderer->CreateShader("DefaultVert.glsl", "DefaultFrag.glsl"); AddComponent<RigidBody3D>(); aiComponent = AddComponent<AIComponent>(); aiComponent->SetAIType(AIType::KinematicSteering); aiComponent->SetMaxSpeed(5.0f); aiComponent->SetMaxAcceleration(5.0f); aiTarget = nullptr; } AiGameObject::~AiGameObject() { } void AiGameObject::Update(const float deltaTime) { if(aiTarget) { Kinematic::KinematicSeek kSeekAlgo = Kinematic::KinematicSeek(this, aiTarget->transform); Kinematic::KinematicSteeringOutput steering = kSeekAlgo.getSteering(); aiComponent->SetSteering(&steering); /*Kinematic::KinematicArrive kArriveAlgo = Kinematic::KinematicArrive(this, aiTarget->transform, 10.0f, 1.0f); Kinematic::KinematicSteeringOutput steering = kSeekAlgo.getSteering(); aiComponent->SetSteering(&steering);*/ /*Dynamic::DynamicSeek dSeekAlgo = Dynamic::DynamicSeek(this, aiTarget->transform); dSeekAlgo.getSteering();*/ /*Dynamic::DynamicArrive dArriveAlgo = Dynamic::DynamicArrive(this, aiTarget->transform, 10.0f, 25.0f, 1.0f); dArriveAlgo.getSteering();*/ /*Dynamic::DynamicFlee dFleeAlgo = Dynamic::DynamicFlee(this, aiTarget->transform); dFleeAlgo.getSteering();*/ } this->GameObject::Update(deltaTime); }
; A178869: a(n) = 9*a(n-1) - 10*a(n-2); a(0)=0, a(1)=1. ; Submitted by Jamie Morken(s2) ; 0,1,9,71,549,4231,32589,250991,1933029,14887351,114655869,883029311,6800705109,52376052871,403377424749,3106636294031,23925952398789,184267208648791,1419145353851229,10929636098173151,84175271345046069 mov $2,1 lpb $0 sub $0,1 add $1,$2 add $2,$1 mul $1,5 mul $2,2 lpe mov $0,$1 div $0,5
#ifndef OBJECTS_OBJMGR___SEQ_MAP_CI__HPP #define OBJECTS_OBJMGR___SEQ_MAP_CI__HPP /* $Id: seq_map_ci.hpp 496211 2016-03-24 15:33:11Z vasilche $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Authors: * Eugene Vasilchenko * * File Description: * CSeqMap -- formal sequence map to describe sequence parts in general, * i.e. location and type only, without providing real data * */ #include <objmgr/seq_map.hpp> #include <objmgr/impl/heap_scope.hpp> #include <objmgr/tse_handle.hpp> #include <objects/seq/seq_id_handle.hpp> #include <objects/seq/Seq_data.hpp> #include <util/range.hpp> #include <util/sequtil/sequtil.hpp> BEGIN_NCBI_SCOPE BEGIN_SCOPE(objects) class CSeq_entry; class CSeq_entry_Handle; /** @addtogroup ObjectManagerIterators * * @{ */ class CScope; class CSeqMap; class CSeq_entry; class NCBI_XOBJMGR_EXPORT CSeqMap_CI_SegmentInfo { public: CSeqMap_CI_SegmentInfo(void); TSeqPos GetRefPosition(void) const; bool GetRefMinusStrand(void) const; const CSeqMap& x_GetSeqMap(void) const; size_t x_GetIndex(void) const; const CSeqMap::CSegment& x_GetSegment(void) const; const CSeqMap::CSegment& x_GetNextSegment(void) const; bool InRange(void) const; CSeqMap::ESegmentType GetType(void) const; bool IsSetData(void) const; bool x_Move(bool minusStrand, CScope* scope); TSeqPos x_GetLevelRealPos(void) const; TSeqPos x_GetLevelRealEnd(void) const; TSeqPos x_GetLevelPos(void) const; TSeqPos x_GetLevelEnd(void) const; TSeqPos x_GetSkipBefore(void) const; TSeqPos x_GetSkipAfter(void) const; TSeqPos x_CalcLength(void) const; TSeqPos x_GetTopOffset(void) const; int x_GetSequenceClass(void) const; private: // seqmap CTSE_Handle m_TSE; CConstRef<CSeqMap> m_SeqMap; // index of segment in seqmap size_t m_Index; // position inside m_SeqMap // m_RangeEnd >= m_RangePos TSeqPos m_LevelRangePos; TSeqPos m_LevelRangeEnd; bool m_MinusStrand; mutable Int1 m_SequenceClass; friend class CSeqMap_CI; friend class CSeqMap; }; /// Selector used in CSeqMap methods returning iterators. struct NCBI_XOBJMGR_EXPORT SSeqMapSelector { typedef CSeqMap::TFlags TFlags; SSeqMapSelector(void); SSeqMapSelector(TFlags flags, size_t resolve_count = 0); /// Find segment containing the position SSeqMapSelector& SetPosition(TSeqPos pos) { m_Position = pos; return *this; } /// Set range for iterator SSeqMapSelector& SetRange(TSeqPos start, TSeqPos length) { m_Position = start; m_Length = length; return *this; } typedef CRange<TSeqPos> TRange; /// Set range for iterator - CRange<> version SSeqMapSelector& SetRange(const TRange& range) { m_Position = range.GetFrom(); m_Length = range.GetLength(); return *this; } /// Set strand to iterate over SSeqMapSelector& SetStrand(ENa_strand strand) { m_MinusStrand = IsReverse(strand); return *this; } /// Set max depth of resolving seq-map SSeqMapSelector& SetResolveCount(size_t res_cnt) { m_MaxResolveCount = res_cnt; return *this; } SSeqMapSelector& SetLinkUsedTSE(bool link = true) { m_LinkUsedTSE = link; return *this; } SSeqMapSelector& SetLinkUsedTSE(const CTSE_Handle& top_tse) { m_LinkUsedTSE = true; m_TopTSE = top_tse; return *this; } SSeqMapSelector& SetLinkUsedTSE(vector<CTSE_Handle>& used_tses) { m_LinkUsedTSE = true; m_UsedTSEs = &used_tses; return *this; } /// Limit TSE to resolve references SSeqMapSelector& SetLimitTSE(const CSeq_entry_Handle& tse); /// Select segment type(s) SSeqMapSelector& SetFlags(TFlags flags) { m_Flags = flags; return *this; } SSeqMapSelector& SetByFeaturePolicy(void) { m_Flags |= CSeqMap::fByFeaturePolicy; return *this; } SSeqMapSelector& SetBySequenceClass(void) { m_Flags |= CSeqMap::fBySequenceClass; return *this; } size_t GetResolveCount(void) const { return m_MaxResolveCount; } bool CanResolve(void) const { return GetResolveCount() > 0; } void PushResolve(void) { _ASSERT(CanResolve()); --m_MaxResolveCount; } void PopResolve(void) { ++m_MaxResolveCount; _ASSERT(CanResolve()); } void AddUsedTSE(const CTSE_Handle& tse) const; private: friend class CSeqMap; friend class CSeqMap_CI; bool x_HasLimitTSE(void) const { return m_LimitTSE; } const CTSE_Handle& x_GetLimitTSE(CScope* scope = 0) const; // position of segment in whole sequence in residues TSeqPos m_Position; // length of current segment TSeqPos m_Length; // Requested strand bool m_MinusStrand; // Link segment bioseqs to master bool m_LinkUsedTSE; // Top-level TSE (for used TSEs linking) CTSE_Handle m_TopTSE; // maximum resolution level size_t m_MaxResolveCount; // limit search to single TSE CTSE_Handle m_LimitTSE; // return all intermediate resolved sequences TFlags m_Flags; // keep all used TSEs which can not be linked vector<CTSE_Handle>* m_UsedTSEs; }; /// Iterator over CSeqMap class NCBI_XOBJMGR_EXPORT CSeqMap_CI { public: typedef SSeqMapSelector::TFlags TFlags; CSeqMap_CI(void); CSeqMap_CI(const CBioseq_Handle& bioseq, const SSeqMapSelector& selector, TSeqPos pos = 0); CSeqMap_CI(const CBioseq_Handle& bioseq, const SSeqMapSelector& selector, const CRange<TSeqPos>& range); CSeqMap_CI(const CConstRef<CSeqMap>& seqmap, CScope* scope, const SSeqMapSelector& selector, TSeqPos pos = 0); CSeqMap_CI(const CConstRef<CSeqMap>& seqmap, CScope* scope, const SSeqMapSelector& selector, const CRange<TSeqPos>& range); ~CSeqMap_CI(void); bool IsInvalid(void) const; bool IsValid(void) const; DECLARE_OPERATOR_BOOL(IsValid()); bool operator==(const CSeqMap_CI& seg) const; bool operator!=(const CSeqMap_CI& seg) const; bool operator< (const CSeqMap_CI& seg) const; bool operator> (const CSeqMap_CI& seg) const; bool operator<=(const CSeqMap_CI& seg) const; bool operator>=(const CSeqMap_CI& seg) const; /// go to next/next segment, return false if no more segments /// if no_resolve_current == true, do not resolve current segment bool Next(bool resolveExternal = true); bool Prev(void); TFlags GetFlags(void) const; void SetFlags(TFlags flags); CSeqMap_CI& operator++(void); CSeqMap_CI& operator--(void); /// return the depth of current segment size_t GetDepth(void) const; /// return position of current segment in sequence TSeqPos GetPosition(void) const; /// return length of current segment TSeqPos GetLength(void) const; /// return true if current segment is a gap of unknown length bool IsUnknownLength(void) const; /// return end position of current segment in sequence (exclusive) TSeqPos GetEndPosition(void) const; CSeqMap::ESegmentType GetType(void) const; bool IsSetData(void) const; /// will allow only regular data segments (whole, plus strand) const CSeq_data& GetData(void) const; /// will allow any data segments, user should check for position and strand const CSeq_data& GetRefData(void) const; /// return CSeq_literal with gap data, or null if either the segment /// is not a gap, or an unspecified gap CConstRef<CSeq_literal> GetRefGapLiteral(void) const; /// The following function makes sense only /// when the segment is a reference to another seq. CSeq_id_Handle GetRefSeqid(void) const; TSeqPos GetRefPosition(void) const; TSeqPos GetRefEndPosition(void) const; bool GetRefMinusStrand(void) const; CScope* GetScope(void) const; const CTSE_Handle& GetUsingTSE(void) const; bool FeaturePolicyWasApplied(void) const; private: friend class CSeqMap; friend class CSeqMap_I; typedef CSeqMap_CI_SegmentInfo TSegmentInfo; CSeqMap_CI(const CSeqMap_CI& base, const CSeqMap& seqmap, size_t index, TSeqPos pos); const TSegmentInfo& x_GetSegmentInfo(void) const; TSegmentInfo& x_GetSegmentInfo(void); // Check if the current reference can be resolved in the TSE // set by selector bool x_RefTSEMatch(const CSeqMap::CSegment& seg) const; bool x_CanResolve(const CSeqMap::CSegment& seg) const; // valid iterator const CSeqMap& x_GetSeqMap(void) const; size_t x_GetIndex(void) const; const CSeqMap::CSegment& x_GetSegment(void) const; TSeqPos x_GetTopOffset(void) const; void x_Resolve(TSeqPos pos); CBioseq_Handle x_GetBioseq(const CSeq_id& seq_id) const; bool x_Found(void) const; bool x_Push(TSeqPos offset, bool resolveExternal); bool x_Push(TSeqPos offset); void x_Push(const CConstRef<CSeqMap>& seqMap, const CTSE_Handle& tse, TSeqPos from, TSeqPos length, bool minusStrand, TSeqPos pos); bool x_Pop(void); bool x_Next(bool resolveExternal); bool x_Next(void); bool x_Prev(void); bool x_TopNext(void); bool x_TopPrev(void); bool x_SettleNext(void); bool x_SettlePrev(void); void x_Select(const CConstRef<CSeqMap>& seqMap, const SSeqMapSelector& selector, TSeqPos pos); int x_GetSequenceClass(void) const; // CBioseq_Handle::ESequenceClass typedef vector<TSegmentInfo> TStack; // scope for length resolution CHeapScope m_Scope; // position stack TStack m_Stack; // iterator parameters SSeqMapSelector m_Selector; // search range TSeqPos m_SearchPos; TSeqPos m_SearchEnd; // Feature policy was applied bool m_FeaturePolicyWasApplied; protected: void x_UpdateLength(void); }; class CBioseq_EditHandle; /// Non-const iterator over CSeqMap (allows to edit the sequence). class NCBI_XOBJMGR_EXPORT CSeqMap_I : public CSeqMap_CI { public: CSeqMap_I(void); CSeqMap_I(const CBioseq_EditHandle& bioseq, const SSeqMapSelector& selector, TSeqPos pos = 0); CSeqMap_I(const CBioseq_EditHandle& bioseq, const SSeqMapSelector& selector, const CRange<TSeqPos>& range); CSeqMap_I(CRef<CSeqMap>& seqmap, CScope* scope, const SSeqMapSelector& selector, TSeqPos pos = 0); CSeqMap_I(CRef<CSeqMap>& seqmap, CScope* scope, const SSeqMapSelector& selector, const CRange<TSeqPos>& range); ~CSeqMap_I(void); /// Change current segment to gap. void SetGap(TSeqPos length, CSeq_data* gap_data = 0); /// Change current segment to reference. void SetRef(const CSeq_id_Handle& ref_id, TSeqPos ref_pos, TSeqPos ref_length, bool ref_minus_strand = false); /// Change current segment to data. void SetSeq_data(TSeqPos length, CSeq_data& data); /// Insert gap. On return the iterator points to the new segment. CSeqMap_I& InsertGap(TSeqPos length, CSeq_data* gap_data = 0); /// Insert reference. On return the iterator points to the new segment. CSeqMap_I& InsertRef(const CSeq_id_Handle& ref_id, TSeqPos ref_pos, TSeqPos ref_length, bool ref_minus_strand = false); /// Insert data. On return the iterator points to the new segment. CSeqMap_I& InsertData(TSeqPos length, CSeq_data& data); /// Insert data segment using the sequence string and the selected coding. CSeqMap_I& InsertData(const string& buffer, CSeqUtil::ECoding buffer_coding, CSeq_data::E_Choice seq_data_coding); /// Remove current segment. On return the iterator points to the next /// segment or becomes invalid. CSeqMap_I& Remove(void); /// Get current sequence as a string with the selected encoding. /// NOTE: Some seq-data types (Gap) and encodings (Ncbipna, Ncbipaa) /// are not supported. void GetSequence(string& buffer, CSeqUtil::ECoding buffer_coding) const; /// Set sequence data. The buffer is converted from buffer_coding /// to seq_data_coding and put into the new seq-data. /// NOTE: Some seq-data types (Gap) and encodings (Ncbipna, Ncbipaa) /// are not supported. void SetSequence(const string& buffer, CSeqUtil::ECoding buffer_coding, CSeq_data::E_Choice seq_data_coding); private: static SSeqMapSelector sx_AdjustSelector(const SSeqMapSelector& selector); CRef<CSeqMap> m_SeqMap; }; ///////////////////////////////////////////////////////////////////// // CSeqMap_CI_SegmentInfo inline const CSeqMap& CSeqMap_CI_SegmentInfo::x_GetSeqMap(void) const { return *m_SeqMap; } inline size_t CSeqMap_CI_SegmentInfo::x_GetIndex(void) const { return m_Index; } inline const CSeqMap::CSegment& CSeqMap_CI_SegmentInfo::x_GetSegment(void) const { return x_GetSeqMap().x_GetSegment(x_GetIndex()); } inline CSeqMap_CI_SegmentInfo::CSeqMap_CI_SegmentInfo(void) : m_Index(kInvalidSeqPos), m_LevelRangePos(kInvalidSeqPos), m_LevelRangeEnd(kInvalidSeqPos), m_MinusStrand(false), m_SequenceClass(-1) { } inline TSeqPos CSeqMap_CI_SegmentInfo::x_GetLevelRealPos(void) const { return x_GetSegment().m_Position; } inline TSeqPos CSeqMap_CI_SegmentInfo::x_GetLevelRealEnd(void) const { const CSeqMap::CSegment& seg = x_GetSegment(); return seg.m_Position + seg.m_Length; } inline TSeqPos CSeqMap_CI_SegmentInfo::x_GetLevelPos(void) const { return max(m_LevelRangePos, x_GetLevelRealPos()); } inline TSeqPos CSeqMap_CI_SegmentInfo::x_GetLevelEnd(void) const { return min(m_LevelRangeEnd, x_GetLevelRealEnd()); } inline TSeqPos CSeqMap_CI_SegmentInfo::x_GetSkipBefore(void) const { TSignedSeqPos skip = m_LevelRangePos - x_GetLevelRealPos(); if ( skip < 0 ) skip = 0; return skip; } inline TSeqPos CSeqMap_CI_SegmentInfo::x_GetSkipAfter(void) const { TSignedSeqPos skip = x_GetLevelRealEnd() - m_LevelRangeEnd; if ( skip < 0 ) skip = 0; return skip; } inline TSeqPos CSeqMap_CI_SegmentInfo::x_CalcLength(void) const { return x_GetLevelEnd() - x_GetLevelPos(); } inline bool CSeqMap_CI_SegmentInfo::GetRefMinusStrand(void) const { return x_GetSegment().m_RefMinusStrand ^ m_MinusStrand; } inline bool CSeqMap_CI_SegmentInfo::InRange(void) const { const CSeqMap::CSegment& seg = x_GetSegment(); return seg.m_Position < m_LevelRangeEnd && seg.m_Position + seg.m_Length > m_LevelRangePos; } inline CSeqMap::ESegmentType CSeqMap_CI_SegmentInfo::GetType(void) const { return InRange()? CSeqMap::ESegmentType(x_GetSegment().m_SegType): CSeqMap::eSeqEnd; } inline bool CSeqMap_CI_SegmentInfo::IsSetData(void) const { return InRange() && x_GetSegment().IsSetData(); } ///////////////////////////////////////////////////////////////////// // CSeqMap_CI inline size_t CSeqMap_CI::GetDepth(void) const { return m_Stack.size(); } inline const CSeqMap_CI::TSegmentInfo& CSeqMap_CI::x_GetSegmentInfo(void) const { return m_Stack.back(); } inline CSeqMap_CI::TSegmentInfo& CSeqMap_CI::x_GetSegmentInfo(void) { return m_Stack.back(); } inline const CSeqMap& CSeqMap_CI::x_GetSeqMap(void) const { return x_GetSegmentInfo().x_GetSeqMap(); } inline size_t CSeqMap_CI::x_GetIndex(void) const { return x_GetSegmentInfo().x_GetIndex(); } inline const CSeqMap::CSegment& CSeqMap_CI::x_GetSegment(void) const { return x_GetSegmentInfo().x_GetSegment(); } inline CScope* CSeqMap_CI::GetScope(void) const { return m_Scope.GetScopeOrNull(); } inline CSeqMap::ESegmentType CSeqMap_CI::GetType(void) const { return x_GetSegmentInfo().GetType(); } inline bool CSeqMap_CI::IsSetData(void) const { return x_GetSegmentInfo().IsSetData(); } inline TSeqPos CSeqMap_CI::GetPosition(void) const { return m_Selector.m_Position; } inline TSeqPos CSeqMap_CI::GetLength(void) const { return m_Selector.m_Length; } inline TSeqPos CSeqMap_CI::GetEndPosition(void) const { return m_Selector.m_Position + m_Selector.m_Length; } inline bool CSeqMap_CI::IsInvalid(void) const { return m_Stack.empty(); } inline TSeqPos CSeqMap_CI::GetRefPosition(void) const { return x_GetSegmentInfo().GetRefPosition(); } inline bool CSeqMap_CI::GetRefMinusStrand(void) const { return x_GetSegmentInfo().GetRefMinusStrand(); } inline TSeqPos CSeqMap_CI::GetRefEndPosition(void) const { return GetRefPosition() + GetLength(); } inline bool CSeqMap_CI::operator==(const CSeqMap_CI& seg) const { return GetPosition() == seg.GetPosition() && m_Stack.size() == seg.m_Stack.size() && x_GetIndex() == seg.x_GetIndex(); } inline bool CSeqMap_CI::operator<(const CSeqMap_CI& seg) const { return GetPosition() < seg.GetPosition() || (GetPosition() == seg.GetPosition() && (m_Stack.size() < seg.m_Stack.size() || (m_Stack.size() == seg.m_Stack.size() && x_GetIndex() < seg.x_GetIndex()))); } inline bool CSeqMap_CI::operator>(const CSeqMap_CI& seg) const { return GetPosition() > seg.GetPosition() || (GetPosition() == seg.GetPosition() && (m_Stack.size() > seg.m_Stack.size() || (m_Stack.size() == seg.m_Stack.size() && x_GetIndex() > seg.x_GetIndex()))); } inline bool CSeqMap_CI::operator!=(const CSeqMap_CI& seg) const { return !(*this == seg); } inline bool CSeqMap_CI::operator<=(const CSeqMap_CI& seg) const { return !(*this > seg); } inline bool CSeqMap_CI::operator>=(const CSeqMap_CI& seg) const { return !(*this < seg); } inline CSeqMap_CI& CSeqMap_CI::operator++(void) { Next(); return *this; } inline CSeqMap_CI& CSeqMap_CI::operator--(void) { Prev(); return *this; } inline CSeqMap_CI::TFlags CSeqMap_CI::GetFlags(void) const { return m_Selector.m_Flags; } inline const CTSE_Handle& CSeqMap_CI::GetUsingTSE(void) const { return x_GetSegmentInfo().m_TSE; } inline bool CSeqMap_CI::FeaturePolicyWasApplied(void) const { return m_FeaturePolicyWasApplied; } ///////////////////////////////////////////////////////////////////// // CSeqMap_I /* @} */ END_SCOPE(objects) END_NCBI_SCOPE #endif // OBJECTS_OBJMGR___SEQ_MAP_CI__HPP
SECTION rodata_font_fzx PUBLIC _ff_ind_TerminoLatin5 _ff_ind_TerminoLatin5: BINARY "font/fzx/fonts/ind/Termino/Termino_Latin5.fzx"
global _start section .text _start: jmp code hello_world: db 'hello world',0xa code: mov al, 1 xor rdi, rdi add rdi, 1 lea rsi, [rel hello_world] xor rdx,rdx add rdx,12 syscall xor rax,rax add rax,60 xor rdi,rdi syscall
// Copyright 2013 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 "google_apis/gcm/base/socket_stream.h" #include <stdint.h> #include <memory> #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/run_loop.h" #include "base/stl_util.h" #include "base/strings/string_piece.h" #include "base/test/bind.h" #include "base/test/task_environment.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote.h" #include "net/base/ip_address.h" #include "net/base/network_isolation_key.h" #include "net/log/net_log_source.h" #include "net/socket/socket_test_util.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request_test_util.h" #include "services/network/network_context.h" #include "services/network/network_service.h" #include "services/network/public/mojom/proxy_resolving_socket.mojom.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/origin.h" namespace gcm { namespace { typedef std::vector<net::MockRead> ReadList; typedef std::vector<net::MockWrite> WriteList; const char kReadData[] = "read_data"; const int kReadDataSize = base::size(kReadData) - 1; const char kReadData2[] = "read_alternate_data"; const int kReadData2Size = base::size(kReadData2) - 1; const char kWriteData[] = "write_data"; const int kWriteDataSize = base::size(kWriteData) - 1; class GCMSocketStreamTest : public testing::Test { public: GCMSocketStreamTest(); ~GCMSocketStreamTest() override; // Build a socket with the expected reads and writes. void BuildSocket(const ReadList& read_list, const WriteList& write_list); // Pump the message loop until idle. void PumpLoop(); // Simulates a google::protobuf::io::CodedInputStream read. base::StringPiece DoInputStreamRead(int bytes); // Simulates a google::protobuf::io::CodedOutputStream write. int DoOutputStreamWrite(const base::StringPiece& write_src); // Simulates a google::protobuf::io::CodedOutputStream write, but do not call // flush. int DoOutputStreamWriteWithoutFlush(const base::StringPiece& write_src); // Synchronous Refresh wrapper. void WaitForData(int msg_size); SocketInputStream* input_stream() { return socket_input_stream_.get(); } SocketOutputStream* output_stream() { return socket_output_stream_.get(); } mojo::Remote<network::mojom::ProxyResolvingSocket> mojo_socket_remote_; void set_socket_output_stream(std::unique_ptr<SocketOutputStream> stream) { socket_output_stream_ = std::move(stream); } private: void OpenConnection(); void ResetInputStream(); void ResetOutputStream(); base::test::TaskEnvironment task_environment_; // SocketStreams and their data providers. ReadList mock_reads_; WriteList mock_writes_; std::unique_ptr<net::StaticSocketDataProvider> data_provider_; std::unique_ptr<net::SSLSocketDataProvider> ssl_data_provider_; std::unique_ptr<SocketInputStream> socket_input_stream_; std::unique_ptr<SocketOutputStream> socket_output_stream_; // net:: components. net::AddressList address_list_; std::unique_ptr<net::NetworkChangeNotifier> network_change_notifier_; std::unique_ptr<network::NetworkService> network_service_; mojo::Remote<network::mojom::NetworkContext> network_context_remote_; net::MockClientSocketFactory socket_factory_; net::TestURLRequestContext url_request_context_; std::unique_ptr<network::NetworkContext> network_context_; mojo::Remote<network::mojom::ProxyResolvingSocketFactory> mojo_socket_factory_remote_; mojo::ScopedDataPipeConsumerHandle receive_pipe_handle_; mojo::ScopedDataPipeProducerHandle send_pipe_handle_; }; GCMSocketStreamTest::GCMSocketStreamTest() : task_environment_(base::test::TaskEnvironment::MainThreadType::IO), network_change_notifier_( net::NetworkChangeNotifier::CreateMockIfNeeded()), network_service_(network::NetworkService::CreateForTesting()), url_request_context_(true /* delay_initialization */) { address_list_ = net::AddressList::CreateFromIPAddress( net::IPAddress::IPv4Localhost(), 5228); socket_factory_.set_enable_read_if_ready(true); url_request_context_.set_client_socket_factory(&socket_factory_); url_request_context_.Init(); network_context_ = std::make_unique<network::NetworkContext>( network_service_.get(), network_context_remote_.BindNewPipeAndPassReceiver(), &url_request_context_, /*cors_exempt_header_list=*/std::vector<std::string>()); } GCMSocketStreamTest::~GCMSocketStreamTest() {} void GCMSocketStreamTest::BuildSocket(const ReadList& read_list, const WriteList& write_list) { mock_reads_ = read_list; mock_writes_ = write_list; data_provider_ = std::make_unique<net::StaticSocketDataProvider>( mock_reads_, mock_writes_); ssl_data_provider_ = std::make_unique<net::SSLSocketDataProvider>(net::SYNCHRONOUS, net::OK); socket_factory_.AddSocketDataProvider(data_provider_.get()); socket_factory_.AddSSLSocketDataProvider(ssl_data_provider_.get()); OpenConnection(); ResetInputStream(); ResetOutputStream(); } void GCMSocketStreamTest::PumpLoop() { base::RunLoop run_loop; run_loop.RunUntilIdle(); } base::StringPiece GCMSocketStreamTest::DoInputStreamRead(int bytes) { int total_bytes_read = 0; const void* initial_buffer = nullptr; const void* buffer = nullptr; int size = 0; do { DCHECK(socket_input_stream_->GetState() == SocketInputStream::EMPTY || socket_input_stream_->GetState() == SocketInputStream::READY); if (!socket_input_stream_->Next(&buffer, &size)) break; total_bytes_read += size; if (initial_buffer) { // Verify the buffer doesn't skip data. EXPECT_EQ(static_cast<const uint8_t*>(initial_buffer) + total_bytes_read, static_cast<const uint8_t*>(buffer) + size); } else { initial_buffer = buffer; } } while (total_bytes_read < bytes); if (total_bytes_read > bytes) { socket_input_stream_->BackUp(total_bytes_read - bytes); total_bytes_read = bytes; } return base::StringPiece(static_cast<const char*>(initial_buffer), total_bytes_read); } int GCMSocketStreamTest::DoOutputStreamWrite( const base::StringPiece& write_src) { int total_bytes_written = DoOutputStreamWriteWithoutFlush(write_src); base::RunLoop run_loop; if (socket_output_stream_->Flush(run_loop.QuitClosure()) == net::ERR_IO_PENDING) { run_loop.Run(); } return total_bytes_written; } int GCMSocketStreamTest::DoOutputStreamWriteWithoutFlush( const base::StringPiece& write_src) { DCHECK_EQ(socket_output_stream_->GetState(), SocketOutputStream::EMPTY); int total_bytes_written = 0; void* buffer = nullptr; int size = 0; const int bytes = write_src.size(); do { if (!socket_output_stream_->Next(&buffer, &size)) break; int bytes_to_write = (size < bytes ? size : bytes); memcpy(buffer, write_src.data() + total_bytes_written, bytes_to_write); if (bytes_to_write < size) socket_output_stream_->BackUp(size - bytes_to_write); total_bytes_written += bytes_to_write; } while (total_bytes_written < bytes); return total_bytes_written; } void GCMSocketStreamTest::WaitForData(int msg_size) { while (input_stream()->UnreadByteCount() < msg_size) { base::RunLoop run_loop; if (input_stream()->Refresh(run_loop.QuitClosure(), msg_size - input_stream()->UnreadByteCount()) == net::ERR_IO_PENDING) { run_loop.Run(); } if (input_stream()->GetState() == SocketInputStream::CLOSED) return; } } void GCMSocketStreamTest::OpenConnection() { network_context_->CreateProxyResolvingSocketFactory( mojo_socket_factory_remote_.BindNewPipeAndPassReceiver()); base::RunLoop run_loop; int net_error = net::ERR_FAILED; const GURL kDestination("https://example.com"); network::mojom::ProxyResolvingSocketOptionsPtr options = network::mojom::ProxyResolvingSocketOptions::New(); options->use_tls = true; const url::Origin kOrigin = url::Origin::Create(kDestination); mojo_socket_factory_remote_->CreateProxyResolvingSocket( kDestination, net::NetworkIsolationKey(kOrigin /* top_frame_origin */, kOrigin /* frame_origin */), std::move(options), net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS), mojo_socket_remote_.BindNewPipeAndPassReceiver(), mojo::NullRemote() /* observer */, base::BindLambdaForTesting( [&](int result, const absl::optional<net::IPEndPoint>& local_addr, const absl::optional<net::IPEndPoint>& peer_addr, mojo::ScopedDataPipeConsumerHandle receive_pipe_handle, mojo::ScopedDataPipeProducerHandle send_pipe_handle) { net_error = result; receive_pipe_handle_ = std::move(receive_pipe_handle); send_pipe_handle_ = std::move(send_pipe_handle); run_loop.Quit(); })); run_loop.Run(); PumpLoop(); } void GCMSocketStreamTest::ResetInputStream() { DCHECK(mojo_socket_remote_); socket_input_stream_ = std::make_unique<SocketInputStream>(std::move(receive_pipe_handle_)); } void GCMSocketStreamTest::ResetOutputStream() { DCHECK(mojo_socket_remote_); socket_output_stream_ = std::make_unique<SocketOutputStream>(std::move(send_pipe_handle_)); } // A read where all data is already available. TEST_F(GCMSocketStreamTest, ReadDataSync) { ReadList read_list; read_list.push_back( net::MockRead(net::SYNCHRONOUS, kReadData, kReadDataSize)); read_list.push_back(net::MockRead(net::ASYNC, net::OK) /* EOF */); BuildSocket(read_list, WriteList()); WaitForData(kReadDataSize); ASSERT_EQ(std::string(kReadData, kReadDataSize), DoInputStreamRead(kReadDataSize)); } // A read that comes in two parts. TEST_F(GCMSocketStreamTest, ReadPartialDataSync) { int first_read_len = kReadDataSize / 2; int second_read_len = kReadDataSize - first_read_len; ReadList read_list; read_list.push_back( net::MockRead(net::SYNCHRONOUS, kReadData, first_read_len)); read_list.push_back( net::MockRead(net::SYNCHRONOUS, &kReadData[first_read_len], second_read_len)); // Add an EOF. read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK)); BuildSocket(read_list, WriteList()); WaitForData(kReadDataSize); ASSERT_EQ(std::string(kReadData, kReadDataSize), DoInputStreamRead(kReadDataSize)); } // A read where no data is available at first (IO_PENDING will be returned). TEST_F(GCMSocketStreamTest, ReadAsync) { int first_read_len = kReadDataSize / 2; int second_read_len = kReadDataSize - first_read_len; ReadList read_list; read_list.push_back( net::MockRead(net::ASYNC, kReadData, first_read_len)); read_list.push_back( net::MockRead(net::ASYNC, &kReadData[first_read_len], second_read_len)); read_list.push_back(net::MockRead(net::ASYNC, net::OK) /* EOF */); BuildSocket(read_list, WriteList()); WaitForData(kReadDataSize); ASSERT_EQ(std::string(kReadData, kReadDataSize), DoInputStreamRead(kReadDataSize)); } // Simulate two packets arriving at once. Read them in two separate calls. TEST_F(GCMSocketStreamTest, TwoReadsAtOnce) { std::string long_data = std::string(kReadData, kReadDataSize) + std::string(kReadData2, kReadData2Size); ReadList read_list; read_list.push_back( net::MockRead(net::SYNCHRONOUS, long_data.c_str(), long_data.size())); // Add an EOF. read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK)); BuildSocket(read_list, WriteList()); WaitForData(kReadDataSize); ASSERT_EQ(std::string(kReadData, kReadDataSize), DoInputStreamRead(kReadDataSize)); WaitForData(kReadData2Size); ASSERT_EQ(std::string(kReadData2, kReadData2Size), DoInputStreamRead(kReadData2Size)); } // Simulate two packets arriving at once. Read them in two calls separated // by a Rebuild. TEST_F(GCMSocketStreamTest, TwoReadsAtOnceWithRebuild) { std::string long_data = std::string(kReadData, kReadDataSize) + std::string(kReadData2, kReadData2Size); ReadList read_list; read_list.push_back( net::MockRead(net::SYNCHRONOUS, long_data.c_str(), long_data.size())); // Add an EOF. read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK)); BuildSocket(read_list, WriteList()); WaitForData(kReadDataSize); ASSERT_EQ(std::string(kReadData, kReadDataSize), DoInputStreamRead(kReadDataSize)); input_stream()->RebuildBuffer(); WaitForData(kReadData2Size); ASSERT_EQ(std::string(kReadData2, kReadData2Size), DoInputStreamRead(kReadData2Size)); } // Simulate a read that is aborted. TEST_F(GCMSocketStreamTest, ReadError) { int result = net::ERR_ABORTED; BuildSocket(ReadList(1, net::MockRead(net::SYNCHRONOUS, result)), WriteList()); WaitForData(kReadDataSize); ASSERT_EQ(SocketInputStream::CLOSED, input_stream()->GetState()); ASSERT_EQ(net::ERR_FAILED, input_stream()->last_error()); } // Simulate a read after the connection is closed. TEST_F(GCMSocketStreamTest, ReadDisconnected) { BuildSocket(ReadList(1, net::MockRead(net::SYNCHRONOUS, net::ERR_IO_PENDING)), WriteList()); mojo_socket_remote_.reset(); WaitForData(kReadDataSize); ASSERT_EQ(SocketInputStream::CLOSED, input_stream()->GetState()); ASSERT_EQ(net::ERR_FAILED, input_stream()->last_error()); } // Write a full message in one go. TEST_F(GCMSocketStreamTest, WriteFull) { BuildSocket(ReadList(1, net::MockRead(net::SYNCHRONOUS, net::ERR_IO_PENDING)), WriteList(1, net::MockWrite(net::SYNCHRONOUS, kWriteData, kWriteDataSize))); ASSERT_EQ(kWriteDataSize, DoOutputStreamWrite(base::StringPiece(kWriteData, kWriteDataSize))); } // Write a message in two go's. TEST_F(GCMSocketStreamTest, WritePartial) { WriteList write_list; write_list.push_back(net::MockWrite(net::SYNCHRONOUS, kWriteData, kWriteDataSize / 2)); write_list.push_back(net::MockWrite(net::SYNCHRONOUS, kWriteData + kWriteDataSize / 2, kWriteDataSize / 2)); BuildSocket(ReadList(1, net::MockRead(net::SYNCHRONOUS, net::ERR_IO_PENDING)), write_list); ASSERT_EQ(kWriteDataSize, DoOutputStreamWrite(base::StringPiece(kWriteData, kWriteDataSize))); } // Regression test for crbug.com/866635. TEST_F(GCMSocketStreamTest, WritePartialWithLengthChecking) { // Add a prefix data in front of kWriteData. std::string prefix_data("xxxxx"); const size_t kPrefixDataSize = 5; // |pipe| has a capacity that is one byte smaller than |prefix_data.size()| + // |kWriteDataSize|. This is so that the first write is a partial write // of |prefix_data|, and the second write is a complete write of kWriteData. // The 1 byte shortage is to simulate the partial write. mojo::ScopedDataPipeProducerHandle producer_handle; mojo::ScopedDataPipeConsumerHandle consumer_handle; ASSERT_EQ( mojo::CreateDataPipe(kWriteDataSize + prefix_data.size() - 1 /* size */, producer_handle, consumer_handle), MOJO_RESULT_OK); // Prepopulate |producer_handle| of |prefix_data|, now the pipe's capacity is // less than |kWriteDataSize|. uint32_t num_bytes = prefix_data.size(); MojoResult r = producer_handle->WriteData(prefix_data.data(), &num_bytes, MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(MOJO_RESULT_OK, r); ASSERT_EQ(prefix_data.size(), num_bytes); // Create a SocketOutputStream from the producer pipe. auto socket_output_stream = std::make_unique<SocketOutputStream>(std::move(producer_handle)); set_socket_output_stream(std::move(socket_output_stream)); // Write but do not flush. EXPECT_EQ(kWriteDataSize, DoOutputStreamWriteWithoutFlush(kWriteData)); base::RunLoop run_loop; output_stream()->Flush(run_loop.QuitClosure()); // Flush should be able to flush exactly 5 bytes, because of the data pipe // capacity. base::RunLoop().RunUntilIdle(); std::string contents; // Read prefix. char buffer[kPrefixDataSize]; uint32_t read_size = sizeof(buffer); ASSERT_EQ(MOJO_RESULT_OK, consumer_handle->ReadData( buffer, &read_size, MOJO_READ_DATA_FLAG_NONE)); ASSERT_EQ(kPrefixDataSize, read_size); contents += std::string(buffer, read_size); base::RunLoop().RunUntilIdle(); // Flush now should complete. run_loop.Run(); // Closes |producer_handle|. set_socket_output_stream(nullptr); // Read everything in |consumer_handle| now that |producer_handle| is closed // to make sure data is as what we expected, and there is no trailing garbage // data. while (true) { char buffer[5]; uint32_t read_size = sizeof(buffer); MojoResult r = consumer_handle->ReadData(buffer, &read_size, MOJO_READ_DATA_FLAG_NONE); if (r == MOJO_RESULT_SHOULD_WAIT) continue; if (r != MOJO_RESULT_OK) break; ASSERT_EQ(MOJO_RESULT_OK, r); contents += std::string(buffer, read_size); } std::string expected(prefix_data); expected.append(kWriteData); EXPECT_EQ(expected, contents); } // Write a message completely asynchronously (returns IO_PENDING before // finishing the write in two go's). TEST_F(GCMSocketStreamTest, WriteNone) { WriteList write_list; write_list.push_back(net::MockWrite(net::SYNCHRONOUS, kWriteData, kWriteDataSize / 2)); write_list.push_back(net::MockWrite(net::SYNCHRONOUS, kWriteData + kWriteDataSize / 2, kWriteDataSize / 2)); BuildSocket(ReadList(1, net::MockRead(net::SYNCHRONOUS, net::ERR_IO_PENDING)), write_list); ASSERT_EQ(kWriteDataSize, DoOutputStreamWrite(base::StringPiece(kWriteData, kWriteDataSize))); } // Write a message then read a message. TEST_F(GCMSocketStreamTest, WriteThenRead) { ReadList read_list; read_list.push_back( net::MockRead(net::SYNCHRONOUS, kReadData, kReadDataSize)); // Add an EOF. read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK)); BuildSocket(read_list, WriteList(1, net::MockWrite(net::SYNCHRONOUS, kWriteData, kWriteDataSize))); ASSERT_EQ(kWriteDataSize, DoOutputStreamWrite(base::StringPiece(kWriteData, kWriteDataSize))); WaitForData(kReadDataSize); ASSERT_EQ(std::string(kReadData, kReadDataSize), DoInputStreamRead(kReadDataSize)); } // Read a message then write a message. TEST_F(GCMSocketStreamTest, ReadThenWrite) { ReadList read_list; read_list.push_back( net::MockRead(net::SYNCHRONOUS, kReadData, kReadDataSize)); // Add an EOF. read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK)); BuildSocket(read_list, WriteList(1, net::MockWrite(net::SYNCHRONOUS, kWriteData, kWriteDataSize))); WaitForData(kReadDataSize); ASSERT_EQ(std::string(kReadData, kReadDataSize), DoInputStreamRead(kReadDataSize)); ASSERT_EQ(kWriteDataSize, DoOutputStreamWrite(base::StringPiece(kWriteData, kWriteDataSize))); } // Simulate a write that gets aborted. TEST_F(GCMSocketStreamTest, WriteError) { int result = net::ERR_ABORTED; BuildSocket(ReadList(1, net::MockRead(net::SYNCHRONOUS, net::ERR_IO_PENDING)), WriteList(1, net::MockWrite(net::SYNCHRONOUS, result))); // Mojo data pipe buffers data, so there is a delay before write error is // observed.Continue writing if error is not observed. while (output_stream()->GetState() != SocketOutputStream::CLOSED) { DoOutputStreamWrite(base::StringPiece(kWriteData, kWriteDataSize)); } ASSERT_EQ(SocketOutputStream::CLOSED, output_stream()->GetState()); ASSERT_EQ(net::ERR_FAILED, output_stream()->last_error()); } // Simulate a write after the connection is closed. TEST_F(GCMSocketStreamTest, WriteDisconnected) { BuildSocket(ReadList(1, net::MockRead(net::SYNCHRONOUS, net::ERR_IO_PENDING)), WriteList()); mojo_socket_remote_.reset(); DoOutputStreamWrite(base::StringPiece(kWriteData, kWriteDataSize)); ASSERT_EQ(SocketOutputStream::CLOSED, output_stream()->GetState()); ASSERT_EQ(net::ERR_FAILED, output_stream()->last_error()); } } // namespace } // namespace gcm
; Z88 Small C+ Run Time Library ; Long functions ; SECTION code_clib SECTION code_l_sccz80 PUBLIC l_long_xor l_long_xor: ; dehl = secondary ; stack = primary, ret pop ix pop bc ld a,c xor l ld l,a ld a,b xor h ld h,a pop bc ld a,c xor e ld e,a ld a,b xor d ld d,a jp (ix)
#include "ScanImageTo3D.h" #include "RegardRGBDMainWindow.h" #include <iostream> #include <sstream> #include <limits> #include <Eigen/LU> #include <Eigen/Geometry> #include <open3d/pipelines/registration/GlobalOptimization.h> #include <open3d/pipelines/color_map/ColorMapOptimization.h> ScanImageTo3D::ScanImageTo3D() { } ScanImageTo3D::~ScanImageTo3D() { } void ScanImageTo3D::setup() { } void ScanImageTo3D::addNewImage(const open3d::geometry::Image& colorImg, const open3d::geometry::Image& depthImg) { //open3d::pipelines::integration::ScalableTSDFVolume volume(4.0 / 512, 0.04, open3d::pipelines::integration::TSDFVolumeColorType::RGB8); open3d::camera::PinholeCameraIntrinsic intrinsic = open3d::camera::PinholeCameraIntrinsic( open3d::camera::PinholeCameraIntrinsicParameters::PrimeSenseDefault); //intrinsic.SetIntrinsics(640, 480, 524.0, 524.0, 316.7, 238.5); // from https://www.researchgate.net/figure/ntrinsic-parameters-of-Kinect-RGB-camera_tbl2_305108995 //intrinsic.SetIntrinsics(640, 480, 517.3, 516.5, 318.6, 255.3); // from Freiburg test data set //intrinsic.SetIntrinsics(640, 480, 537.408, 537.40877, 321.897, 236.29); // from Calibration of my own camera //intrinsic.SetIntrinsics(640, 480, 533.82, 533.82, 320.55, 232.35); // from Calibration of my own camera intrinsic.SetIntrinsics(640, 480, 542.7693, 544.396, 318.79, 239.99); // from Calibration of my own camera //open3d::io::WriteImageToPNG("color.png", colorImg_); //open3d::io::WriteImageToPNG("depth.png", depthImg_); Eigen::Matrix4d identity = Eigen::Matrix4d::Identity(); auto depthFlt = depthImg.ConvertDepthToFloatImage(depthScale_, std::numeric_limits<float>::max()); open3d::geometry::RGBDImage source(colorImg, *depthFlt); //volume.Integrate(source, intrinsic, identity); { std::unique_lock<std::mutex> lock(mutex_); //triangleMesh_ = volume.ExtractTriangleMesh(); pointCloud_ = open3d::geometry::PointCloud::CreateFromRGBDImage(source, intrinsic); } if(pRegardRGBDMainWindow_ != nullptr) pRegardRGBDMainWindow_->update3DScanMesh(); } void ScanImageTo3D::saveVolume() { } void ScanImageTo3D::reset() { std::unique_lock<std::mutex> lock(mutex_); setup(); } /** * Makes a copy of the triangle mesh. */ const std::shared_ptr<open3d::geometry::TriangleMesh> ScanImageTo3D::getTriangleMesh() { std::unique_lock<std::mutex> lock(mutex_); return std::make_shared<open3d::geometry::TriangleMesh>(*triangleMesh_); } /** * Makes a copy of the point cloud. */ const std::shared_ptr<open3d::geometry::PointCloud> ScanImageTo3D::getPointCloud() { std::unique_lock<std::mutex> lock(mutex_); return std::make_shared<open3d::geometry::PointCloud>(*pointCloud_); }
; ---------------------------------------------------------------- ; Z88DK INTERFACE LIBRARY FOR THE BIFROST*2 ENGINE ; ; See "bifrost2.h" for further details ; ---------------------------------------------------------------- ; unsigned char BIFROST2_getTile(unsigned int px,unsigned int py) ; callee SECTION code_clib SECTION code_bifrost2 PUBLIC _BIFROST2_getTile_callee _BIFROST2_getTile_callee: pop af ; RET address pop hl ; HL=px pop bc ; BC=py push af INCLUDE "arch/zx/bifrost2/z80/asm_BIFROST2_getTile.asm"
; A141104: Lower Even Swappage of Upper Wythoff Sequence. ; 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,40,44,46,48,52,54,56,60,62,64,68,70,72,74,78,80,82,86,88,90,94,96,98,102,104,106,108,112,114,116,120,122,124,128,130,132,136,138,140,142,146,148,150,154,156,158,162 add $0,1 mul $0,34 div $0,26 mul $0,2 mov $1,$0
CAPS_ON - Turn the keyboard CAPS LOCK key on ; ; inputs: none ; output: none ;* * * * * * * * * * * * * *  CAPS_ON PROC FAR push ax MOV AX,40FFh JMP keyboard_set CAPS_ON ENDP comment  ;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -(MOUSE/KEY) NUMLOCK_ON - Turn the keyboard NUM LOCK key on ; ; inputs: none ; output: none ;* * * * * * * * * * * * * *  NUMLOCK_ON PROC FAR push ax MOV AX,20FFh JMP keyboard_set NUMLOCK_ON ENDP comment  ;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -(MOUSE/KEY) SCROLL_ON - Turn the keyboard SCROLL LOCK key on ; ; inputs: none ; output: none ;* * * * * * * * * * * * * *  SCROLL_ON PROC FAR push ax MOV AX,10FFh JMP keyboard_set SCROLL_ON ENDP comment  ;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -(MOUSE/KEY) INSERT_OFF - Turn the keyboard INS key off ; ; inputs: none ; output: none ;* * * * * * * * * * * * * *  INSERT_OFF PROC FAR push ax MOV AX,007Fh JMP keyboard_set INSERT_OFF ENDP comment  ;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -(MOUSE/KEY) CAPS_OFF - Turn the keyboard CAPS LOCK key off ; ; inputs: none ; output: none ;* * * * * * * * * * * * * *  CAPS_OFF PROC FAR push ax MOV AX,00BFh JMP keyboard_set CAPS_OFF ENDP comment  ;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -(MOUSE/KEY) NUMLOCK_OFF - Turn the keyboard NUM LOCK key off ; ; inputs: none ; output: none ;* * * * * * * * * * * * * *  NUMLOCK_OFF PROC FAR push ax MOV AX,00DFh JMP keyboard_set NUMLOCK_OFF ENDP comment  ;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -(MOUSE/KEY) SCROLL_OFF - Turn the keyboard SCROLL LOCK key off ; ; inputs: none ; output: none ;* * * * * * * * * * * * * *  SCROLL_OFF PROC FAR push ax MOV AX,00EFh keyboard_set: apush bx,es XOR BX,BX MOV ES,BX OR BYTE PTR ES:[417h],AH AND BYTE PTR ES:[417h],AL apop es,bx pop ax RETF SCROLL_OFF ENDP LIBSEG ENDS end
; =============================================================== ; Dec 2013 ; =============================================================== ; ; size_t strlcat(char * restrict s1, const char * restrict s2, size_t n) ; ; Append chars from s2 to s1 such that the total length of the resulting s1 ; is maximum n chars including terminating NUL. ; ; s1 is unaltered if n < strlen(s1). ; ; Return strlen(s1) + strlen(s2). ; ; =============================================================== SECTION code_string PUBLIC asm_strlcat asm_strlcat: ; enter : hl = char *s1 = dst ; de = char *s2 = src ; bc = size_t n ; exit : hl = strlen(s1) + strlen(s2) ; bc = char *s1 ; carry set if complete strlcat not possible ; ; uses : af, bc, de, hl push hl ; save s1 to compute strlen(s1) later ld a,b ; catch degenerate case where n == 0 or c jr z, szexceeded0 xor a ; find end of string s1 cpir dec hl ; hl parked on NUL and bc decr by one extra for the NUL jp po, szexceeded0 ; oops, size exceeded within string s1 ; append to string s1 with chars from string s2 ex de,hl ; de = s1, hl = s2 cpyloop: cp (hl) jr z, success ldi jp pe, cpyloop ; incomplete appending of string src xor a ld (de),a ; terminate string s1 szexceeded1: ; de = end of char *s1 (pointing at NUL) ; hl = somewhere in char *s2, next char to copy ; bc = 0 ; a = 0 ; carry reset ; stack = char *s1 push hl ; save current position in s2 to compute strlens later cpir dec hl ; hl = end of char *s2 (pointing at NUL) pop bc sbc hl,bc ex de,hl ; de = strlen(s2 remnant) pop bc sbc hl,bc ; hl = strlen(result s1) add hl,de ; return strlen(s1)+strlen(s2) scf ; not enough space ret szexceeded0: ; hl = nth char in s1 ; de = char *s2 ; bc = 0 ; a = 0 ; carry reset ; stack = char *s1 cpir dec hl ; hl = end of char *s1 (pointing at NUL) ld c,a ld b,a ex de,hl jr szexceeded1 success: ex de,hl ld (hl),a ; terminate s1 with NUL ; hl = end of char *s1 (pointing at NUL) ; carry flag reset ; stack = char *s1 pop bc sbc hl,bc ; hl = strlen(final s1) ret
Music_MeetEvilTrainer_Ch0:: tempo 124 volume 7, 7 duty 2 toggleperfectpitch notetype 12, 11, 1 rest 4 octave 3 D_ 2 C# 2 notetype 12, 4, 15 D_ 4 Music_MeetEvilTrainer_branch_7f6ae:: notetype 12, 10, 1 D_ 4 D_ 4 D_ 4 notetype 12, 7, 0 D_ 4 loopchannel 0, Music_MeetEvilTrainer_branch_7f6ae Music_MeetEvilTrainer_Ch1:: duty 1 notetype 12, 11, 6 octave 3 B_ 2 A# 2 B_ 8 Music_MeetEvilTrainer_branch_7f6c2:: notetype 12, 12, 2 octave 4 D# 2 D_ 2 C# 2 C_ 2 octave 3 B_ 4 B_ 4 B_ 4 B_ 4 B_ 4 notetype 12, 4, 15 A# 4 notetype 12, 12, 2 G_ 2 G# 2 A_ 2 A# 2 B_ 4 B_ 4 B_ 4 B_ 4 B_ 4 notetype 12, 3, 15 A# 4 notetype 12, 12, 2 loopchannel 0, Music_MeetEvilTrainer_branch_7f6c2 Music_MeetEvilTrainer_Ch2:: notetype 12, 1, 0 rest 8 octave 4 F# 1 rest 1 F_ 1 rest 1 Music_MeetEvilTrainer_branch_7f6ee:: F# 1 rest 3 F# 1 rest 3 F# 1 rest 3 A# 4 loopchannel 0, Music_MeetEvilTrainer_branch_7f6ee
; Map structure: ; Field size: 128x128 ; Each tile is 2 bytes worth: ; - If it's grass or a stump, the first byte is the type; the second byte is not used ; - If it's a tree or resource, the first byte is the type; the second byte is how full the tree/resource is ; - If it's a building, the first byte is the type; the second byte is the index in the buildings array, with more information like health etc ; - If it's a unit or more units, the first byte is the type from the ground, like grass, with the highest bit set; the second byte is the index in the units array, with a linked list to eventually other units at the same tile GenerateMap: call EraseArea ld de, screenBuffer ld hl, blackBuffer ld bc, lcdWidth * lcdHeight ldir printString GeneratingMapMessage, 5, 112 ld hl, (0F30044h) call _srand ld ixh, 0 PlaceTreesLoop: randInt MAP_SIZE push hl randInt MAP_SIZE ld h, lcdWidth / 2 mlt hl add hl, hl pop de add hl, de ld de, screenBuffer add hl, de push hl randInt AMOUNT_OF_TREES ld a, l add a, TILE_TREE pop hl ld (hl), a dec ixh jr nz, PlaceTreesLoop ld ixh, 3 ; Food, stone, gold PlaceAllResourceTypesLoop: ld ixl, 20 ; Place max 20 resources of each PlaceResourceTypeLoop: randInt 7 ; 7 types of different groups for resources push hl pop de add hl, hl add hl, hl add hl, hl add hl, de ld de, resource_type_1 add hl, de push hl randInt MAP_SIZE - 2 - 2 ; X inc hl inc hl ld h, lcdWidth / 2 mlt hl add hl, hl push hl randInt MAP_SIZE - 2 - 2 ; Y inc hl inc hl pop de add hl, de ld de, screenBuffer add hl, de push hl ld de, lcdWidth - 2 ld a, (hl) ; Check if one of the 9 blocks is already a tree/part of resource inc hl or a, (hl) inc hl or a, (hl) add hl, de or a, (hl) inc hl or a, (hl) inc hl or a, (hl) add hl, de or a, (hl) inc hl or a, (hl) inc hl or a, (hl) pop hl, de jr nz, DontDrawResource ld b, 3 PlaceResource: ld c, b ld b, 3 PlaceResourceRowLoop: ld a, (de) or a, a jr z, DontDisplayResource ld a, r ; I like it and a, 1 add a, TILE_FOOD_1 - 2 add a, ixh add a, ixh ld (hl), a DontDisplayResource: inc hl inc de djnz PlaceResourceRowLoop ld a, c inc b ld c, (lcdWidth and 0FFh) - 3 add hl, bc ld b, a djnz PlaceResource DontDrawResource: dec ixl jp nz, PlaceResourceTypeLoop dec ixh jp nz, PlaceAllResourceTypesLoop ; All the resources are now placed, so copy them to the map data ld de, (map_data_ptr) ld hl, screenBuffer ld ixh, MAP_SIZE CopyMapToNewAppvarLoop: ld b, MAP_SIZE CopyRowLoop: ld a, (hl) or a, a jr nz, TileIsNonEmpty inc a TileIsNonEmpty: ld (de), a inc de dec a jr z, TileIsResource ld a, RESOURCE_MAX TileIsResource: ld (de), a inc hl inc de djnz CopyRowLoop ld bc, lcdWidth - MAP_SIZE add hl, bc dec ixh jr nz, CopyMapToNewAppvarLoop LoadMap: call EraseArea printString LoadingMapMessage, 5, 112 or a, 1 ; Set NZ ret GeneratingMapMessage: db "Generating map...", 0 LoadingMapMessage: db "Loading map...", 0
; ; VDP line interrupt timer ; ; 300 Hz resolution ; LineTimer_SAMPLES: equ 147 LineTimer_LINESTEP_60HZ: equ 52 LineTimer_LINESTEP_50HZ: equ 51 LineTimer_IE1: equ 00010000B LineTimer: MACRO super: Timer LineTimer_Start, LineTimer_Stop, LineTimer_Reset, Update liffy: equ LineInterruptHandler.liffy lastLiffy: db 0 ; ix = this ; de <- time passed Update: PROC ld b,(ix + LineTimer.lastLiffy) Wait: ld a,(ix + LineTimer.liffy) cp b jr z,Wait ld (ix + LineTimer.lastLiffy),a sub b ld b,a ld hl,0 ld de,LineTimer_SAMPLES Loop: add hl,de djnz Loop ex de,hl jr super.Callback ENDP InterruptHandler: PROC push af ld a,1 out (VDP_PORT_1),a ld a,15 | VDP_REGISTER out (VDP_PORT_1),a in a,(VDP_PORT_1) rrca jr c,LineInterruptHandler xor a out (VDP_PORT_1),a ld a,15 | VDP_REGISTER out (VDP_PORT_1),a pop af oldHook: ds Interrupt_HOOK_SIZE,0C9H ENDP LineInterruptHandler: PROC ld a,0 liffy: equ $ - 1 inc a ld (liffy),a liffyReference: equ $ - 2 ld a,0 line: equ $ - 1 add a,0 lineStep: equ $ - 1 jr nc,NoReset xor a NoReset: ld (line),a lineReference: equ $ - 2 out (VDP_PORT_1),a ld a,19 | VDP_REGISTER out (VDP_PORT_1),a xor a out (VDP_PORT_1),a ld a,15 | VDP_REGISTER out (VDP_PORT_1),a pop af ei ret ENDP _size: ENDM LineTimer_class: Class LineTimer, LineTimer_template, Heap_main LineTimer_template: LineTimer ; hl = callback ; ix = this LineTimer_Construct: call Timer_Construct ld e,ixl ld d,ixh ld hl,LineTimer.LineInterruptHandler.liffy add hl,de ld (ix + LineTimer.LineInterruptHandler.liffyReference),l ld (ix + LineTimer.LineInterruptHandler.liffyReference + 1),h ld hl,LineTimer.LineInterruptHandler.line add hl,de ld (ix + LineTimer.LineInterruptHandler.lineReference),l ld (ix + LineTimer.LineInterruptHandler.lineReference + 1),h ret ; ix = this LineTimer_Destruct: equ Timer_Destruct ; jp Timer_Destruct ; ix = this LineTimer_Start: PROC call LineTimer_Reset ld a,0 ld (ix + LineTimer.LineInterruptHandler.line),a ld b,19 call VDP_SetRegister call VDP_Is60Hz ld (ix + LineTimer.LineInterruptHandler.lineStep),LineTimer_LINESTEP_60HZ jr z,Is60Hz ld (ix + LineTimer.LineInterruptHandler.lineStep),LineTimer_LINESTEP_50HZ Is60Hz: call LineTimer_InstallInterruptHandler ld a,(VDP_MIRROR_0) or LineTimer_IE1 ld (VDP_MIRROR_0),a ld b,0 jp VDP_SetRegister ENDP ; ix = this LineTimer_Stop: ld a,(VDP_MIRROR_0) and ~LineTimer_IE1 ld (VDP_MIRROR_0),a ld b,0 call VDP_SetRegister jr LineTimer_UninstallInterruptHandler ; ix = this LineTimer_InstallInterruptHandler: push ix ld ix,Interrupt_instance call Interrupt_Construct pop ix ld c,ixl ld b,ixh ld hl,LineTimer.InterruptHandler.oldHook add hl,bc ex de,hl ld hl,LineTimer.InterruptHandler add hl,bc push ix ld ix,Interrupt_instance call Interrupt_Hook pop ix ret ; ix = this LineTimer_UninstallInterruptHandler: push ix ld ix,Interrupt_instance call Interrupt_Destruct pop ix ret ; ix = this LineTimer_Reset: ld a,(ix + LineTimer.liffy) ld (ix + LineTimer.lastLiffy),a ret ; f <- c: found LineTimer_Detect: call VDP_IsTMS9918A scf ret nz ccf ret
; A304384: a(n) = 168*2^n - 26 (n>=1). ; 310,646,1318,2662,5350,10726,21478,42982,85990,172006,344038,688102,1376230,2752486,5504998,11010022,22020070,44040166,88080358,176160742,352321510,704643046,1409286118,2818572262,5637144550,11274289126,22548578278,45097156582,90194313190,180388626406,360777252838,721554505702,1443109011430,2886218022886,5772436045798,11544872091622,23089744183270,46179488366566,92358976733158,184717953466342,369435906932710,738871813865446,1477743627730918,2955487255461862,5910974510923750,11821949021847526 mov $1,2 pow $1,$0 sub $1,1 mul $1,336 add $1,310 mov $0,$1
;------------------------------------------------------------------------------ ; ; CpuFlushTlb() for ARM ; ; Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR> ; Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR> ; SPDX-License-Identifier: BSD-2-Clause-Patent ; ;------------------------------------------------------------------------------ EXPORT CpuFlushTlb AREA cpu_flush_tlb, CODE, READONLY ;/** ; Flushes all the Translation Lookaside Buffers(TLB) entries in a CPU. ; ; Flushes all the Translation Lookaside Buffers(TLB) entries in a CPU. ; ;**/ ;VOID ;EFIAPI ;CpuFlushTlb ( ; VOID ; ); ; CpuFlushTlb MOV r0,#0 MCR p15,0,r0,c8,c5,0 ;Invalidate all the unlocked entried in TLB BX LR END
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // See docs in ../ops/image_ops.cc #define EIGEN_USE_THREADS #include "tensorflow/core/kernels/scale_and_translate_op.h" #include <memory> #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/framework/bounds_check.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/kernels/sampling_kernels.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "tensorflow/core/platform/logging.h" namespace tensorflow { using strings::Printf; typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; namespace functor { namespace { template <typename T> inline const T& Clamp(const T& low, const T& high, const T& value) { if (high < value) return high; if (value < low) return low; return value; } template <typename Kernel> Status ComputeSpansCore(OpKernelContext* context, const Kernel& kernel, const int64 output_size, const int64 input_size, const float scale, const float translate, const bool antialias, Spans* spans) { // When sampling, we need the inverse scale and translation, to map from an // output to an input pixel. const float inv_scale = 1.0 / scale; const float inv_translate = -inv_scale * translate; // When downsampling the kernel should be scaled since we want to low pass // filter and interpolate, but when upsampling it should not be since we only // want to interpolate. const float kernel_scale = antialias ? std::max(inv_scale, 1.0f) : 1.0f; spans->span_size = std::min( 2 * static_cast<int>(std::ceil(kernel.Radius() * kernel_scale)) + 1, static_cast<int>(input_size)); AllocatorAttributes alloc_attr; alloc_attr.set_on_host(true); TF_RETURN_IF_ERROR(context->allocate_temp( tensorflow::DT_INT32, tensorflow::TensorShape({output_size}), &spans->starts, alloc_attr)); auto starts_vec = spans->starts.vec<int32>(); TF_RETURN_IF_ERROR(context->allocate_temp( tensorflow::DT_FLOAT, tensorflow::TensorShape({spans->span_size * output_size}), &spans->weights, alloc_attr)); auto weights_vec = spans->weights.vec<float>(); weights_vec.setZero(); const float one_over_kernel_scale = 1.0f / kernel_scale; int max_span_size = 0; std::vector<float> temp_weights; for (int x = 0; x < output_size; ++x) { const float col_f = x + 0.5f; const float sample_f = col_f * inv_scale + inv_translate; // Don't sample when the sampling location is outside the source image. if (sample_f < 0 || sample_f > input_size) { // Add an empty span. starts_vec(x) = 0; continue; } int64 span_start = std::ceil(sample_f - kernel.Radius() * kernel_scale - 0.5f); int64 span_end = std::floor(sample_f + kernel.Radius() * kernel_scale - 0.5f); span_start = Clamp(static_cast<int64>(0), input_size - 1, span_start); span_end = Clamp(static_cast<int64>(0), input_size - 1, span_end) + 1; const int this_span_size = span_end - span_start; if (this_span_size > spans->span_size) { return errors::Internal(Printf("Span is too large: %d vs %d.", this_span_size, spans->span_size)); } float total_weight_sum = 0.0f; temp_weights.clear(); for (int source = span_start; source < span_end; ++source) { float kernel_pos = static_cast<float>(source) + 0.5f - sample_f; float weight = kernel(std::abs(kernel_pos * one_over_kernel_scale)); total_weight_sum += weight; temp_weights.push_back(weight); } max_span_size = std::max(max_span_size, this_span_size); if (std::abs(total_weight_sum) >= 1000.0f * std::numeric_limits<float>::min()) { float one_over_total_weight_sum = 1.0f / total_weight_sum; int out_index = spans->span_size * x; for (float weight : temp_weights) { weights_vec(out_index) = weight * one_over_total_weight_sum; ++out_index; } } starts_vec(x) = span_start; } return Status::OK(); } Status ComputeGradSpansCore(OpKernelContext* context, const Spans& spans, const int64 forward_output_size, const int64 forward_input_size, Spans* grad_spans) { struct GradComponent { int index; float weight; }; std::vector<std::vector<GradComponent>> grad_components(forward_input_size); auto weights_vec = spans.weights.vec<float>(); auto starts_vec = spans.starts.vec<int32>(); for (int output_index = 0; output_index < forward_output_size; ++output_index) { int input_index = starts_vec(output_index); for (int j = 0; j < spans.span_size; ++j, ++input_index) { const float weight = weights_vec(output_index * spans.span_size + j); if (weight != 0.0f && input_index < forward_input_size) { grad_components[input_index].push_back( GradComponent{output_index, weight}); } } } int max_size = 0; for (std::vector<GradComponent>& gc : grad_components) { if (!gc.empty()) { std::sort(gc.begin(), gc.end(), [](const GradComponent& x1, const GradComponent& x2) { return x1.index < x2.index; }); max_size = std::max(gc.back().index - gc.front().index + 1, max_size); } } grad_spans->span_size = max_size; AllocatorAttributes alloc_attr; alloc_attr.set_on_host(true); TF_RETURN_IF_ERROR(context->allocate_temp( tensorflow::DT_INT32, tensorflow::TensorShape({forward_input_size}), &grad_spans->starts, alloc_attr)); auto grad_starts_vec = grad_spans->starts.vec<int32>(); TF_RETURN_IF_ERROR(context->allocate_temp( tensorflow::DT_FLOAT, tensorflow::TensorShape({grad_spans->span_size * forward_input_size}), &grad_spans->weights, alloc_attr)); auto grad_weights_vec = grad_spans->weights.vec<float>(); grad_weights_vec.setZero(); for (int input_index = 0; input_index < forward_input_size; ++input_index) { if (!grad_components[input_index].empty()) { const int start_span = grad_components[input_index].front().index; grad_starts_vec(input_index) = start_span; for (const GradComponent& gc : grad_components[input_index]) { grad_weights_vec(input_index * grad_spans->span_size + gc.index - start_span) += gc.weight; } } else { grad_starts_vec(input_index) = 0; } } return Status::OK(); } // Computes the spans for the passed kernel, for a input dimension of length // input_size transformed by scale and translate to an output dimension of // length output_size. Note that there's no requirement that; // output_size = input_size * scale. Status ComputeSpans(OpKernelContext* context, const functor::SamplingKernelType kernel_type, const int64 output_size, const int64 input_size, const float scale, const float translate, const bool antialias, Spans* spans) { switch (kernel_type) { case functor::Lanczos1Kernel: { return ComputeSpansCore(context, CreateLanczos1Kernel(), output_size, input_size, scale, translate, antialias, spans); } case functor::Lanczos3Kernel: { return ComputeSpansCore(context, CreateLanczos3Kernel(), output_size, input_size, scale, translate, antialias, spans); } case functor::Lanczos5Kernel: { return ComputeSpansCore(context, CreateLanczos5Kernel(), output_size, input_size, scale, translate, antialias, spans); } case functor::GaussianKernel: { return ComputeSpansCore(context, CreateGaussianKernel(), output_size, input_size, scale, translate, antialias, spans); } case functor::BoxKernel: { return ComputeSpansCore(context, CreateBoxKernel(), output_size, input_size, scale, translate, antialias, spans); } case functor::TriangleKernel: { return ComputeSpansCore(context, CreateTriangleKernel(), output_size, input_size, scale, translate, antialias, spans); } case functor::KeysCubicKernel: { return ComputeSpansCore(context, CreateKeysCubicKernel(), output_size, input_size, scale, translate, antialias, spans); } case functor::MitchellCubicKernel: { return ComputeSpansCore(context, CreateMitchellCubicKernel(), output_size, input_size, scale, translate, antialias, spans); } default: return errors::InvalidArgument(Printf("Unrecognized kernel type: %d", static_cast<int>(kernel_type))); } return Status::OK(); } // Computes the grad spans for the passed kernel. // forward_input_size and forward_output_size are the input and output size from // the forward operation. Status ComputeGradSpans(OpKernelContext* context, const functor::SamplingKernelType kernel_type, const int64 forward_output_size, const int64 forward_input_size, const float scale, const float translate, const bool antialias, Spans* grad_spans) { Spans spans; TF_RETURN_IF_ERROR(ComputeSpans(context, kernel_type, forward_output_size, forward_input_size, scale, translate, antialias, &spans)); return ComputeGradSpansCore(context, spans, forward_output_size, forward_input_size, grad_spans); } void GetValues(OpKernelContext* context, int input_index, float* v_1, float* v_2) { // Tensor mutable_input(int index, False); const Tensor& t = context->input(input_index); OP_REQUIRES(context, t.dims() == 1, errors::InvalidArgument("t must be 1-dimensional", t.shape().DebugString())); OP_REQUIRES(context, t.NumElements() == 2, errors::InvalidArgument("t must have two elements", t.shape().DebugString())); auto data_vec = t.flat<float>().data(); *v_1 = data_vec[0]; *v_2 = data_vec[1]; } template <typename Device, typename T> class ScaleAndTranslateOp : public OpKernel { public: explicit ScaleAndTranslateOp(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("antialias", &antialias_)); string kernel_type_str; OP_REQUIRES_OK(context, context->GetAttr("kernel_type", &kernel_type_str)); kernel_type_ = functor::SamplingKernelTypeFromString(kernel_type_str); OP_REQUIRES(context, kernel_type_ != functor::SamplingKernelTypeEnd, errors::InvalidArgument("Unrecognized kernel type: " + kernel_type_str)); } void Compute(OpKernelContext* context) override { const Tensor& input = context->input(0); OP_REQUIRES(context, input.dims() == 4, errors::InvalidArgument("input must be 4-dimensional", input.shape().DebugString())); const Tensor& output_shape_t = context->input(1); OP_REQUIRES(context, output_shape_t.dims() == 1, errors::InvalidArgument("output_shape_t must be 1-dimensional", output_shape_t.shape().DebugString())); OP_REQUIRES(context, output_shape_t.NumElements() == 2, errors::InvalidArgument("output_shape_t must have two elements", output_shape_t.shape().DebugString())); auto output_shape_vec = output_shape_t.vec<int32>(); const int64 output_height = internal::SubtleMustCopy(output_shape_vec(0)); const int64 output_width = internal::SubtleMustCopy(output_shape_vec(1)); OP_REQUIRES( context, FastBoundsCheck(input.dim_size(1), std::numeric_limits<int32>::max()) && FastBoundsCheck(input.dim_size(2), std::numeric_limits<int32>::max()), errors::InvalidArgument("input sizes must be between 0 and max int32")); const int64 batch_size = input.dim_size(0); const int64 input_height = input.dim_size(1); const int64 input_width = input.dim_size(2); const int64 channels = input.dim_size(3); OP_REQUIRES(context, output_height > 0 && output_width > 0, errors::InvalidArgument("output dimensions must be positive")); OP_REQUIRES( context, channels > 0, errors::InvalidArgument("image must have at least one channel")); OP_REQUIRES( context, input.dim_size(1) > 0 && input.dim_size(2) > 0, errors::InvalidArgument("input image must be of non-zero size")); float row_scale, col_scale; GetValues(context, 2, &row_scale, &col_scale); OP_REQUIRES(context, row_scale > 0 && col_scale > 0, errors::InvalidArgument("Scale must be greater than zero.")); float row_translation, col_translation; GetValues(context, 3, &row_translation, &col_translation); Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output( 0, TensorShape({input.dim_size(0), output_height, output_width, input.dim_size(3)}), &output)); if (!context->status().ok()) return; // Return if the output is empty. if (output->NumElements() == 0) return; typename TTypes<T, 4>::ConstTensor image_data(input.tensor<T, 4>()); TTypes<float, 4>::Tensor output_data = output->tensor<float, 4>(); functor::Spans col_spans; OP_REQUIRES_OK( context, ComputeSpans(context, kernel_type_, output_width, input_width, col_scale, col_translation, antialias_, &col_spans)); functor::Spans row_spans; OP_REQUIRES_OK( context, ComputeSpans(context, kernel_type_, output_height, input_height, row_scale, row_translation, antialias_, &row_spans)); Tensor intermediate_t; OP_REQUIRES_OK( context, context->allocate_temp(DT_FLOAT, TensorShape({batch_size, output_height, input_width, channels}), &intermediate_t)); TTypes<float, 4>::Tensor intermediate_data = intermediate_t.tensor<float, 4>(); const functor::Spans& const_row_spans = row_spans; typename TTypes<int32, 1>::ConstTensor row_starts( const_row_spans.starts.tensor<int32, 1>()); typename TTypes<float, 1>::ConstTensor row_weights( const_row_spans.weights.tensor<float, 1>()); const functor::Spans& const_col_spans = col_spans; typename TTypes<int32, 1>::ConstTensor col_starts( const_col_spans.starts.tensor<int32, 1>()); typename TTypes<float, 1>::ConstTensor col_weights( const_col_spans.weights.tensor<float, 1>()); functor::GatherSpans<Device, T>()( context->eigen_device<Device>(), row_spans.span_size, row_starts, row_weights, col_spans.span_size, col_starts, col_weights, image_data, intermediate_data, output_data); } functor::SamplingKernelType kernel_type_; bool antialias_; }; template <typename Device, typename T> class ScaleAndTranslateGradOp : public OpKernel { public: explicit ScaleAndTranslateGradOp(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("antialias", &antialias_)); string kernel_type_str; OP_REQUIRES_OK(context, context->GetAttr("kernel_type", &kernel_type_str)); kernel_type_ = functor::SamplingKernelTypeFromString(kernel_type_str); OP_REQUIRES(context, kernel_type_ != functor::SamplingKernelTypeEnd, errors::InvalidArgument("Unrecognized kernel type: " + kernel_type_str)); } void Compute(OpKernelContext* context) override { const Tensor& input = context->input(0); const Tensor& original_image = context->input(1); OP_REQUIRES(context, input.dims() == 4, errors::InvalidArgument("input_grad must be 4-dimensional", input.shape().DebugString())); // Resizers always produce float images, so input gradient must // always be a float. OP_REQUIRES(context, input.dtype() == DT_FLOAT, errors::InvalidArgument("input_grad must be of type float", DataTypeString(input.dtype()))); OP_REQUIRES(context, original_image.dims() == 4, errors::InvalidArgument("original_image must be 4-dimensional", original_image.shape().DebugString())); // Allocate output and initialize to zeros. const int64 batch_size = input.dim_size(0); const int64 channels = input.dim_size(3); const int64 forward_input_height = original_image.dim_size(1); const int64 forward_input_width = original_image.dim_size(2); OP_REQUIRES(context, FastBoundsCheck(forward_input_height, std::numeric_limits<int32>::max()) && FastBoundsCheck(forward_input_width, std::numeric_limits<int32>::max()), errors::InvalidArgument( "original sizes must be between 0 and max int32")); Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output( 0, TensorShape({batch_size, forward_input_height, forward_input_width, channels}), &output)); float row_scale, col_scale; GetValues(context, 2, &row_scale, &col_scale); OP_REQUIRES(context, row_scale > 0 && col_scale > 0, errors::InvalidArgument("Scale must be greater than zero.")); float row_translation, col_translation; GetValues(context, 3, &row_translation, &col_translation); if (!context->status().ok()) return; TTypes<float, 4>::ConstTensor input_grad = input.tensor<float, 4>(); typename TTypes<T, 4>::Tensor output_grad(output->tensor<T, 4>()); const int64 forward_output_height = input_grad.dimension(1); const int64 forward_output_width = input_grad.dimension(2); functor::Spans col_spans; OP_REQUIRES_OK(context, ComputeGradSpans(context, kernel_type_, forward_output_width, forward_input_width, col_scale, col_translation, antialias_, &col_spans)); functor::Spans row_spans; OP_REQUIRES_OK( context, ComputeGradSpans(context, kernel_type_, forward_output_height, forward_input_height, row_scale, row_translation, antialias_, &row_spans)); Tensor intermediate_t; OP_REQUIRES_OK(context, context->allocate_temp( DT_FLOAT, TensorShape({batch_size, forward_input_height, forward_output_width, channels}), &intermediate_t)); TTypes<float, 4>::Tensor intermediate_data = intermediate_t.tensor<float, 4>(); const functor::Spans& const_row_spans = row_spans; typename TTypes<int32, 1>::ConstTensor row_starts = const_row_spans.starts.tensor<int32, 1>(); typename TTypes<float, 1>::ConstTensor row_weights( const_row_spans.weights.tensor<float, 1>()); const functor::Spans& const_col_spans = col_spans; typename TTypes<int32, 1>::ConstTensor col_starts( const_col_spans.starts.tensor<int32, 1>()); typename TTypes<float, 1>::ConstTensor col_weights( const_col_spans.weights.tensor<float, 1>()); functor::GatherSpans<Device, T>()( context->eigen_device<Device>(), row_spans.span_size, row_starts, row_weights, col_spans.span_size, col_starts, col_weights, input_grad, intermediate_data, output_grad); } functor::SamplingKernelType kernel_type_; bool antialias_; }; template <typename T> void GatherColumns(int span_size, const int32* starts, const float* weights, const T* image, const int64 input_height, const int64 input_width, const int64 output_height, const int64 output_width, const int channels, float* output) { const int64 in_row_size = input_width * channels; const int64 out_row_size = output_width * channels; for (int y = 0; y < output_height; ++y) { const T* input_row_start = image + in_row_size * y; float* out_pix = output + out_row_size * y; for (int x = 0; x < output_width; ++x, out_pix += channels) { const T* in_pix = input_row_start + starts[x] * channels; const float* weights_start = weights + x * span_size; const int real_span_size = std::min(starts[x] + span_size, static_cast<int>(input_width)) - starts[x]; const float* weights_end = weights_start + real_span_size; for (int c = 0; c < channels; ++c) { out_pix[c] = 0.0f; } for (const float* weight_ptr = weights_start; weight_ptr != weights_end; ++weight_ptr) { float w = *weight_ptr; for (int c = 0; c < channels; ++c) { out_pix[c] += w * static_cast<float>(in_pix[c]); } in_pix += channels; } } } } template <typename T> inline void AddScaledVector(const T* in_vec, int vec_len, float weight, float* out_vec) { float* out_vec_end = out_vec + vec_len; for (; out_vec != out_vec_end; ++out_vec, ++in_vec) { *out_vec += weight * static_cast<float>(*in_vec); } } template <typename T> void GatherRows(int span_size, const int32* starts, const float* weights, const T* image, const int64 input_height, const int64 input_width, const int64 output_height, const int64 output_width, const int channels, float* output) { const int64 in_row_size = input_width * channels; const int64 out_row_size = output_width * channels; for (int y = 0; y < output_height; ++y) { float* out_row_data = output + out_row_size * y; std::fill(out_row_data, out_row_data + out_row_size, 0.0f); int in_row = starts[y]; const T* in_row_data = image + in_row_size * in_row; const float* weights_start = weights + y * span_size; const int real_span_size = std::min(starts[y] + span_size, static_cast<int>(input_height)) - starts[y]; const float* const weights_end = weights_start + real_span_size; for (const float* weight_it = weights_start; weight_it != weights_end; ++weight_it) { AddScaledVector(in_row_data, in_row_size, *weight_it, out_row_data); in_row_data += in_row_size; } } } } // namespace // Partial specialization of GatherSpans functor for a CPUDevice. template <typename T> struct GatherSpans<CPUDevice, T> { void operator()(const CPUDevice& d, int row_span_size, typename TTypes<int32, 1>::ConstTensor row_starts, typename TTypes<float, 1>::ConstTensor row_weights, int col_span_size, typename TTypes<int32, 1>::ConstTensor col_starts, typename TTypes<float, 1>::ConstTensor col_weights, typename TTypes<T, 4>::ConstTensor images, typename TTypes<float, 4>::Tensor intermediate_buffer, typename TTypes<float, 4>::Tensor resized_images) { const int batch_size = images.dimension(0); const int64 input_height = images.dimension(1); const int64 input_width = images.dimension(2); const int channels = images.dimension(3); const int64 output_height = resized_images.dimension(1); const int64 output_width = resized_images.dimension(2); const int64 input_pix_per_batch = input_width * input_height * channels; const int64 intermediate_pix_per_batch = input_width * output_height * channels; const int64 output_pix_per_batch = output_width * output_height * channels; float* intermediate_ptr = intermediate_buffer.data(); const T* image_ptr = images.data(); float* out_ptr = resized_images.data(); for (int b = 0; b < batch_size; ++b, image_ptr += input_pix_per_batch, intermediate_ptr += intermediate_pix_per_batch, out_ptr += output_pix_per_batch) { GatherRows(row_span_size, row_starts.data(), row_weights.data(), image_ptr, input_height, input_width, output_height, input_width, channels, intermediate_ptr); GatherColumns(col_span_size, col_starts.data(), col_weights.data(), intermediate_ptr, output_height, input_width, output_height, output_width, channels, out_ptr); } } }; #define REGISTER_KERNEL(T) \ REGISTER_KERNEL_BUILDER(Name("ScaleAndTranslate") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T") \ .HostMemory("size") \ .HostMemory("scale") \ .HostMemory("translation"), \ ScaleAndTranslateOp<CPUDevice, T>); TF_CALL_REAL_NUMBER_TYPES(REGISTER_KERNEL); #undef REGISTER_KERNEL #define REGISTER_GRAD_KERNEL(T) \ REGISTER_KERNEL_BUILDER(Name("ScaleAndTranslateGrad") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T") \ .HostMemory("scale") \ .HostMemory("translation"), \ ScaleAndTranslateGradOp<CPUDevice, T>); TF_CALL_float(REGISTER_GRAD_KERNEL); #undef REGISTER_GRAD_KERNEL } // namespace functor } // namespace tensorflow
;=============================================================================== ; Util to invoke a HBIOS function ; Usage B C .... ; stksiz .equ $200 ; Working stack size restart .equ $0000 ; CP/M restart vector bdos .equ $0005 ; BDOS invocation vector #DEFINE PRTS(S) CALL prtstrd \ .TEXT S ;=============================================================================== ; Entry ;=============================================================================== .org $100 ; setup stack LD (stksav), sp ; save stack LD sp, stack ; set new stack PRTS( "HBIOS Test Utility v0.3\r\n$") CALL parse ; parse command line LD iy, bcValue LD B, 'B' LD C, 'C' CALL prtregs LD iy, deValue LD B, 'D' LD C, 'E' CALL prtregs LD iy, hlValue LD B, 'H' LD C, 'L' CALL prtregs CALL invokehbios PRTS( "Ret AF: 0x$") LD IY, afResult CALL prtreg PRTS( "\r\nRet BC: 0x$") LD IY, bcResult CALL prtreg PRTS( "\r\nRet DE: 0x$") LD IY, deResult CALL prtreg PRTS( "\r\nRet HL: 0x$") LD IY, hlResult CALL prtreg PRTS( "\r\nRet DE:HL: 0x$") LD IY, deResult CALL prtreg LD IY, hlResult CALL prtreg PRTS( "\r\nReturned registers\r\n$") exit: CALL crlf ; formatting LD sp, (stksav) ; restore stack RET ; return to CP/M prtregs: ; iy is location of data to print LD a, b call prtchr PRTS( ": 0x$") LD a, (iy+1) ; b is chr of 1st register call prthex CALL crlf LD a, c call prtchr PRTS( ": 0x$") LD a, (iy) ; b is chr of 1st register call prthex call crlf RET ;=============================================================================== prtreg: ; print 16 bit value at IY LD E, (IY) LD d, (IY + 1) LD a, d CALL prthex LD a, e JP prthex invokehbios: LD bc, (bcValue) LD de, (deValue) LD hl, (hlValue) RST 08 LD (bcResult), bc LD (deResult), de LD (hlResult), hl PUSH AF POP BC LD (afResult), BC RET ;=============================================================================== ; convert char in A to a number from 0-15 based on it HEX string value fromchar: ; value is returned in B SUB '0' ; CP 10 ; greater than 9 JR c, numchar SUB 'A' - '0' CP 7 ; greater than F JP nc, errprm ADD a, 10 numchar: LD b, a RET ;=============================================================================== readhexbyte: ; Read 2 chars - and convert to a byte - returned in A LD a, (hl) OR a JP z, errprm CALL fromchar LD a, b RLCA RLCA RLCA RLCA LD c, a INC hl LD a, (hl) OR a JP z, errprm CALL fromchar LD a, b INC hl OR c LD c, a RET ;=============================================================================== ; Parse command line ; if parse error, writes error string and then jp to exit parse: LD hl, $81 ; point to start of command tail (after length byte) LD IY, bcValue CALL parsehexbyte LD a, (hl) ; if no more args OR a RET z LD IY, deValue ; D and E values CALL parsehexbyte LD a, (hl) ; if no more args OR a RET z LD IY, hlValue ; H and L values CALL parsehexbyte RET parsehexbyte: CALL nonblank ; skip blanks CALL readhexbyte ; read value for register B LD a, c LD (IY + 1), a CALL nonblank ; skip blanks CALL readhexbyte ; read value for register C LD a, c LD (IY), a RET ;=============================================================================== ; Print character in A without destroying any registers prtchr: PUSH bc ; save registers PUSH de PUSH hl LD e, a ; character to print in E LD c, $02 ; BDOS function to output a character CALL bdos ; do it POP hl ; restore registers POP de POP bc RET ;=============================================================================== ; Print a $ terminated string at (HL) without destroying any registers prtstrz: LD a, (hl) ; get next char INC hl CP '$' RET z CALL prtchr JR prtstrz ;=============================================================================== ; Print the value in A in hex without destroying any registers prthex: PUSH af ; save AF PUSH de ; save DE CALL hexascii ; convert value in A to hex chars in DE LD a, d ; get the high order hex char CALL prtchr ; print it LD a, e ; get the low order hex char CALL prtchr ; print it POP de ; restore DE POP af ; restore AF RET ; done ;=============================================================================== ; Convert binary value in A to ascii hex characters in DE hexascii: LD d, a ; save A in D CALL hexconv ; convert low nibble of A to hex LD e, a ; save it in E LD a, d ; get original value back RLCA ; rotate high order nibble to low bits RLCA RLCA RLCA CALL hexconv ; convert nibble LD d, a ; save it in D RET ; done ;=============================================================================== ; Convert low nibble of A to ascii hex hexconv: AND $0F ; low nibble only ADD a, $90 DAA ADC a, $40 DAA RET ;=============================================================================== ; Start a new line crlf: LD a, 13 ; <CR> CALL prtchr ; print it LD a, 10 ; <LF> JR prtchr ; print it ;=============================================================================== ; Get the next non-blank character from (HL). nonblank: LD a, (hl) ; load next character OR a JP z, erruse cp ' ' ; string ends with a null JR nz, errprm ; if no blank found as expected, return error to user skipblank: INC hl ; if blank, increment character pointer LD a, (hl) ; load next character OR a ; string ends with a null RET z ; if null, return pointing to null CP ' ' ; check for blank RET nz ; return if not blank JR skipblank ; and loop ;=============================================================================== ; Errors erruse: ; command usage error (syntax) LD hl, msguse JR err errprm: ; command parameter error (syntax) LD hl, msgprm err: ; print error string and return error signal CALL crlf ; print newline CALL prtstrz ; print error string JP exit ;=============================================================================== ; PRINT A STRING DIRECT: REFERENCED BY POINTER AT TOP OF STACK ; STRING MUST BE TERMINATED BY '$' ; USAGE: ; CALL PRTSTR ; .DB "HELLO$" prtstrd: EX (SP), HL CALL prtstrz EX (SP), HL RET ;=============================================================================== ; Storage Section ;=============================================================================== stksav .dw 0 ; stack pointer saved at start .fill stksiz, 0 ; stack stack .equ $ ; stack top ;=============================================================================== ; Messages msguse .db "Usage: HBIOS BB CC [DD EE] [HH LL]$" msgprm .db "Parameter error$" ;=============================================================================== ; Register values to supply to hbios bcValue .dw 0 deValue .dw 0 hlValue .dw 0 ;=============================================================================== ; Captured register returned by hbios call afResult .dw 0 bcResult .dw 0 deResult .dw 0 hlResult .dw 0 .end
// Copyright (c) 2009-2018 The Karmacoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <psbt.h> #include <util/strencodings.h> #include <numeric> PartiallySignedTransaction::PartiallySignedTransaction(const CMutableTransaction& tx) : tx(tx) { inputs.resize(tx.vin.size()); outputs.resize(tx.vout.size()); } bool PartiallySignedTransaction::IsNull() const { return !tx && inputs.empty() && outputs.empty() && unknown.empty(); } bool PartiallySignedTransaction::Merge(const PartiallySignedTransaction& psbt) { // Prohibited to merge two PSBTs over different transactions if (tx->GetHash() != psbt.tx->GetHash()) { return false; } for (unsigned int i = 0; i < inputs.size(); ++i) { inputs[i].Merge(psbt.inputs[i]); } for (unsigned int i = 0; i < outputs.size(); ++i) { outputs[i].Merge(psbt.outputs[i]); } unknown.insert(psbt.unknown.begin(), psbt.unknown.end()); return true; } bool PartiallySignedTransaction::IsSane() const { for (PSBTInput input : inputs) { if (!input.IsSane()) return false; } return true; } bool PartiallySignedTransaction::AddInput(const CTxIn& txin, PSBTInput& psbtin) { if (std::find(tx->vin.begin(), tx->vin.end(), txin) != tx->vin.end()) { return false; } tx->vin.push_back(txin); psbtin.partial_sigs.clear(); psbtin.final_script_sig.clear(); psbtin.final_script_witness.SetNull(); inputs.push_back(psbtin); return true; } bool PartiallySignedTransaction::AddOutput(const CTxOut& txout, const PSBTOutput& psbtout) { tx->vout.push_back(txout); outputs.push_back(psbtout); return true; } bool PartiallySignedTransaction::GetInputUTXO(CTxOut& utxo, int input_index) const { PSBTInput input = inputs[input_index]; int prevout_index = tx->vin[input_index].prevout.n; if (input.non_witness_utxo) { utxo = input.non_witness_utxo->vout[prevout_index]; } else if (!input.witness_utxo.IsNull()) { utxo = input.witness_utxo; } else { return false; } return true; } bool PSBTInput::IsNull() const { return !non_witness_utxo && witness_utxo.IsNull() && partial_sigs.empty() && unknown.empty() && hd_keypaths.empty() && redeem_script.empty() && witness_script.empty(); } void PSBTInput::FillSignatureData(SignatureData& sigdata) const { if (!final_script_sig.empty()) { sigdata.scriptSig = final_script_sig; sigdata.complete = true; } if (!final_script_witness.IsNull()) { sigdata.scriptWitness = final_script_witness; sigdata.complete = true; } if (sigdata.complete) { return; } sigdata.signatures.insert(partial_sigs.begin(), partial_sigs.end()); if (!redeem_script.empty()) { sigdata.redeem_script = redeem_script; } if (!witness_script.empty()) { sigdata.witness_script = witness_script; } for (const auto& key_pair : hd_keypaths) { sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair); } } void PSBTInput::FromSignatureData(const SignatureData& sigdata) { if (sigdata.complete) { partial_sigs.clear(); hd_keypaths.clear(); redeem_script.clear(); witness_script.clear(); if (!sigdata.scriptSig.empty()) { final_script_sig = sigdata.scriptSig; } if (!sigdata.scriptWitness.IsNull()) { final_script_witness = sigdata.scriptWitness; } return; } partial_sigs.insert(sigdata.signatures.begin(), sigdata.signatures.end()); if (redeem_script.empty() && !sigdata.redeem_script.empty()) { redeem_script = sigdata.redeem_script; } if (witness_script.empty() && !sigdata.witness_script.empty()) { witness_script = sigdata.witness_script; } for (const auto& entry : sigdata.misc_pubkeys) { hd_keypaths.emplace(entry.second); } } void PSBTInput::Merge(const PSBTInput& input) { if (!non_witness_utxo && input.non_witness_utxo) non_witness_utxo = input.non_witness_utxo; if (witness_utxo.IsNull() && !input.witness_utxo.IsNull()) { witness_utxo = input.witness_utxo; non_witness_utxo = nullptr; // Clear out any non-witness utxo when we set a witness one. } partial_sigs.insert(input.partial_sigs.begin(), input.partial_sigs.end()); hd_keypaths.insert(input.hd_keypaths.begin(), input.hd_keypaths.end()); unknown.insert(input.unknown.begin(), input.unknown.end()); if (redeem_script.empty() && !input.redeem_script.empty()) redeem_script = input.redeem_script; if (witness_script.empty() && !input.witness_script.empty()) witness_script = input.witness_script; if (final_script_sig.empty() && !input.final_script_sig.empty()) final_script_sig = input.final_script_sig; if (final_script_witness.IsNull() && !input.final_script_witness.IsNull()) final_script_witness = input.final_script_witness; } bool PSBTInput::IsSane() const { // Cannot have both witness and non-witness utxos if (!witness_utxo.IsNull() && non_witness_utxo) return false; // If we have a witness_script or a scriptWitness, we must also have a witness utxo if (!witness_script.empty() && witness_utxo.IsNull()) return false; if (!final_script_witness.IsNull() && witness_utxo.IsNull()) return false; return true; } void PSBTOutput::FillSignatureData(SignatureData& sigdata) const { if (!redeem_script.empty()) { sigdata.redeem_script = redeem_script; } if (!witness_script.empty()) { sigdata.witness_script = witness_script; } for (const auto& key_pair : hd_keypaths) { sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair); } } void PSBTOutput::FromSignatureData(const SignatureData& sigdata) { if (redeem_script.empty() && !sigdata.redeem_script.empty()) { redeem_script = sigdata.redeem_script; } if (witness_script.empty() && !sigdata.witness_script.empty()) { witness_script = sigdata.witness_script; } for (const auto& entry : sigdata.misc_pubkeys) { hd_keypaths.emplace(entry.second); } } bool PSBTOutput::IsNull() const { return redeem_script.empty() && witness_script.empty() && hd_keypaths.empty() && unknown.empty(); } void PSBTOutput::Merge(const PSBTOutput& output) { hd_keypaths.insert(output.hd_keypaths.begin(), output.hd_keypaths.end()); unknown.insert(output.unknown.begin(), output.unknown.end()); if (redeem_script.empty() && !output.redeem_script.empty()) redeem_script = output.redeem_script; if (witness_script.empty() && !output.witness_script.empty()) witness_script = output.witness_script; } bool PSBTInputSigned(const PSBTInput& input) { return !input.final_script_sig.empty() || !input.final_script_witness.IsNull(); } void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index) { const CTxOut& out = psbt.tx->vout.at(index); PSBTOutput& psbt_out = psbt.outputs.at(index); // Fill a SignatureData with output info SignatureData sigdata; psbt_out.FillSignatureData(sigdata); // Construct a would-be spend of this output, to update sigdata with. // Note that ProduceSignature is used to fill in metadata (not actual signatures), // so provider does not need to provide any private keys (it can be a HidingSigningProvider). MutableTransactionSignatureCreator creator(psbt.tx.get_ptr(), /* index */ 0, out.nValue, SIGHASH_ALL); ProduceSignature(provider, creator, out.scriptPubKey, sigdata); // Put redeem_script, witness_script, key paths, into PSBTOutput. psbt_out.FromSignatureData(sigdata); } bool SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, int sighash, SignatureData* out_sigdata, bool use_dummy) { PSBTInput& input = psbt.inputs.at(index); const CMutableTransaction& tx = *psbt.tx; if (PSBTInputSigned(input)) { return true; } // Fill SignatureData with input info SignatureData sigdata; input.FillSignatureData(sigdata); // Get UTXO bool require_witness_sig = false; CTxOut utxo; // Verify input sanity, which checks that at most one of witness or non-witness utxos is provided. if (!input.IsSane()) { return false; } if (input.non_witness_utxo) { // If we're taking our information from a non-witness UTXO, verify that it matches the prevout. COutPoint prevout = tx.vin[index].prevout; if (input.non_witness_utxo->GetHash() != prevout.hash) { return false; } utxo = input.non_witness_utxo->vout[prevout.n]; } else if (!input.witness_utxo.IsNull()) { utxo = input.witness_utxo; // When we're taking our information from a witness UTXO, we can't verify it is actually data from // the output being spent. This is safe in case a witness signature is produced (which includes this // information directly in the hash), but not for non-witness signatures. Remember that we require // a witness signature in this situation. require_witness_sig = true; } else { return false; } sigdata.witness = false; bool sig_complete; if (use_dummy) { sig_complete = ProduceSignature(provider, DUMMY_SIGNATURE_CREATOR, utxo.scriptPubKey, sigdata); } else { MutableTransactionSignatureCreator creator(&tx, index, utxo.nValue, sighash); sig_complete = ProduceSignature(provider, creator, utxo.scriptPubKey, sigdata); } // Verify that a witness signature was produced in case one was required. if (require_witness_sig && !sigdata.witness) return false; input.FromSignatureData(sigdata); // If we have a witness signature, use the smaller witness UTXO. if (sigdata.witness) { input.witness_utxo = utxo; input.non_witness_utxo = nullptr; } // Fill in the missing info if (out_sigdata) { out_sigdata->missing_pubkeys = sigdata.missing_pubkeys; out_sigdata->missing_sigs = sigdata.missing_sigs; out_sigdata->missing_redeem_script = sigdata.missing_redeem_script; out_sigdata->missing_witness_script = sigdata.missing_witness_script; } return sig_complete; } bool FinalizePSBT(PartiallySignedTransaction& psbtx) { // Finalize input signatures -- in case we have partial signatures that add up to a complete // signature, but have not combined them yet (e.g. because the combiner that created this // PartiallySignedTransaction did not understand them), this will combine them into a final // script. bool complete = true; for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) { complete &= SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, SIGHASH_ALL); } return complete; } bool FinalizeAndExtractPSBT(PartiallySignedTransaction& psbtx, CMutableTransaction& result) { // It's not safe to extract a PSBT that isn't finalized, and there's no easy way to check // whether a PSBT is finalized without finalizing it, so we just do this. if (!FinalizePSBT(psbtx)) { return false; } result = *psbtx.tx; for (unsigned int i = 0; i < result.vin.size(); ++i) { result.vin[i].scriptSig = psbtx.inputs[i].final_script_sig; result.vin[i].scriptWitness = psbtx.inputs[i].final_script_witness; } return true; } TransactionError CombinePSBTs(PartiallySignedTransaction& out, const std::vector<PartiallySignedTransaction>& psbtxs) { out = psbtxs[0]; // Copy the first one // Merge for (auto it = std::next(psbtxs.begin()); it != psbtxs.end(); ++it) { if (!out.Merge(*it)) { return TransactionError::PSBT_MISMATCH; } } if (!out.IsSane()) { return TransactionError::INVALID_PSBT; } return TransactionError::OK; } std::string PSBTRoleName(PSBTRole role) { switch (role) { case PSBTRole::UPDATER: return "updater"; case PSBTRole::SIGNER: return "signer"; case PSBTRole::FINALIZER: return "finalizer"; case PSBTRole::EXTRACTOR: return "extractor"; // no default case, so the compiler can warn about missing cases } assert(false); } bool DecodeBase64PSBT(PartiallySignedTransaction& psbt, const std::string& base64_tx, std::string& error) { bool invalid; std::string tx_data = DecodeBase64(base64_tx, &invalid); if (invalid) { error = "invalid base64"; return false; } return DecodeRawPSBT(psbt, tx_data, error); } bool DecodeRawPSBT(PartiallySignedTransaction& psbt, const std::string& tx_data, std::string& error) { CDataStream ss_data(tx_data.data(), tx_data.data() + tx_data.size(), SER_NETWORK, PROTOCOL_VERSION); try { ss_data >> psbt; if (!ss_data.empty()) { error = "extra data after PSBT"; return false; } } catch (const std::exception& e) { error = e.what(); return false; } return true; }
; $Id: bs3-cmn-RegGetTr.asm 72138 2018-05-07 13:03:51Z vboxsync $ ;; @file ; BS3Kit - Bs3RegGetTr ; ; ; Copyright (C) 2007-2018 Oracle Corporation ; ; This file is part of VirtualBox Open Source Edition (OSE), as ; available from http://www.virtualbox.org. This file is free software; ; you can redistribute it and/or modify it under the terms of the GNU ; General Public License (GPL) as published by the Free Software ; Foundation, in version 2 as it comes in the "COPYING" file of the ; VirtualBox OSE distribution. VirtualBox OSE is distributed in the ; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. ; ; The contents of this file may alternatively be used under the terms ; of the Common Development and Distribution License Version 1.0 ; (CDDL) only, as it comes in the "COPYING.CDDL" file of the ; VirtualBox OSE distribution, in which case the provisions of the ; CDDL are applicable instead of those of the GPL. ; ; You may elect to license modified versions of this file under the ; terms and conditions of either the GPL or the CDDL or both. ; %include "bs3kit-template-header.mac" BS3_EXTERN_CMN Bs3Syscall %if TMPL_BITS == 16 BS3_EXTERN_DATA16 g_bBs3CurrentMode %endif BS3_EXTERN_SYSTEM16 Bs3Gdt TMPL_BEGIN_TEXT ;; ; @cproto BS3_CMN_PROTO_STUB(uint16_t, Bs3RegGetTr,(void)); ; ; @returns The LDTR value. ; @remarks Does not require 20h of parameter scratch space in 64-bit mode. ; ; @uses No GPRs. ; BS3_PROC_BEGIN_CMN Bs3RegGetTr, BS3_PBC_HYBRID_SAFE BS3_CALL_CONV_PROLOG 0 push xBP mov xBP, xSP %if TMPL_BITS == 16 ; If V8086 mode we have to go thru a syscall. test byte [BS3_DATA16_WRT(g_bBs3CurrentMode)], BS3_MODE_CODE_V86 jnz .via_system_call %endif ; Load it. str ax jmp .return .via_system_call: mov ax, BS3_SYSCALL_GET_TR call Bs3Syscall .return: pop xBP BS3_CALL_CONV_EPILOG 0 BS3_HYBRID_RET BS3_PROC_END_CMN Bs3RegGetTr
; ; int fdgetpos(int fd, long *dump) ; ; Return position in file ; ; This returns longs even though there's no real need to do so ; ; $Id: fdgetpos.asm,v 1.2 2003/10/13 22:57:00 dom Exp $ XLIB fdgetpos INCLUDE "#p3dos.def" LIB l_plong XREF dodos .fdgetpos pop hl ;ret address pop de ;where to store it pop bc ;lower 8 is file handle push bc pop de push hl ld b,c push de ;save store location ld iy,DOS_GET_POSITION call dodos pop bc ;get store location back jr nc,fdgetpos_store ld hl,-1 ret .fdgetpos_store ld d,0 ;clear upper byte call l_plong ld hl,0 ret
// Copyright (c) 2012 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 "net/http/http_auth_controller.h" #include <utility> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/platform_thread.h" #include "base/values.h" #include "net/base/auth.h" #include "net/base/url_util.h" #include "net/dns/host_resolver.h" #include "net/http/http_auth_handler.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_network_session.h" #include "net/http/http_request_headers.h" #include "net/http/http_request_info.h" #include "net/http/http_response_headers.h" #include "net/log/net_log_event_type.h" #include "net/log/net_log_source.h" #include "net/log/net_log_source_type.h" #include "net/log/net_log_with_source.h" namespace net { namespace { enum AuthEvent { AUTH_EVENT_START = 0, AUTH_EVENT_REJECT, AUTH_EVENT_MAX, }; enum AuthTarget { AUTH_TARGET_PROXY = 0, AUTH_TARGET_SECURE_PROXY, AUTH_TARGET_SERVER, AUTH_TARGET_SECURE_SERVER, AUTH_TARGET_MAX, }; AuthTarget DetermineAuthTarget(const HttpAuthHandler* handler) { switch (handler->target()) { case HttpAuth::AUTH_PROXY: if (handler->origin().SchemeIsCryptographic()) return AUTH_TARGET_SECURE_PROXY; else return AUTH_TARGET_PROXY; case HttpAuth::AUTH_SERVER: if (handler->origin().SchemeIsCryptographic()) return AUTH_TARGET_SECURE_SERVER; else return AUTH_TARGET_SERVER; default: NOTREACHED(); return AUTH_TARGET_MAX; } } // Records the number of authentication events per authentication scheme. void HistogramAuthEvent(HttpAuthHandler* handler, AuthEvent auth_event) { #if !defined(NDEBUG) // Note: The on-same-thread check is intentionally not using a lock // to protect access to first_thread. This method is meant to be only // used on the same thread, in which case there are no race conditions. If // there are race conditions (say, a read completes during a partial write), // the DCHECK will correctly fail. static base::PlatformThreadId first_thread = base::PlatformThread::CurrentId(); DCHECK_EQ(first_thread, base::PlatformThread::CurrentId()); #endif HttpAuth::Scheme auth_scheme = handler->auth_scheme(); DCHECK(auth_scheme >= 0 && auth_scheme < HttpAuth::AUTH_SCHEME_MAX); // Record start and rejection events for authentication. // // The results map to: // Basic Start: 0 // Basic Reject: 1 // Digest Start: 2 // Digest Reject: 3 // NTLM Start: 4 // NTLM Reject: 5 // Negotiate Start: 6 // Negotiate Reject: 7 static const int kEventBucketsEnd = HttpAuth::AUTH_SCHEME_MAX * AUTH_EVENT_MAX; int event_bucket = auth_scheme * AUTH_EVENT_MAX + auth_event; DCHECK(event_bucket >= 0 && event_bucket < kEventBucketsEnd); UMA_HISTOGRAM_ENUMERATION("Net.HttpAuthCount", event_bucket, kEventBucketsEnd); // Record the target of the authentication. // // The results map to: // Basic Proxy: 0 // Basic Secure Proxy: 1 // Basic Server: 2 // Basic Secure Server: 3 // Digest Proxy: 4 // Digest Secure Proxy: 5 // Digest Server: 6 // Digest Secure Server: 7 // NTLM Proxy: 8 // NTLM Secure Proxy: 9 // NTLM Server: 10 // NTLM Secure Server: 11 // Negotiate Proxy: 12 // Negotiate Secure Proxy: 13 // Negotiate Server: 14 // Negotiate Secure Server: 15 if (auth_event != AUTH_EVENT_START) return; static const int kTargetBucketsEnd = HttpAuth::AUTH_SCHEME_MAX * AUTH_TARGET_MAX; AuthTarget auth_target = DetermineAuthTarget(handler); int target_bucket = auth_scheme * AUTH_TARGET_MAX + auth_target; DCHECK(target_bucket >= 0 && target_bucket < kTargetBucketsEnd); UMA_HISTOGRAM_ENUMERATION("Net.HttpAuthTarget", target_bucket, kTargetBucketsEnd); } base::Value ControllerParamsToValue(HttpAuth::Target target, const GURL& url) { base::Value params(base::Value::Type::DICTIONARY); params.SetStringPath("target", HttpAuth::GetAuthTargetString(target)); params.SetStringPath("url", url.spec()); return params; } } // namespace HttpAuthController::HttpAuthController( HttpAuth::Target target, const GURL& auth_url, const NetworkIsolationKey& network_isolation_key, HttpAuthCache* http_auth_cache, HttpAuthHandlerFactory* http_auth_handler_factory, HostResolver* host_resolver) : target_(target), auth_url_(auth_url), auth_origin_(auth_url.DeprecatedGetOriginAsURL()), auth_path_(auth_url.path()), network_isolation_key_(network_isolation_key), embedded_identity_used_(false), default_credentials_used_(false), http_auth_cache_(http_auth_cache), http_auth_handler_factory_(http_auth_handler_factory), host_resolver_(host_resolver) { DCHECK(target != HttpAuth::AUTH_PROXY || auth_path_ == "/"); } HttpAuthController::~HttpAuthController() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (net_log_.source().IsValid()) net_log_.EndEvent(NetLogEventType::AUTH_CONTROLLER); } void HttpAuthController::BindToCallingNetLog( const NetLogWithSource& caller_net_log) { if (!net_log_.source().IsValid()) { net_log_ = NetLogWithSource::Make(caller_net_log.net_log(), NetLogSourceType::HTTP_AUTH_CONTROLLER); net_log_.BeginEvent(NetLogEventType::AUTH_CONTROLLER, [&] { return ControllerParamsToValue(target_, auth_url_); }); } caller_net_log.AddEventReferencingSource( NetLogEventType::AUTH_BOUND_TO_CONTROLLER, net_log_.source()); } int HttpAuthController::MaybeGenerateAuthToken( const HttpRequestInfo* request, CompletionOnceCallback callback, const NetLogWithSource& caller_net_log) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(!auth_info_); bool needs_auth = HaveAuth() || SelectPreemptiveAuth(caller_net_log); if (!needs_auth) return OK; net_log_.BeginEventReferencingSource(NetLogEventType::AUTH_GENERATE_TOKEN, caller_net_log.source()); const AuthCredentials* credentials = nullptr; if (identity_.source != HttpAuth::IDENT_SRC_DEFAULT_CREDENTIALS) credentials = &identity_.credentials; DCHECK(auth_token_.empty()); DCHECK(callback_.is_null()); int rv = handler_->GenerateAuthToken( credentials, request, base::BindOnce(&HttpAuthController::OnGenerateAuthTokenDone, base::Unretained(this)), &auth_token_); if (rv == ERR_IO_PENDING) { callback_ = std::move(callback); return rv; } return HandleGenerateTokenResult(rv); } bool HttpAuthController::SelectPreemptiveAuth( const NetLogWithSource& caller_net_log) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(!HaveAuth()); DCHECK(identity_.invalid); // Don't do preemptive authorization if the URL contains a username:password, // since we must first be challenged in order to use the URL's identity. if (auth_url_.has_username()) return false; // SelectPreemptiveAuth() is on the critical path for each request, so it // is expected to be fast. LookupByPath() is fast in the common case, since // the number of http auth cache entries is expected to be very small. // (For most users in fact, it will be 0.) HttpAuthCache::Entry* entry = http_auth_cache_->LookupByPath( auth_origin_, target_, network_isolation_key_, auth_path_); if (!entry) return false; BindToCallingNetLog(caller_net_log); // Try to create a handler using the previous auth challenge. std::unique_ptr<HttpAuthHandler> handler_preemptive; int rv_create = http_auth_handler_factory_->CreatePreemptiveAuthHandlerFromString( entry->auth_challenge(), target_, network_isolation_key_, auth_origin_, entry->IncrementNonceCount(), net_log_, host_resolver_, &handler_preemptive); if (rv_create != OK) return false; // Set the state identity_.source = HttpAuth::IDENT_SRC_PATH_LOOKUP; identity_.invalid = false; identity_.credentials = entry->credentials(); handler_.swap(handler_preemptive); return true; } void HttpAuthController::AddAuthorizationHeader( HttpRequestHeaders* authorization_headers) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(HaveAuth()); // auth_token_ can be empty if we encountered a permanent error with // the auth scheme and want to retry. if (!auth_token_.empty()) { authorization_headers->SetHeader( HttpAuth::GetAuthorizationHeaderName(target_), auth_token_); auth_token_.clear(); } } int HttpAuthController::HandleAuthChallenge( scoped_refptr<HttpResponseHeaders> headers, const SSLInfo& ssl_info, bool do_not_send_server_auth, bool establishing_tunnel, const NetLogWithSource& caller_net_log) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(headers.get()); DCHECK(auth_origin_.is_valid()); DCHECK(!auth_info_); BindToCallingNetLog(caller_net_log); net_log_.BeginEventReferencingSource(NetLogEventType::AUTH_HANDLE_CHALLENGE, caller_net_log.source()); // Give the existing auth handler first try at the authentication headers. // This will also evict the entry in the HttpAuthCache if the previous // challenge appeared to be rejected, or is using a stale nonce in the Digest // case. if (HaveAuth()) { std::string challenge_used; HttpAuth::AuthorizationResult result = HttpAuth::HandleChallengeResponse( handler_.get(), *headers, target_, disabled_schemes_, &challenge_used); switch (result) { case HttpAuth::AUTHORIZATION_RESULT_ACCEPT: break; case HttpAuth::AUTHORIZATION_RESULT_INVALID: InvalidateCurrentHandler(INVALIDATE_HANDLER_AND_CACHED_CREDENTIALS); break; case HttpAuth::AUTHORIZATION_RESULT_REJECT: HistogramAuthEvent(handler_.get(), AUTH_EVENT_REJECT); InvalidateCurrentHandler(INVALIDATE_HANDLER_AND_CACHED_CREDENTIALS); break; case HttpAuth::AUTHORIZATION_RESULT_STALE: if (http_auth_cache_->UpdateStaleChallenge( auth_origin_, target_, handler_->realm(), handler_->auth_scheme(), network_isolation_key_, challenge_used)) { InvalidateCurrentHandler(INVALIDATE_HANDLER); } else { // It's possible that a server could incorrectly issue a stale // response when the entry is not in the cache. Just evict the // current value from the cache. InvalidateCurrentHandler(INVALIDATE_HANDLER_AND_CACHED_CREDENTIALS); } break; case HttpAuth::AUTHORIZATION_RESULT_DIFFERENT_REALM: // If the server changes the authentication realm in a // subsequent challenge, invalidate cached credentials for the // previous realm. If the server rejects a preemptive // authorization and requests credentials for a different // realm, we keep the cached credentials. InvalidateCurrentHandler( (identity_.source == HttpAuth::IDENT_SRC_PATH_LOOKUP) ? INVALIDATE_HANDLER : INVALIDATE_HANDLER_AND_CACHED_CREDENTIALS); break; default: NOTREACHED(); break; } } identity_.invalid = true; bool can_send_auth = (target_ != HttpAuth::AUTH_SERVER || !do_not_send_server_auth); do { if (!handler_.get() && can_send_auth) { // Find the best authentication challenge that we support. HttpAuth::ChooseBestChallenge(http_auth_handler_factory_, *headers, ssl_info, network_isolation_key_, target_, auth_origin_, disabled_schemes_, net_log_, host_resolver_, &handler_); if (handler_.get()) HistogramAuthEvent(handler_.get(), AUTH_EVENT_START); } if (!handler_.get()) { if (establishing_tunnel) { // We are establishing a tunnel, we can't show the error page because an // active network attacker could control its contents. Instead, we just // fail to establish the tunnel. DCHECK_EQ(target_, HttpAuth::AUTH_PROXY); net_log_.EndEventWithNetErrorCode( NetLogEventType::AUTH_HANDLE_CHALLENGE, ERR_PROXY_AUTH_UNSUPPORTED); return ERR_PROXY_AUTH_UNSUPPORTED; } // We found no supported challenge -- let the transaction continue so we // end up displaying the error page. net_log_.EndEvent(NetLogEventType::AUTH_HANDLE_CHALLENGE); return OK; } if (handler_->NeedsIdentity()) { // Pick a new auth identity to try, by looking to the URL and auth cache. // If an identity to try is found, it is saved to identity_. SelectNextAuthIdentityToTry(); } else { // Proceed with the existing identity or a null identity. identity_.invalid = false; } // From this point on, we are restartable. if (identity_.invalid) { // We have exhausted all identity possibilities. if (!handler_->AllowsExplicitCredentials()) { // If the handler doesn't accept explicit credentials, then we need to // choose a different auth scheme. HistogramAuthEvent(handler_.get(), AUTH_EVENT_REJECT); InvalidateCurrentHandler(INVALIDATE_HANDLER_AND_DISABLE_SCHEME); } else { // Pass the challenge information back to the client. PopulateAuthChallenge(); } } // If we get here and we don't have a handler_, that's because we // invalidated it due to not having any viable identities to use with it. Go // back and try again. // TODO(asanka): Instead we should create a priority list of // <handler,identity> and iterate through that. } while(!handler_.get()); net_log_.EndEvent(NetLogEventType::AUTH_HANDLE_CHALLENGE); return OK; } void HttpAuthController::ResetAuth(const AuthCredentials& credentials) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(identity_.invalid || credentials.Empty()); if (identity_.invalid) { // Update the credentials. identity_.source = HttpAuth::IDENT_SRC_EXTERNAL; identity_.invalid = false; identity_.credentials = credentials; // auth_info_ is no longer necessary. auth_info_ = absl::nullopt; } DCHECK(identity_.source != HttpAuth::IDENT_SRC_PATH_LOOKUP); // Add the auth entry to the cache before restarting. We don't know whether // the identity is valid yet, but if it is valid we want other transactions // to know about it. If an entry for (origin, handler->realm()) already // exists, we update it. // // If identity_.source is HttpAuth::IDENT_SRC_NONE or // HttpAuth::IDENT_SRC_DEFAULT_CREDENTIALS, identity_ contains no // identity because identity is not required yet or we're using default // credentials. // // TODO(wtc): For NTLM_SSPI, we add the same auth entry to the cache in // round 1 and round 2, which is redundant but correct. It would be nice // to add an auth entry to the cache only once, preferrably in round 1. // See http://crbug.com/21015. switch (identity_.source) { case HttpAuth::IDENT_SRC_NONE: case HttpAuth::IDENT_SRC_DEFAULT_CREDENTIALS: break; default: http_auth_cache_->Add(auth_origin_, target_, handler_->realm(), handler_->auth_scheme(), network_isolation_key_, handler_->challenge(), identity_.credentials, auth_path_); break; } } bool HttpAuthController::HaveAuthHandler() const { return handler_.get() != nullptr; } bool HttpAuthController::HaveAuth() const { return handler_.get() && !identity_.invalid; } bool HttpAuthController::NeedsHTTP11() const { return handler_ && handler_->is_connection_based(); } void HttpAuthController::InvalidateCurrentHandler( InvalidateHandlerAction action) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(handler_.get()); switch (action) { case INVALIDATE_HANDLER_AND_CACHED_CREDENTIALS: InvalidateRejectedAuthFromCache(); break; case INVALIDATE_HANDLER_AND_DISABLE_SCHEME: DisableAuthScheme(handler_->auth_scheme()); break; case INVALIDATE_HANDLER: PrepareIdentityForReuse(); break; } handler_.reset(); identity_ = HttpAuth::Identity(); } void HttpAuthController::InvalidateRejectedAuthFromCache() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(HaveAuth()); // Clear the cache entry for the identity we just failed on. // Note: we require the credentials to match before invalidating // since the entry in the cache may be newer than what we used last time. http_auth_cache_->Remove(auth_origin_, target_, handler_->realm(), handler_->auth_scheme(), network_isolation_key_, identity_.credentials); } void HttpAuthController::PrepareIdentityForReuse() { if (identity_.invalid) return; switch (identity_.source) { case HttpAuth::IDENT_SRC_DEFAULT_CREDENTIALS: DCHECK(default_credentials_used_); default_credentials_used_ = false; break; case HttpAuth::IDENT_SRC_URL: DCHECK(embedded_identity_used_); embedded_identity_used_ = false; break; case HttpAuth::IDENT_SRC_NONE: case HttpAuth::IDENT_SRC_PATH_LOOKUP: case HttpAuth::IDENT_SRC_REALM_LOOKUP: case HttpAuth::IDENT_SRC_EXTERNAL: break; } } bool HttpAuthController::SelectNextAuthIdentityToTry() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(handler_.get()); DCHECK(identity_.invalid); // Try to use the username:password encoded into the URL first. if (target_ == HttpAuth::AUTH_SERVER && auth_url_.has_username() && !embedded_identity_used_) { identity_.source = HttpAuth::IDENT_SRC_URL; identity_.invalid = false; // Extract the username:password from the URL. std::u16string username; std::u16string password; GetIdentityFromURL(auth_url_, &username, &password); identity_.credentials.Set(username, password); embedded_identity_used_ = true; // TODO(eroman): If the password is blank, should we also try combining // with a password from the cache? UMA_HISTOGRAM_BOOLEAN("net.HttpIdentSrcURL", true); return true; } // Check the auth cache for a realm entry. HttpAuthCache::Entry* entry = http_auth_cache_->Lookup(auth_origin_, target_, handler_->realm(), handler_->auth_scheme(), network_isolation_key_); if (entry) { identity_.source = HttpAuth::IDENT_SRC_REALM_LOOKUP; identity_.invalid = false; identity_.credentials = entry->credentials(); return true; } // Use default credentials (single sign-on) if they're allowed and this is the // first attempt at using an identity. Do not allow multiple times as it will // infinite loop. We use default credentials after checking the auth cache so // that if single sign-on doesn't work, we won't try default credentials for // future transactions. if (!default_credentials_used_ && handler_->AllowsDefaultCredentials()) { identity_.source = HttpAuth::IDENT_SRC_DEFAULT_CREDENTIALS; identity_.invalid = false; default_credentials_used_ = true; return true; } return false; } void HttpAuthController::PopulateAuthChallenge() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); // Populates response_.auth_challenge with the authentication challenge info. // This info is consumed by URLRequestHttpJob::GetAuthChallengeInfo(). auth_info_ = AuthChallengeInfo(); auth_info_->is_proxy = (target_ == HttpAuth::AUTH_PROXY); auth_info_->challenger = url::Origin::Create(auth_origin_); auth_info_->scheme = HttpAuth::SchemeToString(handler_->auth_scheme()); auth_info_->realm = handler_->realm(); auth_info_->path = auth_path_; auth_info_->challenge = handler_->challenge(); } int HttpAuthController::HandleGenerateTokenResult(int result) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); net_log_.EndEventWithNetErrorCode(NetLogEventType::AUTH_GENERATE_TOKEN, result); switch (result) { // Occurs if the credential handle is found to be invalid at the point it is // exercised (i.e. GenerateAuthToken stage). We are going to consider this // to be an error that invalidates the identity but not necessarily the // scheme. Doing so allows a different identity to be used with the same // scheme. See https://crbug.com/648366. case ERR_INVALID_HANDLE: // If the GenerateAuthToken call fails with this error, this means that the // handler can no longer be used. However, the authentication scheme is // considered still usable. This allows a scheme that attempted and failed // to use default credentials to recover and use explicit credentials. // // The current handler may be tied to external state that is no longer // valid, hence should be discarded. Since the scheme is still valid, a new // handler can be created for the current scheme. case ERR_INVALID_AUTH_CREDENTIALS: InvalidateCurrentHandler(INVALIDATE_HANDLER_AND_CACHED_CREDENTIALS); auth_token_.clear(); return OK; // Occurs with GSSAPI, if the user has not already logged in. case ERR_MISSING_AUTH_CREDENTIALS: // Can occur with GSSAPI or SSPI if the underlying library reports // a permanent error. case ERR_UNSUPPORTED_AUTH_SCHEME: // These two error codes represent failures we aren't handling. case ERR_UNEXPECTED_SECURITY_LIBRARY_STATUS: case ERR_UNDOCUMENTED_SECURITY_LIBRARY_STATUS: // Can be returned by SSPI if the authenticating authority or // target is not known. case ERR_MISCONFIGURED_AUTH_ENVIRONMENT: // In these cases, disable the current scheme as it cannot // succeed. InvalidateCurrentHandler(INVALIDATE_HANDLER_AND_DISABLE_SCHEME); auth_token_.clear(); return OK; default: return result; } } void HttpAuthController::OnGenerateAuthTokenDone(int result) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); result = HandleGenerateTokenResult(result); if (!callback_.is_null()) { std::move(callback_).Run(result); } } void HttpAuthController::TakeAuthInfo( absl::optional<AuthChallengeInfo>* other) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); auth_info_.swap(*other); } bool HttpAuthController::IsAuthSchemeDisabled(HttpAuth::Scheme scheme) const { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); return disabled_schemes_.find(scheme) != disabled_schemes_.end(); } void HttpAuthController::DisableAuthScheme(HttpAuth::Scheme scheme) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); disabled_schemes_.insert(scheme); } void HttpAuthController::DisableEmbeddedIdentity() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); embedded_identity_used_ = true; } void HttpAuthController::OnConnectionClosed() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); InvalidateCurrentHandler(INVALIDATE_HANDLER); } } // namespace net
/*========================================================================= Library: CTK Copyright (c) Kitware 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.txt 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 <stdexcept> // Qt includes #include <QDate> #include <QDebug> #include <QFile> #include <QFileInfo> #include <QFileSystemWatcher> #include <QSet> #include <QSqlError> #include <QSqlQuery> #include <QSqlRecord> #include <QStringList> #include <QVariant> // ctkDICOM includes #include "ctkDICOMDatabase.h" #include "ctkDICOMAbstractThumbnailGenerator.h" #include "ctkDICOMItem.h" #include "ctkLogger.h" // DCMTK includes #include <dcmtk/dcmdata/dcfilefo.h> #include <dcmtk/dcmdata/dcfilefo.h> #include <dcmtk/dcmdata/dcdeftag.h> #include <dcmtk/dcmdata/dcdatset.h> #include <dcmtk/ofstd/ofcond.h> #include <dcmtk/ofstd/ofstring.h> #include <dcmtk/ofstd/ofstd.h> /* for class OFStandard */ #include <dcmtk/dcmdata/dcddirif.h> /* for class DicomDirInterface */ #include <dcmtk/dcmimgle/dcmimage.h> #include <dcmtk/dcmjpeg/djdecode.h> /* for dcmjpeg decoders */ #include <dcmtk/dcmjpeg/djencode.h> /* for dcmjpeg encoders */ #include <dcmtk/dcmdata/dcrledrg.h> /* for DcmRLEDecoderRegistration */ #include <dcmtk/dcmdata/dcrleerg.h> /* for DcmRLEEncoderRegistration */ //------------------------------------------------------------------------------ static ctkLogger logger("org.commontk.dicom.DICOMDatabase" ); //------------------------------------------------------------------------------ // Flag for tag cache to avoid repeated serarches for // tags that do no exist. static QString TagNotInInstance("__TAG_NOT_IN_INSTANCE__"); // Flag for tag cache indicating that the value // really is the empty string static QString ValueIsEmptyString("__VALUE_IS_EMPTY_STRING__"); //------------------------------------------------------------------------------ class ctkDICOMDatabasePrivate { Q_DECLARE_PUBLIC(ctkDICOMDatabase); protected: ctkDICOMDatabase* const q_ptr; public: ctkDICOMDatabasePrivate(ctkDICOMDatabase&); ~ctkDICOMDatabasePrivate(); void init(QString databaseFile); void registerCompressionLibraries(); bool executeScript(const QString script); /// /// \brief runs a query and prints debug output of status /// bool loggedExec(QSqlQuery& query); bool loggedExec(QSqlQuery& query, const QString& queryString); bool loggedExecBatch(QSqlQuery& query); bool LoggedExecVerbose; /// /// \brief group several inserts into a single transaction /// void beginTransaction(); void endTransaction(); // dataset must be set always // filePath has to be set if this is an import of an actual file void insert ( const ctkDICOMItem& ctkDataset, const QString& filePath, bool storeFile = true, bool generateThumbnail = true); /// /// copy the complete list of files to an extra table /// void createBackupFileList(); /// /// remove the extra table containing the backup /// void removeBackupFileList(); /// /// get all Filename values from table QStringList filenames(QString table); /// Name of the database file (i.e. for SQLITE the sqlite file) QString DatabaseFileName; QString LastError; QSqlDatabase Database; QMap<QString, QString> LoadedHeader; ctkDICOMAbstractThumbnailGenerator* thumbnailGenerator; /// these are for optimizing the import of image sequences /// since most information are identical for all slices QString LastPatientID; QString LastPatientsName; QString LastPatientsBirthDate; QString LastStudyInstanceUID; QString LastSeriesInstanceUID; int LastPatientUID; /// resets the variables to new inserts won't be fooled by leftover values void resetLastInsertedValues(); /// tagCache table has been checked to exist bool TagCacheVerified; /// tag cache has independent database to avoid locking issue /// with other access to the database which need to be /// reading while the tag cache is writing QSqlDatabase TagCacheDatabase; QString TagCacheDatabaseFilename; QStringList TagsToPrecache; void precacheTags( const QString sopInstanceUID ); int insertPatient(const ctkDICOMItem& ctkDataset); void insertStudy(const ctkDICOMItem& ctkDataset, int dbPatientID); void insertSeries( const ctkDICOMItem& ctkDataset, QString studyInstanceUID); }; //------------------------------------------------------------------------------ // ctkDICOMDatabasePrivate methods //------------------------------------------------------------------------------ ctkDICOMDatabasePrivate::ctkDICOMDatabasePrivate(ctkDICOMDatabase& o): q_ptr(&o) { this->thumbnailGenerator = NULL; this->LoggedExecVerbose = false; this->TagCacheVerified = false; this->resetLastInsertedValues(); } //------------------------------------------------------------------------------ void ctkDICOMDatabasePrivate::resetLastInsertedValues() { this->LastPatientID = QString(""); this->LastPatientsName = QString(""); this->LastPatientsBirthDate = QString(""); this->LastStudyInstanceUID = QString(""); this->LastSeriesInstanceUID = QString(""); this->LastPatientUID = -1; } //------------------------------------------------------------------------------ void ctkDICOMDatabasePrivate::init(QString databaseFilename) { Q_Q(ctkDICOMDatabase); q->openDatabase(databaseFilename); } //------------------------------------------------------------------------------ void ctkDICOMDatabasePrivate::registerCompressionLibraries(){ // Register the JPEG libraries in case we need them // (registration only happens once, so it's okay to call repeatedly) // register global JPEG decompression codecs DJDecoderRegistration::registerCodecs(); // register global JPEG compression codecs DJEncoderRegistration::registerCodecs(); // register RLE compression codec DcmRLEEncoderRegistration::registerCodecs(); // register RLE decompression codec DcmRLEDecoderRegistration::registerCodecs(); } //------------------------------------------------------------------------------ ctkDICOMDatabasePrivate::~ctkDICOMDatabasePrivate() { } //------------------------------------------------------------------------------ bool ctkDICOMDatabasePrivate::loggedExec(QSqlQuery& query) { return (loggedExec(query, QString(""))); } //------------------------------------------------------------------------------ bool ctkDICOMDatabasePrivate::loggedExec(QSqlQuery& query, const QString& queryString) { bool success; if (queryString.compare("")) { success = query.exec(queryString); } else { success = query.exec(); } if (!success) { QSqlError sqlError = query.lastError(); logger.debug( "SQL failed\n Bad SQL: " + query.lastQuery()); logger.debug( "Error text: " + sqlError.text()); } else { if (LoggedExecVerbose) { logger.debug( "SQL worked!\n SQL: " + query.lastQuery()); } } return (success); } //------------------------------------------------------------------------------ bool ctkDICOMDatabasePrivate::loggedExecBatch(QSqlQuery& query) { bool success; success = query.execBatch(); if (!success) { QSqlError sqlError = query.lastError(); logger.debug( "SQL failed\n Bad SQL: " + query.lastQuery()); logger.debug( "Error text: " + sqlError.text()); } else { if (LoggedExecVerbose) { logger.debug( "SQL worked!\n SQL: " + query.lastQuery()); } } return (success); } //------------------------------------------------------------------------------ void ctkDICOMDatabasePrivate::beginTransaction() { QSqlQuery transaction( this->Database ); transaction.prepare( "BEGIN TRANSACTION" ); transaction.exec(); } //------------------------------------------------------------------------------ void ctkDICOMDatabasePrivate::endTransaction() { QSqlQuery transaction( this->Database ); transaction.prepare( "END TRANSACTION" ); transaction.exec(); } //------------------------------------------------------------------------------ void ctkDICOMDatabasePrivate::createBackupFileList() { QSqlQuery query(this->Database); loggedExec(query, "CREATE TABLE IF NOT EXISTS main.Filenames_backup (Filename TEXT PRIMARY KEY NOT NULL )" ); loggedExec(query, "INSERT INTO Filenames_backup SELECT Filename FROM Images;" ); } //------------------------------------------------------------------------------ void ctkDICOMDatabasePrivate::removeBackupFileList() { QSqlQuery query(this->Database); loggedExec(query, "DROP TABLE main.Filenames_backup; " ); } //------------------------------------------------------------------------------ void ctkDICOMDatabase::openDatabase(const QString databaseFile, const QString& connectionName ) { Q_D(ctkDICOMDatabase); d->DatabaseFileName = databaseFile; d->Database = QSqlDatabase::addDatabase("QSQLITE", connectionName); d->Database.setDatabaseName(databaseFile); if ( ! (d->Database.open()) ) { d->LastError = d->Database.lastError().text(); return; } if ( d->Database.tables().empty() ) { if (!initializeDatabase()) { d->LastError = QString("Unable to initialize DICOM database!"); return; } } d->resetLastInsertedValues(); if (!isInMemory()) { QFileSystemWatcher* watcher = new QFileSystemWatcher(QStringList(databaseFile),this); connect(watcher, SIGNAL(fileChanged(QString)),this, SIGNAL (databaseChanged()) ); } //Disable synchronous writing to make modifications faster { QSqlQuery pragmaSyncQuery(d->Database); pragmaSyncQuery.exec("PRAGMA synchronous = OFF"); pragmaSyncQuery.finish(); } // set up the tag cache for use later QFileInfo fileInfo(d->DatabaseFileName); d->TagCacheDatabaseFilename = QString( fileInfo.dir().path() + "/ctkDICOMTagCache.sql" ); d->TagCacheVerified = false; if ( !this->tagCacheExists() ) { this->initializeTagCache(); } } //------------------------------------------------------------------------------ // ctkDICOMDatabase methods //------------------------------------------------------------------------------ ctkDICOMDatabase::ctkDICOMDatabase(QString databaseFile) : d_ptr(new ctkDICOMDatabasePrivate(*this)) { Q_D(ctkDICOMDatabase); d->registerCompressionLibraries(); d->init(databaseFile); } ctkDICOMDatabase::ctkDICOMDatabase(QObject* parent) : d_ptr(new ctkDICOMDatabasePrivate(*this)) { Q_UNUSED(parent); Q_D(ctkDICOMDatabase); d->registerCompressionLibraries(); } //------------------------------------------------------------------------------ ctkDICOMDatabase::~ctkDICOMDatabase() { } //---------------------------------------------------------------------------- //------------------------------------------------------------------------------ const QString ctkDICOMDatabase::lastError() const { Q_D(const ctkDICOMDatabase); return d->LastError; } //------------------------------------------------------------------------------ const QString ctkDICOMDatabase::databaseFilename() const { Q_D(const ctkDICOMDatabase); return d->DatabaseFileName; } //------------------------------------------------------------------------------ const QString ctkDICOMDatabase::databaseDirectory() const { QString databaseFile = databaseFilename(); if (!QFileInfo(databaseFile).isAbsolute()) { databaseFile.prepend(QDir::currentPath() + "/"); } return QFileInfo ( databaseFile ).absoluteDir().path(); } //------------------------------------------------------------------------------ const QSqlDatabase& ctkDICOMDatabase::database() const { Q_D(const ctkDICOMDatabase); return d->Database; } //------------------------------------------------------------------------------ void ctkDICOMDatabase::setThumbnailGenerator(ctkDICOMAbstractThumbnailGenerator *generator){ Q_D(ctkDICOMDatabase); d->thumbnailGenerator = generator; } //------------------------------------------------------------------------------ ctkDICOMAbstractThumbnailGenerator* ctkDICOMDatabase::thumbnailGenerator(){ Q_D(const ctkDICOMDatabase); return d->thumbnailGenerator; } //------------------------------------------------------------------------------ bool ctkDICOMDatabasePrivate::executeScript(const QString script) { QFile scriptFile(script); scriptFile.open(QIODevice::ReadOnly); if ( !scriptFile.isOpen() ) { qDebug() << "Script file " << script << " could not be opened!\n"; return false; } QString sqlCommands( QTextStream(&scriptFile).readAll() ); sqlCommands.replace( '\n', ' ' ); sqlCommands.remove( '\r' ); sqlCommands.replace("; ", ";\n"); QStringList sqlCommandsLines = sqlCommands.split('\n'); QSqlQuery query(Database); for (QStringList::iterator it = sqlCommandsLines.begin(); it != sqlCommandsLines.end()-1; ++it) { if (! (*it).startsWith("--") ) { qDebug() << *it << "\n"; query.exec(*it); if (query.lastError().type()) { qDebug() << "There was an error during execution of the statement: " << (*it); qDebug() << "Error message: " << query.lastError().text(); return false; } } } return true; } //------------------------------------------------------------------------------ QStringList ctkDICOMDatabasePrivate::filenames(QString table) { /// get all filenames from the database QSqlQuery allFilesQuery(this->Database); QStringList allFileNames; loggedExec(allFilesQuery,QString("SELECT Filename from %1 ;").arg(table) ); while (allFilesQuery.next()) { allFileNames << allFilesQuery.value(0).toString(); } return allFileNames; } //------------------------------------------------------------------------------ bool ctkDICOMDatabase::initializeDatabase(const char* sqlFileName) { Q_D(ctkDICOMDatabase); d->resetLastInsertedValues(); // remove any existing schema info - this handles the case where an // old schema should be loaded for testing. QSqlQuery dropSchemaInfo(d->Database); d->loggedExec( dropSchemaInfo, QString("DROP TABLE IF EXISTS 'SchemaInfo';") ); return d->executeScript(sqlFileName); } //------------------------------------------------------------------------------ QString ctkDICOMDatabase::schemaVersionLoaded() { Q_D(ctkDICOMDatabase); /// look for the version info in the database QSqlQuery versionQuery(d->Database); if ( !d->loggedExec( versionQuery, QString("SELECT Version from SchemaInfo;") ) ) { return QString(""); } if (versionQuery.next()) { return versionQuery.value(0).toString(); } return QString(""); } //------------------------------------------------------------------------------ QString ctkDICOMDatabase::schemaVersion() { // When changing schema version: // * make sure this matches the Version value in the // SchemaInfo table defined in Resources/dicom-schema.sql // * make sure the 'Images' contains a 'Filename' column // so that the ctkDICOMDatabasePrivate::filenames method // still works. // return QString("0.5.3"); }; //------------------------------------------------------------------------------ bool ctkDICOMDatabase::updateSchemaIfNeeded(const char* schemaFile) { if ( schemaVersionLoaded() != schemaVersion() ) { return this->updateSchema(schemaFile); } else { emit schemaUpdateStarted(0); emit schemaUpdated(); return false; } } //------------------------------------------------------------------------------ bool ctkDICOMDatabase::updateSchema(const char* schemaFile) { // backup filelist // reinit with the new schema // reinsert everything Q_D(ctkDICOMDatabase); d->createBackupFileList(); d->resetLastInsertedValues(); this->initializeDatabase(schemaFile); QStringList allFiles = d->filenames("Filenames_backup"); emit schemaUpdateStarted(allFiles.length()); int progressValue = 0; foreach(QString file, allFiles) { emit schemaUpdateProgress(progressValue); emit schemaUpdateProgress(file); // TODO: use QFuture this->insert(file,false,false,true); progressValue++; } // TODO: check better that everything is ok d->removeBackupFileList(); emit schemaUpdated(); return true; } //------------------------------------------------------------------------------ void ctkDICOMDatabase::closeDatabase() { Q_D(ctkDICOMDatabase); d->Database.close(); d->TagCacheDatabase.close(); } // // Patient/study/series convenience methods // //------------------------------------------------------------------------------ QStringList ctkDICOMDatabase::patients() { Q_D(ctkDICOMDatabase); QSqlQuery query(d->Database); query.prepare ( "SELECT UID FROM Patients" ); query.exec(); QStringList result; while (query.next()) { result << query.value(0).toString(); } return( result ); } //------------------------------------------------------------------------------ QStringList ctkDICOMDatabase::studiesForPatient(QString dbPatientID) { Q_D(ctkDICOMDatabase); QSqlQuery query(d->Database); query.prepare ( "SELECT StudyInstanceUID FROM Studies WHERE PatientsUID = ?" ); query.bindValue ( 0, dbPatientID ); query.exec(); QStringList result; while (query.next()) { result << query.value(0).toString(); } return( result ); } //------------------------------------------------------------------------------ QString ctkDICOMDatabase::studyForSeries(QString seriesUID) { Q_D(ctkDICOMDatabase); QSqlQuery query(d->Database); query.prepare ( "SELECT StudyInstanceUID FROM Series WHERE SeriesInstanceUID= ?" ); query.bindValue ( 0, seriesUID); query.exec(); QString result; if (query.next()) { result = query.value(0).toString(); } return( result ); } //------------------------------------------------------------------------------ QString ctkDICOMDatabase::patientForStudy(QString studyUID) { Q_D(ctkDICOMDatabase); QSqlQuery query(d->Database); query.prepare ( "SELECT PatientsUID FROM Studies WHERE StudyInstanceUID= ?" ); query.bindValue ( 0, studyUID); query.exec(); QString result; if (query.next()) { result = query.value(0).toString(); } return( result ); } //------------------------------------------------------------------------------ QHash<QString,QString> ctkDICOMDatabase::descriptionsForFile(QString fileName) { Q_D(ctkDICOMDatabase); QString seriesUID(this->seriesForFile(fileName)); QString studyUID(this->studyForSeries(seriesUID)); QString patientID(this->patientForStudy(studyUID)); QSqlQuery query(d->Database); query.prepare ( "SELECT SeriesDescription FROM Series WHERE SeriesInstanceUID= ?" ); query.bindValue ( 0, seriesUID); query.exec(); QHash<QString,QString> result; if (query.next()) { result["SeriesDescription"] = query.value(0).toString(); } query.prepare ( "SELECT StudyDescription FROM Studies WHERE StudyInstanceUID= ?" ); query.bindValue ( 0, studyUID); query.exec(); if (query.next()) { result["StudyDescription"] = query.value(0).toString(); } query.prepare ( "SELECT PatientsName FROM Patients WHERE UID= ?" ); query.bindValue ( 0, patientID); query.exec(); if (query.next()) { result["PatientsName"] = query.value(0).toString(); } return( result ); } //------------------------------------------------------------------------------ QString ctkDICOMDatabase::descriptionForSeries(const QString seriesUID) { Q_D(ctkDICOMDatabase); QString result; QSqlQuery query(d->Database); query.prepare ( "SELECT SeriesDescription FROM Series WHERE SeriesInstanceUID= ?" ); query.bindValue ( 0, seriesUID); query.exec(); if (query.next()) { result = query.value(0).toString(); } return result; } //------------------------------------------------------------------------------ QString ctkDICOMDatabase::descriptionForStudy(const QString studyUID) { Q_D(ctkDICOMDatabase); QString result; QSqlQuery query(d->Database); query.prepare ( "SELECT StudyDescription FROM Studies WHERE StudyInstanceUID= ?" ); query.bindValue ( 0, studyUID); query.exec(); if (query.next()) { result = query.value(0).toString(); } return result; } //------------------------------------------------------------------------------ QString ctkDICOMDatabase::nameForPatient(const QString patientUID) { Q_D(ctkDICOMDatabase); QString result; QSqlQuery query(d->Database); query.prepare ( "SELECT PatientsName FROM Patients WHERE UID= ?" ); query.bindValue ( 0, patientUID); query.exec(); if (query.next()) { result = query.value(0).toString(); } return result; } //------------------------------------------------------------------------------ QStringList ctkDICOMDatabase::seriesForStudy(QString studyUID) { Q_D(ctkDICOMDatabase); QSqlQuery query(d->Database); query.prepare ( "SELECT SeriesInstanceUID FROM Series WHERE StudyInstanceUID=?"); query.bindValue ( 0, studyUID ); query.exec(); QStringList result; while (query.next()) { result << query.value(0).toString(); } return( result ); } //------------------------------------------------------------------------------ QStringList ctkDICOMDatabase::instancesForSeries(const QString seriesUID) { Q_D(ctkDICOMDatabase); QSqlQuery query(d->Database); query.prepare("SELECT SOPInstanceUID FROM Images WHERE SeriesInstanceUID= ?"); query.bindValue(0, seriesUID); query.exec(); QStringList result; if (query.next()) { result << query.value(0).toString(); } return result; } //------------------------------------------------------------------------------ QStringList ctkDICOMDatabase::filesForSeries(QString seriesUID) { Q_D(ctkDICOMDatabase); QSqlQuery query(d->Database); query.prepare ( "SELECT Filename FROM Images WHERE SeriesInstanceUID=?"); query.bindValue ( 0, seriesUID ); query.exec(); QStringList result; while (query.next()) { result << query.value(0).toString(); } return( result ); } //------------------------------------------------------------------------------ QString ctkDICOMDatabase::fileForInstance(QString sopInstanceUID) { Q_D(ctkDICOMDatabase); QSqlQuery query(d->Database); query.prepare ( "SELECT Filename FROM Images WHERE SOPInstanceUID=?"); query.bindValue ( 0, sopInstanceUID ); query.exec(); QString result; if (query.next()) { result = query.value(0).toString(); } return( result ); } //------------------------------------------------------------------------------ QString ctkDICOMDatabase::seriesForFile(QString fileName) { Q_D(ctkDICOMDatabase); QSqlQuery query(d->Database); query.prepare ( "SELECT SeriesInstanceUID FROM Images WHERE Filename=?"); query.bindValue ( 0, fileName ); query.exec(); QString result; if (query.next()) { result = query.value(0).toString(); } return( result ); } //------------------------------------------------------------------------------ QString ctkDICOMDatabase::instanceForFile(QString fileName) { Q_D(ctkDICOMDatabase); QSqlQuery query(d->Database); query.prepare ( "SELECT SOPInstanceUID FROM Images WHERE Filename=?"); query.bindValue ( 0, fileName ); query.exec(); QString result; if (query.next()) { result = query.value(0).toString(); } return( result ); } //------------------------------------------------------------------------------ QDateTime ctkDICOMDatabase::insertDateTimeForInstance(QString sopInstanceUID) { Q_D(ctkDICOMDatabase); QSqlQuery query(d->Database); query.prepare ( "SELECT InsertTimestamp FROM Images WHERE SOPInstanceUID=?"); query.bindValue ( 0, sopInstanceUID ); query.exec(); QDateTime result; if (query.next()) { result = QDateTime::fromString(query.value(0).toString(), Qt::ISODate); } return( result ); } // // instance header methods // //------------------------------------------------------------------------------ QStringList ctkDICOMDatabase::allFiles() { Q_D(ctkDICOMDatabase); return d->filenames("Images"); } //------------------------------------------------------------------------------ void ctkDICOMDatabase::loadInstanceHeader (QString sopInstanceUID) { Q_D(ctkDICOMDatabase); QSqlQuery query(d->Database); query.prepare ( "SELECT Filename FROM Images WHERE SOPInstanceUID=?"); query.bindValue ( 0, sopInstanceUID ); query.exec(); if (query.next()) { QString fileName = query.value(0).toString(); this->loadFileHeader(fileName); } return; } //------------------------------------------------------------------------------ void ctkDICOMDatabase::loadFileHeader (QString fileName) { Q_D(ctkDICOMDatabase); d->LoadedHeader.clear(); DcmFileFormat fileFormat; OFCondition status = fileFormat.loadFile(fileName.toLatin1().data()); if (status.good()) { DcmDataset *dataset = fileFormat.getDataset(); DcmStack stack; while (dataset->nextObject(stack, true) == EC_Normal) { DcmObject *dO = stack.top(); if (dO) { QString tag = QString("%1,%2").arg( dO->getGTag(),4,16,QLatin1Char('0')).arg( dO->getETag(),4,16,QLatin1Char('0')); std::ostringstream s; dO->print(s); d->LoadedHeader[tag] = QString(s.str().c_str()); } } } return; } //------------------------------------------------------------------------------ QStringList ctkDICOMDatabase::headerKeys () { Q_D(ctkDICOMDatabase); return (d->LoadedHeader.keys()); } //------------------------------------------------------------------------------ QString ctkDICOMDatabase::headerValue (QString key) { Q_D(ctkDICOMDatabase); return (d->LoadedHeader[key]); } // // instanceValue and fileValue methods // //------------------------------------------------------------------------------ QString ctkDICOMDatabase::instanceValue(QString sopInstanceUID, QString tag) { QString value = this->cachedTag(sopInstanceUID, tag); if (value == TagNotInInstance || value == ValueIsEmptyString) { return ""; } if (value != "") { return value; } unsigned short group, element; this->tagToGroupElement(tag, group, element); return( this->instanceValue(sopInstanceUID, group, element) ); } //------------------------------------------------------------------------------ QString ctkDICOMDatabase::instanceValue(const QString sopInstanceUID, const unsigned short group, const unsigned short element) { QString tag = this->groupElementToTag(group,element); QString value = this->cachedTag(sopInstanceUID, tag); if (value == TagNotInInstance || value == ValueIsEmptyString) { return ""; } if (value != "") { return value; } QString filePath = this->fileForInstance(sopInstanceUID); if (filePath != "" ) { value = this->fileValue(filePath, group, element); return( value ); } else { return (""); } } //------------------------------------------------------------------------------ QString ctkDICOMDatabase::fileValue(const QString fileName, QString tag) { unsigned short group, element; this->tagToGroupElement(tag, group, element); QString sopInstanceUID = this->instanceForFile(fileName); QString value = this->cachedTag(sopInstanceUID, tag); if (value == TagNotInInstance || value == ValueIsEmptyString) { return ""; } if (value != "") { return value; } return( this->fileValue(fileName, group, element) ); } //------------------------------------------------------------------------------ QString ctkDICOMDatabase::fileValue(const QString fileName, const unsigned short group, const unsigned short element) { // here is where the real lookup happens // - first we check the tagCache to see if the value exists for this instance tag // If not, // - for now we create a ctkDICOMItem and extract the value from there // - then we convert to the appropriate type of string // //As an optimization we could consider // - check if we are currently looking at the dataset for this fileName // - if so, are we looking for a group/element that is past the last one // accessed // -- if so, keep looking for the requested group/element // -- if not, start again from the begining QString tag = this->groupElementToTag(group, element); QString sopInstanceUID = this->instanceForFile(fileName); QString value = this->cachedTag(sopInstanceUID, tag); if (value == TagNotInInstance || value == ValueIsEmptyString) { return ""; } if (value != "") { return value; } ctkDICOMItem dataset; dataset.InitializeFromFile(fileName); if (dataset.IsInitialized()) { DcmTagKey tagKey(group, element); value = dataset.GetAllElementValuesAsString(tagKey); } else { value = TagNotInInstance; } this->cacheTag(sopInstanceUID, tag, value); return value; } //------------------------------------------------------------------------------ bool ctkDICOMDatabase::tagToGroupElement(const QString tag, unsigned short& group, unsigned short& element) { QStringList groupElement = tag.split(","); bool groupOK, elementOK; if (groupElement.length() != 2) { return false; } group = groupElement[0].toUInt(&groupOK, 16); element = groupElement[1].toUInt(&elementOK, 16); return( groupOK && elementOK ); } //------------------------------------------------------------------------------ QString ctkDICOMDatabase::groupElementToTag(const unsigned short& group, const unsigned short& element) { return QString("%1,%2").arg(group,4,16,QLatin1Char('0')).arg(element,4,16,QLatin1Char('0')); } // // methods related to insert // //------------------------------------------------------------------------------ void ctkDICOMDatabase::insert( DcmItem *item, bool storeFile, bool generateThumbnail) { if (!item) { return; } ctkDICOMItem ctkDataset; ctkDataset.InitializeFromItem(item, false /* do not take ownership */); this->insert(ctkDataset,storeFile,generateThumbnail); } void ctkDICOMDatabase::insert( const ctkDICOMItem& ctkDataset, bool storeFile, bool generateThumbnail) { Q_D(ctkDICOMDatabase); d->insert(ctkDataset, QString(), storeFile, generateThumbnail); } //------------------------------------------------------------------------------ void ctkDICOMDatabase::insert ( const QString& filePath, bool storeFile, bool generateThumbnail, bool createHierarchy, const QString& destinationDirectoryName) { Q_D(ctkDICOMDatabase); Q_UNUSED(createHierarchy); Q_UNUSED(destinationDirectoryName); /// first we check if the file is already in the database if (fileExistsAndUpToDate(filePath)) { logger.debug( "File " + filePath + " already added."); return; } logger.debug( "Processing " + filePath ); std::string filename = filePath.toStdString(); DcmFileFormat fileformat; ctkDICOMItem ctkDataset; ctkDataset.InitializeFromFile(filePath); if ( ctkDataset.IsInitialized() ) { d->insert( ctkDataset, filePath, storeFile, generateThumbnail ); } else { logger.warn(QString("Could not read DICOM file:") + filePath); } } //------------------------------------------------------------------------------ int ctkDICOMDatabasePrivate::insertPatient(const ctkDICOMItem& ctkDataset) { int dbPatientID; // Check if patient is already present in the db // TODO: maybe add birthdate check for extra safety QString patientID(ctkDataset.GetElementAsString(DCM_PatientID) ); QString patientsName(ctkDataset.GetElementAsString(DCM_PatientName) ); QString patientsBirthDate(ctkDataset.GetElementAsString(DCM_PatientBirthDate) ); QSqlQuery checkPatientExistsQuery(Database); checkPatientExistsQuery.prepare ( "SELECT * FROM Patients WHERE PatientID = ? AND PatientsName = ?" ); checkPatientExistsQuery.bindValue ( 0, patientID ); checkPatientExistsQuery.bindValue ( 1, patientsName ); loggedExec(checkPatientExistsQuery); if (checkPatientExistsQuery.next()) { // we found him dbPatientID = checkPatientExistsQuery.value(checkPatientExistsQuery.record().indexOf("UID")).toInt(); qDebug() << "Found patient in the database as UId: " << dbPatientID; } else { // Insert it QString patientsBirthTime(ctkDataset.GetElementAsString(DCM_PatientBirthTime) ); QString patientsSex(ctkDataset.GetElementAsString(DCM_PatientSex) ); QString patientsAge(ctkDataset.GetElementAsString(DCM_PatientAge) ); QString patientComments(ctkDataset.GetElementAsString(DCM_PatientComments) ); QSqlQuery insertPatientStatement ( Database ); insertPatientStatement.prepare ( "INSERT INTO Patients ('UID', 'PatientsName', 'PatientID', 'PatientsBirthDate', 'PatientsBirthTime', 'PatientsSex', 'PatientsAge', 'PatientsComments' ) values ( NULL, ?, ?, ?, ?, ?, ?, ? )" ); insertPatientStatement.bindValue ( 0, patientsName ); insertPatientStatement.bindValue ( 1, patientID ); insertPatientStatement.bindValue ( 2, QDate::fromString ( patientsBirthDate, "yyyyMMdd" ) ); insertPatientStatement.bindValue ( 3, patientsBirthTime ); insertPatientStatement.bindValue ( 4, patientsSex ); // TODO: shift patient's age to study, // since this is not a patient level attribute in images // insertPatientStatement.bindValue ( 5, patientsAge ); insertPatientStatement.bindValue ( 6, patientComments ); loggedExec(insertPatientStatement); dbPatientID = insertPatientStatement.lastInsertId().toInt(); logger.debug ( "New patient inserted: " + QString().setNum ( dbPatientID ) ); qDebug() << "New patient inserted as : " << dbPatientID; } return dbPatientID; } //------------------------------------------------------------------------------ void ctkDICOMDatabasePrivate::insertStudy(const ctkDICOMItem& ctkDataset, int dbPatientID) { QString studyInstanceUID(ctkDataset.GetElementAsString(DCM_StudyInstanceUID) ); QSqlQuery checkStudyExistsQuery (Database); checkStudyExistsQuery.prepare ( "SELECT * FROM Studies WHERE StudyInstanceUID = ?" ); checkStudyExistsQuery.bindValue ( 0, studyInstanceUID ); checkStudyExistsQuery.exec(); if(!checkStudyExistsQuery.next()) { qDebug() << "Need to insert new study: " << studyInstanceUID; QString studyID(ctkDataset.GetElementAsString(DCM_StudyID) ); QString studyDate(ctkDataset.GetElementAsString(DCM_StudyDate) ); QString studyTime(ctkDataset.GetElementAsString(DCM_StudyTime) ); QString accessionNumber(ctkDataset.GetElementAsString(DCM_AccessionNumber) ); QString modalitiesInStudy(ctkDataset.GetElementAsString(DCM_ModalitiesInStudy) ); QString institutionName(ctkDataset.GetElementAsString(DCM_InstitutionName) ); QString performingPhysiciansName(ctkDataset.GetElementAsString(DCM_PerformingPhysicianName) ); QString referringPhysician(ctkDataset.GetElementAsString(DCM_ReferringPhysicianName) ); QString studyDescription(ctkDataset.GetElementAsString(DCM_StudyDescription) ); QSqlQuery insertStudyStatement ( Database ); insertStudyStatement.prepare ( "INSERT INTO Studies ( 'StudyInstanceUID', 'PatientsUID', 'StudyID', 'StudyDate', 'StudyTime', 'AccessionNumber', 'ModalitiesInStudy', 'InstitutionName', 'ReferringPhysician', 'PerformingPhysiciansName', 'StudyDescription' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" ); insertStudyStatement.bindValue ( 0, studyInstanceUID ); insertStudyStatement.bindValue ( 1, dbPatientID ); insertStudyStatement.bindValue ( 2, studyID ); insertStudyStatement.bindValue ( 3, QDate::fromString ( studyDate, "yyyyMMdd" ) ); insertStudyStatement.bindValue ( 4, studyTime ); insertStudyStatement.bindValue ( 5, accessionNumber ); insertStudyStatement.bindValue ( 6, modalitiesInStudy ); insertStudyStatement.bindValue ( 7, institutionName ); insertStudyStatement.bindValue ( 8, referringPhysician ); insertStudyStatement.bindValue ( 9, performingPhysiciansName ); insertStudyStatement.bindValue ( 10, studyDescription ); if ( !insertStudyStatement.exec() ) { logger.error ( "Error executing statament: " + insertStudyStatement.lastQuery() + " Error: " + insertStudyStatement.lastError().text() ); } else { LastStudyInstanceUID = studyInstanceUID; } } else { qDebug() << "Used existing study: " << studyInstanceUID; } } //------------------------------------------------------------------------------ void ctkDICOMDatabasePrivate::insertSeries(const ctkDICOMItem& ctkDataset, QString studyInstanceUID) { QString seriesInstanceUID(ctkDataset.GetElementAsString(DCM_SeriesInstanceUID) ); QSqlQuery checkSeriesExistsQuery (Database); checkSeriesExistsQuery.prepare ( "SELECT * FROM Series WHERE SeriesInstanceUID = ?" ); checkSeriesExistsQuery.bindValue ( 0, seriesInstanceUID ); logger.warn ( "Statement: " + checkSeriesExistsQuery.lastQuery() ); checkSeriesExistsQuery.exec(); if(!checkSeriesExistsQuery.next()) { qDebug() << "Need to insert new series: " << seriesInstanceUID; QString seriesDate(ctkDataset.GetElementAsString(DCM_SeriesDate) ); QString seriesTime(ctkDataset.GetElementAsString(DCM_SeriesTime) ); QString seriesDescription(ctkDataset.GetElementAsString(DCM_SeriesDescription) ); QString modality(ctkDataset.GetElementAsString(DCM_Modality) ); QString bodyPartExamined(ctkDataset.GetElementAsString(DCM_BodyPartExamined) ); QString frameOfReferenceUID(ctkDataset.GetElementAsString(DCM_FrameOfReferenceUID) ); QString contrastAgent(ctkDataset.GetElementAsString(DCM_ContrastBolusAgent) ); QString scanningSequence(ctkDataset.GetElementAsString(DCM_ScanningSequence) ); long seriesNumber(ctkDataset.GetElementAsInteger(DCM_SeriesNumber) ); long acquisitionNumber(ctkDataset.GetElementAsInteger(DCM_AcquisitionNumber) ); long echoNumber(ctkDataset.GetElementAsInteger(DCM_EchoNumbers) ); long temporalPosition(ctkDataset.GetElementAsInteger(DCM_TemporalPositionIdentifier) ); QSqlQuery insertSeriesStatement ( Database ); insertSeriesStatement.prepare ( "INSERT INTO Series ( 'SeriesInstanceUID', 'StudyInstanceUID', 'SeriesNumber', 'SeriesDate', 'SeriesTime', 'SeriesDescription', 'Modality', 'BodyPartExamined', 'FrameOfReferenceUID', 'AcquisitionNumber', 'ContrastAgent', 'ScanningSequence', 'EchoNumber', 'TemporalPosition' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" ); insertSeriesStatement.bindValue ( 0, seriesInstanceUID ); insertSeriesStatement.bindValue ( 1, studyInstanceUID ); insertSeriesStatement.bindValue ( 2, static_cast<int>(seriesNumber) ); insertSeriesStatement.bindValue ( 3, QDate::fromString ( seriesDate, "yyyyMMdd" ) ); insertSeriesStatement.bindValue ( 4, seriesTime ); insertSeriesStatement.bindValue ( 5, seriesDescription ); insertSeriesStatement.bindValue ( 6, modality ); insertSeriesStatement.bindValue ( 7, bodyPartExamined ); insertSeriesStatement.bindValue ( 8, frameOfReferenceUID ); insertSeriesStatement.bindValue ( 9, static_cast<int>(acquisitionNumber) ); insertSeriesStatement.bindValue ( 10, contrastAgent ); insertSeriesStatement.bindValue ( 11, scanningSequence ); insertSeriesStatement.bindValue ( 12, static_cast<int>(echoNumber) ); insertSeriesStatement.bindValue ( 13, static_cast<int>(temporalPosition) ); if ( !insertSeriesStatement.exec() ) { logger.error ( "Error executing statament: " + insertSeriesStatement.lastQuery() + " Error: " + insertSeriesStatement.lastError().text() ); LastSeriesInstanceUID = ""; } else { LastSeriesInstanceUID = seriesInstanceUID; } } else { qDebug() << "Used existing series: " << seriesInstanceUID; } } //------------------------------------------------------------------------------ void ctkDICOMDatabase::setTagsToPrecache( const QStringList tags) { Q_D(ctkDICOMDatabase); d->TagsToPrecache = tags; } //------------------------------------------------------------------------------ const QStringList ctkDICOMDatabase::tagsToPrecache() { Q_D(ctkDICOMDatabase); return d->TagsToPrecache; } //------------------------------------------------------------------------------ void ctkDICOMDatabasePrivate::precacheTags( const QString sopInstanceUID ) { Q_Q(ctkDICOMDatabase); ctkDICOMItem dataset; QString fileName = q->fileForInstance(sopInstanceUID); dataset.InitializeFromFile(fileName); QStringList sopInstanceUIDs, tags, values; foreach (const QString &tag, this->TagsToPrecache) { unsigned short group, element; q->tagToGroupElement(tag, group, element); DcmTagKey tagKey(group, element); QString value = dataset.GetAllElementValuesAsString(tagKey); sopInstanceUIDs << sopInstanceUID; tags << tag; values << value; } this->beginTransaction(); q->cacheTags(sopInstanceUIDs, tags, values); this->endTransaction(); } //------------------------------------------------------------------------------ void ctkDICOMDatabasePrivate::insert( const ctkDICOMItem& ctkDataset, const QString& filePath, bool storeFile, bool generateThumbnail) { Q_Q(ctkDICOMDatabase); // this is the method that all other insert signatures end up calling // after they have pre-parsed their arguments // Check to see if the file has already been loaded // TODO: // It could make sense to actually remove the dataset and re-add it. This needs the remove // method we still have to write. // // QString sopInstanceUID ( ctkDataset.GetElementAsString(DCM_SOPInstanceUID) ); QSqlQuery fileExistsQuery ( Database ); fileExistsQuery.prepare("SELECT InsertTimestamp,Filename FROM Images WHERE SOPInstanceUID == :sopInstanceUID"); fileExistsQuery.bindValue(":sopInstanceUID",sopInstanceUID); { bool success = fileExistsQuery.exec(); if (!success) { logger.error("SQLITE ERROR: " + fileExistsQuery.lastError().driverText()); return; } fileExistsQuery.next(); QString databaseFilename(fileExistsQuery.value(1).toString()); QDateTime fileLastModified(QFileInfo(databaseFilename).lastModified()); QDateTime databaseInsertTimestamp(QDateTime::fromString(fileExistsQuery.value(0).toString(),Qt::ISODate)); qDebug() << "inserting filePath: " << filePath; if (databaseFilename == "") { qDebug() << "database filename for " << sopInstanceUID << " is empty - we should insert on top of it"; } else { if ( databaseFilename == filePath && fileLastModified < databaseInsertTimestamp ) { logger.debug ( "File " + databaseFilename + " already added" ); return; } else { QSqlQuery deleteFile ( Database ); deleteFile.prepare("DELETE FROM Images WHERE SOPInstanceUID == :sopInstanceUID"); deleteFile.bindValue(":sopInstanceUID",sopInstanceUID); bool success = deleteFile.exec(); if (!success) { logger.error("SQLITE ERROR deleting old image row: " + deleteFile.lastError().driverText()); return; } } } } //If the following fields can not be evaluated, cancel evaluation of the DICOM file QString patientsName(ctkDataset.GetElementAsString(DCM_PatientName) ); QString studyInstanceUID(ctkDataset.GetElementAsString(DCM_StudyInstanceUID) ); QString seriesInstanceUID(ctkDataset.GetElementAsString(DCM_SeriesInstanceUID) ); QString patientID(ctkDataset.GetElementAsString(DCM_PatientID) ); if ( patientID.isEmpty() && !studyInstanceUID.isEmpty() ) { // Use study instance uid as patient id if patient id is empty - can happen on anonymized datasets // see: http://www.na-mic.org/Bug/view.php?id=2040 logger.warn("Patient ID is empty, using studyInstanceUID as patient ID"); patientID = studyInstanceUID; } if ( patientsName.isEmpty() && !patientID.isEmpty() ) { // Use patient id as name if name is empty - can happen on anonymized datasets // see: http://www.na-mic.org/Bug/view.php?id=1643 patientsName = patientID; } if ( patientsName.isEmpty() || studyInstanceUID.isEmpty() || patientID.isEmpty() ) { logger.error("Dataset is missing necessary information (patient name, study instance UID, or patient ID)!"); return; } // store the file if the database is not in memomry // TODO: if we are called from insert(file) we // have to do something else // QString filename = filePath; if ( storeFile && !q->isInMemory() && !seriesInstanceUID.isEmpty() ) { // QString studySeriesDirectory = studyInstanceUID + "/" + seriesInstanceUID; QString destinationDirectoryName = q->databaseDirectory() + "/dicom/"; QDir destinationDir(destinationDirectoryName); filename = destinationDirectoryName + studyInstanceUID + "/" + seriesInstanceUID + "/" + sopInstanceUID; destinationDir.mkpath(studyInstanceUID + "/" + seriesInstanceUID); if(filePath.isEmpty()) { logger.debug ( "Saving file: " + filename ); if ( !ctkDataset.SaveToFile( filename) ) { logger.error ( "Error saving file: " + filename ); return; } } else { // we're inserting an existing file QFile currentFile( filePath ); currentFile.copy(filename); logger.debug( "Copy file from: " + filePath ); logger.debug( "Copy file to : " + filename ); } } //The dbPatientID is a unique number within the database, //generated by the sqlite autoincrement //The patientID is the (non-unique) DICOM patient id int dbPatientID = LastPatientUID; if ( patientID != "" && patientsName != "" ) { //Speed up: Check if patient is the same as in last file; // very probable, as all images belonging to a study have the same patient QString patientsBirthDate(ctkDataset.GetElementAsString(DCM_PatientBirthDate) ); if ( LastPatientID != patientID || LastPatientsBirthDate != patientsBirthDate || LastPatientsName != patientsName ) { QString seriesInstanceUID(ctkDataset.GetElementAsString(DCM_SeriesInstanceUID) ); qDebug() << "This looks like a different patient from last insert: " << patientID; // Ok, something is different from last insert, let's insert him if he's not // already in the db. dbPatientID = insertPatient( ctkDataset ); // let users of this class track when things happen emit q->patientAdded(dbPatientID, patientID, patientsName, patientsBirthDate); /// keep this for the next image LastPatientUID = dbPatientID; LastPatientID = patientID; LastPatientsBirthDate = patientsBirthDate; LastPatientsName = patientsName; } qDebug() << "Going to insert this instance with dbPatientID: " << dbPatientID; // Patient is in now. Let's continue with the study if ( studyInstanceUID != "" && LastStudyInstanceUID != studyInstanceUID ) { insertStudy(ctkDataset,dbPatientID); // let users of this class track when things happen emit q->studyAdded(studyInstanceUID); qDebug() << "Study Added"; } if ( seriesInstanceUID != "" && seriesInstanceUID != LastSeriesInstanceUID ) { insertSeries(ctkDataset, studyInstanceUID); // let users of this class track when things happen emit q->seriesAdded(seriesInstanceUID); qDebug() << "Series Added"; } // TODO: what to do with imported files // if ( !filename.isEmpty() && !seriesInstanceUID.isEmpty() ) { QSqlQuery checkImageExistsQuery (Database); checkImageExistsQuery.prepare ( "SELECT * FROM Images WHERE Filename = ?" ); checkImageExistsQuery.bindValue ( 0, filename ); checkImageExistsQuery.exec(); qDebug() << "Maybe add Instance"; if(!checkImageExistsQuery.next()) { QSqlQuery insertImageStatement ( Database ); insertImageStatement.prepare ( "INSERT INTO Images ( 'SOPInstanceUID', 'Filename', 'SeriesInstanceUID', 'InsertTimestamp' ) VALUES ( ?, ?, ?, ? )" ); insertImageStatement.bindValue ( 0, sopInstanceUID ); insertImageStatement.bindValue ( 1, filename ); insertImageStatement.bindValue ( 2, seriesInstanceUID ); insertImageStatement.bindValue ( 3, QDateTime::currentDateTime() ); insertImageStatement.exec(); // insert was needed, so cache any application-requested tags this->precacheTags(sopInstanceUID); // let users of this class track when things happen emit q->instanceAdded(sopInstanceUID); qDebug() << "Instance Added"; } } if( generateThumbnail && thumbnailGenerator && !seriesInstanceUID.isEmpty() ) { QString studySeriesDirectory = studyInstanceUID + "/" + seriesInstanceUID; //Create thumbnail here QString thumbnailPath = q->databaseDirectory() + "/thumbs/" + studyInstanceUID + "/" + seriesInstanceUID + "/" + sopInstanceUID + ".png"; QFileInfo thumbnailInfo(thumbnailPath); if( !(thumbnailInfo.exists() && (thumbnailInfo.lastModified() > QFileInfo(filename).lastModified()))) { QDir(q->databaseDirectory() + "/thumbs/").mkpath(studySeriesDirectory); DicomImage dcmImage(QDir::toNativeSeparators(filename).toLatin1()); thumbnailGenerator->generateThumbnail(&dcmImage, thumbnailPath); } } if (q->isInMemory()) { emit q->databaseChanged(); } } else { qDebug() << "No patient name or no patient id - not inserting!"; } } //------------------------------------------------------------------------------ bool ctkDICOMDatabase::fileExistsAndUpToDate(const QString& filePath) { Q_D(ctkDICOMDatabase); bool result(false); QSqlQuery check_filename_query(database()); check_filename_query.prepare("SELECT InsertTimestamp FROM Images WHERE Filename == ?"); check_filename_query.bindValue(0,filePath); d->loggedExec(check_filename_query); if ( check_filename_query.next() && QFileInfo(filePath).lastModified() < QDateTime::fromString(check_filename_query.value(0).toString(),Qt::ISODate) ) { result = true; } check_filename_query.finish(); return result; } //------------------------------------------------------------------------------ bool ctkDICOMDatabase::isOpen() const { Q_D(const ctkDICOMDatabase); return d->Database.isOpen(); } //------------------------------------------------------------------------------ bool ctkDICOMDatabase::isInMemory() const { Q_D(const ctkDICOMDatabase); return d->DatabaseFileName == ":memory:"; } //------------------------------------------------------------------------------ bool ctkDICOMDatabase::removeSeries(const QString& seriesInstanceUID) { Q_D(ctkDICOMDatabase); // get all images from series QSqlQuery fileExistsQuery ( d->Database ); fileExistsQuery.prepare("SELECT Filename, SOPInstanceUID, StudyInstanceUID FROM Images,Series WHERE Series.SeriesInstanceUID = Images.SeriesInstanceUID AND Images.SeriesInstanceUID = :seriesID"); fileExistsQuery.bindValue(":seriesID",seriesInstanceUID); bool success = fileExistsQuery.exec(); if (!success) { logger.error("SQLITE ERROR: " + fileExistsQuery.lastError().driverText()); return false; } QList< QPair<QString,QString> > removeList; while ( fileExistsQuery.next() ) { QString dbFilePath = fileExistsQuery.value(fileExistsQuery.record().indexOf("Filename")).toString(); QString sopInstanceUID = fileExistsQuery.value(fileExistsQuery.record().indexOf("SOPInstanceUID")).toString(); QString studyInstanceUID = fileExistsQuery.value(fileExistsQuery.record().indexOf("StudyInstanceUID")).toString(); QString internalFilePath = studyInstanceUID + "/" + seriesInstanceUID + "/" + sopInstanceUID; removeList << qMakePair(dbFilePath,internalFilePath); } QSqlQuery fileRemove ( d->Database ); fileRemove.prepare("DELETE FROM Images WHERE SeriesInstanceUID == :seriesID"); fileRemove.bindValue(":seriesID",seriesInstanceUID); logger.debug("SQLITE: removing seriesInstanceUID " + seriesInstanceUID); success = fileRemove.exec(); if (!success) { logger.error("SQLITE ERROR: could not remove seriesInstanceUID " + seriesInstanceUID); logger.error("SQLITE ERROR: " + fileRemove.lastError().driverText()); } QPair<QString,QString> fileToRemove; foreach (fileToRemove, removeList) { QString dbFilePath = fileToRemove.first; QString thumbnailToRemove = databaseDirectory() + "/thumbs/" + fileToRemove.second + ".png"; // check that the file is below our internal storage if (dbFilePath.startsWith( databaseDirectory() + "/dicom/")) { if (!dbFilePath.endsWith(fileToRemove.second)) { logger.error("Database inconsistency detected during delete!"); continue; } if (QFile( dbFilePath ).remove()) { logger.debug("Removed file " + dbFilePath ); } else { logger.warn("Failed to remove file " + dbFilePath ); } } if (QFile( thumbnailToRemove ).remove()) { logger.debug("Removed thumbnail " + thumbnailToRemove); } else { logger.warn("Failed to remove thumbnail " + thumbnailToRemove); } } this->cleanup(); d->resetLastInsertedValues(); return true; } //------------------------------------------------------------------------------ bool ctkDICOMDatabase::cleanup() { Q_D(ctkDICOMDatabase); QSqlQuery seriesCleanup ( d->Database ); seriesCleanup.exec("DELETE FROM Series WHERE ( SELECT COUNT(*) FROM Images WHERE Images.SeriesInstanceUID = Series.SeriesInstanceUID ) = 0;"); seriesCleanup.exec("DELETE FROM Studies WHERE ( SELECT COUNT(*) FROM Series WHERE Series.StudyInstanceUID = Studies.StudyInstanceUID ) = 0;"); seriesCleanup.exec("DELETE FROM Patients WHERE ( SELECT COUNT(*) FROM Studies WHERE Studies.PatientsUID = Patients.UID ) = 0;"); return true; } //------------------------------------------------------------------------------ bool ctkDICOMDatabase::removeStudy(const QString& studyInstanceUID) { Q_D(ctkDICOMDatabase); QSqlQuery seriesForStudy( d->Database ); seriesForStudy.prepare("SELECT SeriesInstanceUID FROM Series WHERE StudyInstanceUID = :studyID"); seriesForStudy.bindValue(":studyID", studyInstanceUID); bool success = seriesForStudy.exec(); if (!success) { logger.error("SQLITE ERROR: " + seriesForStudy.lastError().driverText()); return false; } bool result = true; while ( seriesForStudy.next() ) { QString seriesInstanceUID = seriesForStudy.value(seriesForStudy.record().indexOf("SeriesInstanceUID")).toString(); if ( ! this->removeSeries(seriesInstanceUID) ) { result = false; } } d->resetLastInsertedValues(); return result; } //------------------------------------------------------------------------------ bool ctkDICOMDatabase::removePatient(const QString& patientID) { Q_D(ctkDICOMDatabase); QSqlQuery studiesForPatient( d->Database ); studiesForPatient.prepare("SELECT StudyInstanceUID FROM Studies WHERE PatientsUID = :patientsID"); studiesForPatient.bindValue(":patientsID", patientID); bool success = studiesForPatient.exec(); if (!success) { logger.error("SQLITE ERROR: " + studiesForPatient.lastError().driverText()); return false; } bool result = true; while ( studiesForPatient.next() ) { QString studyInstanceUID = studiesForPatient.value(studiesForPatient.record().indexOf("StudyInstanceUID")).toString(); if ( ! this->removeStudy(studyInstanceUID) ) { result = false; } } d->resetLastInsertedValues(); return result; } /// /// Code related to the tagCache /// //------------------------------------------------------------------------------ bool ctkDICOMDatabase::tagCacheExists() { Q_D(ctkDICOMDatabase); if (d->TagCacheVerified) { return true; } // try to open the database if it's not already open if ( !(d->TagCacheDatabase.isOpen()) ) { d->TagCacheDatabase = QSqlDatabase::addDatabase("QSQLITE", d->Database.connectionName() + "TagCache"); d->TagCacheDatabase.setDatabaseName(d->TagCacheDatabaseFilename); if ( !(d->TagCacheDatabase.open()) ) { qDebug() << "TagCacheDatabase would not open!\n"; qDebug() << "TagCacheDatabaseFilename is: " << d->TagCacheDatabaseFilename << "\n"; return false; } //Disable synchronous writing to make modifications faster QSqlQuery pragmaSyncQuery(d->TagCacheDatabase); pragmaSyncQuery.exec("PRAGMA synchronous = OFF"); pragmaSyncQuery.finish(); } // check that the table exists QSqlQuery cacheExists( d->TagCacheDatabase ); cacheExists.prepare("SELECT * FROM TagCache LIMIT 1"); bool success = d->loggedExec(cacheExists); if (success) { d->TagCacheVerified = true; return true; } qDebug() << "TagCacheDatabase NOT verified based on table check!\n"; return false; } //------------------------------------------------------------------------------ bool ctkDICOMDatabase::initializeTagCache() { Q_D(ctkDICOMDatabase); // First, drop any existing table if ( this->tagCacheExists() ) { qDebug() << "TagCacheDatabase drop existing table\n"; QSqlQuery dropCacheTable( d->TagCacheDatabase ); dropCacheTable.prepare( "DROP TABLE TagCache" ); d->loggedExec(dropCacheTable); } // now create a table qDebug() << "TagCacheDatabase adding table\n"; QSqlQuery createCacheTable( d->TagCacheDatabase ); createCacheTable.prepare( "CREATE TABLE TagCache (SOPInstanceUID, Tag, Value, PRIMARY KEY (SOPInstanceUID, Tag))" ); bool success = d->loggedExec(createCacheTable); if (success) { d->TagCacheVerified = true; return true; } return false; } //------------------------------------------------------------------------------ QString ctkDICOMDatabase::cachedTag(const QString sopInstanceUID, const QString tag) { Q_D(ctkDICOMDatabase); if ( !this->tagCacheExists() ) { if ( !this->initializeTagCache() ) { return( "" ); } } QSqlQuery selectValue( d->TagCacheDatabase ); selectValue.prepare( "SELECT Value FROM TagCache WHERE SOPInstanceUID = :sopInstanceUID AND Tag = :tag" ); selectValue.bindValue(":sopInstanceUID",sopInstanceUID); selectValue.bindValue(":tag",tag); d->loggedExec(selectValue); QString result(""); if (selectValue.next()) { result = selectValue.value(0).toString(); if (result == QString("")) { result = ValueIsEmptyString; } } return( result ); } //------------------------------------------------------------------------------ bool ctkDICOMDatabase::cacheTag(const QString sopInstanceUID, const QString tag, const QString value) { QStringList sopInstanceUIDs, tags, values; sopInstanceUIDs << sopInstanceUID; tags << tag; values << value; return this->cacheTags(sopInstanceUIDs, tags, values); } //------------------------------------------------------------------------------ bool ctkDICOMDatabase::cacheTags(const QStringList sopInstanceUIDs, const QStringList tags, QStringList values) { Q_D(ctkDICOMDatabase); if ( !this->tagCacheExists() ) { if ( !this->initializeTagCache() ) { return false; } } // replace empty strings with special flag string QStringList::iterator i; for (i = values.begin(); i != values.end(); ++i) { if (*i == "") { *i = TagNotInInstance; } } QSqlQuery insertTags( d->TagCacheDatabase ); insertTags.prepare( "INSERT OR REPLACE INTO TagCache VALUES(?,?,?)" ); insertTags.addBindValue(sopInstanceUIDs); insertTags.addBindValue(tags); insertTags.addBindValue(values); return d->loggedExecBatch(insertTags); }
SECTION code_fp_math48 PUBLIC ___fs2sint_callee EXTERN cm48_sdccixp_ds2sint_callee defc ___fs2sint_callee = cm48_sdccixp_ds2sint_callee
.gba .create "out.bin",0 .area 0x8 .fill 0x8 .close .endarea .macro myopen,offset .open "out2.bin",offset .endmacro .area 0x8 myopen 4 .endarea .close
comment * Algo : GOST Block : 8 bytes Key : 32 bytes (256 b) push offset key ;password ptr, exactly 32 bytes readed as key !!! push offset plain ;data to encrypt ptr push offset encrypted_buf ;destination ptr call Gost_Crypt push offset key ;password ptr, exactly 32 bytes readed as key !!! push offset encrypted_buf ;data to decrypt ptr push offset plain ;destination ptr call Gost_Decrypt 14.11.2001 WiteG//xtreeme (witeg@poczta.fm, www.witeg.prv.pl) * gost_core macro mov ebx, ptrKey mov esi, eax add eax, dword ptr [ebx+ecx] mov ebx, offset sbox_1 xlatb add ebx, 256 ror eax, 8 xlatb add ebx, 256 ror eax, 8 xlatb add ebx, 256 ror eax, 8 xlatb add ebx, 256 rol eax, 3 xor eax, edx endm .code Gost_Crypt proc ptrOut:DWORD, ptrIn:DWORD, ptrKey:DWORD LOCAL counter:DWORD pushad mov esi, ptrIn mov edi, offset keypart mov edx, dword ptr [esi] mov eax, dword ptr [esi+4] xor ecx, ecx mov counter, 32 @@: mov cl, byte ptr [edi] gost_core ;eax, ebx, esi inc edi mov edx, esi dec counter jnz @B mov edi, ptrOut mov dword ptr [edi], edx mov dword ptr [edi+4], eax popad ret Gost_Crypt endp Gost_Decrypt proc ptrOut:DWORD, ptrIn:DWORD, ptrKey:DWORD LOCAL counter:DWORD pushad mov esi, ptrIn mov edi, offset keypart+31 mov eax, dword ptr [esi] mov edx, dword ptr [esi+4] xor ecx, ecx mov counter, 32 @@: mov cl, byte ptr [edi] gost_core ;eax, ebx, esi dec edi mov edx, esi dec counter jnz @B mov edi, ptrOut mov dword ptr [edi], eax mov dword ptr [edi+4], edx popad ret Gost_Decrypt endp .data ;S-boxes from Applied Cryptography 2nd Edition, p. 331-333 keypart db 0,4,8,12,16,20,24,28,0,4,8,12,16,20,24,28,0,4,8,12,16,20,24,28,28,24,20,16,12,8,4,0 sbox_1 db 0E4h, 0EAh, 0E9h, 0E2h, 0EDh, 0E8h, 0E0h, 0EEh, 0E6h, 0EBh, 0E1h, 0ECh, 0E7h, 0EFh, 0E5h, 0E3h db 0B4h, 0BAh, 0B9h, 0B2h, 0BDh, 0B8h, 0B0h, 0BEh, 0B6h, 0BBh, 0B1h, 0BCh, 0B7h, 0BFh, 0B5h, 0B3h db 044h, 04Ah, 049h, 042h, 04Dh, 048h, 040h, 04Eh, 046h, 04Bh, 041h, 04Ch, 047h, 04Fh, 045h, 043h db 0C4h, 0CAh, 0C9h, 0C2h, 0CDh, 0C8h, 0C0h, 0CEh, 0C6h, 0CBh, 0C1h, 0CCh, 0C7h, 0CFh, 0C5h, 0C3h db 064h, 06Ah, 069h, 062h, 06Dh, 068h, 060h, 06Eh, 066h, 06Bh, 061h, 06Ch, 067h, 06Fh, 065h, 063h db 0D4h, 0DAh, 0D9h, 0D2h, 0DDh, 0D8h, 0D0h, 0DEh, 0D6h, 0DBh, 0D1h, 0DCh, 0D7h, 0DFh, 0D5h, 0D3h db 0F4h, 0FAh, 0F9h, 0F2h, 0FDh, 0F8h, 0F0h, 0FEh, 0F6h, 0FBh, 0F1h, 0FCh, 0F7h, 0FFh, 0F5h, 0F3h db 0A4h, 0AAh, 0A9h, 0A2h, 0ADh, 0A8h, 0A0h, 0AEh, 0A6h, 0ABh, 0A1h, 0ACh, 0A7h, 0AFh, 0A5h, 0A3h db 024h, 02Ah, 029h, 022h, 02Dh, 028h, 020h, 02Eh, 026h, 02Bh, 021h, 02Ch, 027h, 02Fh, 025h, 023h db 034h, 03Ah, 039h, 032h, 03Dh, 038h, 030h, 03Eh, 036h, 03Bh, 031h, 03Ch, 037h, 03Fh, 035h, 033h db 084h, 08Ah, 089h, 082h, 08Dh, 088h, 080h, 08Eh, 086h, 08Bh, 081h, 08Ch, 087h, 08Fh, 085h, 083h db 014h, 01Ah, 019h, 012h, 01Dh, 018h, 010h, 01Eh, 016h, 01Bh, 011h, 01Ch, 017h, 01Fh, 015h, 013h db 004h, 00Ah, 009h, 002h, 00Dh, 008h, 000h, 00Eh, 006h, 00Bh, 001h, 00Ch, 007h, 00Fh, 005h, 003h db 074h, 07Ah, 079h, 072h, 07Dh, 078h, 070h, 07Eh, 076h, 07Bh, 071h, 07Ch, 077h, 07Fh, 075h, 073h db 054h, 05Ah, 059h, 052h, 05Dh, 058h, 050h, 05Eh, 056h, 05Bh, 051h, 05Ch, 057h, 05Fh, 055h, 053h db 094h, 09Ah, 099h, 092h, 09Dh, 098h, 090h, 09Eh, 096h, 09Bh, 091h, 09Ch, 097h, 09Fh, 095h, 093h sbox_2 db 075h, 078h, 071h, 07Dh, 07Ah, 073h, 074h, 072h, 07Eh, 07Fh, 07Ch, 077h, 076h, 070h, 079h, 07Bh db 0D5h, 0D8h, 0D1h, 0DDh, 0DAh, 0D3h, 0D4h, 0D2h, 0DEh, 0DFh, 0DCh, 0D7h, 0D6h, 0D0h, 0D9h, 0DBh db 0A5h, 0A8h, 0A1h, 0ADh, 0AAh, 0A3h, 0A4h, 0A2h, 0AEh, 0AFh, 0ACh, 0A7h, 0A6h, 0A0h, 0A9h, 0ABh db 015h, 018h, 011h, 01Dh, 01Ah, 013h, 014h, 012h, 01Eh, 01Fh, 01Ch, 017h, 016h, 010h, 019h, 01Bh db 005h, 008h, 001h, 00Dh, 00Ah, 003h, 004h, 002h, 00Eh, 00Fh, 00Ch, 007h, 006h, 000h, 009h, 00Bh db 085h, 088h, 081h, 08Dh, 08Ah, 083h, 084h, 082h, 08Eh, 08Fh, 08Ch, 087h, 086h, 080h, 089h, 08Bh db 095h, 098h, 091h, 09Dh, 09Ah, 093h, 094h, 092h, 09Eh, 09Fh, 09Ch, 097h, 096h, 090h, 099h, 09Bh db 0F5h, 0F8h, 0F1h, 0FDh, 0FAh, 0F3h, 0F4h, 0F2h, 0FEh, 0FFh, 0FCh, 0F7h, 0F6h, 0F0h, 0F9h, 0FBh db 0E5h, 0E8h, 0E1h, 0EDh, 0EAh, 0E3h, 0E4h, 0E2h, 0EEh, 0EFh, 0ECh, 0E7h, 0E6h, 0E0h, 0E9h, 0EBh db 045h, 048h, 041h, 04Dh, 04Ah, 043h, 044h, 042h, 04Eh, 04Fh, 04Ch, 047h, 046h, 040h, 049h, 04Bh db 065h, 068h, 061h, 06Dh, 06Ah, 063h, 064h, 062h, 06Eh, 06Fh, 06Ch, 067h, 066h, 060h, 069h, 06Bh db 0C5h, 0C8h, 0C1h, 0CDh, 0CAh, 0C3h, 0C4h, 0C2h, 0CEh, 0CFh, 0CCh, 0C7h, 0C6h, 0C0h, 0C9h, 0CBh db 0B5h, 0B8h, 0B1h, 0BDh, 0BAh, 0B3h, 0B4h, 0B2h, 0BEh, 0BFh, 0BCh, 0B7h, 0B6h, 0B0h, 0B9h, 0BBh db 025h, 028h, 021h, 02Dh, 02Ah, 023h, 024h, 022h, 02Eh, 02Fh, 02Ch, 027h, 026h, 020h, 029h, 02Bh db 055h, 058h, 051h, 05Dh, 05Ah, 053h, 054h, 052h, 05Eh, 05Fh, 05Ch, 057h, 056h, 050h, 059h, 05Bh db 035h, 038h, 031h, 03Dh, 03Ah, 033h, 034h, 032h, 03Eh, 03Fh, 03Ch, 037h, 036h, 030h, 039h, 03Bh sbox_3 db 046h, 04Ch, 047h, 041h, 045h, 04Fh, 04Dh, 048h, 044h, 04Ah, 049h, 04Eh, 040h, 043h, 04Bh, 042h db 0B6h, 0BCh, 0B7h, 0B1h, 0B5h, 0BFh, 0BDh, 0B8h, 0B4h, 0BAh, 0B9h, 0BEh, 0B0h, 0B3h, 0BBh, 0B2h db 0A6h, 0ACh, 0A7h, 0A1h, 0A5h, 0AFh, 0ADh, 0A8h, 0A4h, 0AAh, 0A9h, 0AEh, 0A0h, 0A3h, 0ABh, 0A2h db 006h, 00Ch, 007h, 001h, 005h, 00Fh, 00Dh, 008h, 004h, 00Ah, 009h, 00Eh, 000h, 003h, 00Bh, 002h db 076h, 07Ch, 077h, 071h, 075h, 07Fh, 07Dh, 078h, 074h, 07Ah, 079h, 07Eh, 070h, 073h, 07Bh, 072h db 026h, 02Ch, 027h, 021h, 025h, 02Fh, 02Dh, 028h, 024h, 02Ah, 029h, 02Eh, 020h, 023h, 02Bh, 022h db 016h, 01Ch, 017h, 011h, 015h, 01Fh, 01Dh, 018h, 014h, 01Ah, 019h, 01Eh, 010h, 013h, 01Bh, 012h db 0D6h, 0DCh, 0D7h, 0D1h, 0D5h, 0DFh, 0DDh, 0D8h, 0D4h, 0DAh, 0D9h, 0DEh, 0D0h, 0D3h, 0DBh, 0D2h db 036h, 03Ch, 037h, 031h, 035h, 03Fh, 03Dh, 038h, 034h, 03Ah, 039h, 03Eh, 030h, 033h, 03Bh, 032h db 066h, 06Ch, 067h, 061h, 065h, 06Fh, 06Dh, 068h, 064h, 06Ah, 069h, 06Eh, 060h, 063h, 06Bh, 062h db 086h, 08Ch, 087h, 081h, 085h, 08Fh, 08Dh, 088h, 084h, 08Ah, 089h, 08Eh, 080h, 083h, 08Bh, 082h db 056h, 05Ch, 057h, 051h, 055h, 05Fh, 05Dh, 058h, 054h, 05Ah, 059h, 05Eh, 050h, 053h, 05Bh, 052h db 096h, 09Ch, 097h, 091h, 095h, 09Fh, 09Dh, 098h, 094h, 09Ah, 099h, 09Eh, 090h, 093h, 09Bh, 092h db 0C6h, 0CCh, 0C7h, 0C1h, 0C5h, 0CFh, 0CDh, 0C8h, 0C4h, 0CAh, 0C9h, 0CEh, 0C0h, 0C3h, 0CBh, 0C2h db 0F6h, 0FCh, 0F7h, 0F1h, 0F5h, 0FFh, 0FDh, 0F8h, 0F4h, 0FAh, 0F9h, 0FEh, 0F0h, 0F3h, 0FBh, 0F2h db 0E6h, 0ECh, 0E7h, 0E1h, 0E5h, 0EFh, 0EDh, 0E8h, 0E4h, 0EAh, 0E9h, 0EEh, 0E0h, 0E3h, 0EBh, 0E2h sbox_4 db 01Dh, 01Bh, 014h, 011h, 013h, 01Fh, 015h, 019h, 010h, 01Ah, 01Eh, 017h, 016h, 018h, 012h, 01Ch db 0FDh, 0FBh, 0F4h, 0F1h, 0F3h, 0FFh, 0F5h, 0F9h, 0F0h, 0FAh, 0FEh, 0F7h, 0F6h, 0F8h, 0F2h, 0FCh db 0DDh, 0DBh, 0D4h, 0D1h, 0D3h, 0DFh, 0D5h, 0D9h, 0D0h, 0DAh, 0DEh, 0D7h, 0D6h, 0D8h, 0D2h, 0DCh db 00Dh, 00Bh, 004h, 001h, 003h, 00Fh, 005h, 009h, 000h, 00Ah, 00Eh, 007h, 006h, 008h, 002h, 00Ch db 05Dh, 05Bh, 054h, 051h, 053h, 05Fh, 055h, 059h, 050h, 05Ah, 05Eh, 057h, 056h, 058h, 052h, 05Ch db 07Dh, 07Bh, 074h, 071h, 073h, 07Fh, 075h, 079h, 070h, 07Ah, 07Eh, 077h, 076h, 078h, 072h, 07Ch db 0ADh, 0ABh, 0A4h, 0A1h, 0A3h, 0AFh, 0A5h, 0A9h, 0A0h, 0AAh, 0AEh, 0A7h, 0A6h, 0A8h, 0A2h, 0ACh db 04Dh, 04Bh, 044h, 041h, 043h, 04Fh, 045h, 049h, 040h, 04Ah, 04Eh, 047h, 046h, 048h, 042h, 04Ch db 09Dh, 09Bh, 094h, 091h, 093h, 09Fh, 095h, 099h, 090h, 09Ah, 09Eh, 097h, 096h, 098h, 092h, 09Ch db 02Dh, 02Bh, 024h, 021h, 023h, 02Fh, 025h, 029h, 020h, 02Ah, 02Eh, 027h, 026h, 028h, 022h, 02Ch db 03Dh, 03Bh, 034h, 031h, 033h, 03Fh, 035h, 039h, 030h, 03Ah, 03Eh, 037h, 036h, 038h, 032h, 03Ch db 0EDh, 0EBh, 0E4h, 0E1h, 0E3h, 0EFh, 0E5h, 0E9h, 0E0h, 0EAh, 0EEh, 0E7h, 0E6h, 0E8h, 0E2h, 0ECh db 06Dh, 06Bh, 064h, 061h, 063h, 06Fh, 065h, 069h, 060h, 06Ah, 06Eh, 067h, 066h, 068h, 062h, 06Ch db 0BDh, 0BBh, 0B4h, 0B1h, 0B3h, 0BFh, 0B5h, 0B9h, 0B0h, 0BAh, 0BEh, 0B7h, 0B6h, 0B8h, 0B2h, 0BCh db 08Dh, 08Bh, 084h, 081h, 083h, 08Fh, 085h, 089h, 080h, 08Ah, 08Eh, 087h, 086h, 088h, 082h, 08Ch db 0CDh, 0CBh, 0C4h, 0C1h, 0C3h, 0CFh, 0C5h, 0C9h, 0C0h, 0CAh, 0CEh, 0C7h, 0C6h, 0C8h, 0C2h, 0CCh
/** * @file soil.cpp * @author Bernd Giesecke (bernd.giesecke@rakwireless.com) * @brief Soil sensor initialization and readings * @version 0.1 * @date 2021-08-17 * * @copyright Copyright (c) 2021 * */ #include "app.h" /** Sensor */ RAK12035 sensor; soil_data_s g_soil_data; struct calib_values_s { uint16_t dry_cal = 75; uint16_t wet_cal = 250; }; calib_values_s calib_values; uint8_t read_fail_counter = 0; bool init_soil(void) { MYLOG("SOIL", "Init soil sensor"); Serial.flush(); // Check if sensors is available bool found_sensor = false; pinMode(WB_IO2, OUTPUT); digitalWrite(WB_IO2, HIGH); // pinMode(WB_IO5, INPUT); Wire.begin(); // Initialize the sensor sensor.setup(Wire); sensor.begin(); uint8_t data = 0; uint16_t value = 0; // Check the sensor version if (!sensor.get_sensor_version(&data)) { MYLOG("SOIL", "No sensor found"); } else { MYLOG("SOIL", "Sensor FW version %d", data); found_sensor = true; } // Check the sensor calibration values if (!sensor.get_dry_cal(&value)) { MYLOG("SOIL", "No Dry calibration"); } else { MYLOG("SOIL", "Sensor Dry Cal %d", value); found_sensor = true; } // Check the sensor calibration values if (!sensor.get_wet_cal(&value)) { MYLOG("SOIL", "No Wet calibration"); } else { MYLOG("SOIL", "Sensor Wet Cal %d", value); found_sensor = true; } // #define CAL_TEST #ifdef CAL_TEST for (int i = 0; i < 100; i++) { MYLOG("SOIL", "Read cycle %d", i); // Check the sensor calibration values uint16_t value = 0; if (!sensor.get_dry_cal(&value)) { MYLOG("SOIL", "No Dry calibration"); } else { MYLOG("SOIL", "Sensor Dry Cal %d", value); } // Check the sensor calibration values if (!sensor.get_wet_cal(&value)) { MYLOG("SOIL", "No Wet calibration"); } else { MYLOG("SOIL", "Sensor Wet Cal %d", value); } MYLOG("SOIL", "Powercycle Sensor"); sensor.sensor_sleep(); digitalWrite(WB_IO2, LOW); delay(500); digitalWrite(WB_IO2, HIGH); delay(500); sensor.reset(); } #endif sensor.sensor_sleep(); // Wire.end(); return found_sensor; } void read_soil(void) { uint16_t sensTemp = 0; uint8_t sensHumid = 0; uint32_t avgTemp = 0; uint32_t avgHumid = 0; uint16_t sensCap = 0; uint32_t avgCap = 0; // Wake up the sensor // Wire.begin(); if (!sensor.sensor_on()) { MYLOG("SOIL", "Can't wake up sensor"); g_soil_data.temp_1 = 0xFF; g_soil_data.temp_2 = 0xFF; g_soil_data.humid_1 = 0xFF; g_soil_data.valid = 0; // Wire.end(); read_fail_counter++; if (read_fail_counter == 5) { read_fail_counter = 0; delay(1000); api_reset(); } return; } // Get the sensor values bool got_value = false; for (int retry = 0; retry < 3; retry++) { if (sensor.get_sensor_moisture(&sensHumid) && sensor.get_sensor_temperature(&sensTemp)) { got_value = true; retry = 4; avgTemp = sensTemp; avgHumid = sensHumid; sensor.get_sensor_capacitance(&sensCap); delay(250); for (int avg = 0; avg < 50; avg++) { delay(250); if (sensor.get_sensor_temperature(&sensTemp)) { avgTemp += sensTemp; avgTemp /= 2; } if (sensor.get_sensor_moisture(&sensHumid)) { avgHumid += sensHumid; avgHumid /= 2; } if (sensor.get_sensor_capacitance(&sensCap)) { avgCap += sensCap; avgCap /= 2; } } } } MYLOG("SOIL", "Sensor reading was %s", got_value ? "success" : "unsuccessful"); MYLOG("SOIL", "T %.2f H %ld C %ld", (double)(avgTemp / 10.0), avgHumid, avgCap); avgHumid = avgHumid * 2.0; g_soil_data.temp_1 = (uint8_t)(avgTemp >> 8); g_soil_data.temp_2 = (uint8_t)(avgTemp); g_soil_data.humid_1 = (uint8_t)(avgHumid); g_soil_data.cap_1 = (uint8_t)(avgCap >> 8); g_soil_data.cap_2 = (uint8_t)(avgCap); if (got_value) { g_soil_data.valid = 1; } else { g_soil_data.valid = 0; } sensor.sensor_sleep(); // Wire.end(); } uint16_t start_calib(bool is_dry) { MYLOG("SOIL", "Starting calibration for %s", is_dry ? "dry" : "wet"); uint16_t new_reading = 0; uint16_t new_value = 0; digitalWrite(LED_GREEN, LOW); digitalWrite(LED_BLUE, HIGH); // Stop app timer while we do calibration api_timer_stop(); // Wire.begin(); if (!sensor.sensor_on()) { MYLOG("SOIL", "Can't wake up sensor"); // Wire.end(); if (g_lorawan_settings.send_repeat_time != 0) { // Calibration finished, restart the timer that will wakeup the loop frequently api_timer_restart(g_lorawan_settings.send_repeat_time); } digitalWrite(LED_BLUE, LOW); digitalWrite(LED_GREEN, LOW); if (is_dry) { return 0xFFFF; } else { return 0xFFFF; } } sensor.get_sensor_capacitance(&new_value); for (int readings = 0; readings < 100; readings++) { sensor.get_sensor_capacitance(&new_reading); if (new_reading != 0xFFFF) { MYLOG("SOIL", "Capacitance during %s calibration is %d\n", is_dry ? " DRY" : "WET", new_reading); new_value += new_reading; new_value = new_value / 2; } else { MYLOG("SOIL", "Capacitance reading failed\n"); } delay(250); digitalWrite(LED_GREEN, !digitalRead(LED_GREEN)); digitalWrite(LED_BLUE, !digitalRead(LED_BLUE)); } // Send calibration value if (is_dry) { MYLOG("SOIL", "Dry calibration value %d", new_value); // sensor.set_wet_cal(new_value); sensor.set_dry_cal(new_value); calib_values.dry_cal = new_value; } else { MYLOG("SOIL", "Wet calibration value %d", new_value); // sensor.set_dry_cal(new_value); sensor.set_wet_cal(new_value); calib_values.wet_cal = new_value; } if (g_lorawan_settings.send_repeat_time != 0) { // Calibration finished, restart the timer that will wakeup the loop frequently api_timer_restart(g_lorawan_settings.send_repeat_time); } // Return the result digitalWrite(LED_BLUE, LOW); digitalWrite(LED_GREEN, LOW); sensor.sensor_sleep(); // Wire.end(); return new_value; } uint16_t get_calib(bool is_dry) { uint16_t value = 0; // Wire.begin(); sensor.sensor_on(); if (is_dry) { if (!sensor.get_dry_cal(&value)) { MYLOG("SOIL", "No Dry calibration"); } else { MYLOG("SOIL", "Sensor Dry Cal %d", value); } } else { if (!sensor.get_wet_cal(&value)) { MYLOG("SOIL", "No Wet calibration"); } else { MYLOG("SOIL", "Sensor Wet Cal %d", value); } } sensor.sensor_sleep(); // Wire.end(); return value; } uint16_t set_calib(bool is_dry, uint16_t calib_val) { uint16_t value = 0; // Wire.begin(); sensor.sensor_on(); if (is_dry) { MYLOG("SOIL", "Dry calibration value %d", calib_val); // sensor.set_wet_cal(new_value); sensor.set_dry_cal(calib_val); calib_values.dry_cal = calib_val; } else { MYLOG("SOIL", "Wet calibration value %d", calib_val); // sensor.set_dry_cal(new_value); sensor.set_wet_cal(calib_val); calib_values.wet_cal = calib_val; } sensor.sensor_sleep(); // Wire.end(); return value; }
#pragma once #include <mutex> #include <thread> #include <glm/mat4x4.hpp> // mat4 #include "sound/sound.hpp" void loadAudio(); void debugPrintAudio(); typedef short SoundSample; class VehicleEngineAudioStream : public sf::SoundStream { public: void initializeEngineAudio(); void setEngineRpm(float newRpm); private: std::mutex engineRpmMutex; float lastEngineRpm; SoundSample sampleBuffer[100]; unsigned int bufferOffset; unsigned int sampleRate; virtual bool onGetData(sf::SoundStream::Chunk& data); virtual void onSeek(sf::Time timeOffset); }; void updateAudio(const glm::mat4& mainListenerTransform, float frameTime); class PhysicsVehicle; void updateVehicleAudio(PhysicsVehicle& vehicle, float frameTime); // TODO Kill these void playObjectiveGet(); void playVehicleShifting();
; Startup Code for pacman machine ; ; B. Leperchey 2012 ; ; -startup=2 --> provide an IRQ handler (now required for the Tetris game) ; ; $Id:$ ; DEFC ROM_Start = $0000 DEFC INT_Start = $0038 DEFC NMI_Start = $0066 DEFC CODE_Start = $0100 DEFC VRAM_Start = $4000 DEFC VRAM_Length= $0400 DEFC CRAM_Start = $4400 DEFC CRAM_Length= $0400 DEFC RAM_Start = $4C00 DEFC RAM_Length = $0400 DEFC Stack_Top = $4ff0 DEFC irqen = $5000 DEFC snden = $5001 DEFC watchdog= $50c0 MODULE pacman_crt0 ;------- ; Include zcc_opt.def to find out information about us ;------- defc crt0 = 1 INCLUDE "zcc_opt.def" ;------- ; Some general scope declarations ;------- EXTERN _main ;main() is always external to crt0 code IF (startup=2) EXTERN _irq_handler ;Interrupt handlers ENDIF PUBLIC cleanup PUBLIC l_dcal ;jp(hl) IF !DEFINED_CRT_ORG_BSS defc CRT_ORG_BSS = RAM_Start ; Static variables are kept in RAM defc DEFINED_CRT_ORG_BSS = 1 ENDIF defc TAR__register_sp = -1 defc TAR__clib_exit_stack_size = 4 defc __crt_org_bss = CRT_ORG_BSS PUBLIC __CPU_CLOCK defc __CPU_CLOCK = 2000000 INCLUDE "crt/classic/crt_rules.inc" org ROM_Start ; reset di ld sp,Stack_Top ; setup stack call crt0_init_bss jp start ; jump to start ; IRQ code starts at location $0038, (56 decimal). defs INT_Start-ASMPC di ; disable processor interrupts push af push bc push de push hl ld hl,(FRAMES) inc hl ld (FRAMES),hl ld a,h or l jr nz,irq_hndl ld hl,(FRAMES+2) inc hl ld (FRAMES+2),hl irq_hndl: IF (startup=2) call _irq_handler ENDIF xor a ; reset watchdog timer ld hl,watchdog ld (hl),a pop hl pop de pop bc pop af ei ; enable processor interrupts reti ; return from interrupt routine defs NMI_Start-ASMPC ; nmi retn start: ld a,$ff ; set up the interrupt vector (0x38) out (0),a ld a, 1 ; fill register 'a' with 0x01 ld (irqen), a ; enable the external interrupt mechanism xor a ; reset watchdog timer ld hl,watchdog ld (hl),a ; Clear static memory ;ld hl,RAM_Start ;ld de,RAM_Start+1 ;ld bc,RAM_Length-1 ;ld (hl),0 ;ldir ; enable interrupts im 1 ei ; Entry to the user code call _main cleanup: endloop: jr endloop l_dcal: jp (hl) ; If we were given a model then use it IF DEFINED_CRT_MODEL defc __crt_model = CRT_MODEL ELSE defc __crt_model = 1 ENDIF INCLUDE "crt/classic/crt_runtime_selection.asm" INCLUDE "crt/classic/crt_section.asm" SECTION bss_crt PUBLIC FRAMES FRAMES: defw 0 ; 4 bytes timer counter defw 0 SECTION code_crt_init ld hl,$4000 ld (base_graphics),hl
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r12 push %r13 push %r15 push %rax push %rbx push %rcx push %rdi push %rsi lea addresses_UC_ht+0x1e1e9, %r12 nop nop nop sub %rbx, %rbx movups (%r12), %xmm4 vpextrq $1, %xmm4, %r11 nop nop nop nop add $38779, %r10 lea addresses_D_ht+0x167e9, %r15 nop nop sub %r13, %r13 movb (%r15), %al nop nop nop nop and %r11, %r11 lea addresses_WT_ht+0x10a9, %rbx nop nop nop nop nop xor %rax, %rax mov $0x6162636465666768, %r10 movq %r10, %xmm6 movups %xmm6, (%rbx) nop nop nop and $13286, %rax lea addresses_A_ht+0x15ca9, %rsi lea addresses_UC_ht+0x9632, %rdi clflush (%rdi) nop nop inc %rbx mov $30, %rcx rep movsl nop nop cmp %rbx, %rbx pop %rsi pop %rdi pop %rcx pop %rbx pop %rax pop %r15 pop %r13 pop %r12 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r14 push %r15 push %r8 push %rbp push %rsi // Store lea addresses_WT+0x50ed, %r12 nop nop cmp $49326, %r14 mov $0x5152535455565758, %r15 movq %r15, (%r12) nop nop add %rsi, %rsi // Load mov $0x4605f70000000849, %r8 nop nop nop cmp %rbp, %rbp mov (%r8), %r15w dec %r15 // Store lea addresses_WC+0x128a9, %r13 nop add %rsi, %rsi mov $0x5152535455565758, %r8 movq %r8, %xmm6 movups %xmm6, (%r13) nop nop nop nop nop xor $37440, %rbp // Faulty Load lea addresses_PSE+0x104a9, %r15 nop nop nop nop nop cmp %r13, %r13 mov (%r15), %rbp lea oracles, %r12 and $0xff, %rbp shlq $12, %rbp mov (%r12,%rbp,1), %rbp pop %rsi pop %rbp pop %r8 pop %r15 pop %r14 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 2, 'AVXalign': True, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_WT'}} {'src': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_NC'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_WC'}} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 8, 'NT': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 6, 'AVXalign': True, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_WT_ht'}} {'src': {'congruent': 11, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 0, 'same': False, 'type': 'addresses_UC_ht'}} {'33': 21829} 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 */
%include "util.mac" extern buffer, store, array, inprompt, newline, arraysize, inpromptsize, newlinesize, inputarray, printarray section .data outprompt1: db 'MAXIMUM OUTPUT: ' outprompt2: db 'MINIMUM OUTPUT: ' outpromptsize: equ 8 section .bss max: resb 1 min: resb 1 section .text global _start _start: call inputarray write inprompt, inpromptsize write newline, newlinesize call printarray write newline, newlinesize mov byte [max], 0 mov byte [min], 255 mov ecx, 0 mov cl, [arraysize] nextelement: mov al, [max] cmp [array + ecx - 1], al jc skip1 mov al, [array + ecx - 1] mov [max], al skip1: mov al, [min] cmp al, [array + ecx - 1] jc skip2 mov al, [array + ecx - 1] mov [min], al skip2: loop nextelement write outprompt1, outpromptsize mov al, [max] mov ah, 0 printword ax, buffer, 2 write newline, newlinesize write outprompt2, outpromptsize mov al, [min] mov ah, 0 printword ax, buffer, 2 write newline, newlinesize exit
; A116523: a(0)=1, a(1)=1, a(n) = 17*a(n/2) for n=2,4,6,..., a(n) = 16*a((n-1)/2) + a((n+1)/2) for n=3,5,7,.... ; 0,1,17,33,289,305,561,817,4913,4929,5185,5441,9537,9793,13889,17985,83521,83537,83793,84049,88145,88401,92497,96593,162129,162385,166481,170577,236113,240209,305745,371281,1419857,1419873,1420129,1420385,1424481,1424737,1428833,1432929,1498465,1498721,1502817,1506913,1572449,1576545,1642081,1707617,2756193,2756449,2760545,2764641,2830177,2834273,2899809,2965345,4013921,4018017,4083553,4149089,5197665,5263201,6311777,7360353,24137569,24137585,24137841,24138097,24142193,24142449,24146545,24150641,24216177,24216433,24220529,24224625,24290161,24294257,24359793,24425329,25473905,25474161,25478257,25482353,25547889,25551985,25617521,25683057,26731633,26735729,26801265,26866801,27915377,27980913,29029489,30078065,46855281,46855537,46859633,46863729 mov $2,$0 mov $3,$0 lpb $2 mov $0,$3 sub $2,1 sub $0,$2 sub $0,1 seq $0,1316 ; Gould's sequence: a(n) = Sum_{k=0..n} (binomial(n,k) mod 2); number of odd entries in row n of Pascal's triangle (A007318); a(n) = 2^A000120(n). pow $0,4 add $1,$0 lpe mov $0,$1
// Generated from /POI/java/org/apache/poi/util/RLEDecompressingInputStream.java #include <org/apache/poi/util/RLEDecompressingInputStream.hpp> #include <java/io/ByteArrayInputStream.hpp> #include <java/io/ByteArrayOutputStream.hpp> #include <java/io/InputStream.hpp> #include <java/lang/IllegalArgumentException.hpp> #include <java/lang/IllegalStateException.hpp> #include <java/lang/Integer.hpp> #include <java/lang/Math.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/Object.hpp> #include <java/lang/String.hpp> #include <java/lang/System.hpp> #include <java/util/Locale.hpp> #include <org/apache/poi/util/IOUtils.hpp> #include <Array.hpp> #include <ObjectArray.hpp> template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::util::RLEDecompressingInputStream::RLEDecompressingInputStream(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::util::RLEDecompressingInputStream::RLEDecompressingInputStream(::java::io::InputStream* in) /* throws(IOException) */ : RLEDecompressingInputStream(*static_cast< ::default_init_tag* >(0)) { ctor(in); } int32_tArray*& poi::util::RLEDecompressingInputStream::POWER2() { clinit(); return POWER2_; } int32_tArray* poi::util::RLEDecompressingInputStream::POWER2_; void poi::util::RLEDecompressingInputStream::ctor(::java::io::InputStream* in) /* throws(IOException) */ { super::ctor(); this->in = in; buf = new ::int8_tArray(int32_t(4096)); pos = 0; auto header = npc(in)->read(); if(header != 1) { throw new ::java::lang::IllegalArgumentException(::java::lang::String::format(::java::util::Locale::ROOT(), u"Header byte 0x01 expected, received 0x%02X"_j, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(::java::lang::Integer::valueOf(header & int32_t(255)))}))); } len = readChunk(); } int32_t poi::util::RLEDecompressingInputStream::read() /* throws(IOException) */ { if(len == -int32_t(1)) { return -int32_t(1); } if(pos >= len) { if((len = readChunk()) == -int32_t(1)) { return -int32_t(1); } } return (*buf)[pos++] & int32_t(255); } int32_t poi::util::RLEDecompressingInputStream::read(::int8_tArray* b) /* throws(IOException) */ { return read(b, int32_t(0), npc(b)->length); } int32_t poi::util::RLEDecompressingInputStream::read(::int8_tArray* b, int32_t off, int32_t l) /* throws(IOException) */ { if(len == -int32_t(1)) { return -int32_t(1); } auto offset = off; auto length = l; while (length > 0) { if(pos >= len) { if((len = readChunk()) == -int32_t(1)) { return offset > off ? offset - off : -int32_t(1); } } auto c = ::java::lang::Math::min(length, len - pos); ::java::lang::System::arraycopy(buf, pos, b, offset, c); pos += c; length -= c; offset += c; } return l; } int64_t poi::util::RLEDecompressingInputStream::skip(int64_t n) /* throws(IOException) */ { auto length = n; while (length > 0) { if(pos >= len) { if((len = readChunk()) == -int32_t(1)) { return -int32_t(1); } } auto c = static_cast< int32_t >(::java::lang::Math::min(n, static_cast< int64_t >(len - pos))); pos += c; length -= c; } return n; } int32_t poi::util::RLEDecompressingInputStream::available() { return (len > 0 ? len - pos : int32_t(0)); } void poi::util::RLEDecompressingInputStream::close() /* throws(IOException) */ { npc(in)->close(); } int32_t poi::util::RLEDecompressingInputStream::readChunk() /* throws(IOException) */ { pos = 0; auto w = readShort(in); if(w == -int32_t(1)) { return -int32_t(1); } auto chunkSize = (w & int32_t(4095)) + int32_t(1); if((w & int32_t(28672)) != 12288) { throw new ::java::lang::IllegalArgumentException(::java::lang::String::format(::java::util::Locale::ROOT(), u"Chunksize header A should be 0x3000, received 0x%04X"_j, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(::java::lang::Integer::valueOf(w & int32_t(57344)))}))); } auto rawChunk = (w & int32_t(32768)) == 0; if(rawChunk) { if(npc(in)->read(buf, 0, chunkSize) < chunkSize) { throw new ::java::lang::IllegalStateException(::java::lang::String::format(::java::util::Locale::ROOT(), u"Not enough bytes read, expected %d"_j, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(::java::lang::Integer::valueOf(chunkSize))}))); } return chunkSize; } else { auto inOffset = int32_t(0); auto outOffset = int32_t(0); while (inOffset < chunkSize) { auto tokenFlags = npc(in)->read(); inOffset++; if(tokenFlags == -int32_t(1)) { break; } for (auto n = int32_t(0); n < 8; n++) { if(inOffset >= chunkSize) { break; } if((tokenFlags & (*POWER2_)[n]) == 0) { auto const b = npc(in)->read(); if(b == -int32_t(1)) { return -int32_t(1); } (*buf)[outOffset++] = static_cast< int8_t >(b); inOffset++; } else { auto token = readShort(in); if(token == -int32_t(1)) { return -int32_t(1); } inOffset += 2; auto copyLenBits = getCopyLenBits(outOffset - int32_t(1)); auto copyOffset = (token >> (copyLenBits)) + int32_t(1); auto copyLen = (token & ((*POWER2_)[copyLenBits] - int32_t(1))) + int32_t(3); auto startPos = outOffset - copyOffset; auto endPos = startPos + copyLen; for (auto i = startPos; i < endPos; i++) { (*buf)[outOffset++] = (*buf)[i]; } } } } return outOffset; } } int32_t poi::util::RLEDecompressingInputStream::getCopyLenBits(int32_t offset) { clinit(); for (auto n = int32_t(11); n >= 4; n--) { if((offset & (*POWER2_)[n]) != 0) { return int32_t(15) - n; } } return 12; } int32_t poi::util::RLEDecompressingInputStream::readShort() /* throws(IOException) */ { return readShort(this); } int32_t poi::util::RLEDecompressingInputStream::readInt() /* throws(IOException) */ { return readInt(this); } int32_t poi::util::RLEDecompressingInputStream::readShort(::java::io::InputStream* stream) /* throws(IOException) */ { int32_t b0, b1; if((b0 = npc(stream)->read()) == -int32_t(1)) { return -int32_t(1); } if((b1 = npc(stream)->read()) == -int32_t(1)) { return -int32_t(1); } return (b0 & int32_t(255)) | ((b1 & int32_t(255)) << int32_t(8)); } int32_t poi::util::RLEDecompressingInputStream::readInt(::java::io::InputStream* stream) /* throws(IOException) */ { int32_t b0, b1, b2, b3; if((b0 = npc(stream)->read()) == -int32_t(1)) { return -int32_t(1); } if((b1 = npc(stream)->read()) == -int32_t(1)) { return -int32_t(1); } if((b2 = npc(stream)->read()) == -int32_t(1)) { return -int32_t(1); } if((b3 = npc(stream)->read()) == -int32_t(1)) { return -int32_t(1); } return (b0 & int32_t(255)) | ((b1 & int32_t(255)) << int32_t(8)) | ((b2 & int32_t(255)) << int32_t(16))| ((b3 & int32_t(255)) << int32_t(24)); } int8_tArray* poi::util::RLEDecompressingInputStream::decompress(::int8_tArray* compressed) /* throws(IOException) */ { clinit(); return decompress(compressed, 0, npc(compressed)->length); } int8_tArray* poi::util::RLEDecompressingInputStream::decompress(::int8_tArray* compressed, int32_t offset, int32_t length) /* throws(IOException) */ { clinit(); auto out = new ::java::io::ByteArrayOutputStream(); ::java::io::InputStream* instream = new ::java::io::ByteArrayInputStream(compressed, offset, length); ::java::io::InputStream* stream = new RLEDecompressingInputStream(instream); IOUtils::copy(stream, out); npc(stream)->close(); npc(out)->close(); return npc(out)->toByteArray_(); } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::util::RLEDecompressingInputStream::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.util.RLEDecompressingInputStream", 47); return c; } void poi::util::RLEDecompressingInputStream::clinit() { super::clinit(); static bool in_cl_init = false; struct clinit_ { clinit_() { in_cl_init = true; POWER2_ = new ::int32_tArray({ int32_t(1) , int32_t(2) , int32_t(4) , int32_t(8) , int32_t(16) , int32_t(32) , int32_t(64) , int32_t(128) , int32_t(256) , int32_t(512) , int32_t(1024) , int32_t(2048) , int32_t(4096) , int32_t(8192) , int32_t(16384) , int32_t(32768) }); } }; if(!in_cl_init) { static clinit_ clinit_instance; } } java::lang::Class* poi::util::RLEDecompressingInputStream::getClass0() { return class_(); }
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR> ; SPDX-License-Identifier: BSD-2-Clause-Patent ; ; Module Name: ; ; ZeroMem.nasm ; ; Abstract: ; ; ZeroMem function ; ; Notes: ; ;------------------------------------------------------------------------------ DEFAULT REL SECTION .text ;------------------------------------------------------------------------------ ; VOID * ; InternalMemZeroMem ( ; IN VOID *Buffer, ; IN UINTN Count ; ); ;------------------------------------------------------------------------------ global ASM_PFX(InternalMemZeroMem) ASM_PFX(InternalMemZeroMem): push rdi mov rdi, rcx mov rcx, rdx mov r8, rdi and edx, 7 shr rcx, 3 jz @ZeroBytes DB 0xf, 0xef, 0xc0 ; pxor mm0, mm0 .0: DB 0xf, 0xe7, 7 ; movntq [rdi], mm0 add rdi, 8 loop .0 DB 0xf, 0xae, 0xf0 ; mfence @ZeroBytes: xor eax, eax mov ecx, edx rep stosb mov rax, r8 pop rdi ret
.size 8000 .text@48 jp lstatint .text@100 jp lbegin .data@143 c0 .text@150 lbegin: ld a, 00 ldff(ff), a ld a, 30 ldff(00), a ld a, 01 ldff(4d), a stop, 00 ld a, ff ldff(45), a ld b, 91 call lwaitly_b ld hl, fe00 ld d, 10 ld a, d ld(hl++), a ld a, 0d ld(hl++), a inc l inc l ld a, d ld(hl++), a ld a, 14 ld(hl++), a inc l inc l ld a, d ld(hl++), a ld a, 1d ld(hl++), a inc l inc l ld a, d ld(hl++), a ld a, 24 ld(hl++), a inc l inc l ld a, d ld(hl++), a ld a, 2d ld(hl++), a inc l inc l ld a, d ld(hl++), a ld a, 34 ld(hl++), a inc l inc l ld a, d ld(hl++), a ld a, 3d ld(hl++), a inc l inc l ld a, d ld(hl++), a ld a, 44 ld(hl++), a inc l inc l ld a, d ld(hl++), a ld a, 4d ld(hl++), a inc l inc l ld a, d ld(hl++), a ld a, 54 ld(hl++), a ld a, 40 ldff(41), a ld a, 02 ldff(ff), a xor a, a ldff(0f), a ei ld a, 01 ldff(45), a ld c, 41 ld a, 93 ldff(40), a .text@1000 lstatint: nop .text@1094 ldff a, (c) and a, 03 jp lprint_a .text@7000 lprint_a: push af ld b, 91 call lwaitly_b xor a, a ldff(40), a pop af ld(9800), a ld bc, 7a00 ld hl, 8000 ld d, a0 lprint_copytiles: ld a, (bc) inc bc ld(hl++), a dec d jrnz lprint_copytiles ld a, c0 ldff(47), a ld a, 80 ldff(68), a ld a, ff ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a xor a, a ldff(69), a ldff(69), a ldff(43), a ld a, 91 ldff(40), a lprint_limbo: jr lprint_limbo .text@7400 lwaitly_b: ld c, 44 lwaitly_b_loop: ldff a, (c) cmp a, b jrnz lwaitly_b_loop ret .data@7a00 00 00 7f 7f 41 41 41 41 41 41 41 41 41 41 7f 7f 00 00 08 08 08 08 08 08 08 08 08 08 08 08 08 08 00 00 7f 7f 01 01 01 01 7f 7f 40 40 40 40 7f 7f 00 00 7f 7f 01 01 01 01 3f 3f 01 01 01 01 7f 7f 00 00 41 41 41 41 41 41 7f 7f 01 01 01 01 01 01 00 00 7f 7f 40 40 40 40 7e 7e 01 01 01 01 7e 7e 00 00 7f 7f 40 40 40 40 7f 7f 41 41 41 41 7f 7f 00 00 7f 7f 01 01 02 02 04 04 08 08 10 10 10 10 00 00 3e 3e 41 41 41 41 3e 3e 41 41 41 41 3e 3e 00 00 7f 7f 41 41 41 41 7f 7f 01 01 01 01 7f 7f
; A047619: Numbers that are congruent to {1, 2, 5} mod 8. ; 1,2,5,9,10,13,17,18,21,25,26,29,33,34,37,41,42,45,49,50,53,57,58,61,65,66,69,73,74,77,81,82,85,89,90,93,97,98,101,105,106,109,113,114,117,121,122,125,129,130,133,137,138,141,145,146,149,153,154,157,161,162,165,169,170,173,177,178,181,185,186,189,193,194,197,201,202,205,209,210,213,217,218,221,225,226,229,233,234,237,241,242,245,249,250,253,257,258,261,265,266,269,273,274,277,281,282,285,289,290,293,297,298,301,305,306,309,313,314,317,321,322,325,329,330,333,337,338,341,345,346,349,353,354,357,361,362,365,369,370,373,377,378,381,385,386,389,393,394,397,401,402,405,409,410,413,417,418,421,425,426,429,433,434,437,441,442,445,449,450,453,457,458,461,465,466,469,473,474,477,481,482,485,489,490,493,497,498,501,505,506,509,513,514,517,521,522,525,529,530,533,537,538,541,545,546,549,553,554,557,561,562,565,569,570,573,577,578,581,585,586,589,593,594,597,601,602,605,609,610,613,617,618,621,625,626,629,633,634,637,641,642,645,649,650,653,657,658,661,665 mul $0,8 mov $1,3 mov $2,$0 div $0,3 gcd $1,$2 div $1,2 add $1,1 add $1,$0 sub $1,1
; A077588: Maximum number of regions into which the plane is divided by n triangles. ; 1,2,8,20,38,62,92,128,170,218,272,332,398,470,548,632,722,818,920,1028,1142,1262,1388,1520,1658,1802,1952,2108,2270,2438,2612,2792,2978,3170,3368,3572,3782,3998,4220,4448,4682,4922,5168,5420,5678,5942,6212,6488 mul $0,3 sub $2,$0 trn $0,3 add $0,1 add $2,1 mul $0,$2 mov $1,2 sub $1,$0 div $1,3 add $1,1
; SPIR-V ; Version: 1.0 ; Generator: Khronos Glslang Reference Front End; 10 ; Bound: 110 ; Schema: 0 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" %25 %85 OpExecutionMode %4 OriginUpperLeft OpSource ESSL 320 OpName %4 "main" OpName %10 "func(f1;" OpName %9 "x" OpName %25 "gl_FragCoord" OpName %33 "buf1" OpMemberName %33 0 "_GLF_uniform_float_values" OpName %35 "" OpName %75 "param" OpName %85 "_GLF_color" OpName %88 "buf0" OpMemberName %88 0 "_GLF_uniform_int_values" OpName %90 "" OpDecorate %25 BuiltIn FragCoord OpDecorate %32 ArrayStride 16 OpMemberDecorate %33 0 Offset 0 OpDecorate %33 Block OpDecorate %35 DescriptorSet 0 OpDecorate %35 Binding 1 OpDecorate %85 Location 0 OpDecorate %87 ArrayStride 16 OpMemberDecorate %88 0 Offset 0 OpDecorate %88 Block OpDecorate %90 DescriptorSet 0 OpDecorate %90 Binding 0 %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeFloat 32 %7 = OpTypePointer Function %6 %8 = OpTypeFunction %6 %7 %17 = OpTypeBool %18 = OpConstantTrue %17 %23 = OpTypeVector %6 4 %24 = OpTypePointer Input %23 %25 = OpVariable %24 Input %26 = OpTypeInt 32 0 %27 = OpConstant %26 1 %28 = OpTypePointer Input %6 %31 = OpConstant %26 4 %32 = OpTypeArray %6 %31 %33 = OpTypeStruct %32 %34 = OpTypePointer Uniform %33 %35 = OpVariable %34 Uniform %36 = OpTypeInt 32 1 %37 = OpConstant %36 0 %38 = OpConstant %36 2 %39 = OpTypePointer Uniform %6 %49 = OpConstant %26 0 %56 = OpConstant %36 3 %62 = OpConstant %36 1 %84 = OpTypePointer Output %23 %85 = OpVariable %84 Output %86 = OpConstant %26 2 %87 = OpTypeArray %36 %86 %88 = OpTypeStruct %87 %89 = OpTypePointer Uniform %88 %90 = OpVariable %89 Uniform %91 = OpTypePointer Uniform %36 %4 = OpFunction %2 None %3 %5 = OpLabel %75 = OpVariable %7 Function %76 = OpAccessChain %28 %25 %49 %77 = OpLoad %6 %76 OpStore %75 %77 %78 = OpFunctionCall %6 %10 %75 %79 = OpAccessChain %39 %35 %37 %62 %80 = OpLoad %6 %79 %81 = OpFOrdEqual %17 %78 %80 OpSelectionMerge %83 None OpBranchConditional %81 %82 %105 %82 = OpLabel %92 = OpAccessChain %91 %90 %37 %37 %93 = OpLoad %36 %92 %94 = OpConvertSToF %6 %93 %95 = OpAccessChain %91 %90 %37 %62 %96 = OpLoad %36 %95 %97 = OpConvertSToF %6 %96 %98 = OpAccessChain %91 %90 %37 %62 %99 = OpLoad %36 %98 %100 = OpConvertSToF %6 %99 %101 = OpAccessChain %91 %90 %37 %37 %102 = OpLoad %36 %101 %103 = OpConvertSToF %6 %102 %104 = OpCompositeConstruct %23 %94 %97 %100 %103 OpStore %85 %104 OpBranch %83 %105 = OpLabel %106 = OpAccessChain %91 %90 %37 %62 %107 = OpLoad %36 %106 %108 = OpConvertSToF %6 %107 %109 = OpCompositeConstruct %23 %108 %108 %108 %108 OpStore %85 %109 OpBranch %83 %83 = OpLabel OpReturn OpFunctionEnd %10 = OpFunction %6 None %8 %9 = OpFunctionParameter %7 %11 = OpLabel OpBranch %12 %12 = OpLabel OpLoopMerge %14 %15 None OpBranch %16 %16 = OpLabel OpBranchConditional %18 %13 %14 %13 = OpLabel OpBranch %19 %19 = OpLabel OpLoopMerge %21 %22 None OpBranch %20 %20 = OpLabel %29 = OpAccessChain %28 %25 %27 %30 = OpLoad %6 %29 %40 = OpAccessChain %39 %35 %37 %38 %41 = OpLoad %6 %40 %42 = OpFOrdLessThan %17 %30 %41 OpSelectionMerge %44 None OpBranchConditional %42 %43 %44 %43 = OpLabel OpBranch %45 %45 = OpLabel OpLoopMerge %47 %48 None OpBranch %46 %46 = OpLabel OpBranch %48 %48 = OpLabel %50 = OpAccessChain %28 %25 %49 %51 = OpLoad %6 %50 %52 = OpAccessChain %39 %35 %37 %38 %53 = OpLoad %6 %52 %54 = OpFOrdLessThan %17 %51 %53 OpBranchConditional %54 %45 %47 %47 = OpLabel OpBranch %44 %44 = OpLabel %55 = OpLoad %6 %9 %57 = OpAccessChain %39 %35 %37 %56 %58 = OpLoad %6 %57 %59 = OpFOrdLessThan %17 %55 %58 OpSelectionMerge %61 None OpBranchConditional %59 %60 %61 %60 = OpLabel %63 = OpAccessChain %39 %35 %37 %62 %64 = OpLoad %6 %63 OpReturnValue %64 %61 = OpLabel OpBranch %22 %22 = OpLabel %66 = OpAccessChain %28 %25 %27 %67 = OpLoad %6 %66 %68 = OpAccessChain %39 %35 %37 %38 %69 = OpLoad %6 %68 %70 = OpFOrdLessThan %17 %67 %69 OpBranchConditional %70 %19 %21 %21 = OpLabel OpBranch %15 %15 = OpLabel OpBranch %12 %14 = OpLabel %71 = OpAccessChain %39 %35 %37 %37 %72 = OpLoad %6 %71 OpReturnValue %72 OpFunctionEnd
<% from pwnlib.shellcraft.amd64.linux import setsockopt from pwnlib.shellcraft.amd64 import push from pwnlib.constants import SOL_SOCKET, SO_RCVTIMEO %> <%page args="sock, secs"/> <%docstring> Invokes the syscall for setsockopt to set a timeout on a socket in seconds. See 'man 2 setsockopt' for more information. Arguments: sock(int): sock secs(int): secs </%docstring> ${push(0)} ${push(secs)} ${setsockopt(sock, 'SOL_SOCKET', 'SO_RCVTIMEO', 'rsp', 16)}
; A test program for the jasmZ80 assembler ; This assembly program tests the following instructions: ; - ld (bc/de), a ; - ld a, (bc/de) ; - jp (hl) ; - ld (**), hl ; - ld hl, (**) ; - ld (**), a ; - ld (**), bc ; ; NOTE: This program's intention is to test the jasmZ80 assembler ; (and possibly other assemblers) NOT to test emulators! org 100h stackpointer equ AAAAh ld hl, stackpointer ld sp, hl bc_pointer equ BBBBh de_pointer1 equ BBBCh de_pointer2 equ BBBDh ld a, C3h ; 0xC3 = jp opcode ld bc, bc_pointer ; we put the jp instruction into address 0xBBBB ld (bc), a ld hl, go_here ; we load the go_here address to hl ; Here we load the go_here address to address 0xBBBC ld (de_pointer1), hl ; a much simpler way to put the address into the memory ; The other way to do it (with the "ld (de), a" instruction): ; ld a, l ; we put the last byte of go_here into a ; ld de, de_pointer1 ; ld (de), a ; load the data of a to de_pointer1 ; ld a, h ; we put the first byte of go_here into a ; ld de, de_pointer2 ; ld (de), a ; load the data of a to de_pointer2 ; load the content of bc to hl ld h, b ld l, c jp (hl) ; We jump to bc_pointer jp failed go_here: ld a, (bc) nop ld de, de_pointer1 ld a, (de) nop ld de, de_pointer2 ld a, (de) nop ; does the same as the above (loads the go_here address from 0xBBBC) ld hl, (de_pointer1) nop ld c, 9 ld de, success_str call 5 nop nop nop addr1 equ ABBBh addr2 equ ABBCh ld a, C3h ld (addr1), a ld hl, go_here2 ld (addr2), hl ld hl, addr1 jp (hl) go_here2: ld de, success2_str call 5 ld hl, addr1 ld a, 0 ld a, (addr1) ld a, 0 ld a, (addr2) ld bc, 2121h ld (addr2), bc ld hl, (addr2) ld hl, exit jp (hl) ; tests the cp/m bios printing exit: ld de, exitstr ld c, 9 call 5 jp 0 failed: ld c, 9 ld de, failure call 5 jp exit success_str db "test 1 executed succesfully!", Ah, "$" success2_str db "test 2 executed succesfully!", Ah, "$" failure db "test failed!", Ah, "$" exitstr db "program exiting...", Ah, "$" db "This is a test program for the jasmZ80 assembler which has been probably and hopefully assembled by the jasmZ80 assembler", Ah, "$" db "MADE ON EARTH BY HUMANS$"
;/*! ; @file ; ; @ingroup fapi ; ; @brief DosMakePipe DOS wrapper ; ; (c) osFree Project 2022, <http://www.osFree.org> ; for licence see licence.txt in root directory, or project website ; ; This is Family API implementation for DOS, used with BIND tools ; to link required API ; ; @author Yuri Prokushev (yuri.prokushev@gmail.com) ; ; ; ;*/ .8086 ; Helpers INCLUDE HELPERS.INC _TEXT SEGMENT BYTE PUBLIC 'CODE' USE16 @PROLOG DOSMAKEPIPE @START DOSMAKEPIPE XOR AX, AX EXIT: @EPILOG DOSMAKEPIPE _TEXT ENDS END
; A271389: a(n) = 2*a(n-1) + a(n-2) + n^2 for n>1, with a(0)=0, a(1)=1. ; 0,1,6,22,66,179,460,1148,2820,6869,16658,40306,97414,235303,568216,1371960,3312392,7997033,19306782,46610958,112529098,271669595,655868772,1583407668,3822684684,9228777661,22280240682,53789259754,129858760974,313506782543,756872326960,1827251437424 lpb $0 sub $0,1 add $2,1 add $3,$2 add $4,$3 add $1,$4 mov $5,$2 add $2,$3 mov $3,$5 lpe
/* * * Copyright (c) 2021 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // THIS FILE IS GENERATED BY ZAP #include <cinttypes> #include <cstdint> #include "app/util/util.h" #include <app-common/zap-generated/af-structs.h> #include <app-common/zap-generated/callback.h> #include <app-common/zap-generated/cluster-objects.h> #include <app-common/zap-generated/ids/Clusters.h> #include <app-common/zap-generated/ids/Commands.h> #include <app/InteractionModelEngine.h> #include <lib/core/CHIPSafeCasts.h> #include <lib/support/TypeTraits.h> // Currently we need some work to keep compatible with ember lib. #include <app/util/ember-compatibility-functions.h> namespace chip { namespace app { namespace { void ReportCommandUnsupported(Command * aCommandObj, const ConcreteCommandPath & aCommandPath) { aCommandObj->AddStatus(aCommandPath, Protocols::InteractionModel::Status::UnsupportedCommand); ChipLogError(Zcl, "Unknown command " ChipLogFormatMEI " for cluster " ChipLogFormatMEI, ChipLogValueMEI(aCommandPath.mCommandId), ChipLogValueMEI(aCommandPath.mClusterId)); } } // anonymous namespace // Cluster specific command parsing namespace Clusters { namespace AdministratorCommissioning { void DispatchServerCommand(CommandHandler * apCommandObj, const ConcreteCommandPath & aCommandPath, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; bool wasHandled = false; { switch (aCommandPath.mCommandId) { case Commands::OpenBasicCommissioningWindow::Id: { Commands::OpenBasicCommissioningWindow::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfAdministratorCommissioningClusterOpenBasicCommissioningWindowCallback( apCommandObj, aCommandPath, commandData); } break; } case Commands::OpenCommissioningWindow::Id: { Commands::OpenCommissioningWindow::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfAdministratorCommissioningClusterOpenCommissioningWindowCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::RevokeCommissioning::Id: { Commands::RevokeCommissioning::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfAdministratorCommissioningClusterRevokeCommissioningCallback(apCommandObj, aCommandPath, commandData); } break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aCommandPath); return; } } } if (CHIP_NO_ERROR != TLVError || !wasHandled) { apCommandObj->AddStatus(aCommandPath, Protocols::InteractionModel::Status::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, TLVError=%" CHIP_ERROR_FORMAT, TLVError.Format()); } } } // namespace AdministratorCommissioning namespace DiagnosticLogs { void DispatchServerCommand(CommandHandler * apCommandObj, const ConcreteCommandPath & aCommandPath, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; bool wasHandled = false; { switch (aCommandPath.mCommandId) { case Commands::RetrieveLogsRequest::Id: { Commands::RetrieveLogsRequest::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfDiagnosticLogsClusterRetrieveLogsRequestCallback(apCommandObj, aCommandPath, commandData); } break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aCommandPath); return; } } } if (CHIP_NO_ERROR != TLVError || !wasHandled) { apCommandObj->AddStatus(aCommandPath, Protocols::InteractionModel::Status::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, TLVError=%" CHIP_ERROR_FORMAT, TLVError.Format()); } } } // namespace DiagnosticLogs namespace GeneralCommissioning { void DispatchServerCommand(CommandHandler * apCommandObj, const ConcreteCommandPath & aCommandPath, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; bool wasHandled = false; { switch (aCommandPath.mCommandId) { case Commands::ArmFailSafe::Id: { Commands::ArmFailSafe::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfGeneralCommissioningClusterArmFailSafeCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::CommissioningComplete::Id: { Commands::CommissioningComplete::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfGeneralCommissioningClusterCommissioningCompleteCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::SetRegulatoryConfig::Id: { Commands::SetRegulatoryConfig::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfGeneralCommissioningClusterSetRegulatoryConfigCallback(apCommandObj, aCommandPath, commandData); } break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aCommandPath); return; } } } if (CHIP_NO_ERROR != TLVError || !wasHandled) { apCommandObj->AddStatus(aCommandPath, Protocols::InteractionModel::Status::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, TLVError=%" CHIP_ERROR_FORMAT, TLVError.Format()); } } } // namespace GeneralCommissioning namespace LevelControl { void DispatchServerCommand(CommandHandler * apCommandObj, const ConcreteCommandPath & aCommandPath, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; bool wasHandled = false; { switch (aCommandPath.mCommandId) { case Commands::Move::Id: { Commands::Move::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfLevelControlClusterMoveCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::MoveToLevel::Id: { Commands::MoveToLevel::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfLevelControlClusterMoveToLevelCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::MoveToLevelWithOnOff::Id: { Commands::MoveToLevelWithOnOff::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfLevelControlClusterMoveToLevelWithOnOffCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::MoveWithOnOff::Id: { Commands::MoveWithOnOff::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfLevelControlClusterMoveWithOnOffCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::Step::Id: { Commands::Step::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfLevelControlClusterStepCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::StepWithOnOff::Id: { Commands::StepWithOnOff::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfLevelControlClusterStepWithOnOffCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::Stop::Id: { Commands::Stop::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfLevelControlClusterStopCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::StopWithOnOff::Id: { Commands::StopWithOnOff::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfLevelControlClusterStopWithOnOffCallback(apCommandObj, aCommandPath, commandData); } break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aCommandPath); return; } } } if (CHIP_NO_ERROR != TLVError || !wasHandled) { apCommandObj->AddStatus(aCommandPath, Protocols::InteractionModel::Status::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, TLVError=%" CHIP_ERROR_FORMAT, TLVError.Format()); } } } // namespace LevelControl namespace NetworkCommissioning { void DispatchServerCommand(CommandHandler * apCommandObj, const ConcreteCommandPath & aCommandPath, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; bool wasHandled = false; { switch (aCommandPath.mCommandId) { case Commands::AddThreadNetwork::Id: { Commands::AddThreadNetwork::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfNetworkCommissioningClusterAddThreadNetworkCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::AddWiFiNetwork::Id: { Commands::AddWiFiNetwork::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfNetworkCommissioningClusterAddWiFiNetworkCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::DisableNetwork::Id: { Commands::DisableNetwork::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfNetworkCommissioningClusterDisableNetworkCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::EnableNetwork::Id: { Commands::EnableNetwork::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfNetworkCommissioningClusterEnableNetworkCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::GetLastNetworkCommissioningResult::Id: { Commands::GetLastNetworkCommissioningResult::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfNetworkCommissioningClusterGetLastNetworkCommissioningResultCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::RemoveNetwork::Id: { Commands::RemoveNetwork::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfNetworkCommissioningClusterRemoveNetworkCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::ScanNetworks::Id: { Commands::ScanNetworks::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfNetworkCommissioningClusterScanNetworksCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::UpdateThreadNetwork::Id: { Commands::UpdateThreadNetwork::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfNetworkCommissioningClusterUpdateThreadNetworkCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::UpdateWiFiNetwork::Id: { Commands::UpdateWiFiNetwork::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfNetworkCommissioningClusterUpdateWiFiNetworkCallback(apCommandObj, aCommandPath, commandData); } break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aCommandPath); return; } } } if (CHIP_NO_ERROR != TLVError || !wasHandled) { apCommandObj->AddStatus(aCommandPath, Protocols::InteractionModel::Status::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, TLVError=%" CHIP_ERROR_FORMAT, TLVError.Format()); } } } // namespace NetworkCommissioning namespace OnOff { void DispatchServerCommand(CommandHandler * apCommandObj, const ConcreteCommandPath & aCommandPath, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; bool wasHandled = false; { switch (aCommandPath.mCommandId) { case Commands::Off::Id: { Commands::Off::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfOnOffClusterOffCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::On::Id: { Commands::On::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfOnOffClusterOnCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::Toggle::Id: { Commands::Toggle::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfOnOffClusterToggleCallback(apCommandObj, aCommandPath, commandData); } break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aCommandPath); return; } } } if (CHIP_NO_ERROR != TLVError || !wasHandled) { apCommandObj->AddStatus(aCommandPath, Protocols::InteractionModel::Status::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, TLVError=%" CHIP_ERROR_FORMAT, TLVError.Format()); } } } // namespace OnOff namespace OperationalCredentials { void DispatchServerCommand(CommandHandler * apCommandObj, const ConcreteCommandPath & aCommandPath, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; bool wasHandled = false; { switch (aCommandPath.mCommandId) { case Commands::AddNOC::Id: { Commands::AddNOC::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfOperationalCredentialsClusterAddNOCCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::AddTrustedRootCertificate::Id: { Commands::AddTrustedRootCertificate::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfOperationalCredentialsClusterAddTrustedRootCertificateCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::AttestationRequest::Id: { Commands::AttestationRequest::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfOperationalCredentialsClusterAttestationRequestCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::CertificateChainRequest::Id: { Commands::CertificateChainRequest::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfOperationalCredentialsClusterCertificateChainRequestCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::OpCSRRequest::Id: { Commands::OpCSRRequest::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfOperationalCredentialsClusterOpCSRRequestCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::RemoveFabric::Id: { Commands::RemoveFabric::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfOperationalCredentialsClusterRemoveFabricCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::RemoveTrustedRootCertificate::Id: { Commands::RemoveTrustedRootCertificate::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfOperationalCredentialsClusterRemoveTrustedRootCertificateCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::UpdateFabricLabel::Id: { Commands::UpdateFabricLabel::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfOperationalCredentialsClusterUpdateFabricLabelCallback(apCommandObj, aCommandPath, commandData); } break; } case Commands::UpdateNOC::Id: { Commands::UpdateNOC::DecodableType commandData; TLVError = DataModel::Decode(aDataTlv, commandData); if (TLVError == CHIP_NO_ERROR) { wasHandled = emberAfOperationalCredentialsClusterUpdateNOCCallback(apCommandObj, aCommandPath, commandData); } break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aCommandPath); return; } } } if (CHIP_NO_ERROR != TLVError || !wasHandled) { apCommandObj->AddStatus(aCommandPath, Protocols::InteractionModel::Status::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, TLVError=%" CHIP_ERROR_FORMAT, TLVError.Format()); } } } // namespace OperationalCredentials } // namespace Clusters void DispatchSingleClusterCommand(const ConcreteCommandPath & aCommandPath, TLV::TLVReader & aReader, CommandHandler * apCommandObj) { ChipLogDetail(Zcl, "Received Cluster Command: Endpoint=%" PRIx16 " Cluster=" ChipLogFormatMEI " Command=" ChipLogFormatMEI, aCommandPath.mEndpointId, ChipLogValueMEI(aCommandPath.mClusterId), ChipLogValueMEI(aCommandPath.mCommandId)); Compatibility::SetupEmberAfObjects(apCommandObj, aCommandPath); switch (aCommandPath.mClusterId) { case Clusters::AdministratorCommissioning::Id: Clusters::AdministratorCommissioning::DispatchServerCommand(apCommandObj, aCommandPath, aReader); break; case Clusters::DiagnosticLogs::Id: Clusters::DiagnosticLogs::DispatchServerCommand(apCommandObj, aCommandPath, aReader); break; case Clusters::GeneralCommissioning::Id: Clusters::GeneralCommissioning::DispatchServerCommand(apCommandObj, aCommandPath, aReader); break; case Clusters::LevelControl::Id: Clusters::LevelControl::DispatchServerCommand(apCommandObj, aCommandPath, aReader); break; case Clusters::NetworkCommissioning::Id: Clusters::NetworkCommissioning::DispatchServerCommand(apCommandObj, aCommandPath, aReader); break; case Clusters::OnOff::Id: Clusters::OnOff::DispatchServerCommand(apCommandObj, aCommandPath, aReader); break; case Clusters::OperationalCredentials::Id: Clusters::OperationalCredentials::DispatchServerCommand(apCommandObj, aCommandPath, aReader); break; default: ChipLogError(Zcl, "Unknown cluster " ChipLogFormatMEI, ChipLogValueMEI(aCommandPath.mClusterId)); apCommandObj->AddStatus(aCommandPath, Protocols::InteractionModel::Status::UnsupportedCluster); break; } Compatibility::ResetEmberAfObjects(); } void DispatchSingleClusterResponseCommand(const ConcreteCommandPath & aCommandPath, TLV::TLVReader & aReader, CommandSender * apCommandObj) { ChipLogDetail(Zcl, "Received Cluster Command: Endpoint=%" PRIx16 " Cluster=" ChipLogFormatMEI " Command=" ChipLogFormatMEI, aCommandPath.mEndpointId, ChipLogValueMEI(aCommandPath.mClusterId), ChipLogValueMEI(aCommandPath.mCommandId)); Compatibility::SetupEmberAfObjects(apCommandObj, aCommandPath); TLV::TLVType dataTlvType; SuccessOrExit(aReader.EnterContainer(dataTlvType)); switch (aCommandPath.mClusterId) { default: ChipLogError(Zcl, "Unknown cluster " ChipLogFormatMEI, ChipLogValueMEI(aCommandPath.mClusterId)); apCommandObj->AddStatus(aCommandPath, Protocols::InteractionModel::Status::UnsupportedCluster); break; } exit: aReader.ExitContainer(dataTlvType); Compatibility::ResetEmberAfObjects(); } } // namespace app } // namespace chip
#include <service/endpoint_state.hpp> #include <exit/session.hpp> #include <hook/shell.hpp> #include <service/endpoint.hpp> #include <service/outbound_context.hpp> #include <util/str.hpp> namespace llarp { namespace service { bool EndpointState::SetOption(const std::string& k, const std::string& v, Endpoint& ep) { const auto name = ep.Name(); if(k == "keyfile") { m_Keyfile = v; } if(k == "tag") { m_Tag = v; LogInfo("Setting tag to ", v); } if(k == "prefetch-tag") { m_PrefetchTags.insert(v); } if(k == "prefetch-addr") { Address addr; if(addr.FromString(v)) m_PrefetchAddrs.insert(addr); } if(k == "min-latency") { const auto val = atoi(v.c_str()); if(val > 0) m_MinPathLatency = std::chrono::milliseconds(val); } if(k == "paths") { const auto val = atoi(v.c_str()); if(val >= 1 && val <= static_cast< int >(path::PathSet::max_paths)) { ep.numPaths = val; LogInfo(name, " set number of paths to ", ep.numHops); } else { LogWarn(name, " invalid number of paths: ", v); } } if(k == "hops") { const auto val = atoi(v.c_str()); if(val >= 1 && val <= static_cast< int >(path::max_len)) { ep.numHops = val; LogInfo(name, " set number of hops to ", ep.numHops); } else { LogWarn(name, " invalid number of hops: ", v); } } if(k == "bundle-rc") { m_BundleRC = IsTrueValue(v.c_str()); } if(k == "blacklist-snode") { RouterID snode; if(!snode.FromString(v)) { LogError(name, " invalid snode value: ", v); return false; } const auto result = m_SnodeBlacklist.insert(snode); if(!result.second) { LogError(name, " duplicate blacklist-snode: ", snode.ToString()); return false; } LogInfo(name, " adding ", snode.ToString(), " to blacklist"); } if(k == "on-up") { m_OnUp = hooks::ExecShellBackend(v); if(m_OnUp) LogInfo(name, " added on up script: ", v); else LogError(name, " failed to add on up script"); } if(k == "on-down") { m_OnDown = hooks::ExecShellBackend(v); if(m_OnDown) LogInfo(name, " added on down script: ", v); else LogError(name, " failed to add on down script"); } if(k == "on-ready") { m_OnReady = hooks::ExecShellBackend(v); if(m_OnReady) LogInfo(name, " added on ready script: ", v); else LogError(name, " failed to add on ready script"); } return true; } util::StatusObject EndpointState::ExtractStatus(util::StatusObject& obj) const { obj["lastPublished"] = to_json(m_LastPublish); obj["lastPublishAttempt"] = to_json(m_LastPublishAttempt); obj["introset"] = m_IntroSet.ExtractStatus(); if(!m_Tag.IsZero()) { obj["tag"] = m_Tag.ToString(); } static auto getSecond = [](const auto& item) -> auto { return item.second->ExtractStatus(); }; std::transform(m_DeadSessions.begin(), m_DeadSessions.end(), std::back_inserter(obj["deadSessions"]), getSecond); std::transform(m_RemoteSessions.begin(), m_RemoteSessions.end(), std::back_inserter(obj["remoteSessions"]), getSecond); std::transform(m_PendingLookups.begin(), m_PendingLookups.end(), std::back_inserter(obj["lookups"]), getSecond); std::transform( m_SNodeSessions.begin(), m_SNodeSessions.end(), std::back_inserter(obj["snodeSessions"]), [](const auto& item) { return item.second.first->ExtractStatus(); }); util::StatusObject sessionObj{}; for(const auto& item : m_Sessions) { std::string k = item.first.ToHex(); sessionObj[k] = item.second.ExtractStatus(); } obj["converstations"] = sessionObj; return obj; } } // namespace service } // namespace llarp
; A033567: a(n) = (2*n-1)*(4*n-1). ; 1,3,21,55,105,171,253,351,465,595,741,903,1081,1275,1485,1711,1953,2211,2485,2775,3081,3403,3741,4095,4465,4851,5253,5671,6105,6555,7021,7503,8001,8515,9045,9591,10153,10731,11325,11935,12561,13203,13861,14535,15225,15931,16653,17391,18145,18915,19701,20503,21321,22155,23005,23871,24753,25651,26565,27495,28441,29403,30381,31375,32385,33411,34453,35511,36585,37675,38781,39903,41041,42195,43365,44551,45753,46971,48205,49455,50721,52003,53301,54615,55945,57291,58653,60031,61425,62835,64261,65703 mov $1,4 mul $1,$0 sub $1,1 bin $1,2 mov $0,$1
; ; S-OS specific routines ; by Stefano Bodrato, 2013 ; ; Set the current S-OS file name and type ; ; ; int sos_file(char *name,type) ; ; ; $Id: sos_file_callee.asm,v 1.5 2016-06-19 20:58:00 dom Exp $ ; SECTION code_clib PUBLIC sos_file_callee PUBLIC _sos_file_callee PUBLIC asm_sos_file sos_file_callee: _sos_file_callee: pop bc pop hl pop de push bc ; enter : dl = *name ; l = type .asm_sos_file ;jr asmentry ld a,l call $1fa3 ld hl,0 ; return code, nothing (yet) implemented ret
/** * @file LinkedList.hpp * @brief The main header file for the LinkedList Class */ #ifndef _LINKED_LIST_HPP_ #define _LINKED_LIST_HPP_ struct LLNode { int key; LLNode *next; }; class LinkedList { private: LLNode *head; public: LinkedList(); ~LinkedList(); void insert(LLNode *prev, int newKey); // Inserts after prev void insert(int newKey); // Inserts at the end of the list LLNode *search(int key); // Searches linked list void displayAll(); // Displays all LLNodes in the list void displayFirst100(); // Displays the first 100 LLNodes in the list }; #endif
ASSUME CS: code, DS:data ; 8. Print of the screen, for each number between 32 and 126, the value ; of the number (in base 10) and the character whose ASCII code the number is. data SEGMENT public i_start DB 32 i_end DB 126 data ENDS code SEGMENT public ; import print procedure extrn print:proc start: mov AX, data mov DS, AX repeat: mov AL, i_start call print inc i_start cmp AL, i_end jne repeat end_start: mov AX, 4C00h ; function 4C with exit code 0 int 21h code ENDS END start
; A119479: Length of longest run of consecutive integers having exactly n divisors. ; 1,2,1,3,1,5,1,7,1,3,1 pow $0,2 mov $2,$0 lpb $0 div $0,2 add $3,$2 mov $4,$0 cmp $4,0 add $0,$4 gcd $0,$3 sub $2,1 mul $0,$2 add $1,7 lpe div $1,7 add $1,1 mov $0,$1
;************************************************************************** ;* ;* FILE runner.asm ;* Copyright (c) 1994, 2001, 2003 Daniel Kahlin <daniel@kahlin.net> ;* Written by Daniel Kahlin <daniel@kahlin.net> ;* $Id: runner.asm,v 1.12 2003/08/26 16:51:38 tlr Exp $ ;* ;* DESCRIPTION ;* runner for packed vic-tracker tunes. Uses player.asm. ;* Works on both unexpanded and expanded VIC-20s. ;* ;****** PROCESSOR 6502 ; song configuration. NUMSONGS EQU @NUMSONGS@ TITLE EQM @TITLE@ AUTHOR EQM @AUTHOR@ VERSION EQM @VERSION@ IFNCONST RN_VTCOMP ; modes ;RN_DEBUG EQU 1 ;RN_DEBUG EQU 1 RN_UNEXP EQU 1 RN_SPEED_1X EQU 1 ;RN_SPEED_2X EQU 1 ;RN_SPEED_3X EQU 1 ;RN_SPEED_4X EQU 1 ENDIF ;RN_VTCOMP ; macros MAC HEXDIGIT IFCONST [{1}] IF [{1}]<10 dc.b "0"+[{1}] ELSE dc.b "A"+[{1}]-10 ENDIF ELSE dc.b "x" ENDIF ENDM MAC HEXWORD HEXDIGIT [{1}]>>12 HEXDIGIT [[{1}]>>8]&$0f HEXDIGIT [[{1}]>>4]&$0f HEXDIGIT [{1}]&$0f ENDM BorderColor EQU 6 BorderColor_Play EQU 3 BackgroundColor EQU 14 NormalColor EQU [BackgroundColor<<4]+BorderColor+8 PlayColor EQU [BackgroundColor<<4]+BorderColor_Play+8 INFO_POS EQU 7 INFO_HEIGHT EQU 6 BONUS_POS EQU 15 IFCONST RN_DEBUG SCROLL_POS EQU 15 SCROLL_HEIGHT EQU 7 DATA_POS EQU 0 ENDIF ;RN_DEBUG ;the length of a screen in cycles (PAL) SCREENTIME_PAL EQU 22150 ;the length of a screen in cycles (NTSC) SCREENTIME_NTSC EQU 16963 IFCONST RN_SPEED_1X STARTLINE EQU 74+8*6 STARTLINE_PAL EQU STARTLINE STARTLINE_NTSC EQU STARTLINE-24 ENDIF ;RN_SPEED_1X IFCONST RN_SPEED_2X SCREENTIMETWO_PAL EQU SCREENTIME_PAL/2 SCREENTIMETWO_NTSC EQU SCREENTIME_NTSC/2 INT_TIMES EQU 1 STARTLINE EQU 74+8*2 STARTLINE_PAL EQU STARTLINE STARTLINE_NTSC EQU STARTLINE-24 ENDIF ;RN_SPEED_2X IFCONST RN_SPEED_3X SCREENTIMETWO_PAL EQU SCREENTIME_PAL/3 SCREENTIMETWO_NTSC EQU SCREENTIME_NTSC/3 INT_TIMES EQU 2 STARTLINE EQU 74-8*2 STARTLINE_PAL EQU STARTLINE STARTLINE_NTSC EQU STARTLINE-24 ENDIF ;RN_SPEED_3X IFCONST RN_SPEED_4X SCREENTIMETWO_PAL EQU SCREENTIME_PAL/4 SCREENTIMETWO_NTSC EQU SCREENTIME_NTSC/4 INT_TIMES EQU 3 STARTLINE EQU 34 STARTLINE_PAL EQU STARTLINE STARTLINE_NTSC EQU STARTLINE-24 ENDIF ;RN_SPEED_4X IFCONST RN_UNEXP rn_ScreenRAM EQU $1e00 rn_ColorRAM EQU $9600 ELSE ;!RN_UNEXP rn_ScreenRAM EQU $1000 rn_ColorRAM EQU $9400 ENDIF ;RN_UNEXP rn_CopyZP EQU $fb ;only used during copy down rn_ScreenZP EQU $d1 rn_ColorZP EQU $fd rn_YPosZP EQU $ff rn_YTempZP EQU $fb rn_XTempZP EQU $fc seg code org $1201 ; Normal 8,16,24Kb basic starting point rn_LoadStart: ;************************************************************************** ;* ;* Basic line! ;* ;****** TOKEN_SYS EQU $9e TOKEN_PEEK EQU $c2 TOKEN_PLUS EQU $aa TOKEN_TIMES EQU $ac StartOfFile: dc.w EndLine dc.w 2003 dc.b TOKEN_SYS,"(",TOKEN_PEEK,"(43)",TOKEN_PLUS,"256",TOKEN_TIMES,TOKEN_PEEK,"(44)",TOKEN_PLUS,"36) /T.L.R/",0 ; 2003 SYS(PEEK(43)+256*PEEK(44)+36) /T.L.R/ EndLine: dc.w 0 ;************************************************************************** ;* ;* SysAddress... When run we will enter here! ;* ;****** startoffset EQU cp_store-StartOfFile endoffset EQU startoffset+(cp_end-cp_start) startoffset2 EQU rn_MainStart_st-StartOfFile SysAddress: sei ldy #startoffset sa_lp1: lda ($2b),y sta cp_start-startoffset,y iny cpy #endoffset bne sa_lp1 lda $2b clc adc #<startoffset2 sta rn_CopyZP lda $2c adc #>startoffset2 sta rn_CopyZP+1 jmp cp_start cp_store: rorg $200 cp_start: ldy #0 cp_lp1: lda (rn_CopyZP),y cp_lp2: sta rn_Main,y iny bne cp_skp1 inc rn_CopyZP+1 inc cp_lp2+2 cp_skp1: lda cp_lp2+2 cmp #>rn_MainEnd bne cp_lp1 cpy #<rn_MainEnd bne cp_lp1 jmp rn_Main cp_end: rend echo "copydown", cp_start, "-", cp_end rn_MainStart_st: IFCONST RN_UNEXP rorg $1000 ELSE ;RN_UNEXP rorg $1200 ENDIF ;RN_UNEXP ;************************************************************************** ;* ;* This is the main program! ;* ;****** rn_Main: jsr InterruptInit jsr rn_InitScreen rn_Restart: lda #0 sta pl_PlayFlag rn_mn_Toggle: lda pl_PlayFlag pha lda rn_ThisSong jsr pl_Init pla eor #$ff sta pl_PlayFlag beq rn_mn_lp1 lda #0 sta rn_MaxLines rn_mn_lp1: jsr $ffe4 beq rn_mn_lp1 cmp #" " beq rn_mn_Toggle cmp #"P" beq rn_mn_Toggle cmp #"M" beq rn_Restart cmp #"1" ;Less than "1" bcc rn_mn_lp1 ;yes, loop. cmp #"1"+NUMSONGS ;Greater than NUMSONGS bcs rn_mn_lp1 ;yes, loop. rn_mn_StartSong: sec sbc #"1" sta rn_ThisSong jmp rn_Restart ;************************************************************************** ;* ;* Initialize Interrupts! ;* ;****** InterruptInit: sei lda #$7f sta $912e sta $912d lda #%11000000 ; T1 Interrupt Enabled sta $912e lda #%01000000 sta $912b lda #<IRQServer sta $0314 lda #>IRQServer sta $0315 jsr CheckPAL php IFNCONST RN_SPEED_1X ldx #<SCREENTIMETWO_PAL ldy #>SCREENTIMETWO_PAL stx Int_CurCycles sty Int_CurCycles+1 ENDIF ;RN_SPEED_1X ldx #<SCREENTIME_PAL ldy #>SCREENTIME_PAL lda #STARTLINE_PAL/2 plp bne ii_skp1 IFNCONST RN_SPEED_1X ldx #<SCREENTIMETWO_NTSC ldy #>SCREENTIMETWO_NTSC stx Int_CurCycles sty Int_CurCycles+1 ENDIF ;RN_SPEED_1X ldx #<SCREENTIME_NTSC ldy #>SCREENTIME_NTSC lda #STARTLINE_NTSC/2 ii_skp1: jsr WaitLine stx $9124 sty $9125 ;load T1 cli rts ;************************************************************************** ;* ;* CheckPAL ;* Returns: Acc=0 on NTSC-M systems, Acc!=0 on PAL-B systems ;* ;****** CheckPAL: ; find raster line 2 lda #2/2 cpl_lp1: cmp $9004 bne cpl_lp1 ; now we know that we are past raster line 0, see if we find raster line 268 ; before we find raster line 0 cpl_lp2: lda $9004 beq cpl_ex1 cmp #268/2 ; This line does not exist on NTSC. bne cpl_lp2 cpl_ex1: cmp #0 ; test Acc; rts ;************************************************************************** ;* ;* Wait until line ACC is passed ;* ;****** WaitLine: wl_lp1: cmp $9004 bne wl_lp1 wl_lp2: cmp $9004 beq wl_lp2 rts ;************************************************************************** ;* ;* IRQ Interrupt server ;* ;****** IRQServer: lda $912d asl asl bcs irq_skp1 ;Did T1 time out? IFNCONST RN_SPEED_1X asl bcs irq_skp2 ;Did T2 time out? ENDIF ;RN_SPEED_1X jmp $eabf IFNCONST RN_SPEED_1X irq_skp2: dec Int_Count bmi irq_skp3 ; Last Interrupt? lda Int_CurCycles sta $9128 lda Int_CurCycles+1 sta $9129 ;load T2 irq_skp3: lda $9128 ;ACK T2 interrupt. jsr rn_Frame ;Yes, run player. jmp $eb18 ;Just pulls the registers ENDIF ;RN_SPEED_1X irq_skp1: IFNCONST RN_SPEED_1X lda Int_CurCycles sta $9128 lda Int_CurCycles+1 sta $9129 ;load T2 lda #INT_TIMES sta Int_Count lda #%11100000 ;T1 Interrupt + T2 Interrupt sta $912e lda $9124 ;ACK T1 interrupt. cli ;Enable nesting ENDIF ;RN_SPEED_1X jsr rn_Frame ;Yes, run player. lda $9124 ;ACK T1 interrupt. irq_ex1: jmp $eabf IFNCONST RN_SPEED_1X Int_CurCycles: dc.w 0 Int_CurTimes: dc.b 0 Int_Count: dc.b 0 ENDIF ;RN_SPEED_1X ;************************************************************************** ;* ;* Interrupt Routine ;* This gets called every frame! ;* ;****** rn_Frame: lda #PlayColor sta $900f lda $9004 ;Rasterline sta rn_Lines jsr pl_Play lda $9004 ;Rasterline sec sbc rn_Lines asl ; multiply by two sta rn_Lines cmp rn_MaxLines bcc rn_fr_skp2 sta rn_MaxLines rn_fr_skp2: ; if we are not playing, wait a while to ensure that the color is visible lda pl_PlayFlag bne rn_fr_skp1 ldx #10 rn_fr_lp1: dex bne rn_fr_lp1 rn_fr_skp1: lda #NormalColor sta $900f jsr rn_ShowData IFCONST RN_DEBUG lda pl_Count cmp pl_Speed bne rn_fr_ex1 ldx #0 rn_fr_lp2: lda rn_ScreenRAM+[22*[SCROLL_POS+1]],x sta rn_ScreenRAM+[22*[SCROLL_POS]],x inx cpx #22*6 bne rn_fr_lp2 jsr rn_UpdateScroll rn_fr_ex1: ENDIF ;RN_DEBUG rts ;************************************************************************** ;* ;* This displays all other data! ;* ;****** rn_ShowData: ;Show number of raster lines ldx #<[rn_ScreenRAM+[22*[INFO_POS+5]]] ldy #>[rn_ScreenRAM+[22*[INFO_POS+5]]] jsr rn_ScreenPtr ldy #9 sty rn_YPosZP lda rn_Lines jsr rn_PutHex ldy #18 sty rn_YPosZP lda rn_MaxLines jsr rn_PutHex IFCONST RN_DEBUG ldx #<[rn_ScreenRAM+[22*DATA_POS]] ldy #>[rn_ScreenRAM+[22*DATA_POS]] jsr rn_ScreenPtr ;Show a selection of internal player parameters ldy #[22*0+3] sty rn_YPosZP ldx #0 rn_sd_lp1: lda pl_vd_PattlistStep,x jsr rn_PutHex lda pl_vd_FetchMode,x jsr rn_PutHex lda pl_vd_CurrentPattern,x jsr rn_PutHex lda pl_vd_PatternStep,x jsr rn_PutHex lda pl_vd_FreqOffsetLow,x jsr rn_PutHex lda pl_vd_FreqOffsetHigh,x jsr rn_PutHex lda pl_vd_ArpStep,x jsr rn_PutHex lda pl_vd_ArpOffset,x jsr rn_PutHex lda rn_YPosZP clc adc #6 sta rn_YPosZP inx cpx #5 bne rn_sd_lp1 rts IFCONST RN_DEBUG ENDIF ;RN_DEBUG rn_UpdateScroll: ldx #<[rn_ScreenRAM+[22*[SCROLL_POS+SCROLL_HEIGHT-1]]] ldy #>[rn_ScreenRAM+[22*[SCROLL_POS+SCROLL_HEIGHT-1]]] jsr rn_ScreenPtr ;Handle update of the scroller ldy #1 sty rn_YPosZP ldx #0 rn_sd_lp4: lda pl_vd_Note,x jsr rn_PutHex lda pl_vd_Param,x jsr rn_PutHex inx cpx #5 bne rn_sd_lp4 rts ENDIF ;RN_DEBUG rn_ScreenPtr: stx rn_ScreenZP sty rn_ScreenZP+1 rts rn_PutHex: sty rn_YTempZP stx rn_XTempZP pha lsr lsr lsr lsr jsr rn_ph_Put pla and #$0f jsr rn_ph_Put ldx rn_XTempZP ldy rn_YTempZP rts rn_ph_Put: tax ldy rn_YPosZP lda rn_HexTab,x sta (rn_ScreenZP),y inc rn_YPosZP rts rn_HexTab: dc.b "0123456789",1,2,3,4,5,6 rn_ThisSong: dc.b 0 rn_Lines: dc.b 0 rn_MaxLines: dc.b 0 rn_InitScreen: IFCONST RN_UNEXP ; screenmem at $1e00, colormem at $9600 lda $9002 ora #$80 sta $9002 lda #$f0 sta $9005 ELSE ;RN_UNEXP ; screenmem at $1000, colormem at $9400 lda $9002 and #$7f sta $9002 lda #$c0 sta $9005 ENDIF ;!RN_UNEXP lda #NormalColor sta $900f ldx #0 rn_is_lp1: lda #$a0 sta rn_ScreenRAM,x sta rn_ScreenRAM+$100,x lda #6 sta rn_ColorRAM,x sta rn_ColorRAM+$100,x inx bne rn_is_lp1 IFCONST RN_DEBUG lda #>[rn_ColorRAM+[22*SCROLL_POS]] sta rn_ColorZP+1 lda #<[rn_ColorRAM+[22*SCROLL_POS]] sta rn_ColorZP ldx #SCROLL_HEIGHT-1 rn_is_lp2: ldy #21 rn_is_lp3: lda rn_ColorTab,y sta (rn_ColorZP),y dey bpl rn_is_lp3 lda rn_ColorZP clc adc #22 sta rn_ColorZP bcc rn_is_skp1 inc rn_ColorZP+1 rn_is_skp1: dex bpl rn_is_lp2 ENDIF ;RN_DEBUG ldx #22-1 rn_is_lp4: lda #$20 sta rn_ScreenRAM+22*6,x sta rn_ScreenRAM+22*13,x lda rn_Bonus_MSG,x and #$3f ora #$80 sta rn_ScreenRAM+22*BONUS_POS,x dex bpl rn_is_lp4 ldx #22*INFO_HEIGHT rn_is_lp5: lda rn_Info_MSG-1,x and #$3f sta rn_ScreenRAM+22*INFO_POS-1,x lda #1 sta rn_ColorRAM+22*INFO_POS-1,x dex bne rn_is_lp5 rts rn_Info_MSG: ; line1 dc.b "TITLE : " dc.b TITLE ; line2 dc.b "AUTHOR: " dc.b AUTHOR ; line3 dc.b "SONGS : " HEXDIGIT NUMSONGS IF NUMSONGS>1 dc.b " (1-" HEXDIGIT NUMSONGS dc.b ") " ELSE dc.b " " ENDIF ; line4 dc.b "ADDR : $" HEXWORD start dc.b "-$" HEXWORD end dc.b " " ; line5 dc.b "LENGTH: $" HEXWORD end-start dc.b " " ; line6 dc.b "LINES : $00 (MAX $00) " rn_Bonus_MSG: dc.b " VIC-PLAYER " dc.b VERSION dc.b " " IFCONST RN_DEBUG rn_ColorTab: dc.b 6,2,2,2,2,6,6,6,6,2,2,2,2,6,6,6,6,2,2,2,2,6 ENDIF ;RN_DEBUG IFNCONST RN_UNEXP align 256 ENDIF ;RN_UNEXP start: include @FILE@ end: rn_MainEnd: rend rn_LoadEnd: echo "Player: ",start,"-",end,"(=",end-start,"bytes,",(end-start+253)/254,"blocks)" echo "Load: ",rn_LoadStart,"-",rn_LoadEnd,"(=",rn_LoadEnd-rn_LoadStart,"bytes,",(rn_LoadEnd-rn_LoadStart+253)/254,"blocks)" ; eof
; A168489: Numbers that are congruent to {7,11} mod 12. ; 7,11,19,23,31,35,43,47,55,59,67,71,79,83,91,95,103,107,115,119,127,131,139,143,151,155,163,167,175,179,187,191,199,203,211,215,223,227,235,239,247,251,259,263,271,275,283,287,295,299,307,311,319,323,331,335,343,347,355,359,367,371,379,383,391,395,403,407,415,419,427,431,439,443,451,455,463,467,475,479,487,491,499,503,511,515,523,527,535,539,547,551,559,563,571,575,583,587,595,599,607,611,619,623,631,635,643,647,655,659,667,671,679,683,691,695,703,707,715,719,727,731,739,743,751,755,763,767,775,779,787,791,799,803,811,815,823,827,835,839,847,851,859,863,871,875,883,887,895,899,907,911,919,923,931,935,943,947,955,959,967,971,979,983,991,995,1003,1007,1015,1019,1027,1031,1039,1043,1051,1055,1063,1067,1075,1079,1087,1091,1099,1103,1111,1115,1123,1127,1135,1139,1147,1151,1159,1163,1171,1175,1183,1187,1195,1199,1207,1211,1219,1223,1231,1235,1243,1247,1255,1259,1267,1271,1279,1283,1291,1295,1303,1307,1315,1319,1327,1331,1339,1343,1351,1355,1363,1367,1375,1379,1387,1391,1399,1403,1411,1415,1423,1427,1435,1439,1447,1451,1459,1463,1471,1475,1483,1487,1495,1499 mul $0,6 mov $1,$0 div $1,4 mul $1,4 add $1,7
; ; Disk routines for MSDOS ; INCLUDE DOSSEG.ASM CODE SEGMENT BYTE PUBLIC 'CODE' ASSUME SS:DOSGROUP,CS:DOSGROUP .xlist .xcref INCLUDE DOSSYM.ASM INCLUDE DEVSYM.ASM .cref .list TITLE DISK - Disk utility routines NAME Disk i_need COUTDSAV,BYTE i_need COUTSAV,DWORD i_need CINDSAV,BYTE i_need CINSAV,DWORD i_need CONSWAP,BYTE i_need IDLEINT,BYTE i_need THISFCB,DWORD i_need DMAADD,DWORD i_need DEVCALL,BYTE i_need CALLSCNT,WORD i_need CALLXAD,DWORD i_need CONTPOS,WORD i_need NEXTADD,WORD i_need CONBUF,BYTE i_need User_SS,WORD i_need User_SP,WORD i_need DSKStack,BYTE i_need InDOS,BYTE i_need NumIO,BYTE i_need CurDrv,BYTE i_need ThisDrv,BYTE i_need ClusFac,BYTE i_need SecClusPos,BYTE i_need DirSec,WORD i_need ClusNum,WORD i_need NxtClusNum,WORD i_need ReadOp,BYTE i_need DskErr,BYTE i_need RecCnt,WORD i_need RecPos,4 i_need Trans,BYTE i_need BytPos,4 i_need SecPos,WORD i_need BytSecPos,WORD i_need BytCnt1,WORD i_need BytCnt2,WORD i_need SecCnt,WORD i_need ThisDPB,DWORD i_need LastPos,WORD i_need ValSec,WORD i_need GrowCnt,DWORD SUBTTL LOAD -- MAIN READ ROUTINE AND DEVICE IN ROUTINES PAGE ; * * * * Drivers for file input from devices * * * * procedure SWAPBACK,NEAR ASSUME DS:DOSGROUP,ES:NOTHING PUSH ES PUSH DI PUSH SI PUSH BX MOV BX,1 invoke get_sf_from_jfn ADD DI,sf_fcb MOV BL,BYTE PTR [COUTDSAV] LDS SI,[COUTSAV] ASSUME DS:NOTHING MOV WORD PTR ES:[DI.fcb_FIRCLUS],SI MOV WORD PTR ES:[DI.fcb_FIRCLUS+2],DS MOV ES:[DI.fcb_DEVID],BL PUSH SS POP DS ASSUME DS:DOSGROUP XOR BX,BX invoke get_sf_from_jfn ADD DI,sf_fcb MOV BL,BYTE PTR [CINDSAV] LDS SI,[CINSAV] ASSUME DS:NOTHING MOV WORD PTR ES:[DI.fcb_FIRCLUS],SI MOV WORD PTR ES:[DI.fcb_FIRCLUS+2],DS MOV ES:[DI.fcb_DEVID],BL PUSH SS POP DS ASSUME DS:DOSGROUP MOV BYTE PTR [CONSWAP],0 MOV BYTE PTR [IDLEINT],1 SWAPRET: POP BX POP SI POP DI POP ES return SWAPBACK ENDP procedure SWAPCON,NEAR ASSUME DS:DOSGROUP,ES:NOTHING PUSH ES PUSH DI PUSH SI PUSH BX MOV BYTE PTR [CONSWAP],1 MOV BYTE PTR [IDLEINT],0 XOR BX,BX invoke get_sf_from_jfn ADD DI,sf_fcb MOV BL,ES:[DI.fcb_DEVID] MOV BYTE PTR [CINDSAV],BL LDS SI,DWORD PTR ES:[DI.fcb_FIRCLUS] ASSUME DS:NOTHING MOV WORD PTR [CINSAV],SI MOV WORD PTR [CINSAV+2],DS LDS SI,[THISFCB] MOV BL,[SI.fcb_DEVID] LDS SI,DWORD PTR [SI.fcb_FIRCLUS] MOV ES:[DI.fcb_DEVID],BL MOV WORD PTR ES:[DI.fcb_FIRCLUS],SI MOV WORD PTR ES:[DI.fcb_FIRCLUS+2],DS PUSH SS POP DS ASSUME DS:DOSGROUP MOV BX,1 invoke get_sf_from_jfn ADD DI,sf_fcb MOV BL,ES:[DI.fcb_DEVID] MOV BYTE PTR [COUTDSAV],BL LDS SI,DWORD PTR ES:[DI.fcb_FIRCLUS] ASSUME DS:NOTHING MOV WORD PTR [COUTSAV],SI MOV WORD PTR [COUTSAV+2],DS LDS SI,[THISFCB] MOV BL,[SI.fcb_DEVID] LDS SI,DWORD PTR [SI.fcb_FIRCLUS] MOV ES:[DI.fcb_DEVID],BL MOV WORD PTR ES:[DI.fcb_FIRCLUS],SI MOV WORD PTR ES:[DI.fcb_FIRCLUS+2],DS PUSH SS POP DS JMP SWAPRET SWAPCON ENDP procedure LOAD,NEAR ASSUME DS:NOTHING,ES:NOTHING ; ; Inputs: ; DS:DI point to FCB ; DX:AX = Position in file to read ; CX = No. of records to read ; Outputs: ; DX:AX = Position of last record read ; CX = No. of bytes read ; ES:DI point to FCB ; fcb_LSTCLUS, fcb_CLUSPOS fields in FCB set call SETUP ASSUME DS:DOSGROUP OR BL,BL ; Check for named device I/O JS READDEV call DISKREAD return READDEV: ASSUME DS:DOSGROUP,ES:NOTHING LES DI,[DMAADD] TEST BL,40H ; End of file? JZ ENDRDDEVJ3 TEST BL,ISNULL ; NUL device? JZ TESTRAW ; NO XOR AL,AL ; Indicate EOF ENDRDDEVJ3: JMP ENDRDDEVJ2 DVRDRAW: ASSUME DS:DOSGROUP PUSH ES POP DS ASSUME DS:NOTHING DVRDRAWR: MOV BX,DI ; DS:BX transfer addr XOR DX,DX ; Start at 0 XOR AX,AX ; Media Byte, unit = 0 invoke SETREAD LDS SI,[THISFCB] invoke DEVIOCALL MOV DX,DI ; DX is preserved by INT 24 MOV AH,86H ; Read error MOV DI,[DEVCALL.REQSTAT] TEST DI,STERR JZ CRDROK ; No errors invoke CHARHARD MOV DI,DX CMP AL,1 JZ DVRDRAWR ; Retry CRDROK: MOV DI,DX ADD DI,[CALLSCNT] ; Amount transferred JMP SHORT ENDRDDEVJ2 TESTRAW: TEST BL,020H ; Raw mode? JNZ DVRDRAW TEST BL,ISCIN ; Is it console device? JZ NOTRDCON JMP READCON NOTRDCON: MOV AX,ES MOV DS,AX ASSUME DS:NOTHING MOV BX,DI XOR DX,DX MOV AX,DX PUSH CX MOV CX,1 invoke SETREAD POP CX LDS SI,[THISFCB] LDS SI,DWORD PTR [SI.fcb_FIRCLUS] DVRDLP: invoke DSKSTATCHK invoke DEVIOCALL2 PUSH DI MOV AH,86H MOV DI,[DEVCALL.REQSTAT] TEST DI,STERR JZ CRDOK invoke CHARHARD POP DI MOV [CALLSCNT],1 CMP AL,1 JZ DVRDLP ;Retry XOR AL,AL ;Pick some random character JMP SHORT DVRDIGN CRDOK: POP DI CMP [CALLSCNT],1 JNZ ENDRDDEVJ2 PUSH DS MOV DS,WORD PTR [CALLXAD+2] MOV AL,BYTE PTR [DI] POP DS DVRDIGN: INC WORD PTR [CALLXAD] MOV [DEVCALL.REQSTAT],0 INC DI CMP AL,1AH ; ^Z? JZ ENDRDDEVJ CMP AL,c_CR ; CR? LOOPNZ DVRDLP ENDRDDEVJ: DEC DI ENDRDDEVJ2: JMP SHORT ENDRDDEV ASSUME DS:NOTHING,ES:NOTHING TRANBUF: LODSB STOSB CMP AL,c_CR ; Check for carriage return JNZ NORMCH MOV BYTE PTR [SI],c_LF NORMCH: CMP AL,c_LF LOOPNZ TRANBUF JNZ ENDRDCON XOR SI,SI ; Cause a new buffer to be read invoke OUT ; Transmit linefeed OR AL,1 ; Clear zero flag--not end of file ENDRDCON: PUSH SS POP DS ASSUME DS:DOSGROUP CALL SWAPBACK MOV [CONTPOS],SI ENDRDDEV: PUSH SS POP DS ASSUME DS:DOSGROUP MOV [NEXTADD],DI JNZ SETFCBC ; Zero set if Ctrl-Z found in input LES DI,[THISFCB] AND ES:BYTE PTR [DI.fcb_DEVID],0FFH-40H ; Mark as no more data available SETFCBC: call SETFCB return ASSUME DS:NOTHING,ES:NOTHING READCON: ASSUME DS:DOSGROUP CALL SWAPCON MOV SI,[CONTPOS] OR SI,SI JNZ TRANBUF CMP BYTE PTR [CONBUF],128 JZ GETBUF MOV WORD PTR [CONBUF],0FF80H ; Set up 128-byte buffer with no template GETBUF: PUSH CX PUSH ES PUSH DI MOV DX,OFFSET DOSGROUP:CONBUF invoke $STD_CON_STRING_INPUT ; Get input buffer POP DI POP ES POP CX MOV SI,2 + OFFSET DOSGROUP:CONBUF CMP BYTE PTR [SI],1AH ; Check for Ctrl-Z in first character JNZ TRANBUF MOV AL,1AH STOSB DEC DI MOV AL,10 invoke OUT ; Send linefeed XOR SI,SI JMP SHORT ENDRDCON LOAD ENDP SUBTTL STORE -- MAIN WRITE ROUTINE AND DEVICE OUT ROUTINES PAGE ASSUME DS:NOTHING,ES:NOTHING procedure STORE,NEAR ASSUME DS:NOTHING,ES:NOTHING ; Inputs: ; DS:DI point to FCB ; DX:AX = Position in file of disk transfer ; CX = Record count ; Outputs: ; DX:AX = Position of last record written ; CX = No. of records written ; ES:DI point to FCB ; fcb_LSTCLUS, fcb_CLUSPOS fields in FCB set call SETUP ASSUME DS:DOSGROUP OR BL,BL JS WRTDEV invoke DATE16 MOV ES:[DI.fcb_FDATE],AX MOV ES:[DI.fcb_FTIME],DX call DISKWRITE return WRITECON: PUSH DS PUSH SS POP DS ASSUME DS:DOSGROUP CALL SWAPCON POP DS ASSUME DS:NOTHING MOV SI,BX PUSH CX WRCONLP: LODSB CMP AL,1AH ; ^Z? JZ CONEOF invoke OUT LOOP WRCONLP CONEOF: POP AX ; Count SUB AX,CX ; Amount actually written POP DS ASSUME DS:DOSGROUP CALL SWAPBACK JMP SHORT ENDWRDEV DVWRTRAW: ASSUME DS:NOTHING XOR AX,AX ; Media Byte, unit = 0 invoke SETWRITE LDS SI,[THISFCB] invoke DEVIOCALL MOV DX,DI MOV AH,87H MOV DI,[DEVCALL.REQSTAT] TEST DI,STERR JZ CWRTROK invoke CHARHARD MOV BX,DX ; Recall transfer addr CMP AL,1 JZ DVWRTRAW ; Try again CWRTROK: POP DS ASSUME DS:DOSGROUP MOV AX,[CALLSCNT] ; Get actual number of bytes transferred ENDWRDEV: LES DI,[THISFCB] XOR DX,DX DIV ES:[DI.fcb_RECSIZ] MOV CX,AX ; Partial record is ignored call ADDREC return ASSUME DS:DOSGROUP WRTDEV: OR BL,40H ; Reset EOF for input XOR AX,AX JCXZ ENDWRDEV ; problem of creating on a device. PUSH DS MOV AL,BL LDS BX,[DMAADD] ASSUME DS:NOTHING MOV DI,BX XOR DX,DX ; Set starting point TEST AL,020H ; Raw? JNZ DVWRTRAW TEST AL,ISCOUT ; Console output device? JNZ WRITECON TEST AL,ISNULL JNZ WRTNUL MOV AX,DX CMP BYTE PTR [BX],1AH ; ^Z? JZ WRTCOOKDONE ; Yes, transfer nothing PUSH CX MOV CX,1 invoke SETWRITE POP CX LDS SI,[THISFCB] LDS SI,DWORD PTR [SI.fcb_FIRCLUS] DVWRTLP: invoke DSKSTATCHK invoke DEVIOCALL2 PUSH DI MOV AH,87H MOV DI,[DEVCALL.REQSTAT] TEST DI,STERR JZ CWROK invoke CHARHARD POP DI MOV [CALLSCNT],1 CMP AL,1 JZ DVWRTLP JMP SHORT DVWRTIGN CWROK: POP DI CMP [CALLSCNT],0 JZ WRTCOOKDONE DVWRTIGN: INC DX INC WORD PTR [CALLXAD] INC DI PUSH DS MOV DS,WORD PTR [CALLXAD+2] CMP BYTE PTR [DI],1AH ; ^Z? POP DS JZ WRTCOOKDONE MOV [DEVCALL.REQSTAT],0 LOOP DVWRTLP WRTCOOKDONE: MOV AX,DX POP DS JMP ENDWRDEV WRTNUL: MOV DX,CX ;Entire transfer done JMP WRTCOOKDONE STORE ENDP procedure get_io_fcb,near ASSUME DS:NOTHING,ES:NOTHING ; Convert JFN number in BX to FCB in DS:SI PUSH SS POP DS ASSUME DS:DOSGROUP PUSH ES PUSH DI invoke get_sf_from_jfn JC RET44P MOV SI,DI ADD SI,sf_fcb PUSH ES POP DS ASSUME DS:NOTHING RET44P: POP DI POP ES return get_io_fcb ENDP SUBTTL GETTHISDRV -- FIND CURRENT DRIVE PAGE ; Input: AL has drive identifier (1=A, 0=default) ; Output: AL has physical drive (0=A) ; Carry set if invalid drive (and AL is garbage anyway) procedure GetThisDrv,NEAR ASSUME DS:NOTHING,ES:NOTHING CMP BYTE PTR [NUMIO],AL retc DEC AL JNS PHYDRV MOV AL,[CURDRV] PHYDRV: MOV BYTE PTR [THISDRV],AL return GetThisDrv ENDP SUBTTL DIRREAD -- READ A DIRECTORY SECTOR PAGE procedure DirRead,NEAR ASSUME DS:DOSGROUP,ES:NOTHING ; Inputs: ; AX = Directory block number (relative to first block of directory) ; ES:BP = Base of drive parameters ; [DIRSEC] = First sector of first cluster of directory ; [CLUSNUM] = Next cluster ; [CLUSFAC] = Sectors/Cluster ; Function: ; Read the directory block into [CURBUF]. ; Outputs: ; [NXTCLUSNUM] = Next cluster (after the one skipped to) ; [SECCLUSPOS] Set ; ES:BP unchanged [CURBUF] Points to Buffer with dir sector ; All other registers destroyed. MOV CL,[CLUSFAC] DIV CL ; AL # clusters to skip, AH position in cluster MOV [SECCLUSPOS],AH MOV CL,AL XOR CH,CH MOV DX,[DIRSEC] ADD DL,AH ADC DH,0 MOV BX,[CLUSNUM] MOV [NXTCLUSNUM],BX JCXZ FIRSTCLUSTER SKPCLLP: invoke UNPACK XCHG BX,DI CMP BX,0FF8H JAE HAVESKIPPED LOOP SKPCLLP HAVESKIPPED: MOV [NXTCLUSNUM],BX MOV DX,DI MOV BL,AH invoke FIGREC entry FIRSTCLUSTER XOR AL,AL ; Indicate pre-read MOV AH,DIRPRI invoke GETBUFFR ret DirRead ENDP SUBTTL FATSECRD -- READ A FAT SECTOR PAGE procedure FATSecRd,NEAR ASSUME DS:NOTHING,ES:NOTHING ; Inputs: ; Same as DREAD ; DS:BX = Transfer address ; CX = Number of sectors ; DX = Absolute record number ; ES:BP = Base of drive parameters ; Function: ; Calls BIOS to perform FAT read. ; Outputs: ; Same as DREAD MOV DI,CX MOV CL,ES:[BP.dpb_FAT_count] MOV AL,ES:[BP.dpb_FAT_size] XOR AH,AH MOV CH,AH PUSH DX NXTFAT: PUSH CX PUSH AX MOV CX,DI CALL DSKREAD POP AX POP CX JZ RET41P ADD DX,AX LOOP NXTFAT POP DX MOV CX,DI ; NOTE FALL THROUGH SUBTTL DREAD -- DO A DISK READ PAGE entry DREAD ASSUME DS:NOTHING,ES:NOTHING ; Inputs: ; DS:BX = Transfer address ; CX = Number of sectors ; DX = Absolute record number ; ES:BP = Base of drive parameters ; Function: ; Calls BIOS to perform disk read. If BIOS reports ; errors, will call HARDERR for further action. ; DS,ES:BP preserved. All other registers destroyed. CALL DSKREAD retz MOV BYTE PTR [READOP],0 invoke HARDERR CMP AL,1 ; Check for retry JZ DREAD return ; Ignore otherwise RET41P: POP DX return FATSecRd ENDP SUBTTL DSKREAD -- PHYSICAL DISK READ PAGE procedure DskRead,NEAR ASSUME DS:NOTHING,ES:NOTHING ; Inputs: ; DS:BX = Transfer addr ; CX = Number of sectors ; DX = Absolute record number ; ES:BP = Base of drive parameters ; Function: ; Call BIOS to perform disk read ; Outputs: ; DI = CX on entry ; CX = Number of sectors unsuccessfully transfered ; AX = Status word as returned by BIOS (error code in AL if error) ; Zero set if OK (from BIOS) ; Zero clear if error ; SI Destroyed, others preserved PUSH CX MOV AH,ES:[BP.dpb_media] MOV AL,ES:[BP.dpb_UNIT] PUSH BX PUSH ES invoke SETREAD JMP DODSKOP SUBTTL DWRITE -- SEE ABOUT WRITING PAGE entry DWRITE ASSUME DS:NOTHING,ES:NOTHING ; Inputs: ; DS:BX = Transfer address ; CX = Number of sectors ; DX = Absolute record number ; ES:BP = Base of drive parameters ; Function: ; Calls BIOS to perform disk write. If BIOS reports ; errors, will call HARDERR for further action. ; BP preserved. All other registers destroyed. CALL DSKWRITE retz MOV BYTE PTR [READOP],1 invoke HARDERR CMP AL,1 ; Check for retry JZ DWRITE return SUBTTL DSKWRITE -- PHYSICAL DISK WRITE PAGE entry DSKWRITE ASSUME DS:NOTHING,ES:NOTHING ; Inputs: ; DS:BX = Transfer addr ; CX = Number of sectors ; DX = Absolute record number ; ES:BP = Base of drive parameters ; Function: ; Call BIOS to perform disk read ; Outputs: ; DI = CX on entry ; CX = Number of sectors unsuccessfully transfered ; AX = Status word as returned by BIOS (error code in AL if error) ; Zero set if OK (from BIOS) ; Zero clear if error ; SI Destroyed, others preserved PUSH CX MOV AH,ES:[BP.dpb_media] MOV AL,ES:[BP.dpb_UNIT] PUSH BX PUSH ES invoke SETWRITE DODSKOP: MOV CX,DS ; Save DS POP DS ; DS:BP points to DPB PUSH DS LDS SI,DS:[BP.dpb_driver_addr] invoke DEVIOCALL2 MOV DS,CX ; Restore DS POP ES ; Restore ES POP BX MOV CX,[CALLSCNT] ; Number of sectors transferred POP DI SUB CX,DI NEG CX ; Number of sectors not transferred MOV AX,[DEVCALL.REQSTAT] TEST AX,STERR return DskRead ENDP SUBTTL SETUP -- SETUP A DISK READ OR WRITE FROM USER PAGE ASSUME DS:DOSGROUP,ES:NOTHING procedure SETUP,NEAR ASSUME DS:NOTHING,ES:NOTHING ; Inputs: ; DS:DI point to FCB ; DX:AX = Record position in file of disk transfer ; CX = Record count ; Outputs: ; DS = DOSGROUP ; BL = fcb_DEVID from FCB ; CX = No. of bytes to transfer (0 = 64K) ; [THISDPB] = Base of drive parameters ; [RECCNT] = Record count ; [RECPOS] = Record position in file ; ES:DI Points to FCB ; [THISFCB] = ES:DI ; [NEXTADD] = Displacement of disk transfer within segment ; [SECPOS] = Position of first sector ; [BYTPOS] = Byte position in file ; [BYTSECPOS] = Byte position in first sector ; [CLUSNUM] = First cluster ; [SECCLUSPOS] = Sector within first cluster ; [DSKERR] = 0 (no errors yet) ; [TRANS] = 0 (No transfers yet) ; [THISDRV] = Physical drive unit number PUSH AX MOV AL,[DI] DEC AL MOV BYTE PTR [THISDRV],AL MOV AL,[DI.fcb_DEVID] MOV SI,[DI.fcb_RECSIZ] OR SI,SI JNZ HAVRECSIZ MOV SI,128 MOV [DI.fcb_RECSIZ],SI HAVRECSIZ: MOV WORD PTR [THISFCB+2],DS PUSH SS POP DS ; Set DS to DOSGROUP ASSUME DS:DOSGROUP MOV WORD PTR [THISFCB],DI OR AL,AL ; Is it a device? JNS NOTDEVICE XOR AL,AL ; Fake in drive 0 so we can get BP NOTDEVICE: invoke GETBP POP AX JNC CheckRecLen XOR CX,CX MOV BYTE PTR [DSKERR],4 POP BX return CheckRecLen: CMP SI,64 ; Check if highest byte of RECPOS is significant JB SMALREC XOR DH,DH ; Ignore MSB if record >= 64 bytes SMALREC: MOV [RECCNT],CX MOV WORD PTR [RECPOS],AX MOV WORD PTR [RECPOS+2],DX MOV BX,WORD PTR [DMAADD] MOV [NEXTADD],BX MOV BYTE PTR [DSKERR],0 MOV BYTE PTR [TRANS],0 MOV BX,DX MUL SI MOV WORD PTR [BYTPOS],AX PUSH DX MOV AX,BX MUL SI POP BX ADD AX,BX ADC DX,0 ; Ripple carry JNZ EOFERR MOV WORD PTR [BYTPOS+2],AX MOV DX,AX MOV AX,WORD PTR [BYTPOS] MOV BX,ES:[BP.dpb_sector_size] CMP DX,BX ; See if divide will overflow JNC EOFERR DIV BX MOV [SECPOS],AX MOV [BYTSECPOS],DX MOV DX,AX AND AL,ES:[BP.dpb_cluster_mask] MOV [SECCLUSPOS],AL MOV AX,CX ; Record count MOV CL,ES:[BP.dpb_cluster_shift] SHR DX,CL MOV [CLUSNUM],DX MUL SI ; Multiply by bytes per record MOV CX,AX ADD AX,WORD PTR [DMAADD] ; See if it will fit in one segment ADC DX,0 JZ OK ; Must be less than 64K MOV AX,WORD PTR [DMAADD] NEG AX ; Amount of room left in segment JNZ PARTSEG DEC AX PARTSEG: XOR DX,DX DIV SI ; How many records will fit? MOV [RECCNT],AX MUL SI ; Translate that back into bytes MOV BYTE PTR [DSKERR],2 ; Flag that trimming took place MOV CX,AX JCXZ NOROOM OK: LES DI,[THISFCB] MOV BL,ES:[DI.fcb_DEVID] return EOFERR: MOV BYTE PTR [DSKERR],1 XOR CX,CX NOROOM: LES DI,[THISFCB] POP BX ; Kill return address return SETUP ENDP SUBTTL BREAKDOWN -- CUT A USER READ OR WRITE INTO PIECES PAGE procedure BREAKDOWN,near ASSUME DS:DOSGROUP,ES:NOTHING ; Inputs: ; CX = Length of disk transfer in bytes ; ES:BP = Base of drive parameters ; [BYTSECPOS] = Byte position witin first sector ; Outputs: ; [BYTCNT1] = Bytes to transfer in first sector ; [SECCNT] = No. of whole sectors to transfer ; [BYTCNT2] = Bytes to transfer in last sector ; AX, BX, DX destroyed. No other registers affected. MOV AX,[BYTSECPOS] MOV BX,CX OR AX,AX JZ SAVFIR ; Partial first sector? SUB AX,ES:[BP.dpb_sector_size] NEG AX ; Max number of bytes left in first sector SUB BX,AX ; Subtract from total length JAE SAVFIR ADD AX,BX ; Don't use all of the rest of the sector XOR BX,BX ; And no bytes are left SAVFIR: MOV [BYTCNT1],AX MOV AX,BX XOR DX,DX DIV ES:[BP.dpb_sector_size] ; How many whole sectors? MOV [SECCNT],AX MOV [BYTCNT2],DX ; Bytes remaining for last sector OR DX,[BYTCNT1] retnz ; NOT (BYTCNT1 = BYTCNT2 = 0) CMP AX,1 retnz MOV AX,ES:[BP.dpb_sector_size] ; Buffer EXACT one sector I/O MOV [BYTCNT2],AX MOV [SECCNT],DX ; DX = 0 return BreakDown ENDP SUBTTL DISKREAD -- PERFORM USER DISK READ PAGE procedure DISKREAD,NEAR ASSUME DS:DOSGROUP,ES:NOTHING ; Inputs: ; Outputs of SETUP ; Function: ; Perform disk read ; Outputs: ; DX:AX = Position of last record read ; CX = No. of records read ; ES:DI point to FCB ; fcb_LSTCLUS, fcb_CLUSPOS fields in FCB set MOV AX,ES:WORD PTR [DI.fcb_FILSIZ] MOV BX,ES:WORD PTR [DI.fcb_FILSIZ+2] SUB AX,WORD PTR [BYTPOS] SBB BX,WORD PTR [BYTPOS+2] JB RDERR JNZ ENUF OR AX,AX JZ RDERR CMP AX,CX JAE ENUF MOV CX,AX ENUF: LES BP,[THISDPB] CALL BREAKDOWN MOV CX,[CLUSNUM] invoke FNDCLUS OR CX,CX JZ SHORT SKIPERR RDERR: JMP WRTERR RDLASTJ:JMP RDLAST SETFCBJ2: JMP SETFCB SKIPERR: MOV [LASTPOS],DX MOV [CLUSNUM],BX CMP [BYTCNT1],0 JZ RDMID invoke BUFRD RDMID: CMP [SECCNT],0 JZ RDLASTJ invoke NEXTSEC JC SETFCBJ2 MOV BYTE PTR [TRANS],1 ; A transfer is taking place ONSEC: MOV DL,[SECCLUSPOS] MOV CX,[SECCNT] MOV BX,[CLUSNUM] RDLP: invoke OPTIMIZE PUSH DI PUSH AX PUSH BX MOV DS,WORD PTR [DMAADD+2] ASSUME DS:NOTHING PUSH DX PUSH CX CALL DREAD POP BX POP DX ADD BX,DX ; Upper bound of read MOV AL,ES:[BP.dpb_drive] invoke SETVISIT NXTBUF: ; Must see if one of these sectors is buffered MOV [DI.VISIT],1 ; Mark as visited CMP AL,[DI.BUFDRV] JNZ DONXTBUF ; Not for this drive CMP [DI.BUFSECNO],DX JC DONXTBUF ; Below first sector CMP [DI.BUFSECNO],BX JNC DONXTBUF ; Above last sector CMP BYTE PTR [DI.BUFDIRTY],0 JZ CLBUFF ; Buffer is clean, so OK ; A sector has been read in when a dirty copy of it is in a buffer ; The buffered sector must now be read into the right place POP AX ; Recall transfer address PUSH AX PUSH DI ; Save search environment PUSH DX SUB DX,[DI.BUFSECNO] ; How far into transfer? NEG DX MOV SI,DI MOV DI,AX MOV AX,DX MOV CX,ES:[BP.dpb_sector_size] MUL CX ADD DI,AX ; Put the buffer here ADD SI,BUFINSIZ SHR CX,1 PUSH ES MOV ES,WORD PTR [DMAADD+2] REP MOVSW JNC EVENMOV MOVSB EVENMOV: POP ES POP DX POP DI MOV AL,ES:[BP.dpb_drive] CLBUFF: invoke SCANPLACE DONXTBUF: invoke SKIPVISIT JNZ NXTBUF PUSH SS POP DS ASSUME DS:DOSGROUP POP CX POP CX POP BX JCXZ RDLAST CMP BX,0FF8H JAE SETFCB MOV DL,0 INC [LASTPOS] ; We'll be using next cluster JMP RDLP RDLAST: MOV AX,[BYTCNT2] OR AX,AX JZ SETFCB MOV [BYTCNT1],AX invoke NEXTSEC JC SETFCB MOV [BYTSECPOS],0 invoke BUFRD entry SETFCB LES SI,[THISFCB] MOV AX,[NEXTADD] MOV DI,AX SUB AX,WORD PTR [DMAADD] ; Number of bytes transfered XOR DX,DX MOV CX,ES:[SI.fcb_RECSIZ] DIV CX ; Number of records CMP AX,[RECCNT] ; Check if all records transferred JZ FULLREC MOV BYTE PTR [DSKERR],1 OR DX,DX JZ FULLREC ; If remainder 0, then full record transfered MOV BYTE PTR [DSKERR],3 ; Flag partial last record SUB CX,DX ; Bytes left in last record PUSH ES MOV ES,WORD PTR [DMAADD+2] XCHG AX,BX ; Save the record count temporarily XOR AX,AX ; Fill with zeros SHR CX,1 JNC EVENFIL STOSB EVENFIL: REP STOSW XCHG AX,BX ; Restore record count to AX POP ES INC AX ; Add last (partial) record to total FULLREC: MOV CX,AX MOV DI,SI ; ES:DI point to FCB SETCLUS: TEST ES:[DI].fcb_DEVID,-1 JS ADDREC ; don't set clisters if device MOV AX,[CLUSNUM] AND ES:[DI.fcb_LSTCLUS],0F000h ; fcb_lstclus is packed with dir clus OR ES:[DI.fcb_LSTCLUS],AX ; drop in the correct part of fcb_lstclus MOV AX,[LASTPOS] MOV ES:[DI.fcb_CLUSPOS],AX entry AddRec MOV AX,WORD PTR [RECPOS] MOV DX,WORD PTR [RECPOS+2] JCXZ RET28 ; If no records read, don't change position DEC CX ADD AX,CX ; Update current record position ADC DX,0 INC CX RET28: return DISKREAD ENDP SUBTTL DISKWRITE -- PERFORM USER DISK WRITE PAGE procedure DISKWRITE,NEAR ASSUME DS:DOSGROUP,ES:NOTHING ; Inputs: ; Outputs of SETUP ; Function: ; Perform disk write ; Outputs: ; DX:AX = Position of last record written ; CX = No. of records written ; ES:DI point to FCB ; fcb_LSTCLUS, fcb_CLUSPOS fields in FCB set AND BL,3FH ; Mark file as dirty MOV ES:[DI.fcb_DEVID],BL LES BP,[THISDPB] CALL BREAKDOWN MOV AX,WORD PTR [BYTPOS] MOV DX,WORD PTR [BYTPOS+2] JCXZ WRTEOFJ ADD AX,CX ADC DX,0 ; AX:DX=last byte accessed DIV ES:[BP.dpb_sector_size] ; AX=last sector accessed MOV BX,AX ; Save last full sector OR DX,DX JNZ CALCLUS DEC AX ; AX must be zero base indexed CALCLUS: MOV CL,ES:[BP.dpb_cluster_shift] SHR AX,CL ; Last cluster to be accessed PUSH AX PUSH DX ; Save the size of the "tail" PUSH ES LES DI,[THISFCB] MOV AX,ES:WORD PTR [DI.fcb_FILSIZ] MOV DX,ES:WORD PTR [DI.fcb_FILSIZ+2] POP ES DIV ES:[BP.dpb_sector_size] MOV CX,AX ; Save last full sector of current file OR DX,DX JZ NORNDUP INC AX ; Round up if any remainder NORNDUP: MOV [VALSEC],AX ; Number of sectors that have been written XOR AX,AX MOV WORD PTR [GROWCNT],AX MOV WORD PTR [GROWCNT+2],AX POP AX SUB BX,CX ; Number of full sectors JB NOGROW JZ TESTTAIL MOV CX,DX XCHG AX,BX MUL ES:[BP.dpb_sector_size] ; Bytes of full sector growth SUB AX,CX ; Take off current "tail" SBB DX,0 ; 32-bit extension ADD AX,BX ; Add on new "tail" ADC DX,0 ; ripple tim's head off JMP SHORT SETGRW HAVSTART: MOV CX,AX invoke SKPCLP JCXZ DOWRTJ invoke ALLOCATE JNC DOWRTJ WRTERR: XOR CX,CX MOV BYTE PTR [DSKERR],1 MOV AX,WORD PTR [RECPOS] MOV DX,WORD PTR [RECPOS+2] LES DI,[THISFCB] return DOWRTJ: JMP DOWRT WRTEOFJ: JMP WRTEOF TESTTAIL: SUB AX,DX JBE NOGROW XOR DX,DX SETGRW: MOV WORD PTR [GROWCNT],AX MOV WORD PTR [GROWCNT+2],DX NOGROW: POP AX MOV CX,[CLUSNUM] ; First cluster accessed invoke FNDCLUS MOV [CLUSNUM],BX MOV [LASTPOS],DX SUB AX,DX ; Last cluster minus current cluster JZ DOWRT ; If we have last clus, we must have first JCXZ HAVSTART ; See if no more data PUSH CX ; No. of clusters short of first MOV CX,AX invoke ALLOCATE POP AX JC WRTERR MOV CX,AX MOV DX,[LASTPOS] INC DX DEC CX JZ NOSKIP invoke SKPCLP NOSKIP: MOV [CLUSNUM],BX MOV [LASTPOS],DX DOWRT: CMP [BYTCNT1],0 JZ WRTMID MOV BX,[CLUSNUM] invoke BUFWRT WRTMID: MOV AX,[SECCNT] OR AX,AX JZ WRTLAST ADD [SECPOS],AX invoke NEXTSEC MOV BYTE PTR [TRANS],1 ; A transfer is taking place MOV DL,[SECCLUSPOS] MOV BX,[CLUSNUM] MOV CX,[SECCNT] WRTLP: invoke OPTIMIZE PUSH DI PUSH AX PUSH DX PUSH BX MOV AL,ES:[BP.dpb_drive] MOV BX,CX ADD BX,DX ; Upper bound of write invoke SETVISIT ASSUME DS:NOTHING NEXTBUFF: ; Search for buffers MOV [DI.VISIT],1 ; Mark as visited CMP AL,[DI.BUFDRV] JNZ DONEXTBUFF ; Not for this drive CMP [DI.BUFSECNO],DX JC DONEXTBUFF ; Buffer is not in range of write CMP [DI.BUFSECNO],BX JNC DONEXTBUFF ; Buffer is not in range of write MOV WORD PTR [DI.BUFDRV],00FFH ; Free the buffer, it is being over written invoke SCANPLACE DONEXTBUFF: invoke SKIPVISIT JNZ NEXTBUFF POP BX POP DX MOV DS,WORD PTR [DMAADD+2] CALL DWRITE POP CX POP BX PUSH SS POP DS ASSUME DS:DOSGROUP JCXZ WRTLAST MOV DL,0 INC [LASTPOS] ; We'll be using next cluster JMP SHORT WRTLP WRTERRJ: JMP WRTERR WRTLAST: MOV AX,[BYTCNT2] OR AX,AX JZ FINWRT MOV [BYTCNT1],AX invoke NEXTSEC MOV [BYTSECPOS],0 invoke BUFWRT FINWRT: LES DI,[THISFCB] MOV AX,WORD PTR [GROWCNT] MOV CX,WORD PTR [GROWCNT+2] OR AX,AX JNZ UPDATE_size OR CX,CX JZ SAMSIZ Update_size: ADD WORD PTR ES:[DI.fcb_FILSIZ],AX ADC WORD PTR ES:[DI.fcb_FILSIZ+2],CX SAMSIZ: MOV CX,[RECCNT] JMP SETCLUS WRTEOF: MOV CX,AX OR CX,DX JZ KILLFIL SUB AX,1 SBB DX,0 DIV ES:[BP.dpb_sector_size] MOV CL,ES:[BP.dpb_cluster_shift] SHR AX,CL MOV CX,AX invoke FNDCLUS JCXZ RELFILE invoke ALLOCATE JC WRTERRJ UPDATE: LES DI,[THISFCB] MOV AX,WORD PTR [BYTPOS] MOV ES:WORD PTR [DI.fcb_FILSIZ],AX MOV AX,WORD PTR [BYTPOS+2] MOV ES:WORD PTR [DI.fcb_FILSIZ+2],AX XOR CX,CX JMP ADDREC RELFILE: MOV DX,0FFFH invoke RELBLKS JMP SHORT UPDATE KILLFIL: XOR BX,BX PUSH ES LES DI,[THISFCB] MOV ES:[DI.fcb_CLUSPOS],BX XCHG BX,ES:[DI.fcb_FIRCLUS] AND ES:[DI.fcb_LSTCLUS],0F000H POP ES OR BX,BX JZ UPDATE invoke RELEASE JMP SHORT UPDATE DISKWRITE ENDP do_ext CODE ENDS END
OPT --zxnext --syntax=abfw : ORG $1234 RELOCATE_START ASSERT 2 * relocate_count == relocate_size ASSERT 12 == relocate_count dw relocate_count dw relocate_size reloc1: ; generate two relocation records: ld hl,reloc1,,bc,reloc2-reloc1,,de,reloc1+5,,sp,absolute1 jp reloc1,,reloc2-reloc1,,reloc1+5,,absolute1 call reloc1,,reloc2-reloc1,,reloc1+5,,absolute1 add hl,reloc1,,bc,reloc2-reloc1,,de,reloc1+5,,hl,absolute1 ; Z80N extras ld hl,(reloc1),,bc,(reloc2-reloc1),,de,(reloc1+5),,sp,(absolute1) ld (reloc1),hl,,(reloc2-reloc1),bc,,(reloc1+5),de,,(absolute1),sp reloc2: RELOCATE_END absolute1: RELOCATE_TABLE ; 39 12 ($1239) 3F 12 ($123F) ; ld r16,imm16 ; 45 12 ($1245) 4B 12 ($124B) ; jp ; 51 12 ($1251) 57 12 ($1257) ; call ; 5E 12 ($125E) 66 12 ($1266) ; add r16,imm16 ; 6D 12 ($126D) 75 12 ($1275) ; ld r16,(mem16) ; 7C 12 ($127C) 84 12 ($1284) ; ld (mem16),r16 ASSERT 0 == __ERRORS__ ASSERT 0 == __WARNINGS__
; PROLOGUE(mpn_sumdiff_n) ; ; Copyright 2011 The Code Cavern ; ; Windows Conversion Copyright 2008 Brian Gladman ; ; This file is part of the MPIR Library. ; ; The MPIR Library is free software; you can redistribute it and/or modify ; it under the terms of the GNU Lesser General Public License as published ; by the Free Software Foundation; either version 2.1 of the License, or (at ; your option) any later version. ; ; The MPIR 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 Lesser General Public ; License for more details. ; ; You should have received a copy of the GNU Lesser General Public License ; along with the MPIR Library; see the file COPYING.LIB. If not, write ; to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, ; Boston, MA 02110-1301, USA. ; ; mp_limb_t mpn_sumdiff_n(mp_ptr, mp_ptr, mp_ptr, mp_ptr, mp_size_t) ; rax rdi rsi rdx rcx r8 ; rax rcx rdx r8 r9 [rsp+40] %include "yasm_mac.inc" %define reg_save_list rbx, rbp, rsi, rdi, r12, r13, r14, r15 CPU Nehalem BITS 64 FRAME_PROC mpn_sumdiff_n, 0, reg_save_list mov rbx, [rsp+stack_use+40] xor rax, rax mov r10d, 3 lea rdi, [rcx+rbx*8-24] lea rsi, [rdx+rbx*8-24] sub r10, rbx lea rdx, [r8+rbx*8-24] lea rcx, [r9+rbx*8-24] mov r9, rax jnc .2 align 16 .1: sahf mov r8, [rdx+r10*8] mov r12, [rdx+r10*8+24] mov r11, r8 adc r8, [rcx+r10*8] mov rbx, [rdx+r10*8+8] mov r13, rbx adc rbx, [rcx+r10*8+8] mov rbp, [rdx+r10*8+16] mov r14, rbp adc rbp, [rcx+r10*8+16] mov r15, r12 adc r12, [rcx+r10*8+24] lahf add r9b, 255 sbb r11, [rcx+r10*8] mov [rsi+r10*8], r11 sbb r13, [rcx+r10*8+8] sbb r14, [rcx+r10*8+16] sbb r15, [rcx+r10*8+24] setc r9b add r10, 4 mov [rdi+r10*8-32], r8 mov [rdi+r10*8+16-32], rbp mov [rsi+r10*8+8-32], r13 mov [rsi+r10*8+24-32], r15 mov [rdi+r10*8+24-32], r12 mov [rsi+r10*8+16-32], r14 mov [rdi+r10*8+8-32], rbx jnc .1 .2: cmp r10, 2 jg .6 je .5 jp .4 .3: sahf mov r8, [rdx] mov r11, r8 adc r8, [rcx] mov rbx, [rdx+8] mov r13, rbx adc rbx, [rcx+8] mov rbp, [rdx+16] mov r14, rbp adc rbp, [rcx+16] lahf add r9b, 255 sbb r11, [rcx] mov [rsi], r11 sbb r13, [rcx+8] sbb r14, [rcx+16] setc r9b mov [rdi], r8 mov [rdi+16], rbp mov [rsi+8], r13 mov [rsi+16], r14 mov [rdi+8], rbx sahf mov rax, 0 adc rax, 0 add r9b, 255 rcl rax, 1 EXIT_PROC reg_save_list .4: sahf mov r8, [rdx+8] mov r11, r8 adc r8, [rcx+8] mov rbx, [rdx+16] mov r13, rbx adc rbx, [rcx+16] lahf add r9b, 255 sbb r11, [rcx+8] mov [rsi+8], r11 sbb r13, [rcx+16] setc r9b mov [rdi+8], r8 mov [rsi+16], r13 mov [rdi+16], rbx sahf mov rax, 0 adc rax, 0 add r9b, 255 rcl rax, 1 EXIT_PROC reg_save_list .5: sahf mov r8, [rdx+16] mov r11, r8 adc r8, [rcx+16] lahf add r9b, 255 sbb r11, [rcx+16] mov [rsi+16], r11 setc r9b mov [rdi+16], r8 .6: sahf mov rax, 0 adc rax, 0 add r9b, 255 rcl rax, 1 END_PROC reg_save_list end
; int isalnum(int c) SECTION code_clib SECTION code_ctype PUBLIC isalnum EXTERN asm_isalnum, error_zc isalnum: inc h dec h jp nz, error_zc ld a,l call asm_isalnum ld l,h ret c inc l ret ; SDCC bridge for Classic IF __CLASSIC PUBLIC _isalnum defc _isalnum = isalnum ENDIF
lui $1,62486 ori $1,$1,45572 lui $2,21452 ori $2,$2,59355 lui $3,22214 ori $3,$3,65088 lui $4,58524 ori $4,$4,31651 lui $5,47094 ori $5,$5,64407 lui $6,26673 ori $6,$6,57819 mthi $1 mtlo $2 sec0: nop nop nop or $0,$6,$6 sec1: nop nop subu $6,$1,$2 or $4,$6,$6 sec2: nop nop xori $6,$4,27956 or $1,$6,$6 sec3: nop nop mflo $6 or $5,$6,$6 sec4: nop nop lhu $6,16($0) or $3,$6,$6 sec5: nop addu $6,$3,$1 nop or $3,$6,$6 sec6: nop xor $6,$1,$5 nor $6,$3,$1 or $2,$6,$6 sec7: nop addu $6,$0,$6 lui $6,50812 or $3,$6,$6 sec8: nop or $6,$0,$2 mfhi $6 or $1,$6,$6 sec9: nop subu $6,$3,$2 lh $6,4($0) or $4,$6,$6 sec10: nop ori $6,$3,16168 nop or $3,$6,$6 sec11: nop lui $6,49816 and $6,$3,$5 or $3,$6,$6 sec12: nop sltiu $6,$3,8929 slti $6,$4,20782 or $2,$6,$6 sec13: nop slti $6,$0,12108 mfhi $6 or $3,$6,$6 sec14: nop andi $6,$2,62565 lb $6,5($0) or $6,$6,$6 sec15: nop mflo $6 nop or $3,$6,$6 sec16: nop mflo $6 addu $6,$4,$1 or $2,$6,$6 sec17: nop mfhi $6 slti $6,$4,20658 or $2,$6,$6 sec18: nop mflo $6 mflo $6 or $1,$6,$6 sec19: nop mflo $6 lb $6,7($0) or $3,$6,$6 sec20: nop lbu $6,3($0) nop or $6,$6,$6 sec21: nop lbu $6,1($0) addu $6,$1,$2 or $4,$6,$6 sec22: nop lhu $6,10($0) addiu $6,$3,-12084 or $2,$6,$6 sec23: nop lbu $6,15($0) mfhi $6 or $3,$6,$6 sec24: nop lhu $6,6($0) lh $6,12($0) or $3,$6,$6 sec25: or $6,$5,$4 nop nop or $2,$6,$6 sec26: slt $6,$2,$2 nop nor $6,$2,$2 or $3,$6,$6 sec27: slt $6,$0,$3 nop andi $6,$2,24826 or $1,$6,$6 sec28: subu $6,$6,$0 nop mflo $6 or $3,$6,$6 sec29: xor $6,$2,$3 nop lb $6,5($0) or $3,$6,$6 sec30: nor $6,$4,$2 xor $6,$2,$2 nop or $0,$6,$6 sec31: xor $6,$2,$3 nor $6,$4,$4 sltu $6,$5,$3 or $2,$6,$6 sec32: subu $6,$0,$2 addu $6,$4,$5 slti $6,$6,-24286 or $3,$6,$6 sec33: addu $6,$4,$6 addu $6,$0,$3 mfhi $6 or $2,$6,$6 sec34: xor $6,$3,$5 slt $6,$3,$2 lh $6,14($0) or $6,$6,$6 sec35: addu $6,$3,$4 slti $6,$6,-14225 nop or $4,$6,$6 sec36: subu $6,$6,$4 lui $6,23427 and $6,$3,$3 or $5,$6,$6 sec37: addu $6,$0,$4 xori $6,$6,58160 xori $6,$1,35542 or $3,$6,$6 sec38: nor $6,$5,$5 andi $6,$3,16832 mflo $6 or $4,$6,$6 sec39: and $6,$3,$4 ori $6,$5,30722 lbu $6,11($0) or $1,$6,$6 sec40: or $6,$5,$4 mflo $6 nop or $3,$6,$6 sec41: sltu $6,$5,$1 mflo $6 or $6,$4,$5 or $1,$6,$6 sec42: nor $6,$4,$4 mflo $6 lui $6,50996 or $1,$6,$6 sec43: nor $6,$2,$4 mfhi $6 mflo $6 or $4,$6,$6 sec44: and $6,$2,$5 mflo $6 lhu $6,10($0) or $2,$6,$6 sec45: nor $6,$4,$0 lw $6,0($0) nop or $6,$6,$6 sec46: slt $6,$5,$4 lbu $6,8($0) xor $6,$2,$4 or $6,$6,$6 sec47: slt $6,$5,$0 lh $6,12($0) xori $6,$2,22863 or $2,$6,$6 sec48: slt $6,$3,$3 lhu $6,8($0) mfhi $6 or $3,$6,$6 sec49: sltu $6,$2,$0 lw $6,0($0) lw $6,0($0) or $4,$6,$6 sec50: sltiu $6,$5,17272 nop nop or $6,$6,$6 sec51: sltiu $6,$2,-11899 nop slt $6,$1,$4 or $2,$6,$6 sec52: xori $6,$2,48926 nop addiu $6,$5,-21289 or $5,$6,$6 sec53: slti $6,$4,15507 nop mfhi $6 or $4,$6,$6 sec54: slti $6,$2,-27876 nop lhu $6,14($0) or $2,$6,$6 sec55: sltiu $6,$3,-8386 slt $6,$5,$5 nop or $5,$6,$6 sec56: lui $6,2374 nor $6,$2,$3 slt $6,$2,$3 or $5,$6,$6 sec57: ori $6,$3,45763 sltu $6,$3,$0 addiu $6,$2,-11779 or $1,$6,$6 sec58: andi $6,$4,28772 and $6,$1,$4 mflo $6 or $4,$6,$6 sec59: slti $6,$5,1817 nor $6,$5,$4 lhu $6,10($0) or $1,$6,$6 sec60: xori $6,$6,8935 xori $6,$5,24151 nop or $5,$6,$6 sec61: addiu $6,$5,-15768 ori $6,$2,54930 addu $6,$1,$0 or $3,$6,$6 sec62: sltiu $6,$3,-22749 addiu $6,$4,-18263 xori $6,$3,58622 or $5,$6,$6 sec63: xori $6,$5,1989 addiu $6,$5,12231 mflo $6 or $5,$6,$6 sec64: slti $6,$5,23523 sltiu $6,$4,-27174 lw $6,8($0) or $4,$6,$6 sec65: lui $6,35812 mflo $6 nop or $2,$6,$6 sec66: addiu $6,$6,-1529 mflo $6 slt $6,$3,$0 or $4,$6,$6 sec67: sltiu $6,$4,20461 mflo $6 andi $6,$5,31873 or $3,$6,$6 sec68: andi $6,$3,17730 mflo $6 mflo $6 or $6,$6,$6 sec69: addiu $6,$5,-6677 mflo $6 lw $6,4($0) or $2,$6,$6 sec70: lui $6,53140 lbu $6,9($0) nop or $4,$6,$6 sec71: addiu $6,$1,-16171 lbu $6,15($0) and $6,$2,$2 or $5,$6,$6 sec72: xori $6,$4,50624 lh $6,2($0) sltiu $6,$5,-23360 or $6,$6,$6 sec73: slti $6,$2,11118 lbu $6,4($0) mfhi $6 or $6,$6,$6 sec74: slti $6,$3,-14133 lw $6,8($0) lbu $6,6($0) or $3,$6,$6 sec75: mfhi $6 nop nop or $4,$6,$6 sec76: mfhi $6 nop nor $6,$3,$4 or $0,$6,$6 sec77: mfhi $6 nop addiu $6,$1,19407 or $0,$6,$6 sec78: mfhi $6 nop mfhi $6 or $3,$6,$6 sec79: mflo $6 nop lhu $6,14($0) or $6,$6,$6 sec80: mfhi $6 and $6,$5,$4 nop or $3,$6,$6 sec81: mflo $6 xor $6,$1,$3 and $6,$1,$3 or $4,$6,$6 sec82: mfhi $6 nor $6,$3,$1 ori $6,$5,11125 or $6,$6,$6 sec83: mfhi $6 slt $6,$0,$2 mflo $6 or $2,$6,$6 sec84: mflo $6 sltu $6,$4,$2 lb $6,7($0) or $1,$6,$6 sec85: mflo $6 addiu $6,$5,-9628 nop or $3,$6,$6 sec86: mfhi $6 lui $6,26136 xor $6,$1,$3 or $3,$6,$6 sec87: mfhi $6 addiu $6,$0,-4128 sltiu $6,$6,18844 or $6,$6,$6 sec88: mflo $6 sltiu $6,$3,-26140 mfhi $6 or $5,$6,$6 sec89: mflo $6 addiu $6,$6,-18829 lhu $6,8($0) or $3,$6,$6 sec90: mflo $6 mfhi $6 nop or $1,$6,$6 sec91: mfhi $6 mfhi $6 nor $6,$6,$3 or $1,$6,$6 sec92: mfhi $6 mflo $6 xori $6,$4,22726 or $2,$6,$6 sec93: mflo $6 mfhi $6 mfhi $6 or $4,$6,$6 sec94: mflo $6 mflo $6 lw $6,4($0) or $4,$6,$6 sec95: mflo $6 lw $6,12($0) nop or $1,$6,$6 sec96: mfhi $6 lbu $6,4($0) sltu $6,$5,$4 or $2,$6,$6 sec97: mfhi $6 lw $6,16($0) sltiu $6,$3,3989 or $3,$6,$6 sec98: mfhi $6 lhu $6,2($0) mfhi $6 or $3,$6,$6 sec99: mflo $6 lb $6,5($0) lh $6,0($0) or $1,$6,$6 sec100: lh $6,16($0) nop nop or $1,$6,$6 sec101: lbu $6,16($0) nop xor $6,$5,$2 or $4,$6,$6 sec102: lhu $6,0($0) nop slti $6,$2,-31619 or $3,$6,$6 sec103: lb $6,3($0) nop mflo $6 or $4,$6,$6 sec104: lb $6,12($0) nop lhu $6,8($0) or $5,$6,$6 sec105: lb $6,3($0) slt $6,$6,$2 nop or $3,$6,$6 sec106: lh $6,6($0) and $6,$4,$3 xor $6,$6,$5 or $3,$6,$6 sec107: lbu $6,15($0) sltu $6,$4,$3 sltiu $6,$1,-24003 or $3,$6,$6 sec108: lbu $6,15($0) xor $6,$3,$4 mfhi $6 or $3,$6,$6 sec109: lw $6,4($0) slt $6,$2,$4 lb $6,12($0) or $4,$6,$6 sec110: lhu $6,12($0) xori $6,$2,14468 nop or $3,$6,$6 sec111: lhu $6,8($0) sltiu $6,$4,-20470 nor $6,$5,$2 or $2,$6,$6 sec112: lbu $6,5($0) sltiu $6,$2,-32230 slti $6,$0,-26316 or $5,$6,$6 sec113: lw $6,8($0) ori $6,$0,54811 mflo $6 or $3,$6,$6 sec114: lhu $6,10($0) addiu $6,$1,-29663 lb $6,4($0) or $4,$6,$6 sec115: lh $6,2($0) mflo $6 nop or $2,$6,$6 sec116: lw $6,12($0) mfhi $6 nor $6,$3,$2 or $0,$6,$6 sec117: lh $6,12($0) mfhi $6 slti $6,$2,-17653 or $3,$6,$6 sec118: lb $6,2($0) mflo $6 mflo $6 or $2,$6,$6 sec119: lh $6,2($0) mfhi $6 lhu $6,8($0) or $1,$6,$6 sec120: lw $6,8($0) lh $6,0($0) nop or $3,$6,$6 sec121: lh $6,6($0) lh $6,2($0) xor $6,$2,$6 or $1,$6,$6 sec122: lbu $6,10($0) lw $6,16($0) lui $6,52043 or $3,$6,$6 sec123: lhu $6,4($0) lbu $6,14($0) mflo $6 or $1,$6,$6 sec124: lb $6,13($0) lbu $6,6($0) lhu $6,8($0) or $4,$6,$6
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r13 push %rax push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_UC_ht+0x10332, %rsi lea addresses_WC_ht+0x1dbb4, %rdi add %r13, %r13 mov $48, %rcx rep movsb nop nop nop sub $22787, %r10 lea addresses_WT_ht+0x3f8c, %rax nop nop nop nop nop xor %rcx, %rcx vmovups (%rax), %ymm5 vextracti128 $1, %ymm5, %xmm5 vpextrq $1, %xmm5, %rdi nop cmp $50066, %rax lea addresses_UC_ht+0x191e4, %rsi nop nop nop sub %rbx, %rbx movups (%rsi), %xmm0 vpextrq $1, %xmm0, %rax nop nop nop cmp %r13, %r13 lea addresses_UC_ht+0x11c24, %rsi lea addresses_UC_ht+0xc5e4, %rdi inc %rdx mov $63, %rcx rep movsq nop cmp $37540, %rax lea addresses_WC_ht+0x1c2c4, %rdx clflush (%rdx) nop nop nop nop and $23577, %rcx mov (%rdx), %esi nop nop nop nop nop xor $28126, %rcx lea addresses_UC_ht+0x1dfe4, %rbx nop cmp %r10, %r10 movups (%rbx), %xmm0 vpextrq $0, %xmm0, %rsi nop nop mfence lea addresses_WT_ht+0x11380, %rsi nop nop nop sub %rax, %rax mov (%rsi), %r10w nop sub $57971, %rbx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rax pop %r13 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r13 push %r9 push %rax push %rbx push %rdx // Store lea addresses_UC+0x1a3cc, %r13 nop nop nop nop nop xor %rax, %rax movl $0x51525354, (%r13) nop nop nop nop nop and %r13, %r13 // Store lea addresses_normal+0x1c264, %r12 nop nop and %r10, %r10 movb $0x51, (%r12) nop nop nop nop nop and $12350, %r13 // Faulty Load lea addresses_D+0x51e4, %rdx add %rax, %rax movb (%rdx), %r10b lea oracles, %rbx and $0xff, %r10 shlq $12, %r10 mov (%rbx,%r10,1), %r10 pop %rdx pop %rbx pop %rax pop %r9 pop %r13 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_D', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 2, 'type': 'addresses_UC', 'AVXalign': False, 'size': 4}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_normal', 'AVXalign': False, 'size': 1}} [Faulty Load] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_D', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'same': False, 'congruent': 1, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'same': True, 'congruent': 4, 'type': 'addresses_WC_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'} {'src': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 3, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_UC_ht'}} {'src': {'NT': False, 'same': True, 'congruent': 4, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'src': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} {'src': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
/** * @file oglplus/shapes/cage.hpp * @brief Cage builder * * @author Matus Chochlik * * Copyright 2010-2013 Matus Chochlik. 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) */ #pragma once #ifndef OGLPLUS_SHAPES_CAGE_1107121519_HPP #define OGLPLUS_SHAPES_CAGE_1107121519_HPP #include <oglplus/face_mode.hpp> #include <oglplus/shapes/draw.hpp> #include <oglplus/shapes/vert_attr_info.hpp> #include <oglplus/matrix.hpp> #include <oglplus/sphere.hpp> namespace oglplus { namespace shapes { /// Class providing vertex attributes and instructions for rendering of a cage class Cage : public DrawingInstructionWriter { private: Vector<GLdouble, 3> _size; Vector<GLdouble, 3> _barw; Vector<GLdouble, 3> _divs; static const Matrix<GLdouble, 3, 3>& _face_mat(GLuint face); GLdouble _face_size(GLuint face, GLuint axis) const { return std::fabs(Dot(_face_mat(face).Row(axis), _size)); } GLdouble _face_barw(GLuint face, GLuint axis) const { return std::fabs(Dot(_face_mat(face).Row(axis), _barw)); } GLuint _face_divs(GLuint face, GLuint axis) const { return GLuint(std::fabs(Dot(_face_mat(face).Row(axis), _divs))); } static const Vector<GLdouble, 3> _face_vec( GLuint face, const Vector<GLdouble, 3> vec ) { return _face_mat(face)*vec; } template <typename Iter> static Iter _write(Iter iter, const Vector<GLdouble, 3>& vec) { *iter++ = vec.x(); *iter++ = vec.y(); *iter++ = vec.z(); return iter; } GLuint _vert_count(void) const; // primitive-restart-index GLuint _pri(void) const { return _vert_count(); } GLuint _index_count(void) const; public: /// Constructs a unit cage centered at the origin Cage(void) : _size(1, 1, 1) , _barw(0.15, 0.15, 0.15) , _divs(4, 4, 4) { } /// Constructs a cage with width, height, depth Cage( GLdouble xs, GLdouble ys, GLdouble zs, GLdouble xb, GLdouble yb, GLdouble zb, GLuint xd, GLuint yd, GLuint zd ): _size(xs, ys, zs) , _barw(xb, yb, zb) , _divs(xd, yd, zd) { assert(xs > 0.0); assert(ys > 0.0); assert(zs > 0.0); assert(xd > 0); assert(yd > 0); assert(zd > 0); assert(xs > xb*(xd-1)); assert(ys > yb*(yd-1)); assert(zs > zb*(zd-1)); } /// Returns the winding direction of faces FaceOrientation FaceWinding(void) const { return FaceOrientation::CW; } typedef GLuint (Cage::*VertexAttribFunc)(std::vector<GLfloat>&) const; std::vector<GLfloat> _positions(void) const; GLuint Positions(std::vector<GLfloat>& dest) const { dest = _positions(); return 3; } /// Makes the vertices and returns the number of values per vertex template <typename T> GLuint Positions(std::vector<T>& dest) const { auto p = _positions(); dest.assign(p.begin(), p.end()); return 3; } std::vector<GLfloat> _normals(void) const; GLuint Normals(std::vector<GLfloat>& dest) const { dest = _normals(); return 3; } /// Makes the normals and returns the number of values per vertex template <typename T> GLuint Normals(std::vector<T>& dest) const { auto n = _normals(); dest.assign(n.begin(), n.end()); return 3; } std::vector<GLfloat> _tangents(void) const; GLuint Tangents(std::vector<GLfloat>& dest) const { dest = _tangents(); return 3; } /// Makes the tangents and returns the number of values per vertex template <typename T> GLuint Tangents(std::vector<T>& dest) const { auto t = _tangents(); dest.assign(t.begin(), t.end()); return 3; } std::vector<GLfloat> _tex_coords(void) const; GLuint TexCoordinates(std::vector<GLfloat>& dest) const { dest = _tex_coords(); return 3; } /// Makes the texture coordinates and returns the number of values per vertex template <typename T> GLuint TexCoordinates(std::vector<T>& dest) const { auto t = _tex_coords(); dest.assign(t.begin(), t.end()); return 3; } #if OGLPLUS_DOCUMENTATION_ONLY /// Vertex attribute information for this shape builder /** Cage provides build functions for the following named * vertex attributes: * - "Position" the vertex positions (Positions) * - "Normal" the vertex normal vectors (Normals) * - "Tangent" the vertex tangent vector (Tangents) * - "TexCoord" the ST texture coordinates (TexCoordinates) */ typedef VertexAttribsInfo<Cage> VertexAttribs; #else typedef VertexAttribsInfo< Cage, std::tuple< VertexPositionsTag, VertexNormalsTag, VertexTangentsTag, VertexTexCoordinatesTag > > VertexAttribs; #endif /// Queries the bounding sphere coordinates and dimensions template <typename T> void BoundingSphere(oglplus::Sphere<T>& bounding_sphere) const { bounding_sphere = oglplus::Sphere<T>( T(0), T(0), T(0), Length(_size) ); } /// The type of the index container returned by Indices() typedef std::vector<GLuint> IndexArray; /// Returns element indices that are used with the drawing instructions IndexArray Indices(void) const; /// Returns the instructions for rendering of faces DrawingInstructions Instructions(void) const; }; } // shapes } // oglplus #if !OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY) #include <oglplus/shapes/cage.ipp> #endif #endif // include guard
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_TekWall_Sloped_Left_SM_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass TekWall_Sloped_Left_SM.TekWall_Sloped_Left_SM_C // 0x0008 (0x0AF0 - 0x0AE8) class ATekWall_Sloped_Left_SM_C : public ABaseWall_Sloped_Left_SM_C { public: class UStaticMeshComponent* StaticMesh1; // 0x0AE8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass TekWall_Sloped_Left_SM.TekWall_Sloped_Left_SM_C"); return ptr; } void UserConstructionScript(); void ExecuteUbergraph_TekWall_Sloped_Left_SM(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
;***************************************************************************** ;* x86util.asm: x86 utility macros ;***************************************************************************** ;* Copyright (C) 2008-2014 x264 project ;* ;* Authors: Holger Lubitz <holger@lubitz.org> ;* Loren Merritt <lorenm@u.washington.edu> ;* ;* 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 02111, USA. ;* ;* This program is also available under a commercial proprietary license. ;* For more information, contact us at licensing@x264.com. ;***************************************************************************** %assign FENC_STRIDE 16 %assign FDEC_STRIDE 32 %assign SIZEOF_PIXEL 1 %assign SIZEOF_DCTCOEF 2 %define pixel byte %define vpbroadcastdct vpbroadcastw %define vpbroadcastpix vpbroadcastb %if HIGH_BIT_DEPTH %assign SIZEOF_PIXEL 2 %assign SIZEOF_DCTCOEF 4 %define pixel word %define vpbroadcastdct vpbroadcastd %define vpbroadcastpix vpbroadcastw %endif %assign FENC_STRIDEB SIZEOF_PIXEL*FENC_STRIDE %assign FDEC_STRIDEB SIZEOF_PIXEL*FDEC_STRIDE %assign PIXEL_MAX ((1 << BIT_DEPTH)-1) %macro FIX_STRIDES 1-* %if HIGH_BIT_DEPTH %rep %0 add %1, %1 %rotate 1 %endrep %endif %endmacro %macro SBUTTERFLY 4 %ifidn %1, dqqq vperm2i128 m%4, m%2, m%3, q0301 ; punpckh vinserti128 m%2, m%2, xm%3, 1 ; punpckl %elif avx_enabled && mmsize >= 16 punpckh%1 m%4, m%2, m%3 punpckl%1 m%2, m%3 %else mova m%4, m%2 punpckl%1 m%2, m%3 punpckh%1 m%4, m%3 %endif SWAP %3, %4 %endmacro %macro SBUTTERFLY2 4 punpckl%1 m%4, m%2, m%3 punpckh%1 m%2, m%2, m%3 SWAP %2, %4, %3 %endmacro %macro TRANSPOSE4x4W 5 SBUTTERFLY wd, %1, %2, %5 SBUTTERFLY wd, %3, %4, %5 SBUTTERFLY dq, %1, %3, %5 SBUTTERFLY dq, %2, %4, %5 SWAP %2, %3 %endmacro %macro TRANSPOSE2x4x4W 5 SBUTTERFLY wd, %1, %2, %5 SBUTTERFLY wd, %3, %4, %5 SBUTTERFLY dq, %1, %3, %5 SBUTTERFLY dq, %2, %4, %5 SBUTTERFLY qdq, %1, %2, %5 SBUTTERFLY qdq, %3, %4, %5 %endmacro %macro TRANSPOSE4x4D 5 SBUTTERFLY dq, %1, %2, %5 SBUTTERFLY dq, %3, %4, %5 SBUTTERFLY qdq, %1, %3, %5 SBUTTERFLY qdq, %2, %4, %5 SWAP %2, %3 %endmacro %macro TRANSPOSE8x8W 9-11 %if ARCH_X86_64 SBUTTERFLY wd, %1, %2, %9 SBUTTERFLY wd, %3, %4, %9 SBUTTERFLY wd, %5, %6, %9 SBUTTERFLY wd, %7, %8, %9 SBUTTERFLY dq, %1, %3, %9 SBUTTERFLY dq, %2, %4, %9 SBUTTERFLY dq, %5, %7, %9 SBUTTERFLY dq, %6, %8, %9 SBUTTERFLY qdq, %1, %5, %9 SBUTTERFLY qdq, %2, %6, %9 SBUTTERFLY qdq, %3, %7, %9 SBUTTERFLY qdq, %4, %8, %9 SWAP %2, %5 SWAP %4, %7 %else ; in: m0..m7, unless %11 in which case m6 is in %9 ; out: m0..m7, unless %11 in which case m4 is in %10 ; spills into %9 and %10 %if %0<11 movdqa %9, m%7 %endif SBUTTERFLY wd, %1, %2, %7 movdqa %10, m%2 movdqa m%7, %9 SBUTTERFLY wd, %3, %4, %2 SBUTTERFLY wd, %5, %6, %2 SBUTTERFLY wd, %7, %8, %2 SBUTTERFLY dq, %1, %3, %2 movdqa %9, m%3 movdqa m%2, %10 SBUTTERFLY dq, %2, %4, %3 SBUTTERFLY dq, %5, %7, %3 SBUTTERFLY dq, %6, %8, %3 SBUTTERFLY qdq, %1, %5, %3 SBUTTERFLY qdq, %2, %6, %3 movdqa %10, m%2 movdqa m%3, %9 SBUTTERFLY qdq, %3, %7, %2 SBUTTERFLY qdq, %4, %8, %2 SWAP %2, %5 SWAP %4, %7 %if %0<11 movdqa m%5, %10 %endif %endif %endmacro %macro WIDEN_SXWD 2 punpckhwd m%2, m%1 psrad m%2, 16 %if cpuflag(sse4) pmovsxwd m%1, m%1 %else punpcklwd m%1, m%1 psrad m%1, 16 %endif %endmacro %macro ABSW 2-3 ; dst, src, tmp (tmp used only if dst==src) %if cpuflag(ssse3) pabsw %1, %2 %elifidn %3, sign ; version for pairing with PSIGNW: modifies src pxor %1, %1 pcmpgtw %1, %2 pxor %2, %1 psubw %2, %1 SWAP %1, %2 %elifidn %1, %2 pxor %3, %3 psubw %3, %1 pmaxsw %1, %3 %elifid %2 pxor %1, %1 psubw %1, %2 pmaxsw %1, %2 %elif %0 == 2 pxor %1, %1 psubw %1, %2 pmaxsw %1, %2 %else mova %1, %2 pxor %3, %3 psubw %3, %1 pmaxsw %1, %3 %endif %endmacro %macro ABSW2 6 ; dst1, dst2, src1, src2, tmp, tmp %if cpuflag(ssse3) pabsw %1, %3 pabsw %2, %4 %elifidn %1, %3 pxor %5, %5 pxor %6, %6 psubw %5, %1 psubw %6, %2 pmaxsw %1, %5 pmaxsw %2, %6 %else pxor %1, %1 pxor %2, %2 psubw %1, %3 psubw %2, %4 pmaxsw %1, %3 pmaxsw %2, %4 %endif %endmacro %macro ABSB 2 %if cpuflag(ssse3) pabsb %1, %1 %else pxor %2, %2 psubb %2, %1 pminub %1, %2 %endif %endmacro %macro ABSD 2-3 %if cpuflag(ssse3) pabsd %1, %2 %else %define %%s %2 %if %0 == 3 mova %3, %2 %define %%s %3 %endif pxor %1, %1 pcmpgtd %1, %%s pxor %%s, %1 psubd %%s, %1 SWAP %1, %%s %endif %endmacro %macro PSIGN 3-4 %if cpuflag(ssse3) && %0 == 4 psign%1 %2, %3, %4 %elif cpuflag(ssse3) psign%1 %2, %3 %elif %0 == 4 pxor %2, %3, %4 psub%1 %2, %4 %else pxor %2, %3 psub%1 %2, %3 %endif %endmacro %define PSIGNW PSIGN w, %define PSIGND PSIGN d, %macro SPLATB_LOAD 3 %if cpuflag(ssse3) movd %1, [%2-3] pshufb %1, %3 %else movd %1, [%2-3] ;to avoid crossing a cacheline punpcklbw %1, %1 SPLATW %1, %1, 3 %endif %endmacro %imacro SPLATW 2-3 0 %if cpuflag(avx2) && %3 == 0 vpbroadcastw %1, %2 %else PSHUFLW %1, %2, (%3)*q1111 %if mmsize == 16 punpcklqdq %1, %1 %endif %endif %endmacro %imacro SPLATD 2-3 0 %if mmsize == 16 pshufd %1, %2, (%3)*q1111 %else pshufw %1, %2, (%3)*q0101 + ((%3)+1)*q1010 %endif %endmacro %macro CLIPW 3 ;(dst, min, max) pmaxsw %1, %2 pminsw %1, %3 %endmacro %macro HADDD 2 ; sum junk %if sizeof%1 == 32 %define %2 xmm%2 vextracti128 %2, %1, 1 %define %1 xmm%1 paddd %1, %2 %endif %if mmsize >= 16 %if cpuflag(xop) && sizeof%1 == 16 vphadddq %1, %1 %endif movhlps %2, %1 paddd %1, %2 %endif %if notcpuflag(xop) || sizeof%1 != 16 PSHUFLW %2, %1, q0032 paddd %1, %2 %endif %undef %1 %undef %2 %endmacro %macro HADDW 2 ; reg, tmp %if cpuflag(xop) && sizeof%1 == 16 vphaddwq %1, %1 movhlps %2, %1 paddd %1, %2 %else pmaddwd %1, [pw_1] HADDD %1, %2 %endif %endmacro %macro HADDUWD 2 %if cpuflag(xop) && sizeof%1 == 16 vphadduwd %1, %1 %else psrld %2, %1, 16 pslld %1, 16 psrld %1, 16 paddd %1, %2 %endif %endmacro %macro HADDUW 2 %if cpuflag(xop) && sizeof%1 == 16 vphadduwq %1, %1 movhlps %2, %1 paddd %1, %2 %else HADDUWD %1, %2 HADDD %1, %2 %endif %endmacro %macro PALIGNR 4-5 ; [dst,] src1, src2, imm, tmp ; AVX2 version uses a precalculated extra input that ; can be re-used across calls %if sizeof%1==32 ; %3 = abcdefgh ijklmnop (lower address) ; %2 = ABCDEFGH IJKLMNOP (higher address) ; vperm2i128 %5, %2, %3, q0003 ; %5 = ijklmnop ABCDEFGH %if %4 < 16 palignr %1, %5, %3, %4 ; %1 = bcdefghi jklmnopA %else palignr %1, %2, %5, %4-16 ; %1 = pABCDEFG HIJKLMNO %endif %elif cpuflag(ssse3) %if %0==5 palignr %1, %2, %3, %4 %else palignr %1, %2, %3 %endif %else %define %%dst %1 %if %0==5 %ifnidn %1, %2 mova %%dst, %2 %endif %rotate 1 %endif %ifnidn %4, %2 mova %4, %2 %endif %if mmsize==8 psllq %%dst, (8-%3)*8 psrlq %4, %3*8 %else pslldq %%dst, 16-%3 psrldq %4, %3 %endif por %%dst, %4 %endif %endmacro %macro PSHUFLW 1+ %if mmsize == 8 pshufw %1 %else pshuflw %1 %endif %endmacro ; shift a mmxreg by n bytes, or a xmmreg by 2*n bytes ; values shifted in are undefined ; faster if dst==src %define PSLLPIX PSXLPIX l, -1, ;dst, src, shift %define PSRLPIX PSXLPIX r, 1, ;dst, src, shift %macro PSXLPIX 5 %if mmsize == 8 %if %5&1 ps%1lq %3, %4, %5*8 %else pshufw %3, %4, (q3210<<8>>(8+%2*%5))&0xff %endif %else ps%1ldq %3, %4, %5*2 %endif %endmacro %macro DEINTB 5 ; mask, reg1, mask, reg2, optional src to fill masks from %ifnum %5 pand m%3, m%5, m%4 ; src .. y6 .. y4 pand m%1, m%5, m%2 ; dst .. y6 .. y4 %else mova m%1, %5 pand m%3, m%1, m%4 ; src .. y6 .. y4 pand m%1, m%1, m%2 ; dst .. y6 .. y4 %endif psrlw m%2, 8 ; dst .. y7 .. y5 psrlw m%4, 8 ; src .. y7 .. y5 %endmacro %macro SUMSUB_BA 3-4 %if %0==3 padd%1 m%2, m%3 padd%1 m%3, m%3 psub%1 m%3, m%2 %elif avx_enabled padd%1 m%4, m%2, m%3 psub%1 m%3, m%2 SWAP %2, %4 %else mova m%4, m%2 padd%1 m%2, m%3 psub%1 m%3, m%4 %endif %endmacro %macro SUMSUB_BADC 5-6 %if %0==6 SUMSUB_BA %1, %2, %3, %6 SUMSUB_BA %1, %4, %5, %6 %else padd%1 m%2, m%3 padd%1 m%4, m%5 padd%1 m%3, m%3 padd%1 m%5, m%5 psub%1 m%3, m%2 psub%1 m%5, m%4 %endif %endmacro %macro HADAMARD4_V 4+ SUMSUB_BADC w, %1, %2, %3, %4 SUMSUB_BADC w, %1, %3, %2, %4 %endmacro %macro HADAMARD8_V 8+ SUMSUB_BADC w, %1, %2, %3, %4 SUMSUB_BADC w, %5, %6, %7, %8 SUMSUB_BADC w, %1, %3, %2, %4 SUMSUB_BADC w, %5, %7, %6, %8 SUMSUB_BADC w, %1, %5, %2, %6 SUMSUB_BADC w, %3, %7, %4, %8 %endmacro %macro TRANS_SSE2 5-6 ; TRANSPOSE2x2 ; %1: transpose width (d/q) - use SBUTTERFLY qdq for dq ; %2: ord/unord (for compat with sse4, unused) ; %3/%4: source regs ; %5/%6: tmp regs %ifidn %1, d %define mask [mask_10] %define shift 16 %elifidn %1, q %define mask [mask_1100] %define shift 32 %endif %if %0==6 ; less dependency if we have two tmp mova m%5, mask ; ff00 mova m%6, m%4 ; x5x4 psll%1 m%4, shift ; x4.. pand m%6, m%5 ; x5.. pandn m%5, m%3 ; ..x0 psrl%1 m%3, shift ; ..x1 por m%4, m%5 ; x4x0 por m%3, m%6 ; x5x1 %else ; more dependency, one insn less. sometimes faster, sometimes not mova m%5, m%4 ; x5x4 psll%1 m%4, shift ; x4.. pxor m%4, m%3 ; (x4^x1)x0 pand m%4, mask ; (x4^x1).. pxor m%3, m%4 ; x4x0 psrl%1 m%4, shift ; ..(x1^x4) pxor m%5, m%4 ; x5x1 SWAP %4, %3, %5 %endif %endmacro %macro TRANS_SSE4 5-6 ; see above %ifidn %1, d %ifidn %2, ord psrl%1 m%5, m%3, 16 pblendw m%5, m%4, q2222 psll%1 m%4, 16 pblendw m%4, m%3, q1111 SWAP %3, %5 %else %if avx_enabled pblendw m%5, m%3, m%4, q2222 SWAP %3, %5 %else mova m%5, m%3 pblendw m%3, m%4, q2222 %endif psll%1 m%4, 16 psrl%1 m%5, 16 por m%4, m%5 %endif %elifidn %1, q shufps m%5, m%3, m%4, q3131 shufps m%3, m%3, m%4, q2020 SWAP %4, %5 %endif %endmacro %macro TRANS_XOP 5-6 %ifidn %1, d vpperm m%5, m%3, m%4, [transd_shuf1] vpperm m%3, m%3, m%4, [transd_shuf2] %elifidn %1, q shufps m%5, m%3, m%4, q3131 shufps m%3, m%4, q2020 %endif SWAP %4, %5 %endmacro %macro HADAMARD 5-6 ; %1=distance in words (0 for vertical pass, 1/2/4 for horizontal passes) ; %2=sumsub/max/amax (sum and diff / maximum / maximum of absolutes) ; %3/%4: regs ; %5(%6): tmpregs %if %1!=0 ; have to reorder stuff for horizontal op %ifidn %2, sumsub %define ORDER ord ; sumsub needs order because a-b != b-a unless a=b %else %define ORDER unord ; if we just max, order doesn't matter (allows pblendw+or in sse4) %endif %if %1==1 TRANS d, ORDER, %3, %4, %5, %6 %elif %1==2 %if mmsize==8 SBUTTERFLY dq, %3, %4, %5 %else TRANS q, ORDER, %3, %4, %5, %6 %endif %elif %1==4 SBUTTERFLY qdq, %3, %4, %5 %elif %1==8 SBUTTERFLY dqqq, %3, %4, %5 %endif %endif %ifidn %2, sumsub SUMSUB_BA w, %3, %4, %5 %else %ifidn %2, amax %if %0==6 ABSW2 m%3, m%4, m%3, m%4, m%5, m%6 %else ABSW m%3, m%3, m%5 ABSW m%4, m%4, m%5 %endif %endif pmaxsw m%3, m%4 %endif %endmacro %macro HADAMARD2_2D 6-7 sumsub HADAMARD 0, sumsub, %1, %2, %5 HADAMARD 0, sumsub, %3, %4, %5 SBUTTERFLY %6, %1, %2, %5 %ifnum %7 HADAMARD 0, amax, %1, %2, %5, %7 %else HADAMARD 0, %7, %1, %2, %5 %endif SBUTTERFLY %6, %3, %4, %5 %ifnum %7 HADAMARD 0, amax, %3, %4, %5, %7 %else HADAMARD 0, %7, %3, %4, %5 %endif %endmacro %macro HADAMARD4_2D 5-6 sumsub HADAMARD2_2D %1, %2, %3, %4, %5, wd HADAMARD2_2D %1, %3, %2, %4, %5, dq, %6 SWAP %2, %3 %endmacro %macro HADAMARD4_2D_SSE 5-6 sumsub HADAMARD 0, sumsub, %1, %2, %5 ; 1st V row 0 + 1 HADAMARD 0, sumsub, %3, %4, %5 ; 1st V row 2 + 3 SBUTTERFLY wd, %1, %2, %5 ; %1: m0 1+0 %2: m1 1+0 SBUTTERFLY wd, %3, %4, %5 ; %3: m0 3+2 %4: m1 3+2 HADAMARD2_2D %1, %3, %2, %4, %5, dq SBUTTERFLY qdq, %1, %2, %5 HADAMARD 0, %6, %1, %2, %5 ; 2nd H m1/m0 row 0+1 SBUTTERFLY qdq, %3, %4, %5 HADAMARD 0, %6, %3, %4, %5 ; 2nd H m1/m0 row 2+3 %endmacro %macro HADAMARD8_2D 9-10 sumsub HADAMARD2_2D %1, %2, %3, %4, %9, wd HADAMARD2_2D %5, %6, %7, %8, %9, wd HADAMARD2_2D %1, %3, %2, %4, %9, dq HADAMARD2_2D %5, %7, %6, %8, %9, dq HADAMARD2_2D %1, %5, %3, %7, %9, qdq, %10 HADAMARD2_2D %2, %6, %4, %8, %9, qdq, %10 %ifnidn %10, amax SWAP %2, %5 SWAP %4, %7 %endif %endmacro ; doesn't include the "pmaddubsw hmul_8p" pass %macro HADAMARD8_2D_HMUL 10 HADAMARD4_V %1, %2, %3, %4, %9 HADAMARD4_V %5, %6, %7, %8, %9 SUMSUB_BADC w, %1, %5, %2, %6, %9 HADAMARD 2, sumsub, %1, %5, %9, %10 HADAMARD 2, sumsub, %2, %6, %9, %10 SUMSUB_BADC w, %3, %7, %4, %8, %9 HADAMARD 2, sumsub, %3, %7, %9, %10 HADAMARD 2, sumsub, %4, %8, %9, %10 HADAMARD 1, amax, %1, %5, %9, %10 HADAMARD 1, amax, %2, %6, %9, %5 HADAMARD 1, amax, %3, %7, %9, %5 HADAMARD 1, amax, %4, %8, %9, %5 %endmacro %macro SUMSUB2_AB 4 %if cpuflag(xop) pmacs%1%1 m%4, m%3, [p%1_m2], m%2 pmacs%1%1 m%2, m%2, [p%1_2], m%3 %elifnum %3 psub%1 m%4, m%2, m%3 psub%1 m%4, m%3 padd%1 m%2, m%2 padd%1 m%2, m%3 %else mova m%4, m%2 padd%1 m%2, m%2 padd%1 m%2, %3 psub%1 m%4, %3 psub%1 m%4, %3 %endif %endmacro %macro SUMSUBD2_AB 5 %ifnum %4 psra%1 m%5, m%2, 1 ; %3: %3>>1 psra%1 m%4, m%3, 1 ; %2: %2>>1 padd%1 m%4, m%2 ; %3: %3>>1+%2 psub%1 m%5, m%3 ; %2: %2>>1-%3 SWAP %2, %5 SWAP %3, %4 %else mova %5, m%2 mova %4, m%3 psra%1 m%3, 1 ; %3: %3>>1 psra%1 m%2, 1 ; %2: %2>>1 padd%1 m%3, %5 ; %3: %3>>1+%2 psub%1 m%2, %4 ; %2: %2>>1-%3 %endif %endmacro %macro DCT4_1D 5 %ifnum %5 SUMSUB_BADC w, %4, %1, %3, %2, %5 SUMSUB_BA w, %3, %4, %5 SUMSUB2_AB w, %1, %2, %5 SWAP %1, %3, %4, %5, %2 %else SUMSUB_BADC w, %4, %1, %3, %2 SUMSUB_BA w, %3, %4 mova [%5], m%2 SUMSUB2_AB w, %1, [%5], %2 SWAP %1, %3, %4, %2 %endif %endmacro %macro IDCT4_1D 6-7 %ifnum %6 SUMSUBD2_AB %1, %3, %5, %7, %6 ; %3: %3>>1-%5 %5: %3+%5>>1 SUMSUB_BA %1, %4, %2, %7 ; %4: %2+%4 %2: %2-%4 SUMSUB_BADC %1, %5, %4, %3, %2, %7 ; %5: %2+%4 + (%3+%5>>1) ; %4: %2+%4 - (%3+%5>>1) ; %3: %2-%4 + (%3>>1-%5) ; %2: %2-%4 - (%3>>1-%5) %else %ifidn %1, w SUMSUBD2_AB %1, %3, %5, [%6], [%6+16] %else SUMSUBD2_AB %1, %3, %5, [%6], [%6+32] %endif SUMSUB_BA %1, %4, %2 SUMSUB_BADC %1, %5, %4, %3, %2 %endif SWAP %2, %5, %4 ; %2: %2+%4 + (%3+%5>>1) row0 ; %3: %2-%4 + (%3>>1-%5) row1 ; %4: %2-%4 - (%3>>1-%5) row2 ; %5: %2+%4 - (%3+%5>>1) row3 %endmacro %macro LOAD_DIFF 5-6 1 %if HIGH_BIT_DEPTH %if %6 ; %5 aligned? mova %1, %4 psubw %1, %5 %else movu %1, %4 movu %2, %5 psubw %1, %2 %endif %else ; !HIGH_BIT_DEPTH %ifidn %3, none movh %1, %4 movh %2, %5 punpcklbw %1, %2 punpcklbw %2, %2 psubw %1, %2 %else movh %1, %4 punpcklbw %1, %3 movh %2, %5 punpcklbw %2, %3 psubw %1, %2 %endif %endif ; HIGH_BIT_DEPTH %endmacro %macro LOAD_DIFF8x4 8 ; 4x dst, 1x tmp, 1x mul, 2x ptr %if BIT_DEPTH == 8 && cpuflag(ssse3) movh m%2, [%8+%1*FDEC_STRIDE] movh m%1, [%7+%1*FENC_STRIDE] punpcklbw m%1, m%2 movh m%3, [%8+%2*FDEC_STRIDE] movh m%2, [%7+%2*FENC_STRIDE] punpcklbw m%2, m%3 movh m%4, [%8+%3*FDEC_STRIDE] movh m%3, [%7+%3*FENC_STRIDE] punpcklbw m%3, m%4 movh m%5, [%8+%4*FDEC_STRIDE] movh m%4, [%7+%4*FENC_STRIDE] punpcklbw m%4, m%5 pmaddubsw m%1, m%6 pmaddubsw m%2, m%6 pmaddubsw m%3, m%6 pmaddubsw m%4, m%6 %else LOAD_DIFF m%1, m%5, m%6, [%7+%1*FENC_STRIDEB], [%8+%1*FDEC_STRIDEB] LOAD_DIFF m%2, m%5, m%6, [%7+%2*FENC_STRIDEB], [%8+%2*FDEC_STRIDEB] LOAD_DIFF m%3, m%5, m%6, [%7+%3*FENC_STRIDEB], [%8+%3*FDEC_STRIDEB] LOAD_DIFF m%4, m%5, m%6, [%7+%4*FENC_STRIDEB], [%8+%4*FDEC_STRIDEB] %endif %endmacro %macro STORE_DCT 6 movq [%5+%6+ 0], m%1 movq [%5+%6+ 8], m%2 movq [%5+%6+16], m%3 movq [%5+%6+24], m%4 movhps [%5+%6+32], m%1 movhps [%5+%6+40], m%2 movhps [%5+%6+48], m%3 movhps [%5+%6+56], m%4 %endmacro %macro STORE_IDCT 4 movhps [r0-4*FDEC_STRIDE], %1 movh [r0-3*FDEC_STRIDE], %1 movhps [r0-2*FDEC_STRIDE], %2 movh [r0-1*FDEC_STRIDE], %2 movhps [r0+0*FDEC_STRIDE], %3 movh [r0+1*FDEC_STRIDE], %3 movhps [r0+2*FDEC_STRIDE], %4 movh [r0+3*FDEC_STRIDE], %4 %endmacro %macro LOAD_DIFF_8x4P 7-11 r0,r2,0,1 ; 4x dest, 2x temp, 2x pointer, increment, aligned? LOAD_DIFF m%1, m%5, m%7, [%8], [%9], %11 LOAD_DIFF m%2, m%6, m%7, [%8+r1], [%9+r3], %11 LOAD_DIFF m%3, m%5, m%7, [%8+2*r1], [%9+2*r3], %11 LOAD_DIFF m%4, m%6, m%7, [%8+r4], [%9+r5], %11 %if %10 lea %8, [%8+4*r1] lea %9, [%9+4*r3] %endif %endmacro ; 2xdst, 2xtmp, 2xsrcrow %macro LOAD_DIFF16x2_AVX2 6 pmovzxbw m%1, [r1+%5*FENC_STRIDE] pmovzxbw m%2, [r1+%6*FENC_STRIDE] pmovzxbw m%3, [r2+(%5-4)*FDEC_STRIDE] pmovzxbw m%4, [r2+(%6-4)*FDEC_STRIDE] psubw m%1, m%3 psubw m%2, m%4 %endmacro %macro DIFFx2 6-7 movh %3, %5 punpcklbw %3, %4 psraw %1, 6 paddsw %1, %3 movh %3, %6 punpcklbw %3, %4 psraw %2, 6 paddsw %2, %3 packuswb %2, %1 %endmacro ; (high depth) in: %1, %2, min to clip, max to clip, mem128 ; in: %1, tmp, %3, mem64 %macro STORE_DIFF 4-5 %if HIGH_BIT_DEPTH psrad %1, 6 psrad %2, 6 packssdw %1, %2 paddw %1, %5 CLIPW %1, %3, %4 mova %5, %1 %else movh %2, %4 punpcklbw %2, %3 psraw %1, 6 paddsw %1, %2 packuswb %1, %1 movh %4, %1 %endif %endmacro %macro SHUFFLE_MASK_W 8 %rep 8 %if %1>=0x80 db %1, %1 %else db %1*2 db %1*2+1 %endif %rotate 1 %endrep %endmacro ; instruction, accum, input, iteration (zero to swap, nonzero to add) %macro ACCUM 4 %if %4 %1 m%2, m%3 %else SWAP %2, %3 %endif %endmacro
; A269446: a(n) = n*(n^6 + n^3 + 1)*(n^6 - n^3 + 1)*(n^2 + n + 1)*(n^2 - n + 1)*(n + 1) + 1. ; 1,19,524287,581130733,91625968981,4768371582031,121871948002099,1899815864228857,20587884010836553,168856464709124011,1111111111111111111,6115909044841454629,29043636306420266077,121826690864620509223,459715689149916492091,1583455585752214704241,5037190915060954894609,14942027230321957802947,41660902667961039785743,109912203092239643840221,275941052631578947368421,662424832016551306279039,1526903676810398364086467,3391612314890486843723113,7282588256957615350925401,15158245029548803965250651,30658690608014475618984919,60386265349310831216943637,116048312964052164128548333,217973615949642553199244631,400779816206896551724137931,722355407332346539823809249,1277873588939747380541031457,2221339193279999324884908403,3798266944257473266711034911,6394607984527780308442957261,10609122649875979418919719029,17359221971967836881896586927,28034099579103634892287370323,44714042666548209930918273241,70481514601025641025641025641,109858404241720078965262101259,169415312355265195739719427047,258613603420486109878768921093,390960064489743555528220426621,585578449280908796570517800071,869333244926326187979597262939,1279680255301727941466580948817,1868467947605686541562499217713,2706975238481729585774419702051,3892548230229591836734693877551,5557293596373742578676911931069,7879403716418967349669786879237,11097832834124892930621135337183,15531219839131064226486652546531,21602168064970280078958581995081,29868253154491245231253916502649,41061445202310552245986983525307,56138011095652165931373963776503,76341418908412835325355686147061,103281311866185762711864406779661,139032270387890472660272230794679,186256854983341624264497690274027,248358340979608222424723302452673,329669641811735087525745798680641,435686197988821897112429141998291,573352114691143033129973591044159,751410597400064602523400427092397,980831801927439563490955781452693,1275333627958785735783178712064271,1652013794981614927536231884057971,2132114804102901616229953146908089,2741947174014594541063807855777417,3514000717681733693029076371283563,4488278680720638869491626295954951,5713895385466654457755990930505701,7250984720063682688334396667213469,9172974495450436172205687603706087,11569290494275982594206865277372283,14548564098806166089741452511749681,18242428870361502784810126582278481,22810004539250914091988149723207299,28443181749670586054587326688835407,35372837808267474310223682569565853,43876132851190463092812370815335461,54285057541336632875522658938453311,66996427932059205955259294168056579,82483550813324793676691035214702377,101309814051971756061534760165381273,124144491546329200451312931487339291,151781091873369897640449438202247191,185158623992888664845939971981348309,225386203013373809889616692754173997,273771474593959449759128628035755543,331853398686183737557838886609628171,401440002697135760758578320767017121,484651791534438302301345481297339489,583971588194530989529610991090697267,702301674474115814135999483752045663,843029207995496671706038611156809101 mov $2,17 mov $3,1 add $3,$0 lpb $2 sub $2,1 mul $3,$0 add $3,1 lpe mov $0,$3
; A167548: The fifth row of the ED1 array A167546 ; 24,240,960,2688,6144,12264,22200,37320,59208,89664,130704,184560,253680,340728,448584,580344,739320,929040,1153248,1415904,1721184,2073480,2477400,2937768,3459624,4048224,4709040,5447760,6270288,7182744,8191464,9303000,10524120,11861808,13323264,14915904,16647360,18525480,20558328,22754184,25121544,27669120,30405840,33340848,36483504,39843384,43430280,47254200,51325368,55654224,60251424,65127840,70294560,75762888,81544344,87650664,94093800,100885920,108039408,115566864,123481104,131795160,140522280,149675928,159269784,169317744,179833920,190832640,202328448,214336104,226870584,239947080,253581000,267787968,282583824,297984624,314006640,330666360,347980488,365965944,384639864,404019600,424122720,444967008,466570464,488951304,512127960,536119080,560943528,586620384,613168944,640608720,668959440,698241048,728473704,759677784,791873880,825082800,859325568,894623424,930997824,968470440,1007063160,1046798088,1087697544,1129784064,1173080400,1217609520,1263394608,1310459064,1358826504,1408520760,1459565880,1511986128,1565805984,1621050144,1677743520,1735911240,1795578648,1856771304,1919514984,1983835680,2049759600,2117313168,2186523024,2257416024,2330019240,2404359960,2480465688,2558364144,2638083264,2719651200,2803096320,2888447208,2975732664,3064981704,3156223560,3249487680,3344803728,3442201584,3541711344,3643363320,3747188040,3853216248,3961478904,4072007184,4184832480,4299986400,4417500768,4537407624,4659739224,4784528040,4911806760,5041608288,5173965744,5308912464,5446482000,5586708120,5729624808,5875266264,6023666904,6174861360,6328884480,6485771328,6645557184,6808277544,6973968120,7142664840,7314403848,7489221504,7667154384,7848239280,8032513200,8220013368,8410777224,8604842424,8802246840,9003028560,9207225888,9414877344,9626021664,9840697800,10058944920,10280802408,10506309864,10735507104,10968434160,11205131280,11445638928,11689997784,11938248744,12190432920,12446591640,12706766448,12970999104,13239331584,13511806080,13788465000,14069350968,14354506824,14643975624,14937800640,15236025360,15538693488,15845848944,16157535864,16473798600,16794681720,17120230008,17450488464,17785502304,18125316960,18469978080,18819531528,19174023384,19533499944,19898007720,20267593440,20642304048,21022186704,21407288784,21797657880,22193341800,22594388568,23000846424,23412763824,23830189440,24253172160,24681761088,25116005544,25555955064,26001659400,26453168520,26910532608,27373802064,27843027504,28318259760,28799549880,29286949128,29780508984,30280281144,30786317520,31298670240,31817391648,32342534304,32874150984,33412294680,33957018600,34508376168,35066421024 mov $1,$0 mov $3,$0 lpb $0,1 add $1,$0 sub $0,1 lpe mul $1,2 add $1,24 mov $2,75 mov $4,$3 lpb $2,1 add $1,$4 sub $2,1 lpe mov $6,$3 lpb $6,1 add $5,$4 sub $6,1 lpe mov $2,98 mov $4,$5 lpb $2,1 add $1,$4 sub $2,1 lpe mov $5,0 mov $6,$3 lpb $6,1 add $5,$4 sub $6,1 lpe mov $2,30 mov $4,$5 lpb $2,1 add $1,$4 sub $2,1 lpe mov $5,0 mov $6,$3 lpb $6,1 add $5,$4 sub $6,1 lpe mov $2,9 mov $4,$5 lpb $2,1 add $1,$4 sub $2,1 lpe
#pragma once #include "../../../JObject.hpp" namespace android::hardware::biometrics { class BiometricPrompt_AuthenticationCallback; } namespace android::hardware::biometrics { class BiometricPrompt_CryptoObject; } namespace android::os { class CancellationSignal; } namespace android::hardware::biometrics { class BiometricPrompt : public JObject { public: // Fields static jint BIOMETRIC_ACQUIRED_GOOD(); static jint BIOMETRIC_ACQUIRED_IMAGER_DIRTY(); static jint BIOMETRIC_ACQUIRED_INSUFFICIENT(); static jint BIOMETRIC_ACQUIRED_PARTIAL(); static jint BIOMETRIC_ACQUIRED_TOO_FAST(); static jint BIOMETRIC_ACQUIRED_TOO_SLOW(); static jint BIOMETRIC_ERROR_CANCELED(); static jint BIOMETRIC_ERROR_HW_NOT_PRESENT(); static jint BIOMETRIC_ERROR_HW_UNAVAILABLE(); static jint BIOMETRIC_ERROR_LOCKOUT(); static jint BIOMETRIC_ERROR_LOCKOUT_PERMANENT(); static jint BIOMETRIC_ERROR_NO_BIOMETRICS(); static jint BIOMETRIC_ERROR_NO_SPACE(); static jint BIOMETRIC_ERROR_TIMEOUT(); static jint BIOMETRIC_ERROR_UNABLE_TO_PROCESS(); static jint BIOMETRIC_ERROR_USER_CANCELED(); static jint BIOMETRIC_ERROR_VENDOR(); // QJniObject forward template<typename ...Ts> explicit BiometricPrompt(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} BiometricPrompt(QJniObject obj); // Constructors // Methods void authenticate(android::os::CancellationSignal arg0, JObject arg1, android::hardware::biometrics::BiometricPrompt_AuthenticationCallback arg2) const; void authenticate(android::hardware::biometrics::BiometricPrompt_CryptoObject arg0, android::os::CancellationSignal arg1, JObject arg2, android::hardware::biometrics::BiometricPrompt_AuthenticationCallback arg3) const; }; } // namespace android::hardware::biometrics
; ; z88dk library: Generic VDP support code ; ; int msx_vram(); ; ; Detects the VRAM size (in KB) ; ; $Id: gen_vram.asm,v 1.3 2016/06/16 19:30:25 dom Exp $ ; SECTION code_clib PUBLIC msx_vram PUBLIC _msx_vram INCLUDE "msx/vdp.inc" msx_vram: _msx_vram: ld hl,VRAM_SIZE ret
; A078049: Expansion of (1-x)/(1+x+2*x^2-x^3). ; Submitted by Simon Strandgaard ; 1,-2,0,5,-7,-3,22,-23,-24,92,-67,-141,367,-152,-723,1394,-100,-3411,5005,1717,-15138,16709,15284,-63840,49981,92983,-256785,120800,485753,-984138,133432,2320597,-3571599,-936163,10399958,-12099231,-9636848,44235268,-37060803,-61046581,179403455,-94371096,-325482395,693628042,-137034348,-1575704131,2543400869,470973045,-7133478914,8734933693,6002997180,-30606343480,27335282813,39880401327,-125157310433,72731790592,217463231601,-488084123218,125889450608,1067742027429,-1807605051863,-201989552387 mov $1,2 mov $3,1 lpb $0 sub $0,1 sub $3,$1 add $1,$3 add $2,$3 add $1,$2 sub $2,$1 add $3,$2 lpe add $0,1 mov $1,3 sub $3,$0 add $1,$3 sub $1,2 mov $0,$1
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r15 push %r9 push %rax push %rbp push %rcx push %rdi push %rsi lea addresses_normal_ht+0x15488, %rsi lea addresses_A_ht+0x66cc, %rdi nop nop nop nop nop sub %rax, %rax mov $105, %rcx rep movsw nop nop lfence lea addresses_WT_ht+0x135c8, %r15 nop nop xor $56649, %rdi mov $0x6162636465666768, %rbp movq %rbp, (%r15) nop nop nop nop sub %rcx, %rcx lea addresses_D_ht+0xff88, %r15 clflush (%r15) nop nop nop nop cmp $57127, %r9 mov (%r15), %rcx nop dec %rsi lea addresses_UC_ht+0xfa38, %rdi nop nop nop nop nop xor %rbp, %rbp movb $0x61, (%rdi) nop xor $26496, %rax lea addresses_A_ht+0x10dbc, %rsi lea addresses_A_ht+0x1df8, %rdi nop xor $33020, %r15 mov $26, %rcx rep movsw nop cmp $57989, %rbp lea addresses_WT_ht+0x1cd88, %r15 xor %r9, %r9 mov (%r15), %rbp nop xor $17769, %rcx lea addresses_UC_ht+0x17ad8, %rsi lea addresses_A_ht+0x110db, %rdi clflush (%rsi) nop nop nop nop and %r13, %r13 mov $76, %rcx rep movsb nop nop cmp %rcx, %rcx lea addresses_normal_ht+0x9088, %rdi nop nop nop xor %rax, %rax mov (%rdi), %r9w nop nop nop nop nop add $32630, %rcx pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r9 pop %r15 pop %r13 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r14 push %r15 push %r8 push %rbp push %rbx // Store lea addresses_RW+0xfe08, %r8 nop nop xor $50862, %rbx movl $0x51525354, (%r8) nop nop nop nop nop dec %r15 // Store lea addresses_US+0xc488, %r8 clflush (%r8) nop nop xor $60147, %r11 mov $0x5152535455565758, %r15 movq %r15, %xmm0 vmovups %ymm0, (%r8) nop nop sub %r8, %r8 // Store lea addresses_US+0xc488, %r8 nop and %r11, %r11 movl $0x51525354, (%r8) xor %r10, %r10 // Store lea addresses_A+0x14bc8, %r15 nop dec %r10 movw $0x5152, (%r15) and $2355, %r10 // Store lea addresses_A+0xdc88, %rbx clflush (%rbx) xor $50127, %rbp mov $0x5152535455565758, %r15 movq %r15, %xmm6 vmovups %ymm6, (%rbx) nop nop nop nop cmp %rbp, %rbp // Store mov $0x94e5f000000084f, %r14 nop nop nop sub %r10, %r10 movw $0x5152, (%r14) nop nop nop nop nop add %r15, %r15 // Faulty Load lea addresses_US+0xc488, %r10 cmp $22236, %r14 movb (%r10), %r15b lea oracles, %rbx and $0xff, %r15 shlq $12, %r15 mov (%rbx,%r15,1), %r15 pop %rbx pop %rbp pop %r8 pop %r15 pop %r14 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'size': 4, 'AVXalign': True, 'NT': False, 'congruent': 7, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_US', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_US', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_A', 'size': 2, 'AVXalign': True, 'NT': True, 'congruent': 5, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 3, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': True, 'NT': False, 'congruent': 8, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}} {'54': 1826} 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 */
object_const_def ; object_event constants const GOLDENRODNAMERATER_NAME_RATER GoldenrodNameRater_MapScripts: db 0 ; scene scripts db 0 ; callbacks GoldenrodNameRater: faceplayer opentext special NameRater waitbutton closetext end GoldenrodNameRaterBookshelf: jumpstd difficultbookshelf GoldenrodNameRaterRadio: jumpstd radio2 GoldenrodNameRater_MapEvents: db 0, 0 ; filler db 2 ; warp events warp_event 2, 7, GOLDENROD_CITY, 8 warp_event 3, 7, GOLDENROD_CITY, 8 db 0 ; coord events db 3 ; bg events bg_event 0, 1, BGEVENT_READ, GoldenrodNameRaterBookshelf bg_event 1, 1, BGEVENT_READ, GoldenrodNameRaterBookshelf bg_event 7, 1, BGEVENT_READ, GoldenrodNameRaterRadio db 1 ; object events object_event 2, 4, SPRITE_GENTLEMAN, SPRITEMOVEDATA_STANDING_DOWN, 2, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, GoldenrodNameRater, -1
; A040133: Continued fraction for sqrt(146). ; 12,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12 pow $1,$0 sub $1,2 gcd $1,$0 mul $1,12 mov $0,$1
#include "stdafx.h" #include "FFmpegAVDecoder.h" #include "Util/FFmpeg/FFmpegUtils.h" #include "UseLoggerLibBlackVision.h" namespace bv { // ********************************* // FFmpegAVDecoder::FFmpegAVDecoder ( AVAssetConstPtr asset ) : m_muted( false ) , m_paused( false ) { auto path = asset->GetStreamPath(); m_demuxer = std::unique_ptr< FFmpegDemuxer >( new FFmpegDemuxer( path ) ); m_demuxerThread = std::unique_ptr< FFmpegDemuxerThread >( new FFmpegDemuxerThread( m_demuxer.get() ) ); UInt64 videoDuration = 0, audioDuration = 0; FFmpegVideoStreamDecoder * videoStreamDecoder = nullptr; FFmpegAudioStreamDecoder * audioStreamDecoder = nullptr; if( asset->IsVideoEnabled() ) { auto vstreamIdx = m_demuxer->GetStreamIndex( AVMEDIA_TYPE_VIDEO ); if( vstreamIdx >= 0 ) { videoStreamDecoder = new FFmpegVideoStreamDecoder( asset, m_demuxer->GetFormatContext(), vstreamIdx, 10, m_demuxer.get() ); m_streams[ AVMEDIA_TYPE_VIDEO ] = std::move( std::unique_ptr< FFmpegVideoStreamDecoder >( videoStreamDecoder ) ); videoDuration = videoStreamDecoder->GetDuration(); m_videoStreamsDecoderThread = std::move( std::unique_ptr< FFmpegStreamsDecoderThread >( new FFmpegStreamsDecoderThread( videoStreamDecoder ) ) ); } } if( asset->IsAudioEnabled() ) { auto astreamIdx = m_demuxer->GetStreamIndex( AVMEDIA_TYPE_AUDIO ); if( astreamIdx >= 0 ) { audioStreamDecoder = new FFmpegAudioStreamDecoder( asset, m_demuxer->GetFormatContext(), astreamIdx, 100, m_demuxer.get() ); m_streams[ AVMEDIA_TYPE_AUDIO ] = std::move( std::unique_ptr< FFmpegAudioStreamDecoder >( audioStreamDecoder ) ); audioDuration = audioStreamDecoder->GetDuration(); m_audioStreamsDecoderThread = std::move( std::unique_ptr< FFmpegStreamsDecoderThread >( new FFmpegStreamsDecoderThread( audioStreamDecoder ) ) ); } } m_duration = ( std::max )( videoDuration, audioDuration ); m_demuxerThread->Start(); if( m_videoStreamsDecoderThread ) { m_videoDecoderThread = std::unique_ptr< AVDecoderThread >( new AVDecoderThread( videoStreamDecoder, m_timer ) ); m_videoStreamsDecoderThread->Start(); m_videoDecoderThread->Start(); } if( m_audioStreamsDecoderThread ) { m_audioDecoderThread = std::unique_ptr< AVDecoderThread >( new AVDecoderThread( audioStreamDecoder, m_timer ) ); m_audioStreamsDecoderThread->Start(); m_audioDecoderThread->Start(); } } // ********************************* // FFmpegAVDecoder::~FFmpegAVDecoder () { StopDecoding(); StopPlayer(); ClearQueues(); if( m_videoStreamsDecoderThread ) { m_videoStreamsDecoderThread->Kill(); m_videoStreamsDecoderThread->Join(); m_videoStreamsDecoderThread = nullptr; } if( m_audioStreamsDecoderThread ) { m_audioStreamsDecoderThread->Kill(); m_audioStreamsDecoderThread->Join(); m_audioStreamsDecoderThread = nullptr; } m_demuxerThread->Kill(); m_demuxerThread->Join(); m_demuxerThread = nullptr; for( auto & s : m_streams ) { s.second->FinishQueue(); } FlushBuffers(); if( m_videoDecoderThread ) { m_videoDecoderThread->Kill(); m_videoDecoderThread->Join(); m_videoDecoderThread = nullptr; } if( m_audioDecoderThread ) { m_audioDecoderThread->Kill(); m_audioDecoderThread->Join(); m_audioDecoderThread = nullptr; } m_streams.clear(); //force m_demuxer = nullptr; } // ********************************* // void FFmpegAVDecoder::Play () { RestartDecoding(); RestartPlayer(); if( m_paused ) m_timer.UnPause(); else m_timer.Start(); } // ********************************* // void FFmpegAVDecoder::Pause () { auto lastPTS = GetLastPlayedFramePTS(); m_timer.PauseOnAsync( lastPTS ); m_paused = true; //if( m_audioDecoderThread ) // m_audioDecoderThread->Pause(); //if( m_videoDecoderThread ) // m_videoDecoderThread->Pause(); } // ********************************* // void FFmpegAVDecoder::Stop () { m_timer.Pause(); StopDecoding(); StopPlayer(); ClearQueues(); m_timer.Reset(); } // ********************************* // bool FFmpegAVDecoder::GetVideoMediaData ( AVMediaData & mediaData ) { if( HasVideo() ) { return m_streams[ AVMEDIA_TYPE_VIDEO ]->PopData( mediaData ); } return false; } // ********************************* // bool FFmpegAVDecoder::GetAudioMediaData ( AVMediaData & mediaData ) { if( HasAudio() ) { return m_streams[ AVMEDIA_TYPE_AUDIO ]->PopData( mediaData ); } return false; } // *********************** // Jumps to frameTime. This function doesn't return to time before this function call. AVMediaData FFmpegAVDecoder::GetSingleFrame ( TimeType frameTime ) { AVMediaData data; if( HasVideo() ) { Seek( frameTime ); Play(); while( !GetVideoMediaData( data ) ); Stop(); } return data; } // ********************************* // bool FFmpegAVDecoder::NextDataReady ( AVMediaType type, UInt64 time, bool block ) { if( m_streams.count( type ) ) { return m_streams[ type ]->NextDataReady( time, block ); } return false; } // ********************************* // bool FFmpegAVDecoder::NextDataReady ( UInt64 time, bool block ) { bool result = true; for( auto & stream : m_streams ) { result &= stream.second->NextDataReady( time, block ); } return result; } // ********************************* // SizeType FFmpegAVDecoder::GetVideoFrameSize () const { if( HasVideo() ) { return static_cast< FFmpegVideoStreamDecoder * >( m_streams.at( AVMEDIA_TYPE_VIDEO ).get() )->GetFrameSize(); } return 0; } // ********************************* // UInt32 FFmpegAVDecoder::GetWidth () const { if( HasVideo() ) { return static_cast< FFmpegVideoStreamDecoder * >( m_streams.at( AVMEDIA_TYPE_VIDEO ).get() )->GetWidth(); } return 0; } // ********************************* // UInt32 FFmpegAVDecoder::GetHeight () const { if( HasVideo() ) { return static_cast< FFmpegVideoStreamDecoder * >( m_streams.at( AVMEDIA_TYPE_VIDEO ).get() )->GetHeight(); } return 0; } // ********************************* // Int32 FFmpegAVDecoder::GetSampleRate () const { if( HasAudio() ) { return static_cast< FFmpegAudioStreamDecoder * >( m_streams.at( AVMEDIA_TYPE_AUDIO ).get() )->GetSampleRate(); } return 0; } // ********************************* // AudioFormat FFmpegAVDecoder::GetAudioFormat () const { if( HasAudio() ) { return static_cast< FFmpegAudioStreamDecoder * >( m_streams.at( AVMEDIA_TYPE_AUDIO ).get() )->GetFormat(); } return AudioFormat::AF_TOTAL; } // ********************************* // UInt64 FFmpegAVDecoder::GetDuration () const { return m_duration; } // ********************************* // bool FFmpegAVDecoder::HasVideo () const { return ( m_streams.count( AVMEDIA_TYPE_VIDEO ) > 0 ); } // ********************************* // bool FFmpegAVDecoder::HasAudio () const { return ( m_streams.count( AVMEDIA_TYPE_AUDIO ) > 0 ); } // ********************************* // void FFmpegAVDecoder::Seek ( Float64 time ) { LOG_MESSAGE( SeverityLevel::debug ) << "Seek to time: " << time; time = std::min( m_duration / 1000.0, time ); time = std::max( time, 0.0 ); StopDecoding(); StopPlayer(); ClearQueues(); m_timer.Pause(); m_timer.Reset(); FlushBuffers(); // seek all streams to the nearest keyframe for( auto & stream : m_streams ) { auto decoder = stream.second.get(); m_demuxer->Seek( decoder->ConvertTime( time ), decoder->GetStreamIdx() ); } // accurate seek all stream to the given frame if( m_streams.count( AVMediaType::AVMEDIA_TYPE_VIDEO ) > 0 ) { auto vdecoder = m_streams[ AVMediaType::AVMEDIA_TYPE_VIDEO ].get(); Int64 currPTS; if( Seek( vdecoder, FFmpegUtils::ConvertToMiliseconds( time ), &currPTS ) ) { vdecoder->SetOffset( currPTS ); } else { LOG_MESSAGE( SeverityLevel::debug ) << "VIDEO seek returns false."; } } if( m_streams.count( AVMediaType::AVMEDIA_TYPE_AUDIO ) > 0 ) { auto adecoder = m_streams[ AVMediaType::AVMEDIA_TYPE_AUDIO ].get(); Int64 currPTS; if( Seek( adecoder, FFmpegUtils::ConvertToMiliseconds( time ), &currPTS ) ) { adecoder->SetOffset( currPTS ); } else { LOG_MESSAGE( SeverityLevel::debug ) << "AUDIO seek returns false."; } } ProcessFirstAVFrame(); } // ********************************* // void FFmpegAVDecoder::FlushBuffers () { m_demuxer->ClearPacketQueue( false ); for( auto & stream : m_streams ) { stream.second->Reset(); } } // ********************************* // bool FFmpegAVDecoder::IsEOF () const { return m_demuxer->IsEOF(); } // ********************************* // bool FFmpegAVDecoder::IsFinished () const { bool finished = true; finished &= IsEOF(); for( auto & stream : m_streams ) { finished &= m_demuxer->IsPacketQueueEmpty( stream.second->GetStreamIdx() ); finished &= IsFinished( stream.first ); } return finished; } // ********************************* // bool FFmpegAVDecoder::IsFinished ( AVMediaType steamId ) const { bool finished = true; if( m_streams.count( steamId ) ) { finished &= m_streams.at( steamId )->IsDataQueueEmpty(); finished &= m_streams.at( steamId )->IsOutQueueEmpty(); } return finished; } // ********************************* // void FFmpegAVDecoder::Mute ( bool mute ) { if( HasAudio() ) { Pause(); if( mute ) { m_streams[ AVMEDIA_TYPE_AUDIO ]->Reset(); m_demuxer->ClearPacketQueue( m_streams[ AVMEDIA_TYPE_AUDIO ]->GetStreamIdx(), false ); m_demuxer->DisableStream( AVMediaType::AVMEDIA_TYPE_AUDIO ); } else { m_demuxer->GetStreamIndex( AVMediaType::AVMEDIA_TYPE_AUDIO ); } m_muted = mute; Play(); } } // ********************************* // void FFmpegAVDecoder::ProcessFirstAVFrame () { RestartDecoding(); if( HasVideo() ) { auto decoder = m_streams[ AVMEDIA_TYPE_VIDEO ].get(); while( decoder->IsOutQueueEmpty() && !( decoder->IsDataQueueEmpty() && m_demuxer->IsPacketQueueEmpty( decoder->GetStreamIdx() ) ) ) { NextDataReady( AVMEDIA_TYPE_VIDEO, decoder->GetCurrentPTS() - decoder->GetOffset(), false ); } } if( HasAudio() ) { auto i = 0; auto t = 0; auto decoder = m_streams[ AVMEDIA_TYPE_AUDIO ].get(); while( t < 100 && i < 5 && !( decoder->IsDataQueueEmpty() && m_demuxer->IsPacketQueueEmpty( decoder->GetStreamIdx() ) && m_demuxer->IsEOF() ) && decoder->GetCurrentPTS() - decoder->GetOffset() < 100 ) // FIXME: 1000 miliseconds hardcoded. { t++; if( NextDataReady( AVMEDIA_TYPE_AUDIO, decoder->GetCurrentPTS() - decoder->GetOffset(), false ) ) { i++; } } if( i < 5 ) { i = i; } } } // ********************************* // Restarts demuxer and decoder threads void FFmpegAVDecoder::RestartDecoding () { m_demuxerThread->Restart(); if( m_audioStreamsDecoderThread ) m_audioStreamsDecoderThread->Restart(); if( m_videoStreamsDecoderThread ) m_videoStreamsDecoderThread->Restart(); } // ********************************* // Restarts player thread ( called FFmpegAVDecoder ) void FFmpegAVDecoder::RestartPlayer () { if( m_audioDecoderThread ) m_audioDecoderThread->Restart(); if( m_videoDecoderThread ) m_videoDecoderThread->Restart(); } // ********************************* // Stops player thread ( called FFmpegAVDecoder ) void FFmpegAVDecoder::StopPlayer () { if( m_audioDecoderThread ) m_audioDecoderThread->Stop(); if( m_videoDecoderThread ) m_videoDecoderThread->Stop(); for( auto & s : m_streams ) { s.second->SetWaitingInterrupt(); } while( ( m_audioDecoderThread && !m_audioDecoderThread->Stopped() ) ) { m_streams[ AVMEDIA_TYPE_AUDIO ]->ClearDataQueue(); m_streams[ AVMEDIA_TYPE_AUDIO ]->EnqueueDummyDataMessage(); } while( m_videoDecoderThread && !m_videoDecoderThread->Stopped() ) { m_streams[ AVMEDIA_TYPE_VIDEO ]->ClearDataQueue(); m_streams[ AVMEDIA_TYPE_VIDEO ]->EnqueueDummyDataMessage(); } } // ********************************* // Stops demuxer and decoder threads void FFmpegAVDecoder::StopDecoding () { m_demuxerThread->Stop(); while( !m_demuxerThread->Stopped() ) { m_demuxer->ClearPacketQueue( false ); } if( m_videoStreamsDecoderThread ) m_videoStreamsDecoderThread->Stop(); if( m_audioStreamsDecoderThread ) m_audioStreamsDecoderThread->Stop(); while( ( m_audioStreamsDecoderThread && !m_audioStreamsDecoderThread->Stopped() ) ) { m_streams[ AVMEDIA_TYPE_AUDIO ]->ClearDataQueue(); m_demuxer->EnqueueDummyMessage( m_demuxer->GetStreamIndex( AVMediaType::AVMEDIA_TYPE_AUDIO ) ); } while( m_videoStreamsDecoderThread && !m_videoStreamsDecoderThread->Stopped() ) { m_streams[ AVMEDIA_TYPE_VIDEO ]->ClearDataQueue(); m_demuxer->EnqueueDummyMessage( m_demuxer->GetStreamIndex( AVMediaType::AVMEDIA_TYPE_VIDEO ) ); } // // Clearing queues //for( auto & s : m_streams ) //{ // s.second->ClearDataQueue(); // s.second->ClearOutQueue(); // s.second->SetWaitingInterrupt(); //} //// Remove dummy messages //m_demuxer->ClearPacketQueue( false ); } // ********************************* // Clears queues void FFmpegAVDecoder::ClearQueues () { for( auto & s : m_streams ) { s.second->ClearDataQueue(); s.second->ClearOutQueue(); s.second->SetWaitingInterrupt(); } // Remove dummy messages m_demuxer->ClearPacketQueue( false ); } // ********************************* // bool FFmpegAVDecoder::Seek ( FFmpegStreamDecoder * decoder, Int64 time, Int64 * nearestTimestamp ) { *nearestTimestamp = 0; // decode packets till reaching frame with given timestamp while( !m_demuxer->IsEOF() ) { while( decoder->ProcessPacket() ) { *nearestTimestamp = decoder->GetCurrentPTS(); decoder->UploadData(); if( *nearestTimestamp < time ) { AVMediaData data; decoder->PopData( data ); } else { return true; } } if( !m_demuxer->IsAnyQueueFull() ) { m_demuxer->ProcessPacket(); } else { return false; } } if( m_demuxer->IsEOF() ) { *nearestTimestamp = decoder->GetDuration(); return true; } else { return false; } } // ********************************* // Returns last played frame presentation time stamp for all streams UInt64 FFmpegAVDecoder::GetLastPlayedFramePTS () const { UInt64 ts = 0; for( auto & s : m_streams ) { ts = std::max( s.second->GetLastPlayedFramePTS(), ts ); } return ts; } } //bv
; ; ZX Spectrum specific routines ; by Stefano Bodrato, 29/06/2006 ; ; Copy a string to a BASIC variable ; ; int __CALLEE__ zx_setstr_callee(char variable, char *value); ; ; ; $Id: zx_setstr_callee.asm,v 1.1 2007/06/13 00:03:17 aralbrec Exp $ ; XLIB zx_setstr_callee XDEF ASMDISP_ZX_SETSTR_CALLEE zx_setstr_callee: pop bc pop hl pop de push bc ; enter : hl = char *value ; e = char variable .asmentry ld a,e and 95 ld (morevar+1),a ld (pointer+1),hl ld hl,($5c4b) ; VARS loop: ld a,(hl) cp 128 jr nz,morevar jr store ; variable not found morevar: cp 0 jr nz,nextvar call $19b8 ; get next variable start call $19e8 ; reclaim space (delete) store: ld bc,0 pointer: ld de,0 ; point to the string push de lenloop: inc bc ; string length counter inc de ld a,(de) and a jr nz,lenloop push hl push bc inc bc inc bc inc bc call $1655 ; MAKE-ROOM pop bc pop hl ld a,(morevar+1) ld (hl),a inc hl ld (hl),c inc hl ld (hl),b inc hl pop de ex de,hl ldir ret nextvar: call $19b8 ;get next variable start ex de,hl jr loop DEFC ASMDISP_ZX_SETSTR_CALLEE = asmentry - zx_setstr_callee
; A214045: Least m>0 such that n! <= 5^m. ; 1,1,2,2,3,5,6,7,8,10,11,13,15,16,18,20,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,56,58,60,62,64,67,69,71,74,76,78,81,83,86,88,90,93,95,98,100,103,105,108,110,113,115,118,120,123,125,128,131,133,136,138,141,144,146,149,152,154,157,160,162,165,168,171,173,176,179,182,184,187,190,193,195,198,201,204,207,209,212,215,218,221,224,227 add $0,1 mov $2,1 lpb $0 cmp $3,0 lpb $0 mul $3,$0 sub $0,1 lpe lpe lpb $3 div $3,5 add $4,$2 lpe mov $0,$4
#include <cmath> #include "../include/Scene.h" // Classe responsável por controlar os objetos em renderização Scene::Scene(const GLint &program){ this->_program = program; this->_id_current_obj = 0; } void Scene::insertObject(Object &obj){ this->_objects.insert(this->_objects.end(), obj); } void Scene::nextObject(){ this->_id_current_obj = (this->_id_current_obj+1)%this->_objects.size(); } void Scene::prevObject(){ this->_id_current_obj = this->_id_current_obj == 0 ? this->_objects.size()-1 : this->_id_current_obj-1; } Object *Scene::currentObject(){ return &this->_objects[this->_id_current_obj]; } // loadBuffer: recarrega o buffer para cada objeto void Scene::loadBuffer(Object *obj){ for(Build bld : obj->getBuild()){ GLuint buffer; glGenBuffers(0, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); // Abaixo, nós enviamos todo o conteúdo da variável vertices. glBufferData(GL_ARRAY_BUFFER, bld.count * sizeof(std::vector<Vertex>), &obj->getVertex()[bld.first], GL_DYNAMIC_DRAW); // Associando variáveis do programa GLSL (Vertex Shaders) com nossos dados GLint loc = glGetAttribLocation(this->_program, "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, sizeof(obj->getVertex()[0]), (void*) 0); GLint loc_mat = glGetUniformLocation(this->_program, "mat_transformation"); glUniformMatrix4fv(loc_mat, 1, GL_TRUE, &obj->getTransformationMatrix()[0]); // Associando variáveis do programa GLSL (Fragment Shaders) com nossos dados GLint loc_color = glGetUniformLocation(this->_program, "color"); glUniform4f(loc_color, bld.color[0], bld.color[1], bld.color[2], bld.color[3]); glDrawArrays(bld.mode, 0, bld.count); glDisableVertexAttribArray(loc); } } void Scene::render(){ for(auto &obj : this->_objects){ loadBuffer(&obj); } }
/*! * @file * @brief Camera Controller * @author Gus Grubba <mavlink@grubba.com> * */ #include "QGCCameraControl.h" #include "QGCCameraIO.h" #include "SettingsManager.h" #include "VideoManager.h" #include "QGCMapEngine.h" #include <QDir> #include <QStandardPaths> #include <QDomDocument> #include <QDomNodeList> QGC_LOGGING_CATEGORY(CameraControlLog, "CameraControlLog") QGC_LOGGING_CATEGORY(CameraControlLogVerbose, "CameraControlLogVerbose") static const char* kCondition = "condition"; static const char* kControl = "control"; static const char* kDefault = "default"; static const char* kDefnition = "definition"; static const char* kDescription = "description"; static const char* kExclusion = "exclude"; static const char* kExclusions = "exclusions"; static const char* kLocale = "locale"; static const char* kLocalization = "localization"; static const char* kMax = "max"; static const char* kMin = "min"; static const char* kModel = "model"; static const char* kName = "name"; static const char* kOption = "option"; static const char* kOptions = "options"; static const char* kOriginal = "original"; static const char* kParameter = "parameter"; static const char* kParameterrange = "parameterrange"; static const char* kParameterranges = "parameterranges"; static const char* kParameters = "parameters"; static const char* kReadOnly = "readonly"; static const char* kWriteOnly = "writeonly"; static const char* kRoption = "roption"; static const char* kStep = "step"; static const char* kDecimalPlaces = "decimalPlaces"; static const char* kStrings = "strings"; static const char* kTranslated = "translated"; static const char* kType = "type"; static const char* kUnit = "unit"; static const char* kUpdate = "update"; static const char* kUpdates = "updates"; static const char* kValue = "value"; static const char* kVendor = "vendor"; static const char* kVersion = "version"; static const char* kPhotoMode = "PhotoMode"; static const char* kPhotoLapse = "PhotoLapse"; static const char* kPhotoLapseCount = "PhotoLapseCount"; //----------------------------------------------------------------------------- // Known Parameters static const char *kCAM_EV = "CAM_EV"; static const char *kCAM_EXPMODE = "CAM_EXPMODE"; static const char *kCAM_ISO = "CAM_ISO"; static const char* kCAM_SHUTTER = "CAM_SHUTTER"; static const char* kCAM_APERTURE = "CAM_APERTURE"; static const char* kCAM_WBMODE = "CAM_WBMODE"; //----------------------------------------------------------------------------- QGCCameraOptionExclusion::QGCCameraOptionExclusion(QObject* parent, QString param_, QString value_, QStringList exclusions_) : QObject(parent) , param(param_) , value(value_) , exclusions(exclusions_) { } //----------------------------------------------------------------------------- QGCCameraOptionRange::QGCCameraOptionRange(QObject* parent, QString param_, QString value_, QString targetParam_, QString condition_, QStringList optNames_, QStringList optValues_) : QObject(parent) , param(param_) , value(value_) , targetParam(targetParam_) , condition(condition_) , optNames(optNames_) , optValues(optValues_) { } //----------------------------------------------------------------------------- static bool read_attribute(QDomNode& node, const char* tagName, bool& target) { QDomNamedNodeMap attrs = node.attributes(); if(!attrs.count()) { return false; } QDomNode subNode = attrs.namedItem(tagName); if(subNode.isNull()) { return false; } target = subNode.nodeValue() != "0"; return true; } //----------------------------------------------------------------------------- static bool read_attribute(QDomNode& node, const char* tagName, int& target) { QDomNamedNodeMap attrs = node.attributes(); if(!attrs.count()) { return false; } QDomNode subNode = attrs.namedItem(tagName); if(subNode.isNull()) { return false; } target = subNode.nodeValue().toInt(); return true; } //----------------------------------------------------------------------------- static bool read_attribute(QDomNode& node, const char* tagName, QString& target) { QDomNamedNodeMap attrs = node.attributes(); if(!attrs.count()) { return false; } QDomNode subNode = attrs.namedItem(tagName); if(subNode.isNull()) { return false; } target = subNode.nodeValue(); return true; } //----------------------------------------------------------------------------- static bool read_value(QDomNode& element, const char* tagName, QString& target) { QDomElement de = element.firstChildElement(tagName); if(de.isNull()) { return false; } target = de.text(); return true; } //----------------------------------------------------------------------------- QGCCameraControl::QGCCameraControl(const mavlink_camera_information_t *info, Vehicle* vehicle, int compID, QObject* parent) : FactGroup(0, parent) , _vehicle(vehicle) , _compID(compID) , _version(0) , _cached(false) , _paramComplete(false) , _storageFree(0) , _storageTotal(0) , _netManager(nullptr) , _cameraMode(CAM_MODE_UNDEFINED) , _photoMode(PHOTO_CAPTURE_SINGLE) , _photoLapse(1.0) , _photoLapseCount(0) , _video_status(VIDEO_CAPTURE_STATUS_UNDEFINED) , _photo_status(PHOTO_CAPTURE_STATUS_UNDEFINED) , _storageInfoRetries(0) , _captureInfoRetries(0) , _resetting(false) { QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership); memcpy(&_info, info, sizeof(mavlink_camera_information_t)); connect(this, &QGCCameraControl::dataReady, this, &QGCCameraControl::_dataReady); _vendor = QString(reinterpret_cast<const char*>(info->vendor_name)); _modelName = QString(reinterpret_cast<const char*>(info->model_name)); int ver = static_cast<int>(_info.cam_definition_version); _cacheFile.sprintf("%s/%s_%s_%03d.xml", qgcApp()->toolbox()->settingsManager()->appSettings()->parameterSavePath().toStdString().c_str(), _vendor.toStdString().c_str(), _modelName.toStdString().c_str(), ver); if(info->cam_definition_uri[0] != 0) { //-- Process camera definition file _handleDefinitionFile(info->cam_definition_uri); } else { _initWhenReady(); } QSettings settings; _photoMode = static_cast<PhotoMode>(settings.value(kPhotoMode, static_cast<int>(PHOTO_CAPTURE_SINGLE)).toInt()); _photoLapse = settings.value(kPhotoLapse, 1.0).toDouble(); _photoLapseCount = settings.value(kPhotoLapseCount, 0).toInt(); } //----------------------------------------------------------------------------- QGCCameraControl::~QGCCameraControl() { if(_netManager) { delete _netManager; } } //----------------------------------------------------------------------------- void QGCCameraControl::_initWhenReady() { qCDebug(CameraControlLog) << "_initWhenReady()"; if(isBasic()) { qCDebug(CameraControlLog) << "Basic, MAVLink only messages."; _requestCameraSettings(); } else { _requestAllParameters(); //-- Give some time to load the parameters before going after the camera settings QTimer::singleShot(2000, this, &QGCCameraControl::_requestCameraSettings); } connect(_vehicle, &Vehicle::mavCommandResult, this, &QGCCameraControl::_mavCommandResult); connect(&_captureStatusTimer, &QTimer::timeout, this, &QGCCameraControl::_requestCaptureStatus); _captureStatusTimer.setSingleShot(true); QTimer::singleShot(2500, this, &QGCCameraControl::_requestStorageInfo); _captureStatusTimer.start(2750); emit infoChanged(); if(_netManager) { delete _netManager; _netManager = nullptr; } } //----------------------------------------------------------------------------- QString QGCCameraControl::firmwareVersion() { int major = (_info.firmware_version >> 24) & 0xFF; int minor = (_info.firmware_version >> 16) & 0xFF; int build = _info.firmware_version & 0xFFFF; QString ver; ver.sprintf("%d.%d.%d", major, minor, build); return ver; } //----------------------------------------------------------------------------- QGCCameraControl::VideoStatus QGCCameraControl::videoStatus() { return _video_status; } //----------------------------------------------------------------------------- QGCCameraControl::PhotoStatus QGCCameraControl::photoStatus() { return _photo_status; } //----------------------------------------------------------------------------- QString QGCCameraControl::storageFreeStr() { return QGCMapEngine::bigSizeToString(static_cast<quint64>(_storageFree) * 1024 * 1024); } //----------------------------------------------------------------------------- void QGCCameraControl::setCameraMode(CameraMode mode) { if(!_resetting) { qCDebug(CameraControlLog) << "setCameraMode(" << mode << ")"; if(mode == CAM_MODE_VIDEO) { setVideoMode(); } else if(mode == CAM_MODE_PHOTO) { setPhotoMode(); } else { qCDebug(CameraControlLog) << "setCameraMode() Invalid mode:" << mode; return; } } } //----------------------------------------------------------------------------- void QGCCameraControl::setPhotoMode(PhotoMode mode) { if(!_resetting) { _photoMode = mode; QSettings settings; settings.setValue(kPhotoMode, static_cast<int>(mode)); emit photoModeChanged(); } } //----------------------------------------------------------------------------- void QGCCameraControl::setPhotoLapse(qreal interval) { _photoLapse = interval; QSettings settings; settings.setValue(kPhotoLapse, interval); emit photoLapseChanged(); } //----------------------------------------------------------------------------- void QGCCameraControl::setPhotoLapseCount(int count) { _photoLapseCount = count; QSettings settings; settings.setValue(kPhotoLapseCount, count); emit photoLapseCountChanged(); } //----------------------------------------------------------------------------- void QGCCameraControl::_setCameraMode(CameraMode mode) { _cameraMode = mode; emit cameraModeChanged(); } //----------------------------------------------------------------------------- void QGCCameraControl::toggleMode() { if(!_resetting) { if(cameraMode() == CAM_MODE_PHOTO || cameraMode() == CAM_MODE_SURVEY) { setVideoMode(); } else if(cameraMode() == CAM_MODE_VIDEO) { setPhotoMode(); } } } //----------------------------------------------------------------------------- bool QGCCameraControl::toggleVideo() { if(!_resetting) { if(videoStatus() == VIDEO_CAPTURE_STATUS_RUNNING) { return stopVideo(); } else { return startVideo(); } } return false; } //----------------------------------------------------------------------------- bool QGCCameraControl::takePhoto() { qCDebug(CameraControlLog) << "takePhoto()"; //-- Check if camera can capture photos or if it can capture it while in Video Mode if(!capturesPhotos() || (cameraMode() == CAM_MODE_VIDEO && !photosInVideoMode()) || photoStatus() != PHOTO_CAPTURE_IDLE) { return false; } if(!_resetting) { if(capturesPhotos()) { _vehicle->sendMavCommand( _compID, // Target component MAV_CMD_IMAGE_START_CAPTURE, // Command id false, // ShowError 0, // Reserved (Set to 0) static_cast<float>(_photoMode == PHOTO_CAPTURE_SINGLE ? 0 : _photoLapse), // Duration between two consecutive pictures (in seconds--ignored if single image) _photoMode == PHOTO_CAPTURE_SINGLE ? 1 : _photoLapseCount); // Number of images to capture total - 0 for unlimited capture _setPhotoStatus(PHOTO_CAPTURE_IN_PROGRESS); _captureInfoRetries = 0; //-- Capture local image as well QString photoPath = qgcApp()->toolbox()->settingsManager()->appSettings()->savePath()->rawValue().toString() + QStringLiteral("/Photo"); QDir().mkpath(photoPath); photoPath += + "/" + QDateTime::currentDateTime().toString("yyyy-MM-dd_hh.mm.ss.zzz") + ".jpg"; qgcApp()->toolbox()->videoManager()->videoReceiver()->grabImage(photoPath); return true; } } return false; } //----------------------------------------------------------------------------- bool QGCCameraControl::stopTakePhoto() { if(!_resetting) { qCDebug(CameraControlLog) << "stopTakePhoto()"; if(photoStatus() == PHOTO_CAPTURE_IDLE || (photoStatus() != PHOTO_CAPTURE_INTERVAL_IDLE && photoStatus() != PHOTO_CAPTURE_INTERVAL_IN_PROGRESS)) { return false; } if(capturesPhotos()) { _vehicle->sendMavCommand( _compID, // Target component MAV_CMD_IMAGE_STOP_CAPTURE, // Command id false, // ShowError 0); // Reserved (Set to 0) _setPhotoStatus(PHOTO_CAPTURE_IDLE); _captureInfoRetries = 0; return true; } } return false; } //----------------------------------------------------------------------------- bool QGCCameraControl::startVideo() { if(!_resetting) { qCDebug(CameraControlLog) << "startVideo()"; //-- Check if camera can capture videos or if it can capture it while in Photo Mode if(!capturesVideo() || (cameraMode() == CAM_MODE_PHOTO && !videoInPhotoMode())) { return false; } if(videoStatus() != VIDEO_CAPTURE_STATUS_RUNNING) { _vehicle->sendMavCommand( _compID, // Target component MAV_CMD_VIDEO_START_CAPTURE, // Command id true, // ShowError 0, // Reserved (Set to 0) 0); // CAMERA_CAPTURE_STATUS Frequency return true; } } return false; } //----------------------------------------------------------------------------- bool QGCCameraControl::stopVideo() { if(!_resetting) { qCDebug(CameraControlLog) << "stopVideo()"; if(videoStatus() == VIDEO_CAPTURE_STATUS_RUNNING) { _vehicle->sendMavCommand( _compID, // Target component MAV_CMD_VIDEO_STOP_CAPTURE, // Command id true, // ShowError 0); // Reserved (Set to 0) return true; } } return false; } //----------------------------------------------------------------------------- void QGCCameraControl::setVideoMode() { if(!_resetting) { if(hasModes() && _cameraMode != CAM_MODE_VIDEO) { qCDebug(CameraControlLog) << "setVideoMode()"; //-- Use basic MAVLink message _vehicle->sendMavCommand( _compID, // Target component MAV_CMD_SET_CAMERA_MODE, // Command id true, // ShowError 0, // Reserved (Set to 0) CAM_MODE_VIDEO); // Camera mode (0: photo, 1: video) _setCameraMode(CAM_MODE_VIDEO); } } } //----------------------------------------------------------------------------- void QGCCameraControl::setPhotoMode() { if(!_resetting) { if(hasModes() && _cameraMode != CAM_MODE_PHOTO) { qCDebug(CameraControlLog) << "setPhotoMode()"; //-- Use basic MAVLink message _vehicle->sendMavCommand( _compID, // Target component MAV_CMD_SET_CAMERA_MODE, // Command id true, // ShowError 0, // Reserved (Set to 0) CAM_MODE_PHOTO); // Camera mode (0: photo, 1: video) _setCameraMode(CAM_MODE_PHOTO); } } } //----------------------------------------------------------------------------- void QGCCameraControl::setZoomLevel(qreal level) { qCDebug(CameraControlLog) << "setZoomLevel()" << level; if(hasZoom()) { //-- Limit level = std::min(std::max(level, 0.0), 100.0); if(_vehicle) { _vehicle->sendMavCommand( _compID, // Target component MAV_CMD_SET_CAMERA_ZOOM, // Command id false, // ShowError ZOOM_TYPE_RANGE, // Zoom type static_cast<float>(level)); // Level } } } //----------------------------------------------------------------------------- void QGCCameraControl::setFocusLevel(qreal level) { qCDebug(CameraControlLog) << "setFocusLevel()" << level; if(hasFocus()) { //-- Limit level = std::min(std::max(level, 0.0), 100.0); if(_vehicle) { _vehicle->sendMavCommand( _compID, // Target component MAV_CMD_SET_CAMERA_FOCUS, // Command id false, // ShowError FOCUS_TYPE_RANGE, // Focus type static_cast<float>(level)); // Level } } } //----------------------------------------------------------------------------- void QGCCameraControl::resetSettings() { if(!_resetting) { qCDebug(CameraControlLog) << "resetSettings()"; _resetting = true; _vehicle->sendMavCommand( _compID, // Target component MAV_CMD_RESET_CAMERA_SETTINGS, // Command id true, // ShowError 1); // Do Reset } } //----------------------------------------------------------------------------- void QGCCameraControl::formatCard(int id) { if(!_resetting) { qCDebug(CameraControlLog) << "formatCard()"; if(_vehicle) { _vehicle->sendMavCommand( _compID, // Target component MAV_CMD_STORAGE_FORMAT, // Command id true, // ShowError id, // Storage ID (1 for first, 2 for second, etc.) 1); // Do Format } } } //----------------------------------------------------------------------------- void QGCCameraControl::stepZoom(int direction) { qCDebug(CameraControlLog) << "stepZoom()" << direction; if(_vehicle && hasZoom()) { _vehicle->sendMavCommand( _compID, // Target component MAV_CMD_SET_CAMERA_ZOOM, // Command id false, // ShowError ZOOM_TYPE_STEP, // Zoom type direction); // Direction (-1 wide, 1 tele) } } //----------------------------------------------------------------------------- void QGCCameraControl::startZoom(int direction) { qCDebug(CameraControlLog) << "startZoom()" << direction; if(_vehicle && hasZoom()) { _vehicle->sendMavCommand( _compID, // Target component MAV_CMD_SET_CAMERA_ZOOM, // Command id true, // ShowError ZOOM_TYPE_CONTINUOUS, // Zoom type direction); // Direction (-1 wide, 1 tele) } } //----------------------------------------------------------------------------- void QGCCameraControl::stopZoom() { qCDebug(CameraControlLog) << "stopZoom()"; if(_vehicle && hasZoom()) { _vehicle->sendMavCommand( _compID, // Target component MAV_CMD_SET_CAMERA_ZOOM, // Command id true, // ShowError ZOOM_TYPE_CONTINUOUS, // Zoom type 0); // Direction (-1 wide, 1 tele) } } //----------------------------------------------------------------------------- void QGCCameraControl::_requestCaptureStatus() { qCDebug(CameraControlLog) << "_requestCaptureStatus()"; _vehicle->sendMavCommand( _compID, // target component MAV_CMD_REQUEST_CAMERA_CAPTURE_STATUS, // command id false, // showError 1); // Do Request } //----------------------------------------------------------------------------- void QGCCameraControl::factChanged(Fact* pFact) { _updateActiveList(); _updateRanges(pFact); } //----------------------------------------------------------------------------- void QGCCameraControl::_mavCommandResult(int vehicleId, int component, int command, int result, bool noReponseFromVehicle) { //-- Is this ours? if(_vehicle->id() != vehicleId || compID() != component) { return; } if(!noReponseFromVehicle && result == MAV_RESULT_IN_PROGRESS) { //-- Do Nothing qCDebug(CameraControlLog) << "In progress response for" << command; }else if(!noReponseFromVehicle && result == MAV_RESULT_ACCEPTED) { switch(command) { case MAV_CMD_RESET_CAMERA_SETTINGS: _resetting = false; if(isBasic()) { _requestCameraSettings(); } else { QTimer::singleShot(500, this, &QGCCameraControl::_requestAllParameters); QTimer::singleShot(2500, this, &QGCCameraControl::_requestCameraSettings); } break; case MAV_CMD_VIDEO_START_CAPTURE: _setVideoStatus(VIDEO_CAPTURE_STATUS_RUNNING); _captureStatusTimer.start(1000); break; case MAV_CMD_VIDEO_STOP_CAPTURE: _setVideoStatus(VIDEO_CAPTURE_STATUS_STOPPED); _captureStatusTimer.start(1000); break; case MAV_CMD_REQUEST_CAMERA_CAPTURE_STATUS: _captureInfoRetries = 0; break; case MAV_CMD_REQUEST_STORAGE_INFORMATION: _storageInfoRetries = 0; break; } } else { if(noReponseFromVehicle || result == MAV_RESULT_TEMPORARILY_REJECTED || result == MAV_RESULT_FAILED) { if(noReponseFromVehicle) { qCDebug(CameraControlLog) << "No response for" << command; } else if (result == MAV_RESULT_TEMPORARILY_REJECTED) { qCDebug(CameraControlLog) << "Command temporarily rejected for" << command; } else { qCDebug(CameraControlLog) << "Command failed for" << command; } switch(command) { case MAV_CMD_IMAGE_START_CAPTURE: case MAV_CMD_IMAGE_STOP_CAPTURE: if(++_captureInfoRetries < 5) { _captureStatusTimer.start(1000); } else { qCDebug(CameraControlLog) << "Giving up requesting capture status"; } break; case MAV_CMD_REQUEST_CAMERA_CAPTURE_STATUS: if(++_captureInfoRetries < 3) { _captureStatusTimer.start(500); } else { qCDebug(CameraControlLog) << "Giving up requesting capture status"; } break; case MAV_CMD_REQUEST_STORAGE_INFORMATION: if(++_storageInfoRetries < 3) { QTimer::singleShot(500, this, &QGCCameraControl::_requestStorageInfo); } else { qCDebug(CameraControlLog) << "Giving up requesting storage status"; } break; } } else { qCDebug(CameraControlLog) << "Bad response for" << command << result; } } } //----------------------------------------------------------------------------- void QGCCameraControl::_setVideoStatus(VideoStatus status) { if(_video_status != status) { _video_status = status; emit videoStatusChanged(); } } //----------------------------------------------------------------------------- void QGCCameraControl::_setPhotoStatus(PhotoStatus status) { if(_photo_status != status) { _photo_status = status; emit photoStatusChanged(); } } //----------------------------------------------------------------------------- bool QGCCameraControl::_loadCameraDefinitionFile(QByteArray& bytes) { QByteArray originalData(bytes); //-- Handle localization if(!_handleLocalization(bytes)) { return false; } int errorLine; QString errorMsg; QDomDocument doc; if(!doc.setContent(bytes, false, &errorMsg, &errorLine)) { qCritical() << "Unable to parse camera definition file on line:" << errorLine; qCritical() << errorMsg; return false; } //-- Load camera constants QDomNodeList defElements = doc.elementsByTagName(kDefnition); if(!defElements.size() || !_loadConstants(defElements)) { qWarning() << "Unable to load camera constants from camera definition"; return false; } //-- Load camera parameters QDomNodeList paramElements = doc.elementsByTagName(kParameters); if(!paramElements.size() || !_loadSettings(paramElements)) { qWarning() << "Unable to load camera parameters from camera definition"; return false; } //-- If this is new, cache it if(!_cached) { qCDebug(CameraControlLog) << "Saving camera definition file" << _cacheFile; QFile file(_cacheFile); if (!file.open(QIODevice::WriteOnly)) { qWarning() << QString("Could not save cache file %1. Error: %2").arg(_cacheFile).arg(file.errorString()); } else { file.write(originalData); } } return true; } //----------------------------------------------------------------------------- bool QGCCameraControl::_loadConstants(const QDomNodeList nodeList) { QDomNode node = nodeList.item(0); if(!read_attribute(node, kVersion, _version)) { return false; } if(!read_value(node, kModel, _modelName)) { return false; } if(!read_value(node, kVendor, _vendor)) { return false; } return true; } //----------------------------------------------------------------------------- bool QGCCameraControl::_loadSettings(const QDomNodeList nodeList) { QDomNode node = nodeList.item(0); QDomElement elem = node.toElement(); QDomNodeList parameters = elem.elementsByTagName(kParameter); //-- Pre-process settings (maintain order and skip non-controls) for(int i = 0; i < parameters.size(); i++) { QDomNode parameterNode = parameters.item(i); QString name; if(read_attribute(parameterNode, kName, name)) { bool control = true; read_attribute(parameterNode, kControl, control); if(control) { _settings << name; } } else { qCritical() << "Parameter entry missing parameter name"; return false; } } //-- Load parameters for(int i = 0; i < parameters.size(); i++) { QDomNode parameterNode = parameters.item(i); QString factName; read_attribute(parameterNode, kName, factName); QString type; if(!read_attribute(parameterNode, kType, type)) { qCritical() << QString("Parameter %1 missing parameter type").arg(factName); return false; } //-- Does it have a control? bool control = true; read_attribute(parameterNode, kControl, control); //-- Is it read only? bool readOnly = false; read_attribute(parameterNode, kReadOnly, readOnly); //-- Is it write only? bool writeOnly = false; read_attribute(parameterNode, kWriteOnly, writeOnly); //-- It can't be both if(readOnly && writeOnly) { qCritical() << QString("Parameter %1 cannot be both read only and write only").arg(factName); } //-- Param type bool unknownType; FactMetaData::ValueType_t factType = FactMetaData::stringToType(type, unknownType); if (unknownType) { qCritical() << QString("Unknown type for parameter %1").arg(factName); return false; } //-- By definition, custom types do not have control if(factType == FactMetaData::valueTypeCustom) { control = false; } //-- Description QString description; if(!read_value(parameterNode, kDescription, description)) { qCritical() << QString("Parameter %1 missing parameter description").arg(factName); return false; } //-- Check for updates QStringList updates = _loadUpdates(parameterNode); if(updates.size()) { qCDebug(CameraControlLogVerbose) << "Parameter" << factName << "requires updates for:" << updates; _requestUpdates[factName] = updates; } //-- Build metadata FactMetaData* metaData = new FactMetaData(factType, factName, this); QQmlEngine::setObjectOwnership(metaData, QQmlEngine::CppOwnership); metaData->setShortDescription(description); metaData->setLongDescription(description); metaData->setHasControl(control); metaData->setReadOnly(readOnly); metaData->setWriteOnly(writeOnly); //-- Options (enums) QDomElement optionElem = parameterNode.toElement(); QDomNodeList optionsRoot = optionElem.elementsByTagName(kOptions); if(optionsRoot.size()) { //-- Iterate options QDomNode node = optionsRoot.item(0); QDomElement elem = node.toElement(); QDomNodeList options = elem.elementsByTagName(kOption); for(int i = 0; i < options.size(); i++) { QDomNode option = options.item(i); QString optName; QString optValue; QVariant optVariant; if(!_loadNameValue(option, factName, metaData, optName, optValue, optVariant)) { delete metaData; return false; } metaData->addEnumInfo(optName, optVariant); _originalOptNames[factName] << optName; _originalOptValues[factName] << optVariant; //-- Check for exclusions QStringList exclusions = _loadExclusions(option); if(exclusions.size()) { qCDebug(CameraControlLogVerbose) << "New exclusions:" << factName << optValue << exclusions; QGCCameraOptionExclusion* pExc = new QGCCameraOptionExclusion(this, factName, optValue, exclusions); QQmlEngine::setObjectOwnership(pExc, QQmlEngine::CppOwnership); _valueExclusions.append(pExc); } //-- Check for range rules if(!_loadRanges(option, factName, optValue)) { delete metaData; return false; } } } QString defaultValue; if(read_attribute(parameterNode, kDefault, defaultValue)) { QVariant defaultVariant; QString errorString; if (metaData->convertAndValidateRaw(defaultValue, false, defaultVariant, errorString)) { metaData->setRawDefaultValue(defaultVariant); } else { qWarning() << "Invalid default value for" << factName << " type:" << metaData->type() << " value:" << defaultValue << " error:" << errorString; } } //-- Set metadata and Fact if (_nameToFactMetaDataMap.contains(factName)) { qWarning() << QStringLiteral("Duplicate fact name:") << factName; delete metaData; } else { { //-- Check for Min Value QString attr; if(read_attribute(parameterNode, kMin, attr)) { QVariant typedValue; QString errorString; if (metaData->convertAndValidateRaw(attr, true /* convertOnly */, typedValue, errorString)) { metaData->setRawMin(typedValue); } else { qWarning() << "Invalid min value for" << factName << " type:" << metaData->type() << " value:" << attr << " error:" << errorString; } } } { //-- Check for Max Value QString attr; if(read_attribute(parameterNode, kMax, attr)) { QVariant typedValue; QString errorString; if (metaData->convertAndValidateRaw(attr, true /* convertOnly */, typedValue, errorString)) { metaData->setRawMax(typedValue); } else { qWarning() << "Invalid max value for" << factName << " type:" << metaData->type() << " value:" << attr << " error:" << errorString; } } } { //-- Check for Step Value QString attr; if(read_attribute(parameterNode, kStep, attr)) { QVariant typedValue; QString errorString; if (metaData->convertAndValidateRaw(attr, true /* convertOnly */, typedValue, errorString)) { metaData->setRawIncrement(typedValue.toDouble()); } else { qWarning() << "Invalid step value for" << factName << " type:" << metaData->type() << " value:" << attr << " error:" << errorString; } } } { //-- Check for Decimal Places QString attr; if(read_attribute(parameterNode, kDecimalPlaces, attr)) { QVariant typedValue; QString errorString; if (metaData->convertAndValidateRaw(attr, true /* convertOnly */, typedValue, errorString)) { metaData->setDecimalPlaces(typedValue.toInt()); } else { qWarning() << "Invalid decimal places value for" << factName << " type:" << metaData->type() << " value:" << attr << " error:" << errorString; } } } { //-- Check for Units QString attr; if(read_attribute(parameterNode, kUnit, attr)) { metaData->setRawUnits(attr); } } qCDebug(CameraControlLog) << "New parameter:" << factName << (readOnly ? "ReadOnly" : "Writable") << (writeOnly ? "WriteOnly" : "Readable"); _nameToFactMetaDataMap[factName] = metaData; Fact* pFact = new Fact(_compID, factName, factType, this); QQmlEngine::setObjectOwnership(pFact, QQmlEngine::CppOwnership); pFact->setMetaData(metaData); pFact->_containerSetRawValue(metaData->rawDefaultValue()); QGCCameraParamIO* pIO = new QGCCameraParamIO(this, pFact, _vehicle); QQmlEngine::setObjectOwnership(pIO, QQmlEngine::CppOwnership); _paramIO[factName] = pIO; _addFact(pFact, factName); } } if(_nameToFactMetaDataMap.size() > 0) { _addFactGroup(this, "camera"); _processRanges(); _activeSettings = _settings; emit activeSettingsChanged(); return true; } return false; } //----------------------------------------------------------------------------- bool QGCCameraControl::_handleLocalization(QByteArray& bytes) { QString errorMsg; int errorLine; QDomDocument doc; if(!doc.setContent(bytes, false, &errorMsg, &errorLine)) { qCritical() << "Unable to parse camera definition file on line:" << errorLine; qCritical() << errorMsg; return false; } //-- Find out where we are QLocale locale = QLocale::system(); #if defined (Q_OS_MAC) locale = QLocale(locale.name()); #endif QString localeName = locale.name().toLower().replace("-", "_"); qCDebug(CameraControlLog) << "Current locale:" << localeName; if(localeName == "en_us") { // Nothing to do return true; } QDomNodeList locRoot = doc.elementsByTagName(kLocalization); if(!locRoot.size()) { // Nothing to do return true; } //-- Iterate locales QDomNode node = locRoot.item(0); QDomElement elem = node.toElement(); QDomNodeList locales = elem.elementsByTagName(kLocale); for(int i = 0; i < locales.size(); i++) { QDomNode locale = locales.item(i); QString name; if(!read_attribute(locale, kName, name)) { qWarning() << "Localization entry is missing its name attribute"; continue; } // If we found a direct match, deal with it now if(localeName == name.toLower().replace("-", "_")) { return _replaceLocaleStrings(locale, bytes); } } //-- No direct match. Pick first matching language (if any) localeName = localeName.left(3); for(int i = 0; i < locales.size(); i++) { QDomNode locale = locales.item(i); QString name; read_attribute(locale, kName, name); if(name.toLower().startsWith(localeName)) { return _replaceLocaleStrings(locale, bytes); } } //-- Could not find a language to use qWarning() << "No match for" << QLocale::system().name() << "in camera definition file"; //-- Just use default, en_US return true; } //----------------------------------------------------------------------------- bool QGCCameraControl::_replaceLocaleStrings(const QDomNode node, QByteArray& bytes) { QDomElement stringElem = node.toElement(); QDomNodeList strings = stringElem.elementsByTagName(kStrings); for(int i = 0; i < strings.size(); i++) { QDomNode stringNode = strings.item(i); QString original; QString translated; if(read_attribute(stringNode, kOriginal, original)) { if(read_attribute(stringNode, kTranslated, translated)) { QString o; o = "\"" + original + "\""; QString t; t = "\"" + translated + "\""; bytes.replace(o.toUtf8(), t.toUtf8()); o = ">" + original + "<"; t = ">" + translated + "<"; bytes.replace(o.toUtf8(), t.toUtf8()); } } } return true; } //----------------------------------------------------------------------------- void QGCCameraControl::_requestAllParameters() { //-- Reset receive list for(QString paramName: _paramIO.keys()) { if(_paramIO[paramName]) { _paramIO[paramName]->setParamRequest(); } else { qCritical() << "QGCParamIO is NULL" << paramName; } } MAVLinkProtocol* mavlink = qgcApp()->toolbox()->mavlinkProtocol(); mavlink_message_t msg; mavlink_msg_param_ext_request_list_pack_chan( static_cast<uint8_t>(mavlink->getSystemId()), static_cast<uint8_t>(mavlink->getComponentId()), _vehicle->priorityLink()->mavlinkChannel(), &msg, static_cast<uint8_t>(_vehicle->id()), static_cast<uint8_t>(compID())); _vehicle->sendMessageOnLink(_vehicle->priorityLink(), msg); qCDebug(CameraControlLogVerbose) << "Request all parameters"; } //----------------------------------------------------------------------------- QString QGCCameraControl::_getParamName(const char* param_id) { QByteArray bytes(param_id, MAVLINK_MSG_PARAM_VALUE_FIELD_PARAM_ID_LEN); QString parameterName(bytes); return parameterName; } //----------------------------------------------------------------------------- void QGCCameraControl::handleParamAck(const mavlink_param_ext_ack_t& ack) { QString paramName = _getParamName(ack.param_id); if(!_paramIO.contains(paramName)) { qCWarning(CameraControlLog) << "Received PARAM_EXT_ACK for unknown param:" << paramName; return; } if(_paramIO[paramName]) { _paramIO[paramName]->handleParamAck(ack); } else { qCritical() << "QGCParamIO is NULL" << paramName; } } //----------------------------------------------------------------------------- void QGCCameraControl::handleParamValue(const mavlink_param_ext_value_t& value) { QString paramName = _getParamName(value.param_id); if(!_paramIO.contains(paramName)) { qCWarning(CameraControlLog) << "Received PARAM_EXT_VALUE for unknown param:" << paramName; return; } if(_paramIO[paramName]) { _paramIO[paramName]->handleParamValue(value); } else { qCritical() << "QGCParamIO is NULL" << paramName; } } //----------------------------------------------------------------------------- void QGCCameraControl::_updateActiveList() { //-- Clear out excluded parameters based on exclusion rules QStringList exclusionList; for(QGCCameraOptionExclusion* param: _valueExclusions) { Fact* pFact = getFact(param->param); if(pFact) { QString option = pFact->rawValueString(); if(param->value == option) { exclusionList << param->exclusions; } } } QStringList active; for(QString key: _settings) { if(!exclusionList.contains(key)) { active.append(key); } } if(active != _activeSettings) { qCDebug(CameraControlLogVerbose) << "Excluding" << exclusionList; _activeSettings = active; emit activeSettingsChanged(); //-- Force validity of "Facts" based on active set if(_paramComplete) { emit parametersReady(); } } } //----------------------------------------------------------------------------- bool QGCCameraControl::_processConditionTest(const QString conditionTest) { enum { TEST_NONE, TEST_EQUAL, TEST_NOT_EQUAL, TEST_GREATER, TEST_SMALLER }; qCDebug(CameraControlLogVerbose) << "_processConditionTest(" << conditionTest << ")"; int op = TEST_NONE; QStringList test; if(conditionTest.contains("!=")) { test = conditionTest.split("!=", QString::SkipEmptyParts); op = TEST_NOT_EQUAL; } else if(conditionTest.contains("=")) { test = conditionTest.split("=", QString::SkipEmptyParts); op = TEST_EQUAL; } else if(conditionTest.contains(">")) { test = conditionTest.split(">", QString::SkipEmptyParts); op = TEST_GREATER; } else if(conditionTest.contains("<")) { test = conditionTest.split("<", QString::SkipEmptyParts); op = TEST_SMALLER; } if(test.size() == 2) { Fact* pFact = getFact(test[0]); if(pFact) { switch(op) { case TEST_EQUAL: return pFact->rawValueString() == test[1]; case TEST_NOT_EQUAL: return pFact->rawValueString() != test[1]; case TEST_GREATER: return pFact->rawValueString() > test[1]; case TEST_SMALLER: return pFact->rawValueString() < test[1]; case TEST_NONE: break; } } else { qWarning() << "Invalid condition parameter:" << test[0] << "in" << conditionTest; return false; } } qWarning() << "Invalid condition" << conditionTest; return false; } //----------------------------------------------------------------------------- bool QGCCameraControl::_processCondition(const QString condition) { qCDebug(CameraControlLogVerbose) << "_processCondition(" << condition << ")"; bool result = true; bool andOp = true; if(!condition.isEmpty()) { QStringList scond = condition.split(" ", QString::SkipEmptyParts); while(scond.size()) { QString test = scond.first(); scond.removeFirst(); if(andOp) { result = result && _processConditionTest(test); } else { result = result || _processConditionTest(test); } if(!scond.size()) { return result; } andOp = scond.first().toUpper() == "AND"; scond.removeFirst(); } } return result; } //----------------------------------------------------------------------------- void QGCCameraControl::_updateRanges(Fact* pFact) { QMap<Fact*, QGCCameraOptionRange*> rangesSet; QMap<Fact*, QString> rangesReset; QStringList changedList; QStringList resetList; QStringList updates; //-- Iterate range sets looking for limited ranges for(QGCCameraOptionRange* pRange: _optionRanges) { //-- If this fact or one of its conditions is part of this range set if(!changedList.contains(pRange->targetParam) && (pRange->param == pFact->name() || pRange->condition.contains(pFact->name()))) { Fact* pRFact = getFact(pRange->param); //-- This parameter Fact* pTFact = getFact(pRange->targetParam); //-- The target parameter (the one its range is to change) if(pRFact && pTFact) { //qCDebug(CameraControlLogVerbose) << "Check new set of options for" << pTFact->name(); QString option = pRFact->rawValueString(); //-- This parameter value //-- If this value (and condition) triggers a change in the target range //qCDebug(CameraControlLogVerbose) << "Range value:" << pRange->value << "Current value:" << option << "Condition:" << pRange->condition; if(pRange->value == option && _processCondition(pRange->condition)) { if(pTFact->enumStrings() != pRange->optNames) { //-- Set limited range set rangesSet[pTFact] = pRange; } changedList << pRange->targetParam; } } } } //-- Iterate range sets again looking for resets for(QGCCameraOptionRange* pRange: _optionRanges) { if(!changedList.contains(pRange->targetParam) && (pRange->param == pFact->name() || pRange->condition.contains(pFact->name()))) { Fact* pTFact = getFact(pRange->targetParam); //-- The target parameter (the one its range is to change) if(!resetList.contains(pRange->targetParam)) { if(pTFact->enumStrings() != _originalOptNames[pRange->targetParam]) { //-- Restore full option set rangesReset[pTFact] = pRange->targetParam; } resetList << pRange->targetParam; } } } //-- Update limited range set for (Fact* f: rangesSet.keys()) { f->setEnumInfo(rangesSet[f]->optNames, rangesSet[f]->optVariants); if(!updates.contains(f->name())) { _paramIO[f->name()]->optNames = rangesSet[f]->optNames; _paramIO[f->name()]->optVariants = rangesSet[f]->optVariants; emit f->enumsChanged(); qCDebug(CameraControlLogVerbose) << "Limited set of options for:" << f->name() << rangesSet[f]->optNames;; updates << f->name(); } } //-- Restore full range set for (Fact* f: rangesReset.keys()) { f->setEnumInfo(_originalOptNames[rangesReset[f]], _originalOptValues[rangesReset[f]]); if(!updates.contains(f->name())) { _paramIO[f->name()]->optNames = _originalOptNames[rangesReset[f]]; _paramIO[f->name()]->optVariants = _originalOptValues[rangesReset[f]]; emit f->enumsChanged(); qCDebug(CameraControlLogVerbose) << "Restore full set of options for:" << f->name() << _originalOptNames[f->name()]; updates << f->name(); } } //-- Parameter update requests if(_requestUpdates.contains(pFact->name())) { for(QString param: _requestUpdates[pFact->name()]) { if(!_updatesToRequest.contains(param)) { _updatesToRequest << param; } } } if(_updatesToRequest.size()) { QTimer::singleShot(500, this, &QGCCameraControl::_requestParamUpdates); } } //----------------------------------------------------------------------------- void QGCCameraControl::_requestParamUpdates() { for(QString param: _updatesToRequest) { _paramIO[param]->paramRequest(); } _updatesToRequest.clear(); } //----------------------------------------------------------------------------- void QGCCameraControl::_requestCameraSettings() { qCDebug(CameraControlLog) << "_requestCameraSettings()"; if(_vehicle) { _vehicle->sendMavCommand( _compID, // Target component MAV_CMD_REQUEST_CAMERA_SETTINGS, // command id false, // showError 1); // Do Request } } //----------------------------------------------------------------------------- void QGCCameraControl::_requestStorageInfo() { qCDebug(CameraControlLog) << "_requestStorageInfo()"; if(_vehicle) { _vehicle->sendMavCommand( _compID, // Target component MAV_CMD_REQUEST_STORAGE_INFORMATION, // command id false, // showError 0, // Storage ID (0 for all, 1 for first, 2 for second, etc.) 1); // Do Request } } //----------------------------------------------------------------------------- void QGCCameraControl::handleSettings(const mavlink_camera_settings_t& settings) { qCDebug(CameraControlLog) << "handleSettings() Mode:" << settings.mode_id; _setCameraMode(static_cast<CameraMode>(settings.mode_id)); qreal z = static_cast<qreal>(settings.zoomLevel); qreal f = static_cast<qreal>(settings.focusLevel); if(std::isfinite(z) && z != _zoomLevel) { _zoomLevel = z; emit zoomLevelChanged(); } if(std::isfinite(f) && f != _focusLevel) { _focusLevel = f; emit focusLevelChanged(); } } //----------------------------------------------------------------------------- void QGCCameraControl::handleStorageInfo(const mavlink_storage_information_t& st) { qCDebug(CameraControlLog) << "_handleStorageInfo:" << st.available_capacity << st.status << st.storage_count << st.storage_id << st.total_capacity << st.used_capacity; uint32_t t = static_cast<uint32_t>(st.total_capacity); if(_storageTotal != t) { _storageTotal = t; } //-- Always emit this emit storageTotalChanged(); uint32_t a = static_cast<uint32_t>(st.available_capacity); if(_storageFree != a) { _storageFree = a; emit storageFreeChanged(); } } //----------------------------------------------------------------------------- void QGCCameraControl::handleCaptureStatus(const mavlink_camera_capture_status_t& cap) { //-- This is a response to MAV_CMD_REQUEST_CAMERA_CAPTURE_STATUS qCDebug(CameraControlLog) << "handleCaptureStatus:" << cap.available_capacity << cap.image_interval << cap.image_status << cap.recording_time_ms << cap.video_status; //-- Disk Free Space uint32_t a = static_cast<uint32_t>(cap.available_capacity); if(_storageFree != a) { _storageFree = a; emit storageFreeChanged(); } //-- Video/Image Capture Status uint8_t vs = cap.video_status < static_cast<uint8_t>(VIDEO_CAPTURE_STATUS_LAST) ? cap.video_status : static_cast<uint8_t>(VIDEO_CAPTURE_STATUS_UNDEFINED); uint8_t ps = cap.image_status < static_cast<uint8_t>(PHOTO_CAPTURE_LAST) ? cap.image_status : static_cast<uint8_t>(PHOTO_CAPTURE_STATUS_UNDEFINED); _setVideoStatus(static_cast<VideoStatus>(vs)); _setPhotoStatus(static_cast<PhotoStatus>(ps)); //-- Keep asking for it once in a while when recording if(videoStatus() == VIDEO_CAPTURE_STATUS_RUNNING) { _captureStatusTimer.start(5000); //-- Same while (single) image capture is busy } else if(photoStatus() != PHOTO_CAPTURE_IDLE && photoMode() == PHOTO_CAPTURE_SINGLE) { _captureStatusTimer.start(1000); } //-- Time Lapse if(photoStatus() == PHOTO_CAPTURE_INTERVAL_IDLE || photoStatus() == PHOTO_CAPTURE_INTERVAL_IN_PROGRESS) { //-- Capture local image as well QString photoPath = qgcApp()->toolbox()->settingsManager()->appSettings()->savePath()->rawValue().toString() + QStringLiteral("/Photo"); QDir().mkpath(photoPath); photoPath += + "/" + QDateTime::currentDateTime().toString("yyyy-MM-dd_hh.mm.ss.zzz") + ".jpg"; qgcApp()->toolbox()->videoManager()->videoReceiver()->grabImage(photoPath); } } //----------------------------------------------------------------------------- QStringList QGCCameraControl::_loadExclusions(QDomNode option) { QStringList exclusionList; QDomElement optionElem = option.toElement(); QDomNodeList excRoot = optionElem.elementsByTagName(kExclusions); if(excRoot.size()) { //-- Iterate exclusions QDomNode node = excRoot.item(0); QDomElement elem = node.toElement(); QDomNodeList exclusions = elem.elementsByTagName(kExclusion); for(int i = 0; i < exclusions.size(); i++) { QString exclude = exclusions.item(i).toElement().text(); if(!exclude.isEmpty()) { exclusionList << exclude; } } } return exclusionList; } //----------------------------------------------------------------------------- QStringList QGCCameraControl::_loadUpdates(QDomNode option) { QStringList updateList; QDomElement optionElem = option.toElement(); QDomNodeList updateRoot = optionElem.elementsByTagName(kUpdates); if(updateRoot.size()) { //-- Iterate updates QDomNode node = updateRoot.item(0); QDomElement elem = node.toElement(); QDomNodeList updates = elem.elementsByTagName(kUpdate); for(int i = 0; i < updates.size(); i++) { QString update = updates.item(i).toElement().text(); if(!update.isEmpty()) { updateList << update; } } } return updateList; } //----------------------------------------------------------------------------- bool QGCCameraControl::_loadRanges(QDomNode option, const QString factName, QString paramValue) { QDomElement optionElem = option.toElement(); QDomNodeList rangeRoot = optionElem.elementsByTagName(kParameterranges); if(rangeRoot.size()) { QDomNode node = rangeRoot.item(0); QDomElement elem = node.toElement(); QDomNodeList parameterRanges = elem.elementsByTagName(kParameterrange); //-- Iterate parameter ranges for(int i = 0; i < parameterRanges.size(); i++) { QString param; QString condition; QMap<QString, QVariant> rangeList; QDomNode paramRange = parameterRanges.item(i); if(!read_attribute(paramRange, kParameter, param)) { qCritical() << QString("Malformed option range for parameter %1").arg(factName); return false; } read_attribute(paramRange, kCondition, condition); QDomElement pelem = paramRange.toElement(); QDomNodeList rangeOptions = pelem.elementsByTagName(kRoption); QStringList optNames; QStringList optValues; //-- Iterate options for(int i = 0; i < rangeOptions.size(); i++) { QString optName; QString optValue; QDomNode roption = rangeOptions.item(i); if(!read_attribute(roption, kName, optName)) { qCritical() << QString("Malformed roption for parameter %1").arg(factName); return false; } if(!read_attribute(roption, kValue, optValue)) { qCritical() << QString("Malformed rvalue for parameter %1").arg(factName); return false; } optNames << optName; optValues << optValue; } if(optNames.size()) { QGCCameraOptionRange* pRange = new QGCCameraOptionRange(this, factName, paramValue, param, condition, optNames, optValues); _optionRanges.append(pRange); qCDebug(CameraControlLogVerbose) << "New range limit:" << factName << paramValue << param << condition << optNames << optValues; } } } return true; } //----------------------------------------------------------------------------- void QGCCameraControl::_processRanges() { //-- After all parameter are loaded, process parameter ranges for(QGCCameraOptionRange* pRange: _optionRanges) { Fact* pRFact = getFact(pRange->targetParam); if(pRFact) { for(int i = 0; i < pRange->optNames.size(); i++) { QVariant optVariant; QString errorString; if (!pRFact->metaData()->convertAndValidateRaw(pRange->optValues[i], false, optVariant, errorString)) { qWarning() << "Invalid roption value, name:" << pRange->targetParam << " type:" << pRFact->metaData()->type() << " value:" << pRange->optValues[i] << " error:" << errorString; } else { pRange->optVariants << optVariant; } } } } } //----------------------------------------------------------------------------- bool QGCCameraControl::_loadNameValue(QDomNode option, const QString factName, FactMetaData* metaData, QString& optName, QString& optValue, QVariant& optVariant) { if(!read_attribute(option, kName, optName)) { qCritical() << QString("Malformed option for parameter %1").arg(factName); return false; } if(!read_attribute(option, kValue, optValue)) { qCritical() << QString("Malformed value for parameter %1").arg(factName); return false; } QString errorString; if (!metaData->convertAndValidateRaw(optValue, false, optVariant, errorString)) { qWarning() << "Invalid option value, name:" << factName << " type:" << metaData->type() << " value:" << optValue << " error:" << errorString; } return true; } //----------------------------------------------------------------------------- void QGCCameraControl::_handleDefinitionFile(const QString &url) { //-- First check and see if we have it cached QFile xmlFile(_cacheFile); if (!xmlFile.exists()) { qCDebug(CameraControlLog) << "No camera definition file cached"; _httpRequest(url); return; } if (!xmlFile.open(QIODevice::ReadOnly)) { qWarning() << "Could not read cached camera definition file:" << _cacheFile; _httpRequest(url); return; } QByteArray bytes = xmlFile.readAll(); QDomDocument doc; if(!doc.setContent(bytes, false)) { qWarning() << "Could not parse cached camera definition file:" << _cacheFile; _httpRequest(url); return; } //-- We have it qCDebug(CameraControlLog) << "Using cached camera definition file:" << _cacheFile; _cached = true; emit dataReady(bytes); } //----------------------------------------------------------------------------- void QGCCameraControl::_httpRequest(const QString &url) { qCDebug(CameraControlLog) << "Request camera definition:" << url; if(!_netManager) { _netManager = new QNetworkAccessManager(this); } QNetworkProxy savedProxy = _netManager->proxy(); QNetworkProxy tempProxy; tempProxy.setType(QNetworkProxy::DefaultProxy); _netManager->setProxy(tempProxy); QNetworkRequest request(url); request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); QSslConfiguration conf = request.sslConfiguration(); conf.setPeerVerifyMode(QSslSocket::VerifyNone); request.setSslConfiguration(conf); QNetworkReply* reply = _netManager->get(request); connect(reply, &QNetworkReply::finished, this, &QGCCameraControl::_downloadFinished); _netManager->setProxy(savedProxy); } //----------------------------------------------------------------------------- void QGCCameraControl::_downloadFinished() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); if(!reply) { return; } int err = reply->error(); int http_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); QByteArray data = reply->readAll(); if(err == QNetworkReply::NoError && http_code == 200) { data.append("\n"); } else { data.clear(); qWarning() << QString("Camera Definition download error: %1 status: %2").arg(reply->errorString(), reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString()); } emit dataReady(data); //reply->deleteLater(); } //----------------------------------------------------------------------------- void QGCCameraControl::_dataReady(QByteArray data) { if(data.size()) { qCDebug(CameraControlLog) << "Parsing camera definition"; _loadCameraDefinitionFile(data); } else { qCDebug(CameraControlLog) << "No camera definition"; } _initWhenReady(); } //----------------------------------------------------------------------------- void QGCCameraControl::_paramDone() { for(QString param: _paramIO.keys()) { if(!_paramIO[param]->paramDone()) { return; } } //-- All parameters loaded (or timed out) _paramComplete = true; emit parametersReady(); } //----------------------------------------------------------------------------- bool QGCCameraControl::incomingParameter(Fact* pFact, QVariant& newValue) { Q_UNUSED(pFact); Q_UNUSED(newValue); return true; } //----------------------------------------------------------------------------- bool QGCCameraControl::validateParameter(Fact* pFact, QVariant& newValue) { Q_UNUSED(pFact); Q_UNUSED(newValue); return true; } //----------------------------------------------------------------------------- QStringList QGCCameraControl::activeSettings() { qCDebug(CameraControlLog) << "Active:" << _activeSettings; return _activeSettings; } //----------------------------------------------------------------------------- Fact* QGCCameraControl::exposureMode() { return (_paramComplete && _activeSettings.contains(kCAM_EXPMODE)) ? getFact(kCAM_EXPMODE) : nullptr; } //----------------------------------------------------------------------------- Fact* QGCCameraControl::ev() { return (_paramComplete && _activeSettings.contains(kCAM_EV)) ? getFact(kCAM_EV) : nullptr; } //----------------------------------------------------------------------------- Fact* QGCCameraControl::iso() { return (_paramComplete && _activeSettings.contains(kCAM_ISO)) ? getFact(kCAM_ISO) : nullptr; } //----------------------------------------------------------------------------- Fact* QGCCameraControl::shutter() { return (_paramComplete && _activeSettings.contains(kCAM_SHUTTER)) ? getFact(kCAM_SHUTTER) : nullptr; } //----------------------------------------------------------------------------- Fact* QGCCameraControl::aperture() { return (_paramComplete && _activeSettings.contains(kCAM_APERTURE)) ? getFact(kCAM_APERTURE) : nullptr; } //----------------------------------------------------------------------------- Fact* QGCCameraControl::wb() { return (_paramComplete && _activeSettings.contains(kCAM_WBMODE)) ? getFact(kCAM_WBMODE) : nullptr; }
bits 64 sub rsp, 8 sub rsp, 128 sub rdi, r10 sub al, 10 sub ax, 10 sub rdx, rcx sub rax, 32 sub [rbp-40], rax ; sub rdi, [rbp-72] sub eax, dword [rdi+44] sub dword [rdi+44], 1 sub r10, rcx