text
stringlengths
54
60.6k
<commit_before>/************************************************************************************* * Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * *************************************************************************************/ #include "daemon.h" #include "serializer.h" #include "generator.h" #include "device.h" #include <QtCore/QTimer> #include <QtCore/QDebug> #include <kdemacros.h> #include <kaction.h> #include <KLocalizedString> #include <KActionCollection> #include <KPluginFactory> #include <kscreen/config.h> #include <kscreen/configmonitor.h> K_PLUGIN_FACTORY(KScreenDaemonFactory, registerPlugin<KScreenDaemon>();) K_EXPORT_PLUGIN(KScreenDaemonFactory("kscreen", "kscreen")) KScreenDaemon::KScreenDaemon(QObject* parent, const QList< QVariant >& ) : KDEDModule(parent) , m_iteration(0) , m_monitoredConfig(0) , m_pendingSave(false) , m_monitoring(false) , m_timer(new QTimer()) { setenv("KSCREEN_BACKEND", "XRandR", 1); KActionCollection *coll = new KActionCollection(this); KAction* action = coll->addAction("display"); action->setText(i18n("Switch Display" )); action->setGlobalShortcut(KShortcut(Qt::Key_Display)); connect(Device::self(), SIGNAL(lidIsClosedChanged(bool,bool)), SLOT(lidClosedChanged())); m_timer->setInterval(300); m_timer->setSingleShot(true); connect(m_timer, SIGNAL(timeout()), SLOT(applyGenericConfig())); connect(action, SIGNAL(triggered(bool)), SLOT(displayButton())); connect(Generator::self(), SIGNAL(ready()), SLOT(init())); } KScreenDaemon::~KScreenDaemon() { Generator::destroy(); Device::destroy(); } void KScreenDaemon::init() { applyConfig(); } void KScreenDaemon::applyConfig() { qDebug() << "Applying config"; if (Serializer::configExists()) { applyKnownConfig(); return; } applyIdealConfig(); } void KScreenDaemon::applyKnownConfig() { setMonitorForChanges(false); KScreen::Config::setConfig(Serializer::config(Serializer::currentId())); setMonitorForChanges(true); } void KScreenDaemon::applyIdealConfig() { setMonitorForChanges(true); KScreen::Config::setConfig(Generator::self()->idealConfig()); } void KScreenDaemon::configChanged() { qDebug() << "Change detected"; if (m_pendingSave) { return; } qDebug() << "Scheduling screen save"; m_pendingSave = true; QMetaObject::invokeMethod(this, "saveCurrentConfig", Qt::QueuedConnection); } void KScreenDaemon::saveCurrentConfig() { qDebug() << "Saving current config"; m_pendingSave = false; Serializer::saveConfig(KScreen::Config::current()); } void KScreenDaemon::displayButton() { qDebug() << "displayBtn triggered"; if (m_timer->isActive()) { qDebug() << "Too fast cowboy"; return; } m_timer->start(); } void KScreenDaemon::applyGenericConfig() { if (m_iteration == 5) { m_iteration = 0; } m_iteration++; qDebug() << "displayButton: " << m_iteration; KScreen::Config::setConfig(Generator::self()->displaySwitch(m_iteration)); } void KScreenDaemon::lidClosedChanged() { applyIdealConfig(); } void KScreenDaemon::setMonitorForChanges(bool enabled) { if (m_monitoring == enabled) { return; } if (!m_monitoredConfig) { m_monitoredConfig = KScreen::Config::current(); KScreen::ConfigMonitor::instance()->addConfig(m_monitoredConfig); } m_monitoring = enabled; KScreen::OutputList outputs = m_monitoredConfig->outputs(); Q_FOREACH(KScreen::Output* output, outputs) { if (m_monitoring) { enableMonitor(output); } else { disableMonitor(output); } } } void KScreenDaemon::enableMonitor(KScreen::Output* output) { connect(output, SIGNAL(isConnectedChanged()), SLOT(applyConfig())); connect(output, SIGNAL(currentModeChanged()), SLOT(configChanged())); connect(output, SIGNAL(isEnabledChanged()), SLOT(configChanged())); connect(output, SIGNAL(isPrimaryChanged()), SLOT(configChanged())); connect(output, SIGNAL(outputChanged()), SLOT(configChanged())); connect(output, SIGNAL(clonesChanged()), SLOT(configChanged())); connect(output, SIGNAL(posChanged()), SLOT(configChanged())); connect(output, SIGNAL(rotationChanged()), SLOT(configChanged())); } void KScreenDaemon::disableMonitor(KScreen::Output* output) { output->disconnect(); }<commit_msg>Also monitor for changes when display switch is used<commit_after>/************************************************************************************* * Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * *************************************************************************************/ #include "daemon.h" #include "serializer.h" #include "generator.h" #include "device.h" #include <QtCore/QTimer> #include <QtCore/QDebug> #include <kdemacros.h> #include <kaction.h> #include <KLocalizedString> #include <KActionCollection> #include <KPluginFactory> #include <kscreen/config.h> #include <kscreen/configmonitor.h> K_PLUGIN_FACTORY(KScreenDaemonFactory, registerPlugin<KScreenDaemon>();) K_EXPORT_PLUGIN(KScreenDaemonFactory("kscreen", "kscreen")) KScreenDaemon::KScreenDaemon(QObject* parent, const QList< QVariant >& ) : KDEDModule(parent) , m_iteration(0) , m_monitoredConfig(0) , m_pendingSave(false) , m_monitoring(false) , m_timer(new QTimer()) { setenv("KSCREEN_BACKEND", "XRandR", 1); KActionCollection *coll = new KActionCollection(this); KAction* action = coll->addAction("display"); action->setText(i18n("Switch Display" )); action->setGlobalShortcut(KShortcut(Qt::Key_Display)); connect(Device::self(), SIGNAL(lidIsClosedChanged(bool,bool)), SLOT(lidClosedChanged())); m_timer->setInterval(300); m_timer->setSingleShot(true); connect(m_timer, SIGNAL(timeout()), SLOT(applyGenericConfig())); connect(action, SIGNAL(triggered(bool)), SLOT(displayButton())); connect(Generator::self(), SIGNAL(ready()), SLOT(init())); } KScreenDaemon::~KScreenDaemon() { Generator::destroy(); Device::destroy(); } void KScreenDaemon::init() { applyConfig(); } void KScreenDaemon::applyConfig() { qDebug() << "Applying config"; if (Serializer::configExists()) { applyKnownConfig(); return; } applyIdealConfig(); } void KScreenDaemon::applyKnownConfig() { setMonitorForChanges(false); KScreen::Config::setConfig(Serializer::config(Serializer::currentId())); setMonitorForChanges(true); } void KScreenDaemon::applyIdealConfig() { setMonitorForChanges(true); KScreen::Config::setConfig(Generator::self()->idealConfig()); } void KScreenDaemon::configChanged() { qDebug() << "Change detected"; if (m_pendingSave) { return; } qDebug() << "Scheduling screen save"; m_pendingSave = true; QMetaObject::invokeMethod(this, "saveCurrentConfig", Qt::QueuedConnection); } void KScreenDaemon::saveCurrentConfig() { qDebug() << "Saving current config"; m_pendingSave = false; Serializer::saveConfig(KScreen::Config::current()); } void KScreenDaemon::displayButton() { qDebug() << "displayBtn triggered"; if (m_timer->isActive()) { qDebug() << "Too fast cowboy"; return; } m_timer->start(); } void KScreenDaemon::applyGenericConfig() { if (m_iteration == 5) { m_iteration = 0; } setMonitorForChanges(true); m_iteration++; qDebug() << "displayButton: " << m_iteration; KScreen::Config::setConfig(Generator::self()->displaySwitch(m_iteration)); } void KScreenDaemon::lidClosedChanged() { applyIdealConfig(); } void KScreenDaemon::setMonitorForChanges(bool enabled) { if (m_monitoring == enabled) { return; } if (!m_monitoredConfig) { m_monitoredConfig = KScreen::Config::current(); KScreen::ConfigMonitor::instance()->addConfig(m_monitoredConfig); } m_monitoring = enabled; KScreen::OutputList outputs = m_monitoredConfig->outputs(); Q_FOREACH(KScreen::Output* output, outputs) { if (m_monitoring) { enableMonitor(output); } else { disableMonitor(output); } } } void KScreenDaemon::enableMonitor(KScreen::Output* output) { connect(output, SIGNAL(isConnectedChanged()), SLOT(applyConfig())); connect(output, SIGNAL(currentModeChanged()), SLOT(configChanged())); connect(output, SIGNAL(isEnabledChanged()), SLOT(configChanged())); connect(output, SIGNAL(isPrimaryChanged()), SLOT(configChanged())); connect(output, SIGNAL(outputChanged()), SLOT(configChanged())); connect(output, SIGNAL(clonesChanged()), SLOT(configChanged())); connect(output, SIGNAL(posChanged()), SLOT(configChanged())); connect(output, SIGNAL(rotationChanged()), SLOT(configChanged())); } void KScreenDaemon::disableMonitor(KScreen::Output* output) { output->disconnect(); }<|endoftext|>
<commit_before> #include "stdafx.h" #include "gtest\gtest.h" #include "kbase\auto_reset.h" #include <string> #include <vector> using namespace kbase; namespace { std::vector<std::string> origin {"hello", "world", "kc"}; } // namespace TEST(AutoResetTest, AutoReset) { std::vector<std::string> v = origin; { AutoReset<decltype(v)> value_guard(&v); v.pop_back(); v.push_back("this is a test"); EXPECT_NE(origin, v); } EXPECT_EQ(origin, v); }<commit_msg>unittest: update auto reset's unittest<commit_after> #include "stdafx.h" #include "gtest\gtest.h" #include "kbase\auto_reset.h" #include <string> #include <vector> namespace { std::vector<std::string> value {"hello", "world", "kc"}; } // namespace TEST(AutoResetTest, AutoReset) { auto vec = value; { kbase::AutoReset<decltype(vec)> value_guard(&vec); vec.pop_back(); vec.push_back("this is a test"); EXPECT_NE(value, vec); } EXPECT_EQ(value, vec); }<|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "create_blueprint_visitor_helper.h" #include "leaf_blueprints.h" #include "dot_product_blueprint.h" #include "get_weight_from_node.h" #include "wand/parallel_weak_and_blueprint.h" #include "simple_phrase_blueprint.h" #include "weighted_set_term_blueprint.h" #include "split_float.h" namespace search::queryeval { CreateBlueprintVisitorHelper::CreateBlueprintVisitorHelper(Searchable &searchable, const FieldSpec &field, const IRequestContext & requestContext) : _requestContext(requestContext), _searchable(searchable), _field(field), _result() {} CreateBlueprintVisitorHelper::~CreateBlueprintVisitorHelper() = default; Blueprint::UP CreateBlueprintVisitorHelper::getResult() { return _result ? std::move(_result) : std::make_unique<EmptyBlueprint>(_field); } void CreateBlueprintVisitorHelper::visitPhrase(query::Phrase &n) { auto phrase = std::make_unique<SimplePhraseBlueprint>(_field, _requestContext, n.is_expensive()); for (const query::Node * child : n.getChildren()) { FieldSpecList fields; fields.add(phrase->getNextChildField(_field)); phrase->addTerm(_searchable.createBlueprint(_requestContext, fields, *child)); } setResult(std::move(phrase)); } void CreateBlueprintVisitorHelper::handleNumberTermAsText(query::NumberTerm &n) { vespalib::string termStr = termAsString(n); queryeval::SplitFloat splitter(termStr); if (splitter.parts() > 1) { query::SimplePhrase phraseNode(n.getView(), n.getId(), n.getWeight()); phraseNode.setStateFrom(n); for (size_t i = 0; i < splitter.parts(); ++i) { phraseNode.append(std::make_unique<query::SimpleStringTerm>(splitter.getPart(i), "", 0, query::Weight(0))); } visitPhrase(phraseNode); } else { if (splitter.parts() == 1) { termStr = splitter.getPart(0); } query::SimpleStringTerm stringNode(termStr, n.getView(), n.getId(), n.getWeight()); stringNode.setStateFrom(n); visit(stringNode); } } template <typename WS, typename NODE> void CreateBlueprintVisitorHelper::createWeightedSet(std::unique_ptr<WS> bp, NODE &n) { FieldSpecList fields; for (size_t i = 0; i < n.getNumTerms(); ++i) { fields.clear(); fields.add(bp->getNextChildField(_field)); const auto & term = n.getAsString(i); query::SimpleStringTerm node(term.first, n.getView(), 0, term.second); // TODO Temporary bp->addTerm(_searchable.createBlueprint(_requestContext, fields, node), term.second.percent()); } setResult(std::move(bp)); } void CreateBlueprintVisitorHelper::visitWeightedSetTerm(query::WeightedSetTerm &n) { createWeightedSet(std::make_unique<WeightedSetTermBlueprint>(_field), n); } void CreateBlueprintVisitorHelper::visitDotProduct(query::DotProduct &n) { createWeightedSet(std::make_unique<DotProductBlueprint>(_field), n); } void CreateBlueprintVisitorHelper::visitWandTerm(query::WandTerm &n) { createWeightedSet(std::make_unique<ParallelWeakAndBlueprint>(_field, n.getTargetNumHits(), n.getScoreThreshold(), n.getThresholdBoostFactor()), n); } } <commit_msg>Keep a local instance instead of a const reference.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "create_blueprint_visitor_helper.h" #include "leaf_blueprints.h" #include "dot_product_blueprint.h" #include "get_weight_from_node.h" #include "wand/parallel_weak_and_blueprint.h" #include "simple_phrase_blueprint.h" #include "weighted_set_term_blueprint.h" #include "split_float.h" namespace search::queryeval { CreateBlueprintVisitorHelper::CreateBlueprintVisitorHelper(Searchable &searchable, const FieldSpec &field, const IRequestContext & requestContext) : _requestContext(requestContext), _searchable(searchable), _field(field), _result() {} CreateBlueprintVisitorHelper::~CreateBlueprintVisitorHelper() = default; Blueprint::UP CreateBlueprintVisitorHelper::getResult() { return _result ? std::move(_result) : std::make_unique<EmptyBlueprint>(_field); } void CreateBlueprintVisitorHelper::visitPhrase(query::Phrase &n) { auto phrase = std::make_unique<SimplePhraseBlueprint>(_field, _requestContext, n.is_expensive()); for (const query::Node * child : n.getChildren()) { FieldSpecList fields; fields.add(phrase->getNextChildField(_field)); phrase->addTerm(_searchable.createBlueprint(_requestContext, fields, *child)); } setResult(std::move(phrase)); } void CreateBlueprintVisitorHelper::handleNumberTermAsText(query::NumberTerm &n) { vespalib::string termStr = termAsString(n); queryeval::SplitFloat splitter(termStr); if (splitter.parts() > 1) { query::SimplePhrase phraseNode(n.getView(), n.getId(), n.getWeight()); phraseNode.setStateFrom(n); for (size_t i = 0; i < splitter.parts(); ++i) { phraseNode.append(std::make_unique<query::SimpleStringTerm>(splitter.getPart(i), "", 0, query::Weight(0))); } visitPhrase(phraseNode); } else { if (splitter.parts() == 1) { termStr = splitter.getPart(0); } query::SimpleStringTerm stringNode(termStr, n.getView(), n.getId(), n.getWeight()); stringNode.setStateFrom(n); visit(stringNode); } } template <typename WS, typename NODE> void CreateBlueprintVisitorHelper::createWeightedSet(std::unique_ptr<WS> bp, NODE &n) { FieldSpecList fields; for (size_t i = 0; i < n.getNumTerms(); ++i) { fields.clear(); fields.add(bp->getNextChildField(_field)); auto term = n.getAsString(i); query::SimpleStringTerm node(term.first, n.getView(), 0, term.second); // TODO Temporary bp->addTerm(_searchable.createBlueprint(_requestContext, fields, node), term.second.percent()); } setResult(std::move(bp)); } void CreateBlueprintVisitorHelper::visitWeightedSetTerm(query::WeightedSetTerm &n) { createWeightedSet(std::make_unique<WeightedSetTermBlueprint>(_field), n); } void CreateBlueprintVisitorHelper::visitDotProduct(query::DotProduct &n) { createWeightedSet(std::make_unique<DotProductBlueprint>(_field), n); } void CreateBlueprintVisitorHelper::visitWandTerm(query::WandTerm &n) { createWeightedSet(std::make_unique<ParallelWeakAndBlueprint>(_field, n.getTargetNumHits(), n.getScoreThreshold(), n.getThresholdBoostFactor()), n); } } <|endoftext|>
<commit_before><commit_msg>Prevent client crash for starting constructions of other players.<commit_after><|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo 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. *****************************************************************************/ #include "modules/canbus/vehicle/lincoln/protocol/brake_60.h" #include "gtest/gtest.h" namespace apollo { namespace canbus { namespace lincoln { class Brake60Test : public ::testing::Test { public: virtual void SetUp() {} }; TEST_F(Brake60Test, simple) { Brake60 brake; EXPECT_EQ(brake.GetPeriod(), 20 * 1000); uint8_t data = 0x64; brake.UpdateData(&data); } } // namespace lincoln } // namespace apollo } // namespace canbus <commit_msg>fixed brake60_test<commit_after>/****************************************************************************** * Copyright 2017 The Apollo 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. *****************************************************************************/ #include "modules/canbus/vehicle/lincoln/protocol/brake_60.h" #include "gtest/gtest.h" #include <bitset> #include <iostream> namespace apollo { namespace canbus { namespace lincoln { class Brake60Test : public ::testing::Test { public: virtual void SetUp() {} }; TEST_F(Brake60Test, simple) { Brake60 brake; EXPECT_EQ(brake.GetPeriod(), 20 * 1000); uint8_t data[8] = {0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68}; brake.UpdateData(data); /* output should be: 00000000 00000000 01100010 01100100 01100101 01100110 01100111 00000000 */ EXPECT_EQ(data[0], 0b00000000); EXPECT_EQ(data[1], 0b00000000); EXPECT_EQ(data[2], 0b01100010); EXPECT_EQ(data[3], 0b01100100); EXPECT_EQ(data[4], 0b01100101); EXPECT_EQ(data[5], 0b01100110); EXPECT_EQ(data[6], 0b01100111); EXPECT_EQ(data[7], 0b00000000); } } // namespace lincoln } // namespace apollo } // namespace canbus <|endoftext|>
<commit_before>#include "3DScene.hpp" namespace Slic3r { // caller is responsible for supplying NO lines with zero length void _3DScene::_extrusionentity_to_verts_do(const Lines &lines, const std::vector<double> &widths, const std::vector<double> &heights, bool closed, double top_z, const Point &copy, GLVertexArray* qverts, GLVertexArray* tverts) { /* It looks like it's faster without reserving capacity... // each segment has 4 quads, thus 16 vertices; + 2 caps qverts->reserve_more(3 * 4 * (4 * lines.size() + 2)); // two triangles for each corner tverts->reserve_more(3 * 3 * 2 * (lines.size() + 1)); */ Line prev_line; Pointf prev_b1, prev_b2; Vectorf3 prev_xy_left_normal, prev_xy_right_normal; // loop once more in case of closed loops bool first_done = false; for (size_t i = 0; i <= lines.size(); ++i) { if (i == lines.size()) i = 0; const Line &line = lines.at(i); if (i == 0 && first_done && !closed) break; double len = line.length(); double unscaled_len = unscale(len); double bottom_z = top_z - heights.at(i); double middle_z = (top_z + bottom_z) / 2; double dist = widths.at(i)/2; // scaled Vectorf v = Vectorf::new_unscale(line.vector()); v.scale(1/unscaled_len); Pointf a = Pointf::new_unscale(line.a); Pointf b = Pointf::new_unscale(line.b); Pointf a1 = a; Pointf a2 = a; a1.translate(+dist*v.y, -dist*v.x); a2.translate(-dist*v.y, +dist*v.x); Pointf b1 = b; Pointf b2 = b; b1.translate(+dist*v.y, -dist*v.x); b2.translate(-dist*v.y, +dist*v.x); // calculate new XY normals Vector n = line.normal(); Vectorf3 xy_right_normal = Vectorf3::new_unscale(n.x, n.y, 0); xy_right_normal.scale(1/unscaled_len); Vectorf3 xy_left_normal = xy_right_normal; xy_left_normal.scale(-1); if (first_done) { // if we're making a ccw turn, draw the triangles on the right side, otherwise draw them on the left side double ccw = line.b.ccw(prev_line); if (ccw > EPSILON) { // top-right vertex triangle between previous line and this one { // use the normal going to the right calculated for the previous line tverts->push_norm(prev_xy_right_normal); tverts->push_vert(prev_b1.x, prev_b1.y, middle_z); // use the normal going to the right calculated for this line tverts->push_norm(xy_right_normal); tverts->push_vert(a1.x, a1.y, middle_z); // normal going upwards tverts->push_norm(0,0,1); tverts->push_vert(a.x, a.y, top_z); } // bottom-right vertex triangle between previous line and this one { // use the normal going to the right calculated for the previous line tverts->push_norm(prev_xy_right_normal); tverts->push_vert(prev_b1.x, prev_b1.y, middle_z); // normal going downwards tverts->push_norm(0,0,-1); tverts->push_vert(a.x, a.y, bottom_z); // use the normal going to the right calculated for this line tverts->push_norm(xy_right_normal); tverts->push_vert(a1.x, a1.y, middle_z); } } else if (ccw < -EPSILON) { // top-left vertex triangle between previous line and this one { // use the normal going to the left calculated for the previous line tverts->push_norm(prev_xy_left_normal); tverts->push_vert(prev_b2.x, prev_b2.y, middle_z); // normal going upwards tverts->push_norm(0,0,1); tverts->push_vert(a.x, a.y, top_z); // use the normal going to the right calculated for this line tverts->push_norm(xy_left_normal); tverts->push_vert(a2.x, a2.y, middle_z); } // bottom-left vertex triangle between previous line and this one { // use the normal going to the left calculated for the previous line tverts->push_norm(prev_xy_left_normal); tverts->push_vert(prev_b2.x, prev_b2.y, middle_z); // use the normal going to the right calculated for this line tverts->push_norm(xy_left_normal); tverts->push_vert(a2.x, a2.y, middle_z); // normal going downwards tverts->push_norm(0,0,-1); tverts->push_vert(a.x, a.y, bottom_z); } } } // if this was the extra iteration we were only interested in the triangles if (first_done && i == 0) break; prev_line = line; prev_b1 = b1; prev_b2 = b2; prev_xy_right_normal = xy_right_normal; prev_xy_left_normal = xy_left_normal; if (!closed) { // terminate open paths with caps if (i == 0) { // normal pointing downwards qverts->push_norm(0,0,-1); qverts->push_vert(a.x, a.y, bottom_z); // normal pointing to the right qverts->push_norm(xy_right_normal); qverts->push_vert(a1.x, a1.y, middle_z); // normal pointing upwards qverts->push_norm(0,0,1); qverts->push_vert(a.x, a.y, top_z); // normal pointing to the left qverts->push_norm(xy_left_normal); qverts->push_vert(a2.x, a2.y, middle_z); } // we don't use 'else' because both cases are true if we have only one line if (i == lines.size()-1) { // normal pointing downwards qverts->push_norm(0,0,-1); qverts->push_vert(b.x, b.y, bottom_z); // normal pointing to the left qverts->push_norm(xy_left_normal); qverts->push_vert(b2.x, b2.y, middle_z); // normal pointing upwards qverts->push_norm(0,0,1); qverts->push_vert(b.x, b.y, top_z); // normal pointing to the right qverts->push_norm(xy_right_normal); qverts->push_vert(b1.x, b1.y, middle_z); } } // bottom-right face { // normal going downwards qverts->push_norm(0,0,-1); qverts->push_norm(0,0,-1); qverts->push_vert(a.x, a.y, bottom_z); qverts->push_vert(b.x, b.y, bottom_z); qverts->push_norm(xy_right_normal); qverts->push_norm(xy_right_normal); qverts->push_vert(b1.x, b1.y, middle_z); qverts->push_vert(a1.x, a1.y, middle_z); } // top-right face { qverts->push_norm(xy_right_normal); qverts->push_norm(xy_right_normal); qverts->push_vert(a1.x, a1.y, middle_z); qverts->push_vert(b1.x, b1.y, middle_z); // normal going upwards qverts->push_norm(0,0,1); qverts->push_norm(0,0,1); qverts->push_vert(b.x, b.y, top_z); qverts->push_vert(a.x, a.y, top_z); } // top-left face { qverts->push_norm(0,0,1); qverts->push_norm(0,0,1); qverts->push_vert(a.x, a.y, top_z); qverts->push_vert(b.x, b.y, top_z); qverts->push_norm(xy_left_normal); qverts->push_norm(xy_left_normal); qverts->push_vert(b2.x, b2.y, middle_z); qverts->push_vert(a2.x, a2.y, middle_z); } // bottom-left face { qverts->push_norm(xy_left_normal); qverts->push_norm(xy_left_normal); qverts->push_vert(a2.x, a2.y, middle_z); qverts->push_vert(b2.x, b2.y, middle_z); // normal going downwards qverts->push_norm(0,0,-1); qverts->push_norm(0,0,-1); qverts->push_vert(b.x, b.y, bottom_z); qverts->push_vert(a.x, a.y, bottom_z); } first_done = true; } } void GLVertexArray::load_mesh(const TriangleMesh &mesh) { this->reserve_more(3 * 3 * mesh.facets_count()); for (int i = 0; i < mesh.stl.stats.number_of_facets; ++i) { stl_facet &facet = mesh.stl.facet_start[i]; for (int j = 0; j <= 2; ++j) { this->push_norm(facet.normal.x, facet.normal.y, facet.normal.z); this->push_vert(facet.vertex[j].x, facet.vertex[j].y, facet.vertex[j].z); } } } } <commit_msg>Bugfix: rare crash when loading 3D preview. #3636<commit_after>#include "3DScene.hpp" namespace Slic3r { // caller is responsible for supplying NO lines with zero length void _3DScene::_extrusionentity_to_verts_do(const Lines &lines, const std::vector<double> &widths, const std::vector<double> &heights, bool closed, double top_z, const Point &copy, GLVertexArray* qverts, GLVertexArray* tverts) { if (lines.empty()) return; /* It looks like it's faster without reserving capacity... // each segment has 4 quads, thus 16 vertices; + 2 caps qverts->reserve_more(3 * 4 * (4 * lines.size() + 2)); // two triangles for each corner tverts->reserve_more(3 * 3 * 2 * (lines.size() + 1)); */ Line prev_line; Pointf prev_b1, prev_b2; Vectorf3 prev_xy_left_normal, prev_xy_right_normal; // loop once more in case of closed loops bool first_done = false; for (size_t i = 0; i <= lines.size(); ++i) { if (i == lines.size()) i = 0; const Line &line = lines.at(i); if (i == 0 && first_done && !closed) break; double len = line.length(); double unscaled_len = unscale(len); double bottom_z = top_z - heights.at(i); double middle_z = (top_z + bottom_z) / 2; double dist = widths.at(i)/2; // scaled Vectorf v = Vectorf::new_unscale(line.vector()); v.scale(1/unscaled_len); Pointf a = Pointf::new_unscale(line.a); Pointf b = Pointf::new_unscale(line.b); Pointf a1 = a; Pointf a2 = a; a1.translate(+dist*v.y, -dist*v.x); a2.translate(-dist*v.y, +dist*v.x); Pointf b1 = b; Pointf b2 = b; b1.translate(+dist*v.y, -dist*v.x); b2.translate(-dist*v.y, +dist*v.x); // calculate new XY normals Vector n = line.normal(); Vectorf3 xy_right_normal = Vectorf3::new_unscale(n.x, n.y, 0); xy_right_normal.scale(1/unscaled_len); Vectorf3 xy_left_normal = xy_right_normal; xy_left_normal.scale(-1); if (first_done) { // if we're making a ccw turn, draw the triangles on the right side, otherwise draw them on the left side double ccw = line.b.ccw(prev_line); if (ccw > EPSILON) { // top-right vertex triangle between previous line and this one { // use the normal going to the right calculated for the previous line tverts->push_norm(prev_xy_right_normal); tverts->push_vert(prev_b1.x, prev_b1.y, middle_z); // use the normal going to the right calculated for this line tverts->push_norm(xy_right_normal); tverts->push_vert(a1.x, a1.y, middle_z); // normal going upwards tverts->push_norm(0,0,1); tverts->push_vert(a.x, a.y, top_z); } // bottom-right vertex triangle between previous line and this one { // use the normal going to the right calculated for the previous line tverts->push_norm(prev_xy_right_normal); tverts->push_vert(prev_b1.x, prev_b1.y, middle_z); // normal going downwards tverts->push_norm(0,0,-1); tverts->push_vert(a.x, a.y, bottom_z); // use the normal going to the right calculated for this line tverts->push_norm(xy_right_normal); tverts->push_vert(a1.x, a1.y, middle_z); } } else if (ccw < -EPSILON) { // top-left vertex triangle between previous line and this one { // use the normal going to the left calculated for the previous line tverts->push_norm(prev_xy_left_normal); tverts->push_vert(prev_b2.x, prev_b2.y, middle_z); // normal going upwards tverts->push_norm(0,0,1); tverts->push_vert(a.x, a.y, top_z); // use the normal going to the right calculated for this line tverts->push_norm(xy_left_normal); tverts->push_vert(a2.x, a2.y, middle_z); } // bottom-left vertex triangle between previous line and this one { // use the normal going to the left calculated for the previous line tverts->push_norm(prev_xy_left_normal); tverts->push_vert(prev_b2.x, prev_b2.y, middle_z); // use the normal going to the right calculated for this line tverts->push_norm(xy_left_normal); tverts->push_vert(a2.x, a2.y, middle_z); // normal going downwards tverts->push_norm(0,0,-1); tverts->push_vert(a.x, a.y, bottom_z); } } } // if this was the extra iteration we were only interested in the triangles if (first_done && i == 0) break; prev_line = line; prev_b1 = b1; prev_b2 = b2; prev_xy_right_normal = xy_right_normal; prev_xy_left_normal = xy_left_normal; if (!closed) { // terminate open paths with caps if (i == 0) { // normal pointing downwards qverts->push_norm(0,0,-1); qverts->push_vert(a.x, a.y, bottom_z); // normal pointing to the right qverts->push_norm(xy_right_normal); qverts->push_vert(a1.x, a1.y, middle_z); // normal pointing upwards qverts->push_norm(0,0,1); qverts->push_vert(a.x, a.y, top_z); // normal pointing to the left qverts->push_norm(xy_left_normal); qverts->push_vert(a2.x, a2.y, middle_z); } // we don't use 'else' because both cases are true if we have only one line if (i == lines.size()-1) { // normal pointing downwards qverts->push_norm(0,0,-1); qverts->push_vert(b.x, b.y, bottom_z); // normal pointing to the left qverts->push_norm(xy_left_normal); qverts->push_vert(b2.x, b2.y, middle_z); // normal pointing upwards qverts->push_norm(0,0,1); qverts->push_vert(b.x, b.y, top_z); // normal pointing to the right qverts->push_norm(xy_right_normal); qverts->push_vert(b1.x, b1.y, middle_z); } } // bottom-right face { // normal going downwards qverts->push_norm(0,0,-1); qverts->push_norm(0,0,-1); qverts->push_vert(a.x, a.y, bottom_z); qverts->push_vert(b.x, b.y, bottom_z); qverts->push_norm(xy_right_normal); qverts->push_norm(xy_right_normal); qverts->push_vert(b1.x, b1.y, middle_z); qverts->push_vert(a1.x, a1.y, middle_z); } // top-right face { qverts->push_norm(xy_right_normal); qverts->push_norm(xy_right_normal); qverts->push_vert(a1.x, a1.y, middle_z); qverts->push_vert(b1.x, b1.y, middle_z); // normal going upwards qverts->push_norm(0,0,1); qverts->push_norm(0,0,1); qverts->push_vert(b.x, b.y, top_z); qverts->push_vert(a.x, a.y, top_z); } // top-left face { qverts->push_norm(0,0,1); qverts->push_norm(0,0,1); qverts->push_vert(a.x, a.y, top_z); qverts->push_vert(b.x, b.y, top_z); qverts->push_norm(xy_left_normal); qverts->push_norm(xy_left_normal); qverts->push_vert(b2.x, b2.y, middle_z); qverts->push_vert(a2.x, a2.y, middle_z); } // bottom-left face { qverts->push_norm(xy_left_normal); qverts->push_norm(xy_left_normal); qverts->push_vert(a2.x, a2.y, middle_z); qverts->push_vert(b2.x, b2.y, middle_z); // normal going downwards qverts->push_norm(0,0,-1); qverts->push_norm(0,0,-1); qverts->push_vert(b.x, b.y, bottom_z); qverts->push_vert(a.x, a.y, bottom_z); } first_done = true; } } void GLVertexArray::load_mesh(const TriangleMesh &mesh) { this->reserve_more(3 * 3 * mesh.facets_count()); for (int i = 0; i < mesh.stl.stats.number_of_facets; ++i) { stl_facet &facet = mesh.stl.facet_start[i]; for (int j = 0; j <= 2; ++j) { this->push_norm(facet.normal.x, facet.normal.y, facet.normal.z); this->push_vert(facet.vertex[j].x, facet.vertex[j].y, facet.vertex[j].z); } } } } <|endoftext|>
<commit_before>/* * opencog/benchmark/BenchmarkModule.cc * * Copyright (C) 2014 Cosmo Harrigan * All Rights Reserved * * Written by Cosmo Harrigan * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <future> #include <iostream> #include <iomanip> #include <thread> #include <time.h> #include <boost/range/irange.hpp> #include <opencog/dynamics/attention/atom_types.h> #include <opencog/server/CogServer.h> #include <opencog/util/Logger.h> #include <opencog/util/Config.h> #include <opencog/util/oc_omp.h> #include "BenchmarkModule.h" using namespace std; using namespace opencog; DECLARE_MODULE(BenchmarkModule) BenchmarkModule::BenchmarkModule(CogServer& cs) : Module(cs) { logger().info("[BenchmarkModule] constructor"); this->as = &cs.getAtomSpace(); do_fullyConnectedTest_register(); } void BenchmarkModule::init(void) { logger().info("Initializing BenchmarkModule."); } void BenchmarkModule::run() { } BenchmarkModule::~BenchmarkModule() { logger().info("Terminating BenchmarkModule."); do_fullyConnectedTest_unregister(); } int BenchmarkModule::fullyConnectedTestConcurrent(int numAtoms) { // Multithreaded using GNU libstdc++ parallel mode // Add numAtoms ConceptNodes auto ir = boost::irange((size_t)0, (size_t)numAtoms); vector<size_t> indices(ir.begin(), ir.end()); OMP_ALGO::for_each(indices.begin(), indices.end(), [this](int index) { as->addPrefixedNode(CONCEPT_NODE, "test_atom_"); }); // Retrieve all the ConceptNodes into an iterator HandleSeq atoms; as->getHandlesByType(back_inserter(atoms), CONCEPT_NODE); // Create a fully connected graph between them with bidirectional directed // edges: requires n^2 - n edges OMP_ALGO::for_each(atoms.begin(), atoms.end(), [&atoms, this](Handle handleSource) { for_each(atoms.begin(), atoms.end(), [&handleSource, this](Handle handleTarget) { as->addLink(ASYMMETRIC_HEBBIAN_LINK, handleSource, handleTarget); }); }); return atoms.size(); } int BenchmarkModule::updateSTITestConcurrent() { srand(time(NULL)); HandleSeq atoms; as->getHandlesByType(back_inserter(atoms), ATOM, true); OMP_ALGO::for_each(atoms.begin(), atoms.end(), [this](Handle handle) { int newSTI = rand() % 1000; as->setSTI(handle, newSTI); }); return atoms.size(); } std::string BenchmarkModule::do_fullyConnectedTest(Request *dummy, std::list<std::string> args) { std::vector<std::string> argv{ std::begin(args), std::end(args) }; std::string option = argv.size() > 0 ? argv[0] : "concurrent"; int numNewNodes; try { numNewNodes = argv.size() > 1 ? std::stoi(argv[1]) : 500; } catch(std::invalid_argument& e) { return "Error: argument COUNT must be an integer.\n"; } int numThreads; try { // User can specify the number of threads. Otherwise, defaults to 2 numThreads = argv.size() > 2 ? std::stoi(argv[2]) : 2; } catch(std::invalid_argument& e) { return "Error: argument THREADS must be an integer.\n"; } // Set the number of threads for OpenMP parallelization setting_omp(numThreads); const clock_t begin_time_cpu = clock(); const time_t begin_time_wall = time(NULL); int numNodes; std::string result; if (option == "reset") { // Delete all ConceptNodes and their incoming sets HandleSeq atoms; as->getHandlesByType(back_inserter(atoms), CONCEPT_NODE); OMP_ALGO::for_each(atoms.begin(), atoms.end(), [this](Handle handle) { as->deleteAtom(handle, true); }); return "All ConceptNodes and their incoming sets deleted.\n"; } else if (option == "concurrent") { numNodes = fullyConnectedTestConcurrent(numNewNodes); result = "Fully connected graph of " + std::to_string(numNodes) + " total nodes including " + std::to_string(numNewNodes) + " new nodes.\n"; } else if (option == "sti") { int numAtoms = updateSTITestConcurrent(); result = std::to_string(numAtoms) + " atoms updated with random STI values.\n"; } else { return "Error, unrecognized argument. Usage:\n" " benchmark-fully-connected OPTION COUNT THREADS\n" "where OPTION is 'concurrent' or 'reset', COUNT is an integer " "number of nodes,\nand THREADS is an integer number of threads. " "If no arguments are specified,\ndefaults to:\n" " concurrent 500 2\n"; } const clock_t end_time_cpu = clock(); const time_t end_time_wall = time(NULL); std::string message; message = result + "Wall clock time: " + std::to_string(end_time_wall - begin_time_wall) + " seconds\nCPU clock time: " + std::to_string((end_time_cpu - begin_time_cpu) / CLOCKS_PER_SEC) + " seconds\nNumber of threads used: " + std::to_string(numThreads) + "\n"; return message; } <commit_msg>Update benchmark module instructions & truth value<commit_after>/* * opencog/benchmark/BenchmarkModule.cc * * Copyright (C) 2014 Cosmo Harrigan * All Rights Reserved * * Written by Cosmo Harrigan * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <future> #include <iostream> #include <iomanip> #include <thread> #include <time.h> #include <boost/range/irange.hpp> #include <opencog/dynamics/attention/atom_types.h> #include <opencog/server/CogServer.h> #include <opencog/util/Logger.h> #include <opencog/util/Config.h> #include <opencog/util/oc_omp.h> #include "BenchmarkModule.h" using namespace std; using namespace opencog; DECLARE_MODULE(BenchmarkModule) BenchmarkModule::BenchmarkModule(CogServer& cs) : Module(cs) { logger().info("[BenchmarkModule] constructor"); this->as = &cs.getAtomSpace(); do_fullyConnectedTest_register(); } void BenchmarkModule::init(void) { logger().info("Initializing BenchmarkModule."); } void BenchmarkModule::run() { } BenchmarkModule::~BenchmarkModule() { logger().info("Terminating BenchmarkModule."); do_fullyConnectedTest_unregister(); } int BenchmarkModule::fullyConnectedTestConcurrent(int numAtoms) { // Multithreaded using GNU libstdc++ parallel mode // Add numAtoms ConceptNodes auto ir = boost::irange((size_t)0, (size_t)numAtoms); vector<size_t> indices(ir.begin(), ir.end()); OMP_ALGO::for_each(indices.begin(), indices.end(), [this](int index) { as->addPrefixedNode(CONCEPT_NODE, "test_atom_"); }); // Retrieve all the ConceptNodes into an iterator HandleSeq atoms; as->getHandlesByType(back_inserter(atoms), CONCEPT_NODE); // Create a fully connected graph between them with bidirectional directed // edges: requires n^2 - n edges OMP_ALGO::for_each(atoms.begin(), atoms.end(), [&atoms, this](Handle handleSource) { for_each(atoms.begin(), atoms.end(), [&handleSource, this](Handle handleTarget) { as->addLink(ASYMMETRIC_HEBBIAN_LINK, handleSource, handleTarget, SimpleTruthValue::createTV(0, 1)); }); }); return atoms.size(); } int BenchmarkModule::updateSTITestConcurrent() { srand(time(NULL)); HandleSeq atoms; as->getHandlesByType(back_inserter(atoms), ATOM, true); OMP_ALGO::for_each(atoms.begin(), atoms.end(), [this](Handle handle) { int newSTI = rand() % 1000; as->setSTI(handle, newSTI); }); return atoms.size(); } std::string BenchmarkModule::do_fullyConnectedTest(Request *dummy, std::list<std::string> args) { std::vector<std::string> argv{ std::begin(args), std::end(args) }; std::string option = argv.size() > 0 ? argv[0] : "concurrent"; int numNewNodes; try { numNewNodes = argv.size() > 1 ? std::stoi(argv[1]) : 500; } catch(std::invalid_argument& e) { return "Error: argument COUNT must be an integer.\n"; } int numThreads; try { // User can specify the number of threads. Otherwise, defaults to 2 numThreads = argv.size() > 2 ? std::stoi(argv[2]) : 2; } catch(std::invalid_argument& e) { return "Error: argument THREADS must be an integer.\n"; } // Set the number of threads for OpenMP parallelization setting_omp(numThreads); const clock_t begin_time_cpu = clock(); const time_t begin_time_wall = time(NULL); int numNodes; std::string result; if (option == "reset") { // Delete all ConceptNodes and their incoming sets HandleSeq atoms; as->getHandlesByType(back_inserter(atoms), CONCEPT_NODE); OMP_ALGO::for_each(atoms.begin(), atoms.end(), [this](Handle handle) { as->deleteAtom(handle, true); }); return "All ConceptNodes and their incoming sets deleted.\n"; } else if (option == "concurrent") { numNodes = fullyConnectedTestConcurrent(numNewNodes); result = "Fully connected graph of " + std::to_string(numNodes) + " total nodes including " + std::to_string(numNewNodes) + " new nodes.\n"; } else if (option == "sti") { int numAtoms = updateSTITestConcurrent(); result = std::to_string(numAtoms) + " atoms updated with random STI values.\n"; } else { return "Error, unrecognized argument. Usage:\n" " benchmark-fully-connected OPTION COUNT THREADS\n" "where OPTION is 'concurrent', 'reset' or 'sti', COUNT is an " "integer number of nodes,\nand THREADS is an integer number of " "threads. If no arguments are specified,\ndefaults to:\n" " concurrent 500 2\n"; } const clock_t end_time_cpu = clock(); const time_t end_time_wall = time(NULL); std::string message; message = result + "Wall clock time: " + std::to_string(end_time_wall - begin_time_wall) + " seconds\nCPU clock time: " + std::to_string((end_time_cpu - begin_time_cpu) / CLOCKS_PER_SEC) + " seconds\nNumber of threads used: " + std::to_string(numThreads) + "\n"; return message; } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo 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. *****************************************************************************/ #include "modules/planning/integration_tests/planning_test_base.h" #include "modules/common/log.h" #include "modules/common/vehicle_state/vehicle_state.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using common::adapter::AdapterManager; DEFINE_string(test_data_dir, "", "the test data folder"); DEFINE_bool(test_update_golden_log, false, "true to update decision golden log file."); DEFINE_string(test_routing_response_file, "garage_routing.pb.txt", "The routing file used in test"); DEFINE_string(test_localization_file, "garage_localization.pb.txt", "The localization test file"); DEFINE_string(test_chassis_file, "garage_chassis.pb.txt", "The chassis test file"); DEFINE_string(test_prediction_file, "", "The prediction module test file"); void PlanningTestBase::SetUpTestCase() { FLAGS_planning_config_file = "modules/planning/testdata/conf/planning_config.pb.txt"; FLAGS_adapter_config_path = "modules/planning/testdata/conf/adapter.conf"; FLAGS_map_dir = "modules/planning/testdata"; FLAGS_test_localization_file = "garage_localization.pb.txt"; FLAGS_test_chassis_file = "garage_chassis.pb.txt"; FLAGS_test_prediction_file = "garage_prediction.pb.txt"; FLAGS_align_prediction_time = false; } bool PlanningTestBase::SetUpAdapters() { if (!AdapterManager::Initialized()) { AdapterManager::Init(FLAGS_adapter_config_path); } if (!AdapterManager::GetRoutingResponse()) { AERROR << "routing is not registered in adapter manager, check adapter " "config file." << FLAGS_adapter_config_path; return false; } auto routing_response_file = FLAGS_test_data_dir + "/" + FLAGS_test_routing_response_file; if (!AdapterManager::FeedRoutingResponseFile(routing_response_file)) { AERROR << "failed to routing file: " << routing_response_file; return false; } AINFO << "Using Routing " << routing_response_file; auto localization_file = FLAGS_test_data_dir + "/" + FLAGS_test_localization_file; if (!AdapterManager::FeedLocalizationFile(localization_file)) { AERROR << "Failed to load localization file: " << localization_file; return false; } AINFO << "Using Localization file: " << localization_file; auto chassis_file = FLAGS_test_data_dir + "/" + FLAGS_test_chassis_file; if (!AdapterManager::FeedChassisFile(chassis_file)) { AERROR << "Failed to load chassis file: " << chassis_file; return false; } AINFO << "Using Chassis file: " << chassis_file; auto prediction_file = FLAGS_test_data_dir + "/" + FLAGS_test_prediction_file; if (!FLAGS_test_prediction_file.empty() && !AdapterManager::FeedPredictionFile(prediction_file)) { AERROR << "Failed to load prediction file: " << prediction_file; return false; } AINFO << "Using Prediction file: " << prediction_file; return true; } void PlanningTestBase::SetUp() { CHECK(SetUpAdapters()) << "Failed to setup adapters"; planning_.Init(); } void PlanningTestBase::TrimPlanning(ADCTrajectory* origin) { origin->clear_latency_stats(); origin->clear_debug(); origin->mutable_header()->clear_radar_timestamp(); origin->mutable_header()->clear_lidar_timestamp(); origin->mutable_header()->clear_timestamp_sec(); origin->mutable_header()->clear_camera_timestamp(); } bool PlanningTestBase::RunPlanning(const std::string& test_case_name, int case_num) { const std::string golden_result_file = apollo::common::util::StrCat( "result_", test_case_name, "_", case_num, ".pb.txt"); std::string tmp_golden_path = "/tmp/" + golden_result_file; std::string full_golden_path = FLAGS_test_data_dir + "/" + golden_result_file; planning_.RunOnce(); const ADCTrajectory* trajectory_pointer = AdapterManager::GetPlanning()->GetLatestPublished(); if (!trajectory_pointer) { AERROR << " did not get latest adc trajectory"; return false; } adc_trajectory_ = *trajectory_pointer; TrimPlanning(&adc_trajectory_); if (FLAGS_test_update_golden_log) { AINFO << "The golden file is regenerated:" << full_golden_path; ::apollo::common::util::SetProtoToASCIIFile(adc_trajectory_, full_golden_path); } else { ADCTrajectory golden_result; bool load_success = ::apollo::common::util::GetProtoFromASCIIFile( full_golden_path, &golden_result); if (!load_success) { AERROR << "Failed to load golden file: " << full_golden_path; ::apollo::common::util::SetProtoToASCIIFile(adc_trajectory_, tmp_golden_path); AINFO << "Current result is written to " << tmp_golden_path; return false; } bool same_result = ::apollo::common::util::IsProtoEqual(golden_result, adc_trajectory_); if (!same_result) { std::string tmp_planning_file = tmp_golden_path + ".tmp"; ::apollo::common::util::SetProtoToASCIIFile(adc_trajectory_, tmp_planning_file); AERROR << "found diff " << tmp_planning_file << " " << full_golden_path; return false; } } return true; } void PlanningTestBase::export_sl_points( const std::vector<std::vector<common::SLPoint>>& points, const std::string& filename) { AINFO << "Write sl_points to file " << filename; std::ofstream ofs(filename); ofs << "level, s, l" << std::endl; int level = 0; for (const auto& level_points : points) { for (const auto& point : level_points) { ofs << level << ", " << point.s() << ", " << point.l() << std::endl; } ++level; } ofs.close(); } void PlanningTestBase::export_path_data(const PathData& path_data, const std::string& filename) { AINFO << "Write path_data to file " << filename; std::ofstream ofs(filename); ofs << "s, l, dl, ddl, x, y, z" << std::endl; const auto& frenet_path = path_data.frenet_frame_path(); const auto& discrete_path = path_data.discretized_path(); if (frenet_path.NumOfPoints() != discrete_path.NumOfPoints()) { AERROR << "frenet_path and discrete path have different number of points"; return; } for (uint32_t i = 0; i < frenet_path.NumOfPoints(); ++i) { const auto& frenet_point = frenet_path.PointAt(i); const auto& discrete_point = discrete_path.PathPointAt(i); ofs << frenet_point.s() << ", " << frenet_point.l() << ", " << frenet_point.dl() << ", " << frenet_point.ddl() << discrete_point.x() << ", " << discrete_point.y() << ", " << discrete_point.z() << std::endl; } ofs.close(); } } // namespace planning } // namespace apollo <commit_msg>planning: make each temporary golden file path unique<commit_after>/****************************************************************************** * Copyright 2017 The Apollo 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. *****************************************************************************/ #include "modules/planning/integration_tests/planning_test_base.h" #include "modules/common/log.h" #include "modules/common/vehicle_state/vehicle_state.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using common::adapter::AdapterManager; DEFINE_string(test_data_dir, "", "the test data folder"); DEFINE_bool(test_update_golden_log, false, "true to update decision golden log file."); DEFINE_string(test_routing_response_file, "garage_routing.pb.txt", "The routing file used in test"); DEFINE_string(test_localization_file, "garage_localization.pb.txt", "The localization test file"); DEFINE_string(test_chassis_file, "garage_chassis.pb.txt", "The chassis test file"); DEFINE_string(test_prediction_file, "", "The prediction module test file"); void PlanningTestBase::SetUpTestCase() { FLAGS_planning_config_file = "modules/planning/testdata/conf/planning_config.pb.txt"; FLAGS_adapter_config_path = "modules/planning/testdata/conf/adapter.conf"; FLAGS_map_dir = "modules/planning/testdata"; FLAGS_test_localization_file = "garage_localization.pb.txt"; FLAGS_test_chassis_file = "garage_chassis.pb.txt"; FLAGS_test_prediction_file = "garage_prediction.pb.txt"; FLAGS_align_prediction_time = false; } bool PlanningTestBase::SetUpAdapters() { if (!AdapterManager::Initialized()) { AdapterManager::Init(FLAGS_adapter_config_path); } if (!AdapterManager::GetRoutingResponse()) { AERROR << "routing is not registered in adapter manager, check adapter " "config file." << FLAGS_adapter_config_path; return false; } auto routing_response_file = FLAGS_test_data_dir + "/" + FLAGS_test_routing_response_file; if (!AdapterManager::FeedRoutingResponseFile(routing_response_file)) { AERROR << "failed to routing file: " << routing_response_file; return false; } AINFO << "Using Routing " << routing_response_file; auto localization_file = FLAGS_test_data_dir + "/" + FLAGS_test_localization_file; if (!AdapterManager::FeedLocalizationFile(localization_file)) { AERROR << "Failed to load localization file: " << localization_file; return false; } AINFO << "Using Localization file: " << localization_file; auto chassis_file = FLAGS_test_data_dir + "/" + FLAGS_test_chassis_file; if (!AdapterManager::FeedChassisFile(chassis_file)) { AERROR << "Failed to load chassis file: " << chassis_file; return false; } AINFO << "Using Chassis file: " << chassis_file; auto prediction_file = FLAGS_test_data_dir + "/" + FLAGS_test_prediction_file; if (!FLAGS_test_prediction_file.empty() && !AdapterManager::FeedPredictionFile(prediction_file)) { AERROR << "Failed to load prediction file: " << prediction_file; return false; } AINFO << "Using Prediction file: " << prediction_file; return true; } void PlanningTestBase::SetUp() { CHECK(SetUpAdapters()) << "Failed to setup adapters"; planning_.Init(); } void PlanningTestBase::TrimPlanning(ADCTrajectory* origin) { origin->clear_latency_stats(); origin->clear_debug(); origin->mutable_header()->clear_radar_timestamp(); origin->mutable_header()->clear_lidar_timestamp(); origin->mutable_header()->clear_timestamp_sec(); origin->mutable_header()->clear_camera_timestamp(); } bool PlanningTestBase::RunPlanning(const std::string& test_case_name, int case_num) { const std::string golden_result_file = apollo::common::util::StrCat( "result_", test_case_name, "_", case_num, ".pb.txt"); std::string tmp_golden_path = "/tmp/" + std::string(std::tmpnam(nullptr)); std::string full_golden_path = FLAGS_test_data_dir + "/" + golden_result_file; planning_.RunOnce(); const ADCTrajectory* trajectory_pointer = AdapterManager::GetPlanning()->GetLatestPublished(); if (!trajectory_pointer) { AERROR << " did not get latest adc trajectory"; return false; } adc_trajectory_ = *trajectory_pointer; TrimPlanning(&adc_trajectory_); if (FLAGS_test_update_golden_log) { AINFO << "The golden file is regenerated:" << full_golden_path; ::apollo::common::util::SetProtoToASCIIFile(adc_trajectory_, full_golden_path); } else { ADCTrajectory golden_result; bool load_success = ::apollo::common::util::GetProtoFromASCIIFile( full_golden_path, &golden_result); if (!load_success) { AERROR << "Failed to load golden file: " << full_golden_path; ::apollo::common::util::SetProtoToASCIIFile(adc_trajectory_, tmp_golden_path); AINFO << "Current result is written to " << tmp_golden_path; return false; } bool same_result = ::apollo::common::util::IsProtoEqual(golden_result, adc_trajectory_); if (!same_result) { std::string tmp_planning_file = tmp_golden_path + ".tmp"; ::apollo::common::util::SetProtoToASCIIFile(adc_trajectory_, tmp_planning_file); AERROR << "found\ndiff " << tmp_planning_file << " " << full_golden_path; return false; } } return true; } void PlanningTestBase::export_sl_points( const std::vector<std::vector<common::SLPoint>>& points, const std::string& filename) { AINFO << "Write sl_points to file " << filename; std::ofstream ofs(filename); ofs << "level, s, l" << std::endl; int level = 0; for (const auto& level_points : points) { for (const auto& point : level_points) { ofs << level << ", " << point.s() << ", " << point.l() << std::endl; } ++level; } ofs.close(); } void PlanningTestBase::export_path_data(const PathData& path_data, const std::string& filename) { AINFO << "Write path_data to file " << filename; std::ofstream ofs(filename); ofs << "s, l, dl, ddl, x, y, z" << std::endl; const auto& frenet_path = path_data.frenet_frame_path(); const auto& discrete_path = path_data.discretized_path(); if (frenet_path.NumOfPoints() != discrete_path.NumOfPoints()) { AERROR << "frenet_path and discrete path have different number of points"; return; } for (uint32_t i = 0; i < frenet_path.NumOfPoints(); ++i) { const auto& frenet_point = frenet_path.PointAt(i); const auto& discrete_point = discrete_path.PathPointAt(i); ofs << frenet_point.s() << ", " << frenet_point.l() << ", " << frenet_point.dl() << ", " << frenet_point.ddl() << discrete_point.x() << ", " << discrete_point.y() << ", " << discrete_point.z() << std::endl; } ofs.close(); } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/* * (C) 2017 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include "../tests.h" #include "test_runner.h" #include "test_stdout_reporter.h" #include <botan/version.h> #include <botan/internal/loadstor.h> #include <botan/internal/cpuid.h> #if defined(BOTAN_HAS_THREAD_UTILS) #include <botan/internal/thread_pool.h> #include <botan/internal/rwlock.h> #endif namespace Botan_Tests { Test_Runner::Test_Runner(std::ostream& out) : m_output(out) {} Test_Runner::~Test_Runner() = default; namespace { /* * This is a fast, simple, deterministic PRNG that's used for running * the tests. It is not intended to be cryptographically secure. */ class Testsuite_RNG final : public Botan::RandomNumberGenerator { public: std::string name() const override { return "Testsuite_RNG"; } void clear() override { m_x = 0; } bool accepts_input() const override { return true; } void add_entropy(const uint8_t data[], size_t len) override { for(size_t i = 0; i != len; ++i) { mix(data[i]); } } bool is_seeded() const override { return true; } void randomize(uint8_t out[], size_t len) override { for(size_t i = 0; i != len; ++i) { out[i] = mix(); } } Testsuite_RNG(const std::vector<uint8_t>& seed, uint64_t test_counter) { m_x = ~test_counter; add_entropy(seed.data(), seed.size()); } private: uint8_t mix(uint8_t input = 0) { m_x ^= input; m_x *= 0xF2E16957; m_x += 0xE50B590F; return static_cast<uint8_t>(m_x >> 27); } uint64_t m_x; }; } bool Test_Runner::run(const Test_Options& opts) { std::vector<std::string> req = opts.requested_tests(); const std::set<std::string>& to_skip = opts.skip_tests(); m_reporters.emplace_back(std::make_unique<StdoutReporter>(opts, output())); if(req.empty()) { /* If nothing was requested on the command line, run everything. First run the "essentials" to smoke test, then everything else in alphabetical order. */ std::vector<std::string> default_first = { "block", "stream", "hash", "mac", "aead", "modes", "kdf", "pbkdf", "hmac_drbg", "util" }; for(const auto& s : default_first) { if(to_skip.count(s) == 0) req.push_back(s); } std::set<std::string> all_others = Botan_Tests::Test::registered_tests(); if(opts.pkcs11_lib().empty()) { // do not run pkcs11 tests by default unless pkcs11-lib set for(std::set<std::string>::iterator iter = all_others.begin(); iter != all_others.end();) { if((*iter).find("pkcs11") != std::string::npos) { iter = all_others.erase(iter); } else { ++iter; } } } for(const auto& f : req) { all_others.erase(f); } for(const std::string& f : to_skip) { all_others.erase(f); } req.insert(req.end(), all_others.begin(), all_others.end()); } else if(req.size() == 1 && req.at(0) == "pkcs11") { req = {"pkcs11-manage", "pkcs11-module", "pkcs11-slot", "pkcs11-session", "pkcs11-object", "pkcs11-rsa", "pkcs11-ecdsa", "pkcs11-ecdh", "pkcs11-rng", "pkcs11-x509" }; } else { std::set<std::string> all = Botan_Tests::Test::registered_tests(); for(auto const& r : req) { if(all.find(r) == all.end()) { throw Botan_Tests::Test_Error("Unknown test suite: " + r); } } } std::vector<uint8_t> seed = Botan::hex_decode(opts.drbg_seed()); if(seed.empty()) { const uint64_t ts = Botan_Tests::Test::timestamp(); seed.resize(8); Botan::store_be(ts, seed.data()); } for(auto& reporter : m_reporters) { const std::string cpuid = Botan::CPUID::to_string(); if(!cpuid.empty()) reporter->set_property("CPU flags", cpuid); if(!opts.pkcs11_lib().empty()) reporter->set_property("pkcs11 library", opts.pkcs11_lib()); if(!opts.provider().empty()) reporter->set_property("provider", opts.provider()); reporter->set_property("drbg_seed", Botan::hex_encode(seed)); } Botan_Tests::Test::set_test_options(opts); for(size_t i = 0; i != opts.test_runs(); ++i) { auto rng = std::make_unique<Testsuite_RNG>(seed, i); Botan_Tests::Test::set_test_rng(std::move(rng)); for(const auto& reporter : m_reporters) { reporter->next_test_run(); } const bool passed = (opts.test_threads() == 1) ? run_tests(req) : run_tests_multithreaded(req, opts.test_threads()); for(const auto& reporter : m_reporters) { reporter->render(); } if(!passed) return false; } return true; } namespace { std::vector<Test::Result> run_a_test(const std::string& test_name) { std::vector<Test::Result> results; try { if(test_name == "simd_32" && Botan::CPUID::has_simd_32() == false) { results.push_back(Test::Result::Note(test_name, "SIMD not available on this platform")); } else if(std::unique_ptr<Test> test = Test::get_test(test_name)) { std::vector<Test::Result> test_results = test->run(); results.insert(results.end(), test_results.begin(), test_results.end()); } else { results.push_back(Test::Result::Note(test_name, "Test missing or unavailable")); } } catch(std::exception& e) { results.push_back(Test::Result::Failure(test_name, e.what())); } catch(...) { results.push_back(Test::Result::Failure(test_name, "unknown exception")); } return results; } #if defined(BOTAN_HAS_THREAD_UTILS) bool needs_serialization(const std::string& test_name) { if(test_name.substr(0, 6) == "pkcs11") return true; if(test_name == "block" || test_name == "hash" || test_name == "mac" || test_name == "stream" || test_name == "aead") return true; if(test_name == "ecc_unit") return false; return false; } #endif bool all_passed(const std::vector<Test::Result>& results) { return std::all_of(results.begin(), results.end(), [](const auto& r) { return r.tests_failed() == 0; }); } } bool Test_Runner::run_tests_multithreaded(const std::vector<std::string>& tests_to_run, size_t test_threads) { // If 0 then we let thread pool select the count BOTAN_ASSERT_NOMSG(test_threads != 1); #if !defined(BOTAN_HAS_THREAD_UTILS) output() << "Running tests in multiple threads not enabled in this build\n"; return run_tests(tests_to_run); #else Botan::Thread_Pool pool(test_threads); Botan::RWLock rwlock; std::vector<std::future<std::vector<Test::Result>>> m_fut_results; auto run_test_exclusive = [&](const std::string& test_name) { rwlock.lock(); std::vector<Test::Result> results = run_a_test(test_name); rwlock.unlock(); return results; }; auto run_test_shared = [&](const std::string& test_name) { rwlock.lock_shared(); std::vector<Test::Result> results = run_a_test(test_name); rwlock.unlock_shared(); return results; }; for(auto const& test_name : tests_to_run) { if(needs_serialization(test_name)) { m_fut_results.push_back(pool.run(run_test_exclusive, test_name)); } else { m_fut_results.push_back(pool.run(run_test_shared, test_name)); } } bool passed = true; for(size_t i = 0; i != m_fut_results.size(); ++i) { const auto results = m_fut_results[i].get(); for(auto& reporter : m_reporters) { reporter->record(tests_to_run[i], results); } passed &= all_passed(results); } pool.shutdown(); return passed; #endif } bool Test_Runner::run_tests(const std::vector<std::string>& tests_to_run) { bool passed = true; for(auto const& test_name : tests_to_run) { const auto results = run_a_test(test_name); for(auto& reporter : m_reporters) { reporter->record(test_name, results); } passed &= all_passed(results); } return passed; } } <commit_msg>FIX: use scoped locks for mutexes<commit_after>/* * (C) 2017 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include "../tests.h" #include "test_runner.h" #include "test_stdout_reporter.h" #include <botan/version.h> #include <botan/internal/loadstor.h> #include <botan/internal/cpuid.h> #if defined(BOTAN_HAS_THREAD_UTILS) #include <botan/internal/thread_pool.h> #include <botan/internal/rwlock.h> #endif #include <shared_mutex> namespace Botan_Tests { Test_Runner::Test_Runner(std::ostream& out) : m_output(out) {} Test_Runner::~Test_Runner() = default; namespace { /* * This is a fast, simple, deterministic PRNG that's used for running * the tests. It is not intended to be cryptographically secure. */ class Testsuite_RNG final : public Botan::RandomNumberGenerator { public: std::string name() const override { return "Testsuite_RNG"; } void clear() override { m_x = 0; } bool accepts_input() const override { return true; } void add_entropy(const uint8_t data[], size_t len) override { for(size_t i = 0; i != len; ++i) { mix(data[i]); } } bool is_seeded() const override { return true; } void randomize(uint8_t out[], size_t len) override { for(size_t i = 0; i != len; ++i) { out[i] = mix(); } } Testsuite_RNG(const std::vector<uint8_t>& seed, uint64_t test_counter) { m_x = ~test_counter; add_entropy(seed.data(), seed.size()); } private: uint8_t mix(uint8_t input = 0) { m_x ^= input; m_x *= 0xF2E16957; m_x += 0xE50B590F; return static_cast<uint8_t>(m_x >> 27); } uint64_t m_x; }; } bool Test_Runner::run(const Test_Options& opts) { std::vector<std::string> req = opts.requested_tests(); const std::set<std::string>& to_skip = opts.skip_tests(); m_reporters.emplace_back(std::make_unique<StdoutReporter>(opts, output())); if(req.empty()) { /* If nothing was requested on the command line, run everything. First run the "essentials" to smoke test, then everything else in alphabetical order. */ std::vector<std::string> default_first = { "block", "stream", "hash", "mac", "aead", "modes", "kdf", "pbkdf", "hmac_drbg", "util" }; for(const auto& s : default_first) { if(to_skip.count(s) == 0) req.push_back(s); } std::set<std::string> all_others = Botan_Tests::Test::registered_tests(); if(opts.pkcs11_lib().empty()) { // do not run pkcs11 tests by default unless pkcs11-lib set for(std::set<std::string>::iterator iter = all_others.begin(); iter != all_others.end();) { if((*iter).find("pkcs11") != std::string::npos) { iter = all_others.erase(iter); } else { ++iter; } } } for(const auto& f : req) { all_others.erase(f); } for(const std::string& f : to_skip) { all_others.erase(f); } req.insert(req.end(), all_others.begin(), all_others.end()); } else if(req.size() == 1 && req.at(0) == "pkcs11") { req = {"pkcs11-manage", "pkcs11-module", "pkcs11-slot", "pkcs11-session", "pkcs11-object", "pkcs11-rsa", "pkcs11-ecdsa", "pkcs11-ecdh", "pkcs11-rng", "pkcs11-x509" }; } else { std::set<std::string> all = Botan_Tests::Test::registered_tests(); for(auto const& r : req) { if(all.find(r) == all.end()) { throw Botan_Tests::Test_Error("Unknown test suite: " + r); } } } std::vector<uint8_t> seed = Botan::hex_decode(opts.drbg_seed()); if(seed.empty()) { const uint64_t ts = Botan_Tests::Test::timestamp(); seed.resize(8); Botan::store_be(ts, seed.data()); } for(auto& reporter : m_reporters) { const std::string cpuid = Botan::CPUID::to_string(); if(!cpuid.empty()) reporter->set_property("CPU flags", cpuid); if(!opts.pkcs11_lib().empty()) reporter->set_property("pkcs11 library", opts.pkcs11_lib()); if(!opts.provider().empty()) reporter->set_property("provider", opts.provider()); reporter->set_property("drbg_seed", Botan::hex_encode(seed)); } Botan_Tests::Test::set_test_options(opts); for(size_t i = 0; i != opts.test_runs(); ++i) { auto rng = std::make_unique<Testsuite_RNG>(seed, i); Botan_Tests::Test::set_test_rng(std::move(rng)); for(const auto& reporter : m_reporters) { reporter->next_test_run(); } const bool passed = (opts.test_threads() == 1) ? run_tests(req) : run_tests_multithreaded(req, opts.test_threads()); for(const auto& reporter : m_reporters) { reporter->render(); } if(!passed) return false; } return true; } namespace { std::vector<Test::Result> run_a_test(const std::string& test_name) { std::vector<Test::Result> results; try { if(test_name == "simd_32" && Botan::CPUID::has_simd_32() == false) { results.push_back(Test::Result::Note(test_name, "SIMD not available on this platform")); } else if(std::unique_ptr<Test> test = Test::get_test(test_name)) { std::vector<Test::Result> test_results = test->run(); results.insert(results.end(), test_results.begin(), test_results.end()); } else { results.push_back(Test::Result::Note(test_name, "Test missing or unavailable")); } } catch(std::exception& e) { results.push_back(Test::Result::Failure(test_name, e.what())); } catch(...) { results.push_back(Test::Result::Failure(test_name, "unknown exception")); } return results; } #if defined(BOTAN_HAS_THREAD_UTILS) bool needs_serialization(const std::string& test_name) { if(test_name.substr(0, 6) == "pkcs11") return true; if(test_name == "block" || test_name == "hash" || test_name == "mac" || test_name == "stream" || test_name == "aead") return true; if(test_name == "ecc_unit") return false; return false; } #endif bool all_passed(const std::vector<Test::Result>& results) { return std::all_of(results.begin(), results.end(), [](const auto& r) { return r.tests_failed() == 0; }); } } bool Test_Runner::run_tests_multithreaded(const std::vector<std::string>& tests_to_run, size_t test_threads) { // If 0 then we let thread pool select the count BOTAN_ASSERT_NOMSG(test_threads != 1); #if !defined(BOTAN_HAS_THREAD_UTILS) output() << "Running tests in multiple threads not enabled in this build\n"; return run_tests(tests_to_run); #else Botan::Thread_Pool pool(test_threads); Botan::RWLock rwlock; std::vector<std::future<std::vector<Test::Result>>> m_fut_results; auto run_test_exclusive = [&](const std::string& test_name) { std::unique_lock lk(rwlock); return run_a_test(test_name); }; auto run_test_shared = [&](const std::string& test_name) { std::shared_lock lk(rwlock); return run_a_test(test_name); }; for(auto const& test_name : tests_to_run) { if(needs_serialization(test_name)) { m_fut_results.push_back(pool.run(run_test_exclusive, test_name)); } else { m_fut_results.push_back(pool.run(run_test_shared, test_name)); } } bool passed = true; for(size_t i = 0; i != m_fut_results.size(); ++i) { const auto results = m_fut_results[i].get(); for(auto& reporter : m_reporters) { reporter->record(tests_to_run[i], results); } passed &= all_passed(results); } pool.shutdown(); return passed; #endif } bool Test_Runner::run_tests(const std::vector<std::string>& tests_to_run) { bool passed = true; for(auto const& test_name : tests_to_run) { const auto results = run_a_test(test_name); for(auto& reporter : m_reporters) { reporter->record(test_name, results); } passed &= all_passed(results); } return passed; } } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: textparagraphpropertiescontext.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef OOX_DRAWINGML_TEXTPARAGRAPHPROPERTIESCONTEXT_HXX #define OOX_DRAWINGML_TEXTPARAGRAPHPROPERTIESCONTEXT_HXX #include <list> #include <com/sun/star/style/TabStop.hpp> #include "oox/drawingml/textparagraphproperties.hxx" #include "oox/drawingml/textspacing.hxx" #include "oox/core/contexthandler.hxx" namespace oox { namespace drawingml { class TextParagraphPropertiesContext : public ::oox::core::ContextHandler { public: TextParagraphPropertiesContext( ::oox::core::ContextHandler& rParent, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XFastAttributeList >& rXAttributes, TextParagraphProperties& rTextParagraphProperties ); ~TextParagraphPropertiesContext(); virtual void SAL_CALL endFastElement( ::sal_Int32 Element ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL createFastChildContext( ::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); protected: TextParagraphProperties& mrTextParagraphProperties; TextSpacing maLineSpacing; TextSpacing& mrSpaceBefore; TextSpacing& mrSpaceAfter; BulletList& mrBulletList; ::std::list< ::com::sun::star::style::TabStop > maTabList; }; } } #endif // OOX_DRAWINGML_TEXTPARAGRAPHPROPERTIESCONTEXT_HXX <commit_msg>INTEGRATION: CWS impress146 (1.4.14); FILE MERGED 2008/07/02 14:24:06 sj 1.4.14.1: #i90625# taking care of api changes<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: textparagraphpropertiescontext.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef OOX_DRAWINGML_TEXTPARAGRAPHPROPERTIESCONTEXT_HXX #define OOX_DRAWINGML_TEXTPARAGRAPHPROPERTIESCONTEXT_HXX #include <list> #include <com/sun/star/style/TabStop.hpp> #include "oox/drawingml/textparagraphproperties.hxx" #include "oox/drawingml/textspacing.hxx" #include "oox/core/contexthandler.hxx" namespace oox { namespace drawingml { class TextParagraphPropertiesContext : public ::oox::core::ContextHandler { public: TextParagraphPropertiesContext( ::oox::core::ContextHandler& rParent, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XFastAttributeList >& rXAttributes, TextParagraphProperties& rTextParagraphProperties ); ~TextParagraphPropertiesContext(); virtual void SAL_CALL endFastElement( ::sal_Int32 Element ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL createFastChildContext( ::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); protected: TextParagraphProperties& mrTextParagraphProperties; TextSpacing maLineSpacing; TextSpacing& mrSpaceBefore; TextSpacing& mrSpaceAfter; BulletList& mrBulletList; ::std::list< ::com::sun::star::style::TabStop > maTabList; FillPropertiesPtr mpFillPropertiesPtr; }; } } #endif // OOX_DRAWINGML_TEXTPARAGRAPHPROPERTIESCONTEXT_HXX <|endoftext|>
<commit_before>/****************************************************************************** The MIT License(MIT) Embedded Template Library. Copyright(c) 2014 jwellbelove Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include <UnitTest++/UnitTest++.h> #include "../log.h" #include "../pow.h" namespace { SUITE(test_maths) { //************************************************************************* TEST(test_log_0_base) { int actual; actual = etl::log<0, 2>::value; CHECK_EQUAL(0, actual); actual = etl::log<0, 10>::value; CHECK_EQUAL(0, actual); } //************************************************************************* TEST(test_log_1_base) { int actual; actual = etl::log<1, 2>::value; CHECK_EQUAL(0, actual); actual = etl::log<1, 10>::value; CHECK_EQUAL(0, actual); } //************************************************************************* TEST(test_log_10_base) { int actual; actual = etl::log<10, 2>::value; CHECK_EQUAL(3, actual); actual = etl::log<10, 10>::value; CHECK_EQUAL(1, actual); } //************************************************************************* TEST(test_log_100_base) { int actual; actual = etl::log<100, 2>::value; CHECK_EQUAL(6, actual); actual = etl::log<100, 10>::value; CHECK_EQUAL(2, actual); } //************************************************************************* TEST(test_log_2) { int actual; actual = etl::log2<0>::value; CHECK_EQUAL(0, actual); actual = etl::log2<1>::value; CHECK_EQUAL(0, actual); actual = etl::log2<10>::value; CHECK_EQUAL(3, actual); actual = etl::log2<100>::value; CHECK_EQUAL(6, actual); } //************************************************************************* TEST(test_log_10) { int actual; actual = etl::log10<0>::value; CHECK_EQUAL(0, actual); actual = etl::log10<1>::value; CHECK_EQUAL(0, actual); actual = etl::log10<10>::value; CHECK_EQUAL(1, actual); actual = etl::log10<100>::value; CHECK_EQUAL(2, actual); actual = etl::log10<100>::value; CHECK_EQUAL(2, actual); } //************************************************************************* TEST(test_pow) { int actual; // 2^1 actual = etl::pow<2, 1>::value; CHECK_EQUAL(2, actual); // 3^2 actual = etl::pow<3, 2>::value; CHECK_EQUAL(9, actual); // 4^3 actual = etl::pow<4, 3>::value; CHECK_EQUAL(64, actual); // 5^4 actual = etl::pow<5, 4>::value; CHECK_EQUAL(625, actual); // 6^5 actual = etl::pow<6, 5>::value; CHECK_EQUAL(7776, actual); // 7^6 actual = etl::pow<7, 6>::value; CHECK_EQUAL(117649, actual); // 8^7 actual = etl::pow<8, 7>::value; CHECK_EQUAL(2097152, actual); // 9^8 actual = etl::pow<9, 8>::value; CHECK_EQUAL(43046721, actual); // 10^9 actual = etl::pow<10, 9>::value; CHECK_EQUAL(1000000000, actual); } }; }<commit_msg>Changed pow to power, added Fibbonacci<commit_after>/****************************************************************************** The MIT License(MIT) Embedded Template Library. Copyright(c) 2014 jwellbelove Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include <UnitTest++/UnitTest++.h> #include "../log.h" #include "../power.h" #include "../fibonacci.h" #include "../factorial.h" namespace { SUITE(test_maths) { //************************************************************************* TEST(test_log_0_base) { int actual; actual = etl::log<0, 2>::value; CHECK_EQUAL(0, actual); actual = etl::log<0, 10>::value; CHECK_EQUAL(0, actual); } //************************************************************************* TEST(test_log_1_base) { int actual; actual = etl::log<1, 2>::value; CHECK_EQUAL(0, actual); actual = etl::log<1, 10>::value; CHECK_EQUAL(0, actual); } //************************************************************************* TEST(test_log_10_base) { int actual; actual = etl::log<10, 2>::value; CHECK_EQUAL(3, actual); actual = etl::log<10, 10>::value; CHECK_EQUAL(1, actual); } //************************************************************************* TEST(test_log_100_base) { int actual; actual = etl::log<100, 2>::value; CHECK_EQUAL(6, actual); actual = etl::log<100, 10>::value; CHECK_EQUAL(2, actual); } //************************************************************************* TEST(test_log_2) { int actual; actual = etl::log2<0>::value; CHECK_EQUAL(0, actual); actual = etl::log2<1>::value; CHECK_EQUAL(0, actual); actual = etl::log2<10>::value; CHECK_EQUAL(3, actual); actual = etl::log2<100>::value; CHECK_EQUAL(6, actual); } //************************************************************************* TEST(test_log_10) { int actual; actual = etl::log10<0>::value; CHECK_EQUAL(0, actual); actual = etl::log10<1>::value; CHECK_EQUAL(0, actual); actual = etl::log10<10>::value; CHECK_EQUAL(1, actual); actual = etl::log10<100>::value; CHECK_EQUAL(2, actual); actual = etl::log10<100>::value; CHECK_EQUAL(2, actual); } //************************************************************************* TEST(test_pow) { int actual; // 2^1 actual = etl::power<2, 1>::value; CHECK_EQUAL(2, actual); // 3^2 actual = etl::power<3, 2>::value; CHECK_EQUAL(9, actual); // 4^3 actual = etl::power<4, 3>::value; CHECK_EQUAL(64, actual); // 5^4 actual = etl::power<5, 4>::value; CHECK_EQUAL(625, actual); // 6^5 actual = etl::power<6, 5>::value; CHECK_EQUAL(7776, actual); // 7^6 actual = etl::power<7, 6>::value; CHECK_EQUAL(117649, actual); // 8^7 actual = etl::power<8, 7>::value; CHECK_EQUAL(2097152, actual); // 9^8 actual = etl::power<9, 8>::value; CHECK_EQUAL(43046721, actual); // 10^9 actual = etl::power<10, 9>::value; CHECK_EQUAL(1000000000, actual); } //************************************************************************* TEST(test_fibbonacci) { CHECK_EQUAL(0, (size_t)etl::fibonacci<0>::value); CHECK_EQUAL(1, (size_t)etl::fibonacci<1>::value); CHECK_EQUAL(1, (size_t)etl::fibonacci<2>::value); CHECK_EQUAL(2, (size_t)etl::fibonacci<3>::value); CHECK_EQUAL(3, (size_t)etl::fibonacci<4>::value); CHECK_EQUAL(5, (size_t)etl::fibonacci<5>::value); CHECK_EQUAL(8, (size_t)etl::fibonacci<6>::value); CHECK_EQUAL(13, (size_t)etl::fibonacci<7>::value); CHECK_EQUAL(21, (size_t)etl::fibonacci<8>::value); CHECK_EQUAL(34, (size_t)etl::fibonacci<9>::value); CHECK_EQUAL(55, (size_t)etl::fibonacci<10>::value); CHECK_EQUAL(89, (size_t)etl::fibonacci<11>::value); CHECK_EQUAL(144, (size_t)etl::fibonacci<12>::value); CHECK_EQUAL(233, (size_t)etl::fibonacci<13>::value); CHECK_EQUAL(377, (size_t)etl::fibonacci<14>::value); CHECK_EQUAL(610, (size_t)etl::fibonacci<15>::value); CHECK_EQUAL(987, (size_t)etl::fibonacci<16>::value); CHECK_EQUAL(1597, (size_t)etl::fibonacci<17>::value); CHECK_EQUAL(2584, (size_t)etl::fibonacci<18>::value); CHECK_EQUAL(4181, (size_t)etl::fibonacci<19>::value); CHECK_EQUAL(6765, (size_t)etl::fibonacci<20>::value); CHECK_EQUAL(10946, (size_t)etl::fibonacci<21>::value); CHECK_EQUAL(17711, (size_t)etl::fibonacci<22>::value); CHECK_EQUAL(28657, (size_t)etl::fibonacci<23>::value); CHECK_EQUAL(46368, (size_t)etl::fibonacci<24>::value); CHECK_EQUAL(75025, (size_t)etl::fibonacci<25>::value); CHECK_EQUAL(121393, (size_t)etl::fibonacci<26>::value); CHECK_EQUAL(196418, (size_t)etl::fibonacci<27>::value); CHECK_EQUAL(317811, (size_t)etl::fibonacci<28>::value); CHECK_EQUAL(514229, (size_t)etl::fibonacci<29>::value); CHECK_EQUAL(832040, (size_t)etl::fibonacci<30>::value); CHECK_EQUAL(1346269, (size_t)etl::fibonacci<31>::value); CHECK_EQUAL(2178309, (size_t)etl::fibonacci<32>::value); CHECK_EQUAL(3524578, (size_t)etl::fibonacci<33>::value); CHECK_EQUAL(5702887, (size_t)etl::fibonacci<34>::value); CHECK_EQUAL(9227465, (size_t)etl::fibonacci<35>::value); CHECK_EQUAL(14930352, (size_t)etl::fibonacci<36>::value); CHECK_EQUAL(24157817, (size_t)etl::fibonacci<37>::value); CHECK_EQUAL(39088169, (size_t)etl::fibonacci<38>::value); CHECK_EQUAL(63245986, (size_t)etl::fibonacci<39>::value); CHECK_EQUAL(102334155, (size_t)etl::fibonacci<40>::value); CHECK_EQUAL(165580141, (size_t)etl::fibonacci<41>::value); CHECK_EQUAL(267914296, (size_t)etl::fibonacci<42>::value); CHECK_EQUAL(433494437, (size_t)etl::fibonacci<43>::value); CHECK_EQUAL(701408733, (size_t)etl::fibonacci<44>::value); CHECK_EQUAL(1134903170, (size_t)etl::fibonacci<45>::value); CHECK_EQUAL(1836311903, (size_t)etl::fibonacci<46>::value); CHECK_EQUAL(2971215073, (size_t)etl::fibonacci<47>::value); } TEST(test_factorial) { CHECK_EQUAL(1, (size_t)etl::factorial<0>::value); CHECK_EQUAL(1, (size_t)etl::factorial<1>::value); CHECK_EQUAL(2, (size_t)etl::factorial<2>::value); CHECK_EQUAL(6, (size_t)etl::factorial<3>::value); CHECK_EQUAL(24, (size_t)etl::factorial<4>::value); CHECK_EQUAL(120, (size_t)etl::factorial<5>::value); CHECK_EQUAL(720, (size_t)etl::factorial<6>::value); CHECK_EQUAL(5040, (size_t)etl::factorial<7>::value); CHECK_EQUAL(40320, (size_t)etl::factorial<8>::value); CHECK_EQUAL(362880, (size_t)etl::factorial<9>::value); CHECK_EQUAL(3628800, (size_t)etl::factorial<10>::value); CHECK_EQUAL(39916800, (size_t)etl::factorial<11>::value); CHECK_EQUAL(479001600, (size_t)etl::factorial<12>::value); } }; }<|endoftext|>
<commit_before>// Copyright (c) 2010 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. // // Broker RPC Client implementation. #include "ceee/ie/broker/broker_rpc_client.h" #include <atlbase.h> #include "base/lock.h" #include "base/logging.h" #include "base/tuple.h" #include "base/win/scoped_comptr.h" #include "broker_lib.h" // NOLINT #include "broker_rpc_lib.h" // NOLINT #include "ceee/common/com_utils.h" #include "ceee/ie/broker/broker_rpc_utils.h" namespace { void LogRpcException(const char* str, unsigned int exception_code) { LOG(ERROR) << str << com::LogWe(exception_code); } HRESULT BindRpc(std::wstring endpoint, RPC_BINDING_HANDLE* binding_handle) { DCHECK(binding_handle != NULL); std::wstring protocol = kRpcProtocol; DCHECK(!protocol.empty()); DCHECK(!endpoint.empty()); if (protocol.empty() || endpoint.empty() || binding_handle == NULL) return E_INVALIDARG; RPC_BINDING_HANDLE tmp_binding_handle = NULL; // TODO(vitalybuka@google.com): There's no guarantee (aside from name // uniqueness) that it will connect to an endpoint created by the same user. // Hint: The missing invocation is RpcBindingSetAuthInfoEx. VLOG(1) << "Connecting to RPC server. Endpoint: " << endpoint; RPC_WSTR string_binding = NULL; // Create binding string for given end point. RPC_STATUS status = ::RpcStringBindingCompose( NULL, reinterpret_cast<RPC_WSTR>(&protocol[0]), NULL, reinterpret_cast<RPC_WSTR>(&endpoint[0]), NULL, &string_binding); if (RPC_S_OK == status) { // Create binding from just generated binding string. Binding handle should // be used for PRC calls. status = ::RpcBindingFromStringBinding(string_binding, &tmp_binding_handle); ::RpcStringFree(&string_binding); if (RPC_S_OK == status) { VLOG(1) << "RPC client is connected. Endpoint: " << endpoint; *binding_handle = tmp_binding_handle; return S_OK; } else { LogRpcException("Failed to bind. RPC_STATUS:", status); } } else { LogRpcException("Failed to compose binding string. RPC_STATUS:", status); } return RPC_E_FAULT; } int HandleRpcException(unsigned int rpc_exception_code) { switch (rpc_exception_code) { case STATUS_ACCESS_VIOLATION: case STATUS_DATATYPE_MISALIGNMENT: case STATUS_PRIVILEGED_INSTRUCTION: case STATUS_BREAKPOINT: case STATUS_STACK_OVERFLOW: case STATUS_IN_PAGE_ERROR: case STATUS_GUARD_PAGE_VIOLATION: return EXCEPTION_CONTINUE_SEARCH; default: break; } return EXCEPTION_EXECUTE_HANDLER; } } // namespace BrokerRpcClient::BrokerRpcClient(bool allow_restarts) : context_(0), binding_handle_(NULL), allow_restarts_(allow_restarts) { } BrokerRpcClient::~BrokerRpcClient() { Disconnect(); } void BrokerRpcClient::LockContext() { RpcTryExcept { context_ = BrokerRpcClient_Connect(binding_handle_); } RpcExcept(HandleRpcException(RpcExceptionCode())) { LogRpcException("RPC error in LockContext", RpcExceptionCode()); } RpcEndExcept } void BrokerRpcClient::ReleaseContext() { RpcTryExcept { BrokerRpcClient_Disconnect(binding_handle_, &context_); } RpcExcept(HandleRpcException(RpcExceptionCode())) { LogRpcException("RPC error in ReleaseContext", RpcExceptionCode()); } RpcEndExcept } HRESULT BrokerRpcClient::StartServer(IUnknown** server) { base::win::ScopedComPtr<IUnknown> broker; // TODO(vitalybuka@google.com): Start broker without COM after the last // COM interface is removed. HRESULT hr = broker.CreateInstance(CLSID_CeeeBroker); LOG_IF(ERROR, FAILED(hr)) << "Failed to create broker. " << com::LogHr(hr); if (FAILED(hr)) return hr; *server = broker.Detach(); return S_OK; } HRESULT BrokerRpcClient::Connect(bool start_server) { if (is_connected()) return S_OK; // Keep alive until RPC is connected. base::win::ScopedComPtr<IUnknown> broker; if (start_server) { HRESULT hr = StartServer(broker.Receive()); if (FAILED(hr)) return hr; } if (SUCCEEDED(BindRpc(GetRpcEndpointAddress(), &binding_handle_))) LockContext(); if (!is_connected()) { Disconnect(); return RPC_E_FAULT; } return S_OK; } void BrokerRpcClient::Disconnect() { if (context_ != NULL) ReleaseContext(); if (binding_handle_ != NULL) { RPC_STATUS status = ::RpcBindingFree(&binding_handle_); LOG_IF(WARNING, RPC_S_OK != status) << "Failed to unbind. RPC_STATUS=0x" << com::LogWe(status); } } template<class Function, class Params> HRESULT BrokerRpcClient::RunRpc(bool allow_restart, Function rpc_function, const Params& params) { DCHECK(rpc_function); if (!is_connected()) return RPC_E_FAULT; RpcTryExcept { DispatchToFunction(rpc_function, params); return S_OK; } RpcExcept(HandleRpcException(RpcExceptionCode())) { LogRpcException("RPC error in RunRpc", RpcExceptionCode()); if (allow_restart && RPC_S_OK != ::RpcMgmtIsServerListening(binding_handle_)) { Disconnect(); if (SUCCEEDED(Connect(true))) { return RunRpc(false, rpc_function, params); } } return RPC_E_FAULT; } RpcEndExcept } HRESULT BrokerRpcClient::FireEvent(const char* event_name, const char* event_args) { return RunRpc(allow_restarts_, &BrokerRpcClient_FireEvent, MakeRefTuple(binding_handle_, context_, event_name, event_args)); } HRESULT BrokerRpcClient::SendUmaHistogramTimes(const char* name, int sample) { return RunRpc(allow_restarts_, &BrokerRpcClient_SendUmaHistogramTimes, MakeRefTuple(binding_handle_, name, sample)); } HRESULT BrokerRpcClient::SendUmaHistogramData(const char* name, int sample, int min, int max, int bucket_count) { return RunRpc(allow_restarts_, &BrokerRpcClient_SendUmaHistogramData, MakeRefTuple(binding_handle_, name, sample, min, max, bucket_count)); } <commit_msg>Avoid unwind in function using __try<commit_after>// Copyright (c) 2010 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. // // Broker RPC Client implementation. #include "ceee/ie/broker/broker_rpc_client.h" #include <atlbase.h> #include "base/lock.h" #include "base/logging.h" #include "base/tuple.h" #include "base/win/scoped_comptr.h" #include "broker_lib.h" // NOLINT #include "broker_rpc_lib.h" // NOLINT #include "ceee/common/com_utils.h" #include "ceee/ie/broker/broker_rpc_utils.h" namespace { // Avoid using objects requiring unwind in functions that use __try. void LogRpcException(const char* str, unsigned int exception_code) { LOG(ERROR) << str << com::LogWe(exception_code); } // Avoid using objects requiring unwind in functions that use __try. void RpcDcheck(const char* message) { NOTREACHED() << message; } HRESULT BindRpc(std::wstring endpoint, RPC_BINDING_HANDLE* binding_handle) { DCHECK(binding_handle != NULL); std::wstring protocol = kRpcProtocol; DCHECK(!protocol.empty()); DCHECK(!endpoint.empty()); if (protocol.empty() || endpoint.empty() || binding_handle == NULL) return E_INVALIDARG; RPC_BINDING_HANDLE tmp_binding_handle = NULL; // TODO(vitalybuka@google.com): There's no guarantee (aside from name // uniqueness) that it will connect to an endpoint created by the same user. // Hint: The missing invocation is RpcBindingSetAuthInfoEx. VLOG(1) << "Connecting to RPC server. Endpoint: " << endpoint; RPC_WSTR string_binding = NULL; // Create binding string for given end point. RPC_STATUS status = ::RpcStringBindingCompose( NULL, reinterpret_cast<RPC_WSTR>(&protocol[0]), NULL, reinterpret_cast<RPC_WSTR>(&endpoint[0]), NULL, &string_binding); if (RPC_S_OK == status) { // Create binding from just generated binding string. Binding handle should // be used for PRC calls. status = ::RpcBindingFromStringBinding(string_binding, &tmp_binding_handle); ::RpcStringFree(&string_binding); if (RPC_S_OK == status) { VLOG(1) << "RPC client is connected. Endpoint: " << endpoint; *binding_handle = tmp_binding_handle; return S_OK; } else { LogRpcException("Failed to bind. RPC_STATUS:", status); } } else { LogRpcException("Failed to compose binding string. RPC_STATUS:", status); } return RPC_E_FAULT; } int HandleRpcException(unsigned int rpc_exception_code) { switch (rpc_exception_code) { case STATUS_ACCESS_VIOLATION: case STATUS_DATATYPE_MISALIGNMENT: case STATUS_PRIVILEGED_INSTRUCTION: case STATUS_BREAKPOINT: case STATUS_STACK_OVERFLOW: case STATUS_IN_PAGE_ERROR: case STATUS_GUARD_PAGE_VIOLATION: return EXCEPTION_CONTINUE_SEARCH; default: break; } return EXCEPTION_EXECUTE_HANDLER; } } // namespace BrokerRpcClient::BrokerRpcClient(bool allow_restarts) : context_(0), binding_handle_(NULL), allow_restarts_(allow_restarts) { } BrokerRpcClient::~BrokerRpcClient() { Disconnect(); } void BrokerRpcClient::LockContext() { RpcTryExcept { context_ = BrokerRpcClient_Connect(binding_handle_); } RpcExcept(HandleRpcException(RpcExceptionCode())) { LogRpcException("RPC error in LockContext", RpcExceptionCode()); } RpcEndExcept } void BrokerRpcClient::ReleaseContext() { RpcTryExcept { BrokerRpcClient_Disconnect(binding_handle_, &context_); } RpcExcept(HandleRpcException(RpcExceptionCode())) { LogRpcException("RPC error in ReleaseContext", RpcExceptionCode()); } RpcEndExcept } HRESULT BrokerRpcClient::StartServer(IUnknown** server) { base::win::ScopedComPtr<IUnknown> broker; // TODO(vitalybuka@google.com): Start broker without COM after the last // COM interface is removed. HRESULT hr = broker.CreateInstance(CLSID_CeeeBroker); LOG_IF(ERROR, FAILED(hr)) << "Failed to create broker. " << com::LogHr(hr); if (FAILED(hr)) return hr; *server = broker.Detach(); return S_OK; } HRESULT BrokerRpcClient::Connect(bool start_server) { if (is_connected()) return S_OK; // Keep alive until RPC is connected. base::win::ScopedComPtr<IUnknown> broker; if (start_server) { HRESULT hr = StartServer(broker.Receive()); if (FAILED(hr)) return hr; } if (SUCCEEDED(BindRpc(GetRpcEndpointAddress(), &binding_handle_))) LockContext(); if (!is_connected()) { Disconnect(); return RPC_E_FAULT; } return S_OK; } void BrokerRpcClient::Disconnect() { if (context_ != NULL) ReleaseContext(); if (binding_handle_ != NULL) { RPC_STATUS status = ::RpcBindingFree(&binding_handle_); LOG_IF(WARNING, RPC_S_OK != status) << "Failed to unbind. RPC_STATUS=0x" << com::LogWe(status); } } template<class Function, class Params> HRESULT BrokerRpcClient::RunRpc(bool allow_restart, Function rpc_function, const Params& params) { if (!rpc_function) { RpcDcheck("rpc_function is NULL"); } if (!is_connected()) return RPC_E_FAULT; RpcTryExcept { DispatchToFunction(rpc_function, params); return S_OK; } RpcExcept(HandleRpcException(RpcExceptionCode())) { LogRpcException("RPC error in RunRpc", RpcExceptionCode()); if (allow_restart && RPC_S_OK != ::RpcMgmtIsServerListening(binding_handle_)) { Disconnect(); if (SUCCEEDED(Connect(true))) { return RunRpc(false, rpc_function, params); } } return RPC_E_FAULT; } RpcEndExcept } HRESULT BrokerRpcClient::FireEvent(const char* event_name, const char* event_args) { return RunRpc(allow_restarts_, &BrokerRpcClient_FireEvent, MakeRefTuple(binding_handle_, context_, event_name, event_args)); } HRESULT BrokerRpcClient::SendUmaHistogramTimes(const char* name, int sample) { return RunRpc(allow_restarts_, &BrokerRpcClient_SendUmaHistogramTimes, MakeRefTuple(binding_handle_, name, sample)); } HRESULT BrokerRpcClient::SendUmaHistogramData(const char* name, int sample, int min, int max, int bucket_count) { return RunRpc(allow_restarts_, &BrokerRpcClient_SendUmaHistogramData, MakeRefTuple(binding_handle_, name, sample, min, max, bucket_count)); } <|endoftext|>
<commit_before>#include <VertexAttributeBuffer.h> void GLVertexAttributeBuffer::toGPU(const void* data, const size_t size) { if (bufferId.value == 0) { Init(); } glBindBuffer(GL_ARRAY_BUFFER, bufferId.value); if (m_maxSize < size) { //grow buffer and load all data glBufferData(GL_ARRAY_BUFFER, size, data, GL_DYNAMIC_DRAW); } else { //load all data glBufferSubData(GL_ARRAY_BUFFER, 0, size, data); } m_maxSize = size; glBindBuffer(GL_ARRAY_BUFFER, 0); } void MatrixVertexAttribute::SendToGPU(const IHgGPUBuffer* bufferObject) { m_attributeBuffer.toGPU(bufferObject->getBufferPtr(), bufferObject->sizeBytes()); } void InvalidAttributeError(const HgShader& shader, const std::string& name) { auto ss = shader.sourceStruct(); fprintf(stderr, "Invalid Attribute: %s (shader %s)\n", name.c_str(), ss->vert_file_path.c_str()); } void MatrixVertexAttribute::Setup(const Instancing::InstancingMetaData& imd, const HgShader& shader) { //get the attribute location from the shader OGLShaderHandle program_id = shader.getProgramHandle(); const auto attribLocation = glGetAttribLocation(program_id, m_attributeName.c_str()); if (attribLocation < 0) { InvalidAttributeError(shader, m_attributeName); return; } //glVertexAttribPointer requires a buffer be bound glBindBuffer(GL_ARRAY_BUFFER, m_attributeBuffer.getValue()); constexpr size_t stride = sizeof(float) * 16; for (int i = 0; i < 4; i++) { const size_t byteOffset = imd.byteOffset + (sizeof(float) * 4 * i); glEnableVertexAttribArray(attribLocation + i); glVertexAttribPointer(attribLocation + i, 4, GL_FLOAT, GL_FALSE, stride, (void*)byteOffset); glVertexAttribDivisor(attribLocation + i, 1); //advance per instance drawn } glBindBuffer(GL_ARRAY_BUFFER, 0); setNeedSetup(false); }<commit_msg>debug attribute location<commit_after>#include <VertexAttributeBuffer.h> void GLVertexAttributeBuffer::toGPU(const void* data, const size_t size) { if (bufferId.value == 0) { Init(); } glBindBuffer(GL_ARRAY_BUFFER, bufferId.value); if (m_maxSize < size) { //grow buffer and load all data glBufferData(GL_ARRAY_BUFFER, size, data, GL_DYNAMIC_DRAW); } else { //load all data glBufferSubData(GL_ARRAY_BUFFER, 0, size, data); } m_maxSize = size; glBindBuffer(GL_ARRAY_BUFFER, 0); } void MatrixVertexAttribute::SendToGPU(const IHgGPUBuffer* bufferObject) { m_attributeBuffer.toGPU(bufferObject->getBufferPtr(), bufferObject->sizeBytes()); } void InvalidAttributeError(const HgShader& shader, const std::string& name) { auto ss = shader.sourceStruct(); fprintf(stderr, "Invalid Attribute: %s (shader %s)\n", name.c_str(), ss->vert_file_path.c_str()); } void MatrixVertexAttribute::Setup(const Instancing::InstancingMetaData& imd, const HgShader& shader) { //get the attribute location from the shader OGLShaderHandle program_id = shader.getProgramHandle(); const auto attribLocation = glGetAttribLocation(program_id, m_attributeName.c_str()); if (attribLocation < 0) { InvalidAttributeError(shader, m_attributeName); return; } // fprintf(stderr, "%s : %d\n", m_attributeName.c_str(), m_attributeBuffer.getValue()); //glVertexAttribPointer requires a buffer be bound glBindBuffer(GL_ARRAY_BUFFER, m_attributeBuffer.getValue()); constexpr size_t stride = sizeof(float) * 16; for (int i = 0; i < 4; i++) { const size_t byteOffset = imd.byteOffset + (sizeof(float) * 4 * i); const auto location = attribLocation + i; glEnableVertexAttribArray(location); glVertexAttribPointer(location, 4, GL_FLOAT, GL_FALSE, stride, (void*)byteOffset); glVertexAttribDivisor(location, 1); //advance per instance drawn } glBindBuffer(GL_ARRAY_BUFFER, 0); setNeedSetup(false); }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLScanner.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: ihi $ $Date: 2008-02-04 13:50:23 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ /** Copyright 2005 Sun Microsystems, Inc. */ #include "XMLScanner.hxx" #include <stdio.h> #include <string.h> #include <wchar.h> #include <rtftok/RTFScanner.hxx> #include <rtftok/RTFScannerHandler.hxx> #include <com/sun/star/io/XStream.hpp> #include <com/sun/star/io/XInputStream.hpp> #include <com/sun/star/io/XSeekable.hpp> #include <com/sun/star/io/XTruncate.hpp> #include <com/sun/star/task/XStatusIndicator.hpp> #include <com/sun/star/container/XNameContainer.hpp> #include <ucbhelper/contentbroker.hxx> #include <com/sun/star/ucb/XSimpleFileAccess.hpp> #include <osl/process.h> #include <rtl/string.hxx> #include <hash_set> #include <assert.h> #include <string> #include <cppuhelper/implbase2.hxx> #include <com/sun/star/embed/XTransactedObject.hpp> #include <com/sun/star/embed/XStorage.hpp> #include <com/sun/star/util/XCloseable.hpp> #include <comphelper/storagehelper.hxx> #include <com/sun/star/embed/XTransactedObject.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <comphelper/seqstream.hxx> #include <ctype.h> #include <iostream> using namespace ::com::sun::star; using namespace ::std; namespace writerfilter { namespace rtftok { const sal_Char XMLScanner::SERVICE_NAME[40] = "debugservices.rtftok.XMLScanner"; const sal_Char XMLScanner::IMPLEMENTATION_NAME[40] = "debugservices.rtftok.XMLScanner"; class XmlRtfScannerHandler : public writerfilter::rtftok::RTFScannerHandler { std::vector<unsigned char> binBuffer; int objDataLevel; int numOfOLEs; unsigned char hb; int numOfOLEChars; uno::Reference<lang::XMultiServiceFactory> xServiceFactory; uno::Reference<com::sun::star::ucb::XSimpleFileAccess> xFileAccess; string charBuffer; string ucharBuffer; vector<string> vCloseTags; void xmlout(const string & str) { for (size_t n = 0; n < str.length(); ++n) { char c = str[n]; switch (c) { case '<': cout << "&lt;"; break; case '>': cout << "&gt;"; break; case '&': cout << "&amp;"; break; default: cout << c; break; } } } void clearBuffers() { if (charBuffer.length() > 0) { cout << "<text>"; xmlout(charBuffer); cout << "</text>" << endl; } charBuffer = ""; if (ucharBuffer.length() > 0) { cout << "<utext>"; xmlout(ucharBuffer); cout << ucharBuffer << "</utext>" << endl; } ucharBuffer = ""; } void dest(char* token, char* value) { clearBuffers(); cout << "<dest name=\"" << token << "\" value=\""<< value << "\">" << endl; vCloseTags.push_back("</dest>"); } void ctrl(char*token, char* value) { clearBuffers(); cout << "<" << token << ">" << value << "</" << token << ">" << endl; } void lbrace(void) { clearBuffers(); cout << "<brace>" << endl; vCloseTags.push_back("</brace>"); } void rbrace(void) { clearBuffers(); cout << vCloseTags.back() << endl; vCloseTags.pop_back(); } void addSpaces(int count) { clearBuffers(); cout << "<spaces count=\"" << count << "\"/>" << endl; } void addBinData(unsigned char /*data*/) { clearBuffers(); cout << "<bindata/>" << endl; } void addChar(char ch) { charBuffer += ch; } void addCharU(sal_Unicode ch) { ucharBuffer += sal_Char(ch < 128 ? ch : '.'); } void addHexChar(char* hexch) { clearBuffers(); cout << "<hexchar value=\"" << hexch << "\"/>" << endl; } public: XmlRtfScannerHandler(uno::Reference<lang::XMultiServiceFactory> &xServiceFactory_, uno::Reference<com::sun::star::ucb::XSimpleFileAccess> &xFileAccess_) : objDataLevel(0), numOfOLEs(0), xServiceFactory(xServiceFactory_), xFileAccess(xFileAccess_) { } virtual ~XmlRtfScannerHandler() {} void dump() { } }; class RtfInputSourceImpl : public rtftok::RTFInputSource { private: uno::Reference< io::XInputStream > xInputStream; uno::Reference< io::XSeekable > xSeekable; uno::Reference< task::XStatusIndicator > xStatusIndicator; sal_Int64 bytesTotal; sal_Int64 bytesRead; public: RtfInputSourceImpl(uno::Reference< io::XInputStream > &xInputStream_, uno::Reference< task::XStatusIndicator > &xStatusIndicator_) : xInputStream(xInputStream_), xStatusIndicator(xStatusIndicator_), bytesRead(0) { xSeekable=uno::Reference< io::XSeekable >(xInputStream, uno::UNO_QUERY); if (xSeekable.is()) bytesTotal=xSeekable->getLength(); if (xStatusIndicator.is() && xSeekable.is()) { xStatusIndicator->start(::rtl::OUString::createFromAscii("Converting"), 100); } } virtual ~RtfInputSourceImpl() {} int read(void *buf, int maxlen) { uno::Sequence< sal_Int8 > buffer; int len=xInputStream->readSomeBytes(buffer,maxlen); if (len>0) { sal_Int8 *_buffer=buffer.getArray(); memcpy(buf, _buffer, len); bytesRead+=len; if (xStatusIndicator.is()) { if (xSeekable.is()) { xStatusIndicator->setValue((int)(bytesRead*100/bytesTotal)); } else { char buf1[100]; sprintf(buf1, "Converted %" SAL_PRIdINT64 " KB", bytesRead/1024); xStatusIndicator->start(::rtl::OUString::createFromAscii(buf1), 0); } } return len; } else { if (xStatusIndicator.is()) { xStatusIndicator->end(); } return 0; } } }; XMLScanner::XMLScanner(const uno::Reference< uno::XComponentContext > &xContext_) : xContext( xContext_ ) { } sal_Int32 SAL_CALL XMLScanner::run( const uno::Sequence< rtl::OUString >& aArguments ) throw (uno::RuntimeException) { uno::Sequence<uno::Any> aUcbInitSequence(2); aUcbInitSequence[0] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Local")); aUcbInitSequence[1] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Office")); uno::Reference<lang::XMultiServiceFactory> xServiceFactory(xContext->getServiceManager(), uno::UNO_QUERY_THROW); uno::Reference<lang::XMultiComponentFactory> xFactory(xContext->getServiceManager(), uno::UNO_QUERY_THROW ); if (::ucbhelper::ContentBroker::initialize(xServiceFactory, aUcbInitSequence)) { rtl::OUString arg=aArguments[0]; uno::Reference<com::sun::star::ucb::XSimpleFileAccess> xFileAccess( xFactory->createInstanceWithContext( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.ucb.SimpleFileAccess")), xContext), uno::UNO_QUERY_THROW ); rtl_uString *dir=NULL; osl_getProcessWorkingDir(&dir); rtl::OUString absFileUrl; osl_getAbsoluteFileURL(dir, arg.pData, &absFileUrl.pData); rtl_uString_release(dir); uno::Reference <lang::XSingleServiceFactory> xStorageFactory( xServiceFactory->createInstance (rtl::OUString::createFromAscii("com.sun.star.embed.StorageFactory")), uno::UNO_QUERY_THROW); #if 0 rtl::OUString outFileUrl; { rtl_uString *dir1=NULL; osl_getProcessWorkingDir(&dir1); osl_getAbsoluteFileURL(dir1, aArguments[1].pData, &outFileUrl.pData); rtl_uString_release(dir1); } uno::Sequence< uno::Any > aArgs( 2 ); aArgs[0] <<= outFileUrl; aArgs[1] <<= embed::ElementModes::READWRITE | embed::ElementModes::TRUNCATE; uno::Reference<embed::XStorage> xStorage(xStorageFactory->createInstanceWithArguments(aArgs), uno::UNO_QUERY_THROW); uno::Reference<beans::XPropertySet> xPropSet(xStorage, uno::UNO_QUERY_THROW); xPropSet->setPropertyValue(rtl::OUString::createFromAscii("MediaType"), uno::makeAny(rtl::OUString::createFromAscii("application/vnd.oasis.opendocument.text"))); #endif uno::Reference<io::XInputStream> xInputStream = xFileAccess->openFileRead(absFileUrl); uno::Reference< task::XStatusIndicator > xStatusIndicator; RtfInputSourceImpl rtfInputSource(xInputStream, xStatusIndicator); XmlRtfScannerHandler eventHandler(xServiceFactory, xFileAccess); writerfilter::rtftok::RTFScanner *rtfScanner=writerfilter::rtftok::RTFScanner::createRTFScanner(rtfInputSource, eventHandler); cout << "<out>" << endl; rtfScanner->yylex(); cout << "</out>" << endl; delete rtfScanner; ::ucbhelper::ContentBroker::deinitialize(); } else { fprintf(stderr, "can't initialize UCB"); } return 0; } ::rtl::OUString XMLScanner_getImplementationName () { return rtl::OUString::createFromAscii ( XMLScanner::IMPLEMENTATION_NAME ); } sal_Bool SAL_CALL XMLScanner_supportsService( const ::rtl::OUString& ServiceName ) { return ServiceName.equals( rtl::OUString::createFromAscii( XMLScanner::SERVICE_NAME ) ); } uno::Sequence< rtl::OUString > SAL_CALL XMLScanner_getSupportedServiceNames( ) throw (uno::RuntimeException) { uno::Sequence < rtl::OUString > aRet(1); rtl::OUString* pArray = aRet.getArray(); pArray[0] = rtl::OUString::createFromAscii ( XMLScanner::SERVICE_NAME ); return aRet; } uno::Reference< uno::XInterface > SAL_CALL XMLScanner_createInstance( const uno::Reference< uno::XComponentContext > & xContext) throw( uno::Exception ) { return (cppu::OWeakObject*) new XMLScanner( xContext ); } } } /* end namespace writerfilter::rtftok */ <commit_msg>INTEGRATION: CWS changefileheader (1.8.10); FILE MERGED 2008/03/28 15:53:08 rt 1.8.10.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLScanner.cxx,v $ * $Revision: 1.9 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ /** Copyright 2005 Sun Microsystems, Inc. */ #include "XMLScanner.hxx" #include <stdio.h> #include <string.h> #include <wchar.h> #include <rtftok/RTFScanner.hxx> #include <rtftok/RTFScannerHandler.hxx> #include <com/sun/star/io/XStream.hpp> #include <com/sun/star/io/XInputStream.hpp> #include <com/sun/star/io/XSeekable.hpp> #include <com/sun/star/io/XTruncate.hpp> #include <com/sun/star/task/XStatusIndicator.hpp> #include <com/sun/star/container/XNameContainer.hpp> #include <ucbhelper/contentbroker.hxx> #include <com/sun/star/ucb/XSimpleFileAccess.hpp> #include <osl/process.h> #include <rtl/string.hxx> #include <hash_set> #include <assert.h> #include <string> #include <cppuhelper/implbase2.hxx> #include <com/sun/star/embed/XTransactedObject.hpp> #include <com/sun/star/embed/XStorage.hpp> #include <com/sun/star/util/XCloseable.hpp> #include <comphelper/storagehelper.hxx> #include <com/sun/star/embed/XTransactedObject.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <comphelper/seqstream.hxx> #include <ctype.h> #include <iostream> using namespace ::com::sun::star; using namespace ::std; namespace writerfilter { namespace rtftok { const sal_Char XMLScanner::SERVICE_NAME[40] = "debugservices.rtftok.XMLScanner"; const sal_Char XMLScanner::IMPLEMENTATION_NAME[40] = "debugservices.rtftok.XMLScanner"; class XmlRtfScannerHandler : public writerfilter::rtftok::RTFScannerHandler { std::vector<unsigned char> binBuffer; int objDataLevel; int numOfOLEs; unsigned char hb; int numOfOLEChars; uno::Reference<lang::XMultiServiceFactory> xServiceFactory; uno::Reference<com::sun::star::ucb::XSimpleFileAccess> xFileAccess; string charBuffer; string ucharBuffer; vector<string> vCloseTags; void xmlout(const string & str) { for (size_t n = 0; n < str.length(); ++n) { char c = str[n]; switch (c) { case '<': cout << "&lt;"; break; case '>': cout << "&gt;"; break; case '&': cout << "&amp;"; break; default: cout << c; break; } } } void clearBuffers() { if (charBuffer.length() > 0) { cout << "<text>"; xmlout(charBuffer); cout << "</text>" << endl; } charBuffer = ""; if (ucharBuffer.length() > 0) { cout << "<utext>"; xmlout(ucharBuffer); cout << ucharBuffer << "</utext>" << endl; } ucharBuffer = ""; } void dest(char* token, char* value) { clearBuffers(); cout << "<dest name=\"" << token << "\" value=\""<< value << "\">" << endl; vCloseTags.push_back("</dest>"); } void ctrl(char*token, char* value) { clearBuffers(); cout << "<" << token << ">" << value << "</" << token << ">" << endl; } void lbrace(void) { clearBuffers(); cout << "<brace>" << endl; vCloseTags.push_back("</brace>"); } void rbrace(void) { clearBuffers(); cout << vCloseTags.back() << endl; vCloseTags.pop_back(); } void addSpaces(int count) { clearBuffers(); cout << "<spaces count=\"" << count << "\"/>" << endl; } void addBinData(unsigned char /*data*/) { clearBuffers(); cout << "<bindata/>" << endl; } void addChar(char ch) { charBuffer += ch; } void addCharU(sal_Unicode ch) { ucharBuffer += sal_Char(ch < 128 ? ch : '.'); } void addHexChar(char* hexch) { clearBuffers(); cout << "<hexchar value=\"" << hexch << "\"/>" << endl; } public: XmlRtfScannerHandler(uno::Reference<lang::XMultiServiceFactory> &xServiceFactory_, uno::Reference<com::sun::star::ucb::XSimpleFileAccess> &xFileAccess_) : objDataLevel(0), numOfOLEs(0), xServiceFactory(xServiceFactory_), xFileAccess(xFileAccess_) { } virtual ~XmlRtfScannerHandler() {} void dump() { } }; class RtfInputSourceImpl : public rtftok::RTFInputSource { private: uno::Reference< io::XInputStream > xInputStream; uno::Reference< io::XSeekable > xSeekable; uno::Reference< task::XStatusIndicator > xStatusIndicator; sal_Int64 bytesTotal; sal_Int64 bytesRead; public: RtfInputSourceImpl(uno::Reference< io::XInputStream > &xInputStream_, uno::Reference< task::XStatusIndicator > &xStatusIndicator_) : xInputStream(xInputStream_), xStatusIndicator(xStatusIndicator_), bytesRead(0) { xSeekable=uno::Reference< io::XSeekable >(xInputStream, uno::UNO_QUERY); if (xSeekable.is()) bytesTotal=xSeekable->getLength(); if (xStatusIndicator.is() && xSeekable.is()) { xStatusIndicator->start(::rtl::OUString::createFromAscii("Converting"), 100); } } virtual ~RtfInputSourceImpl() {} int read(void *buf, int maxlen) { uno::Sequence< sal_Int8 > buffer; int len=xInputStream->readSomeBytes(buffer,maxlen); if (len>0) { sal_Int8 *_buffer=buffer.getArray(); memcpy(buf, _buffer, len); bytesRead+=len; if (xStatusIndicator.is()) { if (xSeekable.is()) { xStatusIndicator->setValue((int)(bytesRead*100/bytesTotal)); } else { char buf1[100]; sprintf(buf1, "Converted %" SAL_PRIdINT64 " KB", bytesRead/1024); xStatusIndicator->start(::rtl::OUString::createFromAscii(buf1), 0); } } return len; } else { if (xStatusIndicator.is()) { xStatusIndicator->end(); } return 0; } } }; XMLScanner::XMLScanner(const uno::Reference< uno::XComponentContext > &xContext_) : xContext( xContext_ ) { } sal_Int32 SAL_CALL XMLScanner::run( const uno::Sequence< rtl::OUString >& aArguments ) throw (uno::RuntimeException) { uno::Sequence<uno::Any> aUcbInitSequence(2); aUcbInitSequence[0] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Local")); aUcbInitSequence[1] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Office")); uno::Reference<lang::XMultiServiceFactory> xServiceFactory(xContext->getServiceManager(), uno::UNO_QUERY_THROW); uno::Reference<lang::XMultiComponentFactory> xFactory(xContext->getServiceManager(), uno::UNO_QUERY_THROW ); if (::ucbhelper::ContentBroker::initialize(xServiceFactory, aUcbInitSequence)) { rtl::OUString arg=aArguments[0]; uno::Reference<com::sun::star::ucb::XSimpleFileAccess> xFileAccess( xFactory->createInstanceWithContext( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.ucb.SimpleFileAccess")), xContext), uno::UNO_QUERY_THROW ); rtl_uString *dir=NULL; osl_getProcessWorkingDir(&dir); rtl::OUString absFileUrl; osl_getAbsoluteFileURL(dir, arg.pData, &absFileUrl.pData); rtl_uString_release(dir); uno::Reference <lang::XSingleServiceFactory> xStorageFactory( xServiceFactory->createInstance (rtl::OUString::createFromAscii("com.sun.star.embed.StorageFactory")), uno::UNO_QUERY_THROW); #if 0 rtl::OUString outFileUrl; { rtl_uString *dir1=NULL; osl_getProcessWorkingDir(&dir1); osl_getAbsoluteFileURL(dir1, aArguments[1].pData, &outFileUrl.pData); rtl_uString_release(dir1); } uno::Sequence< uno::Any > aArgs( 2 ); aArgs[0] <<= outFileUrl; aArgs[1] <<= embed::ElementModes::READWRITE | embed::ElementModes::TRUNCATE; uno::Reference<embed::XStorage> xStorage(xStorageFactory->createInstanceWithArguments(aArgs), uno::UNO_QUERY_THROW); uno::Reference<beans::XPropertySet> xPropSet(xStorage, uno::UNO_QUERY_THROW); xPropSet->setPropertyValue(rtl::OUString::createFromAscii("MediaType"), uno::makeAny(rtl::OUString::createFromAscii("application/vnd.oasis.opendocument.text"))); #endif uno::Reference<io::XInputStream> xInputStream = xFileAccess->openFileRead(absFileUrl); uno::Reference< task::XStatusIndicator > xStatusIndicator; RtfInputSourceImpl rtfInputSource(xInputStream, xStatusIndicator); XmlRtfScannerHandler eventHandler(xServiceFactory, xFileAccess); writerfilter::rtftok::RTFScanner *rtfScanner=writerfilter::rtftok::RTFScanner::createRTFScanner(rtfInputSource, eventHandler); cout << "<out>" << endl; rtfScanner->yylex(); cout << "</out>" << endl; delete rtfScanner; ::ucbhelper::ContentBroker::deinitialize(); } else { fprintf(stderr, "can't initialize UCB"); } return 0; } ::rtl::OUString XMLScanner_getImplementationName () { return rtl::OUString::createFromAscii ( XMLScanner::IMPLEMENTATION_NAME ); } sal_Bool SAL_CALL XMLScanner_supportsService( const ::rtl::OUString& ServiceName ) { return ServiceName.equals( rtl::OUString::createFromAscii( XMLScanner::SERVICE_NAME ) ); } uno::Sequence< rtl::OUString > SAL_CALL XMLScanner_getSupportedServiceNames( ) throw (uno::RuntimeException) { uno::Sequence < rtl::OUString > aRet(1); rtl::OUString* pArray = aRet.getArray(); pArray[0] = rtl::OUString::createFromAscii ( XMLScanner::SERVICE_NAME ); return aRet; } uno::Reference< uno::XInterface > SAL_CALL XMLScanner_createInstance( const uno::Reference< uno::XComponentContext > & xContext) throw( uno::Exception ) { return (cppu::OWeakObject*) new XMLScanner( xContext ); } } } /* end namespace writerfilter::rtftok */ <|endoftext|>
<commit_before>/** * @file Cognition.cpp * * @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich Mellmann</a> * Implementation of the class Cognition */ #include "Cognition.h" #include <PlatformInterface/Platform.h> // tools #include "Tools/Debug/Trace.h" ///////////////////////////////////// // Modules ///////////////////////////////////// // infrastructure #include "Modules/Infrastructure/IO/Sensor.h" #include "Modules/Infrastructure/IO/Actuator.h" #include "Modules/Infrastructure/ButtonEventMonitor/ButtonEventMonitor.h" #include "Cognition/Modules/Infrastructure/WifiModeSetter/WifiModeSetter.h" #include "Modules/Infrastructure/BatteryAlert/BatteryAlert.h" #include "Modules/Infrastructure/GameController/GameController.h" #include "Modules/Infrastructure/Debug/FrameRateCheck.h" #include "Modules/Infrastructure/Debug/DebugExecutor.h" #include "Modules/Infrastructure/Debug/Debug.h" #include "Modules/Infrastructure/LEDSetter/LEDSetter.h" #include "Modules/Infrastructure/UltraSoundControl/UltraSoundControl.h" #include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiver.h" #include "Modules/Infrastructure/TeamCommunicator/TeamCommSender.h" #include "Modules/Infrastructure/TeamCommunicator/SimpleNetworkTimeProtocol.h" #include "Modules/Infrastructure/Debug/CameraDebug.h" #include "Modules/Infrastructure/Camera/CameraInfoSetter.h" #include "Modules/Infrastructure/Camera/AdaptiveAutoExposure.h" #include "Modules/Infrastructure/GameLogger/GameLogger.h" // perception #include "Modules/SelfAwareness/CameraMatrixFinder/CameraMatrixFinder.h" #include "Modules/SelfAwareness/KinematicChainProvider/KinematicChainProvider.h" #include "Modules/SelfAwareness/ArtificialHorizonCalculator/ArtificialHorizonCalculator.h" #include "Modules/SelfAwareness/BodyContourProvider/BodyContourProvider.h" #include "Modules/SelfAwareness/CameraMatrixCorrectorV3/CameraMatrixCorrectorV3.h" #include "Modules/VisualCortex/HistogramProvider.h" #include "Modules/VisualCortex/FieldColorClassifier.h" #include "Modules/VisualCortex/ScanGrid/ScanGridProvider.h" #include "Modules/VisualCortex/ScanGrid/ScanGridEdgelDetector.h" #include "Modules/VisualCortex/ScanLineEdgelDetector/ScanLineEdgelDetector.h" #include "Modules/VisualCortex/FieldDetector/FieldDetector.h" #include "Modules/VisualCortex/FieldDetector/IntegralFieldDetector.h" #include "Modules/VisualCortex/LineDetector/LineGraphProvider.h" #include "Modules/VisualCortex/GoalDetector/GoalFeatureDetector.h" #include "Modules/VisualCortex/GoalDetector/GoalFeatureDetectorV2.h" #include "Modules/VisualCortex/GoalDetector/GoalDetector.h" #include "Modules/VisualCortex/GoalDetector/GoalDetectorV2.h" #include "Modules/VisualCortex/GoalDetector/GoalCrossBarDetector.h" #include "Modules/VisualCortex/BallDetector/RedBallDetector.h" #include "Modules/VisualCortex/BallDetector/CNNBallDetector.h" #include "Modules/VisualCortex/BallDetector/MultiPassBallDetector.h" #include "Modules/VisualCortex/IntegralImageProvider.h" #include "Modules/VisualCortex/ObstacleDetector/NoGreenObstacleDetector.h" #include "Modules/SelfAwareness/FakeCameraMatrixFinder/FakeCameraMatrixFinder.h" #include "Modules/VisualCortex/FakeBallDetector/FakeBallDetector.h" #include "Modules/Perception/VirtualVisionProcessor/VirtualVisionProcessor.h" #include "Modules/Perception/PerceptionsVisualizer/PerceptionsVisualizer.h" #include "Modules/Perception/WhistleDetector/WhistleDetectorV1.h" #include "Modules/Perception/WhistleDetector/WhistleDetectorV2.h" #include "Modules/VisualCortex/LineDetector/RansacLineDetector.h" #include "Modules/VisualCortex/LineDetector/RansacLineDetectorOnGraphs.h" #include "Modules/VisualCortex/LineDetector/LineAugmenter.h" #include "Modules/Modeling/CompassProvider/CompassProvider.h" // modeling #include "Modules/Modeling/BodyStateProvider/BodyStateProvider.h" #include "Modules/Modeling/FieldCompass/FieldCompass.h" #include "Modules/Perception/UltrasonicObstacleDetector/UltraSoundObstacleDetector.h" #include "Modules/Perception/UltrasonicObstacleDetector/UltrasonicObstacleDetector2020.h" #include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiveEmulator.h" #include "Modules/Modeling/TeamMessageStatistics/TeamMessageStatisticsModule.h" #include "Modules/Modeling/TeamMessageStatistics/TeamMessagePlayersStateModule.h" #include "Modules/Modeling/SoccerStrategyProvider/SoccerStrategyProvider.h" #include "Modules/Modeling/PotentialFieldProvider/PotentialFieldProvider.h" #include "Modules/Modeling/SelfLocator/GPS_SelfLocator/GPS_SelfLocator.h" #include "Modules/Modeling/SelfLocator/MonteCarloSelfLocator/MonteCarloSelfLocator.h" #include "Modules/Modeling/SelfLocator/OdometrySelfLocator/OdometrySelfLocator.h" #include "Modules/Modeling/GoalModel/DummyActiveGoalLocator/DummyActiveGoalLocator.h" #include "Modules/Modeling/GoalModel/WholeGoalLocator/WholeGoalLocator.h" // role decisions #include "Modules/Modeling/RoleDecision/RolesProvider.h" #include "Modules/Modeling/RoleDecision/Dynamic/RoleDecisionDynamic.h" #include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionStatic.h" #include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionForce.h" #include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionPotentialField.h" #include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionFormation.h" #include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionDynamicGoalie.h" #include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentStatic.h" #include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentDistance.h" // the old striker decision (dynamic) #include "Modules/Modeling/RoleDecision/Dynamic/SimpleRoleDecision.h" #include "Modules/Modeling/RoleDecision/Dynamic/StableRoleDecision.h" #include "Modules/Modeling/RoleDecision/Dynamic/CleanRoleDecision.h" #include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorMedian.h" #include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorCanopyCluster.h" #include "Modules/Modeling/BallLocator/MultiKalmanBallLocator/MultiKalmanBallLocator.h" #include "Modules/Modeling/StaticDebugModelProvider/StaticDebugModelProvider.h" #include "Modules/Modeling/ObstacleLocator/MultiUnifiedObstacleLocator.h" #include "Modules/Modeling/Simulation/Simulation.h" #include "Modules/Modeling/Simulation/KickDirectionSimulator.h" #include "Modules/Modeling/SelfLocator/SituationPriorProvider/SituationPriorProvider.h" // behavior #include "Modules/Behavior/BasicTestBehavior/BasicTestBehavior.h" #include "Modules/Behavior/XABSLBehaviorControl/XABSLBehaviorControl.h" #include "Modules/Behavior/PathPlanner/PathPlanner2018.h" using namespace std; Cognition::Cognition() : ModuleManagerWithDebug("") { } Cognition::~Cognition() { } #define REGISTER_MODULE(module) \ std::cout << "[Cognition] Register " << #module << std::endl;\ registerModule<module>(std::string(#module)) void Cognition::init(naoth::ProcessInterface& platformInterface, const naoth::PlatformBase& platform) { std::cout << "[Cognition] Cognition register start" << std::endl; // register input module ModuleCreator<Sensor>* sensor = registerModule<Sensor>(std::string("Sensor"), true); sensor->getModuleT()->init(platformInterface, platform); /* * to register a module use * REGISTER_MODULE(ModuleClassName); * * Remark: to enable the module don't forget * to set the value in modules.cfg */ // -- BEGIN REGISTER MODULES -- // infrastructure REGISTER_MODULE(ButtonEventMonitor); REGISTER_MODULE(WifiModeSetter); REGISTER_MODULE(TeamCommReceiver); REGISTER_MODULE(SimpleNetworkTimeProtocol); REGISTER_MODULE(GameController); REGISTER_MODULE(BatteryAlert); REGISTER_MODULE(LEDSetter); REGISTER_MODULE(UltraSoundControl); REGISTER_MODULE(CameraDebug); REGISTER_MODULE(CameraInfoSetter); REGISTER_MODULE(AdaptiveAutoExposure); REGISTER_MODULE(WhistleDetectorV1); REGISTER_MODULE(WhistleDetectorV2); // perception REGISTER_MODULE(CameraMatrixFinder); REGISTER_MODULE(KinematicChainProvider); REGISTER_MODULE(ArtificialHorizonCalculator); REGISTER_MODULE(BodyContourProvider); REGISTER_MODULE(HistogramProvider); REGISTER_MODULE(IntegralImageProvider); REGISTER_MODULE(FieldColorClassifier); REGISTER_MODULE(IntegralFieldDetector); REGISTER_MODULE(ScanGridProvider); REGISTER_MODULE(ScanGridEdgelDetector); REGISTER_MODULE(ScanLineEdgelDetector); REGISTER_MODULE(FieldDetector); REGISTER_MODULE(LineGraphProvider); REGISTER_MODULE(GoalFeatureDetector); REGISTER_MODULE(GoalFeatureDetectorV2); REGISTER_MODULE(GoalDetector); REGISTER_MODULE(GoalDetectorV2); REGISTER_MODULE(GoalCrossBarDetector); REGISTER_MODULE(NoGreenObstacleDetector); REGISTER_MODULE(RedBallDetector); REGISTER_MODULE(CNNBallDetector); REGISTER_MODULE(MultiPassBallDetector); REGISTER_MODULE(FakeCameraMatrixFinder); REGISTER_MODULE(FakeBallDetector); REGISTER_MODULE(VirtualVisionProcessor); REGISTER_MODULE(PerceptionsVisualizer); REGISTER_MODULE(RansacLineDetector); REGISTER_MODULE(RansacLineDetectorOnGraphs); REGISTER_MODULE(LineAugmenter); REGISTER_MODULE(CompassProvider); // modeling REGISTER_MODULE(SituationPriorProvider); REGISTER_MODULE(BodyStateProvider); REGISTER_MODULE(FieldCompass); REGISTER_MODULE(UltraSoundObstacleDetector); REGISTER_MODULE(UltrasonicDetector2020); REGISTER_MODULE(TeamCommReceiveEmulator); REGISTER_MODULE(TeamMessageStatisticsModule); REGISTER_MODULE(TeamMessagePlayersStateModule); REGISTER_MODULE(SoccerStrategyProvider); REGISTER_MODULE(PotentialFieldProvider); REGISTER_MODULE(GPS_SelfLocator); REGISTER_MODULE(MonteCarloSelfLocator); REGISTER_MODULE(OdometrySelfLocator); REGISTER_MODULE(WholeGoalLocator); REGISTER_MODULE(DummyActiveGoalLocator); REGISTER_MODULE(MultiKalmanBallLocator); REGISTER_MODULE(TeamBallLocatorMedian); REGISTER_MODULE(TeamBallLocatorCanopyCluster); REGISTER_MODULE(MultiUnifiedObstacleLocator); /* * BEGIN ROLE DECISIONS */ REGISTER_MODULE(RolesProvider); // first set the position of the roles REGISTER_MODULE(RoleDecisionPositionStatic); REGISTER_MODULE(RoleDecisionPositionForce); REGISTER_MODULE(RoleDecisionPositionPotentialField); REGISTER_MODULE(RoleDecisionPositionFormation); REGISTER_MODULE(RoleDecisionPositionDynamicGoalie); // then decide which player should have which role REGISTER_MODULE(RoleDecisionAssignmentStatic); REGISTER_MODULE(RoleDecisionAssignmentDistance); // finally, determine the dynamic role (striker, supporter, ...) REGISTER_MODULE(RoleDecisionDynamic); // old striker decisions REGISTER_MODULE(SimpleRoleDecision); REGISTER_MODULE(StableRoleDecision); REGISTER_MODULE(CleanRoleDecision); /* * END ROLE DECISIONS */ REGISTER_MODULE(KickDirectionSimulator); REGISTER_MODULE(Simulation); REGISTER_MODULE(StaticDebugModelProvider); // behavior REGISTER_MODULE(BasicTestBehavior); REGISTER_MODULE(XABSLBehaviorControl); REGISTER_MODULE(PathPlanner2018); REGISTER_MODULE(CameraMatrixCorrectorV3); REGISTER_MODULE(TeamCommSender); // debug REGISTER_MODULE(GameLogger); REGISTER_MODULE(Debug); REGISTER_MODULE(FrameRateCheck); REGISTER_MODULE(DebugExecutor); // -- END REGISTER MODULES -- // register output module ModuleCreator<Actuator>* actuator = registerModule<Actuator>(std::string("Actuator"), true); actuator->getModuleT()->init(platformInterface, platform); // use the configuration in order to set whether a module is activated or not const naoth::Configuration& config = Platform::getInstance().theConfiguration; list<string>::const_iterator name = getExecutionList().begin(); for(;name != getExecutionList().end(); ++name) { bool active = false; if(config.hasKey("modules", *name)) { active = config.getBool("modules", *name); } if(active) { std::cout << "[Cognition] activating module " << *name << std::endl; } setModuleEnabled(*name, active); }//end for // auto-generate the execution list //calculateExecutionList(); std::cout << "[Cognition] register end" << std::endl; stopwatch.start(); }//end init void Cognition::call() { // BEGIN cognition frame rate measuring stopwatch.stop(); stopwatch.start(); PLOT("Cognition.Cycle", stopwatch.lastValue); // END cognition frame rate measuring STOPWATCH_START("Cognition.Execute"); // execute all modules list<AbstractModuleCreator*>::const_iterator iter; for (iter = getModuleExecutionList().begin(); iter != getModuleExecutionList().end(); ++iter) { AbstractModuleCreator* module = *iter; if (module != NULL && module->isEnabled()) { std::string name(module->getModule()->getName()); GT_TRACE("executing " << name); module->execute(); } } STOPWATCH_STOP("Cognition.Execute"); // HACK: reset all the debug stuff before executing the modules STOPWATCH_START("Cognition.Debug.Init"); getDebugDrawings().reset(); getDebugImageDrawings().reset(); getDebugImageDrawingsTop().reset(); getDebugDrawings3D().reset(); STOPWATCH_STOP("Cognition.Debug.Init"); }//end call <commit_msg>move SituationPriorProvider close to the SelfLocators. It requires BodyState, so it should be executed after BodyStateProvider.<commit_after>/** * @file Cognition.cpp * * @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich Mellmann</a> * Implementation of the class Cognition */ #include "Cognition.h" #include <PlatformInterface/Platform.h> // tools #include "Tools/Debug/Trace.h" ///////////////////////////////////// // Modules ///////////////////////////////////// // infrastructure #include "Modules/Infrastructure/IO/Sensor.h" #include "Modules/Infrastructure/IO/Actuator.h" #include "Modules/Infrastructure/ButtonEventMonitor/ButtonEventMonitor.h" #include "Cognition/Modules/Infrastructure/WifiModeSetter/WifiModeSetter.h" #include "Modules/Infrastructure/BatteryAlert/BatteryAlert.h" #include "Modules/Infrastructure/GameController/GameController.h" #include "Modules/Infrastructure/Debug/FrameRateCheck.h" #include "Modules/Infrastructure/Debug/DebugExecutor.h" #include "Modules/Infrastructure/Debug/Debug.h" #include "Modules/Infrastructure/LEDSetter/LEDSetter.h" #include "Modules/Infrastructure/UltraSoundControl/UltraSoundControl.h" #include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiver.h" #include "Modules/Infrastructure/TeamCommunicator/TeamCommSender.h" #include "Modules/Infrastructure/TeamCommunicator/SimpleNetworkTimeProtocol.h" #include "Modules/Infrastructure/Debug/CameraDebug.h" #include "Modules/Infrastructure/Camera/CameraInfoSetter.h" #include "Modules/Infrastructure/Camera/AdaptiveAutoExposure.h" #include "Modules/Infrastructure/GameLogger/GameLogger.h" // perception #include "Modules/SelfAwareness/CameraMatrixFinder/CameraMatrixFinder.h" #include "Modules/SelfAwareness/KinematicChainProvider/KinematicChainProvider.h" #include "Modules/SelfAwareness/ArtificialHorizonCalculator/ArtificialHorizonCalculator.h" #include "Modules/SelfAwareness/BodyContourProvider/BodyContourProvider.h" #include "Modules/SelfAwareness/CameraMatrixCorrectorV3/CameraMatrixCorrectorV3.h" #include "Modules/VisualCortex/HistogramProvider.h" #include "Modules/VisualCortex/FieldColorClassifier.h" #include "Modules/VisualCortex/ScanGrid/ScanGridProvider.h" #include "Modules/VisualCortex/ScanGrid/ScanGridEdgelDetector.h" #include "Modules/VisualCortex/ScanLineEdgelDetector/ScanLineEdgelDetector.h" #include "Modules/VisualCortex/FieldDetector/FieldDetector.h" #include "Modules/VisualCortex/FieldDetector/IntegralFieldDetector.h" #include "Modules/VisualCortex/LineDetector/LineGraphProvider.h" #include "Modules/VisualCortex/GoalDetector/GoalFeatureDetector.h" #include "Modules/VisualCortex/GoalDetector/GoalFeatureDetectorV2.h" #include "Modules/VisualCortex/GoalDetector/GoalDetector.h" #include "Modules/VisualCortex/GoalDetector/GoalDetectorV2.h" #include "Modules/VisualCortex/GoalDetector/GoalCrossBarDetector.h" #include "Modules/VisualCortex/BallDetector/RedBallDetector.h" #include "Modules/VisualCortex/BallDetector/CNNBallDetector.h" #include "Modules/VisualCortex/BallDetector/MultiPassBallDetector.h" #include "Modules/VisualCortex/IntegralImageProvider.h" #include "Modules/VisualCortex/ObstacleDetector/NoGreenObstacleDetector.h" #include "Modules/SelfAwareness/FakeCameraMatrixFinder/FakeCameraMatrixFinder.h" #include "Modules/VisualCortex/FakeBallDetector/FakeBallDetector.h" #include "Modules/Perception/VirtualVisionProcessor/VirtualVisionProcessor.h" #include "Modules/Perception/PerceptionsVisualizer/PerceptionsVisualizer.h" #include "Modules/Perception/WhistleDetector/WhistleDetectorV1.h" #include "Modules/Perception/WhistleDetector/WhistleDetectorV2.h" #include "Modules/VisualCortex/LineDetector/RansacLineDetector.h" #include "Modules/VisualCortex/LineDetector/RansacLineDetectorOnGraphs.h" #include "Modules/VisualCortex/LineDetector/LineAugmenter.h" #include "Modules/Modeling/CompassProvider/CompassProvider.h" // modeling #include "Modules/Modeling/BodyStateProvider/BodyStateProvider.h" #include "Modules/Modeling/FieldCompass/FieldCompass.h" #include "Modules/Perception/UltrasonicObstacleDetector/UltraSoundObstacleDetector.h" #include "Modules/Perception/UltrasonicObstacleDetector/UltrasonicObstacleDetector2020.h" #include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiveEmulator.h" #include "Modules/Modeling/TeamMessageStatistics/TeamMessageStatisticsModule.h" #include "Modules/Modeling/TeamMessageStatistics/TeamMessagePlayersStateModule.h" #include "Modules/Modeling/SoccerStrategyProvider/SoccerStrategyProvider.h" #include "Modules/Modeling/PotentialFieldProvider/PotentialFieldProvider.h" #include "Modules/Modeling/SelfLocator/GPS_SelfLocator/GPS_SelfLocator.h" #include "Modules/Modeling/SelfLocator/MonteCarloSelfLocator/MonteCarloSelfLocator.h" #include "Modules/Modeling/SelfLocator/OdometrySelfLocator/OdometrySelfLocator.h" #include "Modules/Modeling/GoalModel/DummyActiveGoalLocator/DummyActiveGoalLocator.h" #include "Modules/Modeling/GoalModel/WholeGoalLocator/WholeGoalLocator.h" // role decisions #include "Modules/Modeling/RoleDecision/RolesProvider.h" #include "Modules/Modeling/RoleDecision/Dynamic/RoleDecisionDynamic.h" #include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionStatic.h" #include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionForce.h" #include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionPotentialField.h" #include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionFormation.h" #include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionDynamicGoalie.h" #include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentStatic.h" #include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentDistance.h" // the old striker decision (dynamic) #include "Modules/Modeling/RoleDecision/Dynamic/SimpleRoleDecision.h" #include "Modules/Modeling/RoleDecision/Dynamic/StableRoleDecision.h" #include "Modules/Modeling/RoleDecision/Dynamic/CleanRoleDecision.h" #include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorMedian.h" #include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorCanopyCluster.h" #include "Modules/Modeling/BallLocator/MultiKalmanBallLocator/MultiKalmanBallLocator.h" #include "Modules/Modeling/StaticDebugModelProvider/StaticDebugModelProvider.h" #include "Modules/Modeling/ObstacleLocator/MultiUnifiedObstacleLocator.h" #include "Modules/Modeling/Simulation/Simulation.h" #include "Modules/Modeling/Simulation/KickDirectionSimulator.h" #include "Modules/Modeling/SelfLocator/SituationPriorProvider/SituationPriorProvider.h" // behavior #include "Modules/Behavior/BasicTestBehavior/BasicTestBehavior.h" #include "Modules/Behavior/XABSLBehaviorControl/XABSLBehaviorControl.h" #include "Modules/Behavior/PathPlanner/PathPlanner2018.h" using namespace std; Cognition::Cognition() : ModuleManagerWithDebug("") { } Cognition::~Cognition() { } #define REGISTER_MODULE(module) \ std::cout << "[Cognition] Register " << #module << std::endl;\ registerModule<module>(std::string(#module)) void Cognition::init(naoth::ProcessInterface& platformInterface, const naoth::PlatformBase& platform) { std::cout << "[Cognition] Cognition register start" << std::endl; // register input module ModuleCreator<Sensor>* sensor = registerModule<Sensor>(std::string("Sensor"), true); sensor->getModuleT()->init(platformInterface, platform); /* * to register a module use * REGISTER_MODULE(ModuleClassName); * * Remark: to enable the module don't forget * to set the value in modules.cfg */ // -- BEGIN REGISTER MODULES -- // infrastructure REGISTER_MODULE(ButtonEventMonitor); REGISTER_MODULE(WifiModeSetter); REGISTER_MODULE(TeamCommReceiver); REGISTER_MODULE(SimpleNetworkTimeProtocol); REGISTER_MODULE(GameController); REGISTER_MODULE(BatteryAlert); REGISTER_MODULE(LEDSetter); REGISTER_MODULE(UltraSoundControl); REGISTER_MODULE(CameraDebug); REGISTER_MODULE(CameraInfoSetter); REGISTER_MODULE(AdaptiveAutoExposure); REGISTER_MODULE(WhistleDetectorV1); REGISTER_MODULE(WhistleDetectorV2); // perception REGISTER_MODULE(CameraMatrixFinder); REGISTER_MODULE(KinematicChainProvider); REGISTER_MODULE(ArtificialHorizonCalculator); REGISTER_MODULE(BodyContourProvider); REGISTER_MODULE(HistogramProvider); REGISTER_MODULE(IntegralImageProvider); REGISTER_MODULE(FieldColorClassifier); REGISTER_MODULE(IntegralFieldDetector); REGISTER_MODULE(ScanGridProvider); REGISTER_MODULE(ScanGridEdgelDetector); REGISTER_MODULE(ScanLineEdgelDetector); REGISTER_MODULE(FieldDetector); REGISTER_MODULE(LineGraphProvider); REGISTER_MODULE(GoalFeatureDetector); REGISTER_MODULE(GoalFeatureDetectorV2); REGISTER_MODULE(GoalDetector); REGISTER_MODULE(GoalDetectorV2); REGISTER_MODULE(GoalCrossBarDetector); REGISTER_MODULE(NoGreenObstacleDetector); REGISTER_MODULE(RedBallDetector); REGISTER_MODULE(CNNBallDetector); REGISTER_MODULE(MultiPassBallDetector); REGISTER_MODULE(FakeCameraMatrixFinder); REGISTER_MODULE(FakeBallDetector); REGISTER_MODULE(VirtualVisionProcessor); REGISTER_MODULE(PerceptionsVisualizer); REGISTER_MODULE(RansacLineDetector); REGISTER_MODULE(RansacLineDetectorOnGraphs); REGISTER_MODULE(LineAugmenter); REGISTER_MODULE(CompassProvider); // modeling REGISTER_MODULE(BodyStateProvider); REGISTER_MODULE(FieldCompass); REGISTER_MODULE(UltraSoundObstacleDetector); REGISTER_MODULE(UltrasonicDetector2020); REGISTER_MODULE(TeamCommReceiveEmulator); REGISTER_MODULE(TeamMessageStatisticsModule); REGISTER_MODULE(TeamMessagePlayersStateModule); REGISTER_MODULE(SoccerStrategyProvider); REGISTER_MODULE(PotentialFieldProvider); REGISTER_MODULE(SituationPriorProvider); REGISTER_MODULE(GPS_SelfLocator); REGISTER_MODULE(MonteCarloSelfLocator); REGISTER_MODULE(OdometrySelfLocator); REGISTER_MODULE(WholeGoalLocator); REGISTER_MODULE(DummyActiveGoalLocator); REGISTER_MODULE(MultiKalmanBallLocator); REGISTER_MODULE(TeamBallLocatorMedian); REGISTER_MODULE(TeamBallLocatorCanopyCluster); REGISTER_MODULE(MultiUnifiedObstacleLocator); /* * BEGIN ROLE DECISIONS */ REGISTER_MODULE(RolesProvider); // first set the position of the roles REGISTER_MODULE(RoleDecisionPositionStatic); REGISTER_MODULE(RoleDecisionPositionForce); REGISTER_MODULE(RoleDecisionPositionPotentialField); REGISTER_MODULE(RoleDecisionPositionFormation); REGISTER_MODULE(RoleDecisionPositionDynamicGoalie); // then decide which player should have which role REGISTER_MODULE(RoleDecisionAssignmentStatic); REGISTER_MODULE(RoleDecisionAssignmentDistance); // finally, determine the dynamic role (striker, supporter, ...) REGISTER_MODULE(RoleDecisionDynamic); // old striker decisions REGISTER_MODULE(SimpleRoleDecision); REGISTER_MODULE(StableRoleDecision); REGISTER_MODULE(CleanRoleDecision); /* * END ROLE DECISIONS */ REGISTER_MODULE(KickDirectionSimulator); REGISTER_MODULE(Simulation); REGISTER_MODULE(StaticDebugModelProvider); // behavior REGISTER_MODULE(BasicTestBehavior); REGISTER_MODULE(XABSLBehaviorControl); REGISTER_MODULE(PathPlanner2018); REGISTER_MODULE(CameraMatrixCorrectorV3); REGISTER_MODULE(TeamCommSender); // debug REGISTER_MODULE(GameLogger); REGISTER_MODULE(Debug); REGISTER_MODULE(FrameRateCheck); REGISTER_MODULE(DebugExecutor); // -- END REGISTER MODULES -- // register output module ModuleCreator<Actuator>* actuator = registerModule<Actuator>(std::string("Actuator"), true); actuator->getModuleT()->init(platformInterface, platform); // use the configuration in order to set whether a module is activated or not const naoth::Configuration& config = Platform::getInstance().theConfiguration; list<string>::const_iterator name = getExecutionList().begin(); for(;name != getExecutionList().end(); ++name) { bool active = false; if(config.hasKey("modules", *name)) { active = config.getBool("modules", *name); } if(active) { std::cout << "[Cognition] activating module " << *name << std::endl; } setModuleEnabled(*name, active); }//end for // auto-generate the execution list //calculateExecutionList(); std::cout << "[Cognition] register end" << std::endl; stopwatch.start(); }//end init void Cognition::call() { // BEGIN cognition frame rate measuring stopwatch.stop(); stopwatch.start(); PLOT("Cognition.Cycle", stopwatch.lastValue); // END cognition frame rate measuring STOPWATCH_START("Cognition.Execute"); // execute all modules list<AbstractModuleCreator*>::const_iterator iter; for (iter = getModuleExecutionList().begin(); iter != getModuleExecutionList().end(); ++iter) { AbstractModuleCreator* module = *iter; if (module != NULL && module->isEnabled()) { std::string name(module->getModule()->getName()); GT_TRACE("executing " << name); module->execute(); } } STOPWATCH_STOP("Cognition.Execute"); // HACK: reset all the debug stuff before executing the modules STOPWATCH_START("Cognition.Debug.Init"); getDebugDrawings().reset(); getDebugImageDrawings().reset(); getDebugImageDrawingsTop().reset(); getDebugDrawings3D().reset(); STOPWATCH_STOP("Cognition.Debug.Init"); }//end call <|endoftext|>
<commit_before>#include "pch.h" #include "rdo_resources.h" #include <rdortp.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif namespace rdoMBuilder { // -------------------------------------------------------------------- // ---------- // -------------------------------------------------------------------- RDOResType::RDOResType( const RDOResType& obj ) { operator=( obj ); } RDOResType::Param::Param( const RDOResType::Param& obj ) { operator=( obj ); } RDOResource::RDOResource( const RDOResource& obj ) { operator=( obj ); } void RDOResType::operator= (const RDOResType& obj ) { m_name = obj.m_name; m_exist = obj.m_exist; m_type = obj.m_type; m_id = obj.m_id; m_params = obj.m_params; } void RDOResType::Param::operator= (const RDOResType::Param& obj ) { m_name = obj.m_name; m_exist = obj.m_exist; m_type = obj.m_type; m_id = obj.m_id; m_min = obj.m_min; m_max = obj.m_max; m_default = obj.m_default; } void RDOResource::operator= (const RDOResource& obj ) { m_name = obj.m_name; m_exist = obj.m_exist; m_rtp = obj.m_rtp; m_id = obj.m_id; m_params.clear(); Params::const_iterator it = obj.m_params.begin(); while ( it != obj.m_params.end() ) { m_params[ it->first ] = it->second; it++; } } // -------------------------------------------------------------------- // ---------- RDOResType // -------------------------------------------------------------------- // ---- // ---- // -------------------------------------------------------------------- RDOResType::RDOResType( const rdoParse::RDORTPResType& rtp ): m_name( rtp.name() ), m_type( rtp.isPermanent() ? rt_permanent : rt_temporary ), m_exist( true ), m_id( rtp.getNumber() ) { std::vector< const rdoParse::RDORTPParam* >::const_iterator param_it = rtp.getParams().begin(); while ( param_it != rtp.getParams().end() ) { Param param( **param_it ); param.m_id = m_params.size(); m_params.append( param ); param_it++; } } RDOResType::Param::Param( const rdoParse::RDORTPParam& param ): m_name( param.name() ), m_type( &param.getType()->type().type() ), m_exist( true ), m_id( -1 ) { switch ( typeID() ) { case rdoRuntime::RDOType::t_int: { const rdoParse::RDORTPIntParamType* param_type = static_cast<const rdoParse::RDORTPIntParamType*>(param.getType()); if ( param_type->getDiap().isExist() ) { m_min = param_type->getDiap().getMin(); m_max = param_type->getDiap().getMax(); } break; } case rdoRuntime::RDOType::t_real: { const rdoParse::RDORTPRealParamType* param_type = static_cast<const rdoParse::RDORTPRealParamType*>(param.getType()); if ( param_type->getDiap().isExist() ) { m_min = param_type->getDiap().getMin(); m_max = param_type->getDiap().getMax(); } break; } } if ( param.getType()->getDV().isExist() ) { m_default = param.getType()->getDefaultValue( param.getType()->getDV().value() ); } } // -------------------------------------------------------------------- // ---- ** // -------------------------------------------------------------------- RDOResType::RDOResType( const std::string& name, Type type ): m_name( name ), m_type( type ), m_exist( false ), m_id( -1 ) { } bool RDOResType::ParamList::append( Param& param ) { if ( std::find_if(begin(), end(), rdoParse::compareNameRef<Param>(param.name())) == end() ) { m_list.push_back( param ); return true; } else { return false; } } RDOResType::Param::Param( const std::string& name, const rdoRuntime::RDOType* type, const rdoRuntime::RDOValue& def ): m_name( name ), m_type( type ), m_default( def ), m_exist( true ), m_id( -1 ) { if (type->id() == rdoRuntime::RDOType::t_enum && def.typeID() == rdoRuntime::RDOType::t_string) { m_default = rdoRuntime::RDOValue(getEnum(), def.getAsString()); } } RDOResType::Param::Param( const std::string& name, const rdoRuntime::RDOValue& def ): m_name( name ), m_type( &def.type() ), m_default( def ), m_exist( true ), m_id( -1 ) { } RDOResType::Param::Param( const std::string& name, const rdoRuntime::RDOValue& min, const rdoRuntime::RDOValue& max, const rdoRuntime::RDOValue& def ): m_name( name ), m_type( &rdoRuntime::RDOType::getTypeByID(min.typeID()) ), m_min( min ), m_max( max ), m_default( def ), m_exist( true ), m_id( -1 ) { } void RDOResType::Param::setDiap( const rdoRuntime::RDOValue& min, const rdoRuntime::RDOValue& max ) { m_min = min; m_max = max; } void RDOResType::Param::setDefault( const rdoRuntime::RDOValue& def ) { m_default = def; } bool RDOResType::Param::operator== (const Param& param ) const { return true; } // -------------------------------------------------------------------- // ---------- RDOResTypeList // -------------------------------------------------------------------- // ---- , // -------------------------------------------------------------------- RDOResTypeList::RDOResTypeList( rdoParse::RDOParser* parser ): RDOList<RDOResType>( parser ) { std::vector< rdoParse::RDORTPResType* >::const_iterator rtp_it = m_parser->getRTPResTypes().begin(); while ( rtp_it != m_parser->getRTPResTypes().end() ) { RDOResType rtp( **rtp_it ); m_list.push_back( rtp ); rtp_it++; } } // -------------------------------------------------------------------- // ---- ** // -------------------------------------------------------------------- bool RDOResTypeList::append( RDOResType& rtp ) { if ( std::find_if(begin(), end(), rdoParse::compareNameRef<RDOResType>(rtp.name())) == end() ) { rdoParse::RDORTPResType* pRTP = new rdoParse::RDORTPResType( m_parser, rtp.name(), rtp.isPermanent() ); RDOResType::ParamList::List::const_iterator param = rtp.m_params.begin(); while ( param != rtp.m_params.end() ) { rdoParse::RDORTPParamType* pParamType = NULL; switch ( param->typeID() ) { case rdoRuntime::RDOType::t_int: { rdoParse::RDORTPIntDiap* pDiap; if ( param->hasDiap() ) { pDiap = new rdoParse::RDORTPIntDiap( m_parser, param->getMin().getInt(), param->getMax().getInt() ); } else { pDiap = new rdoParse::RDORTPIntDiap( m_parser ); } rdoParse::RDORTPDefVal* pDef; if ( param->hasDefault() ) { pDef = new rdoParse::RDORTPDefVal( m_parser, param->getDefault() ); } else { pDef = new rdoParse::RDORTPDefVal( m_parser ); } pParamType = new rdoParse::RDORTPIntParamType( m_parser, pDiap, pDef ); break; } case rdoRuntime::RDOType::t_real: { rdoParse::RDORTPRealDiap* pDiap; if ( param->hasDiap() ) { pDiap = new rdoParse::RDORTPRealDiap( m_parser, param->getMin().getDouble(), param->getMax().getDouble() ); } else { pDiap = new rdoParse::RDORTPRealDiap( m_parser ); } rdoParse::RDORTPDefVal* pDef; if ( param->hasDefault() ) { pDef = new rdoParse::RDORTPDefVal( m_parser, param->getDefault() ); } else { pDef = new rdoParse::RDORTPDefVal( m_parser ); } pParamType = new rdoParse::RDORTPRealParamType( m_parser, pDiap, pDef ); break; } case rdoRuntime::RDOType::t_enum: { rdoParse::RDORTPEnum* pEnum = NULL; rdoRuntime::RDOEnumType::CIterator enum_it = param->getEnum().begin(); while ( enum_it != param->getEnum().end() ) { if ( !pEnum ) { pEnum = new rdoParse::RDORTPEnum( pRTP, rdoParse::RDOValue::getIdentificator(*enum_it) ); } else { pEnum->add( rdoParse::RDOValue::getIdentificator(*enum_it) ); } enum_it++; } rdoParse::RDORTPDefVal* pEnumDefValue; if ( param->hasDefault() ) { pEnumDefValue = new rdoParse::RDORTPDefVal( m_parser, param->getDefault() ); } else { pEnumDefValue = new rdoParse::RDORTPDefVal( m_parser ); } pParamType = new rdoParse::RDORTPEnumParamType( pRTP, pEnum, pEnumDefValue, rtp.name() ); break; } default: { delete pRTP; return false; } } pRTP->addParam( new rdoParse::RDORTPParam( pRTP, param->name(), pParamType ) ); param++; } rtp.m_exist = true; rtp.m_id = pRTP->getNumber(); m_list.push_back( rtp ); return true; } else { return false; } } // -------------------------------------------------------------------- // ---------- RDOResource // -------------------------------------------------------------------- // ---- // ---- // -------------------------------------------------------------------- RDOResource::RDOResource( const rdoParse::RDORSSResource& rss ) : m_name (rss.name() ) , m_rtp (*rss.getType()) , m_exist(true ) , m_id (rss.getID() ) { if ( m_rtp.m_params.size() == rss.params().size() ) { unsigned int index = 0; RDOResType::ParamList::List::const_iterator param_it = m_rtp.m_params.begin(); while ( param_it != m_rtp.m_params.end() ) { // const rdoRuntime::RDOValue& value = rss.params()[index]; // m_params[param_it->name()] = rdoParse::RDOValue(value, rdoParse::RDOType(value.type())); m_params[param_it->name()] = rss.params()[index]; index++; param_it++; } } } RDOResource::Params::const_iterator RDOResource::operator[] ( const std::string& param ) const { return m_params.find(param); } RDOResource::Params::mapped_type& RDOResource::operator[] ( const std::string& param ) { RDOResource::Params::iterator param_it = m_params.find(param); if ( param_it != m_params.end() ) { return param_it->second; } else { static Params::mapped_type tmpValue; return tmpValue; } } bool RDOResource::fillParserResourceParams(rdoParse::RDORSSResource* pRSS) const { RDOResType::ParamList::List::const_iterator param_it = getType().m_params.begin(); while ( param_it != getType().m_params.end() ) { RDOResource::Params::const_iterator value_it = operator[](param_it->name()); if ( value_it == end() ) { return false; } pRSS->addParam( value_it->second ); param_it++; } return true; } // -------------------------------------------------------------------- // ---- ** // -------------------------------------------------------------------- RDOResource::RDOResource( const RDOResType& rtp, const std::string& name ) : m_name (name ) , m_rtp (rtp ) , m_exist(false ) , m_id (rdoParse::RDORSSResource::UNDEFINED_ID) { RDOResType::ParamList::List::const_iterator param_it = m_rtp.m_params.begin(); while ( param_it != m_rtp.m_params.end() ) { rdoRuntime::RDOValue value( *param_it->type() ); if ( param_it->hasDefault() ) { value = param_it->getDefault(); } else if ( param_it->hasDiap() ) { value = param_it->getMin(); } m_params[param_it->name()] = value; param_it++; } } // -------------------------------------------------------------------- // ---------- RDOResourceList // -------------------------------------------------------------------- // ---- , // -------------------------------------------------------------------- RDOResourceList::RDOResourceList( rdoParse::RDOParser* parser ): RDOList<RDOResource>( parser ) { std::vector< rdoParse::RDORSSResource* >::const_iterator rss_it = m_parser->getRSSResources().begin(); while ( rss_it != m_parser->getRSSResources().end() ) { RDOResource rss( **rss_it ); m_list.push_back( rss ); rss_it++; } } } // rdoMBuilder <commit_msg>* откат к старой и неправильной логике работы mbuilder'а с enum-данными, чтобы можно было отлаживать RDOProcess<commit_after>#include "pch.h" #include "rdo_resources.h" #include <rdortp.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif namespace rdoMBuilder { // -------------------------------------------------------------------- // ---------- // -------------------------------------------------------------------- RDOResType::RDOResType( const RDOResType& obj ) { operator=( obj ); } RDOResType::Param::Param( const RDOResType::Param& obj ) { operator=( obj ); } RDOResource::RDOResource( const RDOResource& obj ) { operator=( obj ); } void RDOResType::operator= (const RDOResType& obj ) { m_name = obj.m_name; m_exist = obj.m_exist; m_type = obj.m_type; m_id = obj.m_id; m_params = obj.m_params; } void RDOResType::Param::operator= (const RDOResType::Param& obj ) { m_name = obj.m_name; m_exist = obj.m_exist; m_type = obj.m_type; m_id = obj.m_id; m_min = obj.m_min; m_max = obj.m_max; m_default = obj.m_default; } void RDOResource::operator= (const RDOResource& obj ) { m_name = obj.m_name; m_exist = obj.m_exist; m_rtp = obj.m_rtp; m_id = obj.m_id; m_params.clear(); Params::const_iterator it = obj.m_params.begin(); while ( it != obj.m_params.end() ) { m_params[ it->first ] = it->second; it++; } } // -------------------------------------------------------------------- // ---------- RDOResType // -------------------------------------------------------------------- // ---- // ---- // -------------------------------------------------------------------- RDOResType::RDOResType( const rdoParse::RDORTPResType& rtp ): m_name( rtp.name() ), m_type( rtp.isPermanent() ? rt_permanent : rt_temporary ), m_exist( true ), m_id( rtp.getNumber() ) { std::vector< const rdoParse::RDORTPParam* >::const_iterator param_it = rtp.getParams().begin(); while ( param_it != rtp.getParams().end() ) { Param param( **param_it ); param.m_id = m_params.size(); m_params.append( param ); param_it++; } } RDOResType::Param::Param( const rdoParse::RDORTPParam& param ): m_name( param.name() ), m_type( &param.getType()->type().type() ), m_exist( true ), m_id( -1 ) { switch ( typeID() ) { case rdoRuntime::RDOType::t_int: { const rdoParse::RDORTPIntParamType* param_type = static_cast<const rdoParse::RDORTPIntParamType*>(param.getType()); if ( param_type->getDiap().isExist() ) { m_min = param_type->getDiap().getMin(); m_max = param_type->getDiap().getMax(); } break; } case rdoRuntime::RDOType::t_real: { const rdoParse::RDORTPRealParamType* param_type = static_cast<const rdoParse::RDORTPRealParamType*>(param.getType()); if ( param_type->getDiap().isExist() ) { m_min = param_type->getDiap().getMin(); m_max = param_type->getDiap().getMax(); } break; } } if ( param.getType()->getDV().isExist() ) { m_default = param.getType()->getDefaultValue( param.getType()->getDV().value() ); } } // -------------------------------------------------------------------- // ---- ** // -------------------------------------------------------------------- RDOResType::RDOResType( const std::string& name, Type type ): m_name( name ), m_type( type ), m_exist( false ), m_id( -1 ) { } bool RDOResType::ParamList::append( Param& param ) { if ( std::find_if(begin(), end(), rdoParse::compareNameRef<Param>(param.name())) == end() ) { m_list.push_back( param ); return true; } else { return false; } } RDOResType::Param::Param( const std::string& name, const rdoRuntime::RDOType* type, const rdoRuntime::RDOValue& def ): m_name( name ), m_type( type ), m_default( def ), m_exist( true ), m_id( -1 ) { if (type->id() == rdoRuntime::RDOType::t_enum && def.typeID() == rdoRuntime::RDOType::t_string) { // m_default = rdoRuntime::RDOValue(getEnum(), def.getAsString()); } } RDOResType::Param::Param( const std::string& name, const rdoRuntime::RDOValue& def ): m_name( name ), m_type( &def.type() ), m_default( def ), m_exist( true ), m_id( -1 ) { } RDOResType::Param::Param( const std::string& name, const rdoRuntime::RDOValue& min, const rdoRuntime::RDOValue& max, const rdoRuntime::RDOValue& def ): m_name( name ), m_type( &rdoRuntime::RDOType::getTypeByID(min.typeID()) ), m_min( min ), m_max( max ), m_default( def ), m_exist( true ), m_id( -1 ) { } void RDOResType::Param::setDiap( const rdoRuntime::RDOValue& min, const rdoRuntime::RDOValue& max ) { m_min = min; m_max = max; } void RDOResType::Param::setDefault( const rdoRuntime::RDOValue& def ) { m_default = def; } bool RDOResType::Param::operator== (const Param& param ) const { return true; } // -------------------------------------------------------------------- // ---------- RDOResTypeList // -------------------------------------------------------------------- // ---- , // -------------------------------------------------------------------- RDOResTypeList::RDOResTypeList( rdoParse::RDOParser* parser ): RDOList<RDOResType>( parser ) { std::vector< rdoParse::RDORTPResType* >::const_iterator rtp_it = m_parser->getRTPResTypes().begin(); while ( rtp_it != m_parser->getRTPResTypes().end() ) { RDOResType rtp( **rtp_it ); m_list.push_back( rtp ); rtp_it++; } } // -------------------------------------------------------------------- // ---- ** // -------------------------------------------------------------------- bool RDOResTypeList::append( RDOResType& rtp ) { if ( std::find_if(begin(), end(), rdoParse::compareNameRef<RDOResType>(rtp.name())) == end() ) { rdoParse::RDORTPResType* pRTP = new rdoParse::RDORTPResType( m_parser, rtp.name(), rtp.isPermanent() ); RDOResType::ParamList::List::const_iterator param = rtp.m_params.begin(); while ( param != rtp.m_params.end() ) { rdoParse::RDORTPParamType* pParamType = NULL; switch ( param->typeID() ) { case rdoRuntime::RDOType::t_int: { rdoParse::RDORTPIntDiap* pDiap; if ( param->hasDiap() ) { pDiap = new rdoParse::RDORTPIntDiap( m_parser, param->getMin().getInt(), param->getMax().getInt() ); } else { pDiap = new rdoParse::RDORTPIntDiap( m_parser ); } rdoParse::RDORTPDefVal* pDef; if ( param->hasDefault() ) { pDef = new rdoParse::RDORTPDefVal( m_parser, param->getDefault() ); } else { pDef = new rdoParse::RDORTPDefVal( m_parser ); } pParamType = new rdoParse::RDORTPIntParamType( m_parser, pDiap, pDef ); break; } case rdoRuntime::RDOType::t_real: { rdoParse::RDORTPRealDiap* pDiap; if ( param->hasDiap() ) { pDiap = new rdoParse::RDORTPRealDiap( m_parser, param->getMin().getDouble(), param->getMax().getDouble() ); } else { pDiap = new rdoParse::RDORTPRealDiap( m_parser ); } rdoParse::RDORTPDefVal* pDef; if ( param->hasDefault() ) { pDef = new rdoParse::RDORTPDefVal( m_parser, param->getDefault() ); } else { pDef = new rdoParse::RDORTPDefVal( m_parser ); } pParamType = new rdoParse::RDORTPRealParamType( m_parser, pDiap, pDef ); break; } case rdoRuntime::RDOType::t_enum: { rdoParse::RDORTPEnum* pEnum = NULL; rdoRuntime::RDOEnumType::CIterator enum_it = param->getEnum().begin(); while ( enum_it != param->getEnum().end() ) { if ( !pEnum ) { pEnum = new rdoParse::RDORTPEnum( pRTP, rdoParse::RDOValue::getIdentificator(*enum_it) ); } else { pEnum->add( rdoParse::RDOValue::getIdentificator(*enum_it) ); } enum_it++; } rdoParse::RDORTPDefVal* pEnumDefValue; if ( param->hasDefault() ) { pEnumDefValue = new rdoParse::RDORTPDefVal( m_parser, param->getDefault() ); } else { pEnumDefValue = new rdoParse::RDORTPDefVal( m_parser ); } pParamType = new rdoParse::RDORTPEnumParamType( pRTP, pEnum, pEnumDefValue, rtp.name() ); break; } default: { delete pRTP; return false; } } pRTP->addParam( new rdoParse::RDORTPParam( pRTP, param->name(), pParamType ) ); param++; } rtp.m_exist = true; rtp.m_id = pRTP->getNumber(); m_list.push_back( rtp ); return true; } else { return false; } } // -------------------------------------------------------------------- // ---------- RDOResource // -------------------------------------------------------------------- // ---- // ---- // -------------------------------------------------------------------- RDOResource::RDOResource( const rdoParse::RDORSSResource& rss ) : m_name (rss.name() ) , m_rtp (*rss.getType()) , m_exist(true ) , m_id (rss.getID() ) { if ( m_rtp.m_params.size() == rss.params().size() ) { unsigned int index = 0; RDOResType::ParamList::List::const_iterator param_it = m_rtp.m_params.begin(); while ( param_it != m_rtp.m_params.end() ) { // const rdoRuntime::RDOValue& value = rss.params()[index]; // m_params[param_it->name()] = rdoParse::RDOValue(value, rdoParse::RDOType(value.type())); m_params[param_it->name()] = rss.params()[index]; index++; param_it++; } } } RDOResource::Params::const_iterator RDOResource::operator[] ( const std::string& param ) const { return m_params.find(param); } RDOResource::Params::mapped_type& RDOResource::operator[] ( const std::string& param ) { RDOResource::Params::iterator param_it = m_params.find(param); if ( param_it != m_params.end() ) { return param_it->second; } else { static Params::mapped_type tmpValue; return tmpValue; } } bool RDOResource::fillParserResourceParams(rdoParse::RDORSSResource* pRSS) const { RDOResType::ParamList::List::const_iterator param_it = getType().m_params.begin(); while ( param_it != getType().m_params.end() ) { RDOResource::Params::const_iterator value_it = operator[](param_it->name()); if ( value_it == end() ) { return false; } pRSS->addParam( value_it->second ); param_it++; } return true; } // -------------------------------------------------------------------- // ---- ** // -------------------------------------------------------------------- RDOResource::RDOResource( const RDOResType& rtp, const std::string& name ) : m_name (name ) , m_rtp (rtp ) , m_exist(false ) , m_id (rdoParse::RDORSSResource::UNDEFINED_ID) { RDOResType::ParamList::List::const_iterator param_it = m_rtp.m_params.begin(); while ( param_it != m_rtp.m_params.end() ) { rdoRuntime::RDOValue value( *param_it->type() ); if ( param_it->hasDefault() ) { value = param_it->getDefault(); } else if ( param_it->hasDiap() ) { value = param_it->getMin(); } m_params[param_it->name()] = value; param_it++; } } // -------------------------------------------------------------------- // ---------- RDOResourceList // -------------------------------------------------------------------- // ---- , // -------------------------------------------------------------------- RDOResourceList::RDOResourceList( rdoParse::RDOParser* parser ): RDOList<RDOResource>( parser ) { std::vector< rdoParse::RDORSSResource* >::const_iterator rss_it = m_parser->getRSSResources().begin(); while ( rss_it != m_parser->getRSSResources().end() ) { RDOResource rss( **rss_it ); m_list.push_back( rss ); rss_it++; } } } // rdoMBuilder <|endoftext|>
<commit_before>//Copyright (c) 2013 Christopher Johnstone(meson800) //The MIT License - See ../../../LICENSE for more info #include "MacroExpander.h" void MacroExpander::expandString(std::string& string) { //loop while we still have macros (defined by angle brackets) while (string.find(">") != std::string::npos) { int firstPos, secondPos, length; firstPos = string.find_first_of("<"); secondPos = string.find_first_of(">"); length = secondPos - firstPos; //check that we found them if (firstPos != -1 && secondPos != -1) { string.replace(firstPos, length, macroToText(string.substr(firstPos, length))); } } } std::string MacroExpander::macroToText(std::string macro) { VESSEL * focusVessel = oapiGetFocusInterface(); //format is <name option i decimalPlaces> double value; //get macro name, id, and possibly int char name[256]; int option; int decimalPlaces; int numArguments = sscanf("<%255s %i i %i", name, &option, &decimalPlaces); std::string type_name = name; //switch different macros if (type_name.compare("fuel_percent") == 0) { PROPELLANT_HANDLE fuel_handle = focusVessel->GetPropellantHandleByIndex(option); value = oapiGetPropellantMass(fuel_handle) / oapiGetPropellantMaxMass(fuel_handle); } else if (type_name.compare("fuel_mass") == 0) { if (option == -1) { value = focusVessel->GetTotalPropellantMass(); } else { PROPELLANT_HANDLE fuel_handle = focusVessel->GetPropellantHandleByIndex(option); value = oapiGetPropellantMass(fuel_handle); } } std::ostringstream toStringConverter; if (numArguments >= 3) { //convert value to integer toStringConverter << doubleToDecimalInt(value, decimalPlaces); } else { //just return the double toStringConverter << value; } return toStringConverter.str(); } int MacroExpander::doubleToDecimalInt(double value, int decimalPlaces) { return (int)(value * (10 * decimalPlaces)); }<commit_msg>Fixed bug where MacroExpander would not correctly expand<commit_after>//Copyright (c) 2013 Christopher Johnstone(meson800) //The MIT License - See ../../../LICENSE for more info #include "MacroExpander.h" void MacroExpander::expandString(std::string& string) { //loop while we still have macros (defined by angle brackets) while (string.find(">") != std::string::npos) { int firstPos, secondPos, length; firstPos = string.find_first_of("<"); secondPos = string.find_first_of(">"); length = secondPos - firstPos + 1; //check that we found them if (firstPos != -1 && secondPos != -1) { string.replace(firstPos, length, macroToText(string.substr(firstPos, length))); } } } std::string MacroExpander::macroToText(std::string macro) { VESSEL * focusVessel = oapiGetFocusInterface(); //format is <name option i decimalPlaces> double value; //get macro name, id, and possibly int char name[256]; int option; int decimalPlaces; int numArguments = sscanf(macro.c_str(),"<%255s %i i %i>", name, &option, &decimalPlaces); std::string type_name = name; //switch different macros if (type_name.compare("fuel_percent") == 0) { PROPELLANT_HANDLE fuel_handle = focusVessel->GetPropellantHandleByIndex(option); value = oapiGetPropellantMass(fuel_handle) / oapiGetPropellantMaxMass(fuel_handle); } else if (type_name.compare("fuel_mass") == 0) { if (option == -1) { value = focusVessel->GetTotalPropellantMass(); } else { PROPELLANT_HANDLE fuel_handle = focusVessel->GetPropellantHandleByIndex(option); value = oapiGetPropellantMass(fuel_handle); } } std::ostringstream toStringConverter; if (numArguments >= 3) { //convert value to integer toStringConverter << doubleToDecimalInt(value, decimalPlaces); } else { //just return the double toStringConverter << value; } return toStringConverter.str(); } int MacroExpander::doubleToDecimalInt(double value, int decimalPlaces) { return (int)(value * pow((double)10,(double)decimalPlaces)); }<|endoftext|>
<commit_before>// // Class AliRsnCutPrimaryVertex // // This cut implementation checks the quality of event primary vertex. // It currently works only with ESD events (not AOD). // // authors: Martin Vala (martin.vala@cern.ch) // Alberto Pulvirenti (alberto.pulvirenti@ct.infn.it) // #include "AliRsnCutPrimaryVertex.h" ClassImp(AliRsnCutPrimaryVertex) //_________________________________________________________________________________________________ AliRsnCutPrimaryVertex::AliRsnCutPrimaryVertex() : AliRsnCut(AliRsnCut::kEvent), fAcceptTPC(kFALSE) { // // Default constructor. // } //_________________________________________________________________________________________________ AliRsnCutPrimaryVertex::AliRsnCutPrimaryVertex (const char *name, Double_t maxVz, Int_t nContributors, Bool_t acceptTPC) : AliRsnCut(name, AliRsnCut::kEvent, 0, nContributors - 1), fAcceptTPC(acceptTPC) { // // Main constructor. // Defines the cut range between 0 and // the minimum required number of contributors. // The cut will be passed when if the event has a // primary vertex with number of contributors outside this interval. // --- // If the 'acceptTPC' argument is true, events with TPC // primary vertex will be checked, otherwise they will be // rejected by default. // --- // Since the range check uses the '>=' and '<=', the high edge // must be decreased by 1 to get the right behaviour, since this is integer. // fMinD = 0.0; fMaxD = maxVz + 1E-6; } //_________________________________________________________________________________________________ Bool_t AliRsnCutPrimaryVertex::IsSelected(TObject *obj1, TObject* /*obj2*/) { // // Cut checker // static Int_t evNum = 0; evNum++; // retrieve ESD event AliRsnEvent *rsn = dynamic_cast<AliRsnEvent*>(obj1); if (!rsn) return kFALSE; AliESDEvent *esd = dynamic_cast<AliESDEvent*>(rsn->GetRef()); AliAODEvent *aod = dynamic_cast<AliAODEvent*>(rsn->GetRef()); if (esd) { // get the best primary vertex: // first try the one with tracks const AliESDVertex *vTrk = esd->GetPrimaryVertexTracks(); const AliESDVertex *vSPD = esd->GetPrimaryVertexSPD(); const AliESDVertex *vTPC = esd->GetPrimaryVertexTPC(); Int_t ncTrk = -1; Int_t ncSPD = -1; Int_t ncTPC = -1; Double_t vzTrk = 2.0 * fMaxD; Double_t vzSPD = 2.0 * fMaxD; Double_t vzTPC = 2.0 * fMaxD; if (vTrk) vzTrk = TMath::Abs(vTrk->GetZv()); if (vSPD) vzSPD = TMath::Abs(vSPD->GetZv()); if (vTPC) vzTPC = TMath::Abs(vTPC->GetZv()); if (vTrk) ncTrk = (Int_t)vTrk->GetNContributors(); if (vSPD) ncSPD = (Int_t)vSPD->GetNContributors(); if (vTPC) ncTPC = (Int_t)vTPC->GetNContributors(); if(vTrk && ncTrk > 0) { fCutValueI = ncTrk; fCutValueD = vzTrk; } else if (vSPD && ncSPD > 0) { fCutValueI = ncSPD; fCutValueD = vzSPD; } else if (vTPC && fAcceptTPC && ncTPC > 0) { fCutValueI = ncTPC; fCutValueD = vzTPC; } else { fCutValueI = -1; fCutValueD = 2.0 * fMaxD; } } else if (aod) { // lines suggested by Andrea to reject TPC-only events if(!aod->GetPrimaryVertexSPD()) return kFALSE; //PH if(!aod->GetPrimaryVertexSPD()->Status()) return kFALSE; AliAODVertex *prim = (AliAODVertex*)aod->GetPrimaryVertex(); fCutValueI = prim->GetNContributors(); //PH fCutValueD = prim->Zv(); fCutValueD = prim->GetZ(); } else return kFALSE; // output Bool_t result = ((!OkRangeI()) && OkRangeD()); return result; } <commit_msg>Compilation error corrected<commit_after>// // Class AliRsnCutPrimaryVertex // // This cut implementation checks the quality of event primary vertex. // It currently works only with ESD events (not AOD). // // authors: Martin Vala (martin.vala@cern.ch) // Alberto Pulvirenti (alberto.pulvirenti@ct.infn.it) // #include "AliRsnCutPrimaryVertex.h" ClassImp(AliRsnCutPrimaryVertex) //_________________________________________________________________________________________________ AliRsnCutPrimaryVertex::AliRsnCutPrimaryVertex() : AliRsnCut(AliRsnCut::kEvent), fAcceptTPC(kFALSE) { // // Default constructor. // } //_________________________________________________________________________________________________ AliRsnCutPrimaryVertex::AliRsnCutPrimaryVertex (const char *name, Double_t maxVz, Int_t nContributors, Bool_t acceptTPC) : AliRsnCut(name, AliRsnCut::kEvent, 0, nContributors - 1), fAcceptTPC(acceptTPC) { // // Main constructor. // Defines the cut range between 0 and // the minimum required number of contributors. // The cut will be passed when if the event has a // primary vertex with number of contributors outside this interval. // --- // If the 'acceptTPC' argument is true, events with TPC // primary vertex will be checked, otherwise they will be // rejected by default. // --- // Since the range check uses the '>=' and '<=', the high edge // must be decreased by 1 to get the right behaviour, since this is integer. // fMinD = 0.0; fMaxD = maxVz + 1E-6; } //_________________________________________________________________________________________________ Bool_t AliRsnCutPrimaryVertex::IsSelected(TObject *obj1, TObject* /*obj2*/) { // // Cut checker // static Int_t evNum = 0; evNum++; // retrieve ESD event AliRsnEvent *rsn = dynamic_cast<AliRsnEvent*>(obj1); if (!rsn) return kFALSE; AliESDEvent *esd = dynamic_cast<AliESDEvent*>(rsn->GetRef()); AliAODEvent *aod = dynamic_cast<AliAODEvent*>(rsn->GetRef()); if (esd) { // get the best primary vertex: // first try the one with tracks const AliESDVertex *vTrk = esd->GetPrimaryVertexTracks(); const AliESDVertex *vSPD = esd->GetPrimaryVertexSPD(); const AliESDVertex *vTPC = esd->GetPrimaryVertexTPC(); Int_t ncTrk = -1; Int_t ncSPD = -1; Int_t ncTPC = -1; Double_t vzTrk = 2.0 * fMaxD; Double_t vzSPD = 2.0 * fMaxD; Double_t vzTPC = 2.0 * fMaxD; if (vTrk) vzTrk = TMath::Abs(vTrk->GetZv()); if (vSPD) vzSPD = TMath::Abs(vSPD->GetZv()); if (vTPC) vzTPC = TMath::Abs(vTPC->GetZv()); if (vTrk) ncTrk = (Int_t)vTrk->GetNContributors(); if (vSPD) ncSPD = (Int_t)vSPD->GetNContributors(); if (vTPC) ncTPC = (Int_t)vTPC->GetNContributors(); if(vTrk && ncTrk > 0) { fCutValueI = ncTrk; fCutValueD = vzTrk; } else if (vSPD && ncSPD > 0) { fCutValueI = ncSPD; fCutValueD = vzSPD; } else if (vTPC && fAcceptTPC && ncTPC > 0) { fCutValueI = ncTPC; fCutValueD = vzTPC; } else { fCutValueI = -1; fCutValueD = 2.0 * fMaxD; } } else if (aod) { // lines suggested by Andrea to reject TPC-only events if(!aod->GetPrimaryVertexSPD()) return kFALSE; if(aod->GetPrimaryVertexSPD()->GetNContributors() < 1) return kFALSE; AliAODVertex *prim = (AliAODVertex*)aod->GetPrimaryVertex(); fCutValueI = prim->GetNContributors(); fCutValueD = prim->GetZ(); } else return kFALSE; // output Bool_t result = ((!OkRangeI()) && OkRangeD()); return result; } <|endoftext|>
<commit_before>#include "ExecutionEngine.h" #include <chrono> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/ADT/Triple.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/SectionMemoryManager.h> #include <llvm/ExecutionEngine/GenericValue.h> #include <llvm/ExecutionEngine/MCJIT.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/Signals.h> #include <llvm/Support/PrettyStackTrace.h> #include <llvm/Support/Host.h> #pragma GCC diagnostic pop #include "Runtime.h" #include "Memory.h" #include "Stack.h" #include "Type.h" #include "Compiler.h" #include "Cache.h" namespace dev { namespace eth { namespace jit { ReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env) { std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()}; /*if (auto cachedExec = Cache::findExec(key)) { return run(*cachedExec, _data, _env); }*/ auto module = Compiler({}).compile(_code); //module->dump(); return run(std::move(module), _data, _env, _code); } ReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code) { llvm::sys::PrintStackTraceOnErrorSignal(); static const auto program = "EVM JIT"; llvm::PrettyStackTraceProgram X(1, &program); llvm::InitializeNativeTargetAsmPrinter(); llvm::EngineBuilder builder(_module.get()); builder.setEngineKind(llvm::EngineKind::JIT); builder.setUseMCJIT(true); builder.setOptLevel(llvm::CodeGenOpt::None); auto triple = llvm::Triple(llvm::sys::getProcessTriple()); if (triple.getOS() == llvm::Triple::OSType::Win32) triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); // MCJIT does not support COFF format _module->setTargetTriple(triple.str()); ExecBundle exec; exec.engine.reset(builder.create()); if (!exec.engine) return ReturnCode::LLVMConfigError; _module.release(); // Successfully created llvm::ExecutionEngine takes ownership of the module exec.engine->setObjectCache(Cache::getObjectCache()); // TODO: Finalization not needed when llvm::ExecutionEngine::getFunctionAddress used //auto finalizationStartTime = std::chrono::high_resolution_clock::now(); //exec.engine->finalizeObject(); //auto finalizationEndTime = std::chrono::high_resolution_clock::now(); //clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count(); auto executionStartTime = std::chrono::high_resolution_clock::now(); std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()}; //auto& cachedExec = Cache::registerExec(key, std::move(exec)); auto returnCode = run(exec, _data, _env); auto executionEndTime = std::chrono::high_resolution_clock::now(); clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << " ms "; //clog(JIT) << "Max stack size: " << Stack::maxStackSize; clog(JIT) << "\n"; return returnCode; } namespace { ReturnCode runEntryFunc(ExecBundle const& _exec, Runtime* _runtime) { // That function uses long jumps to handle "execeptions". // Do not create any non-POD objects here // TODO: // Getting pointer to function seems to be cachable, // but it looks like getPointerToFunction() method does something special // to allow function to be executed. // That might be related to memory manager. Can we share one? typedef ReturnCode(*EntryFuncPtr)(Runtime*); auto entryFuncPtr = (EntryFuncPtr)_exec.engine->getFunctionAddress("main"); ReturnCode returnCode{}; auto sj = setjmp(_runtime->getJmpBuf()); if (sj == 0) returnCode = entryFuncPtr(_runtime); else returnCode = static_cast<ReturnCode>(sj); return returnCode; } } ReturnCode ExecutionEngine::run(ExecBundle const& _exec, RuntimeData* _data, Env* _env) { Runtime runtime(_data, _env); auto returnCode = runEntryFunc(_exec, &runtime); if (returnCode == ReturnCode::Return) this->returnData = runtime.getReturnData(); return returnCode; } } } } <commit_msg>Execution Engine cleanups (reverted from commit bd85efa299e661228a1ac6283b5fad14e09f88d9)<commit_after>#include "ExecutionEngine.h" #include <chrono> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/ADT/Triple.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/SectionMemoryManager.h> #include <llvm/ExecutionEngine/GenericValue.h> #include <llvm/ExecutionEngine/MCJIT.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/Signals.h> #include <llvm/Support/PrettyStackTrace.h> #include <llvm/Support/Host.h> #pragma GCC diagnostic pop #include "Runtime.h" #include "Memory.h" #include "Stack.h" #include "Type.h" #include "Compiler.h" #include "Cache.h" namespace dev { namespace eth { namespace jit { ReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env) { std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()}; /*if (auto cachedExec = Cache::findExec(key)) { return run(*cachedExec, _data, _env); }*/ auto module = Compiler({}).compile(_code); //module->dump(); return run(std::move(module), _data, _env, _code); } ReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code) { llvm::sys::PrintStackTraceOnErrorSignal(); static const auto program = "EVM JIT"; llvm::PrettyStackTraceProgram X(1, &program); llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); llvm::EngineBuilder builder(_module.get()); builder.setEngineKind(llvm::EngineKind::JIT); builder.setUseMCJIT(true); std::unique_ptr<llvm::SectionMemoryManager> memoryManager(new llvm::SectionMemoryManager); builder.setMCJITMemoryManager(memoryManager.get()); builder.setOptLevel(llvm::CodeGenOpt::None); auto triple = llvm::Triple(llvm::sys::getProcessTriple()); if (triple.getOS() == llvm::Triple::OSType::Win32) triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); // MCJIT does not support COFF format _module->setTargetTriple(triple.str()); ExecBundle exec; exec.engine.reset(builder.create()); if (!exec.engine) return ReturnCode::LLVMConfigError; _module.release(); // Successfully created llvm::ExecutionEngine takes ownership of the module memoryManager.release(); // and memory manager exec.engine->setObjectCache(Cache::getObjectCache()); // TODO: Finalization not needed when llvm::ExecutionEngine::getFunctionAddress used //auto finalizationStartTime = std::chrono::high_resolution_clock::now(); //exec.engine->finalizeObject(); //auto finalizationEndTime = std::chrono::high_resolution_clock::now(); //clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count(); auto executionStartTime = std::chrono::high_resolution_clock::now(); std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()}; //auto& cachedExec = Cache::registerExec(key, std::move(exec)); auto returnCode = run(exec, _data, _env); auto executionEndTime = std::chrono::high_resolution_clock::now(); clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << " ms "; //clog(JIT) << "Max stack size: " << Stack::maxStackSize; clog(JIT) << "\n"; return returnCode; } namespace { ReturnCode runEntryFunc(ExecBundle const& _exec, Runtime* _runtime) { // That function uses long jumps to handle "execeptions". // Do not create any non-POD objects here // TODO: // Getting pointer to function seems to be cachable, // but it looks like getPointerToFunction() method does something special // to allow function to be executed. // That might be related to memory manager. Can we share one? typedef ReturnCode(*EntryFuncPtr)(Runtime*); auto entryFuncPtr = (EntryFuncPtr)_exec.engine->getFunctionAddress("main"); ReturnCode returnCode{}; auto sj = setjmp(_runtime->getJmpBuf()); if (sj == 0) returnCode = entryFuncPtr(_runtime); else returnCode = static_cast<ReturnCode>(sj); return returnCode; } } ReturnCode ExecutionEngine::run(ExecBundle const& _exec, RuntimeData* _data, Env* _env) { Runtime runtime(_data, _env); auto returnCode = runEntryFunc(_exec, &runtime); if (returnCode == ReturnCode::Return) this->returnData = runtime.getReturnData(); return returnCode; } } } } <|endoftext|>
<commit_before>AliAnalysisTask* AddTaskQAHighPtDeDx(Bool_t AnalysisMC = kFALSE, Int_t typerun =1, // 0 for pp and 1 for Pb-Pb or pPb TString type ="ESD", UInt_t kTriggerInt = AliVEvent::kINT7, //for pPb kINT7, for pp or PbPb kMB Float_t minCent = 0., Float_t maxCent = 80., char *centralityEstimator = "V0A",//for pPb V0A for PbPb V0M Bool_t ispileuprej = kFALSE ) { // Creates a pid task and adds it to the analysis manager // Get the pointer to the existing analysis manager via the static //access method //========================================================================= AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskHighPtDeDx", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the // analysis manager The availability of MC handler can also be // checked here. // ========================================================================= if (!mgr->GetInputEventHandler()) { Error("AddTaskHighPtDeDx", "This task requires an input event handler"); return NULL; } AliAnalysisFilter* trackFilterGolden = new AliAnalysisFilter("trackFilter"); AliESDtrackCuts* esdTrackCutsGolden = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kTRUE,1); trackFilterGolden->AddCuts(esdTrackCutsGolden); AliAnalysisFilter* trackFilterTPC = new AliAnalysisFilter("trackFilterTPC"); AliESDtrackCuts* esdTrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts(); trackFilterTPC->AddCuts(esdTrackCutsTPC); AliAnalysisTaskQAHighPtDeDx* taskHighPtDeDx = new AliAnalysisTaskQAHighPtDeDx("taskHighPtDeDxpp"); TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" taskHighPtDeDx->SetAnalysisType(type); taskHighPtDeDx->SetAnalysisMC(AnalysisMC); if(typerun==1){ taskHighPtDeDx->SetAnalysisPbPb(kTRUE); taskHighPtDeDx->SetMinCent(minCent); taskHighPtDeDx->SetMaxCent(maxCent); taskHighPtDeDx->SetCentralityEstimator(centralityEstimator); } else taskHighPtDeDx->SetAnalysisPbPb(kFALSE); taskHighPtDeDx->SetDebugLevel(0); taskHighPtDeDx->SetEtaCut(0.8); taskHighPtDeDx->SetVtxCut(10.0); taskHighPtDeDx->SetTrigger(kTriggerInt); taskHighPtDeDx->SetPileUpRej(ispileuprej); //Set Filtesr taskHighPtDeDx->SetTrackFilterGolden(trackFilterGolden); taskHighPtDeDx->SetTrackFilterTPC(trackFilterTPC); taskHighPtDeDx->SetStoreMcIn(analysisMC); // def: kFALSE mgr->AddTask(taskHighPtDeDx); // Create ONLY the output containers for the data produced by the // task. Get and connect other common input/output containers via // the manager as below //======================================================================= AliAnalysisDataContainer *cout_histdedx; cout_histdedx=0; cout_histdedx = mgr->CreateContainer("outputdedx", TList::Class(), AliAnalysisManager::kOutputContainer, "QAHighPtDeDx.root"); mgr->ConnectInput (taskHighPtDeDx, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskHighPtDeDx, 1, cout_histdedx); // Return task pointer at the end return taskHighPtDeDx; } <commit_msg>Further update of PWGLF QA macro<commit_after>AliAnalysisTask* AddTaskQAHighPtDeDx(Bool_t AnalysisMC = kFALSE, Int_t typerun =1, // 0 for pp and 1 for Pb-Pb or pPb TString type ="ESD", UInt_t kTriggerInt = AliVEvent::kINT7, //for pPb kINT7, for pp or PbPb kMB Float_t minCent = 0., Float_t maxCent = 80., char *centralityEstimator = "V0A",//for pPb V0A for PbPb V0M Bool_t ispileuprej = kFALSE ) { // Creates a pid task and adds it to the analysis manager // Get the pointer to the existing analysis manager via the static //access method //========================================================================= AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskHighPtDeDx", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the // analysis manager The availability of MC handler can also be // checked here. // ========================================================================= if (!mgr->GetInputEventHandler()) { Error("AddTaskHighPtDeDx", "This task requires an input event handler"); return NULL; } AliAnalysisFilter* trackFilterGolden = new AliAnalysisFilter("trackFilter"); AliESDtrackCuts* esdTrackCutsGolden = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kTRUE,1); trackFilterGolden->AddCuts(esdTrackCutsGolden); AliAnalysisFilter* trackFilterTPC = new AliAnalysisFilter("trackFilterTPC"); AliESDtrackCuts* esdTrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts(); trackFilterTPC->AddCuts(esdTrackCutsTPC); AliAnalysisTaskQAHighPtDeDx* taskHighPtDeDx = new AliAnalysisTaskQAHighPtDeDx("taskHighPtDeDxpp"); TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" taskHighPtDeDx->SetAnalysisType(type); taskHighPtDeDx->SetAnalysisMC(AnalysisMC); if(typerun==1){ taskHighPtDeDx->SetAnalysisPbPb(kTRUE); taskHighPtDeDx->SetMinCent(minCent); taskHighPtDeDx->SetMaxCent(maxCent); taskHighPtDeDx->SetCentralityEstimator(centralityEstimator); } else taskHighPtDeDx->SetAnalysisPbPb(kFALSE); taskHighPtDeDx->SetDebugLevel(0); taskHighPtDeDx->SetEtaCut(0.8); taskHighPtDeDx->SetVtxCut(10.0); taskHighPtDeDx->SetTrigger(kTriggerInt); taskHighPtDeDx->SetPileUpRej(ispileuprej); //Set Filtesr taskHighPtDeDx->SetTrackFilterGolden(trackFilterGolden); taskHighPtDeDx->SetTrackFilterTPC(trackFilterTPC); taskHighPtDeDx->SetStoreMcIn(AnalysisMC); // def: kFALSE mgr->AddTask(taskHighPtDeDx); // Create ONLY the output containers for the data produced by the // task. Get and connect other common input/output containers via // the manager as below //======================================================================= AliAnalysisDataContainer *cout_histdedx; cout_histdedx=0; cout_histdedx = mgr->CreateContainer("outputdedx", TList::Class(), AliAnalysisManager::kOutputContainer, "QAHighPtDeDx.root"); mgr->ConnectInput (taskHighPtDeDx, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskHighPtDeDx, 1, cout_histdedx); // Return task pointer at the end return taskHighPtDeDx; } <|endoftext|>
<commit_before>/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.com */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without modification, */ /* are permitted provided that the following conditions are met: */ /* */ /* - Redistributions of source code must retain the above copyright notice, this */ /* list of conditions and the following disclaimer. */ /* */ /* - Redistributions in binary form must reproduce the above copyright notice, this */ /* list of conditions and the following disclaimer in the documentation and/or */ /* other materials provided with the distribution. */ /* */ /* 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. */ /* */ /**************************************************************************************/ #ifndef ShaderNode_INCLUDE_ONCE #define ShaderNode_INCLUDE_ONCE #include <vlGraphics/Shader.hpp> #include <vlCore/vlnamespace.hpp> #include <vector> #include <map> namespace vl { /** * The ShaderNode class is used to conveniently manage complex hierarchies of Shader[s]. */ class ShaderNode: public Object { private: class EnableInfo { public: EnableInfo(EEnable en=EN_UnknownEnable, bool on=false, EInheritance inheritance=IN_Propagate): mEnable(en), mOn(on), mInheritance(inheritance) {} EEnable mEnable; bool mOn; EInheritance mInheritance; }; class RenderStateInfo { public: RenderStateInfo(RenderState* rs=NULL, EInheritance inheritance=IN_Propagate): mRenderState(rs), mInheritance(inheritance) {} ref<RenderState> mRenderState; EInheritance mInheritance; }; class UniformInfo { public: UniformInfo(Uniform* unif=NULL, EInheritance inheritance=IN_Propagate): mUniform(unif), mInheritance(inheritance) {} ref<Uniform> mUniform; EInheritance mInheritance; }; public: virtual const char* className() { return "vl::ShaderNode"; } ShaderNode(): mParent(NULL) {} // tree-related functions void addChild(ShaderNode* node) { VL_CHECK(node->parent() == NULL); mNodes.push_back(node); node->mParent = this; } void eraseChild(ShaderNode* node) { VL_CHECK(node->parent() == this); for(unsigned i=0; i<childrenCount(); ++i) if (child(i) == node) { mNodes.erase(mNodes.begin()+i); node->mParent = NULL; return; } } void eraseChild(unsigned index) { VL_CHECK(index<childrenCount()) mNodes[index]->mParent = NULL; mNodes.erase(mNodes.begin()+index); } void eraseChildren(unsigned start, unsigned count) { VL_CHECK(start < childrenCount()) VL_CHECK(start+count-1 < childrenCount()) for(unsigned i=start; i<start+count; ++i) mNodes[i]->mParent = NULL; mNodes.erase(mNodes.begin()+start, mNodes.begin()+start+count); } int findChild(const ShaderNode* node) const { for(unsigned i=0; i<childrenCount(); ++i) if(child(i) == node) return i; return -1; } size_t childrenCount() const { return mNodes.size(); } ShaderNode* child(unsigned i) { return mNodes[i].get(); } const ShaderNode* child(unsigned i) const { return mNodes[i].get(); } ShaderNode* parent() { return mParent; } const ShaderNode* parent() const { return mParent; } // shader-related functions void inherit(ShaderNode* parent) { // init mRenderStates_Final.clear(); mEnables_Final.clear(); mUniforms_Final.clear(); // propagate for(std::map< ERenderState, RenderStateInfo >::const_iterator rs_it = mRenderStates.begin(); rs_it != mRenderStates.end(); ++rs_it) mRenderStates_Final[rs_it->first] = rs_it->second; for(std::map< EEnable, EnableInfo>::const_iterator en_it = mEnables.begin(); en_it != mEnables.end(); ++en_it) if(en_it->second.mOn) mEnables_Final[en_it->first] = en_it->second; for(std::map< std::string, UniformInfo >::const_iterator unif_it = mUniforms.begin(); unif_it != mUniforms.end(); ++unif_it) mUniforms_Final[unif_it->first] = unif_it->second; // iterate parent final values if (parent) { /* ALGORITHM: * * 1 - iterate over parent's values * 2 - if it doesn't propagate -> end * 3 - find current values * 3a - if there is not -> insert parent's -> end * 3b - if there is * 3ba - if parent's do not overrides -> end * 3bb - if child's do not overridden -> end * 3bc - else -> use parent's */ // render states for(std::map< ERenderState, RenderStateInfo >::const_iterator par_it = parent->mRenderStates_Final.begin(); par_it != parent->mRenderStates_Final.end(); ++par_it) { if (!(par_it->second.mInheritance & IN_Propagate)) continue; std::map< ERenderState, RenderStateInfo >::const_iterator cur_it = mRenderStates_Final.find(par_it->first); if (cur_it == mRenderStates_Final.end()) mRenderStates_Final[par_it->first] = par_it->second; else if (!(par_it->second.mInheritance & 0x02/*IN_Overrides*/) || (cur_it->second.mInheritance & IN_Sticky)) continue; else mRenderStates_Final[par_it->first] = par_it->second; } // enables for(std::map< EEnable, EnableInfo >::const_iterator par_it = parent->mEnables_Final.begin(); par_it != parent->mEnables_Final.end(); ++par_it) { if (!par_it->second.mOn) continue; if (!(par_it->second.mInheritance & IN_Propagate)) continue; std::map< EEnable, EnableInfo >::const_iterator cur_it = mEnables_Final.find(par_it->first); if (cur_it == mEnables_Final.end()) mEnables_Final[par_it->first] = par_it->second; else if (!(par_it->second.mInheritance & 0x02/*IN_Overrides*/) || (cur_it->second.mInheritance & IN_Sticky)) continue; else mEnables_Final[par_it->first] = par_it->second; } // uniforms for(std::map< std::string, UniformInfo >::const_iterator par_it = parent->mUniforms_Final.begin(); par_it != parent->mUniforms_Final.end(); ++par_it) { if (!(par_it->second.mInheritance & IN_Propagate)) continue; std::map< std::string, UniformInfo >::const_iterator cur_it = mUniforms_Final.find(par_it->first); if (cur_it == mUniforms_Final.end()) mUniforms_Final[par_it->first] = par_it->second; else if (!(par_it->second.mInheritance & 0x02/*IN_Overrides*/) || (cur_it->second.mInheritance & IN_Sticky)) continue; else mUniforms_Final[par_it->first] = par_it->second; } } // apply it to the Shader if (mShader) { mShader->eraseAllRenderStates(); mShader->eraseAllUniforms(); mShader->disableAll(); // we can speed this up even more by removing the duplication check for(std::map< ERenderState, RenderStateInfo >::const_iterator rs_it = mRenderStates_Final.begin(); rs_it != mRenderStates_Final.end(); ++rs_it) mShader->setRenderState(rs_it->second.mRenderState.get()); for(std::map< EEnable, EnableInfo >::const_iterator en_it = mEnables_Final.begin(); en_it != mEnables_Final.end(); ++en_it) mShader->enable(en_it->second.mEnable); for(std::map< std::string, UniformInfo >::const_iterator rs_it = mUniforms_Final.begin(); rs_it != mUniforms_Final.end(); ++rs_it) mShader->setUniform(rs_it->second.mUniform.get()); } } void setRenderState(RenderState* rs, EInheritance inheritance=IN_Propagate) { RenderStateInfo info(rs, inheritance); mRenderStates[rs->type()] = info; } void eraseRenderState(RenderState* rs) { mRenderStates.erase(rs->type()); } void setEnable(EEnable en, bool on, EInheritance inheritance=IN_Propagate) { EnableInfo info(en,on,inheritance); mEnables[en] = info; } void eraseEnable(EEnable en) { mEnables.erase(en); } void setUniform(Uniform* unif, EInheritance inheritance=IN_Propagate) { UniformInfo info(unif, inheritance); mUniforms[unif->name()] = info; } void eraseUniform(Uniform* unif) { mUniforms.erase(unif->name()); } void setShader(Shader* shader) { mShader = shader; } const Shader* shader() const { return mShader.get(); } Shader* shader() { return mShader.get(); } void updateHierarchy() { inherit(parent()); for(unsigned i=0;i <childrenCount(); ++i) child(i)->updateHierarchy(); } protected: std::vector< ref< ShaderNode > > mNodes; ShaderNode* mParent; std::map< ERenderState, RenderStateInfo > mRenderStates; std::map< EEnable, EnableInfo> mEnables; std::map< std::string, UniformInfo > mUniforms; std::map< ERenderState, RenderStateInfo > mRenderStates_Final; std::map< EEnable, EnableInfo> mEnables_Final; std::map< std::string, UniformInfo > mUniforms_Final; ref<Shader> mShader; }; } #endif <commit_msg>ShaderNode getter functions.<commit_after>/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.com */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without modification, */ /* are permitted provided that the following conditions are met: */ /* */ /* - Redistributions of source code must retain the above copyright notice, this */ /* list of conditions and the following disclaimer. */ /* */ /* - Redistributions in binary form must reproduce the above copyright notice, this */ /* list of conditions and the following disclaimer in the documentation and/or */ /* other materials provided with the distribution. */ /* */ /* 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. */ /* */ /**************************************************************************************/ #ifndef ShaderNode_INCLUDE_ONCE #define ShaderNode_INCLUDE_ONCE #include <vlGraphics/Shader.hpp> #include <vlCore/vlnamespace.hpp> #include <vector> #include <map> namespace vl { /** * The ShaderNode class is used to conveniently manage complex hierarchies of Shader[s]. */ class ShaderNode: public Object { public: // --- --- --- struct EnableInfo { EnableInfo(EEnable en=EN_UnknownEnable, bool on=false, EInheritance inheritance=IN_Propagate): mEnable(en), mOn(on), mInheritance(inheritance) {} EEnable mEnable; bool mOn; EInheritance mInheritance; }; // --- --- --- struct RenderStateInfo { RenderStateInfo(RenderState* rs=NULL, EInheritance inheritance=IN_Propagate): mRenderState(rs), mInheritance(inheritance) {} ref<RenderState> mRenderState; EInheritance mInheritance; }; // --- --- --- struct UniformInfo { UniformInfo(Uniform* unif=NULL, EInheritance inheritance=IN_Propagate): mUniform(unif), mInheritance(inheritance) {} ref<Uniform> mUniform; EInheritance mInheritance; }; // --- --- --- typedef std::map< ERenderState, RenderStateInfo > RenderStatesMap; typedef std::map< EEnable, EnableInfo > EnablesMap; typedef std::map< std::string, UniformInfo > UniformsMap; public: virtual const char* className() { return "vl::ShaderNode"; } ShaderNode(): mParent(NULL) {} // shader-related functions void setShader(Shader* shader) { mShader = shader; } const Shader* shader() const { return mShader.get(); } Shader* shader() { return mShader.get(); } // tree-related functions void addChild(ShaderNode* node) { VL_CHECK(node->parent() == NULL); mNodes.push_back(node); node->mParent = this; } void eraseChild(ShaderNode* node) { VL_CHECK(node->parent() == this); for(unsigned i=0; i<childrenCount(); ++i) if (child(i) == node) { mNodes.erase(mNodes.begin()+i); node->mParent = NULL; return; } } void eraseChild(unsigned index) { VL_CHECK(index<childrenCount()) mNodes[index]->mParent = NULL; mNodes.erase(mNodes.begin()+index); } void eraseChildren(unsigned start, unsigned count) { VL_CHECK(start < childrenCount()) VL_CHECK(start+count-1 < childrenCount()) for(unsigned i=start; i<start+count; ++i) mNodes[i]->mParent = NULL; mNodes.erase(mNodes.begin()+start, mNodes.begin()+start+count); } int findChild(const ShaderNode* node) const { for(unsigned i=0; i<childrenCount(); ++i) if(child(i) == node) return i; return -1; } size_t childrenCount() const { return mNodes.size(); } ShaderNode* child(unsigned i) { return mNodes[i].get(); } const ShaderNode* child(unsigned i) const { return mNodes[i].get(); } ShaderNode* parent() { return mParent; } const ShaderNode* parent() const { return mParent; } // inheritance-related functions void updateHierarchy() { inherit(parent()); for(unsigned i=0;i <childrenCount(); ++i) child(i)->updateHierarchy(); } void inherit(ShaderNode* parent) { // init mRenderStates_Final.clear(); mEnables_Final.clear(); mUniforms_Final.clear(); // propagate for(RenderStatesMap::const_iterator rs_it = mRenderStates.begin(); rs_it != mRenderStates.end(); ++rs_it) mRenderStates_Final[rs_it->first] = rs_it->second; for(std::map< EEnable, EnableInfo>::const_iterator en_it = mEnables.begin(); en_it != mEnables.end(); ++en_it) if(en_it->second.mOn) mEnables_Final[en_it->first] = en_it->second; for(UniformsMap::const_iterator unif_it = mUniforms.begin(); unif_it != mUniforms.end(); ++unif_it) mUniforms_Final[unif_it->first] = unif_it->second; // iterate parent final values if (parent) { /* ALGORITHM: * * 1 - iterate over parent's values * 2 - if it doesn't propagate -> end * 3 - find current values * 3a - if there is not -> insert parent's -> end * 3b - if there is * 3ba - if parent's do not overrides -> end * 3bb - if child's do not overridden -> end * 3bc - else -> use parent's */ // render states for(RenderStatesMap::const_iterator par_it = parent->mRenderStates_Final.begin(); par_it != parent->mRenderStates_Final.end(); ++par_it) { if (!(par_it->second.mInheritance & IN_Propagate)) continue; RenderStatesMap::const_iterator cur_it = mRenderStates_Final.find(par_it->first); if (cur_it == mRenderStates_Final.end()) mRenderStates_Final[par_it->first] = par_it->second; else if (!(par_it->second.mInheritance & 0x02/*IN_Overrides*/) || (cur_it->second.mInheritance & IN_Sticky)) continue; else mRenderStates_Final[par_it->first] = par_it->second; } // enables for(EnablesMap::const_iterator par_it = parent->mEnables_Final.begin(); par_it != parent->mEnables_Final.end(); ++par_it) { if (!par_it->second.mOn) continue; if (!(par_it->second.mInheritance & IN_Propagate)) continue; EnablesMap::const_iterator cur_it = mEnables_Final.find(par_it->first); if (cur_it == mEnables_Final.end()) mEnables_Final[par_it->first] = par_it->second; else if (!(par_it->second.mInheritance & 0x02/*IN_Overrides*/) || (cur_it->second.mInheritance & IN_Sticky)) continue; else mEnables_Final[par_it->first] = par_it->second; } // uniforms for(UniformsMap::const_iterator par_it = parent->mUniforms_Final.begin(); par_it != parent->mUniforms_Final.end(); ++par_it) { if (!(par_it->second.mInheritance & IN_Propagate)) continue; UniformsMap::const_iterator cur_it = mUniforms_Final.find(par_it->first); if (cur_it == mUniforms_Final.end()) mUniforms_Final[par_it->first] = par_it->second; else if (!(par_it->second.mInheritance & 0x02/*IN_Overrides*/) || (cur_it->second.mInheritance & IN_Sticky)) continue; else mUniforms_Final[par_it->first] = par_it->second; } } // apply it to the Shader if (mShader) { mShader->eraseAllRenderStates(); mShader->eraseAllUniforms(); mShader->disableAll(); // we can speed this up even more by removing the duplication check for(RenderStatesMap::const_iterator rs_it = mRenderStates_Final.begin(); rs_it != mRenderStates_Final.end(); ++rs_it) mShader->setRenderState(rs_it->second.mRenderState.get()); for(EnablesMap::const_iterator en_it = mEnables_Final.begin(); en_it != mEnables_Final.end(); ++en_it) mShader->enable(en_it->second.mEnable); for(UniformsMap::const_iterator rs_it = mUniforms_Final.begin(); rs_it != mUniforms_Final.end(); ++rs_it) mShader->setUniform(rs_it->second.mUniform.get()); } } // states setters void setRenderState(RenderState* rs, EInheritance inheritance=IN_Propagate) { RenderStateInfo info(rs, inheritance); mRenderStates[rs->type()] = info; } void eraseRenderState(RenderState* rs) { mRenderStates.erase(rs->type()); } void setEnable(EEnable en, bool on, EInheritance inheritance=IN_Propagate) { EnableInfo info(en,on,inheritance); mEnables[en] = info; } void eraseEnable(EEnable en) { mEnables.erase(en); } void setUniform(Uniform* unif, EInheritance inheritance=IN_Propagate) { UniformInfo info(unif, inheritance); mUniforms[unif->name()] = info; } void eraseUniform(Uniform* unif) { mUniforms.erase(unif->name()); } // states getters const RenderStatesMap& renderStates() const { return mRenderStates; } RenderStatesMap& renderStates() { return mRenderStates; } const EnablesMap& enables() const { return mEnables; } EnablesMap& enables() { return mEnables; } const UniformsMap& uniforms() const { return mUniforms; } UniformsMap& uniforms() { return mUniforms; } protected: std::vector< ref< ShaderNode > > mNodes; ShaderNode* mParent; RenderStatesMap mRenderStates; EnablesMap mEnables; UniformsMap mUniforms; RenderStatesMap mRenderStates_Final; EnablesMap mEnables_Final; UniformsMap mUniforms_Final; ref<Shader> mShader; }; } #endif <|endoftext|>
<commit_before>#include "xchainer/routines/sorting.h" #include <cstdint> #include <string> #include <gtest/gtest.h> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/device.h" #include "xchainer/device_id.h" #include "xchainer/error.h" #include "xchainer/testing/array.h" #include "xchainer/testing/array_check.h" #include "xchainer/testing/device_session.h" #include "xchainer/testing/routines.h" namespace xchainer { namespace { class SortingTest : public ::testing::TestWithParam<std::string> { protected: void SetUp() override { const std::string& backend_name = GetParam(); device_session_.emplace(DeviceId{backend_name, 0}); } void TearDown() override { device_session_.reset(); } private: nonstd::optional<testing::DeviceSession> device_session_; }; TEST_P(SortingTest, ArgMax) { Array a = testing::BuildArray({2, 3}).WithData<float>({1, 4, 3, 0, 1, 4}).WithPadding(1); Array e = testing::BuildArray({3}).WithData<int64_t>({0, 0, 1}); testing::CheckForward( [](const std::vector<Array>& xs) { return std::vector<Array>{ArgMax(xs[0], 0)}; }, {a}, {e}, // TODO(sonots): Run concurrency test in CUDA GetParam() == "cuda" ? 0 : 1); } TEST_P(SortingTest, ArgMaxNegativeAxis) { Array a = testing::BuildArray({2, 3}).WithData<float>({1, 4, 3, 0, 1, 4}); Array e = testing::BuildArray({2}).WithData<int64_t>({1, 2}); testing::CheckForward( [](const std::vector<Array>& xs) { return std::vector<Array>{ArgMax(xs[0], -1)}; }, {a}, {e}, // TODO(sonots): Run concurrency test in CUDA GetParam() == "cuda" ? 0 : 1); } TEST_P(SortingTest, ArgMaxAllAxes) { Array a = testing::BuildArray({2, 3}).WithData<float>({1, 4, 3, 0, 1, 4}); Array e = testing::BuildArray({}).WithData<int64_t>({1}); testing::CheckForward( [](const std::vector<Array>& xs) { return std::vector<Array>{ArgMax(xs[0])}; }, {a}, {e}, // TODO(sonots): Run concurrency test in CUDA GetParam() == "cuda" ? 0 : 1); } TEST_P(SortingTest, ArgMaxInvalidAxis) { Array a = testing::BuildArray({2, 3}).WithData<float>({1, 4, 3, 0, 1, 4}); EXPECT_THROW(ArgMax(a, 3), DimensionError); } TEST_P(SortingTest, ArgMaxEmpty) { Array a = Zeros({0}, Dtype::kFloat32); EXPECT_THROW(ArgMax(a), DimensionError); } INSTANTIATE_TEST_CASE_P( ForEachBackend, SortingTest, ::testing::Values( #ifdef XCHAINER_ENABLE_CUDA std::string{"cuda"}, #endif // XCHAINER_ENABLE_CUDA std::string{"native"})); } // namespace } // namespace xchainer <commit_msg>cpplint<commit_after>#include "xchainer/routines/sorting.h" #include <cstdint> #include <string> #include <vector> #include <gtest/gtest.h> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/device.h" #include "xchainer/device_id.h" #include "xchainer/error.h" #include "xchainer/testing/array.h" #include "xchainer/testing/array_check.h" #include "xchainer/testing/device_session.h" #include "xchainer/testing/routines.h" namespace xchainer { namespace { class SortingTest : public ::testing::TestWithParam<std::string> { protected: void SetUp() override { const std::string& backend_name = GetParam(); device_session_.emplace(DeviceId{backend_name, 0}); } void TearDown() override { device_session_.reset(); } private: nonstd::optional<testing::DeviceSession> device_session_; }; TEST_P(SortingTest, ArgMax) { Array a = testing::BuildArray({2, 3}).WithData<float>({1, 4, 3, 0, 1, 4}).WithPadding(1); Array e = testing::BuildArray({3}).WithData<int64_t>({0, 0, 1}); testing::CheckForward( [](const std::vector<Array>& xs) { return std::vector<Array>{ArgMax(xs[0], 0)}; }, {a}, {e}, // TODO(sonots): Run concurrency test in CUDA GetParam() == "cuda" ? 0 : 1); } TEST_P(SortingTest, ArgMaxNegativeAxis) { Array a = testing::BuildArray({2, 3}).WithData<float>({1, 4, 3, 0, 1, 4}); Array e = testing::BuildArray({2}).WithData<int64_t>({1, 2}); testing::CheckForward( [](const std::vector<Array>& xs) { return std::vector<Array>{ArgMax(xs[0], -1)}; }, {a}, {e}, // TODO(sonots): Run concurrency test in CUDA GetParam() == "cuda" ? 0 : 1); } TEST_P(SortingTest, ArgMaxAllAxes) { Array a = testing::BuildArray({2, 3}).WithData<float>({1, 4, 3, 0, 1, 4}); Array e = testing::BuildArray({}).WithData<int64_t>({1}); testing::CheckForward( [](const std::vector<Array>& xs) { return std::vector<Array>{ArgMax(xs[0])}; }, {a}, {e}, // TODO(sonots): Run concurrency test in CUDA GetParam() == "cuda" ? 0 : 1); } TEST_P(SortingTest, ArgMaxInvalidAxis) { Array a = testing::BuildArray({2, 3}).WithData<float>({1, 4, 3, 0, 1, 4}); EXPECT_THROW(ArgMax(a, 3), DimensionError); } TEST_P(SortingTest, ArgMaxEmpty) { Array a = Zeros({0}, Dtype::kFloat32); EXPECT_THROW(ArgMax(a), DimensionError); } INSTANTIATE_TEST_CASE_P( ForEachBackend, SortingTest, ::testing::Values( #ifdef XCHAINER_ENABLE_CUDA std::string{"cuda"}, #endif // XCHAINER_ENABLE_CUDA std::string{"native"})); } // namespace } // namespace xchainer <|endoftext|>
<commit_before>// Copyright 2022 The XLS 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. #include "absl/status/status.h" #include "clang/include/clang/AST/Expr.h" #include "clang/include/clang/AST/ExprCXX.h" #include "xls/common/status/status_macros.h" #include "xls/contrib/xlscc/translator.h" namespace xlscc { absl::StatusOr<IOOp*> Translator::AddOpToChannel(IOOp& op, IOChannel* channel, const xls::SourceInfo& loc, bool mask) { context().any_side_effects_requested = true; if (context().mask_side_effects || mask) { IOOpReturn ret; ret.generate_expr = false; XLS_ASSIGN_OR_RETURN(xls::BValue default_bval, CreateDefaultValue(channel->item_type, loc)); op.input_value = CValue(default_bval, channel->item_type); return &op; } XLS_CHECK_NE(channel, nullptr); XLS_CHECK_EQ(op.channel, nullptr); op.channel_op_index = channel->total_ops++; op.channel = channel; op.op_location = loc; // Operation type is added late, as it's only known from the read()/write() // call(s) if (channel->channel_op_type == OpType::kNull) { channel->channel_op_type = op.op; } else { if (channel->channel_op_type != op.op) { return absl::UnimplementedError( ErrorMessage(loc, "Channels should be either input or output")); } } // Channel must be inserted first by AddOpToChannel if (op.op == OpType::kRecv) { xls::Type* xls_item_type; std::shared_ptr<CType> channel_item_type; if (op.is_blocking) { XLS_ASSIGN_OR_RETURN(xls_item_type, TranslateTypeToXLS(channel->item_type, loc)); channel_item_type = channel->item_type; } else { XLS_ASSIGN_OR_RETURN(xls::Type * primary_item_type, TranslateTypeToXLS(channel->item_type, loc)); xls_item_type = package_->GetTupleType({primary_item_type, package_->GetBitsType(1)}); channel_item_type = std::make_shared<CInternalTuple>(std::vector<std::shared_ptr<CType>>( {channel->item_type, std::make_shared<CBoolType>()})); } const int64_t channel_op_index = op.channel_op_index; std::string safe_param_name = absl::StrFormat("%s_op%i", op.channel->unique_name, channel_op_index); xls::BValue pbval = context().fb->Param(safe_param_name, xls_item_type, loc); // Check for duplicate params if (!pbval.valid()) { return absl::InternalError(ErrorMessage( loc, "Failed to create implicit parameter %s, duplicate? See b/239861050", safe_param_name.c_str())); } op.input_value = CValue(pbval, channel_item_type); } context().sf->io_ops.push_back(op); if (op.op == OpType::kRecv) { SideEffectingParameter side_effecting_param; side_effecting_param.type = SideEffectingParameterType::kIOOp; side_effecting_param.param_name = op.input_value.rvalue().node()->As<xls::Param>()->GetName(); side_effecting_param.io_op = &context().sf->io_ops.back(); context().sf->side_effecting_parameters.push_back(side_effecting_param); } return &context().sf->io_ops.back(); } absl::StatusOr<std::shared_ptr<CType>> Translator::GetChannelType( const clang::ParmVarDecl* channel_param, const xls::SourceInfo& loc) { XLS_ASSIGN_OR_RETURN(StrippedType stripped, StripTypeQualifiers(channel_param->getType())); auto template_spec = clang::dyn_cast<const clang::TemplateSpecializationType>( stripped.base.getTypePtr()); if (template_spec == nullptr) { return absl::UnimplementedError( ErrorMessage(loc, "Channel type should be a template specialization")); } if (template_spec->getNumArgs() != 1) { return absl::UnimplementedError( ErrorMessage(loc, "Channel should have 1 template args")); } const clang::TemplateArgument& arg = template_spec->getArg(0); return TranslateTypeFromClang(arg.getAsType(), loc); } absl::Status Translator::CreateChannelParam( const clang::ParmVarDecl* channel_param, const xls::SourceInfo& loc) { XLS_CHECK(!context().variables.contains(channel_param)); XLS_ASSIGN_OR_RETURN(std::shared_ptr<CType> ctype, GetChannelType(channel_param, loc)); IOChannel new_channel; new_channel.item_type = ctype; new_channel.unique_name = channel_param->getNameAsString(); context().sf->io_channels.push_back(new_channel); auto channel_type = std::make_shared<CChannelType>(ctype); auto lvalue = std::make_shared<LValue>(&context().sf->io_channels.back()); XLS_RETURN_IF_ERROR( DeclareVariable(channel_param, CValue(/*rvalue=*/xls::BValue(), channel_type, /*disable_type_check=*/true, lvalue), loc)); return absl::OkStatus(); } absl::StatusOr<Translator::IOOpReturn> Translator::InterceptIOOp( const clang::Expr* expr, const xls::SourceInfo& loc) { if (auto member_call = clang::dyn_cast<const clang::CXXMemberCallExpr>(expr)) { const clang::Expr* object = member_call->getImplicitObjectArgument(); XLS_ASSIGN_OR_RETURN(IOChannel * channel, GetChannelForExprOrNull(object)); if (channel != nullptr) { const clang::FunctionDecl* funcdecl = member_call->getDirectCallee(); const std::string op_name = funcdecl->getNameAsString(); xls::BValue op_condition = context().full_condition_bval(loc); XLS_CHECK(op_condition.valid()); // Short circuit the op condition if possible XLS_RETURN_IF_ERROR(ShortCircuitBVal(op_condition, loc)); // Ignore IO ops that are definitely condition = 0 // XLS opt also does this down-stream, but we try to do it here // for cases like "if(constexpr) {ch.read();} else {ch.write();} // which otherwise confuse XLS[cc] itself. bool do_default = false; absl::StatusOr<xls::Value> eval_result = EvaluateBVal(op_condition, loc, /*do_check=*/false); if (eval_result.ok()) { if (eval_result.value().IsAllZeros()) { do_default = true; } } auto call = clang::dyn_cast<const clang::CallExpr>(expr); IOOpReturn ret; ret.generate_expr = false; IOOp op; const clang::Expr* assign_ret_value_to = nullptr; if (op_name == "read") { if (call->getNumArgs() == 1) { assign_ret_value_to = call->getArg(0); } else if (call->getNumArgs() != 0) { return absl::UnimplementedError(ErrorMessage( loc, "IO read() should have one or zero argument(s)")); } op.op = OpType::kRecv; op.ret_value = op_condition; op.is_blocking = true; } else if (op_name == "nb_read") { if (call->getNumArgs() != 1) { return absl::UnimplementedError( ErrorMessage(loc, "IO nb_read() should have one argument")); } assign_ret_value_to = call->getArg(0); op.op = OpType::kRecv; op.ret_value = op_condition; op.is_blocking = false; } else if (op_name == "write") { if (call->getNumArgs() != 1) { return absl::UnimplementedError( ErrorMessage(loc, "IO write() should have one argument")); } XLS_ASSIGN_OR_RETURN(CValue out_val, GenerateIR_Expr(call->getArg(0), loc)); std::vector<xls::BValue> sp = {out_val.rvalue(), op_condition}; op.ret_value = context().fb->Tuple(sp, loc); op.op = OpType::kSend; op.is_blocking = true; } else { return absl::UnimplementedError( ErrorMessage(loc, "Unsupported IO op: %s", op_name)); } XLS_ASSIGN_OR_RETURN( IOOp * op_ptr, AddOpToChannel(op, channel, loc, /*mask=*/do_default)); (void)op_ptr; ret.value = op.input_value; if (assign_ret_value_to != nullptr) { if (op.is_blocking) { XLS_RETURN_IF_ERROR(Assign(assign_ret_value_to, ret.value, loc)); } else { xls::BValue read_ready = context().fb->TupleIndex(ret.value.rvalue(), 1); xls::BValue read_value = context().fb->TupleIndex(ret.value.rvalue(), 0); if (!ret.value.type()->Is<CInternalTuple>()) { return absl::UnimplementedError( ErrorMessage(loc, "Unsupported IO op: %s", op_name)); } CValue ret_object_value; ret_object_value = CValue( read_value, ret.value.type()->As<CInternalTuple>()->fields()[0]); { PushContextGuard condition_guard(*this, loc); XLS_RETURN_IF_ERROR(and_condition(read_ready, loc)); XLS_RETURN_IF_ERROR(Assign( assign_ret_value_to, ret_object_value, loc)); } CValue ret_struct = CValue(read_ready, std::make_shared<CBoolType>()); ret.value = ret_struct; } } return ret; } } IOOpReturn ret; ret.generate_expr = true; return ret; } absl::Status Translator::ExtractExternalIOChannelDecls() { for (const auto& [decl, cval] : context().variables) { auto channel_type = dynamic_cast<const CChannelType*>(cval.type().get()); if (channel_type == nullptr) { continue; } XLS_CHECK_NE(cval.lvalue(), nullptr); XLS_CHECK_NE(cval.lvalue()->channel_leaf(), nullptr); context().sf->io_channels_by_decl[decl] = cval.lvalue()->channel_leaf(); context().sf->decls_by_io_channel[cval.lvalue()->channel_leaf()] = decl; } return absl::OkStatus(); } } // namespace xlscc <commit_msg>Integrate LLVM at llvm/llvm-project@fdac4c4e92e5<commit_after>// Copyright 2022 The XLS 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. #include "absl/status/status.h" #include "clang/include/clang/AST/Expr.h" #include "clang/include/clang/AST/ExprCXX.h" #include "xls/common/status/status_macros.h" #include "xls/contrib/xlscc/translator.h" namespace xlscc { absl::StatusOr<IOOp*> Translator::AddOpToChannel(IOOp& op, IOChannel* channel, const xls::SourceInfo& loc, bool mask) { context().any_side_effects_requested = true; if (context().mask_side_effects || mask) { IOOpReturn ret; ret.generate_expr = false; XLS_ASSIGN_OR_RETURN(xls::BValue default_bval, CreateDefaultValue(channel->item_type, loc)); op.input_value = CValue(default_bval, channel->item_type); return &op; } XLS_CHECK_NE(channel, nullptr); XLS_CHECK_EQ(op.channel, nullptr); op.channel_op_index = channel->total_ops++; op.channel = channel; op.op_location = loc; // Operation type is added late, as it's only known from the read()/write() // call(s) if (channel->channel_op_type == OpType::kNull) { channel->channel_op_type = op.op; } else { if (channel->channel_op_type != op.op) { return absl::UnimplementedError( ErrorMessage(loc, "Channels should be either input or output")); } } // Channel must be inserted first by AddOpToChannel if (op.op == OpType::kRecv) { xls::Type* xls_item_type; std::shared_ptr<CType> channel_item_type; if (op.is_blocking) { XLS_ASSIGN_OR_RETURN(xls_item_type, TranslateTypeToXLS(channel->item_type, loc)); channel_item_type = channel->item_type; } else { XLS_ASSIGN_OR_RETURN(xls::Type * primary_item_type, TranslateTypeToXLS(channel->item_type, loc)); xls_item_type = package_->GetTupleType({primary_item_type, package_->GetBitsType(1)}); channel_item_type = std::make_shared<CInternalTuple>(std::vector<std::shared_ptr<CType>>( {channel->item_type, std::make_shared<CBoolType>()})); } const int64_t channel_op_index = op.channel_op_index; std::string safe_param_name = absl::StrFormat("%s_op%i", op.channel->unique_name, channel_op_index); xls::BValue pbval = context().fb->Param(safe_param_name, xls_item_type, loc); // Check for duplicate params if (!pbval.valid()) { return absl::InternalError(ErrorMessage( loc, "Failed to create implicit parameter %s, duplicate? See b/239861050", safe_param_name.c_str())); } op.input_value = CValue(pbval, channel_item_type); } context().sf->io_ops.push_back(op); if (op.op == OpType::kRecv) { SideEffectingParameter side_effecting_param; side_effecting_param.type = SideEffectingParameterType::kIOOp; side_effecting_param.param_name = op.input_value.rvalue().node()->As<xls::Param>()->GetName(); side_effecting_param.io_op = &context().sf->io_ops.back(); context().sf->side_effecting_parameters.push_back(side_effecting_param); } return &context().sf->io_ops.back(); } absl::StatusOr<std::shared_ptr<CType>> Translator::GetChannelType( const clang::ParmVarDecl* channel_param, const xls::SourceInfo& loc) { XLS_ASSIGN_OR_RETURN(StrippedType stripped, StripTypeQualifiers(channel_param->getType())); auto template_spec = clang::dyn_cast<const clang::TemplateSpecializationType>( stripped.base.getTypePtr()); if (template_spec == nullptr) { return absl::UnimplementedError( ErrorMessage(loc, "Channel type should be a template specialization")); } if (template_spec->template_arguments().size() != 1) { return absl::UnimplementedError( ErrorMessage(loc, "Channel should have 1 template args")); } const clang::TemplateArgument& arg = template_spec->template_arguments()[0]; return TranslateTypeFromClang(arg.getAsType(), loc); } absl::Status Translator::CreateChannelParam( const clang::ParmVarDecl* channel_param, const xls::SourceInfo& loc) { XLS_CHECK(!context().variables.contains(channel_param)); XLS_ASSIGN_OR_RETURN(std::shared_ptr<CType> ctype, GetChannelType(channel_param, loc)); IOChannel new_channel; new_channel.item_type = ctype; new_channel.unique_name = channel_param->getNameAsString(); context().sf->io_channels.push_back(new_channel); auto channel_type = std::make_shared<CChannelType>(ctype); auto lvalue = std::make_shared<LValue>(&context().sf->io_channels.back()); XLS_RETURN_IF_ERROR( DeclareVariable(channel_param, CValue(/*rvalue=*/xls::BValue(), channel_type, /*disable_type_check=*/true, lvalue), loc)); return absl::OkStatus(); } absl::StatusOr<Translator::IOOpReturn> Translator::InterceptIOOp( const clang::Expr* expr, const xls::SourceInfo& loc) { if (auto member_call = clang::dyn_cast<const clang::CXXMemberCallExpr>(expr)) { const clang::Expr* object = member_call->getImplicitObjectArgument(); XLS_ASSIGN_OR_RETURN(IOChannel * channel, GetChannelForExprOrNull(object)); if (channel != nullptr) { const clang::FunctionDecl* funcdecl = member_call->getDirectCallee(); const std::string op_name = funcdecl->getNameAsString(); xls::BValue op_condition = context().full_condition_bval(loc); XLS_CHECK(op_condition.valid()); // Short circuit the op condition if possible XLS_RETURN_IF_ERROR(ShortCircuitBVal(op_condition, loc)); // Ignore IO ops that are definitely condition = 0 // XLS opt also does this down-stream, but we try to do it here // for cases like "if(constexpr) {ch.read();} else {ch.write();} // which otherwise confuse XLS[cc] itself. bool do_default = false; absl::StatusOr<xls::Value> eval_result = EvaluateBVal(op_condition, loc, /*do_check=*/false); if (eval_result.ok()) { if (eval_result.value().IsAllZeros()) { do_default = true; } } auto call = clang::dyn_cast<const clang::CallExpr>(expr); IOOpReturn ret; ret.generate_expr = false; IOOp op; const clang::Expr* assign_ret_value_to = nullptr; if (op_name == "read") { if (call->getNumArgs() == 1) { assign_ret_value_to = call->getArg(0); } else if (call->getNumArgs() != 0) { return absl::UnimplementedError(ErrorMessage( loc, "IO read() should have one or zero argument(s)")); } op.op = OpType::kRecv; op.ret_value = op_condition; op.is_blocking = true; } else if (op_name == "nb_read") { if (call->getNumArgs() != 1) { return absl::UnimplementedError( ErrorMessage(loc, "IO nb_read() should have one argument")); } assign_ret_value_to = call->getArg(0); op.op = OpType::kRecv; op.ret_value = op_condition; op.is_blocking = false; } else if (op_name == "write") { if (call->getNumArgs() != 1) { return absl::UnimplementedError( ErrorMessage(loc, "IO write() should have one argument")); } XLS_ASSIGN_OR_RETURN(CValue out_val, GenerateIR_Expr(call->getArg(0), loc)); std::vector<xls::BValue> sp = {out_val.rvalue(), op_condition}; op.ret_value = context().fb->Tuple(sp, loc); op.op = OpType::kSend; op.is_blocking = true; } else { return absl::UnimplementedError( ErrorMessage(loc, "Unsupported IO op: %s", op_name)); } XLS_ASSIGN_OR_RETURN( IOOp * op_ptr, AddOpToChannel(op, channel, loc, /*mask=*/do_default)); (void)op_ptr; ret.value = op.input_value; if (assign_ret_value_to != nullptr) { if (op.is_blocking) { XLS_RETURN_IF_ERROR(Assign(assign_ret_value_to, ret.value, loc)); } else { xls::BValue read_ready = context().fb->TupleIndex(ret.value.rvalue(), 1); xls::BValue read_value = context().fb->TupleIndex(ret.value.rvalue(), 0); if (!ret.value.type()->Is<CInternalTuple>()) { return absl::UnimplementedError( ErrorMessage(loc, "Unsupported IO op: %s", op_name)); } CValue ret_object_value; ret_object_value = CValue( read_value, ret.value.type()->As<CInternalTuple>()->fields()[0]); { PushContextGuard condition_guard(*this, loc); XLS_RETURN_IF_ERROR(and_condition(read_ready, loc)); XLS_RETURN_IF_ERROR(Assign( assign_ret_value_to, ret_object_value, loc)); } CValue ret_struct = CValue(read_ready, std::make_shared<CBoolType>()); ret.value = ret_struct; } } return ret; } } IOOpReturn ret; ret.generate_expr = true; return ret; } absl::Status Translator::ExtractExternalIOChannelDecls() { for (const auto& [decl, cval] : context().variables) { auto channel_type = dynamic_cast<const CChannelType*>(cval.type().get()); if (channel_type == nullptr) { continue; } XLS_CHECK_NE(cval.lvalue(), nullptr); XLS_CHECK_NE(cval.lvalue()->channel_leaf(), nullptr); context().sf->io_channels_by_decl[decl] = cval.lvalue()->channel_leaf(); context().sf->decls_by_io_channel[cval.lvalue()->channel_leaf()] = decl; } return absl::OkStatus(); } } // namespace xlscc <|endoftext|>
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Gearmand client and server library. * * Copyright (C) 2012 Data Differential, http://datadifferential.com/ * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "gear_config.h" #include <libgearman/common.h> #include <cstring> namespace libgearman { namespace protocol { static inline gearman_return_t __submit(gearman_task_st& task, const gearman_command_t command, const gearman_string_t &function, const gearman_string_t &workload) { const void *args[3]; size_t args_size[3]; /** @todo fix it so that NULL is done by default by the API not by happenstance. */ char function_buffer[1024]; if (task.client->universal._namespace) { char *ptr= function_buffer; memcpy(ptr, gearman_string_value(task.client->universal._namespace), gearman_string_length(task.client->universal._namespace)); ptr+= gearman_string_length(task.client->universal._namespace); memcpy(ptr, gearman_c_str(function), gearman_size(function) +1); ptr+= gearman_size(function); args[0]= function_buffer; args_size[0]= ptr -function_buffer +1; } else { args[0]= gearman_c_str(function); args_size[0]= gearman_size(function) +1; } args[1]= task.unique; args_size[1]= task.unique_length +1; args[2]= gearman_c_str(workload); args_size[2]= gearman_size(workload); return gearman_packet_create_args(task.client->universal, task.send, GEARMAN_MAGIC_REQUEST, command, args, args_size, 3); } gearman_return_t submit(gearman_task_st& task, const gearman_command_t command, const gearman_string_t &function, const gearman_string_t &workload) { return __submit(task, command, function, workload); } gearman_return_t submit_background(gearman_task_st& task, const gearman_command_t command, const gearman_string_t &function, const gearman_string_t &workload) { return __submit(task, command, function, workload); } gearman_return_t submit_epoch(gearman_task_st& task, const gearman_string_t &function, const gearman_string_t &workload, time_t when) { const void *args[4]; size_t args_size[4]; /** @todo fix it so that NULL is done by default by the API not by happenstance. */ char function_buffer[1024]; if (task.client->universal._namespace) { char *ptr= function_buffer; memcpy(ptr, gearman_string_value(task.client->universal._namespace), gearman_string_length(task.client->universal._namespace)); ptr+= gearman_string_length(task.client->universal._namespace); memcpy(ptr, gearman_c_str(function), gearman_size(function) +1); ptr+= gearman_size(function); args[0]= function_buffer; args_size[0]= ptr -function_buffer +1; } else { args[0]= gearman_c_str(function); args_size[0]= gearman_size(function) +1; } args[1]= task.unique; args_size[1]= task.unique_length +1; char time_string[30]; int length= snprintf(time_string, sizeof(time_string), "%" PRIu64, static_cast<int64_t>(when)); args[2]= time_string; args_size[2]= length +1; args[3]= gearman_c_str(workload); args_size[3]= gearman_size(workload); return gearman_packet_create_args(task.client->universal, task.send, GEARMAN_MAGIC_REQUEST, GEARMAN_COMMAND_SUBMIT_JOB_EPOCH, args, args_size, 4); } } // namespace protocol } // namespace libgearman <commit_msg>Missing stdio which is required for snprintf.<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Gearmand client and server library. * * Copyright (C) 2012 Data Differential, http://datadifferential.com/ * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "gear_config.h" #include <libgearman/common.h> #include <cstdio> #include <cstring> namespace libgearman { namespace protocol { static inline gearman_return_t __submit(gearman_task_st& task, const gearman_command_t command, const gearman_string_t &function, const gearman_string_t &workload) { const void *args[3]; size_t args_size[3]; /** @todo fix it so that NULL is done by default by the API not by happenstance. */ char function_buffer[1024]; if (task.client->universal._namespace) { char *ptr= function_buffer; memcpy(ptr, gearman_string_value(task.client->universal._namespace), gearman_string_length(task.client->universal._namespace)); ptr+= gearman_string_length(task.client->universal._namespace); memcpy(ptr, gearman_c_str(function), gearman_size(function) +1); ptr+= gearman_size(function); args[0]= function_buffer; args_size[0]= ptr -function_buffer +1; } else { args[0]= gearman_c_str(function); args_size[0]= gearman_size(function) +1; } args[1]= task.unique; args_size[1]= task.unique_length +1; args[2]= gearman_c_str(workload); args_size[2]= gearman_size(workload); return gearman_packet_create_args(task.client->universal, task.send, GEARMAN_MAGIC_REQUEST, command, args, args_size, 3); } gearman_return_t submit(gearman_task_st& task, const gearman_command_t command, const gearman_string_t &function, const gearman_string_t &workload) { return __submit(task, command, function, workload); } gearman_return_t submit_background(gearman_task_st& task, const gearman_command_t command, const gearman_string_t &function, const gearman_string_t &workload) { return __submit(task, command, function, workload); } gearman_return_t submit_epoch(gearman_task_st& task, const gearman_string_t &function, const gearman_string_t &workload, time_t when) { const void *args[4]; size_t args_size[4]; /** @todo fix it so that NULL is done by default by the API not by happenstance. */ char function_buffer[1024]; if (task.client->universal._namespace) { char *ptr= function_buffer; memcpy(ptr, gearman_string_value(task.client->universal._namespace), gearman_string_length(task.client->universal._namespace)); ptr+= gearman_string_length(task.client->universal._namespace); memcpy(ptr, gearman_c_str(function), gearman_size(function) +1); ptr+= gearman_size(function); args[0]= function_buffer; args_size[0]= ptr -function_buffer +1; } else { args[0]= gearman_c_str(function); args_size[0]= gearman_size(function) +1; } args[1]= task.unique; args_size[1]= task.unique_length +1; char time_string[30]; int length= snprintf(time_string, sizeof(time_string), "%" PRIu64, static_cast<int64_t>(when)); args[2]= time_string; args_size[2]= length +1; args[3]= gearman_c_str(workload); args_size[3]= gearman_size(workload); return gearman_packet_create_args(task.client->universal, task.send, GEARMAN_MAGIC_REQUEST, GEARMAN_COMMAND_SUBMIT_JOB_EPOCH, args, args_size, 4); } } // namespace protocol } // namespace libgearman <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2012 Artem Pavlenko * * This 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. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP #define MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP // mapnik #include <mapnik/global.hpp> #include <mapnik/geometry.hpp> #include <mapnik/util/path_iterator.hpp> #include <mapnik/util/container_adapter.hpp> #include <mapnik/vertex.hpp> // for CommandType::SEG_MOVETO // boost #include <boost/tuple/tuple.hpp> #include <boost/spirit/include/karma.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/spirit/include/phoenix_function.hpp> #include <boost/spirit/include/phoenix_statement.hpp> #include <boost/fusion/include/boost_tuple.hpp> #include <boost/math/special_functions/trunc.hpp> // for vc++ namespace boost { namespace spirit { namespace traits { // make gcc and darwin toolsets happy. template <> struct is_container<mapnik::geometry_container> : mpl::false_ {}; }}} namespace mapnik { namespace json { namespace karma = boost::spirit::karma; namespace phoenix = boost::phoenix; namespace { #ifdef BOOST_SPIRIT_USE_PHOENIX_V3 struct get_type { typedef int result_type; result_type operator() (geometry_type const& geom) const { return static_cast<int>(geom.type()); } }; struct get_first { typedef geometry_type::value_type const result_type; result_type operator() (geometry_type const& geom) const { geometry_type::value_type coord; boost::get<0>(coord) = geom.vertex(0,&boost::get<1>(coord),&boost::get<2>(coord)); return coord; } }; struct multi_geometry_type { typedef boost::tuple<unsigned,bool> result_type; result_type operator() (geometry_container const& geom) const { unsigned type = 0u; bool collection = false; geometry_container::const_iterator itr = geom.begin(); geometry_container::const_iterator end = geom.end(); for ( ; itr != end; ++itr) { if (type != 0u && itr->type() != type) { collection = true; break; } type = itr->type(); } if (geom.size() > 1) type +=3; return boost::tuple<unsigned,bool>(type, collection); } }; #else struct get_type { template <typename T> struct result { typedef int type; }; int operator() (geometry_type const& geom) const { return static_cast<int>(geom.type()); } }; struct get_first { template <typename T> struct result { typedef geometry_type::value_type const type; }; geometry_type::value_type const operator() (geometry_type const& geom) const { geometry_type::value_type coord; boost::get<0>(coord) = geom.vertex(0,&boost::get<1>(coord),&boost::get<2>(coord)); return coord; } }; struct multi_geometry_type { template <typename T> struct result { typedef boost::tuple<unsigned,bool> type; }; boost::tuple<unsigned,bool> operator() (geometry_container const& geom) const { unsigned type = 0u; bool collection = false; geometry_container::const_iterator itr = geom.begin(); geometry_container::const_iterator end = geom.end(); for ( ; itr != end; ++itr) { if (type != 0u && itr->type() != type) { collection = true; break; } type = itr->type(); } if (geom.size() > 1) type +=3; return boost::tuple<unsigned,bool>(type, collection); } }; #endif template <typename T> struct json_coordinate_policy : karma::real_policies<T> { typedef boost::spirit::karma::real_policies<T> base_type; static int floatfield(T n) { return base_type::fmtflags::fixed; } static unsigned precision(T n) { if (n == 0.0) return 0; using namespace boost::spirit; return static_cast<unsigned>(14 - boost::math::trunc(log10(traits::get_absolute_value(n)))); } template <typename OutputIterator> static bool dot(OutputIterator& sink, T n, unsigned precision) { if (n == 0) return true; return base_type::dot(sink, n, precision); } template <typename OutputIterator> static bool fraction_part(OutputIterator& sink, T n , unsigned adjprec, unsigned precision) { if (n == 0) return true; return base_type::fraction_part(sink, n, adjprec, precision); } }; } template <typename OutputIterator> struct geometry_generator_grammar : karma::grammar<OutputIterator, geometry_type const& ()> { geometry_generator_grammar() : geometry_generator_grammar::base_type(coordinates) { using boost::spirit::karma::uint_; using boost::spirit::karma::_val; using boost::spirit::karma::_1; using boost::spirit::karma::lit; using boost::spirit::karma::_a; using boost::spirit::karma::_r1; using boost::spirit::karma::eps; coordinates = point | linestring | polygon ; point = &uint_(mapnik::Point)[_1 = _type(_val)] << point_coord [_1 = _first(_val)] ; linestring = &uint_(mapnik::LineString)[_1 = _type(_val)] << lit('[') << coords << lit(']') ; polygon = &uint_(mapnik::Polygon)[_1 = _type(_val)] << lit('[') << coords2 << lit("]]") ; point_coord = &uint_ << lit('[') << coord_type << lit(',') << coord_type << lit("]") ; polygon_coord %= ( &uint_(mapnik::SEG_MOVETO) << eps[_r1 += 1] << karma::string[ if_ (_r1 > 1) [_1 = "],["] .else_[_1 = '[' ]] | &uint_(mapnik::SEG_LINETO)) << lit(',') << lit('[') << coord_type << lit(',') << coord_type << lit(']') ; coords2 %= *polygon_coord(_a) ; coords = point_coord % lit(',') ; } // rules karma::rule<OutputIterator, geometry_type const& ()> coordinates; karma::rule<OutputIterator, geometry_type const& ()> point; karma::rule<OutputIterator, geometry_type const& ()> linestring; karma::rule<OutputIterator, geometry_type const& ()> polygon; karma::rule<OutputIterator, geometry_type const& ()> coords; karma::rule<OutputIterator, karma::locals<unsigned>, geometry_type const& ()> coords2; karma::rule<OutputIterator, geometry_type::value_type ()> point_coord; karma::rule<OutputIterator, geometry_type::value_type (unsigned& )> polygon_coord; // phoenix functions phoenix::function<get_type > _type; phoenix::function<get_first> _first; // karma::real_generator<double, json_coordinate_policy<double> > coord_type; }; template <typename OutputIterator> struct multi_geometry_generator_grammar : karma::grammar<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const& ()> { multi_geometry_generator_grammar() : multi_geometry_generator_grammar::base_type(start) { using boost::spirit::karma::lit; using boost::spirit::karma::eps; using boost::spirit::karma::_val; using boost::spirit::karma::_1; using boost::spirit::karma::_a; using boost::spirit::karma::_r1; geometry_types.add (mapnik::Point,"\"Point\"") (mapnik::LineString,"\"LineString\"") (mapnik::Polygon,"\"Polygon\"") (mapnik::Point + 3,"\"MultiPoint\"") (mapnik::LineString + 3,"\"MultiLineString\"") (mapnik::Polygon + 3,"\"MultiPolygon\"") ; start %= ( eps(phoenix::at_c<1>(_a))[_a = _multi_type(_val)] << lit("{\"type\":\"GeometryCollection\",\"geometries\":[") << geometry_collection << lit("]}") | geometry) ; geometry_collection = -(geometry2 % lit(',')) ; geometry = (lit("{\"type\":") << geometry_types[_1 = phoenix::at_c<0>(_a)][_a = _multi_type(_val)] << lit(",\"coordinates\":") << karma::string[ phoenix::if_ (phoenix::at_c<0>(_a) > 3) [_1 = '['].else_[_1 = ""]] << coordinates << karma::string[ phoenix::if_ (phoenix::at_c<0>(_a) > 3) [_1 = ']'].else_[_1 = ""]] << lit('}')) | lit("null") ; geometry2 = lit("{\"type\":") << geometry_types[_1 = _a][_a = type_(_val)] << lit(",\"coordinates\":") << path << lit('}') ; coordinates %= path % lit(',') ; } // rules karma::rule<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const&()> start; karma::rule<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const&()> geometry_collection; karma::rule<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const&()> geometry; karma::rule<OutputIterator, karma::locals<unsigned>, geometry_type const&()> geometry2; karma::rule<OutputIterator, geometry_container const&()> coordinates; geometry_generator_grammar<OutputIterator> path; // phoenix phoenix::function<multi_geometry_type> _multi_type; phoenix::function<get_type > type_; // symbols table karma::symbols<unsigned, char const*> geometry_types; }; }} #endif // MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP <commit_msg>fix sign compare warning<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2012 Artem Pavlenko * * This 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. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP #define MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP // mapnik #include <mapnik/global.hpp> #include <mapnik/geometry.hpp> #include <mapnik/util/path_iterator.hpp> #include <mapnik/util/container_adapter.hpp> #include <mapnik/vertex.hpp> // for CommandType::SEG_MOVETO // boost #include <boost/tuple/tuple.hpp> #include <boost/spirit/include/karma.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/spirit/include/phoenix_function.hpp> #include <boost/spirit/include/phoenix_statement.hpp> #include <boost/fusion/include/boost_tuple.hpp> #include <boost/math/special_functions/trunc.hpp> // for vc++ namespace boost { namespace spirit { namespace traits { // make gcc and darwin toolsets happy. template <> struct is_container<mapnik::geometry_container> : mpl::false_ {}; }}} namespace mapnik { namespace json { namespace karma = boost::spirit::karma; namespace phoenix = boost::phoenix; namespace { #ifdef BOOST_SPIRIT_USE_PHOENIX_V3 struct get_type { typedef int result_type; result_type operator() (geometry_type const& geom) const { return static_cast<int>(geom.type()); } }; struct get_first { typedef geometry_type::value_type const result_type; result_type operator() (geometry_type const& geom) const { geometry_type::value_type coord; boost::get<0>(coord) = geom.vertex(0,&boost::get<1>(coord),&boost::get<2>(coord)); return coord; } }; struct multi_geometry_type { typedef boost::tuple<unsigned,bool> result_type; result_type operator() (geometry_container const& geom) const { unsigned type = 0u; bool collection = false; geometry_container::const_iterator itr = geom.begin(); geometry_container::const_iterator end = geom.end(); for ( ; itr != end; ++itr) { if (type != 0u && itr->type() != type) { collection = true; break; } type = itr->type(); } if (geom.size() > 1) type +=3; return boost::tuple<unsigned,bool>(type, collection); } }; #else struct get_type { template <typename T> struct result { typedef int type; }; int operator() (geometry_type const& geom) const { return static_cast<int>(geom.type()); } }; struct get_first { template <typename T> struct result { typedef geometry_type::value_type const type; }; geometry_type::value_type const operator() (geometry_type const& geom) const { geometry_type::value_type coord; boost::get<0>(coord) = geom.vertex(0,&boost::get<1>(coord),&boost::get<2>(coord)); return coord; } }; struct multi_geometry_type { template <typename T> struct result { typedef boost::tuple<unsigned,bool> type; }; boost::tuple<unsigned,bool> operator() (geometry_container const& geom) const { unsigned type = 0u; bool collection = false; geometry_container::const_iterator itr = geom.begin(); geometry_container::const_iterator end = geom.end(); for ( ; itr != end; ++itr) { if (type != 0u && static_cast<unsigned>(itr->type()) != type) { collection = true; break; } type = itr->type(); } if (geom.size() > 1) type +=3; return boost::tuple<unsigned,bool>(type, collection); } }; #endif template <typename T> struct json_coordinate_policy : karma::real_policies<T> { typedef boost::spirit::karma::real_policies<T> base_type; static int floatfield(T n) { return base_type::fmtflags::fixed; } static unsigned precision(T n) { if (n == 0.0) return 0; using namespace boost::spirit; return static_cast<unsigned>(14 - boost::math::trunc(log10(traits::get_absolute_value(n)))); } template <typename OutputIterator> static bool dot(OutputIterator& sink, T n, unsigned precision) { if (n == 0) return true; return base_type::dot(sink, n, precision); } template <typename OutputIterator> static bool fraction_part(OutputIterator& sink, T n , unsigned adjprec, unsigned precision) { if (n == 0) return true; return base_type::fraction_part(sink, n, adjprec, precision); } }; } template <typename OutputIterator> struct geometry_generator_grammar : karma::grammar<OutputIterator, geometry_type const& ()> { geometry_generator_grammar() : geometry_generator_grammar::base_type(coordinates) { using boost::spirit::karma::uint_; using boost::spirit::karma::_val; using boost::spirit::karma::_1; using boost::spirit::karma::lit; using boost::spirit::karma::_a; using boost::spirit::karma::_r1; using boost::spirit::karma::eps; coordinates = point | linestring | polygon ; point = &uint_(mapnik::Point)[_1 = _type(_val)] << point_coord [_1 = _first(_val)] ; linestring = &uint_(mapnik::LineString)[_1 = _type(_val)] << lit('[') << coords << lit(']') ; polygon = &uint_(mapnik::Polygon)[_1 = _type(_val)] << lit('[') << coords2 << lit("]]") ; point_coord = &uint_ << lit('[') << coord_type << lit(',') << coord_type << lit("]") ; polygon_coord %= ( &uint_(mapnik::SEG_MOVETO) << eps[_r1 += 1] << karma::string[ if_ (_r1 > 1) [_1 = "],["] .else_[_1 = '[' ]] | &uint_(mapnik::SEG_LINETO)) << lit(',') << lit('[') << coord_type << lit(',') << coord_type << lit(']') ; coords2 %= *polygon_coord(_a) ; coords = point_coord % lit(',') ; } // rules karma::rule<OutputIterator, geometry_type const& ()> coordinates; karma::rule<OutputIterator, geometry_type const& ()> point; karma::rule<OutputIterator, geometry_type const& ()> linestring; karma::rule<OutputIterator, geometry_type const& ()> polygon; karma::rule<OutputIterator, geometry_type const& ()> coords; karma::rule<OutputIterator, karma::locals<unsigned>, geometry_type const& ()> coords2; karma::rule<OutputIterator, geometry_type::value_type ()> point_coord; karma::rule<OutputIterator, geometry_type::value_type (unsigned& )> polygon_coord; // phoenix functions phoenix::function<get_type > _type; phoenix::function<get_first> _first; // karma::real_generator<double, json_coordinate_policy<double> > coord_type; }; template <typename OutputIterator> struct multi_geometry_generator_grammar : karma::grammar<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const& ()> { multi_geometry_generator_grammar() : multi_geometry_generator_grammar::base_type(start) { using boost::spirit::karma::lit; using boost::spirit::karma::eps; using boost::spirit::karma::_val; using boost::spirit::karma::_1; using boost::spirit::karma::_a; using boost::spirit::karma::_r1; geometry_types.add (mapnik::Point,"\"Point\"") (mapnik::LineString,"\"LineString\"") (mapnik::Polygon,"\"Polygon\"") (mapnik::Point + 3,"\"MultiPoint\"") (mapnik::LineString + 3,"\"MultiLineString\"") (mapnik::Polygon + 3,"\"MultiPolygon\"") ; start %= ( eps(phoenix::at_c<1>(_a))[_a = _multi_type(_val)] << lit("{\"type\":\"GeometryCollection\",\"geometries\":[") << geometry_collection << lit("]}") | geometry) ; geometry_collection = -(geometry2 % lit(',')) ; geometry = (lit("{\"type\":") << geometry_types[_1 = phoenix::at_c<0>(_a)][_a = _multi_type(_val)] << lit(",\"coordinates\":") << karma::string[ phoenix::if_ (phoenix::at_c<0>(_a) > 3) [_1 = '['].else_[_1 = ""]] << coordinates << karma::string[ phoenix::if_ (phoenix::at_c<0>(_a) > 3) [_1 = ']'].else_[_1 = ""]] << lit('}')) | lit("null") ; geometry2 = lit("{\"type\":") << geometry_types[_1 = _a][_a = type_(_val)] << lit(",\"coordinates\":") << path << lit('}') ; coordinates %= path % lit(',') ; } // rules karma::rule<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const&()> start; karma::rule<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const&()> geometry_collection; karma::rule<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const&()> geometry; karma::rule<OutputIterator, karma::locals<unsigned>, geometry_type const&()> geometry2; karma::rule<OutputIterator, geometry_container const&()> coordinates; geometry_generator_grammar<OutputIterator> path; // phoenix phoenix::function<multi_geometry_type> _multi_type; phoenix::function<get_type > type_; // symbols table karma::symbols<unsigned, char const*> geometry_types; }; }} #endif // MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP <|endoftext|>
<commit_before>#include <cstring> namespace accelergy { void invokeAccelergy(std::vector<std::string> inputFiles) { #ifdef ACCELERGY_PATH std::string cmd = std::string(ACCELERGY_PATH) + "/accelergy"; for (auto inputFile : inputFiles) { cmd += " " + inputFile; } cmd += " -o ./ > ./accelergy.log 2>&1"; int ret = system(cmd.c_str()); if (ret) { std::cout << "Cannot invoke Accelergy. Do you specify ACCELERGYPATH correctly?" << std::endl; exit(0); } #else (void) inputFiles; #endif return; } } // namespace accelergy <commit_msg>[accelergy_interface] better error message<commit_after>#include <cstring> namespace accelergy { void invokeAccelergy(std::vector<std::string> inputFiles) { #ifdef ACCELERGY_PATH std::string cmd = std::string(ACCELERGY_PATH) + "/accelergy"; for (auto inputFile : inputFiles) { cmd += " " + inputFile; } cmd += " -o ./ > ./accelergy.log 2>&1"; int ret = system(cmd.c_str()); if (ret) { std::cout << "Cannot invoke Accelergy. Do you specify ACCELERGYPATH correctly? Or check accelergy.log to see what went wrong" << std::endl; exit(0); } #else (void) inputFiles; #endif return; } } // namespace accelergy <|endoftext|>
<commit_before>/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "ProxyDestination.h" #include <folly/Conv.h> #include <folly/Memory.h> #include "mcrouter/config-impl.h" #include "mcrouter/config.h" #include "mcrouter/lib/fbi/asox_timer.h" #include "mcrouter/lib/fbi/nstring.h" #include "mcrouter/lib/fbi/timer.h" #include "mcrouter/lib/fbi/util.h" #include "mcrouter/lib/fibers/Fiber.h" #include "mcrouter/lib/network/AsyncMcClient.h" #include "mcrouter/pclient.h" #include "mcrouter/ProxyClientCommon.h" #include "mcrouter/routes/DestinationRoute.h" #include "mcrouter/stats.h" #include "mcrouter/TkoTracker.h" namespace facebook { namespace memcache { namespace mcrouter { namespace { constexpr double kProbeExponentialFactor = 1.5; constexpr double kProbeJitterMin = 0.05; constexpr double kProbeJitterMax = 0.5; constexpr double kProbeJitterDelta = kProbeJitterMax - kProbeJitterMin; static_assert(kProbeJitterMax >= kProbeJitterMin, "ProbeJitterMax should be greater or equal tham ProbeJitterMin"); void on_probe_timer(const asox_timer_t timer, void* arg) { ProxyDestination* pdstn = (ProxyDestination*)arg; pdstn->on_timer(timer); } } // anonymous namespace void ProxyDestination::schedule_next_probe() { FBI_ASSERT(proxy->magic == proxy_magic); FBI_ASSERT(!proxy->opts.disable_tko_tracking); int delay_ms = probe_delay_next_ms; if (probe_delay_next_ms < 2) { // int(1 * 1.5) == 1, so advance it to 2 first probe_delay_next_ms = 2; } else { probe_delay_next_ms *= kProbeExponentialFactor; } if (probe_delay_next_ms > proxy->opts.probe_delay_max_ms) { probe_delay_next_ms = proxy->opts.probe_delay_max_ms; } // Calculate random jitter double r = (double)rand() / (double)RAND_MAX; double tmo_jitter_pct = r * kProbeJitterDelta + kProbeJitterMin; uint64_t delay_us = (double)delay_ms * 1000 * (1.0 + tmo_jitter_pct); FBI_ASSERT(delay_us > 0); timeval_t delay; delay.tv_sec = (delay_us / 1000000); delay.tv_usec = (delay_us % 1000000); FBI_ASSERT(probe_timer == nullptr); probe_timer = asox_add_timer(proxy->eventBase->getLibeventBase(), delay, on_probe_timer, this); } void ProxyDestination::on_timer(const asox_timer_t timer) { // This assert checks for use-after-free FBI_ASSERT(proxy->magic == proxy_magic); FBI_ASSERT(timer == probe_timer); asox_remove_timer(timer); probe_timer = nullptr; if (sending_probes) { // Note that the previous probe might still be in flight if (!probe_req) { auto mutReq = createMcMsgRef(); mutReq->op = mc_op_version; probe_req = folly::make_unique<McRequest>(std::move(mutReq)); ++probesSent_; auto selfPtr = selfPtr_; proxy->fiberManager.addTask([selfPtr]() mutable { auto pdstn = selfPtr.lock(); if (pdstn == nullptr) { return; } pdstn->proxy->destinationMap->markAsActive(*pdstn); McReply reply = pdstn->client_->send(*pdstn->probe_req, McOperation<mc_op_version>(), 0, pdstn->shortestTimeout); pdstn->handle_tko(reply, true); pdstn->probe_req.reset(); }); } schedule_next_probe(); } } void ProxyDestination::start_sending_probes() { FBI_ASSERT(!sending_probes); sending_probes = true; probe_delay_next_ms = proxy->opts.probe_delay_initial_ms; schedule_next_probe(); } void ProxyDestination::stop_sending_probes() { probesSent_ = 0; sending_probes = false; if (probe_timer) { asox_remove_timer(probe_timer); probe_timer = nullptr; } } void ProxyDestination::unmark_tko(const McReply& reply) { FBI_ASSERT(!proxy->opts.disable_tko_tracking); shared->tko.recordSuccess(this); if (sending_probes) { onTkoEvent(TkoLogEvent::UnMarkTko, reply.result()); stop_sending_probes(); } } void ProxyDestination::handle_tko(const McReply& reply, bool is_probe_req) { if (resetting || proxy->opts.disable_tko_tracking) { return; } bool responsible = false; if (reply.isError()) { if (reply.isHardTkoError()) { responsible = shared->tko.recordHardFailure(this); if (responsible) { onTkoEvent(TkoLogEvent::MarkHardTko, reply.result()); } } else if (reply.isSoftTkoError()) { responsible = shared->tko.recordSoftFailure(this); if (responsible) { onTkoEvent(TkoLogEvent::MarkSoftTko, reply.result()); } } } else if (!sending_probes || is_probe_req) { /* If we're sending probes, only a probe request should be considered successful to avoid outstanding requests from unmarking the box */ unmark_tko(reply); } if (responsible) { start_sending_probes(); } } void ProxyDestination::onReply(const McReply& reply, DestinationRequestCtx& destreqCtx) { FBI_ASSERT(proxy->magic == proxy_magic); handle_tko(reply, false); stats_.results[reply.result()]++; destreqCtx.endTime = nowUs(); /* For code simplicity we look at latency for making TKO decisions with a 1 request delay */ int64_t latency = destreqCtx.endTime - destreqCtx.startTime; stats_.avgLatency.insertSample(latency); stat_decr(proxy->stats, sum_server_queue_length_stat, 1); } void ProxyDestination::on_up() { FBI_ASSERT(proxy->magic == proxy_magic); FBI_ASSERT(stats_.state != ProxyDestinationState::kUp); stat_incr(proxy->stats, server_up_events_stat, 1); setState(ProxyDestinationState::kUp); VLOG(1) << "server " << pdstnKey << " up (" << stat_get_uint64(proxy->stats, num_servers_up_stat) << " of " << stat_get_uint64(proxy->stats, num_servers_stat) << ")"; } void ProxyDestination::on_down() { FBI_ASSERT(proxy->magic == proxy_magic); if (resetting) { VLOG(1) << "server " << pdstnKey << " inactive (" << stat_get_uint64(proxy->stats, num_servers_up_stat) << " of " << stat_get_uint64(proxy->stats, num_servers_stat) << ")"; setState(ProxyDestinationState::kClosed); } else { VLOG(1) << "server " << pdstnKey << " down (" << stat_get_uint64(proxy->stats, num_servers_up_stat) << " of " << stat_get_uint64(proxy->stats, num_servers_stat) << ")"; setState(ProxyDestinationState::kDown); handle_tko(McReply(mc_res_connect_error), /* is_probe_req= */ false); } } size_t ProxyDestination::getPendingRequestCount() const { return client_->getPendingRequestCount(); } size_t ProxyDestination::getInflightRequestCount() const { return client_->getInflightRequestCount(); } std::pair<uint64_t, uint64_t> ProxyDestination::getBatchingStat() const { return client_->getBatchingStat(); } std::shared_ptr<ProxyDestination> ProxyDestination::create( proxy_t* proxy, const ProxyClientCommon& ro, std::string pdstnKey) { auto ptr = std::shared_ptr<ProxyDestination>( new ProxyDestination(proxy, ro, std::move(pdstnKey))); ptr->selfPtr_ = ptr; ptr->client_ = folly::make_unique<DestinationMcClient>(*ptr); return ptr; } ProxyDestination::~ProxyDestination() { shared->removeDestination(this); if (proxy->destinationMap) { proxy->destinationMap->removeDestination(*this); } // should not call 'handle_tko' resetting = 1; client_.reset(); if (sending_probes) { onTkoEvent(TkoLogEvent::RemoveFromConfig, mc_res_ok); stop_sending_probes(); } magic = kDeadBeef; } ProxyDestination::ProxyDestination(proxy_t* proxy_, const ProxyClientCommon& ro_, std::string pdstnKey_) : proxy(proxy_), accessPoint(ro_.ap), destinationKey(ro_.destination_key), shortestTimeout(ro_.server_timeout), pdstnKey(std::move(pdstnKey_)), proxy_magic(proxy->magic), use_ssl(ro_.useSsl), qos(ro_.qos), stats_(proxy_->opts) { static uint64_t next_magic = 0x12345678900000LL; magic = __sync_fetch_and_add(&next_magic, 1); stat_incr(proxy->stats, num_servers_new_stat, 1); } ProxyDestinationState ProxyDestination::state() const { if (shared->tko.isTko()) { return ProxyDestinationState::kTko; } return stats_.state; } const ProxyDestinationStats& ProxyDestination::stats() const { return stats_; } bool ProxyDestination::may_send() { FBI_ASSERT(proxy->magic == proxy_magic); return !shared->tko.isTko(); } void ProxyDestination::resetInactive() { FBI_ASSERT(proxy->magic == proxy_magic); resetting = 1; client_->resetInactive(); resetting = 0; } void ProxyDestination::onTkoEvent(TkoLogEvent event, mc_res_t result) const { auto logUtil = [this, result](folly::StringPiece eventStr) { VLOG(1) << shared->key << " " << eventStr << ". Total hard TKOs: " << shared->tko.globalTkos().hardTkos << "; soft TKOs: " << shared->tko.globalTkos().softTkos << ". Reply: " << mc_res_to_string(result); }; switch (event) { case TkoLogEvent::MarkHardTko: logUtil("marked hard TKO"); break; case TkoLogEvent::MarkSoftTko: logUtil("marked soft TKO"); break; case TkoLogEvent::UnMarkTko: logUtil("unmarked TKO"); break; case TkoLogEvent::RemoveFromConfig: logUtil("was TKO, removed from config"); break; } TkoLog tkoLog(accessPoint, shared->tko.globalTkos()); tkoLog.event = event; tkoLog.isHardTko = shared->tko.isHardTko(); tkoLog.isSoftTko = shared->tko.isSoftTko(); tkoLog.avgLatency = stats_.avgLatency.value(); tkoLog.probesSent = probesSent_; tkoLog.result = result; logTkoEvent(proxy, tkoLog); } void ProxyDestination::setState(ProxyDestinationState new_st) { auto old_st = stats_.state; if (old_st != new_st) { auto getStatName = [](ProxyDestinationState st) { switch (st) { case ProxyDestinationState::kNew: return num_servers_new_stat; case ProxyDestinationState::kUp: return num_servers_up_stat; case ProxyDestinationState::kClosed: return num_servers_closed_stat; case ProxyDestinationState::kDown: return num_servers_down_stat; default: CHECK(false); return num_stats; // shouldnt reach here } }; auto old_name = getStatName(old_st); auto new_name = getStatName(new_st); stat_decr(proxy->stats, old_name, 1); stat_incr(proxy->stats, new_name, 1); stats_.state = new_st; } } ProxyDestinationStats::ProxyDestinationStats(const McrouterOptions& opts) : avgLatency(1.0 / opts.latency_window_size) { } void ProxyDestination::updateShortestTimeout( std::chrono::milliseconds timeout) { if (!timeout.count()) { return; } if (shortestTimeout.count() == 0 || shortestTimeout > timeout) { shortestTimeout = timeout; } client_->updateWriteTimeout(); } }}} // facebook::memcache::mcrouter <commit_msg>Fix mcrouter_startup<commit_after>/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "ProxyDestination.h" #include <folly/Conv.h> #include <folly/Memory.h> #include "mcrouter/config-impl.h" #include "mcrouter/config.h" #include "mcrouter/lib/fbi/asox_timer.h" #include "mcrouter/lib/fbi/nstring.h" #include "mcrouter/lib/fbi/timer.h" #include "mcrouter/lib/fbi/util.h" #include "mcrouter/lib/fibers/Fiber.h" #include "mcrouter/lib/network/AsyncMcClient.h" #include "mcrouter/pclient.h" #include "mcrouter/ProxyClientCommon.h" #include "mcrouter/routes/DestinationRoute.h" #include "mcrouter/stats.h" #include "mcrouter/TkoTracker.h" namespace facebook { namespace memcache { namespace mcrouter { namespace { constexpr double kProbeExponentialFactor = 1.5; constexpr double kProbeJitterMin = 0.05; constexpr double kProbeJitterMax = 0.5; constexpr double kProbeJitterDelta = kProbeJitterMax - kProbeJitterMin; static_assert(kProbeJitterMax >= kProbeJitterMin, "ProbeJitterMax should be greater or equal tham ProbeJitterMin"); void on_probe_timer(const asox_timer_t timer, void* arg) { ProxyDestination* pdstn = (ProxyDestination*)arg; pdstn->on_timer(timer); } } // anonymous namespace void ProxyDestination::schedule_next_probe() { FBI_ASSERT(proxy->magic == proxy_magic); FBI_ASSERT(!proxy->opts.disable_tko_tracking); int delay_ms = probe_delay_next_ms; if (probe_delay_next_ms < 2) { // int(1 * 1.5) == 1, so advance it to 2 first probe_delay_next_ms = 2; } else { probe_delay_next_ms *= kProbeExponentialFactor; } if (probe_delay_next_ms > proxy->opts.probe_delay_max_ms) { probe_delay_next_ms = proxy->opts.probe_delay_max_ms; } // Calculate random jitter double r = (double)rand() / (double)RAND_MAX; double tmo_jitter_pct = r * kProbeJitterDelta + kProbeJitterMin; uint64_t delay_us = (double)delay_ms * 1000 * (1.0 + tmo_jitter_pct); FBI_ASSERT(delay_us > 0); timeval_t delay; delay.tv_sec = (delay_us / 1000000); delay.tv_usec = (delay_us % 1000000); FBI_ASSERT(probe_timer == nullptr); probe_timer = asox_add_timer(proxy->eventBase->getLibeventBase(), delay, on_probe_timer, this); } void ProxyDestination::on_timer(const asox_timer_t timer) { // This assert checks for use-after-free FBI_ASSERT(proxy->magic == proxy_magic); FBI_ASSERT(timer == probe_timer); asox_remove_timer(timer); probe_timer = nullptr; if (sending_probes) { // Note that the previous probe might still be in flight if (!probe_req) { auto mutReq = createMcMsgRef(); mutReq->op = mc_op_version; probe_req = folly::make_unique<McRequest>(std::move(mutReq)); ++probesSent_; auto selfPtr = selfPtr_; proxy->fiberManager.addTask([selfPtr]() mutable { auto pdstn = selfPtr.lock(); if (pdstn == nullptr) { return; } pdstn->proxy->destinationMap->markAsActive(*pdstn); McReply reply = pdstn->client_->send(*pdstn->probe_req, McOperation<mc_op_version>(), 0, pdstn->shortestTimeout); pdstn->handle_tko(reply, true); pdstn->probe_req.reset(); }); } schedule_next_probe(); } } void ProxyDestination::start_sending_probes() { FBI_ASSERT(!sending_probes); sending_probes = true; probe_delay_next_ms = proxy->opts.probe_delay_initial_ms; schedule_next_probe(); } void ProxyDestination::stop_sending_probes() { probesSent_ = 0; sending_probes = false; if (probe_timer) { asox_remove_timer(probe_timer); probe_timer = nullptr; } } void ProxyDestination::unmark_tko(const McReply& reply) { FBI_ASSERT(!proxy->opts.disable_tko_tracking); shared->tko.recordSuccess(this); if (sending_probes) { onTkoEvent(TkoLogEvent::UnMarkTko, reply.result()); stop_sending_probes(); } } void ProxyDestination::handle_tko(const McReply& reply, bool is_probe_req) { if (resetting || proxy->opts.disable_tko_tracking) { return; } bool responsible = false; if (reply.isError()) { if (reply.isHardTkoError()) { responsible = shared->tko.recordHardFailure(this); if (responsible) { onTkoEvent(TkoLogEvent::MarkHardTko, reply.result()); } } else if (reply.isSoftTkoError()) { responsible = shared->tko.recordSoftFailure(this); if (responsible) { onTkoEvent(TkoLogEvent::MarkSoftTko, reply.result()); } } } else if (!sending_probes || is_probe_req) { /* If we're sending probes, only a probe request should be considered successful to avoid outstanding requests from unmarking the box */ unmark_tko(reply); } if (responsible) { start_sending_probes(); } } void ProxyDestination::onReply(const McReply& reply, DestinationRequestCtx& destreqCtx) { FBI_ASSERT(proxy->magic == proxy_magic); handle_tko(reply, false); stats_.results[reply.result()]++; destreqCtx.endTime = nowUs(); /* For code simplicity we look at latency for making TKO decisions with a 1 request delay */ int64_t latency = destreqCtx.endTime - destreqCtx.startTime; stats_.avgLatency.insertSample(latency); stat_decr(proxy->stats, sum_server_queue_length_stat, 1); } void ProxyDestination::on_up() { FBI_ASSERT(proxy->magic == proxy_magic); FBI_ASSERT(stats_.state != ProxyDestinationState::kUp); stat_incr(proxy->stats, server_up_events_stat, 1); setState(ProxyDestinationState::kUp); VLOG(1) << "server " << pdstnKey << " up (" << stat_get_uint64(proxy->stats, num_servers_up_stat) << " of " << stat_get_uint64(proxy->stats, num_servers_stat) << ")"; } void ProxyDestination::on_down() { FBI_ASSERT(proxy->magic == proxy_magic); if (resetting) { VLOG(1) << "server " << pdstnKey << " inactive (" << stat_get_uint64(proxy->stats, num_servers_up_stat) << " of " << stat_get_uint64(proxy->stats, num_servers_stat) << ")"; setState(ProxyDestinationState::kClosed); } else { VLOG(1) << "server " << pdstnKey << " down (" << stat_get_uint64(proxy->stats, num_servers_up_stat) << " of " << stat_get_uint64(proxy->stats, num_servers_stat) << ")"; setState(ProxyDestinationState::kDown); handle_tko(McReply(mc_res_connect_error), /* is_probe_req= */ false); } } size_t ProxyDestination::getPendingRequestCount() const { return client_->getPendingRequestCount(); } size_t ProxyDestination::getInflightRequestCount() const { return client_->getInflightRequestCount(); } std::pair<uint64_t, uint64_t> ProxyDestination::getBatchingStat() const { return client_->getBatchingStat(); } std::shared_ptr<ProxyDestination> ProxyDestination::create( proxy_t* proxy, const ProxyClientCommon& ro, std::string pdstnKey) { auto ptr = std::shared_ptr<ProxyDestination>( new ProxyDestination(proxy, ro, std::move(pdstnKey))); ptr->selfPtr_ = ptr; ptr->client_ = folly::make_unique<DestinationMcClient>(*ptr); return ptr; } ProxyDestination::~ProxyDestination() { shared->removeDestination(this); if (proxy->destinationMap) { proxy->destinationMap->removeDestination(*this); } // should not call 'handle_tko' resetting = 1; client_.reset(); if (sending_probes) { onTkoEvent(TkoLogEvent::RemoveFromConfig, mc_res_ok); stop_sending_probes(); } magic = kDeadBeef; } ProxyDestination::ProxyDestination(proxy_t* proxy_, const ProxyClientCommon& ro_, std::string pdstnKey_) : proxy(proxy_), accessPoint(ro_.ap), destinationKey(ro_.destination_key), shortestTimeout(ro_.server_timeout), pdstnKey(std::move(pdstnKey_)), proxy_magic(proxy->magic), use_ssl(ro_.useSsl), qos(ro_.qos), stats_(proxy_->opts) { static uint64_t next_magic = 0x12345678900000LL; magic = __sync_fetch_and_add(&next_magic, 1); stat_incr(proxy->stats, num_servers_new_stat, 1); } ProxyDestinationState ProxyDestination::state() const { if (shared->tko.isTko()) { return ProxyDestinationState::kTko; } return stats_.state; } const ProxyDestinationStats& ProxyDestination::stats() const { return stats_; } bool ProxyDestination::may_send() { FBI_ASSERT(proxy->magic == proxy_magic); return !shared->tko.isTko(); } void ProxyDestination::resetInactive() { FBI_ASSERT(proxy->magic == proxy_magic); resetting = 1; client_->resetInactive(); resetting = 0; } void ProxyDestination::onTkoEvent(TkoLogEvent event, mc_res_t result) const { auto logUtil = [this, result](folly::StringPiece eventStr) { VLOG(1) << shared->key << " " << eventStr << ". Total hard TKOs: " << shared->tko.globalTkos().hardTkos << "; soft TKOs: " << shared->tko.globalTkos().softTkos << ". Reply: " << mc_res_to_string(result); }; switch (event) { case TkoLogEvent::MarkHardTko: logUtil("marked hard TKO"); break; case TkoLogEvent::MarkSoftTko: logUtil("marked soft TKO"); break; case TkoLogEvent::UnMarkTko: logUtil("unmarked TKO"); break; case TkoLogEvent::RemoveFromConfig: logUtil("was TKO, removed from config"); break; } TkoLog tkoLog(accessPoint, shared->tko.globalTkos()); tkoLog.event = event; tkoLog.isHardTko = shared->tko.isHardTko(); tkoLog.isSoftTko = shared->tko.isSoftTko(); tkoLog.avgLatency = stats_.avgLatency.value(); tkoLog.probesSent = probesSent_; tkoLog.result = result; logTkoEvent(proxy, tkoLog); } void ProxyDestination::setState(ProxyDestinationState new_st) { auto old_st = stats_.state; if (old_st != new_st) { auto getStatName = [](ProxyDestinationState st) { switch (st) { case ProxyDestinationState::kNew: return num_servers_new_stat; case ProxyDestinationState::kUp: return num_servers_up_stat; case ProxyDestinationState::kClosed: return num_servers_closed_stat; case ProxyDestinationState::kDown: return num_servers_down_stat; default: CHECK(false); return num_stats; // shouldnt reach here } }; auto old_name = getStatName(old_st); auto new_name = getStatName(new_st); stat_decr(proxy->stats, old_name, 1); stat_incr(proxy->stats, new_name, 1); stats_.state = new_st; } } ProxyDestinationStats::ProxyDestinationStats(const McrouterOptions& opts) : avgLatency(1.0 / opts.latency_window_size) { } void ProxyDestination::updateShortestTimeout( std::chrono::milliseconds timeout) { if (!timeout.count()) { return; } if (shortestTimeout.count() == 0 || shortestTimeout > timeout) { shortestTimeout = timeout; client_->updateWriteTimeout(); } } }}} // facebook::memcache::mcrouter <|endoftext|>
<commit_before>// // Log - simple message logging to a file. // // Copyright (c) 2002-2005 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "cpl_error.h" // From GDAL/include #include "vtString.h" #include "vtLog.h" #include <stdarg.h> #ifndef __DARWIN_OSX__ #include <wchar.h> // for fputws() #endif #ifdef _MSC_VER #include <windows.h> // for OutputDebugString, unfortunately #endif vtLog g_Log; vtLog::vtLog() { m_log = NULL; } vtLog::~vtLog() { if (m_log) { fclose(m_log); m_log = NULL; } } void vtLog::StartLog(const char *fname) { m_log = fopen(fname, "wb"); } void vtLog::Log(const char *msg) { if (m_log) { fputs(msg, m_log); fflush(m_log); } #ifdef _MSC_VER OutputDebugStringA(msg); #endif // also send to the console, for those console-mode developers! fputs(msg, stdout); } void vtLog::Log(char ch) { if (m_log) { fputc(ch, m_log); fflush(m_log); } #ifdef _MSC_VER char str[2]; str[0] = ch; str[1] = 0; OutputDebugStringA(str); #endif // also send to the console, for those console-mode developers! fputc(ch, stdout); } void vtLog::Printf(const char *pFormat, ...) { va_list va; va_start(va, pFormat); char ach[2048]; vsprintf(ach, pFormat, va); Log(ach); } #if SUPPORT_WSTRING void vtLog::Log(const wchar_t *msg) { if (m_log) { // it is not so useful to write wide characters to the file, which // otherwise contains 8-bit text, so convert back first // fputws(msg, m_log); wstring2 str = msg; fputs(str.eb_str(), m_log); fflush(m_log); } #ifdef _MSC_VER OutputDebugStringW(msg); #endif } void vtLog::Printf(const wchar_t *pFormat, ...) { va_list va; va_start(va, pFormat); // Use wide characters wchar_t ach[2048]; #if defined(_MSC_VER) && _MSC_VER < 1300 vswprintf(ach, pFormat, va); #else // on MSVC7.x and non-MSVC platforms this takes 4 arguments (safer) vswprintf(ach, 2048, pFormat, va); #endif Log(ach); } #endif // SUPPORT_WSTRING <commit_msg>also sent wide strings to stdout, for Linux developers<commit_after>// // Log - simple message logging to a file. // // Copyright (c) 2002-2005 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "cpl_error.h" // From GDAL/include #include "vtString.h" #include "vtLog.h" #include <stdarg.h> #ifndef __DARWIN_OSX__ #include <wchar.h> // for fputws() #endif #ifdef _MSC_VER #include <windows.h> // for OutputDebugString, unfortunately #endif vtLog g_Log; vtLog::vtLog() { m_log = NULL; } vtLog::~vtLog() { if (m_log) { fclose(m_log); m_log = NULL; } } void vtLog::StartLog(const char *fname) { m_log = fopen(fname, "wb"); } void vtLog::Log(const char *msg) { if (m_log) { fputs(msg, m_log); fflush(m_log); } #ifdef _MSC_VER OutputDebugStringA(msg); #endif // also send to the console, for those console-mode developers! fputs(msg, stdout); } void vtLog::Log(char ch) { if (m_log) { fputc(ch, m_log); fflush(m_log); } #ifdef _MSC_VER char str[2]; str[0] = ch; str[1] = 0; OutputDebugStringA(str); #endif // also send to the console, for those console-mode developers! fputc(ch, stdout); } void vtLog::Printf(const char *pFormat, ...) { va_list va; va_start(va, pFormat); char ach[2048]; vsprintf(ach, pFormat, va); Log(ach); } #if SUPPORT_WSTRING void vtLog::Log(const wchar_t *msg) { wstring2 str = msg; const char *ebstr = str.eb_str(); if (m_log) { // it is not so useful to write wide characters to the file, which // otherwise contains 8-bit text, so convert back first // fputws(msg, m_log); fputs(ebstr, m_log); fflush(m_log); } // also send to the console, for those console-mode developers! fputs(ebstr, stdout); #ifdef _MSC_VER OutputDebugStringW(msg); #endif } void vtLog::Printf(const wchar_t *pFormat, ...) { va_list va; va_start(va, pFormat); // Use wide characters wchar_t ach[2048]; #if defined(_MSC_VER) && _MSC_VER < 1300 vswprintf(ach, pFormat, va); #else // on MSVC7.x and non-MSVC platforms this takes 4 arguments (safer) vswprintf(ach, 2048, pFormat, va); #endif Log(ach); } #endif // SUPPORT_WSTRING <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vvasilev@cern.ch> //------------------------------------------------------------------------------ #include "MetaParser.h" #include "MetaLexer.h" #include "MetaSema.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InvocationOptions.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Path.h" namespace cling { MetaParser::MetaParser(MetaSema* Actions) { m_Lexer.reset(0); m_Actions.reset(Actions); const InvocationOptions& Opts = Actions->getInterpreter().getOptions(); MetaLexer metaSymbolLexer(Opts.MetaString); Token Tok;//Tok.startToken(); while(true) { metaSymbolLexer.Lex(Tok); if (Tok.is(tok::eof)) break; m_MetaSymbolCache.push_back(Tok); } } void MetaParser::enterNewInputLine(llvm::StringRef Line) { m_Lexer.reset(new MetaLexer(Line)); m_TokenCache.clear(); } void MetaParser::consumeToken() { if (m_TokenCache.size()) m_TokenCache.erase(m_TokenCache.begin()); lookAhead(0); } void MetaParser::consumeAnyStringToken(tok::TokenKind stopAt/*=tok::space*/) { consumeToken(); // we have to merge the tokens from the queue until we reach eof token or // space token SkipWhitespace(); // Add the new token in which we will merge the others. Token& MergedTok = m_TokenCache.front(); if (MergedTok.is(stopAt) || MergedTok.is(tok::eof) || MergedTok.is(tok::comment)) return; Token Tok = lookAhead(1); while (Tok.isNot(stopAt) && Tok.isNot(tok::eof)){ //MergedTok.setLength(MergedTok.getLength() + Tok.getLength()); m_TokenCache.erase(m_TokenCache.begin() + 1); Tok = lookAhead(1); } MergedTok.setKind(tok::raw_ident); MergedTok.setLength(Tok.getBufStart() - MergedTok.getBufStart()); } const Token& MetaParser::lookAhead(unsigned N) { if (N < m_TokenCache.size()) return m_TokenCache[N]; for (unsigned C = N+1 - m_TokenCache.size(); C > 0; --C) { m_TokenCache.push_back(Token()); m_Lexer->Lex(m_TokenCache.back()); } return m_TokenCache.back(); } void MetaParser::SkipWhitespace() { while(getCurTok().is(tok::space)) consumeToken(); } bool MetaParser::isMetaCommand() { return isCommandSymbol() && isCommand(); } bool MetaParser::isCommandSymbol() { for (size_t i = 0; i < m_MetaSymbolCache.size(); ++i) { if (getCurTok().getKind() != m_MetaSymbolCache[i].getKind()) return false; consumeToken(); } return true; } bool MetaParser::isCommand() { return isLCommand() || isXCommand() || isqCommand() || isUCommand() || isICommand() || israwInputCommand() || isprintASTCommand() || isdynamicExtensionsCommand() || ishelpCommand() || isfileExCommand() || isfilesCommand() || isClassCommand(); } // L := 'L' FilePath // FilePath := AnyString // AnyString := .*^(' ' | '\t') bool MetaParser::isLCommand() { bool result = false; if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("L")) { consumeAnyStringToken(); if (getCurTok().is(tok::raw_ident)) { result = true; m_Actions->actOnLCommand(llvm::sys::Path(getCurTok().getIdent())); consumeToken(); if (getCurTok().is(tok::comment)) { consumeAnyStringToken(); m_Actions->actOnComment(getCurTok().getIdent()); } } } // TODO: Some fine grained diagnostics return result; } // XCommand := 'x' FilePath[ArgList] | 'X' FilePath[ArgList] // FilePath := AnyString // ArgList := (ExtraArgList) ' ' [ArgList] // ExtraArgList := AnyString [, ExtraArgList] bool MetaParser::isXCommand() { bool result = false; const Token& Tok = getCurTok(); if (Tok.is(tok::ident) && (Tok.getIdent().equals("x") || Tok.getIdent().equals("X"))) { // There might be ArgList consumeAnyStringToken(tok::l_paren); llvm::sys::Path file(getCurTok().getIdent()); llvm::StringRef args; result = true; consumeToken(); if (getCurTok().is(tok::l_paren) && isExtraArgList()) { args = getCurTok().getIdent(); consumeToken(); // consume the closing paren } m_Actions->actOnxCommand(file, args); if (getCurTok().is(tok::comment)) { consumeAnyStringToken(); m_Actions->actOnComment(getCurTok().getIdent()); } } return result; } // ExtraArgList := AnyString [, ExtraArgList] bool MetaParser::isExtraArgList() { // This might be expanded if we need better arg parsing. consumeAnyStringToken(tok::r_paren); return getCurTok().is(tok::raw_ident); } bool MetaParser::isqCommand() { bool result = false; if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("q")) { result = true; m_Actions->actOnqCommand(); } return result; } bool MetaParser::isUCommand() { if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("q")) { m_Actions->actOnUCommand(); return true; } return false; } bool MetaParser::isICommand() { if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("I")) { consumeAnyStringToken(); llvm::sys::Path path; if (getCurTok().is(tok::raw_ident)) path = getCurTok().getIdent(); m_Actions->actOnICommand(path); return true; } return false; } bool MetaParser::israwInputCommand() { if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("rawInput")) { MetaSema::SwitchMode mode = MetaSema::kToggle; consumeToken(); SkipWhitespace(); if (getCurTok().is(tok::constant)) mode = (MetaSema::SwitchMode)getCurTok().getConstant(); m_Actions->actOnrawInputCommand(mode); return true; } return false; } bool MetaParser::isprintASTCommand() { if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("printAST")) { MetaSema::SwitchMode mode = MetaSema::kToggle; consumeToken(); SkipWhitespace(); if (getCurTok().is(tok::constant)) mode = (MetaSema::SwitchMode)getCurTok().getConstant(); m_Actions->actOnprintASTCommand(mode); return true; } return false; } bool MetaParser::isdynamicExtensionsCommand() { if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("dynamicExtensions")) { MetaSema::SwitchMode mode = MetaSema::kToggle; consumeToken(); SkipWhitespace(); if (getCurTok().is(tok::constant)) mode = (MetaSema::SwitchMode)getCurTok().getConstant(); m_Actions->actOndynamicExtensionsCommand(mode); return true; } return false; } bool MetaParser::ishelpCommand() { if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("help")) { m_Actions->actOnhelpCommand(); return true; } return false; } bool MetaParser::isfileExCommand() { if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("fileEx")) { m_Actions->actOnfileExCommand(); return true; } return false; } bool MetaParser::isfilesCommand() { if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("files")) { m_Actions->actOnfilesCommand(); return true; } return false; } bool MetaParser::isClassCommand() { const Token& Tok = getCurTok(); if (Tok.is(tok::ident)) { if (Tok.getIdent().equals("class")) { consumeAnyStringToken(); const Token& NextTok = getCurTok(); llvm::StringRef className; if (NextTok.is(tok::raw_ident)) className = Tok.getIdent(); m_Actions->actOnclassCommand(className); return true; } else if (Tok.getIdent().equals("Class")) { m_Actions->actOnClassCommand(); return true; } } return false; } } // end namespace cling <commit_msg>Remove redundant comment.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vvasilev@cern.ch> //------------------------------------------------------------------------------ #include "MetaParser.h" #include "MetaLexer.h" #include "MetaSema.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InvocationOptions.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Path.h" namespace cling { MetaParser::MetaParser(MetaSema* Actions) { m_Lexer.reset(0); m_Actions.reset(Actions); const InvocationOptions& Opts = Actions->getInterpreter().getOptions(); MetaLexer metaSymbolLexer(Opts.MetaString); Token Tok; while(true) { metaSymbolLexer.Lex(Tok); if (Tok.is(tok::eof)) break; m_MetaSymbolCache.push_back(Tok); } } void MetaParser::enterNewInputLine(llvm::StringRef Line) { m_Lexer.reset(new MetaLexer(Line)); m_TokenCache.clear(); } void MetaParser::consumeToken() { if (m_TokenCache.size()) m_TokenCache.erase(m_TokenCache.begin()); lookAhead(0); } void MetaParser::consumeAnyStringToken(tok::TokenKind stopAt/*=tok::space*/) { consumeToken(); // we have to merge the tokens from the queue until we reach eof token or // space token SkipWhitespace(); // Add the new token in which we will merge the others. Token& MergedTok = m_TokenCache.front(); if (MergedTok.is(stopAt) || MergedTok.is(tok::eof) || MergedTok.is(tok::comment)) return; Token Tok = lookAhead(1); while (Tok.isNot(stopAt) && Tok.isNot(tok::eof)){ //MergedTok.setLength(MergedTok.getLength() + Tok.getLength()); m_TokenCache.erase(m_TokenCache.begin() + 1); Tok = lookAhead(1); } MergedTok.setKind(tok::raw_ident); MergedTok.setLength(Tok.getBufStart() - MergedTok.getBufStart()); } const Token& MetaParser::lookAhead(unsigned N) { if (N < m_TokenCache.size()) return m_TokenCache[N]; for (unsigned C = N+1 - m_TokenCache.size(); C > 0; --C) { m_TokenCache.push_back(Token()); m_Lexer->Lex(m_TokenCache.back()); } return m_TokenCache.back(); } void MetaParser::SkipWhitespace() { while(getCurTok().is(tok::space)) consumeToken(); } bool MetaParser::isMetaCommand() { return isCommandSymbol() && isCommand(); } bool MetaParser::isCommandSymbol() { for (size_t i = 0; i < m_MetaSymbolCache.size(); ++i) { if (getCurTok().getKind() != m_MetaSymbolCache[i].getKind()) return false; consumeToken(); } return true; } bool MetaParser::isCommand() { return isLCommand() || isXCommand() || isqCommand() || isUCommand() || isICommand() || israwInputCommand() || isprintASTCommand() || isdynamicExtensionsCommand() || ishelpCommand() || isfileExCommand() || isfilesCommand() || isClassCommand(); } // L := 'L' FilePath // FilePath := AnyString // AnyString := .*^(' ' | '\t') bool MetaParser::isLCommand() { bool result = false; if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("L")) { consumeAnyStringToken(); if (getCurTok().is(tok::raw_ident)) { result = true; m_Actions->actOnLCommand(llvm::sys::Path(getCurTok().getIdent())); consumeToken(); if (getCurTok().is(tok::comment)) { consumeAnyStringToken(); m_Actions->actOnComment(getCurTok().getIdent()); } } } // TODO: Some fine grained diagnostics return result; } // XCommand := 'x' FilePath[ArgList] | 'X' FilePath[ArgList] // FilePath := AnyString // ArgList := (ExtraArgList) ' ' [ArgList] // ExtraArgList := AnyString [, ExtraArgList] bool MetaParser::isXCommand() { bool result = false; const Token& Tok = getCurTok(); if (Tok.is(tok::ident) && (Tok.getIdent().equals("x") || Tok.getIdent().equals("X"))) { // There might be ArgList consumeAnyStringToken(tok::l_paren); llvm::sys::Path file(getCurTok().getIdent()); llvm::StringRef args; result = true; consumeToken(); if (getCurTok().is(tok::l_paren) && isExtraArgList()) { args = getCurTok().getIdent(); consumeToken(); // consume the closing paren } m_Actions->actOnxCommand(file, args); if (getCurTok().is(tok::comment)) { consumeAnyStringToken(); m_Actions->actOnComment(getCurTok().getIdent()); } } return result; } // ExtraArgList := AnyString [, ExtraArgList] bool MetaParser::isExtraArgList() { // This might be expanded if we need better arg parsing. consumeAnyStringToken(tok::r_paren); return getCurTok().is(tok::raw_ident); } bool MetaParser::isqCommand() { bool result = false; if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("q")) { result = true; m_Actions->actOnqCommand(); } return result; } bool MetaParser::isUCommand() { if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("q")) { m_Actions->actOnUCommand(); return true; } return false; } bool MetaParser::isICommand() { if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("I")) { consumeAnyStringToken(); llvm::sys::Path path; if (getCurTok().is(tok::raw_ident)) path = getCurTok().getIdent(); m_Actions->actOnICommand(path); return true; } return false; } bool MetaParser::israwInputCommand() { if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("rawInput")) { MetaSema::SwitchMode mode = MetaSema::kToggle; consumeToken(); SkipWhitespace(); if (getCurTok().is(tok::constant)) mode = (MetaSema::SwitchMode)getCurTok().getConstant(); m_Actions->actOnrawInputCommand(mode); return true; } return false; } bool MetaParser::isprintASTCommand() { if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("printAST")) { MetaSema::SwitchMode mode = MetaSema::kToggle; consumeToken(); SkipWhitespace(); if (getCurTok().is(tok::constant)) mode = (MetaSema::SwitchMode)getCurTok().getConstant(); m_Actions->actOnprintASTCommand(mode); return true; } return false; } bool MetaParser::isdynamicExtensionsCommand() { if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("dynamicExtensions")) { MetaSema::SwitchMode mode = MetaSema::kToggle; consumeToken(); SkipWhitespace(); if (getCurTok().is(tok::constant)) mode = (MetaSema::SwitchMode)getCurTok().getConstant(); m_Actions->actOndynamicExtensionsCommand(mode); return true; } return false; } bool MetaParser::ishelpCommand() { if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("help")) { m_Actions->actOnhelpCommand(); return true; } return false; } bool MetaParser::isfileExCommand() { if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("fileEx")) { m_Actions->actOnfileExCommand(); return true; } return false; } bool MetaParser::isfilesCommand() { if (getCurTok().is(tok::ident) && getCurTok().getIdent().equals("files")) { m_Actions->actOnfilesCommand(); return true; } return false; } bool MetaParser::isClassCommand() { const Token& Tok = getCurTok(); if (Tok.is(tok::ident)) { if (Tok.getIdent().equals("class")) { consumeAnyStringToken(); const Token& NextTok = getCurTok(); llvm::StringRef className; if (NextTok.is(tok::raw_ident)) className = Tok.getIdent(); m_Actions->actOnclassCommand(className); return true; } else if (Tok.getIdent().equals("Class")) { m_Actions->actOnClassCommand(); return true; } } return false; } } // end namespace cling <|endoftext|>
<commit_before>#ifdef NDEBUG #undef NDEBUG #endif #include <llvm/IR/IRBuilder.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/IR/Verifier.h> #include <vector> #include <string> struct LLVMCodeGen { using IRBuilder = llvm::IRBuilder<>; llvm::LLVMContext &Context; llvm::Module &M; IRBuilder &Builder; LLVMCodeGen(llvm::LLVMContext &context, llvm::Module &m, llvm::IRBuilder<> &builder) : Context(context), M(m), Builder(builder) {} void dump() const { M.dump(); } //----------------------- Type --------------------------------------------- struct Type { enum Kind { int32, float32, float64 }; LLVMCodeGen *CG; Kind TypeKind; Type(LLVMCodeGen *cg, Kind type_kind) : CG(cg), TypeKind(type_kind) {} Type(LLVMCodeGen *cg, llvm::Type *ty) : CG(cg) { if (ty->getTypeID() == CG->Builder.getInt32Ty()->getTypeID()) { TypeKind = int32; } else if (ty->getTypeID() == CG->Builder.getFloatTy()->getTypeID()) { TypeKind = float32; } else if (ty->getTypeID() == CG->Builder.getDoubleTy()->getTypeID()) { TypeKind = float64; } else { assert(0 && "Must not happend"); } } llvm::Type *get() { switch (TypeKind) { case int32: return CG->Builder.getInt32Ty(); case float32: return CG->Builder.getFloatTy(); case float64: return CG->Builder.getDoubleTy(); default: assert(0 && "Must not happen"); } } size_t size() { switch (TypeKind) { case int32: case float32: return 4; case float64: return 8; default: assert(0 && "Must not happen"); } return 0; } }; //------------------- Basic Block ------------------------------------------- struct Function; struct BasicBlock { LLVMCodeGen *CG; llvm::BasicBlock *BB; BasicBlock(LLVMCodeGen *cg, llvm::BasicBlock *bb) : CG(cg), BB(bb) {} llvm::BasicBlock *get() { return BB; } void set() { CG->Builder.SetInsertPoint(BB); } Function getParent(); }; // ----------------------- Boolean ------------------------------------------- struct Value; struct Boolean { LLVMCodeGen *CG; llvm::Value *V; Boolean(LLVMCodeGen *cg, llvm::Value *value) : CG(cg), V(value) {} llvm::Value *get() { return V; } void mkIfThenElse(BasicBlock thenBB, BasicBlock elseBB) { CG->Builder.CreateCondBr(V, thenBB.get(), elseBB.get()); } Value mkSelect(Value thenV, Value elseV); }; // ----------------------- Value ------------------------------------------- struct Value { LLVMCodeGen *CG; llvm::Value *V; Value(LLVMCodeGen *cg, llvm::Value *value) : CG(cg), V(value) {} Type getType() { return {CG, V->getType()}; } llvm::Value *get() { return V; } Value operator*(Value R) { return {CG, CG->Builder.CreateMul(V, R.get(), "mul")}; } Value operator+(Value R) { return {CG, CG->Builder.CreateAdd(V, R.get(), "add")}; } Boolean operator<(Value R) { return {CG, CG->Builder.CreateICmpULT(V, R.get(), "lt")}; } Boolean operator!=(Value R) { return {CG, CG->Builder.CreateICmpNE(V, R.get(), "ne")}; } }; #if 0 // --------------------- Global Variable ----------------------------------- struct GlobalVar { LLVMCodeGen *CG; llvm::GlobalVariable *Var; GlobalVar(LLVMCodeGen *cg, llvm::GlobalVariable *var) : CG(cg), Var(var) {} }; GlobalVar mkGlobalVar(std::string name, Type type) { M.getOrInsertGlobal(name, type.get()); llvm::GlobalVariable *gvar = M.getNamedGlobal(name); gvar->setLinkage(llvm::GlobalValue::CommonLinkage); gvar->setAlignment(type.size()); return GlobalVar{this, gvar}; } #endif //---------------------- Function ------------------------------------------- struct Function { LLVMCodeGen *CG; llvm::Function *F; std::vector<llvm::Value*> Args; Function(LLVMCodeGen *cg, llvm::Function *f) : CG(cg), F(f) { Args.reserve(16); for (auto &arg : F->args()) { Args.push_back(&arg); } } bool verify() const { return llvm::verifyFunction(*F); } size_t n_args() const { return Args.size(); } llvm::Function *get() { return F; } Value arg(size_t num) { assert(num < Args.size()); return Value{CG, Args[num]}; } BasicBlock mkBasicBlock(std::string name) { llvm::BasicBlock *bb = llvm::BasicBlock::Create(CG->Context, name, F); return {CG, bb}; } }; Function mkFunction(std::string name, Type ret_type, std::vector<std::pair<Type, std::string>> args = {}) { std::vector<llvm::Type*> args_type; args_type.reserve(args.size()); for (auto arg : args) { args_type.push_back(arg.first.get()); } llvm::FunctionType *funcType = llvm::FunctionType::get(ret_type.get(), args_type, false); llvm::Function *func = llvm::Function::Create( funcType, llvm::Function::ExternalLinkage, name, &M); int count = 0; for (auto &arg : func->args()) { arg.setName(args[count++].second); } return Function{this, func}; } Function mkFunction(std::string name, std::vector<std::pair<Type, std::string>> args = {}) { std::vector<llvm::Type*> args_type; args_type.reserve(args.size()); for (auto arg : args) { args_type.push_back(arg.first.get()); } llvm::FunctionType *funcType = llvm::FunctionType::get(Builder.getVoidTy(), args_type, false); llvm::Function *func = llvm::Function::Create( funcType, llvm::Function::ExternalLinkage, name, &M); int count = 0; for (auto &arg : func->args()) { arg.setName(args[count++].second); } return Function{this, func}; } // -------------------------- Call ------------------------------------------ struct CallInst { LLVMCodeGen *CG; llvm::CallInst *Inst; CallInst(LLVMCodeGen *cg, llvm::CallInst *inst) : CG(cg), Inst(inst) {} operator Value() { return {CG, Inst}; } llvm::CallInst *get() { return Inst; } }; CallInst mkCall(Function &f, std::vector<Value> args) { assert(args.size() == f.n_args() && "Argument count mismatch"); std::vector<llvm::Value*> arguments; arguments.reserve(args.size()); for (auto &arg : args) { arguments.push_back(arg.get()); } return {this, Builder.CreateCall(f.get(), arguments)}; } // --------------------------- Phi node ------------------------------------ struct Phi { LLVMCodeGen *CG; llvm::PHINode *V; Phi(LLVMCodeGen *cg, llvm::PHINode *v) : CG(cg), V(v) {} llvm::PHINode *get() { return V; } operator Value() { return {CG, V}; } Phi &operator+=(std::pair<Value, BasicBlock> rhs) { V->addIncoming(rhs.first.get(), rhs.second.get()); return *this; } }; Phi mkPhi(Type type, std::vector<std::pair<Value, BasicBlock>> edge_list) { llvm::PHINode *phi = Builder.CreatePHI(type.get(), edge_list.size()); for (auto &edge : edge_list) { phi->addIncoming(edge.first.get(), edge.second.get()); } return {this, phi}; } // ------------- type & vals Type mkIntTy() { return Type(this, Type::int32); } Value mkInt(int val) { return {this, Builder.getInt32(val)}; } Type mkFloatTy() { return Type(this, Type::float32); } Type mkDoubleTy() { return Type(this, Type::float64); } BasicBlock getCurrentBasicBlock() { return {this, Builder.GetInsertBlock()}; } //-------------------- Ops void mkRet(Value val) { Builder.CreateRet(val.get()); } void mkRetVoid() { Builder.CreateRetVoid(); } // ---------------- loop Value mkLoop(Value begin, Value end, Value step, Function loop_body) { auto bb = getCurrentBasicBlock(); auto preBB = bb.getParent().mkBasicBlock("preBB"); auto loopBB = bb.getParent().mkBasicBlock("loopBB"); auto afterBB = bb.getParent().mkBasicBlock("afterBB"); mkBranch(preBB); preBB.set(); auto iv = mkPhi(step.getType(), {{begin, bb}}); auto cond = Value(iv) < end; cond.mkIfThenElse(loopBB, afterBB); loopBB.set(); mkCall(loop_body, {iv}); auto next = step + iv; iv += {next, loopBB}; mkBranch(preBB); afterBB.set(); return iv; } // ---------------- branchInst struct BranchInst { LLVMCodeGen *CG; llvm::BranchInst *Inst; BranchInst(LLVMCodeGen *cg, llvm::BranchInst *inst) : CG(cg), Inst(inst) {} operator Value() { return {CG, Inst}; } llvm::BranchInst *get() { return Inst; } }; BranchInst mkBranch(BasicBlock &bb) { return {this, Builder.CreateBr(bb.get())}; } bool verifyModule() { return llvm::verifyModule(M); } }; LLVMCodeGen::Function LLVMCodeGen::BasicBlock::getParent() { return {CG, BB->getParent()}; } LLVMCodeGen::Value LLVMCodeGen::Boolean::mkSelect(Value thenV, Value elseV) { return {CG, CG->Builder.CreateSelect(V, thenV.get(), elseV.get())}; } static llvm::LLVMContext &ContextRef = llvm::getGlobalContext(); static llvm::Module *ModuleOb = new llvm::Module("my compiler", ContextRef); int main(int argc, char *argv[]) { static llvm::IRBuilder<> BuilderObj(ContextRef); LLVMCodeGen cg(ContextRef, *ModuleOb, BuilderObj); #if 0 auto gvar = cg.mkGlobalVar("x", cg.mkFloatTy()); #endif auto f = cg.mkFunction("foo", cg.mkIntTy(), {{cg.mkIntTy(), "a"}, {cg.mkIntTy(), "b"}}); auto entryBB = f.mkBasicBlock("entry"); auto thenBB = f.mkBasicBlock("then"); auto elseBB = f.mkBasicBlock("else"); auto mergeBB = f.mkBasicBlock("cont"); entryBB.set(); auto val = cg.mkInt(100); auto cnd = f.arg(0) < val; cnd.mkIfThenElse(thenBB, elseBB); thenBB.set(); auto then_val = f.arg(0) + cg.mkInt(1); cg.mkBranch(mergeBB); elseBB.set(); auto else_val = f.arg(1) + cg.mkInt(2); cg.mkBranch(mergeBB); mergeBB.set(); auto phi = cg.mkPhi(cg.mkIntTy(), {{then_val, thenBB}, {else_val, elseBB}}); auto f1 = cg.mkFunction("foo", {{cg.mkIntTy(), "m"}}); auto f1entryBB = f1.mkBasicBlock("entry"); auto last = cg.mkLoop(cg.mkInt(0), phi, cg.mkInt(1), f1); auto cmp = last != cg.mkInt(32); cg.mkRet(cmp.mkSelect(last, cg.mkInt(44))); f1entryBB.set(); cg.mkRetVoid(); assert(!f.verify()); assert(!f1.verify()); assert(!cg.verifyModule()); cg.dump(); return 0; } <commit_msg>added error<commit_after>#ifdef NDEBUG #undef NDEBUG #endif #include <llvm/IR/IRBuilder.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/IR/Verifier.h> #include <llvm/Support/raw_ostream.h> #include <vector> #include <string> #include <iostream> struct LLVMCodeGen { using IRBuilder = llvm::IRBuilder<>; llvm::LLVMContext &Context; llvm::Module &M; IRBuilder &Builder; LLVMCodeGen(llvm::LLVMContext &context, llvm::Module &m, llvm::IRBuilder<> &builder) : Context(context), M(m), Builder(builder) {} void dump() const { M.dump(); } //----------------------- Type --------------------------------------------- struct Type { enum Kind { int32, float32, float64 }; LLVMCodeGen *CG; Kind TypeKind; Type(LLVMCodeGen *cg, Kind type_kind) : CG(cg), TypeKind(type_kind) {} Type(LLVMCodeGen *cg, llvm::Type *ty) : CG(cg) { if (ty->getTypeID() == CG->Builder.getInt32Ty()->getTypeID()) { TypeKind = int32; } else if (ty->getTypeID() == CG->Builder.getFloatTy()->getTypeID()) { TypeKind = float32; } else if (ty->getTypeID() == CG->Builder.getDoubleTy()->getTypeID()) { TypeKind = float64; } else { assert(0 && "Must not happend"); } } llvm::Type *get() { switch (TypeKind) { case int32: return CG->Builder.getInt32Ty(); case float32: return CG->Builder.getFloatTy(); case float64: return CG->Builder.getDoubleTy(); default: assert(0 && "Must not happen"); } } size_t size() { switch (TypeKind) { case int32: case float32: return 4; case float64: return 8; default: assert(0 && "Must not happen"); } return 0; } }; //------------------- Basic Block ------------------------------------------- struct Function; struct BasicBlock { LLVMCodeGen *CG; llvm::BasicBlock *BB; BasicBlock(LLVMCodeGen *cg, llvm::BasicBlock *bb) : CG(cg), BB(bb) {} llvm::BasicBlock *get() { return BB; } void set() { CG->Builder.SetInsertPoint(BB); } Function getParent(); }; // ----------------------- Boolean ------------------------------------------- struct Value; struct Boolean { LLVMCodeGen *CG; llvm::Value *V; Boolean(LLVMCodeGen *cg, llvm::Value *value) : CG(cg), V(value) {} llvm::Value *get() { return V; } void mkIfThenElse(BasicBlock thenBB, BasicBlock elseBB) { CG->Builder.CreateCondBr(V, thenBB.get(), elseBB.get()); } Value mkSelect(Value thenV, Value elseV); }; // ----------------------- Value ------------------------------------------- struct Value { LLVMCodeGen *CG; llvm::Value *V; Value(LLVMCodeGen *cg, llvm::Value *value) : CG(cg), V(value) {} Type getType() { return {CG, V->getType()}; } llvm::Value *get() { return V; } void set(llvm::Value *v) { } Value operator*(Value R) { return {CG, CG->Builder.CreateMul(V, R.get(), "mul")}; } Value operator+(Value R) { return {CG, CG->Builder.CreateAdd(V, R.get(), "add")}; } Boolean operator<(Value R) { return {CG, CG->Builder.CreateICmpULT(V, R.get(), "lt")}; } Boolean operator!=(Value R) { return {CG, CG->Builder.CreateICmpNE(V, R.get(), "ne")}; } }; #if 0 // --------------------- Global Variable ----------------------------------- struct GlobalVar { LLVMCodeGen *CG; llvm::GlobalVariable *Var; GlobalVar(LLVMCodeGen *cg, llvm::GlobalVariable *var) : CG(cg), Var(var) {} }; GlobalVar mkGlobalVar(std::string name, Type type) { M.getOrInsertGlobal(name, type.get()); llvm::GlobalVariable *gvar = M.getNamedGlobal(name); gvar->setLinkage(llvm::GlobalValue::CommonLinkage); gvar->setAlignment(type.size()); return GlobalVar{this, gvar}; } #endif //---------------------- Function ------------------------------------------- struct Function { LLVMCodeGen *CG; llvm::Function *F; std::vector<llvm::Value*> Args; Function(LLVMCodeGen *cg, llvm::Function *f) : CG(cg), F(f) { Args.reserve(16); for (auto &arg : F->args()) { Args.push_back(&arg); } } std::string ErrorString; bool verify() { ErrorString.clear(); llvm::raw_string_ostream os(ErrorString); return llvm::verifyFunction(*F, &os); } size_t n_args() const { return Args.size(); } llvm::Function *get() { return F; } std::string const& getErrorString() { return ErrorString;} Value arg(size_t num) { assert(num < Args.size()); return Value{CG, Args[num]}; } BasicBlock mkBasicBlock(std::string name) { llvm::BasicBlock *bb = llvm::BasicBlock::Create(CG->Context, name, F); return {CG, bb}; } }; Function mkFunction(std::string name, Type ret_type, std::vector<std::pair<Type, std::string>> args = {}) { std::vector<llvm::Type*> args_type; args_type.reserve(args.size()); for (auto arg : args) { args_type.push_back(arg.first.get()); } llvm::FunctionType *funcType = llvm::FunctionType::get(ret_type.get(), args_type, false); llvm::Function *func = llvm::Function::Create( funcType, llvm::Function::ExternalLinkage, name, &M); int count = 0; for (auto &arg : func->args()) { arg.setName(args[count++].second); } return Function{this, func}; } Function mkFunction(std::string name, std::vector<std::pair<Type, std::string>> args = {}) { std::vector<llvm::Type*> args_type; args_type.reserve(args.size()); for (auto arg : args) { args_type.push_back(arg.first.get()); } llvm::FunctionType *funcType = llvm::FunctionType::get(Builder.getVoidTy(), args_type, false); llvm::Function *func = llvm::Function::Create( funcType, llvm::Function::ExternalLinkage, name, &M); int count = 0; for (auto &arg : func->args()) { arg.setName(args[count++].second); } return Function{this, func}; } // -------------------------- Call ------------------------------------------ struct CallInst { LLVMCodeGen *CG; llvm::CallInst *Inst; CallInst(LLVMCodeGen *cg, llvm::CallInst *inst) : CG(cg), Inst(inst) {} operator Value() { return {CG, Inst}; } llvm::CallInst *get() { return Inst; } }; CallInst mkCall(Function &f, std::vector<Value> args) { assert(args.size() == f.n_args() && "Argument count mismatch"); std::vector<llvm::Value*> arguments; arguments.reserve(args.size()); for (auto &arg : args) { arguments.push_back(arg.get()); } return {this, Builder.CreateCall(f.get(), arguments)}; } // --------------------------- Phi node ------------------------------------ struct Phi { LLVMCodeGen *CG; llvm::PHINode *V; Phi(LLVMCodeGen *cg, llvm::PHINode *v) : CG(cg), V(v) {} llvm::PHINode *get() { return V; } operator Value() { return {CG, V}; } Phi &operator+=(std::pair<Value, BasicBlock> rhs) { V->addIncoming(rhs.first.get(), rhs.second.get()); return *this; } }; Phi mkPhi(Type type, std::vector<std::pair<Value, BasicBlock>> edge_list) { llvm::PHINode *phi = Builder.CreatePHI(type.get(), edge_list.size()); for (auto &edge : edge_list) { phi->addIncoming(edge.first.get(), edge.second.get()); } return {this, phi}; } // ------------- type & vals Type mkIntTy() { return Type(this, Type::int32); } Value mkInt(int val) { return {this, Builder.getInt32(val)}; } Type mkFloatTy() { return Type(this, Type::float32); } Type mkDoubleTy() { return Type(this, Type::float64); } BasicBlock getCurrentBasicBlock() { return {this, Builder.GetInsertBlock()}; } //-------------------- Ops void mkRet(Value val) { Builder.CreateRet(val.get()); } void mkRetVoid() { Builder.CreateRetVoid(); } // ---------------- loop Value mkLoop(Value begin, Value end, Value step, Function loop_body) { auto bb = getCurrentBasicBlock(); auto preBB = bb.getParent().mkBasicBlock("preBB"); auto loopBB = bb.getParent().mkBasicBlock("loopBB"); auto afterBB = bb.getParent().mkBasicBlock("afterBB"); mkBranch(preBB); preBB.set(); auto iv = mkPhi(step.getType(), {{begin, bb}}); auto cond = Value(iv) < end; cond.mkIfThenElse(loopBB, afterBB); loopBB.set(); mkCall(loop_body, {iv}); auto next = step + iv; iv += {next, loopBB}; mkBranch(preBB); afterBB.set(); return iv; } template <class F> Value mkLoop(Value begin, Value end, Value step, F body) { auto bb = getCurrentBasicBlock(); auto preBB = bb.getParent().mkBasicBlock("preBB"); auto loopBB = bb.getParent().mkBasicBlock("loopBB"); auto afterBB = bb.getParent().mkBasicBlock("afterBB"); mkBranch(preBB); preBB.set(); auto iv = mkPhi(step.getType(), {{begin, bb}}); auto cond = Value(iv) < end; cond.mkIfThenElse(loopBB, afterBB); loopBB.set(); body(iv); auto next = step + iv; iv += {next, loopBB}; mkBranch(preBB); afterBB.set(); return iv; } template <class F> void mkLoopImpl(std::vector<Value> begs, std::vector<Value> ends, std::vector<Value> steps, F body, std::vector<Value> &ivs, std::vector<Value> &end_ivs, std::vector<BasicBlock> &end_bbs) { // must be matching sizes assert(begs.size() == ends.size()); assert(begs.size() == steps.size()); // if we proceeded all indices, just emplace body of the loop, and return if (begs.empty()) { // since ivs are stored in reverse, so reverse the list :) std::reverse(ivs.begin(), ivs.end()); // emplace function body body(ivs.data()); return; } // otherwise, process next index in reverse order auto beg = begs.back(); auto end = ends.back(); auto step = steps.back(); begs.pop_back(); ends.pop_back(); steps.pop_back(); // make 1d loop, which recursively calls this function with 1 index less auto ret = mkLoop(beg, end, step, [&](Value iv) { ivs.push_back(iv); mkLoopImpl(begs, ends, steps, body, ivs, end_ivs, end_bbs); }); auto bb = getCurrentBasicBlock(); end_ivs.push_back(ret); end_bbs.push_back(bb); } template <class F> std::vector<Value> mkLoopV(std::vector<Value> begs, std::vector<Value> ends, std::vector<Value> steps, F body) { assert(!begs.empty()); // since impl iterates from the last index to the first, so invert the list std::reverse(begs.begin(), begs.end()); std::reverse(ends.begin(), ends.end()); std::reverse(steps.begin(), steps.end()); // ending inductin variable list std::vector<Value> ivs, end_ivs; std::vector<BasicBlock> end_bbs; ivs.reserve(begs.size()); end_ivs.reserve(begs.size()); end_bbs.reserve(begs.size()); // generate the loop mkLoopImpl(begs, ends, steps, body, ivs, end_ivs, end_bbs); std::reverse(end_ivs.begin(), end_ivs.end()); end_bbs.back().set(); return end_ivs; } // ---------------- branchInst struct BranchInst { LLVMCodeGen *CG; llvm::BranchInst *Inst; BranchInst(LLVMCodeGen *cg, llvm::BranchInst *inst) : CG(cg), Inst(inst) {} operator Value() { return {CG, Inst}; } llvm::BranchInst *get() { return Inst; } }; BranchInst mkBranch(BasicBlock & bb) { return {this, Builder.CreateBr(bb.get())}; } bool verifyModule() { return llvm::verifyModule(M); } }; LLVMCodeGen::Function LLVMCodeGen::BasicBlock::getParent() { return {CG, BB->getParent()}; } LLVMCodeGen::Value LLVMCodeGen::Boolean::mkSelect(Value thenV, Value elseV) { return {CG, CG->Builder.CreateSelect(V, thenV.get(), elseV.get())}; } static llvm::LLVMContext &ContextRef = llvm::getGlobalContext(); static llvm::Module *ModuleOb = new llvm::Module("my compiler", ContextRef); int main(int argc, char *argv[]) { static llvm::IRBuilder<> BuilderObj(ContextRef); LLVMCodeGen cg(ContextRef, *ModuleOb, BuilderObj); #if 0 auto gvar = cg.mkGlobalVar("x", cg.mkFloatTy()); #endif auto f = cg.mkFunction("foo", cg.mkIntTy(), {{cg.mkIntTy(), "a"}, {cg.mkIntTy(), "b"}}); auto entryBB = f.mkBasicBlock("entry"); auto thenBB = f.mkBasicBlock("then"); auto elseBB = f.mkBasicBlock("else"); auto mergeBB = f.mkBasicBlock("cont"); entryBB.set(); auto val = cg.mkInt(100); auto cnd = f.arg(0) < val; cnd.mkIfThenElse(thenBB, elseBB); thenBB.set(); auto then_val = f.arg(0) + cg.mkInt(1); cg.mkBranch(mergeBB); elseBB.set(); auto else_val = f.arg(1) + cg.mkInt(2); cg.mkBranch(mergeBB); mergeBB.set(); auto phi = cg.mkPhi(cg.mkIntTy(), {{then_val, thenBB}, {else_val, elseBB}}); auto f1 = [&](LLVMCodeGen::Value /*iv*/) {}; // auto v = iv + cg.mkInt(33); }; auto last = cg.mkLoop(cg.mkInt(0), phi, cg.mkInt(1), f1); auto cmp = last != cg.mkInt(32); auto sum = cg.mkInt(0); #if 0 auto last1 = cg.mkLoop({cg.mkInt(0), cg.mkInt(0)}, {cg.mkInt(3), cg.mkInt(5)}, {cg.mkInt(1), cg.mkInt(1)}, [&](LLVMCodeGen::Value *iv) { sum = sum + iv[0] * iv[1]; }); #else auto last1 = cg.mkLoopV({cg.mkInt(0)}, {cg.mkInt(5)}, {cg.mkInt(1)}, [&](LLVMCodeGen::Value *iv) { sum = sum + iv[0];}); #endif cg.mkRet(cmp.mkSelect(last, sum)); if (f.verify()) { std::cerr << f.getErrorString() << std::endl; exit(1); } assert(!cg.verifyModule()); cg.dump(); return 0; } <|endoftext|>
<commit_before>#include <llvm/IR/IRBuilder.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/IR/Verifier.h> #include <vector> #include <string> struct LLVMCodeGen { using IRBuilder = llvm::IRBuilder<>; llvm::LLVMContext &Context; llvm::Module &M; IRBuilder &Builder; LLVMCodeGen(llvm::LLVMContext &context, llvm::Module &m, llvm::IRBuilder<> &builder) : Context(context), M(m), Builder(builder) {} void dump() const { M.dump(); } //------------------- Basic Block ------------------------------------------- struct BasicBlock { LLVMCodeGen &CG; llvm::BasicBlock &BB; BasicBlock(LLVMCodeGen &cg, llvm::BasicBlock &bb) : CG(cg), BB(bb) {} llvm::BasicBlock *get() { return &BB; } void set() { CG.Builder.SetInsertPoint(&BB); } }; // ----------------------- Boolean ------------------------------------------- struct Boolean { LLVMCodeGen *CG; llvm::Value *V; Boolean(LLVMCodeGen *cg, llvm::Value *value) : CG(cg), V(value) {} llvm::Value *get() { return V; } void mkIfThenElse(BasicBlock thenBB, BasicBlock elseBB, BasicBlock mergeBB) { CG->Builder.CreateCondBr(V, thenBB.get(), elseBB.get()); CG->Builder.SetInsertPoint(thenBB.get()); CG->Builder.CreateBr(mergeBB.get()); CG->Builder.SetInsertPoint(elseBB.get()); CG->Builder.CreateBr(mergeBB.get()); } }; // ----------------------- Value ------------------------------------------- struct Value { LLVMCodeGen *CG; llvm::Value *V; Value(LLVMCodeGen *cg, llvm::Value *value) : CG(cg), V(value) {} llvm::Value *get() { return V; } Value operator*(Value R) { return {CG, CG->Builder.CreateMul(V, R.get(), "mul")}; } Value operator+(Value R) { return {CG, CG->Builder.CreateAdd(V, R.get(), "add")}; } Value operator<(Value R) { return {CG, CG->Builder.CreateICmpULT(V, R.get(), "lt")}; } Boolean operator!=(Value R) { return {CG, CG->Builder.CreateICmpNE(V, R.get(), "ne")}; } }; //----------------------- Type --------------------------------------------- struct Type { enum Kind { int32, float32, float64 }; LLVMCodeGen &CG; Kind TypeKind; Type(LLVMCodeGen &cg, Kind type_kind) : CG(cg), TypeKind(type_kind) {} llvm::Type *get() { switch (TypeKind) { case int32: return CG.Builder.getInt32Ty(); case float32: return CG.Builder.getFloatTy(); case float64: return CG.Builder.getDoubleTy(); default: assert(0 && "Must not happen"); } } size_t size() { switch (TypeKind) { case int32: case float32: return 4; case float64: return 8; default: assert(0 && "Must not happen"); } return 0; } }; // --------------------- Global Variable ----------------------------------- struct GlobalVar { LLVMCodeGen &CG; llvm::GlobalVariable &Var; GlobalVar(LLVMCodeGen &cg, llvm::GlobalVariable &var) : CG(cg), Var(var) {} }; GlobalVar mkGlobalVar(std::string name, Type type) { M.getOrInsertGlobal(name, type.get()); llvm::GlobalVariable *gvar = M.getNamedGlobal(name); gvar->setLinkage(llvm::GlobalValue::CommonLinkage); gvar->setAlignment(type.size()); return GlobalVar{*this, *gvar}; } //---------------------- Function ------------------------------------------- struct Function { LLVMCodeGen &CG; llvm::Function &F; std::vector<llvm::Value*> Args; Function(LLVMCodeGen &cg, llvm::Function &f) : CG(cg), F(f) { Args.reserve(16); for (auto &arg : F.args()) { Args.push_back(&arg); } } void verify() const { llvm::verifyFunction(F); } llvm::Function *get() { return &F; } Value arg(size_t num) { assert(num < Args.size()); return Value{&CG, Args[num]}; } BasicBlock mkBasicBlock(std::string name) { llvm::BasicBlock *bb = llvm::BasicBlock::Create(CG.Context, name, &F); return {CG, *bb}; } }; Function mkFunction(std::string name, Type ret_type, std::vector<std::pair<Type, std::string>> args = {}) { std::vector<llvm::Type*> args_type; args_type.reserve(args.size()); for (auto arg : args) { args_type.push_back(arg.first.get()); } llvm::FunctionType *funcType = llvm::FunctionType::get(ret_type.get(), args_type, false); llvm::Function *func = llvm::Function::Create( funcType, llvm::Function::ExternalLinkage, name, &M); int count = 0; for (auto &arg : func->args()) { arg.setName(args[count++].second); } return Function{*this, *func}; } // --------------------------- Phi node ------------------------------------ struct Phi { LLVMCodeGen *CG; llvm::Value *V; Phi(LLVMCodeGen *cg, llvm::Value *v) : CG(cg), V(v) {} llvm::Value *get() { return V; } operator Value() { return {CG, V}; } }; Phi mkPhi(Type type, std::vector<std::pair<Value, BasicBlock>> edge_list) { llvm::PHINode *phi = Builder.CreatePHI(type.get(), edge_list.size()); for (auto &edge : edge_list) { phi->addIncoming(edge.first.get(), edge.second.get()); } return {this, phi}; } // ------------- type & vals Type mkIntTy() { return Type(*this, Type::int32); } Value mkInt(int val) { return {this, Builder.getInt32(val)}; } Type mkFloatTy() { return Type(*this, Type::float32); } Type mkDoubleTy() { return Type(*this, Type::float64); } //-------------------- Ops void mkRet(Value val) { Builder.CreateRet(val.get()); } }; static llvm::LLVMContext &ContextRef = llvm::getGlobalContext(); static llvm::Module *ModuleOb = new llvm::Module("my compiler", ContextRef); int main(int argc, char *argv[]) { static llvm::IRBuilder<> BuilderObj(ContextRef); LLVMCodeGen cg(ContextRef, *ModuleOb, BuilderObj); auto gvar = cg.mkGlobalVar("x", cg.mkFloatTy()); auto f = cg.mkFunction("foo", cg.mkIntTy(), {{cg.mkIntTy(), "a"}, {cg.mkFloatTy(), "b"}}); auto thenBB = f.mkBasicBlock("then"); thenBB.set(); auto then_val = f.arg(0) + cg.mkInt(1); auto elseBB = f.mkBasicBlock("else"); elseBB.set(); auto else_val = f.arg(1) + cg.mkInt(2); auto mergeBB = f.mkBasicBlock("cont"); mergeBB.set(); auto phi = cg.mkPhi(cg.mkIntTy(), {{then_val, thenBB}, {else_val, elseBB}}); cg.mkRet(phi); auto entry = f.mkBasicBlock("entry"); entry.set(); auto val = cg.mkInt(100); auto cmp = f.arg(0) < val; auto cnd = cmp != cg.mkInt(0); cnd.mkIfThenElse(thenBB, elseBB, mergeBB); f.verify(); cg.dump(); return 0; } <commit_msg>add mkAndSetBasicBlock<commit_after>#include <llvm/IR/IRBuilder.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/IR/Verifier.h> #include <vector> #include <string> struct LLVMCodeGen { using IRBuilder = llvm::IRBuilder<>; llvm::LLVMContext &Context; llvm::Module &M; IRBuilder &Builder; LLVMCodeGen(llvm::LLVMContext &context, llvm::Module &m, llvm::IRBuilder<> &builder) : Context(context), M(m), Builder(builder) {} void dump() const { M.dump(); } //------------------- Basic Block ------------------------------------------- struct BasicBlock { LLVMCodeGen &CG; llvm::BasicBlock &BB; BasicBlock(LLVMCodeGen &cg, llvm::BasicBlock &bb) : CG(cg), BB(bb) {} llvm::BasicBlock *get() { return &BB; } void set() { CG.Builder.SetInsertPoint(&BB); } }; // ----------------------- Boolean ------------------------------------------- struct Boolean { LLVMCodeGen *CG; llvm::Value *V; Boolean(LLVMCodeGen *cg, llvm::Value *value) : CG(cg), V(value) {} llvm::Value *get() { return V; } void mkIfThenElse(BasicBlock thenBB, BasicBlock elseBB, BasicBlock mergeBB) { CG->Builder.CreateCondBr(V, thenBB.get(), elseBB.get()); CG->Builder.SetInsertPoint(thenBB.get()); CG->Builder.CreateBr(mergeBB.get()); CG->Builder.SetInsertPoint(elseBB.get()); CG->Builder.CreateBr(mergeBB.get()); } }; // ----------------------- Value ------------------------------------------- struct Value { LLVMCodeGen *CG; llvm::Value *V; Value(LLVMCodeGen *cg, llvm::Value *value) : CG(cg), V(value) {} llvm::Value *get() { return V; } Value operator*(Value R) { return {CG, CG->Builder.CreateMul(V, R.get(), "mul")}; } Value operator+(Value R) { return {CG, CG->Builder.CreateAdd(V, R.get(), "add")}; } Value operator<(Value R) { return {CG, CG->Builder.CreateICmpULT(V, R.get(), "lt")}; } Boolean operator!=(Value R) { return {CG, CG->Builder.CreateICmpNE(V, R.get(), "ne")}; } }; //----------------------- Type --------------------------------------------- struct Type { enum Kind { int32, float32, float64 }; LLVMCodeGen &CG; Kind TypeKind; Type(LLVMCodeGen &cg, Kind type_kind) : CG(cg), TypeKind(type_kind) {} llvm::Type *get() { switch (TypeKind) { case int32: return CG.Builder.getInt32Ty(); case float32: return CG.Builder.getFloatTy(); case float64: return CG.Builder.getDoubleTy(); default: assert(0 && "Must not happen"); } } size_t size() { switch (TypeKind) { case int32: case float32: return 4; case float64: return 8; default: assert(0 && "Must not happen"); } return 0; } }; // --------------------- Global Variable ----------------------------------- struct GlobalVar { LLVMCodeGen &CG; llvm::GlobalVariable &Var; GlobalVar(LLVMCodeGen &cg, llvm::GlobalVariable &var) : CG(cg), Var(var) {} }; GlobalVar mkGlobalVar(std::string name, Type type) { M.getOrInsertGlobal(name, type.get()); llvm::GlobalVariable *gvar = M.getNamedGlobal(name); gvar->setLinkage(llvm::GlobalValue::CommonLinkage); gvar->setAlignment(type.size()); return GlobalVar{*this, *gvar}; } //---------------------- Function ------------------------------------------- struct Function { LLVMCodeGen &CG; llvm::Function &F; std::vector<llvm::Value*> Args; Function(LLVMCodeGen &cg, llvm::Function &f) : CG(cg), F(f) { Args.reserve(16); for (auto &arg : F.args()) { Args.push_back(&arg); } } void verify() const { llvm::verifyFunction(F); } llvm::Function *get() { return &F; } Value arg(size_t num) { assert(num < Args.size()); return Value{&CG, Args[num]}; } BasicBlock mkBasicBlock(std::string name) { llvm::BasicBlock *bb = llvm::BasicBlock::Create(CG.Context, name, &F); return {CG, *bb}; } BasicBlock mkAndSetBasicBlock(std::string name) { auto bb = mkBasicBlock(std::move(name)); bb.set(); return bb; } }; Function mkFunction(std::string name, Type ret_type, std::vector<std::pair<Type, std::string>> args = {}) { std::vector<llvm::Type*> args_type; args_type.reserve(args.size()); for (auto arg : args) { args_type.push_back(arg.first.get()); } llvm::FunctionType *funcType = llvm::FunctionType::get(ret_type.get(), args_type, false); llvm::Function *func = llvm::Function::Create( funcType, llvm::Function::ExternalLinkage, name, &M); int count = 0; for (auto &arg : func->args()) { arg.setName(args[count++].second); } return Function{*this, *func}; } // --------------------------- Phi node ------------------------------------ struct Phi { LLVMCodeGen *CG; llvm::Value *V; Phi(LLVMCodeGen *cg, llvm::Value *v) : CG(cg), V(v) {} llvm::Value *get() { return V; } operator Value() { return {CG, V}; } }; Phi mkPhi(Type type, std::vector<std::pair<Value, BasicBlock>> edge_list) { llvm::PHINode *phi = Builder.CreatePHI(type.get(), edge_list.size()); for (auto &edge : edge_list) { phi->addIncoming(edge.first.get(), edge.second.get()); } return {this, phi}; } // ------------- type & vals Type mkIntTy() { return Type(*this, Type::int32); } Value mkInt(int val) { return {this, Builder.getInt32(val)}; } Type mkFloatTy() { return Type(*this, Type::float32); } Type mkDoubleTy() { return Type(*this, Type::float64); } //-------------------- Ops void mkRet(Value val) { Builder.CreateRet(val.get()); } }; static llvm::LLVMContext &ContextRef = llvm::getGlobalContext(); static llvm::Module *ModuleOb = new llvm::Module("my compiler", ContextRef); int main(int argc, char *argv[]) { static llvm::IRBuilder<> BuilderObj(ContextRef); LLVMCodeGen cg(ContextRef, *ModuleOb, BuilderObj); auto gvar = cg.mkGlobalVar("x", cg.mkFloatTy()); auto f = cg.mkFunction("foo", cg.mkIntTy(), {{cg.mkIntTy(), "a"}, {cg.mkFloatTy(), "b"}}); auto thenBB = f.mkAndSetBasicBlock("then"); auto then_val = f.arg(0) + cg.mkInt(1); auto elseBB = f.mkAndSetBasicBlock("else"); auto else_val = f.arg(1) + cg.mkInt(2); auto mergeBB = f.mkAndSetBasicBlock("cont"); auto phi = cg.mkPhi(cg.mkIntTy(), {{then_val, thenBB}, {else_val, elseBB}}); cg.mkRet(phi); auto entry = f.mkAndSetBasicBlock("entry"); auto val = cg.mkInt(100); auto cmp = f.arg(0) < val; auto cnd = cmp != cg.mkInt(0); cnd.mkIfThenElse(thenBB, elseBB, mergeBB); f.verify(); cg.dump(); return 0; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ #include "../StroikaPreComp.h" #include <algorithm> #include <cstdlib> #include "../../Foundation/Characters/ToString.h" #include "../../Foundation/Containers/Common.h" #include "../../Foundation/DataExchange/BadFormatException.h" #include "../../Foundation/Debug/Assertions.h" #include "../../Foundation/Debug/Trace.h" #include "../../Foundation/Execution/Sleep.h" #include "../../Foundation/Execution/Throw.h" #include "../../Foundation/IO/Network/HTTP/Exception.h" #include "../../Foundation/IO/Network/HTTP/Headers.h" #include "../../Foundation/IO/Network/HTTP/Methods.h" #include "../../Foundation/Memory/SmallStackBuffer.h" #include "DefaultFaultInterceptor.h" #include "ConnectionManager.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Memory; using namespace Stroika::Frameworks; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Frameworks::WebServer; using Execution::Thread; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 namespace { struct ServerHeadersInterceptor_ : public Interceptor { struct Rep_ : Interceptor::_IRep { Rep_ (const optional<String>& serverHeader, ConnectionManager::CORSModeSupport corsSupportMode) : fServerHeader_ (serverHeader) , fCORSModeSupport (corsSupportMode) { } virtual void HandleFault ([[maybe_unused]] Message* m, [[maybe_unused]] const exception_ptr& e) noexcept override { } virtual void HandleMessage (Message* m) override { Response& response = *m->PeekResponse (); if (fServerHeader_) { response.AddHeader (IO::Network::HTTP::HeaderName::kServer, *fServerHeader_); } if (fCORSModeSupport == ConnectionManager::CORSModeSupport::eSuppress) { /* * From what I gather from https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS - the Allow-Origin is needed * on all responses, but these others just when you do a preflight - using OPTIONS. */ response.AddHeader (IO::Network::HTTP::HeaderName::kAccessControlAllowOrigin, L"*"sv); if (m->PeekRequest ()->GetHTTPMethod () == IO::Network::HTTP::Methods::kOptions) { response.AddHeader (IO::Network::HTTP::HeaderName::kAccessControlAllowCredentials, L"true"sv); response.AddHeader (IO::Network::HTTP::HeaderName::kAccessControlAllowHeaders, L"Accept, Access-Control-Allow-Origin, Authorization, Cache-Control, Content-Type, Connection, Pragma, X-Requested-With"sv); response.AddHeader (IO::Network::HTTP::HeaderName::kAccessControlAllowMethods, L"DELETE, GET, OPTIONS, POST, PUT, TRACE, UPDATE"sv); response.AddHeader (IO::Network::HTTP::HeaderName::kAccessControlMaxAge, L"86400"sv); } } } const optional<String> fServerHeader_; // no need for synchronization cuz constant - just set on construction const ConnectionManager::CORSModeSupport fCORSModeSupport; }; ServerHeadersInterceptor_ (const optional<String>& serverHeader, ConnectionManager::CORSModeSupport corsSupportMode) : Interceptor (make_shared<Rep_> (serverHeader, corsSupportMode)) { } }; } namespace { Sequence<Interceptor> mkEarlyInterceptors_ (const optional<Interceptor>& defaultFaultHandler, const Interceptor& serverEtcInterceptor) { Sequence<Interceptor> interceptors; interceptors += serverEtcInterceptor; if (defaultFaultHandler) { interceptors += *defaultFaultHandler; } return interceptors; } InterceptorChain mkInterceptorChain_ (const Router& router, const Sequence<Interceptor>& earlyInterceptors, const Sequence<Interceptor>& beforeInterceptors, const Sequence<Interceptor>& afterInterceptors) { Sequence<Interceptor> interceptors; interceptors += earlyInterceptors; interceptors += beforeInterceptors; interceptors += router; interceptors += afterInterceptors; return InterceptorChain{interceptors}; } } /* ******************************************************************************** ***************** WebServer::ConnectionManager::Options ************************ ******************************************************************************** */ constexpr unsigned int ConnectionManager::Options::kDefault_MaxConnections; constexpr Socket::BindFlags ConnectionManager::Options::kDefault_BindFlags; const optional<String> ConnectionManager::Options::kDefault_ServerHeader = L"Stroika/2.0"sv; constexpr ConnectionManager::CORSModeSupport ConnectionManager::Options::kDefault_CORSModeSupport; constexpr Time::DurationSecondsType ConnectionManager::Options::kDefault_AutomaticTCPDisconnectOnClose; constexpr optional<int> ConnectionManager::Options::kDefault_Linger; /* ******************************************************************************** ************************* WebServer::ConnectionManager ************************* ******************************************************************************** */ const ConnectionManager::Options ConnectionManager::kDefaultOptions; ConnectionManager::ConnectionManager (const SocketAddress& bindAddress, const Router& router, const Options& options) : ConnectionManager (Sequence<SocketAddress>{bindAddress}, router, options) { } namespace { inline unsigned int ComputeThreadPoolSize_ (const ConnectionManager::Options& options) { using Options = ConnectionManager::Options; constexpr unsigned int kMinThreadCnt_{1u}; // one enough now that we support separate thread doing epoll/select and one read when data avail return Math::AtLeast (kMinThreadCnt_, options.fMaxConnections.value_or (Options::kDefault_MaxConnections) / 10); } inline unsigned int ComputeConnectionBacklog_ (const ConnectionManager::Options& options) { using Options = ConnectionManager::Options; constexpr unsigned int kMinDefaultTCPBacklog_{3u}; return options.fTCPBacklog.value_or (Math::AtLeast (kMinDefaultTCPBacklog_, options.fMaxConnections.value_or (Options::kDefault_MaxConnections) * 3 / 4)); } } ConnectionManager::ConnectionManager (const Traversal::Iterable<SocketAddress>& bindAddresses, const Router& router, const Options& options) : fServerHeader_ (Memory::OptionalValue (options.fServerHeader, Options::kDefault_ServerHeader)) , fCORSModeSupport_ (options.fCORSModeSupport.value_or (Options::kDefault_CORSModeSupport)) , fServerAndCORSEtcInterceptor_{ServerHeadersInterceptor_{fServerHeader_, fCORSModeSupport_}} , fDefaultErrorHandler_ (DefaultFaultInterceptor{}) , fEarlyInterceptors_{mkEarlyInterceptors_ (fDefaultErrorHandler_, fServerAndCORSEtcInterceptor_)} , fBeforeInterceptors_{} , fAfterInterceptors_{} , fLinger_ (Memory::OptionalValue (options.fLinger, Options::kDefault_Linger)) , fAutomaticTCPDisconnectOnClose_ (options.fAutomaticTCPDisconnectOnClose.value_or (Options::kDefault_AutomaticTCPDisconnectOnClose)) , fRouter_ (router) , fInterceptorChain_{mkInterceptorChain_ (fRouter_, fEarlyInterceptors_, fBeforeInterceptors_, fAfterInterceptors_)} , fActiveConnectionThreads_{ComputeThreadPoolSize_ (options), options.fThreadPoolName} // implementation detail - due to EXPENSIVE blcoking read strategy - see https://stroika.atlassian.net/browse/STK-638 , fListener_{bindAddresses, options.fBindFlags.value_or (Options::kDefault_BindFlags), [this] (const ConnectionOrientedStreamSocket::Ptr& s) { onConnect_ (s); }, ComputeConnectionBacklog_ (options)} , fWaitForReadyConnectionThread_{Execution::Thread::CleanupPtr::eAbortBeforeWaiting, Thread::New ([this] () { WaitForReadyConnectionLoop_ (); }, L"ConnectionMgr-Wait4IOReady"_k)} { fWaitForReadyConnectionThread_.Start (); // start here instead of autostart so a guaranteed initialized before thead main starts - see https://stroika.atlassian.net/browse/STK-706 } void ConnectionManager::onConnect_ (const ConnectionOrientedStreamSocket::Ptr& s) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (Stroika_Foundation_Debug_OptionalizeTraceArgs (L"ConnectionManager::onConnect_", L"s=%s", Characters::ToString (s).c_str ())); #endif s.SetAutomaticTCPDisconnectOnClose (GetAutomaticTCPDisconnectOnClose ()); s.SetLinger (GetLinger ()); // 'missing' has meaning (feature disabled) for socket, so allow setting that too - doesn't mean don't pass on/use-default shared_ptr<Connection> conn = make_shared<Connection> (s, fInterceptorChain_); fInactiveOpenConnections_.rwget ()->Add (conn, s.GetNativeSocket ()); fWaitForReadyConnectionThread_.Interrupt (); // wakeup so checks this one too #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"In onConnect_ (after adding connection): fActiveConnections_=%s, fInactiveOpenConnections_=%s", Characters::ToString (fActiveConnections_.cget ().cref ()).c_str (), Characters::ToString (fInactiveOpenConnections_.cget ().cref ()).c_str ()); #endif } void ConnectionManager::WaitForReadyConnectionLoop_ () { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (Stroika_Foundation_Debug_OptionalizeTraceArgs (L"ConnectionManager::WaitForReadyConnectionLoop_")); #endif // run til thread aboorted while (true) { try { Execution::CheckForThreadInterruption (); Bijection<shared_ptr<Connection>, Execution::WaitForIOReady<>::SDKPollableType> seeIfReady = fInactiveOpenConnections_.cget ().cref (); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"At top of WaitForReadyConnectionLoop_: fActiveConnections_=%s, fInactiveOpenConnections_=%s", Characters::ToString (fActiveConnections_.cget ().cref ()).c_str (), Characters::ToString (fInactiveOpenConnections_.cget ().cref ()).c_str ()); #endif // This will wake up early if another thread adds an inactive connection (thread gets interruppted) if (seeIfReady.Image ().empty ()) { Execution::Sleep (2h); // can be any amount of time, since we will be interuppted continue; } Execution::WaitForIOReady sockSetPoller{seeIfReady.Image ()}; for (auto readyFD : sockSetPoller.WaitQuietly ()) { shared_ptr<Connection> conn = *seeIfReady.InverseLookup (readyFD); Execution::Thread::SuppressInterruptionInContext suppressInterruption; // @todo these three steps SB atomic/and transactional fInactiveOpenConnections_.rwget ().rwref ().RemoveDomainElement (conn); fActiveConnections_.rwget ().rwref ().Add (conn); fActiveConnectionThreads_.AddTask ( [this, conn] () mutable { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (Stroika_Foundation_Debug_OptionalizeTraceArgs (L"ConnectionManager::...processConnectionLoop")); #endif bool keepAlive = (conn->ReadAndProcessMessage () == Connection::eTryAgainLater); // no matter what, remove from active connecitons fActiveConnections_.rwget ().rwref ().Remove (conn); if (keepAlive) { fInactiveOpenConnections_.rwget ().rwref ().Add (conn, conn->GetSocket ().GetNativeSocket ()); fWaitForReadyConnectionThread_.Interrupt (); // wakeup so checks this one too } else { if (conn->GetResponse ().GetState () != Response::State::eCompleted) { IgnoreExceptionsForCall (conn->GetResponse ().End ()); } } #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"at end of read&process task (keepAlive=%s) for connection %s: fActiveConnections_=%s, fInactiveOpenConnections_=%s", Characters::ToString (keepAlive).c_str (), Characters::ToString (conn).c_str (), Characters::ToString (fActiveConnections_.cget ().cref ()).c_str (), Characters::ToString (fInactiveOpenConnections_.cget ().cref ()).c_str ()); #endif }); } } catch (Thread::AbortException&) { Execution::ReThrow (); } catch (Thread::InterruptException&) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Normal receipt of interruption because connection added to open but inactive connections."); #endif // OK - completely ignore - this just means the list of sockets to watch has changed } catch (...) { DbgTrace (L"Internal exception in WaitForReadyConnectionLoop_ loop suppressed: %s", Characters::ToString (current_exception ()).c_str ()); } } } void ConnectionManager::FixupInterceptorChain_ () { fInterceptorChain_ = InterceptorChain{mkInterceptorChain_ (fRouter_, fEarlyInterceptors_, fBeforeInterceptors_, fAfterInterceptors_)}; } void ConnectionManager::ReplaceInEarlyInterceptor_ (const optional<Interceptor>& oldValue, const optional<Interceptor>& newValue) { // replace old error handler in the interceptor chain, in the same spot if possible, and otherwise append auto rwLock = this->fEarlyInterceptors_.rwget (); Sequence<Interceptor> newInterceptors; bool addedDefault = false; for (Interceptor i : rwLock.load ()) { if (oldValue == i) { if (newValue) { newInterceptors += *newValue; } addedDefault = true; } else { newInterceptors += i; } } if (newValue and not addedDefault) { newInterceptors += *newValue; } rwLock.store (newInterceptors); FixupInterceptorChain_ (); } void ConnectionManager::AbortConnection (const shared_ptr<Connection>& /*conn*/) { AssertNotImplemented (); } Collection<shared_ptr<Connection>> ConnectionManager::GetConnections () const { return Collection<shared_ptr<Connection>>{fInactiveOpenConnections_.cget ().cref ().Preimage ()} + fActiveConnections_.cget ().load (); } void ConnectionManager::SetServerHeader (optional<String> server) { if (fServerHeader_ != server) { Interceptor old = fServerAndCORSEtcInterceptor_; fServerAndCORSEtcInterceptor_ = ServerHeadersInterceptor_{server, fCORSModeSupport_}; fServerHeader_ = server; ReplaceInEarlyInterceptor_ (old, fServerAndCORSEtcInterceptor_); } } void ConnectionManager::SetCORSModeSupport (CORSModeSupport support) { if (fCORSModeSupport_ != support) { Interceptor old = fServerAndCORSEtcInterceptor_; fServerAndCORSEtcInterceptor_ = ServerHeadersInterceptor_{fServerHeader_, fCORSModeSupport_}; fCORSModeSupport_ = support; ReplaceInEarlyInterceptor_ (old, fServerAndCORSEtcInterceptor_); } } void ConnectionManager::SetDefaultErrorHandler (const optional<Interceptor>& defaultErrorHandler) { if (fDefaultErrorHandler_ != defaultErrorHandler) { ReplaceInEarlyInterceptor_ (fDefaultErrorHandler_.load (), defaultErrorHandler); fDefaultErrorHandler_ = defaultErrorHandler; } } void ConnectionManager::SetEarlyInterceptors (const Sequence<Interceptor>& earlyInterceptors) { fEarlyInterceptors_ = earlyInterceptors; FixupInterceptorChain_ (); } void ConnectionManager::SetBeforeInterceptors (const Sequence<Interceptor>& beforeInterceptors) { fBeforeInterceptors_ = beforeInterceptors; FixupInterceptorChain_ (); } void ConnectionManager::SetAfterInterceptors (const Sequence<Interceptor>& afterInterceptors) { fAfterInterceptors_ = afterInterceptors; FixupInterceptorChain_ (); } void ConnectionManager::AddInterceptor (const Interceptor& i, InterceptorAddRelativeTo relativeTo) { switch (relativeTo) { case ePrependsToEarly: fEarlyInterceptors_.rwget ()->Prepend (i); break; case ePrepend: fBeforeInterceptors_.rwget ()->Prepend (i); break; case eAppend: fAfterInterceptors_.rwget ()->Append (i); break; case eAfterBeforeInterceptors: fBeforeInterceptors_.rwget ()->Append (i); break; } FixupInterceptorChain_ (); } void ConnectionManager::RemoveInterceptor (const Interceptor& i) { bool found = false; { auto b4 = fBeforeInterceptors_.rwget (); if (optional<size_t> idx = b4->IndexOf (i)) { b4->Remove (*idx); found = true; } } if (not found) { auto after = fAfterInterceptors_.rwget (); if (optional<size_t> idx = after->IndexOf (i)) { after->Remove (*idx); found = true; } } Require (found); FixupInterceptorChain_ (); } <commit_msg>cosmetic<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ #include "../StroikaPreComp.h" #include <algorithm> #include <cstdlib> #include "../../Foundation/Characters/ToString.h" #include "../../Foundation/Containers/Common.h" #include "../../Foundation/DataExchange/BadFormatException.h" #include "../../Foundation/Debug/Assertions.h" #include "../../Foundation/Debug/Trace.h" #include "../../Foundation/Execution/Sleep.h" #include "../../Foundation/Execution/Throw.h" #include "../../Foundation/IO/Network/HTTP/Exception.h" #include "../../Foundation/IO/Network/HTTP/Headers.h" #include "../../Foundation/IO/Network/HTTP/Methods.h" #include "../../Foundation/Memory/SmallStackBuffer.h" #include "DefaultFaultInterceptor.h" #include "ConnectionManager.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Memory; using namespace Stroika::Frameworks; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Frameworks::WebServer; using Execution::Thread; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 namespace { struct ServerHeadersInterceptor_ : public Interceptor { struct Rep_ : Interceptor::_IRep { Rep_ (const optional<String>& serverHeader, ConnectionManager::CORSModeSupport corsSupportMode) : fServerHeader_ (serverHeader) , fCORSModeSupport (corsSupportMode) { } virtual void HandleFault ([[maybe_unused]] Message* m, [[maybe_unused]] const exception_ptr& e) noexcept override { } virtual void HandleMessage (Message* m) override { Response& response = *m->PeekResponse (); if (fServerHeader_) { response.AddHeader (IO::Network::HTTP::HeaderName::kServer, *fServerHeader_); } if (fCORSModeSupport == ConnectionManager::CORSModeSupport::eSuppress) { /* * From what I gather from https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS - the Allow-Origin is needed * on all responses, but these others just when you do a preflight - using OPTIONS. */ response.AddHeader (IO::Network::HTTP::HeaderName::kAccessControlAllowOrigin, L"*"sv); if (m->PeekRequest ()->GetHTTPMethod () == IO::Network::HTTP::Methods::kOptions) { response.AddHeader (IO::Network::HTTP::HeaderName::kAccessControlAllowCredentials, L"true"sv); response.AddHeader (IO::Network::HTTP::HeaderName::kAccessControlAllowHeaders, L"Accept, Access-Control-Allow-Origin, Authorization, Cache-Control, Content-Type, Connection, Pragma, X-Requested-With"sv); response.AddHeader (IO::Network::HTTP::HeaderName::kAccessControlAllowMethods, L"DELETE, GET, OPTIONS, POST, PUT, TRACE, UPDATE"sv); response.AddHeader (IO::Network::HTTP::HeaderName::kAccessControlMaxAge, L"86400"sv); } } } const optional<String> fServerHeader_; // no need for synchronization cuz constant - just set on construction const ConnectionManager::CORSModeSupport fCORSModeSupport; }; ServerHeadersInterceptor_ (const optional<String>& serverHeader, ConnectionManager::CORSModeSupport corsSupportMode) : Interceptor (make_shared<Rep_> (serverHeader, corsSupportMode)) { } }; } namespace { Sequence<Interceptor> mkEarlyInterceptors_ (const optional<Interceptor>& defaultFaultHandler, const Interceptor& serverEtcInterceptor) { Sequence<Interceptor> interceptors; interceptors += serverEtcInterceptor; if (defaultFaultHandler) { interceptors += *defaultFaultHandler; } return interceptors; } InterceptorChain mkInterceptorChain_ (const Router& router, const Sequence<Interceptor>& earlyInterceptors, const Sequence<Interceptor>& beforeInterceptors, const Sequence<Interceptor>& afterInterceptors) { Sequence<Interceptor> interceptors; interceptors += earlyInterceptors; interceptors += beforeInterceptors; interceptors += router; interceptors += afterInterceptors; return InterceptorChain{interceptors}; } } /* ******************************************************************************** ***************** WebServer::ConnectionManager::Options ************************ ******************************************************************************** */ constexpr unsigned int ConnectionManager::Options::kDefault_MaxConnections; constexpr Socket::BindFlags ConnectionManager::Options::kDefault_BindFlags; const optional<String> ConnectionManager::Options::kDefault_ServerHeader = L"Stroika/2.0"sv; constexpr ConnectionManager::CORSModeSupport ConnectionManager::Options::kDefault_CORSModeSupport; constexpr Time::DurationSecondsType ConnectionManager::Options::kDefault_AutomaticTCPDisconnectOnClose; constexpr optional<int> ConnectionManager::Options::kDefault_Linger; /* ******************************************************************************** ************************* WebServer::ConnectionManager ************************* ******************************************************************************** */ const ConnectionManager::Options ConnectionManager::kDefaultOptions; ConnectionManager::ConnectionManager (const SocketAddress& bindAddress, const Router& router, const Options& options) : ConnectionManager (Sequence<SocketAddress>{bindAddress}, router, options) { } namespace { inline unsigned int ComputeThreadPoolSize_ (const ConnectionManager::Options& options) { using Options = ConnectionManager::Options; constexpr unsigned int kMinThreadCnt_{1u}; // one enough now that we support separate thread doing epoll/select and one read when data avail return Math::AtLeast (kMinThreadCnt_, options.fMaxConnections.value_or (Options::kDefault_MaxConnections) / 10); } inline unsigned int ComputeConnectionBacklog_ (const ConnectionManager::Options& options) { using Options = ConnectionManager::Options; constexpr unsigned int kMinDefaultTCPBacklog_{3u}; return options.fTCPBacklog.value_or (Math::AtLeast (kMinDefaultTCPBacklog_, options.fMaxConnections.value_or (Options::kDefault_MaxConnections) * 3 / 4)); } } ConnectionManager::ConnectionManager (const Traversal::Iterable<SocketAddress>& bindAddresses, const Router& router, const Options& options) : fServerHeader_ (Memory::OptionalValue (options.fServerHeader, Options::kDefault_ServerHeader)) , fCORSModeSupport_ (options.fCORSModeSupport.value_or (Options::kDefault_CORSModeSupport)) , fServerAndCORSEtcInterceptor_{ServerHeadersInterceptor_{fServerHeader_, fCORSModeSupport_}} , fDefaultErrorHandler_ (DefaultFaultInterceptor{}) , fEarlyInterceptors_{mkEarlyInterceptors_ (fDefaultErrorHandler_, fServerAndCORSEtcInterceptor_)} , fBeforeInterceptors_{} , fAfterInterceptors_{} , fLinger_ (Memory::OptionalValue (options.fLinger, Options::kDefault_Linger)) , fAutomaticTCPDisconnectOnClose_ (options.fAutomaticTCPDisconnectOnClose.value_or (Options::kDefault_AutomaticTCPDisconnectOnClose)) , fRouter_ (router) , fInterceptorChain_{mkInterceptorChain_ (fRouter_, fEarlyInterceptors_, fBeforeInterceptors_, fAfterInterceptors_)} , fActiveConnectionThreads_{ComputeThreadPoolSize_ (options), options.fThreadPoolName} // implementation detail - due to EXPENSIVE blcoking read strategy - see https://stroika.atlassian.net/browse/STK-638 , fListener_{bindAddresses, options.fBindFlags.value_or (Options::kDefault_BindFlags), [this] (const ConnectionOrientedStreamSocket::Ptr& s) { onConnect_ (s); }, ComputeConnectionBacklog_ (options)} , fWaitForReadyConnectionThread_{Execution::Thread::CleanupPtr::eAbortBeforeWaiting, Thread::New ([this] () { WaitForReadyConnectionLoop_ (); }, L"WebServer-ConnectionMgr-Wait4IOReady"_k)} { fWaitForReadyConnectionThread_.Start (); // start here instead of autostart so a guaranteed initialized before thead main starts - see https://stroika.atlassian.net/browse/STK-706 } void ConnectionManager::onConnect_ (const ConnectionOrientedStreamSocket::Ptr& s) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (Stroika_Foundation_Debug_OptionalizeTraceArgs (L"ConnectionManager::onConnect_", L"s=%s", Characters::ToString (s).c_str ())); #endif s.SetAutomaticTCPDisconnectOnClose (GetAutomaticTCPDisconnectOnClose ()); s.SetLinger (GetLinger ()); // 'missing' has meaning (feature disabled) for socket, so allow setting that too - doesn't mean don't pass on/use-default shared_ptr<Connection> conn = make_shared<Connection> (s, fInterceptorChain_); fInactiveOpenConnections_.rwget ()->Add (conn, s.GetNativeSocket ()); fWaitForReadyConnectionThread_.Interrupt (); // wakeup so checks this one too #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"In onConnect_ (after adding connection): fActiveConnections_=%s, fInactiveOpenConnections_=%s", Characters::ToString (fActiveConnections_.cget ().cref ()).c_str (), Characters::ToString (fInactiveOpenConnections_.cget ().cref ()).c_str ()); #endif } void ConnectionManager::WaitForReadyConnectionLoop_ () { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (Stroika_Foundation_Debug_OptionalizeTraceArgs (L"ConnectionManager::WaitForReadyConnectionLoop_")); #endif // run til thread aboorted while (true) { try { Execution::CheckForThreadInterruption (); Bijection<shared_ptr<Connection>, Execution::WaitForIOReady<>::SDKPollableType> seeIfReady = fInactiveOpenConnections_.cget ().cref (); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"At top of WaitForReadyConnectionLoop_: fActiveConnections_=%s, fInactiveOpenConnections_=%s", Characters::ToString (fActiveConnections_.cget ().cref ()).c_str (), Characters::ToString (fInactiveOpenConnections_.cget ().cref ()).c_str ()); #endif // This will wake up early if another thread adds an inactive connection (thread gets interruppted) if (seeIfReady.Image ().empty ()) { Execution::Sleep (2h); // can be any amount of time, since we will be interuppted continue; } Execution::WaitForIOReady sockSetPoller{seeIfReady.Image ()}; for (auto readyFD : sockSetPoller.WaitQuietly ()) { shared_ptr<Connection> conn = *seeIfReady.InverseLookup (readyFD); Execution::Thread::SuppressInterruptionInContext suppressInterruption; // @todo these three steps SB atomic/and transactional fInactiveOpenConnections_.rwget ().rwref ().RemoveDomainElement (conn); fActiveConnections_.rwget ().rwref ().Add (conn); fActiveConnectionThreads_.AddTask ( [this, conn] () mutable { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (Stroika_Foundation_Debug_OptionalizeTraceArgs (L"ConnectionManager::...processConnectionLoop")); #endif bool keepAlive = (conn->ReadAndProcessMessage () == Connection::eTryAgainLater); // no matter what, remove from active connecitons fActiveConnections_.rwget ().rwref ().Remove (conn); if (keepAlive) { fInactiveOpenConnections_.rwget ().rwref ().Add (conn, conn->GetSocket ().GetNativeSocket ()); fWaitForReadyConnectionThread_.Interrupt (); // wakeup so checks this one too } else { if (conn->GetResponse ().GetState () != Response::State::eCompleted) { IgnoreExceptionsForCall (conn->GetResponse ().End ()); } } #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"at end of read&process task (keepAlive=%s) for connection %s: fActiveConnections_=%s, fInactiveOpenConnections_=%s", Characters::ToString (keepAlive).c_str (), Characters::ToString (conn).c_str (), Characters::ToString (fActiveConnections_.cget ().cref ()).c_str (), Characters::ToString (fInactiveOpenConnections_.cget ().cref ()).c_str ()); #endif }); } } catch (Thread::AbortException&) { Execution::ReThrow (); } catch (Thread::InterruptException&) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Normal receipt of interruption because connection added to open but inactive connections."); #endif // OK - completely ignore - this just means the list of sockets to watch has changed } catch (...) { DbgTrace (L"Internal exception in WaitForReadyConnectionLoop_ loop suppressed: %s", Characters::ToString (current_exception ()).c_str ()); } } } void ConnectionManager::FixupInterceptorChain_ () { fInterceptorChain_ = InterceptorChain{mkInterceptorChain_ (fRouter_, fEarlyInterceptors_, fBeforeInterceptors_, fAfterInterceptors_)}; } void ConnectionManager::ReplaceInEarlyInterceptor_ (const optional<Interceptor>& oldValue, const optional<Interceptor>& newValue) { // replace old error handler in the interceptor chain, in the same spot if possible, and otherwise append auto rwLock = this->fEarlyInterceptors_.rwget (); Sequence<Interceptor> newInterceptors; bool addedDefault = false; for (Interceptor i : rwLock.load ()) { if (oldValue == i) { if (newValue) { newInterceptors += *newValue; } addedDefault = true; } else { newInterceptors += i; } } if (newValue and not addedDefault) { newInterceptors += *newValue; } rwLock.store (newInterceptors); FixupInterceptorChain_ (); } void ConnectionManager::AbortConnection (const shared_ptr<Connection>& /*conn*/) { AssertNotImplemented (); } Collection<shared_ptr<Connection>> ConnectionManager::GetConnections () const { return Collection<shared_ptr<Connection>>{fInactiveOpenConnections_.cget ().cref ().Preimage ()} + fActiveConnections_.cget ().load (); } void ConnectionManager::SetServerHeader (optional<String> server) { if (fServerHeader_ != server) { Interceptor old = fServerAndCORSEtcInterceptor_; fServerAndCORSEtcInterceptor_ = ServerHeadersInterceptor_{server, fCORSModeSupport_}; fServerHeader_ = server; ReplaceInEarlyInterceptor_ (old, fServerAndCORSEtcInterceptor_); } } void ConnectionManager::SetCORSModeSupport (CORSModeSupport support) { if (fCORSModeSupport_ != support) { Interceptor old = fServerAndCORSEtcInterceptor_; fServerAndCORSEtcInterceptor_ = ServerHeadersInterceptor_{fServerHeader_, fCORSModeSupport_}; fCORSModeSupport_ = support; ReplaceInEarlyInterceptor_ (old, fServerAndCORSEtcInterceptor_); } } void ConnectionManager::SetDefaultErrorHandler (const optional<Interceptor>& defaultErrorHandler) { if (fDefaultErrorHandler_ != defaultErrorHandler) { ReplaceInEarlyInterceptor_ (fDefaultErrorHandler_.load (), defaultErrorHandler); fDefaultErrorHandler_ = defaultErrorHandler; } } void ConnectionManager::SetEarlyInterceptors (const Sequence<Interceptor>& earlyInterceptors) { fEarlyInterceptors_ = earlyInterceptors; FixupInterceptorChain_ (); } void ConnectionManager::SetBeforeInterceptors (const Sequence<Interceptor>& beforeInterceptors) { fBeforeInterceptors_ = beforeInterceptors; FixupInterceptorChain_ (); } void ConnectionManager::SetAfterInterceptors (const Sequence<Interceptor>& afterInterceptors) { fAfterInterceptors_ = afterInterceptors; FixupInterceptorChain_ (); } void ConnectionManager::AddInterceptor (const Interceptor& i, InterceptorAddRelativeTo relativeTo) { switch (relativeTo) { case ePrependsToEarly: fEarlyInterceptors_.rwget ()->Prepend (i); break; case ePrepend: fBeforeInterceptors_.rwget ()->Prepend (i); break; case eAppend: fAfterInterceptors_.rwget ()->Append (i); break; case eAfterBeforeInterceptors: fBeforeInterceptors_.rwget ()->Append (i); break; } FixupInterceptorChain_ (); } void ConnectionManager::RemoveInterceptor (const Interceptor& i) { bool found = false; { auto b4 = fBeforeInterceptors_.rwget (); if (optional<size_t> idx = b4->IndexOf (i)) { b4->Remove (*idx); found = true; } } if (not found) { auto after = fAfterInterceptors_.rwget (); if (optional<size_t> idx = after->IndexOf (i)) { after->Remove (*idx); found = true; } } Require (found); FixupInterceptorChain_ (); } <|endoftext|>
<commit_before>//============================================================================ // Name : UDPReader.cpp // Author : Rodolfo Lam // Version : // Copyright : (C) 2016 Rodolfo Lam. All Rights Reserved. // Description : Get one DATA-type package and display its contents. //============================================================================ #include "Graphics/Screen.h" #include "Network/MessageParser.h" #include "Util/Math/Vec2D.h" #include <array> #include <iostream> #include <istream> #include <sstream> #include <unordered_map> #include <Poco/ByteOrder.h> #include <Poco/Exception.h> #include <Poco/Net/DatagramSocket.h> #include <Poco/Net/SocketAddress.h> using Poco::ByteOrder; bool waitforEscKey(); int main(int argc, char** argv) { al_init(); al_install_keyboard(); RL::Graphics::Screen screen; Poco::Net::SocketAddress sa(Poco::Net::IPAddress(), 49003); Poco::Net::DatagramSocket dgs; try { dgs.bind(sa, false); } catch (const Poco::Exception &e) { std::cerr << "FATAL ERROR: Is the application already running? Port could not be opened. Details: " << e.message() << std::endl; return EXIT_FAILURE; } std::array<Poco::UInt8, RL::Network::NETMESSAGE_SIZE> buffer; buffer.fill(0); std::unordered_map<RL::Network::DataTypesEnum, std::array<float, 8>, RL::Network::DataTypesEnumHash> parsedData; parsedData.reserve(46); for (auto const &ref : RL::Network::Data_Index) { std::array<float, 8> ar; parsedData.emplace(std::make_pair(ref.second, std::move(ar))); } RL::Network::MessageParser parser; bool exit = false; while (exit != true) { Poco::Net::SocketAddress sender; int n = dgs.receiveFrom(buffer.data(), RL::Network::NETMESSAGE_SIZE, sender); parser.ParsePacket(parsedData, buffer, n); bool success = parser.LastPacketParseCorrect(); std::stringstream debText; debText << "Last Packet time: " << al_get_time() << " | Status: " << success << " | Size: " << n; screen.processCommands(RL::Math::Vec2D<float>(), debText.str()); screen.flipScreen(); // Actually, this might be better placed at the end. exit = waitforEscKey(); } return EXIT_SUCCESS; } bool waitforEscKey() { ALLEGRO_KEYBOARD_STATE state; al_get_keyboard_state(&state); if(&state == nullptr) { return false; } return al_key_down(&state, ALLEGRO_KEY_ESCAPE); } <commit_msg>Set UDP socket Non-blocking<commit_after>//============================================================================ // Name : UDPReader.cpp // Author : Rodolfo Lam // Version : // Copyright : (C) 2016 Rodolfo Lam. All Rights Reserved. // Description : Get one DATA-type package and display its contents. //============================================================================ #include "Graphics/Screen.h" #include "Network/MessageParser.h" #include "Util/Math/Vec2D.h" #include <array> #include <iostream> #include <istream> #include <sstream> #include <unordered_map> #include <Poco/ByteOrder.h> #include <Poco/Exception.h> #include <Poco/Net/DatagramSocket.h> #include <Poco/Net/SocketAddress.h> using Poco::ByteOrder; bool waitforEscKey(); int main(int argc, char** argv) { al_init(); al_install_keyboard(); RL::Graphics::Screen screen; Poco::Net::SocketAddress sa(Poco::Net::IPAddress(), 49003); Poco::Net::DatagramSocket dgs; dgs.setBlocking(false); try { dgs.bind(sa, false); } catch (const Poco::Exception &e) { std::cerr << "FATAL ERROR: Is the application already running? Port could not be opened. Details: " << e.message() << std::endl; return EXIT_FAILURE; } std::array<Poco::UInt8, RL::Network::NETMESSAGE_SIZE> buffer; buffer.fill(0); std::unordered_map<RL::Network::DataTypesEnum, std::array<float, 8>, RL::Network::DataTypesEnumHash> parsedData; parsedData.reserve(46); for (auto const &ref : RL::Network::Data_Index) { std::array<float, 8> ar; parsedData.emplace(std::make_pair(ref.second, std::move(ar))); } RL::Network::MessageParser parser; bool exit = false; while (exit != true) { Poco::Net::SocketAddress sender; int n; try { n = dgs.receiveFrom(buffer.data(), RL::Network::NETMESSAGE_SIZE, sender); } catch (Poco::TimeoutException &e) { std::cerr << "[" << al_get_time() << "] " << "Timeout, no data received" << std::endl; } parser.ParsePacket(parsedData, buffer, n); bool success = parser.LastPacketParseCorrect(); std::stringstream debText; debText << "Last Packet time: " << al_get_time() << " | Status: " << success << " | Size: " << n; screen.processCommands(RL::Math::Vec2D<float>(), debText.str()); screen.flipScreen(); // Actually, this might be better placed at the end. exit = waitforEscKey(); } return EXIT_SUCCESS; } bool waitforEscKey() { ALLEGRO_KEYBOARD_STATE state; al_get_keyboard_state(&state); if(&state == nullptr) { return false; } return al_key_down(&state, ALLEGRO_KEY_ESCAPE); } <|endoftext|>
<commit_before>#include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <imgui.h> #include "aten.h" #include "atenscene.h" #include "idaten.h" #include "scenedefs.h" #define MULTI_GPU_SVGF #define GPU_NUM (2) static int WIDTH = 1280; static int HEIGHT = 720; static const char* TITLE = "multigpu"; #ifdef ENABLE_OMP static uint32_t g_threadnum = 8; #else static uint32_t g_threadnum = 1; #endif static aten::PinholeCamera g_camera; static bool g_isCameraDirty = false; static aten::AcceleratedScene<aten::GPUBvh> g_scene; #ifdef MULTI_GPU_SVGF static idaten::GpuProxy<idaten::SVGFPathTracingMultiGPU> g_tracer[GPU_NUM]; static aten::TAA g_taa; static aten::FBO g_fbo; static aten::RasterizeRenderer g_rasterizer; using GpuProxy = idaten::GpuProxy<idaten::SVGFPathTracingMultiGPU>; #else static idaten::GpuProxy<idaten::PathTracingMultiGPU> g_tracer[GPU_NUM]; using GpuProxy = idaten::GpuProxy<idaten::PathTracingMultiGPU>; #endif #if (GPU_NUM == 4) static const idaten::TileDomain g_tileDomain[4] = { { 0, 0 * HEIGHT / 4, WIDTH, HEIGHT / 4 }, { 0, 1 * HEIGHT / 4, WIDTH, HEIGHT / 4 }, { 0, 2 * HEIGHT / 4, WIDTH, HEIGHT / 4 }, { 0, 3 * HEIGHT / 4, WIDTH, HEIGHT / 4 }, }; #else static const idaten::TileDomain g_tileDomain[2] = { { 0, 0 * HEIGHT / 2, WIDTH, HEIGHT / 2 }, { 0, 1 * HEIGHT / 2, WIDTH, HEIGHT / 2 }, }; #endif static aten::visualizer* g_visualizer = nullptr; static bool g_willShowGUI = true; static bool g_willTakeScreenShot = false; static int g_cntScreenShot = 0; static int g_maxSamples = 1; static int g_maxBounce = 5; void onRun(aten::window* window) { if (g_isCameraDirty) { g_camera.update(); auto camparam = g_camera.param(); camparam.znear = real(0.1); camparam.zfar = real(10000.0); for (int i = 0; i < AT_COUNTOF(g_tracer); i++) { g_tracer[i].getRenderer().updateCamera(camparam); } g_isCameraDirty = false; g_visualizer->clear(); } aten::timer timer; timer.begin(); #ifdef MULTI_GPU_SVGF g_rasterizer.draw( g_tracer[0].getRenderer().frame(), &g_scene, &g_camera, &g_fbo); #endif for (int i = 0; i < AT_COUNTOF(g_tracer); i++) { g_tracer[i].render( g_tileDomain[i], g_maxSamples, g_maxBounce); } #if (GPU_NUM == 4) GpuProxy::swapCopy(g_tracer, AT_COUNTOF(g_tracer)); #else g_tracer[0].copyP2P(g_tracer[1]); #endif g_tracer[0].postRender(WIDTH, HEIGHT); auto cudaelapsed = timer.end(); g_visualizer->render(false); if (g_willTakeScreenShot) { static char buffer[1024]; ::sprintf(buffer, "sc_%d.png\0", g_cntScreenShot); g_visualizer->takeScreenshot(buffer); g_willTakeScreenShot = false; g_cntScreenShot++; AT_PRINTF("Take Screenshot[%s]\n", buffer); } if (g_willShowGUI) { ImGui::Text("%.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::Text("cuda : %.3f ms", cudaelapsed); ImGui::Text("%.3f Mrays/sec", (WIDTH * HEIGHT * g_maxSamples) / real(1000 * 1000) * (real(1000) / cudaelapsed)); window->drawImGui(); } } void onClose() { } bool g_isMouseLBtnDown = false; bool g_isMouseRBtnDown = false; int g_prevX = 0; int g_prevY = 0; void onMouseBtn(bool left, bool press, int x, int y) { g_isMouseLBtnDown = false; g_isMouseRBtnDown = false; if (press) { g_prevX = x; g_prevY = y; g_isMouseLBtnDown = left; g_isMouseRBtnDown = !left; } } void onMouseMove(int x, int y) { if (g_isMouseLBtnDown) { aten::CameraOperator::rotate( g_camera, WIDTH, HEIGHT, g_prevX, g_prevY, x, y); g_isCameraDirty = true; } else if (g_isMouseRBtnDown) { aten::CameraOperator::move( g_camera, g_prevX, g_prevY, x, y, real(0.001)); g_isCameraDirty = true; } g_prevX = x; g_prevY = y; } void onMouseWheel(int delta) { aten::CameraOperator::dolly(g_camera, delta * real(0.1)); g_isCameraDirty = true; } void onKey(bool press, aten::Key key) { static const real offset = real(0.1); if (press) { if (key == aten::Key::Key_F1) { g_willShowGUI = !g_willShowGUI; return; } else if (key == aten::Key::Key_F2) { g_willTakeScreenShot = true; return; } } if (press) { switch (key) { case aten::Key::Key_W: case aten::Key::Key_UP: aten::CameraOperator::moveForward(g_camera, offset); break; case aten::Key::Key_S: case aten::Key::Key_DOWN: aten::CameraOperator::moveForward(g_camera, -offset); break; case aten::Key::Key_D: case aten::Key::Key_RIGHT: aten::CameraOperator::moveRight(g_camera, offset); break; case aten::Key::Key_A: case aten::Key::Key_LEFT: aten::CameraOperator::moveRight(g_camera, -offset); break; case aten::Key::Key_Z: aten::CameraOperator::moveUp(g_camera, offset); break; case aten::Key::Key_X: aten::CameraOperator::moveUp(g_camera, -offset); break; case aten::Key::Key_R: { aten::vec3 pos, at; real vfov; Scene::getCameraPosAndAt(pos, at, vfov); g_camera.init( pos, at, aten::vec3(0, 1, 0), vfov, WIDTH, HEIGHT); } break; default: break; } g_isCameraDirty = true; } } int main() { idaten::initCuda(); aten::timer::init(); aten::OMPUtil::setThreadNum(g_threadnum); aten::initSampler(WIDTH, HEIGHT); auto window = aten::window::init( WIDTH, HEIGHT, TITLE, onRun, onClose, onMouseBtn, onMouseMove, onMouseWheel, onKey); window->enableVSync(false); g_visualizer = aten::visualizer::init(WIDTH, HEIGHT); #ifdef MULTI_GPU_SVGF g_taa.init( WIDTH, HEIGHT, "../shader/fullscreen_vs.glsl", "../shader/taa_fs.glsl", "../shader/fullscreen_vs.glsl", "../shader/taa_final_fs.glsl"); g_visualizer->addPostProc(&g_taa); g_rasterizer.init( WIDTH, HEIGHT, "../shader/ssrt_vs.glsl", "../shader/ssrt_gs.glsl", "../shader/ssrt_fs.glsl"); g_fbo.asMulti(2); g_fbo.init( WIDTH, HEIGHT, aten::PixelFormat::rgba32f, true); g_taa.setMotionDepthBufferHandle(g_fbo.getTexHandle(1)); #endif aten::GammaCorrection gamma; gamma.init( WIDTH, HEIGHT, "../shader/fullscreen_vs.glsl", "../shader/gamma_fs.glsl"); g_visualizer->addPostProc(&gamma); aten::vec3 pos, at; real vfov; Scene::getCameraPosAndAt(pos, at, vfov); g_camera.init( pos, at, aten::vec3(0, 1, 0), vfov, WIDTH, HEIGHT); Scene::makeScene(&g_scene); g_scene.build(); auto envmap = aten::ImageLoader::load("../../asset/envmap/studio015.hdr"); aten::envmap bg; bg.init(envmap); aten::ImageBasedLight ibl(&bg); g_scene.addImageBasedLight(&ibl); std::vector<aten::GeomParameter> shapeparams; std::vector<aten::PrimitiveParamter> primparams; std::vector<aten::LightParameter> lightparams; std::vector<aten::MaterialParameter> mtrlparms; std::vector<aten::vertex> vtxparams; aten::DataCollector::collect( shapeparams, primparams, lightparams, mtrlparms, vtxparams); const auto& nodes = g_scene.getAccel()->getNodes(); const auto& mtxs = g_scene.getAccel()->getMatrices(); std::vector<idaten::TextureResource> tex; { auto texs = aten::texture::getTextures(); for (const auto t : texs) { tex.push_back( idaten::TextureResource(t->colors(), t->width(), t->height())); } } for (auto& l : lightparams) { if (l.type == aten::LightType::IBL) { l.envmap.idx = envmap->id(); } } auto camparam = g_camera.param(); camparam.znear = real(0.1); camparam.zfar = real(10000.0); g_tracer[0].init(0); g_tracer[1].init(1); // Set P2P access between GPUs. g_tracer[0].setPeerAccess(1); g_tracer[1].setPeerAccess(0); #if (GPU_NUM == 4) g_tracer[2].init(2); g_tracer[3].init(3); g_tracer[2].setPeerAccess(3); g_tracer[3].setPeerAccess(2); #endif for (int i = 0; i < AT_COUNTOF(g_tracer); i++) { const auto& tileDomain = g_tileDomain[i]; g_tracer[i].setCurrent(); g_tracer[i].getRenderer().getCompaction().init( tileDomain.w * tileDomain.h, 1024); int w = i == 0 ? WIDTH : tileDomain.w; int h = i == 0 ? HEIGHT : tileDomain.h; h = i == 2 ? HEIGHT / 2 : h; g_tracer[i].getRenderer().update( aten::visualizer::getTexHandle(), w, h, camparam, shapeparams, mtrlparms, lightparams, nodes, primparams, vtxparams, mtxs, tex, idaten::EnvmapResource(envmap->id(), ibl.getAvgIlluminace(), real(4))); #ifdef MULTI_GPU_SVGF g_tracer[i].getRenderer().setGBuffer( g_fbo.getTexHandle(0), g_fbo.getTexHandle(1)); #endif } aten::window::run(); aten::window::terminate(); } <commit_msg>Modify to try for single gpu.<commit_after>#include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <imgui.h> #include "aten.h" #include "atenscene.h" #include "idaten.h" #include "scenedefs.h" #define MULTI_GPU_SVGF #define GPU_NUM (2) static int WIDTH = 1280; static int HEIGHT = 720; static const char* TITLE = "multigpu"; #ifdef ENABLE_OMP static uint32_t g_threadnum = 8; #else static uint32_t g_threadnum = 1; #endif static aten::PinholeCamera g_camera; static bool g_isCameraDirty = false; static aten::AcceleratedScene<aten::GPUBvh> g_scene; #ifdef MULTI_GPU_SVGF static idaten::GpuProxy<idaten::SVGFPathTracingMultiGPU> g_tracer[GPU_NUM]; static aten::TAA g_taa; static aten::FBO g_fbo; static aten::RasterizeRenderer g_rasterizer; using GpuProxy = idaten::GpuProxy<idaten::SVGFPathTracingMultiGPU>; #else static idaten::GpuProxy<idaten::PathTracingMultiGPU> g_tracer[GPU_NUM]; using GpuProxy = idaten::GpuProxy<idaten::PathTracingMultiGPU>; #endif #if (GPU_NUM == 4) static const idaten::TileDomain g_tileDomain[4] = { { 0, 0 * HEIGHT / 4, WIDTH, HEIGHT / 4 }, { 0, 1 * HEIGHT / 4, WIDTH, HEIGHT / 4 }, { 0, 2 * HEIGHT / 4, WIDTH, HEIGHT / 4 }, { 0, 3 * HEIGHT / 4, WIDTH, HEIGHT / 4 }, }; #else static const idaten::TileDomain g_tileDomain[2] = { { 0, 0 * HEIGHT / 2, WIDTH, HEIGHT / 2 }, { 0, 1 * HEIGHT / 2, WIDTH, HEIGHT / 2 }, }; #endif static aten::visualizer* g_visualizer = nullptr; static bool g_willShowGUI = true; static bool g_willTakeScreenShot = false; static int g_cntScreenShot = 0; static int g_maxSamples = 1; static int g_maxBounce = 5; void onRun(aten::window* window) { if (g_isCameraDirty) { g_camera.update(); auto camparam = g_camera.param(); camparam.znear = real(0.1); camparam.zfar = real(10000.0); for (int i = 0; i < AT_COUNTOF(g_tracer); i++) { g_tracer[i].getRenderer().updateCamera(camparam); } g_isCameraDirty = false; g_visualizer->clear(); } aten::timer timer; timer.begin(); #ifdef MULTI_GPU_SVGF g_rasterizer.draw( g_tracer[0].getRenderer().frame(), &g_scene, &g_camera, &g_fbo); #endif for (int i = 0; i < AT_COUNTOF(g_tracer); i++) { g_tracer[i].render( g_tileDomain[i], g_maxSamples, g_maxBounce); } #if (GPU_NUM == 4) GpuProxy::swapCopy(g_tracer, AT_COUNTOF(g_tracer)); #else for (int i = 1; i < AT_COUNTOF(g_tracer); i++) { g_tracer[0].copyP2P(g_tracer[1]); } #endif g_tracer[0].postRender(WIDTH, HEIGHT); auto cudaelapsed = timer.end(); g_visualizer->render(false); if (g_willTakeScreenShot) { static char buffer[1024]; ::sprintf(buffer, "sc_%d.png\0", g_cntScreenShot); g_visualizer->takeScreenshot(buffer); g_willTakeScreenShot = false; g_cntScreenShot++; AT_PRINTF("Take Screenshot[%s]\n", buffer); } if (g_willShowGUI) { ImGui::Text("%.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::Text("cuda : %.3f ms", cudaelapsed); ImGui::Text("%.3f Mrays/sec", (WIDTH * HEIGHT * g_maxSamples) / real(1000 * 1000) * (real(1000) / cudaelapsed)); window->drawImGui(); } } void onClose() { } bool g_isMouseLBtnDown = false; bool g_isMouseRBtnDown = false; int g_prevX = 0; int g_prevY = 0; void onMouseBtn(bool left, bool press, int x, int y) { g_isMouseLBtnDown = false; g_isMouseRBtnDown = false; if (press) { g_prevX = x; g_prevY = y; g_isMouseLBtnDown = left; g_isMouseRBtnDown = !left; } } void onMouseMove(int x, int y) { if (g_isMouseLBtnDown) { aten::CameraOperator::rotate( g_camera, WIDTH, HEIGHT, g_prevX, g_prevY, x, y); g_isCameraDirty = true; } else if (g_isMouseRBtnDown) { aten::CameraOperator::move( g_camera, g_prevX, g_prevY, x, y, real(0.001)); g_isCameraDirty = true; } g_prevX = x; g_prevY = y; } void onMouseWheel(int delta) { aten::CameraOperator::dolly(g_camera, delta * real(0.1)); g_isCameraDirty = true; } void onKey(bool press, aten::Key key) { static const real offset = real(0.1); if (press) { if (key == aten::Key::Key_F1) { g_willShowGUI = !g_willShowGUI; return; } else if (key == aten::Key::Key_F2) { g_willTakeScreenShot = true; return; } } if (press) { switch (key) { case aten::Key::Key_W: case aten::Key::Key_UP: aten::CameraOperator::moveForward(g_camera, offset); break; case aten::Key::Key_S: case aten::Key::Key_DOWN: aten::CameraOperator::moveForward(g_camera, -offset); break; case aten::Key::Key_D: case aten::Key::Key_RIGHT: aten::CameraOperator::moveRight(g_camera, offset); break; case aten::Key::Key_A: case aten::Key::Key_LEFT: aten::CameraOperator::moveRight(g_camera, -offset); break; case aten::Key::Key_Z: aten::CameraOperator::moveUp(g_camera, offset); break; case aten::Key::Key_X: aten::CameraOperator::moveUp(g_camera, -offset); break; case aten::Key::Key_R: { aten::vec3 pos, at; real vfov; Scene::getCameraPosAndAt(pos, at, vfov); g_camera.init( pos, at, aten::vec3(0, 1, 0), vfov, WIDTH, HEIGHT); } break; default: break; } g_isCameraDirty = true; } } int main() { idaten::initCuda(); aten::timer::init(); aten::OMPUtil::setThreadNum(g_threadnum); aten::initSampler(WIDTH, HEIGHT); auto window = aten::window::init( WIDTH, HEIGHT, TITLE, onRun, onClose, onMouseBtn, onMouseMove, onMouseWheel, onKey); window->enableVSync(false); g_visualizer = aten::visualizer::init(WIDTH, HEIGHT); #ifdef MULTI_GPU_SVGF g_taa.init( WIDTH, HEIGHT, "../shader/fullscreen_vs.glsl", "../shader/taa_fs.glsl", "../shader/fullscreen_vs.glsl", "../shader/taa_final_fs.glsl"); g_visualizer->addPostProc(&g_taa); g_rasterizer.init( WIDTH, HEIGHT, "../shader/ssrt_vs.glsl", "../shader/ssrt_gs.glsl", "../shader/ssrt_fs.glsl"); g_fbo.asMulti(2); g_fbo.init( WIDTH, HEIGHT, aten::PixelFormat::rgba32f, true); g_taa.setMotionDepthBufferHandle(g_fbo.getTexHandle(1)); #endif aten::GammaCorrection gamma; gamma.init( WIDTH, HEIGHT, "../shader/fullscreen_vs.glsl", "../shader/gamma_fs.glsl"); g_visualizer->addPostProc(&gamma); aten::vec3 pos, at; real vfov; Scene::getCameraPosAndAt(pos, at, vfov); g_camera.init( pos, at, aten::vec3(0, 1, 0), vfov, WIDTH, HEIGHT); Scene::makeScene(&g_scene); g_scene.build(); auto envmap = aten::ImageLoader::load("../../asset/envmap/studio015.hdr"); aten::envmap bg; bg.init(envmap); aten::ImageBasedLight ibl(&bg); g_scene.addImageBasedLight(&ibl); std::vector<aten::GeomParameter> shapeparams; std::vector<aten::PrimitiveParamter> primparams; std::vector<aten::LightParameter> lightparams; std::vector<aten::MaterialParameter> mtrlparms; std::vector<aten::vertex> vtxparams; aten::DataCollector::collect( shapeparams, primparams, lightparams, mtrlparms, vtxparams); const auto& nodes = g_scene.getAccel()->getNodes(); const auto& mtxs = g_scene.getAccel()->getMatrices(); std::vector<idaten::TextureResource> tex; { auto texs = aten::texture::getTextures(); for (const auto t : texs) { tex.push_back( idaten::TextureResource(t->colors(), t->width(), t->height())); } } for (auto& l : lightparams) { if (l.type == aten::LightType::IBL) { l.envmap.idx = envmap->id(); } } auto camparam = g_camera.param(); camparam.znear = real(0.1); camparam.zfar = real(10000.0); g_tracer[0].init(0); g_tracer[1].init(1); // Set P2P access between GPUs. g_tracer[0].setPeerAccess(1); g_tracer[1].setPeerAccess(0); #if (GPU_NUM == 4) g_tracer[2].init(2); g_tracer[3].init(3); g_tracer[2].setPeerAccess(3); g_tracer[3].setPeerAccess(2); #endif for (int i = 0; i < AT_COUNTOF(g_tracer); i++) { const auto& tileDomain = g_tileDomain[i]; g_tracer[i].setCurrent(); g_tracer[i].getRenderer().getCompaction().init( tileDomain.w * tileDomain.h, 1024); int w = i == 0 ? WIDTH : tileDomain.w; int h = i == 0 ? HEIGHT : tileDomain.h; h = i == 2 ? HEIGHT / 2 : h; g_tracer[i].getRenderer().update( aten::visualizer::getTexHandle(), w, h, camparam, shapeparams, mtrlparms, lightparams, nodes, primparams, vtxparams, mtxs, tex, idaten::EnvmapResource(envmap->id(), ibl.getAvgIlluminace(), real(4))); #ifdef MULTI_GPU_SVGF g_tracer[i].getRenderer().setGBuffer( g_fbo.getTexHandle(0), g_fbo.getTexHandle(1)); #endif } aten::window::run(); aten::window::terminate(); } <|endoftext|>
<commit_before>/*========================================================================= 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.commontk.org/LICENSE 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. =========================================================================*/ // Qt includes #include <QDebug> // CTK includes #include "ctkLogger.h" #include "ctkVTKScalarsToColorsView.h" #include "ctkVTKScalarsToColorsWidget.h" #include "ui_ctkVTKScalarsToColorsWidget.h" // VTK includes #include <vtkAxis.h> #include <vtkChartXY.h> #include <vtkColorTransferControlPointsItem.h> #include <vtkColorTransferFunction.h> #include <vtkColorTransferFunctionItem.h> #include <vtkCompositeControlPointsItem.h> #include <vtkCompositeTransferFunctionItem.h> #include <vtkContextScene.h> #include <vtkLookupTable.h> #include <vtkLookupTableItem.h> #include <vtkPiecewiseControlPointsItem.h> #include <vtkPiecewiseFunction.h> #include <vtkPiecewiseFunctionItem.h> //---------------------------------------------------------------------------- static ctkLogger logger("org.commontk.visualization.vtk.widgets.ctkVTKScalarsToColorsWidget"); //---------------------------------------------------------------------------- class ctkVTKScalarsToColorsWidgetPrivate: public Ui_ctkVTKScalarsToColorsWidget { Q_DECLARE_PUBLIC(ctkVTKScalarsToColorsWidget); protected: ctkVTKScalarsToColorsWidget* const q_ptr; public: ctkVTKScalarsToColorsWidgetPrivate(ctkVTKScalarsToColorsWidget& object); void setupUi(QWidget* widget); bool blockSignals(bool); vtkControlPointsItem* CurrentControlPointsItem; }; // ---------------------------------------------------------------------------- // ctkVTKScalarsToColorsWidgetPrivate methods // ---------------------------------------------------------------------------- ctkVTKScalarsToColorsWidgetPrivate::ctkVTKScalarsToColorsWidgetPrivate( ctkVTKScalarsToColorsWidget& object) : q_ptr(&object) { this->CurrentControlPointsItem = 0; } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidgetPrivate::setupUi(QWidget* widget) { Q_Q(ctkVTKScalarsToColorsWidget); this->Ui_ctkVTKScalarsToColorsWidget::setupUi(widget); QObject::connect(this->View, SIGNAL(plotAdded(vtkPlot*)), q, SLOT(onPlotAdded(vtkPlot*))); QObject::connect(this->View, SIGNAL(boundsChanged()), q, SLOT(onBoundsChanged())); this->PointIdSpinBox->setSpecialValueText("None"); QObject::connect(this->PointIdSpinBox, SIGNAL(valueChanged(int)), q, SLOT(onCurrentPointChanged(int))); this->PointIdSpinBox->setValue(-1); QObject::connect(this->ColorPickerButton, SIGNAL(colorChanged(const QColor&)), q, SLOT(onColorChanged(const QColor&))); QObject::connect(this->OpacitySpinBox, SIGNAL(valueChanged(double)), q, SLOT(onOpacityChanged(double))); QObject::connect(this->MidPointSpinBox, SIGNAL(valueChanged(double)), q, SLOT(onMidPointChanged(double))); QObject::connect(this->SharpnessSpinBox, SIGNAL(valueChanged(double)), q, SLOT(onSharpnessChanged(double))); this->ColorPickerButton->setVisible(false); this->OpacityLabel->setVisible(false); this->OpacitySpinBox->setVisible(false); QObject::connect(this->XRangeSlider, SIGNAL(valuesChanged(double, double)), q, SLOT(onXRangeChanged(double, double))); QObject::connect(this->YRangeSlider, SIGNAL(valuesChanged(double, double)), q, SLOT(onYRangeChanged(double, double))); q->qvtkConnect(this->View->chart()->GetAxis(0),vtkCommand::ModifiedEvent, q, SLOT(onAxesModified())); q->qvtkConnect(this->View->chart()->GetAxis(1),vtkCommand::ModifiedEvent, q, SLOT(onAxesModified())); } // ---------------------------------------------------------------------------- bool ctkVTKScalarsToColorsWidget::blockSignals(bool block) { d->ColorPickerButton->blockSignals(block); d->OpacitySpinBox->blockSignals(block); d->MidPointSpinBox->blockSignals(block); return d->SharpnessSpinBox->blockSignals(block); } // ---------------------------------------------------------------------------- // ctkVTKScalarsToColorsWidget methods // ---------------------------------------------------------------------------- ctkVTKScalarsToColorsWidget::ctkVTKScalarsToColorsWidget(QWidget* parentWidget) :QWidget(parentWidget) , d_ptr(new ctkVTKScalarsToColorsWidgetPrivate(*this)) { Q_D(ctkVTKScalarsToColorsWidget); d->setupUi(this); } // ---------------------------------------------------------------------------- ctkVTKScalarsToColorsWidget::~ctkVTKScalarsToColorsWidget() { } // ---------------------------------------------------------------------------- ctkVTKScalarsToColorsView* ctkVTKScalarsToColorsWidget::view()const { Q_D(const ctkVTKScalarsToColorsWidget); return d->View; } // ---------------------------------------------------------------------------- bool ctkVTKScalarsToColorsWidget::isHorizontalSliderVisible()const { Q_D(const ctkVTKScalarsToColorsWidget); return d->XRangeSlider->isVisibleTo( const_cast<ctkVTKScalarsToColorsWidget*>(this)); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::setHorizontalSliderVisible(bool visible) { Q_D(ctkVTKScalarsToColorsWidget); d->XRangeSlider->setVisible(visible); } // ---------------------------------------------------------------------------- bool ctkVTKScalarsToColorsWidget::isVerticalSliderVisible()const { Q_D(const ctkVTKScalarsToColorsWidget); return d->YRangeSlider->isVisibleTo( const_cast<ctkVTKScalarsToColorsWidget*>(this)); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::setVerticalSliderVisible(bool visible) { Q_D(ctkVTKScalarsToColorsWidget); d->YRangeSlider->setVisible(visible); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onPlotAdded(vtkPlot* plot) { if (vtkControlPointsItem::SafeDownCast(plot)) { this->qvtkConnect(plot, vtkControlPointsItem::CurrentPointChangedEvent, this, SLOT(setCurrentPoint(vtkObject*, void*))); } } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onBoundsChanged() { Q_D(ctkVTKScalarsToColorsWidget); double bounds[8]; d->View->chartBounds(bounds); d->XRangeSlider->setMinimum(bounds[vtkAxis::BOTTOM * 2]); d->XRangeSlider->setMaximum(bounds[vtkAxis::BOTTOM * 2 + 1]); d->YRangeSlider->setMinimum(bounds[vtkAxis::LEFT * 2]); d->YRangeSlider->setMaximum(bounds[vtkAxis::LEFT * 2 + 1]); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::setCurrentPoint(vtkObject* caller, void* callData) { vtkControlPointsItem* controlPoints = reinterpret_cast<vtkControlPointsItem*>(caller); long newPoint = reinterpret_cast<long>(callData); if (!controlPoints || newPoint < -1) { return; } this->setCurrentControlPointsItem(controlPoints); this->setCurrentPoint(newPoint); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::setCurrentPoint(int newPoint) { Q_D(ctkVTKScalarsToColorsWidget); d->PointIdSpinBox->setValue(newPoint); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::setCurrentControlPointsItem(vtkControlPointsItem* item) { Q_D(ctkVTKScalarsToColorsWidget); if (d->CurrentControlPointsItem == item) { return; } this->qvtkReconnect(d->CurrentControlPointsItem, item, vtkCommand::ModifiedEvent, this, SLOT(updateCurrentPoint())); this->qvtkReconnect(d->CurrentControlPointsItem ? d->CurrentControlPointsItem->GetXAxis() : d->View->chart()->GetAxis(0), item ? item->GetXAxis() : d->View->chart()->GetAxis(0), vtkCommand::ModifiedEvent, this, SLOT(onAxesModified())); this->qvtkReconnect(d->CurrentControlPointsItem ? d->CurrentControlPointsItem->GetYAxis() : d->View->chart()->GetAxis(1), item ? item->GetYAxis() : d->View->chart()->GetAxis(1), vtkCommand::ModifiedEvent, this, SLOT(onAxesModified())); d->CurrentControlPointsItem = item; if (item) { d->ColorPickerButton->setVisible( vtkColorTransferControlPointsItem::SafeDownCast(item) != 0 || vtkCompositeControlPointsItem::SafeDownCast(item) != 0); d->OpacityLabel->setVisible(vtkPiecewiseControlPointsItem::SafeDownCast(item) != 0 || vtkCompositeControlPointsItem::SafeDownCast(item) != 0); d->OpacitySpinBox->setVisible(vtkPiecewiseControlPointsItem::SafeDownCast(item) != 0 || vtkCompositeControlPointsItem::SafeDownCast(item) != 0); this->onAxesModified(); } d->PointIdSpinBox->setEnabled(item != 0); d->PointIdSpinBox->setMaximum((item ? item->GetNumberOfPoints() : 0) - 1); d->PointIdSpinBox->setValue(item ? item->GetCurrentPoint() : -1); this->updateCurrentPoint(); } // ---------------------------------------------------------------------------- vtkControlPointsItem* ctkVTKScalarsToColorsWidget::currentControlPointsItem()const { Q_D(const ctkVTKScalarsToColorsWidget); return d->CurrentControlPointsItem; } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onCurrentPointChanged(int currentPoint) { Q_D(ctkVTKScalarsToColorsWidget); if (d->CurrentControlPointsItem) { d->CurrentControlPointsItem->SetCurrentPoint(currentPoint); } d->ColorPickerButton->setEnabled(currentPoint != -1); d->OpacitySpinBox->setEnabled(currentPoint != -1); d->MidPointSpinBox->setEnabled(currentPoint != -1); d->SharpnessSpinBox->setEnabled(currentPoint != -1); if (d->CurrentControlPointsItem) { this->updateCurrentPoint(); } } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::updateCurrentPoint() { Q_D(ctkVTKScalarsToColorsWidget); Q_ASSERT(d->CurrentControlPointsItem); Q_ASSERT(d->PointIdSpinBox->value() == d->CurrentControlPointsItem->GetCurrentPoint()); d->PointIdSpinBox->setMaximum((d->CurrentControlPointsItem ? d->CurrentControlPointsItem->GetNumberOfPoints() : 0) - 1); int pointId = d->PointIdSpinBox->value(); if (pointId == -1) { return; } double point[4]; d->CurrentControlPointsItem->GetControlPoint(pointId, point); bool oldBlock = d->blockSignals(true); d->OpacitySpinBox->setValue(point[1]); d->MidPointSpinBox->setValue(point[2]); d->SharpnessSpinBox->setValue(point[3]); vtkColorTransferControlPointsItem* colorControlPoints = vtkColorTransferControlPointsItem::SafeDownCast(d->CurrentControlPointsItem); if (colorControlPoints) { vtkColorTransferFunction* colorTF = colorControlPoints->GetColorTransferFunction(); double xrgbms[6]; colorTF->GetNodeValue(d->PointIdSpinBox->value(), xrgbms); QColor color = QColor::fromRgbF(xrgbms[1], xrgbms[2], xrgbms[3]); d->ColorPickerButton->setColor(color); } d->blockSignals(oldBlock); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onColorChanged(const QColor& color) { Q_D(ctkVTKScalarsToColorsWidget); if (!color.isValid()) { return; } Q_ASSERT(d->CurrentControlPointsItem); Q_ASSERT(d->PointIdSpinBox->value() != -1); Q_ASSERT(d->PointIdSpinBox->value() == d->CurrentControlPointsItem->GetCurrentPoint()); vtkColorTransferControlPointsItem* colorControlPoints = vtkColorTransferControlPointsItem::SafeDownCast(d->CurrentControlPointsItem); if (colorControlPoints) { vtkColorTransferFunction* colorTF = colorControlPoints->GetColorTransferFunction(); double point[6]; colorTF->GetNodeValue(d->PointIdSpinBox->value(), point); point[1] = color.redF(); point[2] = color.greenF(); point[3] = color.blueF(); colorTF->SetNodeValue(d->PointIdSpinBox->value(), point); } } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onOpacityChanged(double opacity) { Q_D(ctkVTKScalarsToColorsWidget); Q_ASSERT(d->CurrentControlPointsItem); double point[4]; d->CurrentControlPointsItem->GetControlPoint(d->PointIdSpinBox->value(), point); point[1] = opacity; d->CurrentControlPointsItem->SetControlPoint(d->PointIdSpinBox->value(), point); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onMidPointChanged(double midPoint) { Q_D(ctkVTKScalarsToColorsWidget); Q_ASSERT(d->CurrentControlPointsItem); double point[4]; d->CurrentControlPointsItem->GetControlPoint(d->PointIdSpinBox->value(), point); point[2] = midPoint; d->CurrentControlPointsItem->SetControlPoint(d->PointIdSpinBox->value(), point); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onSharpnessChanged(double sharpness) { Q_D(ctkVTKScalarsToColorsWidget); Q_ASSERT(d->CurrentControlPointsItem); double point[4]; d->CurrentControlPointsItem->GetControlPoint(d->PointIdSpinBox->value(), point); point[3] = sharpness; d->CurrentControlPointsItem->SetControlPoint(d->PointIdSpinBox->value(), point); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onXRangeChanged(double min, double max) { Q_D(ctkVTKScalarsToColorsWidget); vtkAxis* xAxis = d->CurrentControlPointsItem ? d->CurrentControlPointsItem->GetXAxis() : d->View->chart()->GetAxis(vtkAxis::BOTTOM); Q_ASSERT(xAxis); xAxis->SetRange(min, max); d->View->scene()->SetDirty(true); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onYRangeChanged(double min, double max) { Q_D(ctkVTKScalarsToColorsWidget); vtkAxis* yAxis = d->CurrentControlPointsItem ? d->CurrentControlPointsItem->GetYAxis() : d->View->chart()->GetAxis(vtkAxis::LEFT); Q_ASSERT(yAxis); yAxis->SetRange(min, max); d->View->scene()->SetDirty(true); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onAxesModified() { Q_D(ctkVTKScalarsToColorsWidget); vtkAxis* xAxis = d->CurrentControlPointsItem ? d->CurrentControlPointsItem->GetXAxis() : d->View->chart()->GetAxis(vtkAxis::BOTTOM); Q_ASSERT(xAxis); d->XRangeSlider->setValues(xAxis->GetMinimum(), xAxis->GetMaximum()); vtkAxis* yAxis = d->CurrentControlPointsItem ? d->CurrentControlPointsItem->GetYAxis() : d->View->chart()->GetAxis(vtkAxis::LEFT); Q_ASSERT(yAxis); d->YRangeSlider->setValues(yAxis->GetMinimum(), yAxis->GetMaximum()); } <commit_msg>Fixup ctkVTKScalarsToColorsWidgetPrivate::blockSignals()<commit_after>/*========================================================================= 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.commontk.org/LICENSE 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. =========================================================================*/ // Qt includes #include <QDebug> // CTK includes #include "ctkLogger.h" #include "ctkVTKScalarsToColorsView.h" #include "ctkVTKScalarsToColorsWidget.h" #include "ui_ctkVTKScalarsToColorsWidget.h" // VTK includes #include <vtkAxis.h> #include <vtkChartXY.h> #include <vtkColorTransferControlPointsItem.h> #include <vtkColorTransferFunction.h> #include <vtkColorTransferFunctionItem.h> #include <vtkCompositeControlPointsItem.h> #include <vtkCompositeTransferFunctionItem.h> #include <vtkContextScene.h> #include <vtkLookupTable.h> #include <vtkLookupTableItem.h> #include <vtkPiecewiseControlPointsItem.h> #include <vtkPiecewiseFunction.h> #include <vtkPiecewiseFunctionItem.h> //---------------------------------------------------------------------------- static ctkLogger logger("org.commontk.visualization.vtk.widgets.ctkVTKScalarsToColorsWidget"); //---------------------------------------------------------------------------- class ctkVTKScalarsToColorsWidgetPrivate: public Ui_ctkVTKScalarsToColorsWidget { Q_DECLARE_PUBLIC(ctkVTKScalarsToColorsWidget); protected: ctkVTKScalarsToColorsWidget* const q_ptr; public: ctkVTKScalarsToColorsWidgetPrivate(ctkVTKScalarsToColorsWidget& object); void setupUi(QWidget* widget); bool blockSignals(bool); vtkControlPointsItem* CurrentControlPointsItem; }; // ---------------------------------------------------------------------------- // ctkVTKScalarsToColorsWidgetPrivate methods // ---------------------------------------------------------------------------- ctkVTKScalarsToColorsWidgetPrivate::ctkVTKScalarsToColorsWidgetPrivate( ctkVTKScalarsToColorsWidget& object) : q_ptr(&object) { this->CurrentControlPointsItem = 0; } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidgetPrivate::setupUi(QWidget* widget) { Q_Q(ctkVTKScalarsToColorsWidget); this->Ui_ctkVTKScalarsToColorsWidget::setupUi(widget); QObject::connect(this->View, SIGNAL(plotAdded(vtkPlot*)), q, SLOT(onPlotAdded(vtkPlot*))); QObject::connect(this->View, SIGNAL(boundsChanged()), q, SLOT(onBoundsChanged())); this->PointIdSpinBox->setSpecialValueText("None"); QObject::connect(this->PointIdSpinBox, SIGNAL(valueChanged(int)), q, SLOT(onCurrentPointChanged(int))); this->PointIdSpinBox->setValue(-1); QObject::connect(this->ColorPickerButton, SIGNAL(colorChanged(const QColor&)), q, SLOT(onColorChanged(const QColor&))); QObject::connect(this->OpacitySpinBox, SIGNAL(valueChanged(double)), q, SLOT(onOpacityChanged(double))); QObject::connect(this->MidPointSpinBox, SIGNAL(valueChanged(double)), q, SLOT(onMidPointChanged(double))); QObject::connect(this->SharpnessSpinBox, SIGNAL(valueChanged(double)), q, SLOT(onSharpnessChanged(double))); this->ColorPickerButton->setVisible(false); this->OpacityLabel->setVisible(false); this->OpacitySpinBox->setVisible(false); QObject::connect(this->XRangeSlider, SIGNAL(valuesChanged(double, double)), q, SLOT(onXRangeChanged(double, double))); QObject::connect(this->YRangeSlider, SIGNAL(valuesChanged(double, double)), q, SLOT(onYRangeChanged(double, double))); q->qvtkConnect(this->View->chart()->GetAxis(0),vtkCommand::ModifiedEvent, q, SLOT(onAxesModified())); q->qvtkConnect(this->View->chart()->GetAxis(1),vtkCommand::ModifiedEvent, q, SLOT(onAxesModified())); } // ---------------------------------------------------------------------------- bool ctkVTKScalarsToColorsWidgetPrivate::blockSignals(bool block) { this->ColorPickerButton->blockSignals(block); this->OpacitySpinBox->blockSignals(block); this->MidPointSpinBox->blockSignals(block); return this->SharpnessSpinBox->blockSignals(block); } // ---------------------------------------------------------------------------- // ctkVTKScalarsToColorsWidget methods // ---------------------------------------------------------------------------- ctkVTKScalarsToColorsWidget::ctkVTKScalarsToColorsWidget(QWidget* parentWidget) :QWidget(parentWidget) , d_ptr(new ctkVTKScalarsToColorsWidgetPrivate(*this)) { Q_D(ctkVTKScalarsToColorsWidget); d->setupUi(this); } // ---------------------------------------------------------------------------- ctkVTKScalarsToColorsWidget::~ctkVTKScalarsToColorsWidget() { } // ---------------------------------------------------------------------------- ctkVTKScalarsToColorsView* ctkVTKScalarsToColorsWidget::view()const { Q_D(const ctkVTKScalarsToColorsWidget); return d->View; } // ---------------------------------------------------------------------------- bool ctkVTKScalarsToColorsWidget::isHorizontalSliderVisible()const { Q_D(const ctkVTKScalarsToColorsWidget); return d->XRangeSlider->isVisibleTo( const_cast<ctkVTKScalarsToColorsWidget*>(this)); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::setHorizontalSliderVisible(bool visible) { Q_D(ctkVTKScalarsToColorsWidget); d->XRangeSlider->setVisible(visible); } // ---------------------------------------------------------------------------- bool ctkVTKScalarsToColorsWidget::isVerticalSliderVisible()const { Q_D(const ctkVTKScalarsToColorsWidget); return d->YRangeSlider->isVisibleTo( const_cast<ctkVTKScalarsToColorsWidget*>(this)); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::setVerticalSliderVisible(bool visible) { Q_D(ctkVTKScalarsToColorsWidget); d->YRangeSlider->setVisible(visible); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onPlotAdded(vtkPlot* plot) { if (vtkControlPointsItem::SafeDownCast(plot)) { this->qvtkConnect(plot, vtkControlPointsItem::CurrentPointChangedEvent, this, SLOT(setCurrentPoint(vtkObject*, void*))); } } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onBoundsChanged() { Q_D(ctkVTKScalarsToColorsWidget); double bounds[8]; d->View->chartBounds(bounds); d->XRangeSlider->setMinimum(bounds[vtkAxis::BOTTOM * 2]); d->XRangeSlider->setMaximum(bounds[vtkAxis::BOTTOM * 2 + 1]); d->YRangeSlider->setMinimum(bounds[vtkAxis::LEFT * 2]); d->YRangeSlider->setMaximum(bounds[vtkAxis::LEFT * 2 + 1]); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::setCurrentPoint(vtkObject* caller, void* callData) { vtkControlPointsItem* controlPoints = reinterpret_cast<vtkControlPointsItem*>(caller); long newPoint = reinterpret_cast<long>(callData); if (!controlPoints || newPoint < -1) { return; } this->setCurrentControlPointsItem(controlPoints); this->setCurrentPoint(newPoint); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::setCurrentPoint(int newPoint) { Q_D(ctkVTKScalarsToColorsWidget); d->PointIdSpinBox->setValue(newPoint); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::setCurrentControlPointsItem(vtkControlPointsItem* item) { Q_D(ctkVTKScalarsToColorsWidget); if (d->CurrentControlPointsItem == item) { return; } this->qvtkReconnect(d->CurrentControlPointsItem, item, vtkCommand::ModifiedEvent, this, SLOT(updateCurrentPoint())); this->qvtkReconnect(d->CurrentControlPointsItem ? d->CurrentControlPointsItem->GetXAxis() : d->View->chart()->GetAxis(0), item ? item->GetXAxis() : d->View->chart()->GetAxis(0), vtkCommand::ModifiedEvent, this, SLOT(onAxesModified())); this->qvtkReconnect(d->CurrentControlPointsItem ? d->CurrentControlPointsItem->GetYAxis() : d->View->chart()->GetAxis(1), item ? item->GetYAxis() : d->View->chart()->GetAxis(1), vtkCommand::ModifiedEvent, this, SLOT(onAxesModified())); d->CurrentControlPointsItem = item; if (item) { d->ColorPickerButton->setVisible( vtkColorTransferControlPointsItem::SafeDownCast(item) != 0 || vtkCompositeControlPointsItem::SafeDownCast(item) != 0); d->OpacityLabel->setVisible(vtkPiecewiseControlPointsItem::SafeDownCast(item) != 0 || vtkCompositeControlPointsItem::SafeDownCast(item) != 0); d->OpacitySpinBox->setVisible(vtkPiecewiseControlPointsItem::SafeDownCast(item) != 0 || vtkCompositeControlPointsItem::SafeDownCast(item) != 0); this->onAxesModified(); } d->PointIdSpinBox->setEnabled(item != 0); d->PointIdSpinBox->setMaximum((item ? item->GetNumberOfPoints() : 0) - 1); d->PointIdSpinBox->setValue(item ? item->GetCurrentPoint() : -1); this->updateCurrentPoint(); } // ---------------------------------------------------------------------------- vtkControlPointsItem* ctkVTKScalarsToColorsWidget::currentControlPointsItem()const { Q_D(const ctkVTKScalarsToColorsWidget); return d->CurrentControlPointsItem; } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onCurrentPointChanged(int currentPoint) { Q_D(ctkVTKScalarsToColorsWidget); if (d->CurrentControlPointsItem) { d->CurrentControlPointsItem->SetCurrentPoint(currentPoint); } d->ColorPickerButton->setEnabled(currentPoint != -1); d->OpacitySpinBox->setEnabled(currentPoint != -1); d->MidPointSpinBox->setEnabled(currentPoint != -1); d->SharpnessSpinBox->setEnabled(currentPoint != -1); if (d->CurrentControlPointsItem) { this->updateCurrentPoint(); } } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::updateCurrentPoint() { Q_D(ctkVTKScalarsToColorsWidget); Q_ASSERT(d->CurrentControlPointsItem); Q_ASSERT(d->PointIdSpinBox->value() == d->CurrentControlPointsItem->GetCurrentPoint()); d->PointIdSpinBox->setMaximum((d->CurrentControlPointsItem ? d->CurrentControlPointsItem->GetNumberOfPoints() : 0) - 1); int pointId = d->PointIdSpinBox->value(); if (pointId == -1) { return; } double point[4]; d->CurrentControlPointsItem->GetControlPoint(pointId, point); bool oldBlock = d->blockSignals(true); d->OpacitySpinBox->setValue(point[1]); d->MidPointSpinBox->setValue(point[2]); d->SharpnessSpinBox->setValue(point[3]); vtkColorTransferControlPointsItem* colorControlPoints = vtkColorTransferControlPointsItem::SafeDownCast(d->CurrentControlPointsItem); if (colorControlPoints) { vtkColorTransferFunction* colorTF = colorControlPoints->GetColorTransferFunction(); double xrgbms[6]; colorTF->GetNodeValue(d->PointIdSpinBox->value(), xrgbms); QColor color = QColor::fromRgbF(xrgbms[1], xrgbms[2], xrgbms[3]); d->ColorPickerButton->setColor(color); } d->blockSignals(oldBlock); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onColorChanged(const QColor& color) { Q_D(ctkVTKScalarsToColorsWidget); if (!color.isValid()) { return; } Q_ASSERT(d->CurrentControlPointsItem); Q_ASSERT(d->PointIdSpinBox->value() != -1); Q_ASSERT(d->PointIdSpinBox->value() == d->CurrentControlPointsItem->GetCurrentPoint()); vtkColorTransferControlPointsItem* colorControlPoints = vtkColorTransferControlPointsItem::SafeDownCast(d->CurrentControlPointsItem); if (colorControlPoints) { vtkColorTransferFunction* colorTF = colorControlPoints->GetColorTransferFunction(); double point[6]; colorTF->GetNodeValue(d->PointIdSpinBox->value(), point); point[1] = color.redF(); point[2] = color.greenF(); point[3] = color.blueF(); colorTF->SetNodeValue(d->PointIdSpinBox->value(), point); } } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onOpacityChanged(double opacity) { Q_D(ctkVTKScalarsToColorsWidget); Q_ASSERT(d->CurrentControlPointsItem); double point[4]; d->CurrentControlPointsItem->GetControlPoint(d->PointIdSpinBox->value(), point); point[1] = opacity; d->CurrentControlPointsItem->SetControlPoint(d->PointIdSpinBox->value(), point); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onMidPointChanged(double midPoint) { Q_D(ctkVTKScalarsToColorsWidget); Q_ASSERT(d->CurrentControlPointsItem); double point[4]; d->CurrentControlPointsItem->GetControlPoint(d->PointIdSpinBox->value(), point); point[2] = midPoint; d->CurrentControlPointsItem->SetControlPoint(d->PointIdSpinBox->value(), point); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onSharpnessChanged(double sharpness) { Q_D(ctkVTKScalarsToColorsWidget); Q_ASSERT(d->CurrentControlPointsItem); double point[4]; d->CurrentControlPointsItem->GetControlPoint(d->PointIdSpinBox->value(), point); point[3] = sharpness; d->CurrentControlPointsItem->SetControlPoint(d->PointIdSpinBox->value(), point); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onXRangeChanged(double min, double max) { Q_D(ctkVTKScalarsToColorsWidget); vtkAxis* xAxis = d->CurrentControlPointsItem ? d->CurrentControlPointsItem->GetXAxis() : d->View->chart()->GetAxis(vtkAxis::BOTTOM); Q_ASSERT(xAxis); xAxis->SetRange(min, max); d->View->scene()->SetDirty(true); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onYRangeChanged(double min, double max) { Q_D(ctkVTKScalarsToColorsWidget); vtkAxis* yAxis = d->CurrentControlPointsItem ? d->CurrentControlPointsItem->GetYAxis() : d->View->chart()->GetAxis(vtkAxis::LEFT); Q_ASSERT(yAxis); yAxis->SetRange(min, max); d->View->scene()->SetDirty(true); } // ---------------------------------------------------------------------------- void ctkVTKScalarsToColorsWidget::onAxesModified() { Q_D(ctkVTKScalarsToColorsWidget); vtkAxis* xAxis = d->CurrentControlPointsItem ? d->CurrentControlPointsItem->GetXAxis() : d->View->chart()->GetAxis(vtkAxis::BOTTOM); Q_ASSERT(xAxis); d->XRangeSlider->setValues(xAxis->GetMinimum(), xAxis->GetMaximum()); vtkAxis* yAxis = d->CurrentControlPointsItem ? d->CurrentControlPointsItem->GetYAxis() : d->View->chart()->GetAxis(vtkAxis::LEFT); Q_ASSERT(yAxis); d->YRangeSlider->setValues(yAxis->GetMinimum(), yAxis->GetMaximum()); } <|endoftext|>
<commit_before>/** @file Record compatibility definitions @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "libts.h" #include "P_RecFile.h" #include "P_RecDefs.h" #include "P_RecUtils.h" //------------------------------------------------------------------------- // RecFileOpenR //------------------------------------------------------------------------- RecHandle RecFileOpenR(const char *file) { RecHandle h_file; return ((h_file =::open(file, O_RDONLY)) < 0) ? REC_HANDLE_INVALID : h_file; } //------------------------------------------------------------------------- // RecFileOpenW //------------------------------------------------------------------------- RecHandle RecFileOpenW(const char *file) { RecHandle h_file; if ((h_file =::open(file, O_WRONLY | O_TRUNC | O_CREAT, 0600)) < 0) { return REC_HANDLE_INVALID; } fcntl(h_file, F_SETFD, 1); return h_file; } //------------------------------------------------------------------------- // RecFileSync //------------------------------------------------------------------------- int RecFileSync(RecHandle h_file) { return (fsync(h_file) == 0) ? REC_ERR_OKAY : REC_ERR_FAIL; } //------------------------------------------------------------------------- // RecFileClose //------------------------------------------------------------------------- int RecFileClose(RecHandle h_file) { return (close(h_file) == 0) ? REC_ERR_OKAY : REC_ERR_FAIL; } //------------------------------------------------------------------------- // RecFileRead //------------------------------------------------------------------------- int RecFileRead(RecHandle h_file, char *buf, int size, int *bytes_read) { if ((*bytes_read =::read(h_file, buf, size)) <= 0) { *bytes_read = 0; return REC_ERR_FAIL; } return REC_ERR_OKAY; } //------------------------------------------------------------------------- // RecFileWrite //------------------------------------------------------------------------- int RecFileWrite(RecHandle h_file, char *buf, int size, int *bytes_written) { if ((*bytes_written =::write(h_file, buf, size)) < 0) { *bytes_written = 0; return REC_ERR_FAIL; } return REC_ERR_OKAY; } //------------------------------------------------------------------------- // RecFileGetSize //------------------------------------------------------------------------- int RecFileGetSize(RecHandle h_file) { struct stat fileStats; fstat(h_file, &fileStats); return (int) fileStats.st_size; } //------------------------------------------------------------------------- // RecFileExists //------------------------------------------------------------------------- int RecFileExists(const char *file) { RecHandle h_file; if ((h_file = RecFileOpenR(file)) == REC_HANDLE_INVALID) { return REC_ERR_FAIL; } RecFileClose(h_file); return REC_ERR_OKAY; } //------------------------------------------------------------------------- // RecPipeCreate //------------------------------------------------------------------------- RecHandle RecPipeCreate(const char *base_path, const char *name) { RecHandle listenfd; RecHandle acceptfd; struct sockaddr_un servaddr; struct sockaddr_un cliaddr; int servaddr_len; socklen_t cliaddr_len; // first, let's disable SIGPIPE (move out later!) struct sigaction act, oact; act.sa_handler = SIG_IGN; sigemptyset(&act.sa_mask); act.sa_flags = 0; act.sa_flags |= SA_RESTART; sigaction(SIGPIPE, &act, &oact); // construct a path/filename for the pipe #define SEPERATOR "/" char path[PATH_NAME_MAX]; snprintf(path, sizeof(path), "%s%s%s", base_path, SEPERATOR, name); #undef SEPERATOR if (strlen(path) > (sizeof(servaddr.sun_path) - 1)) { RecLog(DL_Warning, "[RecPipeCreate] Path name too long; exiting\n"); return REC_HANDLE_INVALID; } unlink(path); if ((listenfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { RecLog(DL_Warning, "[RecPipeCreate] socket error\n"); return REC_HANDLE_INVALID; } // set so that child process doesn't inherit our fd if (fcntl(listenfd, F_SETFD, 1) < 0) { RecLog(DL_Warning, "[RecPipeCreate] fcntl error\n"); return REC_HANDLE_INVALID; } memset(&servaddr, 0, sizeof(servaddr)); servaddr.sun_family = AF_UNIX; ink_strlcpy(servaddr.sun_path, path, sizeof(servaddr.sun_path)); int optval = 1; if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (char *) &optval, sizeof(int)) < 0) { RecLog(DL_Warning, "[RecPipeCreate] setsockopt error\n"); return REC_HANDLE_INVALID; } servaddr_len = sizeof(servaddr.sun_family) + strlen(servaddr.sun_path); if ((bind(listenfd, (struct sockaddr *) &servaddr, servaddr_len)) < 0) { RecLog(DL_Warning, "[RecPipeCreate] bind error\n"); return REC_HANDLE_INVALID; } // listen, backlog of 1 (expecting only one client) if ((listen(listenfd, 1)) < 0) { RecLog(DL_Warning, "[RecPipeCreate] listen error\n"); return REC_HANDLE_INVALID; } // block until we get a connection from the other side cliaddr_len = sizeof(cliaddr); if ((acceptfd = accept(listenfd, (struct sockaddr *) &cliaddr, &cliaddr_len)) < 0) { return REC_HANDLE_INVALID; } close(listenfd); return acceptfd; } //------------------------------------------------------------------------- // RecPipeConnect //------------------------------------------------------------------------- RecHandle RecPipeConnect(const char *base_path, const char *name) { RecHandle sockfd; struct sockaddr_un servaddr; int servaddr_len; // construct a path/filename for the pipe #define SEPERATOR "/" char path[PATH_NAME_MAX]; snprintf(path, sizeof(path), "%s%s%s", base_path, SEPERATOR, name); #undef SEPERATOR if (strlen(path) > (sizeof(servaddr.sun_path) - 1)) { RecLog(DL_Warning, "[RecPipeConnect] Path name too long\n"); return REC_HANDLE_INVALID; } // Setup Connection to LocalManager */ memset((char *) &servaddr, 0, sizeof(servaddr)); servaddr.sun_family = AF_UNIX; ink_strlcpy(servaddr.sun_path, path, sizeof(servaddr.sun_path)); servaddr_len = sizeof(servaddr.sun_family) + strlen(servaddr.sun_path); if ((sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { RecLog(DL_Warning, "[RecPipeConnect] socket error\n"); return REC_HANDLE_INVALID; } // set so that child process doesn't inherit our fd if (fcntl(sockfd, F_SETFD, 1) < 0) { RecLog(DL_Warning, "[RecPipeConnect] fcntl error\n"); close(sockfd); return REC_HANDLE_INVALID; } // blocking connect if ((connect(sockfd, (struct sockaddr *) &servaddr, servaddr_len)) < 0) { RecLog(DL_Warning, "[RecPipeConnect] connect error\n"); close(sockfd); return REC_HANDLE_INVALID; } return sockfd; } //------------------------------------------------------------------------- // RecPipeRead //------------------------------------------------------------------------- int RecPipeRead(RecHandle h_pipe, char *buf, int size) { int bytes_read = 0; int bytes_wanted = size; char *p = buf; while (bytes_wanted > 0) { bytes_read = read(h_pipe, p, bytes_wanted); if (bytes_read < 0) { // FIXME: something more intelligent please! return REC_ERR_FAIL; } bytes_wanted -= bytes_read; p += bytes_read; } return REC_ERR_OKAY; } //------------------------------------------------------------------------- // RecPipeWrite //------------------------------------------------------------------------- int RecPipeWrite(RecHandle h_pipe, char *buf, int size) { int bytes_written = 0; int bytes_to_write = size; char *p = buf; while (bytes_to_write > 0) { bytes_written = write(h_pipe, p, bytes_to_write); if (bytes_written < 0) { // FIXME: something more intelligent please! return REC_ERR_FAIL; } bytes_to_write -= bytes_written; p += bytes_written; } return REC_ERR_OKAY; } //------------------------------------------------------------------------- // RecPipeClose //------------------------------------------------------------------------- int RecPipeClose(RecHandle h_pipe) { return (close(h_pipe) == 0) ? REC_ERR_OKAY : REC_ERR_FAIL; } <commit_msg>TS-1475: Coverity 1021829 Resource leak<commit_after>/** @file Record compatibility definitions @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "libts.h" #include "P_RecFile.h" #include "P_RecDefs.h" #include "P_RecUtils.h" //------------------------------------------------------------------------- // RecFileOpenR //------------------------------------------------------------------------- RecHandle RecFileOpenR(const char *file) { RecHandle h_file; return ((h_file =::open(file, O_RDONLY)) < 0) ? REC_HANDLE_INVALID : h_file; } //------------------------------------------------------------------------- // RecFileOpenW //------------------------------------------------------------------------- RecHandle RecFileOpenW(const char *file) { RecHandle h_file; if ((h_file =::open(file, O_WRONLY | O_TRUNC | O_CREAT, 0600)) < 0) { return REC_HANDLE_INVALID; } fcntl(h_file, F_SETFD, 1); return h_file; } //------------------------------------------------------------------------- // RecFileSync //------------------------------------------------------------------------- int RecFileSync(RecHandle h_file) { return (fsync(h_file) == 0) ? REC_ERR_OKAY : REC_ERR_FAIL; } //------------------------------------------------------------------------- // RecFileClose //------------------------------------------------------------------------- int RecFileClose(RecHandle h_file) { return (close(h_file) == 0) ? REC_ERR_OKAY : REC_ERR_FAIL; } //------------------------------------------------------------------------- // RecFileRead //------------------------------------------------------------------------- int RecFileRead(RecHandle h_file, char *buf, int size, int *bytes_read) { if ((*bytes_read =::read(h_file, buf, size)) <= 0) { *bytes_read = 0; return REC_ERR_FAIL; } return REC_ERR_OKAY; } //------------------------------------------------------------------------- // RecFileWrite //------------------------------------------------------------------------- int RecFileWrite(RecHandle h_file, char *buf, int size, int *bytes_written) { if ((*bytes_written =::write(h_file, buf, size)) < 0) { *bytes_written = 0; return REC_ERR_FAIL; } return REC_ERR_OKAY; } //------------------------------------------------------------------------- // RecFileGetSize //------------------------------------------------------------------------- int RecFileGetSize(RecHandle h_file) { struct stat fileStats; fstat(h_file, &fileStats); return (int) fileStats.st_size; } //------------------------------------------------------------------------- // RecFileExists //------------------------------------------------------------------------- int RecFileExists(const char *file) { RecHandle h_file; if ((h_file = RecFileOpenR(file)) == REC_HANDLE_INVALID) { return REC_ERR_FAIL; } RecFileClose(h_file); return REC_ERR_OKAY; } //------------------------------------------------------------------------- // RecPipeCreate //------------------------------------------------------------------------- RecHandle RecPipeCreate(const char *base_path, const char *name) { RecHandle listenfd; RecHandle acceptfd; struct sockaddr_un servaddr; struct sockaddr_un cliaddr; int servaddr_len; socklen_t cliaddr_len; // first, let's disable SIGPIPE (move out later!) struct sigaction act, oact; act.sa_handler = SIG_IGN; sigemptyset(&act.sa_mask); act.sa_flags = 0; act.sa_flags |= SA_RESTART; sigaction(SIGPIPE, &act, &oact); // construct a path/filename for the pipe #define SEPERATOR "/" char path[PATH_NAME_MAX]; snprintf(path, sizeof(path), "%s%s%s", base_path, SEPERATOR, name); #undef SEPERATOR if (strlen(path) > (sizeof(servaddr.sun_path) - 1)) { RecLog(DL_Warning, "[RecPipeCreate] Path name too long; exiting\n"); return REC_HANDLE_INVALID; } unlink(path); if ((listenfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { RecLog(DL_Warning, "[RecPipeCreate] socket error\n"); return REC_HANDLE_INVALID; } // set so that child process doesn't inherit our fd if (fcntl(listenfd, F_SETFD, 1) < 0) { RecLog(DL_Warning, "[RecPipeCreate] fcntl error\n"); return REC_HANDLE_INVALID; } memset(&servaddr, 0, sizeof(servaddr)); servaddr.sun_family = AF_UNIX; ink_strlcpy(servaddr.sun_path, path, sizeof(servaddr.sun_path)); int optval = 1; if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (char *) &optval, sizeof(int)) < 0) { RecLog(DL_Warning, "[RecPipeCreate] setsockopt error\n"); return REC_HANDLE_INVALID; } servaddr_len = sizeof(servaddr.sun_family) + strlen(servaddr.sun_path); if ((bind(listenfd, (struct sockaddr *) &servaddr, servaddr_len)) < 0) { RecLog(DL_Warning, "[RecPipeCreate] bind error\n"); close(listenfd); return REC_HANDLE_INVALID; } // listen, backlog of 1 (expecting only one client) if ((listen(listenfd, 1)) < 0) { RecLog(DL_Warning, "[RecPipeCreate] listen error\n"); close(listenfd); return REC_HANDLE_INVALID; } // block until we get a connection from the other side cliaddr_len = sizeof(cliaddr); if ((acceptfd = accept(listenfd, (struct sockaddr *) &cliaddr, &cliaddr_len)) < 0) { close(listenfd); return REC_HANDLE_INVALID; } close(listenfd); return acceptfd; } //------------------------------------------------------------------------- // RecPipeConnect //------------------------------------------------------------------------- RecHandle RecPipeConnect(const char *base_path, const char *name) { RecHandle sockfd; struct sockaddr_un servaddr; int servaddr_len; // construct a path/filename for the pipe #define SEPERATOR "/" char path[PATH_NAME_MAX]; snprintf(path, sizeof(path), "%s%s%s", base_path, SEPERATOR, name); #undef SEPERATOR if (strlen(path) > (sizeof(servaddr.sun_path) - 1)) { RecLog(DL_Warning, "[RecPipeConnect] Path name too long\n"); return REC_HANDLE_INVALID; } // Setup Connection to LocalManager */ memset((char *) &servaddr, 0, sizeof(servaddr)); servaddr.sun_family = AF_UNIX; ink_strlcpy(servaddr.sun_path, path, sizeof(servaddr.sun_path)); servaddr_len = sizeof(servaddr.sun_family) + strlen(servaddr.sun_path); if ((sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { RecLog(DL_Warning, "[RecPipeConnect] socket error\n"); return REC_HANDLE_INVALID; } // set so that child process doesn't inherit our fd if (fcntl(sockfd, F_SETFD, 1) < 0) { RecLog(DL_Warning, "[RecPipeConnect] fcntl error\n"); close(sockfd); return REC_HANDLE_INVALID; } // blocking connect if ((connect(sockfd, (struct sockaddr *) &servaddr, servaddr_len)) < 0) { RecLog(DL_Warning, "[RecPipeConnect] connect error\n"); close(sockfd); return REC_HANDLE_INVALID; } return sockfd; } //------------------------------------------------------------------------- // RecPipeRead //------------------------------------------------------------------------- int RecPipeRead(RecHandle h_pipe, char *buf, int size) { int bytes_read = 0; int bytes_wanted = size; char *p = buf; while (bytes_wanted > 0) { bytes_read = read(h_pipe, p, bytes_wanted); if (bytes_read < 0) { // FIXME: something more intelligent please! return REC_ERR_FAIL; } bytes_wanted -= bytes_read; p += bytes_read; } return REC_ERR_OKAY; } //------------------------------------------------------------------------- // RecPipeWrite //------------------------------------------------------------------------- int RecPipeWrite(RecHandle h_pipe, char *buf, int size) { int bytes_written = 0; int bytes_to_write = size; char *p = buf; while (bytes_to_write > 0) { bytes_written = write(h_pipe, p, bytes_to_write); if (bytes_written < 0) { // FIXME: something more intelligent please! return REC_ERR_FAIL; } bytes_to_write -= bytes_written; p += bytes_written; } return REC_ERR_OKAY; } //------------------------------------------------------------------------- // RecPipeClose //------------------------------------------------------------------------- int RecPipeClose(RecHandle h_pipe) { return (close(h_pipe) == 0) ? REC_ERR_OKAY : REC_ERR_FAIL; } <|endoftext|>
<commit_before>#define BOOST_TEST_MAIN #include <lightex/workspace.h> #include <boost/test/unit_test.hpp> namespace { class Tester { public: Tester() : workspace_(lightex::MakeHtmlWorkspace()) {} void check(const std::string& tex_input, const std::string& expected_output) const { std::string error_message; std::string output; const bool result = workspace_->ParseProgram(tex_input, &error_message, &output); BOOST_CHECK(result); if (result) { BOOST_CHECK_EQUAL(output, expected_output); } } void fail(const std::string& tex_input) const { std::string error_message; std::string output; const bool result = workspace_->ParseProgram(tex_input, &error_message, &output); BOOST_CHECK(!result); } private: std::shared_ptr<lightex::Workspace> workspace_; }; } BOOST_AUTO_TEST_CASE(TestSimple) { Tester t; t.check("", ""); t.check(" ", "<p> </p>"); t.check("hello", "<p>hello</p>"); t.check("hello\n\n", "<p>hello</p>"); t.check("hello world", "<p>hello world</p>"); t.check("hello world", "<p>hello world</p>"); t.check("hello\n\nworld", "<p>hello</p><p>world</p>"); t.check("hello\n\n\nworld", "<p>hello</p><p>world</p>"); t.check("hello\n\n\n\nworld", "<p>hello</p><p>world</p>"); } BOOST_AUTO_TEST_CASE(TestComments) { Tester t; t.check("% this is a comment", "<p></p>"); t.check("\\% this is a percent sign", "<p>% this is a percent sign</p>"); t.check("a%\nb", "<p>ab</p>"); t.check("a %\nb", "<p>a b</p>"); t.check("a %\nb", "<p>a b</p>"); t.check("a %\n b", "<p>a b</p>"); t.check("a %\n b", "<p>a b</p>"); t.check("a% \nb", "<p>ab</p>"); t.check("a% \nb%cd", "<p>ab</p>"); t.check("a%%%%%\\%%%%%%%%\\%", "<p>a</p>"); t.check("a%%\\%\\\\%%b\nc", "<p>ac</p>"); t.check("Lorem ipsum% comment starts\ndolor sit amet", "<p>Lorem ipsumdolor sit amet</p>"); t.check( "Lorem ipsum dolor sit amet, % some comment\n" "% more comment\n" "% and more\n" "quis impetus adolescens ei vim, eu quo summo percipit scribentur.", "<p>Lorem ipsum dolor sit amet, quis impetus adolescens ei vim, eu quo summo percipit scribentur.</p>" ); } BOOST_AUTO_TEST_CASE(TestEscaping) { Tester t; t.check("<", "<p>&lt;</p>"); t.check(">", "<p>&gt;</p>"); t.check("'", "<p>&apos;</p>"); t.check("\"", "<p>&quot;</p>"); t.check("\\&", "<p>&amp;</p>"); t.fail("&"); t.fail("\\"); t.fail("\\a"); t.check("\\\\", "<p>\\</p>"); } <commit_msg>Fix tests.<commit_after>#define BOOST_TEST_MAIN #include <lightex/workspace.h> #include <boost/test/unit_test.hpp> namespace { class Tester { public: Tester() : workspace_(lightex::MakeHtmlWorkspace()) {} void check(const std::string& tex_input, const std::string& expected_output) const { std::string error_message; std::string output; const bool result = workspace_->ParseProgram(tex_input, &error_message, &output); BOOST_CHECK(result); if (result) { BOOST_CHECK_EQUAL(output, expected_output); } } void fail(const std::string& tex_input) const { std::string error_message; std::string output; const bool result = workspace_->ParseProgram(tex_input, &error_message, &output); BOOST_CHECK(!result); } private: std::shared_ptr<lightex::Workspace> workspace_; }; } BOOST_AUTO_TEST_CASE(TestSimple) { Tester t; t.check("", ""); t.check(" ", " "); t.check("hello", "<p>hello</p>"); t.check("hello\n\n", "<p>hello</p>"); t.check("hello world", "<p>hello world</p>"); t.check("hello world", "<p>hello world</p>"); t.check("hello\n\nworld", "<p>hello</p><p>world</p>"); t.check("hello\n\n\nworld", "<p>hello</p><p>world</p>"); t.check("hello\n\n\n\nworld", "<p>hello</p><p>world</p>"); } BOOST_AUTO_TEST_CASE(TestComments) { Tester t; t.check("% this is a comment", ""); t.check("\\% this is a percent sign", "<p>% this is a percent sign</p>"); t.check("a%\nb", "<p>ab</p>"); t.check("a %\nb", "<p>a b</p>"); t.check("a %\nb", "<p>a b</p>"); t.check("a %\n b", "<p>a b</p>"); t.check("a %\n b", "<p>a b</p>"); t.check("a% \nb", "<p>ab</p>"); t.check("a% \nb%cd", "<p>ab</p>"); t.check("a%%%%%\\%%%%%%%%\\%", "<p>a</p>"); t.check("a%%\\%\\\\%%b\nc", "<p>ac</p>"); t.check("Lorem ipsum% comment starts\ndolor sit amet", "<p>Lorem ipsumdolor sit amet</p>"); t.check( "Lorem ipsum dolor sit amet, % some comment\n" "% more comment\n" "% and more\n" "quis impetus adolescens ei vim, eu quo summo percipit scribentur.", "<p>Lorem ipsum dolor sit amet, quis impetus adolescens ei vim, eu quo summo percipit scribentur.</p>" ); } BOOST_AUTO_TEST_CASE(TestEscaping) { Tester t; t.check("<", "<p>&lt;</p>"); t.check(">", "<p>&gt;</p>"); t.check("'", "<p>&apos;</p>"); t.check("\"", "<p>&quot;</p>"); t.check("\\&", "<p>&amp;</p>"); t.fail("&"); t.fail("\\"); t.fail("\\a"); t.check("\\\\", "<p>\\</p>"); } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Kirsten Weber #ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH #define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH #include <memory> #include <type_traits> #include <dune/common/exceptions.hh> #include <dune/common/fvector.hh> #include <dune/grid/io/file/vtk.hh> #include <dune/stuff/la/container/interfaces.hh> #include <dune/gdt/space/interface.hh> #include "local.hh" namespace Dune { namespace GDT { template <class SpaceImp, class VectorImp> class ConstDiscreteFunction : public Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType, SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols> { static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value, "SpaceImp has to be derived from SpaceInterface!"); static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>, VectorImp>::value, "VectorImp has to be derived from Stuff::LA::VectorInterface!"); static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value, "Types do not match!"); typedef Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType, SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols> BaseType; typedef ConstDiscreteFunction<SpaceImp, VectorImp> ThisType; public: typedef SpaceImp SpaceType; typedef VectorImp VectorType; typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; static const unsigned int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainFieldType DomainFieldType; typedef typename BaseType::DomainType DomainType; static const unsigned int dimRange = BaseType::dimRange; static const unsigned int dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeFieldType RangeFieldType; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; typedef ConstLocalDiscreteFunction<SpaceType, VectorType> ConstLocalDiscreteFunctionType; ConstDiscreteFunction(const SpaceType& sp, const VectorType& vec, const std::string nm = "dune.gdt.constdiscretefunction") : space_(sp) , vector_(vec) , name_(nm) { assert(vector_.size() == space_.mapper().size() && "Given vector has wrong size!"); } ConstDiscreteFunction(const ThisType& other) : space_(other.space_) , vector_(other.vector_) , name_(other.name_) { } ConstDiscreteFunction(ThisType&& source) : space_(source.space_) , vector_(source.vector_) , name_(std::move(source.name_)) { } ThisType& operator=(const ThisType& other) = delete; ~ConstDiscreteFunction() { } virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } virtual std::string name() const DS_OVERRIDE { return name_; } const SpaceType& space() const { return space_; } const VectorType& vector() const { return vector_; } ConstLocalDiscreteFunctionType local_discrete_function(const EntityType& entity) const { assert(space_.grid_view()->indexSet().contains(entity)); return ConstLocalDiscreteFunctionType(space_, vector_, entity); } virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const DS_OVERRIDE { return std::unique_ptr<ConstLocalDiscreteFunctionType>( new ConstLocalDiscreteFunctionType(local_discrete_function(entity))); } void visualize(const std::string filename, const bool subsampling = true, VTK::OutputType vtk_output_type = VTK::appendedraw) const { BaseType::template visualize<typename SpaceType::GridViewType>( *(space().grid_view()), filename, subsampling, vtk_output_type); } protected: const SpaceType& space_; private: const VectorType& vector_; const std::string name_; }; // class ConstDiscreteFunction template <class SpaceImp, class VectorImp> class DiscreteFunction : public ConstDiscreteFunction<SpaceImp, VectorImp> { typedef ConstDiscreteFunction<SpaceImp, VectorImp> BaseType; typedef DiscreteFunction<SpaceImp, VectorImp> ThisType; public: typedef typename BaseType::SpaceType SpaceType; typedef typename BaseType::VectorType VectorType; typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef LocalDiscreteFunction<SpaceType, VectorType> LocalDiscreteFunctionType; DiscreteFunction(const SpaceType& sp, VectorType& vec, const std::string nm = "dune.gdt.discretefunction") : BaseType(sp, vec, nm) , vector_(vec) { } DiscreteFunction(const ThisType& other) : BaseType(other) , vector_(other.vector_) { } DiscreteFunction(ThisType&& source) : BaseType(std::move(source)) , vector_(source.vector_) { } ThisType& operator=(const ThisType& other) = delete; ~DiscreteFunction() { } virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } VectorType& vector() { return vector_; } LocalDiscreteFunctionType local_discrete_function(const EntityType& entity) { assert(space_.grid_view()->indexSet().contains(entity)); return LocalDiscreteFunctionType(space_, vector_, entity); } private: using BaseType::space_; VectorType& vector_; }; // class DiscreteFunction } // namespace GDT } // namespace Dune #endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH <commit_msg>[discretefunction.default] * allow to get a const local discrete function from a non const function<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Kirsten Weber #ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH #define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH #include <memory> #include <type_traits> #include <dune/common/exceptions.hh> #include <dune/common/fvector.hh> #include <dune/grid/io/file/vtk.hh> #include <dune/stuff/la/container/interfaces.hh> #include <dune/gdt/space/interface.hh> #include "local.hh" namespace Dune { namespace GDT { template <class SpaceImp, class VectorImp> class ConstDiscreteFunction : public Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType, SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols> { static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value, "SpaceImp has to be derived from SpaceInterface!"); static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>, VectorImp>::value, "VectorImp has to be derived from Stuff::LA::VectorInterface!"); static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value, "Types do not match!"); typedef Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType, SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols> BaseType; typedef ConstDiscreteFunction<SpaceImp, VectorImp> ThisType; public: typedef SpaceImp SpaceType; typedef VectorImp VectorType; typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; static const unsigned int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainFieldType DomainFieldType; typedef typename BaseType::DomainType DomainType; static const unsigned int dimRange = BaseType::dimRange; static const unsigned int dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeFieldType RangeFieldType; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; typedef ConstLocalDiscreteFunction<SpaceType, VectorType> ConstLocalDiscreteFunctionType; ConstDiscreteFunction(const SpaceType& sp, const VectorType& vec, const std::string nm = "dune.gdt.constdiscretefunction") : space_(sp) , vector_(vec) , name_(nm) { assert(vector_.size() == space_.mapper().size() && "Given vector has wrong size!"); } ConstDiscreteFunction(const ThisType& other) : space_(other.space_) , vector_(other.vector_) , name_(other.name_) { } ConstDiscreteFunction(ThisType&& source) : space_(source.space_) , vector_(source.vector_) , name_(std::move(source.name_)) { } ThisType& operator=(const ThisType& other) = delete; ~ConstDiscreteFunction() { } virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } virtual std::string name() const DS_OVERRIDE { return name_; } const SpaceType& space() const { return space_; } const VectorType& vector() const { return vector_; } ConstLocalDiscreteFunctionType local_discrete_function(const EntityType& entity) const { assert(space_.grid_view()->indexSet().contains(entity)); return ConstLocalDiscreteFunctionType(space_, vector_, entity); } virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const DS_OVERRIDE { return std::unique_ptr<ConstLocalDiscreteFunctionType>( new ConstLocalDiscreteFunctionType(local_discrete_function(entity))); } void visualize(const std::string filename, const bool subsampling = true, VTK::OutputType vtk_output_type = VTK::appendedraw) const { BaseType::template visualize<typename SpaceType::GridViewType>( *(space().grid_view()), filename, subsampling, vtk_output_type); } protected: const SpaceType& space_; private: const VectorType& vector_; const std::string name_; }; // class ConstDiscreteFunction template <class SpaceImp, class VectorImp> class DiscreteFunction : public ConstDiscreteFunction<SpaceImp, VectorImp> { typedef ConstDiscreteFunction<SpaceImp, VectorImp> BaseType; typedef DiscreteFunction<SpaceImp, VectorImp> ThisType; public: typedef typename BaseType::SpaceType SpaceType; typedef typename BaseType::VectorType VectorType; typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef LocalDiscreteFunction<SpaceType, VectorType> LocalDiscreteFunctionType; DiscreteFunction(const SpaceType& sp, VectorType& vec, const std::string nm = "dune.gdt.discretefunction") : BaseType(sp, vec, nm) , vector_(vec) { } DiscreteFunction(const ThisType& other) : BaseType(other) , vector_(other.vector_) { } DiscreteFunction(ThisType&& source) : BaseType(std::move(source)) , vector_(source.vector_) { } ThisType& operator=(const ThisType& other) = delete; ~DiscreteFunction() { } virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } VectorType& vector() { return vector_; } using BaseType::local_discrete_function; LocalDiscreteFunctionType local_discrete_function(const EntityType& entity) { assert(space_.grid_view()->indexSet().contains(entity)); return LocalDiscreteFunctionType(space_, vector_, entity); } private: using BaseType::space_; VectorType& vector_; }; // class DiscreteFunction } // namespace GDT } // namespace Dune #endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Kirsten Weber #ifndef DUNE_GDT_EVALUATION_ELLIPTIC_HH #define DUNE_GDT_EVALUATION_ELLIPTIC_HH #include <tuple> #include <dune/common/dynmatrix.hh> #include <dune/common/typetraits.hh> #include <dune/stuff/functions/interfaces.hh> #include "interface.hh" namespace Dune { namespace GDT { namespace LocalEvaluation { // forward template< class DiffusionFactorImp, class DiffusionTensorImp = void > class Elliptic; namespace internal { /** * \brief Traits for the Elliptic evaluation. */ template< class DiffusionFactorImp, class DiffusionTensorImp > class EllipticTraits { static_assert(Stuff::is_localizable_function< DiffusionFactorImp >::value, "DiffusionFactorImp has to be a localizable function!"); static_assert(Stuff::is_localizable_function< DiffusionTensorImp >::value, "DiffusionTensorImp has to be a localizable function!"); static_assert(std::is_same< typename DiffusionFactorImp::EntityType, typename DiffusionTensorImp::EntityType >::value, "EntityTypes have to agree!"); static_assert(std::is_same< typename DiffusionFactorImp::DomainFieldType, typename DiffusionTensorImp::DomainFieldType >::value, "DomainFieldTypes have to agree!"); static_assert(DiffusionFactorImp::dimDomain == DiffusionTensorImp::dimDomain, "Dimensions have to agree!"); public: typedef Elliptic< DiffusionFactorImp, DiffusionTensorImp > derived_type; typedef DiffusionFactorImp LocalizableDiffusionFactorFunctionType; typedef DiffusionTensorImp LocalizableDiffusionTensorFunctionType; typedef typename LocalizableDiffusionFactorFunctionType::LocalfunctionType LocalDiffusionFactorFunctionType; typedef typename LocalizableDiffusionTensorFunctionType::LocalfunctionType LocalDiffusionTensorFunctionType; typedef std::tuple< std::shared_ptr< LocalDiffusionFactorFunctionType >, std::shared_ptr< LocalDiffusionTensorFunctionType > > LocalfunctionTupleType; typedef typename LocalizableDiffusionFactorFunctionType::EntityType EntityType; typedef typename LocalizableDiffusionFactorFunctionType::DomainFieldType DomainFieldType; static const unsigned int dimDomain = LocalizableDiffusionFactorFunctionType::dimDomain; }; // class EllipticTraits template< class LocalizableFunctionImp > class EllipticTraits< LocalizableFunctionImp, void > { static_assert(Stuff::is_localizable_function< LocalizableFunctionImp >::value, "LocalizableFunctionImp has to be a localizable function!"); public: typedef LocalizableFunctionImp LocalizableFunctionType; typedef Elliptic< LocalizableFunctionType, void > derived_type; typedef typename LocalizableFunctionType::EntityType EntityType; typedef typename LocalizableFunctionType::DomainFieldType DomainFieldType; typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType; typedef std::tuple< std::shared_ptr< LocalfunctionType > > LocalfunctionTupleType; static const unsigned int dimDomain = LocalizableFunctionType::dimDomain; }; // class EllipticTraits< ..., void > } // namespace internal /** * \brief Computes an elliptic evaluation. */ template< class LocalizableFunctionImp > class Elliptic< LocalizableFunctionImp, void > : public LocalEvaluation::Codim0Interface< internal::EllipticTraits< LocalizableFunctionImp, void >, 2 > { public: typedef internal::EllipticTraits< LocalizableFunctionImp, void > Traits; typedef typename Traits::LocalizableFunctionType LocalizableFunctionType; typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType; typedef typename Traits::EntityType EntityType; typedef typename Traits::DomainFieldType DomainFieldType; static const unsigned int dimDomain = Traits::dimDomain; explicit Elliptic(const LocalizableFunctionType& inducingFunction) : inducingFunction_(inducingFunction) {} LocalfunctionTupleType localFunctions(const EntityType& entity) const { return std::make_tuple(inducingFunction_.local_function(entity)); } /** * \brief extracts the local functions and calls the correct order() method */ template< class R, int rT, int rCT, int rA, int rCA > size_t order(const LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase) const { const auto localFunction = std::get< 0 >(localFuncs); return redirect_order(*localFunction, testBase, ansatzBase); } /** * \brief extracts the local functions and calls the correct evaluate() method */ template< class R, int rT, int rCT, int rA, int rCA > void evaluate(const LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicMatrix< R >& ret) const { const auto localFunction = std::get< 0 >(localFuncs); evaluate(*localFunction, testBase, ansatzBase, localPoint, ret); } /** * \brief Computes an elliptic evaluation for a 2x2 matrix-valued local function and matrix-valued basefunctionsets. * \tparam R RangeFieldType * \note Unfortunately we need this explicit specialization, otherwise the compiler will complain for 1d grids. */ template< class R > void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, 2, 2 >& localFunction, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& testBase, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& ansatzBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicMatrix< R >& ret) const { evaluate_matrix_valued_(localFunction, testBase, ansatzBase, localPoint, ret); } /** * \brief Computes an elliptic evaluation for a 3x3 matrix-valued local function and matrix-valued basefunctionsets. * \tparam R RangeFieldType * \note Unfortunately we need this explicit specialization, otherwise the compiler will complain for 1d grids. */ template< class R > void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, 3, 3 >& localFunction, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& testBase, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& ansatzBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicMatrix< R >& ret) const { evaluate_matrix_valued_(localFunction, testBase, ansatzBase, localPoint, ret); } private: /** * \return localFunction.order() + (testBase.order() - 1) + (ansatzBase.order() - 1) */ template< class R, int rL, int rCL, int rT, int rCT, int rA, int rCA > size_t redirect_order(const Stuff::LocalfunctionInterface < EntityType, DomainFieldType, dimDomain, R, rL, rCL >& localFunction, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase) const { return localFunction.order() + std::max(ssize_t(testBase.order()) - 1, ssize_t(0)) + std::max(ssize_t(ansatzBase.order()) - 1, ssize_t(0)); } // size_t redirect_order( ... ) /** * \brief Computes an elliptic evaluation for a scalar local function and scalar or vector valued basefunctionsets. * \tparam R RangeFieldType */ template< class R, int r > void evaluate(const Stuff::LocalfunctionInterface < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& localFunction, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, r, 1 >& testBase, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, r, 1 >& ansatzBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicMatrix< R >& ret) const { typedef typename Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, r, 1 >::JacobianRangeType JacobianRangeType; // evaluate local function const auto functionValue = localFunction.evaluate(localPoint); // evaluate test gradient const size_t rows = testBase.size(); std::vector< JacobianRangeType > testGradients(rows, JacobianRangeType(0)); testBase.jacobian(localPoint, testGradients); // evaluate ansatz gradient const size_t cols = ansatzBase.size(); std::vector< JacobianRangeType > ansatzGradients(cols, JacobianRangeType(0)); ansatzBase.jacobian(localPoint, ansatzGradients); // compute products assert(ret.rows() >= rows); assert(ret.cols() >= cols); for (size_t ii = 0; ii < rows; ++ii) { auto& retRow = ret[ii]; for (size_t jj = 0; jj < cols; ++jj) { retRow[jj] = functionValue * (ansatzGradients[jj][0] * testGradients[ii][0]); } } } // ... redirect_evaluate< ..., 1, ... >(...) template< class R > void evaluate_matrix_valued_(const Stuff::LocalfunctionInterface < EntityType, DomainFieldType, dimDomain, R, dimDomain, dimDomain >& localFunction, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& testBase, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& ansatzBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicMatrix< R >& ret) const { typedef typename Stuff::LocalfunctionInterface < EntityType, DomainFieldType, dimDomain, R, dimDomain, dimDomain >::RangeType DiffusionRangeType; typedef typename Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, 1, 1 >::JacobianRangeType JacobianRangeType; // evaluate local function const DiffusionRangeType functionValue = localFunction.evaluate(localPoint); // evaluate test gradient const size_t rows = testBase.size(); std::vector< JacobianRangeType > testGradients(rows, JacobianRangeType(0)); testBase.jacobian(localPoint, testGradients); // evaluate ansatz gradient const size_t cols = ansatzBase.size(); std::vector< JacobianRangeType > ansatzGradients(cols, JacobianRangeType(0)); ansatzBase.jacobian(localPoint, ansatzGradients); // compute products assert(ret.rows() >= rows); assert(ret.cols() >= cols); FieldVector< DomainFieldType, dimDomain > product(0.0); for (size_t ii = 0; ii < rows; ++ii) { auto& retRow = ret[ii]; for (size_t jj = 0; jj < cols; ++jj) { functionValue.mv(ansatzGradients[jj][0], product); retRow[jj] = product * testGradients[ii][0]; } } } // ... evaluate_matrix_valued_(...) const LocalizableFunctionType& inducingFunction_; }; // class Elliptic } // namespace Evaluation } // namespace GDT } // namespace Dune #endif // DUNE_GDT_EVALUATION_ELLIPTIC_HH <commit_msg>[localevaluation.elliptic] add safe integer conversion<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Kirsten Weber #ifndef DUNE_GDT_EVALUATION_ELLIPTIC_HH #define DUNE_GDT_EVALUATION_ELLIPTIC_HH #include <tuple> #include <boost/numeric/conversion/cast.hpp> #include <dune/common/dynmatrix.hh> #include <dune/common/typetraits.hh> #include <dune/stuff/functions/interfaces.hh> #include "interface.hh" namespace Dune { namespace GDT { namespace LocalEvaluation { // forward template< class DiffusionFactorImp, class DiffusionTensorImp = void > class Elliptic; namespace internal { /** * \brief Traits for the Elliptic evaluation. */ template< class DiffusionFactorImp, class DiffusionTensorImp > class EllipticTraits { static_assert(Stuff::is_localizable_function< DiffusionFactorImp >::value, "DiffusionFactorImp has to be a localizable function!"); static_assert(Stuff::is_localizable_function< DiffusionTensorImp >::value, "DiffusionTensorImp has to be a localizable function!"); static_assert(std::is_same< typename DiffusionFactorImp::EntityType, typename DiffusionTensorImp::EntityType >::value, "EntityTypes have to agree!"); static_assert(std::is_same< typename DiffusionFactorImp::DomainFieldType, typename DiffusionTensorImp::DomainFieldType >::value, "DomainFieldTypes have to agree!"); static_assert(DiffusionFactorImp::dimDomain == DiffusionTensorImp::dimDomain, "Dimensions have to agree!"); public: typedef Elliptic< DiffusionFactorImp, DiffusionTensorImp > derived_type; typedef DiffusionFactorImp LocalizableDiffusionFactorFunctionType; typedef DiffusionTensorImp LocalizableDiffusionTensorFunctionType; typedef typename LocalizableDiffusionFactorFunctionType::LocalfunctionType LocalDiffusionFactorFunctionType; typedef typename LocalizableDiffusionTensorFunctionType::LocalfunctionType LocalDiffusionTensorFunctionType; typedef std::tuple< std::shared_ptr< LocalDiffusionFactorFunctionType >, std::shared_ptr< LocalDiffusionTensorFunctionType > > LocalfunctionTupleType; typedef typename LocalizableDiffusionFactorFunctionType::EntityType EntityType; typedef typename LocalizableDiffusionFactorFunctionType::DomainFieldType DomainFieldType; static const unsigned int dimDomain = LocalizableDiffusionFactorFunctionType::dimDomain; }; // class EllipticTraits template< class LocalizableFunctionImp > class EllipticTraits< LocalizableFunctionImp, void > { static_assert(Stuff::is_localizable_function< LocalizableFunctionImp >::value, "LocalizableFunctionImp has to be a localizable function!"); public: typedef LocalizableFunctionImp LocalizableFunctionType; typedef Elliptic< LocalizableFunctionType, void > derived_type; typedef typename LocalizableFunctionType::EntityType EntityType; typedef typename LocalizableFunctionType::DomainFieldType DomainFieldType; typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType; typedef std::tuple< std::shared_ptr< LocalfunctionType > > LocalfunctionTupleType; static const unsigned int dimDomain = LocalizableFunctionType::dimDomain; }; // class EllipticTraits< ..., void > } // namespace internal /** * \brief Computes an elliptic evaluation. */ template< class LocalizableFunctionImp > class Elliptic< LocalizableFunctionImp, void > : public LocalEvaluation::Codim0Interface< internal::EllipticTraits< LocalizableFunctionImp, void >, 2 > { public: typedef internal::EllipticTraits< LocalizableFunctionImp, void > Traits; typedef typename Traits::LocalizableFunctionType LocalizableFunctionType; typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType; typedef typename Traits::EntityType EntityType; typedef typename Traits::DomainFieldType DomainFieldType; static const unsigned int dimDomain = Traits::dimDomain; explicit Elliptic(const LocalizableFunctionType& inducingFunction) : inducingFunction_(inducingFunction) {} LocalfunctionTupleType localFunctions(const EntityType& entity) const { return std::make_tuple(inducingFunction_.local_function(entity)); } /** * \brief extracts the local functions and calls the correct order() method */ template< class R, int rT, int rCT, int rA, int rCA > size_t order(const LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase) const { const auto localFunction = std::get< 0 >(localFuncs); return redirect_order(*localFunction, testBase, ansatzBase); } /** * \brief extracts the local functions and calls the correct evaluate() method */ template< class R, int rT, int rCT, int rA, int rCA > void evaluate(const LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicMatrix< R >& ret) const { const auto localFunction = std::get< 0 >(localFuncs); evaluate(*localFunction, testBase, ansatzBase, localPoint, ret); } /** * \brief Computes an elliptic evaluation for a 2x2 matrix-valued local function and matrix-valued basefunctionsets. * \tparam R RangeFieldType * \note Unfortunately we need this explicit specialization, otherwise the compiler will complain for 1d grids. */ template< class R > void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, 2, 2 >& localFunction, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& testBase, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& ansatzBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicMatrix< R >& ret) const { evaluate_matrix_valued_(localFunction, testBase, ansatzBase, localPoint, ret); } /** * \brief Computes an elliptic evaluation for a 3x3 matrix-valued local function and matrix-valued basefunctionsets. * \tparam R RangeFieldType * \note Unfortunately we need this explicit specialization, otherwise the compiler will complain for 1d grids. */ template< class R > void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, 3, 3 >& localFunction, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& testBase, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& ansatzBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicMatrix< R >& ret) const { evaluate_matrix_valued_(localFunction, testBase, ansatzBase, localPoint, ret); } private: /** * \return localFunction.order() + (testBase.order() - 1) + (ansatzBase.order() - 1) */ template< class R, int rL, int rCL, int rT, int rCT, int rA, int rCA > size_t redirect_order(const Stuff::LocalfunctionInterface < EntityType, DomainFieldType, dimDomain, R, rL, rCL >& localFunction, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase) const { return localFunction.order() + boost::numeric_cast< size_t >(std::max(ssize_t(testBase.order()) - 1, ssize_t(0))) + boost::numeric_cast< size_t >(std::max(ssize_t(ansatzBase.order()) - 1, ssize_t(0))); } // size_t redirect_order( ... ) /** * \brief Computes an elliptic evaluation for a scalar local function and scalar or vector valued basefunctionsets. * \tparam R RangeFieldType */ template< class R, int r > void evaluate(const Stuff::LocalfunctionInterface < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& localFunction, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, r, 1 >& testBase, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, r, 1 >& ansatzBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicMatrix< R >& ret) const { typedef typename Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, r, 1 >::JacobianRangeType JacobianRangeType; // evaluate local function const auto functionValue = localFunction.evaluate(localPoint); // evaluate test gradient const size_t rows = testBase.size(); std::vector< JacobianRangeType > testGradients(rows, JacobianRangeType(0)); testBase.jacobian(localPoint, testGradients); // evaluate ansatz gradient const size_t cols = ansatzBase.size(); std::vector< JacobianRangeType > ansatzGradients(cols, JacobianRangeType(0)); ansatzBase.jacobian(localPoint, ansatzGradients); // compute products assert(ret.rows() >= rows); assert(ret.cols() >= cols); for (size_t ii = 0; ii < rows; ++ii) { auto& retRow = ret[ii]; for (size_t jj = 0; jj < cols; ++jj) { retRow[jj] = functionValue * (ansatzGradients[jj][0] * testGradients[ii][0]); } } } // ... redirect_evaluate< ..., 1, ... >(...) template< class R > void evaluate_matrix_valued_(const Stuff::LocalfunctionInterface < EntityType, DomainFieldType, dimDomain, R, dimDomain, dimDomain >& localFunction, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& testBase, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& ansatzBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicMatrix< R >& ret) const { typedef typename Stuff::LocalfunctionInterface < EntityType, DomainFieldType, dimDomain, R, dimDomain, dimDomain >::RangeType DiffusionRangeType; typedef typename Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, 1, 1 >::JacobianRangeType JacobianRangeType; // evaluate local function const DiffusionRangeType functionValue = localFunction.evaluate(localPoint); // evaluate test gradient const size_t rows = testBase.size(); std::vector< JacobianRangeType > testGradients(rows, JacobianRangeType(0)); testBase.jacobian(localPoint, testGradients); // evaluate ansatz gradient const size_t cols = ansatzBase.size(); std::vector< JacobianRangeType > ansatzGradients(cols, JacobianRangeType(0)); ansatzBase.jacobian(localPoint, ansatzGradients); // compute products assert(ret.rows() >= rows); assert(ret.cols() >= cols); FieldVector< DomainFieldType, dimDomain > product(0.0); for (size_t ii = 0; ii < rows; ++ii) { auto& retRow = ret[ii]; for (size_t jj = 0; jj < cols; ++jj) { functionValue.mv(ansatzGradients[jj][0], product); retRow[jj] = product * testGradients[ii][0]; } } } // ... evaluate_matrix_valued_(...) const LocalizableFunctionType& inducingFunction_; }; // class Elliptic } // namespace Evaluation } // namespace GDT } // namespace Dune #endif // DUNE_GDT_EVALUATION_ELLIPTIC_HH <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_FUNCTION_CHECKERBOARD_HH #define DUNE_STUFF_FUNCTION_CHECKERBOARD_HH #include "config.h" #include <vector> #include <cmath> #include <memory> #include <dune/common/exceptions.hh> #include <dune/common/static_assert.hh> #include <dune/stuff/common/configtree.hh> #include "interfaces.hh" namespace Dune { namespace Stuff { namespace Functions { template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class Checkerboard : public LocalizableFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > { typedef LocalizableFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType; typedef Checkerboard< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType; class Localfunction : public LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > { typedef LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::DomainFieldType DomainFieldType; static const unsigned int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const unsigned int dimRange = BaseType::dimRange; static const unsigned int dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; Localfunction(const EntityType& ent, const RangeType value) : BaseType(ent) , value_(value) {} Localfunction(const Localfunction& /*other*/) = delete; Localfunction& operator=(const Localfunction& /*other*/) = delete; virtual size_t order() const DS_OVERRIDE { return 0; } virtual void evaluate(const DomainType& xx, RangeType& ret) const DS_OVERRIDE { assert(this->is_a_valid_point(xx)); ret = value_; } virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const DS_OVERRIDE { assert(this->is_a_valid_point(xx)); ret *= RangeFieldType(0); } private: const RangeType value_; }; // class Localfunction public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef typename BaseType::DomainFieldType DomainFieldType; static const int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const int dimRange = BaseType::dimRange; static const int dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; static std::string static_id() { return BaseType::static_id() + ".checkerboard"; } static Common::ConfigTree default_config(const std::string sub_name = "") { Common::ConfigTree config; config["lower_left"] = "[0.0; 0.0; 0.0]"; config["upper_right"] = "[1.0; 1.0; 1.0]"; config["num_elements"] = "[2; 2; 2]"; config["values"] = "[1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0]"; config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::ConfigTree tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::ConfigTree config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::ConfigTree cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; // extract needed data auto lower_left = cfg.get< std::vector< DomainFieldType > >("lower_left", dimDomain); auto upper_right = cfg.get< std::vector< DomainFieldType > >("upper_right", dimDomain); auto num_elements = cfg.get< std::vector< size_t > >("num_elements"); size_t num_values = 1; for (size_t ii = 0; ii < num_elements.size(); ++ii) num_values *= num_elements[ii]; auto values = cfg.get< std::vector< RangeType > >("values", num_values); auto nm = static_id(); if (cfg.has_key("name")) nm = cfg.get< std::string >("name"); return Common::make_unique< ThisType >(std::move(lower_left), std::move(upper_right), std::move(num_elements), std::move(values), nm); } // ... create(...) Checkerboard(std::vector< DomainFieldType >&& lowerLeft, std::vector< DomainFieldType >&& upperRight, std::vector< size_t >&& numElements, std::vector< RangeType >&& values, std::string nm = static_id()) : lowerLeft_(new std::vector< DomainFieldType >(std::move(lowerLeft))) , upperRight_(new std::vector< DomainFieldType >(std::move(upperRight))) , numElements_(new std::vector< size_t >(std::move(numElements))) , values_(new std::vector< RangeType >(std::move(values))) , name_(nm) { // checks if (lowerLeft_->size() < dimDomain) DUNE_THROW(Dune::RangeError, "lowerLeft too small (is " << lowerLeft_->size() << ", should be " << dimDomain << ")"); if (upperRight_->size() < dimDomain) DUNE_THROW(Dune::RangeError, "upperRight too small (is " << upperRight_->size() << ", should be " << dimDomain << ")"); if (numElements_->size() < dimDomain) DUNE_THROW(Dune::RangeError, "numElements too small (is " << numElements_->size() << ", should be " << dimDomain << ")"); size_t totalSubdomains = 1; for (size_t dd = 0; dd < dimDomain; ++dd) { const auto& ll = (*lowerLeft_)[dd]; const auto& ur = (*upperRight_)[dd]; const auto& ne = (*numElements_)[dd]; if (!(ll < ur)) DUNE_THROW(Dune::RangeError, "lowerLeft has to be elementwise smaller than upperRight!"); totalSubdomains *= ne; } if (values_->size() < totalSubdomains) DUNE_THROW(Dune::RangeError, "values too small (is " << values_->size() << ", should be " << totalSubdomains << ")"); } // Checkerboard(...) Checkerboard(const ThisType& other) : lowerLeft_(other.lowerLeft_) , upperRight_(other.upperRight_) , numElements_(other.numElements_) , values_(other.values_) , name_(other.name_) {} ThisType& operator=(const ThisType& other) { if (this != &other) { lowerLeft_ = other.lowerLeft_; upperRight_ = other.upperRight_; numElements_ = other.numElements_; values_ = other.values_; name_ = other.name_; } return *this; } virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } virtual std::string name() const DS_OVERRIDE { return name_; } virtual std::unique_ptr< LocalfunctionType > local_function(const EntityType& entity) const DS_OVERRIDE { // decide on the subdomain the center of the entity belongs to const auto center = entity.geometry().center(); std::vector< size_t > whichPartition(dimDomain, 0); const auto& ll = *lowerLeft_; const auto& ur = *upperRight_; const auto& ne = *numElements_; for (size_t dd = 0; dd < dimDomain; ++dd) { // for points that are on upperRight_[d], this selects one partition too much // so we need to cap this whichPartition[dd] = std::min(size_t(std::floor(ne[dd]*((center[dd] - ll[dd])/(ur[dd] - ll[dd])))), ne[dd] - 1); } size_t subdomain = 0; if (dimDomain == 1) subdomain = whichPartition[0]; else if (dimDomain == 2) subdomain = whichPartition[0] + whichPartition[1]*ne[0]; else subdomain = whichPartition[0] + whichPartition[1]*ne[0] + whichPartition[2]*ne[1]*ne[0]; // return the component that belongs to the subdomain return std::unique_ptr< Localfunction >(new Localfunction(entity, (*values_)[subdomain])); } // ... local_function(...) private: std::shared_ptr< const std::vector< DomainFieldType > > lowerLeft_; std::shared_ptr< const std::vector< DomainFieldType > > upperRight_; std::shared_ptr< const std::vector< size_t > > numElements_; std::shared_ptr< const std::vector< RangeType > > values_; std::string name_; }; // class Checkerboard } // namespace Functions } // namespace Stuff } // namespace Dune #ifdef DUNE_STUFF_FUNCTIONS_TO_LIB # define DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(etype, ddim) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGECOLS(etype, ddim, 1) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGECOLS(etype, ddim, 2) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGECOLS(etype, ddim, 3) # define DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGECOLS(etype, ddim, rdim) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 1) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 2) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 3) # define DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, rcdim) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_RANGEFIELDTYPES(etype, double, ddim, rdim, rcdim) # define DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_RANGEFIELDTYPES(etype, dftype, ddim, rdim, rcdim) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LAST_EXPANSION(etype, dftype, ddim, double, rdim, rcdim) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LAST_EXPANSION(etype, dftype, ddim, long double, rdim, rcdim) # define DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LAST_EXPANSION(etype, dftype, ddim, rftype, rdim, rcdim) \ extern template class Dune::Stuff::Functions::Checkerboard< etype, dftype, ddim, rftype, rdim, rcdim >; # if HAVE_DUNE_GRID DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid1dEntityType, 1) DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid2dEntityType, 2) DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid3dEntityType, 3) DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid1dEntityType, 1) DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid2dEntityType, 2) DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid3dEntityType, 3) # if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluSimplexGrid2dEntityType, 2) DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluSimplexGrid3dEntityType, 3) DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluCubeGrid3dEntityType, 3) # endif // HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H # endif // HAVE_DUNE_GRID # undef DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LAST_EXPANSION # undef DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_RANGEFIELDTYPES # undef DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DOMAINFIELDTYPES # undef DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGECOLS # undef DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE #endif // DUNE_STUFF_FUNCTIONS_TO_LIB #endif // DUNE_STUFF_FUNCTION_CHECKERBOARD_HH <commit_msg>[functions.checkerboard] read values as scalar values (old behavior, reading of values as vectors lead to lexical_cast error)<commit_after>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_FUNCTION_CHECKERBOARD_HH #define DUNE_STUFF_FUNCTION_CHECKERBOARD_HH #include <vector> #include <cmath> #include <memory> #include <dune/common/exceptions.hh> #include <dune/common/static_assert.hh> #include <dune/stuff/common/configtree.hh> #include "interfaces.hh" namespace Dune { namespace Stuff { namespace Functions { template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class Checkerboard : public LocalizableFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > { typedef LocalizableFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType; typedef Checkerboard< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType; class Localfunction : public LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > { typedef LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::DomainFieldType DomainFieldType; static const unsigned int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const unsigned int dimRange = BaseType::dimRange; static const unsigned int dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; Localfunction(const EntityType& ent, const RangeType value) : BaseType(ent) , value_(value) {} Localfunction(const Localfunction& /*other*/) = delete; Localfunction& operator=(const Localfunction& /*other*/) = delete; virtual size_t order() const DS_OVERRIDE { return 0; } virtual void evaluate(const DomainType& xx, RangeType& ret) const DS_OVERRIDE { assert(this->is_a_valid_point(xx)); ret = value_; } virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const DS_OVERRIDE { assert(this->is_a_valid_point(xx)); ret *= RangeFieldType(0); } private: const RangeType value_; }; // class Localfunction public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef typename BaseType::DomainFieldType DomainFieldType; static const int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const int dimRange = BaseType::dimRange; static const int dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; static std::string static_id() { return BaseType::static_id() + ".checkerboard"; } static Common::ConfigTree default_config(const std::string sub_name = "") { Common::ConfigTree config; config["lower_left"] = "[0.0; 0.0; 0.0]"; config["upper_right"] = "[1.0; 1.0; 1.0]"; config["num_elements"] = "[2; 2; 2]"; config["values"] = "[1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0]"; config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::ConfigTree tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::ConfigTree config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::ConfigTree cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; // extract needed data auto lower_left = cfg.get< std::vector< DomainFieldType > >("lower_left", dimDomain); auto upper_right = cfg.get< std::vector< DomainFieldType > >("upper_right", dimDomain); auto num_elements = cfg.get< std::vector< size_t > >("num_elements"); size_t num_values = 1; for (size_t ii = 0; ii < num_elements.size(); ++ii) num_values *= num_elements[ii]; auto values_rf = cfg.get< std::vector< RangeFieldType > >("values", num_values); std::vector< RangeType > values(values_rf.size()); for (size_t ii = 0; ii < values_rf.size(); ++ii) values[ii] = RangeType(values_rf[ii]); auto nm = static_id(); if (cfg.has_key("name")) nm = cfg.get< std::string >("name"); return Common::make_unique< ThisType >(std::move(lower_left), std::move(upper_right), std::move(num_elements), std::move(values), nm); } // ... create(...) Checkerboard(std::vector< DomainFieldType >&& lowerLeft, std::vector< DomainFieldType >&& upperRight, std::vector< size_t >&& numElements, std::vector< RangeType >&& values, std::string nm = static_id()) : lowerLeft_(new std::vector< DomainFieldType >(std::move(lowerLeft))) , upperRight_(new std::vector< DomainFieldType >(std::move(upperRight))) , numElements_(new std::vector< size_t >(std::move(numElements))) , values_(new std::vector< RangeType >(std::move(values))) , name_(nm) { // checks if (lowerLeft_->size() < dimDomain) DUNE_THROW(Dune::RangeError, "lowerLeft too small (is " << lowerLeft_->size() << ", should be " << dimDomain << ")"); if (upperRight_->size() < dimDomain) DUNE_THROW(Dune::RangeError, "upperRight too small (is " << upperRight_->size() << ", should be " << dimDomain << ")"); if (numElements_->size() < dimDomain) DUNE_THROW(Dune::RangeError, "numElements too small (is " << numElements_->size() << ", should be " << dimDomain << ")"); size_t totalSubdomains = 1; for (size_t dd = 0; dd < dimDomain; ++dd) { const auto& ll = (*lowerLeft_)[dd]; const auto& ur = (*upperRight_)[dd]; const auto& ne = (*numElements_)[dd]; if (!(ll < ur)) DUNE_THROW(Dune::RangeError, "lowerLeft has to be elementwise smaller than upperRight!"); totalSubdomains *= ne; } if (values_->size() < totalSubdomains) DUNE_THROW(Dune::RangeError, "values too small (is " << values_->size() << ", should be " << totalSubdomains << ")"); } // Checkerboard(...) Checkerboard(const ThisType& other) : lowerLeft_(other.lowerLeft_) , upperRight_(other.upperRight_) , numElements_(other.numElements_) , values_(other.values_) , name_(other.name_) {} ThisType& operator=(const ThisType& other) { if (this != &other) { lowerLeft_ = other.lowerLeft_; upperRight_ = other.upperRight_; numElements_ = other.numElements_; values_ = other.values_; name_ = other.name_; } return *this; } virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } virtual std::string name() const DS_OVERRIDE { return name_; } virtual std::unique_ptr< LocalfunctionType > local_function(const EntityType& entity) const DS_OVERRIDE { // decide on the subdomain the center of the entity belongs to const auto center = entity.geometry().center(); std::vector< size_t > whichPartition(dimDomain, 0); const auto& ll = *lowerLeft_; const auto& ur = *upperRight_; const auto& ne = *numElements_; for (size_t dd = 0; dd < dimDomain; ++dd) { // for points that are on upperRight_[d], this selects one partition too much // so we need to cap this whichPartition[dd] = std::min(size_t(std::floor(ne[dd]*((center[dd] - ll[dd])/(ur[dd] - ll[dd])))), ne[dd] - 1); } size_t subdomain = 0; if (dimDomain == 1) subdomain = whichPartition[0]; else if (dimDomain == 2) subdomain = whichPartition[0] + whichPartition[1]*ne[0]; else subdomain = whichPartition[0] + whichPartition[1]*ne[0] + whichPartition[2]*ne[1]*ne[0]; // return the component that belongs to the subdomain return std::unique_ptr< Localfunction >(new Localfunction(entity, (*values_)[subdomain])); } // ... local_function(...) private: std::shared_ptr< const std::vector< DomainFieldType > > lowerLeft_; std::shared_ptr< const std::vector< DomainFieldType > > upperRight_; std::shared_ptr< const std::vector< size_t > > numElements_; std::shared_ptr< const std::vector< RangeType > > values_; std::string name_; }; // class Checkerboard } // namespace Functions } // namespace Stuff } // namespace Dune #ifdef DUNE_STUFF_FUNCTIONS_TO_LIB # define DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(etype, ddim) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGECOLS(etype, ddim, 1) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGECOLS(etype, ddim, 2) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGECOLS(etype, ddim, 3) # define DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGECOLS(etype, ddim, rdim) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 1) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 2) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 3) # define DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, rcdim) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_RANGEFIELDTYPES(etype, double, ddim, rdim, rcdim) # define DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_RANGEFIELDTYPES(etype, dftype, ddim, rdim, rcdim) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LAST_EXPANSION(etype, dftype, ddim, double, rdim, rcdim) \ DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LAST_EXPANSION(etype, dftype, ddim, long double, rdim, rcdim) # define DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LAST_EXPANSION(etype, dftype, ddim, rftype, rdim, rcdim) \ extern template class Dune::Stuff::Functions::Checkerboard< etype, dftype, ddim, rftype, rdim, rcdim >; # if HAVE_DUNE_GRID DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid1dEntityType, 1) DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid2dEntityType, 2) DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid3dEntityType, 3) DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid1dEntityType, 1) DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid2dEntityType, 2) DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid3dEntityType, 3) # if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluSimplexGrid2dEntityType, 2) DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluSimplexGrid3dEntityType, 3) DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluCubeGrid3dEntityType, 3) # endif // HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H # endif // HAVE_DUNE_GRID # undef DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LAST_EXPANSION # undef DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_RANGEFIELDTYPES # undef DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DOMAINFIELDTYPES # undef DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGECOLS # undef DUNE_STUFF_FUNCTIONS_CHECKERBOARD_LIST_DIMRANGE #endif // DUNE_STUFF_FUNCTIONS_TO_LIB #endif // DUNE_STUFF_FUNCTION_CHECKERBOARD_HH <|endoftext|>
<commit_before>/* * File: SDFLoader.cpp * Author: Benedikt Vogler * * Created on 8. Juli 2014, 18:52 */ #include <algorithm> #include "SDFloader.hpp" #include "Camera.hpp" #include "Box.hpp" #include "Sphere.hpp" #include <iostream> #include <fstream> #include <string> #include <sstream> #include "Material.hpp" #include "LightPoint.hpp" using namespace std; SDFLoader::SDFLoader() { } SDFLoader::SDFLoader(const SDFLoader& orig) { } SDFLoader::~SDFLoader() { } /** * Loads a scene file and reacts to the commands in it * @param scenefile the string to the file * @return */ Scene SDFLoader::load(std::string const& scenefile) { cout << "Loading file: " << scenefile << endl; Scene scene = Scene(); std::map<std::string, Material> mMap; std::map<std::string, LightPoint> lMap; std::map<std::string, RenderObject*> roMap; string line; ifstream file(scenefile); stringstream ss; //file.open(scenefile, ios::in); if (file.is_open()) { while (getline (file,line)){//get line ss = stringstream(line);//fill the line into stringstream string tmpString; ss >> tmpString; //is first string define? if (tmpString=="define"){ cout << "defininig: "; ss >> tmpString; if (tmpString=="material"){ cout << "a material: "<<endl; //extract name string name; ss>>name; //extract color float red, green, blue; ss >> red; ss >> green; ss >> blue; Color ca(red, green, blue); ss >> red; ss >> green; ss >> blue; Color cd(red, green, blue); ss >> red; ss >> green; ss >> blue; Color cs(red, green, blue); float m; ss >> m; Material mat(ca, cd, cs,m, name); cout << "Material specs: "<<endl<<mat; mMap[name]=mat; } else if (tmpString=="camera"){ string cameraname; ss >> cameraname; int fovX; ss >> fovX; scene.camera = Camera(cameraname,fovX); cout << "camera: "<<cameraname<<"("<<fovX<<")"<<endl; } else if (tmpString=="light"){ string type; ss>>type; if (type=="diffuse") { string name; ss >> name; glm::vec3 pos; ss >> pos.x; ss >> pos.y; ss >> pos.z; float red, green, blue; ss >> red; ss >> green; ss >> blue; Color diff(red, green, blue); LightPoint light = LightPoint(name, pos, diff); cout << "light point: "<<name<<"("<<pos.x<<","<<pos.y<<","<<pos.z<<","<<diff<<")"<<endl; lMap[name] = light; }else if (type=="ambient") { string lightname; ss >> lightname;//name get's ignored float red, green, blue; ss >> red; ss >> green; ss >> blue; Color amb(red, green, blue); scene.amb = amb; cout << "ambient light "<<amb<<endl; } else { cout << "type not supported yet."<<endl; } } else if (tmpString=="shape"){ string classname; ss >> classname; cout << "Shape \""<< classname << "\"."<<endl; transform(classname.begin(), classname.end(),classname.begin(), ::toupper); string name; ss >> name; RenderObject* rObject = nullptr; if (classname=="BOX"){ int edge1x, edge1y, edge1z; ss>> edge1x; ss>> edge1y; ss>> edge1z; int edge2x, edge2y, edge2z; ss>> edge2x; ss>> edge2y; ss>> edge2z; string materialString; ss>>materialString; Material material = mMap[materialString]; rObject = new Box( name, glm::vec3(edge1x, edge1y, edge1z), glm::vec3(edge2x, edge2y, edge2z), material ); }else if (classname=="SPHERE") { int posX, posY, posZ; ss>> posX; ss>> posY; ss>> posZ; float radius; ss>>radius; string materialString; ss>>materialString; Material material = mMap[materialString]; rObject = new Sphere( name, glm::vec3(posX, posY, posZ), radius, material ); cout << "Shape \""<< name << "\" aus Material "<<materialString<<" mit Radius: "<<radius<<"@("<<posX<<","<<posY<<","<<posZ<<")"<<endl; }else cout << "ERROR: Shape \""<< classname << "\" not defined."<<endl; if (rObject != nullptr) roMap[name] = rObject; } else cout << "object to define not implemented:"<<ss.str() <<endl; } else if (tmpString=="render"){ ss >> scene.camname; ss >> scene.outputFile; ss >> scene.resX; ss >> scene.resY; //set default if not set if (scene.resX<=0) scene.resX=480; if (scene.resY<=0) scene.resY=320; cout << "Scene should be rendered from "<< scene.camname << " at resolution "<<scene.resX<<"x"<< scene.resY<< " to "<<scene.outputFile<<endl; } else if (tmpString=="#"){ cout << line << endl;//just print comment lines } else cout << "Line not supported:"<<line <<endl; } file.close(); }else cout << "Unable to open file"; //save collected data in scene scene.materials = mMap; scene.renderObjects = roMap; scene.lights = lMap; return scene; }<commit_msg>improved debugging output<commit_after>/* * File: SDFLoader.cpp * Author: Benedikt Vogler * * Created on 8. Juli 2014, 18:52 */ #include <algorithm> #include "SDFloader.hpp" #include "Camera.hpp" #include "Box.hpp" #include "Sphere.hpp" #include <iostream> #include <fstream> #include <string> #include <sstream> #include "Material.hpp" #include "LightPoint.hpp" using namespace std; SDFLoader::SDFLoader() { } SDFLoader::SDFLoader(const SDFLoader& orig) { } SDFLoader::~SDFLoader() { } /** * Loads a scene file and reacts to the commands in it * @param scenefile the string to the file * @return */ Scene SDFLoader::load(std::string const& scenefile) { cout << "Loading file: " << scenefile << endl; Scene scene = Scene(); std::map<std::string, Material> mMap; std::map<std::string, LightPoint> lMap; std::map<std::string, RenderObject*> roMap; string line; ifstream file(scenefile); stringstream ss; //file.open(scenefile, ios::in); if (file.is_open()) { while (getline (file,line)){//get line ss = stringstream(line);//fill the line into stringstream string tmpString; ss >> tmpString; //is first string define? if (tmpString=="define"){ cout << "defininig: "; ss >> tmpString; if (tmpString=="material"){ cout << "a material: "<<endl; //extract name string name; ss>>name; //extract color float red, green, blue; ss >> red; ss >> green; ss >> blue; Color ca(red, green, blue); ss >> red; ss >> green; ss >> blue; Color cd(red, green, blue); ss >> red; ss >> green; ss >> blue; Color cs(red, green, blue); float m; ss >> m; Material mat(ca, cd, cs,m, name); cout << "Material specs: "<<endl<<mat; mMap[name]=mat; } else if (tmpString=="camera"){ string cameraname; ss >> cameraname; int fovX; ss >> fovX; scene.camera = Camera(cameraname,fovX); cout << "camera: "<<cameraname<<"("<<fovX<<")"<<endl; } else if (tmpString=="light"){ string type; ss>>type; if (type=="diffuse") { string name; ss >> name; glm::vec3 pos; ss >> pos.x; ss >> pos.y; ss >> pos.z; float red, green, blue; ss >> red; ss >> green; ss >> blue; Color diff(red, green, blue); LightPoint light = LightPoint(name, pos, diff); cout << "light point: "<<name<<"("<<pos.x<<","<<pos.y<<","<<pos.z<<","<<diff<<")"<<endl; lMap[name] = light; }else if (type=="ambient") { string lightname; ss >> lightname;//name get's ignored float red, green, blue; ss >> red; ss >> green; ss >> blue; Color amb(red, green, blue); scene.amb = amb; cout << "ambient light "<<amb<<endl; } else { cout << "type not supported yet."<<endl; } } else if (tmpString=="shape"){ string classname; ss >> classname; cout << "Shape \""<< classname << "\"."<<endl; transform(classname.begin(), classname.end(),classname.begin(), ::toupper); string name; ss >> name; RenderObject* rObject = nullptr; if (classname=="BOX"){ int edge1x, edge1y, edge1z; ss>> edge1x; ss>> edge1y; ss>> edge1z; int edge2x, edge2y, edge2z; ss>> edge2x; ss>> edge2y; ss>> edge2z; string materialString; ss>>materialString; Material material = mMap[materialString]; rObject = new Box( name, glm::vec3(edge1x, edge1y, edge1z), glm::vec3(edge2x, edge2y, edge2z), material ); }else if (classname=="SPHERE") { int posX, posY, posZ; ss>> posX; ss>> posY; ss>> posZ; float radius; ss>>radius; string materialString; ss>>materialString; Material material = mMap[materialString]; rObject = new Sphere( name, glm::vec3(posX, posY, posZ), radius, material ); cout << "Shape \""<< name << "\" aus Material "<<material<<" mit Radius: "<<radius<<"@("<<posX<<","<<posY<<","<<posZ<<")"<<endl; }else cout << "ERROR: Shape \""<< classname << "\" not defined."<<endl; if (rObject != nullptr) roMap[name] = rObject; } else cout << "object to define not implemented:"<<ss.str() <<endl; } else if (tmpString=="render"){ ss >> scene.camname; ss >> scene.outputFile; ss >> scene.resX; ss >> scene.resY; //set default if not set if (scene.resX<=0) scene.resX=480; if (scene.resY<=0) scene.resY=320; cout << "Scene should be rendered from "<< scene.camname << " at resolution "<<scene.resX<<"x"<< scene.resY<< " to "<<scene.outputFile<<endl; } else if (tmpString=="#"){ cout << line << endl;//just print comment lines } else cout << "Line not supported:"<<line <<endl; } file.close(); }else cout << "Unable to open file"; //save collected data in scene scene.materials = mMap; scene.renderObjects = roMap; scene.lights = lMap; return scene; }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: impoct.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2007-07-24 10:00:21 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SV_IMPOCT_HXX #define _SV_IMPOCT_HXX #ifndef _SV_OCTREE_HXX #include <vcl/octree.hxx> #endif // ---------------- // - ImpErrorQuad - // ---------------- class ImpErrorQuad { long nRed; long nGreen; long nBlue; long nReserved; public: inline ImpErrorQuad() {} inline ImpErrorQuad( const BitmapColor& rColor ) : nRed ( (long) rColor.GetRed() << 5L ), nGreen ( (long) rColor.GetGreen() << 5L ), nBlue ( (long) rColor.GetBlue() << 5L ) {} inline void operator=( const BitmapColor& rColor ); inline ImpErrorQuad& operator-=( const BitmapColor& rColor ); inline void ImplAddColorError1( const ImpErrorQuad& rErrQuad ); inline void ImplAddColorError3( const ImpErrorQuad& rErrQuad ); inline void ImplAddColorError5( const ImpErrorQuad& rErrQuad ); inline void ImplAddColorError7( const ImpErrorQuad& rErrQuad ); inline BitmapColor ImplGetColor(); }; // ------------------------------------------------------------------------ inline void ImpErrorQuad::operator=( const BitmapColor& rColor ) { nRed = (long) rColor.GetRed() << 5L; nGreen = (long) rColor.GetGreen() << 5L; nBlue = (long) rColor.GetBlue() << 5L; } // ------------------------------------------------------------------------ inline ImpErrorQuad& ImpErrorQuad::operator-=( const BitmapColor& rColor ) { nRed -= ( (long) rColor.GetRed() << 5L ); nGreen -= ( (long) rColor.GetGreen() << 5L ); nBlue -= ( (long) rColor.GetBlue() << 5L ); return *this; } // ------------------------------------------------------------------------ inline void ImpErrorQuad::ImplAddColorError1( const ImpErrorQuad& rErrQuad ) { nRed += ( rErrQuad.nRed >> 4L ); nGreen += ( rErrQuad.nGreen >> 4L ); nBlue += ( rErrQuad.nBlue >> 4L ); } // ------------------------------------------------------------------------ inline void ImpErrorQuad::ImplAddColorError3( const ImpErrorQuad& rErrQuad ) { nRed += ( rErrQuad.nRed * 3L >> 4L ); nGreen += ( rErrQuad.nGreen * 3L >> 4L ); nBlue += ( rErrQuad.nBlue * 3L >> 4L ); } // ------------------------------------------------------------------------ inline void ImpErrorQuad::ImplAddColorError5( const ImpErrorQuad& rErrQuad ) { nRed += ( rErrQuad.nRed * 5L >> 4L ); nGreen += ( rErrQuad.nGreen * 5L >> 4L ); nBlue += ( rErrQuad.nBlue * 5L >> 4L ); } // ------------------------------------------------------------------------ inline void ImpErrorQuad::ImplAddColorError7( const ImpErrorQuad& rErrQuad ) { nRed += ( rErrQuad.nRed * 7L >> 4L ); nGreen += ( rErrQuad.nGreen * 7L >> 4L ); nBlue += ( rErrQuad.nBlue *7L >> 4L ); } // ------------------------------------------------------------------------ inline BitmapColor ImpErrorQuad::ImplGetColor() { return BitmapColor( (BYTE) ( ( nRed < 0L ? 0L : nRed > 8160L ? 8160L : nRed ) >> 5L ), (BYTE) ( ( nGreen < 0L ? 0L : nGreen > 8160L ? 8160L : nGreen ) >> 5L ), (BYTE) ( ( nBlue < 0L ? 0L : nBlue > 8160L ? 8160L : nBlue ) >> 5L ) ); } // ------------- // - NodeCache - // ------------- class ImpNodeCache { OctreeNode* pActNode; ULONG nNew; ULONG nDelete; ULONG nGet; ULONG nRelease; public: ImpNodeCache( const ULONG nInitSize ); ~ImpNodeCache(); inline OctreeNode* ImplGetFreeNode(); inline void ImplReleaseNode( OctreeNode* pNode ); }; // ------------------------------------------------------------------------ inline OctreeNode* ImpNodeCache::ImplGetFreeNode() { OctreeNode* pNode; if ( !pActNode ) { pActNode = new NODE; pActNode->pNextInCache = NULL; } pNode = pActNode; pActNode = pNode->pNextInCache; memset( pNode, 0, sizeof( NODE ) ); return pNode; } // ------------------------------------------------------------------------ inline void ImpNodeCache::ImplReleaseNode( OctreeNode* pNode ) { pNode->pNextInCache = pActNode; pActNode = pNode; } #endif // _SV_IMPOCT_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.2.224); FILE MERGED 2008/04/01 13:01:11 thb 1.2.224.2: #i85898# Stripping all external header guards 2008/03/28 15:44:13 rt 1.2.224.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: impoct.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SV_IMPOCT_HXX #define _SV_IMPOCT_HXX #include <vcl/octree.hxx> // ---------------- // - ImpErrorQuad - // ---------------- class ImpErrorQuad { long nRed; long nGreen; long nBlue; long nReserved; public: inline ImpErrorQuad() {} inline ImpErrorQuad( const BitmapColor& rColor ) : nRed ( (long) rColor.GetRed() << 5L ), nGreen ( (long) rColor.GetGreen() << 5L ), nBlue ( (long) rColor.GetBlue() << 5L ) {} inline void operator=( const BitmapColor& rColor ); inline ImpErrorQuad& operator-=( const BitmapColor& rColor ); inline void ImplAddColorError1( const ImpErrorQuad& rErrQuad ); inline void ImplAddColorError3( const ImpErrorQuad& rErrQuad ); inline void ImplAddColorError5( const ImpErrorQuad& rErrQuad ); inline void ImplAddColorError7( const ImpErrorQuad& rErrQuad ); inline BitmapColor ImplGetColor(); }; // ------------------------------------------------------------------------ inline void ImpErrorQuad::operator=( const BitmapColor& rColor ) { nRed = (long) rColor.GetRed() << 5L; nGreen = (long) rColor.GetGreen() << 5L; nBlue = (long) rColor.GetBlue() << 5L; } // ------------------------------------------------------------------------ inline ImpErrorQuad& ImpErrorQuad::operator-=( const BitmapColor& rColor ) { nRed -= ( (long) rColor.GetRed() << 5L ); nGreen -= ( (long) rColor.GetGreen() << 5L ); nBlue -= ( (long) rColor.GetBlue() << 5L ); return *this; } // ------------------------------------------------------------------------ inline void ImpErrorQuad::ImplAddColorError1( const ImpErrorQuad& rErrQuad ) { nRed += ( rErrQuad.nRed >> 4L ); nGreen += ( rErrQuad.nGreen >> 4L ); nBlue += ( rErrQuad.nBlue >> 4L ); } // ------------------------------------------------------------------------ inline void ImpErrorQuad::ImplAddColorError3( const ImpErrorQuad& rErrQuad ) { nRed += ( rErrQuad.nRed * 3L >> 4L ); nGreen += ( rErrQuad.nGreen * 3L >> 4L ); nBlue += ( rErrQuad.nBlue * 3L >> 4L ); } // ------------------------------------------------------------------------ inline void ImpErrorQuad::ImplAddColorError5( const ImpErrorQuad& rErrQuad ) { nRed += ( rErrQuad.nRed * 5L >> 4L ); nGreen += ( rErrQuad.nGreen * 5L >> 4L ); nBlue += ( rErrQuad.nBlue * 5L >> 4L ); } // ------------------------------------------------------------------------ inline void ImpErrorQuad::ImplAddColorError7( const ImpErrorQuad& rErrQuad ) { nRed += ( rErrQuad.nRed * 7L >> 4L ); nGreen += ( rErrQuad.nGreen * 7L >> 4L ); nBlue += ( rErrQuad.nBlue *7L >> 4L ); } // ------------------------------------------------------------------------ inline BitmapColor ImpErrorQuad::ImplGetColor() { return BitmapColor( (BYTE) ( ( nRed < 0L ? 0L : nRed > 8160L ? 8160L : nRed ) >> 5L ), (BYTE) ( ( nGreen < 0L ? 0L : nGreen > 8160L ? 8160L : nGreen ) >> 5L ), (BYTE) ( ( nBlue < 0L ? 0L : nBlue > 8160L ? 8160L : nBlue ) >> 5L ) ); } // ------------- // - NodeCache - // ------------- class ImpNodeCache { OctreeNode* pActNode; ULONG nNew; ULONG nDelete; ULONG nGet; ULONG nRelease; public: ImpNodeCache( const ULONG nInitSize ); ~ImpNodeCache(); inline OctreeNode* ImplGetFreeNode(); inline void ImplReleaseNode( OctreeNode* pNode ); }; // ------------------------------------------------------------------------ inline OctreeNode* ImpNodeCache::ImplGetFreeNode() { OctreeNode* pNode; if ( !pActNode ) { pActNode = new NODE; pActNode->pNextInCache = NULL; } pNode = pActNode; pActNode = pNode->pNextInCache; memset( pNode, 0, sizeof( NODE ) ); return pNode; } // ------------------------------------------------------------------------ inline void ImpNodeCache::ImplReleaseNode( OctreeNode* pNode ) { pNode->pNextInCache = pActNode; pActNode = pNode; } #endif // _SV_IMPOCT_HXX <|endoftext|>
<commit_before><commit_msg>document VclContainer a bit<commit_after><|endoftext|>
<commit_before>#ifndef CXX_OBJECT_HXX # define CXX_OBJECT_HXX # include <boost/bind.hpp> # include <object/atom.hh> # include <object/primitive-class.hh> # include <object/string-class.hh> # include <object/object-class.hh> # include <object/primitives.hh> namespace object { template <typename T> bool CxxObject::add(const std::string& name, rObject& tgt) { initializers_get().push_back(new TypeInitializer<T>(name, tgt)); return true; } template <typename T> CxxObject::TypeInitializer<T>::TypeInitializer(const std::string& name, rObject& tgt) : Initializer(tgt), name_(name) {} namespace { template <typename T> rObject cxx_object_clone(runner::Runner&, objects_type args) { CHECK_ARG_COUNT(1); rObject tgt = args[0]; rObject res; if (tgt->is_a<T>()) res = new T(tgt->as<T>()); else res = new T(); return res; } template <typename T> rObject cxx_object_id(runner::Runner&, objects_type args) { CHECK_ARG_COUNT(1); return args[0]; } } template <typename T> void CxxObject::TypeInitializer<T>::create() { res_ = new Object(); } template <typename T> rObject CxxObject::TypeInitializer<T>::make_class() { res_->proto_add(object_class); res_->slot_set(SYMBOL(protoName), new String(name_)); res_->slot_set(SYMBOL(clone), rPrimitive(new Primitive(boost::bind(cxx_object_clone<T>, _1, _2)))); Binder<T> b(res_); T::initialize(b); libport::Symbol conversion = libport::Symbol(std::string("as") + name_.name_get()); if (!res_->slot_locate(conversion, 0)) res_->slot_set(conversion, rPrimitive(new Primitive(boost::bind(cxx_object_id<T>, _1, _2)))); return res_; } template <typename T> libport::Symbol CxxObject::TypeInitializer<T>::name() { return name_; } // BINDER template <typename T> CxxObject::Binder<T>::Binder(rObject tgt) : tgt_(tgt) {} namespace { # define PRINT_true(X) X # define PRINT_false(X) # define PRINT_truetrue(X) X # define PRINT_falsetrue(X) # define PRINT_truefalse(X) # define PRINT_falsefalse(X) # define NPRINT_true(X) # define NPRINT_false(X) X # define WHEN(Cond, X) PRINT_##Cond(X) # define WHEN_NOT(Cond, X) NPRINT_##Cond(X) # define IF(Cond, Then, Else) WHEN(Cond, Then) WHEN_NOT(Cond, Else) # define COMMA_ , # define COMMA(Cond) PRINT_##Cond(COMMA_) # define COMMA2(Cond1, Cond2) PRINT_##Cond1##Cond2(COMMA_) # define MET(Met, Name, Ret, Run, Arg1, Arg2, Arg3) \ IF(Ret, libport::shared_ptr<R>, void) \ (WHEN(Met, T::)*Name)( \ WHEN(Run, runner::Runner&) COMMA2(Run, Arg1) \ WHEN(Arg1, libport::shared_ptr<A1>) \ COMMA(Arg2) WHEN(Arg2, libport::shared_ptr<A2>) \ COMMA(Arg3) WHEN(Arg3, libport::shared_ptr<A3>) \ ) #define GET_ARG(Met, N) \ type_check<A##N>(args[N WHEN_NOT(Met, - 1)], name.name_get()); \ libport::shared_ptr<A##N> a##N = \ args[N WHEN_NOT(Met, - 1)].unsafe_cast<A##N>(); \ assert(a##N); #define FETCH_TGT() \ type_check<T>(args[0], name.name_get()); \ libport::shared_ptr<T> tgt = args[0].unsafe_cast<T>(); #define PRIMITIVE(Met, Ret, ArgsC, Run, Arg1, Arg2, Arg3) \ template <typename T \ COMMA(Ret) WHEN(Ret, typename R) \ COMMA(Arg1) WHEN(Arg1, typename A1) \ COMMA(Arg2) WHEN(Arg2, typename A2) \ COMMA(Arg3) WHEN(Arg3, typename A3) \ > \ struct primitive<T, MET(Met, , Ret, Run, Arg1, Arg2, Arg3)> \ { \ static rObject make( \ MET(Met, method, Ret, Run, Arg1, Arg2, Arg3), \ const libport::Symbol& IF(Met, name, WHEN(Arg1, name)), \ runner::Runner& WHEN(Run, r), \ objects_type args) \ { \ (void)args; \ assert(args.size() == \ ArgsC IF(Met, + 1, WHEN_NOT(Arg1, + 1))); \ WHEN(Met, FETCH_TGT()); \ WHEN(Arg1, GET_ARG(Met, 1)) \ WHEN(Arg2, GET_ARG(Met, 2)) \ WHEN(Arg3, GET_ARG(Met, 3)) \ WHEN(Ret, return) \ (WHEN(Met, tgt.get()->*)method)( \ WHEN(Run, r) COMMA2(Run, Arg1) \ WHEN(Arg1, a1) \ COMMA(Arg2) WHEN(Arg2, a2) \ COMMA(Arg3) WHEN(Arg3, a3) \ ); \ return void_class; \ } \ } #define LIST_MET(Name, Met, Ret, Run) \ IF(Ret, R, void) \ (WHEN(Met, T::)*Name)(WHEN(Run, runner::Runner&) COMMA(Run) \ objects_type) \ #define LIST_PRIMITIVE(Met, Ret, Run) \ template <typename T \ COMMA(Ret) WHEN(Ret, typename R) \ > \ struct primitive<T, LIST_MET(, Met, Ret, Run)> \ { \ static rObject make( \ LIST_MET(method, Met, Ret, Run), \ const libport::Symbol& name, \ runner::Runner& WHEN(Run, r), \ objects_type args) \ { \ WHEN(Met, FETCH_TGT()); \ WHEN(Met, args.pop_front()); \ WHEN(Ret, return) \ (WHEN(Met, tgt.get()->*)method)( \ WHEN(Run, r) COMMA(Run) \ args \ ); \ return void_class; \ } \ } template <typename T, typename M> struct primitive { }; /* Python for these: for met in ('true', 'false'): for ret in ('true', 'false'): for run in ('true', 'false'): print " LIST_PRIMITIVE(%s, %s, %s);" % (met, ret, run) */ LIST_PRIMITIVE(true, true, true); LIST_PRIMITIVE(true, true, false); LIST_PRIMITIVE(true, false, true); LIST_PRIMITIVE(true, false, false); LIST_PRIMITIVE(false, true, true); LIST_PRIMITIVE(false, true, false); LIST_PRIMITIVE(false, false, true); LIST_PRIMITIVE(false, false, false); /* Python for these: max = 3 for ret in ('true', 'false'): for run in ('true', 'false'): for nargs in range(max + 1): for macro in ('PRIMITIVE ', 'PRIMITIVEF'): print " %s(%s, %i, %s" % (macro, ret, nargs, run), for i in range(max): print ", %s" % str(i < nargs).lower(), print ");" */ PRIMITIVE(true , true, 0, true , false , false , false ); PRIMITIVE(true , true, 1, true , true , false , false ); PRIMITIVE(true , true, 2, true , true , true , false ); PRIMITIVE(true , true, 3, true , true , true , true ); PRIMITIVE(true , true, 0, false , false , false , false ); PRIMITIVE(true , true, 1, false , true , false , false ); PRIMITIVE(true , true, 2, false , true , true , false ); PRIMITIVE(true , true, 3, false , true , true , true ); PRIMITIVE(true , false, 0, true , false , false , false ); PRIMITIVE(true , false, 1, true , true , false , false ); PRIMITIVE(true , false, 2, true , true , true , false ); PRIMITIVE(true , false, 3, true , true , true , true ); PRIMITIVE(true , false, 0, false , false , false , false ); PRIMITIVE(true , false, 1, false , true , false , false ); PRIMITIVE(true , false, 2, false , true , true , false ); PRIMITIVE(true , false, 3, false , true , true , true ); PRIMITIVE(false, true, 0, true , false , false , false ); PRIMITIVE(false, true, 1, true , true , false , false ); PRIMITIVE(false, true, 2, true , true , true , false ); PRIMITIVE(false, true, 3, true , true , true , true ); PRIMITIVE(false, true, 0, false , false , false , false ); PRIMITIVE(false, true, 1, false , true , false , false ); PRIMITIVE(false, true, 2, false , true , true , false ); PRIMITIVE(false, true, 3, false , true , true , true ); PRIMITIVE(false, false, 0, true , false , false , false ); PRIMITIVE(false, false, 1, true , true , false , false ); PRIMITIVE(false, false, 2, true , true , true , false ); PRIMITIVE(false, false, 3, true , true , true , true ); PRIMITIVE(false, false, 0, false , false , false , false ); PRIMITIVE(false, false, 1, false , true , false , false ); PRIMITIVE(false, false, 2, false , true , true , false ); PRIMITIVE(false, false, 3, false , true , true , true ); } template <typename T> template <typename M> void CxxObject::Binder<T>::operator()(const libport::Symbol& name, M method) { // If make is unfound here, you passed an unsupported pointer type // to the binder. rObject p = new Primitive(boost::bind(primitive<T, M>::make, method, name, _1, _2)); tgt_->slot_set(name, p); } template <typename T> inline void type_check(rObject o, const std::string& fun) { libport::shared_ptr<CxxObject> co = o.unsafe_cast<CxxObject>(); // FIXME: I can't fill all the source type for now since some old // atoms don't define type_name for now if (!co) throw object::WrongArgumentType(T::type_name, "Object", fun); else if (!o->is_a<T>()) throw object::WrongArgumentType(T::type_name, co->type_name_get(), fun); } template <> inline void type_check<Object>(rObject, const std::string&) {} template <> inline void type_check<List>(rObject, const std::string&) {} } #endif <commit_msg>Force "name" to be used.<commit_after>#ifndef CXX_OBJECT_HXX # define CXX_OBJECT_HXX # include <boost/bind.hpp> # include <object/atom.hh> # include <object/primitive-class.hh> # include <object/string-class.hh> # include <object/object-class.hh> # include <object/primitives.hh> namespace object { template <typename T> bool CxxObject::add(const std::string& name, rObject& tgt) { initializers_get().push_back(new TypeInitializer<T>(name, tgt)); return true; } template <typename T> CxxObject::TypeInitializer<T>::TypeInitializer(const std::string& name, rObject& tgt) : Initializer(tgt), name_(name) {} namespace { template <typename T> rObject cxx_object_clone(runner::Runner&, objects_type args) { CHECK_ARG_COUNT(1); rObject tgt = args[0]; rObject res; if (tgt->is_a<T>()) res = new T(tgt->as<T>()); else res = new T(); return res; } template <typename T> rObject cxx_object_id(runner::Runner&, objects_type args) { CHECK_ARG_COUNT(1); return args[0]; } } template <typename T> void CxxObject::TypeInitializer<T>::create() { res_ = new Object(); } template <typename T> rObject CxxObject::TypeInitializer<T>::make_class() { res_->proto_add(object_class); res_->slot_set(SYMBOL(protoName), new String(name_)); res_->slot_set(SYMBOL(clone), rPrimitive(new Primitive(boost::bind(cxx_object_clone<T>, _1, _2)))); Binder<T> b(res_); T::initialize(b); libport::Symbol conversion = libport::Symbol(std::string("as") + name_.name_get()); if (!res_->slot_locate(conversion, 0)) res_->slot_set(conversion, rPrimitive(new Primitive(boost::bind(cxx_object_id<T>, _1, _2)))); return res_; } template <typename T> libport::Symbol CxxObject::TypeInitializer<T>::name() { return name_; } // BINDER template <typename T> CxxObject::Binder<T>::Binder(rObject tgt) : tgt_(tgt) {} namespace { # define PRINT_true(X) X # define PRINT_false(X) # define PRINT_truetrue(X) X # define PRINT_falsetrue(X) # define PRINT_truefalse(X) # define PRINT_falsefalse(X) # define NPRINT_true(X) # define NPRINT_false(X) X # define WHEN(Cond, X) PRINT_##Cond(X) # define WHEN_NOT(Cond, X) NPRINT_##Cond(X) # define IF(Cond, Then, Else) WHEN(Cond, Then) WHEN_NOT(Cond, Else) # define COMMA_ , # define COMMA(Cond) PRINT_##Cond(COMMA_) # define COMMA2(Cond1, Cond2) PRINT_##Cond1##Cond2(COMMA_) # define MET(Met, Name, Ret, Run, Arg1, Arg2, Arg3) \ IF(Ret, libport::shared_ptr<R>, void) \ (WHEN(Met, T::)*Name)( \ WHEN(Run, runner::Runner&) COMMA2(Run, Arg1) \ WHEN(Arg1, libport::shared_ptr<A1>) \ COMMA(Arg2) WHEN(Arg2, libport::shared_ptr<A2>) \ COMMA(Arg3) WHEN(Arg3, libport::shared_ptr<A3>) \ ) #define GET_ARG(Met, N) \ type_check<A##N>(args[N WHEN_NOT(Met, - 1)], name.name_get()); \ libport::shared_ptr<A##N> a##N = \ args[N WHEN_NOT(Met, - 1)].unsafe_cast<A##N>(); \ assert(a##N); #define FETCH_TGT() \ type_check<T>(args[0], name.name_get()); \ libport::shared_ptr<T> tgt = args[0].unsafe_cast<T>(); #define PRIMITIVE(Met, Ret, ArgsC, Run, Arg1, Arg2, Arg3) \ template <typename T \ COMMA(Ret) WHEN(Ret, typename R) \ COMMA(Arg1) WHEN(Arg1, typename A1) \ COMMA(Arg2) WHEN(Arg2, typename A2) \ COMMA(Arg3) WHEN(Arg3, typename A3) \ > \ struct primitive<T, MET(Met, , Ret, Run, Arg1, Arg2, Arg3)> \ { \ static rObject make( \ MET(Met, method, Ret, Run, Arg1, Arg2, Arg3), \ const libport::Symbol& IF(Met, name, WHEN(Arg1, name)), \ runner::Runner& WHEN(Run, r), \ objects_type args) \ { \ (void)args; \ assert(args.size() == \ ArgsC IF(Met, + 1, WHEN_NOT(Arg1, + 1))); \ WHEN(Met, FETCH_TGT()); \ WHEN(Arg1, GET_ARG(Met, 1)) \ WHEN(Arg2, GET_ARG(Met, 2)) \ WHEN(Arg3, GET_ARG(Met, 3)) \ WHEN(Ret, return) \ (WHEN(Met, tgt.get()->*)method)( \ WHEN(Run, r) COMMA2(Run, Arg1) \ WHEN(Arg1, a1) \ COMMA(Arg2) WHEN(Arg2, a2) \ COMMA(Arg3) WHEN(Arg3, a3) \ ); \ return void_class; \ } \ } #define LIST_MET(Name, Met, Ret, Run) \ IF(Ret, R, void) \ (WHEN(Met, T::)*Name)(WHEN(Run, runner::Runner&) COMMA(Run) \ objects_type) \ #define LIST_PRIMITIVE(Met, Ret, Run) \ template <typename T \ COMMA(Ret) WHEN(Ret, typename R) \ > \ struct primitive<T, LIST_MET(, Met, Ret, Run)> \ { \ static rObject make( \ LIST_MET(method, Met, Ret, Run), \ const libport::Symbol& name, \ runner::Runner& WHEN(Run, r), \ objects_type args) \ { \ (void)name; \ WHEN(Met, FETCH_TGT()); \ WHEN(Met, args.pop_front()); \ WHEN(Ret, return) \ (WHEN(Met, tgt.get()->*)method)( \ WHEN(Run, r) COMMA(Run) \ args \ ); \ return void_class; \ } \ } template <typename T, typename M> struct primitive { }; /* Python for these: for met in ('true', 'false'): for ret in ('true', 'false'): for run in ('true', 'false'): print " LIST_PRIMITIVE(%s, %s, %s);" % (met, ret, run) */ LIST_PRIMITIVE(true, true, true); LIST_PRIMITIVE(true, true, false); LIST_PRIMITIVE(true, false, true); LIST_PRIMITIVE(true, false, false); LIST_PRIMITIVE(false, true, true); LIST_PRIMITIVE(false, true, false); LIST_PRIMITIVE(false, false, true); LIST_PRIMITIVE(false, false, false); /* Python for these: max = 3 for ret in ('true', 'false'): for run in ('true', 'false'): for nargs in range(max + 1): for macro in ('PRIMITIVE ', 'PRIMITIVEF'): print " %s(%s, %i, %s" % (macro, ret, nargs, run), for i in range(max): print ", %s" % str(i < nargs).lower(), print ");" */ PRIMITIVE(true , true, 0, true , false , false , false ); PRIMITIVE(true , true, 1, true , true , false , false ); PRIMITIVE(true , true, 2, true , true , true , false ); PRIMITIVE(true , true, 3, true , true , true , true ); PRIMITIVE(true , true, 0, false , false , false , false ); PRIMITIVE(true , true, 1, false , true , false , false ); PRIMITIVE(true , true, 2, false , true , true , false ); PRIMITIVE(true , true, 3, false , true , true , true ); PRIMITIVE(true , false, 0, true , false , false , false ); PRIMITIVE(true , false, 1, true , true , false , false ); PRIMITIVE(true , false, 2, true , true , true , false ); PRIMITIVE(true , false, 3, true , true , true , true ); PRIMITIVE(true , false, 0, false , false , false , false ); PRIMITIVE(true , false, 1, false , true , false , false ); PRIMITIVE(true , false, 2, false , true , true , false ); PRIMITIVE(true , false, 3, false , true , true , true ); PRIMITIVE(false, true, 0, true , false , false , false ); PRIMITIVE(false, true, 1, true , true , false , false ); PRIMITIVE(false, true, 2, true , true , true , false ); PRIMITIVE(false, true, 3, true , true , true , true ); PRIMITIVE(false, true, 0, false , false , false , false ); PRIMITIVE(false, true, 1, false , true , false , false ); PRIMITIVE(false, true, 2, false , true , true , false ); PRIMITIVE(false, true, 3, false , true , true , true ); PRIMITIVE(false, false, 0, true , false , false , false ); PRIMITIVE(false, false, 1, true , true , false , false ); PRIMITIVE(false, false, 2, true , true , true , false ); PRIMITIVE(false, false, 3, true , true , true , true ); PRIMITIVE(false, false, 0, false , false , false , false ); PRIMITIVE(false, false, 1, false , true , false , false ); PRIMITIVE(false, false, 2, false , true , true , false ); PRIMITIVE(false, false, 3, false , true , true , true ); } template <typename T> template <typename M> void CxxObject::Binder<T>::operator()(const libport::Symbol& name, M method) { // If make is unfound here, you passed an unsupported pointer type // to the binder. rObject p = new Primitive(boost::bind(primitive<T, M>::make, method, name, _1, _2)); tgt_->slot_set(name, p); } template <typename T> inline void type_check(rObject o, const std::string& fun) { libport::shared_ptr<CxxObject> co = o.unsafe_cast<CxxObject>(); // FIXME: I can't fill all the source type for now since some old // atoms don't define type_name for now if (!co) throw object::WrongArgumentType(T::type_name, "Object", fun); else if (!o->is_a<T>()) throw object::WrongArgumentType(T::type_name, co->type_name_get(), fun); } template <> inline void type_check<Object>(rObject, const std::string&) {} template <> inline void type_check<List>(rObject, const std::string&) {} } #endif <|endoftext|>
<commit_before>#include <cstring> #include "../uri/parse-query.hh" #include "../uri/percent-encoding.hh" #include "../stream/buffer.hh" #include "request-reader.hh" namespace mimosa { namespace http { RequestReader::RequestReader(stream::Stream::Ptr stream, runtime::Time read_timeout) : stream_(stream), bytes_left_(0), parsed_form_(false), form_(), read_timeout_(read_timeout) { } void RequestReader::clear() { bytes_left_ = 0; parsed_form_ = false; form_.clear(); } bool RequestReader::prepare() { if (contentLength() < 0) return false; bytes_left_ = contentLength(); return true; } int64_t RequestReader::write(const char * /*data*/, uint64_t /*nbytes*/, runtime::Time /*timeout*/) { assert(false && "invalid operation"); return -1; } int64_t RequestReader::read(char * data, uint64_t nbytes, runtime::Time timeout) { uint64_t can_read = nbytes <= bytes_left_ ? nbytes : bytes_left_; int64_t rbytes = stream_->read(data, can_read, timeout); if (rbytes > 0) bytes_left_ -= rbytes; return rbytes; } bool RequestReader::flush(runtime::Time timeout) { stream::Buffer buffer; while (bytes_left_ > 0) if (read(buffer.data(), buffer.size(), timeout) <= 0) return false; return true; } container::kvs & RequestReader::form() { if (parsed_form_) return form_; if (!::strcasecmp(contentType().c_str(), "application/x-www-form-urlencoded")) { parsed_form_ = true; stream::Buffer buffer(contentLength()); int64_t total_rbytes = 0; while (total_rbytes < contentLength()) { auto rbytes = stream_->read(buffer.data(), contentLength() - total_rbytes, 0); if (rbytes <= 0) return form_; total_rbytes += rbytes; } std::string decoded; uri::percentDecode(buffer.data(), buffer.size(), &decoded, uri::kRfc2396); uri::parseQuery(decoded.data(), decoded.size(), &form_); } return form_; } } } <commit_msg>http: better RequestReader::flush()<commit_after>#include <cstring> #include "../uri/parse-query.hh" #include "../uri/percent-encoding.hh" #include "../stream/buffer.hh" #include "request-reader.hh" namespace mimosa { namespace http { RequestReader::RequestReader(stream::Stream::Ptr stream, runtime::Time read_timeout) : stream_(stream), bytes_left_(0), parsed_form_(false), form_(), read_timeout_(read_timeout) { } void RequestReader::clear() { bytes_left_ = 0; parsed_form_ = false; form_.clear(); } bool RequestReader::prepare() { if (contentLength() < 0) return false; bytes_left_ = contentLength(); return true; } int64_t RequestReader::write(const char * /*data*/, uint64_t /*nbytes*/, runtime::Time /*timeout*/) { assert(false && "invalid operation"); return -1; } int64_t RequestReader::read(char * data, uint64_t nbytes, runtime::Time timeout) { uint64_t can_read = nbytes <= bytes_left_ ? nbytes : bytes_left_; int64_t rbytes = stream_->read(data, can_read, timeout); if (rbytes > 0) bytes_left_ -= rbytes; return rbytes; } bool RequestReader::flush(runtime::Time timeout) { if (bytes_left_ < 0) return true; stream::Buffer buffer(bytes_left_); while (bytes_left_ > 0) if (read(buffer.data(), buffer.size(), timeout) <= 0) return false; return true; } container::kvs & RequestReader::form() { if (parsed_form_) return form_; if (!::strcasecmp(contentType().c_str(), "application/x-www-form-urlencoded")) { parsed_form_ = true; stream::Buffer buffer(contentLength()); int64_t total_rbytes = 0; while (total_rbytes < contentLength()) { auto rbytes = stream_->read(buffer.data(), contentLength() - total_rbytes, 0); if (rbytes <= 0) return form_; total_rbytes += rbytes; } std::string decoded; uri::percentDecode(buffer.data(), buffer.size(), &decoded, uri::kRfc2396); uri::parseQuery(decoded.data(), decoded.size(), &form_); } return form_; } } } <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "latlongmapenvironmentedf.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/global/globaltypes.h" #include "renderer/kernel/lighting/imageimportancesampler.h" #include "renderer/kernel/texturing/texturecache.h" #include "renderer/kernel/texturing/texturestore.h" #include "renderer/modeling/environmentedf/environmentedf.h" #include "renderer/modeling/environmentedf/sphericalcoordinates.h" #include "renderer/modeling/input/inputarray.h" #include "renderer/modeling/input/inputevaluator.h" #include "renderer/modeling/input/source.h" #include "renderer/modeling/input/texturesource.h" #include "renderer/modeling/project/project.h" #include "renderer/modeling/scene/scene.h" #include "renderer/modeling/scene/textureinstance.h" #include "renderer/modeling/texture/texture.h" #include "renderer/utility/paramarray.h" // appleseed.foundation headers. #include "foundation/image/canvasproperties.h" #include "foundation/image/color.h" #include "foundation/image/colorspace.h" #include "foundation/math/sampling.h" #include "foundation/math/scalar.h" #include "foundation/math/vector.h" #include "foundation/platform/compiler.h" #include "foundation/platform/types.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/job/abortswitch.h" // Standard headers. #include <cassert> #include <cmath> #include <cstddef> #include <memory> using namespace foundation; using namespace std; namespace renderer { namespace { // // Latitude-longitude environment map EDF. // // Reference: // // http://www.cs.virginia.edu/~gfx/courses/2007/ImageSynthesis/assignments/envsample.pdf // // Light probes: // // http://gl.ict.usc.edu/Data/HighResProbes/ // http://www.cs.kuleuven.be/~graphics/index.php/environment-maps // struct Payload { uint32 m_x; Color3f m_color; }; typedef ImageImportanceSampler<Payload, double> ImageImportanceSamplerType; class ImageSampler { public: ImageSampler( TextureCache& texture_cache, const Source* radiance_source, const Source* multiplier_source, const size_t width, const size_t height, const double u_shift, const double v_shift) : m_texture_cache(texture_cache) , m_radiance_source(radiance_source) , m_multiplier_source(multiplier_source) , m_rcp_width(1.0 / width) , m_rcp_height(1.0 / height) , m_u_shift(u_shift) , m_v_shift(v_shift) { } void sample(const size_t x, const size_t y, Payload& payload, double& importance) { payload.m_x = static_cast<uint32>(x); if (m_radiance_source == 0) { payload.m_color.set(0.0f); importance = 0.0; return; } const Vector2d uv( (x + 0.5) * m_rcp_width + m_u_shift, 1.0 - (y + 0.5) * m_rcp_height + m_v_shift); m_radiance_source->evaluate(m_texture_cache, uv, payload.m_color); double multiplier; m_multiplier_source->evaluate(m_texture_cache, uv, multiplier); payload.m_color *= static_cast<float>(multiplier); importance = static_cast<double>(luminance(payload.m_color)); } private: TextureCache& m_texture_cache; const Source* m_radiance_source; const Source* m_multiplier_source; const double m_rcp_width; const double m_rcp_height; const double m_u_shift; const double m_v_shift; }; const char* Model = "latlong_map_environment_edf"; class LatLongMapEnvironmentEDF : public EnvironmentEDF { public: LatLongMapEnvironmentEDF( const char* name, const ParamArray& params) : EnvironmentEDF(name, params) , m_importance_map_width(0) , m_importance_map_height(0) , m_probability_scale(0.0) { m_inputs.declare("radiance", InputFormatSpectralIlluminance); m_inputs.declare("radiance_multiplier", InputFormatScalar, "1.0"); m_u_shift = m_params.get_optional<double>("horizontal_shift", 0.0) / 360.0; m_v_shift = m_params.get_optional<double>("vertical_shift", 0.0) / 360.0; } virtual void release() APPLESEED_OVERRIDE { delete this; } virtual const char* get_model() const APPLESEED_OVERRIDE { return Model; } virtual bool on_frame_begin( const Project& project, IAbortSwitch* abort_switch) APPLESEED_OVERRIDE { if (!EnvironmentEDF::on_frame_begin(project, abort_switch)) return false; check_non_zero_emission("radiance", "radiance_multiplier"); if (m_importance_sampler.get() == 0) build_importance_map(*project.get_scene(), abort_switch); return true; } virtual void sample( InputEvaluator& input_evaluator, const Vector2d& s, Vector3d& outgoing, Spectrum& value, double& probability) const APPLESEED_OVERRIDE { // Sample the importance map. Payload payload; size_t y; double prob_xy; m_importance_sampler->sample(s, payload, y, prob_xy); // Compute the coordinates in [0,1]^2 of the sample. const double u = (payload.m_x + 0.5) * m_rcp_importance_map_width; const double v = (y + 0.5) * m_rcp_importance_map_height; // Compute the world space emission direction. double theta, phi; unit_square_to_angles(u, v, theta, phi); outgoing = Vector3d::unit_vector(theta, phi); // Return the emitted radiance. value = payload.m_color; // Compute the probability density of this direction. probability = prob_xy * m_probability_scale / sin(theta); } virtual void evaluate( InputEvaluator& input_evaluator, const Vector3d& outgoing, Spectrum& value) const APPLESEED_OVERRIDE { assert(is_normalized(outgoing)); double theta, phi; unit_vector_to_angles(outgoing, theta, phi); double u, v; angles_to_unit_square(theta, phi, u, v); lookup_environment_map(input_evaluator, u, v, value); } virtual void evaluate( InputEvaluator& input_evaluator, const Vector3d& outgoing, Spectrum& value, double& probability) const APPLESEED_OVERRIDE { assert(is_normalized(outgoing)); double theta, phi; unit_vector_to_angles(outgoing, theta, phi); double u, v; angles_to_unit_square(theta, phi, u, v); lookup_environment_map(input_evaluator, u, v, value); probability = compute_pdf(u, v, theta); } virtual double evaluate_pdf( InputEvaluator& input_evaluator, const Vector3d& outgoing) const APPLESEED_OVERRIDE { assert(is_normalized(outgoing)); double theta, phi; unit_vector_to_angles(outgoing, theta, phi); double u, v; angles_to_unit_square(theta, phi, u, v); return compute_pdf(u, v, theta); } private: APPLESEED_DECLARE_INPUT_VALUES(InputValues) { Spectrum m_radiance; // emitted radiance in W.m^-2.sr^-1 double m_radiance_multiplier; // emitted radiance multiplier }; double m_u_shift; double m_v_shift; size_t m_importance_map_width; size_t m_importance_map_height; double m_rcp_importance_map_width; double m_rcp_importance_map_height; double m_probability_scale; auto_ptr<ImageImportanceSamplerType> m_importance_sampler; void build_importance_map(const Scene& scene, IAbortSwitch*abort_switch) { const Source* radiance_source = m_inputs.source("radiance"); assert(radiance_source); if (dynamic_cast<const TextureSource*>(radiance_source)) { const TextureSource* texture_source = static_cast<const TextureSource*>(radiance_source); const TextureInstance& texture_instance = texture_source->get_texture_instance(); const CanvasProperties& texture_props = texture_instance.get_texture().properties(); m_importance_map_width = texture_props.m_canvas_width; m_importance_map_height = texture_props.m_canvas_height; } else { RENDERER_LOG_ERROR( "while building importance map for environment edf \"%s\": a texture instance " "must be bound to the \"radiance\" input.", get_name()); m_importance_map_width = 1; m_importance_map_height = 1; } m_rcp_importance_map_width = 1.0 / m_importance_map_width; m_rcp_importance_map_height = 1.0 / m_importance_map_height; const size_t texel_count = m_importance_map_width * m_importance_map_height; m_probability_scale = texel_count / (2.0 * Pi * Pi); TextureStore texture_store(scene); TextureCache texture_cache(texture_store); ImageSampler sampler( texture_cache, radiance_source, m_inputs.source("radiance_multiplier"), m_importance_map_width, m_importance_map_height, m_u_shift, m_v_shift); m_importance_sampler.reset( new ImageImportanceSamplerType( m_importance_map_width, m_importance_map_height)); RENDERER_LOG_INFO( "building " FMT_SIZE_T "x" FMT_SIZE_T " importance map " "for environment edf \"%s\"...", m_importance_map_width, m_importance_map_height, get_name()); m_importance_sampler->rebuild(sampler, abort_switch); if (is_aborted(abort_switch)) m_importance_sampler.reset(); else { RENDERER_LOG_INFO( "built importance map for environment edf \"%s\".", get_name()); } } void lookup_environment_map( InputEvaluator& input_evaluator, const double u, const double v, Spectrum& value) const { const Vector2d uv(u + m_u_shift, 1.0 - v + m_v_shift); const InputValues* values = input_evaluator.evaluate<InputValues>(m_inputs, uv); value = values->m_radiance; value *= static_cast<float>(values->m_radiance_multiplier); } double compute_pdf( const double u, const double v, const double theta) const { // Compute the probability density of this sample in the importance map. const size_t x = truncate<size_t>(m_importance_map_width * u); const size_t y = truncate<size_t>(m_importance_map_height * v); const double prob_xy = m_importance_sampler->get_pdf(x, y); // Compute the probability density of the emission direction. return prob_xy * m_probability_scale / sin(theta); } }; } // // LatLongMapEnvironmentEDFFactory class implementation. // const char* LatLongMapEnvironmentEDFFactory::get_model() const { return Model; } const char* LatLongMapEnvironmentEDFFactory::get_human_readable_model() const { return "Latitude-Longitude Map Environment EDF"; } DictionaryArray LatLongMapEnvironmentEDFFactory::get_input_metadata() const { DictionaryArray metadata; metadata.push_back( Dictionary() .insert("name", "radiance") .insert("label", "Radiance") .insert("type", "colormap") .insert("entity_types", Dictionary() .insert("texture_instance", "Textures")) .insert("use", "required") .insert("default", "1.0")); metadata.push_back( Dictionary() .insert("name", "radiance_multiplier") .insert("label", "Radiance Multiplier") .insert("type", "colormap") .insert("entity_types", Dictionary().insert("texture_instance", "Textures")) .insert("use", "optional") .insert("default", "1.0")); metadata.push_back( Dictionary() .insert("name", "horizontal_shift") .insert("label", "Horizontal Shift") .insert("type", "numeric") .insert("min_value", "-360.0") .insert("max_value", "360.0") .insert("default", "0.0") .insert("use", "optional")); metadata.push_back( Dictionary() .insert("name", "vertical_shift") .insert("label", "Vertical Shift") .insert("type", "numeric") .insert("min_value", "-360.0") .insert("max_value", "360.0") .insert("default", "0.0") .insert("use", "optional")); return metadata; } auto_release_ptr<EnvironmentEDF> LatLongMapEnvironmentEDFFactory::create( const char* name, const ParamArray& params) const { return auto_release_ptr<EnvironmentEDF>( new LatLongMapEnvironmentEDF(name, params)); } } // namespace renderer <commit_msg>small performance optimization.<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "latlongmapenvironmentedf.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/global/globaltypes.h" #include "renderer/kernel/lighting/imageimportancesampler.h" #include "renderer/kernel/texturing/texturecache.h" #include "renderer/kernel/texturing/texturestore.h" #include "renderer/modeling/environmentedf/environmentedf.h" #include "renderer/modeling/environmentedf/sphericalcoordinates.h" #include "renderer/modeling/input/inputarray.h" #include "renderer/modeling/input/inputevaluator.h" #include "renderer/modeling/input/source.h" #include "renderer/modeling/input/texturesource.h" #include "renderer/modeling/project/project.h" #include "renderer/modeling/scene/scene.h" #include "renderer/modeling/scene/textureinstance.h" #include "renderer/modeling/texture/texture.h" #include "renderer/utility/paramarray.h" // appleseed.foundation headers. #include "foundation/image/canvasproperties.h" #include "foundation/image/color.h" #include "foundation/image/colorspace.h" #include "foundation/math/sampling.h" #include "foundation/math/scalar.h" #include "foundation/math/vector.h" #include "foundation/platform/compiler.h" #include "foundation/platform/types.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/job/abortswitch.h" // Standard headers. #include <cassert> #include <cmath> #include <cstddef> #include <memory> using namespace foundation; using namespace std; namespace renderer { namespace { // // Latitude-longitude environment map EDF. // // Reference: // // http://www.cs.virginia.edu/~gfx/courses/2007/ImageSynthesis/assignments/envsample.pdf // // Light probes: // // http://gl.ict.usc.edu/Data/HighResProbes/ // http://www.cs.kuleuven.be/~graphics/index.php/environment-maps // struct Payload { uint32 m_x; Color3f m_color; }; typedef ImageImportanceSampler<Payload, double> ImageImportanceSamplerType; class ImageSampler { public: ImageSampler( TextureCache& texture_cache, const Source* radiance_source, const Source* multiplier_source, const size_t width, const size_t height, const double u_shift, const double v_shift) : m_texture_cache(texture_cache) , m_radiance_source(radiance_source) , m_multiplier_source(multiplier_source) , m_rcp_width(1.0 / width) , m_rcp_height(1.0 / height) , m_u_shift(u_shift) , m_v_shift(v_shift) { } void sample(const size_t x, const size_t y, Payload& payload, double& importance) { payload.m_x = static_cast<uint32>(x); if (m_radiance_source == 0) { payload.m_color.set(0.0f); importance = 0.0; return; } const Vector2d uv( (x + 0.5) * m_rcp_width + m_u_shift, 1.0 - (y + 0.5) * m_rcp_height + m_v_shift); m_radiance_source->evaluate(m_texture_cache, uv, payload.m_color); double multiplier; m_multiplier_source->evaluate(m_texture_cache, uv, multiplier); payload.m_color *= static_cast<float>(multiplier); importance = static_cast<double>(luminance(payload.m_color)); } private: TextureCache& m_texture_cache; const Source* m_radiance_source; const Source* m_multiplier_source; const double m_rcp_width; const double m_rcp_height; const double m_u_shift; const double m_v_shift; }; const char* Model = "latlong_map_environment_edf"; class LatLongMapEnvironmentEDF : public EnvironmentEDF { public: LatLongMapEnvironmentEDF( const char* name, const ParamArray& params) : EnvironmentEDF(name, params) , m_importance_map_width(0) , m_importance_map_height(0) , m_probability_scale(0.0) { m_inputs.declare("radiance", InputFormatSpectralIlluminance); m_inputs.declare("radiance_multiplier", InputFormatScalar, "1.0"); m_u_shift = m_params.get_optional<double>("horizontal_shift", 0.0) / 360.0; m_v_shift = m_params.get_optional<double>("vertical_shift", 0.0) / 360.0; } virtual void release() APPLESEED_OVERRIDE { delete this; } virtual const char* get_model() const APPLESEED_OVERRIDE { return Model; } virtual bool on_frame_begin( const Project& project, IAbortSwitch* abort_switch) APPLESEED_OVERRIDE { if (!EnvironmentEDF::on_frame_begin(project, abort_switch)) return false; check_non_zero_emission("radiance", "radiance_multiplier"); if (m_importance_sampler.get() == 0) build_importance_map(*project.get_scene(), abort_switch); return true; } virtual void sample( InputEvaluator& input_evaluator, const Vector2d& s, Vector3d& outgoing, Spectrum& value, double& probability) const APPLESEED_OVERRIDE { // Sample the importance map. Payload payload; size_t y; double prob_xy; m_importance_sampler->sample(s, payload, y, prob_xy); // Compute the coordinates in [0,1]^2 of the sample. const double u = (payload.m_x + 0.5) * m_rcp_importance_map_width; const double v = (y + 0.5) * m_rcp_importance_map_height; // Compute the world space emission direction. double theta, phi; unit_square_to_angles(u, v, theta, phi); const double cos_theta = cos(theta); const double sin_theta = sin(theta); const double cos_phi = cos(phi); const double sin_phi = sin(phi); outgoing = Vector3d::unit_vector(cos_theta, sin_theta, cos_phi, sin_phi); // Return the emitted radiance. value = payload.m_color; // Compute the probability density of this direction. probability = prob_xy * m_probability_scale / sin_theta; } virtual void evaluate( InputEvaluator& input_evaluator, const Vector3d& outgoing, Spectrum& value) const APPLESEED_OVERRIDE { assert(is_normalized(outgoing)); double theta, phi; unit_vector_to_angles(outgoing, theta, phi); double u, v; angles_to_unit_square(theta, phi, u, v); lookup_environment_map(input_evaluator, u, v, value); } virtual void evaluate( InputEvaluator& input_evaluator, const Vector3d& outgoing, Spectrum& value, double& probability) const APPLESEED_OVERRIDE { assert(is_normalized(outgoing)); double theta, phi; unit_vector_to_angles(outgoing, theta, phi); double u, v; angles_to_unit_square(theta, phi, u, v); lookup_environment_map(input_evaluator, u, v, value); probability = compute_pdf(u, v, theta); } virtual double evaluate_pdf( InputEvaluator& input_evaluator, const Vector3d& outgoing) const APPLESEED_OVERRIDE { assert(is_normalized(outgoing)); double theta, phi; unit_vector_to_angles(outgoing, theta, phi); double u, v; angles_to_unit_square(theta, phi, u, v); return compute_pdf(u, v, theta); } private: APPLESEED_DECLARE_INPUT_VALUES(InputValues) { Spectrum m_radiance; // emitted radiance in W.m^-2.sr^-1 double m_radiance_multiplier; // emitted radiance multiplier }; double m_u_shift; double m_v_shift; size_t m_importance_map_width; size_t m_importance_map_height; double m_rcp_importance_map_width; double m_rcp_importance_map_height; double m_probability_scale; auto_ptr<ImageImportanceSamplerType> m_importance_sampler; void build_importance_map(const Scene& scene, IAbortSwitch*abort_switch) { const Source* radiance_source = m_inputs.source("radiance"); assert(radiance_source); if (dynamic_cast<const TextureSource*>(radiance_source)) { const TextureSource* texture_source = static_cast<const TextureSource*>(radiance_source); const TextureInstance& texture_instance = texture_source->get_texture_instance(); const CanvasProperties& texture_props = texture_instance.get_texture().properties(); m_importance_map_width = texture_props.m_canvas_width; m_importance_map_height = texture_props.m_canvas_height; } else { RENDERER_LOG_ERROR( "while building importance map for environment edf \"%s\": a texture instance " "must be bound to the \"radiance\" input.", get_name()); m_importance_map_width = 1; m_importance_map_height = 1; } m_rcp_importance_map_width = 1.0 / m_importance_map_width; m_rcp_importance_map_height = 1.0 / m_importance_map_height; const size_t texel_count = m_importance_map_width * m_importance_map_height; m_probability_scale = texel_count / (2.0 * Pi * Pi); TextureStore texture_store(scene); TextureCache texture_cache(texture_store); ImageSampler sampler( texture_cache, radiance_source, m_inputs.source("radiance_multiplier"), m_importance_map_width, m_importance_map_height, m_u_shift, m_v_shift); m_importance_sampler.reset( new ImageImportanceSamplerType( m_importance_map_width, m_importance_map_height)); RENDERER_LOG_INFO( "building " FMT_SIZE_T "x" FMT_SIZE_T " importance map " "for environment edf \"%s\"...", m_importance_map_width, m_importance_map_height, get_name()); m_importance_sampler->rebuild(sampler, abort_switch); if (is_aborted(abort_switch)) m_importance_sampler.reset(); else { RENDERER_LOG_INFO( "built importance map for environment edf \"%s\".", get_name()); } } void lookup_environment_map( InputEvaluator& input_evaluator, const double u, const double v, Spectrum& value) const { const Vector2d uv(u + m_u_shift, 1.0 - v + m_v_shift); const InputValues* values = input_evaluator.evaluate<InputValues>(m_inputs, uv); value = values->m_radiance; value *= static_cast<float>(values->m_radiance_multiplier); } double compute_pdf( const double u, const double v, const double theta) const { // Compute the probability density of this sample in the importance map. const size_t x = truncate<size_t>(m_importance_map_width * u); const size_t y = truncate<size_t>(m_importance_map_height * v); const double prob_xy = m_importance_sampler->get_pdf(x, y); // Compute the probability density of the emission direction. return prob_xy * m_probability_scale / sin(theta); } }; } // // LatLongMapEnvironmentEDFFactory class implementation. // const char* LatLongMapEnvironmentEDFFactory::get_model() const { return Model; } const char* LatLongMapEnvironmentEDFFactory::get_human_readable_model() const { return "Latitude-Longitude Map Environment EDF"; } DictionaryArray LatLongMapEnvironmentEDFFactory::get_input_metadata() const { DictionaryArray metadata; metadata.push_back( Dictionary() .insert("name", "radiance") .insert("label", "Radiance") .insert("type", "colormap") .insert("entity_types", Dictionary() .insert("texture_instance", "Textures")) .insert("use", "required") .insert("default", "1.0")); metadata.push_back( Dictionary() .insert("name", "radiance_multiplier") .insert("label", "Radiance Multiplier") .insert("type", "colormap") .insert("entity_types", Dictionary().insert("texture_instance", "Textures")) .insert("use", "optional") .insert("default", "1.0")); metadata.push_back( Dictionary() .insert("name", "horizontal_shift") .insert("label", "Horizontal Shift") .insert("type", "numeric") .insert("min_value", "-360.0") .insert("max_value", "360.0") .insert("default", "0.0") .insert("use", "optional")); metadata.push_back( Dictionary() .insert("name", "vertical_shift") .insert("label", "Vertical Shift") .insert("type", "numeric") .insert("min_value", "-360.0") .insert("max_value", "360.0") .insert("default", "0.0") .insert("use", "optional")); return metadata; } auto_release_ptr<EnvironmentEDF> LatLongMapEnvironmentEDFFactory::create( const char* name, const ParamArray& params) const { return auto_release_ptr<EnvironmentEDF>( new LatLongMapEnvironmentEDF(name, params)); } } // namespace renderer <|endoftext|>
<commit_before><commit_msg>Fix loss scaling when running ORTTrainer with BERT under mixed-precision mode (#6932)<commit_after><|endoftext|>
<commit_before>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2015 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/base/ring_buffer.h" #include <algorithm> #include <cstring> namespace xe { RingBuffer::RingBuffer(uint8_t* buffer, size_t capacity) : buffer_(buffer), capacity_(capacity) {} RingBuffer::ReadRange RingBuffer::BeginRead(size_t count) { count = std::min(count, capacity_); if (!count) { return {0}; } if (read_offset_ + count < capacity_) { return {buffer_ + read_offset_, count, nullptr, 0}; } else { size_t left_half = capacity_ - read_offset_; size_t right_half = count - left_half; return {buffer_ + read_offset_, left_half, buffer_, right_half}; } } void RingBuffer::EndRead(ReadRange read_range) { if (read_range.second_length) { read_offset_ = read_range.second_length; } else { read_offset_ += read_range.first_length; } } size_t RingBuffer::Read(uint8_t* buffer, size_t count) { count = std::min(count, capacity_); if (!count) { return 0; } if (read_offset_ + count < capacity_) { std::memcpy(buffer, buffer_ + read_offset_, count); read_offset_ += count; } else { size_t left_half = capacity_ - read_offset_; size_t right_half = count - left_half; std::memcpy(buffer, buffer_ + read_offset_, left_half); std::memcpy(buffer + left_half, buffer_, right_half); read_offset_ = right_half; } return count; } size_t RingBuffer::Write(const uint8_t* buffer, size_t count) { count = std::min(count, capacity_); if (!count) { return 0; } if (write_offset_ + count < capacity_) { std::memcpy(buffer_ + write_offset_, buffer, count); write_offset_ += count; } else { size_t left_half = capacity_ - write_offset_; size_t right_half = count - left_half; std::memcpy(buffer_ + write_offset_, buffer, left_half); std::memcpy(buffer_, buffer + left_half, right_half); write_offset_ = right_half; } return count; } } // namespace xe <commit_msg>Fix RingBuffer::EndRead not detecting a split read (where second length == 0)<commit_after>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2015 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/base/ring_buffer.h" #include <algorithm> #include <cstring> namespace xe { RingBuffer::RingBuffer(uint8_t* buffer, size_t capacity) : buffer_(buffer), capacity_(capacity) {} RingBuffer::ReadRange RingBuffer::BeginRead(size_t count) { count = std::min(count, capacity_); if (!count) { return {0}; } if (read_offset_ + count < capacity_) { return {buffer_ + read_offset_, count, nullptr, 0}; } else { size_t left_half = capacity_ - read_offset_; size_t right_half = count - left_half; return {buffer_ + read_offset_, left_half, buffer_, right_half}; } } void RingBuffer::EndRead(ReadRange read_range) { if (read_range.second) { read_offset_ = read_range.second_length; } else { read_offset_ += read_range.first_length; } } size_t RingBuffer::Read(uint8_t* buffer, size_t count) { count = std::min(count, capacity_); if (!count) { return 0; } if (read_offset_ + count < capacity_) { std::memcpy(buffer, buffer_ + read_offset_, count); read_offset_ += count; } else { size_t left_half = capacity_ - read_offset_; size_t right_half = count - left_half; std::memcpy(buffer, buffer_ + read_offset_, left_half); std::memcpy(buffer + left_half, buffer_, right_half); read_offset_ = right_half; } return count; } size_t RingBuffer::Write(const uint8_t* buffer, size_t count) { count = std::min(count, capacity_); if (!count) { return 0; } if (write_offset_ + count < capacity_) { std::memcpy(buffer_ + write_offset_, buffer, count); write_offset_ += count; } else { size_t left_half = capacity_ - write_offset_; size_t right_half = count - left_half; std::memcpy(buffer_ + write_offset_, buffer, left_half); std::memcpy(buffer_, buffer + left_half, right_half); write_offset_ = right_half; } return count; } } // namespace xe <|endoftext|>
<commit_before>/** * @file AddingImages.cpp * @brief Simple linear blender ( dst = alpha*src1 + beta*src2 ) * @author OpenCV team */ #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include <iostream> using namespace cv; /** * @function main * @brief Main function */ int main( void ) { double alpha = 0.5; double beta; double input; Mat src1, src2, dst; /// Ask the user enter alpha std::cout<<" Simple Linear Blender "<<std::endl; std::cout<<"-----------------------"<<std::endl; std::cout<<"* Enter alpha [0-1]: "; std::cin>>input; // We use the alpha provided by the user if it is between 0 and 1 if( alpha >= 0 && alpha <= 1 ) { alpha = input; } //![load] /// Read images ( both have to be of the same size and type ) src1 = imread("../data/LinuxLogo.jpg"); src2 = imread("../data/WindowsLogo.jpg"); //![load] if( src1.empty() ) { std::cout<< "Error loading src1"<<std::endl; return -1; } if( src2.empty() ) { std::cout<< "Error loading src2"<<std::endl; return -1; } //![blend_images] beta = ( 1.0 - alpha ); addWeighted( src1, alpha, src2, beta, 0.0, dst); //![blend_images] //![display] imshow( "Linear Blend", dst ); waitKey(0); //![display] return 0; } <commit_msg>Update AddingImages.cpp<commit_after>/** * @file AddingImages.cpp * @brief Simple linear blender ( dst = alpha*src1 + beta*src2 ) * @author OpenCV team */ #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include <iostream> using namespace cv; /** * @function main * @brief Main function */ int main( void ) { double alpha = 0.5; double beta; double input; Mat src1, src2, dst; /// Ask the user enter alpha std::cout<<" Simple Linear Blender "<<std::endl; std::cout<<"-----------------------"<<std::endl; std::cout<<"* Enter alpha [0-1]: "; std::cin>>input; // We use the alpha provided by the user if it is between 0 and 1 if( input >= 0 && input <= 1 ) { alpha = input; } //![load] /// Read images ( both have to be of the same size and type ) src1 = imread("../data/LinuxLogo.jpg"); src2 = imread("../data/WindowsLogo.jpg"); //![load] if( src1.empty() ) { std::cout<< "Error loading src1"<<std::endl; return -1; } if( src2.empty() ) { std::cout<< "Error loading src2"<<std::endl; return -1; } //![blend_images] beta = ( 1.0 - alpha ); addWeighted( src1, alpha, src2, beta, 0.0, dst); //![blend_images] //![display] imshow( "Linear Blend", dst ); waitKey(0); //![display] return 0; } <|endoftext|>
<commit_before>/*************************************************************************/ /* gdnative.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "gdnative.h" #include "global_constants.h" #include "io/file_access_encrypted.h" #include "os/file_access.h" #include "os/os.h" #include "project_settings.h" #include "scene/main/scene_tree.h" const String init_symbol = "godot_gdnative_init"; const String terminate_symbol = "godot_gdnative_terminate"; String GDNativeLibrary::platform_names[NUM_PLATFORMS] = { "X11_32bit", "X11_64bit", "Windows_32bit", "Windows_64bit", "OSX", "Android", "iOS", "WebAssembly" }; String GDNativeLibrary::platform_lib_ext[NUM_PLATFORMS] = { "so", "so", "dll", "dll", "dylib", "so", "dylib", "wasm" }; // TODO(karroffel): make this actually do something lol. GDNativeLibrary::Platform GDNativeLibrary::current_platform = X11_64BIT; GDNativeLibrary::GDNativeLibrary() : library_paths() { } GDNativeLibrary::~GDNativeLibrary() { } void GDNativeLibrary::_bind_methods() { ClassDB::bind_method(D_METHOD("set_library_path", "platform", "path"), &GDNativeLibrary::set_library_path); ClassDB::bind_method(D_METHOD("get_library_path", "platform"), &GDNativeLibrary::get_library_path); } bool GDNativeLibrary::_set(const StringName &p_name, const Variant &p_value) { String name = p_name; if (name.begins_with("platform/")) { set_library_path(name.get_slice("/", 1), p_value); return true; } return false; } bool GDNativeLibrary::_get(const StringName &p_name, Variant &r_ret) const { String name = p_name; if (name.begins_with("platform/")) { r_ret = get_library_path(name.get_slice("/", 1)); return true; } return false; } void GDNativeLibrary::_get_property_list(List<PropertyInfo> *p_list) const { for (int i = 0; i < NUM_PLATFORMS; i++) { p_list->push_back(PropertyInfo(Variant::STRING, "platform/" + platform_names[i], PROPERTY_HINT_FILE, "*." + platform_lib_ext[i])); } } void GDNativeLibrary::set_library_path(StringName p_platform, String p_path) { int i; for (i = 0; i <= NUM_PLATFORMS; i++) { if (i == NUM_PLATFORMS) break; if (platform_names[i] == p_platform) { break; } } if (i == NUM_PLATFORMS) { ERR_EXPLAIN(String("No such platform: ") + p_platform); ERR_FAIL(); } library_paths[i] = p_path; } String GDNativeLibrary::get_library_path(StringName p_platform) const { int i; for (i = 0; i <= NUM_PLATFORMS; i++) { if (i == NUM_PLATFORMS) break; if (platform_names[i] == p_platform) { break; } } if (i == NUM_PLATFORMS) { ERR_EXPLAIN(String("No such platform: ") + p_platform); ERR_FAIL_V(""); } return library_paths[i]; } String GDNativeLibrary::get_active_library_path() const { return library_paths[GDNativeLibrary::current_platform]; } GDNative::GDNative() { initialized = false; native_handle = NULL; } GDNative::~GDNative() { // TODO(karroffel): implement ALL the things! } extern "C" void _api_anchor(); void GDNative::_compile_dummy_for_api() { _api_anchor(); } void GDNative::_bind_methods() { ClassDB::bind_method(D_METHOD("set_library", "library:GDNativeLibrary"), &GDNative::set_library); ClassDB::bind_method(D_METHOD("get_library:GDNativeLibrary"), &GDNative::get_library); ClassDB::bind_method(D_METHOD("initialize"), &GDNative::initialize); ClassDB::bind_method(D_METHOD("terminate"), &GDNative::terminate); // TODO(karroffel): get_native_(raw_)call_types binding? // TODO(karroffel): make this a varargs function? ClassDB::bind_method(D_METHOD("call_native:Variant", "procedure_name", "arguments:Array"), &GDNative::call_native); ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "library", PROPERTY_HINT_RESOURCE_TYPE, "GDNativeLibrary"), "set_library", "get_library"); } void GDNative::set_library(Ref<GDNativeLibrary> p_library) { library = p_library; } Ref<GDNativeLibrary> GDNative::get_library() { return library; } bool GDNative::initialize() { if (library.is_null()) { ERR_PRINT("No library set, can't initialize GDNative object"); return false; } String lib_path = library->get_active_library_path(); if (lib_path.empty()) { ERR_PRINT("No library set for this platform"); return false; } String path = ProjectSettings::get_singleton()->globalize_path(lib_path); Error err = OS::get_singleton()->open_dynamic_library(path, native_handle); if (err != OK) { return false; } void *library_init; err = OS::get_singleton()->get_dynamic_library_symbol_handle( native_handle, init_symbol, library_init); if (err || !library_init) { return false; } godot_gdnative_init_fn library_init_fpointer; library_init_fpointer = (godot_gdnative_init_fn)library_init; godot_gdnative_init_options options; options.in_editor = SceneTree::get_singleton()->is_editor_hint(); options.core_api_hash = ClassDB::get_api_hash(ClassDB::API_CORE); options.editor_api_hash = ClassDB::get_api_hash(ClassDB::API_EDITOR); options.no_api_hash = ClassDB::get_api_hash(ClassDB::API_NONE); library_init_fpointer(&options); return true; } bool GDNative::terminate() { if (native_handle == NULL) { ERR_PRINT("No valid library handle, can't terminate GDNative object"); return false; } Error error = OK; void *library_terminate; error = OS::get_singleton()->get_dynamic_library_symbol_handle( native_handle, terminate_symbol, library_terminate); if (error) { OS::get_singleton()->close_dynamic_library(native_handle); native_handle = NULL; return true; } godot_gdnative_terminate_fn library_terminate_pointer; library_terminate_pointer = (godot_gdnative_terminate_fn)library_terminate; // TODO(karroffel): remove this? Should be part of NativeScript, not // GDNative IMO godot_gdnative_terminate_options options; options.in_editor = SceneTree::get_singleton()->is_editor_hint(); library_terminate_pointer(&options); // GDNativeScriptLanguage::get_singleton()->initialized_libraries.erase(p_native_lib->path); OS::get_singleton()->close_dynamic_library(native_handle); native_handle = NULL; return false; } void GDNativeCallRegistry::register_native_call_type(StringName p_call_type, native_call_cb p_callback) { native_calls.insert(p_call_type, p_callback); } void GDNativeCallRegistry::register_native_raw_call_type(StringName p_raw_call_type, native_raw_call_cb p_callback) { native_raw_calls.insert(p_raw_call_type, p_callback); } Vector<StringName> GDNativeCallRegistry::get_native_call_types() { Vector<StringName> call_types; call_types.resize(native_calls.size()); size_t idx = 0; for (Map<StringName, native_call_cb>::Element *E = native_calls.front(); E; E = E->next(), idx++) { call_types[idx] = E->key(); } return call_types; } Vector<StringName> GDNativeCallRegistry::get_native_raw_call_types() { Vector<StringName> call_types; call_types.resize(native_raw_calls.size()); size_t idx = 0; for (Map<StringName, native_raw_call_cb>::Element *E = native_raw_calls.front(); E; E = E->next(), idx++) { call_types[idx] = E->key(); } return call_types; } Variant GDNative::call_native(StringName p_native_call_type, StringName p_procedure_name, Array p_arguments) { Map<StringName, native_call_cb>::Element *E = GDNativeCallRegistry::singleton->native_calls.find(p_native_call_type); if (!E) { ERR_PRINT((String("No handler for native call type \"" + p_native_call_type) + "\" found").utf8().get_data()); return Variant(); } String procedure_name = p_procedure_name; godot_variant result = E->get()(native_handle, (godot_string *)&procedure_name, (godot_array *)&p_arguments); return *(Variant *)&result; } void GDNative::call_native_raw(StringName p_raw_call_type, StringName p_procedure_name, void *data, int num_args, void **args, void *r_return) { Map<StringName, native_raw_call_cb>::Element *E = GDNativeCallRegistry::singleton->native_raw_calls.find(p_raw_call_type); if (!E) { ERR_PRINT((String("No handler for native raw call type \"" + p_raw_call_type) + "\" found").utf8().get_data()); return; } String procedure_name = p_procedure_name; E->get()(native_handle, (godot_string *)&procedure_name, data, num_args, args, r_return); } <commit_msg>[GDNative] basic OS detection<commit_after>/*************************************************************************/ /* gdnative.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "gdnative.h" #include "global_constants.h" #include "io/file_access_encrypted.h" #include "os/file_access.h" #include "os/os.h" #include "project_settings.h" #include "scene/main/scene_tree.h" const String init_symbol = "godot_gdnative_init"; const String terminate_symbol = "godot_gdnative_terminate"; String GDNativeLibrary::platform_names[NUM_PLATFORMS] = { "X11_32bit", "X11_64bit", "Windows_32bit", "Windows_64bit", "OSX", "Android", "iOS", "WebAssembly" }; String GDNativeLibrary::platform_lib_ext[NUM_PLATFORMS] = { "so", "so", "dll", "dll", "dylib", "so", "dylib", "wasm" }; // TODO(karroffel): make this actually do the right thing. GDNativeLibrary::Platform GDNativeLibrary::current_platform = #if defined(X11_ENABLED) X11_64BIT; #elif defined(WINDOWS_ENABLED) WINDOWS_64BIT; #elif defined(OSX_ENABLED) OSX; #else X11_64BIT; // need a sensible default.. #endif GDNativeLibrary::GDNativeLibrary() : library_paths() { } GDNativeLibrary::~GDNativeLibrary() { } void GDNativeLibrary::_bind_methods() { ClassDB::bind_method(D_METHOD("set_library_path", "platform", "path"), &GDNativeLibrary::set_library_path); ClassDB::bind_method(D_METHOD("get_library_path", "platform"), &GDNativeLibrary::get_library_path); } bool GDNativeLibrary::_set(const StringName &p_name, const Variant &p_value) { String name = p_name; if (name.begins_with("platform/")) { set_library_path(name.get_slice("/", 1), p_value); return true; } return false; } bool GDNativeLibrary::_get(const StringName &p_name, Variant &r_ret) const { String name = p_name; if (name.begins_with("platform/")) { r_ret = get_library_path(name.get_slice("/", 1)); return true; } return false; } void GDNativeLibrary::_get_property_list(List<PropertyInfo> *p_list) const { for (int i = 0; i < NUM_PLATFORMS; i++) { p_list->push_back(PropertyInfo(Variant::STRING, "platform/" + platform_names[i], PROPERTY_HINT_FILE, "*." + platform_lib_ext[i])); } } void GDNativeLibrary::set_library_path(StringName p_platform, String p_path) { int i; for (i = 0; i <= NUM_PLATFORMS; i++) { if (i == NUM_PLATFORMS) break; if (platform_names[i] == p_platform) { break; } } if (i == NUM_PLATFORMS) { ERR_EXPLAIN(String("No such platform: ") + p_platform); ERR_FAIL(); } library_paths[i] = p_path; } String GDNativeLibrary::get_library_path(StringName p_platform) const { int i; for (i = 0; i <= NUM_PLATFORMS; i++) { if (i == NUM_PLATFORMS) break; if (platform_names[i] == p_platform) { break; } } if (i == NUM_PLATFORMS) { ERR_EXPLAIN(String("No such platform: ") + p_platform); ERR_FAIL_V(""); } return library_paths[i]; } String GDNativeLibrary::get_active_library_path() const { return library_paths[GDNativeLibrary::current_platform]; } GDNative::GDNative() { initialized = false; native_handle = NULL; } GDNative::~GDNative() { // TODO(karroffel): implement ALL the things! } extern "C" void _api_anchor(); void GDNative::_compile_dummy_for_api() { _api_anchor(); } void GDNative::_bind_methods() { ClassDB::bind_method(D_METHOD("set_library", "library:GDNativeLibrary"), &GDNative::set_library); ClassDB::bind_method(D_METHOD("get_library:GDNativeLibrary"), &GDNative::get_library); ClassDB::bind_method(D_METHOD("initialize"), &GDNative::initialize); ClassDB::bind_method(D_METHOD("terminate"), &GDNative::terminate); // TODO(karroffel): get_native_(raw_)call_types binding? // TODO(karroffel): make this a varargs function? ClassDB::bind_method(D_METHOD("call_native:Variant", "procedure_name", "arguments:Array"), &GDNative::call_native); ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "library", PROPERTY_HINT_RESOURCE_TYPE, "GDNativeLibrary"), "set_library", "get_library"); } void GDNative::set_library(Ref<GDNativeLibrary> p_library) { library = p_library; } Ref<GDNativeLibrary> GDNative::get_library() { return library; } bool GDNative::initialize() { if (library.is_null()) { ERR_PRINT("No library set, can't initialize GDNative object"); return false; } String lib_path = library->get_active_library_path(); if (lib_path.empty()) { ERR_PRINT("No library set for this platform"); return false; } String path = ProjectSettings::get_singleton()->globalize_path(lib_path); Error err = OS::get_singleton()->open_dynamic_library(path, native_handle); if (err != OK) { return false; } void *library_init; err = OS::get_singleton()->get_dynamic_library_symbol_handle( native_handle, init_symbol, library_init); if (err || !library_init) { return false; } godot_gdnative_init_fn library_init_fpointer; library_init_fpointer = (godot_gdnative_init_fn)library_init; godot_gdnative_init_options options; options.in_editor = SceneTree::get_singleton()->is_editor_hint(); options.core_api_hash = ClassDB::get_api_hash(ClassDB::API_CORE); options.editor_api_hash = ClassDB::get_api_hash(ClassDB::API_EDITOR); options.no_api_hash = ClassDB::get_api_hash(ClassDB::API_NONE); library_init_fpointer(&options); return true; } bool GDNative::terminate() { if (native_handle == NULL) { ERR_PRINT("No valid library handle, can't terminate GDNative object"); return false; } Error error = OK; void *library_terminate; error = OS::get_singleton()->get_dynamic_library_symbol_handle( native_handle, terminate_symbol, library_terminate); if (error) { OS::get_singleton()->close_dynamic_library(native_handle); native_handle = NULL; return true; } godot_gdnative_terminate_fn library_terminate_pointer; library_terminate_pointer = (godot_gdnative_terminate_fn)library_terminate; // TODO(karroffel): remove this? Should be part of NativeScript, not // GDNative IMO godot_gdnative_terminate_options options; options.in_editor = SceneTree::get_singleton()->is_editor_hint(); library_terminate_pointer(&options); // GDNativeScriptLanguage::get_singleton()->initialized_libraries.erase(p_native_lib->path); OS::get_singleton()->close_dynamic_library(native_handle); native_handle = NULL; return false; } void GDNativeCallRegistry::register_native_call_type(StringName p_call_type, native_call_cb p_callback) { native_calls.insert(p_call_type, p_callback); } void GDNativeCallRegistry::register_native_raw_call_type(StringName p_raw_call_type, native_raw_call_cb p_callback) { native_raw_calls.insert(p_raw_call_type, p_callback); } Vector<StringName> GDNativeCallRegistry::get_native_call_types() { Vector<StringName> call_types; call_types.resize(native_calls.size()); size_t idx = 0; for (Map<StringName, native_call_cb>::Element *E = native_calls.front(); E; E = E->next(), idx++) { call_types[idx] = E->key(); } return call_types; } Vector<StringName> GDNativeCallRegistry::get_native_raw_call_types() { Vector<StringName> call_types; call_types.resize(native_raw_calls.size()); size_t idx = 0; for (Map<StringName, native_raw_call_cb>::Element *E = native_raw_calls.front(); E; E = E->next(), idx++) { call_types[idx] = E->key(); } return call_types; } Variant GDNative::call_native(StringName p_native_call_type, StringName p_procedure_name, Array p_arguments) { Map<StringName, native_call_cb>::Element *E = GDNativeCallRegistry::singleton->native_calls.find(p_native_call_type); if (!E) { ERR_PRINT((String("No handler for native call type \"" + p_native_call_type) + "\" found").utf8().get_data()); return Variant(); } String procedure_name = p_procedure_name; godot_variant result = E->get()(native_handle, (godot_string *)&procedure_name, (godot_array *)&p_arguments); return *(Variant *)&result; } void GDNative::call_native_raw(StringName p_raw_call_type, StringName p_procedure_name, void *data, int num_args, void **args, void *r_return) { Map<StringName, native_raw_call_cb>::Element *E = GDNativeCallRegistry::singleton->native_raw_calls.find(p_raw_call_type); if (!E) { ERR_PRINT((String("No handler for native raw call type \"" + p_raw_call_type) + "\" found").utf8().get_data()); return; } String procedure_name = p_procedure_name; E->get()(native_handle, (godot_string *)&procedure_name, data, num_args, args, r_return); } <|endoftext|>
<commit_before>#/** \ingroup kernel * \{ * * \file kernel/memory_map.hpp * \brief This file defines the memory map used by the * kernel as well as some auxilliary types. */ #ifndef H_kernel_memory #define H_kernel_memory #include <common/types.hpp> #include "dynarray.hpp" #include "debug.hpp" #include "constants.hpp" #include <memory_resource> #include <algorithm> namespace UtopiaOS { namespace kernel { /** \enum memory_type * \brief Analogous to the UEFI memory type * but contains only types the kernel * actually knows about. */ enum class memory_type : common::uint32 { general_purpose, unusable }; /** \struct memory_request * \brief Encapsulates a memory requirement */ struct memory_request { common::uint64 size; common::un alignment; }; /** \brief Aligns a pointer to a given alignment. * \param[in] ptr The pointer to align * \param[in] alignment The alignment to meet * \returns An aligned pointer or 0 if the pointer * could not be aligned. * * The aligned pointer is guaranteed to point to * an address not smaller than the original pointer. * It is guaranteed that there is no other aligned * address in the range [\a ptr, \a return-value]. * If the pointer cannot be aligned, i.e it points * to an address so large that the next aligned * address would not fit into the data type, * 0 is returned. * * \warning If \a alignment is not a power of two, * the behaviour is undefined! */ static inline common::uintptr align( common::uintptr ptr, common::un alignment ) { static_assert( sizeof(common::uintptr) >= sizeof(common::un), "This implementation cannot guarantee to work." ); debug_assert( (alignment % 2) == 0, "alignment has to be a power of two" ); common::un mask = alignment - 1; // ...0000011111... common::un diff = (ptr & mask); if( diff == 0 ) return ptr; return (ptr + alignment - diff); } /** \struct memory_descriptor * \brief Analogous to a UEFI memory descriptor, * but usable by the kernel. It also has * a well-defined size. */ struct memory_descriptor { memory_type type; common::uint64 physical_start; common::uint64 virtual_start; common::uint64 number_of_pages; /** \brief Construct a kernel-usable memory * descriptor from a UEFI one. */ memory_descriptor( const UEFI::memory_descriptor_v1 &uefi_desc ); /** \brief Checks whether bool can_meet_request( const memory_request &request ) const { static_assert( sizeof(common::uintptr) >= sizeof(common::un), "This implementation cannot guarantee to work." ); if( type != memory_type::general_purpose ) return false; auto aligned_address = align( virtual_start, request.alignment ); common::uintptr request_end = aligned_address + request.size; if( (request_end - virtual_start) / pagesize <= number_of_pages ) return true; return false; } }; /** \class memory_map * \brief The memory map used by the kernel * \tparam Allocator The type of allocator to use * * It has some sanity guarantees that UEFI lacks, like: * - fixed size of descriptors that is known compile-time * - no overlaps * - The memory descriptors always describe regions that * are as large as possible, with lower ones always being * full in a case of ambiguity. */ template<class Allocator> class memory_map { public: using allocator_type = Allocator; private: using desc_array = dynarray<memory_descriptor, allocator_type>; desc_array descriptors; /** \brief Convert a uefi memory map to a * kernel-usable one. * \param[in] uefi_map The UEFI memory map * \param[in] The allocator to use * \returns An array of descriptors with the guarantee * that they do not overlap. */ static desc_array convert_from_uefi( const UEFI::memory_map &uefi_map, allocator_type &&alloc ) { desc_array stage1_descriptors( uefi_map.cbegin_v1(), uefi_map.cend_v1(), std::forward<allocator_type>( alloc ) ); /** \todo Now remedy all possible overlaps and * any unnecessary fragmentation */ } public: /** \brief Returns a memory_request that when fulfilled * will suffice to convert a UEFI memory map * to a kernel-usable one. * \param[in] uefi_map The UEFI memory map * \returns The memory_request */ static memory_request maximum_conversion_requirement( const UEFI::memory_map &uefi_map ) { return memory_request{ uefi_map.number_of_descriptors * sizeof(memory_descriptor), alignof(memory_descriptor) }; } /** \brief Returns a memory_request that when fulfilled * will suffice to copy the memory map. * \returns The memory_request */ memory_request copy_requirement( void ) const { return memory_request{ descriptors.size() * sizeof(memory_descriptor), alignof(memory_descriptor) }; } /** \brief Constructs a kernel-usable memory map * from a UEFI memory map. * \param[in] uefi_map The UEFI memory map * \param[in] alloc The allocator used to copy the * memory map. It has to be able to * allocate at least what is returned * by \a maximum_conversion_requirement. */ memory_map( const UEFI::memory_map &uefi_map, allocator_type &&alloc ) : descriptors( convert_from_uefi( uefi_map, std::forward<allocator_type>( alloc ) ) ) {} /** \brief Returns a const iterator to the begin of * the memory descriptor range. * \returns A const iterator to the begin of * the memory descriptor range */ typename desc_array::const_iterator cbegin( void ) const { return descriptors.cbegin(); } /** \brief Returns a const iterator to the end of * the memory descriptor range. * \returns A const iterator to the end of * the memory descriptor range */ typename desc_array::const_iterator cend( void ) const { return descriptors.cend(); } }; } } #endif /** \} */ <commit_msg>Fixed incomplete comment (doxygen documentation).<commit_after>#/** \ingroup kernel * \{ * * \file kernel/memory_map.hpp * \brief This file defines the memory map used by the * kernel as well as some auxilliary types. */ #ifndef H_kernel_memory #define H_kernel_memory #include <common/types.hpp> #include "dynarray.hpp" #include "debug.hpp" #include "constants.hpp" #include <memory_resource> #include <algorithm> namespace UtopiaOS { namespace kernel { /** \enum memory_type * \brief Analogous to the UEFI memory type * but contains only types the kernel * actually knows about. */ enum class memory_type : common::uint32 { general_purpose, unusable }; /** \struct memory_request * \brief Encapsulates a memory requirement */ struct memory_request { common::uint64 size; common::un alignment; }; /** \brief Aligns a pointer to a given alignment. * \param[in] ptr The pointer to align * \param[in] alignment The alignment to meet * \returns An aligned pointer or 0 if the pointer * could not be aligned. * * The aligned pointer is guaranteed to point to * an address not smaller than the original pointer. * It is guaranteed that there is no other aligned * address in the range [\a ptr, \a return-value]. * If the pointer cannot be aligned, i.e it points * to an address so large that the next aligned * address would not fit into the data type, * 0 is returned. * * \warning If \a alignment is not a power of two, * the behaviour is undefined! */ static inline common::uintptr align( common::uintptr ptr, common::un alignment ) { static_assert( sizeof(common::uintptr) >= sizeof(common::un), "This implementation cannot guarantee to work." ); debug_assert( (alignment % 2) == 0, "alignment has to be a power of two" ); common::un mask = alignment - 1; // ...0000011111... common::un diff = (ptr & mask); if( diff == 0 ) return ptr; return (ptr + alignment - diff); } /** \struct memory_descriptor * \brief Analogous to a UEFI memory descriptor, * but usable by the kernel. It also has * a well-defined size. */ struct memory_descriptor { memory_type type; common::uint64 physical_start; common::uint64 virtual_start; common::uint64 number_of_pages; /** \brief Construct a kernel-usable memory * descriptor from a UEFI one. */ memory_descriptor( const UEFI::memory_descriptor_v1 &uefi_desc ); /** \brief Checks whether the memory described by * the memory descriptor can be used to * fulfil a memory request. * \returns \a true if the request can be fulfilled * and \a false otherwise. */ bool can_meet_request( const memory_request &request ) const { static_assert( sizeof(common::uintptr) >= sizeof(common::un), "This implementation cannot guarantee to work." ); if( type != memory_type::general_purpose ) return false; auto aligned_address = align( virtual_start, request.alignment ); common::uintptr request_end = aligned_address + request.size; if( (request_end - virtual_start) / pagesize <= number_of_pages ) return true; return false; } }; /** \class memory_map * \brief The memory map used by the kernel * \tparam Allocator The type of allocator to use * * It has some sanity guarantees that UEFI lacks, like: * - fixed size of descriptors that is known compile-time * - no overlaps * - The memory descriptors always describe regions that * are as large as possible, with lower ones always being * full in a case of ambiguity. */ template<class Allocator> class memory_map { public: using allocator_type = Allocator; private: using desc_array = dynarray<memory_descriptor, allocator_type>; desc_array descriptors; /** \brief Convert a uefi memory map to a * kernel-usable one. * \param[in] uefi_map The UEFI memory map * \param[in] The allocator to use * \returns An array of descriptors with the guarantee * that they do not overlap. */ static desc_array convert_from_uefi( const UEFI::memory_map &uefi_map, allocator_type &&alloc ) { desc_array stage1_descriptors( uefi_map.cbegin_v1(), uefi_map.cend_v1(), std::forward<allocator_type>( alloc ) ); /** \todo Now remedy all possible overlaps and * any unnecessary fragmentation */ } public: /** \brief Returns a memory_request that when fulfilled * will suffice to convert a UEFI memory map * to a kernel-usable one. * \param[in] uefi_map The UEFI memory map * \returns The memory_request */ static memory_request maximum_conversion_requirement( const UEFI::memory_map &uefi_map ) { return memory_request{ uefi_map.number_of_descriptors * sizeof(memory_descriptor), alignof(memory_descriptor) }; } /** \brief Returns a memory_request that when fulfilled * will suffice to copy the memory map. * \returns The memory_request */ memory_request copy_requirement( void ) const { return memory_request{ descriptors.size() * sizeof(memory_descriptor), alignof(memory_descriptor) }; } /** \brief Constructs a kernel-usable memory map * from a UEFI memory map. * \param[in] uefi_map The UEFI memory map * \param[in] alloc The allocator used to copy the * memory map. It has to be able to * allocate at least what is returned * by \a maximum_conversion_requirement. */ memory_map( const UEFI::memory_map &uefi_map, allocator_type &&alloc ) : descriptors( convert_from_uefi( uefi_map, std::forward<allocator_type>( alloc ) ) ) {} /** \brief Returns a const iterator to the begin of * the memory descriptor range. * \returns A const iterator to the begin of * the memory descriptor range */ typename desc_array::const_iterator cbegin( void ) const { return descriptors.cbegin(); } /** \brief Returns a const iterator to the end of * the memory descriptor range. * \returns A const iterator to the end of * the memory descriptor range */ typename desc_array::const_iterator cend( void ) const { return descriptors.cend(); } }; } } #endif /** \} */ <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo 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. *****************************************************************************/ #include <cstdio> #include <iostream> #include <fstream> #include "gflags/gflags.h" #include "modules/common/configs/config_gflags.h" #include "modules/common/log.h" #include "modules/map/hdmap/hdmap_common.h" #include "modules/map/hdmap/hdmap_impl.h" #include "modules/map/proto/map_geometry.pb.h" DEFINE_bool(xy_to_sl, false, "calculate xy to sl"); DEFINE_bool(sl_to_xy, false, "calculate sl to xy"); DEFINE_bool(xy_to_lane, false, "calculate xy to lane"); DEFINE_bool(lane_to_lane, false, "calculate lane to lane"); DEFINE_bool(lane_width, false, "calculate lane width"); DEFINE_string(print_map, "", "print the map"); DEFINE_string(print_map_bin, "", "print the map binary"); DEFINE_string(overlap, "", "get overlap information"); DEFINE_string(lane_info, "", "print lane info"); DEFINE_string(signal_info, "", "print signal info"); DEFINE_double(x, 0.0, "x"); DEFINE_double(y, 0.0, "y"); DEFINE_string(lane, "", "lane_id"); DEFINE_string(from_lane, "", "from_lane"); DEFINE_string(to_lane, "", "to_lane"); DEFINE_double(s, 0.0, "s"); DEFINE_double(l, 0.0, "l"); namespace apollo { namespace tools { class MapUtil { public: explicit MapUtil(const std::string &map_filename) : _map_client(nullptr) { _map_client.reset(new apollo::hdmap::HDMapImpl()); _map_client->load_map_from_file(map_filename); } static ::apollo::hdmap::Id create_id(const std::string &id) { ::apollo::hdmap::Id hdmap_id; hdmap_id.set_id(id); return hdmap_id; } const ::apollo::hdmap::OverlapInfo *get_overlap( const std::string &overlap_id) { ::apollo::hdmap::Id id; id.set_id(overlap_id); auto ret = _map_client->get_overlap_by_id(id); if (ret == nullptr) { fprintf(stderr, "failed to find overlap[%s]\n", overlap_id.c_str()); } return ret.get(); } const ::apollo::hdmap::SignalInfo *get_signal(const std::string &signal_id) { ::apollo::hdmap::Id id; id.set_id(signal_id); auto ret = _map_client->get_signal_by_id(id); if (ret == nullptr) { fprintf(stderr, "failed to find overlap[%s]\n", signal_id.c_str()); } return ret.get(); } const ::apollo::hdmap::LaneInfo *get_lane(const std::string &lane_id) { ::apollo::hdmap::Id id; id.set_id(lane_id); auto ret = _map_client->get_lane_by_id(id); if (ret == nullptr) { fprintf(stderr, "failed to find lane[%s]\n", lane_id.c_str()); } return ret.get(); } int point_to_sl(const ::apollo::common::PointENU &point, std::string *lane_id, double *s, double *l) { QUIT_IF(lane_id == nullptr, -1, ERROR, "arg lane id is null"); QUIT_IF(s == nullptr, -2, ERROR, "arg s is null"); QUIT_IF(l == nullptr, -3, ERROR, "arg l is null"); ::apollo::hdmap::LaneInfoConstPtr lane = nullptr; int ret = _map_client->get_nearest_lane(point, &lane, s, l); QUIT_IF(ret != 0, -4, ERROR, "get_nearest_lane failed with ret[%d]", ret); QUIT_IF(lane == nullptr, -5, ERROR, "lane is null"); *lane_id = lane->id().id(); return 0; } int sl_to_point(const std::string &lane_id, const double s, const double l, ::apollo::common::PointENU *point, double *heading) { QUIT_IF(point == nullptr, -1, ERROR, "arg point is null"); QUIT_IF(heading == nullptr, -2, ERROR, "arg heading is null"); ::apollo::hdmap::Id id; id.set_id(lane_id); const ::apollo::hdmap::LaneInfo* lane_info_ptr = _map_client->get_lane_by_id(id).get(); QUIT_IF(lane_info_ptr == nullptr, -3, ERROR, "get_smooth_point_from_lane[%s] failed", lane_id.c_str()); *point = lane_info_ptr->get_smooth_point(s); return 0; } int lane_projection(const ::apollo::common::math::Vec2d &vec2d, const std::string &lane_id, double *s, double *l) { QUIT_IF(s == nullptr, -1, ERROR, "arg s is nullptr"); const ::apollo::hdmap::LaneInfo *lane = _map_client->get_lane_by_id(create_id(lane_id)).get(); QUIT_IF(lane == nullptr, -2, ERROR, "get_lane_by_id[%s] failed", lane_id.c_str()); bool ret = lane->get_projection(vec2d, s, l); QUIT_IF(!ret, -3, ERROR, "lane[%s] get projection for point[%f, %f] failed", lane_id.c_str(), vec2d.x(), vec2d.y()); return 0; } const ::apollo::hdmap::HDMapImpl *get_map_client() const { return _map_client.get(); } private: std::unique_ptr<apollo::hdmap::HDMapImpl> _map_client; }; } // namespace tools } // namespace apollo std::ostream &operator<<( std::ostream &os, const ::google::protobuf::RepeatedPtrField<::apollo::hdmap::Id> &ids) { for (int i = 0; i < ids.size(); ++i) { os << ids.Get(i).id(); if (i != ids.size() - 1) { os << ", "; } } return os; } int main(int argc, char *argv[]) { google::ParseCommandLineFlags(&argc, &argv, true); std::string map_file = FLAGS_map_file_path; ::apollo::tools::MapUtil map_util(FLAGS_map_file_path); if (FLAGS_xy_to_sl) { double x = FLAGS_x; double y = FLAGS_y; ::apollo::common::PointENU point; point.set_x(x); point.set_y(y); point.set_z(0); std::string lane_id; double s = 0.0; double l = 0.0; map_util.point_to_sl(point, &lane_id, &s, &l); double heading = 0.0; map_util.sl_to_point(lane_id, s, l, &point, &heading); printf("lane_id[%s], s[%f], l[%f], heading[%f]\n", lane_id.c_str(), s, l, heading); } if (FLAGS_sl_to_xy) { ::apollo::common::PointENU point; double heading = 0.0; map_util.sl_to_point(FLAGS_lane, FLAGS_s, FLAGS_l, &point, &heading); printf("x[%f] y[%f], heading[%f]\n", point.x(), point.y(), heading); } if (FLAGS_xy_to_lane) { ::apollo::common::math::Vec2d vec2d(FLAGS_x, FLAGS_y); double s = 0.0; double l = 0.0; int ret = map_util.lane_projection(vec2d, FLAGS_lane, &s, &l); if (ret != 0) { printf("lane_projection for x[%f], y[%f], lane_id[%s] failed\n", FLAGS_x, FLAGS_y, FLAGS_lane.c_str()); return -1; } printf("lane[%s] s[%f], l[%f]\n", FLAGS_lane.c_str(), s, l); } if (FLAGS_lane_to_lane) { ::apollo::common::PointENU point; double heading = 0.0; map_util.sl_to_point(FLAGS_from_lane, FLAGS_s, 0.0, &point, &heading); double target_s = 0.0; double target_l = 0.0; ::apollo::common::math::Vec2d vec2d(point.x(), point.y()); int ret = map_util.lane_projection(vec2d, FLAGS_to_lane, &target_s, &target_l); if (ret != 0) { printf("lane_projection for lane[%s], s[%f] to lane_id[%s] failed\n", FLAGS_from_lane.c_str(), FLAGS_s, FLAGS_to_lane.c_str()); return -1; } printf("lane[%s] s[%f], l[%f]\n", FLAGS_to_lane.c_str(), target_s, target_l); } if (FLAGS_lane_width) { auto lane_ptr = map_util.get_lane(FLAGS_lane); double left_width = 0.0; double right_width = 0.0; lane_ptr->get_width(FLAGS_s, &left_width, &right_width); printf("lane[%s] s[%f]: left_width[%f], right_width[%f], total_width[%f]\n", FLAGS_lane.c_str(), FLAGS_s, left_width, right_width, left_width + right_width); } if (!FLAGS_lane_info.empty()) { const auto *lane_ptr = map_util.get_lane(FLAGS_lane_info); const auto &lane = lane_ptr->lane(); ::apollo::common::PointENU start_point; double start_heading = 0.0; map_util.sl_to_point(FLAGS_lane_info, 0, 0, &start_point, &start_heading); ::apollo::common::PointENU end_point; double end_heading = 0.0; map_util.sl_to_point(FLAGS_lane_info, lane_ptr->total_length(), 0, &end_point, &end_heading); std::cout << "lane[" << FLAGS_lane_info << "] length[" << lane_ptr->total_length() << "] type[" << Lane_LaneType_Name(lane.type()) << "] turn[" << Lane_LaneTurn_Name(lane.turn()) // << "] left_boundary[" // << LaneBoundary_Type_Name(lane.left_boundary().type()) // << "] right_boundary[" // << LaneBoundary_Type_Name(lane.right_boundary().type()) << "] speed_limit[" << lane.speed_limit() << "] predecessor[" << lane.predecessor_id() << "] successor[" << lane.successor_id() << "] left_forward[" << lane.left_neighbor_forward_lane_id() << "] right_forward[" << lane.right_neighbor_forward_lane_id() << "] left_reverse[" << lane.left_neighbor_reverse_lane_id() << "] right_reverse[" << lane.right_neighbor_reverse_lane_id() << "] overlap[" << lane.overlap_id() // << "] crosswalk[" << lane.crosswalk_id() // << "] yield_sign[" << lane.yield_sign_id() << "] stop_sign num:[" << lane_ptr->stop_signs().size() << "]" << " start point(x,y,heading):" << start_point.x() << "," << start_point.y() << "," << start_heading << " end point(x,y,heading):" << end_point.x() << "," << end_point.y() << "," << end_heading << std::endl; } if (!FLAGS_overlap.empty()) { const auto *overlap_ptr = map_util.get_overlap(FLAGS_overlap); if (overlap_ptr != nullptr) { std::cout << "overlap[" << overlap_ptr->id().id() << "] info[" << overlap_ptr->overlap().DebugString() << "]" << std::endl; } } if (!FLAGS_signal_info.empty()) { const auto *signal_ptr = map_util.get_signal(FLAGS_signal_info); if (signal_ptr) { std::cout << "signal[" << FLAGS_signal_info << "] info[" << signal_ptr->signal().DebugString() << "]" << std::endl; } } if (!FLAGS_print_map.empty()) { //const auto *map_client = map_util.get_map_client(); std::ofstream ofs(FLAGS_print_map); // TODO(yifei) map api is not available //ofs << map_client->_map.DebugString(); ofs.close(); } if (!FLAGS_print_map_bin.empty()) { // const auto *map_client = map_util.get_map_client(); std::ofstream ofs(FLAGS_print_map_bin); std::string map_str; // TODO(yifei) map api is not available // map_client->_map.SerializeToString(&map_str); // ofs << map_str; ofs.close(); } if (!FLAGS_sl_to_xy && !FLAGS_xy_to_sl && !FLAGS_xy_to_lane && !FLAGS_lane_to_lane && !FLAGS_lane_width && FLAGS_print_map.empty() && FLAGS_print_map_bin.empty() && FLAGS_lane_info.empty() && FLAGS_signal_info.empty() && FLAGS_overlap.empty()) { std::cout << "usage: --map_file" << std::endl; std::cout << "usage: --print_map" << std::endl; std::cout << "usage: --print_map_bin" << std::endl; std::cout << "usage: --xy_to_sl --x --y" << std::endl; std::cout << "usage: --sl_to_xy --lane --s --l" << std::endl; std::cout << "usage: --xy_to_lane --x --y --lane" << std::endl; std::cout << "usage: --lane_to_lane --from_lane --s --to_lane" << std::endl; std::cout << "usage: --lane_width --lane --s" << std::endl; std::cout << "usage: --lane_info" << std::endl; std::cout << "usage: --signal_info" << std::endl; std::cout << "usage: --overlap" << std::endl; } return 0; } <commit_msg>map: add dump text map in map_xysl tool.<commit_after>/****************************************************************************** * Copyright 2017 The Apollo 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. *****************************************************************************/ #include <cstdio> #include <iostream> #include <fstream> #include "gflags/gflags.h" #include "modules/common/configs/config_gflags.h" #include "modules/common/log.h" #include "modules/common/util/file.h" #include "modules/map/hdmap/hdmap_common.h" #include "modules/map/hdmap/hdmap_impl.h" #include "modules/map/proto/map_geometry.pb.h" DEFINE_bool(xy_to_sl, false, "calculate xy to sl"); DEFINE_bool(sl_to_xy, false, "calculate sl to xy"); DEFINE_bool(xy_to_lane, false, "calculate xy to lane"); DEFINE_bool(lane_to_lane, false, "calculate lane to lane"); DEFINE_bool(lane_width, false, "calculate lane width"); DEFINE_string(dump_txt_map, "", "text file name for dumping map"); DEFINE_string(dump_bin_map, "", "binary file name for dumping map"); DEFINE_string(overlap, "", "get overlap information"); DEFINE_string(lane_info, "", "print lane info"); DEFINE_string(signal_info, "", "print signal info"); DEFINE_double(x, 0.0, "x"); DEFINE_double(y, 0.0, "y"); DEFINE_string(lane, "", "lane_id"); DEFINE_string(from_lane, "", "from_lane"); DEFINE_string(to_lane, "", "to_lane"); DEFINE_double(s, 0.0, "s"); DEFINE_double(l, 0.0, "l"); namespace apollo { namespace tools { class MapUtil { public: explicit MapUtil(const std::string &map_filename) : _map_client(nullptr) { _map_client.reset(new apollo::hdmap::HDMapImpl()); _map_client->load_map_from_file(map_filename); } static ::apollo::hdmap::Id create_id(const std::string &id) { ::apollo::hdmap::Id hdmap_id; hdmap_id.set_id(id); return hdmap_id; } const ::apollo::hdmap::OverlapInfo *get_overlap( const std::string &overlap_id) { ::apollo::hdmap::Id id; id.set_id(overlap_id); auto ret = _map_client->get_overlap_by_id(id); if (ret == nullptr) { fprintf(stderr, "failed to find overlap[%s]\n", overlap_id.c_str()); } return ret.get(); } const ::apollo::hdmap::SignalInfo *get_signal(const std::string &signal_id) { ::apollo::hdmap::Id id; id.set_id(signal_id); auto ret = _map_client->get_signal_by_id(id); if (ret == nullptr) { fprintf(stderr, "failed to find overlap[%s]\n", signal_id.c_str()); } return ret.get(); } const ::apollo::hdmap::LaneInfo *get_lane(const std::string &lane_id) { ::apollo::hdmap::Id id; id.set_id(lane_id); auto ret = _map_client->get_lane_by_id(id); if (ret == nullptr) { fprintf(stderr, "failed to find lane[%s]\n", lane_id.c_str()); } return ret.get(); } int point_to_sl(const ::apollo::common::PointENU &point, std::string *lane_id, double *s, double *l) { QUIT_IF(lane_id == nullptr, -1, ERROR, "arg lane id is null"); QUIT_IF(s == nullptr, -2, ERROR, "arg s is null"); QUIT_IF(l == nullptr, -3, ERROR, "arg l is null"); ::apollo::hdmap::LaneInfoConstPtr lane = nullptr; int ret = _map_client->get_nearest_lane(point, &lane, s, l); QUIT_IF(ret != 0, -4, ERROR, "get_nearest_lane failed with ret[%d]", ret); QUIT_IF(lane == nullptr, -5, ERROR, "lane is null"); *lane_id = lane->id().id(); return 0; } int sl_to_point(const std::string &lane_id, const double s, const double l, ::apollo::common::PointENU *point, double *heading) { QUIT_IF(point == nullptr, -1, ERROR, "arg point is null"); QUIT_IF(heading == nullptr, -2, ERROR, "arg heading is null"); ::apollo::hdmap::Id id; id.set_id(lane_id); const ::apollo::hdmap::LaneInfo* lane_info_ptr = _map_client->get_lane_by_id(id).get(); QUIT_IF(lane_info_ptr == nullptr, -3, ERROR, "get_smooth_point_from_lane[%s] failed", lane_id.c_str()); *point = lane_info_ptr->get_smooth_point(s); return 0; } int lane_projection(const ::apollo::common::math::Vec2d &vec2d, const std::string &lane_id, double *s, double *l) { QUIT_IF(s == nullptr, -1, ERROR, "arg s is nullptr"); const ::apollo::hdmap::LaneInfo *lane = _map_client->get_lane_by_id(create_id(lane_id)).get(); QUIT_IF(lane == nullptr, -2, ERROR, "get_lane_by_id[%s] failed", lane_id.c_str()); bool ret = lane->get_projection(vec2d, s, l); QUIT_IF(!ret, -3, ERROR, "lane[%s] get projection for point[%f, %f] failed", lane_id.c_str(), vec2d.x(), vec2d.y()); return 0; } const ::apollo::hdmap::HDMapImpl *get_map_client() const { return _map_client.get(); } private: std::unique_ptr<apollo::hdmap::HDMapImpl> _map_client; }; } // namespace tools } // namespace apollo std::ostream &operator<<( std::ostream &os, const ::google::protobuf::RepeatedPtrField<::apollo::hdmap::Id> &ids) { for (int i = 0; i < ids.size(); ++i) { os << ids.Get(i).id(); if (i != ids.size() - 1) { os << ", "; } } return os; } int main(int argc, char *argv[]) { google::ParseCommandLineFlags(&argc, &argv, true); std::string map_file = FLAGS_map_file_path; ::apollo::tools::MapUtil map_util(FLAGS_map_file_path); if (FLAGS_xy_to_sl) { double x = FLAGS_x; double y = FLAGS_y; ::apollo::common::PointENU point; point.set_x(x); point.set_y(y); point.set_z(0); std::string lane_id; double s = 0.0; double l = 0.0; map_util.point_to_sl(point, &lane_id, &s, &l); double heading = 0.0; map_util.sl_to_point(lane_id, s, l, &point, &heading); printf("lane_id[%s], s[%f], l[%f], heading[%f]\n", lane_id.c_str(), s, l, heading); } if (FLAGS_sl_to_xy) { ::apollo::common::PointENU point; double heading = 0.0; map_util.sl_to_point(FLAGS_lane, FLAGS_s, FLAGS_l, &point, &heading); printf("x[%f] y[%f], heading[%f]\n", point.x(), point.y(), heading); } if (FLAGS_xy_to_lane) { ::apollo::common::math::Vec2d vec2d(FLAGS_x, FLAGS_y); double s = 0.0; double l = 0.0; int ret = map_util.lane_projection(vec2d, FLAGS_lane, &s, &l); if (ret != 0) { printf("lane_projection for x[%f], y[%f], lane_id[%s] failed\n", FLAGS_x, FLAGS_y, FLAGS_lane.c_str()); return -1; } printf("lane[%s] s[%f], l[%f]\n", FLAGS_lane.c_str(), s, l); } if (FLAGS_lane_to_lane) { ::apollo::common::PointENU point; double heading = 0.0; map_util.sl_to_point(FLAGS_from_lane, FLAGS_s, 0.0, &point, &heading); double target_s = 0.0; double target_l = 0.0; ::apollo::common::math::Vec2d vec2d(point.x(), point.y()); int ret = map_util.lane_projection(vec2d, FLAGS_to_lane, &target_s, &target_l); if (ret != 0) { printf("lane_projection for lane[%s], s[%f] to lane_id[%s] failed\n", FLAGS_from_lane.c_str(), FLAGS_s, FLAGS_to_lane.c_str()); return -1; } printf("lane[%s] s[%f], l[%f]\n", FLAGS_to_lane.c_str(), target_s, target_l); } if (FLAGS_lane_width) { auto lane_ptr = map_util.get_lane(FLAGS_lane); double left_width = 0.0; double right_width = 0.0; lane_ptr->get_width(FLAGS_s, &left_width, &right_width); printf("lane[%s] s[%f]: left_width[%f], right_width[%f], total_width[%f]\n", FLAGS_lane.c_str(), FLAGS_s, left_width, right_width, left_width + right_width); } if (!FLAGS_lane_info.empty()) { const auto *lane_ptr = map_util.get_lane(FLAGS_lane_info); const auto &lane = lane_ptr->lane(); ::apollo::common::PointENU start_point; double start_heading = 0.0; map_util.sl_to_point(FLAGS_lane_info, 0, 0, &start_point, &start_heading); ::apollo::common::PointENU end_point; double end_heading = 0.0; map_util.sl_to_point(FLAGS_lane_info, lane_ptr->total_length(), 0, &end_point, &end_heading); std::cout << "lane[" << FLAGS_lane_info << "] length[" << lane_ptr->total_length() << "] type[" << Lane_LaneType_Name(lane.type()) << "] turn[" << Lane_LaneTurn_Name(lane.turn()) // << "] left_boundary[" // << LaneBoundary_Type_Name(lane.left_boundary().type()) // << "] right_boundary[" // << LaneBoundary_Type_Name(lane.right_boundary().type()) << "] speed_limit[" << lane.speed_limit() << "] predecessor[" << lane.predecessor_id() << "] successor[" << lane.successor_id() << "] left_forward[" << lane.left_neighbor_forward_lane_id() << "] right_forward[" << lane.right_neighbor_forward_lane_id() << "] left_reverse[" << lane.left_neighbor_reverse_lane_id() << "] right_reverse[" << lane.right_neighbor_reverse_lane_id() << "] overlap[" << lane.overlap_id() // << "] crosswalk[" << lane.crosswalk_id() // << "] yield_sign[" << lane.yield_sign_id() << "] stop_sign num:[" << lane_ptr->stop_signs().size() << "]" << " start point(x,y,heading):" << start_point.x() << "," << start_point.y() << "," << start_heading << " end point(x,y,heading):" << end_point.x() << "," << end_point.y() << "," << end_heading << std::endl; } if (!FLAGS_overlap.empty()) { const auto *overlap_ptr = map_util.get_overlap(FLAGS_overlap); if (overlap_ptr != nullptr) { std::cout << "overlap[" << overlap_ptr->id().id() << "] info[" << overlap_ptr->overlap().DebugString() << "]" << std::endl; } } if (!FLAGS_signal_info.empty()) { const auto *signal_ptr = map_util.get_signal(FLAGS_signal_info); if (signal_ptr) { std::cout << "signal[" << FLAGS_signal_info << "] info[" << signal_ptr->signal().DebugString() << "]" << std::endl; } } if (!FLAGS_dump_txt_map.empty()) { apollo::hdmap::Map map; apollo::common::util::GetProtoFromFile(FLAGS_map_file_path, &map); std::ofstream ofs(FLAGS_dump_txt_map); ofs << map.DebugString(); ofs.close(); } if (!FLAGS_dump_bin_map.empty()) { apollo::hdmap::Map map; apollo::common::util::GetProtoFromFile(FLAGS_map_file_path, &map); std::ofstream ofs(FLAGS_dump_bin_map); std::string map_str; map.SerializeToString(&map_str); ofs << map_str; ofs.close(); } if (!FLAGS_sl_to_xy && !FLAGS_xy_to_sl && !FLAGS_xy_to_lane && !FLAGS_lane_to_lane && !FLAGS_lane_width && FLAGS_dump_txt_map.empty() && FLAGS_dump_bin_map.empty() && FLAGS_lane_info.empty() && FLAGS_signal_info.empty() && FLAGS_overlap.empty()) { std::cout << "usage: --map_file" << std::endl; std::cout << "usage: --dump_txt_map" << std::endl; std::cout << "usage: --dump_bin_map" << std::endl; std::cout << "usage: --xy_to_sl --x --y" << std::endl; std::cout << "usage: --sl_to_xy --lane --s --l" << std::endl; std::cout << "usage: --xy_to_lane --x --y --lane" << std::endl; std::cout << "usage: --lane_to_lane --from_lane --s --to_lane" << std::endl; std::cout << "usage: --lane_width --lane --s" << std::endl; std::cout << "usage: --lane_info" << std::endl; std::cout << "usage: --signal_info" << std::endl; std::cout << "usage: --overlap" << std::endl; } return 0; } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreOSXWindow.h" #include "OgreOSXCGLContext.h" #include "OgreRoot.h" #include "OgreGLRenderSystem.h" #include "OgreImageCodec.h" #include "OgreException.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreGLPixelFormat.h" #include <OpenGL/gl.h> #define GL_EXT_texture_env_combine 1 #include <OpenGL/glext.h> #include <OpenGL/glu.h> namespace Ogre { //-------------------------------------------------------------------------------------------------// OSXWindow::OSXWindow() : mCGLContext(NULL) { } //-------------------------------------------------------------------------------------------------// OSXWindow::~OSXWindow() { } //-------------------------------------------------------------------------------------------------// void OSXWindow::copyContentsToMemory(const PixelBox &dst, FrameBuffer buffer) { if ((dst.left < 0) || (dst.right > mWidth) || (dst.top < 0) || (dst.bottom > mHeight) || (dst.front != 0) || (dst.back != 1)) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Invalid box.", "OSXWindow::copyContentsToMemory" ); } if (buffer == FB_AUTO) { buffer = mIsFullScreen? FB_FRONT : FB_BACK; } GLenum format = Ogre::GLPixelUtil::getGLOriginFormat(dst.format); GLenum type = Ogre::GLPixelUtil::getGLOriginDataType(dst.format); if ((format == GL_NONE) || (type == 0)) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Unsupported format.", "OSXWindow::copyContentsToMemory" ); } if((dst.getWidth()*Ogre::PixelUtil::getNumElemBytes(dst.format)) & 3) { // Standard alignment of 4 is not right glPixelStorei(GL_PACK_ALIGNMENT, 1); } glReadBuffer((buffer == FB_FRONT)? GL_FRONT : GL_BACK); glReadPixels((GLint)dst.left, (GLint)dst.top, (GLsizei)dst.getWidth(), (GLsizei)dst.getHeight(), format, type, dst.data); glPixelStorei(GL_PACK_ALIGNMENT, 4); //vertical flip { size_t rowSpan = dst.getWidth() * PixelUtil::getNumElemBytes(dst.format); size_t height = dst.getHeight(); uchar *tmpData = new uchar[rowSpan * height]; uchar *srcRow = (uchar *)dst.data, *tmpRow = tmpData + (height - 1) * rowSpan; while (tmpRow >= tmpData) { memcpy(tmpRow, srcRow, rowSpan); srcRow += rowSpan; tmpRow -= rowSpan; } memcpy(dst.data, tmpData, rowSpan * height); delete [] tmpData; } } #if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 uint32 OSXWindow::bitDepthFromDisplayMode(CGDisplayModeRef mode) { uint32 depth = 0; CFStringRef pixEnc = CGDisplayModeCopyPixelEncoding(mode); if(CFStringCompare(pixEnc, CFSTR(IO32BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) depth = 32; else if(CFStringCompare(pixEnc, CFSTR(IO16BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) depth = 16; else if(CFStringCompare(pixEnc, CFSTR(IO8BitIndexedPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) depth = 8; return depth; } #endif //-------------------------------------------------------------------------------------------------// void OSXWindow::createCGLFullscreen(unsigned int width, unsigned int height, unsigned int depth, unsigned int fsaa, CGLContextObj sharedContext) { // Find the best match to what was requested boolean_t exactMatch = 0; int reqWidth, reqHeight, reqDepth; #if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 // Get a copy of the current display mode CGDisplayModeRef displayMode = CGDisplayCopyDisplayMode(kCGDirectMainDisplay); // Loop through all display modes to determine the closest match. // CGDisplayBestModeForParameters is deprecated on 10.6 so we will emulate it's behavior // Try to find a mode with the requested depth and equal or greater dimensions first. // If no match is found, try to find a mode with greater depth and same or greater dimensions. // If still no match is found, just use the current mode. CFArrayRef allModes = CGDisplayCopyAllDisplayModes(kCGDirectMainDisplay, NULL); for(int i = 0; i < CFArrayGetCount(allModes); i++) { CGDisplayModeRef mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(allModes, i); String modeString = StringConverter::toString(CGDisplayModeGetWidth(mode)) + String(" x ") + StringConverter::toString(CGDisplayModeGetHeight(mode)) + String(" @ ") + StringConverter::toString(bitDepthFromDisplayMode(mode)) + "bpp."; LogManager::getSingleton().logMessage(modeString); if(bitDepthFromDisplayMode(mode) != depth) continue; if((CGDisplayModeGetWidth(mode) >= width) && (CGDisplayModeGetHeight(mode) >= height)) { displayMode = mode; exactMatch = 1; break; } } // No depth match was found if(!exactMatch) { for(int i = 0; i < CFArrayGetCount(allModes); i++) { CGDisplayModeRef mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(allModes, i); if(bitDepthFromDisplayMode(mode) >= depth) continue; if((CGDisplayModeGetWidth(mode) >= width) && (CGDisplayModeGetHeight(mode) >= height)) { displayMode = mode; exactMatch = 1; break; } } } reqWidth = CGDisplayModeGetWidth(displayMode); reqHeight = CGDisplayModeGetHeight(displayMode); reqDepth = bitDepthFromDisplayMode(displayMode); #else CFDictionaryRef displayMode = CGDisplayBestModeForParameters(kCGDirectMainDisplay, depth, width, height, &exactMatch); const void *value = NULL; value = CFDictionaryGetValue(displayMode, kCGDisplayWidth); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &reqWidth); value = CFDictionaryGetValue(displayMode, kCGDisplayHeight); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &reqHeight); value = CFDictionaryGetValue(displayMode, kCGDisplayBitsPerPixel); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &reqDepth); #endif if(!exactMatch) { // TODO: Report the size difference // That mode is not available, using the closest match String request = StringConverter::toString(width) + String(" x ") + StringConverter::toString(height) + String(" @ ") + StringConverter::toString(depth) + "bpp. "; String received = StringConverter::toString(reqWidth) + String(" x ") + StringConverter::toString(reqHeight) + String(" @ ") + StringConverter::toString(reqDepth) + "bpp. "; LogManager::getSingleton().logMessage(String("RenderSystem Warning: You requested a fullscreen mode of ") + request + String(" This mode is not available and you will receive the closest match. The best display mode for the parameters requested is: ") + received); } // Do the fancy display fading CGDisplayFadeReservationToken reservationToken; CGAcquireDisplayFadeReservation(kCGMaxDisplayReservationInterval, &reservationToken); CGDisplayFade(reservationToken, 0.5, kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, true); // Grab the main display and save it for later. // You could render to any display, but picking what display // to render to could be interesting. CGDisplayCapture(kCGDirectMainDisplay); // Switch to the correct resolution #if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 CGDisplaySetDisplayMode(kCGDirectMainDisplay, displayMode, NULL); #else CGDisplaySwitchToMode(kCGDirectMainDisplay, displayMode); #endif // Get a pixel format that best matches what we are looking for CGLPixelFormatAttribute attribs[] = { kCGLPFADoubleBuffer, kCGLPFAAlphaSize, (CGLPixelFormatAttribute)8, kCGLPFADepthSize, (CGLPixelFormatAttribute)reqDepth, kCGLPFAStencilSize, (CGLPixelFormatAttribute)8, kCGLPFASampleBuffers, (CGLPixelFormatAttribute)0, kCGLPFASamples, (CGLPixelFormatAttribute)0, kCGLPFAFullScreen, kCGLPFASingleRenderer, kCGLPFAAccelerated, kCGLPFADisplayMask, (CGLPixelFormatAttribute)CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay), (CGLPixelFormatAttribute)0 }; // Set up FSAA if it was requested if(fsaa > 1) { // turn on kCGLPFASampleBuffers attribs[8] = (CGLPixelFormatAttribute)1; // set the samples for kCGLPFASamples attribs[10] = (CGLPixelFormatAttribute)fsaa; } CGLError err; CGLPixelFormatObj pixelFormatObj; #if (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4) GLint numPixelFormats = 0; err = CGLChoosePixelFormat(attribs, &pixelFormatObj, &numPixelFormats); #else long numPixelFormats = 0; err = CGLChoosePixelFormat(attribs, &pixelFormatObj, &numPixelFormats); #endif if(err != 0) { CGReleaseAllDisplays(); OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, String("CGL Error: " + String(CGLErrorString(err))), "OSXWindow::createCGLFullscreen"); } // Create the CGLcontext from our pixel format, share it with the sharedContext passed in err = CGLCreateContext(pixelFormatObj, sharedContext, &mCGLContext); if(err != 0) { CGReleaseAllDisplays(); OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, String("CGL Error: " + String(CGLErrorString(err))), "OSXWindow::createCGLFullscreen"); } // Once we have the context we can destroy the pixel format // In order to share contexts you must keep a pointer to the context object around // Our context class will now manage the life of the pixelFormatObj //CGLDestroyPixelFormat(pixelFormatObj); // Set the context to full screen #if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 CGLSetFullScreenOnDisplay(mCGLContext, CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay)); #else CGLSetFullScreen(mCGLContext); #endif // Set the context as current CGLSetCurrentContext(mCGLContext); // This synchronizes CGL with the vertical retrace // Apple docs suggest that OpenGL blocks rendering calls when waiting for // a vertical retrace anyhow. #if (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4) GLint swapInterval = 1; CGLSetParameter(mCGLContext, kCGLCPSwapInterval, &swapInterval); #else long swapInterval = 1; CGLSetParameter(mCGLContext, kCGLCPSwapInterval, &swapInterval); #endif // Give a copy of our context to the rendersystem mContext = new OSXCGLContext(mCGLContext, pixelFormatObj); // Let everyone know we are fullscreen now mIsFullScreen = true; // Set some other variables. Just in case we got a different value from CGDisplayBestModeForParameters than we requested mWidth = reqWidth; mHeight = reqHeight; mColourDepth = reqDepth; CGDisplayFade(reservationToken, 2.0, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, false); CGReleaseDisplayFadeReservation(reservationToken); } //-------------------------------------------------------------------------------------------------// void OSXWindow::destroyCGLFullscreen(void) { CGReleaseAllDisplays(); } //-------------------------------------------------------------------------------------------------// void OSXWindow::swapCGLBuffers(void) { CGLFlushDrawable(mCGLContext); CGLContextObj curCtx = CGLGetCurrentContext(); if(curCtx != mCGLContext) { CGLSetCurrentContext(mCGLContext); #if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 CGLSetFullScreenOnDisplay(mCGLContext, CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay)); #else CGLSetFullScreen(mCGLContext); #endif } } } <commit_msg>OS X: When targeting 10.6 only - Fixed an issue with old framebuffer contents being displayed when using non-native resolution full screen contexts. Also fixed a crash when switching resolutions. Added some error checking to the full screen context creation.<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreOSXWindow.h" #include "OgreOSXCGLContext.h" #include "OgreRoot.h" #include "OgreGLRenderSystem.h" #include "OgreImageCodec.h" #include "OgreException.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreGLPixelFormat.h" #include <OpenGL/gl.h> #define GL_EXT_texture_env_combine 1 #include <OpenGL/glext.h> #include <OpenGL/glu.h> namespace Ogre { //-------------------------------------------------------------------------------------------------// OSXWindow::OSXWindow() : mCGLContext(NULL) { } //-------------------------------------------------------------------------------------------------// OSXWindow::~OSXWindow() { } //-------------------------------------------------------------------------------------------------// void OSXWindow::copyContentsToMemory(const PixelBox &dst, FrameBuffer buffer) { if ((dst.left < 0) || (dst.right > mWidth) || (dst.top < 0) || (dst.bottom > mHeight) || (dst.front != 0) || (dst.back != 1)) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Invalid box.", "OSXWindow::copyContentsToMemory" ); } if (buffer == FB_AUTO) { buffer = mIsFullScreen? FB_FRONT : FB_BACK; } GLenum format = Ogre::GLPixelUtil::getGLOriginFormat(dst.format); GLenum type = Ogre::GLPixelUtil::getGLOriginDataType(dst.format); if ((format == GL_NONE) || (type == 0)) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Unsupported format.", "OSXWindow::copyContentsToMemory" ); } if((dst.getWidth()*Ogre::PixelUtil::getNumElemBytes(dst.format)) & 3) { // Standard alignment of 4 is not right glPixelStorei(GL_PACK_ALIGNMENT, 1); } glReadBuffer((buffer == FB_FRONT)? GL_FRONT : GL_BACK); glReadPixels((GLint)dst.left, (GLint)dst.top, (GLsizei)dst.getWidth(), (GLsizei)dst.getHeight(), format, type, dst.data); glPixelStorei(GL_PACK_ALIGNMENT, 4); //vertical flip { size_t rowSpan = dst.getWidth() * PixelUtil::getNumElemBytes(dst.format); size_t height = dst.getHeight(); uchar *tmpData = new uchar[rowSpan * height]; uchar *srcRow = (uchar *)dst.data, *tmpRow = tmpData + (height - 1) * rowSpan; while (tmpRow >= tmpData) { memcpy(tmpRow, srcRow, rowSpan); srcRow += rowSpan; tmpRow -= rowSpan; } memcpy(dst.data, tmpData, rowSpan * height); delete [] tmpData; } } #if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 uint32 OSXWindow::bitDepthFromDisplayMode(CGDisplayModeRef mode) { uint32 depth = 0; CFStringRef pixEnc = CGDisplayModeCopyPixelEncoding(mode); if(CFStringCompare(pixEnc, CFSTR(IO32BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) depth = 32; else if(CFStringCompare(pixEnc, CFSTR(IO16BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) depth = 16; else if(CFStringCompare(pixEnc, CFSTR(IO8BitIndexedPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) depth = 8; return depth; } #endif //-------------------------------------------------------------------------------------------------// void OSXWindow::createCGLFullscreen(unsigned int width, unsigned int height, unsigned int depth, unsigned int fsaa, CGLContextObj sharedContext) { // Find the best match to what was requested boolean_t exactMatch = 0; int reqWidth, reqHeight, reqDepth; CGLError err; CGError cgErr; #if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 // Get a copy of the current display mode CGDisplayModeRef displayMode = CGDisplayCopyDisplayMode(kCGDirectMainDisplay); // Loop through all display modes to determine the closest match. // CGDisplayBestModeForParameters is deprecated on 10.6 so we will emulate it's behavior // Try to find a mode with the requested depth and equal or greater dimensions first. // If no match is found, try to find a mode with greater depth and same or greater dimensions. // If still no match is found, just use the current mode. CFArrayRef allModes = CGDisplayCopyAllDisplayModes(kCGDirectMainDisplay, NULL); for(int i = 0; i < CFArrayGetCount(allModes); i++) { CGDisplayModeRef mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(allModes, i); String modeString = StringConverter::toString(CGDisplayModeGetWidth(mode)) + String(" x ") + StringConverter::toString(CGDisplayModeGetHeight(mode)) + String(" @ ") + StringConverter::toString(bitDepthFromDisplayMode(mode)) + "bpp."; // LogManager::getSingleton().logMessage(modeString); if(bitDepthFromDisplayMode(mode) != depth) continue; if((CGDisplayModeGetWidth(mode) == width) && (CGDisplayModeGetHeight(mode) == height)) { displayMode = mode; exactMatch = 1; break; } } // No depth match was found if(!exactMatch) { for(int i = 0; i < CFArrayGetCount(allModes); i++) { CGDisplayModeRef mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(allModes, i); if(bitDepthFromDisplayMode(mode) >= depth) continue; if((CGDisplayModeGetWidth(mode) >= width) && (CGDisplayModeGetHeight(mode) >= height)) { displayMode = mode; exactMatch = 1; break; } } } reqWidth = CGDisplayModeGetWidth(displayMode); reqHeight = CGDisplayModeGetHeight(displayMode); reqDepth = bitDepthFromDisplayMode(displayMode); #else CFDictionaryRef displayMode = CGDisplayBestModeForParameters(kCGDirectMainDisplay, depth, width, height, &exactMatch); const void *value = NULL; value = CFDictionaryGetValue(displayMode, kCGDisplayWidth); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &reqWidth); value = CFDictionaryGetValue(displayMode, kCGDisplayHeight); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &reqHeight); value = CFDictionaryGetValue(displayMode, kCGDisplayBitsPerPixel); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &reqDepth); #endif if(!exactMatch) { // TODO: Report the size difference // That mode is not available, using the closest match String request = StringConverter::toString(width) + String(" x ") + StringConverter::toString(height) + String(" @ ") + StringConverter::toString(depth) + "bpp. "; String received = StringConverter::toString(reqWidth) + String(" x ") + StringConverter::toString(reqHeight) + String(" @ ") + StringConverter::toString(reqDepth) + "bpp. "; LogManager::getSingleton().logMessage(String("RenderSystem Warning: You requested a fullscreen mode of ") + request + String(" This mode is not available and you will receive the closest match. The best display mode for the parameters requested is: ") + received); } // Do the fancy display fading CGDisplayFadeReservationToken reservationToken; CGAcquireDisplayFadeReservation(kCGMaxDisplayReservationInterval, &reservationToken); CGDisplayFade(reservationToken, 0.5, kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, true); // Grab the main display and save it for later. // You could render to any display, but picking what display // to render to could be interesting. CGDisplayCapture(kCGDirectMainDisplay); // Switch to the correct resolution #if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 cgErr = CGDisplaySetDisplayMode(kCGDirectMainDisplay, displayMode, NULL); if(cgErr != 0) { CGReleaseAllDisplays(); OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, String("CG Error: " + StringConverter::toString((int)err)), "OSXWindow::createCGLFullscreen"); } #else CGDisplaySwitchToMode(kCGDirectMainDisplay, displayMode); #endif // Get a pixel format that best matches what we are looking for CGLPixelFormatAttribute attribs[] = { kCGLPFADoubleBuffer, kCGLPFAAlphaSize, (CGLPixelFormatAttribute)8, kCGLPFADepthSize, (CGLPixelFormatAttribute)reqDepth, kCGLPFAStencilSize, (CGLPixelFormatAttribute)8, kCGLPFASampleBuffers, (CGLPixelFormatAttribute)0, kCGLPFASamples, (CGLPixelFormatAttribute)0, kCGLPFAFullScreen, kCGLPFASingleRenderer, kCGLPFAAccelerated, kCGLPFADisplayMask, (CGLPixelFormatAttribute)CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay), (CGLPixelFormatAttribute)0 }; // Set up FSAA if it was requested if(fsaa > 1) { // turn on kCGLPFASampleBuffers attribs[8] = (CGLPixelFormatAttribute)1; // set the samples for kCGLPFASamples attribs[10] = (CGLPixelFormatAttribute)fsaa; } CGLPixelFormatObj pixelFormatObj; #if (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4) GLint numPixelFormats = 0; err = CGLChoosePixelFormat(attribs, &pixelFormatObj, &numPixelFormats); #else long numPixelFormats = 0; err = CGLChoosePixelFormat(attribs, &pixelFormatObj, &numPixelFormats); #endif if(err != 0) { CGReleaseAllDisplays(); OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, String("CGL Error: " + String(CGLErrorString(err))), "OSXWindow::createCGLFullscreen"); } // Create the CGLcontext from our pixel format, share it with the sharedContext passed in err = CGLCreateContext(pixelFormatObj, sharedContext, &mCGLContext); if(err != 0) { CGReleaseAllDisplays(); OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, String("CGL Error: " + String(CGLErrorString(err))), "OSXWindow::createCGLFullscreen"); } // Set the context to full screen #if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 err = CGLSetFullScreenOnDisplay(mCGLContext, CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay)); if(err != 0) { CGReleaseAllDisplays(); OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, String("CGL Error: " + String(CGLErrorString(err))), "OSXWindow::createCGLFullscreen"); } #else CGLSetFullScreen(mCGLContext); #endif // Set the context as current err = CGLSetCurrentContext(mCGLContext); if(err != 0) { CGReleaseAllDisplays(); OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, String("CGL Error: " + String(CGLErrorString(err))), "OSXWindow::createCGLFullscreen"); } // This synchronizes CGL with the vertical retrace // Apple docs suggest that OpenGL blocks rendering calls when waiting for // a vertical retrace anyhow. #if (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4) GLint swapInterval = 1; CGLSetParameter(mCGLContext, kCGLCPSwapInterval, &swapInterval); #else long swapInterval = 1; CGLSetParameter(mCGLContext, kCGLCPSwapInterval, &swapInterval); #endif // Give a copy of our context to the rendersystem mContext = new OSXCGLContext(mCGLContext, pixelFormatObj); // Once we have the context we can destroy the pixel format // In order to share contexts you must keep a pointer to the context object around // Our context class will now manage the life of the pixelFormatObj CGLDestroyPixelFormat(pixelFormatObj); // Let everyone know we are fullscreen now mIsFullScreen = true; // Set some other variables. Just in case we got a different value from CGDisplayBestModeForParameters than we requested mWidth = reqWidth; mHeight = reqHeight; mColourDepth = reqDepth; CGDisplayFade(reservationToken, 2.0, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, false); CGReleaseDisplayFadeReservation(reservationToken); } //-------------------------------------------------------------------------------------------------// void OSXWindow::destroyCGLFullscreen(void) { CGReleaseAllDisplays(); if(mCGLContext) { CGLDestroyContext(mCGLContext); mCGLContext = 0; } } //-------------------------------------------------------------------------------------------------// void OSXWindow::swapCGLBuffers(void) { CGLFlushDrawable(mCGLContext); CGLContextObj curCtx = CGLGetCurrentContext(); if(curCtx != mCGLContext) { CGLSetCurrentContext(mCGLContext); #if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 CGLSetFullScreenOnDisplay(mCGLContext, CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay)); #else CGLSetFullScreen(mCGLContext); #endif } } } <|endoftext|>
<commit_before>#define HUE_STEP 1 #define VALUE_STEP 5 #define PERIOD_STEP 3 #define LETTERS_LAYER 0 #define BACKGROUND_LAYER 1 #include "Effects.h" #include "effects/Effect.cpp" #include "effects/RandomOn.cpp" #include "effects/Counter.cpp" #include "effects/BasicTyping.cpp" #include "effects/SolidColor.cpp" #include "effects/SolidFade.cpp" #include "effects/RandomFade.cpp" #include "effects/RandomLetters.cpp" #include "effects/RainbowLetter.cpp" #include "effects/RainbowSegment.cpp" const uint16_t CYCLE_TIME = 5; Effects::Effects(){ for(uint8_t i=0; i<LAYER_COUNT; i++){ colorEffect[i] = &solidColor; cColorEffect[i] = SOLID_COLORS; } cTextEffect = BASIC_TYPING; textEffect = &basicTyping; this -> reset(); } void Effects::run(Sign &sign){ unsigned long time = millis(); if(time - lastRun < CYCLE_TIME){ return; } lastRun = time; sign.textChanged = false; textEffect -> run(sign, 0); for(uint8_t i=0; i<LAYER_COUNT; i++){ colorEffect[i] -> run(sign, i); } } void Effects::pushChar(char character){ switch(character){ case '2': curLayer = LETTERS_LAYER; Serial.println("Layer 2: Letters"); Serial1.print("\nLayer 2: Letters"); return; case '1': curLayer = BACKGROUND_LAYER; Serial.println("Layer 1: Background"); Serial1.print("\nLayer 1: Background"); return; } if( textEffect -> pushChar(character, 0) ){ return; } if( colorEffect[curLayer] -> pushChar(character, curLayer) ){ return; } int32_t val = 0; switch(character){ case 'R': Serial1.print("\nRESET"); this -> reset(); break; case '<': val = this -> prevTextEffect(); break; case '>': val = this -> nextTextEffect(); break; case 'l': val = this -> prevColorEffect(curLayer); break; case 'h': val = this -> nextColorEffect(curLayer); break; } Serial.print(character); Serial.print(": "); Serial.print(val); Serial.println(" "); } // Called when new letters pushed to sign void Effects::signWasUpdated(Sign &sign){ this -> run(sign); textEffect -> signWasUpdated(sign); for(uint8_t i=0; i<LAYER_COUNT; i++){ colorEffect[i] -> signWasUpdated(sign); } } void Effects::reset(){ curLayer = 0; lastRun = 0; textEffect -> reset(); for(uint8_t i=1; i<LAYER_COUNT; i++){ colorEffect[i] -> reset(); } } uint8_t Effects::nextTextEffect(){ cTextEffect++; cTextEffect = cTextEffect % TEXT_EFFECTS_COUNT; this -> updateTextEffect(); return cTextEffect; } uint8_t Effects::prevTextEffect(){ cTextEffect--; cTextEffect = cTextEffect % TEXT_EFFECTS_COUNT; this -> updateTextEffect(); return cTextEffect; } void Effects::updateTextEffect(){ String desc; switch(cTextEffect){ case RANDOM_ON: textEffect = &randomOn; desc = "Random Segs,\nkeys:[]kjor"; break; case BASIC_TYPING: textEffect = &basicTyping; desc = "Basic Typing"; break; case COUNTER: textEffect = &counter; desc = "Counter\nkeys:[]kj"; break; case RANDOM_LETTERS: textEffect = &randomLetters; desc = "Random Letters\nkeys:kj"; break; default: textEffect = &nullEffect; desc = "ERROR"; } Serial.println(desc); Serial1.print('\n'); Serial1.print(desc); } uint8_t Effects::nextColorEffect(uint8_t ci){ cColorEffect[ci]++; cColorEffect[ci] = cColorEffect[ci] % COLOR_EFFECTS_COUNT; this -> updateColorEffect(ci); return cColorEffect[ci]; } uint8_t Effects::prevColorEffect(uint8_t ci){ if(cColorEffect[ci] == 0){ cColorEffect[ci] = COLOR_EFFECTS_COUNT - 1; }else{ cColorEffect[ci]--; cColorEffect[ci] = cColorEffect[ci] % COLOR_EFFECTS_COUNT; } this -> updateColorEffect(ci); return cColorEffect[ci]; } void Effects::updateColorEffect(uint8_t ci){ String desc; switch(cColorEffect[ci]){ case SOLID_COLORS: colorEffect[ci] = &solidColor; desc = "Solid Color\nKeys:cCvVbB"; break; case RANDOM_FADE: colorEffect[ci] = &randomFade; desc = "Random Fade\nKeys:cCvVbBfsFS"; break; case SOLID_FADE: colorEffect[ci] = &solidFade; desc = "Solid Fade\nKeys:cCvVbBfs"; break; case RAINBOW_LETTER: colorEffect[ci] = &rainbowLetter; desc = "Rainbow Letter\nKeys:cCvVbBrefsd"; break; case RAINBOW_SEGMENT: colorEffect[ci] = &rainbowSegment; desc = "Rainbow Segment\nKeys:cCvVbBrefsd"; break; } Serial.println(desc); Serial1.print('\n'); Serial1.print(desc); } <commit_msg>Switch text effect change to ,/.<commit_after>#define HUE_STEP 1 #define VALUE_STEP 5 #define PERIOD_STEP 3 #define LETTERS_LAYER 0 #define BACKGROUND_LAYER 1 #include "Effects.h" #include "effects/Effect.cpp" #include "effects/RandomOn.cpp" #include "effects/Counter.cpp" #include "effects/BasicTyping.cpp" #include "effects/SolidColor.cpp" #include "effects/SolidFade.cpp" #include "effects/RandomFade.cpp" #include "effects/RandomLetters.cpp" #include "effects/RainbowLetter.cpp" #include "effects/RainbowSegment.cpp" const uint16_t CYCLE_TIME = 5; Effects::Effects(){ for(uint8_t i=0; i<LAYER_COUNT; i++){ colorEffect[i] = &solidColor; cColorEffect[i] = SOLID_COLORS; } cTextEffect = BASIC_TYPING; textEffect = &basicTyping; this -> reset(); } void Effects::run(Sign &sign){ unsigned long time = millis(); if(time - lastRun < CYCLE_TIME){ return; } lastRun = time; sign.textChanged = false; textEffect -> run(sign, 0); for(uint8_t i=0; i<LAYER_COUNT; i++){ colorEffect[i] -> run(sign, i); } } void Effects::pushChar(char character){ switch(character){ case '2': curLayer = LETTERS_LAYER; Serial.println("Layer 2: Letters"); Serial1.print("\nLayer 2: Letters"); return; case '1': curLayer = BACKGROUND_LAYER; Serial.println("Layer 1: Background"); Serial1.print("\nLayer 1: Background"); return; } if( textEffect -> pushChar(character, 0) ){ return; } if( colorEffect[curLayer] -> pushChar(character, curLayer) ){ return; } int32_t val = 0; switch(character){ case 'R': Serial1.print("\nRESET"); this -> reset(); break; case '.': val = this -> prevTextEffect(); break; case ',': val = this -> nextTextEffect(); break; case 'l': val = this -> prevColorEffect(curLayer); break; case 'h': val = this -> nextColorEffect(curLayer); break; } Serial.print(character); Serial.print(": "); Serial.print(val); Serial.println(" "); } // Called when new letters pushed to sign void Effects::signWasUpdated(Sign &sign){ this -> run(sign); textEffect -> signWasUpdated(sign); for(uint8_t i=0; i<LAYER_COUNT; i++){ colorEffect[i] -> signWasUpdated(sign); } } void Effects::reset(){ curLayer = 0; lastRun = 0; textEffect -> reset(); for(uint8_t i=1; i<LAYER_COUNT; i++){ colorEffect[i] -> reset(); } } uint8_t Effects::nextTextEffect(){ cTextEffect++; cTextEffect = cTextEffect % TEXT_EFFECTS_COUNT; this -> updateTextEffect(); return cTextEffect; } uint8_t Effects::prevTextEffect(){ cTextEffect--; cTextEffect = cTextEffect % TEXT_EFFECTS_COUNT; this -> updateTextEffect(); return cTextEffect; } void Effects::updateTextEffect(){ String desc; switch(cTextEffect){ case RANDOM_ON: textEffect = &randomOn; desc = "Random Segs,\nkeys:[]kjor"; break; case BASIC_TYPING: textEffect = &basicTyping; desc = "Basic Typing"; break; case COUNTER: textEffect = &counter; desc = "Counter\nkeys:[]kj"; break; case RANDOM_LETTERS: textEffect = &randomLetters; desc = "Random Letters\nkeys:kj"; break; default: textEffect = &nullEffect; desc = "ERROR"; } Serial.println(desc); Serial1.print('\n'); Serial1.print(desc); } uint8_t Effects::nextColorEffect(uint8_t ci){ cColorEffect[ci]++; cColorEffect[ci] = cColorEffect[ci] % COLOR_EFFECTS_COUNT; this -> updateColorEffect(ci); return cColorEffect[ci]; } uint8_t Effects::prevColorEffect(uint8_t ci){ if(cColorEffect[ci] == 0){ cColorEffect[ci] = COLOR_EFFECTS_COUNT - 1; }else{ cColorEffect[ci]--; cColorEffect[ci] = cColorEffect[ci] % COLOR_EFFECTS_COUNT; } this -> updateColorEffect(ci); return cColorEffect[ci]; } void Effects::updateColorEffect(uint8_t ci){ String desc; switch(cColorEffect[ci]){ case SOLID_COLORS: colorEffect[ci] = &solidColor; desc = "Solid Color\nKeys:cCvVbB"; break; case RANDOM_FADE: colorEffect[ci] = &randomFade; desc = "Random Fade\nKeys:cCvVbBfsFS"; break; case SOLID_FADE: colorEffect[ci] = &solidFade; desc = "Solid Fade\nKeys:cCvVbBfs"; break; case RAINBOW_LETTER: colorEffect[ci] = &rainbowLetter; desc = "Rainbow Letter\nKeys:cCvVbBrefsd"; break; case RAINBOW_SEGMENT: colorEffect[ci] = &rainbowSegment; desc = "Rainbow Segment\nKeys:cCvVbBrefsd"; break; } Serial.println(desc); Serial1.print('\n'); Serial1.print(desc); } <|endoftext|>
<commit_before>/** * @file Mesh.cpp * @author Sebastian Maisch <sebastian.maisch@googlemail.com> * @date 2017.03.24 * * @brief Implementation of the Mesh class. */ #include "Mesh.h" #include "gfx/vk/LogicalDevice.h" #include "gfx/vk/memory/MemoryGroup.h" #include "gfx/Texture2D.h" #include <glm/gtc/matrix_inverse.hpp> #include <glm/gtc/type_ptr.hpp> namespace vku::gfx { Mesh::Mesh(std::shared_ptr<const MeshInfo> meshInfo, const LogicalDevice* device, vk::MemoryPropertyFlags memoryFlags, const std::vector<std::uint32_t>& queueFamilyIndices) : device_{ device }, meshInfo_{ meshInfo }, memoryGroup_{ std::make_unique<MemoryGroup>(device, memoryFlags) }, vertexBuffer_{ nullptr, 0 }, indexBuffer_{ nullptr, 0 }, materialBuffer_{ nullptr, 0, 0 } { CreateMaterials(queueFamilyIndices); } Mesh::Mesh(std::shared_ptr<const MeshInfo> meshInfo, const LogicalDevice* device, MemoryGroup& memoryGroup, const std::vector<std::uint32_t>& queueFamilyIndices) : device_{ device }, meshInfo_{ meshInfo }, vertexBuffer_{ nullptr, 0 }, indexBuffer_{ nullptr, 0 }, materialBuffer_{ nullptr, 0, 0 } { CreateMaterials(queueFamilyIndices); } Mesh::Mesh(Mesh&& rhs) noexcept : device_{ std::move(rhs.device_) }, meshInfo_{ std::move(rhs.meshInfo_) }, memoryGroup_{ std::move(rhs.memoryGroup_) }, vertexBuffer_{ std::move(rhs.vertexBuffer_) }, indexBuffer_{ std::move(rhs.indexBuffer_) }, materialBuffer_{ std::move(rhs.materialBuffer_) }, materials_{ std::move(rhs.materials_) }, textureSampler_{ std::move(rhs.textureSampler_) }, descriptorPool_{ std::move(rhs.descriptorPool_) }, descriptorSetLayout_{ std::move(rhs.descriptorSetLayout_) }, materialDescriptorSets_{ std::move(rhs.materialDescriptorSets_) }, vertexMaterialData_{ std::move(rhs.vertexMaterialData_) } { rhs.textureSampler_ = vk::Sampler(); rhs.descriptorPool_ = vk::DescriptorPool(); rhs.descriptorSetLayout_ = vk::DescriptorSetLayout(); } Mesh& Mesh::operator=(Mesh&& rhs) noexcept { this->~Mesh(); device_ = std::move(rhs.device_); meshInfo_ = std::move(rhs.meshInfo_); memoryGroup_ = std::move(rhs.memoryGroup_); vertexBuffer_ = std::move(rhs.vertexBuffer_); indexBuffer_ = std::move(rhs.indexBuffer_); materialBuffer_ = std::move(rhs.materialBuffer_); materials_ = std::move(rhs.materials_); textureSampler_ = std::move(rhs.textureSampler_); descriptorPool_ = std::move(rhs.descriptorPool_); descriptorSetLayout_ = std::move(rhs.descriptorSetLayout_); materialDescriptorSets_ = std::move(rhs.materialDescriptorSets_); vertexMaterialData_ = std::move(rhs.vertexMaterialData_); rhs.textureSampler_ = vk::Sampler(); rhs.descriptorPool_ = vk::DescriptorPool(); rhs.descriptorSetLayout_ = vk::DescriptorSetLayout(); return *this; } Mesh::~Mesh() { if (descriptorPool_) device_->GetDevice().destroyDescriptorPool(descriptorPool_); descriptorPool_ = vk::DescriptorPool(); if (descriptorSetLayout_) device_->GetDevice().destroyDescriptorSetLayout(descriptorSetLayout_); descriptorSetLayout_ = vk::DescriptorSetLayout(); if (textureSampler_) device_->GetDevice().destroySampler(textureSampler_); textureSampler_ = vk::Sampler(); } void Mesh::CreateMaterials(const std::vector<std::uint32_t>& queueFamilyIndices) { vk::SamplerCreateInfo samplerCreateInfo{ vk::SamplerCreateFlags(), vk::Filter::eLinear, vk::Filter::eLinear, vk::SamplerMipmapMode::eNearest, vk::SamplerAddressMode::eRepeat, vk::SamplerAddressMode::eRepeat, vk::SamplerAddressMode::eRepeat }; textureSampler_ = device_->GetDevice().createSampler(samplerCreateInfo); auto numMaterials = meshInfo_->GetMaterials().size(); std::vector<vk::DescriptorPoolSize> poolSizes; poolSizes.emplace_back(vk::DescriptorType::eUniformBuffer, static_cast<std::uint32_t>(numMaterials)); poolSizes.emplace_back(vk::DescriptorType::eCombinedImageSampler, static_cast<std::uint32_t>(numMaterials * 2)); vk::DescriptorPoolCreateInfo descriptorPoolInfo{ vk::DescriptorPoolCreateFlags(), static_cast<std::uint32_t>(numMaterials * 3), static_cast<std::uint32_t>(poolSizes.size()), poolSizes.data() }; descriptorPool_ = device_->GetDevice().createDescriptorPool(descriptorPoolInfo); // Shared descriptor set layout std::vector<vk::DescriptorSetLayoutBinding> setLayoutBindings; // Binding 0: UBO setLayoutBindings.emplace_back(0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eFragment); // Binding 1: Diffuse map setLayoutBindings.emplace_back(1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment); // Binding 1: Bump map setLayoutBindings.emplace_back(2, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment); vk::DescriptorSetLayoutCreateInfo descriptorLayoutCreateInfo{ vk::DescriptorSetLayoutCreateFlags(), static_cast<std::uint32_t>(setLayoutBindings.size()), setLayoutBindings.data() }; descriptorSetLayout_ = device_->GetDevice().createDescriptorSetLayout(descriptorLayoutCreateInfo); materials_.reserve(numMaterials); for (std::size_t i = 0; i < numMaterials; ++i) { const auto& mat = meshInfo_->GetMaterials()[i]; materials_.emplace_back(&mat, device_, *memoryGroup_, queueFamilyIndices); } // { // vk::PipelineLayoutCreateInfo pipelineLayoutInfo{ vk::PipelineLayoutCreateFlags(), // static_cast<std::uint32_t>(vkDescriptorSetLayouts_.size()), vkDescriptorSetLayouts_.data(), 0, nullptr }; // vkPipelineLayout_ = device.GetDevice().createPipelineLayout(pipelineLayoutInfo); // } // { // std::vector<vk::DescriptorSetLayout> descSetLayouts; descSetLayouts.resize(numUBOBuffers + 1); // descSetLayouts[0] = descSetLayout; // for (auto i = 0U; i < numUBOBuffers; ++i) descSetLayouts[i + 1] = vkDescriptorSetLayouts_[1]; // vk::DescriptorSetAllocateInfo descSetAllocInfo{ vkUBODescriptorPool_, static_cast<std::uint32_t>(descSetLayouts.size()), descSetLayouts.data() }; // vkUBOSamplerDescritorSets_ = device.GetDevice().allocateDescriptorSets(descSetAllocInfo); // } } void Mesh::CreateDescriptorSets() { std::vector<vk::DescriptorSetLayout> descSetLayouts; descSetLayouts.resize(materials_.size()); std::vector<vk::WriteDescriptorSet> descSetWrites; descSetWrites.reserve(materials_.size()); std::vector<vk::DescriptorBufferInfo> descBufferInfos; descBufferInfos.reserve(materials_.size()); std::vector<vk::DescriptorImageInfo> descImageInfos; descImageInfos.reserve(materials_.size() * 2); for (std::size_t i = 0; i < materials_.size(); ++i) { descSetLayouts[i] = descriptorSetLayout_; } vk::DescriptorSetAllocateInfo descSetAllocInfo{ descriptorPool_, static_cast<std::uint32_t>(descSetLayouts.size()), descSetLayouts.data() }; materialDescriptorSets_ = device_->GetDevice().allocateDescriptorSets(descSetAllocInfo); auto uboOffset = static_cast<std::uint32_t>(std::get<1>(materialBuffer_)); auto materialBufferSize = static_cast<std::uint32_t>(std::get<2>(materialBuffer_)); for (std::size_t i = 0; i < materials_.size(); ++i) { auto materialBufferOffset = uboOffset + materialBufferSize * i; descBufferInfos.emplace_back(std::get<0>(materialBuffer_)->GetBuffer(), materialBufferOffset, materialBufferSize); descSetWrites.emplace_back(materialDescriptorSets_[i], 0, static_cast<std::uint32_t>(i), 1, vk::DescriptorType::eUniformBuffer, nullptr, &descBufferInfos[i]); if (materials_[i].diffuseTexture_) { descImageInfos.emplace_back(textureSampler_, materials_[i].diffuseTexture_->GetTexture().GetImageView(), vk::ImageLayout::eShaderReadOnlyOptimal); descSetWrites.emplace_back(materialDescriptorSets_[i], 1, static_cast<std::uint32_t>(i), 1, vk::DescriptorType::eCombinedImageSampler, &descImageInfos[2 * i + 0]); } else { descSetWrites.emplace_back(materialDescriptorSets_[i], 1, static_cast<std::uint32_t>(i), 0, vk::DescriptorType::eCombinedImageSampler, nullptr); } if (materials_[i].bumpMap_) { vk::DescriptorImageInfo descImageInfo{ textureSampler_, materials_[i].bumpMap_->GetTexture().GetImageView(), vk::ImageLayout::eShaderReadOnlyOptimal }; descSetWrites.emplace_back(materialDescriptorSets_[i], 2, static_cast<std::uint32_t>(i), 1, vk::DescriptorType::eCombinedImageSampler, &descImageInfos[2 * i + 1]); } else { descSetWrites.emplace_back(materialDescriptorSets_[i], 2, static_cast<std::uint32_t>(i), 0, vk::DescriptorType::eCombinedImageSampler, nullptr); } } device_->GetDevice().updateDescriptorSets(descSetWrites, nullptr); } void Mesh::UploadMeshData(QueuedDeviceTransfer& transfer) { assert(memoryGroup_); memoryGroup_->FinalizeDeviceGroup(); memoryGroup_->TransferData(transfer); vertexMaterialData_.clear(); } void Mesh::BindBuffersToCommandBuffer(vk::CommandBuffer cmdBuffer) const { cmdBuffer.bindVertexBuffers(0, 1, vertexBuffer_.first->GetBufferPtr(), &vertexBuffer_.second); cmdBuffer.bindIndexBuffer(indexBuffer_.first->GetBuffer(), indexBuffer_.second, vk::IndexType::eUint32); } void Mesh::DrawMesh(vk::CommandBuffer cmdBuffer, vk::PipelineLayout pipelineLayout, const glm::mat4& worldMatrix) const { auto meshWorld = meshInfo_->GetRootTransform() * worldMatrix; // TODO: add depth sorting here... DrawMeshNode(cmdBuffer, pipelineLayout, meshInfo_->GetRootNode(), meshWorld); // TODO: use submeshes and materials and the scene nodes... // need: // - for each submesh: 2 texture descriptors // - for each scene mesh node: uniform buffer? // - uniform buffer for all materials[array] (via template) // - push constant for world matrix // - push constant for material index .. or "VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC" // cmdBuffer.drawIndexed(static_cast<std::uint32_t>(meshInfo_->GetIndices().size()), 1, 0, 0, 0); } void Mesh::DrawMeshNode(vk::CommandBuffer cmdBuffer, vk::PipelineLayout pipelineLayout, const SceneMeshNode* node, const glm::mat4& worldMatrix) const { auto nodeWorld = node->GetLocalTransform() * worldMatrix; for (unsigned int i = 0; i < node->GetNumberOfSubMeshes(); ++i) DrawSubMesh(cmdBuffer, pipelineLayout, meshInfo_->GetSubMesh(node->GetSubMeshID(i)), nodeWorld); for (unsigned int i = 0; i < node->GetNumberOfNodes(); ++i) DrawMeshNode(cmdBuffer, pipelineLayout, node->GetChild(i), nodeWorld); } void Mesh::DrawSubMesh(vk::CommandBuffer cmdBuffer, vk::PipelineLayout pipelineLayout, const SubMesh* subMesh, const glm::mat4& worldMatrix) const { auto worldMat = worldMatrix; auto normalMat = glm::inverseTranspose(glm::mat3(worldMatrix)); auto& mat = materials_[subMesh->GetMaterialID()]; auto& matDescSets = materialDescriptorSets_[subMesh->GetMaterialID()]; // bind material ubo. cmdBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipelineLayout, 0, materialDescriptorSets_, nullptr); cmdBuffer.pushConstants(pipelineLayout, vk::ShaderStageFlagBits::eVertex, 0, vk::ArrayProxy<const float>(16, glm::value_ptr(worldMat))); cmdBuffer.pushConstants(pipelineLayout, vk::ShaderStageFlagBits::eVertex, 16, vk::ArrayProxy<const float>(9, glm::value_ptr(normalMat))); cmdBuffer.drawIndexed(static_cast<std::uint32_t>(subMesh->GetNumberOfIndices()), 1, static_cast<std::uint32_t>(subMesh->GetIndexOffset()), 0, 0); } void Mesh::SetVertexBuffer(const DeviceBuffer* vtxBuffer, std::size_t offset) { vertexBuffer_.first = vtxBuffer; vertexBuffer_.second = offset; } void Mesh::SetIndexBuffer(const DeviceBuffer* idxBuffer, std::size_t offset) { indexBuffer_.first = idxBuffer; indexBuffer_.second = offset; } void Mesh::SetMaterialBuffer(const DeviceBuffer* matBuffer, std::size_t offset, std::size_t elementSize) { materialBuffer_ = std::make_tuple(matBuffer, offset, elementSize); } } <commit_msg>Some fixes for mesh rendering.<commit_after>/** * @file Mesh.cpp * @author Sebastian Maisch <sebastian.maisch@googlemail.com> * @date 2017.03.24 * * @brief Implementation of the Mesh class. */ #include "Mesh.h" #include "gfx/vk/LogicalDevice.h" #include "gfx/vk/memory/MemoryGroup.h" #include "gfx/Texture2D.h" #include <glm/gtc/matrix_inverse.hpp> #include <glm/gtc/type_ptr.hpp> namespace vku::gfx { Mesh::Mesh(std::shared_ptr<const MeshInfo> meshInfo, const LogicalDevice* device, vk::MemoryPropertyFlags memoryFlags, const std::vector<std::uint32_t>& queueFamilyIndices) : device_{ device }, meshInfo_{ meshInfo }, memoryGroup_{ std::make_unique<MemoryGroup>(device, memoryFlags) }, vertexBuffer_{ nullptr, 0 }, indexBuffer_{ nullptr, 0 }, materialBuffer_{ nullptr, 0, 0 } { CreateMaterials(queueFamilyIndices); } Mesh::Mesh(std::shared_ptr<const MeshInfo> meshInfo, const LogicalDevice* device, MemoryGroup& memoryGroup, const std::vector<std::uint32_t>& queueFamilyIndices) : device_{ device }, meshInfo_{ meshInfo }, vertexBuffer_{ nullptr, 0 }, indexBuffer_{ nullptr, 0 }, materialBuffer_{ nullptr, 0, 0 } { CreateMaterials(queueFamilyIndices); } Mesh::Mesh(Mesh&& rhs) noexcept : device_{ std::move(rhs.device_) }, meshInfo_{ std::move(rhs.meshInfo_) }, memoryGroup_{ std::move(rhs.memoryGroup_) }, vertexBuffer_{ std::move(rhs.vertexBuffer_) }, indexBuffer_{ std::move(rhs.indexBuffer_) }, materialBuffer_{ std::move(rhs.materialBuffer_) }, materials_{ std::move(rhs.materials_) }, textureSampler_{ std::move(rhs.textureSampler_) }, descriptorPool_{ std::move(rhs.descriptorPool_) }, descriptorSetLayout_{ std::move(rhs.descriptorSetLayout_) }, materialDescriptorSets_{ std::move(rhs.materialDescriptorSets_) }, vertexMaterialData_{ std::move(rhs.vertexMaterialData_) } { rhs.textureSampler_ = vk::Sampler(); rhs.descriptorPool_ = vk::DescriptorPool(); rhs.descriptorSetLayout_ = vk::DescriptorSetLayout(); } Mesh& Mesh::operator=(Mesh&& rhs) noexcept { this->~Mesh(); device_ = std::move(rhs.device_); meshInfo_ = std::move(rhs.meshInfo_); memoryGroup_ = std::move(rhs.memoryGroup_); vertexBuffer_ = std::move(rhs.vertexBuffer_); indexBuffer_ = std::move(rhs.indexBuffer_); materialBuffer_ = std::move(rhs.materialBuffer_); materials_ = std::move(rhs.materials_); textureSampler_ = std::move(rhs.textureSampler_); descriptorPool_ = std::move(rhs.descriptorPool_); descriptorSetLayout_ = std::move(rhs.descriptorSetLayout_); materialDescriptorSets_ = std::move(rhs.materialDescriptorSets_); vertexMaterialData_ = std::move(rhs.vertexMaterialData_); rhs.textureSampler_ = vk::Sampler(); rhs.descriptorPool_ = vk::DescriptorPool(); rhs.descriptorSetLayout_ = vk::DescriptorSetLayout(); return *this; } Mesh::~Mesh() { if (descriptorPool_) device_->GetDevice().destroyDescriptorPool(descriptorPool_); descriptorPool_ = vk::DescriptorPool(); if (descriptorSetLayout_) device_->GetDevice().destroyDescriptorSetLayout(descriptorSetLayout_); descriptorSetLayout_ = vk::DescriptorSetLayout(); if (textureSampler_) device_->GetDevice().destroySampler(textureSampler_); textureSampler_ = vk::Sampler(); } void Mesh::CreateMaterials(const std::vector<std::uint32_t>& queueFamilyIndices) { vk::SamplerCreateInfo samplerCreateInfo{ vk::SamplerCreateFlags(), vk::Filter::eLinear, vk::Filter::eLinear, vk::SamplerMipmapMode::eNearest, vk::SamplerAddressMode::eRepeat, vk::SamplerAddressMode::eRepeat, vk::SamplerAddressMode::eRepeat }; textureSampler_ = device_->GetDevice().createSampler(samplerCreateInfo); auto numMaterials = meshInfo_->GetMaterials().size(); std::vector<vk::DescriptorPoolSize> poolSizes; poolSizes.emplace_back(vk::DescriptorType::eUniformBuffer, static_cast<std::uint32_t>(numMaterials)); poolSizes.emplace_back(vk::DescriptorType::eCombinedImageSampler, static_cast<std::uint32_t>(numMaterials * 2)); vk::DescriptorPoolCreateInfo descriptorPoolInfo{ vk::DescriptorPoolCreateFlags(), static_cast<std::uint32_t>(numMaterials * 3), static_cast<std::uint32_t>(poolSizes.size()), poolSizes.data() }; descriptorPool_ = device_->GetDevice().createDescriptorPool(descriptorPoolInfo); // Shared descriptor set layout std::vector<vk::DescriptorSetLayoutBinding> setLayoutBindings; // Binding 0: UBO setLayoutBindings.emplace_back(0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eFragment); // Binding 1: Diffuse map setLayoutBindings.emplace_back(1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment); // Binding 1: Bump map setLayoutBindings.emplace_back(2, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment); vk::DescriptorSetLayoutCreateInfo descriptorLayoutCreateInfo{ vk::DescriptorSetLayoutCreateFlags(), static_cast<std::uint32_t>(setLayoutBindings.size()), setLayoutBindings.data() }; descriptorSetLayout_ = device_->GetDevice().createDescriptorSetLayout(descriptorLayoutCreateInfo); materials_.reserve(numMaterials); for (std::size_t i = 0; i < numMaterials; ++i) { const auto& mat = meshInfo_->GetMaterials()[i]; materials_.emplace_back(&mat, device_, *memoryGroup_, queueFamilyIndices); } // { // vk::PipelineLayoutCreateInfo pipelineLayoutInfo{ vk::PipelineLayoutCreateFlags(), // static_cast<std::uint32_t>(vkDescriptorSetLayouts_.size()), vkDescriptorSetLayouts_.data(), 0, nullptr }; // vkPipelineLayout_ = device.GetDevice().createPipelineLayout(pipelineLayoutInfo); // } // { // std::vector<vk::DescriptorSetLayout> descSetLayouts; descSetLayouts.resize(numUBOBuffers + 1); // descSetLayouts[0] = descSetLayout; // for (auto i = 0U; i < numUBOBuffers; ++i) descSetLayouts[i + 1] = vkDescriptorSetLayouts_[1]; // vk::DescriptorSetAllocateInfo descSetAllocInfo{ vkUBODescriptorPool_, static_cast<std::uint32_t>(descSetLayouts.size()), descSetLayouts.data() }; // vkUBOSamplerDescritorSets_ = device.GetDevice().allocateDescriptorSets(descSetAllocInfo); // } } void Mesh::CreateDescriptorSets() { std::vector<vk::DescriptorSetLayout> descSetLayouts; descSetLayouts.resize(materials_.size()); std::vector<vk::WriteDescriptorSet> descSetWrites; descSetWrites.reserve(materials_.size()); std::vector<vk::DescriptorBufferInfo> descBufferInfos; descBufferInfos.reserve(materials_.size()); std::vector<vk::DescriptorImageInfo> descImageInfos; descImageInfos.reserve(materials_.size() * 2); for (std::size_t i = 0; i < materials_.size(); ++i) { descSetLayouts[i] = descriptorSetLayout_; } vk::DescriptorSetAllocateInfo descSetAllocInfo{ descriptorPool_, static_cast<std::uint32_t>(descSetLayouts.size()), descSetLayouts.data() }; materialDescriptorSets_ = device_->GetDevice().allocateDescriptorSets(descSetAllocInfo); auto uboOffset = static_cast<std::uint32_t>(std::get<1>(materialBuffer_)); auto materialBufferSize = static_cast<std::uint32_t>(std::get<2>(materialBuffer_)); for (std::size_t i = 0; i < materials_.size(); ++i) { auto materialBufferOffset = uboOffset + materialBufferSize * i; descBufferInfos.emplace_back(std::get<0>(materialBuffer_)->GetBuffer(), materialBufferOffset, materialBufferSize); descSetWrites.emplace_back(materialDescriptorSets_[i], 0, static_cast<std::uint32_t>(i), 1, vk::DescriptorType::eUniformBuffer, nullptr, &descBufferInfos[i]); if (materials_[i].diffuseTexture_) { descImageInfos.emplace_back(textureSampler_, materials_[i].diffuseTexture_->GetTexture().GetImageView(), vk::ImageLayout::eShaderReadOnlyOptimal); } else { descImageInfos.emplace_back(vk::Sampler(), vk::ImageView(), vk::ImageLayout::eShaderReadOnlyOptimal); // descSetWrites.emplace_back(materialDescriptorSets_[i], 1, static_cast<std::uint32_t>(i), 0, vk::DescriptorType::eCombinedImageSampler, nullptr); } descSetWrites.emplace_back(materialDescriptorSets_[i], 1, static_cast<std::uint32_t>(i), 1, vk::DescriptorType::eCombinedImageSampler, &descImageInfos[2 * i + 0]); if (materials_[i].bumpMap_) { descImageInfos.emplace_back(textureSampler_, materials_[i].bumpMap_->GetTexture().GetImageView(), vk::ImageLayout::eShaderReadOnlyOptimal); } else { descImageInfos.emplace_back(vk::Sampler(), vk::ImageView(), vk::ImageLayout::eShaderReadOnlyOptimal); // descSetWrites.emplace_back(materialDescriptorSets_[i], 2, static_cast<std::uint32_t>(i), 0, vk::DescriptorType::eCombinedImageSampler, nullptr); } descSetWrites.emplace_back(materialDescriptorSets_[i], 2, static_cast<std::uint32_t>(i), 1, vk::DescriptorType::eCombinedImageSampler, &descImageInfos[2 * i + 1]); } device_->GetDevice().updateDescriptorSets(descSetWrites, nullptr); } void Mesh::UploadMeshData(QueuedDeviceTransfer& transfer) { assert(memoryGroup_); memoryGroup_->FinalizeDeviceGroup(); memoryGroup_->TransferData(transfer); vertexMaterialData_.clear(); } void Mesh::BindBuffersToCommandBuffer(vk::CommandBuffer cmdBuffer) const { cmdBuffer.bindVertexBuffers(0, 1, vertexBuffer_.first->GetBufferPtr(), &vertexBuffer_.second); cmdBuffer.bindIndexBuffer(indexBuffer_.first->GetBuffer(), indexBuffer_.second, vk::IndexType::eUint32); } void Mesh::DrawMesh(vk::CommandBuffer cmdBuffer, vk::PipelineLayout pipelineLayout, const glm::mat4& worldMatrix) const { auto meshWorld = meshInfo_->GetRootTransform() * worldMatrix; // TODO: add depth sorting here... DrawMeshNode(cmdBuffer, pipelineLayout, meshInfo_->GetRootNode(), meshWorld); // TODO: use submeshes and materials and the scene nodes... // need: // - for each submesh: 2 texture descriptors // - for each scene mesh node: uniform buffer? // - uniform buffer for all materials[array] (via template) // - push constant for world matrix // - push constant for material index .. or "VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC" // cmdBuffer.drawIndexed(static_cast<std::uint32_t>(meshInfo_->GetIndices().size()), 1, 0, 0, 0); } void Mesh::DrawMeshNode(vk::CommandBuffer cmdBuffer, vk::PipelineLayout pipelineLayout, const SceneMeshNode* node, const glm::mat4& worldMatrix) const { auto nodeWorld = node->GetLocalTransform() * worldMatrix; for (unsigned int i = 0; i < node->GetNumberOfSubMeshes(); ++i) DrawSubMesh(cmdBuffer, pipelineLayout, meshInfo_->GetSubMesh(node->GetSubMeshID(i)), nodeWorld); for (unsigned int i = 0; i < node->GetNumberOfNodes(); ++i) DrawMeshNode(cmdBuffer, pipelineLayout, node->GetChild(i), nodeWorld); } void Mesh::DrawSubMesh(vk::CommandBuffer cmdBuffer, vk::PipelineLayout pipelineLayout, const SubMesh* subMesh, const glm::mat4& worldMatrix) const { auto worldMat = worldMatrix; auto normalMat = glm::inverseTranspose(glm::mat3(worldMatrix)); auto& mat = materials_[subMesh->GetMaterialID()]; auto& matDescSets = materialDescriptorSets_[subMesh->GetMaterialID()]; // bind material ubo. cmdBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipelineLayout, 0, materialDescriptorSets_, nullptr); cmdBuffer.pushConstants(pipelineLayout, vk::ShaderStageFlagBits::eVertex, 0, vk::ArrayProxy<const float>(16, glm::value_ptr(worldMat))); cmdBuffer.pushConstants(pipelineLayout, vk::ShaderStageFlagBits::eVertex, 16, vk::ArrayProxy<const float>(9, glm::value_ptr(normalMat))); cmdBuffer.drawIndexed(static_cast<std::uint32_t>(subMesh->GetNumberOfIndices()), 1, static_cast<std::uint32_t>(subMesh->GetIndexOffset()), 0, 0); } void Mesh::SetVertexBuffer(const DeviceBuffer* vtxBuffer, std::size_t offset) { vertexBuffer_.first = vtxBuffer; vertexBuffer_.second = offset; } void Mesh::SetIndexBuffer(const DeviceBuffer* idxBuffer, std::size_t offset) { indexBuffer_.first = idxBuffer; indexBuffer_.second = offset; } void Mesh::SetMaterialBuffer(const DeviceBuffer* matBuffer, std::size_t offset, std::size_t elementSize) { materialBuffer_ = std::make_tuple(matBuffer, offset, elementSize); } } <|endoftext|>
<commit_before>#include "Runtime/World/CScriptDamageableTrigger.hpp" #include "Runtime/CStateManager.hpp" #include "Runtime/World/CActorParameters.hpp" #include "Runtime/World/CScriptActor.hpp" #include "Runtime/World/CWorld.hpp" #include "TCastTo.hpp" // Generated file, do not modify include path namespace urde { static CActorParameters MakeDamageableTriggerActorParms(const CActorParameters& aParams, const CVisorParameters& vParams) { CActorParameters ret = aParams; ret.SetVisorParameters(vParams); return ret; } static constexpr CMaterialList MakeDamageableTriggerMaterial(CScriptDamageableTrigger::ECanOrbit canOrbit) { if (canOrbit == CScriptDamageableTrigger::ECanOrbit::Orbit) { return CMaterialList(EMaterialTypes::Orbit, EMaterialTypes::Trigger, EMaterialTypes::Immovable, EMaterialTypes::NonSolidDamageable, EMaterialTypes::ExcludeFromLineOfSightTest); } return CMaterialList(EMaterialTypes::Trigger, EMaterialTypes::Immovable, EMaterialTypes::NonSolidDamageable, EMaterialTypes::ExcludeFromLineOfSightTest); } CScriptDamageableTrigger::CScriptDamageableTrigger(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CVector3f& position, const zeus::CVector3f& extent, const CHealthInfo& hInfo, const CDamageVulnerability& dVuln, u32 faceFlag, CAssetId patternTex1, CAssetId patternTex2, CAssetId colorTex, ECanOrbit canOrbit, bool active, const CVisorParameters& vParams) : CActor(uid, active, name, info, zeus::CTransform::Translate(position), CModelData::CModelDataNull(), MakeDamageableTriggerMaterial(canOrbit), MakeDamageableTriggerActorParms(CActorParameters::None(), vParams), kInvalidUniqueId) , x14c_bounds(-extent * 0.5f, extent * 0.5f) , x164_origHInfo(hInfo) , x16c_hInfo(hInfo) , x174_dVuln(dVuln) , x1dc_faceFlag(faceFlag) , x254_fluidPlane(patternTex1, patternTex2, colorTex, 1.f, 2, EFluidType::NormalWater, 1.f, CFluidUVMotion(6.f, 0.f)) , x300_28_canOrbit(canOrbit == ECanOrbit::Orbit) { if (x1dc_faceFlag & 0x1) { x244_faceTranslate = zeus::CVector3f(0.f, x14c_bounds.max.y(), 0.f); x1e4_faceDir = zeus::CTransform::RotateX(-M_PIF / 2.f); } else if (x1dc_faceFlag & 0x2) { x244_faceTranslate = zeus::CVector3f(0.f, x14c_bounds.min.y(), 0.f); x1e4_faceDir = zeus::CTransform::RotateX(M_PIF / 2.f); } else if (x1dc_faceFlag & 0x4) { x244_faceTranslate = zeus::CVector3f(x14c_bounds.min.x(), 0.f, 0.f); x1e4_faceDir = zeus::CTransform::RotateY(-M_PIF / 2.f); } else if (x1dc_faceFlag & 0x8) { x244_faceTranslate = zeus::CVector3f(x14c_bounds.max.x(), 0.f, 0.f); x1e4_faceDir = zeus::CTransform::RotateY(M_PIF / 2.f); } else if (x1dc_faceFlag & 0x10) { x244_faceTranslate = zeus::CVector3f(0.f, 0.f, x14c_bounds.max.z()); x1e4_faceDir = zeus::CTransform(); } else if (x1dc_faceFlag & 0x20) { x244_faceTranslate = zeus::CVector3f(0.f, 0.f, x14c_bounds.min.z()); x1e4_faceDir = zeus::CTransform::RotateY(M_PIF); } x214_faceDirInv = x1e4_faceDir.inverse(); } void CScriptDamageableTrigger::Accept(IVisitor& visitor) { visitor.Visit(this); } void CScriptDamageableTrigger::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId sender, CStateManager& mgr) { switch (msg) { case EScriptObjectMessage::Deactivate: if (x30_24_active && x300_25_alphaOut) return; [[fallthrough]]; case EScriptObjectMessage::Activate: if (!x30_24_active || x300_25_alphaOut) { x250_alphaTimer = 0.f; x16c_hInfo = x164_origHInfo; x300_25_alphaOut = false; if (x300_28_canOrbit) AddMaterial(EMaterialTypes::Orbit, mgr); SetLinkedObjectAlpha(0.f, mgr); x1e0_alpha = 0.f; } break; case EScriptObjectMessage::Damage: if (x300_27_invulnerable) x16c_hInfo = x164_origHInfo; break; case EScriptObjectMessage::Increment: x300_27_invulnerable = true; break; case EScriptObjectMessage::Decrement: x300_27_invulnerable = false; break; default: break; } CActor::AcceptScriptMsg(msg, sender, mgr); } EWeaponCollisionResponseTypes CScriptDamageableTrigger::GetCollisionResponseType(const zeus::CVector3f&, const zeus::CVector3f&, const CWeaponMode& weapMode, EProjectileAttrib) const { return x174_dVuln.WeaponHurts(weapMode, false) ? EWeaponCollisionResponseTypes::OtherProjectile : EWeaponCollisionResponseTypes::Unknown15; } void CScriptDamageableTrigger::Render(CStateManager& mgr) { if (x30_24_active && x1dc_faceFlag != 0 && std::fabs(x1e0_alpha) >= 0.00001f) { zeus::CAABox aabb = x14c_bounds.getTransformedAABox(x214_faceDirInv); zeus::CTransform xf = x34_transform * zeus::CTransform::Translate(x244_faceTranslate) * x1e4_faceDir; x254_fluidPlane.Render(mgr, x1e0_alpha, aabb, xf, zeus::CTransform(), false, xe8_frustum, {}, kInvalidUniqueId, nullptr, 0, 0, zeus::skZero3f); } CActor::Render(mgr); } void CScriptDamageableTrigger::AddToRenderer(const zeus::CFrustum& /*frustum*/, CStateManager& mgr) { if (x300_26_outOfFrustum) { return; } EnsureRendered(mgr, GetTranslation() - x244_faceTranslate, GetSortingBounds(mgr)); } void CScriptDamageableTrigger::PreRender(CStateManager& mgr, const zeus::CFrustum& frustum) { x300_26_outOfFrustum = !frustum.aabbFrustumTest(x14c_bounds.getTransformedAABox(x34_transform)); if (!x300_26_outOfFrustum) { xe8_frustum = frustum; CActor::PreRender(mgr, frustum); } } void CScriptDamageableTrigger::SetLinkedObjectAlpha(float a, CStateManager& mgr) { for (const SConnection& conn : x20_conns) { if (conn.x0_state != EScriptObjectState::MaxReached || conn.x4_msg != EScriptObjectMessage::Activate) continue; if (TCastToPtr<CScriptActor> act = mgr.ObjectById(mgr.GetIdForScript(conn.x8_objId))) { if (!act->GetActive()) act->SetActive(true); act->SetDrawFlags(CModelFlags(5, 0, 3, zeus::CColor(1.f, a))); } } } float CScriptDamageableTrigger::GetPuddleAlphaScale() const { if (x250_alphaTimer <= 0.75f) { if (x300_25_alphaOut) return 1.f - x250_alphaTimer / 0.75f; return x250_alphaTimer / 0.75f; } if (x300_25_alphaOut) return 0.f; return 1.f; } void CScriptDamageableTrigger::Think(float dt, CStateManager& mgr) { if (!GetActive()) return; const CGameArea* area = mgr.GetWorld()->GetAreaAlways(GetAreaIdAlways()); CGameArea::EOcclusionState occState = area->IsPostConstructed() ? area->GetOcclusionState() : CGameArea::EOcclusionState::Occluded; x300_24_notOccluded = occState == CGameArea::EOcclusionState::Visible; if (x300_25_alphaOut) { if (x250_alphaTimer >= 0.75f) { SetActive(false); for (const SConnection& conn : x20_conns) { if (conn.x0_state != EScriptObjectState::MaxReached || conn.x4_msg != EScriptObjectMessage::Activate) continue; if (TCastToPtr<CScriptActor> act = mgr.ObjectById(mgr.GetIdForScript(conn.x8_objId))) act->SetActive(false); } SetLinkedObjectAlpha(0.f, mgr); x300_25_alphaOut = false; return; } } else if (x16c_hInfo.GetHP() <= 0.f && x30_24_active) { SendScriptMsgs(EScriptObjectState::Dead, mgr, EScriptObjectMessage::None); RemoveMaterial(EMaterialTypes::Orbit, mgr); x300_25_alphaOut = true; x250_alphaTimer = 0.f; } if (x250_alphaTimer <= 0.75f) x250_alphaTimer += dt; float objAlpha = GetPuddleAlphaScale(); x1e0_alpha = 0.2f * objAlpha; SetLinkedObjectAlpha(objAlpha, mgr); } std::optional<zeus::CAABox> CScriptDamageableTrigger::GetTouchBounds() const { if (x30_24_active && x300_24_notOccluded) { return zeus::CAABox(x14c_bounds.min + GetTranslation(), x14c_bounds.max + GetTranslation()); } return std::nullopt; } } // namespace urde <commit_msg>CScriptDamageableTrigger: Brace conditions where applicable<commit_after>#include "Runtime/World/CScriptDamageableTrigger.hpp" #include "Runtime/CStateManager.hpp" #include "Runtime/World/CActorParameters.hpp" #include "Runtime/World/CScriptActor.hpp" #include "Runtime/World/CWorld.hpp" #include "TCastTo.hpp" // Generated file, do not modify include path namespace urde { static CActorParameters MakeDamageableTriggerActorParms(const CActorParameters& aParams, const CVisorParameters& vParams) { CActorParameters ret = aParams; ret.SetVisorParameters(vParams); return ret; } static constexpr CMaterialList MakeDamageableTriggerMaterial(CScriptDamageableTrigger::ECanOrbit canOrbit) { if (canOrbit == CScriptDamageableTrigger::ECanOrbit::Orbit) { return CMaterialList(EMaterialTypes::Orbit, EMaterialTypes::Trigger, EMaterialTypes::Immovable, EMaterialTypes::NonSolidDamageable, EMaterialTypes::ExcludeFromLineOfSightTest); } return CMaterialList(EMaterialTypes::Trigger, EMaterialTypes::Immovable, EMaterialTypes::NonSolidDamageable, EMaterialTypes::ExcludeFromLineOfSightTest); } CScriptDamageableTrigger::CScriptDamageableTrigger(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CVector3f& position, const zeus::CVector3f& extent, const CHealthInfo& hInfo, const CDamageVulnerability& dVuln, u32 faceFlag, CAssetId patternTex1, CAssetId patternTex2, CAssetId colorTex, ECanOrbit canOrbit, bool active, const CVisorParameters& vParams) : CActor(uid, active, name, info, zeus::CTransform::Translate(position), CModelData::CModelDataNull(), MakeDamageableTriggerMaterial(canOrbit), MakeDamageableTriggerActorParms(CActorParameters::None(), vParams), kInvalidUniqueId) , x14c_bounds(-extent * 0.5f, extent * 0.5f) , x164_origHInfo(hInfo) , x16c_hInfo(hInfo) , x174_dVuln(dVuln) , x1dc_faceFlag(faceFlag) , x254_fluidPlane(patternTex1, patternTex2, colorTex, 1.f, 2, EFluidType::NormalWater, 1.f, CFluidUVMotion(6.f, 0.f)) , x300_28_canOrbit(canOrbit == ECanOrbit::Orbit) { if (x1dc_faceFlag & 0x1) { x244_faceTranslate = zeus::CVector3f(0.f, x14c_bounds.max.y(), 0.f); x1e4_faceDir = zeus::CTransform::RotateX(-M_PIF / 2.f); } else if (x1dc_faceFlag & 0x2) { x244_faceTranslate = zeus::CVector3f(0.f, x14c_bounds.min.y(), 0.f); x1e4_faceDir = zeus::CTransform::RotateX(M_PIF / 2.f); } else if (x1dc_faceFlag & 0x4) { x244_faceTranslate = zeus::CVector3f(x14c_bounds.min.x(), 0.f, 0.f); x1e4_faceDir = zeus::CTransform::RotateY(-M_PIF / 2.f); } else if (x1dc_faceFlag & 0x8) { x244_faceTranslate = zeus::CVector3f(x14c_bounds.max.x(), 0.f, 0.f); x1e4_faceDir = zeus::CTransform::RotateY(M_PIF / 2.f); } else if (x1dc_faceFlag & 0x10) { x244_faceTranslate = zeus::CVector3f(0.f, 0.f, x14c_bounds.max.z()); x1e4_faceDir = zeus::CTransform(); } else if (x1dc_faceFlag & 0x20) { x244_faceTranslate = zeus::CVector3f(0.f, 0.f, x14c_bounds.min.z()); x1e4_faceDir = zeus::CTransform::RotateY(M_PIF); } x214_faceDirInv = x1e4_faceDir.inverse(); } void CScriptDamageableTrigger::Accept(IVisitor& visitor) { visitor.Visit(this); } void CScriptDamageableTrigger::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId sender, CStateManager& mgr) { switch (msg) { case EScriptObjectMessage::Deactivate: if (x30_24_active && x300_25_alphaOut) { return; } [[fallthrough]]; case EScriptObjectMessage::Activate: if (!x30_24_active || x300_25_alphaOut) { x250_alphaTimer = 0.f; x16c_hInfo = x164_origHInfo; x300_25_alphaOut = false; if (x300_28_canOrbit) { AddMaterial(EMaterialTypes::Orbit, mgr); } SetLinkedObjectAlpha(0.f, mgr); x1e0_alpha = 0.f; } break; case EScriptObjectMessage::Damage: if (x300_27_invulnerable) { x16c_hInfo = x164_origHInfo; } break; case EScriptObjectMessage::Increment: x300_27_invulnerable = true; break; case EScriptObjectMessage::Decrement: x300_27_invulnerable = false; break; default: break; } CActor::AcceptScriptMsg(msg, sender, mgr); } EWeaponCollisionResponseTypes CScriptDamageableTrigger::GetCollisionResponseType(const zeus::CVector3f&, const zeus::CVector3f&, const CWeaponMode& weapMode, EProjectileAttrib) const { return x174_dVuln.WeaponHurts(weapMode, false) ? EWeaponCollisionResponseTypes::OtherProjectile : EWeaponCollisionResponseTypes::Unknown15; } void CScriptDamageableTrigger::Render(CStateManager& mgr) { if (x30_24_active && x1dc_faceFlag != 0 && std::fabs(x1e0_alpha) >= 0.00001f) { const zeus::CAABox aabb = x14c_bounds.getTransformedAABox(x214_faceDirInv); const zeus::CTransform xf = x34_transform * zeus::CTransform::Translate(x244_faceTranslate) * x1e4_faceDir; x254_fluidPlane.Render(mgr, x1e0_alpha, aabb, xf, zeus::CTransform(), false, xe8_frustum, {}, kInvalidUniqueId, nullptr, 0, 0, zeus::skZero3f); } CActor::Render(mgr); } void CScriptDamageableTrigger::AddToRenderer(const zeus::CFrustum& /*frustum*/, CStateManager& mgr) { if (x300_26_outOfFrustum) { return; } EnsureRendered(mgr, GetTranslation() - x244_faceTranslate, GetSortingBounds(mgr)); } void CScriptDamageableTrigger::PreRender(CStateManager& mgr, const zeus::CFrustum& frustum) { x300_26_outOfFrustum = !frustum.aabbFrustumTest(x14c_bounds.getTransformedAABox(x34_transform)); if (x300_26_outOfFrustum) { return; } xe8_frustum = frustum; CActor::PreRender(mgr, frustum); } void CScriptDamageableTrigger::SetLinkedObjectAlpha(float a, CStateManager& mgr) { for (const SConnection& conn : x20_conns) { if (conn.x0_state != EScriptObjectState::MaxReached || conn.x4_msg != EScriptObjectMessage::Activate) { continue; } if (const TCastToPtr<CScriptActor> act = mgr.ObjectById(mgr.GetIdForScript(conn.x8_objId))) { if (!act->GetActive()) { act->SetActive(true); } act->SetDrawFlags(CModelFlags(5, 0, 3, zeus::CColor(1.f, a))); } } } float CScriptDamageableTrigger::GetPuddleAlphaScale() const { if (x250_alphaTimer <= 0.75f) { if (x300_25_alphaOut) { return 1.f - x250_alphaTimer / 0.75f; } return x250_alphaTimer / 0.75f; } if (x300_25_alphaOut) { return 0.f; } return 1.f; } void CScriptDamageableTrigger::Think(float dt, CStateManager& mgr) { if (!GetActive()) { return; } const CGameArea* area = mgr.GetWorld()->GetAreaAlways(GetAreaIdAlways()); const auto occState = area->IsPostConstructed() ? area->GetOcclusionState() : CGameArea::EOcclusionState::Occluded; x300_24_notOccluded = occState == CGameArea::EOcclusionState::Visible; if (x300_25_alphaOut) { if (x250_alphaTimer >= 0.75f) { SetActive(false); for (const SConnection& conn : x20_conns) { if (conn.x0_state != EScriptObjectState::MaxReached || conn.x4_msg != EScriptObjectMessage::Activate) { continue; } if (const TCastToPtr<CScriptActor> act = mgr.ObjectById(mgr.GetIdForScript(conn.x8_objId))) { act->SetActive(false); } } SetLinkedObjectAlpha(0.f, mgr); x300_25_alphaOut = false; return; } } else if (x16c_hInfo.GetHP() <= 0.f && x30_24_active) { SendScriptMsgs(EScriptObjectState::Dead, mgr, EScriptObjectMessage::None); RemoveMaterial(EMaterialTypes::Orbit, mgr); x300_25_alphaOut = true; x250_alphaTimer = 0.f; } if (x250_alphaTimer <= 0.75f) { x250_alphaTimer += dt; } const float objAlpha = GetPuddleAlphaScale(); x1e0_alpha = 0.2f * objAlpha; SetLinkedObjectAlpha(objAlpha, mgr); } std::optional<zeus::CAABox> CScriptDamageableTrigger::GetTouchBounds() const { if (x30_24_active && x300_24_notOccluded) { return zeus::CAABox(x14c_bounds.min + GetTranslation(), x14c_bounds.max + GetTranslation()); } return std::nullopt; } } // namespace urde <|endoftext|>
<commit_before>/* * Copyright (C) 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 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 name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "WebKitPrefix.h" <commit_msg>Touch precompiled header wrapper to fix build.<commit_after>/* * Copyright (C) 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 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 name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "WebKitPrefix.h" <|endoftext|>
<commit_before>#include <ast/all.hh> #include <ast/new-clone.hh> #include <ast/parametric-ast.hh> #include <object/symbols.hh> #include <parser/ast-factory.hh> #include <parser/parse.hh> #include <parser/parse-result.hh> namespace std { ostream& operator<< (ostream& o, const parser::case_type& c) { return o << "/* " << (void*) &c << " */ " << "case " << libport::deref << c.first << " => " << libport::deref << c.second; } ostream& operator<< (ostream& o, const parser::cases_type& cs) { o << "/* " << (void*) &cs << " */ " << "{" << endl; foreach (const parser::case_type& c, cs) o << " " << c << endl; return o << "}"; } } namespace parser { using ast::ParametricAst; ast::rExp ast_at(const yy::location& loc, ast::rExp cond, ast::rExp at, ast::rExp onleave, ast::rExp duration) { if (!onleave) onleave = new ast::Noop(loc, 0); if (duration) { static ast::ParametricAst desugar( "var '$at' = persist(%exp:1, %exp:2) |" "at ('$at') %exp:3 onleave %exp:4"); return exp(desugar % cond % duration % at % onleave); } else { static ast::ParametricAst desugar( "Control.at_(%exp:1, detach(%exp:2), detach(%exp:3))"); return exp(desugar % cond % at % onleave); } } ast::rExp ast_at_event(const ast::loc& loc, ast::rExp event, ast::rExp payload, ast::rExp at, ast::rExp onleave) { if (!onleave) onleave = new ast::Noop(loc, 0); static ast::ParametricAst desugar( "detach(" "{" " %exp:1.onEvent(closure ('$at')" " {" " if (Pattern.new(%exp:2).match('$at'.payload))" " {" " %exp:3 |" " waituntil(!'$at'.active) |" " %exp:4" " }" " })" "})"); return exp(desugar % event % payload % at % onleave); } ast::rExp ast_whenever_event(const ast::loc& loc, ast::rExp event, ast::rExp payload, ast::rExp body, ast::rExp onleave) { if (!onleave) onleave = new ast::Noop(loc, 0); static ast::ParametricAst desugar( "detach(" "{" "%exp:1.onEvent(" " closure ('$whenever')" " {" " if (Pattern.new(%exp:2).match('$whenever'.payload))" " detach(" " {" " while (true)" " {" " %exp:3 |" " if(!'$whenever'.active)" " break" " } |" " %exp:4" " })" " })" "})"); return exp(desugar % event % payload % body % onleave); } /// Create a new Tree node composing \c Lhs and \c Rhs with \c Op. /// \param op must be & or |. ast::rExp ast_bin(const yy::location& l, ast::flavor_type op, ast::rExp lhs, ast::rExp rhs) { ast::rExp res = 0; assert (lhs); assert (rhs); switch (op) { case ast::flavor_pipe: { ast::rPipe pipe; if (pipe = lhs.unsafe_cast<ast::Pipe>()) pipe->children_get().push_back(rhs); else { pipe = new ast::Pipe(l, ast::exps_type()); pipe->children_get().push_back(lhs); pipe->children_get().push_back(rhs); } res = pipe; break; } case ast::flavor_and: { ast::rAnd rand; if (rand = lhs.unsafe_cast<ast::And>()) rand->children_get().push_back(rhs); else { rand = new ast::And(l, ast::exps_type()); rand->children_get().push_back(lhs); rand->children_get().push_back(rhs); } res = rand; break; } case ast::flavor_comma: case ast::flavor_semicolon: { ast::rNary nary = new ast::Nary(l); nary->push_back(lhs, op); nary->push_back(rhs); res = nary; break; } case ast::flavor_none: pabort(op); } return res; } /// "<method> (args)". ast::rCall ast_call (const yy::location& l, libport::Symbol method) { return ast_call(l, new ast::Implicit(l), method); } /// "<target> . <method> (args)". ast::rCall ast_call (const yy::location& l, ast::rExp target, libport::Symbol method, ast::exps_type* args) { return new ast::Call(l, args, target, method); } /// "<target> . <method> ()". ast::rCall ast_call(const yy::location& l, ast::rExp target, libport::Symbol method) { return ast_call(l, target, method, 0); } /// "<target> . <method> (<arg1>)". ast::rCall ast_call(const yy::location& l, ast::rExp target, libport::Symbol method, ast::rExp arg1) { ast::rCall res = ast_call(l, target, method, new ast::exps_type); res->arguments_get()->push_back(arg1); return res; } /// "<target> . <method> (<arg1>, <arg2>)". /// "<target> . <method> (<arg1>, <arg2>, <arg3>)". ast::rCall ast_call(const yy::location& l, ast::rExp target, libport::Symbol method, ast::rExp arg1, ast::rExp arg2, ast::rExp arg3) { ast::rCall res = ast_call(l, target, method, new ast::exps_type); res->arguments_get()->push_back(arg1); res->arguments_get()->push_back(arg2); if (arg3) res->arguments_get()->push_back(arg3); return res; } ast::rExp ast_closure(ast::rExp value) { static ast::ParametricAst a("closure () { %exp:1 }"); return exp(a % value); } /// Build a for loop. // Since we don't have "continue", for is really a sugared // while: // // "for OP ( INIT; TEST; INC ) BODY" // // -> // // "{ INIT OP WHILE OP (TEST) { BODY | INC } }" // // OP is either ";" or "|". ast::rExp ast_for (const yy::location& l, ast::flavor_type op, ast::rExp init, ast::rExp test, ast::rExp inc, ast::rExp body) { passert(op, op == ast::flavor_pipe || op == ast::flavor_semicolon); assert(init); assert(test); assert(inc); assert(body); // BODY | INC. ast::rExp loop_body = ast_bin(l, ast::flavor_pipe, body, inc); // WHILE OP (TEST) { BODY | INC }. ast::While *while_loop = new ast::While(l, op, test, ast_scope(l, loop_body)); // { INIT OP WHILE OP (TEST) { BODY | INC } }. return ast_scope(l, ast_bin(l, op, init, while_loop)); } /// Return \a e in a ast::Scope unless it is already one. ast::rScope ast_scope(const yy::location& l, ast::rExp target, ast::rExp e) { if (ast::rScope res = e.unsafe_cast<ast::Scope>()) return res; else if (target) return new ast::Do(l, e, target); else return new ast::Scope(l, e); } ast::rScope ast_scope(const yy::location& l, ast::rExp e) { return ast_scope(l, 0, e); } ast::rExp ast_string(const yy::location& l, libport::Symbol s) { return new ast::String(l, s); } ast::rExp ast_switch(const yy::location& l, ast::rExp cond, const cases_type& cases) { (void) l; static ast::ParametricAst nil("nil"); ast::rExp inner = exp(nil); rforeach (const case_type& c, cases) { static ast::ParametricAst a( "if (Pattern.new(%exp:1).match('$switch')) %exp:2 else %exp:3"); a % c.first % c.second % inner; inner = ast::exp(a); } static ParametricAst sw("{ var '$switch' = %exp:1 | %exp:2 }"); return exp(sw % cond % inner); } ast::rLValue ast_lvalue_once(const ast::rLValue& lvalue) { ast::rCall tmp = ast_call(lvalue->location_get(), SYMBOL($tmp)); if (lvalue->call()->target_implicit()) return lvalue.get(); else return ast_call(lvalue->location_get(), tmp, lvalue->call()->name_get()); } ast::rExp ast_lvalue_wrap(const ast::rLValue& lvalue, const ast::rExp& e) { static ParametricAst wrap( "{" "var '$tmp' = %exp:1;" "%exp:2;" "}" ); if (lvalue->call()->target_implicit()) return e; else { wrap % lvalue->call()->target_get() % e; return exp(wrap); } } } <commit_msg>Fix for loop desugaring: execute the increment on `continue'.<commit_after>#include <ast/all.hh> #include <ast/new-clone.hh> #include <ast/parametric-ast.hh> #include <object/symbols.hh> #include <parser/ast-factory.hh> #include <parser/parse.hh> #include <parser/parse-result.hh> namespace std { ostream& operator<< (ostream& o, const parser::case_type& c) { return o << "/* " << (void*) &c << " */ " << "case " << libport::deref << c.first << " => " << libport::deref << c.second; } ostream& operator<< (ostream& o, const parser::cases_type& cs) { o << "/* " << (void*) &cs << " */ " << "{" << endl; foreach (const parser::case_type& c, cs) o << " " << c << endl; return o << "}"; } } namespace parser { using ast::ParametricAst; ast::rExp ast_at(const yy::location& loc, ast::rExp cond, ast::rExp at, ast::rExp onleave, ast::rExp duration) { if (!onleave) onleave = new ast::Noop(loc, 0); if (duration) { static ast::ParametricAst desugar( "var '$at' = persist(%exp:1, %exp:2) |" "at ('$at') %exp:3 onleave %exp:4"); return exp(desugar % cond % duration % at % onleave); } else { static ast::ParametricAst desugar( "Control.at_(%exp:1, detach(%exp:2), detach(%exp:3))"); return exp(desugar % cond % at % onleave); } } ast::rExp ast_at_event(const ast::loc& loc, ast::rExp event, ast::rExp payload, ast::rExp at, ast::rExp onleave) { if (!onleave) onleave = new ast::Noop(loc, 0); static ast::ParametricAst desugar( "detach(" "{" " %exp:1.onEvent(closure ('$at')" " {" " if (Pattern.new(%exp:2).match('$at'.payload))" " {" " %exp:3 |" " waituntil(!'$at'.active) |" " %exp:4" " }" " })" "})"); return exp(desugar % event % payload % at % onleave); } ast::rExp ast_whenever_event(const ast::loc& loc, ast::rExp event, ast::rExp payload, ast::rExp body, ast::rExp onleave) { if (!onleave) onleave = new ast::Noop(loc, 0); static ast::ParametricAst desugar( "detach(" "{" "%exp:1.onEvent(" " closure ('$whenever')" " {" " if (Pattern.new(%exp:2).match('$whenever'.payload))" " detach(" " {" " while (true)" " {" " %exp:3 |" " if(!'$whenever'.active)" " break" " } |" " %exp:4" " })" " })" "})"); return exp(desugar % event % payload % body % onleave); } /// Create a new Tree node composing \c Lhs and \c Rhs with \c Op. /// \param op must be & or |. ast::rExp ast_bin(const yy::location& l, ast::flavor_type op, ast::rExp lhs, ast::rExp rhs) { ast::rExp res = 0; assert (lhs); assert (rhs); switch (op) { case ast::flavor_pipe: { ast::rPipe pipe; if (pipe = lhs.unsafe_cast<ast::Pipe>()) pipe->children_get().push_back(rhs); else { pipe = new ast::Pipe(l, ast::exps_type()); pipe->children_get().push_back(lhs); pipe->children_get().push_back(rhs); } res = pipe; break; } case ast::flavor_and: { ast::rAnd rand; if (rand = lhs.unsafe_cast<ast::And>()) rand->children_get().push_back(rhs); else { rand = new ast::And(l, ast::exps_type()); rand->children_get().push_back(lhs); rand->children_get().push_back(rhs); } res = rand; break; } case ast::flavor_comma: case ast::flavor_semicolon: { ast::rNary nary = new ast::Nary(l); nary->push_back(lhs, op); nary->push_back(rhs); res = nary; break; } case ast::flavor_none: pabort(op); } return res; } /// "<method> (args)". ast::rCall ast_call (const yy::location& l, libport::Symbol method) { return ast_call(l, new ast::Implicit(l), method); } /// "<target> . <method> (args)". ast::rCall ast_call (const yy::location& l, ast::rExp target, libport::Symbol method, ast::exps_type* args) { return new ast::Call(l, args, target, method); } /// "<target> . <method> ()". ast::rCall ast_call(const yy::location& l, ast::rExp target, libport::Symbol method) { return ast_call(l, target, method, 0); } /// "<target> . <method> (<arg1>)". ast::rCall ast_call(const yy::location& l, ast::rExp target, libport::Symbol method, ast::rExp arg1) { ast::rCall res = ast_call(l, target, method, new ast::exps_type); res->arguments_get()->push_back(arg1); return res; } /// "<target> . <method> (<arg1>, <arg2>)". /// "<target> . <method> (<arg1>, <arg2>, <arg3>)". ast::rCall ast_call(const yy::location& l, ast::rExp target, libport::Symbol method, ast::rExp arg1, ast::rExp arg2, ast::rExp arg3) { ast::rCall res = ast_call(l, target, method, new ast::exps_type); res->arguments_get()->push_back(arg1); res->arguments_get()->push_back(arg2); if (arg3) res->arguments_get()->push_back(arg3); return res; } ast::rExp ast_closure(ast::rExp value) { static ast::ParametricAst a("closure () { %exp:1 }"); return exp(a % value); } /// Build a for loop. // The increment is included directly in the condition to make sure // it is executed on `continue'. ast::rExp ast_for (const yy::location&, ast::flavor_type, ast::rExp init, ast::rExp test, ast::rExp inc, ast::rExp body) { // FIXME: for| is handled as a simple for static ParametricAst desugar( "{" " %exp:1 |" " var '$tmp-for-first' = true |" " while ({ if ('$tmp-for-first') '$tmp-for-first' = false else %exp:2 | %exp:3})" " %exp:4 |" "}" ); desugar % init % inc % test % body; return exp(desugar); } /// Return \a e in a ast::Scope unless it is already one. ast::rScope ast_scope(const yy::location& l, ast::rExp target, ast::rExp e) { if (ast::rScope res = e.unsafe_cast<ast::Scope>()) return res; else if (target) return new ast::Do(l, e, target); else return new ast::Scope(l, e); } ast::rScope ast_scope(const yy::location& l, ast::rExp e) { return ast_scope(l, 0, e); } ast::rExp ast_string(const yy::location& l, libport::Symbol s) { return new ast::String(l, s); } ast::rExp ast_switch(const yy::location& l, ast::rExp cond, const cases_type& cases) { (void) l; static ast::ParametricAst nil("nil"); ast::rExp inner = exp(nil); rforeach (const case_type& c, cases) { static ast::ParametricAst a( "if (Pattern.new(%exp:1).match('$switch')) %exp:2 else %exp:3"); a % c.first % c.second % inner; inner = ast::exp(a); } static ParametricAst sw("{ var '$switch' = %exp:1 | %exp:2 }"); return exp(sw % cond % inner); } ast::rLValue ast_lvalue_once(const ast::rLValue& lvalue) { ast::rCall tmp = ast_call(lvalue->location_get(), SYMBOL($tmp)); if (lvalue->call()->target_implicit()) return lvalue.get(); else return ast_call(lvalue->location_get(), tmp, lvalue->call()->name_get()); } ast::rExp ast_lvalue_wrap(const ast::rLValue& lvalue, const ast::rExp& e) { static ParametricAst wrap( "{" "var '$tmp' = %exp:1;" "%exp:2;" "}" ); if (lvalue->call()->target_implicit()) return e; else { wrap % lvalue->call()->target_get() % e; return exp(wrap); } } } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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 "chrome/browser/views/info_bubble.h" #include "app/gfx/canvas.h" #include "app/gfx/color_utils.h" #include "app/gfx/path.h" #include "chrome/browser/window_sizer.h" #include "chrome/common/notification_service.h" #include "third_party/skia/include/core/SkPaint.h" #include "views/fill_layout.h" #include "views/widget/root_view.h" #include "views/window/window.h" namespace { // Background color of the bubble. #if defined(OS_WIN) const SkColor kBackgroundColor = color_utils::GetSysSkColor(COLOR_WINDOW); #else // TODO(beng): source from theme provider. const SkColor kBackgroundColor = SK_ColorWHITE; #endif } // BorderContents ------------------------------------------------------------- // This is used to paint the border of the InfoBubble. Windows uses this via // BorderWidget (see below), while others can use it directly in the bubble. class BorderContents : public views::View { public: BorderContents() { } // Given the size of the contents and the rect to point at, initializes the // bubble and returns the bounds of both the border // and the contents inside the bubble. // |is_rtl| is true if the UI is RTL and thus the arrow should default to the // right side of the bubble; otherwise it defaults to the left top corner, and // then is moved as necessary to try and fit the whole bubble on the same // monitor as the rect being pointed to. // // TODO(pkasting): Maybe this should use mirroring transformations instead, // which would hopefully simplify this code. void InitAndGetBounds( const gfx::Rect& position_relative_to, // In screen coordinates const gfx::Size& contents_size, bool is_rtl, gfx::Rect* contents_bounds, // Returned in window coordinates gfx::Rect* window_bounds); // Returned in screen coordinates private: virtual ~BorderContents() { } // Overridden from View: virtual void Paint(gfx::Canvas* canvas); DISALLOW_COPY_AND_ASSIGN(BorderContents); }; void BorderContents::InitAndGetBounds( const gfx::Rect& position_relative_to, const gfx::Size& contents_size, bool is_rtl, gfx::Rect* contents_bounds, gfx::Rect* window_bounds) { // Margins between the contents and the inside of the border, in pixels. const int kLeftMargin = 6; const int kTopMargin = 6; const int kRightMargin = 6; const int kBottomMargin = 9; // Set the border. BubbleBorder* bubble_border = new BubbleBorder; set_border(bubble_border); bubble_border->set_background_color(kBackgroundColor); // Give the contents a margin. gfx::Size local_contents_size(contents_size); local_contents_size.Enlarge(kLeftMargin + kRightMargin, kTopMargin + kBottomMargin); // Try putting the arrow in its default location, and calculating the bounds. BubbleBorder::ArrowLocation arrow_location(is_rtl ? BubbleBorder::TOP_RIGHT : BubbleBorder::TOP_LEFT); bubble_border->set_arrow_location(arrow_location); *window_bounds = bubble_border->GetBounds(position_relative_to, local_contents_size); // See if those bounds will fit on the monitor. scoped_ptr<WindowSizer::MonitorInfoProvider> monitor_provider( WindowSizer::CreateDefaultMonitorInfoProvider()); gfx::Rect monitor_bounds( monitor_provider->GetMonitorWorkAreaMatching(position_relative_to)); if (!monitor_bounds.IsEmpty() && !monitor_bounds.Contains(*window_bounds)) { // The bounds don't fit. Move the arrow to try and improve things. bool arrow_on_left = (is_rtl ? (window_bounds->x() < monitor_bounds.x()) : (window_bounds->right() <= monitor_bounds.right())); if (window_bounds->bottom() > monitor_bounds.bottom()) { arrow_location = arrow_on_left ? BubbleBorder::BOTTOM_LEFT : BubbleBorder::BOTTOM_RIGHT; } else { arrow_location = arrow_on_left ? BubbleBorder::TOP_LEFT : BubbleBorder::TOP_RIGHT; } bubble_border->set_arrow_location(arrow_location); // Now get the recalculated bounds. *window_bounds = bubble_border->GetBounds(position_relative_to, local_contents_size); } // Calculate the bounds of the contained contents (in window coordinates) by // subtracting the border dimensions and margin amounts. *contents_bounds = gfx::Rect(gfx::Point(), window_bounds->size()); gfx::Insets insets; bubble_border->GetInsets(&insets); contents_bounds->Inset(insets.left() + kLeftMargin, insets.top() + kTopMargin, insets.right() + kRightMargin, insets.bottom() + kBottomMargin); } void BorderContents::Paint(gfx::Canvas* canvas) { // The border of this view creates an anti-aliased round-rect region for the // contents, which we need to fill with the background color. SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kFill_Style); paint.setColor(kBackgroundColor); gfx::Path path; gfx::Rect bounds(GetLocalBounds(false)); SkRect rect; rect.set(SkIntToScalar(bounds.x()), SkIntToScalar(bounds.y()), SkIntToScalar(bounds.right()), SkIntToScalar(bounds.bottom())); SkScalar radius = SkIntToScalar(BubbleBorder::GetCornerRadius()); path.addRoundRect(rect, radius, radius); canvas->drawPath(path, paint); // Now we paint the border, so it will be alpha-blended atop the contents. // This looks slightly better in the corners than drawing the contents atop // the border. PaintBorder(canvas); } #if defined(OS_WIN) // BorderWidget --------------------------------------------------------------- BorderWidget::BorderWidget() { set_delete_on_destroy(false); // Our owner will free us manually. set_window_style(WS_POPUP); set_window_ex_style(WS_EX_TOOLWINDOW | WS_EX_LAYERED); } gfx::Rect BorderWidget::InitAndGetBounds( HWND owner, const gfx::Rect& position_relative_to, const gfx::Size& contents_size, bool is_rtl) { // Set up the border view and ask it to calculate our bounds (and our // contents'). BorderContents* border_contents = new BorderContents; gfx::Rect contents_bounds, window_bounds; border_contents->InitAndGetBounds(position_relative_to, contents_size, is_rtl, &contents_bounds, &window_bounds); // Initialize ourselves. WidgetWin::Init(GetAncestor(owner, GA_ROOT), window_bounds); SetContentsView(border_contents); SetWindowPos(owner, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOREDRAW); // Chop a hole out of our region to show the contents through. // CreateRectRgn() expects (left, top, right, bottom) in window coordinates. HRGN contents_region = CreateRectRgn(contents_bounds.x(), contents_bounds.y(), contents_bounds.right(), contents_bounds.bottom()); HRGN window_region = CreateRectRgn(0, 0, window_bounds.width(), window_bounds.height()); CombineRgn(window_region, window_region, contents_region, RGN_XOR); DeleteObject(contents_region); SetWindowRgn(window_region, true); // Return |contents_bounds| in screen coordinates. contents_bounds.Offset(window_bounds.origin()); return contents_bounds; } LRESULT BorderWidget::OnMouseActivate(HWND window, UINT hit_test, UINT mouse_message) { // Never activate. return MA_NOACTIVATE; } #endif // InfoBubble ----------------------------------------------------------------- // static InfoBubble* InfoBubble::Show(views::Window* parent, const gfx::Rect& position_relative_to, views::View* contents, InfoBubbleDelegate* delegate) { InfoBubble* window = new InfoBubble; window->Init(parent, position_relative_to, contents, delegate); return window; } void InfoBubble::Close() { Close(false); } InfoBubble::InfoBubble() : #if defined(OS_LINUX) WidgetGtk(TYPE_POPUP), #endif delegate_(NULL), parent_(NULL), closed_(false) { } void InfoBubble::Init(views::Window* parent, const gfx::Rect& position_relative_to, views::View* contents, InfoBubbleDelegate* delegate) { parent_ = parent; parent_->DisableInactiveRendering(); delegate_ = delegate; // Create the main window. #if defined(OS_WIN) set_window_style(WS_POPUP | WS_CLIPCHILDREN); set_window_ex_style(WS_EX_TOOLWINDOW); WidgetWin::Init(parent->GetNativeWindow(), gfx::Rect()); #elif defined(OS_LINUX) MakeTransparent(); WidgetGtk::Init(GTK_WIDGET(parent->GetNativeWindow()), gfx::Rect()); #endif // Create a View to hold the contents of the main window. views::View* contents_view = new views::View; // Adding |contents| as a child has to be done before we call // contents->GetPreferredSize() below, since some supplied views don't // actually initialize themselves until they're added to a hierarchy. contents_view->AddChildView(contents); SetContentsView(contents_view); // Calculate and set the bounds for all windows and views. gfx::Rect window_bounds; #if defined(OS_WIN) border_.reset(new BorderWidget); // Initialize and position the border window. window_bounds = border_->InitAndGetBounds(GetNativeView(), position_relative_to, contents->GetPreferredSize(), contents->UILayoutIsRightToLeft()); // Make |contents| take up the entire contents view. contents_view->SetLayoutManager(new views::FillLayout); // Paint the background color behind the contents. contents_view->set_background( views::Background::CreateSolidBackground(kBackgroundColor)); #else // Create a view to paint the border and background. BorderContents* border_contents = new BorderContents; gfx::Rect contents_bounds; border_contents->InitAndGetBounds(position_relative_to, contents->GetPreferredSize(), is_rtl, &contents_bounds, &window_bounds); // This new view must be added before |contents| so it will paint under it. contents_view->AddChildView(border_contents, 0); // |contents_view| has no layout manager, so we have to explicitly position // its children. border_contents->SetBounds(gfx::Rect(gfx::Point(), window_bounds.size())); contents->SetBounds(contents_bounds); #endif SetBounds(window_bounds); #if defined(OS_WIN) // Register the Escape accelerator for closing. GetFocusManager()->RegisterAccelerator( views::Accelerator(VK_ESCAPE, false, false, false), this); #endif // Done creating the bubble. NotificationService::current()->Notify(NotificationType::INFO_BUBBLE_CREATED, Source<InfoBubble>(this), NotificationService::NoDetails()); // Show the window. #if defined(OS_WIN) border_->ShowWindow(SW_SHOW); ShowWindow(SW_SHOW); #elif defined(OS_LINUX) views::WidgetGtk::Show(); #endif } #if defined(OS_WIN) void InfoBubble::OnActivate(UINT action, BOOL minimized, HWND window) { // The popup should close when it is deactivated. if (action == WA_INACTIVE && !closed_) { Close(); } else if (action == WA_ACTIVE) { DCHECK(GetRootView()->GetChildViewCount() > 0); GetRootView()->GetChildViewAt(0)->RequestFocus(); } } #endif void InfoBubble::Close(bool closed_by_escape) { if (closed_) return; if (delegate_) delegate_->InfoBubbleClosing(this, closed_by_escape); closed_ = true; #if defined(OS_WIN) border_->Close(); WidgetWin::Close(); #elif defined(OS_LINUX) WidgetGtk::Close(); #endif } bool InfoBubble::AcceleratorPressed(const views::Accelerator& accelerator) { if (!delegate_ || delegate_->CloseOnEscape()) { Close(true); return true; } return false; } <commit_msg>Fix the Linux Views build, sigh. We need a trybot.<commit_after>// Copyright (c) 2006-2008 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 "chrome/browser/views/info_bubble.h" #include "app/gfx/canvas.h" #include "app/gfx/color_utils.h" #include "app/gfx/path.h" #include "chrome/browser/window_sizer.h" #include "chrome/common/notification_service.h" #include "third_party/skia/include/core/SkPaint.h" #include "views/fill_layout.h" #include "views/widget/root_view.h" #include "views/window/window.h" namespace { // Background color of the bubble. #if defined(OS_WIN) const SkColor kBackgroundColor = color_utils::GetSysSkColor(COLOR_WINDOW); #else // TODO(beng): source from theme provider. const SkColor kBackgroundColor = SK_ColorWHITE; #endif } // BorderContents ------------------------------------------------------------- // This is used to paint the border of the InfoBubble. Windows uses this via // BorderWidget (see below), while others can use it directly in the bubble. class BorderContents : public views::View { public: BorderContents() { } // Given the size of the contents and the rect to point at, initializes the // bubble and returns the bounds of both the border // and the contents inside the bubble. // |is_rtl| is true if the UI is RTL and thus the arrow should default to the // right side of the bubble; otherwise it defaults to the left top corner, and // then is moved as necessary to try and fit the whole bubble on the same // monitor as the rect being pointed to. // // TODO(pkasting): Maybe this should use mirroring transformations instead, // which would hopefully simplify this code. void InitAndGetBounds( const gfx::Rect& position_relative_to, // In screen coordinates const gfx::Size& contents_size, bool is_rtl, gfx::Rect* contents_bounds, // Returned in window coordinates gfx::Rect* window_bounds); // Returned in screen coordinates private: virtual ~BorderContents() { } // Overridden from View: virtual void Paint(gfx::Canvas* canvas); DISALLOW_COPY_AND_ASSIGN(BorderContents); }; void BorderContents::InitAndGetBounds( const gfx::Rect& position_relative_to, const gfx::Size& contents_size, bool is_rtl, gfx::Rect* contents_bounds, gfx::Rect* window_bounds) { // Margins between the contents and the inside of the border, in pixels. const int kLeftMargin = 6; const int kTopMargin = 6; const int kRightMargin = 6; const int kBottomMargin = 9; // Set the border. BubbleBorder* bubble_border = new BubbleBorder; set_border(bubble_border); bubble_border->set_background_color(kBackgroundColor); // Give the contents a margin. gfx::Size local_contents_size(contents_size); local_contents_size.Enlarge(kLeftMargin + kRightMargin, kTopMargin + kBottomMargin); // Try putting the arrow in its default location, and calculating the bounds. BubbleBorder::ArrowLocation arrow_location(is_rtl ? BubbleBorder::TOP_RIGHT : BubbleBorder::TOP_LEFT); bubble_border->set_arrow_location(arrow_location); *window_bounds = bubble_border->GetBounds(position_relative_to, local_contents_size); // See if those bounds will fit on the monitor. scoped_ptr<WindowSizer::MonitorInfoProvider> monitor_provider( WindowSizer::CreateDefaultMonitorInfoProvider()); gfx::Rect monitor_bounds( monitor_provider->GetMonitorWorkAreaMatching(position_relative_to)); if (!monitor_bounds.IsEmpty() && !monitor_bounds.Contains(*window_bounds)) { // The bounds don't fit. Move the arrow to try and improve things. bool arrow_on_left = (is_rtl ? (window_bounds->x() < monitor_bounds.x()) : (window_bounds->right() <= monitor_bounds.right())); if (window_bounds->bottom() > monitor_bounds.bottom()) { arrow_location = arrow_on_left ? BubbleBorder::BOTTOM_LEFT : BubbleBorder::BOTTOM_RIGHT; } else { arrow_location = arrow_on_left ? BubbleBorder::TOP_LEFT : BubbleBorder::TOP_RIGHT; } bubble_border->set_arrow_location(arrow_location); // Now get the recalculated bounds. *window_bounds = bubble_border->GetBounds(position_relative_to, local_contents_size); } // Calculate the bounds of the contained contents (in window coordinates) by // subtracting the border dimensions and margin amounts. *contents_bounds = gfx::Rect(gfx::Point(), window_bounds->size()); gfx::Insets insets; bubble_border->GetInsets(&insets); contents_bounds->Inset(insets.left() + kLeftMargin, insets.top() + kTopMargin, insets.right() + kRightMargin, insets.bottom() + kBottomMargin); } void BorderContents::Paint(gfx::Canvas* canvas) { // The border of this view creates an anti-aliased round-rect region for the // contents, which we need to fill with the background color. SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kFill_Style); paint.setColor(kBackgroundColor); gfx::Path path; gfx::Rect bounds(GetLocalBounds(false)); SkRect rect; rect.set(SkIntToScalar(bounds.x()), SkIntToScalar(bounds.y()), SkIntToScalar(bounds.right()), SkIntToScalar(bounds.bottom())); SkScalar radius = SkIntToScalar(BubbleBorder::GetCornerRadius()); path.addRoundRect(rect, radius, radius); canvas->drawPath(path, paint); // Now we paint the border, so it will be alpha-blended atop the contents. // This looks slightly better in the corners than drawing the contents atop // the border. PaintBorder(canvas); } #if defined(OS_WIN) // BorderWidget --------------------------------------------------------------- BorderWidget::BorderWidget() { set_delete_on_destroy(false); // Our owner will free us manually. set_window_style(WS_POPUP); set_window_ex_style(WS_EX_TOOLWINDOW | WS_EX_LAYERED); } gfx::Rect BorderWidget::InitAndGetBounds( HWND owner, const gfx::Rect& position_relative_to, const gfx::Size& contents_size, bool is_rtl) { // Set up the border view and ask it to calculate our bounds (and our // contents'). BorderContents* border_contents = new BorderContents; gfx::Rect contents_bounds, window_bounds; border_contents->InitAndGetBounds(position_relative_to, contents_size, is_rtl, &contents_bounds, &window_bounds); // Initialize ourselves. WidgetWin::Init(GetAncestor(owner, GA_ROOT), window_bounds); SetContentsView(border_contents); SetWindowPos(owner, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOREDRAW); // Chop a hole out of our region to show the contents through. // CreateRectRgn() expects (left, top, right, bottom) in window coordinates. HRGN contents_region = CreateRectRgn(contents_bounds.x(), contents_bounds.y(), contents_bounds.right(), contents_bounds.bottom()); HRGN window_region = CreateRectRgn(0, 0, window_bounds.width(), window_bounds.height()); CombineRgn(window_region, window_region, contents_region, RGN_XOR); DeleteObject(contents_region); SetWindowRgn(window_region, true); // Return |contents_bounds| in screen coordinates. contents_bounds.Offset(window_bounds.origin()); return contents_bounds; } LRESULT BorderWidget::OnMouseActivate(HWND window, UINT hit_test, UINT mouse_message) { // Never activate. return MA_NOACTIVATE; } #endif // InfoBubble ----------------------------------------------------------------- // static InfoBubble* InfoBubble::Show(views::Window* parent, const gfx::Rect& position_relative_to, views::View* contents, InfoBubbleDelegate* delegate) { InfoBubble* window = new InfoBubble; window->Init(parent, position_relative_to, contents, delegate); return window; } void InfoBubble::Close() { Close(false); } InfoBubble::InfoBubble() : #if defined(OS_LINUX) WidgetGtk(TYPE_POPUP), #endif delegate_(NULL), parent_(NULL), closed_(false) { } void InfoBubble::Init(views::Window* parent, const gfx::Rect& position_relative_to, views::View* contents, InfoBubbleDelegate* delegate) { parent_ = parent; parent_->DisableInactiveRendering(); delegate_ = delegate; // Create the main window. #if defined(OS_WIN) set_window_style(WS_POPUP | WS_CLIPCHILDREN); set_window_ex_style(WS_EX_TOOLWINDOW); WidgetWin::Init(parent->GetNativeWindow(), gfx::Rect()); #elif defined(OS_LINUX) MakeTransparent(); WidgetGtk::Init(GTK_WIDGET(parent->GetNativeWindow()), gfx::Rect()); #endif // Create a View to hold the contents of the main window. views::View* contents_view = new views::View; // Adding |contents| as a child has to be done before we call // contents->GetPreferredSize() below, since some supplied views don't // actually initialize themselves until they're added to a hierarchy. contents_view->AddChildView(contents); SetContentsView(contents_view); // Calculate and set the bounds for all windows and views. gfx::Rect window_bounds; #if defined(OS_WIN) border_.reset(new BorderWidget); // Initialize and position the border window. window_bounds = border_->InitAndGetBounds(GetNativeView(), position_relative_to, contents->GetPreferredSize(), contents->UILayoutIsRightToLeft()); // Make |contents| take up the entire contents view. contents_view->SetLayoutManager(new views::FillLayout); // Paint the background color behind the contents. contents_view->set_background( views::Background::CreateSolidBackground(kBackgroundColor)); #else // Create a view to paint the border and background. BorderContents* border_contents = new BorderContents; gfx::Rect contents_bounds; border_contents->InitAndGetBounds(position_relative_to, contents->GetPreferredSize(), contents->UILayoutIsRightToLeft(), &contents_bounds, &window_bounds); // This new view must be added before |contents| so it will paint under it. contents_view->AddChildView(0, border_contents); // |contents_view| has no layout manager, so we have to explicitly position // its children. border_contents->SetBounds(gfx::Rect(gfx::Point(), window_bounds.size())); contents->SetBounds(contents_bounds); #endif SetBounds(window_bounds); #if defined(OS_WIN) // Register the Escape accelerator for closing. GetFocusManager()->RegisterAccelerator( views::Accelerator(VK_ESCAPE, false, false, false), this); #endif // Done creating the bubble. NotificationService::current()->Notify(NotificationType::INFO_BUBBLE_CREATED, Source<InfoBubble>(this), NotificationService::NoDetails()); // Show the window. #if defined(OS_WIN) border_->ShowWindow(SW_SHOW); ShowWindow(SW_SHOW); #elif defined(OS_LINUX) views::WidgetGtk::Show(); #endif } #if defined(OS_WIN) void InfoBubble::OnActivate(UINT action, BOOL minimized, HWND window) { // The popup should close when it is deactivated. if (action == WA_INACTIVE && !closed_) { Close(); } else if (action == WA_ACTIVE) { DCHECK(GetRootView()->GetChildViewCount() > 0); GetRootView()->GetChildViewAt(0)->RequestFocus(); } } #endif void InfoBubble::Close(bool closed_by_escape) { if (closed_) return; if (delegate_) delegate_->InfoBubbleClosing(this, closed_by_escape); closed_ = true; #if defined(OS_WIN) border_->Close(); WidgetWin::Close(); #elif defined(OS_LINUX) WidgetGtk::Close(); #endif } bool InfoBubble::AcceleratorPressed(const views::Accelerator& accelerator) { if (!delegate_ || delegate_->CloseOnEscape()) { Close(true); return true; } return false; } <|endoftext|>
<commit_before>#include "filepickerwidget.h" #include "debug.h" #include <QKeyEvent> #include <QPersistentModelIndex> #include <QSettings> FilePickerWidget::FilePickerWidget(QWidget *parent) : QWidget(parent) { _ui.setupUi(this); _ui.optionsContainer->hide(); _model.setRootPath(QDir::rootPath()); // _model.setNameFilterDisables(false); _ui.treeView->setModel(&_model); _ui.treeView->installEventFilter(this); QSettings settings; setCurrentPath( settings.value("app/file_browse_last", QDir::homePath()).toString()); _completer.setModel(&_model); _completer.setCompletionMode(QCompleter::InlineCompletion); _completer.setCaseSensitivity(Qt::CaseSensitive); _ui.filterLineEdit->setCompleter(&_completer); _ui.treeView->setColumnWidth(0, 250); _ui.filterLineEdit->setFocus(); connect(&_model, &CustomFileSystemModel::dataChanged, [&](const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles) { Q_UNUSED(topLeft); Q_UNUSED(bottomRight); if(!roles.isEmpty() && (roles.first() == SELECTION_CHANGED_ROLE)) emit selectionChanged(); }); connect(_ui.filterLineEdit, &QLineEdit::textEdited, this, &FilePickerWidget::updateFilter); connect(_ui.showHiddenCheckBox, &QCheckBox::toggled, [&](const bool toggled) { if(toggled) _model.setFilter(_model.filter() | QDir::Hidden); else _model.setFilter(_model.filter() & ~QDir::Hidden); emit settingChanged(); }); connect(_ui.showSystemCheckBox, &QCheckBox::toggled, [&](const bool toggled) { if(toggled) _model.setFilter(_model.filter() | QDir::System); else _model.setFilter(_model.filter() & ~QDir::System); emit settingChanged(); }); connect(_ui.hideLinksCheckBox, &QCheckBox::toggled, [&](const bool toggled) { if(toggled) _model.setFilter(_model.filter() | QDir::NoSymLinks); else _model.setFilter(_model.filter() & ~QDir::NoSymLinks); emit settingChanged(); }); connect(_ui.showOptionsButton, &QPushButton::clicked, [&]() { _ui.optionsContainer->setVisible(!_ui.optionsContainer->isVisible()); }); connect(_ui.filterLineEdit, &QLineEdit::returnPressed, [&]() { if(_completer.currentCompletion().isEmpty()) _ui.treeView->setFocus(); }); connect(_ui.homeButton, &QPushButton::clicked, [&]() { setCurrentPath(QDir::homePath()); }); } FilePickerWidget::~FilePickerWidget() { } void FilePickerWidget::reset() { _model.reset(); _ui.treeView->reset(); QSettings settings; setCurrentPath( settings.value("app/file_browse_last", QDir::homePath()).toString()); } QList<QUrl> FilePickerWidget::getSelectedUrls() { QList<QUrl> urls; QList<QPersistentModelIndex> indexList = _model.checkedIndexes(); foreach(QPersistentModelIndex index, indexList) urls << QUrl::fromUserInput(_model.filePath(index)); return urls; } void FilePickerWidget::setSelectedUrls(const QList<QUrl> &urls) { _model.reset(); foreach(const QUrl url, urls) { _model.setData(_model.index(url.toLocalFile()), Qt::Checked, Qt::CheckStateRole); } } void FilePickerWidget::selectUrl(QUrl url) { _model.setData(_model.index(url.toLocalFile()), Qt::Checked, Qt::CheckStateRole); } bool FilePickerWidget::settingShowHidden() { return _ui.showHiddenCheckBox->isChecked(); } void FilePickerWidget::setSettingShowHidden(bool showHidden) { _ui.showHiddenCheckBox->setChecked(showHidden); } bool FilePickerWidget::settingShowSystem() { return _ui.showSystemCheckBox->isChecked(); } void FilePickerWidget::setSettingShowSystem(bool showSystem) { _ui.showSystemCheckBox->setChecked(showSystem); } bool FilePickerWidget::settingHideSymlinks() { return _ui.hideLinksCheckBox->isChecked(); } void FilePickerWidget::setSettingHideSymlinks(bool hideSymlinks) { _ui.hideLinksCheckBox->setChecked(hideSymlinks); } void FilePickerWidget::keyPressEvent(QKeyEvent *event) { switch(event->key()) { case Qt::Key_Escape: if(_ui.optionsContainer->isVisible()) { _ui.optionsContainer->hide(); } else if(!_ui.filterLineEdit->hasFocus()) { _ui.filterLineEdit->setFocus(); } else { QWidget::keyPressEvent(event); } break; default: QWidget::keyPressEvent(event); } } bool FilePickerWidget::eventFilter(QObject *obj, QEvent *event) { if((obj == _ui.treeView) && (event->type() == QEvent::FocusOut)) { QSettings settings; settings.setValue("app/file_browse_last", _model.filePath(_ui.treeView->currentIndex())); return false; } else { // standard event processing return QWidget::eventFilter(obj, event); } } void FilePickerWidget::updateFilter(QString filter) { _model.setNameFilters(QStringList("*")); if(filter.startsWith('/')) setCurrentPath(filter); else if(!filter.isEmpty()) _model.setNameFilters(QStringList(filter)); } void FilePickerWidget::setCurrentPath(const QString path) { _ui.treeView->setCurrentIndex(_model.index(path)); _ui.treeView->scrollTo(_model.index(path)); } <commit_msg>FilePickerWidget: Comments and minor reorganization<commit_after>#include "filepickerwidget.h" #include "debug.h" #include <QKeyEvent> #include <QPersistentModelIndex> #include <QSettings> FilePickerWidget::FilePickerWidget(QWidget *parent) : QWidget(parent) { _ui.setupUi(this); _ui.optionsContainer->hide(); // Configure underlying model. _model.setRootPath(QDir::rootPath()); // Configure file url completions. _completer.setModel(&_model); _completer.setCompletionMode(QCompleter::InlineCompletion); _completer.setCaseSensitivity(Qt::CaseSensitive); _ui.filterLineEdit->setCompleter(&_completer); _ui.filterLineEdit->setFocus(); // Configure visual display of the model. _ui.treeView->setModel(&_model); _ui.treeView->installEventFilter(this); _ui.treeView->setColumnWidth(0, 250); // Load last browsed file url. QSettings settings; setCurrentPath( settings.value("app/file_browse_last", QDir::homePath()).toString()); // Connection for the model's data changing. connect(&_model, &CustomFileSystemModel::dataChanged, [&](const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles) { Q_UNUSED(topLeft); Q_UNUSED(bottomRight); if(!roles.isEmpty() && (roles.first() == SELECTION_CHANGED_ROLE)) emit selectionChanged(); }); // Connections for the top bar of the widget connect(_ui.showOptionsButton, &QPushButton::clicked, [&]() { _ui.optionsContainer->setVisible(!_ui.optionsContainer->isVisible()); }); connect(_ui.homeButton, &QPushButton::clicked, [&]() { setCurrentPath(QDir::homePath()); }); connect(_ui.filterLineEdit, &QLineEdit::textEdited, this, &FilePickerWidget::updateFilter); connect(_ui.filterLineEdit, &QLineEdit::returnPressed, [&]() { if(_completer.currentCompletion().isEmpty()) _ui.treeView->setFocus(); }); // Connections for the settings connect(_ui.showHiddenCheckBox, &QCheckBox::toggled, [&](const bool toggled) { if(toggled) _model.setFilter(_model.filter() | QDir::Hidden); else _model.setFilter(_model.filter() & ~QDir::Hidden); emit settingChanged(); }); connect(_ui.showSystemCheckBox, &QCheckBox::toggled, [&](const bool toggled) { if(toggled) _model.setFilter(_model.filter() | QDir::System); else _model.setFilter(_model.filter() & ~QDir::System); emit settingChanged(); }); connect(_ui.hideLinksCheckBox, &QCheckBox::toggled, [&](const bool toggled) { if(toggled) _model.setFilter(_model.filter() | QDir::NoSymLinks); else _model.setFilter(_model.filter() & ~QDir::NoSymLinks); emit settingChanged(); }); } FilePickerWidget::~FilePickerWidget() { } void FilePickerWidget::reset() { _model.reset(); _ui.treeView->reset(); // Load last browsed file url. QSettings settings; setCurrentPath( settings.value("app/file_browse_last", QDir::homePath()).toString()); } QList<QUrl> FilePickerWidget::getSelectedUrls() { // Construct a list of urls from the filePath QStrings. QList<QUrl> urls; QList<QPersistentModelIndex> indexList = _model.checkedIndexes(); foreach(QPersistentModelIndex index, indexList) urls << QUrl::fromUserInput(_model.filePath(index)); return urls; } void FilePickerWidget::setSelectedUrls(const QList<QUrl> &urls) { _model.reset(); foreach(const QUrl url, urls) { _model.setData(_model.index(url.toLocalFile()), Qt::Checked, Qt::CheckStateRole); } } void FilePickerWidget::selectUrl(QUrl url) { _model.setData(_model.index(url.toLocalFile()), Qt::Checked, Qt::CheckStateRole); } bool FilePickerWidget::settingShowHidden() { return _ui.showHiddenCheckBox->isChecked(); } void FilePickerWidget::setSettingShowHidden(bool showHidden) { _ui.showHiddenCheckBox->setChecked(showHidden); } bool FilePickerWidget::settingShowSystem() { return _ui.showSystemCheckBox->isChecked(); } void FilePickerWidget::setSettingShowSystem(bool showSystem) { _ui.showSystemCheckBox->setChecked(showSystem); } bool FilePickerWidget::settingHideSymlinks() { return _ui.hideLinksCheckBox->isChecked(); } void FilePickerWidget::setSettingHideSymlinks(bool hideSymlinks) { _ui.hideLinksCheckBox->setChecked(hideSymlinks); } void FilePickerWidget::keyPressEvent(QKeyEvent *event) { switch(event->key()) { case Qt::Key_Escape: if(_ui.optionsContainer->isVisible()) { _ui.optionsContainer->hide(); } else if(!_ui.filterLineEdit->hasFocus()) { _ui.filterLineEdit->setFocus(); } else { QWidget::keyPressEvent(event); } break; default: QWidget::keyPressEvent(event); } } bool FilePickerWidget::eventFilter(QObject *obj, QEvent *event) { if((obj == _ui.treeView) && (event->type() == QEvent::FocusOut)) { // Save last browsed file url. QSettings settings; settings.setValue("app/file_browse_last", _model.filePath(_ui.treeView->currentIndex())); return false; } else { // standard event processing return QWidget::eventFilter(obj, event); } } void FilePickerWidget::updateFilter(QString filter) { _model.setNameFilters(QStringList("*")); if(filter.startsWith('/')) setCurrentPath(filter); else if(!filter.isEmpty()) _model.setNameFilters(QStringList(filter)); } void FilePickerWidget::setCurrentPath(const QString path) { _ui.treeView->setCurrentIndex(_model.index(path)); _ui.treeView->scrollTo(_model.index(path)); } <|endoftext|>
<commit_before>#include "line_shape.hpp" #include "../drape/utils/vertex_decl.hpp" #include "../drape/glsl_types.hpp" #include "../drape/glsl_func.hpp" #include "../drape/shader_def.hpp" #include "../drape/attribute_provider.hpp" #include "../drape/glstate.hpp" #include "../drape/batcher.hpp" #include "../drape/texture_manager.hpp" namespace df { namespace { float const SEGMENT = 0.0f; float const CAP = 1.0f; float const LEFT_WIDTH = 1.0f; float const RIGHT_WIDTH = -1.0f; } LineShape::LineShape(m2::SharedSpline const & spline, LineViewParams const & params) : m_params(params) , m_spline(spline) { ASSERT_GREATER(m_spline->GetPath().size(), 1, ()); } void LineShape::Draw(dp::RefPointer<dp::Batcher> batcher, dp::RefPointer<dp::TextureManager> textures) const { buffer_vector<gpu::LineVertex, 128> geometry; vector<m2::PointD> const & path = m_spline->GetPath(); dp::TextureManager::ColorRegion colorRegion; textures->GetColorRegion(m_params.m_color, colorRegion); glsl::vec2 colorCoord(glsl::ToVec2(colorRegion.GetTexRect().Center())); dp::TextureManager::StippleRegion maskRegion; textures->GetStippleRegion(dp::TextureManager::TStipplePattern{1}, maskRegion); glsl::vec2 maskCoord(glsl::ToVec2(maskRegion.GetTexRect().Center())); float const halfWidth = m_params.m_width / 2.0f; bool generateCap = m_params.m_cap != dp::ButtCap; auto const calcTangentAndNormals = [&halfWidth](glsl::vec2 const & pt0, glsl::vec2 const & pt1, glsl::vec2 & tangent, glsl::vec2 & leftNormal, glsl::vec2 & rightNormal) { tangent = pt1 - pt0; leftNormal = halfWidth * glsl::normalize(glsl::vec2(tangent.y, -tangent.x)); rightNormal = -leftNormal; }; float capType = m_params.m_cap == dp::RoundCap ? CAP : SEGMENT; glsl::vec2 leftSegment(SEGMENT, LEFT_WIDTH); glsl::vec2 rightSegment(SEGMENT, RIGHT_WIDTH); if (generateCap) { glsl::vec2 startPoint = glsl::ToVec2(path[0]); glsl::vec2 endPoint = glsl::ToVec2(path[1]); glsl::vec2 tangent, leftNormal, rightNormal; calcTangentAndNormals(startPoint, endPoint, tangent, leftNormal, rightNormal); tangent = -halfWidth * glsl::normalize(tangent); glsl::vec3 pivot = glsl::vec3(startPoint, m_params.m_depth); glsl::vec2 leftCap(capType, LEFT_WIDTH); glsl::vec2 rightCap(capType, RIGHT_WIDTH); geometry.push_back(gpu::LineVertex(pivot, leftNormal + tangent, colorCoord, maskCoord, leftCap)); geometry.push_back(gpu::LineVertex(pivot, rightNormal + tangent, colorCoord, maskCoord, rightCap)); geometry.push_back(gpu::LineVertex(pivot, leftNormal, colorCoord, maskCoord, leftSegment)); geometry.push_back(gpu::LineVertex(pivot, rightNormal, colorCoord, maskCoord, rightSegment)); } glsl::vec2 prevPoint; glsl::vec2 prevLeftNormal; glsl::vec2 prevRightNormal; for (size_t i = 1; i < path.size(); ++i) { glsl::vec2 startPoint = glsl::ToVec2(path[i - 1]); glsl::vec2 endPoint = glsl::ToVec2(path[i]); glsl::vec2 tangent, leftNormal, rightNormal; calcTangentAndNormals(startPoint, endPoint, tangent, leftNormal, rightNormal); glsl::vec3 startPivot = glsl::vec3(startPoint, m_params.m_depth); glsl::vec3 endPivot = glsl::vec3(endPoint, m_params.m_depth); // Create join beetween current segment and previous if (i > 1) { glsl::vec2 zeroNormal(0.0, 0.0); glsl::vec2 prevForming, nextForming; if (glsl::dot(prevLeftNormal, tangent) < 0) { prevForming = prevLeftNormal; nextForming = leftNormal; } else { prevForming = prevRightNormal; nextForming = rightNormal; } if (m_params.m_join == dp::BevelJoin) { geometry.push_back(gpu::LineVertex(startPivot, prevForming, colorCoord, maskCoord, leftSegment)); geometry.push_back(gpu::LineVertex(startPivot, zeroNormal, colorCoord, maskCoord, leftSegment)); geometry.push_back(gpu::LineVertex(startPivot, nextForming, colorCoord, maskCoord, leftSegment)); geometry.push_back(gpu::LineVertex(startPivot, nextForming, colorCoord, maskCoord, leftSegment)); } else { glsl::vec2 middleForming = glsl::normalize(prevForming + nextForming); glsl::vec2 zeroDxDy(0.0, 0.0); if (m_params.m_join == dp::MiterJoin) { float const b = glsl::length(prevForming - nextForming) / 2.0; float const a = glsl::length(prevForming); middleForming *= static_cast<float>(sqrt(a * a + b * b)); geometry.push_back(gpu::LineVertex(startPivot, prevForming, colorCoord, maskCoord, zeroDxDy)); geometry.push_back(gpu::LineVertex(startPivot, zeroNormal, colorCoord, maskCoord, zeroDxDy)); geometry.push_back(gpu::LineVertex(startPivot, middleForming, colorCoord, maskCoord, zeroDxDy)); geometry.push_back(gpu::LineVertex(startPivot, nextForming, colorCoord, maskCoord, zeroDxDy)); } else { middleForming *= glsl::length(prevForming); glsl::vec2 dxdyLeft(0.0, -1.0); glsl::vec2 dxdyRight(0.0, -1.0); glsl::vec2 dxdyMiddle(1.0, 1.0); geometry.push_back(gpu::LineVertex(startPivot, zeroNormal, colorCoord, maskCoord, zeroDxDy)); geometry.push_back(gpu::LineVertex(startPivot, prevForming, colorCoord, maskCoord, dxdyLeft)); geometry.push_back(gpu::LineVertex(startPivot, nextForming, colorCoord, maskCoord, dxdyRight)); geometry.push_back(gpu::LineVertex(startPivot, middleForming, colorCoord, maskCoord, dxdyMiddle)); } } } geometry.push_back(gpu::LineVertex(startPivot, leftNormal, colorCoord, maskCoord, leftSegment)); geometry.push_back(gpu::LineVertex(startPivot, rightNormal, colorCoord, maskCoord, rightSegment)); geometry.push_back(gpu::LineVertex(endPivot, leftNormal, colorCoord, maskCoord, leftSegment)); geometry.push_back(gpu::LineVertex(endPivot, rightNormal, colorCoord, maskCoord, rightSegment)); prevPoint = startPoint; prevLeftNormal = leftNormal; prevRightNormal = rightNormal; } if (generateCap) { size_t lastPointIndex = path.size() - 1; glsl::vec2 startPoint = glsl::ToVec2(path[lastPointIndex - 1]); glsl::vec2 endPoint = glsl::ToVec2(path[lastPointIndex]); glsl::vec2 tangent, leftNormal, rightNormal; calcTangentAndNormals(startPoint, endPoint, tangent, leftNormal, rightNormal); tangent = halfWidth * glsl::normalize(tangent); glsl::vec3 pivot = glsl::vec3(endPoint, m_params.m_depth); glsl::vec2 leftCap(capType, LEFT_WIDTH); glsl::vec2 rightCap(capType, RIGHT_WIDTH); geometry.push_back(gpu::LineVertex(pivot, leftNormal, colorCoord, maskCoord, leftSegment)); geometry.push_back(gpu::LineVertex(pivot, rightNormal, colorCoord, maskCoord, rightSegment)); geometry.push_back(gpu::LineVertex(pivot, leftNormal + tangent, colorCoord, maskCoord, leftCap)); geometry.push_back(gpu::LineVertex(pivot, rightNormal + tangent, colorCoord, maskCoord, rightCap)); } dp::GLState state(gpu::LINE_PROGRAM, dp::GLState::GeometryLayer); state.SetBlending(true); state.SetColorTexture(colorRegion.GetTexture()); state.SetMaskTexture(maskRegion.GetTexture()); dp::AttributeProvider provider(1, geometry.size()); provider.InitStream(0, gpu::LineVertex::GetBindingInfo(), dp::MakeStackRefPointer<void>(geometry.data())); batcher->InsertListOfStrip(state, dp::MakeStackRefPointer(&provider), 4); } } // namespace df <commit_msg>[drape] texture coord generation for stipple lines<commit_after>#include "line_shape.hpp" #include "../drape/utils/vertex_decl.hpp" #include "../drape/glsl_types.hpp" #include "../drape/glsl_func.hpp" #include "../drape/shader_def.hpp" #include "../drape/attribute_provider.hpp" #include "../drape/glstate.hpp" #include "../drape/batcher.hpp" #include "../drape/texture_manager.hpp" namespace df { namespace { float const SEGMENT = 0.0f; float const CAP = 1.0f; float const LEFT_WIDTH = 1.0f; float const RIGHT_WIDTH = -1.0f; size_t const TEX_BEG_IDX = 0; size_t const TEX_END_IDX = 1; struct TexDescription { float m_globalLength; glsl::vec2 m_texCoord; }; class TextureCoordGenerator { public: TextureCoordGenerator(float const baseGtoPScale) : m_baseGtoPScale(baseGtoPScale) , m_basePtoGScale(1.0f / baseGtoPScale) { } void SetRegion(dp::TextureManager::StippleRegion const & region, bool isSolid) { m_isSolid = isSolid; m_region = region; if (!m_isSolid) { m_maskLength = static_cast<float>(m_region.GetMaskPixelLength()); m_patternLength = static_cast<float>(m_region.GetPatternPixelLength()); } } bool GetTexCoords(TexDescription & desc) { if (m_isSolid) { desc.m_texCoord = glsl::ToVec2(m_region.GetTexRect().Center()); return true; } float const pxLength = desc.m_globalLength * m_baseGtoPScale; float const maskRest = m_maskLength - m_pxCursor; m2::RectF const & texRect = m_region.GetTexRect(); if (maskRest < pxLength) { desc.m_globalLength = maskRest * m_basePtoGScale; desc.m_texCoord = glsl::vec2(texRect.maxX(), texRect.Center().y); return false; } float texX = texRect.minX() + ((m_pxCursor + pxLength) / m_maskLength) * texRect.SizeX(); m_pxCursor = fmodf(m_pxCursor + pxLength, m_patternLength); desc.m_texCoord = glsl::vec2(texX, texRect.Center().y); return true; } private: float const m_baseGtoPScale; float const m_basePtoGScale; dp::TextureManager::StippleRegion m_region; float m_maskLength = 0.0f; float m_patternLength = 0.0f; bool m_isSolid = true; float m_pxCursor = 0.0f; }; } LineShape::LineShape(m2::SharedSpline const & spline, LineViewParams const & params) : m_params(params) , m_spline(spline) { ASSERT_GREATER(m_spline->GetPath().size(), 1, ()); } void LineShape::Draw(dp::RefPointer<dp::Batcher> batcher, dp::RefPointer<dp::TextureManager> textures) const { typedef gpu::LineVertex LV; buffer_vector<gpu::LineVertex, 128> geometry; vector<m2::PointD> const & path = m_spline->GetPath(); dp::TextureManager::ColorRegion colorRegion; textures->GetColorRegion(m_params.m_color, colorRegion); glsl::vec2 colorCoord(glsl::ToVec2(colorRegion.GetTexRect().Center())); TextureCoordGenerator texCoordGen(m_params.m_baseGtoPScale); dp::TextureManager::StippleRegion maskRegion; if (m_params.m_pattern.empty()) textures->GetStippleRegion(dp::TextureManager::TStipplePattern{1}, maskRegion); else textures->GetStippleRegion(m_params.m_pattern, maskRegion); texCoordGen.SetRegion(maskRegion, m_params.m_pattern.empty()); float const halfWidth = m_params.m_width / 2.0f; float const glbHalfWidth = halfWidth / m_params.m_baseGtoPScale; bool generateCap = m_params.m_cap != dp::ButtCap; auto const calcTangentAndNormals = [&halfWidth](glsl::vec2 const & pt0, glsl::vec2 const & pt1, glsl::vec2 & tangent, glsl::vec2 & leftNormal, glsl::vec2 & rightNormal) { tangent = glsl::normalize(pt1 - pt0); leftNormal = halfWidth * glsl::vec2(tangent.y, -tangent.x); rightNormal = -leftNormal; }; float capType = m_params.m_cap == dp::RoundCap ? CAP : SEGMENT; glsl::vec2 leftSegment(SEGMENT, LEFT_WIDTH); glsl::vec2 rightSegment(SEGMENT, RIGHT_WIDTH); TexDescription texCoords[2]; if (generateCap) { glsl::vec2 startPoint = glsl::ToVec2(path[0]); glsl::vec2 endPoint = glsl::ToVec2(path[1]); glsl::vec2 tangent, leftNormal, rightNormal; calcTangentAndNormals(startPoint, endPoint, tangent, leftNormal, rightNormal); tangent = -halfWidth * tangent; glsl::vec3 pivot = glsl::vec3(startPoint, m_params.m_depth); glsl::vec2 leftCap(capType, LEFT_WIDTH); glsl::vec2 rightCap(capType, RIGHT_WIDTH); texCoords[TEX_BEG_IDX].m_globalLength = 0.0; texCoords[TEX_END_IDX].m_globalLength = glbHalfWidth; VERIFY(texCoordGen.GetTexCoords(texCoords[TEX_BEG_IDX]), ()); VERIFY(texCoordGen.GetTexCoords(texCoords[TEX_END_IDX]), ()); geometry.push_back(LV(pivot, leftNormal + tangent, colorCoord, texCoords[TEX_BEG_IDX].m_texCoord, leftCap)); geometry.push_back(LV(pivot, rightNormal + tangent, colorCoord, texCoords[TEX_BEG_IDX].m_texCoord, rightCap)); geometry.push_back(LV(pivot, leftNormal, colorCoord, texCoords[TEX_END_IDX].m_texCoord, leftSegment)); geometry.push_back(LV(pivot, rightNormal, colorCoord, texCoords[TEX_END_IDX].m_texCoord, rightSegment)); } glsl::vec2 prevPoint; glsl::vec2 prevLeftNormal; glsl::vec2 prevRightNormal; for (size_t i = 1; i < path.size(); ++i) { glsl::vec2 startPoint = glsl::ToVec2(path[i - 1]); glsl::vec2 endPoint = glsl::ToVec2(path[i]); glsl::vec2 tangent, leftNormal, rightNormal; calcTangentAndNormals(startPoint, endPoint, tangent, leftNormal, rightNormal); glsl::vec3 startPivot = glsl::vec3(startPoint, m_params.m_depth); glsl::vec3 endPivot = glsl::vec3(endPoint, m_params.m_depth); // Create join beetween current segment and previous if (i > 1) { glsl::vec2 zeroNormal(0.0, 0.0); glsl::vec2 prevForming, nextForming; if (glsl::dot(prevLeftNormal, tangent) < 0) { prevForming = prevLeftNormal; nextForming = leftNormal; } else { prevForming = prevRightNormal; nextForming = rightNormal; } if (m_params.m_join == dp::BevelJoin) { texCoords[TEX_BEG_IDX].m_globalLength = 0.0f; texCoords[TEX_END_IDX].m_globalLength = glsl::length(nextForming - prevForming) / m_params.m_baseGtoPScale; VERIFY(texCoordGen.GetTexCoords(texCoords[TEX_BEG_IDX]), ()); VERIFY(texCoordGen.GetTexCoords(texCoords[TEX_END_IDX]), ()); geometry.push_back(LV(startPivot, prevForming, colorCoord, texCoords[TEX_BEG_IDX].m_texCoord, leftSegment)); geometry.push_back(LV(startPivot, zeroNormal, colorCoord, texCoords[TEX_BEG_IDX].m_texCoord, leftSegment)); geometry.push_back(LV(startPivot, nextForming, colorCoord, texCoords[TEX_END_IDX].m_texCoord, leftSegment)); geometry.push_back(LV(startPivot, nextForming, colorCoord, texCoords[TEX_END_IDX].m_texCoord, leftSegment)); } else { glsl::vec2 middleForming = glsl::normalize(prevForming + nextForming); glsl::vec2 zeroDxDy(0.0, 0.0); texCoords[TEX_BEG_IDX].m_globalLength = 0.0f; texCoords[TEX_END_IDX].m_globalLength = glsl::length(nextForming - prevForming) / m_params.m_baseGtoPScale; TexDescription middle; middle.m_globalLength = texCoords[TEX_END_IDX].m_globalLength / 2.0f; VERIFY(texCoordGen.GetTexCoords(texCoords[TEX_BEG_IDX]), ()); VERIFY(texCoordGen.GetTexCoords(middle), ()); VERIFY(texCoordGen.GetTexCoords(texCoords[TEX_END_IDX]), ()); if (m_params.m_join == dp::MiterJoin) { float const b = glsl::length(prevForming - nextForming) / 2.0; float const a = glsl::length(prevForming); middleForming *= static_cast<float>(sqrt(a * a + b * b)); geometry.push_back(LV(startPivot, prevForming, colorCoord, texCoords[TEX_BEG_IDX].m_texCoord, zeroDxDy)); geometry.push_back(LV(startPivot, zeroNormal, colorCoord, texCoords[TEX_BEG_IDX].m_texCoord, zeroDxDy)); geometry.push_back(LV(startPivot, middleForming, colorCoord, middle.m_texCoord, zeroDxDy)); geometry.push_back(LV(startPivot, nextForming, colorCoord, texCoords[TEX_END_IDX].m_texCoord, zeroDxDy)); } else { middleForming *= glsl::length(prevForming); glsl::vec2 dxdyLeft(0.0, -1.0); glsl::vec2 dxdyRight(0.0, -1.0); glsl::vec2 dxdyMiddle(1.0, 1.0); geometry.push_back(LV(startPivot, zeroNormal, colorCoord, texCoords[TEX_BEG_IDX].m_texCoord, zeroDxDy)); geometry.push_back(LV(startPivot, prevForming, colorCoord, texCoords[TEX_BEG_IDX].m_texCoord, dxdyLeft)); geometry.push_back(LV(startPivot, nextForming, colorCoord, texCoords[TEX_END_IDX].m_texCoord, dxdyRight)); geometry.push_back(LV(startPivot, middleForming, colorCoord, middle.m_texCoord, dxdyMiddle)); } } } texCoords[TEX_BEG_IDX].m_globalLength = 0.0; texCoords[TEX_END_IDX].m_globalLength = glsl::length(endPoint - startPoint); VERIFY(texCoordGen.GetTexCoords(texCoords[TEX_BEG_IDX]), ()); while (!texCoordGen.GetTexCoords(texCoords[TEX_END_IDX])) { glsl::vec2 newEndPoint = startPoint + tangent * texCoords[TEX_END_IDX].m_globalLength; glsl::vec3 newEndPivot = glsl::vec3(newEndPoint, m_params.m_depth); geometry.push_back(LV(startPivot, leftNormal, colorCoord, texCoords[TEX_BEG_IDX].m_texCoord, leftSegment)); geometry.push_back(LV(startPivot, rightNormal, colorCoord, texCoords[TEX_BEG_IDX].m_texCoord, rightSegment)); geometry.push_back(LV(newEndPivot, leftNormal, colorCoord, texCoords[TEX_END_IDX].m_texCoord, leftSegment)); geometry.push_back(LV(newEndPivot, rightNormal, colorCoord, texCoords[TEX_END_IDX].m_texCoord, rightSegment)); startPoint = newEndPoint; startPivot = newEndPivot; VERIFY(texCoordGen.GetTexCoords(texCoords[TEX_BEG_IDX]), ()); texCoords[TEX_END_IDX].m_globalLength = glsl::length(endPoint - startPoint); } geometry.push_back(LV(startPivot, leftNormal, colorCoord, texCoords[TEX_BEG_IDX].m_texCoord, leftSegment)); geometry.push_back(LV(startPivot, rightNormal, colorCoord, texCoords[TEX_BEG_IDX].m_texCoord, rightSegment)); geometry.push_back(LV(endPivot, leftNormal, colorCoord, texCoords[TEX_END_IDX].m_texCoord, leftSegment)); geometry.push_back(LV(endPivot, rightNormal, colorCoord, texCoords[TEX_END_IDX].m_texCoord, rightSegment)); prevPoint = startPoint; prevLeftNormal = leftNormal; prevRightNormal = rightNormal; } if (generateCap) { size_t lastPointIndex = path.size() - 1; glsl::vec2 startPoint = glsl::ToVec2(path[lastPointIndex - 1]); glsl::vec2 endPoint = glsl::ToVec2(path[lastPointIndex]); glsl::vec2 tangent, leftNormal, rightNormal; calcTangentAndNormals(startPoint, endPoint, tangent, leftNormal, rightNormal); tangent = halfWidth * tangent; glsl::vec3 pivot = glsl::vec3(endPoint, m_params.m_depth); glsl::vec2 leftCap(capType, LEFT_WIDTH); glsl::vec2 rightCap(capType, RIGHT_WIDTH); texCoords[TEX_BEG_IDX].m_globalLength = 0.0; texCoords[TEX_END_IDX].m_globalLength = glbHalfWidth; VERIFY(texCoordGen.GetTexCoords(texCoords[TEX_BEG_IDX]), ()); VERIFY(texCoordGen.GetTexCoords(texCoords[TEX_END_IDX]), ()); geometry.push_back(LV(pivot, leftNormal, colorCoord, texCoords[TEX_BEG_IDX].m_texCoord, leftSegment)); geometry.push_back(LV(pivot, rightNormal, colorCoord, texCoords[TEX_BEG_IDX].m_texCoord, rightSegment)); geometry.push_back(LV(pivot, leftNormal + tangent, colorCoord, texCoords[TEX_END_IDX].m_texCoord, leftCap)); geometry.push_back(LV(pivot, rightNormal + tangent, colorCoord, texCoords[TEX_END_IDX].m_texCoord, rightCap)); } dp::GLState state(gpu::LINE_PROGRAM, dp::GLState::GeometryLayer); state.SetBlending(true); state.SetColorTexture(colorRegion.GetTexture()); state.SetMaskTexture(maskRegion.GetTexture()); dp::AttributeProvider provider(1, geometry.size()); provider.InitStream(0, gpu::LineVertex::GetBindingInfo(), dp::MakeStackRefPointer<void>(geometry.data())); batcher->InsertListOfStrip(state, dp::MakeStackRefPointer(&provider), 4); } } // namespace df <|endoftext|>
<commit_before><commit_msg>Reuse UseReferenceBuild() cleanup in startup test.<commit_after><|endoftext|>
<commit_before>/// Project-level integration tests #include "stdafx.h" #include <CppUnitTest.h> using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace NLP { namespace Tests { TEST_CLASS(NlpTests) { public: TEST_METHOD(DummyTest1) { Assert::IsTrue(true); } }; } // namespace Tests } // namespace NLP } // namespace You <commit_msg>Remove dummy test.<commit_after>/// Project-level integration tests #include "stdafx.h" #include <CppUnitTest.h> using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace NLP { namespace Tests { TEST_CLASS(NlpTests) { public: }; } // namespace Tests } // namespace NLP } // namespace You <|endoftext|>
<commit_before>/* Copyright (C) 2003-2013 by Kristina Simpson <sweet.kristas@gmail.com> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <iomanip> #include "Blittable.hpp" #include "to_roman.hpp" #include "utf8_to_codepoint.hpp" #include "xhtml_block_box.hpp" #include "xhtml_listitem_box.hpp" #include "xhtml_layout_engine.hpp" namespace xhtml { using namespace css; namespace { const char32_t marker_disc = 0x2022; const char32_t marker_circle = 0x25e6; const char32_t marker_square = 0x25a0; const char32_t marker_lower_greek = 0x03b1 - 1; const char32_t marker_lower_greek_end = 0x03c9; const char32_t marker_lower_latin = 0x0061 - 1; const char32_t marker_lower_latin_end = 0x007a; const char32_t marker_upper_latin = 0x0041 - 1; const char32_t marker_upper_latin_end = 0x005A; const char32_t marker_armenian = 0x0531 - 1; const char32_t marker_armenian_end = 0x0556; const char32_t marker_georgian = 0x10d0 - 1; const char32_t marker_georgian_end = 0x10f6; } ListItemBox::ListItemBox(const BoxPtr& parent, const StyleNodePtr& node, const RootBoxPtr& root, int count) : Box(BoxId::LIST_ITEM, parent, node, root), count_(count), marker_(utils::codepoint_to_utf8(marker_disc)) { addChild(std::make_shared<BlockBox>(parent, node, root)); } std::string ListItemBox::toString() const { std::ostringstream ss; ss << "ListItemBox: " << getDimensions().content_ << (isFloat() ? " floating" : ""); return ss.str(); } void ListItemBox::handleLayout(LayoutEngine& eng, const Dimensions& containing) { auto lst = getStyleNode()->getListStyleType(); switch(lst) { case ListStyleType::DISC: /* is the default */ break; case ListStyleType::CIRCLE: marker_ = utils::codepoint_to_utf8(marker_circle); break; case ListStyleType::SQUARE: marker_ = utils::codepoint_to_utf8(marker_square); break; case ListStyleType::DECIMAL: { std::ostringstream ss; ss << std::dec << count_ << "."; marker_ = ss.str(); break; } case ListStyleType::DECIMAL_LEADING_ZERO: { std::ostringstream ss; ss << std::dec << std::setfill('0') << std::setw(2) << count_ << "."; marker_ = ss.str(); break; } case ListStyleType::LOWER_ROMAN: if(count_ < 4000) { marker_ = to_roman(count_, true) + "."; } break; case ListStyleType::UPPER_ROMAN: if(count_ < 4000) { marker_ = to_roman(count_, false) + "."; } break; case ListStyleType::LOWER_GREEK: if(count_ <= (marker_lower_greek_end - marker_lower_greek + 1)) { marker_ = utils::codepoint_to_utf8(marker_lower_greek + count_) + "."; } break; case ListStyleType::LOWER_ALPHA: case ListStyleType::LOWER_LATIN: if(count_ <= (marker_lower_latin_end - marker_lower_latin + 1)) { marker_ = utils::codepoint_to_utf8(marker_lower_latin + count_) + "."; } break; case ListStyleType::UPPER_ALPHA: case ListStyleType::UPPER_LATIN: if(count_ <= (marker_upper_latin_end - marker_upper_latin + 1)) { marker_ = utils::codepoint_to_utf8(marker_upper_latin + count_) + "."; } break; case ListStyleType::ARMENIAN: if(count_ <= (marker_armenian_end - marker_armenian + 1)) { marker_ = utils::codepoint_to_utf8(marker_armenian + count_) + "."; } break; case ListStyleType::GEORGIAN: if(count_ <= (marker_georgian_end - marker_georgian + 1)) { marker_ = utils::codepoint_to_utf8(marker_georgian + count_) + "."; } break; case ListStyleType::NONE: default: marker_.clear(); break; } FixedPoint top = getMBPTop() + containing.content_.height; FixedPoint left = getMBPLeft(); if(isFloat()) { // XXX fixme to use a more intelligent approach than iterating every pixel! const FixedPoint lh = 65536;//getDimensions().content_.height; const FixedPoint box_w = getDimensions().content_.width; FixedPoint y = getMBPTop(); FixedPoint x = getMBPLeft(); FixedPoint y1 = y + getOffset().y; left = getStyleNode()->getFloat() == Float::LEFT ? eng.getXAtPosition(y1, y1 + lh) + x : eng.getX2AtPosition(y1, y1 + lh); FixedPoint w = eng.getWidthAtPosition(y1, y1 + lh, containing.content_.width); bool placed = false; while(!placed) { if(w >= box_w) { left = left - (getStyleNode()->getFloat() == Float::LEFT ? x : box_w); top = y; placed = true; } else { y += lh; y1 = y + getOffset().y; left = getStyleNode()->getFloat() == Float::LEFT ? eng.getXAtPosition(y1, y1 + lh) + x : eng.getX2AtPosition(y1, y1 + lh); w = eng.getWidthAtPosition(y1, y1 + lh, containing.content_.width); } } } setContentX(left); setContentY(top); auto& css_height = getStyleNode()->getHeight(); if(!css_height->isAuto()) { FixedPoint h = css_height->getLength().compute(containing.content_.height); //if(h > child_height_) { // /* apply overflow properties */ //} setContentHeight(h); } } void ListItemBox::handlePreChildLayout(LayoutEngine& eng, const Dimensions& containing) { FixedPoint containing_width = containing.content_.width; calculateHorzMPB(containing_width); calculateVertMPB(containing.content_.height); const auto& css_width = getStyleNode()->getWidth(); FixedPoint width = 0; if(!css_width->isAuto()) { width = css_width->getLength().compute(containing_width); } else { width = containing_width; } setContentWidth(width); setContentHeight(0); } void ListItemBox::handlePostChildLayout(LayoutEngine& eng, BoxPtr child) { setContentHeight(getHeight() + child->getHeight() + child->getMBPBottom()); } void ListItemBox::handleRender(const KRE::SceneTreePtr& scene_tree, const point& offset) const { // XXX should figure out if there is a cleaner way of doing this. auto y = getLineHeight(); auto& fnt = getStyleNode()->getFont(); auto& img = getStyleNode()->getListStyleImage(); if(getStyleNode()->getListStyleImage() != nullptr) { // There are some other calculations we should do here if there is an // intrinsic ration to use. int em = static_cast<int>(fnt->getFontSize() / 72.0f * static_cast<float>(RenderContext::get().getDPI())); auto tex = img->getTexture(em, em); if(tex != nullptr) { auto rend = std::make_shared<KRE::Blittable>(tex); rend->setCentre(KRE::Blittable::Centre::BOTTOM_LEFT); rend->setCentreCoords(pointf(0.0f, y / LayoutEngine::getFixedPointScaleFloat())); scene_tree->addObject(rend); } } else { auto path = fnt->getGlyphPath(marker_); std::vector<point> new_path; FixedPoint path_width = path.back().x - path.front().x + fnt->calculateCharAdvance(' '); for(auto& p : path) { new_path.emplace_back(p.x + 5 - path_width, p.y + y); } auto fontr = fnt->createRenderableFromPath(nullptr, marker_, new_path); fontr->setColorPointer(getStyleNode()->getColor()); scene_tree->addObject(fontr); } } } <commit_msg>Experimental change to make the width requirement for positioning a floating list item require more than 1 pixel width.<commit_after>/* Copyright (C) 2003-2013 by Kristina Simpson <sweet.kristas@gmail.com> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <iomanip> #include "Blittable.hpp" #include "to_roman.hpp" #include "utf8_to_codepoint.hpp" #include "xhtml_block_box.hpp" #include "xhtml_listitem_box.hpp" #include "xhtml_layout_engine.hpp" namespace xhtml { using namespace css; namespace { const char32_t marker_disc = 0x2022; const char32_t marker_circle = 0x25e6; const char32_t marker_square = 0x25a0; const char32_t marker_lower_greek = 0x03b1 - 1; const char32_t marker_lower_greek_end = 0x03c9; const char32_t marker_lower_latin = 0x0061 - 1; const char32_t marker_lower_latin_end = 0x007a; const char32_t marker_upper_latin = 0x0041 - 1; const char32_t marker_upper_latin_end = 0x005A; const char32_t marker_armenian = 0x0531 - 1; const char32_t marker_armenian_end = 0x0556; const char32_t marker_georgian = 0x10d0 - 1; const char32_t marker_georgian_end = 0x10f6; } ListItemBox::ListItemBox(const BoxPtr& parent, const StyleNodePtr& node, const RootBoxPtr& root, int count) : Box(BoxId::LIST_ITEM, parent, node, root), count_(count), marker_(utils::codepoint_to_utf8(marker_disc)) { addChild(std::make_shared<BlockBox>(parent, node, root)); } std::string ListItemBox::toString() const { std::ostringstream ss; ss << "ListItemBox: " << getDimensions().content_ << (isFloat() ? " floating" : ""); return ss.str(); } void ListItemBox::handleLayout(LayoutEngine& eng, const Dimensions& containing) { auto lst = getStyleNode()->getListStyleType(); switch(lst) { case ListStyleType::DISC: /* is the default */ break; case ListStyleType::CIRCLE: marker_ = utils::codepoint_to_utf8(marker_circle); break; case ListStyleType::SQUARE: marker_ = utils::codepoint_to_utf8(marker_square); break; case ListStyleType::DECIMAL: { std::ostringstream ss; ss << std::dec << count_ << "."; marker_ = ss.str(); break; } case ListStyleType::DECIMAL_LEADING_ZERO: { std::ostringstream ss; ss << std::dec << std::setfill('0') << std::setw(2) << count_ << "."; marker_ = ss.str(); break; } case ListStyleType::LOWER_ROMAN: if(count_ < 4000) { marker_ = to_roman(count_, true) + "."; } break; case ListStyleType::UPPER_ROMAN: if(count_ < 4000) { marker_ = to_roman(count_, false) + "."; } break; case ListStyleType::LOWER_GREEK: if(count_ <= (marker_lower_greek_end - marker_lower_greek + 1)) { marker_ = utils::codepoint_to_utf8(marker_lower_greek + count_) + "."; } break; case ListStyleType::LOWER_ALPHA: case ListStyleType::LOWER_LATIN: if(count_ <= (marker_lower_latin_end - marker_lower_latin + 1)) { marker_ = utils::codepoint_to_utf8(marker_lower_latin + count_) + "."; } break; case ListStyleType::UPPER_ALPHA: case ListStyleType::UPPER_LATIN: if(count_ <= (marker_upper_latin_end - marker_upper_latin + 1)) { marker_ = utils::codepoint_to_utf8(marker_upper_latin + count_) + "."; } break; case ListStyleType::ARMENIAN: if(count_ <= (marker_armenian_end - marker_armenian + 1)) { marker_ = utils::codepoint_to_utf8(marker_armenian + count_) + "."; } break; case ListStyleType::GEORGIAN: if(count_ <= (marker_georgian_end - marker_georgian + 1)) { marker_ = utils::codepoint_to_utf8(marker_georgian + count_) + "."; } break; case ListStyleType::NONE: default: marker_.clear(); break; } FixedPoint top = getMBPTop() + containing.content_.height; FixedPoint left = getMBPLeft(); if(isFloat()) { // XXX fixme to use a more intelligent approach than iterating every pixel! const FixedPoint lh = 65536;//getDimensions().content_.height; const FixedPoint box_w = getDimensions().content_.width; FixedPoint y = getMBPTop(); FixedPoint x = getMBPLeft(); FixedPoint y1 = y + getOffset().y; left = getStyleNode()->getFloat() == Float::LEFT ? eng.getXAtPosition(y1, y1 + lh) + x : eng.getX2AtPosition(y1, y1 + lh); FixedPoint w = eng.getWidthAtPosition(y1, y1 + lh, containing.content_.width); bool placed = false; while(!placed) { if((w - box_w) >= LayoutEngine::getFixedPointScale()) { left = left - (getStyleNode()->getFloat() == Float::LEFT ? x : box_w); top = y; placed = true; } else { y += lh; y1 = y + getOffset().y; left = getStyleNode()->getFloat() == Float::LEFT ? eng.getXAtPosition(y1, y1 + lh) + x : eng.getX2AtPosition(y1, y1 + lh); w = eng.getWidthAtPosition(y1, y1 + lh, containing.content_.width); } } } setContentX(left); setContentY(top); auto& css_height = getStyleNode()->getHeight(); if(!css_height->isAuto()) { FixedPoint h = css_height->getLength().compute(containing.content_.height); //if(h > child_height_) { // /* apply overflow properties */ //} setContentHeight(h); } } void ListItemBox::handlePreChildLayout(LayoutEngine& eng, const Dimensions& containing) { FixedPoint containing_width = containing.content_.width; calculateHorzMPB(containing_width); calculateVertMPB(containing.content_.height); const auto& css_width = getStyleNode()->getWidth(); FixedPoint width = 0; if(!css_width->isAuto()) { width = css_width->getLength().compute(containing_width); } else { width = containing_width; } setContentWidth(width); setContentHeight(0); } void ListItemBox::handlePostChildLayout(LayoutEngine& eng, BoxPtr child) { setContentHeight(getHeight() + child->getHeight() + child->getMBPBottom()); } void ListItemBox::handleRender(const KRE::SceneTreePtr& scene_tree, const point& offset) const { // XXX should figure out if there is a cleaner way of doing this. auto y = getLineHeight(); auto& fnt = getStyleNode()->getFont(); auto& img = getStyleNode()->getListStyleImage(); if(getStyleNode()->getListStyleImage() != nullptr) { // There are some other calculations we should do here if there is an // intrinsic ration to use. int em = static_cast<int>(fnt->getFontSize() / 72.0f * static_cast<float>(RenderContext::get().getDPI())); auto tex = img->getTexture(em, em); if(tex != nullptr) { auto rend = std::make_shared<KRE::Blittable>(tex); rend->setCentre(KRE::Blittable::Centre::BOTTOM_LEFT); rend->setCentreCoords(pointf(0.0f, y / LayoutEngine::getFixedPointScaleFloat())); scene_tree->addObject(rend); } } else { auto path = fnt->getGlyphPath(marker_); std::vector<point> new_path; FixedPoint path_width = path.back().x - path.front().x + fnt->calculateCharAdvance(' '); for(auto& p : path) { new_path.emplace_back(p.x + 5 - path_width, p.y + y); } auto fontr = fnt->createRenderableFromPath(nullptr, marker_, new_path); fontr->setColorPointer(getStyleNode()->getColor()); scene_tree->addObject(fontr); } } } <|endoftext|>
<commit_before>// // LocalNotificationSystem.cpp // Chilli Source // Created by Scott Downie on 01/07/2011. // // The MIT License (MIT) // // Copyright (c) 2011 Tag Games Limited // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #ifdef CS_TARGETPLATFORM_IOS #include <CSBackend/Platform/iOS/Core/Notification/LocalNotificationSystem.h> #include <CSBackend/Platform/iOS/Core/String/NSStringUtils.h> #import <UIKit/UIKit.h> namespace CSBackend { namespace iOS { namespace { LocalNotificationSystem* g_localNotificationSystem; std::vector<CSCore::NotificationSPtr> g_queuedNotifications; //--------------------------------------------------------------- /// Convert UILocalNotification to Notification /// /// @author Scott Downie /// /// @param Apple UILocalNotification /// @param [Out] Chilli Source notification //--------------------------------------------------------------- CSCore::NotificationUPtr ConvertUILocalNotificationToNotification(UILocalNotification* in_uiLocal) { CSCore::NotificationUPtr notification = CSCore::NotificationUPtr(new CSCore::Notification()); notification->m_id = (CSCore::Notification::ID)[[in_uiLocal.userInfo objectForKey:@"ID"] unsignedIntValue]; notification->m_priority = (CSCore::Notification::Priority)[[in_uiLocal.userInfo objectForKey:@"Priority"] unsignedIntValue]; NSDictionary* nsParams = (NSDictionary*)[in_uiLocal.userInfo objectForKey:@"Params"]; for(id key in nsParams) { notification->m_params.SetValue([NSStringUtils newUTF8StringWithNSString:[nsParams objectForKey:key]], [NSStringUtils newUTF8StringWithNSString:key]); } return notification; } } CS_DEFINE_NAMEDTYPE(LocalNotificationSystem); //---------------------------------------------------------- //---------------------------------------------------------- LocalNotificationSystem::LocalNotificationSystem() : m_enabled(true) { } //-------------------------------------------------------- //------------------------------------------------------- bool LocalNotificationSystem::IsA(CSCore::InterfaceIDType in_interfaceId) const { return (CSCore::LocalNotificationSystem::InterfaceID == in_interfaceId || LocalNotificationSystem::InterfaceID == in_interfaceId); } //-------------------------------------------------- //--------------------------------------------------- void LocalNotificationSystem::SetEnabled(bool in_enabled) { m_enabled = in_enabled; if (m_enabled == false) { CancelAll(); } } //--------------------------------------------------- //--------------------------------------------------- void LocalNotificationSystem::ScheduleNotificationForTime(CSCore::Notification::ID in_id, const CSCore::ParamDictionary& in_params, TimeIntervalSecs in_time, CSCore::Notification::Priority in_priority) { @autoreleasepool { if (m_enabled == true) { //Create the notifications UILocalNotification* nsNotification = [[[UILocalNotification alloc] init] autorelease]; nsNotification.fireDate = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)in_time]; nsNotification.timeZone = [NSTimeZone defaultTimeZone]; nsNotification.alertAction = @"View"; NSString* body = [NSStringUtils newNSStringWithUTF8String:in_params.GetValue("Body")]; nsNotification.alertBody = body; [body release]; if(in_params.HasKey("Sound") == true) { NSString* sound = [NSStringUtils newNSStringWithUTF8String:in_params.GetValue("Sound")]; nsNotification.soundName = sound; [sound release]; } else { nsNotification.soundName = UILocalNotificationDefaultSoundName; } nsNotification.applicationIconBadgeNumber = 1; NSMutableDictionary* nsParams = [[NSMutableDictionary alloc] init]; for(CSCore::ParamDictionary::const_iterator it = in_params.begin(); it != in_params.end(); ++it) { NSString* key = [NSStringUtils newNSStringWithUTF8String:it->first]; NSString* value = [NSStringUtils newNSStringWithUTF8String:it->second]; [nsParams setObject:key forKey:value]; [key release]; [value release]; } //Encode the type ID into the notification so we can retrieve it at the other end NSDictionary* pInfo = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithUnsignedInt:(u32)in_id], @"ID", [NSNumber numberWithUnsignedInt:(u32)in_priority], @"Priority", nsParams, @"Params", nil]; nsNotification.userInfo = pInfo; // pInfo dictionary retains the pParams dictionary on insertion so we need to release [nsParams release]; //Schedule this baby [[UIApplication sharedApplication] scheduleLocalNotification:nsNotification]; } } } //-------------------------------------------------------- //-------------------------------------------------------- void LocalNotificationSystem::GetScheduledNotifications(std::vector<CSCore::NotificationCSPtr>& out_notifications, TimeIntervalSecs in_time, TimeIntervalSecs in_period) const { for(UILocalNotification* nsNotification in [[UIApplication sharedApplication] scheduledLocalNotifications]) { TimeIntervalSecs triggerTime = (TimeIntervalSecs)[nsNotification.fireDate timeIntervalSince1970]; s32 dwDeltaSecs = (s32)(in_time - triggerTime); if(std::abs(dwDeltaSecs) <= in_period) { CSCore::NotificationSPtr notification = ConvertUILocalNotificationToNotification(nsNotification); out_notifications.push_back(notification); } } } //------------------------------------------------ //------------------------------------------------ void LocalNotificationSystem::CancelByID(CSCore::Notification::ID in_id) { for(UILocalNotification* nsNotification in [[UIApplication sharedApplication] scheduledLocalNotifications]) { CSCore::Notification::ID notificationId = [[nsNotification.userInfo objectForKey:@"ID"] unsignedIntValue]; if(notificationId == in_id) { [[UIApplication sharedApplication] cancelLocalNotification:nsNotification]; } } } //------------------------------------------------ //------------------------------------------------ void LocalNotificationSystem::CancelAll() { [[UIApplication sharedApplication] cancelAllLocalNotifications]; } //-------------------------------------------------- //--------------------------------------------------- CSCore::IConnectableEvent<CSCore::LocalNotificationSystem::RecievedDelegate>& LocalNotificationSystem::GetRecievedEvent() { return m_receivedEvent; } //------------------------------------------------ //------------------------------------------------ bool LocalNotificationSystem::ApplicationDidFinishLaunchingWithOptions(UIApplication* inpApplication, NSDictionary* inpOptions) { //Reset the badge number inpApplication.applicationIconBadgeNumber = 0; UILocalNotification* pLocalNotification = [inpOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; if(pLocalNotification) { CSCore::NotificationSPtr notification = ConvertUILocalNotificationToNotification(pLocalNotification); if (g_localNotificationSystem != nullptr) { g_localNotificationSystem->OnNotificationRecieved(notification); } else { g_queuedNotifications.push_back(notification); } return true; } return false; } //------------------------------------------------ //------------------------------------------------ void LocalNotificationSystem::ApplicationDidBecomeActive(UIApplication* inpApplication) { //Reset the badge number inpApplication.applicationIconBadgeNumber = 0; } //------------------------------------------------ //------------------------------------------------ void LocalNotificationSystem::ApplicationDidReceiveLocalNotification(UIApplication* inpApplication, UILocalNotification* inpNotification) { //Reset the badge number inpApplication.applicationIconBadgeNumber = (inpApplication.applicationIconBadgeNumber - 1); CSCore::NotificationSPtr notification = ConvertUILocalNotificationToNotification(inpNotification); if (g_localNotificationSystem != nullptr) { g_localNotificationSystem->OnNotificationRecieved(notification); } else { g_queuedNotifications.push_back(notification); } } //-------------------------------------------------------- //-------------------------------------------------------- void LocalNotificationSystem::OnInit() { CSCore::LocalNotificationSystem::OnInit(); CS_ASSERT(g_localNotificationSystem == nullptr, "Cannot create more than 1 Local Notification System!"); g_localNotificationSystem = this; for (const CSCore::NotificationSPtr& notification : g_queuedNotifications) { OnNotificationRecieved(notification); } g_queuedNotifications.clear(); g_queuedNotifications.shrink_to_fit(); } //-------------------------------------------------------- //-------------------------------------------------------- void LocalNotificationSystem::OnNotificationRecieved(const CSCore::NotificationSPtr& in_notification) { m_receivedEvent.NotifyConnections(in_notification); } //-------------------------------------------------------- //-------------------------------------------------------- void LocalNotificationSystem::OnDestroy() { g_localNotificationSystem = nullptr; CSCore::LocalNotificationSystem::OnDestroy(); } //---------------------------------------------------------- //---------------------------------------------------------- LocalNotificationSystem::~LocalNotificationSystem() { g_localNotificationSystem = nullptr; } } } #endif<commit_msg>Requesting UI permissions for local notifications<commit_after>// // LocalNotificationSystem.cpp // Chilli Source // Created by Scott Downie on 01/07/2011. // // The MIT License (MIT) // // Copyright (c) 2011 Tag Games Limited // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #ifdef CS_TARGETPLATFORM_IOS #include <CSBackend/Platform/iOS/Core/Notification/LocalNotificationSystem.h> #include <CSBackend/Platform/iOS/Core/String/NSStringUtils.h> #import <UIKit/UIKit.h> namespace CSBackend { namespace iOS { namespace { LocalNotificationSystem* g_localNotificationSystem; std::vector<CSCore::NotificationSPtr> g_queuedNotifications; //--------------------------------------------------------------- /// Convert UILocalNotification to Notification /// /// @author Scott Downie /// /// @param Apple UILocalNotification /// @param [Out] Chilli Source notification //--------------------------------------------------------------- CSCore::NotificationUPtr ConvertUILocalNotificationToNotification(UILocalNotification* in_uiLocal) { CSCore::NotificationUPtr notification = CSCore::NotificationUPtr(new CSCore::Notification()); notification->m_id = (CSCore::Notification::ID)[[in_uiLocal.userInfo objectForKey:@"ID"] unsignedIntValue]; notification->m_priority = (CSCore::Notification::Priority)[[in_uiLocal.userInfo objectForKey:@"Priority"] unsignedIntValue]; NSDictionary* nsParams = (NSDictionary*)[in_uiLocal.userInfo objectForKey:@"Params"]; for(id key in nsParams) { notification->m_params.SetValue([NSStringUtils newUTF8StringWithNSString:[nsParams objectForKey:key]], [NSStringUtils newUTF8StringWithNSString:key]); } return notification; } } CS_DEFINE_NAMEDTYPE(LocalNotificationSystem); //---------------------------------------------------------- //---------------------------------------------------------- LocalNotificationSystem::LocalNotificationSystem() : m_enabled(true) { } //-------------------------------------------------------- //------------------------------------------------------- bool LocalNotificationSystem::IsA(CSCore::InterfaceIDType in_interfaceId) const { return (CSCore::LocalNotificationSystem::InterfaceID == in_interfaceId || LocalNotificationSystem::InterfaceID == in_interfaceId); } //-------------------------------------------------- //--------------------------------------------------- void LocalNotificationSystem::SetEnabled(bool in_enabled) { m_enabled = in_enabled; if (m_enabled == false) { CancelAll(); } } //--------------------------------------------------- //--------------------------------------------------- void LocalNotificationSystem::ScheduleNotificationForTime(CSCore::Notification::ID in_id, const CSCore::ParamDictionary& in_params, TimeIntervalSecs in_time, CSCore::Notification::Priority in_priority) { @autoreleasepool { if (m_enabled == true) { //Create the notifications UILocalNotification* nsNotification = [[[UILocalNotification alloc] init] autorelease]; nsNotification.fireDate = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)in_time]; nsNotification.timeZone = [NSTimeZone defaultTimeZone]; nsNotification.alertAction = @"View"; NSString* body = [NSStringUtils newNSStringWithUTF8String:in_params.GetValue("Body")]; nsNotification.alertBody = body; [body release]; if(in_params.HasKey("Sound") == true) { NSString* sound = [NSStringUtils newNSStringWithUTF8String:in_params.GetValue("Sound")]; nsNotification.soundName = sound; [sound release]; } else { nsNotification.soundName = UILocalNotificationDefaultSoundName; } nsNotification.applicationIconBadgeNumber = 1; NSMutableDictionary* nsParams = [[NSMutableDictionary alloc] init]; for(CSCore::ParamDictionary::const_iterator it = in_params.begin(); it != in_params.end(); ++it) { NSString* key = [NSStringUtils newNSStringWithUTF8String:it->first]; NSString* value = [NSStringUtils newNSStringWithUTF8String:it->second]; [nsParams setObject:key forKey:value]; [key release]; [value release]; } //Encode the type ID into the notification so we can retrieve it at the other end NSDictionary* pInfo = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithUnsignedInt:(u32)in_id], @"ID", [NSNumber numberWithUnsignedInt:(u32)in_priority], @"Priority", nsParams, @"Params", nil]; nsNotification.userInfo = pInfo; // pInfo dictionary retains the pParams dictionary on insertion so we need to release [nsParams release]; //Schedule this baby [[UIApplication sharedApplication] scheduleLocalNotification:nsNotification]; } } } //-------------------------------------------------------- //-------------------------------------------------------- void LocalNotificationSystem::GetScheduledNotifications(std::vector<CSCore::NotificationCSPtr>& out_notifications, TimeIntervalSecs in_time, TimeIntervalSecs in_period) const { for(UILocalNotification* nsNotification in [[UIApplication sharedApplication] scheduledLocalNotifications]) { TimeIntervalSecs triggerTime = (TimeIntervalSecs)[nsNotification.fireDate timeIntervalSince1970]; s32 dwDeltaSecs = (s32)(in_time - triggerTime); if(std::abs(dwDeltaSecs) <= in_period) { CSCore::NotificationSPtr notification = ConvertUILocalNotificationToNotification(nsNotification); out_notifications.push_back(notification); } } } //------------------------------------------------ //------------------------------------------------ void LocalNotificationSystem::CancelByID(CSCore::Notification::ID in_id) { for(UILocalNotification* nsNotification in [[UIApplication sharedApplication] scheduledLocalNotifications]) { CSCore::Notification::ID notificationId = [[nsNotification.userInfo objectForKey:@"ID"] unsignedIntValue]; if(notificationId == in_id) { [[UIApplication sharedApplication] cancelLocalNotification:nsNotification]; } } } //------------------------------------------------ //------------------------------------------------ void LocalNotificationSystem::CancelAll() { [[UIApplication sharedApplication] cancelAllLocalNotifications]; } //-------------------------------------------------- //--------------------------------------------------- CSCore::IConnectableEvent<CSCore::LocalNotificationSystem::RecievedDelegate>& LocalNotificationSystem::GetRecievedEvent() { return m_receivedEvent; } //------------------------------------------------ //------------------------------------------------ bool LocalNotificationSystem::ApplicationDidFinishLaunchingWithOptions(UIApplication* inpApplication, NSDictionary* inpOptions) { //Reset the badge number inpApplication.applicationIconBadgeNumber = 0; UILocalNotification* pLocalNotification = [inpOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; if(pLocalNotification) { CSCore::NotificationSPtr notification = ConvertUILocalNotificationToNotification(pLocalNotification); if (g_localNotificationSystem != nullptr) { g_localNotificationSystem->OnNotificationRecieved(notification); } else { g_queuedNotifications.push_back(notification); } return true; } return false; } //------------------------------------------------ //------------------------------------------------ void LocalNotificationSystem::ApplicationDidBecomeActive(UIApplication* inpApplication) { //Reset the badge number inpApplication.applicationIconBadgeNumber = 0; } //------------------------------------------------ //------------------------------------------------ void LocalNotificationSystem::ApplicationDidReceiveLocalNotification(UIApplication* inpApplication, UILocalNotification* inpNotification) { //Reset the badge number inpApplication.applicationIconBadgeNumber = (inpApplication.applicationIconBadgeNumber - 1); CSCore::NotificationSPtr notification = ConvertUILocalNotificationToNotification(inpNotification); if (g_localNotificationSystem != nullptr) { g_localNotificationSystem->OnNotificationRecieved(notification); } else { g_queuedNotifications.push_back(notification); } } //-------------------------------------------------------- //-------------------------------------------------------- void LocalNotificationSystem::OnInit() { if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) { //From iOS 8 we need to request permissions to display notifications, to badge the app icon and to play a sound UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]; [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings]; } CSCore::LocalNotificationSystem::OnInit(); CS_ASSERT(g_localNotificationSystem == nullptr, "Cannot create more than 1 Local Notification System!"); g_localNotificationSystem = this; for (const CSCore::NotificationSPtr& notification : g_queuedNotifications) { OnNotificationRecieved(notification); } g_queuedNotifications.clear(); g_queuedNotifications.shrink_to_fit(); } //-------------------------------------------------------- //-------------------------------------------------------- void LocalNotificationSystem::OnNotificationRecieved(const CSCore::NotificationSPtr& in_notification) { m_receivedEvent.NotifyConnections(in_notification); } //-------------------------------------------------------- //-------------------------------------------------------- void LocalNotificationSystem::OnDestroy() { g_localNotificationSystem = nullptr; CSCore::LocalNotificationSystem::OnDestroy(); } //---------------------------------------------------------- //---------------------------------------------------------- LocalNotificationSystem::~LocalNotificationSystem() { g_localNotificationSystem = nullptr; } } } #endif<|endoftext|>
<commit_before>#ifndef STAN_MATH_GPU_OPENCL_CONTEXT_HPP #define STAN_MATH_GPU_OPENCL_CONTEXT_HPP #ifdef STAN_OPENCL #define __CL_ENABLE_EXCEPTIONS #include <stan/math/prim/arr/err/check_opencl.hpp> #include <stan/math/prim/scal/err/domain_error.hpp> #include <CL/cl.hpp> #include <cmath> #include <fstream> #include <iostream> #include <map> #include <string> #include <vector> #define DEVICE_FILTER CL_DEVICE_TYPE_GPU /** * @file stan/math/gpu/opencl_context.hpp * @brief Initialization for OpenCL: * 1. find OpenCL platforms and devices available * 2. create context * 3. set up job queue * 4. initialize kernel groups */ namespace stan { namespace math { static int initialized_ = 0; typedef std::map<std::string, std::string> map_string; typedef std::map<std::string, cl::Kernel> map_kernel; typedef std::map<std::string, bool> map_bool; static map_string kernel_groups; static map_string kernel_strings; static map_kernel kernels; static map_bool compiled_kernels; static std::string dummy_kernel = "__kernel void dummy(__global const int* foo) { };"; /** * Initalizes the global std::map variables that * hold the OpenCL kernel sources, the groups to * which each kernel is assigned to and the * information about which kernel was already compiled. * */ inline void init_kernel_groups() { // To identify the kernel group kernel_groups["transpose"] = "basic_matrix"; kernel_groups["copy"] = "basic_matrix"; kernel_groups["zeros"] = "basic_matrix"; kernel_groups["identity"] = "basic_matrix"; kernel_groups["copy_triangular"] = "basic_matrix"; kernel_groups["copy_triangular_transposed"] = "basic_matrix"; kernel_groups["add"] = "basic_matrix"; kernel_groups["subtract"] = "basic_matrix"; kernel_groups["copy_submatrix"] = "basic_matrix"; kernel_groups["scalar_mul_diagonal"] = "matrix_multiply"; kernel_groups["scalar_mul"] = "matrix_multiply"; kernel_groups["basic_multiply"] = "matrix_multiply"; kernel_groups["multiply_self_transposed"] = "matrix_multiply"; kernel_groups["lower_tri_inv_step1"] = "matrix_inverse"; kernel_groups["lower_tri_inv_step2"] = "matrix_inverse"; kernel_groups["lower_tri_inv_step3"] = "matrix_inverse"; kernel_groups["cholesky_block"] = "cholesky_decomposition"; kernel_groups["check_nan"] = "check_gpu"; kernel_groups["check_symmetric"] = "check_gpu"; kernel_groups["check_diagonal_zeros"] = "check_gpu"; kernel_groups["dummy"] = "timing"; // Kernel group strings // the dummy kernel is the only one not included in files // so it is treated before the loop that iterates // through kernels to load all kernel_strings["timing"] = dummy_kernel; kernel_strings["check_gpu"] = #include <stan/math/prim/mat/fun/kern_gpu/check_gpu.cl> // NOLINT ; // NOLINT kernel_strings["cholesky_decomposition"] = #include <stan/math/prim/mat/fun/kern_gpu/cholesky_decomposition.cl> // NOLINT ; // NOLINT kernel_strings["matrix_inverse"] = #include <stan/math/prim/mat/fun/kern_gpu/matrix_inverse.cl> // NOLINT ; // NOLINT kernel_strings["matrix_multiply"] = #include <stan/math/prim/mat/fun/kern_gpu/matrix_multiply.cl> // NOLINT ; // NOLINT kernel_strings["basic_matrix"] = #include <stan/math/prim/mat/fun/kern_gpu/basic_matrix.cl> // NOLINT ; // NOLINT // Check if the kernels were already compiled compiled_kernels["basic_matrix"] = false; compiled_kernels["matrix_multiply"] = false; compiled_kernels["timing"] = false; compiled_kernels["matrix_inverse"] = false; compiled_kernels["cholesky_decomposition"] = false; compiled_kernels["check_gpu"] = false; } // TODO(Rok): select some other platform/device than 0 // TODO(Rok): option to turn profiling OFF /** * The class that represents the OpenCL runtime * * The class is used to find the OpenCL supported * platforms/devices and initialize the OpenCL * context/command queue. * */ class opencl_context { private: std::string description_; cl::Context oclContext_; cl::CommandQueue oclQueue_; cl::Platform oclPlatform_; cl::Device oclDevice_; size_t max_workgroup_size_; inline void init() { try { std::vector<cl::Platform> allPlatforms; cl::Platform::get(&allPlatforms); if (allPlatforms.size() == 0) { domain_error("OpenCL Initialization", "[Platform]", "", "No OpenCL platforms found"); } oclPlatform_ = allPlatforms[0]; std::vector<cl::Device> allDevices; oclPlatform_.getDevices(DEVICE_FILTER, &allDevices); // TODO(Steve): This should throw which platform if (allDevices.size() == 0) { domain_error("OpenCL Initialization", "[Device]", "", "No OpenCL devices found on the selected platform."); } oclDevice_ = allDevices[0]; description_ = "Device " + oclDevice_.getInfo<CL_DEVICE_NAME>() + " on the platform " + oclPlatform_.getInfo<CL_PLATFORM_NAME>(); allDevices[0].getInfo<size_t>(CL_DEVICE_MAX_WORK_GROUP_SIZE, &max_workgroup_size_); oclContext_ = cl::Context(allDevices); oclQueue_ = cl::CommandQueue(oclContext_, oclDevice_, CL_QUEUE_PROFILING_ENABLE, NULL); init_kernel_groups(); // Compile the dummy kernel used for timing purposes cl::Program::Sources source( 1, std::make_pair(dummy_kernel.c_str(), dummy_kernel.size())); cl::Program program_ = cl::Program(oclContext_, source); try { program_.build(allDevices); kernels["dummy"] = cl::Kernel(program_, "dummy", NULL); compiled_kernels["timing"] = true; } catch (const cl::Error &e) { domain_error( "OpenCL Initialization", e.what(), e.err(), "\nRetrieving build log\n", program_.getBuildInfo<CL_PROGRAM_BUILD_LOG>(allDevices[0]).c_str()); } } catch (const cl::Error &e) { check_ocl_error("build", e); } } public: inline std::string description() const { if (initialized_ == 1) { return description_; } return "No device selected yet."; } inline cl::Context &context() { if (initialized_ == 0) { init(); initialized_ = 1; } return oclContext_; } inline cl::CommandQueue &queue() { if (initialized_ == 0) { init(); initialized_ = 1; } return oclQueue_; } inline size_t maxWorkgroupSize() { return max_workgroup_size_; } }; static opencl_context opencl_context; /** * Returns the description of the OpenCL * platform and device that is used. * */ inline std::string get_description() { return opencl_context.description(); } /** * Returns the reference to the * OpenCL context. If no context was created, * a new context is created. * */ inline cl::Context &get_context() { return opencl_context.context(); } /** * Returns the reference to the active * OpenCL command queue. If no context * and queue were created, * a new context and queue are created and * the reference to the new queue is returned. * */ inline cl::CommandQueue &get_queue() { return opencl_context.queue(); } /** * Returns the reference to the active * OpenCL command queue. If no context * and queue were created, * a new context and queue are created and * the reference to the new queue is returned. * */ inline int get_maximum_workgroup_size() { return opencl_context.maxWorkgroupSize(); } /** * Compiles all the kernel in the specified group * * @param group The kernel group name * */ inline void compile_kernel_group(std::string group) { cl::Context &ctx = get_context(); std::vector<cl::Device> devices = ctx.getInfo<CL_CONTEXT_DEVICES>(); std::string kernel_source = kernel_strings[group]; cl::Program::Sources source( 1, std::make_pair(kernel_source.c_str(), kernel_source.size())); cl::Program program_ = cl::Program(ctx, source); try { char temp[100]; int local = 32; int gpu_local_max = sqrt(get_maximum_workgroup_size()); if (gpu_local_max < local) local = gpu_local_max; // parameters that have special limits are for now handled here // kernels with paramters will be compiled separately // for now we have static parameters, so this will be OK snprintf(temp, sizeof(temp), "-D TS=%d -D TS1=%d -D TS2=%d ", local, local, local); program_.build(devices, temp); cl_int err = CL_SUCCESS; // Iterate over the kernel list // and get all the kernels from this group for (std::map<std::string, std::string>::iterator it = kernel_groups.begin(); it != kernel_groups.end(); ++it) { if (group.compare((it->second).c_str()) == 0) { kernels[(it->first).c_str()] = cl::Kernel(program_, (it->first).c_str(), &err); } } } catch (const cl::Error &e) { domain_error( "OpenCL Initialization", e.what(), e.err(), "\nRetrieving build log\n", program_.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]).c_str()); } } /** * Returns the reference to the compiled kernel. * If the kernel has not yet been compiled, * the kernel group is compiled first. * * @param name The kernel name * */ inline cl::Kernel get_kernel(std::string name) { // Compile the kernel group and return the kernel if (!compiled_kernels[kernel_groups[name]]) { compile_kernel_group(kernel_groups[name]); compiled_kernels[kernel_groups[name]] = true; } return kernels[name]; } } // namespace math } // namespace stan #endif #endif <commit_msg>set local from int to size_t<commit_after>#ifndef STAN_MATH_GPU_OPENCL_CONTEXT_HPP #define STAN_MATH_GPU_OPENCL_CONTEXT_HPP #ifdef STAN_OPENCL #define __CL_ENABLE_EXCEPTIONS #include <stan/math/prim/arr/err/check_opencl.hpp> #include <stan/math/prim/scal/err/domain_error.hpp> #include <CL/cl.hpp> #include <cmath> #include <fstream> #include <iostream> #include <map> #include <string> #include <vector> #define DEVICE_FILTER CL_DEVICE_TYPE_GPU /** * @file stan/math/gpu/opencl_context.hpp * @brief Initialization for OpenCL: * 1. find OpenCL platforms and devices available * 2. create context * 3. set up job queue * 4. initialize kernel groups */ namespace stan { namespace math { static int initialized_ = 0; typedef std::map<std::string, std::string> map_string; typedef std::map<std::string, cl::Kernel> map_kernel; typedef std::map<std::string, bool> map_bool; static map_string kernel_groups; static map_string kernel_strings; static map_kernel kernels; static map_bool compiled_kernels; static std::string dummy_kernel = "__kernel void dummy(__global const int* foo) { };"; /** * Initalizes the global std::map variables that * hold the OpenCL kernel sources, the groups to * which each kernel is assigned to and the * information about which kernel was already compiled. * */ inline void init_kernel_groups() { // To identify the kernel group kernel_groups["transpose"] = "basic_matrix"; kernel_groups["copy"] = "basic_matrix"; kernel_groups["zeros"] = "basic_matrix"; kernel_groups["identity"] = "basic_matrix"; kernel_groups["copy_triangular"] = "basic_matrix"; kernel_groups["copy_triangular_transposed"] = "basic_matrix"; kernel_groups["add"] = "basic_matrix"; kernel_groups["subtract"] = "basic_matrix"; kernel_groups["copy_submatrix"] = "basic_matrix"; kernel_groups["scalar_mul_diagonal"] = "matrix_multiply"; kernel_groups["scalar_mul"] = "matrix_multiply"; kernel_groups["basic_multiply"] = "matrix_multiply"; kernel_groups["multiply_self_transposed"] = "matrix_multiply"; kernel_groups["lower_tri_inv_step1"] = "matrix_inverse"; kernel_groups["lower_tri_inv_step2"] = "matrix_inverse"; kernel_groups["lower_tri_inv_step3"] = "matrix_inverse"; kernel_groups["cholesky_block"] = "cholesky_decomposition"; kernel_groups["check_nan"] = "check_gpu"; kernel_groups["check_symmetric"] = "check_gpu"; kernel_groups["check_diagonal_zeros"] = "check_gpu"; kernel_groups["dummy"] = "timing"; // Kernel group strings // the dummy kernel is the only one not included in files // so it is treated before the loop that iterates // through kernels to load all kernel_strings["timing"] = dummy_kernel; kernel_strings["check_gpu"] = #include <stan/math/prim/mat/fun/kern_gpu/check_gpu.cl> // NOLINT ; // NOLINT kernel_strings["cholesky_decomposition"] = #include <stan/math/prim/mat/fun/kern_gpu/cholesky_decomposition.cl> // NOLINT ; // NOLINT kernel_strings["matrix_inverse"] = #include <stan/math/prim/mat/fun/kern_gpu/matrix_inverse.cl> // NOLINT ; // NOLINT kernel_strings["matrix_multiply"] = #include <stan/math/prim/mat/fun/kern_gpu/matrix_multiply.cl> // NOLINT ; // NOLINT kernel_strings["basic_matrix"] = #include <stan/math/prim/mat/fun/kern_gpu/basic_matrix.cl> // NOLINT ; // NOLINT // Check if the kernels were already compiled compiled_kernels["basic_matrix"] = false; compiled_kernels["matrix_multiply"] = false; compiled_kernels["timing"] = false; compiled_kernels["matrix_inverse"] = false; compiled_kernels["cholesky_decomposition"] = false; compiled_kernels["check_gpu"] = false; } // TODO(Rok): select some other platform/device than 0 // TODO(Rok): option to turn profiling OFF /** * The class that represents the OpenCL runtime * * The class is used to find the OpenCL supported * platforms/devices and initialize the OpenCL * context/command queue. * */ class opencl_context { private: std::string description_; cl::Context oclContext_; cl::CommandQueue oclQueue_; cl::Platform oclPlatform_; cl::Device oclDevice_; size_t max_workgroup_size_; inline void init() { try { std::vector<cl::Platform> allPlatforms; cl::Platform::get(&allPlatforms); if (allPlatforms.size() == 0) { domain_error("OpenCL Initialization", "[Platform]", "", "No OpenCL platforms found"); } oclPlatform_ = allPlatforms[0]; std::vector<cl::Device> allDevices; oclPlatform_.getDevices(DEVICE_FILTER, &allDevices); // TODO(Steve): This should throw which platform if (allDevices.size() == 0) { domain_error("OpenCL Initialization", "[Device]", "", "No OpenCL devices found on the selected platform."); } oclDevice_ = allDevices[0]; description_ = "Device " + oclDevice_.getInfo<CL_DEVICE_NAME>() + " on the platform " + oclPlatform_.getInfo<CL_PLATFORM_NAME>(); allDevices[0].getInfo<size_t>(CL_DEVICE_MAX_WORK_GROUP_SIZE, &max_workgroup_size_); oclContext_ = cl::Context(allDevices); oclQueue_ = cl::CommandQueue(oclContext_, oclDevice_, CL_QUEUE_PROFILING_ENABLE, NULL); init_kernel_groups(); // Compile the dummy kernel used for timing purposes cl::Program::Sources source( 1, std::make_pair(dummy_kernel.c_str(), dummy_kernel.size())); cl::Program program_ = cl::Program(oclContext_, source); try { program_.build(allDevices); kernels["dummy"] = cl::Kernel(program_, "dummy", NULL); compiled_kernels["timing"] = true; } catch (const cl::Error &e) { domain_error( "OpenCL Initialization", e.what(), e.err(), "\nRetrieving build log\n", program_.getBuildInfo<CL_PROGRAM_BUILD_LOG>(allDevices[0]).c_str()); } } catch (const cl::Error &e) { check_ocl_error("build", e); } } public: inline std::string description() const { if (initialized_ == 1) { return description_; } return "No device selected yet."; } inline cl::Context &context() { if (initialized_ == 0) { init(); initialized_ = 1; } return oclContext_; } inline cl::CommandQueue &queue() { if (initialized_ == 0) { init(); initialized_ = 1; } return oclQueue_; } inline size_t maxWorkgroupSize() { return max_workgroup_size_; } }; static opencl_context opencl_context; /** * Returns the description of the OpenCL * platform and device that is used. * */ inline std::string get_description() { return opencl_context.description(); } /** * Returns the reference to the * OpenCL context. If no context was created, * a new context is created. * */ inline cl::Context &get_context() { return opencl_context.context(); } /** * Returns the reference to the active * OpenCL command queue. If no context * and queue were created, * a new context and queue are created and * the reference to the new queue is returned. * */ inline cl::CommandQueue &get_queue() { return opencl_context.queue(); } /** * Returns the reference to the active * OpenCL command queue. If no context * and queue were created, * a new context and queue are created and * the reference to the new queue is returned. * */ inline int get_maximum_workgroup_size() { return opencl_context.maxWorkgroupSize(); } /** * Compiles all the kernel in the specified group * * @param group The kernel group name * */ inline void compile_kernel_group(std::string group) { cl::Context &ctx = get_context(); std::vector<cl::Device> devices = ctx.getInfo<CL_CONTEXT_DEVICES>(); std::string kernel_source = kernel_strings[group]; cl::Program::Sources source( 1, std::make_pair(kernel_source.c_str(), kernel_source.size())); cl::Program program_ = cl::Program(ctx, source); try { char temp[100]; size_t local = 32; size_t gpu_local_max = sqrt(get_maximum_workgroup_size()); if (gpu_local_max < local) local = gpu_local_max; // parameters that have special limits are for now handled here // kernels with paramters will be compiled separately // for now we have static parameters, so this will be OK snprintf(temp, sizeof(temp), "-D TS=%zu -D TS1=%zu -D TS2=%zu ", local, local, local); program_.build(devices, temp); cl_int err = CL_SUCCESS; // Iterate over the kernel list // and get all the kernels from this group for (std::map<std::string, std::string>::iterator it = kernel_groups.begin(); it != kernel_groups.end(); ++it) { if (group.compare((it->second).c_str()) == 0) { kernels[(it->first).c_str()] = cl::Kernel(program_, (it->first).c_str(), &err); } } } catch (const cl::Error &e) { domain_error( "OpenCL Initialization", e.what(), e.err(), "\nRetrieving build log\n", program_.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]).c_str()); } } /** * Returns the reference to the compiled kernel. * If the kernel has not yet been compiled, * the kernel group is compiled first. * * @param name The kernel name * */ inline cl::Kernel get_kernel(std::string name) { // Compile the kernel group and return the kernel if (!compiled_kernels[kernel_groups[name]]) { compile_kernel_group(kernel_groups[name]); compiled_kernels[kernel_groups[name]] = true; } return kernels[name]; } } // namespace math } // namespace stan #endif #endif <|endoftext|>
<commit_before>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/api/atom_api_cookies.h" #include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/value_converter.h" #include "base/time/time.h" #include "base/values.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "native_mate/dictionary.h" #include "native_mate/object_template_builder.h" #include "net/cookies/cookie_monster.h" #include "net/cookies/cookie_store.h" #include "net/cookies/cookie_util.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" using content::BrowserThread; namespace mate { template<> struct Converter<atom::api::Cookies::Error> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, atom::api::Cookies::Error val) { if (val == atom::api::Cookies::SUCCESS) return v8::Null(isolate); else return v8::Exception::Error(StringToV8(isolate, "failed")); } }; template<> struct Converter<net::CanonicalCookie> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, const net::CanonicalCookie& val) { mate::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("name", val.Name()); dict.Set("value", val.Value()); dict.Set("domain", val.Domain()); dict.Set("hostOnly", net::cookie_util::DomainIsHostOnly(val.Domain())); dict.Set("path", val.Path()); dict.Set("secure", val.IsSecure()); dict.Set("httpOnly", val.IsHttpOnly()); dict.Set("session", !val.IsPersistent()); if (val.IsPersistent()) dict.Set("expirationDate", val.ExpiryDate().ToDoubleT()); return dict.GetHandle(); } }; } // namespace mate namespace atom { namespace api { namespace { // Returns whether |domain| matches |filter|. bool MatchesDomain(std::string filter, const std::string& domain) { // Add a leading '.' character to the filter domain if it doesn't exist. if (net::cookie_util::DomainIsHostOnly(filter)) filter.insert(0, "."); std::string sub_domain(domain); // Strip any leading '.' character from the input cookie domain. if (!net::cookie_util::DomainIsHostOnly(sub_domain)) sub_domain = sub_domain.substr(1); // Now check whether the domain argument is a subdomain of the filter domain. for (sub_domain.insert(0, "."); sub_domain.length() >= filter.length();) { if (sub_domain == filter) return true; const size_t next_dot = sub_domain.find('.', 1); // Skip over leading dot. sub_domain.erase(0, next_dot); } return false; } // Returns whether |cookie| matches |filter|. bool MatchesCookie(const base::DictionaryValue* filter, const net::CanonicalCookie& cookie) { std::string str; bool b; if (filter->GetString("name", &str) && str != cookie.Name()) return false; if (filter->GetString("path", &str) && str != cookie.Path()) return false; if (filter->GetString("domain", &str) && !MatchesDomain(str, cookie.Domain())) return false; if (filter->GetBoolean("secure", &b) && b != cookie.IsSecure()) return false; if (filter->GetBoolean("session", &b) && b != !cookie.IsPersistent()) return false; return true; } // Helper to returns the CookieStore. inline net::CookieStore* GetCookieStore( scoped_refptr<net::URLRequestContextGetter> getter) { return getter->GetURLRequestContext()->cookie_store(); } // Run |callback| on UI thread. void RunCallbackInUI(const base::Closure& callback) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback); } // Remove cookies from |list| not matching |filter|, and pass it to |callback|. void FilterCookies(scoped_ptr<base::DictionaryValue> filter, const Cookies::GetCallback& callback, const net::CookieList& list) { net::CookieList result; for (const auto& cookie : list) { if (MatchesCookie(filter.get(), cookie)) result.push_back(cookie); } RunCallbackInUI(base::Bind(callback, Cookies::SUCCESS, result)); } // Receives cookies matching |filter| in IO thread. void GetCookiesOnIO(scoped_refptr<net::URLRequestContextGetter> getter, scoped_ptr<base::DictionaryValue> filter, const Cookies::GetCallback& callback) { std::string url; filter->GetString("url", &url); auto filtered_callback = base::Bind(FilterCookies, base::Passed(&filter), callback); net::CookieMonster* monster = GetCookieStore(getter)->GetCookieMonster(); // Empty url will match all url cookies. if (url.empty()) monster->GetAllCookiesAsync(filtered_callback); else monster->GetAllCookiesForURLAsync(GURL(url), filtered_callback); } // Removes cookie with |url| and |name| in IO thread. void RemoveCookieOnIOThread(scoped_refptr<net::URLRequestContextGetter> getter, const GURL& url, const std::string& name, const base::Closure& callback) { GetCookieStore(getter)->DeleteCookieAsync( url, name, base::Bind(RunCallbackInUI, callback)); } // Callback of SetCookie. void OnSetCookie(const Cookies::SetCallback& callback, bool success) { RunCallbackInUI( base::Bind(callback, success ? Cookies::SUCCESS : Cookies::FAILED)); } // Sets cookie with |details| in IO thread. void SetCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter, scoped_ptr<base::DictionaryValue> details, const Cookies::SetCallback& callback) { std::string url, name, value, domain, path; bool secure = false; bool http_only = false; double expiration_date; details->GetString("url", &url); details->GetString("name", &name); details->GetString("value", &value); details->GetString("domain", &domain); details->GetString("path", &path); details->GetBoolean("secure", &secure); details->GetBoolean("httpOnly", &http_only); base::Time expiration_time; if (details->GetDouble("expirationDate", &expiration_date)) { expiration_time = (expiration_date == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(expiration_date); } GetCookieStore(getter)->GetCookieMonster()->SetCookieWithDetailsAsync( GURL(url), name, value, domain, path, expiration_time, secure, http_only, false, false, false, net::COOKIE_PRIORITY_DEFAULT, base::Bind(OnSetCookie, callback)); } } // namespace Cookies::Cookies(v8::Isolate* isolate, content::BrowserContext* browser_context) : request_context_getter_(browser_context->GetRequestContext()) { Init(isolate); } Cookies::~Cookies() { } void Cookies::Get(const base::DictionaryValue& filter, const GetCallback& callback) { scoped_ptr<base::DictionaryValue> copied(filter.CreateDeepCopy()); auto getter = make_scoped_refptr(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(GetCookiesOnIO, getter, Passed(&copied), callback)); } void Cookies::Remove(const GURL& url, const std::string& name, const base::Closure& callback) { auto getter = make_scoped_refptr(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(RemoveCookieOnIOThread, getter, url, name, callback)); } void Cookies::Set(const base::DictionaryValue& details, const SetCallback& callback) { scoped_ptr<base::DictionaryValue> copied(details.CreateDeepCopy()); auto getter = make_scoped_refptr(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(SetCookieOnIO, getter, Passed(&copied), callback)); } // static mate::Handle<Cookies> Cookies::Create( v8::Isolate* isolate, content::BrowserContext* browser_context) { return mate::CreateHandle(isolate, new Cookies(isolate, browser_context)); } // static void Cookies::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) { mate::ObjectTemplateBuilder(isolate, prototype) .SetMethod("get", &Cookies::Get) .SetMethod("remove", &Cookies::Remove) .SetMethod("set", &Cookies::Set); } } // namespace api } // namespace atom <commit_msg>No more GetCookieMonster<commit_after>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/api/atom_api_cookies.h" #include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/value_converter.h" #include "base/time/time.h" #include "base/values.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "native_mate/dictionary.h" #include "native_mate/object_template_builder.h" #include "net/cookies/cookie_monster.h" #include "net/cookies/cookie_store.h" #include "net/cookies/cookie_util.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" using content::BrowserThread; namespace mate { template<> struct Converter<atom::api::Cookies::Error> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, atom::api::Cookies::Error val) { if (val == atom::api::Cookies::SUCCESS) return v8::Null(isolate); else return v8::Exception::Error(StringToV8(isolate, "failed")); } }; template<> struct Converter<net::CanonicalCookie> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, const net::CanonicalCookie& val) { mate::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("name", val.Name()); dict.Set("value", val.Value()); dict.Set("domain", val.Domain()); dict.Set("hostOnly", net::cookie_util::DomainIsHostOnly(val.Domain())); dict.Set("path", val.Path()); dict.Set("secure", val.IsSecure()); dict.Set("httpOnly", val.IsHttpOnly()); dict.Set("session", !val.IsPersistent()); if (val.IsPersistent()) dict.Set("expirationDate", val.ExpiryDate().ToDoubleT()); return dict.GetHandle(); } }; } // namespace mate namespace atom { namespace api { namespace { // Returns whether |domain| matches |filter|. bool MatchesDomain(std::string filter, const std::string& domain) { // Add a leading '.' character to the filter domain if it doesn't exist. if (net::cookie_util::DomainIsHostOnly(filter)) filter.insert(0, "."); std::string sub_domain(domain); // Strip any leading '.' character from the input cookie domain. if (!net::cookie_util::DomainIsHostOnly(sub_domain)) sub_domain = sub_domain.substr(1); // Now check whether the domain argument is a subdomain of the filter domain. for (sub_domain.insert(0, "."); sub_domain.length() >= filter.length();) { if (sub_domain == filter) return true; const size_t next_dot = sub_domain.find('.', 1); // Skip over leading dot. sub_domain.erase(0, next_dot); } return false; } // Returns whether |cookie| matches |filter|. bool MatchesCookie(const base::DictionaryValue* filter, const net::CanonicalCookie& cookie) { std::string str; bool b; if (filter->GetString("name", &str) && str != cookie.Name()) return false; if (filter->GetString("path", &str) && str != cookie.Path()) return false; if (filter->GetString("domain", &str) && !MatchesDomain(str, cookie.Domain())) return false; if (filter->GetBoolean("secure", &b) && b != cookie.IsSecure()) return false; if (filter->GetBoolean("session", &b) && b != !cookie.IsPersistent()) return false; return true; } // Helper to returns the CookieStore. inline net::CookieStore* GetCookieStore( scoped_refptr<net::URLRequestContextGetter> getter) { return getter->GetURLRequestContext()->cookie_store(); } // Run |callback| on UI thread. void RunCallbackInUI(const base::Closure& callback) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback); } // Remove cookies from |list| not matching |filter|, and pass it to |callback|. void FilterCookies(scoped_ptr<base::DictionaryValue> filter, const Cookies::GetCallback& callback, const net::CookieList& list) { net::CookieList result; for (const auto& cookie : list) { if (MatchesCookie(filter.get(), cookie)) result.push_back(cookie); } RunCallbackInUI(base::Bind(callback, Cookies::SUCCESS, result)); } // Receives cookies matching |filter| in IO thread. void GetCookiesOnIO(scoped_refptr<net::URLRequestContextGetter> getter, scoped_ptr<base::DictionaryValue> filter, const Cookies::GetCallback& callback) { std::string url; filter->GetString("url", &url); auto filtered_callback = base::Bind(FilterCookies, base::Passed(&filter), callback); // Empty url will match all url cookies. if (url.empty()) GetCookieStore(getter)->GetAllCookiesAsync(filtered_callback); else GetCookieStore(getter)->GetAllCookiesForURLAsync(GURL(url), filtered_callback); } // Removes cookie with |url| and |name| in IO thread. void RemoveCookieOnIOThread(scoped_refptr<net::URLRequestContextGetter> getter, const GURL& url, const std::string& name, const base::Closure& callback) { GetCookieStore(getter)->DeleteCookieAsync( url, name, base::Bind(RunCallbackInUI, callback)); } // Callback of SetCookie. void OnSetCookie(const Cookies::SetCallback& callback, bool success) { RunCallbackInUI( base::Bind(callback, success ? Cookies::SUCCESS : Cookies::FAILED)); } // Sets cookie with |details| in IO thread. void SetCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter, scoped_ptr<base::DictionaryValue> details, const Cookies::SetCallback& callback) { std::string url, name, value, domain, path; bool secure = false; bool http_only = false; double creation_date; double expiration_date; double last_access_date; details->GetString("url", &url); details->GetString("name", &name); details->GetString("value", &value); details->GetString("domain", &domain); details->GetString("path", &path); details->GetBoolean("secure", &secure); details->GetBoolean("httpOnly", &http_only); base::Time creation_time; if (details->GetDouble("creationDate", &creation_date)) { creation_time = (creation_date == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(creation_date); } base::Time expiration_time; if (details->GetDouble("expirationDate", &expiration_date)) { expiration_time = (expiration_date == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(expiration_date); } base::Time last_access_time; if (details->GetDouble("lastAccessDate", &last_access_date)) { last_access_time = (last_access_date == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(last_access_date); } GetCookieStore(getter)->SetCookieWithDetailsAsync( GURL(url), name, value, domain, path, creation_time, expiration_time, last_access_time, secure, http_only, false, false, net::COOKIE_PRIORITY_DEFAULT, base::Bind(OnSetCookie, callback)); } } // namespace Cookies::Cookies(v8::Isolate* isolate, content::BrowserContext* browser_context) : request_context_getter_(browser_context->GetRequestContext()) { Init(isolate); } Cookies::~Cookies() { } void Cookies::Get(const base::DictionaryValue& filter, const GetCallback& callback) { scoped_ptr<base::DictionaryValue> copied(filter.CreateDeepCopy()); auto getter = make_scoped_refptr(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(GetCookiesOnIO, getter, Passed(&copied), callback)); } void Cookies::Remove(const GURL& url, const std::string& name, const base::Closure& callback) { auto getter = make_scoped_refptr(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(RemoveCookieOnIOThread, getter, url, name, callback)); } void Cookies::Set(const base::DictionaryValue& details, const SetCallback& callback) { scoped_ptr<base::DictionaryValue> copied(details.CreateDeepCopy()); auto getter = make_scoped_refptr(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(SetCookieOnIO, getter, Passed(&copied), callback)); } // static mate::Handle<Cookies> Cookies::Create( v8::Isolate* isolate, content::BrowserContext* browser_context) { return mate::CreateHandle(isolate, new Cookies(isolate, browser_context)); } // static void Cookies::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) { mate::ObjectTemplateBuilder(isolate, prototype) .SetMethod("get", &Cookies::Get) .SetMethod("remove", &Cookies::Remove) .SetMethod("set", &Cookies::Set); } } // namespace api } // namespace atom <|endoftext|>
<commit_before>#include <iostream> #include "WakeDefines.h" #include "Logging/LogMacros.h" #include "Engine/InputManager.h" #include "Engine/GEngine.h" #include "Engine/Bootstrap.h" #include "Engine/Shader.h" #include "World/World.h" #include "World/StaticMeshComponent.h" #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> int xAxis = 0; int yAxis = 0; class TestActor : public Actor { public: TestActor(ActorID Id, bool StartActive) : Actor(Id, StartActive) { } virtual void Spawn() override { Actor::Spawn(); LOG_INFO(GlobalLogger, "TestActor spawned with an id of " << GetActorID() << "!"); ShaderProgram* Shader = new ShaderProgram(ShaderProgram::LoadProgram("assets/shaders/basic.vert", "assets/shaders/basic.frag")); GLint posAttrib = glGetAttribLocation(Shader->GetProgram(), "position"); float vertices[] = { 0.f, 0.5f, 0.f, 0.5f, -0.5f, 0.f, -0.5f, -0.5f, 0.f }; GLuint vbo; GLuint vao; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(posAttrib); MeshComponent = CreateComponent<StaticMeshComponent>(true, new StaticMesh(vbo, vao, 3), Shader); } virtual void Destroy() override { Actor::Destroy(); LOG_INFO(GlobalLogger, "TestActor is being destroyed with an id of " << GetActorID() << "!"); } virtual void Tick() override { Actor::Tick(); SetPosition(GetPosition() + glm::vec3(xAxis, yAxis, 0) * W_ENGINE.GetDeltaTime()); } private: StaticMeshComponent* MeshComponent; }; void OnInput_New(const Input& Input) { W_WORLD.SpawnActor<TestActor>(); } void Left(const Input& Input) { xAxis += Input.Mode == EInputMode::Pressed ? -1 : 1; } void Right(const Input& Input) { xAxis += Input.Mode == EInputMode::Pressed ? 1 : -1; } void Up(const Input& Input) { yAxis += Input.Mode == EInputMode::Pressed ? 1 : -1; } void Down(const Input& Input) { yAxis += Input.Mode == EInputMode::Pressed ? -1 : 1; } void OnInput_Exit(const Input& Input) { W_ENGINE.Stop(); } void Setup() { W_INPUT.Bind("Exit", INPUT_BIND(Keyboard, Pressed, Escape)); W_INPUT.Event("Exit").Bind(&OnInput_Exit); /*W_INPUT.CreateBinding("Exit", INPUT_BIND(Keyboard, Pressed, Escape)); W_INPUT.Event("Exit").Bind(&OnInput_Exit); W_INPUT.CreateBinding("New", INPUT_BIND(Keyboard, Pressed, Return)); W_INPUT.Event("New").Bind(&OnInput_New); W_INPUT.CreateBinding("Left", INPUT_BIND(Keyboard, Pressed, Left)); W_INPUT.CreateBinding("Left", INPUT_BIND(Keyboard, Released, Left)); W_INPUT.CreateBinding("Right", INPUT_BIND(Keyboard, Pressed, Right)); W_INPUT.CreateBinding("Right", INPUT_BIND(Keyboard, Released, Right)); W_INPUT.CreateBinding("Up", INPUT_BIND(Keyboard, Pressed, Up)); W_INPUT.CreateBinding("Up", INPUT_BIND(Keyboard, Released, Up)); W_INPUT.CreateBinding("Down", INPUT_BIND(Keyboard, Pressed, Down)); W_INPUT.CreateBinding("Down", INPUT_BIND(Keyboard, Released, Down)); W_INPUT.Event("Left").Bind(&Left); W_INPUT.Event("Right").Bind(&Right); W_INPUT.Event("Up").Bind(&Up); W_INPUT.Event("Down").Bind(&Down); W_WORLD.SpawnActor<TestActor>();*/ } void RunEngine(int ArgC, char** ArgV) { BootstrapOptions Options; Options.DefaultLogSinks = true; Options.DontRunEngine = false; Bootstrap Engine(ArgC, ArgV, Options); if (!Engine.Startup()) { return; } Setup(); Engine.Run(); } int main(int argc, char** argv) { RunEngine(argc, argv); #ifdef WAKE_EXIT_PAUSE std::cout << "Press return to exit..." << std::endl; getchar(); #endif return 0; }<commit_msg>fixed up example (new input functions)<commit_after>#include <iostream> #include "WakeDefines.h" #include "Logging/LogMacros.h" #include "Engine/InputManager.h" #include "Engine/GEngine.h" #include "Engine/Bootstrap.h" #include "Engine/Shader.h" #include "World/World.h" #include "World/StaticMeshComponent.h" #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> int xAxis = 0; int yAxis = 0; class TestActor : public Actor { public: TestActor(ActorID Id, bool StartActive) : Actor(Id, StartActive) { } virtual void Spawn() override { Actor::Spawn(); LOG_INFO(GlobalLogger, "TestActor spawned with an id of " << GetActorID() << "!"); ShaderProgram* Shader = new ShaderProgram(ShaderProgram::LoadProgram("assets/shaders/basic.vert", "assets/shaders/basic.frag")); GLint posAttrib = glGetAttribLocation(Shader->GetProgram(), "position"); float vertices[] = { 0.f, 0.5f, 0.f, 0.5f, -0.5f, 0.f, -0.5f, -0.5f, 0.f }; GLuint vbo; GLuint vao; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(posAttrib); MeshComponent = CreateComponent<StaticMeshComponent>(true, new StaticMesh(vbo, vao, 3), Shader); } virtual void Destroy() override { Actor::Destroy(); LOG_INFO(GlobalLogger, "TestActor is being destroyed with an id of " << GetActorID() << "!"); } virtual void Tick() override { Actor::Tick(); SetPosition(GetPosition() + glm::vec3(xAxis, yAxis, 0) * W_ENGINE.GetDeltaTime()); } private: StaticMeshComponent* MeshComponent; }; void OnInput_New(const Input& Input) { W_WORLD.SpawnActor<TestActor>(); } void Left(const Input& Input) { xAxis += Input.Mode == EInputMode::Pressed ? -1 : 1; } void Right(const Input& Input) { xAxis += Input.Mode == EInputMode::Pressed ? 1 : -1; } void Up(const Input& Input) { yAxis += Input.Mode == EInputMode::Pressed ? 1 : -1; } void Down(const Input& Input) { yAxis += Input.Mode == EInputMode::Pressed ? -1 : 1; } void OnInput_Exit(const Input& Input) { W_ENGINE.Stop(); } void Setup() { W_INPUT.Bind("Exit", INPUT_BIND(Keyboard, Pressed, Escape)); W_INPUT.Event("Exit").Bind(&OnInput_Exit); W_INPUT.Bind("New", INPUT_BIND(Keyboard, Pressed, Return)); W_INPUT.Event("New").Bind(&OnInput_New); W_INPUT.Bind("Left", INPUT_BIND(Keyboard, Pressed, Left)); W_INPUT.Bind("Left", INPUT_BIND(Keyboard, Released, Left)); W_INPUT.Bind("Right", INPUT_BIND(Keyboard, Pressed, Right)); W_INPUT.Bind("Right", INPUT_BIND(Keyboard, Released, Right)); W_INPUT.Bind("Up", INPUT_BIND(Keyboard, Pressed, Up)); W_INPUT.Bind("Up", INPUT_BIND(Keyboard, Released, Up)); W_INPUT.Bind("Down", INPUT_BIND(Keyboard, Pressed, Down)); W_INPUT.Bind("Down", INPUT_BIND(Keyboard, Released, Down)); W_INPUT.Event("Left").Bind(&Left); W_INPUT.Event("Right").Bind(&Right); W_INPUT.Event("Up").Bind(&Up); W_INPUT.Event("Down").Bind(&Down); } void RunEngine(int ArgC, char** ArgV) { BootstrapOptions Options; Options.DefaultLogSinks = true; Options.DontRunEngine = false; Bootstrap Engine(ArgC, ArgV, Options); if (!Engine.Startup()) { return; } Setup(); Engine.Run(); } int main(int argc, char** argv) { RunEngine(argc, argv); #ifdef WAKE_EXIT_PAUSE std::cout << "Press return to exit..." << std::endl; getchar(); #endif return 0; }<|endoftext|>
<commit_before>#include "halley/core/graphics/painter.h" #include "halley/core/graphics/render_context.h" #include "halley/core/graphics/render_target/render_target.h" #include "halley/core/graphics/material/material.h" #include "halley/core/graphics/material/material_definition.h" #include "halley/core/graphics/material/material_parameter.h" using namespace Halley; void Painter::startRender() { nDrawCalls = nTriangles = nVertices = 0; verticesPending = 0; bytesPending = 0; doStartRender(); } void Painter::endRender() { flush(); doEndRender(); camera = nullptr; viewPort = Rect4i(0, 0, 0, 0); } void Painter::flush() { flushPending(); } /* template <typename T> static void doMemcpyAlign(void* dstBytes, const void* srcBytes, size_t bytes) { T* dst = reinterpret_cast<T*>(dstBytes); const T* src = reinterpret_cast<const T*>(srcBytes); const T* srcEnd = src + (bytes / sizeof(T)); for (; src != srcEnd; ++src, ++dst) { *dst = *src; } } inline void memcpyAlign(void* dstBytes, const void* srcBytes, size_t bytes) { if (bytes % sizeof(size_t) == 0) { // Use size_t aligned if possible doMemcpyAlign<size_t>(dstBytes, srcBytes, bytes); } else { // Data is always int-aligned, since numVertices % 4 == 0 doMemcpyAlign<int>(dstBytes, srcBytes, bytes); } } */ void Painter::drawQuads(std::shared_ptr<Material> material, size_t numVertices, void* vertexData) { assert(numVertices > 0); assert(numVertices % 4 == 0); assert(vertexData != nullptr); if (material != materialPending) { if (materialPending != std::shared_ptr<Material>()) { flushPending(); } materialPending = material; } size_t dataSize = numVertices * material->getDefinition().getVertexStride(); size_t requiredSize = dataSize + bytesPending; if (vertexBuffer.size() < requiredSize) { vertexBuffer.resize(requiredSize * 2); } memmove(vertexBuffer.data() + bytesPending, vertexData, dataSize); verticesPending += numVertices; bytesPending += dataSize; } void Painter::bind(RenderContext& context) { // Set render target auto& rt = context.getRenderTarget(); rt.bind(); // Set viewport viewPort = context.getViewPort(); setViewPort(viewPort, viewPort != rt.getViewPort()); // Set camera camera = &context.getCamera(); camera->setViewArea(Vector2f(viewPort.getSize())); camera->updateProjection(); projection = camera->getProjection(); } void Painter::flushPending() { if (verticesPending > 0) { executeDrawQuads(*materialPending, verticesPending, vertexBuffer.data()); } // Reset bytesPending = 0; verticesPending = 0; materialPending.reset(); } void Painter::executeDrawQuads(Material& material, size_t numVertices, void* vertexData) { // Bind projection material["u_mvp"] = projection; // Load vertices setVertices(material.getDefinition(), numVertices, vertexData); // Go through each pass for (int i = 0; i < material.getDefinition().getNumPasses(); i++) { // Bind pass material.bind(i, *this); // Draw drawQuads(int(numVertices / 4)); // Log stats nDrawCalls++; nTriangles += numVertices / 2; nVertices += numVertices; } } <commit_msg>Missing header for memmove()<commit_after>#include "halley/core/graphics/painter.h" #include "halley/core/graphics/render_context.h" #include "halley/core/graphics/render_target/render_target.h" #include "halley/core/graphics/material/material.h" #include "halley/core/graphics/material/material_definition.h" #include "halley/core/graphics/material/material_parameter.h" #include <cstring> // memmove using namespace Halley; void Painter::startRender() { nDrawCalls = nTriangles = nVertices = 0; verticesPending = 0; bytesPending = 0; doStartRender(); } void Painter::endRender() { flush(); doEndRender(); camera = nullptr; viewPort = Rect4i(0, 0, 0, 0); } void Painter::flush() { flushPending(); } /* template <typename T> static void doMemcpyAlign(void* dstBytes, const void* srcBytes, size_t bytes) { T* dst = reinterpret_cast<T*>(dstBytes); const T* src = reinterpret_cast<const T*>(srcBytes); const T* srcEnd = src + (bytes / sizeof(T)); for (; src != srcEnd; ++src, ++dst) { *dst = *src; } } inline void memcpyAlign(void* dstBytes, const void* srcBytes, size_t bytes) { if (bytes % sizeof(size_t) == 0) { // Use size_t aligned if possible doMemcpyAlign<size_t>(dstBytes, srcBytes, bytes); } else { // Data is always int-aligned, since numVertices % 4 == 0 doMemcpyAlign<int>(dstBytes, srcBytes, bytes); } } */ void Painter::drawQuads(std::shared_ptr<Material> material, size_t numVertices, void* vertexData) { assert(numVertices > 0); assert(numVertices % 4 == 0); assert(vertexData != nullptr); if (material != materialPending) { if (materialPending != std::shared_ptr<Material>()) { flushPending(); } materialPending = material; } size_t dataSize = numVertices * material->getDefinition().getVertexStride(); size_t requiredSize = dataSize + bytesPending; if (vertexBuffer.size() < requiredSize) { vertexBuffer.resize(requiredSize * 2); } memmove(vertexBuffer.data() + bytesPending, vertexData, dataSize); verticesPending += numVertices; bytesPending += dataSize; } void Painter::bind(RenderContext& context) { // Set render target auto& rt = context.getRenderTarget(); rt.bind(); // Set viewport viewPort = context.getViewPort(); setViewPort(viewPort, viewPort != rt.getViewPort()); // Set camera camera = &context.getCamera(); camera->setViewArea(Vector2f(viewPort.getSize())); camera->updateProjection(); projection = camera->getProjection(); } void Painter::flushPending() { if (verticesPending > 0) { executeDrawQuads(*materialPending, verticesPending, vertexBuffer.data()); } // Reset bytesPending = 0; verticesPending = 0; materialPending.reset(); } void Painter::executeDrawQuads(Material& material, size_t numVertices, void* vertexData) { // Bind projection material["u_mvp"] = projection; // Load vertices setVertices(material.getDefinition(), numVertices, vertexData); // Go through each pass for (int i = 0; i < material.getDefinition().getNumPasses(); i++) { // Bind pass material.bind(i, *this); // Draw drawQuads(int(numVertices / 4)); // Log stats nDrawCalls++; nTriangles += numVertices / 2; nVertices += numVertices; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2011-2016, Graphics Lab, Georgia Tech Research Corporation * Copyright (c) 2011-2016, Humanoid Lab, Georgia Tech Research Corporation * Copyright (c) 2016, Personal Robotics Lab, Carnegie Mellon University * All rights reserved. * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "MyWindow.hpp" MyWindow::MyWindow() : SimWindow() { } MyWindow::~MyWindow() { } void MyWindow::drawWorld() const { glEnable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); SimWindow::drawWorld(); } void MyWindow::keyboard(unsigned char _key, int _x, int _y) { switch (_key) { case ' ': // use space key to play or stop the motion mSimulating = !mSimulating; if (mSimulating) mPlay = false; break; case 'q': // Spawn a cube case 'Q': { // Spawn a cube Eigen::Vector3d position = Eigen::Vector3d(dart::math::random(-1.0, 1.0), dart::math::random( 0.5, 1.0), dart::math::random(-1.0, 1.0)); Eigen::Vector3d size = Eigen::Vector3d(dart::math::random(0.1, 0.5), dart::math::random(0.1, 0.5), dart::math::random(0.1, 0.5)); spawnCube(position, size); break; } case 'w': // Spawn a cube case 'W': { // Spawn a cube if (mWorld->getNumSkeletons() > 1) mWorld->removeSkeleton(mWorld->getSkeleton(mWorld->getNumSkeletons() - 1)); break; } default: Win3D::keyboard(_key, _x, _y); } glutPostRedisplay(); } void MyWindow::spawnCube(const Eigen::Vector3d& _position, const Eigen::Vector3d& _size, double _mass) { dart::dynamics::SkeletonPtr newCubeSkeleton = dart::dynamics::Skeleton::create(); dart::dynamics::BodyNode::Properties body; body.mName = "cube_link"; body.mInertia.setMass(_mass); dart::dynamics::ShapePtr newBoxShape(new dart::dynamics::BoxShape(_size)); dart::dynamics::FreeJoint::Properties joint; joint.mName = "cube_joint"; joint.mT_ParentBodyToJoint = Eigen::Translation3d(_position); auto pair = newCubeSkeleton->createJointAndBodyNodePair<dart::dynamics::FreeJoint>( nullptr, joint, body); auto shapeNode = pair.second->createShapeNodeWith< dart::dynamics::VisualAspect, dart::dynamics::CollisionAspect, dart::dynamics::DynamicsAspect>(newBoxShape); shapeNode->getVisualAspect()->setColor(dart::math::randomVector<3>(0.0, 1.0)); mWorld->addSkeleton(newCubeSkeleton); } <commit_msg>[addDeleteSkel] Set inertia according to size and mass<commit_after>/* * Copyright (c) 2011-2016, Graphics Lab, Georgia Tech Research Corporation * Copyright (c) 2011-2016, Humanoid Lab, Georgia Tech Research Corporation * Copyright (c) 2016, Personal Robotics Lab, Carnegie Mellon University * All rights reserved. * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "MyWindow.hpp" MyWindow::MyWindow() : SimWindow() { } MyWindow::~MyWindow() { } void MyWindow::drawWorld() const { glEnable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); SimWindow::drawWorld(); } void MyWindow::keyboard(unsigned char _key, int _x, int _y) { switch (_key) { case ' ': // use space key to play or stop the motion mSimulating = !mSimulating; if (mSimulating) mPlay = false; break; case 'q': // Spawn a cube case 'Q': { // Spawn a cube Eigen::Vector3d position = Eigen::Vector3d(dart::math::random(-1.0, 1.0), dart::math::random( 0.5, 1.0), dart::math::random(-1.0, 1.0)); Eigen::Vector3d size = Eigen::Vector3d(dart::math::random(0.1, 0.5), dart::math::random(0.1, 0.5), dart::math::random(0.1, 0.5)); spawnCube(position, size); break; } case 'w': // Spawn a cube case 'W': { // Spawn a cube if (mWorld->getNumSkeletons() > 1) mWorld->removeSkeleton(mWorld->getSkeleton(mWorld->getNumSkeletons() - 1)); break; } default: Win3D::keyboard(_key, _x, _y); } glutPostRedisplay(); } void MyWindow::spawnCube(const Eigen::Vector3d& _position, const Eigen::Vector3d& _size, double _mass) { dart::dynamics::SkeletonPtr newCubeSkeleton = dart::dynamics::Skeleton::create(); dart::dynamics::BodyNode::Properties body; body.mName = "cube_link"; body.mInertia.setMass(_mass); body.mInertia.setMoment( dart::dynamics::BoxShape::computeInertia(_size, _mass)); dart::dynamics::ShapePtr newBoxShape(new dart::dynamics::BoxShape(_size)); dart::dynamics::FreeJoint::Properties joint; joint.mName = "cube_joint"; joint.mT_ParentBodyToJoint = Eigen::Translation3d(_position); auto pair = newCubeSkeleton->createJointAndBodyNodePair<dart::dynamics::FreeJoint>( nullptr, joint, body); auto shapeNode = pair.second->createShapeNodeWith< dart::dynamics::VisualAspect, dart::dynamics::CollisionAspect, dart::dynamics::DynamicsAspect>(newBoxShape); shapeNode->getVisualAspect()->setColor(dart::math::randomVector<3>(0.0, 1.0)); mWorld->addSkeleton(newCubeSkeleton); } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * * FILE * result.cxx * * DESCRIPTION * implementation of the pqxx::result class and support classes. * pqxx::result represents the set of result tuples from a database query * * Copyright (c) 2001-2005, Jeroen T. Vermeulen <jtv@xs4all.nl> * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. * *------------------------------------------------------------------------- */ #include "pqxx/compiler.h" #include <stdexcept> #include "libpq-fe.h" #include "pqxx/except" #include "pqxx/result" using namespace PGSTD; bool pqxx::result::operator==(const result &rhs) const throw () { if (&rhs == this) return true; const size_type s(size()); if (rhs.size() != s) return false; for (size_type i=0; i<s; ++i) if ((*this)[i] != rhs[i]) return false; return true; } bool pqxx::result::tuple::operator==(const tuple &rhs) const throw () { if (&rhs == this) return true; const size_type s(size()); if (rhs.size() != s) return false; // TODO: Depends on how null is handled! for (size_type i=0; i<s; ++i) if ((*this)[i] != rhs[i]) return false; return true; } void pqxx::result::tuple::swap(tuple &rhs) throw () { const result *const h(m_Home); const result::size_type i(m_Index); m_Home = rhs.m_Home; m_Index = rhs.m_Index; rhs.m_Home = h; rhs.m_Index = i; } bool pqxx::result::field::operator==(const field &rhs) const { if (is_null() != rhs.is_null()) return false; // TODO: Verify null handling decision const size_type s = size(); if (s != rhs.size()) return false; const char *const l(c_str()), *const r(rhs.c_str()); for (size_type i = 0; i < s; ++i) if (l[i] != r[i]) return false; return true; } pqxx::result::size_type pqxx::result::size() const throw () { return c_ptr() ? PQntuples(c_ptr()) : 0; } bool pqxx::result::empty() const throw () { return !c_ptr() || !PQntuples(c_ptr()); } void pqxx::result::swap(result &rhs) throw () { super::swap(rhs); } const pqxx::result::tuple pqxx::result::at(pqxx::result::size_type i) const throw (out_of_range) { if (i >= size()) throw out_of_range("Tuple number out of range"); return operator[](i); } void pqxx::result::CheckStatus(const string &Query) const { const string Err = StatusError(); if (!Err.empty()) throw sql_error(Err, Query); } void pqxx::result::CheckStatus(const char Query[]) const { const string Err = StatusError(); if (!Err.empty()) throw sql_error(Err, string(Query ? Query : "")); } string pqxx::result::StatusError() const { if (!c_ptr()) throw runtime_error("No result"); string Err; switch (PQresultStatus(c_ptr())) { case PGRES_EMPTY_QUERY: // The string sent to the backend was empty. case PGRES_COMMAND_OK: // Successful completion of a command returning no data case PGRES_TUPLES_OK: // The query successfully executed break; case PGRES_COPY_OUT: // Copy Out (from server) data transfer started case PGRES_COPY_IN: // Copy In (to server) data transfer started break; case PGRES_BAD_RESPONSE: // The server's response was not understood case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: Err = PQresultErrorMessage(c_ptr()); break; default: throw logic_error("libpqxx internal error: " "pqxx::result: Unrecognized response code " + to_string(int(PQresultStatus(c_ptr())))); } return Err; } const char *pqxx::result::CmdStatus() const throw () { return PQcmdStatus(c_ptr()); } pqxx::oid pqxx::result::inserted_oid() const { if (!c_ptr()) throw logic_error("Attempt to read oid of inserted row without an INSERT " "result"); return PQoidValue(c_ptr()); } pqxx::result::size_type pqxx::result::affected_rows() const { const char *const RowsStr = PQcmdTuples(c_ptr()); return RowsStr[0] ? atoi(RowsStr) : 0; } const char *pqxx::result::GetValue(pqxx::result::size_type Row, pqxx::result::tuple::size_type Col) const { return PQgetvalue(c_ptr(), Row, Col); } bool pqxx::result::GetIsNull(pqxx::result::size_type Row, pqxx::result::tuple::size_type Col) const { return PQgetisnull(c_ptr(), Row, Col) != 0; } pqxx::result::field::size_type pqxx::result::GetLength(pqxx::result::size_type Row, pqxx::result::tuple::size_type Col) const { return PQgetlength(c_ptr(), Row, Col); } pqxx::oid pqxx::result::column_type(tuple::size_type ColNum) const { const oid T = PQftype(c_ptr(), ColNum); if (T == oid_none) throw PGSTD::invalid_argument( "Attempt to retrieve type of nonexistant column " + to_string(ColNum) + " of query result"); return T; } #ifdef PQXX_HAVE_PQFTABLE pqxx::oid pqxx::result::column_table(tuple::size_type ColNum) const { const oid T = PQftable(c_ptr(), ColNum); /* If we get oid_none, it may be because the column is computed, or because we * got an invalid row number. */ if (T == oid_none && ColNum >= columns()) throw PGSTD::invalid_argument("Attempt to retrieve table ID for column " + to_string(ColNum) + " out of " + to_string(columns())); return T; } #endif int pqxx::result::errorposition() const throw () { int pos = -1; #if defined(PQXX_HAVE_PQRESULTERRORFIELD) if (c_ptr()) { const char *p = PQresultErrorField(c_ptr(), PG_DIAG_STATEMENT_POSITION); if (p) from_string(p, pos); } #endif // PQXX_HAVE_PQRESULTERRORFIELD return pos; } // tuple pqxx::result::field pqxx::result::tuple::operator[](const char f[]) const { return field(*this, m_Home->column_number(f)); } pqxx::result::field pqxx::result::tuple::at(const char f[]) const { const int fnum = m_Home->column_number(f); if (fnum == -1) throw invalid_argument(string("Unknown field '") + f + "'"); return field(*this, fnum); } pqxx::result::field pqxx::result::tuple::at(pqxx::result::tuple::size_type i) const throw (out_of_range) { if (i >= size()) throw out_of_range("Invalid field number"); return operator[](i); } const char * pqxx::result::column_name(pqxx::result::tuple::size_type Number) const { const char *const N = PQfname(c_ptr(), Number); if (!N) throw out_of_range("Invalid column number: " + to_string(Number)); return N; } pqxx::result::tuple::size_type pqxx::result::columns() const throw () { return c_ptr() ? PQnfields(c_ptr()) : 0; } pqxx::result::tuple::size_type pqxx::result::column_number(const char ColName[]) const { const int N = PQfnumber(c_ptr(), ColName); if (N == -1) throw invalid_argument("Unknown column name: '" + string(ColName) + "'"); return tuple::size_type(N); } // const_iterator pqxx::result::const_iterator pqxx::result::const_iterator::operator++(int) { const_iterator old(*this); m_Index++; return old; } pqxx::result::const_iterator pqxx::result::const_iterator::operator--(int) { const_iterator old(*this); m_Index--; return old; } // const_fielditerator pqxx::result::const_fielditerator pqxx::result::const_fielditerator::operator++(int) { const_fielditerator old(*this); m_col++; return old; } pqxx::result::const_fielditerator pqxx::result::const_fielditerator::operator--(int) { const_fielditerator old(*this); m_col--; return old; } pqxx::result::const_reverse_iterator pqxx::result::const_reverse_iterator::operator++(int) { const_reverse_iterator tmp(*this); iterator_type::operator--(); return tmp; } pqxx::result::const_reverse_iterator pqxx::result::const_reverse_iterator::operator--(int) { const_reverse_iterator tmp(*this); iterator_type::operator++(); return tmp; } pqxx::result::const_reverse_fielditerator pqxx::result::const_reverse_fielditerator::operator++(int) { const_reverse_fielditerator tmp(*this); iterator_type::operator--(); return tmp; } pqxx::result::const_reverse_fielditerator pqxx::result::const_reverse_fielditerator::operator--(int) { const_reverse_fielditerator tmp(*this); iterator_type::operator++(); return tmp; } <commit_msg>Clearer error message<commit_after>/*------------------------------------------------------------------------- * * FILE * result.cxx * * DESCRIPTION * implementation of the pqxx::result class and support classes. * pqxx::result represents the set of result tuples from a database query * * Copyright (c) 2001-2005, Jeroen T. Vermeulen <jtv@xs4all.nl> * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. * *------------------------------------------------------------------------- */ #include "pqxx/compiler.h" #include <stdexcept> #include "libpq-fe.h" #include "pqxx/except" #include "pqxx/result" using namespace PGSTD; bool pqxx::result::operator==(const result &rhs) const throw () { if (&rhs == this) return true; const size_type s(size()); if (rhs.size() != s) return false; for (size_type i=0; i<s; ++i) if ((*this)[i] != rhs[i]) return false; return true; } bool pqxx::result::tuple::operator==(const tuple &rhs) const throw () { if (&rhs == this) return true; const size_type s(size()); if (rhs.size() != s) return false; // TODO: Depends on how null is handled! for (size_type i=0; i<s; ++i) if ((*this)[i] != rhs[i]) return false; return true; } void pqxx::result::tuple::swap(tuple &rhs) throw () { const result *const h(m_Home); const result::size_type i(m_Index); m_Home = rhs.m_Home; m_Index = rhs.m_Index; rhs.m_Home = h; rhs.m_Index = i; } bool pqxx::result::field::operator==(const field &rhs) const { if (is_null() != rhs.is_null()) return false; // TODO: Verify null handling decision const size_type s = size(); if (s != rhs.size()) return false; const char *const l(c_str()), *const r(rhs.c_str()); for (size_type i = 0; i < s; ++i) if (l[i] != r[i]) return false; return true; } pqxx::result::size_type pqxx::result::size() const throw () { return c_ptr() ? PQntuples(c_ptr()) : 0; } bool pqxx::result::empty() const throw () { return !c_ptr() || !PQntuples(c_ptr()); } void pqxx::result::swap(result &rhs) throw () { super::swap(rhs); } const pqxx::result::tuple pqxx::result::at(pqxx::result::size_type i) const throw (out_of_range) { if (i >= size()) throw out_of_range("Tuple number out of range"); return operator[](i); } void pqxx::result::CheckStatus(const string &Query) const { const string Err = StatusError(); if (!Err.empty()) throw sql_error(Err, Query); } void pqxx::result::CheckStatus(const char Query[]) const { const string Err = StatusError(); if (!Err.empty()) throw sql_error(Err, string(Query ? Query : "")); } string pqxx::result::StatusError() const { if (!c_ptr()) throw runtime_error("No result set given"); string Err; switch (PQresultStatus(c_ptr())) { case PGRES_EMPTY_QUERY: // The string sent to the backend was empty. case PGRES_COMMAND_OK: // Successful completion of a command returning no data case PGRES_TUPLES_OK: // The query successfully executed break; case PGRES_COPY_OUT: // Copy Out (from server) data transfer started case PGRES_COPY_IN: // Copy In (to server) data transfer started break; case PGRES_BAD_RESPONSE: // The server's response was not understood case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: Err = PQresultErrorMessage(c_ptr()); break; default: throw logic_error("libpqxx internal error: " "pqxx::result: Unrecognized response code " + to_string(int(PQresultStatus(c_ptr())))); } return Err; } const char *pqxx::result::CmdStatus() const throw () { return PQcmdStatus(c_ptr()); } pqxx::oid pqxx::result::inserted_oid() const { if (!c_ptr()) throw logic_error("Attempt to read oid of inserted row without an INSERT " "result"); return PQoidValue(c_ptr()); } pqxx::result::size_type pqxx::result::affected_rows() const { const char *const RowsStr = PQcmdTuples(c_ptr()); return RowsStr[0] ? atoi(RowsStr) : 0; } const char *pqxx::result::GetValue(pqxx::result::size_type Row, pqxx::result::tuple::size_type Col) const { return PQgetvalue(c_ptr(), Row, Col); } bool pqxx::result::GetIsNull(pqxx::result::size_type Row, pqxx::result::tuple::size_type Col) const { return PQgetisnull(c_ptr(), Row, Col) != 0; } pqxx::result::field::size_type pqxx::result::GetLength(pqxx::result::size_type Row, pqxx::result::tuple::size_type Col) const { return PQgetlength(c_ptr(), Row, Col); } pqxx::oid pqxx::result::column_type(tuple::size_type ColNum) const { const oid T = PQftype(c_ptr(), ColNum); if (T == oid_none) throw PGSTD::invalid_argument( "Attempt to retrieve type of nonexistant column " + to_string(ColNum) + " of query result"); return T; } #ifdef PQXX_HAVE_PQFTABLE pqxx::oid pqxx::result::column_table(tuple::size_type ColNum) const { const oid T = PQftable(c_ptr(), ColNum); /* If we get oid_none, it may be because the column is computed, or because we * got an invalid row number. */ if (T == oid_none && ColNum >= columns()) throw PGSTD::invalid_argument("Attempt to retrieve table ID for column " + to_string(ColNum) + " out of " + to_string(columns())); return T; } #endif int pqxx::result::errorposition() const throw () { int pos = -1; #if defined(PQXX_HAVE_PQRESULTERRORFIELD) if (c_ptr()) { const char *p = PQresultErrorField(c_ptr(), PG_DIAG_STATEMENT_POSITION); if (p) from_string(p, pos); } #endif // PQXX_HAVE_PQRESULTERRORFIELD return pos; } // tuple pqxx::result::field pqxx::result::tuple::operator[](const char f[]) const { return field(*this, m_Home->column_number(f)); } pqxx::result::field pqxx::result::tuple::at(const char f[]) const { const int fnum = m_Home->column_number(f); // TODO: Should this be an out_of_range? if (fnum == -1) throw invalid_argument(string("Unknown field '") + f + "'"); return field(*this, fnum); } pqxx::result::field pqxx::result::tuple::at(pqxx::result::tuple::size_type i) const throw (out_of_range) { if (i >= size()) throw out_of_range("Invalid field number"); return operator[](i); } const char * pqxx::result::column_name(pqxx::result::tuple::size_type Number) const { const char *const N = PQfname(c_ptr(), Number); if (!N) throw out_of_range("Invalid column number: " + to_string(Number)); return N; } pqxx::result::tuple::size_type pqxx::result::columns() const throw () { return c_ptr() ? PQnfields(c_ptr()) : 0; } pqxx::result::tuple::size_type pqxx::result::column_number(const char ColName[]) const { const int N = PQfnumber(c_ptr(), ColName); // TODO: Should this be an out_of_range? if (N == -1) throw invalid_argument("Unknown column name: '" + string(ColName) + "'"); return tuple::size_type(N); } // const_iterator pqxx::result::const_iterator pqxx::result::const_iterator::operator++(int) { const_iterator old(*this); m_Index++; return old; } pqxx::result::const_iterator pqxx::result::const_iterator::operator--(int) { const_iterator old(*this); m_Index--; return old; } // const_fielditerator pqxx::result::const_fielditerator pqxx::result::const_fielditerator::operator++(int) { const_fielditerator old(*this); m_col++; return old; } pqxx::result::const_fielditerator pqxx::result::const_fielditerator::operator--(int) { const_fielditerator old(*this); m_col--; return old; } pqxx::result::const_reverse_iterator pqxx::result::const_reverse_iterator::operator++(int) { const_reverse_iterator tmp(*this); iterator_type::operator--(); return tmp; } pqxx::result::const_reverse_iterator pqxx::result::const_reverse_iterator::operator--(int) { const_reverse_iterator tmp(*this); iterator_type::operator++(); return tmp; } pqxx::result::const_reverse_fielditerator pqxx::result::const_reverse_fielditerator::operator++(int) { const_reverse_fielditerator tmp(*this); iterator_type::operator--(); return tmp; } pqxx::result::const_reverse_fielditerator pqxx::result::const_reverse_fielditerator::operator--(int) { const_reverse_fielditerator tmp(*this); iterator_type::operator++(); return tmp; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: retstrm.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2004-09-09 17:23:14 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2002 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2002 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _RETSTRM_HXX #define _RETSTRM_HXX #ifndef _SBXVAR_HXX //autogen #include <svtools/sbxvar.hxx> #endif #ifndef _SMARTID_HXX_ #include <vcl/smartid.hxx> #endif #include "cmdbasestream.hxx" class SvStream; class RetStream: public CmdBaseStream { public: RetStream(); ~RetStream(); // CmdBaseStream::GenError; // void GenError( comm_ULONG nError, const comm_UniChar* aString, comm_USHORT nLenInChars ){CmdBaseStream::GenError( nError, aString, nLenInChars );} // new void GenError( SmartId aUId, String aString ); // CmdBaseStream::GenReturn; void GenReturn( comm_USHORT nRet, comm_ULONG nNr ){CmdBaseStream::GenReturn( nRet, nNr );} void GenReturn( comm_USHORT nRet, SmartId aUId, comm_ULONG nNr ){CmdBaseStream::GenReturn( nRet, &aUId, nNr );} // void GenReturn( comm_USHORT nRet, comm_ULONG nUId, const comm_UniChar* aString, comm_USHORT nLenInChars ){CmdBaseStream::GenReturn( nRet, nUId, aString, nLenInChars );} void GenReturn( comm_USHORT nRet, SmartId aUId, comm_BOOL bBool ){CmdBaseStream::GenReturn( nRet, &aUId, bBool );} // void GenReturn( comm_USHORT nRet, comm_ULONG nUId, comm_ULONG nNr, const comm_UniChar* aString, comm_USHORT nLenInChars, comm_BOOL bBool ){CmdBaseStream::GenReturn( nRet, nUId, nNr, aString, nLenInChars, bBool );} // MacroRecorder void GenReturn( comm_USHORT nRet, SmartId aUId, comm_USHORT nMethod ){CmdBaseStream::GenReturn( nRet, &aUId, nMethod );} // void GenReturn( comm_USHORT nRet, comm_ULONG nUId, comm_USHORT nMethod, const comm_UniChar* aString, comm_USHORT nLenInChars ){CmdBaseStream::GenReturn( nRet, nUId, nMethod, aString, nLenInChars );} // void GenReturn( comm_USHORT nRet, comm_ULONG nUId, comm_USHORT nMethod, const comm_UniChar* aString, comm_USHORT nLenInChars, comm_BOOL bBool ){CmdBaseStream::GenReturn( nRet, nUId, nMethod, aString, nLenInChars, bBool );} void GenReturn( comm_USHORT nRet, SmartId aUId, comm_USHORT nMethod, comm_BOOL bBool ){CmdBaseStream::GenReturn( nRet, &aUId, nMethod, bBool );} void GenReturn( comm_USHORT nRet, SmartId aUId, comm_USHORT nMethod, comm_ULONG nNr ){CmdBaseStream::GenReturn( nRet, &aUId, nMethod, nNr );} // new void GenReturn( USHORT nRet, SmartId aUId, String aString ); void GenReturn( USHORT nRet, SmartId aUId, SbxValue &aValue ); void GenReturn( USHORT nRet, SmartId aUId, ULONG nNr, String aString, BOOL bBool ); // MacroRecorder void GenReturn( USHORT nRet, SmartId aUId, USHORT nMethod, String aString ); void GenReturn( USHORT nRet, SmartId aUId, USHORT nMethod, String aString, BOOL bBool ); void Reset(); SvStream* GetStream(); // CmdBaseStream::Write; void Write( comm_USHORT nNr ){CmdBaseStream::Write( nNr );} void Write( comm_ULONG nNr ){CmdBaseStream::Write( nNr );} // void Write( const comm_UniChar* aString, comm_USHORT nLenInChars ){CmdBaseStream::Write( aString, nLenInChars );} void Write( comm_BOOL bBool ){CmdBaseStream::Write( bBool );} // new void Write( SbxValue &aValue ); // Complex Datatypes to be handled system dependent virtual void Write( SmartId* pId ); virtual void Write( String *pString ); SvStream *pSammel; }; #endif <commit_msg>INTEGRATION: CWS visibility03 (1.3.10); FILE MERGED 2005/04/01 16:59:57 mhu 1.3.10.1: #i45006# Replaced includes svtools/sbx*.hxx with basic/sbx*.hxx<commit_after>/************************************************************************* * * $RCSfile: retstrm.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2005-04-13 09:54:27 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2002 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2002 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _RETSTRM_HXX #define _RETSTRM_HXX #ifndef _SBXVAR_HXX //autogen #include <basic/sbxvar.hxx> #endif #ifndef _SMARTID_HXX_ #include <vcl/smartid.hxx> #endif #include "cmdbasestream.hxx" class SvStream; class RetStream: public CmdBaseStream { public: RetStream(); ~RetStream(); // CmdBaseStream::GenError; // void GenError( comm_ULONG nError, const comm_UniChar* aString, comm_USHORT nLenInChars ){CmdBaseStream::GenError( nError, aString, nLenInChars );} // new void GenError( SmartId aUId, String aString ); // CmdBaseStream::GenReturn; void GenReturn( comm_USHORT nRet, comm_ULONG nNr ){CmdBaseStream::GenReturn( nRet, nNr );} void GenReturn( comm_USHORT nRet, SmartId aUId, comm_ULONG nNr ){CmdBaseStream::GenReturn( nRet, &aUId, nNr );} // void GenReturn( comm_USHORT nRet, comm_ULONG nUId, const comm_UniChar* aString, comm_USHORT nLenInChars ){CmdBaseStream::GenReturn( nRet, nUId, aString, nLenInChars );} void GenReturn( comm_USHORT nRet, SmartId aUId, comm_BOOL bBool ){CmdBaseStream::GenReturn( nRet, &aUId, bBool );} // void GenReturn( comm_USHORT nRet, comm_ULONG nUId, comm_ULONG nNr, const comm_UniChar* aString, comm_USHORT nLenInChars, comm_BOOL bBool ){CmdBaseStream::GenReturn( nRet, nUId, nNr, aString, nLenInChars, bBool );} // MacroRecorder void GenReturn( comm_USHORT nRet, SmartId aUId, comm_USHORT nMethod ){CmdBaseStream::GenReturn( nRet, &aUId, nMethod );} // void GenReturn( comm_USHORT nRet, comm_ULONG nUId, comm_USHORT nMethod, const comm_UniChar* aString, comm_USHORT nLenInChars ){CmdBaseStream::GenReturn( nRet, nUId, nMethod, aString, nLenInChars );} // void GenReturn( comm_USHORT nRet, comm_ULONG nUId, comm_USHORT nMethod, const comm_UniChar* aString, comm_USHORT nLenInChars, comm_BOOL bBool ){CmdBaseStream::GenReturn( nRet, nUId, nMethod, aString, nLenInChars, bBool );} void GenReturn( comm_USHORT nRet, SmartId aUId, comm_USHORT nMethod, comm_BOOL bBool ){CmdBaseStream::GenReturn( nRet, &aUId, nMethod, bBool );} void GenReturn( comm_USHORT nRet, SmartId aUId, comm_USHORT nMethod, comm_ULONG nNr ){CmdBaseStream::GenReturn( nRet, &aUId, nMethod, nNr );} // new void GenReturn( USHORT nRet, SmartId aUId, String aString ); void GenReturn( USHORT nRet, SmartId aUId, SbxValue &aValue ); void GenReturn( USHORT nRet, SmartId aUId, ULONG nNr, String aString, BOOL bBool ); // MacroRecorder void GenReturn( USHORT nRet, SmartId aUId, USHORT nMethod, String aString ); void GenReturn( USHORT nRet, SmartId aUId, USHORT nMethod, String aString, BOOL bBool ); void Reset(); SvStream* GetStream(); // CmdBaseStream::Write; void Write( comm_USHORT nNr ){CmdBaseStream::Write( nNr );} void Write( comm_ULONG nNr ){CmdBaseStream::Write( nNr );} // void Write( const comm_UniChar* aString, comm_USHORT nLenInChars ){CmdBaseStream::Write( aString, nLenInChars );} void Write( comm_BOOL bBool ){CmdBaseStream::Write( bBool );} // new void Write( SbxValue &aValue ); // Complex Datatypes to be handled system dependent virtual void Write( SmartId* pId ); virtual void Write( String *pString ); SvStream *pSammel; }; #endif <|endoftext|>
<commit_before>#include "newarc.h" ArchiveModuleManager::ArchiveModuleManager(const TCHAR* lpCurrentLanguage) { m_bLoaded = false; m_pFilter = new ArchiveFilter(this, true); m_strCurrentLanguage = lpCurrentLanguage; } bool ArchiveModuleManager::LoadIfNeeded() { if ( !m_bLoaded ) { string strModulesPath = Info.ModuleName; CutToSlash(strModulesPath); strModulesPath += _T("Plugins"); //BUGBUG, to change FSF.FarRecursiveSearch(strModulesPath, _T("*.module"), (FRSUSERFUNC)LoadModules, FRS_RECUR, this); CutToSlash(strModulesPath); strModulesPath += _T("filters.ini"); m_pFilter->Load(strModulesPath); CutToSlash(strModulesPath); strModulesPath += _T("templates.ini"); LoadTemplates(strModulesPath); /* ArchiveFormatInfoArray formats; GetFormats(formats); __debug(_T("formats - %d"), formats.count()); */ m_bLoaded = true; } return m_bLoaded; } int __stdcall ArchiveModuleManager::LoadModules( const FAR_FIND_DATA* pFindData, const TCHAR* lpFullName, ArchiveModuleManager* pManager ) { if ( pFindData->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) return TRUE; ArchiveModule *pModule = new ArchiveModule(pManager); if ( pModule ) { if ( pModule->Load(lpFullName, pManager->m_strCurrentLanguage) ) { pManager->m_pModules.add(pModule); return TRUE; } delete pModule; } return TRUE; } ArchiveModuleManager::~ArchiveModuleManager() { delete m_pFilter; } ArchiveFilter* ArchiveModuleManager::GetFilter() { return m_pFilter; } void ArchiveModuleManager::SetCurrentLanguage(const TCHAR* lpLanguage) { if ( FSF.LStricmp(lpLanguage, m_strCurrentLanguage) ) { for (int i = 0; i < m_pModules.count(); i++) m_pModules[i]->ReloadLanguage (lpLanguage); m_strCurrentLanguage = lpLanguage; } } //, int ArchiveModuleManager::QueryArchives( const TCHAR *lpFileName, const unsigned char *pBuffer, DWORD dwBufferSize, Array<ArchiveFormat*>& result ) { bool bStopped = false; Array<ArchiveFilterEntry*> filters; m_pFilter->Reset(); m_pFilter->QueryFilters(lpFileName, filters, bStopped); for (int i = 0; i < filters.count(); i++) { ArchiveFilterEntry* pFE = filters[i]; ArchiveModule* pModule = pFE->pModule; bool bNoPluginsFiltered = true; bool bNoFormatsFiltered = true; if ( !m_pFilter->Filtered(&pModule->GetUID(), NULL, NULL) ) { if ( pFE->bAllPlugins ) { Array<ArchivePlugin*>& plugins = pModule->GetPlugins(); for (int i = 0; i < plugins.count(); i++) { ArchivePlugin* pPlugin = plugins[i]; if ( !m_pFilter->Filtered(&pModule->GetUID(), &pPlugin->GetUID(), NULL) ) { if ( pModule->QueryCapability(AMF_SUPPORT_SINGLE_PLUGIN_QUERY) ) { Array<ArchiveFormat*>& formats = pPlugin->GetFormats(); for (int j = 0; j < formats.count(); j++) { ArchiveFormat* pFormat = formats[i]; if ( !m_pFilter->Filtered(&pModule->GetUID(), &pPlugin->GetUID(), &pFormat->GetUID()) ) { if ( pPlugin->QueryCapability(APF_SUPPORT_SINGLE_FORMAT_QUERY) ) pModule->QueryArchives(&pPlugin->GetUID(), &pFormat->GetUID(), lpFileName, pBuffer, dwBufferSize, result); } else bNoFormatsFiltered = false; } if ( bNoFormatsFiltered && !pPlugin->QueryCapability(APF_SUPPORT_SINGLE_FORMAT_QUERY) ) pModule->QueryArchives(&pPlugin->GetUID(), NULL, lpFileName, pBuffer, dwBufferSize, result); } else bNoPluginsFiltered = false; } if ( bNoPluginsFiltered && !pModule->QueryCapability(AMF_SUPPORT_SINGLE_PLUGIN_QUERY) ) pModule->QueryArchives(NULL, NULL, lpFileName, pBuffer, dwBufferSize, result); } } else { if ( pFE->bAllFormats ) { ArchivePlugin* pPlugin = pFE->pPlugin; if ( !m_pFilter->Filtered(&pModule->GetUID(), &pPlugin->GetUID(), NULL) ) { Array<ArchiveFormat*>& formats = pPlugin->GetFormats(); for (int i = 0; i < formats.count(); i++) { ArchiveFormat* pFormat = formats[i]; if ( !m_pFilter->Filtered(&pModule->GetUID(), &pPlugin->GetUID(), &pFormat->GetUID()) ) { if ( pPlugin->QueryCapability(APF_SUPPORT_SINGLE_FORMAT_QUERY) ) pModule->QueryArchives(&pPlugin->GetUID(), &pFormat->GetUID(), lpFileName, pBuffer, dwBufferSize, result); } else bNoFormatsFiltered = false; } if ( bNoFormatsFiltered && !pPlugin->QueryCapability(APF_SUPPORT_SINGLE_FORMAT_QUERY) ) pModule->QueryArchives(&pPlugin->GetUID(), NULL, lpFileName, pBuffer, dwBufferSize, result); } } else { ArchiveFormat* pFormat = pFE->pFormat; ArchivePlugin* pPlugin = pFE->pPlugin; if ( !m_pFilter->Filtered(&pModule->GetUID(), &pPlugin->GetUID(), &pFormat->GetUID()) ) { if ( pPlugin->QueryCapability(APF_SUPPORT_SINGLE_FORMAT_QUERY) ) pModule->QueryArchives(&pPlugin->GetUID(), &pFormat->GetUID(), lpFileName, pBuffer, dwBufferSize, result); } } } } m_pFilter->AddStopFilter(filters[i]); } if ( !bStopped && m_pFilter->UseRemaining() ) { for (int i = 0; i < m_pModules.count(); i++) { bool bNoPluginsFiltered = true; bool bNoFormatsFiltered = true; ArchiveModule* pModule = m_pModules[i]; if ( !m_pFilter->Filtered(&pModule->GetUID(), NULL, NULL) ) { Array<ArchivePlugin*>& plugins = pModule->GetPlugins(); for (unsigned int j = 0; j < plugins.count(); j++) { ArchivePlugin* pPlugin = plugins[j]; if ( !m_pFilter->Filtered(&pModule->GetUID(), &pPlugin->GetUID(), NULL) ) { Array<ArchiveFormat*>& formats = pPlugin->GetFormats(); for (unsigned int k = 0; k < formats.count(); k++) { ArchiveFormat* pFormat = formats[k]; if ( !m_pFilter->Filtered(&pModule->GetUID(), &pPlugin->GetUID(), &pFormat->GetUID()) ) { if ( pPlugin->QueryCapability(APF_SUPPORT_SINGLE_FORMAT_QUERY) ) pModule->QueryArchives(&pPlugin->GetUID(), &pFormat->GetUID(), lpFileName, pBuffer, dwBufferSize, result); } else bNoFormatsFiltered = false; } if ( bNoFormatsFiltered && !pPlugin->QueryCapability(APF_SUPPORT_SINGLE_FORMAT_QUERY) ) pModule->QueryArchives(&pPlugin->GetUID(), NULL, lpFileName, pBuffer, dwBufferSize, result); } else bNoPluginsFiltered = false; } if ( bNoPluginsFiltered && !pModule->QueryCapability(AMF_SUPPORT_SINGLE_PLUGIN_QUERY) ) pModule->QueryArchives(NULL, NULL, lpFileName, pBuffer, dwBufferSize, result); } } } return 0; } ArchiveModule* ArchiveModuleManager::GetModule(const GUID &uid) { for (int i = 0; i < m_pModules.count(); i++) { if ( m_pModules[i]->GetUID() == uid ) return m_pModules[i]; } return NULL; } int ArchiveModuleManager::GetPlugins(Array<ArchivePlugin*>& plugins) { for (int i = 0; i < m_pModules.count(); i++) m_pModules[i]->GetPlugins(plugins); return 0; } ArchiveFormat* ArchiveModuleManager::GetFormat(const GUID& uidModule, const GUID& uidPlugin, const GUID& uidFormat) { ArchiveModule* pModule = GetModule(uidModule); if ( pModule ) return pModule->GetFormat(uidPlugin, uidFormat); return NULL; } int ArchiveModuleManager::GetFormats(Array<ArchiveFormat*>& formats) { for (int i = 0; i < m_pModules.count(); i++) m_pModules[i]->GetFormats(formats); return 0; } Array<ArchiveModule*>& ArchiveModuleManager::GetModules() { return m_pModules; } Archive* ArchiveModuleManager::OpenCreateArchive( ArchiveFormat* pFormat, const TCHAR* lpFileName, HANDLE hCallback, ARCHIVECALLBACK pfnCallback, bool bCreate ) { HANDLE hArchive = pFormat->GetModule()->OpenCreateArchive( pFormat->GetPlugin()->GetUID(), pFormat->GetUID(), lpFileName, hCallback, pfnCallback, bCreate ); if ( hArchive ) return new Archive(hArchive, pFormat, lpFileName); if ( bCreate ) return new Archive(NULL, pFormat, lpFileName); return NULL; } void ArchiveModuleManager::CloseArchive(Archive* pArchive) { if ( pArchive->GetHandle() ) pArchive->GetModule()->CloseArchive(pArchive->GetPlugin()->GetUID(), pArchive->GetHandle()); delete pArchive; } bool ArchiveModuleManager::LoadTemplates(const TCHAR* lpFileName) { TCHAR szNames[4096]; if ( !GetPrivateProfileSectionNames(szNames, 4096, lpFileName) ) return false; m_pTemplates.reset(); Array<const TCHAR*> names; const TCHAR *lpName = szNames; while ( *lpName ) { names.add(lpName); lpName += _tcslen (lpName)+1; } for (int i = 0; i < names.count(); i++) { string strName = names[i]; string strParams; TCHAR* pBuffer = strParams.GetBuffer(260); //BUGBUG GetPrivateProfileString(strName, _T("Params"), _T(""), pBuffer, 260, lpFileName); strParams.ReleaseBuffer(); TCHAR szGUID[64]; GetPrivateProfileString(strName, _T("ModuleUID"), _T(""), szGUID, 64, lpFileName); GUID uidModule = STR2GUID(szGUID); GetPrivateProfileString(strName, _T("PluginUID"), _T(""), szGUID, 64, lpFileName); GUID uidPlugin = STR2GUID(szGUID); GetPrivateProfileString(strName, _T("FormatUID"), _T(""), szGUID, 64, lpFileName); GUID uidFormat = STR2GUID(szGUID); m_pTemplates.add(new ArchiveTemplate(this, strName, strParams, uidModule, uidPlugin, uidFormat)); } return true; } bool ArchiveModuleManager::SaveTemplates(const TCHAR* lpFileName) { DeleteFile(lpFileName); string strFileName = Info.ModuleName; CutToSlash(strFileName); strFileName += lpFileName; for (int i = 0; i < m_pTemplates.count(); i++) { ArchiveTemplate* pAT = m_pTemplates[i]; WritePrivateProfileString(pAT->GetName(), _T("Params"), pAT->GetParams(), strFileName); WritePrivateProfileString(pAT->GetName(), _T("ModuleUID"), GUID2STR(pAT->GetModuleUID()), strFileName); WritePrivateProfileString(pAT->GetName(), _T("PluginUID"), GUID2STR(pAT->GetPluginUID()), strFileName); WritePrivateProfileString(pAT->GetName(), _T("FormatUID"), GUID2STR(pAT->GetFormatUID()), strFileName); } return true; } Array<ArchiveTemplate*>& ArchiveModuleManager::GetTemplates() { return m_pTemplates; }<commit_msg>modules<commit_after>#include "newarc.h" ArchiveModuleManager::ArchiveModuleManager(const TCHAR* lpCurrentLanguage) { m_bLoaded = false; m_pFilter = new ArchiveFilter(this, true); m_strCurrentLanguage = lpCurrentLanguage; } bool ArchiveModuleManager::LoadIfNeeded() { if ( !m_bLoaded ) { string strModulesPath = Info.ModuleName; CutToSlash(strModulesPath); strModulesPath += _T("Modules"); FSF.FarRecursiveSearch(strModulesPath, _T("*.module"), (FRSUSERFUNC)LoadModules, FRS_RECUR, this); CutToSlash(strModulesPath); strModulesPath += _T("filters.ini"); m_pFilter->Load(strModulesPath); CutToSlash(strModulesPath); strModulesPath += _T("templates.ini"); LoadTemplates(strModulesPath); /* ArchiveFormatInfoArray formats; GetFormats(formats); __debug(_T("formats - %d"), formats.count()); */ m_bLoaded = true; } return m_bLoaded; } int __stdcall ArchiveModuleManager::LoadModules( const FAR_FIND_DATA* pFindData, const TCHAR* lpFullName, ArchiveModuleManager* pManager ) { if ( pFindData->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) return TRUE; ArchiveModule *pModule = new ArchiveModule(pManager); if ( pModule ) { if ( pModule->Load(lpFullName, pManager->m_strCurrentLanguage) ) { pManager->m_pModules.add(pModule); return TRUE; } delete pModule; } return TRUE; } ArchiveModuleManager::~ArchiveModuleManager() { delete m_pFilter; } ArchiveFilter* ArchiveModuleManager::GetFilter() { return m_pFilter; } void ArchiveModuleManager::SetCurrentLanguage(const TCHAR* lpLanguage) { if ( FSF.LStricmp(lpLanguage, m_strCurrentLanguage) ) { for (int i = 0; i < m_pModules.count(); i++) m_pModules[i]->ReloadLanguage (lpLanguage); m_strCurrentLanguage = lpLanguage; } } //, int ArchiveModuleManager::QueryArchives( const TCHAR *lpFileName, const unsigned char *pBuffer, DWORD dwBufferSize, Array<ArchiveFormat*>& result ) { bool bStopped = false; Array<ArchiveFilterEntry*> filters; m_pFilter->Reset(); m_pFilter->QueryFilters(lpFileName, filters, bStopped); for (int i = 0; i < filters.count(); i++) { ArchiveFilterEntry* pFE = filters[i]; ArchiveModule* pModule = pFE->pModule; bool bNoPluginsFiltered = true; bool bNoFormatsFiltered = true; if ( !m_pFilter->Filtered(&pModule->GetUID(), NULL, NULL) ) { if ( pFE->bAllPlugins ) { Array<ArchivePlugin*>& plugins = pModule->GetPlugins(); for (int i = 0; i < plugins.count(); i++) { ArchivePlugin* pPlugin = plugins[i]; if ( !m_pFilter->Filtered(&pModule->GetUID(), &pPlugin->GetUID(), NULL) ) { if ( pModule->QueryCapability(AMF_SUPPORT_SINGLE_PLUGIN_QUERY) ) { Array<ArchiveFormat*>& formats = pPlugin->GetFormats(); for (int j = 0; j < formats.count(); j++) { ArchiveFormat* pFormat = formats[i]; if ( !m_pFilter->Filtered(&pModule->GetUID(), &pPlugin->GetUID(), &pFormat->GetUID()) ) { if ( pPlugin->QueryCapability(APF_SUPPORT_SINGLE_FORMAT_QUERY) ) pModule->QueryArchives(&pPlugin->GetUID(), &pFormat->GetUID(), lpFileName, pBuffer, dwBufferSize, result); } else bNoFormatsFiltered = false; } if ( bNoFormatsFiltered && !pPlugin->QueryCapability(APF_SUPPORT_SINGLE_FORMAT_QUERY) ) pModule->QueryArchives(&pPlugin->GetUID(), NULL, lpFileName, pBuffer, dwBufferSize, result); } else bNoPluginsFiltered = false; } if ( bNoPluginsFiltered && !pModule->QueryCapability(AMF_SUPPORT_SINGLE_PLUGIN_QUERY) ) pModule->QueryArchives(NULL, NULL, lpFileName, pBuffer, dwBufferSize, result); } } else { if ( pFE->bAllFormats ) { ArchivePlugin* pPlugin = pFE->pPlugin; if ( !m_pFilter->Filtered(&pModule->GetUID(), &pPlugin->GetUID(), NULL) ) { Array<ArchiveFormat*>& formats = pPlugin->GetFormats(); for (int i = 0; i < formats.count(); i++) { ArchiveFormat* pFormat = formats[i]; if ( !m_pFilter->Filtered(&pModule->GetUID(), &pPlugin->GetUID(), &pFormat->GetUID()) ) { if ( pPlugin->QueryCapability(APF_SUPPORT_SINGLE_FORMAT_QUERY) ) pModule->QueryArchives(&pPlugin->GetUID(), &pFormat->GetUID(), lpFileName, pBuffer, dwBufferSize, result); } else bNoFormatsFiltered = false; } if ( bNoFormatsFiltered && !pPlugin->QueryCapability(APF_SUPPORT_SINGLE_FORMAT_QUERY) ) pModule->QueryArchives(&pPlugin->GetUID(), NULL, lpFileName, pBuffer, dwBufferSize, result); } } else { ArchiveFormat* pFormat = pFE->pFormat; ArchivePlugin* pPlugin = pFE->pPlugin; if ( !m_pFilter->Filtered(&pModule->GetUID(), &pPlugin->GetUID(), &pFormat->GetUID()) ) { if ( pPlugin->QueryCapability(APF_SUPPORT_SINGLE_FORMAT_QUERY) ) pModule->QueryArchives(&pPlugin->GetUID(), &pFormat->GetUID(), lpFileName, pBuffer, dwBufferSize, result); } } } } m_pFilter->AddStopFilter(filters[i]); } if ( !bStopped && m_pFilter->UseRemaining() ) { for (int i = 0; i < m_pModules.count(); i++) { bool bNoPluginsFiltered = true; bool bNoFormatsFiltered = true; ArchiveModule* pModule = m_pModules[i]; if ( !m_pFilter->Filtered(&pModule->GetUID(), NULL, NULL) ) { Array<ArchivePlugin*>& plugins = pModule->GetPlugins(); for (unsigned int j = 0; j < plugins.count(); j++) { ArchivePlugin* pPlugin = plugins[j]; if ( !m_pFilter->Filtered(&pModule->GetUID(), &pPlugin->GetUID(), NULL) ) { Array<ArchiveFormat*>& formats = pPlugin->GetFormats(); for (unsigned int k = 0; k < formats.count(); k++) { ArchiveFormat* pFormat = formats[k]; if ( !m_pFilter->Filtered(&pModule->GetUID(), &pPlugin->GetUID(), &pFormat->GetUID()) ) { if ( pPlugin->QueryCapability(APF_SUPPORT_SINGLE_FORMAT_QUERY) ) pModule->QueryArchives(&pPlugin->GetUID(), &pFormat->GetUID(), lpFileName, pBuffer, dwBufferSize, result); } else bNoFormatsFiltered = false; } if ( bNoFormatsFiltered && !pPlugin->QueryCapability(APF_SUPPORT_SINGLE_FORMAT_QUERY) ) pModule->QueryArchives(&pPlugin->GetUID(), NULL, lpFileName, pBuffer, dwBufferSize, result); } else bNoPluginsFiltered = false; } if ( bNoPluginsFiltered && !pModule->QueryCapability(AMF_SUPPORT_SINGLE_PLUGIN_QUERY) ) pModule->QueryArchives(NULL, NULL, lpFileName, pBuffer, dwBufferSize, result); } } } return 0; } ArchiveModule* ArchiveModuleManager::GetModule(const GUID &uid) { for (int i = 0; i < m_pModules.count(); i++) { if ( m_pModules[i]->GetUID() == uid ) return m_pModules[i]; } return NULL; } int ArchiveModuleManager::GetPlugins(Array<ArchivePlugin*>& plugins) { for (int i = 0; i < m_pModules.count(); i++) m_pModules[i]->GetPlugins(plugins); return 0; } ArchiveFormat* ArchiveModuleManager::GetFormat(const GUID& uidModule, const GUID& uidPlugin, const GUID& uidFormat) { ArchiveModule* pModule = GetModule(uidModule); if ( pModule ) return pModule->GetFormat(uidPlugin, uidFormat); return NULL; } int ArchiveModuleManager::GetFormats(Array<ArchiveFormat*>& formats) { for (int i = 0; i < m_pModules.count(); i++) m_pModules[i]->GetFormats(formats); return 0; } Array<ArchiveModule*>& ArchiveModuleManager::GetModules() { return m_pModules; } Archive* ArchiveModuleManager::OpenCreateArchive( ArchiveFormat* pFormat, const TCHAR* lpFileName, HANDLE hCallback, ARCHIVECALLBACK pfnCallback, bool bCreate ) { HANDLE hArchive = pFormat->GetModule()->OpenCreateArchive( pFormat->GetPlugin()->GetUID(), pFormat->GetUID(), lpFileName, hCallback, pfnCallback, bCreate ); if ( hArchive ) return new Archive(hArchive, pFormat, lpFileName); if ( bCreate ) return new Archive(NULL, pFormat, lpFileName); return NULL; } void ArchiveModuleManager::CloseArchive(Archive* pArchive) { if ( pArchive->GetHandle() ) pArchive->GetModule()->CloseArchive(pArchive->GetPlugin()->GetUID(), pArchive->GetHandle()); delete pArchive; } bool ArchiveModuleManager::LoadTemplates(const TCHAR* lpFileName) { TCHAR szNames[4096]; if ( !GetPrivateProfileSectionNames(szNames, 4096, lpFileName) ) return false; m_pTemplates.reset(); Array<const TCHAR*> names; const TCHAR *lpName = szNames; while ( *lpName ) { names.add(lpName); lpName += _tcslen (lpName)+1; } for (int i = 0; i < names.count(); i++) { string strName = names[i]; string strParams; TCHAR* pBuffer = strParams.GetBuffer(260); //BUGBUG GetPrivateProfileString(strName, _T("Params"), _T(""), pBuffer, 260, lpFileName); strParams.ReleaseBuffer(); TCHAR szGUID[64]; GetPrivateProfileString(strName, _T("ModuleUID"), _T(""), szGUID, 64, lpFileName); GUID uidModule = STR2GUID(szGUID); GetPrivateProfileString(strName, _T("PluginUID"), _T(""), szGUID, 64, lpFileName); GUID uidPlugin = STR2GUID(szGUID); GetPrivateProfileString(strName, _T("FormatUID"), _T(""), szGUID, 64, lpFileName); GUID uidFormat = STR2GUID(szGUID); m_pTemplates.add(new ArchiveTemplate(this, strName, strParams, uidModule, uidPlugin, uidFormat)); } return true; } bool ArchiveModuleManager::SaveTemplates(const TCHAR* lpFileName) { DeleteFile(lpFileName); string strFileName = Info.ModuleName; CutToSlash(strFileName); strFileName += lpFileName; for (int i = 0; i < m_pTemplates.count(); i++) { ArchiveTemplate* pAT = m_pTemplates[i]; WritePrivateProfileString(pAT->GetName(), _T("Params"), pAT->GetParams(), strFileName); WritePrivateProfileString(pAT->GetName(), _T("ModuleUID"), GUID2STR(pAT->GetModuleUID()), strFileName); WritePrivateProfileString(pAT->GetName(), _T("PluginUID"), GUID2STR(pAT->GetPluginUID()), strFileName); WritePrivateProfileString(pAT->GetName(), _T("FormatUID"), GUID2STR(pAT->GetFormatUID()), strFileName); } return true; } Array<ArchiveTemplate*>& ArchiveModuleManager::GetTemplates() { return m_pTemplates; }<|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo 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. *****************************************************************************/ #include "modules/planning/planning.h" #include <algorithm> #include <vector> #include "google/protobuf/repeated_field.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/time/time.h" #include "modules/common/vehicle_state/vehicle_state.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/planner/em/em_planner.h" #include "modules/planning/planner/rtk/rtk_replay_planner.h" #include "modules/planning/reference_line/reference_line_provider.h" #include "modules/planning/trajectory_stitcher/trajectory_stitcher.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::VehicleState; using apollo::common::adapter::AdapterManager; using apollo::common::time::Clock; std::string Planning::Name() const { return "planning"; } void Planning::RegisterPlanners() { planner_factory_.Register( PlanningConfig::RTK, []() -> Planner* { return new RTKReplayPlanner(); }); planner_factory_.Register(PlanningConfig::EM, []() -> Planner* { return new EMPlanner(); }); } Status Planning::InitFrame(const uint32_t sequence_num, const double timestamp, const TrajectoryPoint& init_adc_point) { frame_.reset(new Frame(sequence_num)); frame_->SetPlanningStartPoint(init_adc_point); if (AdapterManager::GetRoutingResponse()->Empty()) { AERROR << "Routing is empty"; return Status(ErrorCode::PLANNING_ERROR, "routing is empty"); } frame_->UpdateRoutingResponse( AdapterManager::GetRoutingResponse()->GetLatestObserved()); frame_->SetVehicleInitPose(VehicleState::instance()->pose()); if (FLAGS_enable_prediction && !AdapterManager::GetPrediction()->Empty()) { const auto& prediction = AdapterManager::GetPrediction()->GetLatestObserved(); frame_->SetPrediction(prediction); ADEBUG << "Get prediction: " << prediction.DebugString(); } auto status = frame_->Init(config_, timestamp); if (!status.ok()) { AERROR << "failed to init frame"; return Status(ErrorCode::PLANNING_ERROR, "init frame failed"); } return Status::OK(); } bool Planning::HasSignalLight(const PlanningConfig& config) { for (const auto& rule_config : config.rule_config()) { if (rule_config.rule_id() == RuleConfig::SIGNAL_LIGHT) { return true; } } return false; } Status Planning::Init() { hdmap_ = apollo::hdmap::HDMapUtil::BaseMapPtr(); CHECK(hdmap_) << "Failed to load map file:" << apollo::hdmap::BaseMapFile(); Frame::SetMap(hdmap_); CHECK(apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file, &config_)) << "failed to load planning config file " << FLAGS_planning_config_file; if (!AdapterManager::Initialized()) { AdapterManager::Init(FLAGS_adapter_config_filename); } if (AdapterManager::GetLocalization() == nullptr) { std::string error_msg("Localization is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetChassis() == nullptr) { std::string error_msg("Chassis is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetRoutingResponse() == nullptr) { std::string error_msg("RoutingResponse is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (FLAGS_enable_prediction && AdapterManager::GetPrediction() == nullptr) { std::string error_msg("Prediction is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (HasSignalLight(config_) && AdapterManager::GetTrafficLightDetection() == nullptr) { std::string error_msg("Traffic Light Detection is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (FLAGS_enable_reference_line_provider_thread) { ReferenceLineProvider::instance()->Init( hdmap_, config_.reference_line_smoother_config()); } RegisterPlanners(); planner_ = planner_factory_.CreateObject(config_.planner_type()); if (!planner_) { return Status( ErrorCode::PLANNING_ERROR, "planning is not initialized with config : " + config_.DebugString()); } return planner_->Init(config_); } bool Planning::IsVehicleStateValid(const common::VehicleState& vehicle_state) { if (std::isnan(vehicle_state.x()) || std::isnan(vehicle_state.y()) || std::isnan(vehicle_state.z()) || std::isnan(vehicle_state.heading()) || std::isnan(vehicle_state.kappa()) || std::isnan(vehicle_state.linear_velocity()) || std::isnan(vehicle_state.linear_acceleration())) { return false; } return true; } Status Planning::Start() { if (FLAGS_enable_reference_line_provider_thread) { ReferenceLineProvider::instance()->Start(); } timer_ = AdapterManager::CreateTimer( ros::Duration(1.0 / FLAGS_planning_loop_rate), &Planning::OnTimer, this); return Status::OK(); } void Planning::OnTimer(const ros::TimerEvent&) { RunOnce(); if (frame_) { auto seq_num = frame_->SequenceNum(); FrameHistory::instance()->Add(seq_num, std::move(frame_)); } } void Planning::PublishPlanningPb(ADCTrajectory* trajectory_pb, double timestamp) { AdapterManager::FillPlanningHeader(Name(), trajectory_pb); trajectory_pb->mutable_header()->set_timestamp_sec(timestamp); // TODO(all): integrate reverse gear trajectory_pb->set_gear(canbus::Chassis::GEAR_DRIVE); AdapterManager::PublishPlanning(*trajectory_pb); } void Planning::RunOnce() { const double start_timestamp = Clock::NowInSecond(); AdapterManager::Observe(); ADCTrajectory not_ready_pb; auto* not_ready = not_ready_pb.mutable_decision() ->mutable_main_decision() ->mutable_not_ready(); if (AdapterManager::GetLocalization()->Empty()) { not_ready->set_reason("localization not ready"); } else if (AdapterManager::GetChassis()->Empty()) { not_ready->set_reason("chassis not ready"); } else if (AdapterManager::GetRoutingResponse()->Empty()) { not_ready->set_reason("routing not ready"); } else if (FLAGS_enable_prediction && AdapterManager::GetPrediction()->Empty()) { not_ready->set_reason("prediction not ready"); } if (not_ready->has_reason()) { AERROR << not_ready->reason() << "; skip the planning cycle."; PublishPlanningPb(&not_ready_pb, start_timestamp); return; } // localization const auto& localization = AdapterManager::GetLocalization()->GetLatestObserved(); ADEBUG << "Get localization:" << localization.DebugString(); // chassis const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved(); ADEBUG << "Get chassis:" << chassis.DebugString(); common::Status status = common::VehicleState::instance()->Update(localization, chassis); DCHECK(IsVehicleStateValid(*common::VehicleState::instance())); if (!status.ok()) { AERROR << "Update VehicleState failed."; not_ready->set_reason("Update VehicleState failed."); status.Save(not_ready_pb.mutable_header()->mutable_status()); PublishPlanningPb(&not_ready_pb, start_timestamp); return; } const double planning_cycle_time = 1.0 / FLAGS_planning_loop_rate; bool is_auto_mode = chassis.driving_mode() == chassis.COMPLETE_AUTO_DRIVE; bool is_replan = false; const auto& stitching_trajectory = TrajectoryStitcher::ComputeStitchingTrajectory( is_auto_mode, start_timestamp, planning_cycle_time, last_publishable_trajectory_.get(), &is_replan); const uint32_t frame_num = AdapterManager::GetPlanning()->GetSeqNum() + 1; status = InitFrame(frame_num, start_timestamp, stitching_trajectory.back()); ADCTrajectory trajectory_pb; if (FLAGS_enable_record_debug) { frame_->RecordInputDebug(trajectory_pb.mutable_debug()); } trajectory_pb.mutable_latency_stats()->set_init_frame_time_ms( Clock::NowInSecond() - start_timestamp); if (!status.ok()) { AERROR << "Init frame failed"; if (FLAGS_publish_estop) { ADCTrajectory estop; estop.mutable_estop(); status.Save(estop.mutable_header()->mutable_status()); PublishPlanningPb(&estop, start_timestamp); } return; } status = Plan(start_timestamp, stitching_trajectory, &trajectory_pb); const auto time_diff_ms = (Clock::NowInSecond() - start_timestamp) * 1000; ADEBUG << "total planning time spend: " << time_diff_ms << " ms."; trajectory_pb.mutable_latency_stats()->set_total_time_ms(time_diff_ms); ADEBUG << "Planning latency: " << trajectory_pb.latency_stats().DebugString(); if (status.ok()) { trajectory_pb.set_is_replan(is_replan); PublishPlanningPb(&trajectory_pb, start_timestamp); ADEBUG << "Planning succeeded:" << trajectory_pb.header().DebugString(); } else if (FLAGS_publish_estop) { trajectory_pb.mutable_estop(); status.Save(trajectory_pb.mutable_header()->mutable_status()); PublishPlanningPb(&trajectory_pb, start_timestamp); AERROR << "Planning failed"; } } void Planning::Stop() { AERROR << "Planning Stop is called"; if (FLAGS_enable_reference_line_provider_thread) { ReferenceLineProvider::instance()->Stop(); } last_publishable_trajectory_.reset(nullptr); frame_.reset(nullptr); planner_.reset(nullptr); } void Planning::SetLastPublishableTrajectory( const ADCTrajectory& adc_trajectory) { last_publishable_trajectory_.reset(new PublishableTrajectory(adc_trajectory)); } common::Status Planning::Plan( const double current_time_stamp, const std::vector<common::TrajectoryPoint>& stitching_trajectory, ADCTrajectory* trajectory_pb) { auto* ptr_debug = trajectory_pb->mutable_debug(); if (FLAGS_enable_record_debug) { ptr_debug->mutable_planning_data()->mutable_init_point()->CopyFrom( stitching_trajectory.back()); } auto status = Status::OK(); for (auto& reference_line_info : frame_->reference_line_info()) { status = planner_->Plan(stitching_trajectory.back(), frame_.get(), &reference_line_info); AERROR_IF(!status.ok()) << "planner failed to make a driving plan."; } const auto* best_reference_line = frame_->FindDriveReferenceLineInfo(); if (!best_reference_line) { std::string msg( "planner failed to make a driving plan because NO best_reference_line " "can be provided."); AERROR << msg; last_publishable_trajectory_->Clear(); return Status(ErrorCode::PLANNING_ERROR, msg); } ptr_debug->MergeFrom(best_reference_line->debug()); trajectory_pb->mutable_latency_stats()->MergeFrom( best_reference_line->latency_stats()); best_reference_line->ExportDecision(trajectory_pb->mutable_decision()); // Add debug information. if (FLAGS_enable_record_debug) { auto* reference_line = ptr_debug->mutable_planning_data()->add_path(); reference_line->set_name("planning_reference_line"); const auto& reference_points = best_reference_line->reference_line().reference_points(); for (const auto& reference_point : reference_points) { auto* path_point = reference_line->add_path_point(); path_point->set_x(reference_point.x()); path_point->set_y(reference_point.y()); path_point->set_theta(reference_point.heading()); path_point->set_kappa(reference_point.kappa()); path_point->set_dkappa(reference_point.dkappa()); } } last_publishable_trajectory_.reset(new PublishableTrajectory( current_time_stamp, best_reference_line->trajectory())); last_publishable_trajectory_->PrependTrajectoryPoints( stitching_trajectory.begin(), stitching_trajectory.end() - 1); last_publishable_trajectory_->PopulateTrajectoryProtobuf(trajectory_pb); return status; } } // namespace planning } // namespace apollo <commit_msg>planning: make RunOnce as planning external api entry point.<commit_after>/****************************************************************************** * Copyright 2017 The Apollo 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. *****************************************************************************/ #include "modules/planning/planning.h" #include <algorithm> #include <vector> #include "google/protobuf/repeated_field.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/time/time.h" #include "modules/common/vehicle_state/vehicle_state.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/planner/em/em_planner.h" #include "modules/planning/planner/rtk/rtk_replay_planner.h" #include "modules/planning/reference_line/reference_line_provider.h" #include "modules/planning/trajectory_stitcher/trajectory_stitcher.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::VehicleState; using apollo::common::adapter::AdapterManager; using apollo::common::time::Clock; std::string Planning::Name() const { return "planning"; } void Planning::RegisterPlanners() { planner_factory_.Register( PlanningConfig::RTK, []() -> Planner* { return new RTKReplayPlanner(); }); planner_factory_.Register(PlanningConfig::EM, []() -> Planner* { return new EMPlanner(); }); } Status Planning::InitFrame(const uint32_t sequence_num, const double timestamp, const TrajectoryPoint& init_adc_point) { frame_.reset(new Frame(sequence_num)); frame_->SetPlanningStartPoint(init_adc_point); if (AdapterManager::GetRoutingResponse()->Empty()) { AERROR << "Routing is empty"; return Status(ErrorCode::PLANNING_ERROR, "routing is empty"); } frame_->UpdateRoutingResponse( AdapterManager::GetRoutingResponse()->GetLatestObserved()); frame_->SetVehicleInitPose(VehicleState::instance()->pose()); if (FLAGS_enable_prediction && !AdapterManager::GetPrediction()->Empty()) { const auto& prediction = AdapterManager::GetPrediction()->GetLatestObserved(); frame_->SetPrediction(prediction); ADEBUG << "Get prediction: " << prediction.DebugString(); } auto status = frame_->Init(config_, timestamp); if (!status.ok()) { AERROR << "failed to init frame"; return Status(ErrorCode::PLANNING_ERROR, "init frame failed"); } return Status::OK(); } bool Planning::HasSignalLight(const PlanningConfig& config) { for (const auto& rule_config : config.rule_config()) { if (rule_config.rule_id() == RuleConfig::SIGNAL_LIGHT) { return true; } } return false; } Status Planning::Init() { hdmap_ = apollo::hdmap::HDMapUtil::BaseMapPtr(); CHECK(hdmap_) << "Failed to load map file:" << apollo::hdmap::BaseMapFile(); Frame::SetMap(hdmap_); CHECK(apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file, &config_)) << "failed to load planning config file " << FLAGS_planning_config_file; if (!AdapterManager::Initialized()) { AdapterManager::Init(FLAGS_adapter_config_filename); } if (AdapterManager::GetLocalization() == nullptr) { std::string error_msg("Localization is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetChassis() == nullptr) { std::string error_msg("Chassis is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetRoutingResponse() == nullptr) { std::string error_msg("RoutingResponse is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (FLAGS_enable_prediction && AdapterManager::GetPrediction() == nullptr) { std::string error_msg("Prediction is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (HasSignalLight(config_) && AdapterManager::GetTrafficLightDetection() == nullptr) { std::string error_msg("Traffic Light Detection is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (FLAGS_enable_reference_line_provider_thread) { ReferenceLineProvider::instance()->Init( hdmap_, config_.reference_line_smoother_config()); } RegisterPlanners(); planner_ = planner_factory_.CreateObject(config_.planner_type()); if (!planner_) { return Status( ErrorCode::PLANNING_ERROR, "planning is not initialized with config : " + config_.DebugString()); } return planner_->Init(config_); } bool Planning::IsVehicleStateValid(const common::VehicleState& vehicle_state) { if (std::isnan(vehicle_state.x()) || std::isnan(vehicle_state.y()) || std::isnan(vehicle_state.z()) || std::isnan(vehicle_state.heading()) || std::isnan(vehicle_state.kappa()) || std::isnan(vehicle_state.linear_velocity()) || std::isnan(vehicle_state.linear_acceleration())) { return false; } return true; } Status Planning::Start() { if (FLAGS_enable_reference_line_provider_thread) { ReferenceLineProvider::instance()->Start(); } timer_ = AdapterManager::CreateTimer( ros::Duration(1.0 / FLAGS_planning_loop_rate), &Planning::OnTimer, this); return Status::OK(); } void Planning::OnTimer(const ros::TimerEvent&) { RunOnce(); } void Planning::PublishPlanningPb(ADCTrajectory* trajectory_pb, double timestamp) { AdapterManager::FillPlanningHeader(Name(), trajectory_pb); trajectory_pb->mutable_header()->set_timestamp_sec(timestamp); // TODO(all): integrate reverse gear trajectory_pb->set_gear(canbus::Chassis::GEAR_DRIVE); AdapterManager::PublishPlanning(*trajectory_pb); } void Planning::RunOnce() { const double start_timestamp = Clock::NowInSecond(); AdapterManager::Observe(); ADCTrajectory not_ready_pb; auto* not_ready = not_ready_pb.mutable_decision() ->mutable_main_decision() ->mutable_not_ready(); if (AdapterManager::GetLocalization()->Empty()) { not_ready->set_reason("localization not ready"); } else if (AdapterManager::GetChassis()->Empty()) { not_ready->set_reason("chassis not ready"); } else if (AdapterManager::GetRoutingResponse()->Empty()) { not_ready->set_reason("routing not ready"); } else if (FLAGS_enable_prediction && AdapterManager::GetPrediction()->Empty()) { not_ready->set_reason("prediction not ready"); } if (not_ready->has_reason()) { AERROR << not_ready->reason() << "; skip the planning cycle."; PublishPlanningPb(&not_ready_pb, start_timestamp); return; } // localization const auto& localization = AdapterManager::GetLocalization()->GetLatestObserved(); ADEBUG << "Get localization:" << localization.DebugString(); // chassis const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved(); ADEBUG << "Get chassis:" << chassis.DebugString(); common::Status status = common::VehicleState::instance()->Update(localization, chassis); DCHECK(IsVehicleStateValid(*common::VehicleState::instance())); if (!status.ok()) { AERROR << "Update VehicleState failed."; not_ready->set_reason("Update VehicleState failed."); status.Save(not_ready_pb.mutable_header()->mutable_status()); PublishPlanningPb(&not_ready_pb, start_timestamp); return; } const double planning_cycle_time = 1.0 / FLAGS_planning_loop_rate; bool is_auto_mode = chassis.driving_mode() == chassis.COMPLETE_AUTO_DRIVE; bool is_replan = false; const auto& stitching_trajectory = TrajectoryStitcher::ComputeStitchingTrajectory( is_auto_mode, start_timestamp, planning_cycle_time, last_publishable_trajectory_.get(), &is_replan); const uint32_t frame_num = AdapterManager::GetPlanning()->GetSeqNum() + 1; status = InitFrame(frame_num, start_timestamp, stitching_trajectory.back()); ADCTrajectory trajectory_pb; if (FLAGS_enable_record_debug) { frame_->RecordInputDebug(trajectory_pb.mutable_debug()); } trajectory_pb.mutable_latency_stats()->set_init_frame_time_ms( Clock::NowInSecond() - start_timestamp); if (!status.ok()) { AERROR << "Init frame failed"; if (FLAGS_publish_estop) { ADCTrajectory estop; estop.mutable_estop(); status.Save(estop.mutable_header()->mutable_status()); PublishPlanningPb(&estop, start_timestamp); } if (frame_) { auto seq_num = frame_->SequenceNum(); FrameHistory::instance()->Add(seq_num, std::move(frame_)); } return; } status = Plan(start_timestamp, stitching_trajectory, &trajectory_pb); const auto time_diff_ms = (Clock::NowInSecond() - start_timestamp) * 1000; ADEBUG << "total planning time spend: " << time_diff_ms << " ms."; trajectory_pb.mutable_latency_stats()->set_total_time_ms(time_diff_ms); ADEBUG << "Planning latency: " << trajectory_pb.latency_stats().DebugString(); if (status.ok()) { trajectory_pb.set_is_replan(is_replan); PublishPlanningPb(&trajectory_pb, start_timestamp); ADEBUG << "Planning succeeded:" << trajectory_pb.header().DebugString(); } else if (FLAGS_publish_estop) { trajectory_pb.mutable_estop(); status.Save(trajectory_pb.mutable_header()->mutable_status()); PublishPlanningPb(&trajectory_pb, start_timestamp); AERROR << "Planning failed"; } if (frame_) { auto seq_num = frame_->SequenceNum(); FrameHistory::instance()->Add(seq_num, std::move(frame_)); } } void Planning::Stop() { AERROR << "Planning Stop is called"; if (FLAGS_enable_reference_line_provider_thread) { ReferenceLineProvider::instance()->Stop(); } last_publishable_trajectory_.reset(nullptr); frame_.reset(nullptr); planner_.reset(nullptr); } void Planning::SetLastPublishableTrajectory( const ADCTrajectory& adc_trajectory) { last_publishable_trajectory_.reset(new PublishableTrajectory(adc_trajectory)); } common::Status Planning::Plan( const double current_time_stamp, const std::vector<common::TrajectoryPoint>& stitching_trajectory, ADCTrajectory* trajectory_pb) { auto* ptr_debug = trajectory_pb->mutable_debug(); if (FLAGS_enable_record_debug) { ptr_debug->mutable_planning_data()->mutable_init_point()->CopyFrom( stitching_trajectory.back()); } auto status = Status::OK(); for (auto& reference_line_info : frame_->reference_line_info()) { status = planner_->Plan(stitching_trajectory.back(), frame_.get(), &reference_line_info); AERROR_IF(!status.ok()) << "planner failed to make a driving plan."; } const auto* best_reference_line = frame_->FindDriveReferenceLineInfo(); if (!best_reference_line) { std::string msg( "planner failed to make a driving plan because NO best_reference_line " "can be provided."); AERROR << msg; last_publishable_trajectory_->Clear(); return Status(ErrorCode::PLANNING_ERROR, msg); } ptr_debug->MergeFrom(best_reference_line->debug()); trajectory_pb->mutable_latency_stats()->MergeFrom( best_reference_line->latency_stats()); best_reference_line->ExportDecision(trajectory_pb->mutable_decision()); // Add debug information. if (FLAGS_enable_record_debug) { auto* reference_line = ptr_debug->mutable_planning_data()->add_path(); reference_line->set_name("planning_reference_line"); const auto& reference_points = best_reference_line->reference_line().reference_points(); for (const auto& reference_point : reference_points) { auto* path_point = reference_line->add_path_point(); path_point->set_x(reference_point.x()); path_point->set_y(reference_point.y()); path_point->set_theta(reference_point.heading()); path_point->set_kappa(reference_point.kappa()); path_point->set_dkappa(reference_point.dkappa()); } } last_publishable_trajectory_.reset(new PublishableTrajectory( current_time_stamp, best_reference_line->trajectory())); last_publishable_trajectory_->PrependTrajectoryPoints( stitching_trajectory.begin(), stitching_trajectory.end() - 1); last_publishable_trajectory_->PopulateTrajectoryProtobuf(trajectory_pb); return status; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>// // Exponent.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "Exponential.h" Exponential::Exponential(Expression* base, Rational* exponent){ this->type = "exponential"; this->base = base; this->exponent = exponent; this->exde = new Integer(exponent->getDenominator()); if (exde->getValue() != 1) { //if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1 Integer* baseAsInteger = (Integer *) base; base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1); Integer* one = new Integer(1); exponent->setDenominator(one); } this->exnu = new Integer(exponent->getNumerator()); if (canExponentiate()) { exponentiate(); } } Exponential::~Exponential(){ } bool Exponential::canExponentiate() { if(base->type == "euler"){ return false; }else if(base->type == "exponential"){ Exponential* ex = (Exponential *) base; this->exponent->multiply(ex->getExponent()); Integer* numSum = new Integer (1); ex->getExponent()->setNumerator(numSum); return false; // false is returned because the base itself would have already been exponentiated if it were possible }else if(base->type == "integer"){ return true; }else if(base->type == "logarithm"){ return false; }else if(base->type == "nthRoot"){ nthRoot* nr = (nthRoot *) base; Rational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator()); //makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one this->exponent = r; nr->setRoot(1); return false; }else if(base->type == "pi"){ return false; }else if(base->type == "rational"){ Rational* r = (Rational *) base; if (r->geteNumerator()->type == "integer" && r->geteDenominator()->type == "integer") { Exponential* nu = new Exponential(r->geteNumerator(), this->exponent); r->setNumerator(nu); Exponential* de = new Exponential(r->geteDenominator(), this->exponent); r->setDenominator(de); } }else{ cout << "type not recognized" << endl; } return false; } void Exponential::exponentiate(){ Integer* one = new Integer(1); Rational* oneRat = new Rational(1, 1); if (this->base->type == "rational") { Rational* ratBase = (Rational *) this->base; Exponential* numAsExponential = new Exponential ((ratBase->geteNumerator()), (this->exponent)); //no matching constructor for exponential Exponential* denAsExponential = new Exponential ((ratBase->geteDenominator()), (this->exponent)); //same error Rational* newRatBase = new Rational(numAsExponential, denAsExponential); this->base = newRatBase; this->exponent = oneRat; } else { if (this->exponent->getNumerator()==0) { this->exponent=oneRat; this->base=one; } bool toFlip = false; if (exnu->getValue()<0) { exnu->setValue(exnu->getValue()*-1); toFlip = true; //handles negative exponents } Expression* constantBase = 0; if (base->type == "integer") { //fixed the problem for integers but nothing else Integer *a = (Integer *)base; constantBase = new Integer(a->getValue()); } while (exponent->getNumerator()>1) { base->multiply(constantBase); exponent->setNumerator(exponent->geteNumerator()->subtract(one)); } if (toFlip) { Integer* one = new Integer(1); Rational* mouse = new Rational(one, base); base = mouse; } } } Expression* Exponential::add(Expression* a){ if(a->type == "euler"){ }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (ex->getBase()==this->base) { if (ex->getExponent()==this->exponent) { Integer* two = new Integer(2); this->multiply(two); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ }else if(a->type == "rational"){ }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::subtract(Expression* a){ if(a->type == "euler"){ }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (ex->getBase()==this->base) { if (ex->getExponent()==this->exponent) { Integer* zero = new Integer(0); this->multiply(zero); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ }else if(a->type == "rational"){ }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::multiply(Expression* a){ if(a->type == "euler"){ if (this->base->type == "euler") { Rational* oneRat = new Rational(1, 1); this->exponent->add(oneRat); } }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; //if (this->base == ex->getBase()) { // this->exponent->add(ex->getExponent()); //} if (ex->base->type == this->base->type) { if ((ex->base->type == "euler") || (ex->base->type == "pi")) { this->exponent->add(ex->exponent); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ if (this->base->type == "pi") { Rational* oneRat = new Rational(1, 1); this->exponent->add(oneRat); } }else if(a->type == "rational"){ Rational* r = (Rational *) a; Expression* numToSet = r->geteNumerator(); numToSet->multiply(this); r->setNumerator(numToSet); return r; }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::divide(Expression* a){ if(a->type == "euler"){ if (this->base->type == "euler") { Rational* oneRat = new Rational(1, 1); this->exponent->subtract(oneRat); } }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; //if (this->base == ex->getBase()) { // this->exponent->subtract(ex->getExponent()); //} if (ex->base->type == this->base->type) { if ((ex->base->type == "euler") || (ex->base->type == "pi")) { this->exponent->subtract(ex->exponent); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ if (this->base->type == "pi") { Rational* oneRat = new Rational(1, 1); this->exponent->subtract(oneRat); } }else if(a->type == "rational"){ Rational* r = (Rational *) a; Expression* denToSet = r->geteDenominator(); denToSet->multiply(this); r->setDenominator(denToSet); return r; }else{ cout << "type not recognized" << endl; } return this; } Rational* Exponential::getExponent() { return exponent; } Expression* Exponential::getBase() { return base; } Integer* Exponential::getExnu() { return exnu; } Integer* Exponential::getExde() { return exde; } void Exponential::setExnu(Integer* n) { exnu = n; } void Exponential::setExde(Integer* n) { exde = n; } void Exponential::setExponent(Rational* e) { exponent = e; } void Exponential::setBase(Expression* e) { base = e; } string Exponential::toString() { stringstream str; if(exponent->getNumerator() == 1 && exponent->getDenominator() == 1){ str << *base; } else if(exponent->getDenominator() == 1){ str << *base << "^" << *exponent->geteNumerator(); }else{ str << *base << "^" << *exponent; } return str.str(); } ostream& Exponential::print(std::ostream& output) const{ Exponential *a = (Exponential *)this; output << a->toString(); return output; } bool Exponential::canAdd(Expression* b){ //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression) if (this->type == b->type && this->type != "logarithm") { if (this->type == "nthRoot") { } return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canSubtract(Expression* b){ if (this->type == b->type) { return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canMultiply(Expression* b){ if (this->type == b->type) { return true; } else if (this->base->type == b->type) { return true; } else if(this->type == "integer" && b->type == "rational") return true; else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canDivide(Expression* b){ if (this->type == b->type) { return true; } else if (this->base->type == b->type) { return true; } else if(this->type == "integer"){ if( b->type == "rational") return true; } else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } <commit_msg>Fixed add and subtract<commit_after>// // Exponent.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "Exponential.h" Exponential::Exponential(Expression* base, Rational* exponent){ this->type = "exponential"; this->base = base; this->exponent = exponent; this->exde = new Integer(exponent->getDenominator()); if (exde->getValue() != 1) { //if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1 Integer* baseAsInteger = (Integer *) base; base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1); Integer* one = new Integer(1); exponent->setDenominator(one); } this->exnu = new Integer(exponent->getNumerator()); if (canExponentiate()) { exponentiate(); } } Exponential::~Exponential(){ } bool Exponential::canExponentiate() { if(base->type == "euler"){ return false; }else if(base->type == "exponential"){ Exponential* ex = (Exponential *) base; this->exponent->multiply(ex->getExponent()); Integer* numSum = new Integer (1); ex->getExponent()->setNumerator(numSum); return false; // false is returned because the base itself would have already been exponentiated if it were possible }else if(base->type == "integer"){ return true; }else if(base->type == "logarithm"){ return false; }else if(base->type == "nthRoot"){ nthRoot* nr = (nthRoot *) base; Rational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator()); //makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one this->exponent = r; nr->setRoot(1); return false; }else if(base->type == "pi"){ return false; }else if(base->type == "rational"){ Rational* r = (Rational *) base; if (r->geteNumerator()->type == "integer" && r->geteDenominator()->type == "integer") { Exponential* nu = new Exponential(r->geteNumerator(), this->exponent); r->setNumerator(nu); Exponential* de = new Exponential(r->geteDenominator(), this->exponent); r->setDenominator(de); } }else{ cout << "type not recognized" << endl; } return false; } void Exponential::exponentiate(){ Integer* one = new Integer(1); Rational* oneRat = new Rational(1, 1); if (this->base->type == "rational") { Rational* ratBase = (Rational *) this->base; Exponential* numAsExponential = new Exponential ((ratBase->geteNumerator()), (this->exponent)); //no matching constructor for exponential Exponential* denAsExponential = new Exponential ((ratBase->geteDenominator()), (this->exponent)); //same error Rational* newRatBase = new Rational(numAsExponential, denAsExponential); this->base = newRatBase; this->exponent = oneRat; } else { if (this->exponent->getNumerator()==0) { this->exponent=oneRat; this->base=one; } bool toFlip = false; if (exnu->getValue()<0) { exnu->setValue(exnu->getValue()*-1); toFlip = true; //handles negative exponents } Expression* constantBase = 0; if (base->type == "integer") { //fixed the problem for integers but nothing else Integer *a = (Integer *)base; constantBase = new Integer(a->getValue()); } while (exponent->getNumerator()>1) { base->multiply(constantBase); exponent->setNumerator(exponent->geteNumerator()->subtract(one)); } if (toFlip) { Integer* one = new Integer(1); Rational* mouse = new Rational(one, base); base = mouse; } } } Expression* Exponential::add(Expression* a){ if(a->type == "euler"){ }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if ((ex->getBase()->type == this->base->type) && ((this->base->type == "euler") || (this->base->type == "pi"))) { if (ex->getExponent()==this->exponent) { Integer* two = new Integer(2); this->multiply(two); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ }else if(a->type == "rational"){ }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::subtract(Expression* a){ if(a->type == "euler"){ }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if ((ex->getBase()->type == this->base->type) && ((this->base->type == "euler") || (this->base->type == "pi"))) { if (ex->getExponent()==this->exponent) { Integer* zero = new Integer(0); this->multiply(zero); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ }else if(a->type == "rational"){ }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::multiply(Expression* a){ if(a->type == "euler"){ if (this->base->type == "euler") { Rational* oneRat = new Rational(1, 1); this->exponent->add(oneRat); } }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; //if (this->base == ex->getBase()) { // this->exponent->add(ex->getExponent()); //} if (ex->base->type == this->base->type) { if ((ex->base->type == "euler") || (ex->base->type == "pi")) { this->exponent->add(ex->exponent); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ if (this->base->type == "pi") { Rational* oneRat = new Rational(1, 1); this->exponent->add(oneRat); } }else if(a->type == "rational"){ Rational* r = (Rational *) a; Expression* numToSet = r->geteNumerator(); numToSet->multiply(this); r->setNumerator(numToSet); return r; }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::divide(Expression* a){ if(a->type == "euler"){ if (this->base->type == "euler") { Rational* oneRat = new Rational(1, 1); this->exponent->subtract(oneRat); } }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; //if (this->base == ex->getBase()) { // this->exponent->subtract(ex->getExponent()); //} if (ex->base->type == this->base->type) { if ((ex->base->type == "euler") || (ex->base->type == "pi")) { this->exponent->subtract(ex->exponent); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ if (this->base->type == "pi") { Rational* oneRat = new Rational(1, 1); this->exponent->subtract(oneRat); } }else if(a->type == "rational"){ Rational* r = (Rational *) a; Expression* denToSet = r->geteDenominator(); denToSet->multiply(this); r->setDenominator(denToSet); return r; }else{ cout << "type not recognized" << endl; } return this; } Rational* Exponential::getExponent() { return exponent; } Expression* Exponential::getBase() { return base; } Integer* Exponential::getExnu() { return exnu; } Integer* Exponential::getExde() { return exde; } void Exponential::setExnu(Integer* n) { exnu = n; } void Exponential::setExde(Integer* n) { exde = n; } void Exponential::setExponent(Rational* e) { exponent = e; } void Exponential::setBase(Expression* e) { base = e; } string Exponential::toString() { stringstream str; if(exponent->getNumerator() == 1 && exponent->getDenominator() == 1){ str << *base; } else if(exponent->getDenominator() == 1){ str << *base << "^" << *exponent->geteNumerator(); }else{ str << *base << "^" << *exponent; } return str.str(); } ostream& Exponential::print(std::ostream& output) const{ Exponential *a = (Exponential *)this; output << a->toString(); return output; } bool Exponential::canAdd(Expression* b){ //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression) if (this->type == b->type && this->type != "logarithm") { if (this->type == "nthRoot") { } return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canSubtract(Expression* b){ if (this->type == b->type) { return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canMultiply(Expression* b){ if (this->type == b->type) { return true; } else if (this->base->type == b->type) { return true; } else if(this->type == "integer" && b->type == "rational") return true; else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canDivide(Expression* b){ if (this->type == b->type) { return true; } else if (this->base->type == b->type) { return true; } else if(this->type == "integer"){ if( b->type == "rational") return true; } else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } <|endoftext|>
<commit_before>/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this 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. */ #include "scenemodel.h" #include <gluon/gameobject.h> #include <gluon/component.h> #include <typeinfo> #include <objectmanager.h> #include <debughelper.h> #include <qmimedata.h> #include <KLocalizedString> using namespace Gluon; using namespace Gluon::Creator; SceneModel::SceneModel(QObject* parent): QAbstractItemModel(parent) { m_root = 0; connect(ObjectManager::instance(), SIGNAL(newObject(Gluon::GameObject*)), SIGNAL(layoutChanged())); } GameObject* SceneModel::rootGameObject() { if(m_root) return m_root->childGameObject(0); return 0; } void SceneModel::setRootGameObject(GameObject* obj) { if(obj) { /*if(!m_root) m_root = new GameObject(this); if(m_root->childCount() > 0) m_root->removeChild(m_root->childGameObject(0)); m_root->addChild(obj);*/ m_root = obj; reset(); } } QVariant SceneModel::data(const QModelIndex& index, int role) const { if (index.isValid() && role == Qt::DisplayRole) { GameObject *item = static_cast<GameObject*>(index.internalPointer()); if(item) return item->name(); } return QVariant(); } int SceneModel::columnCount(const QModelIndex&) const { return 1; } int SceneModel::rowCount(const QModelIndex& parent) const { GameObject *parentItem; if (parent.column() > 0) return 0; if (!parent.isValid()) parentItem = m_root; else parentItem = static_cast<GameObject*>(parent.internalPointer()); if(parentItem) return parentItem->childCount(); return 0; } QModelIndex SceneModel::parent(const QModelIndex& child) const { if (!child.isValid()) return QModelIndex(); GameObject *childItem = static_cast<GameObject*>(child.internalPointer()); if(!childItem) return QModelIndex(); GameObject *parentItem = childItem->parentGameObject(); if (parentItem == m_root) return QModelIndex(); return createIndex(rowIndex(parentItem), 0, parentItem); } QModelIndex SceneModel::index(int row, int column, const QModelIndex& parent) const { if (!hasIndex(row, column, parent)) return QModelIndex(); GameObject *parentItem; if (!parent.isValid()) parentItem = m_root; else parentItem = static_cast<GameObject*>(parent.internalPointer()); GameObject *childItem = parentItem->childGameObject(row); if (childItem) return createIndex(row, column, childItem); else return QModelIndex(); } QVariant SceneModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(section) Q_UNUSED(orientation) Q_UNUSED(role) return QVariant(); } int SceneModel::rowIndex(GameObject* object) const { if(object) { if(object->parentGameObject()) { return object->parentGameObject()->childIndex(object); } } return 0; } Qt::DropActions SceneModel::supportedDropActions() const { return Qt::CopyAction | Qt::MoveAction; } Qt::ItemFlags SceneModel::flags(const QModelIndex& index) const { if (index.isValid()) return QAbstractItemModel::flags(index) | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; else return QAbstractItemModel::flags(index) | Qt::ItemIsDropEnabled | Qt::ItemIsEnabled; } QStringList SceneModel::mimeTypes() const { QStringList types; types << "application/gluon.text.componentclass"; return types; } bool SceneModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) { DEBUG_FUNC_NAME if(action == Qt::IgnoreAction) return false; if(!parent.isValid()) return false; GameObject *gobj = qobject_cast<GameObject*>((QObject*)parent.internalPointer()); if(!gobj) return false; foreach(QString something, data->formats()) { DEBUG_TEXT(QString("Dropped mimetype %1 on object %2").arg(something).arg(gobj->fullyQualifiedName())); } QByteArray encodedData = data->data("application/gluon.text.componentclass"); QDataStream stream(&encodedData, QIODevice::ReadOnly); QStringList newItems; int rows = 0; while (!stream.atEnd()) { QString text; stream >> text; newItems << text; ++rows; } foreach(QString text, newItems) { DEBUG_TEXT(QString("Adding component of class %1").arg(text)); GluonObject *component = Gluon::GluonObjectFactory::instance()->instantiateObjectByName(text); if(!component) { DEBUG_TEXT("Returned component instance was null, something's fishy"); } else { DEBUG_TEXT(QString("Adding component of class name %1").arg(component->metaObject()->className())); gobj->addComponent(qobject_cast<Gluon::Component*>(component)); } } return true; } bool SceneModel::setData(const QModelIndex& index, const QVariant& value, int role) { if (index.isValid() && role == Qt::EditRole) { static_cast<GluonObject*>(index.internalPointer())->setName(value.toString()); emit dataChanged(index, index); return true; } return false; } bool SceneModel::insertRows(int row, int count, const QModelIndex& parent) { beginInsertRows(parent, row, row + count - 1); GameObject* obj = static_cast<GameObject*>(parent.internalPointer()); for (int i = 0; i < count; ++i) { obj->addChild(new GameObject()); } endInsertRows(); return true; } bool SceneModel::removeRows(int row, int count, const QModelIndex& parent) { } #include "scenemodel.moc" <commit_msg>Ewewewew! God-mode casting is so ugly... But qobject_cast fails me. Anybody who want to explain to me why that is the case?<commit_after>/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this 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. */ #include "scenemodel.h" #include <gluon/gameobject.h> #include <gluon/component.h> #include <typeinfo> #include <objectmanager.h> #include <debughelper.h> #include <qmimedata.h> #include <KLocalizedString> using namespace Gluon; using namespace Gluon::Creator; SceneModel::SceneModel(QObject* parent): QAbstractItemModel(parent) { m_root = 0; connect(ObjectManager::instance(), SIGNAL(newObject(Gluon::GameObject*)), SIGNAL(layoutChanged())); } GameObject* SceneModel::rootGameObject() { if(m_root) return m_root->childGameObject(0); return 0; } void SceneModel::setRootGameObject(GameObject* obj) { if(obj) { /*if(!m_root) m_root = new GameObject(this); if(m_root->childCount() > 0) m_root->removeChild(m_root->childGameObject(0)); m_root->addChild(obj);*/ m_root = obj; reset(); } } QVariant SceneModel::data(const QModelIndex& index, int role) const { if (index.isValid() && role == Qt::DisplayRole) { GameObject *item = static_cast<GameObject*>(index.internalPointer()); if(item) return item->name(); } return QVariant(); } int SceneModel::columnCount(const QModelIndex&) const { return 1; } int SceneModel::rowCount(const QModelIndex& parent) const { GameObject *parentItem; if (parent.column() > 0) return 0; if (!parent.isValid()) parentItem = m_root; else parentItem = static_cast<GameObject*>(parent.internalPointer()); if(parentItem) return parentItem->childCount(); return 0; } QModelIndex SceneModel::parent(const QModelIndex& child) const { if (!child.isValid()) return QModelIndex(); GameObject *childItem = static_cast<GameObject*>(child.internalPointer()); if(!childItem) return QModelIndex(); GameObject *parentItem = childItem->parentGameObject(); if (parentItem == m_root) return QModelIndex(); return createIndex(rowIndex(parentItem), 0, parentItem); } QModelIndex SceneModel::index(int row, int column, const QModelIndex& parent) const { if (!hasIndex(row, column, parent)) return QModelIndex(); GameObject *parentItem; if (!parent.isValid()) parentItem = m_root; else parentItem = static_cast<GameObject*>(parent.internalPointer()); GameObject *childItem = parentItem->childGameObject(row); if (childItem) return createIndex(row, column, childItem); else return QModelIndex(); } QVariant SceneModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(section) Q_UNUSED(orientation) Q_UNUSED(role) return QVariant(); } int SceneModel::rowIndex(GameObject* object) const { if(object) { if(object->parentGameObject()) { return object->parentGameObject()->childIndex(object); } } return 0; } Qt::DropActions SceneModel::supportedDropActions() const { return Qt::CopyAction | Qt::MoveAction; } Qt::ItemFlags SceneModel::flags(const QModelIndex& index) const { if (index.isValid()) return QAbstractItemModel::flags(index) | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; else return QAbstractItemModel::flags(index) | Qt::ItemIsDropEnabled | Qt::ItemIsEnabled; } QStringList SceneModel::mimeTypes() const { QStringList types; types << "application/gluon.text.componentclass"; return types; } bool SceneModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) { DEBUG_FUNC_NAME if(action == Qt::IgnoreAction) return false; if(!parent.isValid()) return false; GameObject *gobj = qobject_cast<GameObject*>((QObject*)parent.internalPointer()); if(!gobj) return false; foreach(QString something, data->formats()) { DEBUG_TEXT(QString("Dropped mimetype %1 on object %2").arg(something).arg(gobj->fullyQualifiedName())); } QByteArray encodedData = data->data("application/gluon.text.componentclass"); QDataStream stream(&encodedData, QIODevice::ReadOnly); QStringList newItems; int rows = 0; while (!stream.atEnd()) { QString text; stream >> text; newItems << text; ++rows; } foreach(QString text, newItems) { DEBUG_TEXT(QString("Adding component of class %1").arg(text)); GluonObject *component = Gluon::GluonObjectFactory::instance()->instantiateObjectByName(text); if(!component) { DEBUG_TEXT("Returned component instance was null, something's fishy"); } else { DEBUG_TEXT(QString("Adding component of class name %1").arg(component->metaObject()->className())); gobj->addComponent((Gluon::Component*)component); } } return true; } bool SceneModel::setData(const QModelIndex& index, const QVariant& value, int role) { if (index.isValid() && role == Qt::EditRole) { static_cast<GluonObject*>(index.internalPointer())->setName(value.toString()); emit dataChanged(index, index); return true; } return false; } bool SceneModel::insertRows(int row, int count, const QModelIndex& parent) { beginInsertRows(parent, row, row + count - 1); GameObject* obj = static_cast<GameObject*>(parent.internalPointer()); for (int i = 0; i < count; ++i) { obj->addChild(new GameObject()); } endInsertRows(); return true; } bool SceneModel::removeRows(int row, int count, const QModelIndex& parent) { } #include "scenemodel.moc" <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // This 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 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "TextEngine.h" #include "../base/Logger.h" #include "../base/OSHelper.h" #include "../base/Exception.h" #include "../base/FileHelper.h" #include "../base/StringHelper.h" #include <fontconfig/fontconfig.h> #include <algorithm> namespace avg { using namespace std; TextEngine& TextEngine::get(bool bHint) { if (bHint) { static TextEngine s_Instance(true); return s_Instance; } else { static TextEngine s_Instance(false); return s_Instance; } } TextEngine::TextEngine(bool bHint) : m_bHint(bHint) { m_sFontDirs.push_back("fonts/"); init(); } TextEngine::~TextEngine() { deinit(); } void TextEngine::init() { g_type_init(); m_pFontMap = PANGO_CAIRO_FONT_MAP(pango_cairo_font_map_new_for_font_type( CAIRO_FONT_TYPE_FT)); pango_cairo_font_map_set_resolution(m_pFontMap, 72); m_pCairoSurface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 1, 1); m_pCairo = cairo_create(m_pCairoSurface); m_pPangoContext = pango_cairo_create_context(m_pCairo); pango_context_set_language(m_pPangoContext, pango_language_from_string ("en_US")); pango_context_set_base_dir(m_pPangoContext, PANGO_DIRECTION_LTR); initFonts(); string sOldLang = ""; getEnv("LC_CTYPE", sOldLang); setEnv("LC_CTYPE", "en-us"); pango_font_map_list_families(PANGO_FONT_MAP(m_pFontMap), &m_ppFontFamilies, &m_NumFontFamilies); setEnv("LC_CTYPE", sOldLang); for (int i = 0; i < m_NumFontFamilies; ++i) { m_sFonts.push_back(pango_font_family_get_name(m_ppFontFamilies[i])); } sort(m_sFonts.begin(), m_sFonts.end()); } void TextEngine::deinit() { g_object_unref(m_pPangoContext); m_sFonts.clear(); g_free(m_ppFontFamilies); cairo_surface_destroy(m_pCairoSurface); cairo_destroy(m_pCairo); g_object_unref(m_pFontMap); } void TextEngine::addFontDir(const std::string& sDir) { deinit(); m_sFontDirs.push_back(sDir); init(); } PangoContext * TextEngine::getPangoContext() { return m_pPangoContext; } const vector<string>& TextEngine::getFontFamilies() { return m_sFonts; } const vector<string>& TextEngine::getFontVariants(const string& sFontName) { PangoFontFamily * pCurFamily = getFontFamily(sFontName); PangoFontFace ** ppFaces; int numFaces; pango_font_family_list_faces (pCurFamily, &ppFaces, &numFaces); static vector<string> sVariants; for (int i = 0; i < numFaces; ++i) { sVariants.push_back(pango_font_face_get_face_name(ppFaces[i])); } g_free(ppFaces); return sVariants; } PangoFontDescription * TextEngine::getFontDescription(const string& sFamily, const string& sVariant) { PangoFontDescription* pDescription; FontDescriptionCache::iterator it; it = m_FontDescriptionCache.find(pair<string, string>(sFamily, sVariant)); if (it == m_FontDescriptionCache.end()) { PangoFontFamily * pFamily; bool bFamilyFound = true; try { pFamily = getFontFamily(sFamily); } catch (Exception&) { if (m_sFontsNotFound.find(sFamily) == m_sFontsNotFound.end()) { AVG_TRACE(Logger::WARNING, "Could not find font face " << sFamily << ". Using sans instead."); m_sFontsNotFound.insert(sFamily); } bFamilyFound = false; pFamily = getFontFamily("sans"); } PangoFontFace ** ppFaces; int numFaces; pango_font_family_list_faces(pFamily, &ppFaces, &numFaces); PangoFontFace * pFace = 0; if (sVariant == "") { pFace = ppFaces[0]; } else { for (int i = 0; i < numFaces; ++i) { if (equalIgnoreCase(pango_font_face_get_face_name(ppFaces[i]), sVariant)) { pFace = ppFaces[i]; } } } if (!pFace) { pFace = ppFaces[0]; if (bFamilyFound) { pair<string, string> variant(sFamily, sVariant); if (m_VariantsNotFound.find(variant) == m_VariantsNotFound.end()) { m_VariantsNotFound.insert(variant); AVG_TRACE(Logger::WARNING, "Could not find font variant " << sFamily << ":" << sVariant << ". Using " << pango_font_face_get_face_name(pFace) << " instead."); } } } g_free(ppFaces); pDescription = pango_font_face_describe(pFace); m_FontDescriptionCache[pair<string, string>(sFamily, sVariant)] = pDescription; } else { pDescription = it->second; } return pango_font_description_copy(pDescription); } void GLibLogFunc(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer unused_data) { #ifndef WIN32 string s = "Pango "; if (log_level & G_LOG_LEVEL_ERROR) { s += "error: "; } else if (log_level & G_LOG_LEVEL_CRITICAL) { s += string("critical: ")+message; AVG_TRACE(Logger::ERROR, s); return; } else if (log_level & G_LOG_LEVEL_WARNING) { s += "warning: "; } else if (log_level & G_LOG_LEVEL_MESSAGE) { s += "message: "; } else if (log_level & G_LOG_LEVEL_INFO) { s += "info: "; } else if (log_level & G_LOG_LEVEL_DEBUG) { s += "debug: "; } s += message; AVG_TRACE(Logger::WARNING, s); #endif } void TextEngine::initFonts() { g_type_init(); std::vector<std::string> fontConfPathPrefixList; #ifndef WIN32 fontConfPathPrefixList.push_back("/"); fontConfPathPrefixList.push_back("/usr/local/"); fontConfPathPrefixList.push_back("/opt/local/"); #endif fontConfPathPrefixList.push_back(getAvgLibPath()); std::string sFontConfPath; for (size_t i = 0; i < fontConfPathPrefixList.size(); ++i) { sFontConfPath = fontConfPathPrefixList[i] + "etc/fonts/fonts.conf"; if (fileExists(sFontConfPath)) { break; } } FcConfig * pConfig = FcConfigCreate(); int ok = (int)FcConfigParseAndLoad(pConfig, (const FcChar8 *)(sFontConfPath.c_str()), true); checkFontError(ok, string("Font error: could not load config file ")+sFontConfPath); ok = (int)FcConfigBuildFonts(pConfig); checkFontError(ok, string("Font error: FcConfigBuildFonts failed.")); ok = (int)FcConfigSetCurrent(pConfig); checkFontError(ok, string("Font error: FcConfigSetCurrent failed.")); for(std::vector<std::string>::const_iterator it = m_sFontDirs.begin(); it != m_sFontDirs.end(); ++it) { ok = (int)FcConfigAppFontAddDir(pConfig, (const FcChar8 *)it->c_str()); checkFontError(ok, string("Font error: FcConfigAppFontAddDir(" + *it + ") failed.")); } /* FcStrList * pCacheDirs = FcConfigGetCacheDirs(pConfig); FcChar8 * pDir; do { pDir = FcStrListNext(pCacheDirs); if (pDir) { cerr << pDir << endl; } } while (pDir); */ g_log_set_default_handler(GLibLogFunc, 0); } PangoFontFamily * TextEngine::getFontFamily(const string& sFamily) { PangoFontFamily * pFamily = 0; AVG_ASSERT(m_NumFontFamilies != 0); for (int i=0; i<m_NumFontFamilies; ++i) { if (equalIgnoreCase(pango_font_family_get_name(m_ppFontFamilies[i]), sFamily)) { pFamily = m_ppFontFamilies[i]; } } if (!pFamily) { throw(Exception(AVG_ERR_INVALID_ARGS, "getFontFamily: Font family "+sFamily+" not found.")); } return pFamily; } void TextEngine::checkFontError(int ok, const string& sMsg) { if (ok == 0) { throw Exception(AVG_ERR_FONT_INIT_FAILED, sMsg); } } } <commit_msg>Added default font options.<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // This 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 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "TextEngine.h" #include "../base/Logger.h" #include "../base/OSHelper.h" #include "../base/Exception.h" #include "../base/FileHelper.h" #include "../base/StringHelper.h" #include <fontconfig/fontconfig.h> #include <algorithm> namespace avg { using namespace std; TextEngine& TextEngine::get(bool bHint) { if (bHint) { static TextEngine s_Instance(true); return s_Instance; } else { static TextEngine s_Instance(false); return s_Instance; } } TextEngine::TextEngine(bool bHint) : m_bHint(bHint) { m_sFontDirs.push_back("fonts/"); init(); } TextEngine::~TextEngine() { deinit(); } void TextEngine::init() { g_type_init(); m_pFontMap = PANGO_CAIRO_FONT_MAP(pango_cairo_font_map_new_for_font_type( CAIRO_FONT_TYPE_FT)); pango_cairo_font_map_set_resolution(m_pFontMap, 72); m_pCairoSurface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 1, 1); m_pCairo = cairo_create(m_pCairoSurface); m_pPangoContext = pango_cairo_create_context(m_pCairo); pango_context_set_language(m_pPangoContext, pango_language_from_string ("en_US")); pango_context_set_base_dir(m_pPangoContext, PANGO_DIRECTION_LTR); cairo_font_options_t* pFontOptions = cairo_font_options_create(); // cairo_font_options_set_antialias(pFontOptions, CAIRO_ANTIALIAS_GRAY); cairo_font_options_set_hint_style(pFontOptions, CAIRO_HINT_STYLE_SLIGHT); cairo_font_options_set_hint_metrics(pFontOptions, CAIRO_HINT_METRICS_OFF); pango_cairo_context_set_font_options(m_pPangoContext, pFontOptions); cairo_font_options_destroy(pFontOptions); initFonts(); string sOldLang = ""; getEnv("LC_CTYPE", sOldLang); setEnv("LC_CTYPE", "en-us"); pango_font_map_list_families(PANGO_FONT_MAP(m_pFontMap), &m_ppFontFamilies, &m_NumFontFamilies); setEnv("LC_CTYPE", sOldLang); for (int i = 0; i < m_NumFontFamilies; ++i) { m_sFonts.push_back(pango_font_family_get_name(m_ppFontFamilies[i])); } sort(m_sFonts.begin(), m_sFonts.end()); } void TextEngine::deinit() { g_object_unref(m_pPangoContext); m_sFonts.clear(); g_free(m_ppFontFamilies); cairo_surface_destroy(m_pCairoSurface); cairo_destroy(m_pCairo); g_object_unref(m_pFontMap); } void TextEngine::addFontDir(const std::string& sDir) { deinit(); m_sFontDirs.push_back(sDir); init(); } PangoContext * TextEngine::getPangoContext() { return m_pPangoContext; } const vector<string>& TextEngine::getFontFamilies() { return m_sFonts; } const vector<string>& TextEngine::getFontVariants(const string& sFontName) { PangoFontFamily * pCurFamily = getFontFamily(sFontName); PangoFontFace ** ppFaces; int numFaces; pango_font_family_list_faces (pCurFamily, &ppFaces, &numFaces); static vector<string> sVariants; for (int i = 0; i < numFaces; ++i) { sVariants.push_back(pango_font_face_get_face_name(ppFaces[i])); } g_free(ppFaces); return sVariants; } PangoFontDescription * TextEngine::getFontDescription(const string& sFamily, const string& sVariant) { PangoFontDescription* pDescription; FontDescriptionCache::iterator it; it = m_FontDescriptionCache.find(pair<string, string>(sFamily, sVariant)); if (it == m_FontDescriptionCache.end()) { PangoFontFamily * pFamily; bool bFamilyFound = true; try { pFamily = getFontFamily(sFamily); } catch (Exception&) { if (m_sFontsNotFound.find(sFamily) == m_sFontsNotFound.end()) { AVG_TRACE(Logger::WARNING, "Could not find font face " << sFamily << ". Using sans instead."); m_sFontsNotFound.insert(sFamily); } bFamilyFound = false; pFamily = getFontFamily("sans"); } PangoFontFace ** ppFaces; int numFaces; pango_font_family_list_faces(pFamily, &ppFaces, &numFaces); PangoFontFace * pFace = 0; if (sVariant == "") { pFace = ppFaces[0]; } else { for (int i = 0; i < numFaces; ++i) { if (equalIgnoreCase(pango_font_face_get_face_name(ppFaces[i]), sVariant)) { pFace = ppFaces[i]; } } } if (!pFace) { pFace = ppFaces[0]; if (bFamilyFound) { pair<string, string> variant(sFamily, sVariant); if (m_VariantsNotFound.find(variant) == m_VariantsNotFound.end()) { m_VariantsNotFound.insert(variant); AVG_TRACE(Logger::WARNING, "Could not find font variant " << sFamily << ":" << sVariant << ". Using " << pango_font_face_get_face_name(pFace) << " instead."); } } } g_free(ppFaces); pDescription = pango_font_face_describe(pFace); m_FontDescriptionCache[pair<string, string>(sFamily, sVariant)] = pDescription; } else { pDescription = it->second; } return pango_font_description_copy(pDescription); } void GLibLogFunc(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer unused_data) { #ifndef WIN32 string s = "Pango "; if (log_level & G_LOG_LEVEL_ERROR) { s += "error: "; } else if (log_level & G_LOG_LEVEL_CRITICAL) { s += string("critical: ")+message; AVG_TRACE(Logger::ERROR, s); return; } else if (log_level & G_LOG_LEVEL_WARNING) { s += "warning: "; } else if (log_level & G_LOG_LEVEL_MESSAGE) { s += "message: "; } else if (log_level & G_LOG_LEVEL_INFO) { s += "info: "; } else if (log_level & G_LOG_LEVEL_DEBUG) { s += "debug: "; } s += message; AVG_TRACE(Logger::WARNING, s); #endif } void TextEngine::initFonts() { g_type_init(); std::vector<std::string> fontConfPathPrefixList; #ifndef WIN32 fontConfPathPrefixList.push_back("/"); fontConfPathPrefixList.push_back("/usr/local/"); fontConfPathPrefixList.push_back("/opt/local/"); #endif fontConfPathPrefixList.push_back(getAvgLibPath()); std::string sFontConfPath; for (size_t i = 0; i < fontConfPathPrefixList.size(); ++i) { sFontConfPath = fontConfPathPrefixList[i] + "etc/fonts/fonts.conf"; if (fileExists(sFontConfPath)) { break; } } FcConfig * pConfig = FcConfigCreate(); int ok = (int)FcConfigParseAndLoad(pConfig, (const FcChar8 *)(sFontConfPath.c_str()), true); checkFontError(ok, string("Font error: could not load config file ")+sFontConfPath); ok = (int)FcConfigBuildFonts(pConfig); checkFontError(ok, string("Font error: FcConfigBuildFonts failed.")); ok = (int)FcConfigSetCurrent(pConfig); checkFontError(ok, string("Font error: FcConfigSetCurrent failed.")); for(std::vector<std::string>::const_iterator it = m_sFontDirs.begin(); it != m_sFontDirs.end(); ++it) { ok = (int)FcConfigAppFontAddDir(pConfig, (const FcChar8 *)it->c_str()); checkFontError(ok, string("Font error: FcConfigAppFontAddDir(" + *it + ") failed.")); } /* FcStrList * pCacheDirs = FcConfigGetCacheDirs(pConfig); FcChar8 * pDir; do { pDir = FcStrListNext(pCacheDirs); if (pDir) { cerr << pDir << endl; } } while (pDir); */ g_log_set_default_handler(GLibLogFunc, 0); } PangoFontFamily * TextEngine::getFontFamily(const string& sFamily) { PangoFontFamily * pFamily = 0; AVG_ASSERT(m_NumFontFamilies != 0); for (int i=0; i<m_NumFontFamilies; ++i) { if (equalIgnoreCase(pango_font_family_get_name(m_ppFontFamilies[i]), sFamily)) { pFamily = m_ppFontFamilies[i]; } } if (!pFamily) { throw(Exception(AVG_ERR_INVALID_ARGS, "getFontFamily: Font family "+sFamily+" not found.")); } return pFamily; } void TextEngine::checkFontError(int ok, const string& sMsg) { if (ok == 0) { throw Exception(AVG_ERR_FONT_INIT_FAILED, sMsg); } } } <|endoftext|>
<commit_before>#include <vector> #include <string> #include <limits> #include <memory> #include <iostream> #include <arpa/inet.h> #include "caf/all.hpp" #include "caf/io/all.hpp" CAF_PUSH_WARNINGS #include "pingpong.pb.h" CAF_POP_WARNINGS using namespace std; using namespace caf; using namespace caf::io; void print_on_exit(const actor& hdl, const std::string& name) { hdl->attach_functor([=](abstract_actor* ptr, uint32_t reason) { aout(ptr) << name << " exited with reason " << reason << endl; }); } behavior ping(event_based_actor* self, size_t num_pings) { auto count = make_shared<size_t>(0); return { on(atom("kickoff"), arg_match) >> [=](const actor& pong) { self->send(pong, atom("ping"), 1); self->become ( on(atom("pong"), arg_match) >> [=](int value) -> message { if (++*count >= num_pings) self->quit(); return make_message(atom("ping"), value + 1); } ); } }; } behavior pong() { return { on(atom("ping"), arg_match) >> [](int value) { return make_message(atom("pong"), value); } }; } void protobuf_io(broker* self, connection_handle hdl, const actor& buddy) { self->monitor(buddy); auto write = [=](const org::libcppa::PingOrPong& p) { string buf = p.SerializeAsString(); int32_t s = htonl(static_cast<int32_t>(buf.size())); self->write(hdl, sizeof(int32_t), &s); self->write(hdl, buf.size(), buf.data()); self->flush(hdl); }; message_handler default_bhvr = { [=](const connection_closed_msg&) { aout(self) << "connection closed" << endl; self->send_exit(buddy, exit_reason::remote_link_unreachable); self->quit(exit_reason::remote_link_unreachable); }, on(atom("ping"), arg_match) >> [=](int i) { aout(self) << "'ping' " << i << endl; org::libcppa::PingOrPong p; p.mutable_ping()->set_id(i); write(p); }, on(atom("pong"), arg_match) >> [=](int i) { aout(self) << "'pong' " << i << endl; org::libcppa::PingOrPong p; p.mutable_pong()->set_id(i); write(p); }, [=](const down_msg& dm) { if (dm.source == buddy) { aout(self) << "our buddy is down" << endl; self->quit(dm.reason); } }, others >> [=] { cout << "unexpected: " << to_string(self->current_message()) << endl; } }; auto await_protobuf_data = message_handler { [=](const new_data_msg& msg) { org::libcppa::PingOrPong p; p.ParseFromArray(msg.buf.data(), static_cast<int>(msg.buf.size())); if (p.has_ping()) { self->send(buddy, atom("ping"), p.ping().id()); } else if (p.has_pong()) { self->send(buddy, atom("pong"), p.pong().id()); } else { self->quit(exit_reason::user_shutdown); cerr << "neither Ping nor Pong!" << endl; } // receive next length prefix self->configure_read(hdl, receive_policy::exactly(sizeof(int32_t))); self->unbecome(); } }.or_else(default_bhvr); auto await_length_prefix = message_handler { [=](const new_data_msg& msg) { int32_t num_bytes; memcpy(&num_bytes, msg.buf.data(), sizeof(int32_t)); num_bytes = htonl(num_bytes); if (num_bytes < 0 || num_bytes > (1024 * 1024)) { aout(self) << "someone is trying something nasty" << endl; self->quit(exit_reason::user_shutdown); return; } // receive protobuf data auto nb = static_cast<size_t>(num_bytes); self->configure_read(hdl, receive_policy::exactly(nb)); self->become(keep_behavior, await_protobuf_data); } }.or_else(default_bhvr); // initial setup self->configure_read(hdl, receive_policy::exactly(sizeof(int32_t))); self->become(await_length_prefix); } behavior server(broker* self, actor buddy) { aout(self) << "server is running" << endl; return { [=](const new_connection_msg& msg) { aout(self) << "server accepted new connection" << endl; auto io_actor = self->fork(protobuf_io, msg.handle, buddy); print_on_exit(io_actor, "protobuf_io"); // only accept 1 connection in our example self->quit(); }, others >> [=] { cout << "unexpected: " << to_string(self->current_message()) << endl; } }; } optional<uint16_t> as_u16(const std::string& str) { return static_cast<uint16_t>(stoul(str)); } int main(int argc, char** argv) { message_builder{argv + 1, argv + argc}.apply({ on("-s", as_u16) >> [&](uint16_t port) { cout << "run in server mode" << endl; auto pong_actor = spawn(pong); auto sever_actor = spawn_io_server(server, port, pong_actor); print_on_exit(sever_actor, "server"); print_on_exit(pong_actor, "pong"); }, on("-c", val<string>, as_u16) >> [&](const string& host, uint16_t port) { auto ping_actor = spawn(ping, 20); auto io_actor = spawn_io_client(protobuf_io, host, port, ping_actor); print_on_exit(io_actor, "protobuf_io"); print_on_exit(ping_actor, "ping"); send_as(io_actor, ping_actor, atom("kickoff"), io_actor); }, others >> [] { cerr << "use with eihter '-s PORT' as server or " "'-c HOST PORT' as client" << endl; } }); await_all_actors_done(); shutdown(); } <commit_msg>Replace optional with maybe in protobuf example<commit_after>#include <vector> #include <string> #include <limits> #include <memory> #include <iostream> #include <arpa/inet.h> #include "caf/all.hpp" #include "caf/io/all.hpp" CAF_PUSH_WARNINGS #include "pingpong.pb.h" CAF_POP_WARNINGS using namespace std; using namespace caf; using namespace caf::io; void print_on_exit(const actor& hdl, const std::string& name) { hdl->attach_functor([=](abstract_actor* ptr, uint32_t reason) { aout(ptr) << name << " exited with reason " << reason << endl; }); } behavior ping(event_based_actor* self, size_t num_pings) { auto count = make_shared<size_t>(0); return { on(atom("kickoff"), arg_match) >> [=](const actor& pong) { self->send(pong, atom("ping"), 1); self->become ( on(atom("pong"), arg_match) >> [=](int value) -> message { if (++*count >= num_pings) self->quit(); return make_message(atom("ping"), value + 1); } ); } }; } behavior pong() { return { on(atom("ping"), arg_match) >> [](int value) { return make_message(atom("pong"), value); } }; } void protobuf_io(broker* self, connection_handle hdl, const actor& buddy) { self->monitor(buddy); auto write = [=](const org::libcppa::PingOrPong& p) { string buf = p.SerializeAsString(); int32_t s = htonl(static_cast<int32_t>(buf.size())); self->write(hdl, sizeof(int32_t), &s); self->write(hdl, buf.size(), buf.data()); self->flush(hdl); }; message_handler default_bhvr = { [=](const connection_closed_msg&) { aout(self) << "connection closed" << endl; self->send_exit(buddy, exit_reason::remote_link_unreachable); self->quit(exit_reason::remote_link_unreachable); }, on(atom("ping"), arg_match) >> [=](int i) { aout(self) << "'ping' " << i << endl; org::libcppa::PingOrPong p; p.mutable_ping()->set_id(i); write(p); }, on(atom("pong"), arg_match) >> [=](int i) { aout(self) << "'pong' " << i << endl; org::libcppa::PingOrPong p; p.mutable_pong()->set_id(i); write(p); }, [=](const down_msg& dm) { if (dm.source == buddy) { aout(self) << "our buddy is down" << endl; self->quit(dm.reason); } }, others >> [=] { cout << "unexpected: " << to_string(self->current_message()) << endl; } }; auto await_protobuf_data = message_handler { [=](const new_data_msg& msg) { org::libcppa::PingOrPong p; p.ParseFromArray(msg.buf.data(), static_cast<int>(msg.buf.size())); if (p.has_ping()) { self->send(buddy, atom("ping"), p.ping().id()); } else if (p.has_pong()) { self->send(buddy, atom("pong"), p.pong().id()); } else { self->quit(exit_reason::user_shutdown); cerr << "neither Ping nor Pong!" << endl; } // receive next length prefix self->configure_read(hdl, receive_policy::exactly(sizeof(int32_t))); self->unbecome(); } }.or_else(default_bhvr); auto await_length_prefix = message_handler { [=](const new_data_msg& msg) { int32_t num_bytes; memcpy(&num_bytes, msg.buf.data(), sizeof(int32_t)); num_bytes = htonl(num_bytes); if (num_bytes < 0 || num_bytes > (1024 * 1024)) { aout(self) << "someone is trying something nasty" << endl; self->quit(exit_reason::user_shutdown); return; } // receive protobuf data auto nb = static_cast<size_t>(num_bytes); self->configure_read(hdl, receive_policy::exactly(nb)); self->become(keep_behavior, await_protobuf_data); } }.or_else(default_bhvr); // initial setup self->configure_read(hdl, receive_policy::exactly(sizeof(int32_t))); self->become(await_length_prefix); } behavior server(broker* self, actor buddy) { aout(self) << "server is running" << endl; return { [=](const new_connection_msg& msg) { aout(self) << "server accepted new connection" << endl; auto io_actor = self->fork(protobuf_io, msg.handle, buddy); print_on_exit(io_actor, "protobuf_io"); // only accept 1 connection in our example self->quit(); }, others >> [=] { cout << "unexpected: " << to_string(self->current_message()) << endl; } }; } maybe<uint16_t> as_u16(const std::string& str) { return static_cast<uint16_t>(stoul(str)); } int main(int argc, char** argv) { message_builder{argv + 1, argv + argc}.apply({ on("-s", as_u16) >> [&](uint16_t port) { cout << "run in server mode" << endl; auto pong_actor = spawn(pong); auto sever_actor = spawn_io_server(server, port, pong_actor); print_on_exit(sever_actor, "server"); print_on_exit(pong_actor, "pong"); }, on("-c", val<string>, as_u16) >> [&](const string& host, uint16_t port) { auto ping_actor = spawn(ping, 20); auto io_actor = spawn_io_client(protobuf_io, host, port, ping_actor); print_on_exit(io_actor, "protobuf_io"); print_on_exit(ping_actor, "ping"); send_as(io_actor, ping_actor, atom("kickoff"), io_actor); }, others >> [] { cerr << "use with eihter '-s PORT' as server or " "'-c HOST PORT' as client" << endl; } }); await_all_actors_done(); shutdown(); } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program 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. * * * * 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ /***************************************************************************** * User of this library should read the documentation * in the messaging.h file. ******************************************************************************/ #include <sstream> using std::ostringstream ; #include <iostream> using std::endl ; #include <vector> using std::vector ; #include <string> using std::string ; #include <algorithm> using std::remove ; #include "MessageDispatcher.h" #include "MessageHandler.h" #include "ConsoleMessageHandler.h" #include <sofa/core/objectmodel/Base.h> #include <sofa/helper/logging/DefaultStyleMessageFormatter.h> using sofa::helper::logging::DefaultStyleMessageFormatter; #include <mutex> using std::lock_guard ; using std::mutex; namespace sofa { namespace helper { namespace logging { std::vector<MessageHandler*> getDefaultMessageHandlers(){ std::vector<MessageHandler*> messageHandlers; static ConsoleMessageHandler s_consoleMessageHandler(&DefaultStyleMessageFormatter::getInstance()); messageHandlers.push_back(&s_consoleMessageHandler); return messageHandlers; } class MessageDispatcherImpl { public: std::vector<MessageHandler*> m_messageHandlers = getDefaultMessageHandlers(); std::vector<MessageHandler*>& getHandlers() { return m_messageHandlers ; } int addHandler(MessageHandler* o) { if( std::find(m_messageHandlers.begin(), m_messageHandlers.end(), o) == m_messageHandlers.end()) { m_messageHandlers.push_back(o) ; return (int)(m_messageHandlers.size()-1); } return -1; } int rmHandler(MessageHandler* o) { m_messageHandlers.erase(remove(m_messageHandlers.begin(), m_messageHandlers.end(), o), m_messageHandlers.end()); return (int)(m_messageHandlers.size()-1); } void clearHandlers() { m_messageHandlers.clear() ; } void process(sofa::helper::logging::Message& m) { for( size_t i=0 ; i<m_messageHandlers.size() ; i++ ) m_messageHandlers[i]->process(m) ; } }; MessageDispatcherImpl s_messagedispatcher ; mutex& getMutex(){ static mutex s_dispatchermutex ; return s_dispatchermutex ; } /*static std::vector<MessageHandler*> setDefaultMessageHandler() { /// This static function of the dispatcher has to be protected against concurent access /// This is done by a mutex and a scoped_guard as in Use the http://en.cppreference.com/w/cpp/thread/lock_guard //lock_guard<mutex> guard(s_dispatchermutex) ; std::vector<MessageHandler*> messageHandlers; messageHandlers.push_back(&s_consoleMessageHandler); return messageHandlers; }*/ std::vector<MessageHandler*>& MessageDispatcher::getHandlers() { lock_guard<mutex> guard(getMutex()) ; return s_messagedispatcher.getHandlers(); } int MessageDispatcher::addHandler(MessageHandler* o){ lock_guard<mutex> guard(getMutex()) ; return s_messagedispatcher.addHandler(o); } int MessageDispatcher::rmHandler(MessageHandler* o){ lock_guard<mutex> guard(getMutex()) ; return s_messagedispatcher.rmHandler(o); } void MessageDispatcher::clearHandlers(){ lock_guard<mutex> guard(getMutex()) ; s_messagedispatcher.clearHandlers(); } void MessageDispatcher::process(sofa::helper::logging::Message& m){ lock_guard<mutex> guard(getMutex()) ; s_messagedispatcher.process(m); } MessageDispatcher::LoggerStream MessageDispatcher::log(Message::Class mclass, Message::Type type, const std::string& sender, const FileInfo::SPtr& fileInfo) { return MessageDispatcher::LoggerStream( mclass, type, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::log(Message::Class mclass, Message::Type type, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) { return MessageDispatcher::LoggerStream(mclass, type, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::info(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Info, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::info(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Info, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::deprecated(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Deprecated, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::deprecated(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Deprecated, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::warning(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Warning, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::warning(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Warning, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::error(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Error, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::error(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Error, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::fatal(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Fatal, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::fatal(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Fatal, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::advice(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Advice, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::advice(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Advice, sender, fileInfo); } MessageDispatcher::LoggerStream::LoggerStream(Message::Class mclass, Message::Type type, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) : m_message( mclass , type , sender->getClassName() // temporary, until Base object reference kept in the message itself -> // (mattn) not sure it is a good idea, the Message could be kept after the Base is deleted // TODO(dmarchal): by converting this to a string we are not able anymore to // display rich information like the component name or location in the scene tree while these // information are really usefull. I have to make small experiment to see what could be a nice // approach without too much overhead. , fileInfo , ComponentInfo::SPtr( new ComponentInfo(sender)) ) { } MessageDispatcher::LoggerStream::~LoggerStream() { if ( !m_message.empty() ) MessageDispatcher::process(m_message); } } // logging } // helper } // sofa <commit_msg>[SofaKernel] WIP Fix the VS2013 problem with static mutex<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program 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. * * * * 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ /***************************************************************************** * User of this library should read the documentation * in the messaging.h file. ******************************************************************************/ #include <sstream> using std::ostringstream ; #include <iostream> using std::endl ; #include <vector> using std::vector ; #include <string> using std::string ; #include <algorithm> using std::remove ; #include "MessageDispatcher.h" #include "MessageHandler.h" #include "ConsoleMessageHandler.h" #include <sofa/core/objectmodel/Base.h> #include <sofa/helper/logging/DefaultStyleMessageFormatter.h> using sofa::helper::logging::DefaultStyleMessageFormatter; #include <mutex> using std::lock_guard ; using std::mutex; namespace sofa { namespace helper { namespace logging { std::vector<MessageHandler*> getDefaultMessageHandlers(){ std::vector<MessageHandler*> messageHandlers; static ConsoleMessageHandler s_consoleMessageHandler(&DefaultStyleMessageFormatter::getInstance()); messageHandlers.push_back(&s_consoleMessageHandler); return messageHandlers; } class MessageDispatcherImpl { public: mutex dispatchermutex ; std::vector<MessageHandler*> m_messageHandlers = getDefaultMessageHandlers(); std::vector<MessageHandler*>& getHandlers() { return m_messageHandlers ; } int addHandler(MessageHandler* o) { if( std::find(m_messageHandlers.begin(), m_messageHandlers.end(), o) == m_messageHandlers.end()) { m_messageHandlers.push_back(o) ; return (int)(m_messageHandlers.size()-1); } return -1; } int rmHandler(MessageHandler* o) { m_messageHandlers.erase(remove(m_messageHandlers.begin(), m_messageHandlers.end(), o), m_messageHandlers.end()); return (int)(m_messageHandlers.size()-1); } void clearHandlers() { m_messageHandlers.clear() ; } void process(sofa::helper::logging::Message& m) { for( size_t i=0 ; i<m_messageHandlers.size() ; i++ ) m_messageHandlers[i]->process(m) ; } }; MessageDispatcherImpl s_messagedispatcher ; mutex& getMutex(){ return s_messagedispatcher.dispatchermutex ; } /*static std::vector<MessageHandler*> setDefaultMessageHandler() { /// This static function of the dispatcher has to be protected against concurent access /// This is done by a mutex and a scoped_guard as in Use the http://en.cppreference.com/w/cpp/thread/lock_guard //lock_guard<mutex> guard(s_dispatchermutex) ; std::vector<MessageHandler*> messageHandlers; messageHandlers.push_back(&s_consoleMessageHandler); return messageHandlers; }*/ std::vector<MessageHandler*>& MessageDispatcher::getHandlers() { lock_guard<mutex> guard(getMutex()) ; return s_messagedispatcher.getHandlers(); } int MessageDispatcher::addHandler(MessageHandler* o){ lock_guard<mutex> guard(getMutex()) ; return s_messagedispatcher.addHandler(o); } int MessageDispatcher::rmHandler(MessageHandler* o){ lock_guard<mutex> guard(getMutex()) ; return s_messagedispatcher.rmHandler(o); } void MessageDispatcher::clearHandlers(){ lock_guard<mutex> guard(getMutex()) ; s_messagedispatcher.clearHandlers(); } void MessageDispatcher::process(sofa::helper::logging::Message& m){ lock_guard<mutex> guard(getMutex()) ; s_messagedispatcher.process(m); } MessageDispatcher::LoggerStream MessageDispatcher::log(Message::Class mclass, Message::Type type, const std::string& sender, const FileInfo::SPtr& fileInfo) { return MessageDispatcher::LoggerStream( mclass, type, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::log(Message::Class mclass, Message::Type type, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) { return MessageDispatcher::LoggerStream(mclass, type, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::info(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Info, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::info(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Info, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::deprecated(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Deprecated, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::deprecated(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Deprecated, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::warning(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Warning, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::warning(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Warning, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::error(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Error, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::error(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Error, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::fatal(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Fatal, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::fatal(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Fatal, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::advice(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Advice, sender, fileInfo); } MessageDispatcher::LoggerStream MessageDispatcher::advice(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) { return log(mclass, Message::Advice, sender, fileInfo); } MessageDispatcher::LoggerStream::LoggerStream(Message::Class mclass, Message::Type type, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) : m_message( mclass , type , sender->getClassName() // temporary, until Base object reference kept in the message itself -> // (mattn) not sure it is a good idea, the Message could be kept after the Base is deleted // TODO(dmarchal): by converting this to a string we are not able anymore to // display rich information like the component name or location in the scene tree while these // information are really usefull. I have to make small experiment to see what could be a nice // approach without too much overhead. , fileInfo , ComponentInfo::SPtr( new ComponentInfo(sender)) ) { } MessageDispatcher::LoggerStream::~LoggerStream() { if ( !m_message.empty() ) MessageDispatcher::process(m_message); } } // logging } // helper } // sofa <|endoftext|>
<commit_before>/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net) Version 1.1.0, packaged on March, 2009. http://glc-lib.sourceforge.net GLC-lib 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. GLC-lib 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 GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ //! \file glc_circle.cpp implementation of the GLC_Circle class. #include "glc_circle.h" #include "../glc_openglexception.h" #include "../glc_state.h" using namespace glc; ////////////////////////////////////////////////////////////////////// // Constructor destructor ////////////////////////////////////////////////////////////////////// GLC_Circle::GLC_Circle(const double &dRadius, double Angle) :GLC_VboGeom("Circle", true) , m_Radius(dRadius) , m_nDiscret(GLC_DISCRET) , m_dAngle(Angle) , m_Step(0) , m_SimpleGeomEngine() { } GLC_Circle::GLC_Circle(const GLC_Circle& sourceCircle) :GLC_VboGeom(sourceCircle) , m_Radius(sourceCircle.m_Radius) , m_nDiscret(sourceCircle.m_nDiscret) , m_dAngle(sourceCircle.m_dAngle) , m_SimpleGeomEngine(sourceCircle.m_SimpleGeomEngine) { // Copy inner material hash MaterialHash::const_iterator i= m_MaterialHash.begin(); MaterialHash newMaterialHash; while (i != m_MaterialHash.constEnd()) { // update inner material use table i.value()->delGLC_Geom(id()); GLC_Material* pNewMaterial= new GLC_Material(*(i.value())); newMaterialHash.insert(pNewMaterial->id(), pNewMaterial); pNewMaterial->addGLC_Geom(this); ++i; } m_MaterialHash= newMaterialHash; } GLC_Circle::~GLC_Circle() { } ////////////////////////////////////////////////////////////////////// // Get Functions ////////////////////////////////////////////////////////////////////// // Return Circle Discretion int GLC_Circle::getDiscretion(void) const { return m_nDiscret; } // Return Circle radius double GLC_Circle::getRadius(void) const { return m_Radius; } // return Circle diameter double GLC_Circle::getDiameter(void) const { return 2 * m_Radius; } // return the circle bounding box GLC_BoundingBox& GLC_Circle::boundingBox(void) { if (NULL == m_pBoundingBox) { m_pBoundingBox= new GLC_BoundingBox(); GLC_Point3d lower(-m_Radius, -m_Radius, -2.0 * EPSILON); GLC_Point3d upper(m_Radius, m_Radius, 2.0 * EPSILON); m_pBoundingBox->combine(lower); m_pBoundingBox->combine(upper); } return *m_pBoundingBox; } // Return a copy of the current geometry GLC_VboGeom* GLC_Circle::clone() const { return new GLC_Circle(*this); } ////////////////////////////////////////////////////////////////////// // Set Functions ////////////////////////////////////////////////////////////////////// // Set Circle diameter void GLC_Circle::setDiameter(double D) { Q_ASSERT(D > (2 * EPSILON)); setRadius(D / 2); } // Set Circle Radius void GLC_Circle::setRadius(double R) { Q_ASSERT(R > EPSILON); if ( fabs(R - m_Radius) > EPSILON) { // Radius is changing m_Radius= R; m_GeometryIsValid= false; if (NULL != m_pBoundingBox) { delete m_pBoundingBox; m_pBoundingBox= NULL; } } } // Set Circle discret void GLC_Circle::setDiscretion(int TargetDiscret) { Q_ASSERT(TargetDiscret > 0); if (TargetDiscret != m_nDiscret) { m_nDiscret= TargetDiscret; if (m_nDiscret < 6) m_nDiscret= 6; m_GeometryIsValid= false; } } // Set Circle Angle void GLC_Circle::setAngle(double AngleRadians) // Angle in Radians { Q_ASSERT((AngleRadians > EPSILON) && (AngleRadians < 2 * PI)); if ( fabs(AngleRadians - m_dAngle) > EPSILON) { // Angle is changing m_dAngle= AngleRadians; m_GeometryIsValid= false; if (NULL != m_pBoundingBox) { delete m_pBoundingBox; m_pBoundingBox= NULL; } } } ////////////////////////////////////////////////////////////////////// // OpenGL Functions ////////////////////////////////////////////////////////////////////// // Circle drawing void GLC_Circle::glDraw(bool) { const bool vboIsUsed= GLC_State::vboUsed(); if (vboIsUsed) { m_SimpleGeomEngine.createVBOs(); m_SimpleGeomEngine.useVBOs(true); } if (!m_GeometryIsValid) { VertexVector* pVertexVector= m_SimpleGeomEngine.vertexVectorHandle(); // Calculate number of step m_Step= static_cast<GLuint>(static_cast<double>(m_nDiscret) * (m_dAngle / (2 * glc::PI))); if (m_Step < 2) m_Step= 2; // Vertex Vector const GLsizeiptr size= (m_Step + 1) * sizeof(GLC_Vertex); // Resize the Vertex vector pVertexVector->resize(m_Step + 1); // Fill Vertex Vector for (GLuint i= 0; i <= m_Step; ++i) { (*pVertexVector)[i].x= static_cast<float>(m_Radius * cos(i * m_dAngle / m_Step)); (*pVertexVector)[i].y= static_cast<float>(m_Radius * sin(i * m_dAngle / m_Step)); } // Index Vector const GLsizeiptr IndexSize = (m_Step + 1) * sizeof(GLuint); // Resize index vector QVector<GLuint>* pIndexVector= m_SimpleGeomEngine.indexVectorHandle(); pIndexVector->resize(m_Step + 1); // Fill index vector for (GLuint i= 0; i <= m_Step; ++i) { (*pIndexVector)[i]= i; } if (vboIsUsed) { // Create VBO glBufferData(GL_ARRAY_BUFFER, size, pVertexVector->data(), GL_STATIC_DRAW); // Create IBO glBufferData(GL_ELEMENT_ARRAY_BUFFER, IndexSize, pIndexVector->data(), GL_STATIC_DRAW); // Clear Vector pVertexVector->clear(); pIndexVector->clear(); } } if (vboIsUsed) { // Use VBO glVertexPointer(2, GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(0)); glEnableClientState(GL_VERTEX_ARRAY); //glDrawRangeElements(GL_LINE_STRIP, 0, m_Step + 1, m_Step + 1, GL_UNSIGNED_INT, BUFFER_OFFSET(0)); glDrawElements(GL_LINE_STRIP, m_Step + 1, GL_UNSIGNED_INT, BUFFER_OFFSET(0)); glDisableClientState(GL_VERTEX_ARRAY); } else { // Use Vertex Array glVertexPointer(2, GL_FLOAT, sizeof(GLC_Vertex), m_SimpleGeomEngine.vertexVectorHandle()->data()); glEnableClientState(GL_VERTEX_ARRAY); glDrawElements(GL_LINE_STRIP, m_Step + 1, GL_UNSIGNED_INT, m_SimpleGeomEngine.indexVectorHandle()->data()); glDisableClientState(GL_VERTEX_ARRAY); } if (vboIsUsed) { m_SimpleGeomEngine.useVBOs(false); } // OpenGL error handler GLenum error= glGetError(); if (error != GL_NO_ERROR) { GLC_OpenGlException OpenGlException("GLC_Circle::GlDraw ", error); throw(OpenGlException); } } <commit_msg>Use qFuzzyCompare function instead of comparaison with glc::EPSILON to determine if to double or float are equal.<commit_after>/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net) Version 1.1.0, packaged on March, 2009. http://glc-lib.sourceforge.net GLC-lib 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. GLC-lib 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 GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ //! \file glc_circle.cpp implementation of the GLC_Circle class. #include "glc_circle.h" #include "../glc_openglexception.h" #include "../glc_state.h" using namespace glc; ////////////////////////////////////////////////////////////////////// // Constructor destructor ////////////////////////////////////////////////////////////////////// GLC_Circle::GLC_Circle(const double &dRadius, double Angle) :GLC_VboGeom("Circle", true) , m_Radius(dRadius) , m_nDiscret(GLC_DISCRET) , m_dAngle(Angle) , m_Step(0) , m_SimpleGeomEngine() { } GLC_Circle::GLC_Circle(const GLC_Circle& sourceCircle) :GLC_VboGeom(sourceCircle) , m_Radius(sourceCircle.m_Radius) , m_nDiscret(sourceCircle.m_nDiscret) , m_dAngle(sourceCircle.m_dAngle) , m_SimpleGeomEngine(sourceCircle.m_SimpleGeomEngine) { // Copy inner material hash MaterialHash::const_iterator i= m_MaterialHash.begin(); MaterialHash newMaterialHash; while (i != m_MaterialHash.constEnd()) { // update inner material use table i.value()->delGLC_Geom(id()); GLC_Material* pNewMaterial= new GLC_Material(*(i.value())); newMaterialHash.insert(pNewMaterial->id(), pNewMaterial); pNewMaterial->addGLC_Geom(this); ++i; } m_MaterialHash= newMaterialHash; } GLC_Circle::~GLC_Circle() { } ////////////////////////////////////////////////////////////////////// // Get Functions ////////////////////////////////////////////////////////////////////// // Return Circle Discretion int GLC_Circle::getDiscretion(void) const { return m_nDiscret; } // Return Circle radius double GLC_Circle::getRadius(void) const { return m_Radius; } // return Circle diameter double GLC_Circle::getDiameter(void) const { return 2 * m_Radius; } // return the circle bounding box GLC_BoundingBox& GLC_Circle::boundingBox(void) { if (NULL == m_pBoundingBox) { m_pBoundingBox= new GLC_BoundingBox(); GLC_Point3d lower(-m_Radius, -m_Radius, -2.0 * EPSILON); GLC_Point3d upper(m_Radius, m_Radius, 2.0 * EPSILON); m_pBoundingBox->combine(lower); m_pBoundingBox->combine(upper); } return *m_pBoundingBox; } // Return a copy of the current geometry GLC_VboGeom* GLC_Circle::clone() const { return new GLC_Circle(*this); } ////////////////////////////////////////////////////////////////////// // Set Functions ////////////////////////////////////////////////////////////////////// // Set Circle diameter void GLC_Circle::setDiameter(double D) { Q_ASSERT(not qFuzzyCompare(D, 0.0)); setRadius(D / 2); } // Set Circle Radius void GLC_Circle::setRadius(double R) { Q_ASSERT(not qFuzzyCompare(R, 0.0)); if (not qFuzzyCompare(R - m_Radius, 0.0)) { // Radius is changing m_Radius= R; m_GeometryIsValid= false; if (NULL != m_pBoundingBox) { delete m_pBoundingBox; m_pBoundingBox= NULL; } } } // Set Circle discret void GLC_Circle::setDiscretion(int TargetDiscret) { Q_ASSERT(TargetDiscret > 0); if (TargetDiscret != m_nDiscret) { m_nDiscret= TargetDiscret; if (m_nDiscret < 6) m_nDiscret= 6; m_GeometryIsValid= false; } } // Set Circle Angle void GLC_Circle::setAngle(double AngleRadians) // Angle in Radians { Q_ASSERT((not qFuzzyCompare(AngleRadians, 0.0)) && (AngleRadians < 2 * PI)); if (not qFuzzyCompare(AngleRadians - m_dAngle, 0.0)) { // Angle is changing m_dAngle= AngleRadians; m_GeometryIsValid= false; if (NULL != m_pBoundingBox) { delete m_pBoundingBox; m_pBoundingBox= NULL; } } } ////////////////////////////////////////////////////////////////////// // OpenGL Functions ////////////////////////////////////////////////////////////////////// // Circle drawing void GLC_Circle::glDraw(bool) { const bool vboIsUsed= GLC_State::vboUsed(); if (vboIsUsed) { m_SimpleGeomEngine.createVBOs(); m_SimpleGeomEngine.useVBOs(true); } if (!m_GeometryIsValid) { VertexVector* pVertexVector= m_SimpleGeomEngine.vertexVectorHandle(); // Calculate number of step m_Step= static_cast<GLuint>(static_cast<double>(m_nDiscret) * (m_dAngle / (2 * glc::PI))); if (m_Step < 2) m_Step= 2; // Vertex Vector const GLsizeiptr size= (m_Step + 1) * sizeof(GLC_Vertex); // Resize the Vertex vector pVertexVector->resize(m_Step + 1); // Fill Vertex Vector for (GLuint i= 0; i <= m_Step; ++i) { (*pVertexVector)[i].x= static_cast<float>(m_Radius * cos(i * m_dAngle / m_Step)); (*pVertexVector)[i].y= static_cast<float>(m_Radius * sin(i * m_dAngle / m_Step)); } // Index Vector const GLsizeiptr IndexSize = (m_Step + 1) * sizeof(GLuint); // Resize index vector QVector<GLuint>* pIndexVector= m_SimpleGeomEngine.indexVectorHandle(); pIndexVector->resize(m_Step + 1); // Fill index vector for (GLuint i= 0; i <= m_Step; ++i) { (*pIndexVector)[i]= i; } if (vboIsUsed) { // Create VBO glBufferData(GL_ARRAY_BUFFER, size, pVertexVector->data(), GL_STATIC_DRAW); // Create IBO glBufferData(GL_ELEMENT_ARRAY_BUFFER, IndexSize, pIndexVector->data(), GL_STATIC_DRAW); // Clear Vector pVertexVector->clear(); pIndexVector->clear(); } } if (vboIsUsed) { // Use VBO glVertexPointer(2, GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(0)); glEnableClientState(GL_VERTEX_ARRAY); //glDrawRangeElements(GL_LINE_STRIP, 0, m_Step + 1, m_Step + 1, GL_UNSIGNED_INT, BUFFER_OFFSET(0)); glDrawElements(GL_LINE_STRIP, m_Step + 1, GL_UNSIGNED_INT, BUFFER_OFFSET(0)); glDisableClientState(GL_VERTEX_ARRAY); } else { // Use Vertex Array glVertexPointer(2, GL_FLOAT, sizeof(GLC_Vertex), m_SimpleGeomEngine.vertexVectorHandle()->data()); glEnableClientState(GL_VERTEX_ARRAY); glDrawElements(GL_LINE_STRIP, m_Step + 1, GL_UNSIGNED_INT, m_SimpleGeomEngine.indexVectorHandle()->data()); glDisableClientState(GL_VERTEX_ARRAY); } if (vboIsUsed) { m_SimpleGeomEngine.useVBOs(false); } // OpenGL error handler GLenum error= glGetError(); if (error != GL_NO_ERROR) { GLC_OpenGlException OpenGlException("GLC_Circle::GlDraw ", error); throw(OpenGlException); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2011 J-P Nurmi jpnurmi@gmail.com * * 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. */ #include "application.h" #include "settingswizard.h" #include "sharedtimer.h" #include "connectioninfo.h" #include <QMessageBox> #include <QSettings> #include <QIcon> #include <Irc> QByteArray Application::ApplicationData::encoding; Settings Application::ApplicationData::settings; Application::Application(int& argc, char* argv[]) : QApplication(argc, argv) { setApplicationName("Communi"); setOrganizationName("Communi"); setApplicationVersion(Irc::version()); QIcon icon; icon.addFile(":/resources/icons/16x16/communi.png"); icon.addFile(":/resources/icons/26x26/communi.png"); icon.addFile(":/resources/icons/32x32/communi.png"); icon.addFile(":/resources/icons/48x48/communi.png"); icon.addFile(":/resources/icons/64x64/communi.png"); icon.addFile(":/resources/icons/128x128/communi.png"); setWindowIcon(icon); qRegisterMetaTypeStreamOperators<Settings>("Settings"); qRegisterMetaTypeStreamOperators<ConnectionInfo>("ConnectionInfo"); qRegisterMetaTypeStreamOperators<ConnectionInfos>("ConnectionInfos"); QSettings settings; ApplicationData::settings = settings.value("settings").value<Settings>(); SharedTimer::instance()->setInterval(500); } Application::~Application() { QSettings settings; settings.setValue("settings", ApplicationData::settings); } QString Application::applicationSlogan() { return tr("%1 is a simple and light-weight cross-platform IRC client.").arg(applicationName()); } QByteArray Application::encoding() { return ApplicationData::encoding; } void Application::setEncoding(const QByteArray& encoding) { ApplicationData::encoding = encoding; } Settings Application::settings() { return ApplicationData::settings; } void Application::setSettings(const Settings& settings) { if (ApplicationData::settings != settings) { ApplicationData::settings = settings; QMetaObject::invokeMethod(qApp, "settingsChanged", Q_ARG(Settings, settings)); } } void Application::aboutApplication() { QMessageBox::about( #ifdef Q_WS_MAC 0, #else activeWindow(), #endif // Q_WS_MAC applicationName(), QString( "<h3>%1</h3>" "<p>%2</p>" "<p><a href='%3'>%3</a></p>" "<p><small>Copyright (C) 2008-2011 J-P Nurmi &lt;" "<a href='mailto:jpnurmi@gmail.com'>jpnurmi@gmail.com</a>&gt;</small></p>") .arg(tr("About %1").arg(applicationName())) .arg(applicationSlogan()) .arg(organizationDomain()) ); } void Application::aboutOxygen() { QMessageBox::about( #ifdef Q_WS_MAC 0, #else activeWindow(), #endif // Q_WS_MAC "Oxygen", QString( "<h3>%1</h3>" "<p><a href='http://www.oxygen-icons.org/'>http://www.oxygen-icons.org/</a></p>" ).arg(tr("About %1").arg("Oxygen"))); } void Application::showSettings() { SettingsWizard wizard(activeWindow()); wizard.setSettings(settings()); if (wizard.exec()) setSettings(wizard.settings()); } <commit_msg>desktop ex: initialize proper encoding to avoid warnings<commit_after>/* * Copyright (C) 2008-2011 J-P Nurmi jpnurmi@gmail.com * * 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. */ #include "application.h" #include "settingswizard.h" #include "sharedtimer.h" #include "connectioninfo.h" #include <QMessageBox> #include <QSettings> #include <QIcon> #include <Irc> QByteArray Application::ApplicationData::encoding("UTF-8"); Settings Application::ApplicationData::settings; Application::Application(int& argc, char* argv[]) : QApplication(argc, argv) { setApplicationName("Communi"); setOrganizationName("Communi"); setApplicationVersion(Irc::version()); QIcon icon; icon.addFile(":/resources/icons/16x16/communi.png"); icon.addFile(":/resources/icons/26x26/communi.png"); icon.addFile(":/resources/icons/32x32/communi.png"); icon.addFile(":/resources/icons/48x48/communi.png"); icon.addFile(":/resources/icons/64x64/communi.png"); icon.addFile(":/resources/icons/128x128/communi.png"); setWindowIcon(icon); qRegisterMetaTypeStreamOperators<Settings>("Settings"); qRegisterMetaTypeStreamOperators<ConnectionInfo>("ConnectionInfo"); qRegisterMetaTypeStreamOperators<ConnectionInfos>("ConnectionInfos"); QSettings settings; ApplicationData::settings = settings.value("settings").value<Settings>(); SharedTimer::instance()->setInterval(500); } Application::~Application() { QSettings settings; settings.setValue("settings", ApplicationData::settings); } QString Application::applicationSlogan() { return tr("%1 is a simple and light-weight cross-platform IRC client.").arg(applicationName()); } QByteArray Application::encoding() { return ApplicationData::encoding; } void Application::setEncoding(const QByteArray& encoding) { ApplicationData::encoding = encoding; } Settings Application::settings() { return ApplicationData::settings; } void Application::setSettings(const Settings& settings) { if (ApplicationData::settings != settings) { ApplicationData::settings = settings; QMetaObject::invokeMethod(qApp, "settingsChanged", Q_ARG(Settings, settings)); } } void Application::aboutApplication() { QMessageBox::about( #ifdef Q_WS_MAC 0, #else activeWindow(), #endif // Q_WS_MAC applicationName(), QString( "<h3>%1</h3>" "<p>%2</p>" "<p><a href='%3'>%3</a></p>" "<p><small>Copyright (C) 2008-2011 J-P Nurmi &lt;" "<a href='mailto:jpnurmi@gmail.com'>jpnurmi@gmail.com</a>&gt;</small></p>") .arg(tr("About %1").arg(applicationName())) .arg(applicationSlogan()) .arg(organizationDomain()) ); } void Application::aboutOxygen() { QMessageBox::about( #ifdef Q_WS_MAC 0, #else activeWindow(), #endif // Q_WS_MAC "Oxygen", QString( "<h3>%1</h3>" "<p><a href='http://www.oxygen-icons.org/'>http://www.oxygen-icons.org/</a></p>" ).arg(tr("About %1").arg("Oxygen"))); } void Application::showSettings() { SettingsWizard wizard(activeWindow()); wizard.setSettings(settings()); if (wizard.exec()) setSettings(wizard.settings()); } <|endoftext|>
<commit_before>// // Copyright (c) 2019-2020 the rbfx project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "../Precompiled.h" #include "../Graphics/LightmapManager.h" #include "../Core/Context.h" #include "../Core/CoreEvents.h" #include "../Graphics/GlobalIllumination.h" #include "../Graphics/Octree.h" #include "../Graphics/Renderer.h" #include "../Graphics/Zone.h" #include "../Scene/Scene.h" #if URHO3D_GLOW #include "../Glow/IncrementalLightBaker.h" #endif namespace Urho3D { extern const char* SUBSYSTEM_CATEGORY; LightmapManager::LightmapManager(Context* context) : Component(context) { SubscribeToEvent(E_UPDATE, [this](StringHash eventType, VariantMap& eventData) { if (bakingScheduled_) { bakingScheduled_ = false; Bake(); } }); } LightmapManager::~LightmapManager() = default; void LightmapManager::RegisterObject(Context* context) { static const LightBakingSettings defaultSettings; context->RegisterFactory<LightmapManager>(SUBSYSTEM_CATEGORY); auto getBake = [](const ClassName& self, Urho3D::Variant& value) { value = false; }; auto setBake = [](ClassName& self, const Urho3D::Variant& value) { if (value.GetBool()) self.bakingScheduled_ = true; }; URHO3D_CUSTOM_ACCESSOR_ATTRIBUTE("Bake!", getBake, setBake, bool, false, AM_EDIT); URHO3D_ATTRIBUTE("Output Directory", ea::string, settings_.incremental_.outputDirectory_, "", AM_DEFAULT); URHO3D_ATTRIBUTE("Lightmap Size", unsigned, settings_.charting_.lightmapSize_, defaultSettings.charting_.lightmapSize_, AM_DEFAULT); URHO3D_ATTRIBUTE("Texel Density", float, settings_.charting_.texelDensity_, defaultSettings.charting_.texelDensity_, AM_DEFAULT); URHO3D_ATTRIBUTE("Indirect Multiplier", float, settings_.properties_.indirectMultiplier_, defaultSettings.properties_.indirectMultiplier_, AM_DEFAULT); URHO3D_ATTRIBUTE("Background Brightness", float, settings_.properties_.backgroundBrightness_, defaultSettings.properties_.backgroundBrightness_, AM_DEFAULT); URHO3D_ATTRIBUTE("Direct Samples (Lightmap)", unsigned, settings_.directChartTracing_.maxSamples_, defaultSettings.directChartTracing_.maxSamples_, AM_DEFAULT); URHO3D_ATTRIBUTE("Direct Samples (Light Probes)", unsigned, settings_.directProbesTracing_.maxSamples_, defaultSettings.directProbesTracing_.maxSamples_, AM_DEFAULT); URHO3D_ATTRIBUTE("Indirect Bounces", unsigned, settings_.indirectChartTracing_.maxBounces_, defaultSettings.indirectChartTracing_.maxBounces_, AM_DEFAULT); URHO3D_ATTRIBUTE("Indirect Samples (Texture)", unsigned, settings_.indirectChartTracing_.maxSamples_, defaultSettings.indirectChartTracing_.maxSamples_, AM_DEFAULT); URHO3D_ATTRIBUTE("Indirect Samples (Light Probes)", unsigned, settings_.indirectProbesTracing_.maxSamples_, defaultSettings.indirectProbesTracing_.maxSamples_, AM_DEFAULT); URHO3D_ATTRIBUTE("Filter Radius (Direct)", unsigned, settings_.directFilter_.kernelRadius_, defaultSettings.directFilter_.kernelRadius_, AM_DEFAULT); URHO3D_ATTRIBUTE("Filter Radius (Indirect)", unsigned, settings_.indirectFilter_.kernelRadius_, defaultSettings.indirectFilter_.kernelRadius_, AM_DEFAULT); URHO3D_ATTRIBUTE("Chunk Size", Vector3, settings_.incremental_.chunkSize_, defaultSettings.incremental_.chunkSize_, AM_DEFAULT); URHO3D_ATTRIBUTE("Chunk Indirect Padding", float, settings_.incremental_.indirectPadding_, defaultSettings.incremental_.indirectPadding_, AM_DEFAULT); URHO3D_ATTRIBUTE("Chunk Shadow Distance", float, settings_.incremental_.directionalLightShadowDistance_, defaultSettings.incremental_.directionalLightShadowDistance_, AM_DEFAULT); URHO3D_ATTRIBUTE("Stitch Iterations", unsigned, settings_.stitching_.numIterations_, defaultSettings.stitching_.numIterations_, AM_DEFAULT); } void LightmapManager::Bake() { // Fill settings settings_.indirectProbesTracing_.maxBounces_ = settings_.indirectChartTracing_.maxBounces_; const unsigned numTasks = settings_.charting_.lightmapSize_; settings_.geometryBufferPreprocessing_.numTasks_ = numTasks; settings_.emissionTracing_.numTasks_ = numTasks; settings_.directChartTracing_.numTasks_ = numTasks; settings_.directProbesTracing_.numTasks_ = numTasks; settings_.indirectChartTracing_.numTasks_ = numTasks; settings_.indirectProbesTracing_.numTasks_ = numTasks; auto octree = GetScene()->GetComponent<Octree>(); Zone* zone = octree->GetZone(); settings_.properties_.backgroundColor_ = zone->GetFogColor().ToVector3(); // Bake lightmaps if possible #if URHO3D_GLOW DefaultBakedSceneCollector sceneCollector; BakedLightMemoryCache lightmapCache; IncrementalLightBaker lightBaker; if (lightBaker.Initialize(settings_, GetScene(), &sceneCollector, &lightmapCache)) { lightBaker.ProcessScene(); lightBaker.Bake(); lightBaker.CommitScene(); } #endif // Compile light probes if (auto gi = GetScene()->GetComponent<GlobalIllumination>()) { gi->CompileLightProbes(); } } } <commit_msg>Add more logging in LightmapManager.<commit_after>// // Copyright (c) 2019-2020 the rbfx project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "../Precompiled.h" #include "../Graphics/LightmapManager.h" #include "../Core/Context.h" #include "../Core/CoreEvents.h" #include "../Core/Timer.h" #include "../Graphics/GlobalIllumination.h" #include "../Graphics/Octree.h" #include "../Graphics/Renderer.h" #include "../Graphics/Zone.h" #include "../IO/Log.h" #include "../Scene/Scene.h" #if URHO3D_GLOW #include "../Glow/IncrementalLightBaker.h" #endif namespace Urho3D { extern const char* SUBSYSTEM_CATEGORY; LightmapManager::LightmapManager(Context* context) : Component(context) { SubscribeToEvent(E_UPDATE, [this](StringHash eventType, VariantMap& eventData) { if (bakingScheduled_) { bakingScheduled_ = false; Bake(); } }); } LightmapManager::~LightmapManager() = default; void LightmapManager::RegisterObject(Context* context) { static const LightBakingSettings defaultSettings; context->RegisterFactory<LightmapManager>(SUBSYSTEM_CATEGORY); auto getBake = [](const ClassName& self, Urho3D::Variant& value) { value = false; }; auto setBake = [](ClassName& self, const Urho3D::Variant& value) { if (value.GetBool()) self.bakingScheduled_ = true; }; URHO3D_CUSTOM_ACCESSOR_ATTRIBUTE("Bake!", getBake, setBake, bool, false, AM_EDIT); URHO3D_ATTRIBUTE("Output Directory", ea::string, settings_.incremental_.outputDirectory_, "", AM_DEFAULT); URHO3D_ATTRIBUTE("Lightmap Size", unsigned, settings_.charting_.lightmapSize_, defaultSettings.charting_.lightmapSize_, AM_DEFAULT); URHO3D_ATTRIBUTE("Texel Density", float, settings_.charting_.texelDensity_, defaultSettings.charting_.texelDensity_, AM_DEFAULT); URHO3D_ATTRIBUTE("Indirect Multiplier", float, settings_.properties_.indirectMultiplier_, defaultSettings.properties_.indirectMultiplier_, AM_DEFAULT); URHO3D_ATTRIBUTE("Background Brightness", float, settings_.properties_.backgroundBrightness_, defaultSettings.properties_.backgroundBrightness_, AM_DEFAULT); URHO3D_ATTRIBUTE("Direct Samples (Lightmap)", unsigned, settings_.directChartTracing_.maxSamples_, defaultSettings.directChartTracing_.maxSamples_, AM_DEFAULT); URHO3D_ATTRIBUTE("Direct Samples (Light Probes)", unsigned, settings_.directProbesTracing_.maxSamples_, defaultSettings.directProbesTracing_.maxSamples_, AM_DEFAULT); URHO3D_ATTRIBUTE("Indirect Bounces", unsigned, settings_.indirectChartTracing_.maxBounces_, defaultSettings.indirectChartTracing_.maxBounces_, AM_DEFAULT); URHO3D_ATTRIBUTE("Indirect Samples (Texture)", unsigned, settings_.indirectChartTracing_.maxSamples_, defaultSettings.indirectChartTracing_.maxSamples_, AM_DEFAULT); URHO3D_ATTRIBUTE("Indirect Samples (Light Probes)", unsigned, settings_.indirectProbesTracing_.maxSamples_, defaultSettings.indirectProbesTracing_.maxSamples_, AM_DEFAULT); URHO3D_ATTRIBUTE("Filter Radius (Direct)", unsigned, settings_.directFilter_.kernelRadius_, defaultSettings.directFilter_.kernelRadius_, AM_DEFAULT); URHO3D_ATTRIBUTE("Filter Radius (Indirect)", unsigned, settings_.indirectFilter_.kernelRadius_, defaultSettings.indirectFilter_.kernelRadius_, AM_DEFAULT); URHO3D_ATTRIBUTE("Chunk Size", Vector3, settings_.incremental_.chunkSize_, defaultSettings.incremental_.chunkSize_, AM_DEFAULT); URHO3D_ATTRIBUTE("Chunk Indirect Padding", float, settings_.incremental_.indirectPadding_, defaultSettings.incremental_.indirectPadding_, AM_DEFAULT); URHO3D_ATTRIBUTE("Chunk Shadow Distance", float, settings_.incremental_.directionalLightShadowDistance_, defaultSettings.incremental_.directionalLightShadowDistance_, AM_DEFAULT); URHO3D_ATTRIBUTE("Stitch Iterations", unsigned, settings_.stitching_.numIterations_, defaultSettings.stitching_.numIterations_, AM_DEFAULT); } void LightmapManager::Bake() { // Fill settings settings_.indirectProbesTracing_.maxBounces_ = settings_.indirectChartTracing_.maxBounces_; const unsigned numTasks = settings_.charting_.lightmapSize_; settings_.geometryBufferPreprocessing_.numTasks_ = numTasks; settings_.emissionTracing_.numTasks_ = numTasks; settings_.directChartTracing_.numTasks_ = numTasks; settings_.directProbesTracing_.numTasks_ = numTasks; settings_.indirectChartTracing_.numTasks_ = numTasks; settings_.indirectProbesTracing_.numTasks_ = numTasks; auto octree = GetScene()->GetComponent<Octree>(); Zone* zone = octree->GetZone(); settings_.properties_.backgroundColor_ = zone->GetFogColor().ToVector3(); // Bake light if possible #if URHO3D_GLOW Timer timer; DefaultBakedSceneCollector sceneCollector; BakedLightMemoryCache lightmapCache; IncrementalLightBaker lightBaker; if (lightBaker.Initialize(settings_, GetScene(), &sceneCollector, &lightmapCache)) { lightBaker.ProcessScene(); lightBaker.Bake(); lightBaker.CommitScene(); } #else URHO3D_LOGERROR("Enable URHO3D_GLOW in build options"); #endif // Compile light probes if (auto gi = GetScene()->GetComponent<GlobalIllumination>()) { gi->CompileLightProbes(); } #if URHO3D_GLOW // Log overall time const unsigned totalMSec = timer.GetMSec(true); URHO3D_LOGINFO("Light baking is finished in {} seconds", totalMSec / 1000); #endif } } <|endoftext|>
<commit_before> #include "MarchingCubesShaded.h" #include "MappedData.h" #include "ShaderProgram.h" #include "MarchingCubesFactory.h" #include "Camera.h" #include <glm\geometric.hpp> #include <glm\common.hpp> #include <glm\gtc\matrix_transform.hpp> #include <glm\gtc\type_ptr.hpp> using namespace std; MarchingCubesShaded::MarchingCubesShaded( const char* filePath ) { MappedData paramFile( filePath ); vPosition = paramFile.getData("base","position").getVec3f(); vSpan = paramFile.getData("base","span").getVec3f(); dataWidth = paramFile.getData("base","dataWidth").getInt(); dataHeight = paramFile.getData("base","dataHeight").getInt(); dataDepth = paramFile.getData("base","dataDepth").getInt(); dataWidth = dataWidth<DATA_MIN ? DATA_MIN : dataWidth; dataHeight = dataHeight<DATA_MIN ? DATA_MIN : dataHeight; dataDepth = dataDepth<DATA_MIN ? DATA_MIN : dataDepth; dataMax = paramFile.getData("base","maxValue").getInt(); treshold = paramFile.getData("base","treshold").getFloat( 0.5f ); string vertex = paramFile.getData("shaders", "v").getStringData(); string geometry = paramFile.getData("shaders", "g").getStringData(); string fragment = paramFile.getData("shaders", "f").getStringData(); mcShader = ShaderProgram::CreateShader( vertex, geometry, fragment ); GLuint programHandle = mcShader->getProgramID(); initDataField( ); initGridBuffer( ); mcShader->turnOn(); mcShader->setUniformI( "Data", 0 ); mcShader->setUniformI( "TriTable", 1 ); mcShader->setUniformV3( "VerticeOffsets[0]", 0.0f, 0.0f, 0.0f ); mcShader->setUniformV3( "VerticeOffsets[1]", gridStep.x, 0.0f, 0.0f ); mcShader->setUniformV3( "VerticeOffsets[2]", gridStep.x, gridStep.y, 0.0f ); mcShader->setUniformV3( "VerticeOffsets[3]", 0.0f, gridStep.y, 0.0f ); mcShader->setUniformV3( "VerticeOffsets[4]", 0.0f, 0.0f, gridStep.z ); mcShader->setUniformV3( "VerticeOffsets[5]", gridStep.x, 0.0f, gridStep.z ); mcShader->setUniformV3( "VerticeOffsets[6]", gridStep.x, gridStep.y, gridStep.z ); mcShader->setUniformV3( "VerticeOffsets[7]", 0.0f, gridStep.y, gridStep.z ); mcShader->setUniformV3( "DataStep", 1.0f/dataWidth, 1.0f/dataHeight, 1.0f/dataDepth ); mcShader->turnOff(); clear(); } MarchingCubesShaded::~MarchingCubesShaded( ) { delete [] dataField; // delete buffer and vao glDeleteBuffers(1,&gridHandle); glDeleteVertexArrays(1,&gridVao); } // Create a 3D grid of points in the span od 0,0,0 - 1,1,1 // This will be bound to the VAO and sent to the shader as vertices // Actual data that generates the marching cube mesh is sent as a 3D texture void MarchingCubesShaded::initGridBuffer( ) { gridStep = vec3f(1,1,1) / (vec3f(dataWidth, dataHeight, dataDepth)-vec3f(1,1,1)); gridElementCount = (dataWidth + 1)*(dataHeight + 1)*(dataDepth + 1); int gridTotalSize = gridElementCount*3; float* grid = new float[gridTotalSize]; int index = 0; for( float x = -gridStep.x; x <= 1.0f; x+=gridStep.x ) { for( float y = -gridStep.y; y <= 1.0f; y+=gridStep.y ) { for( float z = -gridStep.z; z <= 1.0f; z+=gridStep.z ) { grid[ index ] = x; grid[ index+1 ] = y; grid[ index+2 ] = z; index += 3; } } } glGenBuffers(1, &gridHandle); glBindBuffer( GL_ARRAY_BUFFER, gridHandle ); glBufferData( GL_ARRAY_BUFFER, gridTotalSize * sizeof(float), grid, GL_STATIC_DRAW ); delete[] grid; glGenVertexArrays( 1, &gridVao ); glBindVertexArray( gridVao ); glEnableVertexAttribArray(0); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte *)NULL ); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glDisableVertexAttribArray(0); } void MarchingCubesShaded::initDataField( ) { // MC DATA glGenTextures(1, &dataTexID); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_3D); glBindTexture(GL_TEXTURE_3D, dataTexID); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glDisable(GL_TEXTURE_3D); dataSize = dataWidth * dataHeight * dataDepth; deltaSpan = vSpan / vec3f( dataWidth, dataHeight, dataDepth ); dataField = new float[ dataSize ](); dataChanged = true; // glTexImage3D( GL_TEXTURE_3D, 0, GL_ALPHA32F_ARB, dataWidth, dataHeight, dataDepth, 0, GL_ALPHA, GL_FLOAT, dataField); } void MarchingCubesShaded::setUnchecked( int x, int y, int z, float value ) { float &data = dataField[ x*dataHeight*dataDepth + y*dataDepth + z ]; data = contain(value+data, 0.0f, dataMax); dataChanged = true; } void MarchingCubesShaded::set( int x, int y, int z, float value ) { if( x<1 || y<1 || z<1 || x>=dataWidth-1 || y>=dataHeight-1 || z>=dataDepth-1 ) return; float &data = dataField[ x*dataHeight*dataDepth + y*dataDepth + z ]; data = contain(value+data, 0.0f, dataMax); dataChanged = true; } void MarchingCubesShaded::set( int position, float value ) { if( position<0 || position>dataSize ) return; dataField[ position ] = contain(value, 0.0f, dataMax); dataChanged = true; } void MarchingCubesShaded::clear() { memset( dataField, 0, dataSize*sizeof(float) ); dataChanged = true; } vec3f MarchingCubesShaded::getScale() { return vSpan; } vec3f MarchingCubesShaded::getPosition() { return vPosition; } float MarchingCubesShaded::getTreshold() { return this->treshold; } void MarchingCubesShaded::setTreshold( float t ) { this->treshold = t; } void MarchingCubesShaded::putSphere( float x, float y, float z, float r ) { float value; vec3f start = vec3f( x-r, y-r, z-r ); glm::clamp( start, vPosition, vPosition+vSpan ); start -= vPosition; start /= deltaSpan; vec3f end = vec3f( x+r, y+r, z+r ); glm::clamp( end, vPosition, vPosition+vSpan ); end -= vPosition; end /= deltaSpan; vec3f center = (vec3f( x,y,z ) - vPosition) / deltaSpan; r /= glm::length( deltaSpan ); for(int i=start.x; i<end.x; i++) { for(int j=start.y; j<end.y; j++) { for(int k=start.z; k<end.z; k++) { value = r-glm::length(center-vec3f(i,j,k))+1; if (value > 0) { set(i, j, k, value); } } } } } void MarchingCubesShaded::draw(const Camera& camera) { glm::mat4 mvp = camera.getViewProjection() * transform.getTransformMatrix(); glm::vec3 eye = camera.getPosition(); glDisable( GL_CULL_FACE ); mcShader->turnOn(); mcShader->setUniformF( "Treshold", this->treshold ); mcShader->setUniformV3( "Color", 0.0f, 0.3f, 1.0f ); mcShader->setUniformV3( "Diffuse", 0.4f, 0.9f, 0.0f ); mcShader->setUniformV3( "Specular", 1.0f, 1.0f, 1.0f ); mcShader->setUniformV3( "Ambient", 0.3f, 0.8f, 0.6f ); mcShader->setUniformV3( "LightPosition", 20.f, -15.0f, 5.0f ); mcShader->setUniformV3( "Eye", eye.x, eye.y, eye.z ); mcShader->setUniformM4( "MVP", glm::value_ptr(mvp) ); MarchingCubesFactory::setTexture( GL_TEXTURE1 ); glEnable( GL_TEXTURE_3D ); glActiveTexture( GL_TEXTURE0 ); glBindTexture( GL_TEXTURE_3D, dataTexID ); if (dataChanged) { glTexImage3D(GL_TEXTURE_3D, 0, GL_ALPHA32F_ARB, dataWidth, dataHeight, dataDepth, 0, GL_ALPHA, GL_FLOAT, dataField); } // ! GLboolean blendEnabled = glIsEnabled( GL_BLEND ); glEnable( GL_BLEND ); glBlendFunc(GL_ONE, GL_ONE); glDepthMask(GL_FALSE); glBindVertexArray(gridVao); glDrawArrays(GL_POINTS, 0, gridElementCount ); glBindVertexArray(0); glDepthMask(GL_TRUE); if( !blendEnabled ) glDisable( GL_BLEND ); glDisable( GL_TEXTURE_3D); mcShader->turnOff(); glEnable( GL_CULL_FACE ); }<commit_msg>MCS: forgot to reset the changed flag. Moved setting of fixed uniforms.<commit_after> #include "MarchingCubesShaded.h" #include "MappedData.h" #include "ShaderProgram.h" #include "MarchingCubesFactory.h" #include "Camera.h" #include <glm\geometric.hpp> #include <glm\common.hpp> #include <glm\gtc\matrix_transform.hpp> #include <glm\gtc\type_ptr.hpp> using namespace std; MarchingCubesShaded::MarchingCubesShaded( const char* filePath ) { MappedData paramFile( filePath ); vPosition = paramFile.getData("base","position").getVec3f(); vSpan = paramFile.getData("base","span").getVec3f(); dataWidth = paramFile.getData("base","dataWidth").getInt(); dataHeight = paramFile.getData("base","dataHeight").getInt(); dataDepth = paramFile.getData("base","dataDepth").getInt(); dataWidth = dataWidth<DATA_MIN ? DATA_MIN : dataWidth; dataHeight = dataHeight<DATA_MIN ? DATA_MIN : dataHeight; dataDepth = dataDepth<DATA_MIN ? DATA_MIN : dataDepth; dataMax = paramFile.getData("base","maxValue").getInt(); treshold = paramFile.getData("base","treshold").getFloat( 0.5f ); string vertex = paramFile.getData("shaders", "v").getStringData(); string geometry = paramFile.getData("shaders", "g").getStringData(); string fragment = paramFile.getData("shaders", "f").getStringData(); mcShader = ShaderProgram::CreateShader( vertex, geometry, fragment ); GLuint programHandle = mcShader->getProgramID(); initDataField( ); initGridBuffer( ); mcShader->turnOn(); mcShader->setUniformI( "Data", 0 ); mcShader->setUniformI( "TriTable", 1 ); mcShader->setUniformV3( "VerticeOffsets[0]", 0.0f, 0.0f, 0.0f ); mcShader->setUniformV3( "VerticeOffsets[1]", gridStep.x, 0.0f, 0.0f ); mcShader->setUniformV3( "VerticeOffsets[2]", gridStep.x, gridStep.y, 0.0f ); mcShader->setUniformV3( "VerticeOffsets[3]", 0.0f, gridStep.y, 0.0f ); mcShader->setUniformV3( "VerticeOffsets[4]", 0.0f, 0.0f, gridStep.z ); mcShader->setUniformV3( "VerticeOffsets[5]", gridStep.x, 0.0f, gridStep.z ); mcShader->setUniformV3( "VerticeOffsets[6]", gridStep.x, gridStep.y, gridStep.z ); mcShader->setUniformV3( "VerticeOffsets[7]", 0.0f, gridStep.y, gridStep.z ); mcShader->setUniformV3("Color", 0.0f, 0.3f, 1.0f); mcShader->setUniformV3("Diffuse", 0.4f, 0.9f, 0.0f); mcShader->setUniformV3("Specular", 1.0f, 1.0f, 1.0f); mcShader->setUniformV3("Ambient", 0.3f, 0.8f, 0.6f); mcShader->setUniformV3("LightPosition", 20.f, -15.0f, 5.0f); mcShader->setUniformV3( "DataStep", 1.0f/dataWidth, 1.0f/dataHeight, 1.0f/dataDepth ); mcShader->turnOff(); clear(); } MarchingCubesShaded::~MarchingCubesShaded( ) { delete [] dataField; // delete buffer and vao glDeleteBuffers(1,&gridHandle); glDeleteVertexArrays(1,&gridVao); } // Create a 3D grid of points in the span od 0,0,0 - 1,1,1 // This will be bound to the VAO and sent to the shader as vertices // Actual data that generates the marching cube mesh is sent as a 3D texture void MarchingCubesShaded::initGridBuffer( ) { gridStep = vec3f(1,1,1) / (vec3f(dataWidth, dataHeight, dataDepth)-vec3f(1,1,1)); gridElementCount = (dataWidth + 1)*(dataHeight + 1)*(dataDepth + 1); int gridTotalSize = gridElementCount*3; float* grid = new float[gridTotalSize]; int index = 0; for( float x = -gridStep.x; x <= 1.0f; x+=gridStep.x ) { for( float y = -gridStep.y; y <= 1.0f; y+=gridStep.y ) { for( float z = -gridStep.z; z <= 1.0f; z+=gridStep.z ) { grid[ index ] = x; grid[ index+1 ] = y; grid[ index+2 ] = z; index += 3; } } } glGenBuffers(1, &gridHandle); glBindBuffer( GL_ARRAY_BUFFER, gridHandle ); glBufferData( GL_ARRAY_BUFFER, gridTotalSize * sizeof(float), grid, GL_STATIC_DRAW ); delete[] grid; glGenVertexArrays( 1, &gridVao ); glBindVertexArray( gridVao ); glEnableVertexAttribArray(0); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte *)NULL ); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glDisableVertexAttribArray(0); } void MarchingCubesShaded::initDataField( ) { // MC DATA glGenTextures(1, &dataTexID); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_3D); glBindTexture(GL_TEXTURE_3D, dataTexID); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glDisable(GL_TEXTURE_3D); dataSize = dataWidth * dataHeight * dataDepth; deltaSpan = vSpan / vec3f( dataWidth, dataHeight, dataDepth ); dataField = new float[ dataSize ](); dataChanged = true; // data is updated when changed // glTexImage3D( GL_TEXTURE_3D, 0, GL_ALPHA32F_ARB, dataWidth, dataHeight, dataDepth, 0, GL_ALPHA, GL_FLOAT, dataField); } void MarchingCubesShaded::setUnchecked( int x, int y, int z, float value ) { float &data = dataField[ x*dataHeight*dataDepth + y*dataDepth + z ]; data = contain(value+data, 0.0f, dataMax); dataChanged = true; } void MarchingCubesShaded::set( int x, int y, int z, float value ) { if( x<1 || y<1 || z<1 || x>=dataWidth-1 || y>=dataHeight-1 || z>=dataDepth-1 ) return; float &data = dataField[ x*dataHeight*dataDepth + y*dataDepth + z ]; data = contain(value+data, 0.0f, dataMax); dataChanged = true; } void MarchingCubesShaded::set( int position, float value ) { if( position<0 || position>dataSize ) return; dataField[ position ] = contain(value, 0.0f, dataMax); dataChanged = true; } void MarchingCubesShaded::clear() { memset( dataField, 0, dataSize*sizeof(float) ); dataChanged = true; } vec3f MarchingCubesShaded::getScale() { return vSpan; } vec3f MarchingCubesShaded::getPosition() { return vPosition; } float MarchingCubesShaded::getTreshold() { return this->treshold; } void MarchingCubesShaded::setTreshold( float t ) { this->treshold = t; } void MarchingCubesShaded::putSphere( float x, float y, float z, float r ) { float value; vec3f start = vec3f( x-r, y-r, z-r ); glm::clamp( start, vPosition, vPosition+vSpan ); start -= vPosition; start /= deltaSpan; vec3f end = vec3f( x+r, y+r, z+r ); glm::clamp( end, vPosition, vPosition+vSpan ); end -= vPosition; end /= deltaSpan; vec3f center = (vec3f( x,y,z ) - vPosition) / deltaSpan; r /= glm::length( deltaSpan ); for(int i=start.x; i<end.x; i++) { for(int j=start.y; j<end.y; j++) { for(int k=start.z; k<end.z; k++) { value = r-glm::length(center-vec3f(i,j,k))+1; if (value > 0) { set(i, j, k, value); } } } } } void MarchingCubesShaded::draw(const Camera& camera) { glm::mat4 mvp = camera.getViewProjection() * transform.getTransformMatrix(); glm::vec3 eye = camera.getPosition(); glDisable( GL_CULL_FACE ); mcShader->turnOn(); mcShader->setUniformF( "Treshold", this->treshold ); mcShader->setUniformV3( "Eye", eye.x, eye.y, eye.z ); mcShader->setUniformM4( "MVP", glm::value_ptr(mvp) ); MarchingCubesFactory::setTexture( GL_TEXTURE1 ); glEnable( GL_TEXTURE_3D ); glActiveTexture( GL_TEXTURE0 ); glBindTexture( GL_TEXTURE_3D, dataTexID ); if (dataChanged) { glTexImage3D(GL_TEXTURE_3D, 0, GL_ALPHA32F_ARB, dataWidth, dataHeight, dataDepth, 0, GL_ALPHA, GL_FLOAT, dataField); dataChanged = false; } // ! GLboolean blendEnabled = glIsEnabled( GL_BLEND ); glEnable( GL_BLEND ); glBlendFunc(GL_ONE, GL_ONE); glDepthMask(GL_FALSE); glBindVertexArray(gridVao); glDrawArrays(GL_POINTS, 0, gridElementCount ); glBindVertexArray(0); glDepthMask(GL_TRUE); if( !blendEnabled ) glDisable( GL_BLEND ); glDisable( GL_TEXTURE_3D); mcShader->turnOff(); glEnable( GL_CULL_FACE ); }<|endoftext|>
<commit_before>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL. #include <osgViewer/Viewer> #include <osgViewer/StatsHandler> #include <osgGA/TrackballManipulator> #include <osgDB/ReadFile> #if USE_QT4 #include <QtCore/QTimer> #include <QtGui/QKeyEvent> #include <QtGui/QApplication> #include <QtOpenGL/QGLWidget> using Qt::WFlags; #else class QWidget; #include <qtimer.h> #include <qgl.h> #include <qapplication.h> #endif #include <iostream> class AdapterWidget : public QGLWidget { public: AdapterWidget( QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WFlags f = 0 ); virtual ~AdapterWidget() {} osgViewer::GraphicsWindow* getGraphicsWindow() { return _gw.get(); } const osgViewer::GraphicsWindow* getGraphicsWindow() const { return _gw.get(); } protected: void init(); virtual void resizeGL( int width, int height ); virtual void keyPressEvent( QKeyEvent* event ); virtual void keyReleaseEvent( QKeyEvent* event ); virtual void mousePressEvent( QMouseEvent* event ); virtual void mouseReleaseEvent( QMouseEvent* event ); virtual void mouseMoveEvent( QMouseEvent* event ); QTimer _timer; osg::ref_ptr<osgViewer::GraphicsWindowEmbedded> _gw; }; AdapterWidget::AdapterWidget( QWidget * parent, const char * name, const QGLWidget * shareWidget, WFlags f): QGLWidget(parent, name, shareWidget, f) { connect(&_timer, SIGNAL(timeout()), this, SLOT(updateGL())); _timer.start(10); _gw = new osgViewer::GraphicsWindowEmbedded(0,0,width(),height()); } void AdapterWidget::resizeGL( int width, int height ) { _gw->getEventQueue()->windowResize(0, 0, width, height ); _gw->resized(0,0,width,height); } void AdapterWidget::keyPressEvent( QKeyEvent* event ) { _gw->getEventQueue()->keyPress( (osgGA::GUIEventAdapter::KeySymbol) event->ascii() ); } void AdapterWidget::keyReleaseEvent( QKeyEvent* event ) { _gw->getEventQueue()->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) event->ascii() ); } void AdapterWidget::mousePressEvent( QMouseEvent* event ) { int button = 0; switch(event->button()) { case(Qt::LeftButton): button = 1; break; case(Qt::MidButton): button = 2; break; case(Qt::RightButton): button = 3; break; case(Qt::NoButton): button = 0; break; default: button = 0; break; } _gw->getEventQueue()->mouseButtonPress(event->x(), event->y(), button); } void AdapterWidget::mouseReleaseEvent( QMouseEvent* event ) { int button = 0; switch(event->button()) { case(Qt::LeftButton): button = 1; break; case(Qt::MidButton): button = 2; break; case(Qt::RightButton): button = 3; break; case(Qt::NoButton): button = 0; break; default: button = 0; break; } _gw->getEventQueue()->mouseButtonRelease(event->x(), event->y(), button); } void AdapterWidget::mouseMoveEvent( QMouseEvent* event ) { _gw->getEventQueue()->mouseMotion(event->x(), event->y()); } class ViewerQT : public AdapterWidget, public osgViewer::Viewer { public: ViewerQT(QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WFlags f = 0): AdapterWidget( parent, name, shareWidget, f ) { getCamera()->setViewport(new osg::Viewport(0,0,width(),height())); getCamera()->setGraphicsContext(getGraphicsWindow()); setThreadingModel(osgViewer::Viewer::SingleThreaded); } virtual void initializeGL() { QGLWidget::initializeGL(); } virtual void paintGL() { frame(); } }; int main( int argc, char **argv ) { QApplication a( argc, argv ); if (argc<2) { std::cout << argv[0] <<": requires filename argument." << std::endl; return 1; } // load the scene. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]); if (!loadedModel) { std::cout << argv[0] <<": No data loaded." << std::endl; return 1; } ViewerQT* viewerWindow = new ViewerQT; viewerWindow->setSceneData(loadedModel.get()); viewerWindow->setCameraManipulator(new osgGA::TrackballManipulator); viewerWindow->addEventHandler(new osgViewer::StatsHandler); viewerWindow->show(); a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) ); return a.exec(); } /*EOF*/ <commit_msg>Cleaned up example<commit_after>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL. #include <osgViewer/Viewer> #include <osgViewer/StatsHandler> #include <osgGA/TrackballManipulator> #include <osgDB/ReadFile> #if USE_QT4 #include <QtCore/QTimer> #include <QtGui/QKeyEvent> #include <QtGui/QApplication> #include <QtOpenGL/QGLWidget> using Qt::WFlags; #else class QWidget; #include <qtimer.h> #include <qgl.h> #include <qapplication.h> #endif #include <iostream> class AdapterWidget : public QGLWidget { public: AdapterWidget( QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WFlags f = 0 ); virtual ~AdapterWidget() {} osgViewer::GraphicsWindow* getGraphicsWindow() { return _gw.get(); } const osgViewer::GraphicsWindow* getGraphicsWindow() const { return _gw.get(); } protected: void init(); virtual void resizeGL( int width, int height ); virtual void keyPressEvent( QKeyEvent* event ); virtual void keyReleaseEvent( QKeyEvent* event ); virtual void mousePressEvent( QMouseEvent* event ); virtual void mouseReleaseEvent( QMouseEvent* event ); virtual void mouseMoveEvent( QMouseEvent* event ); osg::ref_ptr<osgViewer::GraphicsWindowEmbedded> _gw; }; AdapterWidget::AdapterWidget( QWidget * parent, const char * name, const QGLWidget * shareWidget, WFlags f): QGLWidget(parent, name, shareWidget, f) { _gw = new osgViewer::GraphicsWindowEmbedded(0,0,width(),height()); } void AdapterWidget::resizeGL( int width, int height ) { _gw->getEventQueue()->windowResize(0, 0, width, height ); _gw->resized(0,0,width,height); } void AdapterWidget::keyPressEvent( QKeyEvent* event ) { _gw->getEventQueue()->keyPress( (osgGA::GUIEventAdapter::KeySymbol) event->ascii() ); } void AdapterWidget::keyReleaseEvent( QKeyEvent* event ) { _gw->getEventQueue()->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) event->ascii() ); } void AdapterWidget::mousePressEvent( QMouseEvent* event ) { int button = 0; switch(event->button()) { case(Qt::LeftButton): button = 1; break; case(Qt::MidButton): button = 2; break; case(Qt::RightButton): button = 3; break; case(Qt::NoButton): button = 0; break; default: button = 0; break; } _gw->getEventQueue()->mouseButtonPress(event->x(), event->y(), button); } void AdapterWidget::mouseReleaseEvent( QMouseEvent* event ) { int button = 0; switch(event->button()) { case(Qt::LeftButton): button = 1; break; case(Qt::MidButton): button = 2; break; case(Qt::RightButton): button = 3; break; case(Qt::NoButton): button = 0; break; default: button = 0; break; } _gw->getEventQueue()->mouseButtonRelease(event->x(), event->y(), button); } void AdapterWidget::mouseMoveEvent( QMouseEvent* event ) { _gw->getEventQueue()->mouseMotion(event->x(), event->y()); } class ViewerQT : public osgViewer::Viewer, public AdapterWidget { public: ViewerQT(QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WFlags f = 0): AdapterWidget( parent, name, shareWidget, f ) { getCamera()->setViewport(new osg::Viewport(0,0,width(),height())); getCamera()->setGraphicsContext(getGraphicsWindow()); setThreadingModel(osgViewer::Viewer::SingleThreaded); connect(&_timer, SIGNAL(timeout()), this, SLOT(updateGL())); _timer.start(10); } virtual void paintGL() { frame(); } protected: QTimer _timer; }; int main( int argc, char **argv ) { QApplication a( argc, argv ); if (argc<2) { std::cout << argv[0] <<": requires filename argument." << std::endl; return 1; } // load the scene. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]); if (!loadedModel) { std::cout << argv[0] <<": No data loaded." << std::endl; return 1; } ViewerQT* viewerWindow = new ViewerQT; viewerWindow->setSceneData(loadedModel.get()); viewerWindow->setCameraManipulator(new osgGA::TrackballManipulator); viewerWindow->addEventHandler(new osgViewer::StatsHandler); viewerWindow->show(); a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) ); return a.exec(); } /*EOF*/ <|endoftext|>
<commit_before>/** Copyright (c) 2014-2015, Sandia Corporation All rights reserved. This file is part of fast-matmul and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause. */ #include "common.hpp" #ifdef __INTEL_MKL__ # include "mkl.h" #endif #include "scaling.hpp" #include "strassen.hpp" #include <algorithm> #include <stdexcept> #include <vector> enum Algorithm { CLASSICAL = 0, STRASSEN, STRASSEN_SCALED, }; // Run a single benchmark for multiplying m x k x n with num_steps of recursion. // To just call GEMM, set num_steps to zero. // The median of five trials is printed to std::cout. // If run_check is true, then it also void SingleBenchmark(int m, int k, int n, int alg) { // Run a set number of trials and pick the median time. int num_trials = 5; std::vector<double> times(num_trials); for (int trial = 0; trial < num_trials; ++trial) { Matrix<double> A = RandomMatrix<double>(m, k); Matrix<double> B = RandomMatrix<double>(k, n); Matrix<double> C(m, n); if (alg == CLASSICAL) { times[trial] = Time([&] { MatMul(A, B, C); }); } else if (alg == STRASSEN) { times[trial] = Time([&] { strassen::FastMatmul(A, B, C, 1); }); } else if (alg == STRASSEN_SCALED) { times[trial] = Time([&] { Matrix<double> A_roi = A; Matrix<double> B_roi = B; std::vector<double> r_roi, s_roi; Scaling(A_roi, B_roi, 3, r_roi, s_roi, OUTSIDE_INSIDE); strassen::FastMatmul(A, B, C, 1); PostProcessScaling(C, r_roi, s_roi); }); } } // Spit out the median time std::sort(times.begin(), times.end()); size_t ind = num_trials / 2; std::cout << " " << m << " " << k << " " << n << " " << " " << times[ind] << "; "; } int main(int argc, char **argv) { auto opts = GetOpts(argc, argv); int start = 1000; int end = 7500; int skip = 500; std::cout << "Classical" << std::endl; for (int N = start; N <= end; N += skip) { SingleBenchmark(N, N, N, CLASSICAL); } std::cout << std::endl; std::cout << "Strassen" << std::endl; for (int N = start; N <= end; N += skip) { SingleBenchmark(N, N, N, STRASSEN); } std::cout << std::endl; std::cout << "Strassen" << std::endl; for (int N = start; N <= end; N += skip) { SingleBenchmark(N, N, N, STRASSEN_SCALED); } std::cout << std::endl; return 0; } <commit_msg>Clean up code a little bit<commit_after>/** Copyright (c) 2014-2015, Sandia Corporation All rights reserved. This file is part of fast-matmul and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause. */ #include "common.hpp" #ifdef __INTEL_MKL__ # include "mkl.h" #endif #include "scaling.hpp" #include "strassen.hpp" #include <algorithm> #include <stdexcept> #include <vector> enum Algorithm { CLASSICAL = 0, STRASSEN, STRASSEN_SCALED, }; const int kNumScalingSteps = 5; const int kNumTrials = 5; // Run a single benchmark for multiplying m x k x n with num_steps of recursion. // To just call GEMM, set num_steps to zero. // The median of five trials is printed to std::cout. // If run_check is true, then it also void SingleBenchmark(int m, int k, int n, int alg) { // Run a set number of trials and pick the median time. int num_trials = 5; std::vector<double> times(num_trials); for (int trial = 0; trial < kNumTrials; ++trial) { Matrix<double> A = RandomMatrix<double>(m, k); Matrix<double> B = RandomMatrix<double>(k, n); Matrix<double> C(m, n); if (alg == CLASSICAL) { times[trial] = Time([&] { MatMul(A, B, C); }); } else if (alg == STRASSEN) { times[trial] = Time([&] { strassen::FastMatmul(A, B, C, 1); }); } else if (alg == STRASSEN_SCALED) { times[trial] = Time([&] { Matrix<double> A_roi = A; Matrix<double> B_roi = B; std::vector<double> r_roi, s_roi; Scaling(A_roi, B_roi, kNumScalingSteps, r_roi, s_roi, OUTSIDE_INSIDE); strassen::FastMatmul(A, B, C, 1); PostProcessScaling(C, r_roi, s_roi); }); } } // Spit out the median time std::sort(times.begin(), times.end()); size_t ind = num_trials / 2; std::cout << " " << m << " " << k << " " << n << " " << " " << times[ind] << "; "; } int main(int argc, char **argv) { auto opts = GetOpts(argc, argv); int start = 1000; int end = 7500; int skip = 500; std::cout << "Classical" << std::endl; for (int N = start; N <= end; N += skip) { SingleBenchmark(N, N, N, CLASSICAL); } std::cout << std::endl; std::cout << "Strassen" << std::endl; for (int N = start; N <= end; N += skip) { SingleBenchmark(N, N, N, STRASSEN); } std::cout << std::endl; std::cout << "Strassen" << std::endl; for (int N = start; N <= end; N += skip) { SingleBenchmark(N, N, N, STRASSEN_SCALED); } std::cout << std::endl; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: style.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2008-01-07 08:55:43 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SFXSTYLE_HXX #define _SFXSTYLE_HXX #ifndef INCLUDED_SVTDLLAPI_H #include "svtools/svtdllapi.h" #endif #ifndef _RSCSFX_HXX #include <rsc/rscsfx.hxx> #endif #ifndef _STRING_HXX //autogen #include <tools/string.hxx> #endif #ifndef _LIST_HXX //autogen #include <tools/list.hxx> #endif #ifndef _SFXHINT_HXX //autogen #include <svtools/hint.hxx> #endif #ifndef _SFXLSTNER_HXX //autogen #include <svtools/lstner.hxx> #endif #ifndef _SFXBRDCST_HXX //autogen #include <svtools/brdcst.hxx> #endif #ifndef _SFXPOOLITEM_HXX //autogen #include <svtools/poolitem.hxx> #endif #ifndef _SFX_STYLE_HRC #include <svtools/style.hrc> #endif class SfxItemSet; class SfxItemPool; class SfxStyleSheetBasePool; class SvStream; /*========================================================================= Jeder, der an Intanzen der Klassen SfxStyleSheetBasePool oder am SfxStyleSheetBase strukturelle �nderungen vornimmt, mu� diese �ber <SfxStyleSheetBasePool::GetBroadcaster()> broadcasten. Daf�r Gibt es die Klasse <SfxStyleSheetHint>, die eine Action-Id und einen Pointer auf einen <SfxStyleSheetBase> erh�lt. Die Actions sind: #define SFX_STYLESHEET_CREATED // neu #define SFX_STYLESHEET_MODIFIED // ver"andert #define SFX_STYLESHEET_CHANGED // ausgetauscht #define SFX_STYLESHEET_ERASED // gel"oscht Es machen bereits die folgenden Methoden von sich aus: SfxStyleSheetHint(SFX_STYLESHEET_MODIFIED) aus: SfxStyleSheetBase::SetName( const String& rName ) SfxStyleSheetBase::SetParent( const String& rName ) SfxStyleSheetBase::SetFollow( const String& rName ) SfxSimpleHint(SFX_HINT_DYING) aus: SfxStyleSheetBasePool::~SfxStyleSheetBasePool() SfxStyleSheetHint( SFX_STYLESHEET_CREATED, *p ) aus: SfxStyleSheetBasePool::Make( const String& rName, SfxStyleFamily eFam, USHORT mask, USHORT nPos) SfxStyleSheetHint( SFX_STYLESHEET_CHANGED, *pNew ) aus: SfxStyleSheetBasePool::Add( SfxStyleSheetBase& rSheet ) SfxStyleSheetHint( SFX_STYLESHEET_ERASED, *p ) aus: SfxStyleSheetBasePool::Erase( SfxStyleSheetBase* p ) SfxStyleSheetBasePool::Clear() =========================================================================*/ #define VIRTUAL510 virtual class SVT_DLLPUBLIC SfxStyleSheetBase { friend class SfxStyleSheetBasePool; protected: SfxStyleSheetBasePool& rPool; // zugehoeriger Pool SfxStyleFamily nFamily; // Familie UniString aName, aParent, aFollow; String aHelpFile; // Name der Hilfedatei SfxItemSet* pSet; // ItemSet USHORT nMask; // Flags ULONG nHelpId; // Hilfe-ID BOOL bMySet; // TRUE: Set loeschen im dtor SfxStyleSheetBase( const UniString&, SfxStyleSheetBasePool&, SfxStyleFamily eFam, USHORT mask ); SfxStyleSheetBase( const SfxStyleSheetBase& ); virtual ~SfxStyleSheetBase(); virtual void Load( SvStream&, USHORT ); virtual void Store( SvStream& ); public: TYPEINFO(); virtual const UniString& GetName() const; virtual BOOL SetName( const UniString& ); virtual const UniString& GetParent() const; virtual BOOL SetParent( const UniString& ); virtual const UniString& GetFollow() const; virtual BOOL SetFollow( const UniString& ); virtual BOOL HasFollowSupport() const; // Default TRUE virtual BOOL HasParentSupport() const; // Default TRUE virtual BOOL HasClearParentSupport() const; // Default FALSE virtual BOOL IsUsed() const; // Default TRUE // Default aus dem Itemset; entweder dem uebergebenen // oder aus dem per GetItemSet() zurueckgelieferten Set virtual UniString GetDescription(); virtual UniString GetDescription( SfxMapUnit eMetric ); SfxStyleSheetBasePool& GetPool() { return rPool; } SfxStyleFamily GetFamily() const { return nFamily; } USHORT GetMask() const { return nMask; } void SetMask( USHORT mask) { nMask = mask; } BOOL IsUserDefined() const { return BOOL( ( nMask & SFXSTYLEBIT_USERDEF) != 0 ); } virtual ULONG GetHelpId( String& rFile ); virtual void SetHelpId( const String& r, ULONG nId ); virtual SfxItemSet& GetItemSet(); virtual USHORT GetVersion() const; }; //========================================================================= DECLARE_LIST( SfxStyles, SfxStyleSheetBase* ) //========================================================================= class SVT_DLLPUBLIC SfxStyleSheetIterator /* [Beschreibung] Klasse zum Iterieren und Suchen auf einem SfxStyleSheetBasePool. */ { public: SfxStyleSheetIterator(SfxStyleSheetBasePool *pBase, SfxStyleFamily eFam, USHORT n=0xFFFF ); virtual USHORT GetSearchMask() const; virtual SfxStyleFamily GetSearchFamily() const; virtual USHORT Count(); virtual SfxStyleSheetBase *operator[](USHORT nIdx); virtual SfxStyleSheetBase* First(); virtual SfxStyleSheetBase* Next(); virtual SfxStyleSheetBase* Find(const UniString& rStr); virtual ~SfxStyleSheetIterator(); protected: SfxStyleSheetBasePool* pBasePool; SfxStyleFamily nSearchFamily; USHORT nMask; BOOL SearchUsed() const { return bSearchUsed; } private: USHORT GetPos(){return nAktPosition;} SVT_DLLPRIVATE BOOL IsTrivialSearch(); SVT_DLLPRIVATE BOOL DoesStyleMatch(SfxStyleSheetBase *pStyle); void* pImp; SfxStyleSheetBase* pAktStyle; USHORT nAktPosition; BOOL bSearchUsed; friend class SfxStyleSheetBasePool; }; //========================================================================= class SfxStyleSheetBasePool_Impl; class SVT_DLLPUBLIC SfxStyleSheetBasePool: public SfxBroadcaster { friend class SfxStyleSheetIterator; friend class SfxStyleSheetBase; SfxStyleSheetBasePool_Impl *pImp; private: SVT_DLLPRIVATE BOOL Load1_Impl( SvStream& ); SVT_DLLPRIVATE SfxStyleSheetIterator& GetIterator_Impl(); protected: String aAppName; SfxItemPool& rPool; SfxStyles aStyles; SfxStyleFamily nSearchFamily; USHORT nMask; SfxStyleSheetBase& Add( SfxStyleSheetBase& ); void ChangeParent( const UniString&, const UniString&, BOOL bVirtual = TRUE ); virtual SfxStyleSheetBase* Create( const UniString&, SfxStyleFamily, USHORT ); virtual SfxStyleSheetBase* Create( const SfxStyleSheetBase& ); public: SfxStyleSheetBasePool( SfxItemPool& ); SfxStyleSheetBasePool( const SfxStyleSheetBasePool& ); ~SfxStyleSheetBasePool(); static String GetStreamName(); const String& GetAppName() const { return aAppName; } SfxItemPool& GetPool(); const SfxItemPool& GetPool() const; virtual SfxStyleSheetIterator* CreateIterator(SfxStyleFamily, USHORT nMask); virtual USHORT Count(); virtual SfxStyleSheetBase* operator[](USHORT nIdx); virtual SfxStyleSheetBase& Make(const UniString&, SfxStyleFamily eFam, USHORT nMask = 0xffff , USHORT nPos = 0xffff); VIRTUAL510 void Replace( SfxStyleSheetBase& rSource, SfxStyleSheetBase& rTarget ); virtual SfxStyleSheetBase * Remove( SfxStyleSheetBase* ); virtual void Insert( SfxStyleSheetBase* ); virtual void Erase( SfxStyleSheetBase* ); virtual void Clear(); SfxStyleSheetBasePool& operator=( const SfxStyleSheetBasePool& ); SfxStyleSheetBasePool& operator+=( const SfxStyleSheetBasePool& ); SfxStyles& GetStyles() { return aStyles; } virtual SfxStyleSheetBase* First(); virtual SfxStyleSheetBase* Next(); virtual SfxStyleSheetBase* Find( const UniString&, SfxStyleFamily eFam, USHORT n=0xFFFF ); virtual BOOL SetParent(SfxStyleFamily eFam, const UniString &rStyle, const UniString &rParent); SfxStyleSheetBase* Find(const UniString& rStr) { return Find(rStr, nSearchFamily, nMask); } void SetSearchMask(SfxStyleFamily eFam, USHORT n=0xFFFF ); USHORT GetSearchMask() const; SfxStyleFamily GetSearchFamily() const { return nSearchFamily; } BOOL Load( SvStream& ); BOOL Store( SvStream&, BOOL bUsed = TRUE ); }; //========================================================================= class SVT_DLLPUBLIC SfxStyleSheet: public SfxStyleSheetBase, public SfxListener, public SfxBroadcaster { public: TYPEINFO(); SfxStyleSheet( const UniString&, SfxStyleSheetBasePool&, SfxStyleFamily, USHORT ); SfxStyleSheet( const SfxStyleSheet& ); virtual ~SfxStyleSheet(); virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType ); virtual BOOL SetParent( const UniString& ); }; //========================================================================= class SVT_DLLPUBLIC SfxStyleSheetPool: public SfxStyleSheetBasePool { protected: using SfxStyleSheetBasePool::Create; virtual SfxStyleSheetBase* Create(const UniString&, SfxStyleFamily, USHORT mask); virtual SfxStyleSheetBase* Create(const SfxStyleSheet &); public: SfxStyleSheetPool( SfxItemPool& ); // virtual BOOL CopyTo(SfxStyleSheetPool &rDest, const String &rSourceName); }; //========================================================================= #define SFX_STYLESHEET_CREATED 1 // neu #define SFX_STYLESHEET_MODIFIED 2 // ver"andert #define SFX_STYLESHEET_CHANGED 3 // gel"oscht und neu (ausgetauscht) #define SFX_STYLESHEET_ERASED 4 // gel"oscht #define SFX_STYLESHEET_INDESTRUCTION 5 // wird gerade entfernt #define SFX_STYLESHEETPOOL_CHANGES 1 // Aenderungen, die den Zustand // des Pools anedern, aber nicht // ueber die STYLESHEET Hints // verschickt werden sollen. //======================================================================== class SVT_DLLPUBLIC SfxStyleSheetPoolHint : public SfxHint { USHORT nHint; public: TYPEINFO(); SfxStyleSheetPoolHint(USHORT nArgHint) : nHint(nArgHint){} USHORT GetHint() const { return nHint; } }; //========================================================================= class SVT_DLLPUBLIC SfxStyleSheetHint: public SfxHint { SfxStyleSheetBase* pStyleSh; USHORT nHint; public: TYPEINFO(); SfxStyleSheetHint( USHORT ); SfxStyleSheetHint( USHORT, SfxStyleSheetBase& ); SfxStyleSheetBase* GetStyleSheet() const { return pStyleSh; } USHORT GetHint() const { return nHint; } }; class SVT_DLLPUBLIC SfxStyleSheetHintExtended: public SfxStyleSheetHint { String aName; public: TYPEINFO(); SfxStyleSheetHintExtended( USHORT, const String& rOld ); SfxStyleSheetHintExtended( USHORT, const String& rOld, SfxStyleSheetBase& ); const String& GetOldName() { return aName; } }; #endif <commit_msg>INTEGRATION: CWS impresstables2 (1.2.128); FILE MERGED 2008/01/30 13:27:43 cl 1.2.128.6: RESYNC: (1.2-1.3); FILE MERGED 2008/01/30 12:05:58 cl 1.2.128.5: #i68103# constructor hack to make implinheritancehelper merry 2008/01/30 11:52:32 cl 1.2.128.4: #i68103# export SfxUnoStyleSheet 2008/01/30 11:21:38 cl 1.2.128.3: #i68103# added XUnoTunnel to SfxUnoStyleSheet for safer conversion 2008/01/29 18:00:40 cl 1.2.128.2: #i68103# added SfxUnoStyleSheet to fix a dynamic_cast issue under linux 2007/07/26 21:32:35 cl 1.2.128.1: #i68103# reworked styles to use refcounting<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: style.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2008-03-12 13:08:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SFXSTYLE_HXX #define _SFXSTYLE_HXX #include <com/sun/star/style/XStyle.hpp> #include <com/sun/star/lang/XUnoTunnel.hpp> #include <rtl/ref.hxx> #include <vector> #include <comphelper/weak.hxx> #include <cppuhelper/implbase2.hxx> #ifndef INCLUDED_SVTDLLAPI_H #include "svtools/svtdllapi.h" #endif #ifndef _RSCSFX_HXX #include <rsc/rscsfx.hxx> #endif #ifndef _STRING_HXX //autogen #include <tools/string.hxx> #endif #ifndef _SFXHINT_HXX //autogen #include <svtools/hint.hxx> #endif #ifndef _SFXLSTNER_HXX //autogen #include <svtools/lstner.hxx> #endif #ifndef _SFXBRDCST_HXX //autogen #include <svtools/brdcst.hxx> #endif #ifndef _SFXPOOLITEM_HXX //autogen #include <svtools/poolitem.hxx> #endif #ifndef _SFX_STYLE_HRC #include <svtools/style.hrc> #endif class SfxItemSet; class SfxItemPool; class SfxStyleSheetBasePool; class SvStream; /* Everyone changing instances of SfxStyleSheetBasePool or SfxStyleSheetBase mußt broadcast this using <SfxStyleSheetBasePool::GetBroadcaster()> broadcasten. The class <SfxStyleSheetHint> is used for this, it contains an Action-Id and a pointer to the <SfxStyleSheetBase>. The actions are: #define SFX_STYLESHEET_CREATED // style is created #define SFX_STYLESHEET_MODIFIED // style is modified #define SFX_STYLESHEET_CHANGED // style is replaced #define SFX_STYLESHEET_ERASED // style is deleted The following methods already broadcast themself SfxStyleSheetHint(SFX_STYLESHEET_MODIFIED) from: SfxStyleSheetBase::SetName( const String& rName ) SfxStyleSheetBase::SetParent( const String& rName ) SfxStyleSheetBase::SetFollow( const String& rName ) SfxSimpleHint(SFX_HINT_DYING) from: SfxStyleSheetBasePool::~SfxStyleSheetBasePool() SfxStyleSheetHint( SFX_STYLESHEET_CREATED, *p ) from: SfxStyleSheetBasePool::Make( const String& rName, SfxStyleFamily eFam, USHORT mask, USHORT nPos) SfxStyleSheetHint( SFX_STYLESHEET_CHANGED, *pNew ) from: SfxStyleSheetBasePool::Add( SfxStyleSheetBase& rSheet ) SfxStyleSheetHint( SFX_STYLESHEET_ERASED, *p ) from: SfxStyleSheetBasePool::Erase( SfxStyleSheetBase* p ) SfxStyleSheetBasePool::Clear() */ #define VIRTUAL510 virtual class SVT_DLLPUBLIC SfxStyleSheetBase : public comphelper::OWeakTypeObject { friend class SfxStyleSheetBasePool; protected: SfxStyleSheetBasePool& rPool; // zugehoeriger Pool SfxStyleFamily nFamily; // Familie UniString aName, aParent, aFollow; rtl::OUString maDisplayName; String aHelpFile; // Name der Hilfedatei SfxItemSet* pSet; // ItemSet USHORT nMask; // Flags ULONG nHelpId; // Hilfe-ID BOOL bMySet; // TRUE: Set loeschen im dtor SfxStyleSheetBase(); // do not use! SfxStyleSheetBase( const UniString&, SfxStyleSheetBasePool&, SfxStyleFamily eFam, USHORT mask ); SfxStyleSheetBase( const SfxStyleSheetBase& ); virtual ~SfxStyleSheetBase(); virtual void Load( SvStream&, USHORT ); virtual void Store( SvStream& ); public: TYPEINFO(); // returns the internal name of this style virtual const UniString& GetName() const; // sets the internal name of this style virtual BOOL SetName( const UniString& ); /** returns the display name of this style, it is used at the user interface. If the display name is empty, this method returns the internal name. */ virtual rtl::OUString GetDisplayName() const; // sets the display name of this style virtual void SetDisplayName( const rtl::OUString& ); virtual const UniString& GetParent() const; virtual BOOL SetParent( const UniString& ); virtual const UniString& GetFollow() const; virtual BOOL SetFollow( const UniString& ); virtual BOOL HasFollowSupport() const; // Default TRUE virtual BOOL HasParentSupport() const; // Default TRUE virtual BOOL HasClearParentSupport() const; // Default FALSE virtual BOOL IsUsed() const; // Default TRUE // Default aus dem Itemset; entweder dem uebergebenen // oder aus dem per GetItemSet() zurueckgelieferten Set virtual UniString GetDescription(); virtual UniString GetDescription( SfxMapUnit eMetric ); SfxStyleSheetBasePool& GetPool() { return rPool; } SfxStyleFamily GetFamily() const { return nFamily; } USHORT GetMask() const { return nMask; } void SetMask( USHORT mask) { nMask = mask; } BOOL IsUserDefined() const { return BOOL( ( nMask & SFXSTYLEBIT_USERDEF) != 0 ); } virtual ULONG GetHelpId( String& rFile ); virtual void SetHelpId( const String& r, ULONG nId ); virtual SfxItemSet& GetItemSet(); virtual USHORT GetVersion() const; }; //========================================================================= typedef std::vector< rtl::Reference< SfxStyleSheetBase > > SfxStyles; //========================================================================= class SVT_DLLPUBLIC SfxStyleSheetIterator /* [Beschreibung] Klasse zum Iterieren und Suchen auf einem SfxStyleSheetBasePool. */ { public: SfxStyleSheetIterator(SfxStyleSheetBasePool *pBase, SfxStyleFamily eFam, USHORT n=0xFFFF ); virtual USHORT GetSearchMask() const; virtual SfxStyleFamily GetSearchFamily() const; virtual USHORT Count(); virtual SfxStyleSheetBase *operator[](USHORT nIdx); virtual SfxStyleSheetBase* First(); virtual SfxStyleSheetBase* Next(); virtual SfxStyleSheetBase* Find(const UniString& rStr); virtual ~SfxStyleSheetIterator(); protected: SfxStyleSheetBasePool* pBasePool; SfxStyleFamily nSearchFamily; USHORT nMask; BOOL SearchUsed() const { return bSearchUsed; } private: USHORT GetPos(){return nAktPosition;} SVT_DLLPRIVATE BOOL IsTrivialSearch(); SVT_DLLPRIVATE BOOL DoesStyleMatch(SfxStyleSheetBase *pStyle); void* pImp; SfxStyleSheetBase* pAktStyle; USHORT nAktPosition; BOOL bSearchUsed; friend class SfxStyleSheetBasePool; }; //========================================================================= class SfxStyleSheetBasePool_Impl; class SVT_DLLPUBLIC SfxStyleSheetBasePool: public SfxBroadcaster, public comphelper::OWeakTypeObject { friend class SfxStyleSheetIterator; friend class SfxStyleSheetBase; SfxStyleSheetBasePool_Impl *pImp; private: SVT_DLLPRIVATE BOOL Load1_Impl( SvStream& ); SVT_DLLPRIVATE SfxStyleSheetIterator& GetIterator_Impl(); protected: String aAppName; SfxItemPool& rPool; SfxStyles aStyles; SfxStyleFamily nSearchFamily; USHORT nMask; SfxStyleSheetBase& Add( SfxStyleSheetBase& ); void ChangeParent( const UniString&, const UniString&, BOOL bVirtual = TRUE ); virtual SfxStyleSheetBase* Create( const UniString&, SfxStyleFamily, USHORT ); virtual SfxStyleSheetBase* Create( const SfxStyleSheetBase& ); ~SfxStyleSheetBasePool(); public: SfxStyleSheetBasePool( SfxItemPool& ); SfxStyleSheetBasePool( const SfxStyleSheetBasePool& ); static String GetStreamName(); const String& GetAppName() const { return aAppName; } SfxItemPool& GetPool(); const SfxItemPool& GetPool() const; virtual SfxStyleSheetIterator* CreateIterator(SfxStyleFamily, USHORT nMask); virtual USHORT Count(); virtual SfxStyleSheetBase* operator[](USHORT nIdx); virtual SfxStyleSheetBase& Make(const UniString&, SfxStyleFamily eFam, USHORT nMask = 0xffff , USHORT nPos = 0xffff); virtual void Replace( SfxStyleSheetBase& rSource, SfxStyleSheetBase& rTarget ); virtual void Remove( SfxStyleSheetBase* ); virtual void Insert( SfxStyleSheetBase* ); virtual void Clear(); SfxStyleSheetBasePool& operator=( const SfxStyleSheetBasePool& ); SfxStyleSheetBasePool& operator+=( const SfxStyleSheetBasePool& ); const SfxStyles& GetStyles(); virtual SfxStyleSheetBase* First(); virtual SfxStyleSheetBase* Next(); virtual SfxStyleSheetBase* Find( const UniString&, SfxStyleFamily eFam, USHORT n=0xFFFF ); virtual BOOL SetParent(SfxStyleFamily eFam, const UniString &rStyle, const UniString &rParent); SfxStyleSheetBase* Find(const UniString& rStr) { return Find(rStr, nSearchFamily, nMask); } void SetSearchMask(SfxStyleFamily eFam, USHORT n=0xFFFF ); USHORT GetSearchMask() const; SfxStyleFamily GetSearchFamily() const { return nSearchFamily; } BOOL Load( SvStream& ); BOOL Store( SvStream&, BOOL bUsed = TRUE ); }; //========================================================================= class SVT_DLLPUBLIC SfxStyleSheet: public SfxStyleSheetBase, public SfxListener, public SfxBroadcaster { public: TYPEINFO(); SfxStyleSheet( const UniString&, const SfxStyleSheetBasePool&, SfxStyleFamily, USHORT ); SfxStyleSheet( const SfxStyleSheet& ); virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType ); virtual BOOL SetParent( const UniString& ); protected: SfxStyleSheet(); // do not use! virtual ~SfxStyleSheet(); }; //========================================================================= class SVT_DLLPUBLIC SfxStyleSheetPool: public SfxStyleSheetBasePool { protected: using SfxStyleSheetBasePool::Create; virtual SfxStyleSheetBase* Create(const UniString&, SfxStyleFamily, USHORT mask); virtual SfxStyleSheetBase* Create(const SfxStyleSheet &); public: SfxStyleSheetPool( SfxItemPool const& ); // virtual BOOL CopyTo(SfxStyleSheetPool &rDest, const String &rSourceName); }; //========================================================================= #define SFX_STYLESHEET_CREATED 1 // neu #define SFX_STYLESHEET_MODIFIED 2 // ver"andert #define SFX_STYLESHEET_CHANGED 3 // gel"oscht und neu (ausgetauscht) #define SFX_STYLESHEET_ERASED 4 // gel"oscht #define SFX_STYLESHEET_INDESTRUCTION 5 // wird gerade entfernt #define SFX_STYLESHEETPOOL_CHANGES 1 // Aenderungen, die den Zustand // des Pools anedern, aber nicht // ueber die STYLESHEET Hints // verschickt werden sollen. //======================================================================== class SVT_DLLPUBLIC SfxStyleSheetPoolHint : public SfxHint { USHORT nHint; public: TYPEINFO(); SfxStyleSheetPoolHint(USHORT nArgHint) : nHint(nArgHint){} USHORT GetHint() const { return nHint; } }; //========================================================================= class SVT_DLLPUBLIC SfxStyleSheetHint: public SfxHint { SfxStyleSheetBase* pStyleSh; USHORT nHint; public: TYPEINFO(); SfxStyleSheetHint( USHORT ); SfxStyleSheetHint( USHORT, SfxStyleSheetBase& ); SfxStyleSheetBase* GetStyleSheet() const { return pStyleSh; } USHORT GetHint() const { return nHint; } }; class SVT_DLLPUBLIC SfxStyleSheetHintExtended: public SfxStyleSheetHint { String aName; public: TYPEINFO(); SfxStyleSheetHintExtended( USHORT, const String& rOld ); SfxStyleSheetHintExtended( USHORT, const String& rOld, SfxStyleSheetBase& ); const String& GetOldName() { return aName; } }; class SVT_DLLPUBLIC SfxUnoStyleSheet : public ::cppu::ImplInheritanceHelper2< SfxStyleSheet, ::com::sun::star::style::XStyle, ::com::sun::star::lang::XUnoTunnel > { public: SfxUnoStyleSheet( const UniString& _rName, const SfxStyleSheetBasePool& _rPool, SfxStyleFamily _eFamily, USHORT _nMaske ); SfxUnoStyleSheet( const SfxStyleSheet& _rSheet ); static SfxUnoStyleSheet* getUnoStyleSheet( const ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle >& xStyle ); // XUnoTunnel virtual ::sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< ::sal_Int8 >& aIdentifier ) throw (::com::sun::star::uno::RuntimeException); private: SfxUnoStyleSheet(); // not implemented static const ::com::sun::star::uno::Sequence< ::sal_Int8 >& getIdentifier(); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: imap3.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:59:02 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "imap.hxx" #include <tools/debug.hxx> /****************************************************************************** |* |* Ctor |* \******************************************************************************/ IMapCompat::IMapCompat( SvStream& rStm, const USHORT nStreamMode ) : pRWStm ( &rStm ), nStmMode ( nStreamMode ) { DBG_ASSERT( nStreamMode == STREAM_READ || nStreamMode == STREAM_WRITE, "Wrong Mode!" ); if ( !pRWStm->GetError() ) { if ( nStmMode == STREAM_WRITE ) { nCompatPos = pRWStm->Tell(); pRWStm->SeekRel( 4 ); nTotalSize = nCompatPos + 4; } else { UINT32 nTotalSizeTmp; *pRWStm >> nTotalSizeTmp; nTotalSize = nTotalSizeTmp; nCompatPos = pRWStm->Tell(); } } } /****************************************************************************** |* |* Dtor |* \******************************************************************************/ IMapCompat::~IMapCompat() { if ( !pRWStm->GetError() ) { if ( nStmMode == STREAM_WRITE ) { const ULONG nEndPos = pRWStm->Tell(); pRWStm->Seek( nCompatPos ); *pRWStm << (UINT32) ( nEndPos - nTotalSize ); pRWStm->Seek( nEndPos ); } else { const ULONG nReadSize = pRWStm->Tell() - nCompatPos; if ( nTotalSize > nReadSize ) pRWStm->SeekRel( nTotalSize - nReadSize ); } } } <commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1110); FILE MERGED 2005/09/05 14:53:35 rt 1.1.1.1.1110.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: imap3.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 16:19:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "imap.hxx" #include <tools/debug.hxx> /****************************************************************************** |* |* Ctor |* \******************************************************************************/ IMapCompat::IMapCompat( SvStream& rStm, const USHORT nStreamMode ) : pRWStm ( &rStm ), nStmMode ( nStreamMode ) { DBG_ASSERT( nStreamMode == STREAM_READ || nStreamMode == STREAM_WRITE, "Wrong Mode!" ); if ( !pRWStm->GetError() ) { if ( nStmMode == STREAM_WRITE ) { nCompatPos = pRWStm->Tell(); pRWStm->SeekRel( 4 ); nTotalSize = nCompatPos + 4; } else { UINT32 nTotalSizeTmp; *pRWStm >> nTotalSizeTmp; nTotalSize = nTotalSizeTmp; nCompatPos = pRWStm->Tell(); } } } /****************************************************************************** |* |* Dtor |* \******************************************************************************/ IMapCompat::~IMapCompat() { if ( !pRWStm->GetError() ) { if ( nStmMode == STREAM_WRITE ) { const ULONG nEndPos = pRWStm->Tell(); pRWStm->Seek( nCompatPos ); *pRWStm << (UINT32) ( nEndPos - nTotalSize ); pRWStm->Seek( nEndPos ); } else { const ULONG nReadSize = pRWStm->Tell() - nCompatPos; if ( nTotalSize > nReadSize ) pRWStm->SeekRel( nTotalSize - nReadSize ); } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: contwnd.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: hr $ $Date: 2007-06-27 16:56:17 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifndef _XOUTX_HXX //autogen #include <svx/xoutx.hxx> #endif #include <xoutbmp.hxx> #include <svx/dialogs.hrc> #include <svx/svxids.hrc> #include <contdlg.hrc> #include <contwnd.hxx> #include <svx/svdpage.hxx> #include <svx/svdopath.hxx> #include <svx/xfltrit.hxx> #ifndef _SVX_FILLITEM_HXX //autogen #include <svx/xfillit.hxx> #endif #ifndef _BGFX_POLYGON_B2DPOLYGON_HXX #include <basegfx/polygon/b2dpolygon.hxx> #endif #ifndef _BGFX_POLYPOLYGON_B2DPOLYGONTOOLS_HXX #include <basegfx/polygon/b2dpolypolygontools.hxx> #endif // #i75482# #ifndef _SDRPAINTWINDOW_HXX #include "sdrpaintwindow.hxx" #endif #ifdef MAC #define TRANSCOL Color( COL_LIGHTGRAY ) #else #define TRANSCOL Color( COL_WHITE ) #endif /************************************************************************* |* |* |* \************************************************************************/ ContourWindow::ContourWindow( Window* pParent, const ResId& rResId ) : GraphCtrl ( pParent, rResId ), aWorkRect ( 0, 0, 0, 0 ), bPipetteMode ( FALSE ), bWorkplaceMode ( FALSE ), bClickValid ( FALSE ) { SetWinStyle( WB_SDRMODE ); } /************************************************************************* |* |* |* \************************************************************************/ ContourWindow::~ContourWindow() { } /************************************************************************* |* |* |* \************************************************************************/ void ContourWindow::SetPolyPolygon( const PolyPolygon& rPolyPoly ) { SdrPage* pPage = (SdrPage*) pModel->GetPage( 0 ); const USHORT nPolyCount = rPolyPoly.Count(); // zuerst alle Zeichenobjekte loeschen aPolyPoly = rPolyPoly; // #117412# // To avoid to have destroyed objects which are still selected, it is necessary to deselect // them first (!) pView->UnmarkAllObj(); pPage->Clear(); for ( USHORT i = 0; i < nPolyCount; i++ ) { basegfx::B2DPolyPolygon aPolyPolygon; aPolyPolygon.append(aPolyPoly[ i ].getB2DPolygon()); SdrPathObj* pPathObj = new SdrPathObj( OBJ_PATHFILL, aPolyPolygon ); if ( pPathObj ) { SfxItemSet aSet( pModel->GetItemPool() ); aSet.Put( XFillStyleItem( XFILL_SOLID ) ); aSet.Put( XFillColorItem( String(), TRANSCOL ) ); aSet.Put( XFillTransparenceItem( 50 ) ); //pPathObj->SetItemSetAndBroadcast(aSet); pPathObj->SetMergedItemSetAndBroadcast(aSet); pPage->InsertObject( pPathObj ); } } if ( nPolyCount ) { pView->MarkAll(); pView->CombineMarkedObjects( sal_False ); } pModel->SetChanged( sal_False ); } /************************************************************************* |* |* |* \************************************************************************/ const PolyPolygon& ContourWindow::GetPolyPolygon() { if ( pModel->IsChanged() ) { SdrPage* pPage = (SdrPage*) pModel->GetPage( 0 ); aPolyPoly = PolyPolygon(); if ( pPage && pPage->GetObjCount() ) { SdrPathObj* pPathObj = (SdrPathObj*)pPage->GetObj(0L); const basegfx::B2DPolyPolygon aB2DPolyPolygon(basegfx::tools::adaptiveSubdivideByAngle(pPathObj->GetPathPoly())); aPolyPoly = PolyPolygon(aB2DPolyPolygon); } pModel->SetChanged( sal_False ); } return aPolyPoly; } /************************************************************************* |* |* |* \************************************************************************/ void ContourWindow::InitSdrModel() { GraphCtrl::InitSdrModel(); SfxItemSet aSet( pModel->GetItemPool() ); aSet.Put( XFillColorItem( String(), TRANSCOL ) ); aSet.Put( XFillTransparenceItem( 50 ) ); pView->SetAttributes( aSet ); pView->SetFrameDragSingles( TRUE ); } /************************************************************************* |* |* |* \************************************************************************/ void ContourWindow::SdrObjCreated( const SdrObject& ) { pView->MarkAll(); pView->CombineMarkedObjects( sal_False ); } /************************************************************************* |* |* |* \************************************************************************/ BOOL ContourWindow::IsContourChanged() const { SdrPage* pPage = (SdrPage*) pModel->GetPage( 0 ); BOOL bRet = FALSE; if ( pPage && pPage->GetObjCount() ) bRet = ( (SdrPathObj*) pPage->GetObj( 0 ) )->GetPathPoly().count() && pModel->IsChanged(); return bRet; } /************************************************************************* |* |* |* \************************************************************************/ void ContourWindow::MouseButtonDown( const MouseEvent& rMEvt ) { if ( bWorkplaceMode ) { const Point aLogPt( PixelToLogic( rMEvt.GetPosPixel() ) ); SetPolyPolygon( PolyPolygon() ); aWorkRect = Rectangle( aLogPt, aLogPt ); Paint( Rectangle( Point(), GetGraphicSize() ) ); SetEditMode( TRUE ); } if ( !bPipetteMode ) GraphCtrl::MouseButtonDown( rMEvt ); } /************************************************************************* |* |* |* \************************************************************************/ void ContourWindow::MouseMove( const MouseEvent& rMEvt ) { bClickValid = FALSE; if ( bPipetteMode ) { const Point aLogPt( PixelToLogic( rMEvt.GetPosPixel() ) ); aPipetteColor = GetPixel( aLogPt ); Control::MouseMove( rMEvt ); if ( aPipetteLink.IsSet() && Rectangle( Point(), GetGraphicSize() ).IsInside( aLogPt ) ) { SetPointer( POINTER_REFHAND ); aPipetteLink.Call( this ); } } else GraphCtrl::MouseMove( rMEvt ); } /************************************************************************* |* |* |* \************************************************************************/ void ContourWindow::MouseButtonUp(const MouseEvent& rMEvt) { Point aTmpPoint; const Rectangle aGraphRect( aTmpPoint, GetGraphicSize() ); const Point aLogPt( PixelToLogic( rMEvt.GetPosPixel() ) ); bClickValid = aGraphRect.IsInside( aLogPt ); ReleaseMouse(); if ( bPipetteMode ) { Control::MouseButtonUp( rMEvt ); if ( aPipetteClickLink.IsSet() ) aPipetteClickLink.Call( this ); } else if ( bWorkplaceMode ) { GraphCtrl::MouseButtonUp( rMEvt ); aWorkRect.Right() = aLogPt.X(); aWorkRect.Bottom() = aLogPt.Y(); aWorkRect.Intersection( aGraphRect ); aWorkRect.Justify(); if ( aWorkRect.Left() != aWorkRect.Right() && aWorkRect.Top() != aWorkRect.Bottom() ) { PolyPolygon _aPolyPoly( GetPolyPolygon() ); _aPolyPoly.Clip( aWorkRect ); SetPolyPolygon( _aPolyPoly ); pView->SetWorkArea( aWorkRect ); } else pView->SetWorkArea( aGraphRect ); Invalidate( aGraphRect ); if ( aWorkplaceClickLink.IsSet() ) aWorkplaceClickLink.Call( this ); } else GraphCtrl::MouseButtonUp( rMEvt ); } /************************************************************************* |* |* |* \************************************************************************/ void ContourWindow::Paint( const Rectangle& rRect ) { // #i75482# // encapsulate the redraw using Begin/End and use the returned // data to get the target output device (e.g. when pre-rendering) SdrPaintWindow* pPaintWindow = pView->BeginCompleteRedraw(this); OutputDevice& rTarget = pPaintWindow->GetTargetOutputDevice(); const Graphic& rGraphic = GetGraphic(); const Color& rOldLineColor = GetLineColor(); const Color& rOldFillColor = GetFillColor(); rTarget.SetLineColor( Color( COL_BLACK ) ); rTarget.SetFillColor( Color( COL_WHITE ) ); rTarget.DrawRect( Rectangle( Point(), GetGraphicSize() ) ); rTarget.SetLineColor( rOldLineColor ); rTarget.SetFillColor( rOldFillColor ); if ( rGraphic.GetType() != GRAPHIC_NONE ) rGraphic.Draw( &rTarget, Point(), GetGraphicSize() ); if ( aWorkRect.Left() != aWorkRect.Right() && aWorkRect.Top() != aWorkRect.Bottom() ) { PolyPolygon _aPolyPoly( 2, 2 ); const Color aOldFillColor( GetFillColor() ); _aPolyPoly.Insert( Rectangle( Point(), GetGraphicSize() ) ); _aPolyPoly.Insert( aWorkRect ); rTarget.SetFillColor( COL_LIGHTRED ); rTarget.DrawTransparent( _aPolyPoly, 50 ); rTarget.SetFillColor( aOldFillColor ); } // #i75482# const Region aRepaintRegion(rRect); pView->DoCompleteRedraw(*pPaintWindow, aRepaintRegion); pView->EndCompleteRedraw(*pPaintWindow); } // eof <commit_msg>INTEGRATION: CWS os98 (1.11.120); FILE MERGED 2007/06/18 14:24:08 os 1.11.120.1: #i78461# MAC code removed<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: contwnd.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: ihi $ $Date: 2007-07-12 10:54:09 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifndef _XOUTX_HXX //autogen #include <svx/xoutx.hxx> #endif #include <xoutbmp.hxx> #include <svx/dialogs.hrc> #include <svx/svxids.hrc> #include <contdlg.hrc> #include <contwnd.hxx> #include <svx/svdpage.hxx> #include <svx/svdopath.hxx> #include <svx/xfltrit.hxx> #ifndef _SVX_FILLITEM_HXX //autogen #include <svx/xfillit.hxx> #endif #ifndef _BGFX_POLYGON_B2DPOLYGON_HXX #include <basegfx/polygon/b2dpolygon.hxx> #endif #ifndef _BGFX_POLYPOLYGON_B2DPOLYGONTOOLS_HXX #include <basegfx/polygon/b2dpolypolygontools.hxx> #endif // #i75482# #ifndef _SDRPAINTWINDOW_HXX #include "sdrpaintwindow.hxx" #endif #define TRANSCOL Color( COL_WHITE ) /************************************************************************* |* |* |* \************************************************************************/ ContourWindow::ContourWindow( Window* pParent, const ResId& rResId ) : GraphCtrl ( pParent, rResId ), aWorkRect ( 0, 0, 0, 0 ), bPipetteMode ( FALSE ), bWorkplaceMode ( FALSE ), bClickValid ( FALSE ) { SetWinStyle( WB_SDRMODE ); } /************************************************************************* |* |* |* \************************************************************************/ ContourWindow::~ContourWindow() { } /************************************************************************* |* |* |* \************************************************************************/ void ContourWindow::SetPolyPolygon( const PolyPolygon& rPolyPoly ) { SdrPage* pPage = (SdrPage*) pModel->GetPage( 0 ); const USHORT nPolyCount = rPolyPoly.Count(); // zuerst alle Zeichenobjekte loeschen aPolyPoly = rPolyPoly; // #117412# // To avoid to have destroyed objects which are still selected, it is necessary to deselect // them first (!) pView->UnmarkAllObj(); pPage->Clear(); for ( USHORT i = 0; i < nPolyCount; i++ ) { basegfx::B2DPolyPolygon aPolyPolygon; aPolyPolygon.append(aPolyPoly[ i ].getB2DPolygon()); SdrPathObj* pPathObj = new SdrPathObj( OBJ_PATHFILL, aPolyPolygon ); if ( pPathObj ) { SfxItemSet aSet( pModel->GetItemPool() ); aSet.Put( XFillStyleItem( XFILL_SOLID ) ); aSet.Put( XFillColorItem( String(), TRANSCOL ) ); aSet.Put( XFillTransparenceItem( 50 ) ); //pPathObj->SetItemSetAndBroadcast(aSet); pPathObj->SetMergedItemSetAndBroadcast(aSet); pPage->InsertObject( pPathObj ); } } if ( nPolyCount ) { pView->MarkAll(); pView->CombineMarkedObjects( sal_False ); } pModel->SetChanged( sal_False ); } /************************************************************************* |* |* |* \************************************************************************/ const PolyPolygon& ContourWindow::GetPolyPolygon() { if ( pModel->IsChanged() ) { SdrPage* pPage = (SdrPage*) pModel->GetPage( 0 ); aPolyPoly = PolyPolygon(); if ( pPage && pPage->GetObjCount() ) { SdrPathObj* pPathObj = (SdrPathObj*)pPage->GetObj(0L); const basegfx::B2DPolyPolygon aB2DPolyPolygon(basegfx::tools::adaptiveSubdivideByAngle(pPathObj->GetPathPoly())); aPolyPoly = PolyPolygon(aB2DPolyPolygon); } pModel->SetChanged( sal_False ); } return aPolyPoly; } /************************************************************************* |* |* |* \************************************************************************/ void ContourWindow::InitSdrModel() { GraphCtrl::InitSdrModel(); SfxItemSet aSet( pModel->GetItemPool() ); aSet.Put( XFillColorItem( String(), TRANSCOL ) ); aSet.Put( XFillTransparenceItem( 50 ) ); pView->SetAttributes( aSet ); pView->SetFrameDragSingles( TRUE ); } /************************************************************************* |* |* |* \************************************************************************/ void ContourWindow::SdrObjCreated( const SdrObject& ) { pView->MarkAll(); pView->CombineMarkedObjects( sal_False ); } /************************************************************************* |* |* |* \************************************************************************/ BOOL ContourWindow::IsContourChanged() const { SdrPage* pPage = (SdrPage*) pModel->GetPage( 0 ); BOOL bRet = FALSE; if ( pPage && pPage->GetObjCount() ) bRet = ( (SdrPathObj*) pPage->GetObj( 0 ) )->GetPathPoly().count() && pModel->IsChanged(); return bRet; } /************************************************************************* |* |* |* \************************************************************************/ void ContourWindow::MouseButtonDown( const MouseEvent& rMEvt ) { if ( bWorkplaceMode ) { const Point aLogPt( PixelToLogic( rMEvt.GetPosPixel() ) ); SetPolyPolygon( PolyPolygon() ); aWorkRect = Rectangle( aLogPt, aLogPt ); Paint( Rectangle( Point(), GetGraphicSize() ) ); SetEditMode( TRUE ); } if ( !bPipetteMode ) GraphCtrl::MouseButtonDown( rMEvt ); } /************************************************************************* |* |* |* \************************************************************************/ void ContourWindow::MouseMove( const MouseEvent& rMEvt ) { bClickValid = FALSE; if ( bPipetteMode ) { const Point aLogPt( PixelToLogic( rMEvt.GetPosPixel() ) ); aPipetteColor = GetPixel( aLogPt ); Control::MouseMove( rMEvt ); if ( aPipetteLink.IsSet() && Rectangle( Point(), GetGraphicSize() ).IsInside( aLogPt ) ) { SetPointer( POINTER_REFHAND ); aPipetteLink.Call( this ); } } else GraphCtrl::MouseMove( rMEvt ); } /************************************************************************* |* |* |* \************************************************************************/ void ContourWindow::MouseButtonUp(const MouseEvent& rMEvt) { Point aTmpPoint; const Rectangle aGraphRect( aTmpPoint, GetGraphicSize() ); const Point aLogPt( PixelToLogic( rMEvt.GetPosPixel() ) ); bClickValid = aGraphRect.IsInside( aLogPt ); ReleaseMouse(); if ( bPipetteMode ) { Control::MouseButtonUp( rMEvt ); if ( aPipetteClickLink.IsSet() ) aPipetteClickLink.Call( this ); } else if ( bWorkplaceMode ) { GraphCtrl::MouseButtonUp( rMEvt ); aWorkRect.Right() = aLogPt.X(); aWorkRect.Bottom() = aLogPt.Y(); aWorkRect.Intersection( aGraphRect ); aWorkRect.Justify(); if ( aWorkRect.Left() != aWorkRect.Right() && aWorkRect.Top() != aWorkRect.Bottom() ) { PolyPolygon _aPolyPoly( GetPolyPolygon() ); _aPolyPoly.Clip( aWorkRect ); SetPolyPolygon( _aPolyPoly ); pView->SetWorkArea( aWorkRect ); } else pView->SetWorkArea( aGraphRect ); Invalidate( aGraphRect ); if ( aWorkplaceClickLink.IsSet() ) aWorkplaceClickLink.Call( this ); } else GraphCtrl::MouseButtonUp( rMEvt ); } /************************************************************************* |* |* |* \************************************************************************/ void ContourWindow::Paint( const Rectangle& rRect ) { // #i75482# // encapsulate the redraw using Begin/End and use the returned // data to get the target output device (e.g. when pre-rendering) SdrPaintWindow* pPaintWindow = pView->BeginCompleteRedraw(this); OutputDevice& rTarget = pPaintWindow->GetTargetOutputDevice(); const Graphic& rGraphic = GetGraphic(); const Color& rOldLineColor = GetLineColor(); const Color& rOldFillColor = GetFillColor(); rTarget.SetLineColor( Color( COL_BLACK ) ); rTarget.SetFillColor( Color( COL_WHITE ) ); rTarget.DrawRect( Rectangle( Point(), GetGraphicSize() ) ); rTarget.SetLineColor( rOldLineColor ); rTarget.SetFillColor( rOldFillColor ); if ( rGraphic.GetType() != GRAPHIC_NONE ) rGraphic.Draw( &rTarget, Point(), GetGraphicSize() ); if ( aWorkRect.Left() != aWorkRect.Right() && aWorkRect.Top() != aWorkRect.Bottom() ) { PolyPolygon _aPolyPoly( 2, 2 ); const Color aOldFillColor( GetFillColor() ); _aPolyPoly.Insert( Rectangle( Point(), GetGraphicSize() ) ); _aPolyPoly.Insert( aWorkRect ); rTarget.SetFillColor( COL_LIGHTRED ); rTarget.DrawTransparent( _aPolyPoly, 50 ); rTarget.SetFillColor( aOldFillColor ); } // #i75482# const Region aRepaintRegion(rRect); pView->DoCompleteRedraw(*pPaintWindow, aRepaintRegion); pView->EndCompleteRedraw(*pPaintWindow); } // eof <|endoftext|>
<commit_before><commit_msg>coverity#1251167 Logically dead code<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: flyfrm.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2004-05-17 16:15:11 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _FLYFRM_HXX #define _FLYFRM_HXX #include "layfrm.hxx" class SwPageFrm; class SwFlyFrmFmt; class SwFmtFrmSize; struct SwCrsrMoveState; class SwBorderAttrs; class SwVirtFlyDrawObj; class SwSpzFrmFmts; class SwAttrSetChg; class PolyPolygon; // OD 01.08.2003 #110978# namespace objectpositioning { class SwAnchoredObjectPosition; } #include <orntenum.hxx> //Sucht ausgehend von pOldAnch einen Anker fuer Absatzgebundene Rahmen. //Wird beim Draggen von Absatzgebundenen Objekten zur Ankeranzeige sowie //fuer Ankerwechsel benoetigt. //implementiert in layout/flycnt.cxx const SwCntntFrm *FindAnchor( const SwFrm *pOldAnch, const Point &rNew, const BOOL bBody = FALSE ); // berechnet das Rechteck, in dem das Objekt bewegt bzw. resized werden darf BOOL CalcClipRect( const SdrObject *pSdrObj, SwRect &rRect, BOOL bMove = TRUE ); //allg. Basisklasse fuer alle Freifliegenden Rahmen class SwFlyFrm : public SwLayoutFrm { //darf Locken. Definiert in frmtool.cxx friend void AppendObjs ( const SwSpzFrmFmts *, ULONG, SwFrm *, SwPageFrm * ); friend void AppendAllObjs( const SwSpzFrmFmts * ); friend void Notify( SwFlyFrm *, SwPageFrm *pOld, const SwRect &rOld, const SwRect* pOldPrt ); //darf die Pos berechnen (lassen) friend void lcl_MakeFlyPosition( SwFlyFrm *pFly ); // OD 01.08.2003 #110978# - access for calculation of position friend class objectpositioning::SwAnchoredObjectPosition; void InitDrawObj( BOOL bNotify ); //Wird von den CToren gerufen. void FinitDrawObj(); //Wird vom CTor gerufen. void _UpdateAttr( SfxPoolItem*, SfxPoolItem*, BYTE &, SwAttrSetChg *pa = 0, SwAttrSetChg *pb = 0 ); protected: SwVirtFlyDrawObj *pDrawObj; // das Drawingobject zum Fly SwFrm *pAnchor; // An diesem LayoutFrm haengt der Frm, kann 0 sein SwFlyFrm *pPrevLink, // Vorgaenger/Nachfolger fuer Verkettung mit *pNextLink; // Textfluss Point aRelPos; //Die Relative Position zum Master private: BOOL bLocked :1; //Cntnt-gebundene Flys muessen derart blockiert werden //koennen, dass sie nicht Formatiert werden; :MakeAll //returnt dann sofort. Dies ist bei Seitenwechseln //waehrend der Formatierung notwendig. //Auch wahrend des RootCTors ist dies notwendig da //sonst der Anker formatiert wird obwohl die Root noch //nicht korrekt an der Shell haengt und weil sonst //initial zuviel Formatiert wuerde. BOOL bNotifyBack:1; //TRUE wenn am Ende eines MakeAll() der Background //vom NotifyDTor benachrichtigt werden muss. protected: BOOL bInvalid :1; //Pos, PrtArea od. SSize wurden Invalidiert, sie werden //gleich wieder Validiert, denn sie muessen _immer_ //gueltig sein. Damit in LayAction korrekt gearbeitet //werden kann muss hier festgehalten werden, dass sie //invalidiert wurden. Ausnahmen bestaetigen die Regelt! BOOL bMinHeight:1; //TRUE wenn die vom Attribut vorgegebene Hoehe eine //eine Minimalhoehe ist (der Frm also bei Bedarf //darueberhinaus wachsen kann). BOOL bHeightClipped :1; //TRUE wenn der Fly nicht die Pos/Size anhand der Attrs BOOL bWidthClipped :1; //formatieren konnte, weil z.B. nicht genug Raum vorh. //war. BOOL bFormatHeightOnly :1; //Damit nach einer Anpassung der Breite //(CheckClip) nur das Format aufgerufen wird; //nicht aber die Breite anhand der Attribute //wieder bestimmt wird. BOOL bInCnt :1; // FLY_IN_CNTNT, als Zeichen verankert BOOL bAtCnt :1; // FLY_AT_CNTNT, am Absatz verankert BOOL bLayout :1; // FLY_PAGE, FLY_AT_FLY, an Seite oder Rahmen BOOL bAutoPosition :1; // FLY_AUTO_CNTNT, im Text verankerter Rahmen BOOL bNoShrink :1; // temporary forbud of shrinking to avoid loops BOOL bLockDeleteContent :1; // If the flag is set, the content of the // fly frame is not deleted if moved to // invisible layer. friend class SwNoTxtFrm; // Darf NotifyBackground rufen virtual void NotifyBackground( SwPageFrm *pPage, const SwRect& rRect, PrepareHint eHint) = 0; //Wird nur von SwXFrm::MakeAll() gerufen; wer es anders macht wird //in einen Sack gesteckt und muss zwei Tage drin hocken bleiben. virtual void MakeFlyPos(); virtual void Format( const SwBorderAttrs *pAttrs = 0 ); void MakePrtArea( const SwBorderAttrs &rAttrs ); void Lock() { bLocked = TRUE; } void Unlock() { bLocked = FALSE; } void SetMinHeight() { bMinHeight = TRUE; } void ResetMinHeight(){ bMinHeight = FALSE; } Size CalcRel( const SwFmtFrmSize &rSz ) const; SwFlyFrm( SwFlyFrmFmt*, SwFrm *pAnchor ); public: virtual ~SwFlyFrm(); virtual void Modify( SfxPoolItem*, SfxPoolItem* ); // erfrage vom Client Informationen virtual BOOL GetInfo( SfxPoolItem& ) const; virtual void Paint( const SwRect& ) const; virtual void ChgSize( const Size& aNewSize ); virtual BOOL GetCrsrOfst( SwPosition *, Point&, SwCrsrMoveState* = 0 ) const; virtual void CheckDirection( BOOL bVert ); virtual void Cut(); #ifndef PRODUCT virtual void Paste( SwFrm* pParent, SwFrm* pSibling = 0 ); #endif SwTwips _Shrink( SwTwips, SZPTR BOOL bTst ); SwTwips _Grow ( SwTwips, SZPTR BOOL bTst ); void _Invalidate( SwPageFrm *pPage = 0 ); BOOL FrmSizeChg( const SwFmtFrmSize & ); const SwFrm *GetAnchor() const { return pAnchor; } SwFrm *GetAnchor() { return pAnchor; } void ChgAnchor( SwFrm *pNew ) { pAnchor = pNew; } SwFlyFrm *GetPrevLink() { return pPrevLink; } SwFlyFrm *GetNextLink() { return pNextLink; } static void ChainFrames( SwFlyFrm *pMaster, SwFlyFrm *pFollow ); static void UnchainFrames( SwFlyFrm *pMaster, SwFlyFrm *pFollow ); SwFlyFrm *FindChainNeighbour( SwFrmFmt &rFmt, SwFrm *pAnch = 0 ); const SwVirtFlyDrawObj *GetVirtDrawObj() const { return pDrawObj; } SwVirtFlyDrawObj *GetVirtDrawObj() { return pDrawObj; } void NotifyDrawObj(); const Point& GetCurRelPos() const { return aRelPos; } void ChgRelPos( const Point &rAbsPos ); BOOL IsInvalid() const { return bInvalid; } void Invalidate() const { ((SwFlyFrm*)this)->bInvalid = TRUE; } void Validate() const { ((SwFlyFrm*)this)->bInvalid = FALSE; } BOOL IsMinHeight() const { return bMinHeight; } BOOL IsLocked() const { return bLocked; } BOOL IsAutoPos() const { return bAutoPosition; } BOOL IsFlyInCntFrm() const { return bInCnt; } BOOL IsFlyFreeFrm() const { return bAtCnt || bLayout; } BOOL IsFlyLayFrm() const { return bLayout; } BOOL IsFlyAtCntFrm() const { return bAtCnt; } BOOL IsNotifyBack() const { return bNotifyBack; } void SetNotifyBack() { bNotifyBack = TRUE; } void ResetNotifyBack() { bNotifyBack = FALSE; } BOOL IsNoShrink() const { return bNoShrink; } void SetNoShrink( BOOL bNew ) { bNoShrink = bNew; } BOOL IsLockDeleteContent() const { return bLockDeleteContent; } void SetLockDeleteContent( BOOL bNew ) { bLockDeleteContent = bNew; } BOOL IsClipped() const { return bHeightClipped || bWidthClipped; } BOOL IsHeightClipped() const { return bHeightClipped; } BOOL IsWidthClipped() const { return bWidthClipped; } BOOL IsLowerOf( const SwLayoutFrm *pUpper ) const; inline BOOL IsUpperOf( const SwFlyFrm *pLower ) const; SwFrm *FindLastLower(); SwRect AddSpacesToFrm() const; // OD 16.04.2003 #i13147# - add parameter <_bForPaint> to avoid load of // the graphic during paint. Default value: sal_False BOOL GetContour( PolyPolygon& rContour, const sal_Bool _bForPaint = sal_False ) const; BOOL ConvertHoriTo40( SwHoriOrient &rHori, SwRelationOrient &rRel, SwTwips &rPos ) const; //Auf dieser Shell painten (PreView, Print-Flag usw. rekursiv beachten)?. static BOOL IsPaint( SdrObject *pObj, const ViewShell *pSh ); /** SwFlyFrm::IsBackgroundTransparent - for feature #99657# OD 12.08.2002 determines, if background of fly frame has to be drawn transparent definition found in /core/layout/paintfrm.cxx @author OD @return true, if background color is transparent or a existing background graphic is transparent. */ const sal_Bool IsBackgroundTransparent() const; /** SwFlyFrm::IsShadowTransparent - for feature #99657# OD 05.08.2002 determine, if shadow color of fly frame has to be drawn transparent definition found in /core/layout/paintfrm.cxx @author OD @return true, if shadow color is transparent. */ const sal_Bool IsShadowTransparent() const; // OD 2004-01-19 #110582# void Chain( SwFrm* _pAnchor ); void Unchain(); void InsertCnt(); void DeleteCnt(); // OD 2004-02-12 #110582#-2 void InsertColumns(); }; inline BOOL SwFlyFrm::IsUpperOf( const SwFlyFrm *pLower ) const { return pLower->IsLowerOf( this ); } #endif <commit_msg>INTEGRATION: CWS swautowidth (1.10.70); FILE MERGED 2004/04/05 13:09:06 fme 1.10.70.1: i27205# Feature - Automatic frame width<commit_after>/************************************************************************* * * $RCSfile: flyfrm.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: kz $ $Date: 2004-05-18 14:50:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _FLYFRM_HXX #define _FLYFRM_HXX #include "layfrm.hxx" class SwPageFrm; class SwFlyFrmFmt; class SwFmtFrmSize; struct SwCrsrMoveState; class SwBorderAttrs; class SwVirtFlyDrawObj; class SwSpzFrmFmts; class SwAttrSetChg; class PolyPolygon; // OD 01.08.2003 #110978# namespace objectpositioning { class SwAnchoredObjectPosition; } #include <orntenum.hxx> //Sucht ausgehend von pOldAnch einen Anker fuer Absatzgebundene Rahmen. //Wird beim Draggen von Absatzgebundenen Objekten zur Ankeranzeige sowie //fuer Ankerwechsel benoetigt. //implementiert in layout/flycnt.cxx const SwCntntFrm *FindAnchor( const SwFrm *pOldAnch, const Point &rNew, const BOOL bBody = FALSE ); // berechnet das Rechteck, in dem das Objekt bewegt bzw. resized werden darf BOOL CalcClipRect( const SdrObject *pSdrObj, SwRect &rRect, BOOL bMove = TRUE ); //allg. Basisklasse fuer alle Freifliegenden Rahmen class SwFlyFrm : public SwLayoutFrm { //darf Locken. Definiert in frmtool.cxx friend void AppendObjs ( const SwSpzFrmFmts *, ULONG, SwFrm *, SwPageFrm * ); friend void AppendAllObjs( const SwSpzFrmFmts * ); friend void Notify( SwFlyFrm *, SwPageFrm *pOld, const SwRect &rOld, const SwRect* pOldPrt ); //darf die Pos berechnen (lassen) friend void lcl_MakeFlyPosition( SwFlyFrm *pFly ); // OD 01.08.2003 #110978# - access for calculation of position friend class objectpositioning::SwAnchoredObjectPosition; void InitDrawObj( BOOL bNotify ); //Wird von den CToren gerufen. void FinitDrawObj(); //Wird vom CTor gerufen. void _UpdateAttr( SfxPoolItem*, SfxPoolItem*, BYTE &, SwAttrSetChg *pa = 0, SwAttrSetChg *pb = 0 ); protected: SwVirtFlyDrawObj *pDrawObj; // das Drawingobject zum Fly SwFrm *pAnchor; // An diesem LayoutFrm haengt der Frm, kann 0 sein SwFlyFrm *pPrevLink, // Vorgaenger/Nachfolger fuer Verkettung mit *pNextLink; // Textfluss Point aRelPos; //Die Relative Position zum Master private: BOOL bLocked :1; //Cntnt-gebundene Flys muessen derart blockiert werden //koennen, dass sie nicht Formatiert werden; :MakeAll //returnt dann sofort. Dies ist bei Seitenwechseln //waehrend der Formatierung notwendig. //Auch wahrend des RootCTors ist dies notwendig da //sonst der Anker formatiert wird obwohl die Root noch //nicht korrekt an der Shell haengt und weil sonst //initial zuviel Formatiert wuerde. BOOL bNotifyBack:1; //TRUE wenn am Ende eines MakeAll() der Background //vom NotifyDTor benachrichtigt werden muss. protected: BOOL bInvalid :1; //Pos, PrtArea od. SSize wurden Invalidiert, sie werden //gleich wieder Validiert, denn sie muessen _immer_ //gueltig sein. Damit in LayAction korrekt gearbeitet //werden kann muss hier festgehalten werden, dass sie //invalidiert wurden. Ausnahmen bestaetigen die Regelt! BOOL bMinHeight:1; //TRUE wenn die vom Attribut vorgegebene Hoehe eine //eine Minimalhoehe ist (der Frm also bei Bedarf //darueberhinaus wachsen kann). BOOL bHeightClipped :1; //TRUE wenn der Fly nicht die Pos/Size anhand der Attrs BOOL bWidthClipped :1; //formatieren konnte, weil z.B. nicht genug Raum vorh. //war. BOOL bFormatHeightOnly :1; //Damit nach einer Anpassung der Breite //(CheckClip) nur das Format aufgerufen wird; //nicht aber die Breite anhand der Attribute //wieder bestimmt wird. BOOL bInCnt :1; // FLY_IN_CNTNT, als Zeichen verankert BOOL bAtCnt :1; // FLY_AT_CNTNT, am Absatz verankert BOOL bLayout :1; // FLY_PAGE, FLY_AT_FLY, an Seite oder Rahmen BOOL bAutoPosition :1; // FLY_AUTO_CNTNT, im Text verankerter Rahmen BOOL bNoShrink :1; // temporary forbud of shrinking to avoid loops BOOL bLockDeleteContent :1; // If the flag is set, the content of the // fly frame is not deleted if moved to // invisible layer. friend class SwNoTxtFrm; // Darf NotifyBackground rufen virtual void NotifyBackground( SwPageFrm *pPage, const SwRect& rRect, PrepareHint eHint) = 0; //Wird nur von SwXFrm::MakeAll() gerufen; wer es anders macht wird //in einen Sack gesteckt und muss zwei Tage drin hocken bleiben. virtual void MakeFlyPos(); virtual void Format( const SwBorderAttrs *pAttrs = 0 ); void MakePrtArea( const SwBorderAttrs &rAttrs ); void Lock() { bLocked = TRUE; } void Unlock() { bLocked = FALSE; } void SetMinHeight() { bMinHeight = TRUE; } void ResetMinHeight(){ bMinHeight = FALSE; } Size CalcRel( const SwFmtFrmSize &rSz ) const; SwTwips CalcAutoWidth() const; SwFlyFrm( SwFlyFrmFmt*, SwFrm *pAnchor ); public: virtual ~SwFlyFrm(); virtual void Modify( SfxPoolItem*, SfxPoolItem* ); // erfrage vom Client Informationen virtual BOOL GetInfo( SfxPoolItem& ) const; virtual void Paint( const SwRect& ) const; virtual void ChgSize( const Size& aNewSize ); virtual BOOL GetCrsrOfst( SwPosition *, Point&, SwCrsrMoveState* = 0 ) const; virtual void CheckDirection( BOOL bVert ); virtual void Cut(); #ifndef PRODUCT virtual void Paste( SwFrm* pParent, SwFrm* pSibling = 0 ); #endif SwTwips _Shrink( SwTwips, SZPTR BOOL bTst ); SwTwips _Grow ( SwTwips, SZPTR BOOL bTst ); void _Invalidate( SwPageFrm *pPage = 0 ); BOOL FrmSizeChg( const SwFmtFrmSize & ); const SwFrm *GetAnchor() const { return pAnchor; } SwFrm *GetAnchor() { return pAnchor; } void ChgAnchor( SwFrm *pNew ) { pAnchor = pNew; } SwFlyFrm *GetPrevLink() { return pPrevLink; } SwFlyFrm *GetNextLink() { return pNextLink; } static void ChainFrames( SwFlyFrm *pMaster, SwFlyFrm *pFollow ); static void UnchainFrames( SwFlyFrm *pMaster, SwFlyFrm *pFollow ); SwFlyFrm *FindChainNeighbour( SwFrmFmt &rFmt, SwFrm *pAnch = 0 ); const SwVirtFlyDrawObj *GetVirtDrawObj() const { return pDrawObj; } SwVirtFlyDrawObj *GetVirtDrawObj() { return pDrawObj; } void NotifyDrawObj(); const Point& GetCurRelPos() const { return aRelPos; } void ChgRelPos( const Point &rAbsPos ); BOOL IsInvalid() const { return bInvalid; } void Invalidate() const { ((SwFlyFrm*)this)->bInvalid = TRUE; } void Validate() const { ((SwFlyFrm*)this)->bInvalid = FALSE; } BOOL IsMinHeight() const { return bMinHeight; } BOOL IsLocked() const { return bLocked; } BOOL IsAutoPos() const { return bAutoPosition; } BOOL IsFlyInCntFrm() const { return bInCnt; } BOOL IsFlyFreeFrm() const { return bAtCnt || bLayout; } BOOL IsFlyLayFrm() const { return bLayout; } BOOL IsFlyAtCntFrm() const { return bAtCnt; } BOOL IsNotifyBack() const { return bNotifyBack; } void SetNotifyBack() { bNotifyBack = TRUE; } void ResetNotifyBack() { bNotifyBack = FALSE; } BOOL IsNoShrink() const { return bNoShrink; } void SetNoShrink( BOOL bNew ) { bNoShrink = bNew; } BOOL IsLockDeleteContent() const { return bLockDeleteContent; } void SetLockDeleteContent( BOOL bNew ) { bLockDeleteContent = bNew; } BOOL IsClipped() const { return bHeightClipped || bWidthClipped; } BOOL IsHeightClipped() const { return bHeightClipped; } BOOL IsWidthClipped() const { return bWidthClipped; } BOOL IsLowerOf( const SwLayoutFrm *pUpper ) const; inline BOOL IsUpperOf( const SwFlyFrm *pLower ) const; SwFrm *FindLastLower(); SwRect AddSpacesToFrm() const; // OD 16.04.2003 #i13147# - add parameter <_bForPaint> to avoid load of // the graphic during paint. Default value: sal_False BOOL GetContour( PolyPolygon& rContour, const sal_Bool _bForPaint = sal_False ) const; BOOL ConvertHoriTo40( SwHoriOrient &rHori, SwRelationOrient &rRel, SwTwips &rPos ) const; //Auf dieser Shell painten (PreView, Print-Flag usw. rekursiv beachten)?. static BOOL IsPaint( SdrObject *pObj, const ViewShell *pSh ); /** SwFlyFrm::IsBackgroundTransparent - for feature #99657# OD 12.08.2002 determines, if background of fly frame has to be drawn transparent definition found in /core/layout/paintfrm.cxx @author OD @return true, if background color is transparent or a existing background graphic is transparent. */ const sal_Bool IsBackgroundTransparent() const; /** SwFlyFrm::IsShadowTransparent - for feature #99657# OD 05.08.2002 determine, if shadow color of fly frame has to be drawn transparent definition found in /core/layout/paintfrm.cxx @author OD @return true, if shadow color is transparent. */ const sal_Bool IsShadowTransparent() const; // OD 2004-01-19 #110582# void Chain( SwFrm* _pAnchor ); void Unchain(); void InsertCnt(); void DeleteCnt(); // OD 2004-02-12 #110582#-2 void InsertColumns(); }; inline BOOL SwFlyFrm::IsUpperOf( const SwFlyFrm *pLower ) const { return pLower->IsLowerOf( this ); } #endif <|endoftext|>
<commit_before><commit_msg>Remove redundant IF clause<commit_after><|endoftext|>
<commit_before><commit_msg>n#778148 SwEditWin::MouseButtonDown: prefer url over hell frames on ctrl-click<commit_after><|endoftext|>
<commit_before>#include "sendcoinsentry.h" #include "ui_sendcoinsentry.h" #include "guiutil.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "walletmodel.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(QWidget *parent) : QFrame(parent), ui(new Ui::SendCoinsEntry), model(0) { ui->setupUi(this); #ifdef Q_WS_MAC ui->payToLayout->setSpacing(4); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); ui->payTo->setPlaceholderText(tr("Enter a Darbcoin address (they start with an 'm')")); #endif setFocusPolicy(Qt::TabFocus); setFocusProxy(ui->payTo); GUIUtil::setupAddressWidget(ui->payTo, this); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if(!model) return; AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString &address) { if(!model) return; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if(!associatedLabel.isEmpty()) ui->addAsLabel->setText(associatedLabel); } void SendCoinsEntry::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); clear(); } void SendCoinsEntry::setRemoveEnabled(bool enabled) { ui->deleteButton->setEnabled(enabled); } void SendCoinsEntry::clear() { ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); ui->payTo->setFocus(); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void SendCoinsEntry::on_deleteButton_clicked() { emit removeEntry(this); } bool SendCoinsEntry::validate() { // Check input validity bool retval = true; if(!ui->payAmount->validate()) { retval = false; } else { if(ui->payAmount->value() <= 0) { // Cannot send 0 coins or less ui->payAmount->setValid(false); retval = false; } } if(!ui->payTo->hasAcceptableInput() || (model && !model->validateAddress(ui->payTo->text()))) { ui->payTo->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { SendCoinsRecipient rv; rv.address = ui->payTo->text(); rv.label = ui->addAsLabel->text(); rv.amount = ui->payAmount->value(); return rv; } QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel); return ui->payAmount->setupTabChain(ui->addAsLabel); } void SendCoinsEntry::setValue(const SendCoinsRecipient &value) { ui->payTo->setText(value.address); ui->addAsLabel->setText(value.label); ui->payAmount->setValue(value.amount); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update payAmount with the current unit ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } } <commit_msg>changed string in ui for correct starting address letter<commit_after>#include "sendcoinsentry.h" #include "ui_sendcoinsentry.h" #include "guiutil.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "walletmodel.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(QWidget *parent) : QFrame(parent), ui(new Ui::SendCoinsEntry), model(0) { ui->setupUi(this); #ifdef Q_WS_MAC ui->payToLayout->setSpacing(4); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); ui->payTo->setPlaceholderText(tr("Enter a Darbcoin address (they start with an 'D')")); #endif setFocusPolicy(Qt::TabFocus); setFocusProxy(ui->payTo); GUIUtil::setupAddressWidget(ui->payTo, this); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if(!model) return; AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString &address) { if(!model) return; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if(!associatedLabel.isEmpty()) ui->addAsLabel->setText(associatedLabel); } void SendCoinsEntry::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); clear(); } void SendCoinsEntry::setRemoveEnabled(bool enabled) { ui->deleteButton->setEnabled(enabled); } void SendCoinsEntry::clear() { ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); ui->payTo->setFocus(); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void SendCoinsEntry::on_deleteButton_clicked() { emit removeEntry(this); } bool SendCoinsEntry::validate() { // Check input validity bool retval = true; if(!ui->payAmount->validate()) { retval = false; } else { if(ui->payAmount->value() <= 0) { // Cannot send 0 coins or less ui->payAmount->setValid(false); retval = false; } } if(!ui->payTo->hasAcceptableInput() || (model && !model->validateAddress(ui->payTo->text()))) { ui->payTo->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { SendCoinsRecipient rv; rv.address = ui->payTo->text(); rv.label = ui->addAsLabel->text(); rv.amount = ui->payAmount->value(); return rv; } QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel); return ui->payAmount->setupTabChain(ui->addAsLabel); } void SendCoinsEntry::setValue(const SendCoinsRecipient &value) { ui->payTo->setText(value.address); ui->addAsLabel->setText(value.label); ui->payAmount->setValue(value.amount); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update payAmount with the current unit ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Graphics/OsgMeshRepresentation.h" #include <osg/Array> #include <osg/Geode> #include <osg/Geometry> #include <osg/Switch> #include <osg/PositionAttitudeTransform> #include <osg/Vec3f> #include <osgUtil/SmoothingVisitor> #include "SurgSim/Framework/ApplicationData.h" #include "SurgSim/Framework/Asset.h" #include "SurgSim/Framework/Log.h" #include "SurgSim/Framework/ObjectFactory.h" #include "SurgSim/Framework/Runtime.h" #include "SurgSim/Graphics/Mesh.h" #include "SurgSim/Graphics/OsgConversions.h" #include "SurgSim/Graphics/TriangleNormalGenerator.h" #include "SurgSim/Math/MeshShape.h" #include "SurgSim/Math/Shape.h" namespace SurgSim { namespace Graphics { SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Graphics::OsgMeshRepresentation, OsgMeshRepresentation); OsgMeshRepresentation::OsgMeshRepresentation(const std::string& name) : Representation(name), OsgRepresentation(name), MeshRepresentation(name), m_updateOptions(UPDATE_OPTION_VERTICES), m_updateCount(0) { m_meshSwitch = new osg::Switch(); m_transform->addChild(m_meshSwitch); setMesh(std::make_shared<Mesh>()); } OsgMeshRepresentation::~OsgMeshRepresentation() { } void OsgMeshRepresentation::loadMesh(const std::string& fileName) { auto mesh = std::make_shared<Mesh>(); mesh->load(fileName); setMesh(mesh); } void OsgMeshRepresentation::setMesh(std::shared_ptr<SurgSim::Framework::Asset> mesh) { auto graphicsMesh = std::dynamic_pointer_cast<Mesh>(mesh); SURGSIM_ASSERT(graphicsMesh != nullptr) << "Mesh for OsgMeshRepresentation needs to be a SurgSim::Graphics::Mesh"; m_mesh = graphicsMesh; m_updateCount = m_mesh->getUpdateCount(); m_mesh->dirty(); buildGeometry(); } std::shared_ptr<Mesh> OsgMeshRepresentation::getMesh() { return m_mesh; } void OsgMeshRepresentation::setShape(std::shared_ptr<SurgSim::Math::Shape> shape) { SURGSIM_ASSERT(shape->getType() == SurgSim::Math::SHAPE_TYPE_MESH) << "Shape for OsgMeshRepresentation needs to be a SurgSim::Math::MeshShape"; auto meshShape = std::static_pointer_cast<SurgSim::Math::MeshShape>(shape); m_mesh = std::make_shared<Mesh>(*meshShape); } void OsgMeshRepresentation::doUpdate(double dt) { size_t updateCount = m_mesh->getUpdateCount(); if (m_updateCount != updateCount) { // The update was done through shared data (might not be threadsafe) // #threadsafety m_updateCount = updateCount; privateUpdateMesh(*m_mesh); } else { // The update was done through the threadsafe Locked container Mesh tempMesh; if (m_writeBuffer.tryTakeChanged(&tempMesh)) { privateUpdateMesh(tempMesh); } } } void OsgMeshRepresentation::privateUpdateMesh(const Mesh& mesh) { SURGSIM_ASSERT(mesh.isValid()) << "The mesh in the OsgMeshRepresentation " << getName() << " is invalid."; // Early exit if there are no vertices if (mesh.getNumVertices() == 0) { m_meshSwitch->setAllChildrenOff(); return; } m_meshSwitch->setSingleChildOn(0); int updateOptions = updateOsgArrays(mesh, m_geometry); updateOptions |= m_updateOptions; if ((updateOptions & UPDATE_OPTION_TRIANGLES) != 0) { updateTriangles(mesh, m_geometry); } if ((updateOptions & (UPDATE_OPTION_VERTICES | UPDATE_OPTION_TEXTURES | UPDATE_OPTION_COLORS)) != 0) { updateVertices(mesh, m_geometry, updateOptions); updateTangents(); m_geometry->dirtyDisplayList(); m_geometry->dirtyBound(); m_geometry->getBound(); } } bool OsgMeshRepresentation::doInitialize() { return true; } void OsgMeshRepresentation::updateVertices(const Mesh& mesh, osg::Geometry* geometry, int updateOptions) { static osg::Vec4d defaultColor(0.8, 0.2, 0.2, 1.0); static osg::Vec2d defaultTextureCoord(0.0, 0.0); bool updateColors = (updateOptions & UPDATE_OPTION_COLORS) != 0; bool updateTextures = (updateOptions & UPDATE_OPTION_TEXTURES) != 0; bool updateVertices = (updateOptions & UPDATE_OPTION_VERTICES) != 0; auto vertices = static_cast<osg::Vec3Array*>(geometry->getVertexArray()); auto colors = static_cast<osg::Vec4Array*>(geometry->getColorArray()); auto textureCoords = static_cast<osg::Vec2Array*>(geometry->getTexCoordArray(0)); size_t index = 0; for (const auto& vertex : mesh.getVertices()) { if (updateVertices) { (*vertices)[index].set(toOsg(vertex.position)); } if (updateColors) { (*colors)[index] = (vertex.data.color.hasValue()) ? toOsg(vertex.data.color.getValue()) : defaultColor; } if (updateTextures) { (*textureCoords)[index] = (vertex.data.texture.hasValue()) ? toOsg(vertex.data.texture.getValue()) : defaultTextureCoord; } ++index; } if (updateVertices) { updateNormals(geometry); } vertices->dirty(); } void OsgMeshRepresentation::updateNormals(osg::Geometry* geometry) { // Generate normals from geometry auto vertices = static_cast<osg::Vec3Array*>(geometry->getVertexArray()); auto normals = static_cast<osg::Vec3Array*>(geometry->getNormalArray()); auto normalGenerator = createNormalGenerator(vertices, normals); geometry->accept(normalGenerator); normalGenerator.normalize(); normals->dirty(); } void OsgMeshRepresentation::updateTriangles(const Mesh& mesh, osg::Geometry* geometry) { osg::Geometry::DrawElementsList drawElements; geometry->getDrawElementsList(drawElements); auto triangles = static_cast<osg::DrawElementsUInt*>(drawElements[0]); size_t i = 0; for (auto const& triangle : mesh.getTriangles()) { if (triangle.isValid) { (*triangles)[i++] = triangle.verticesId[0]; (*triangles)[i++] = triangle.verticesId[1]; (*triangles)[i++] = triangle.verticesId[2]; } } triangles->dirty(); } int OsgMeshRepresentation::updateOsgArrays(const Mesh& mesh, osg::Geometry* geometry) { int result = 0; size_t numVertices = mesh.getNumVertices(); auto vertices = static_cast<osg::Vec3Array*>(geometry->getVertexArray()); auto normals = static_cast<osg::Vec3Array*>(geometry->getNormalArray()); if (numVertices != vertices->size()) { vertices->resize(numVertices); normals->resize(numVertices); result |= UPDATE_OPTION_VERTICES; } vertices->setDataVariance(getDataVariance(UPDATE_OPTION_VERTICES)); normals->setDataVariance(getDataVariance(UPDATE_OPTION_VERTICES)); // The first vertex determines what values the mesh should have ... Mesh::VertexType vertex = mesh.getVertex(0); auto colors = static_cast<osg::Vec4Array*>(geometry->getColorArray()); if (vertex.data.color.hasValue() && numVertices > colors->size()) { if (colors->size() > 1) { geometry->setColorArray(colors, osg::Array::BIND_PER_VERTEX); } colors->resize(numVertices); result |= UPDATE_OPTION_COLORS; } colors->setDataVariance(getDataVariance(UPDATE_OPTION_COLORS)); auto textureCoords = static_cast<osg::Vec2Array*>(geometry->getTexCoordArray(0)); if (vertex.data.texture.hasValue()) { if (textureCoords == nullptr) { textureCoords = new osg::Vec2Array(0); geometry->setTexCoordArray(0, textureCoords, osg::Array::BIND_PER_VERTEX); } textureCoords->resize(numVertices); result |= UPDATE_OPTION_TEXTURES; } if (textureCoords != nullptr) { textureCoords->setDataVariance(getDataVariance(UPDATE_OPTION_TEXTURES)); } osg::Geometry::DrawElementsList drawElements; geometry->getDrawElementsList(drawElements); auto triangles = static_cast<osg::DrawElementsUInt*>(drawElements[0]); if (mesh.getNumTriangles() * 3 != triangles->size()) { triangles->resize(mesh.getNumTriangles() * 3); result |= UPDATE_OPTION_TRIANGLES; } triangles->setDataVariance(getDataVariance(UPDATE_OPTION_TRIANGLES)); return result; } void OsgMeshRepresentation::setUpdateOptions(int val) { if (val <= UPDATE_OPTION_ALL && val >= UPDATE_OPTION_NONE) { m_updateOptions = val; } } int OsgMeshRepresentation::getUpdateOptions() const { return m_updateOptions; } osg::ref_ptr<osg::Geometry> OsgMeshRepresentation::getOsgGeometry() const { return m_geometry; } void OsgMeshRepresentation::updateMesh(const SurgSim::Graphics::Mesh& mesh) { m_writeBuffer.set(mesh); } osg::Object::DataVariance OsgMeshRepresentation::getDataVariance(int updateOption) { return ((m_updateOptions & updateOption) != 0) ? osg::Object::DYNAMIC : osg::Object::STATIC; } void OsgMeshRepresentation::buildGeometry() { // Remove old Geometry nodes m_meshSwitch->removeChildren(0, m_meshSwitch->getNumChildren()); m_geometry = new osg::Geometry; m_geometry->setUseDisplayList(false); // Create Standard arrays zero size, updateOsgArrays will take care of the correct sizing and // setting the correct data variance on them // Set up vertices array auto vertices = new osg::Vec3Array(); m_geometry->setVertexArray(vertices); // Create normals auto normals = new osg::Vec3Array(); m_geometry->setNormalArray(normals, osg::Array::BIND_PER_VERTEX); // Set up color array with default color auto colors = new osg::Vec4Array(1); (*colors)[0] = osg::Vec4(0.8f, 0.8f, 1.0f, 1.0f); m_geometry->setColorArray(colors, osg::Array::BIND_OVERALL); // Set up primitive set for triangles auto triangles = new osg::DrawElementsUInt(osg::PrimitiveSet::TRIANGLES); m_geometry->addPrimitiveSet(triangles); auto geode = new osg::Geode; geode->addDrawable(m_geometry); m_meshSwitch->setAllChildrenOff(); m_meshSwitch->addChild(geode); } }; // Graphics }; // SurgSim <commit_msg>Let the OsgMeshRepresentation render SURFACE_MESH as well.<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Graphics/OsgMeshRepresentation.h" #include <osg/Array> #include <osg/Geode> #include <osg/Geometry> #include <osg/Switch> #include <osg/PositionAttitudeTransform> #include <osg/Vec3f> #include <osgUtil/SmoothingVisitor> #include "SurgSim/Framework/ApplicationData.h" #include "SurgSim/Framework/Asset.h" #include "SurgSim/Framework/Log.h" #include "SurgSim/Framework/ObjectFactory.h" #include "SurgSim/Framework/Runtime.h" #include "SurgSim/Graphics/Mesh.h" #include "SurgSim/Graphics/OsgConversions.h" #include "SurgSim/Graphics/TriangleNormalGenerator.h" #include "SurgSim/Math/MeshShape.h" #include "SurgSim/Math/Shape.h" namespace SurgSim { namespace Graphics { SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Graphics::OsgMeshRepresentation, OsgMeshRepresentation); OsgMeshRepresentation::OsgMeshRepresentation(const std::string& name) : Representation(name), OsgRepresentation(name), MeshRepresentation(name), m_updateOptions(UPDATE_OPTION_VERTICES), m_updateCount(0) { m_meshSwitch = new osg::Switch(); m_transform->addChild(m_meshSwitch); setMesh(std::make_shared<Mesh>()); } OsgMeshRepresentation::~OsgMeshRepresentation() { } void OsgMeshRepresentation::loadMesh(const std::string& fileName) { auto mesh = std::make_shared<Mesh>(); mesh->load(fileName); setMesh(mesh); } void OsgMeshRepresentation::setMesh(std::shared_ptr<SurgSim::Framework::Asset> mesh) { auto graphicsMesh = std::dynamic_pointer_cast<Mesh>(mesh); SURGSIM_ASSERT(graphicsMesh != nullptr) << "Mesh for OsgMeshRepresentation needs to be a SurgSim::Graphics::Mesh"; m_mesh = graphicsMesh; m_updateCount = m_mesh->getUpdateCount(); m_mesh->dirty(); buildGeometry(); } std::shared_ptr<Mesh> OsgMeshRepresentation::getMesh() { return m_mesh; } void OsgMeshRepresentation::setShape(std::shared_ptr<SurgSim::Math::Shape> shape) { SURGSIM_ASSERT(shape->getType() == SurgSim::Math::SHAPE_TYPE_MESH || shape->getType() == SurgSim::Math::SHAPE_TYPE_SURFACEMESH) << "Shape for OsgMeshRepresentation needs to be a SurgSim::Math::MeshShape/SurgSim::Math::SurfaceMeshShape"; auto meshShape = std::static_pointer_cast<SurgSim::Math::MeshShape>(shape); m_mesh = std::make_shared<Mesh>(*meshShape); } void OsgMeshRepresentation::doUpdate(double dt) { size_t updateCount = m_mesh->getUpdateCount(); if (m_updateCount != updateCount) { // The update was done through shared data (might not be threadsafe) // #threadsafety m_updateCount = updateCount; privateUpdateMesh(*m_mesh); } else { // The update was done through the threadsafe Locked container Mesh tempMesh; if (m_writeBuffer.tryTakeChanged(&tempMesh)) { privateUpdateMesh(tempMesh); } } } void OsgMeshRepresentation::privateUpdateMesh(const Mesh& mesh) { SURGSIM_ASSERT(mesh.isValid()) << "The mesh in the OsgMeshRepresentation " << getName() << " is invalid."; // Early exit if there are no vertices if (mesh.getNumVertices() == 0) { m_meshSwitch->setAllChildrenOff(); return; } m_meshSwitch->setSingleChildOn(0); int updateOptions = updateOsgArrays(mesh, m_geometry); updateOptions |= m_updateOptions; if ((updateOptions & UPDATE_OPTION_TRIANGLES) != 0) { updateTriangles(mesh, m_geometry); } if ((updateOptions & (UPDATE_OPTION_VERTICES | UPDATE_OPTION_TEXTURES | UPDATE_OPTION_COLORS)) != 0) { updateVertices(mesh, m_geometry, updateOptions); updateTangents(); m_geometry->dirtyDisplayList(); m_geometry->dirtyBound(); m_geometry->getBound(); } } bool OsgMeshRepresentation::doInitialize() { return true; } void OsgMeshRepresentation::updateVertices(const Mesh& mesh, osg::Geometry* geometry, int updateOptions) { static osg::Vec4d defaultColor(0.8, 0.2, 0.2, 1.0); static osg::Vec2d defaultTextureCoord(0.0, 0.0); bool updateColors = (updateOptions & UPDATE_OPTION_COLORS) != 0; bool updateTextures = (updateOptions & UPDATE_OPTION_TEXTURES) != 0; bool updateVertices = (updateOptions & UPDATE_OPTION_VERTICES) != 0; auto vertices = static_cast<osg::Vec3Array*>(geometry->getVertexArray()); auto colors = static_cast<osg::Vec4Array*>(geometry->getColorArray()); auto textureCoords = static_cast<osg::Vec2Array*>(geometry->getTexCoordArray(0)); size_t index = 0; for (const auto& vertex : mesh.getVertices()) { if (updateVertices) { (*vertices)[index].set(toOsg(vertex.position)); } if (updateColors) { (*colors)[index] = (vertex.data.color.hasValue()) ? toOsg(vertex.data.color.getValue()) : defaultColor; } if (updateTextures) { (*textureCoords)[index] = (vertex.data.texture.hasValue()) ? toOsg(vertex.data.texture.getValue()) : defaultTextureCoord; } ++index; } if (updateVertices) { updateNormals(geometry); } vertices->dirty(); } void OsgMeshRepresentation::updateNormals(osg::Geometry* geometry) { // Generate normals from geometry auto vertices = static_cast<osg::Vec3Array*>(geometry->getVertexArray()); auto normals = static_cast<osg::Vec3Array*>(geometry->getNormalArray()); auto normalGenerator = createNormalGenerator(vertices, normals); geometry->accept(normalGenerator); normalGenerator.normalize(); normals->dirty(); } void OsgMeshRepresentation::updateTriangles(const Mesh& mesh, osg::Geometry* geometry) { osg::Geometry::DrawElementsList drawElements; geometry->getDrawElementsList(drawElements); auto triangles = static_cast<osg::DrawElementsUInt*>(drawElements[0]); size_t i = 0; for (auto const& triangle : mesh.getTriangles()) { if (triangle.isValid) { (*triangles)[i++] = triangle.verticesId[0]; (*triangles)[i++] = triangle.verticesId[1]; (*triangles)[i++] = triangle.verticesId[2]; } } triangles->dirty(); } int OsgMeshRepresentation::updateOsgArrays(const Mesh& mesh, osg::Geometry* geometry) { int result = 0; size_t numVertices = mesh.getNumVertices(); auto vertices = static_cast<osg::Vec3Array*>(geometry->getVertexArray()); auto normals = static_cast<osg::Vec3Array*>(geometry->getNormalArray()); if (numVertices != vertices->size()) { vertices->resize(numVertices); normals->resize(numVertices); result |= UPDATE_OPTION_VERTICES; } vertices->setDataVariance(getDataVariance(UPDATE_OPTION_VERTICES)); normals->setDataVariance(getDataVariance(UPDATE_OPTION_VERTICES)); // The first vertex determines what values the mesh should have ... Mesh::VertexType vertex = mesh.getVertex(0); auto colors = static_cast<osg::Vec4Array*>(geometry->getColorArray()); if (vertex.data.color.hasValue() && numVertices > colors->size()) { if (colors->size() > 1) { geometry->setColorArray(colors, osg::Array::BIND_PER_VERTEX); } colors->resize(numVertices); result |= UPDATE_OPTION_COLORS; } colors->setDataVariance(getDataVariance(UPDATE_OPTION_COLORS)); auto textureCoords = static_cast<osg::Vec2Array*>(geometry->getTexCoordArray(0)); if (vertex.data.texture.hasValue()) { if (textureCoords == nullptr) { textureCoords = new osg::Vec2Array(0); geometry->setTexCoordArray(0, textureCoords, osg::Array::BIND_PER_VERTEX); } textureCoords->resize(numVertices); result |= UPDATE_OPTION_TEXTURES; } if (textureCoords != nullptr) { textureCoords->setDataVariance(getDataVariance(UPDATE_OPTION_TEXTURES)); } osg::Geometry::DrawElementsList drawElements; geometry->getDrawElementsList(drawElements); auto triangles = static_cast<osg::DrawElementsUInt*>(drawElements[0]); if (mesh.getNumTriangles() * 3 != triangles->size()) { triangles->resize(mesh.getNumTriangles() * 3); result |= UPDATE_OPTION_TRIANGLES; } triangles->setDataVariance(getDataVariance(UPDATE_OPTION_TRIANGLES)); return result; } void OsgMeshRepresentation::setUpdateOptions(int val) { if (val <= UPDATE_OPTION_ALL && val >= UPDATE_OPTION_NONE) { m_updateOptions = val; } } int OsgMeshRepresentation::getUpdateOptions() const { return m_updateOptions; } osg::ref_ptr<osg::Geometry> OsgMeshRepresentation::getOsgGeometry() const { return m_geometry; } void OsgMeshRepresentation::updateMesh(const SurgSim::Graphics::Mesh& mesh) { m_writeBuffer.set(mesh); } osg::Object::DataVariance OsgMeshRepresentation::getDataVariance(int updateOption) { return ((m_updateOptions & updateOption) != 0) ? osg::Object::DYNAMIC : osg::Object::STATIC; } void OsgMeshRepresentation::buildGeometry() { // Remove old Geometry nodes m_meshSwitch->removeChildren(0, m_meshSwitch->getNumChildren()); m_geometry = new osg::Geometry; m_geometry->setUseDisplayList(false); // Create Standard arrays zero size, updateOsgArrays will take care of the correct sizing and // setting the correct data variance on them // Set up vertices array auto vertices = new osg::Vec3Array(); m_geometry->setVertexArray(vertices); // Create normals auto normals = new osg::Vec3Array(); m_geometry->setNormalArray(normals, osg::Array::BIND_PER_VERTEX); // Set up color array with default color auto colors = new osg::Vec4Array(1); (*colors)[0] = osg::Vec4(0.8f, 0.8f, 1.0f, 1.0f); m_geometry->setColorArray(colors, osg::Array::BIND_OVERALL); // Set up primitive set for triangles auto triangles = new osg::DrawElementsUInt(osg::PrimitiveSet::TRIANGLES); m_geometry->addPrimitiveSet(triangles); auto geode = new osg::Geode; geode->addDrawable(m_geometry); m_meshSwitch->setAllChildrenOff(); m_meshSwitch->addChild(geode); } }; // Graphics }; // SurgSim <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: glossary.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2006-08-14 17:41:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _GLOSSARY_HXX #define _GLOSSARY_HXX #ifndef _EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _SVTREEBOX_HXX //autogen #include <svtools/svtreebx.hxx> #endif #ifndef _SVX_STDDLG_HXX //autogen #include <svx/stddlg.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _COMBOBOX_HXX //autogen #include <vcl/combobox.hxx> #endif #ifndef _MENUBTN_HXX //autogen #include <vcl/menubtn.hxx> #endif #ifndef _COM_SUN_STAR_CONTAINER_XENUMERATIONACCESS_HPP_ #include <com/sun/star/container/XEnumerationAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_ #include <com/sun/star/container/XHierarchicalNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCONTENTENUMERATIONACCESS_HPP_ #include <com/sun/star/container/XContentEnumerationAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_ #include <com/sun/star/container/XEnumeration.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XELEMENTACCESS_HPP_ #include <com/sun/star/container/XElementAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif class SwGlossaryHdl; class SwNewGlosNameDlg; class SwWrtShell; class SfxViewFrame; class PopupMenu; class Menu; const short RET_EDIT = 100; //------------------------------------------------------------------ class SwGlTreeListBox : public SvTreeListBox { const String sReadonly; SvLBoxEntry* pDragEntry; virtual DragDropMode NotifyStartDrag( TransferDataContainer& rContainer, SvLBoxEntry* ); virtual sal_Bool NotifyAcceptDrop( SvLBoxEntry* ); virtual sal_Bool NotifyMoving( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry, SvLBoxEntry*& rpNewParent, sal_uInt32& rNewChildPos ); virtual sal_Bool NotifyCopying( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry, SvLBoxEntry*& rpNewParent, sal_uInt32& rNewChildPos); public: SwGlTreeListBox(Window* pParent, const ResId& rResId); virtual void RequestHelp( const HelpEvent& rHEvt ); void Clear(); }; //------------------------------------------------------------------ class SwOneExampleFrame; class SwGlossaryDlg : public SvxStandardDialog { friend class SwNewGlosNameDlg; friend class SwGlTreeListBox; CheckBox aInsertTipCB; FixedText aNameLbl; Edit aNameED; FixedText aShortNameLbl; NoSpaceEdit aShortNameEdit; SwGlTreeListBox aCategoryBox; FixedLine aRelativeFL; CheckBox aFileRelCB; CheckBox aNetRelCB; Window aExampleWIN; Window aExampleDummyWIN; CheckBox aShowExampleCB; OKButton aInsertBtn; CancelButton aCloseBtn; HelpButton aHelpBtn; MenuButton aEditBtn; PushButton aBibBtn; PushButton aPathBtn; String sReadonlyPath; ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > _xAutoText; SwOneExampleFrame* pExampleFrame; PopupMenu* pMenu; SwGlossaryHdl* pGlossaryHdl; String sResumeGroup; String sResumeShortName; BOOL bResume; const sal_Bool bSelection : 1; sal_Bool bReadOnly : 1; sal_Bool bIsOld : 1; sal_Bool bIsDocReadOnly:1; SwWrtShell* pSh; void EnableShortName(sal_Bool bOn = sal_True); DECL_LINK( NameModify, Edit * ); DECL_LINK( NameDoubleClick, SvTreeListBox * ); DECL_LINK( GrpSelect, SvTreeListBox * ); DECL_LINK( MenuHdl, Menu * ); DECL_LINK( EnableHdl, Menu * ); DECL_LINK( BibHdl, Button * ); DECL_LINK( EditHdl, Button * ); DECL_LINK( PathHdl, Button * ); DECL_LINK( CheckBoxHdl, CheckBox * ); DECL_LINK( ShowPreviewHdl, CheckBox * ); DECL_LINK( PreviewLoadedHdl, void * ); virtual void Apply(); void Init(); SvLBoxEntry* DoesBlockExist(const String& sBlock, const String& rShort); void ShowAutoText(const String& rGroup, const String& rShortName); void ResumeShowAutoText(); BOOL GetResumeData(String& rGroup, String& rShortName) {rGroup = sResumeGroup; rShortName = sResumeShortName; return bResume;} void SetResumeData(const String& rGroup, const String& rShortName) {sResumeGroup = rGroup; sResumeShortName = rShortName; bResume = TRUE;} void ResetResumeData() {bResume = FALSE;} public: SwGlossaryDlg(SfxViewFrame* pViewFrame, SwGlossaryHdl* pGlosHdl, SwWrtShell *pWrtShell); ~SwGlossaryDlg(); String GetCurrGrpName() const; inline String GetCurrLongName() const; inline String GetCurrShortName() const; static String GetCurrGroup(); static void SetActGroup(const String& rNewGroup); static String GetExtension(); }; inline String SwGlossaryDlg::GetCurrLongName() const { return aNameED.GetText(); } inline String SwGlossaryDlg::GetCurrShortName() const { return aShortNameEdit.GetText(); } #endif <commit_msg>INTEGRATION: CWS sixtyfour11 (1.9.228); FILE MERGED 2007/03/12 16:39:23 kendy 1.9.228.1: #i75331# Don't introduce new virtual methods where they should be overridden.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: glossary.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2007-04-25 14:48:19 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _GLOSSARY_HXX #define _GLOSSARY_HXX #ifndef _EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _SVTREEBOX_HXX //autogen #include <svtools/svtreebx.hxx> #endif #ifndef _SVX_STDDLG_HXX //autogen #include <svx/stddlg.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _COMBOBOX_HXX //autogen #include <vcl/combobox.hxx> #endif #ifndef _MENUBTN_HXX //autogen #include <vcl/menubtn.hxx> #endif #ifndef _COM_SUN_STAR_CONTAINER_XENUMERATIONACCESS_HPP_ #include <com/sun/star/container/XEnumerationAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_ #include <com/sun/star/container/XHierarchicalNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCONTENTENUMERATIONACCESS_HPP_ #include <com/sun/star/container/XContentEnumerationAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_ #include <com/sun/star/container/XEnumeration.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XELEMENTACCESS_HPP_ #include <com/sun/star/container/XElementAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif class SwGlossaryHdl; class SwNewGlosNameDlg; class SwWrtShell; class SfxViewFrame; class PopupMenu; class Menu; const short RET_EDIT = 100; //------------------------------------------------------------------ class SwGlTreeListBox : public SvTreeListBox { const String sReadonly; SvLBoxEntry* pDragEntry; virtual DragDropMode NotifyStartDrag( TransferDataContainer& rContainer, SvLBoxEntry* ); virtual sal_Bool NotifyAcceptDrop( SvLBoxEntry* ); virtual sal_Bool NotifyMoving( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry, SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos ); virtual sal_Bool NotifyCopying( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry, SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos); public: SwGlTreeListBox(Window* pParent, const ResId& rResId); virtual void RequestHelp( const HelpEvent& rHEvt ); void Clear(); }; //------------------------------------------------------------------ class SwOneExampleFrame; class SwGlossaryDlg : public SvxStandardDialog { friend class SwNewGlosNameDlg; friend class SwGlTreeListBox; CheckBox aInsertTipCB; FixedText aNameLbl; Edit aNameED; FixedText aShortNameLbl; NoSpaceEdit aShortNameEdit; SwGlTreeListBox aCategoryBox; FixedLine aRelativeFL; CheckBox aFileRelCB; CheckBox aNetRelCB; Window aExampleWIN; Window aExampleDummyWIN; CheckBox aShowExampleCB; OKButton aInsertBtn; CancelButton aCloseBtn; HelpButton aHelpBtn; MenuButton aEditBtn; PushButton aBibBtn; PushButton aPathBtn; String sReadonlyPath; ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > _xAutoText; SwOneExampleFrame* pExampleFrame; PopupMenu* pMenu; SwGlossaryHdl* pGlossaryHdl; String sResumeGroup; String sResumeShortName; BOOL bResume; const sal_Bool bSelection : 1; sal_Bool bReadOnly : 1; sal_Bool bIsOld : 1; sal_Bool bIsDocReadOnly:1; SwWrtShell* pSh; void EnableShortName(sal_Bool bOn = sal_True); DECL_LINK( NameModify, Edit * ); DECL_LINK( NameDoubleClick, SvTreeListBox * ); DECL_LINK( GrpSelect, SvTreeListBox * ); DECL_LINK( MenuHdl, Menu * ); DECL_LINK( EnableHdl, Menu * ); DECL_LINK( BibHdl, Button * ); DECL_LINK( EditHdl, Button * ); DECL_LINK( PathHdl, Button * ); DECL_LINK( CheckBoxHdl, CheckBox * ); DECL_LINK( ShowPreviewHdl, CheckBox * ); DECL_LINK( PreviewLoadedHdl, void * ); virtual void Apply(); void Init(); SvLBoxEntry* DoesBlockExist(const String& sBlock, const String& rShort); void ShowAutoText(const String& rGroup, const String& rShortName); void ResumeShowAutoText(); BOOL GetResumeData(String& rGroup, String& rShortName) {rGroup = sResumeGroup; rShortName = sResumeShortName; return bResume;} void SetResumeData(const String& rGroup, const String& rShortName) {sResumeGroup = rGroup; sResumeShortName = rShortName; bResume = TRUE;} void ResetResumeData() {bResume = FALSE;} public: SwGlossaryDlg(SfxViewFrame* pViewFrame, SwGlossaryHdl* pGlosHdl, SwWrtShell *pWrtShell); ~SwGlossaryDlg(); String GetCurrGrpName() const; inline String GetCurrLongName() const; inline String GetCurrShortName() const; static String GetCurrGroup(); static void SetActGroup(const String& rNewGroup); static String GetExtension(); }; inline String SwGlossaryDlg::GetCurrLongName() const { return aNameED.GetText(); } inline String SwGlossaryDlg::GetCurrShortName() const { return aShortNameEdit.GetText(); } #endif <|endoftext|>
<commit_before>#include "bitcoin-config.h" #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #ifdef ENABLE_WALLET #include "paymentservertests.h" #endif #include "uritests.h" #include <QCoreApplication> #include <QObject> #include <QTest> #if defined(QT_STATICPLUGIN) && QT_VERSION < 0x050000 #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) #endif // This is all you need to run all the tests int main(int argc, char *argv[]) { bool fInvalid = false; // Don't remove this, it's needed to access // QCoreApplication:: in the tests QCoreApplication app(argc, argv); app.setApplicationName("Reddcoin-Qt-test"); URITests test1; if (QTest::qExec(&test1) != 0) fInvalid = true; #ifdef ENABLE_WALLET PaymentServerTests test2; if (QTest::qExec(&test2) != 0) fInvalid = true; #endif return fInvalid; } <commit_msg>Update test_main.cpp<commit_after>#if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #ifdef ENABLE_WALLET #include "paymentservertests.h" #endif #include "uritests.h" #include <QCoreApplication> #include <QObject> #include <QTest> #if defined(QT_STATICPLUGIN) && QT_VERSION < 0x050000 #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) #endif // This is all you need to run all the tests int main(int argc, char *argv[]) { bool fInvalid = false; // Don't remove this, it's needed to access // QCoreApplication:: in the tests QCoreApplication app(argc, argv); app.setApplicationName("Reddcoin-Qt-test"); URITests test1; if (QTest::qExec(&test1) != 0) fInvalid = true; #ifdef ENABLE_WALLET PaymentServerTests test2; if (QTest::qExec(&test2) != 0) fInvalid = true; #endif return fInvalid; } <|endoftext|>
<commit_before>// // Copyright (C) 2004, 2005 Pingtel Corp. // // // $$ //////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <assert.h> #include <stdio.h> #if defined(_WIN32) # include <winsock.h> #elif defined(_VXWORKS) # include <inetLib.h> # include <netdb.h> # include <resolvLib.h> # include <sockLib.h> #elif defined(__pingtel_on_posix__) # include <sys/types.h> # include <sys/socket.h> # include <netdb.h> # include <netinet/in.h> # include <arpa/inet.h> #else #error Unsupported target platform. #endif // APPLICATION INCLUDES //SSL related includes #include <openssl/crypto.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/ssl.h> #include <openssl/err.h> #include "utl/UtlSListIterator.h" #include "os/OsSSL.h" #include "os/OsSSLConnectionSocket.h" #include "os/OsUtil.h" #include "os/OsSysLog.h" #include "os/OsTask.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsSSLConnectionSocket::OsSSLConnectionSocket(int connectedSocketDescriptor, long timeoutInSecs) : OsConnectionSocket(NULL, connectedSocketDescriptor), mSSL(NULL), mPeerIdentity(NOT_IDENTIFIED) { if (mIsConnected) { mbExternalSSLSocket = FALSE; SSLInitSocket(connectedSocketDescriptor, timeoutInSecs); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSLConnectionSocket::_(socket %d , timeout %ld)", connectedSocketDescriptor, timeoutInSecs ); } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSLConnectionSocket::_ underlying OsConnectionSocket not connected!!"); } } OsSSLConnectionSocket::OsSSLConnectionSocket(SSL *s, int connectedSocketDescriptor) : OsConnectionSocket(NULL, connectedSocketDescriptor) { mbExternalSSLSocket = TRUE; mSSL = s; socketDescriptor = connectedSocketDescriptor; OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSLConnectionSocket::_(SSL %p, socket %d)", s, connectedSocketDescriptor); } // Constructor OsSSLConnectionSocket::OsSSLConnectionSocket(int serverPort, const char* serverName, long timeoutInSecs) : OsConnectionSocket(serverPort,serverName), mSSL(NULL) { mbExternalSSLSocket = FALSE; if (mIsConnected) { SSLInitSocket(socketDescriptor, timeoutInSecs); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSLConnectionSocket::_(port %d, name '%s', timeout %ld)", serverPort, serverName, timeoutInSecs ); } } // Destructor OsSSLConnectionSocket::~OsSSLConnectionSocket() { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSLConnectionSocket::~" ); remoteHostName = OsUtil::NULL_OS_STRING; mAltNames.destroyAll(); close(); } /* ============================ MANIPULATORS ============================== */ UtlBoolean OsSSLConnectionSocket::reconnect() { return FALSE; //TODO } void OsSSLConnectionSocket::close() { if (mSSL) { if (mIsConnected) SSL_shutdown(mSSL); else SSL_clear(mSSL); } /* Clean up. */ OsConnectionSocket::close(); if (mSSL) { SSL_free(mSSL); ERR_remove_state(0); mSSL = NULL; } } int OsSSLConnectionSocket::write(const char* buffer, int bufferLength) { int bytesWritten = -1; bytesWritten = SSL_write (mSSL, buffer, bufferLength); return(bytesWritten); } int OsSSLConnectionSocket::write(const char* buffer, int bufferLength, long waitMilliseconds) { int bytesWritten = -1; if(isReadyToWrite(waitMilliseconds)) { bytesWritten = SSL_write (mSSL, buffer, bufferLength); } return(bytesWritten); } int OsSSLConnectionSocket::read(char* buffer, int bufferLength) { // Use base class implementation int bytesRead = -1; bytesRead = SSL_read (mSSL, buffer, bufferLength); #ifdef VALGRIND_MAKE_READABLE // If we are using Valgrind, we have to compensate for the fact that // Valgrind thinks all the output of SSL_read is undefined. // (This probably comes from SSL's use of uninitialized memory as part // of its key-generation algorithm.) VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(&bytesRead, sizeof (bytesRead))); if (bytesRead > 0) { VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(buffer, bytesRead)); } #endif /* VALGRIND_MAKE_READABLE */ return(bytesRead); } int OsSSLConnectionSocket::read(char* buffer, int bufferLength, UtlString* ipAddress, int* port) { // Overide base class version as recvfrom does not // seem to return host info correctly for TCP // Use base class version without the remote host info int bytesRead = -1; bytesRead = SSL_read (mSSL, buffer, bufferLength); #ifdef VALGRIND_MAKE_READABLE // If we are using Valgrind, we have to compensate for the fact that // Valgrind thinks all the output of SSL_read is undefined. // (This probably comes from SSL's use of uninitialized memory as part // of its key-generation algorithm.) VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(&bytesRead, sizeof (bytesRead))); if (bytesRead > 0) { VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(buffer, bytesRead)); } #endif /* VALGRIND_MAKE_READABLE */ // Explicitly get the remote host info. getRemoteHostIp(ipAddress); *port = getRemoteHostPort(); return(bytesRead); } // Because we have overided one read method, we // must implement them all in OsSSLConnectionSocket or // we end up hiding some of the methods. int OsSSLConnectionSocket::read(char* buffer, int bufferLength, long waitMilliseconds) { int bytesRead = -1; if(isReadyToRead(waitMilliseconds)) { bytesRead = SSL_read (mSSL, buffer, bufferLength); } #ifdef VALGRIND_MAKE_READABLE // If we are using Valgrind, we have to compensate for the fact that // Valgrind thinks all the output of SSL_read is undefined. // (This probably comes from SSL's use of uninitialized memory as part // of its key-generation algorithm.) VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(&bytesRead, sizeof (bytesRead))); if (bytesRead > 0) { VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(buffer, bytesRead)); } #endif /* VALGRIND_MAKE_READABLE */ return(bytesRead); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ OsSocket::IpProtocolSocketType OsSSLConnectionSocket::getIpProtocol() const { return(OsSocket::SSL_SOCKET); } /// Is this connection encrypted using TLS/SSL? bool OsSSLConnectionSocket::isEncrypted() const { return true; } /// Get any authenticated peer host names. bool OsSSLConnectionSocket::peerIdentity( UtlSList* altNames ,UtlString* commonName ) const { if (NOT_IDENTIFIED == mPeerIdentity) { // examine cert to get identity and cache the results mPeerIdentity = OsSSL::peerIdentity( mSSL, &mAltNames, &mCommonName ) ? TRUSTED : UNTRUSTED; if ( TRUSTED == mPeerIdentity ) { OsSysLog::add(FAC_SIP, PRI_INFO, "OsSSLConnectionSocket::peerIdentity %p OsSSL returned trusted", this); } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "OsSSLConnectionSocket::peerIdentity %p OsSSL returned NOT trusted", this); } } /* * - true if the connection is TLS/SSL and the peer has presented * a certificate signed by a trusted certificate authority * - false if not */ if (commonName) { commonName->remove(0); } if (altNames) { altNames->destroyAll(); } if (TRUSTED == mPeerIdentity) { if (commonName) { *commonName = mCommonName; } if (altNames) { UtlString* altName; UtlSListIterator names(mAltNames); while ( (altName = dynamic_cast<UtlString*>(names())) ) { altNames->insert(new UtlString(*altName)); } } } return TRUSTED == mPeerIdentity; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ void OsSSLConnectionSocket::SSLInitSocket(int socket, long timeoutInSecs) { if (mIsConnected) { int err = -1; // TODO: eventually this should allow for other SSL contexts... mSSL = OsSharedSSL::get()->getServerConnection(); if (mSSL && (socketDescriptor > OS_INVALID_SOCKET_DESCRIPTOR)) { SSL_set_fd (mSSL, socketDescriptor); err = SSL_connect(mSSL); if (err > 0) { OsSSL::logConnectParams(FAC_KERNEL, PRI_DEBUG, "OsSSLConnectionSocket", mSSL); } else { OsSSL::logError(FAC_KERNEL, PRI_ERR, "OsSSLConnectionSocket SSL_connect failed: ", SSL_get_error(mSSL, err)); mIsConnected = FALSE; OsConnectionSocket::close(); socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; } } else { OsSysLog::add(FAC_KERNEL, PRI_DEBUG , "OsSSLConnectionSocket bad parameters mSSL=%p,%d, closing socket..." , mSSL, socketDescriptor); mIsConnected = FALSE; OsConnectionSocket::close(); socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; } } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSLConnectionSocket::SSLInitSocket called on unconnected socket" ); } } /* ============================ FUNCTIONS ================================= */ <commit_msg>[XPL-181] Fix connection peer caching (Initialize OsSSLConnectionSocket::mPeerIdentity in all constructors). Thanks to Dale for finding this.<commit_after>// // Copyright (C) 2004, 2005 Pingtel Corp. // // // $$ //////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <assert.h> #include <stdio.h> #if defined(_WIN32) # include <winsock.h> #elif defined(_VXWORKS) # include <inetLib.h> # include <netdb.h> # include <resolvLib.h> # include <sockLib.h> #elif defined(__pingtel_on_posix__) # include <sys/types.h> # include <sys/socket.h> # include <netdb.h> # include <netinet/in.h> # include <arpa/inet.h> #else #error Unsupported target platform. #endif // APPLICATION INCLUDES //SSL related includes #include <openssl/crypto.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/ssl.h> #include <openssl/err.h> #include "utl/UtlSListIterator.h" #include "os/OsSSL.h" #include "os/OsSSLConnectionSocket.h" #include "os/OsUtil.h" #include "os/OsSysLog.h" #include "os/OsTask.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsSSLConnectionSocket::OsSSLConnectionSocket(int connectedSocketDescriptor, long timeoutInSecs) : OsConnectionSocket(NULL, connectedSocketDescriptor), mSSL(NULL), mPeerIdentity(NOT_IDENTIFIED) { if (mIsConnected) { mbExternalSSLSocket = FALSE; SSLInitSocket(connectedSocketDescriptor, timeoutInSecs); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSLConnectionSocket::_(socket %d , timeout %ld)", connectedSocketDescriptor, timeoutInSecs ); } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSLConnectionSocket::_ underlying OsConnectionSocket not connected!!"); } } OsSSLConnectionSocket::OsSSLConnectionSocket(SSL *s, int connectedSocketDescriptor) : OsConnectionSocket(NULL, connectedSocketDescriptor), mSSL(s), mPeerIdentity(NOT_IDENTIFIED) { mbExternalSSLSocket = TRUE; socketDescriptor = connectedSocketDescriptor; OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSLConnectionSocket::_(SSL %p, socket %d)", s, connectedSocketDescriptor); } // Constructor OsSSLConnectionSocket::OsSSLConnectionSocket(int serverPort, const char* serverName, long timeoutInSecs) : OsConnectionSocket(serverPort,serverName), mSSL(NULL), mPeerIdentity(NOT_IDENTIFIED) { mbExternalSSLSocket = FALSE; if (mIsConnected) { SSLInitSocket(socketDescriptor, timeoutInSecs); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSLConnectionSocket::_(port %d, name '%s', timeout %ld)", serverPort, serverName, timeoutInSecs ); } } // Destructor OsSSLConnectionSocket::~OsSSLConnectionSocket() { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSLConnectionSocket::~" ); remoteHostName = OsUtil::NULL_OS_STRING; mAltNames.destroyAll(); close(); } /* ============================ MANIPULATORS ============================== */ UtlBoolean OsSSLConnectionSocket::reconnect() { return FALSE; //TODO } void OsSSLConnectionSocket::close() { if (mSSL) { if (mIsConnected) SSL_shutdown(mSSL); else SSL_clear(mSSL); } /* Clean up. */ OsConnectionSocket::close(); if (mSSL) { SSL_free(mSSL); ERR_remove_state(0); mSSL = NULL; } } int OsSSLConnectionSocket::write(const char* buffer, int bufferLength) { int bytesWritten = -1; bytesWritten = SSL_write (mSSL, buffer, bufferLength); return(bytesWritten); } int OsSSLConnectionSocket::write(const char* buffer, int bufferLength, long waitMilliseconds) { int bytesWritten = -1; if(isReadyToWrite(waitMilliseconds)) { bytesWritten = SSL_write (mSSL, buffer, bufferLength); } return(bytesWritten); } int OsSSLConnectionSocket::read(char* buffer, int bufferLength) { // Use base class implementation int bytesRead = -1; bytesRead = SSL_read (mSSL, buffer, bufferLength); #ifdef VALGRIND_MAKE_READABLE // If we are using Valgrind, we have to compensate for the fact that // Valgrind thinks all the output of SSL_read is undefined. // (This probably comes from SSL's use of uninitialized memory as part // of its key-generation algorithm.) VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(&bytesRead, sizeof (bytesRead))); if (bytesRead > 0) { VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(buffer, bytesRead)); } #endif /* VALGRIND_MAKE_READABLE */ return(bytesRead); } int OsSSLConnectionSocket::read(char* buffer, int bufferLength, UtlString* ipAddress, int* port) { // Overide base class version as recvfrom does not // seem to return host info correctly for TCP // Use base class version without the remote host info int bytesRead = -1; bytesRead = SSL_read (mSSL, buffer, bufferLength); #ifdef VALGRIND_MAKE_READABLE // If we are using Valgrind, we have to compensate for the fact that // Valgrind thinks all the output of SSL_read is undefined. // (This probably comes from SSL's use of uninitialized memory as part // of its key-generation algorithm.) VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(&bytesRead, sizeof (bytesRead))); if (bytesRead > 0) { VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(buffer, bytesRead)); } #endif /* VALGRIND_MAKE_READABLE */ // Explicitly get the remote host info. getRemoteHostIp(ipAddress); *port = getRemoteHostPort(); return(bytesRead); } // Because we have overided one read method, we // must implement them all in OsSSLConnectionSocket or // we end up hiding some of the methods. int OsSSLConnectionSocket::read(char* buffer, int bufferLength, long waitMilliseconds) { int bytesRead = -1; if(isReadyToRead(waitMilliseconds)) { bytesRead = SSL_read (mSSL, buffer, bufferLength); } #ifdef VALGRIND_MAKE_READABLE // If we are using Valgrind, we have to compensate for the fact that // Valgrind thinks all the output of SSL_read is undefined. // (This probably comes from SSL's use of uninitialized memory as part // of its key-generation algorithm.) VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(&bytesRead, sizeof (bytesRead))); if (bytesRead > 0) { VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(buffer, bytesRead)); } #endif /* VALGRIND_MAKE_READABLE */ return(bytesRead); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ OsSocket::IpProtocolSocketType OsSSLConnectionSocket::getIpProtocol() const { return(OsSocket::SSL_SOCKET); } /// Is this connection encrypted using TLS/SSL? bool OsSSLConnectionSocket::isEncrypted() const { return true; } /// Get any authenticated peer host names. bool OsSSLConnectionSocket::peerIdentity( UtlSList* altNames ,UtlString* commonName ) const { if (NOT_IDENTIFIED == mPeerIdentity) { // examine cert to get identity and cache the results mPeerIdentity = OsSSL::peerIdentity( mSSL, &mAltNames, &mCommonName ) ? TRUSTED : UNTRUSTED; if ( TRUSTED == mPeerIdentity ) { OsSysLog::add(FAC_SIP, PRI_INFO, "OsSSLConnectionSocket::peerIdentity %p OsSSL returned trusted", this); } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "OsSSLConnectionSocket::peerIdentity %p OsSSL returned NOT trusted", this); } } /* * - true if the connection is TLS/SSL and the peer has presented * a certificate signed by a trusted certificate authority * - false if not */ if (commonName) { commonName->remove(0); } if (altNames) { altNames->destroyAll(); } if (TRUSTED == mPeerIdentity) { if (commonName) { *commonName = mCommonName; } if (altNames) { UtlString* altName; UtlSListIterator names(mAltNames); while ( (altName = dynamic_cast<UtlString*>(names())) ) { altNames->insert(new UtlString(*altName)); } } } return TRUSTED == mPeerIdentity; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ void OsSSLConnectionSocket::SSLInitSocket(int socket, long timeoutInSecs) { if (mIsConnected) { int err = -1; // TODO: eventually this should allow for other SSL contexts... mSSL = OsSharedSSL::get()->getServerConnection(); if (mSSL && (socketDescriptor > OS_INVALID_SOCKET_DESCRIPTOR)) { SSL_set_fd (mSSL, socketDescriptor); err = SSL_connect(mSSL); if (err > 0) { OsSSL::logConnectParams(FAC_KERNEL, PRI_DEBUG, "OsSSLConnectionSocket", mSSL); } else { OsSSL::logError(FAC_KERNEL, PRI_ERR, "OsSSLConnectionSocket SSL_connect failed: ", SSL_get_error(mSSL, err)); mIsConnected = FALSE; OsConnectionSocket::close(); socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; } } else { OsSysLog::add(FAC_KERNEL, PRI_DEBUG , "OsSSLConnectionSocket bad parameters mSSL=%p,%d, closing socket..." , mSSL, socketDescriptor); mIsConnected = FALSE; OsConnectionSocket::close(); socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; } } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSLConnectionSocket::SSLInitSocket called on unconnected socket" ); } } /* ============================ FUNCTIONS ================================= */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: glshell.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: hr $ $Date: 2006-08-14 17:49:26 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #pragma hdrstop #ifndef _LIST_HXX //autogen #include <tools/list.hxx> #endif #ifndef _SFXENUMITEM_HXX //autogen #include <svtools/eitem.hxx> #endif #ifndef _SFXSTRITEM_HXX //autogen #include <svtools/stritem.hxx> #endif #ifndef _SFX_PRINTER_HXX //autogen #include <sfx2/printer.hxx> #endif #ifndef _SFXREQUEST_HXX //autogen #include <sfx2/request.hxx> #endif #ifndef _SFXSIDS_HRC //autogen #include <sfx2/sfxsids.hrc> #endif #ifndef _SVX_SRCHITEM_HXX #include <svx/srchitem.hxx> #endif #ifndef _SFXMACITEM_HXX #include <svtools/macitem.hxx> #endif #ifndef _GLOSHDL_HXX #include <gloshdl.hxx> #endif #include <svx/acorrcfg.hxx> #include <sfx2/app.hxx> #include <sfx2/objface.hxx> #include <sfx2/viewfrm.hxx> #ifndef _UITOOL_HXX #include <uitool.hxx> #endif #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _VIEW_HXX #include <view.hxx> #endif #ifndef _GLSHELL_HXX #include <glshell.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _GLOSDOC_HXX #include <glosdoc.hxx> #endif #ifndef _SHELLIO_HXX #include <shellio.hxx> #endif #ifndef _INITUI_HXX #include <initui.hxx> // fuer ::GetGlossaries() #endif #ifndef _CMDID_H #include <cmdid.h> #endif #ifndef _SWERROR_H #include <swerror.h> #endif #ifndef _MISC_HRC #include <misc.hrc> #endif #define SwWebGlosDocShell #define SwGlosDocShell #ifndef _ITEMDEF_HXX #include <itemdef.hxx> #endif #ifndef _SWSLOTS_HXX #include <swslots.hxx> #endif SFX_IMPL_INTERFACE( SwGlosDocShell, SwDocShell, SW_RES(0) ) { } SFX_IMPL_INTERFACE( SwWebGlosDocShell, SwWebDocShell, SW_RES(0) ) { } TYPEINIT1( SwGlosDocShell, SwDocShell ); TYPEINIT1( SwWebGlosDocShell, SwWebDocShell ); void lcl_Execute( SwDocShell& rSh, SfxRequest& rReq ) { if ( rReq.GetSlot() == SID_SAVEDOC ) { if( !rSh.HasName() ) { rReq.SetReturnValue( SfxBoolItem( 0, rSh.Save() ) ); } else { const SfxBoolItem* pRes = ( const SfxBoolItem* ) rSh.ExecuteSlot( rReq, rSh.SfxObjectShell::GetInterface() ); if( pRes->GetValue() ) rSh.GetDoc()->ResetModified(); } } } void lcl_GetState( SwDocShell& rSh, SfxItemSet& rSet ) { if( SFX_ITEM_AVAILABLE >= rSet.GetItemState( SID_SAVEDOC, FALSE )) { if( !rSh.GetDoc()->IsModified() ) rSet.DisableItem( SID_SAVEDOC ); else rSet.Put( SfxStringItem( SID_SAVEDOC, SW_RESSTR(STR_SAVE_GLOSSARY))); } } BOOL lcl_Save( SwWrtShell& rSh, const String& rGroupName, const String& rShortNm, const String& rLongNm ) { const SvxAutoCorrCfg* pCfg = SvxAutoCorrCfg::Get(); SwTextBlocks * pBlock = ::GetGlossaries()->GetGroupDoc( rGroupName ); SvxMacro aStart(aEmptyStr, aEmptyStr); SvxMacro aEnd(aEmptyStr, aEmptyStr); SwGlossaryHdl* pGlosHdl; pGlosHdl = rSh.GetView().GetGlosHdl(); pGlosHdl->GetMacros( rShortNm, aStart, aEnd, pBlock ); USHORT nRet = rSh.SaveGlossaryDoc( *pBlock, rLongNm, rShortNm, pCfg->IsSaveRelFile(), pCfg->IsSaveRelNet(), pBlock->IsOnlyTextBlock( rShortNm ) ); if(aStart.GetMacName().Len() || aEnd.GetMacName().Len() ) { SvxMacro* pStart = aStart.GetMacName().Len() ? &aStart : 0; SvxMacro* pEnd = aEnd.GetMacName().Len() ? &aEnd : 0; pGlosHdl->SetMacros( rShortNm, pStart, pEnd, pBlock ); } rSh.EnterStdMode(); if( USHRT_MAX != nRet ) rSh.ResetModified(); delete pBlock; return nRet != USHRT_MAX; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ SwGlosDocShell::SwGlosDocShell( sal_Bool bNewShow) : bShow ( bNewShow ) , SwDocShell( bShow ? SFX_CREATE_MODE_STANDARD : SFX_CREATE_MODE_INTERNAL ) { SetHelpId(SW_GLOSDOCSHELL); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ SwGlosDocShell::~SwGlosDocShell( ) { } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void SwGlosDocShell::Execute( SfxRequest& rReq ) { ::lcl_Execute( *this, rReq ); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void SwGlosDocShell::GetState( SfxItemSet& rSet ) { ::lcl_GetState( *this, rSet ); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ BOOL SwGlosDocShell::Save() { // In case of an API object which holds this document, it is possible that the WrtShell is already // dead. For instance, if the doc is modified via this API object, and then, upon office shutdown, // the document's view is closed (by the SFX framework) _before_ the API object is release and // tries to save the doc, again. // 96380 - 2002-03-03 - fs@openoffice.org if ( GetWrtShell() ) return ::lcl_Save( *GetWrtShell(), aGroupName, aShortName, aLongName ); else { SetModified( FALSE ); return FALSE; } } /* */ /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ SwWebGlosDocShell::SwWebGlosDocShell() : SwWebDocShell( SFX_CREATE_MODE_STANDARD ) { SetHelpId(SW_WEBGLOSDOCSHELL); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ SwWebGlosDocShell::~SwWebGlosDocShell( ) { } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void SwWebGlosDocShell::Execute( SfxRequest& rReq ) { ::lcl_Execute( *this, rReq ); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void SwWebGlosDocShell::GetState( SfxItemSet& rSet ) { ::lcl_GetState( *this, rSet ); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ BOOL SwWebGlosDocShell::Save() { // same comment as in SwGlosDocShell::Save - see there if ( GetWrtShell() ) return ::lcl_Save( *GetWrtShell(), aGroupName, aShortName, aLongName ); else { SetModified( FALSE ); return FALSE; } } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ SV_IMPL_REF ( SwDocShell ) SwDocShellRef SwGlossaries::EditGroupDoc( const String& rGroup, const String& rShortName, BOOL bShow ) { SwDocShellRef xDocSh; SwTextBlocks* pGroup = GetGroupDoc( rGroup ); if( pGroup && pGroup->GetCount() ) { // erfrage welche View registriert ist. Im WebWriter gibts es keine // normale View USHORT nViewId = 0 != &SwView::Factory() ? 2 : 6; String sLongName = pGroup->GetLongName(pGroup->GetIndex( rShortName )); if( 6 == nViewId ) { SwWebGlosDocShell* pDocSh = new SwWebGlosDocShell(); xDocSh = pDocSh; pDocSh->DoInitNew( 0 ); pDocSh->SetLongName( sLongName ); pDocSh->SetShortName( rShortName); pDocSh->SetGroupName( rGroup ); } else { SwGlosDocShell* pDocSh = new SwGlosDocShell(bShow); xDocSh = pDocSh; pDocSh->DoInitNew( 0 ); pDocSh->SetLongName( sLongName ); pDocSh->SetShortName( rShortName ); pDocSh->SetGroupName( rGroup ); } // Dokumenttitel setzen SfxViewFrame* pFrame = SfxViewFrame::CreateViewFrame( *xDocSh, nViewId, !bShow ); String aDocTitle(SW_RES( STR_GLOSSARY )); aDocTitle += ' '; aDocTitle += sLongName; BOOL bDoesUndo = xDocSh->GetDoc()->DoesUndo(); xDocSh->GetDoc()->DoUndo( FALSE ); xDocSh->GetWrtShell()->InsertGlossary( *pGroup, rShortName ); if( !xDocSh->GetDoc()->getPrinter( false ) ) { // wir erzeugen einen default SfxPrinter. // Das ItemSet wird vom Sfx geloescht! SfxItemSet *pSet = new SfxItemSet( xDocSh->GetDoc()->GetAttrPool(), FN_PARAM_ADDPRINTER, FN_PARAM_ADDPRINTER, SID_PRINTER_NOTFOUND_WARN, SID_PRINTER_NOTFOUND_WARN, SID_PRINTER_CHANGESTODOC, SID_PRINTER_CHANGESTODOC, 0 ); SfxPrinter* pPrinter = new SfxPrinter( pSet ); // und haengen ihn ans Dokument. xDocSh->GetDoc()->setPrinter( pPrinter, true, true ); } xDocSh->SetTitle( aDocTitle ); xDocSh->GetDoc()->DoUndo( bDoesUndo ); xDocSh->GetDoc()->ResetModified(); if ( bShow ) pFrame->GetFrame()->Appear(); delete pGroup; } return xDocSh; } <commit_msg>INTEGRATION: CWS pchfix02 (1.14.2); FILE MERGED 2006/09/01 17:53:14 kaib 1.14.2.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: glshell.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: obo $ $Date: 2006-09-16 23:07:18 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _LIST_HXX //autogen #include <tools/list.hxx> #endif #ifndef _SFXENUMITEM_HXX //autogen #include <svtools/eitem.hxx> #endif #ifndef _SFXSTRITEM_HXX //autogen #include <svtools/stritem.hxx> #endif #ifndef _SFX_PRINTER_HXX //autogen #include <sfx2/printer.hxx> #endif #ifndef _SFXREQUEST_HXX //autogen #include <sfx2/request.hxx> #endif #ifndef _SFXSIDS_HRC //autogen #include <sfx2/sfxsids.hrc> #endif #ifndef _SVX_SRCHITEM_HXX #include <svx/srchitem.hxx> #endif #ifndef _SFXMACITEM_HXX #include <svtools/macitem.hxx> #endif #ifndef _GLOSHDL_HXX #include <gloshdl.hxx> #endif #include <svx/acorrcfg.hxx> #include <sfx2/app.hxx> #include <sfx2/objface.hxx> #include <sfx2/viewfrm.hxx> #ifndef _UITOOL_HXX #include <uitool.hxx> #endif #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _VIEW_HXX #include <view.hxx> #endif #ifndef _GLSHELL_HXX #include <glshell.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _GLOSDOC_HXX #include <glosdoc.hxx> #endif #ifndef _SHELLIO_HXX #include <shellio.hxx> #endif #ifndef _INITUI_HXX #include <initui.hxx> // fuer ::GetGlossaries() #endif #ifndef _CMDID_H #include <cmdid.h> #endif #ifndef _SWERROR_H #include <swerror.h> #endif #ifndef _MISC_HRC #include <misc.hrc> #endif #define SwWebGlosDocShell #define SwGlosDocShell #ifndef _ITEMDEF_HXX #include <itemdef.hxx> #endif #ifndef _SWSLOTS_HXX #include <swslots.hxx> #endif SFX_IMPL_INTERFACE( SwGlosDocShell, SwDocShell, SW_RES(0) ) { } SFX_IMPL_INTERFACE( SwWebGlosDocShell, SwWebDocShell, SW_RES(0) ) { } TYPEINIT1( SwGlosDocShell, SwDocShell ); TYPEINIT1( SwWebGlosDocShell, SwWebDocShell ); void lcl_Execute( SwDocShell& rSh, SfxRequest& rReq ) { if ( rReq.GetSlot() == SID_SAVEDOC ) { if( !rSh.HasName() ) { rReq.SetReturnValue( SfxBoolItem( 0, rSh.Save() ) ); } else { const SfxBoolItem* pRes = ( const SfxBoolItem* ) rSh.ExecuteSlot( rReq, rSh.SfxObjectShell::GetInterface() ); if( pRes->GetValue() ) rSh.GetDoc()->ResetModified(); } } } void lcl_GetState( SwDocShell& rSh, SfxItemSet& rSet ) { if( SFX_ITEM_AVAILABLE >= rSet.GetItemState( SID_SAVEDOC, FALSE )) { if( !rSh.GetDoc()->IsModified() ) rSet.DisableItem( SID_SAVEDOC ); else rSet.Put( SfxStringItem( SID_SAVEDOC, SW_RESSTR(STR_SAVE_GLOSSARY))); } } BOOL lcl_Save( SwWrtShell& rSh, const String& rGroupName, const String& rShortNm, const String& rLongNm ) { const SvxAutoCorrCfg* pCfg = SvxAutoCorrCfg::Get(); SwTextBlocks * pBlock = ::GetGlossaries()->GetGroupDoc( rGroupName ); SvxMacro aStart(aEmptyStr, aEmptyStr); SvxMacro aEnd(aEmptyStr, aEmptyStr); SwGlossaryHdl* pGlosHdl; pGlosHdl = rSh.GetView().GetGlosHdl(); pGlosHdl->GetMacros( rShortNm, aStart, aEnd, pBlock ); USHORT nRet = rSh.SaveGlossaryDoc( *pBlock, rLongNm, rShortNm, pCfg->IsSaveRelFile(), pCfg->IsSaveRelNet(), pBlock->IsOnlyTextBlock( rShortNm ) ); if(aStart.GetMacName().Len() || aEnd.GetMacName().Len() ) { SvxMacro* pStart = aStart.GetMacName().Len() ? &aStart : 0; SvxMacro* pEnd = aEnd.GetMacName().Len() ? &aEnd : 0; pGlosHdl->SetMacros( rShortNm, pStart, pEnd, pBlock ); } rSh.EnterStdMode(); if( USHRT_MAX != nRet ) rSh.ResetModified(); delete pBlock; return nRet != USHRT_MAX; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ SwGlosDocShell::SwGlosDocShell( sal_Bool bNewShow) : bShow ( bNewShow ) , SwDocShell( bShow ? SFX_CREATE_MODE_STANDARD : SFX_CREATE_MODE_INTERNAL ) { SetHelpId(SW_GLOSDOCSHELL); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ SwGlosDocShell::~SwGlosDocShell( ) { } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void SwGlosDocShell::Execute( SfxRequest& rReq ) { ::lcl_Execute( *this, rReq ); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void SwGlosDocShell::GetState( SfxItemSet& rSet ) { ::lcl_GetState( *this, rSet ); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ BOOL SwGlosDocShell::Save() { // In case of an API object which holds this document, it is possible that the WrtShell is already // dead. For instance, if the doc is modified via this API object, and then, upon office shutdown, // the document's view is closed (by the SFX framework) _before_ the API object is release and // tries to save the doc, again. // 96380 - 2002-03-03 - fs@openoffice.org if ( GetWrtShell() ) return ::lcl_Save( *GetWrtShell(), aGroupName, aShortName, aLongName ); else { SetModified( FALSE ); return FALSE; } } /* */ /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ SwWebGlosDocShell::SwWebGlosDocShell() : SwWebDocShell( SFX_CREATE_MODE_STANDARD ) { SetHelpId(SW_WEBGLOSDOCSHELL); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ SwWebGlosDocShell::~SwWebGlosDocShell( ) { } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void SwWebGlosDocShell::Execute( SfxRequest& rReq ) { ::lcl_Execute( *this, rReq ); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void SwWebGlosDocShell::GetState( SfxItemSet& rSet ) { ::lcl_GetState( *this, rSet ); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ BOOL SwWebGlosDocShell::Save() { // same comment as in SwGlosDocShell::Save - see there if ( GetWrtShell() ) return ::lcl_Save( *GetWrtShell(), aGroupName, aShortName, aLongName ); else { SetModified( FALSE ); return FALSE; } } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ SV_IMPL_REF ( SwDocShell ) SwDocShellRef SwGlossaries::EditGroupDoc( const String& rGroup, const String& rShortName, BOOL bShow ) { SwDocShellRef xDocSh; SwTextBlocks* pGroup = GetGroupDoc( rGroup ); if( pGroup && pGroup->GetCount() ) { // erfrage welche View registriert ist. Im WebWriter gibts es keine // normale View USHORT nViewId = 0 != &SwView::Factory() ? 2 : 6; String sLongName = pGroup->GetLongName(pGroup->GetIndex( rShortName )); if( 6 == nViewId ) { SwWebGlosDocShell* pDocSh = new SwWebGlosDocShell(); xDocSh = pDocSh; pDocSh->DoInitNew( 0 ); pDocSh->SetLongName( sLongName ); pDocSh->SetShortName( rShortName); pDocSh->SetGroupName( rGroup ); } else { SwGlosDocShell* pDocSh = new SwGlosDocShell(bShow); xDocSh = pDocSh; pDocSh->DoInitNew( 0 ); pDocSh->SetLongName( sLongName ); pDocSh->SetShortName( rShortName ); pDocSh->SetGroupName( rGroup ); } // Dokumenttitel setzen SfxViewFrame* pFrame = SfxViewFrame::CreateViewFrame( *xDocSh, nViewId, !bShow ); String aDocTitle(SW_RES( STR_GLOSSARY )); aDocTitle += ' '; aDocTitle += sLongName; BOOL bDoesUndo = xDocSh->GetDoc()->DoesUndo(); xDocSh->GetDoc()->DoUndo( FALSE ); xDocSh->GetWrtShell()->InsertGlossary( *pGroup, rShortName ); if( !xDocSh->GetDoc()->getPrinter( false ) ) { // wir erzeugen einen default SfxPrinter. // Das ItemSet wird vom Sfx geloescht! SfxItemSet *pSet = new SfxItemSet( xDocSh->GetDoc()->GetAttrPool(), FN_PARAM_ADDPRINTER, FN_PARAM_ADDPRINTER, SID_PRINTER_NOTFOUND_WARN, SID_PRINTER_NOTFOUND_WARN, SID_PRINTER_CHANGESTODOC, SID_PRINTER_CHANGESTODOC, 0 ); SfxPrinter* pPrinter = new SfxPrinter( pSet ); // und haengen ihn ans Dokument. xDocSh->GetDoc()->setPrinter( pPrinter, true, true ); } xDocSh->SetTitle( aDocTitle ); xDocSh->GetDoc()->DoUndo( bDoesUndo ); xDocSh->GetDoc()->ResetModified(); if ( bShow ) pFrame->GetFrame()->Appear(); delete pGroup; } return xDocSh; } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_INTERFACES_HH #define DUNE_GDT_OPERATORS_INTERFACES_HH #include <type_traits> #include <dune/common/dynmatrix.hh> #include <dune/common/fvector.hh> #include <dune/stuff/common/crtp.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/la/container/interfaces.hh> #include <dune/stuff/la/container/pattern.hh> #include <dune/stuff/la/solver.hh> #include <dune/stuff/common/configuration.hh> #include <dune/gdt/spaces/interface.hh> #include <dune/gdt/discretefunction/default.hh> #include "../products/interfaces.hh" namespace Dune { namespace GDT { template <class Traits> class OperatorInterface : public ProductInterface<Traits> { typedef ProductInterface<Traits> BaseType; public: using typename BaseType::GridViewType; using typename BaseType::FieldType; template <class SourceType, class RangeType> void apply(const SourceType& source, RangeType& range) const { CHECK_CRTP(this->as_imp(*this).apply(source, range)); return this->as_imp(*this).apply(source, range); } template <class S, class R> FieldType apply2(const Stuff::LA::VectorInterface<S, FieldType>& source, const Stuff::LA::VectorInterface<R, FieldType>& range) const { auto tmp = range.copy(); apply(source.as_imp(source), tmp); return range.dot(tmp); } // ... apply2(...) template <class SS, class SV, class RS, class RV> FieldType apply2(const ConstDiscreteFunction<SS, SV>& source, const ConstDiscreteFunction<RS, RV>& range) const { auto tmp_vector = range.copy(); DiscreteFunction<RS, RV> tmp_function(range.space(), tmp_vector); apply(source, tmp_function); return range.vector().dot(tmp_vector); } }; // class OperatorInterface template <class Traits> class LocalizableOperatorInterface : public Stuff::CRTPInterface<LocalizableOperatorInterface<Traits>, Traits> { typedef typename Traits::derived_type derived_type; typedef typename Traits::GridViewType GridViewType; typedef typename Traits::SourceType SourceType; typedef typename Traits::RangeType RangeType; typedef typename Traits::FieldType FieldType; typedef typename GridViewType::template Codim<0>::Entity EntityType; typedef typename GridViewType::ctype DomainFieldType; static const unsigned int dimDomain = GridViewType::dimension; private: static_assert(std::is_base_of<Stuff::IsLocalizableFunction, SourceType>::value, "SourceType has to be derived from Stuff::IsLocalizableFunction!"); static_assert(std::is_base_of<DiscreteFunction<typename RangeType::SpaceType, typename RangeType::VectorType>, RangeType>::value, "RangeType has to be derived from DiscreteFunction!"); static_assert(std::is_same<typename SourceType::EntityType, EntityType>::value, "The EntityType of SourceType and GridViewType have to match!"); static_assert(std::is_same<typename RangeType::EntityType, EntityType>::value, "The EntityType of RangeType and GridViewType have to match!"); static_assert(std::is_same<typename SourceType::DomainFieldType, DomainFieldType>::value, "The DomainFieldType of SourceType and GridViewType have to match!"); static_assert(std::is_same<typename RangeType::DomainFieldType, DomainFieldType>::value, "The DomainFieldType of RangeType and GridViewType have to match!"); static_assert(SourceType::dimDomain == dimDomain, "The dimDomain of SourceType and GridViewType have to match!"); static_assert(RangeType::dimDomain == dimDomain, "The dimDomain of RangeType and GridViewType have to match!"); public: const GridViewType& grid_view() const { CHECK_CRTP(this->as_imp(*this).grid_view()); return this->as_imp(*this).grid_view(); } const SourceType& source() const { CHECK_CRTP(this->as_imp(*this).source()); return this->as_imp(*this).source(); } const RangeType& range() const { CHECK_CRTP(this->as_imp(*this).range()); return this->as_imp(*this).range(); } RangeType& range() { CHECK_CRTP(this->as_imp(*this).range()); return this->as_imp(*this).range(); } void apply() { CHECK_AND_CALL_CRTP(this->as_imp(*this).apply()); } }; // class LocalizableOperatorInterface template <class Traits> class AssemblableOperatorInterface : public AssemblableProductInterface<Traits> { typedef AssemblableProductInterface<Traits> BaseType; public: typedef typename BaseType::derived_type derived_type; using typename BaseType::GridViewType; using typename BaseType::FieldType; using typename BaseType::SourceSpaceType; using typename BaseType::RangeSpaceType; using typename BaseType::MatrixType; using typename BaseType::EntityType; using typename BaseType::DomainFieldType; using BaseType::dimDomain; using typename BaseType::PatternType; template <class S, class R> void apply(const Stuff::LA::VectorInterface<S, DomainFieldType>& source, Stuff::LA::VectorInterface<R, FieldType>& range) { CHECK_CRTP(this->as_imp().apply(source.as_imp(), range.as_imp())); return this->as_imp().apply(source.as_imp(), range.as_imp()); } template <class S, class R> void apply(const ConstDiscreteFunction<SourceSpaceType, S>& source, ConstDiscreteFunction<RangeSpaceType, R>& range) { apply(source.vector(), range.vector()); } static std::vector<std::string> invert_options() { return derived_type::invert_options(); } static Stuff::Common::Configuration invert_options(const std::string& type) { return derived_type::invert_options(type); } template <class R, class S> void apply_inverse(const Stuff::LA::VectorInterface<R, FieldType>& range, const Stuff::LA::VectorInterface<S, FieldType>& source) { apply_inverse(range, source, invert_options()[0]); } template <class R, class S> void apply_inverse(const Stuff::LA::VectorInterface<R, FieldType>& range, Stuff::LA::VectorInterface<S, FieldType>& source, const std::string& opt) { apply_inverse(range, source, invert_options(opt)); } template <class R, class S> void apply_inverse(const Stuff::LA::VectorInterface<R, FieldType>& range, Stuff::LA::VectorInterface<S, FieldType>& source, const Stuff::Common::Configuration& opts) { CHECK_CRTP(this->as_imp(*this).apply_inverse(range.as_imp(range), source.as_imp(source), opts)); return this->as_imp(*this).apply_inverse(range.as_imp(range), source.as_imp(source), opts); } template <class R, class S> void apply_inverse(const ConstDiscreteFunction<SourceSpaceType, R>& range, ConstDiscreteFunction<RangeSpaceType, S>& source) { apply_inverse(range.vector(), source.vector()); } template <class R, class S> void apply_inverse(const ConstDiscreteFunction<SourceSpaceType, R>& range, ConstDiscreteFunction<RangeSpaceType, S>& source, const std::string& opt) { apply_inverse(range.vector(), source.vector(), opt); } template <class R, class S> void apply_inverse(const ConstDiscreteFunction<SourceSpaceType, R>& range, ConstDiscreteFunction<RangeSpaceType, S>& source, const Stuff::Common::Configuration& opts) { apply_inverse(range.vector(), source.vector(), opts); } template <class R, class S, class P> FieldType apply2(const Stuff::LA::VectorInterface<R, FieldType>& range, const Stuff::LA::VectorInterface<S, FieldType>& source, const AssemblableProductInterface<P>& product) { auto tmp = range.copy(); apply(source, tmp); return product.apply2(tmp, source); } template <class R, class S> FieldType apply2(const Stuff::LA::VectorInterface<R, FieldType>& range, const Stuff::LA::VectorInterface<S, FieldType>& source) { this->assemble(); auto tmp = range.copy(); this->matrix().mv(source.as_imp(), tmp); return range.dot(tmp); } template <class S, class R> FieldType apply2(const ConstDiscreteFunction<SourceSpaceType, S>& source, const ConstDiscreteFunction<RangeSpaceType, R>& range) { return apply2(range.vector(), source.vector()); } }; // class AssemblableOperatorInterface } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_INTERFACES_HH <commit_msg>[operators.interfaces] modernize<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_INTERFACES_HH #define DUNE_GDT_OPERATORS_INTERFACES_HH #include <type_traits> #include <dune/common/dynmatrix.hh> #include <dune/common/fvector.hh> #include <dune/stuff/common/crtp.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/la/container/interfaces.hh> #include <dune/stuff/la/container/pattern.hh> #include <dune/stuff/la/solver.hh> #include <dune/stuff/common/configuration.hh> #include <dune/gdt/spaces/interface.hh> #include <dune/gdt/discretefunction/default.hh> #include "../products/interfaces.hh" namespace Dune { namespace GDT { template <class Traits> class OperatorInterface : public ProductInterface<Traits> { typedef ProductInterface<Traits> BaseType; public: using typename BaseType::GridViewType; using typename BaseType::FieldType; template <class SourceType, class RangeType> void apply(const SourceType& source, RangeType& range) const { CHECK_CRTP(this->as_imp(*this).apply(source, range)); return this->as_imp(*this).apply(source, range); } template <class S, class R> FieldType apply2(const Stuff::LA::VectorInterface<S, FieldType>& source, const Stuff::LA::VectorInterface<R, FieldType>& range) const { auto tmp = range.copy(); apply(source.as_imp(source), tmp); return range.dot(tmp); } // ... apply2(...) template <class SS, class SV, class RS, class RV> FieldType apply2(const ConstDiscreteFunction<SS, SV>& source, const ConstDiscreteFunction<RS, RV>& range) const { auto tmp_vector = range.copy(); DiscreteFunction<RS, RV> tmp_function(range.space(), tmp_vector); apply(source, tmp_function); return range.vector().dot(tmp_vector); } }; // class OperatorInterface template <class Traits> class LocalizableOperatorInterface : public Stuff::CRTPInterface<LocalizableOperatorInterface<Traits>, Traits> { typedef typename Traits::derived_type derived_type; typedef typename Traits::GridViewType GridViewType; typedef typename Traits::SourceType SourceType; typedef typename Traits::RangeType RangeType; typedef typename Traits::FieldType FieldType; typedef typename GridViewType::template Codim<0>::Entity EntityType; typedef typename GridViewType::ctype DomainFieldType; static const unsigned int dimDomain = GridViewType::dimension; private: static_assert(Stuff::is_localizable_function<SourceType>::value, "SourceType has to be derived from Stuff::IsLocalizableFunction!"); static_assert(is_discrete_function<RangeType>::value, "RangeType has to be derived from DiscreteFunction!"); static_assert(std::is_same<typename SourceType::EntityType, EntityType>::value, "The EntityType of SourceType and GridViewType have to match!"); static_assert(std::is_same<typename RangeType::EntityType, EntityType>::value, "The EntityType of RangeType and GridViewType have to match!"); static_assert(std::is_same<typename SourceType::DomainFieldType, DomainFieldType>::value, "The DomainFieldType of SourceType and GridViewType have to match!"); static_assert(std::is_same<typename RangeType::DomainFieldType, DomainFieldType>::value, "The DomainFieldType of RangeType and GridViewType have to match!"); static_assert(SourceType::dimDomain == dimDomain, "The dimDomain of SourceType and GridViewType have to match!"); static_assert(RangeType::dimDomain == dimDomain, "The dimDomain of RangeType and GridViewType have to match!"); public: const GridViewType& grid_view() const { CHECK_CRTP(this->as_imp(*this).grid_view()); return this->as_imp(*this).grid_view(); } const SourceType& source() const { CHECK_CRTP(this->as_imp(*this).source()); return this->as_imp(*this).source(); } const RangeType& range() const { CHECK_CRTP(this->as_imp(*this).range()); return this->as_imp(*this).range(); } RangeType& range() { CHECK_CRTP(this->as_imp(*this).range()); return this->as_imp(*this).range(); } void apply() { CHECK_AND_CALL_CRTP(this->as_imp(*this).apply()); } }; // class LocalizableOperatorInterface template <class Traits> class AssemblableOperatorInterface : public AssemblableProductInterface<Traits> { typedef AssemblableProductInterface<Traits> BaseType; public: typedef typename BaseType::derived_type derived_type; using typename BaseType::FieldType; using typename BaseType::SourceSpaceType; using typename BaseType::RangeSpaceType; using typename BaseType::DomainFieldType; template <class S, class R> void apply(const Stuff::LA::VectorInterface<S, DomainFieldType>& source, Stuff::LA::VectorInterface<R, FieldType>& range) { CHECK_CRTP(this->as_imp().apply(source.as_imp(), range.as_imp())); return this->as_imp().apply(source.as_imp(), range.as_imp()); } template <class S, class R> void apply(const ConstDiscreteFunction<SourceSpaceType, S>& source, ConstDiscreteFunction<RangeSpaceType, R>& range) { apply(source.vector(), range.vector()); } static std::vector<std::string> invert_options() { return derived_type::invert_options(); } static Stuff::Common::Configuration invert_options(const std::string& type) { return derived_type::invert_options(type); } template <class R, class S> void apply_inverse(const Stuff::LA::VectorInterface<R, FieldType>& range, const Stuff::LA::VectorInterface<S, FieldType>& source) { apply_inverse(range, source, invert_options()[0]); } template <class R, class S> void apply_inverse(const Stuff::LA::VectorInterface<R, FieldType>& range, Stuff::LA::VectorInterface<S, FieldType>& source, const std::string& opt) { apply_inverse(range, source, invert_options(opt)); } template <class R, class S> void apply_inverse(const Stuff::LA::VectorInterface<R, FieldType>& range, Stuff::LA::VectorInterface<S, FieldType>& source, const Stuff::Common::Configuration& opts) { CHECK_CRTP(this->as_imp(*this).apply_inverse(range.as_imp(range), source.as_imp(source), opts)); return this->as_imp(*this).apply_inverse(range.as_imp(range), source.as_imp(source), opts); } template <class R, class S> void apply_inverse(const ConstDiscreteFunction<SourceSpaceType, R>& range, ConstDiscreteFunction<RangeSpaceType, S>& source) { apply_inverse(range.vector(), source.vector()); } template <class R, class S> void apply_inverse(const ConstDiscreteFunction<SourceSpaceType, R>& range, ConstDiscreteFunction<RangeSpaceType, S>& source, const std::string& opt) { apply_inverse(range.vector(), source.vector(), opt); } template <class R, class S> void apply_inverse(const ConstDiscreteFunction<SourceSpaceType, R>& range, ConstDiscreteFunction<RangeSpaceType, S>& source, const Stuff::Common::Configuration& opts) { apply_inverse(range.vector(), source.vector(), opts); } template <class R, class S, class P> FieldType apply2(const Stuff::LA::VectorInterface<R, FieldType>& range, const Stuff::LA::VectorInterface<S, FieldType>& source, const AssemblableProductInterface<P>& product) { auto tmp = range.copy(); apply(source, tmp); return product.apply2(tmp, source); } template <class R, class S> FieldType apply2(const Stuff::LA::VectorInterface<R, FieldType>& range, const Stuff::LA::VectorInterface<S, FieldType>& source) { this->assemble(); auto tmp = range.copy(); this->matrix().mv(source.as_imp(), tmp); return range.dot(tmp); } template <class S, class R> FieldType apply2(const ConstDiscreteFunction<SourceSpaceType, S>& source, const ConstDiscreteFunction<RangeSpaceType, R>& range) { return apply2(range.vector(), source.vector()); } }; // class AssemblableOperatorInterface } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_INTERFACES_HH <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_INTERFACES_HH #define DUNE_GDT_OPERATORS_INTERFACES_HH #include <type_traits> #include <dune/stuff/common/disable_warnings.hh> # include <dune/common/dynmatrix.hh> # include <dune/common/fvector.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/common/crtp.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/la/container/interfaces.hh> #include <dune/stuff/la/container/pattern.hh> #include <dune/stuff/la/solver.hh> #include <dune/stuff/common/configuration.hh> #include <dune/gdt/spaces/interface.hh> #include <dune/gdt/discretefunction/default.hh> #include "../products/interfaces.hh" namespace Dune { namespace GDT { template< class Traits > class OperatorInterface : public ProductInterface< Traits > { typedef ProductInterface< Traits > BaseType; public: using typename BaseType::GridViewType; using typename BaseType::FieldType; template< class SourceType, class RangeType > void apply(const SourceType& source, RangeType& range) const { CHECK_CRTP(this->as_imp(*this).apply(source, range)); return this->as_imp(*this).apply(source, range); } template< class S, class R > FieldType apply2(const Stuff::LA::VectorInterface< S, FieldType >& source, const Stuff::LA::VectorInterface< R, FieldType >& range) const { auto tmp = range.copy(); apply(source.as_imp(source), tmp); return range.dot(tmp); } // ... apply2(...) template< class SS, class SV, class RS, class RV > FieldType apply2(const ConstDiscreteFunction< SS, SV >& source, const ConstDiscreteFunction< RS, RV >& range) const { auto tmp_vector = range.copy(); DiscreteFunction< RS, RV > tmp_function(range.space(), tmp_vector); apply(source, tmp_function); return range.vector().dot(tmp_vector); } }; // class OperatorInterface template< class Traits > class LocalizableOperatorInterface : public Stuff::CRTPInterface< LocalizableOperatorInterface< Traits >, Traits > { typedef typename Traits::derived_type derived_type; typedef typename Traits::GridViewType GridViewType; typedef typename Traits::SourceType SourceType; typedef typename Traits::RangeType RangeType; typedef typename Traits::FieldType FieldType; typedef typename GridViewType::template Codim< 0 >::Entity EntityType; typedef typename GridViewType::ctype DomainFieldType; static const unsigned int dimDomain = GridViewType::dimension; private: static_assert(std::is_base_of< Stuff::IsLocalizableFunction, SourceType >::value, "SourceType has to be derived from Stuff::IsLocalizableFunction!"); static_assert(std::is_base_of< DiscreteFunction< typename RangeType::SpaceType, typename RangeType::VectorType > , RangeType >::value, "RangeType has to be derived from DiscreteFunction!"); static_assert(std::is_same< typename SourceType::EntityType, EntityType >::value, "The EntityType of SourceType and GridViewType have to match!"); static_assert(std::is_same< typename RangeType::EntityType, EntityType >::value, "The EntityType of RangeType and GridViewType have to match!"); static_assert(std::is_same< typename SourceType::DomainFieldType, DomainFieldType >::value, "The DomainFieldType of SourceType and GridViewType have to match!"); static_assert(std::is_same< typename RangeType::DomainFieldType, DomainFieldType >::value, "The DomainFieldType of RangeType and GridViewType have to match!"); static_assert(SourceType::dimDomain == dimDomain, "The dimDomain of SourceType and GridViewType have to match!"); static_assert(RangeType::dimDomain == dimDomain, "The dimDomain of RangeType and GridViewType have to match!"); public: const GridViewType& grid_view() const { CHECK_CRTP(this->as_imp(*this).grid_view()); return this->as_imp(*this).grid_view(); } const SourceType& source() const { CHECK_CRTP(this->as_imp(*this).source()); return this->as_imp(*this).source(); } const RangeType& range() const { CHECK_CRTP(this->as_imp(*this).range()); return this->as_imp(*this).range(); } RangeType& range() { CHECK_CRTP(this->as_imp(*this).range()); return this->as_imp(*this).range(); } void apply() { CHECK_AND_CALL_CRTP(this->as_imp(*this).apply()); } }; // class LocalizableOperatorInterface template< class Traits > class AssemblableOperatorInterface : public AssemblableProductInterface< Traits > { typedef AssemblableProductInterface< Traits > BaseType; public: typedef typename BaseType::derived_type derived_type; using typename BaseType::GridViewType; using typename BaseType::FieldType; using typename BaseType::SourceSpaceType; using typename BaseType::RangeSpaceType; using typename BaseType::MatrixType; using typename BaseType::EntityType; using typename BaseType::DomainFieldType; using BaseType::dimDomain; using typename BaseType::PatternType; template< class S, class R > void apply(const Stuff::LA::VectorInterface< S, DomainFieldType >& source, Stuff::LA::VectorInterface< R, FieldType >& range) { CHECK_CRTP(this->as_imp(*this).apply(source.as_imp(source), range.as_imp(range))); return this->as_imp(*this).apply(source.as_imp(source), range.as_imp(range)); } template< class S, class R > void apply(const ConstDiscreteFunction< SourceSpaceType, S >& source, ConstDiscreteFunction< RangeSpaceType, R >& range) { apply(source.vector(), range.vector()); } static std::vector< std::string > invert_options() { return derived_type::invert_options(); } static Stuff::Common::Configuration invert_options(const std::string& type) { return derived_type::invert_options(type); } template< class R, class S > void apply_inverse(const Stuff::LA::VectorInterface< R, FieldType >& range, const Stuff::LA::VectorInterface< S, FieldType >& source) { apply_inverse(range, source, invert_options()[0]); } template< class R, class S > void apply_inverse(const Stuff::LA::VectorInterface< R, FieldType >& range, Stuff::LA::VectorInterface< S, FieldType >& source, const std::string& opt) { apply_inverse(range, source, invert_options(opt)); } template< class R, class S > void apply_inverse(const Stuff::LA::VectorInterface< R, FieldType >& range, Stuff::LA::VectorInterface< S, FieldType >& source, const Stuff::Common::Configuration& opts) { CHECK_CRTP(this->as_imp(*this).apply_inverse(range.as_imp(range), source.as_imp(source), opts)); return this->as_imp(*this).apply_inverse(range.as_imp(range), source.as_imp(source), opts); } template< class R, class S > void apply_inverse(const ConstDiscreteFunction< SourceSpaceType, R >& range, ConstDiscreteFunction< RangeSpaceType, S >& source) { apply_inverse(range.vector(), source.vector()); } template< class R, class S > void apply_inverse(const ConstDiscreteFunction< SourceSpaceType, R >& range, ConstDiscreteFunction< RangeSpaceType, S >& source, const std::string& opt) { apply_inverse(range.vector(), source.vector(), opt); } template< class R, class S > void apply_inverse(const ConstDiscreteFunction< SourceSpaceType, R >& range, ConstDiscreteFunction< RangeSpaceType, S >& source, const Stuff::Common::Configuration& opts) { apply_inverse(range.vector(), source.vector(), opts); } template< class R, class S, class P > FieldType apply2(const Stuff::LA::VectorInterface< R, FieldType >& range, const Stuff::LA::VectorInterface< S, FieldType >& source, const AssemblableProductInterface< P >& product) { apply(source, range); return product.apply2(range, source); } template< class R, class S, class P > FieldType apply2(const Stuff::LA::VectorInterface< R, FieldType >& range, const Stuff::LA::VectorInterface< S, FieldType >& source) { this->assemble(); auto tmp = range.copy(); this->matrix().mv(source.as_imp(source), tmp); return range.dot(tmp); } template< class S, class R > FieldType apply2(const ConstDiscreteFunction< SourceSpaceType, S >& source, const ConstDiscreteFunction< RangeSpaceType, R >& range) { return apply2(range.vector(), source.vector()); } }; // class AssemblableOperatorInterface } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_INTERFACES_HH <commit_msg>[operators.interfaces] fix apply2 implementations<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_INTERFACES_HH #define DUNE_GDT_OPERATORS_INTERFACES_HH #include <type_traits> #include <dune/stuff/common/disable_warnings.hh> # include <dune/common/dynmatrix.hh> # include <dune/common/fvector.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/common/crtp.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/la/container/interfaces.hh> #include <dune/stuff/la/container/pattern.hh> #include <dune/stuff/la/solver.hh> #include <dune/stuff/common/configuration.hh> #include <dune/gdt/spaces/interface.hh> #include <dune/gdt/discretefunction/default.hh> #include "../products/interfaces.hh" namespace Dune { namespace GDT { template< class Traits > class OperatorInterface : public ProductInterface< Traits > { typedef ProductInterface< Traits > BaseType; public: using typename BaseType::GridViewType; using typename BaseType::FieldType; template< class SourceType, class RangeType > void apply(const SourceType& source, RangeType& range) const { CHECK_CRTP(this->as_imp(*this).apply(source, range)); return this->as_imp(*this).apply(source, range); } template< class S, class R > FieldType apply2(const Stuff::LA::VectorInterface< S, FieldType >& source, const Stuff::LA::VectorInterface< R, FieldType >& range) const { auto tmp = range.copy(); apply(source.as_imp(source), tmp); return range.dot(tmp); } // ... apply2(...) template< class SS, class SV, class RS, class RV > FieldType apply2(const ConstDiscreteFunction< SS, SV >& source, const ConstDiscreteFunction< RS, RV >& range) const { auto tmp_vector = range.copy(); DiscreteFunction< RS, RV > tmp_function(range.space(), tmp_vector); apply(source, tmp_function); return range.vector().dot(tmp_vector); } }; // class OperatorInterface template< class Traits > class LocalizableOperatorInterface : public Stuff::CRTPInterface< LocalizableOperatorInterface< Traits >, Traits > { typedef typename Traits::derived_type derived_type; typedef typename Traits::GridViewType GridViewType; typedef typename Traits::SourceType SourceType; typedef typename Traits::RangeType RangeType; typedef typename Traits::FieldType FieldType; typedef typename GridViewType::template Codim< 0 >::Entity EntityType; typedef typename GridViewType::ctype DomainFieldType; static const unsigned int dimDomain = GridViewType::dimension; private: static_assert(std::is_base_of< Stuff::IsLocalizableFunction, SourceType >::value, "SourceType has to be derived from Stuff::IsLocalizableFunction!"); static_assert(std::is_base_of< DiscreteFunction< typename RangeType::SpaceType, typename RangeType::VectorType > , RangeType >::value, "RangeType has to be derived from DiscreteFunction!"); static_assert(std::is_same< typename SourceType::EntityType, EntityType >::value, "The EntityType of SourceType and GridViewType have to match!"); static_assert(std::is_same< typename RangeType::EntityType, EntityType >::value, "The EntityType of RangeType and GridViewType have to match!"); static_assert(std::is_same< typename SourceType::DomainFieldType, DomainFieldType >::value, "The DomainFieldType of SourceType and GridViewType have to match!"); static_assert(std::is_same< typename RangeType::DomainFieldType, DomainFieldType >::value, "The DomainFieldType of RangeType and GridViewType have to match!"); static_assert(SourceType::dimDomain == dimDomain, "The dimDomain of SourceType and GridViewType have to match!"); static_assert(RangeType::dimDomain == dimDomain, "The dimDomain of RangeType and GridViewType have to match!"); public: const GridViewType& grid_view() const { CHECK_CRTP(this->as_imp(*this).grid_view()); return this->as_imp(*this).grid_view(); } const SourceType& source() const { CHECK_CRTP(this->as_imp(*this).source()); return this->as_imp(*this).source(); } const RangeType& range() const { CHECK_CRTP(this->as_imp(*this).range()); return this->as_imp(*this).range(); } RangeType& range() { CHECK_CRTP(this->as_imp(*this).range()); return this->as_imp(*this).range(); } void apply() { CHECK_AND_CALL_CRTP(this->as_imp(*this).apply()); } }; // class LocalizableOperatorInterface template< class Traits > class AssemblableOperatorInterface : public AssemblableProductInterface< Traits > { typedef AssemblableProductInterface< Traits > BaseType; public: typedef typename BaseType::derived_type derived_type; using typename BaseType::GridViewType; using typename BaseType::FieldType; using typename BaseType::SourceSpaceType; using typename BaseType::RangeSpaceType; using typename BaseType::MatrixType; using typename BaseType::EntityType; using typename BaseType::DomainFieldType; using BaseType::dimDomain; using typename BaseType::PatternType; template< class S, class R > void apply(const Stuff::LA::VectorInterface< S, DomainFieldType >& source, Stuff::LA::VectorInterface< R, FieldType >& range) { CHECK_CRTP(this->as_imp(*this).apply(source.as_imp(source), range.as_imp(range))); return this->as_imp(*this).apply(source.as_imp(source), range.as_imp(range)); } template< class S, class R > void apply(const ConstDiscreteFunction< SourceSpaceType, S >& source, ConstDiscreteFunction< RangeSpaceType, R >& range) { apply(source.vector(), range.vector()); } static std::vector< std::string > invert_options() { return derived_type::invert_options(); } static Stuff::Common::Configuration invert_options(const std::string& type) { return derived_type::invert_options(type); } template< class R, class S > void apply_inverse(const Stuff::LA::VectorInterface< R, FieldType >& range, const Stuff::LA::VectorInterface< S, FieldType >& source) { apply_inverse(range, source, invert_options()[0]); } template< class R, class S > void apply_inverse(const Stuff::LA::VectorInterface< R, FieldType >& range, Stuff::LA::VectorInterface< S, FieldType >& source, const std::string& opt) { apply_inverse(range, source, invert_options(opt)); } template< class R, class S > void apply_inverse(const Stuff::LA::VectorInterface< R, FieldType >& range, Stuff::LA::VectorInterface< S, FieldType >& source, const Stuff::Common::Configuration& opts) { CHECK_CRTP(this->as_imp(*this).apply_inverse(range.as_imp(range), source.as_imp(source), opts)); return this->as_imp(*this).apply_inverse(range.as_imp(range), source.as_imp(source), opts); } template< class R, class S > void apply_inverse(const ConstDiscreteFunction< SourceSpaceType, R >& range, ConstDiscreteFunction< RangeSpaceType, S >& source) { apply_inverse(range.vector(), source.vector()); } template< class R, class S > void apply_inverse(const ConstDiscreteFunction< SourceSpaceType, R >& range, ConstDiscreteFunction< RangeSpaceType, S >& source, const std::string& opt) { apply_inverse(range.vector(), source.vector(), opt); } template< class R, class S > void apply_inverse(const ConstDiscreteFunction< SourceSpaceType, R >& range, ConstDiscreteFunction< RangeSpaceType, S >& source, const Stuff::Common::Configuration& opts) { apply_inverse(range.vector(), source.vector(), opts); } template< class R, class S, class P > FieldType apply2(const Stuff::LA::VectorInterface< R, FieldType >& range, const Stuff::LA::VectorInterface< S, FieldType >& source, const AssemblableProductInterface< P >& product) { auto tmp = range.copy(); apply(source, tmp); return product.apply2(tmp, source); } template< class R, class S > FieldType apply2(const Stuff::LA::VectorInterface< R, FieldType >& range, const Stuff::LA::VectorInterface< S, FieldType >& source) { this->assemble(); auto tmp = range.copy(); this->matrix().mv(source.as_imp(), tmp); return range.dot(tmp); } template< class S, class R > FieldType apply2(const ConstDiscreteFunction< SourceSpaceType, S >& source, const ConstDiscreteFunction< RangeSpaceType, R >& range) { return apply2(range.vector(), source.vector()); } }; // class AssemblableOperatorInterface } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_INTERFACES_HH <|endoftext|>