hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 260 | max_issues_repo_name stringlengths 5 109 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 260 | max_forks_repo_name stringlengths 5 109 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
142e7fc4572ac6d6c3c2987ee52e225da4259bba | 5,270 | h | C | src/cpp/SPL/Core/OPIModelBuilder.h | IBMStreams/OSStreams | c6287bd9ec4323f567d2faf59125baba8604e1db | [
"Apache-2.0"
] | 10 | 2021-02-19T20:19:24.000Z | 2021-09-16T05:11:50.000Z | src/cpp/SPL/Core/OPIModelBuilder.h | xguerin/openstreams | 7000370b81a7f8778db283b2ba9f9ead984b7439 | [
"Apache-2.0"
] | 7 | 2021-02-20T01:17:12.000Z | 2021-06-08T14:56:34.000Z | src/cpp/SPL/Core/OPIModelBuilder.h | IBMStreams/OSStreams | c6287bd9ec4323f567d2faf59125baba8604e1db | [
"Apache-2.0"
] | 4 | 2021-02-19T18:43:10.000Z | 2022-02-23T14:18:16.000Z | /*
* Copyright 2021 IBM Corporation
*
* 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.
*/
#ifndef SPL_OPI_MODEL_BUILDER_H
#define SPL_OPI_MODEL_BUILDER_H
#include <SPL/CodeGen/Expression.h>
#include <SPL/CodeGen/Statement.h>
#include <SPL/Core/OperatorInstanceModelImpl.h>
#include <UTILS/HashMapHelpers.h>
#include <memory>
#include <string>
#include <vector>
class HistoryVisitorContext;
namespace SPL {
class RootTyp;
class FunctionHEad;
class Literal;
class LiteralReplacer;
class OperatorGraphNode;
class PrimitiveOperatorInstance;
namespace Operator {
class OperatorModel;
}
class OPIModelBuilder
{
typedef Operator::Instance::Context Context;
typedef Operator::OperatorModel OperatorModel;
typedef Operator::Instance::OperatorInstanceModel OperatorInstanceModel;
typedef std::tr1::unordered_map<std::string, int> TypeMap;
public:
static void build(PrimitiveOperatorInstance const&, OperatorGraphNode& node);
static void verify(PrimitiveOperatorInstance const&, OperatorGraphNode& node);
private:
static void populateParameters(PrimitiveOperatorInstance const& ir,
OperatorInstanceModel& oim,
OperatorModel const& om,
LiteralReplacer& litRep,
HistoryVisitorContext& historyContext,
TypeMap& typeMap,
bool verify);
static void populateContext(PrimitiveOperatorInstance const& ir,
OperatorInstanceModel& oim,
OperatorModel const& om,
LiteralReplacer& litRep,
TypeMap& typeMap,
std::string const& operatorModelDirectory,
bool verify);
static void populateInputPorts(PrimitiveOperatorInstance const& ir,
OperatorInstanceModel& oim,
OperatorModel const& om,
LiteralReplacer& litRep,
HistoryVisitorContext& historyContext,
bool verify);
static void populateOutputPorts(PrimitiveOperatorInstance const& ir,
OperatorInstanceModel& oim,
OperatorModel const& om,
LiteralReplacer& litRep,
HistoryVisitorContext& historyContext,
TypeMap& typeMap,
bool verify);
static bool simplifyAndReplaceLiterals(std::auto_ptr<Expression>& expr,
LiteralReplacer& litRep,
bool onlySTP);
static void simplifyAndReplaceLiterals(std::auto_ptr<Statement>& stmt, LiteralReplacer& litRep);
static void analyzeExpression(Expression const& expr,
bool& hasFunctions,
bool& hasSideEffects,
bool& readsState);
static Operator::Instance::ExpressionPtr buildStringExpression(std::string const& value);
static Operator::Instance::ExpressionPtr buildGetToolkitDirectoryRelativeExpression(
const std::string& toolkitName,
std::string const& relativePath,
LiteralReplacer& litRep,
TypeMap* typeMap,
const PrimitiveOperatorInstance& ir);
static Operator::Instance::ExpressionPtr buildExpression(Expression const& expr,
bool rewriteIsAllowed,
LiteralReplacer& litRep,
TypeMap* typeMap,
bool genCppCodeInSPLExpnTree,
PrimitiveOperatorInstance const& ir,
bool verify);
static std::string const& getAttrNameFromExpression(Expression const& expr);
static OperatorModel const& getOperatorModel(PrimitiveOperatorInstance const& ir,
OperatorInstanceModel& oim,
std::string& operatorModelDirectory);
static void doBuild(OperatorInstanceModel& oim,
PrimitiveOperatorInstance const&,
OperatorGraphNode& node,
bool verify);
};
};
#endif /* SPL_OPI_MODEL_BUILDER_H */
| 42.845528 | 100 | 0.564516 | [
"vector"
] |
142edb6d8cdb157b14e92474455b5bf1e9e87018 | 784 | h | C | System/Library/PrivateFrameworks/CorePrediction.framework/CPMLEvalutionResult.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 2 | 2021-11-02T09:23:27.000Z | 2022-03-28T08:21:57.000Z | System/Library/PrivateFrameworks/CorePrediction.framework/CPMLEvalutionResult.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/CorePrediction.framework/CPMLEvalutionResult.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 1 | 2022-03-28T08:21:59.000Z | 2022-03-28T08:21:59.000Z | /*
* This header is generated by classdump-dyld 1.5
* on Wednesday, October 27, 2021 at 3:18:06 PM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/CorePrediction.framework/CorePrediction
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
@class NSObject;
@interface CPMLEvalutionResult : NSObject {
NSObject* object;
unsigned long long count;
}
-(double)getDouble;
-(id)getString;
-(id)init:(id)arg1 withConfigurationList:(id)arg2 ;
-(id)getStringList;
-(int)getInt;
-(id)getList;
-(id)getListDict;
@end
| 29.037037 | 130 | 0.622449 | [
"object"
] |
1431498f790096d243f6775c2b8ce9eee33b5bf5 | 3,277 | h | C | RenderCore/render/core/rendering/ClipRects.h | gubaojian/weexuikit | 2eaf54e4c1f4a1c94398b0990ad9767e3ffb9213 | [
"Apache-2.0"
] | 46 | 2019-06-25T11:05:49.000Z | 2021-12-31T04:47:53.000Z | RenderCore/render/core/rendering/ClipRects.h | gubaojian/weexuikit | 2eaf54e4c1f4a1c94398b0990ad9767e3ffb9213 | [
"Apache-2.0"
] | 5 | 2019-10-16T06:54:37.000Z | 2020-02-06T08:22:40.000Z | RenderCore/render/core/rendering/ClipRects.h | gubaojian/weexuikit | 2eaf54e4c1f4a1c94398b0990ad9767e3ffb9213 | [
"Apache-2.0"
] | 18 | 2019-05-22T09:29:23.000Z | 2021-04-28T02:12:42.000Z | /*
* Copyright (C) 2003, 2009, 2012 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef WEEX_UIKIT_CORE_RENDERING_CLIPRECTS_H_
#define WEEX_UIKIT_CORE_RENDERING_CLIPRECTS_H_
#include "render/core/rendering/ClipRect.h"
namespace blink {
class ClipRects {
WTF_MAKE_FAST_ALLOCATED;
public:
static PassRefPtr<ClipRects> create() { return adoptRef(new ClipRects); }
static PassRefPtr<ClipRects> create(const ClipRects& other) {
return adoptRef(new ClipRects(other));
}
ClipRects() : m_refCnt(1), m_fixed(0) {}
void reset(const LayoutRect& r) {
m_overflowClipRect = r;
m_posClipRect = r;
m_fixed = 0;
}
const ClipRect& overflowClipRect() const { return m_overflowClipRect; }
void setOverflowClipRect(const ClipRect& r) { m_overflowClipRect = r; }
const ClipRect& posClipRect() const { return m_posClipRect; }
void setPosClipRect(const ClipRect& r) { m_posClipRect = r; }
bool fixed() const { return static_cast<bool>(m_fixed); }
void setFixed(bool fixed) { m_fixed = fixed ? 1 : 0; }
void ref() { m_refCnt++; }
void deref() {
if (!--m_refCnt)
delete this;
}
bool operator==(const ClipRects& other) const {
return m_overflowClipRect == other.overflowClipRect() &&
m_posClipRect == other.posClipRect() && fixed() == other.fixed();
}
ClipRects& operator=(const ClipRects& other) {
m_overflowClipRect = other.overflowClipRect();
m_posClipRect = other.posClipRect();
m_fixed = other.fixed();
return *this;
}
private:
ClipRects(const LayoutRect& r)
: m_overflowClipRect(r), m_posClipRect(r), m_refCnt(1), m_fixed(0) {}
ClipRects(const ClipRects& other)
: m_overflowClipRect(other.overflowClipRect()),
m_posClipRect(other.posClipRect()),
m_refCnt(1),
m_fixed(other.fixed()) {}
ClipRect m_overflowClipRect;
ClipRect m_posClipRect;
unsigned m_refCnt : 31;
unsigned m_fixed : 1;
};
} // namespace blink
#endif // WEEX_UIKIT_CORE_RENDERING_CLIPRECTS_H_
| 33.783505 | 76 | 0.722612 | [
"render"
] |
143336bfb7a92001bcb18b82e15b30ddbcd2f6a6 | 3,050 | h | C | Tests/TestFramework/TestManager.h | SuckShit/Theron-6.00.02 | aa66bf77775188cc9fa0d5250d920ac54fb16129 | [
"BSL-1.0"
] | 30 | 2015-04-09T21:35:46.000Z | 2021-07-01T01:21:32.000Z | Tests/TestFramework/TestManager.h | SuckShit/Theron-6.00.02 | aa66bf77775188cc9fa0d5250d920ac54fb16129 | [
"BSL-1.0"
] | null | null | null | Tests/TestFramework/TestManager.h | SuckShit/Theron-6.00.02 | aa66bf77775188cc9fa0d5250d920ac54fb16129 | [
"BSL-1.0"
] | 15 | 2015-02-06T21:33:23.000Z | 2020-05-12T06:07:32.000Z | // Copyright (C) by Ashton Mason. See LICENSE.txt for licensing information.
#ifndef TESTFRAMEWORK_TESTMANAGER_H
#define TESTFRAMEWORK_TESTMANAGER_H
#ifdef _MSC_VER
#pragma warning(push,0)
#pragma warning (disable:4530) // C++ exception handler used, but unwind semantics are not enabled
#endif //_MSC_VER
#include <vector>
#ifdef _MSC_VER
#pragma warning(pop)
#endif //_MSC_VER
#include "ITestSuite.h"
namespace TestFramework
{
/// Singleton manager/factory class that manages a collection of unit tests suites.
class TestManager
{
public:
/// Defines a list of pointers to test suites.
typedef std::vector<ITestSuite *> TestSuiteList;
/// Defines a test error message.
typedef ITestSuite::Error Error;
/// Defines a list of test error messages.
typedef ITestSuite::ErrorList ErrorList;
/// Destructor
inline ~TestManager()
{
}
/// Static method that returns a pointer to the single instance of the TestManager singleton.
inline static TestManager *Instance()
{
static TestManager sInstance;
return &sInstance;
}
/// Registers a test suite with the test suite manager.
/// \param testSuite The test suite to be registered, which must implement ITestSuite.
inline void Register(ITestSuite *const testSuite)
{
mTestSuites.push_back(testSuite);
}
/// Registers a test suite with the test suite manager.
/// \return True if the test suites all passed, otherwise false.
inline bool RunTests(const bool verbose)
{
mErrors.clear();
bool passedAllSuites = true;
for (TestSuiteList::const_iterator it = mTestSuites.begin(); it != mTestSuites.end(); ++it)
{
ITestSuite *const testSuite = (*it);
const bool passedSuite = testSuite->RunTests(verbose);
if (!passedSuite)
{
// Collect the errors from the test suite.
const ErrorList &suiteErrors(testSuite->GetErrors());
mErrors.insert(mErrors.end(), suiteErrors.begin(), suiteErrors.end());
passedAllSuites = false;
}
}
return passedAllSuites;
}
/// Gets the errors returned by the failed tests in all registered test suites.
/// \return A list of errors.
inline const ErrorList &GetErrors()
{
return mErrors;
}
private:
/// Private default constructor. This is a singleton class and can't be constructed directly.
inline TestManager()
{
}
/// Disallowed copy constructor. TestManager objects can't be copied.
TestManager(const TestManager &other);
/// Disallowed assignment operator. TestManager objects can't be assigned.
TestManager &operator=(const TestManager &other);
TestSuiteList mTestSuites; ///< List of test suites managed by the manager.
ErrorList mErrors; ///< List of error messages returned by failed tests.
};
} // namespace TestFramework
#endif // TESTFRAMEWORK_TESTMANAGER_H
| 26.99115 | 99 | 0.664918 | [
"vector"
] |
143ee793ba023d9cdf22b7fee831f1a8d150bf17 | 5,426 | h | C | deps/include/CEGUI/WindowFactory.h | mirzazulfan/Xenro-Engine | 0e9383b113ec09a24daf5e92f9a5b84febaffb1b | [
"MIT"
] | 13 | 2019-02-21T09:05:11.000Z | 2021-12-03T09:11:00.000Z | deps/include/CEGUI/WindowFactory.h | mirzazulfan/Xenro-Engine | 0e9383b113ec09a24daf5e92f9a5b84febaffb1b | [
"MIT"
] | 18 | 2018-02-28T21:34:30.000Z | 2018-12-01T19:07:43.000Z | deps/include/CEGUI/WindowFactory.h | mirzazulfan/Xenro-Engine | 0e9383b113ec09a24daf5e92f9a5b84febaffb1b | [
"MIT"
] | 15 | 2015-02-23T16:35:28.000Z | 2022-03-25T13:40:33.000Z | /***********************************************************************
created: 21/2/2004
author: Paul D Turner
purpose: Defines abstract base class for WindowFactory objects
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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.
***************************************************************************/
#ifndef _CEGUIWindowFactory_h_
#define _CEGUIWindowFactory_h_
#include "CEGUI/Base.h"
#include "CEGUI/String.h"
#include "CEGUI/Window.h"
/*!
\brief
Declares a window factory class.
\param T
The window class name.
\note
The class that will be generated is is named <classname>Factory.
A statement like this:
CEGUI_DECLARE_WINDOW_FACTORY(MyWidget);
Would generate a factory class named MyWidgetFactory.
The factory is automatically instantiated and for the example it would
be available as:
WindowFactory* wf = &(getMyWidgetFactory());
or
WindowFactory* wf = &CEGUI_WINDOW_FACTORY(MyWidget);
*/
#define CEGUI_DECLARE_WINDOW_FACTORY( T )\
class T ## Factory : public WindowFactory\
{\
public:\
T ## Factory() : WindowFactory( T::WidgetTypeName ) {}\
Window* createWindow(const String& name)\
{\
return CEGUI_NEW_AO T(d_type, name);\
}\
void destroyWindow(Window* window)\
{\
CEGUI_DELETE_AO window;\
}\
};\
T ## Factory& get ## T ## Factory();
/*!
\brief
Generates code for the constructor for the instance of the window factory
generated from the class name \a T
*/
#define CEGUI_DEFINE_WINDOW_FACTORY( T )\
T ## Factory& get ## T ## Factory()\
{\
static T ## Factory s_factory;\
return s_factory;\
}
/*!
\brief
Helper macro that return the real factory class name from a given class
name \a T
*/
#define CEGUI_WINDOW_FACTORY( T ) (get ## T ## Factory())
// Start of CEGUI namespace section
namespace CEGUI
{
/*!
\brief
Abstract class that defines the required interface for all WindowFactory
objects.
A WindowFactory is used to create and destroy windows of a specific type.
For every type of Window object wihin the system (widgets, dialogs, movable
windows etc) there must be an associated WindowFactory registered with the
WindowFactoryManager so that the system knows how to create and destroy
those types of Window base object.
\note
The use if of the CEGUI_DECLARE_WINDOW_FACTORY, CEGUI_DEFINE_WINDOW_FACTORY
and CEGUI_WINDOW_FACTORY macros is deprecated in favour of the
template class TplWindowFactory and templatised
WindowFactoryManager::addFactory function, whereby you no longer need to
directly create any supporting structure for your new window type, and can
simply do:
\code
CEGUI::WindowFactoryManager::addFactory<TplWindowFactory<MyWidget> >();
\endcode
*/
class CEGUIEXPORT WindowFactory :
public AllocatedObject<WindowFactory>
{
public:
/*!
\brief
Create a new Window object of whatever type this WindowFactory produces.
\param name
A unique name that is to be assigned to the newly created Window object
\return
Pointer to the new Window object.
*/
virtual Window* createWindow(const String& name) = 0;
/*!
\brief
Destroys the given Window object.
\param window
Pointer to the Window object to be destroyed.
\return
Nothing.
*/
virtual void destroyWindow(Window* window) = 0;
/*!
\brief
Get the string that describes the type of Window object this
WindowFactory produces.
\return
String object that contains the unique Window object type produced by
this WindowFactory
*/
const String& getTypeName() const
{ return d_type; }
//! Destructor.
virtual ~WindowFactory()
{}
protected:
//! Constructor
WindowFactory(const String& type) :
d_type(type)
{}
protected:
//! String holding the type of object created by this factory.
String d_type;
};
} // End of CEGUI namespace section
#endif // end of guard _CEGUIWindowFactory_h_
| 31.364162 | 80 | 0.652599 | [
"object"
] |
afd91f16eaca35dd1536119b2231341cc8c7156d | 19,573 | h | C | src/neuralClasses.h | graehl/nplm01 | b2b7bfbe17cb39ef681f60bbc383cca885418f4e | [
"MIT"
] | 1 | 2015-02-21T10:44:02.000Z | 2015-02-21T10:44:02.000Z | src/neuralClasses.h | graehl/nplm01 | b2b7bfbe17cb39ef681f60bbc383cca885418f4e | [
"MIT"
] | null | null | null | src/neuralClasses.h | graehl/nplm01 | b2b7bfbe17cb39ef681f60bbc383cca885418f4e | [
"MIT"
] | 1 | 2015-09-04T13:20:40.000Z | 2015-09-04T13:20:40.000Z | #pragma once
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <vector>
#include <boost/unordered_map.hpp>
#include <Eigen/Dense>
#include "maybe_omp.h"
#include "util.h"
#include "graphClasses.h"
#include "USCMatrix.h"
// classes for various kinds of layers
#include "SoftmaxLoss.h"
#include "Activation_function.h"
//#define EIGEN_DONT_PARALLELIZE
//#define EIGEN_DEFAULT_TO_ROW_MAJOR
namespace nplm
{
// is this cheating?
using Eigen::Matrix;
using Eigen::MatrixBase;
using Eigen::Dynamic;
typedef boost::unordered_map<int,bool> int_map;
class Linear_layer
{
private:
Matrix<double,Dynamic,Dynamic> U;
Matrix<double,Dynamic,Dynamic> U_gradient;
Matrix<double,Dynamic,Dynamic> U_velocity;
Matrix<double,Dynamic,Dynamic> U_running_gradient;
friend class model;
public:
Linear_layer() { }
Linear_layer(int rows, int cols) { resize(rows, cols); }
void resize(int rows, int cols)
{
U.setZero(rows, cols);
U_gradient.setZero(rows, cols);
U_running_gradient.setZero(rows, cols);
U_velocity.setZero(rows, cols);
}
void read(std::ifstream &U_file) { readMatrix(U_file, U); }
void write(std::ofstream &U_file) { writeMatrix(U, U_file); }
template <typename Engine>
void initialize(Engine &engine, bool init_normal, double init_range)
{
initMatrix(engine, U, init_normal, init_range);
}
int n_inputs () const { return U.cols(); }
int n_outputs () const { return U.rows(); }
template <typename DerivedIn, typename DerivedOut>
void fProp(const MatrixBase<DerivedIn> &input, const MatrixBase<DerivedOut> &output) const
{
UNCONST(DerivedOut, output, my_output);
my_output.leftCols(input.cols()).noalias() = U*input;
}
// Sparse input
template <typename ScalarIn, typename DerivedOut>
void fProp(const USCMatrix<ScalarIn> &input, const MatrixBase<DerivedOut> &output_const) const
{
UNCONST(DerivedOut, output_const, output);
output.setZero();
uscgemm(1.0, U, input, output.leftCols(input.cols()));
}
template <typename DerivedGOut, typename DerivedGIn>
void bProp(const MatrixBase<DerivedGOut> &input, MatrixBase<DerivedGIn> &output) const
{
UNCONST(DerivedGIn, output, my_output);
my_output.noalias() = U.transpose()*input;
}
template <typename DerivedGOut, typename DerivedIn>
void computeGradient(const MatrixBase<DerivedGOut> &bProp_input,
const MatrixBase<DerivedIn> &fProp_input,
double learning_rate, double momentum, double L2_reg)
{
U_gradient.noalias() = bProp_input*fProp_input.transpose();
// This used to be multithreaded, but there was no measureable difference
if (L2_reg > 0.0)
{
U_gradient *= 1 - 2*L2_reg;
}
if (momentum > 0.0)
{
U_velocity = momentum*U_velocity + U_gradient;
U += learning_rate * U_velocity;
}
else
{
U += learning_rate * U_gradient;
}
}
template <typename DerivedGOut, typename DerivedIn>
void computeGradientAdagrad(const MatrixBase<DerivedGOut> &bProp_input,
const MatrixBase<DerivedIn> &fProp_input,
double learning_rate, double momentum, double L2_reg)
{
U_gradient.noalias() = bProp_input*fProp_input.transpose();
if (L2_reg != 0)
{
U_gradient *= 1 - 2*L2_reg;
}
// ignore momentum?
U_running_gradient.array() += U_gradient.array().square();
U.array() += learning_rate * U_gradient.array() / U_running_gradient.array().sqrt();
}
template <typename DerivedGOut, typename DerivedIn, typename DerivedGW>
void computeGradientCheck(const MatrixBase<DerivedGOut> &bProp_input,
const MatrixBase<DerivedIn> &fProp_input,
const MatrixBase<DerivedGW> &gradient) const
{
UNCONST(DerivedGW, gradient, my_gradient);
my_gradient.noalias() = bProp_input*fProp_input.transpose();
}
};
class Output_word_embeddings
{
private:
// row-major is better for uscgemm
//Matrix<double,Dynamic,Dynamic,Eigen::RowMajor> W;
// Having W be a pointer to a matrix allows ease of sharing
// input and output word embeddings
Matrix<double,Dynamic,Dynamic,Eigen::RowMajor> *W;
std::vector<double> W_data;
Matrix<double,Dynamic,1> b;
Matrix<double,Dynamic,Dynamic> W_running_gradient;
Matrix<double,Dynamic,Dynamic> W_gradient;
Matrix<double,Dynamic,1> b_running_gradient;
Matrix<double,Dynamic,1> b_gradient;
public:
Output_word_embeddings() { }
Output_word_embeddings(int rows, int cols) { resize(rows, cols); }
void resize(int rows, int cols)
{
W->setZero(rows, cols);
b.setZero(rows);
}
void set_W(Matrix<double,Dynamic,Dynamic,Eigen::RowMajor> *input_W) {
W = input_W;
}
void read_weights(std::ifstream &W_file) { readMatrix(W_file, *W); }
void write_weights(std::ofstream &W_file) { writeMatrix(*W, W_file); }
void read_biases(std::ifstream &b_file) { readMatrix(b_file, b); }
void write_biases(std::ofstream &b_file) { writeMatrix(b, b_file); }
template <typename Engine>
void initialize(Engine &engine, bool init_normal, double init_range, double init_bias)
{
initMatrix(engine, *W, init_normal, init_range);
b.fill(init_bias);
}
int n_inputs () const { return W->cols(); }
int n_outputs () const { return W->rows(); }
template <typename DerivedIn, typename DerivedOut>
void fProp(const MatrixBase<DerivedIn> &input,
const MatrixBase<DerivedOut> &output) const
{
UNCONST(DerivedOut, output, my_output);
my_output = ((*W) * input).colwise() + b;
}
// Sparse output version
template <typename DerivedIn, typename DerivedOutI, typename DerivedOutV>
void fProp(const MatrixBase<DerivedIn> &input,
const MatrixBase<DerivedOutI> &samples,
const MatrixBase<DerivedOutV> &output) const
{
UNCONST(DerivedOutV, output, my_output);
#pragma omp parallel for
for (int instance_id = 0; instance_id < samples.cols(); instance_id++)
for (int sample_id = 0; sample_id < samples.rows(); sample_id++)
my_output(sample_id, instance_id) = b(samples(sample_id, instance_id));
USCMatrix<double> sparse_output(W->rows(), samples, my_output);
uscgemm_masked(1.0, *W, input, sparse_output);
my_output = sparse_output.values; // too bad, so much copying
}
// Return single element of output matrix
template <typename DerivedIn>
double fProp(const MatrixBase<DerivedIn> &input,
int word,
int instance) const
{
return W->row(word).dot(input.col(instance)) + b(word);
}
// Dense versions (for log-likelihood loss)
template <typename DerivedGOut, typename DerivedGIn>
void bProp(const MatrixBase<DerivedGOut> &input_bProp_matrix,
const MatrixBase<DerivedGIn> &bProp_matrix) const
{
// W is vocab_size x output_embedding_dimension
// input_bProp_matrix is vocab_size x minibatch_size
// bProp_matrix is output_embedding_dimension x minibatch_size
UNCONST(DerivedGIn, bProp_matrix, my_bProp_matrix);
my_bProp_matrix.leftCols(input_bProp_matrix.cols()).noalias() =
W->transpose() * input_bProp_matrix;
}
template <typename DerivedIn, typename DerivedGOut>
void computeGradient(const MatrixBase<DerivedIn> &predicted_embeddings,
const MatrixBase<DerivedGOut> &bProp_input,
double learning_rate,
double momentum) //not sure if we want to use momentum here
{
// W is vocab_size x output_embedding_dimension
// b is vocab_size x 1
// predicted_embeddings is output_embedding_dimension x minibatch_size
// bProp_input is vocab_size x minibatch_size
W->noalias() += learning_rate * bProp_input * predicted_embeddings.transpose();
b += learning_rate * bProp_input.rowwise().sum();
}
// Sparse versions
template <typename DerivedGOutI, typename DerivedGOutV, typename DerivedGIn>
void bProp(const MatrixBase<DerivedGOutI> &samples,
const MatrixBase<DerivedGOutV> &weights,
const MatrixBase<DerivedGIn> &bProp_matrix) const
{
UNCONST(DerivedGIn, bProp_matrix, my_bProp_matrix);
my_bProp_matrix.setZero();
uscgemm(1.0,
W->transpose(),
USCMatrix<double>(W->rows(), samples, weights),
my_bProp_matrix.leftCols(samples.cols())); // narrow bProp_matrix for possible short minibatch
}
template <typename DerivedIn, typename DerivedGOutI, typename DerivedGOutV>
void computeGradient(const MatrixBase<DerivedIn> &predicted_embeddings,
const MatrixBase<DerivedGOutI> &samples,
const MatrixBase<DerivedGOutV> &weights,
double learning_rate, double momentum) //not sure if we want to use momentum here
{
USCMatrix<double> gradient_output(W->rows(), samples, weights);
uscgemm(learning_rate,
gradient_output,
predicted_embeddings.leftCols(gradient_output.cols()).transpose(),
*W); // narrow predicted_embeddings for possible short minibatch
uscgemv(learning_rate,
gradient_output,
Matrix<double,Dynamic,1>::Ones(gradient_output.cols()),
b);
}
template <typename DerivedIn, typename DerivedGOutI, typename DerivedGOutV>
void computeGradientAdagrad(const MatrixBase<DerivedIn> &predicted_embeddings,
const MatrixBase<DerivedGOutI> &samples,
const MatrixBase<DerivedGOutV> &weights,
double learning_rate, double momentum) //not sure if we want to use momentum here
{
W_gradient.setZero(W->rows(), W->cols());
b_gradient.setZero(b.size());
if (W_running_gradient.rows() != W->rows() || W_running_gradient.cols() != W->cols())
W_running_gradient.setZero(W->rows(), W->cols());
if (b_running_gradient.size() != b.size())
b_running_gradient.setZero(b.size());
USCMatrix<double> gradient_output(W->rows(), samples, weights);
uscgemm(learning_rate,
gradient_output,
predicted_embeddings.leftCols(samples.cols()).transpose(),
W_gradient);
uscgemv(learning_rate, gradient_output,
Matrix<double,Dynamic,1>::Ones(weights.cols()),
b_gradient);
int_map update_map; //stores all the parameters that have been updated
for (int sample_id=0; sample_id<samples.rows(); sample_id++)
for (int train_id=0; train_id<samples.cols(); train_id++)
update_map[samples(sample_id, train_id)] = 1;
// Convert to std::vector for parallelization
std::vector<int> update_items;
for (int_map::iterator it = update_map.begin(); it != update_map.end(); ++it)
update_items.push_back(it->first);
int num_items = update_items.size();
#pragma omp parallel for
for (int item_id=0; item_id<num_items; item_id++)
{
int update_item = update_items[item_id];
W_running_gradient.row(update_item).array() += W_gradient.row(update_item).array().square();
b_running_gradient(update_item) += b_gradient(update_item) * b_gradient(update_item);
W->row(update_item).array() += learning_rate * W_gradient.row(update_item).array() / W_running_gradient.row(update_item).array().sqrt();
b(update_item) += learning_rate * b_gradient(update_item) / sqrt(b_running_gradient(update_item));
}
}
template <typename DerivedIn, typename DerivedGOutI, typename DerivedGOutV, typename DerivedGW, typename DerivedGb>
void computeGradientCheck(const MatrixBase<DerivedIn> &predicted_embeddings,
const MatrixBase<DerivedGOutI> &samples,
const MatrixBase<DerivedGOutV> &weights,
const MatrixBase<DerivedGW> &gradient_W,
const MatrixBase<DerivedGb> &gradient_b) const
{
UNCONST(DerivedGW, gradient_W, my_gradient_W);
UNCONST(DerivedGb, gradient_b, my_gradient_b);
my_gradient_W.setZero();
my_gradient_b.setZero();
USCMatrix<double> gradient_output(W->rows(), samples, weights);
uscgemm(1.0,
gradient_output,
predicted_embeddings.leftCols(samples.cols()).transpose(),
my_gradient_W);
uscgemv(1.0, gradient_output,
Matrix<double,Dynamic,1>::Ones(weights.cols()), my_gradient_b);
}
};
class Input_word_embeddings
{
private:
Matrix<double,Dynamic,Dynamic,Eigen::RowMajor> *W;
int context_size, vocab_size;
Matrix<double,Dynamic,Dynamic> W_running_gradient;
Matrix<double,Dynamic,Dynamic> W_gradient;
friend class model;
public:
Input_word_embeddings() : context_size(0), vocab_size(0) { }
Input_word_embeddings(int rows, int cols, int context) { resize(rows, cols, context); }
void set_W(Matrix<double,Dynamic,Dynamic,Eigen::RowMajor> *input_W) {
W = input_W;
}
void resize(int rows, int cols, int context)
{
context_size = context;
vocab_size = rows;
W->setZero(rows, cols);
}
void read(std::ifstream &W_file) { readMatrix(W_file, *W); }
void write(std::ofstream &W_file) { writeMatrix(*W, W_file); }
template <typename Engine>
void initialize(Engine &engine, bool init_normal, double init_range)
{
initMatrix(engine,
*W,
init_normal,
init_range);
}
int n_inputs() const { return -1; }
int n_outputs() const { return W->cols() * context_size; }
// set output_id's embedding to the weighted average of all embeddings
template <typename Dist>
void average(const Dist &dist, int output_id)
{
W->row(output_id).setZero();
for (int i=0; i < W->rows(); i++)
if (i != output_id)
W->row(output_id) += dist.prob(i) * W->row(i);
}
template <typename DerivedIn, typename DerivedOut>
void fProp(const MatrixBase<DerivedIn> &input,
const MatrixBase<DerivedOut> &output) const
{
int embedding_dimension = W->cols();
// W is vocab_size x embedding_dimension
// input is ngram_size*vocab_size x minibatch_size
// output is ngram_size*embedding_dimension x minibatch_size
/*
// Dense version:
for (int ngram=0; ngram<context_size; ngram++)
output.middleRows(ngram*embedding_dimension, embedding_dimension) = W.transpose() * input.middleRows(ngram*vocab_size, vocab_size);
*/
UNCONST(DerivedOut, output, my_output);
my_output.setZero();
for (int ngram=0; ngram<context_size; ngram++)
{
// input might be narrower than expected due to a short minibatch,
// so narrow output to match
uscgemm(1.0,
W->transpose(),
USCMatrix<double>(W->rows(),input.middleRows(ngram, 1),Matrix<double,1,Dynamic>::Ones(input.cols())),
my_output.block(ngram*embedding_dimension, 0, embedding_dimension, input.cols()));
}
}
// When model is premultiplied, this layer doesn't get used,
// but this method is used to get the input into a sparse matrix.
// Hopefully this can get eliminated someday
template <typename DerivedIn, typename ScalarOut>
void munge(const MatrixBase<DerivedIn> &input, USCMatrix<ScalarOut> &output) const
{
output.resize(vocab_size*context_size, context_size, input.cols());
for (int i=0; i < context_size; i++)
output.indexes.row(i).array() = input.row(i).array() + i*vocab_size;
output.values.fill(1.0);
}
template <typename DerivedGOut, typename DerivedIn>
void computeGradient(const MatrixBase<DerivedGOut> &bProp_input,
const MatrixBase<DerivedIn> &input_words,
double learning_rate, double momentum, double L2_reg)
{
int embedding_dimension = W->cols();
// W is vocab_size x embedding_dimension
// input is ngram_size*vocab_size x minibatch_size
// bProp_input is ngram_size*embedding_dimension x minibatch_size
/*
// Dense version:
for (int ngram=0; ngram<context_size; ngram++)
W += learning_rate * input_words.middleRows(ngram*vocab_size, vocab_size) * bProp_input.middleRows(ngram*embedding_dimension, embedding_dimension).transpose()
*/
for (int ngram=0; ngram<context_size; ngram++)
{
uscgemm(learning_rate,
USCMatrix<double>(W->rows(), input_words.middleRows(ngram, 1), Matrix<double,1,Dynamic>::Ones(input_words.cols())),
bProp_input.block(ngram*embedding_dimension,0,embedding_dimension,input_words.cols()).transpose(),
*W);
}
}
template <typename DerivedGOut, typename DerivedIn>
void computeGradientAdagrad(const MatrixBase<DerivedGOut> &bProp_input,
const MatrixBase<DerivedIn> &input_words,
double learning_rate, double momentum, double L2_reg)
{
int embedding_dimension = W->cols();
W_gradient.setZero(W->rows(), W->cols());
if (W_running_gradient.rows() != W->rows() || W_running_gradient.cols() != W->cols())
W_running_gradient.setZero(W->rows(), W->cols());
for (int ngram=0; ngram<context_size; ngram++)
{
uscgemm(learning_rate,
USCMatrix<double>(W->rows(),input_words.middleRows(ngram, 1),Matrix<double,1,Dynamic>::Ones(input_words.cols())),
bProp_input.block(ngram*embedding_dimension, 0, embedding_dimension, input_words.cols()).transpose(),
W_gradient);
}
int_map update_map; //stores all the parameters that have been updated
for (int train_id=0; train_id<input_words.cols(); train_id++)
{
update_map[input_words(train_id)] = 1;
}
// Convert to std::vector for parallelization
std::vector<int> update_items;
for (int_map::iterator it = update_map.begin(); it != update_map.end(); ++it)
{
update_items.push_back(it->first);
}
int num_items = update_items.size();
#pragma omp parallel for
for (int item_id=0; item_id<num_items; item_id++)
{
int update_item = update_items[item_id];
W_running_gradient.row(update_item).array() += W_gradient.row(update_item).array().square();
W->row(update_item).array() += learning_rate * W_gradient.row(update_item).array() / W_running_gradient.row(update_item).array().sqrt();
}
}
template <typename DerivedGOut, typename DerivedIn, typename DerivedGW>
void computeGradientCheck(const MatrixBase<DerivedGOut> &bProp_input,
const MatrixBase<DerivedIn> &input_words,
int x, int minibatch_size,
const MatrixBase<DerivedGW> &gradient) const //not sure if we want to use momentum here
{
UNCONST(DerivedGW, gradient, my_gradient);
int embedding_dimension = W->cols();
my_gradient.setZero();
for (int ngram=0; ngram<context_size; ngram++)
uscgemm(1.0,
USCMatrix<double>(W->rows(),input_words.middleRows(ngram, 1),Matrix<double,1,Dynamic>::Ones(input_words.cols())),
bProp_input.block(ngram*embedding_dimension, 0, embedding_dimension, input_words.cols()).transpose(),
my_gradient);
}
};
} // namespace nplm
| 37.568138 | 167 | 0.66321 | [
"vector",
"model"
] |
afe225fa030a16d78bbd1eb597191808bbf834d6 | 136,711 | c | C | sys/platform/pc64/x86_64/pmap.c | mihaicarabas/dragonfly | 24da862f13a89f853ba0298c291319a87ef4f4d5 | [
"BSD-3-Clause"
] | 1 | 2016-05-03T05:46:32.000Z | 2016-05-03T05:46:32.000Z | sys/platform/pc64/x86_64/pmap.c | mihaicarabas/dragonfly | 24da862f13a89f853ba0298c291319a87ef4f4d5 | [
"BSD-3-Clause"
] | null | null | null | sys/platform/pc64/x86_64/pmap.c | mihaicarabas/dragonfly | 24da862f13a89f853ba0298c291319a87ef4f4d5 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 1991 Regents of the University of California.
* Copyright (c) 1994 John S. Dyson
* Copyright (c) 1994 David Greenman
* Copyright (c) 2003 Peter Wemm
* Copyright (c) 2005-2008 Alan L. Cox <alc@cs.rice.edu>
* Copyright (c) 2008, 2009 The DragonFly Project.
* Copyright (c) 2008, 2009 Jordan Gordeev.
* Copyright (c) 2011-2012 Matthew Dillon
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* the Systems Programming Group of the University of Utah Computer
* Science Department and William Jolitz of UUNET Technologies Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
*/
/*
* Manage physical address maps for x86-64 systems.
*/
#if JG
#include "opt_disable_pse.h"
#include "opt_pmap.h"
#endif
#include "opt_msgbuf.h"
#include <sys/param.h>
#include <sys/kernel.h>
#include <sys/proc.h>
#include <sys/msgbuf.h>
#include <sys/vmmeter.h>
#include <sys/mman.h>
#include <sys/systm.h>
#include <vm/vm.h>
#include <vm/vm_param.h>
#include <sys/sysctl.h>
#include <sys/lock.h>
#include <vm/vm_kern.h>
#include <vm/vm_page.h>
#include <vm/vm_map.h>
#include <vm/vm_object.h>
#include <vm/vm_extern.h>
#include <vm/vm_pageout.h>
#include <vm/vm_pager.h>
#include <vm/vm_zone.h>
#include <sys/user.h>
#include <sys/thread2.h>
#include <sys/sysref2.h>
#include <sys/spinlock2.h>
#include <vm/vm_page2.h>
#include <machine/cputypes.h>
#include <machine/md_var.h>
#include <machine/specialreg.h>
#include <machine/smp.h>
#include <machine_base/apic/apicreg.h>
#include <machine/globaldata.h>
#include <machine/pmap.h>
#include <machine/pmap_inval.h>
#include <machine/inttypes.h>
#include <ddb/ddb.h>
#define PMAP_KEEP_PDIRS
#ifndef PMAP_SHPGPERPROC
#define PMAP_SHPGPERPROC 2000
#endif
#if defined(DIAGNOSTIC)
#define PMAP_DIAGNOSTIC
#endif
#define MINPV 2048
/*
* pmap debugging will report who owns a pv lock when blocking.
*/
#ifdef PMAP_DEBUG
#define PMAP_DEBUG_DECL ,const char *func, int lineno
#define PMAP_DEBUG_ARGS , __func__, __LINE__
#define PMAP_DEBUG_COPY , func, lineno
#define pv_get(pmap, pindex) _pv_get(pmap, pindex \
PMAP_DEBUG_ARGS)
#define pv_lock(pv) _pv_lock(pv \
PMAP_DEBUG_ARGS)
#define pv_hold_try(pv) _pv_hold_try(pv \
PMAP_DEBUG_ARGS)
#define pv_alloc(pmap, pindex, isnewp) _pv_alloc(pmap, pindex, isnewp \
PMAP_DEBUG_ARGS)
#else
#define PMAP_DEBUG_DECL
#define PMAP_DEBUG_ARGS
#define PMAP_DEBUG_COPY
#define pv_get(pmap, pindex) _pv_get(pmap, pindex)
#define pv_lock(pv) _pv_lock(pv)
#define pv_hold_try(pv) _pv_hold_try(pv)
#define pv_alloc(pmap, pindex, isnewp) _pv_alloc(pmap, pindex, isnewp)
#endif
/*
* Get PDEs and PTEs for user/kernel address space
*/
#define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
#define pmap_pde_v(pmap, pte) ((*(pd_entry_t *)pte & pmap->pmap_bits[PG_V_IDX]) != 0)
#define pmap_pte_w(pmap, pte) ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_W_IDX]) != 0)
#define pmap_pte_m(pmap, pte) ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_M_IDX]) != 0)
#define pmap_pte_u(pmap, pte) ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_U_IDX]) != 0)
#define pmap_pte_v(pmap, pte) ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_V_IDX]) != 0)
/*
* Given a map and a machine independent protection code,
* convert to a vax protection code.
*/
#define pte_prot(m, p) \
(m->protection_codes[p & (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE)])
static int protection_codes[PROTECTION_CODES_SIZE];
struct pmap kernel_pmap;
static TAILQ_HEAD(,pmap) pmap_list = TAILQ_HEAD_INITIALIZER(pmap_list);
MALLOC_DEFINE(M_OBJPMAP, "objpmap", "pmaps associated with VM objects");
vm_paddr_t avail_start; /* PA of first available physical page */
vm_paddr_t avail_end; /* PA of last available physical page */
vm_offset_t virtual2_start; /* cutout free area prior to kernel start */
vm_offset_t virtual2_end;
vm_offset_t virtual_start; /* VA of first avail page (after kernel bss) */
vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
vm_offset_t KvaStart; /* VA start of KVA space */
vm_offset_t KvaEnd; /* VA end of KVA space (non-inclusive) */
vm_offset_t KvaSize; /* max size of kernel virtual address space */
static boolean_t pmap_initialized = FALSE; /* Has pmap_init completed? */
//static int pgeflag; /* PG_G or-in */
//static int pseflag; /* PG_PS or-in */
uint64_t PatMsr;
static int ndmpdp;
static vm_paddr_t dmaplimit;
static int nkpt;
vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
static pt_entry_t pat_pte_index[PAT_INDEX_SIZE]; /* PAT -> PG_ bits */
/*static pt_entry_t pat_pde_index[PAT_INDEX_SIZE];*/ /* PAT -> PG_ bits */
static uint64_t KPTbase;
static uint64_t KPTphys;
static uint64_t KPDphys; /* phys addr of kernel level 2 */
static uint64_t KPDbase; /* phys addr of kernel level 2 @ KERNBASE */
uint64_t KPDPphys; /* phys addr of kernel level 3 */
uint64_t KPML4phys; /* phys addr of kernel level 4 */
static uint64_t DMPDphys; /* phys addr of direct mapped level 2 */
static uint64_t DMPDPphys; /* phys addr of direct mapped level 3 */
/*
* Data for the pv entry allocation mechanism
*/
static vm_zone_t pvzone;
static struct vm_zone pvzone_store;
static struct vm_object pvzone_obj;
static int pv_entry_max=0, pv_entry_high_water=0;
static int pmap_pagedaemon_waken = 0;
static struct pv_entry *pvinit;
/*
* All those kernel PT submaps that BSD is so fond of
*/
pt_entry_t *CMAP1 = NULL, *ptmmap;
caddr_t CADDR1 = NULL, ptvmmap = NULL;
static pt_entry_t *msgbufmap;
struct msgbuf *msgbufp=NULL;
/*
* PMAP default PG_* bits. Needed to be able to add
* EPT/NPT pagetable pmap_bits for the VMM module
*/
uint64_t pmap_bits_default[] = {
REGULAR_PMAP, /* TYPE_IDX 0 */
X86_PG_V, /* PG_V_IDX 1 */
X86_PG_RW, /* PG_RW_IDX 2 */
X86_PG_U, /* PG_U_IDX 3 */
X86_PG_A, /* PG_A_IDX 4 */
X86_PG_M, /* PG_M_IDX 5 */
X86_PG_PS, /* PG_PS_IDX3 6 */
X86_PG_G, /* PG_G_IDX 7 */
X86_PG_AVAIL1, /* PG_AVAIL1_IDX 8 */
X86_PG_AVAIL2, /* PG_AVAIL2_IDX 9 */
X86_PG_AVAIL3, /* PG_AVAIL3_IDX 10 */
X86_PG_NC_PWT | X86_PG_NC_PCD, /* PG_N_IDX 11 */
};
/*
* Crashdump maps.
*/
static pt_entry_t *pt_crashdumpmap;
static caddr_t crashdumpmap;
#ifdef PMAP_DEBUG2
static int pmap_enter_debug = 0;
SYSCTL_INT(_machdep, OID_AUTO, pmap_enter_debug, CTLFLAG_RW,
&pmap_enter_debug, 0, "Debug pmap_enter's");
#endif
static int pmap_yield_count = 64;
SYSCTL_INT(_machdep, OID_AUTO, pmap_yield_count, CTLFLAG_RW,
&pmap_yield_count, 0, "Yield during init_pt/release");
static int pmap_mmu_optimize = 0;
SYSCTL_INT(_machdep, OID_AUTO, pmap_mmu_optimize, CTLFLAG_RW,
&pmap_mmu_optimize, 0, "Share page table pages when possible");
#define DISABLE_PSE
/* Standard user access funtions */
extern int std_copyinstr (const void *udaddr, void *kaddr, size_t len,
size_t *lencopied);
extern int std_copyin (const void *udaddr, void *kaddr, size_t len);
extern int std_copyout (const void *kaddr, void *udaddr, size_t len);
extern int std_fubyte (const void *base);
extern int std_subyte (void *base, int byte);
extern long std_fuword (const void *base);
extern int std_suword (void *base, long word);
extern int std_suword32 (void *base, int word);
static void pv_hold(pv_entry_t pv);
static int _pv_hold_try(pv_entry_t pv
PMAP_DEBUG_DECL);
static void pv_drop(pv_entry_t pv);
static void _pv_lock(pv_entry_t pv
PMAP_DEBUG_DECL);
static void pv_unlock(pv_entry_t pv);
static pv_entry_t _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew
PMAP_DEBUG_DECL);
static pv_entry_t _pv_get(pmap_t pmap, vm_pindex_t pindex
PMAP_DEBUG_DECL);
static pv_entry_t pv_get_try(pmap_t pmap, vm_pindex_t pindex, int *errorp);
static pv_entry_t pv_find(pmap_t pmap, vm_pindex_t pindex);
static void pv_put(pv_entry_t pv);
static void pv_free(pv_entry_t pv);
static void *pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex);
static pv_entry_t pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
pv_entry_t *pvpp);
static pv_entry_t pmap_allocpte_seg(pmap_t pmap, vm_pindex_t ptepindex,
pv_entry_t *pvpp, vm_map_entry_t entry, vm_offset_t va);
static void pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp,
struct pmap_inval_info *info);
static vm_page_t pmap_remove_pv_page(pv_entry_t pv);
static int pmap_release_pv(pv_entry_t pv, pv_entry_t pvp);
struct pmap_scan_info;
static void pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
pv_entry_t pte_pv, pv_entry_t pt_pv, int sharept,
vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
static void pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
pv_entry_t pte_pv, pv_entry_t pt_pv, int sharept,
vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
static void i386_protection_init (void);
static void create_pagetables(vm_paddr_t *firstaddr);
static void pmap_remove_all (vm_page_t m);
static boolean_t pmap_testbit (vm_page_t m, int bit);
static pt_entry_t * pmap_pte_quick (pmap_t pmap, vm_offset_t va);
static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
static void pmap_pinit_defaults(struct pmap *pmap);
static unsigned pdir4mb;
static int
pv_entry_compare(pv_entry_t pv1, pv_entry_t pv2)
{
if (pv1->pv_pindex < pv2->pv_pindex)
return(-1);
if (pv1->pv_pindex > pv2->pv_pindex)
return(1);
return(0);
}
RB_GENERATE2(pv_entry_rb_tree, pv_entry, pv_entry,
pv_entry_compare, vm_pindex_t, pv_pindex);
static __inline
void
pmap_page_stats_adding(vm_page_t m)
{
globaldata_t gd = mycpu;
if (TAILQ_EMPTY(&m->md.pv_list)) {
++gd->gd_vmtotal.t_arm;
} else if (TAILQ_FIRST(&m->md.pv_list) ==
TAILQ_LAST(&m->md.pv_list, md_page_pv_list)) {
++gd->gd_vmtotal.t_armshr;
++gd->gd_vmtotal.t_avmshr;
} else {
++gd->gd_vmtotal.t_avmshr;
}
}
static __inline
void
pmap_page_stats_deleting(vm_page_t m)
{
globaldata_t gd = mycpu;
if (TAILQ_EMPTY(&m->md.pv_list)) {
--gd->gd_vmtotal.t_arm;
} else if (TAILQ_FIRST(&m->md.pv_list) ==
TAILQ_LAST(&m->md.pv_list, md_page_pv_list)) {
--gd->gd_vmtotal.t_armshr;
--gd->gd_vmtotal.t_avmshr;
} else {
--gd->gd_vmtotal.t_avmshr;
}
}
/*
* Move the kernel virtual free pointer to the next
* 2MB. This is used to help improve performance
* by using a large (2MB) page for much of the kernel
* (.text, .data, .bss)
*/
static
vm_offset_t
pmap_kmem_choose(vm_offset_t addr)
{
vm_offset_t newaddr = addr;
newaddr = (addr + (NBPDR - 1)) & ~(NBPDR - 1);
return newaddr;
}
/*
* pmap_pte_quick:
*
* Super fast pmap_pte routine best used when scanning the pv lists.
* This eliminates many course-grained invltlb calls. Note that many of
* the pv list scans are across different pmaps and it is very wasteful
* to do an entire invltlb when checking a single mapping.
*/
static __inline pt_entry_t *pmap_pte(pmap_t pmap, vm_offset_t va);
static
pt_entry_t *
pmap_pte_quick(pmap_t pmap, vm_offset_t va)
{
return pmap_pte(pmap, va);
}
/*
* Returns the pindex of a page table entry (representing a terminal page).
* There are NUPTE_TOTAL page table entries possible (a huge number)
*
* x86-64 has a 48-bit address space, where bit 47 is sign-extended out.
* We want to properly translate negative KVAs.
*/
static __inline
vm_pindex_t
pmap_pte_pindex(vm_offset_t va)
{
return ((va >> PAGE_SHIFT) & (NUPTE_TOTAL - 1));
}
/*
* Returns the pindex of a page table.
*/
static __inline
vm_pindex_t
pmap_pt_pindex(vm_offset_t va)
{
return (NUPTE_TOTAL + ((va >> PDRSHIFT) & (NUPT_TOTAL - 1)));
}
/*
* Returns the pindex of a page directory.
*/
static __inline
vm_pindex_t
pmap_pd_pindex(vm_offset_t va)
{
return (NUPTE_TOTAL + NUPT_TOTAL +
((va >> PDPSHIFT) & (NUPD_TOTAL - 1)));
}
static __inline
vm_pindex_t
pmap_pdp_pindex(vm_offset_t va)
{
return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
((va >> PML4SHIFT) & (NUPDP_TOTAL - 1)));
}
static __inline
vm_pindex_t
pmap_pml4_pindex(void)
{
return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL + NUPDP_TOTAL);
}
/*
* Return various clipped indexes for a given VA
*
* Returns the index of a pte in a page table, representing a terminal
* page.
*/
static __inline
vm_pindex_t
pmap_pte_index(vm_offset_t va)
{
return ((va >> PAGE_SHIFT) & ((1ul << NPTEPGSHIFT) - 1));
}
/*
* Returns the index of a pt in a page directory, representing a page
* table.
*/
static __inline
vm_pindex_t
pmap_pt_index(vm_offset_t va)
{
return ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
}
/*
* Returns the index of a pd in a page directory page, representing a page
* directory.
*/
static __inline
vm_pindex_t
pmap_pd_index(vm_offset_t va)
{
return ((va >> PDPSHIFT) & ((1ul << NPDPEPGSHIFT) - 1));
}
/*
* Returns the index of a pdp in the pml4 table, representing a page
* directory page.
*/
static __inline
vm_pindex_t
pmap_pdp_index(vm_offset_t va)
{
return ((va >> PML4SHIFT) & ((1ul << NPML4EPGSHIFT) - 1));
}
/*
* Generic procedure to index a pte from a pt, pd, or pdp.
*
* NOTE: Normally passed pindex as pmap_xx_index(). pmap_xx_pindex() is NOT
* a page table page index but is instead of PV lookup index.
*/
static
void *
pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex)
{
pt_entry_t *pte;
pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pv->pv_m));
return(&pte[pindex]);
}
/*
* Return pointer to PDP slot in the PML4
*/
static __inline
pml4_entry_t *
pmap_pdp(pmap_t pmap, vm_offset_t va)
{
return (&pmap->pm_pml4[pmap_pdp_index(va)]);
}
/*
* Return pointer to PD slot in the PDP given a pointer to the PDP
*/
static __inline
pdp_entry_t *
pmap_pdp_to_pd(pml4_entry_t pdp_pte, vm_offset_t va)
{
pdp_entry_t *pd;
pd = (pdp_entry_t *)PHYS_TO_DMAP(pdp_pte & PG_FRAME);
return (&pd[pmap_pd_index(va)]);
}
/*
* Return pointer to PD slot in the PDP.
*/
static __inline
pdp_entry_t *
pmap_pd(pmap_t pmap, vm_offset_t va)
{
pml4_entry_t *pdp;
pdp = pmap_pdp(pmap, va);
if ((*pdp & pmap->pmap_bits[PG_V_IDX]) == 0)
return NULL;
return (pmap_pdp_to_pd(*pdp, va));
}
/*
* Return pointer to PT slot in the PD given a pointer to the PD
*/
static __inline
pd_entry_t *
pmap_pd_to_pt(pdp_entry_t pd_pte, vm_offset_t va)
{
pd_entry_t *pt;
pt = (pd_entry_t *)PHYS_TO_DMAP(pd_pte & PG_FRAME);
return (&pt[pmap_pt_index(va)]);
}
/*
* Return pointer to PT slot in the PD
*
* SIMPLE PMAP NOTE: Simple pmaps (embedded in objects) do not have PDPs,
* so we cannot lookup the PD via the PDP. Instead we
* must look it up via the pmap.
*/
static __inline
pd_entry_t *
pmap_pt(pmap_t pmap, vm_offset_t va)
{
pdp_entry_t *pd;
pv_entry_t pv;
vm_pindex_t pd_pindex;
if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
pd_pindex = pmap_pd_pindex(va);
spin_lock(&pmap->pm_spin);
pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pd_pindex);
spin_unlock(&pmap->pm_spin);
if (pv == NULL || pv->pv_m == NULL)
return NULL;
return (pmap_pd_to_pt(VM_PAGE_TO_PHYS(pv->pv_m), va));
} else {
pd = pmap_pd(pmap, va);
if (pd == NULL || (*pd & pmap->pmap_bits[PG_V_IDX]) == 0)
return NULL;
return (pmap_pd_to_pt(*pd, va));
}
}
/*
* Return pointer to PTE slot in the PT given a pointer to the PT
*/
static __inline
pt_entry_t *
pmap_pt_to_pte(pd_entry_t pt_pte, vm_offset_t va)
{
pt_entry_t *pte;
pte = (pt_entry_t *)PHYS_TO_DMAP(pt_pte & PG_FRAME);
return (&pte[pmap_pte_index(va)]);
}
/*
* Return pointer to PTE slot in the PT
*/
static __inline
pt_entry_t *
pmap_pte(pmap_t pmap, vm_offset_t va)
{
pd_entry_t *pt;
pt = pmap_pt(pmap, va);
if (pt == NULL || (*pt & pmap->pmap_bits[PG_V_IDX]) == 0)
return NULL;
if ((*pt & pmap->pmap_bits[PG_PS_IDX]) != 0)
return ((pt_entry_t *)pt);
return (pmap_pt_to_pte(*pt, va));
}
/*
* Of all the layers (PTE, PT, PD, PDP, PML4) the best one to cache is
* the PT layer. This will speed up core pmap operations considerably.
*
* NOTE: The pmap spinlock does not need to be held but the passed-in pv
* must be in a known associated state (typically by being locked when
* the pmap spinlock isn't held). We allow the race for that case.
*/
static __inline
void
pv_cache(pv_entry_t pv, vm_pindex_t pindex)
{
if (pindex >= pmap_pt_pindex(0) && pindex <= pmap_pd_pindex(0))
pv->pv_pmap->pm_pvhint = pv;
}
/*
* Return address of PT slot in PD (KVM only)
*
* Cannot be used for user page tables because it might interfere with
* the shared page-table-page optimization (pmap_mmu_optimize).
*/
static __inline
pd_entry_t *
vtopt(vm_offset_t va)
{
uint64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
NPML4EPGSHIFT)) - 1);
return (PDmap + ((va >> PDRSHIFT) & mask));
}
/*
* KVM - return address of PTE slot in PT
*/
static __inline
pt_entry_t *
vtopte(vm_offset_t va)
{
uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
return (PTmap + ((va >> PAGE_SHIFT) & mask));
}
static uint64_t
allocpages(vm_paddr_t *firstaddr, long n)
{
uint64_t ret;
ret = *firstaddr;
bzero((void *)ret, n * PAGE_SIZE);
*firstaddr += n * PAGE_SIZE;
return (ret);
}
static
void
create_pagetables(vm_paddr_t *firstaddr)
{
long i; /* must be 64 bits */
long nkpt_base;
long nkpt_phys;
int j;
/*
* We are running (mostly) V=P at this point
*
* Calculate NKPT - number of kernel page tables. We have to
* accomodoate prealloction of the vm_page_array, dump bitmap,
* MSGBUF_SIZE, and other stuff. Be generous.
*
* Maxmem is in pages.
*
* ndmpdp is the number of 1GB pages we wish to map.
*/
ndmpdp = (ptoa(Maxmem) + NBPDP - 1) >> PDPSHIFT;
if (ndmpdp < 4) /* Minimum 4GB of dirmap */
ndmpdp = 4;
KKASSERT(ndmpdp <= NKPDPE * NPDEPG);
/*
* Starting at the beginning of kvm (not KERNBASE).
*/
nkpt_phys = (Maxmem * sizeof(struct vm_page) + NBPDR - 1) / NBPDR;
nkpt_phys += (Maxmem * sizeof(struct pv_entry) + NBPDR - 1) / NBPDR;
nkpt_phys += ((nkpt + nkpt + 1 + NKPML4E + NKPDPE + NDMPML4E +
ndmpdp) + 511) / 512;
nkpt_phys += 128;
/*
* Starting at KERNBASE - map 2G worth of page table pages.
* KERNBASE is offset -2G from the end of kvm.
*/
nkpt_base = (NPDPEPG - KPDPI) * NPTEPG; /* typically 2 x 512 */
/*
* Allocate pages
*/
KPTbase = allocpages(firstaddr, nkpt_base);
KPTphys = allocpages(firstaddr, nkpt_phys);
KPML4phys = allocpages(firstaddr, 1);
KPDPphys = allocpages(firstaddr, NKPML4E);
KPDphys = allocpages(firstaddr, NKPDPE);
/*
* Calculate the page directory base for KERNBASE,
* that is where we start populating the page table pages.
* Basically this is the end - 2.
*/
KPDbase = KPDphys + ((NKPDPE - (NPDPEPG - KPDPI)) << PAGE_SHIFT);
DMPDPphys = allocpages(firstaddr, NDMPML4E);
if ((amd_feature & AMDID_PAGE1GB) == 0)
DMPDphys = allocpages(firstaddr, ndmpdp);
dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
/*
* Fill in the underlying page table pages for the area around
* KERNBASE. This remaps low physical memory to KERNBASE.
*
* Read-only from zero to physfree
* XXX not fully used, underneath 2M pages
*/
for (i = 0; (i << PAGE_SHIFT) < *firstaddr; i++) {
((pt_entry_t *)KPTbase)[i] = i << PAGE_SHIFT;
((pt_entry_t *)KPTbase)[i] |=
pmap_bits_default[PG_RW_IDX] |
pmap_bits_default[PG_V_IDX] |
pmap_bits_default[PG_G_IDX];
}
/*
* Now map the initial kernel page tables. One block of page
* tables is placed at the beginning of kernel virtual memory,
* and another block is placed at KERNBASE to map the kernel binary,
* data, bss, and initial pre-allocations.
*/
for (i = 0; i < nkpt_base; i++) {
((pd_entry_t *)KPDbase)[i] = KPTbase + (i << PAGE_SHIFT);
((pd_entry_t *)KPDbase)[i] |=
pmap_bits_default[PG_RW_IDX] |
pmap_bits_default[PG_V_IDX];
}
for (i = 0; i < nkpt_phys; i++) {
((pd_entry_t *)KPDphys)[i] = KPTphys + (i << PAGE_SHIFT);
((pd_entry_t *)KPDphys)[i] |=
pmap_bits_default[PG_RW_IDX] |
pmap_bits_default[PG_V_IDX];
}
/*
* Map from zero to end of allocations using 2M pages as an
* optimization. This will bypass some of the KPTBase pages
* above in the KERNBASE area.
*/
for (i = 0; (i << PDRSHIFT) < *firstaddr; i++) {
((pd_entry_t *)KPDbase)[i] = i << PDRSHIFT;
((pd_entry_t *)KPDbase)[i] |=
pmap_bits_default[PG_RW_IDX] |
pmap_bits_default[PG_V_IDX] |
pmap_bits_default[PG_PS_IDX] |
pmap_bits_default[PG_G_IDX];
}
/*
* And connect up the PD to the PDP. The kernel pmap is expected
* to pre-populate all of its PDs. See NKPDPE in vmparam.h.
*/
for (i = 0; i < NKPDPE; i++) {
((pdp_entry_t *)KPDPphys)[NPDPEPG - NKPDPE + i] =
KPDphys + (i << PAGE_SHIFT);
((pdp_entry_t *)KPDPphys)[NPDPEPG - NKPDPE + i] |=
pmap_bits_default[PG_RW_IDX] |
pmap_bits_default[PG_V_IDX] |
pmap_bits_default[PG_U_IDX];
}
/*
* Now set up the direct map space using either 2MB or 1GB pages
* Preset PG_M and PG_A because demotion expects it.
*
* When filling in entries in the PD pages make sure any excess
* entries are set to zero as we allocated enough PD pages
*/
if ((amd_feature & AMDID_PAGE1GB) == 0) {
for (i = 0; i < NPDEPG * ndmpdp; i++) {
((pd_entry_t *)DMPDphys)[i] = i << PDRSHIFT;
((pd_entry_t *)DMPDphys)[i] |=
pmap_bits_default[PG_RW_IDX] |
pmap_bits_default[PG_V_IDX] |
pmap_bits_default[PG_PS_IDX] |
pmap_bits_default[PG_G_IDX] |
pmap_bits_default[PG_M_IDX] |
pmap_bits_default[PG_A_IDX];
}
/*
* And the direct map space's PDP
*/
for (i = 0; i < ndmpdp; i++) {
((pdp_entry_t *)DMPDPphys)[i] = DMPDphys +
(i << PAGE_SHIFT);
((pdp_entry_t *)DMPDPphys)[i] |=
pmap_bits_default[PG_RW_IDX] |
pmap_bits_default[PG_V_IDX] |
pmap_bits_default[PG_U_IDX];
}
} else {
for (i = 0; i < ndmpdp; i++) {
((pdp_entry_t *)DMPDPphys)[i] =
(vm_paddr_t)i << PDPSHIFT;
((pdp_entry_t *)DMPDPphys)[i] |=
pmap_bits_default[PG_RW_IDX] |
pmap_bits_default[PG_V_IDX] |
pmap_bits_default[PG_PS_IDX] |
pmap_bits_default[PG_G_IDX] |
pmap_bits_default[PG_M_IDX] |
pmap_bits_default[PG_A_IDX];
}
}
/* And recursively map PML4 to itself in order to get PTmap */
((pdp_entry_t *)KPML4phys)[PML4PML4I] = KPML4phys;
((pdp_entry_t *)KPML4phys)[PML4PML4I] |=
pmap_bits_default[PG_RW_IDX] |
pmap_bits_default[PG_V_IDX] |
pmap_bits_default[PG_U_IDX];
/*
* Connect the Direct Map slots up to the PML4
*/
for (j = 0; j < NDMPML4E; ++j) {
((pdp_entry_t *)KPML4phys)[DMPML4I + j] =
(DMPDPphys + ((vm_paddr_t)j << PML4SHIFT)) |
pmap_bits_default[PG_RW_IDX] |
pmap_bits_default[PG_V_IDX] |
pmap_bits_default[PG_U_IDX];
}
/*
* Connect the KVA slot up to the PML4
*/
((pdp_entry_t *)KPML4phys)[KPML4I] = KPDPphys;
((pdp_entry_t *)KPML4phys)[KPML4I] |=
pmap_bits_default[PG_RW_IDX] |
pmap_bits_default[PG_V_IDX] |
pmap_bits_default[PG_U_IDX];
}
/*
* Bootstrap the system enough to run with virtual memory.
*
* On the i386 this is called after mapping has already been enabled
* and just syncs the pmap module with what has already been done.
* [We can't call it easily with mapping off since the kernel is not
* mapped with PA == VA, hence we would have to relocate every address
* from the linked base (virtual) address "KERNBASE" to the actual
* (physical) address starting relative to 0]
*/
void
pmap_bootstrap(vm_paddr_t *firstaddr)
{
vm_offset_t va;
pt_entry_t *pte;
KvaStart = VM_MIN_KERNEL_ADDRESS;
KvaEnd = VM_MAX_KERNEL_ADDRESS;
KvaSize = KvaEnd - KvaStart;
avail_start = *firstaddr;
/*
* Create an initial set of page tables to run the kernel in.
*/
create_pagetables(firstaddr);
virtual2_start = KvaStart;
virtual2_end = PTOV_OFFSET;
virtual_start = (vm_offset_t) PTOV_OFFSET + *firstaddr;
virtual_start = pmap_kmem_choose(virtual_start);
virtual_end = VM_MAX_KERNEL_ADDRESS;
/* XXX do %cr0 as well */
load_cr4(rcr4() | CR4_PGE | CR4_PSE);
load_cr3(KPML4phys);
/*
* Initialize protection array.
*/
i386_protection_init();
/*
* The kernel's pmap is statically allocated so we don't have to use
* pmap_create, which is unlikely to work correctly at this part of
* the boot sequence (XXX and which no longer exists).
*/
kernel_pmap.pm_pml4 = (pdp_entry_t *) (PTOV_OFFSET + KPML4phys);
kernel_pmap.pm_count = 1;
kernel_pmap.pm_active = (cpumask_t)-1 & ~CPUMASK_LOCK;
RB_INIT(&kernel_pmap.pm_pvroot);
spin_init(&kernel_pmap.pm_spin);
lwkt_token_init(&kernel_pmap.pm_token, "kpmap_tok");
/*
* Reserve some special page table entries/VA space for temporary
* mapping of pages.
*/
#define SYSMAP(c, p, v, n) \
v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
va = virtual_start;
pte = vtopte(va);
/*
* CMAP1/CMAP2 are used for zeroing and copying pages.
*/
SYSMAP(caddr_t, CMAP1, CADDR1, 1)
/*
* Crashdump maps.
*/
SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
/*
* ptvmmap is used for reading arbitrary physical pages via
* /dev/mem.
*/
SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
/*
* msgbufp is used to map the system message buffer.
* XXX msgbufmap is not used.
*/
SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
atop(round_page(MSGBUF_SIZE)))
virtual_start = va;
*CMAP1 = 0;
/*
* PG_G is terribly broken on SMP because we IPI invltlb's in some
* cases rather then invl1pg. Actually, I don't even know why it
* works under UP because self-referential page table mappings
*/
// pgeflag = 0;
/*
* Initialize the 4MB page size flag
*/
// pseflag = 0;
/*
* The 4MB page version of the initial
* kernel page mapping.
*/
pdir4mb = 0;
#if !defined(DISABLE_PSE)
if (cpu_feature & CPUID_PSE) {
pt_entry_t ptditmp;
/*
* Note that we have enabled PSE mode
*/
// pseflag = kernel_pmap.pmap_bits[PG_PS_IDX];
ptditmp = *(PTmap + x86_64_btop(KERNBASE));
ptditmp &= ~(NBPDR - 1);
ptditmp |= pmap_bits_default[PG_V_IDX] |
pmap_bits_default[PG_RW_IDX] |
pmap_bits_default[PG_PS_IDX] |
pmap_bits_default[PG_U_IDX];
// pgeflag;
pdir4mb = ptditmp;
}
#endif
cpu_invltlb();
/* Initialize the PAT MSR */
pmap_init_pat();
pmap_pinit_defaults(&kernel_pmap);
}
/*
* Setup the PAT MSR.
*/
void
pmap_init_pat(void)
{
uint64_t pat_msr;
u_long cr0, cr4;
/*
* Default values mapping PATi,PCD,PWT bits at system reset.
* The default values effectively ignore the PATi bit by
* repeating the encodings for 0-3 in 4-7, and map the PCD
* and PWT bit combinations to the expected PAT types.
*/
pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) | /* 000 */
PAT_VALUE(1, PAT_WRITE_THROUGH) | /* 001 */
PAT_VALUE(2, PAT_UNCACHED) | /* 010 */
PAT_VALUE(3, PAT_UNCACHEABLE) | /* 011 */
PAT_VALUE(4, PAT_WRITE_BACK) | /* 100 */
PAT_VALUE(5, PAT_WRITE_THROUGH) | /* 101 */
PAT_VALUE(6, PAT_UNCACHED) | /* 110 */
PAT_VALUE(7, PAT_UNCACHEABLE); /* 111 */
pat_pte_index[PAT_WRITE_BACK] = 0;
pat_pte_index[PAT_WRITE_THROUGH]= 0 | X86_PG_NC_PWT;
pat_pte_index[PAT_UNCACHED] = X86_PG_NC_PCD;
pat_pte_index[PAT_UNCACHEABLE] = X86_PG_NC_PCD | X86_PG_NC_PWT;
pat_pte_index[PAT_WRITE_PROTECTED] = pat_pte_index[PAT_UNCACHEABLE];
pat_pte_index[PAT_WRITE_COMBINING] = pat_pte_index[PAT_UNCACHEABLE];
if (cpu_feature & CPUID_PAT) {
/*
* If we support the PAT then set-up entries for
* WRITE_PROTECTED and WRITE_COMBINING using bit patterns
* 4 and 5.
*/
pat_msr = (pat_msr & ~PAT_MASK(4)) |
PAT_VALUE(4, PAT_WRITE_PROTECTED);
pat_msr = (pat_msr & ~PAT_MASK(5)) |
PAT_VALUE(5, PAT_WRITE_COMBINING);
pat_pte_index[PAT_WRITE_PROTECTED] = X86_PG_PTE_PAT | 0;
pat_pte_index[PAT_WRITE_COMBINING] = X86_PG_PTE_PAT | X86_PG_NC_PWT;
/*
* Then enable the PAT
*/
/* Disable PGE. */
cr4 = rcr4();
load_cr4(cr4 & ~CR4_PGE);
/* Disable caches (CD = 1, NW = 0). */
cr0 = rcr0();
load_cr0((cr0 & ~CR0_NW) | CR0_CD);
/* Flushes caches and TLBs. */
wbinvd();
cpu_invltlb();
/* Update PAT and index table. */
wrmsr(MSR_PAT, pat_msr);
/* Flush caches and TLBs again. */
wbinvd();
cpu_invltlb();
/* Restore caches and PGE. */
load_cr0(cr0);
load_cr4(cr4);
PatMsr = pat_msr;
}
}
/*
* Set 4mb pdir for mp startup
*/
void
pmap_set_opt(void)
{
if (cpu_feature & CPUID_PSE) {
load_cr4(rcr4() | CR4_PSE);
if (pdir4mb && mycpu->gd_cpuid == 0) { /* only on BSP */
cpu_invltlb();
}
}
}
/*
* Initialize the pmap module.
* Called by vm_init, to initialize any structures that the pmap
* system needs to map virtual memory.
* pmap_init has been enhanced to support in a fairly consistant
* way, discontiguous physical memory.
*/
void
pmap_init(void)
{
int i;
int initial_pvs;
/*
* Allocate memory for random pmap data structures. Includes the
* pv_head_table.
*/
for (i = 0; i < vm_page_array_size; i++) {
vm_page_t m;
m = &vm_page_array[i];
TAILQ_INIT(&m->md.pv_list);
}
/*
* init the pv free list
*/
initial_pvs = vm_page_array_size;
if (initial_pvs < MINPV)
initial_pvs = MINPV;
pvzone = &pvzone_store;
pvinit = (void *)kmem_alloc(&kernel_map,
initial_pvs * sizeof (struct pv_entry));
zbootinit(pvzone, "PV ENTRY", sizeof (struct pv_entry),
pvinit, initial_pvs);
/*
* Now it is safe to enable pv_table recording.
*/
pmap_initialized = TRUE;
}
/*
* Initialize the address space (zone) for the pv_entries. Set a
* high water mark so that the system can recover from excessive
* numbers of pv entries.
*/
void
pmap_init2(void)
{
int shpgperproc = PMAP_SHPGPERPROC;
int entry_max;
TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
pv_entry_max = shpgperproc * maxproc + vm_page_array_size;
TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
pv_entry_high_water = 9 * (pv_entry_max / 10);
/*
* Subtract out pages already installed in the zone (hack)
*/
entry_max = pv_entry_max - vm_page_array_size;
if (entry_max <= 0)
entry_max = 1;
zinitna(pvzone, &pvzone_obj, NULL, 0, entry_max, ZONE_INTERRUPT, 1);
}
/*
* Typically used to initialize a fictitious page by vm/device_pager.c
*/
void
pmap_page_init(struct vm_page *m)
{
vm_page_init(m);
TAILQ_INIT(&m->md.pv_list);
}
/***************************************************
* Low level helper routines.....
***************************************************/
/*
* this routine defines the region(s) of memory that should
* not be tested for the modified bit.
*/
static __inline
int
pmap_track_modified(vm_pindex_t pindex)
{
vm_offset_t va = (vm_offset_t)pindex << PAGE_SHIFT;
if ((va < clean_sva) || (va >= clean_eva))
return 1;
else
return 0;
}
/*
* Extract the physical page address associated with the map/VA pair.
* The page must be wired for this to work reliably.
*
* XXX for the moment we're using pv_find() instead of pv_get(), as
* callers might be expecting non-blocking operation.
*/
vm_paddr_t
pmap_extract(pmap_t pmap, vm_offset_t va)
{
vm_paddr_t rtval;
pv_entry_t pt_pv;
pt_entry_t *ptep;
rtval = 0;
if (va >= VM_MAX_USER_ADDRESS) {
/*
* Kernel page directories might be direct-mapped and
* there is typically no PV tracking of pte's
*/
pd_entry_t *pt;
pt = pmap_pt(pmap, va);
if (pt && (*pt & pmap->pmap_bits[PG_V_IDX])) {
if (*pt & pmap->pmap_bits[PG_PS_IDX]) {
rtval = *pt & PG_PS_FRAME;
rtval |= va & PDRMASK;
} else {
ptep = pmap_pt_to_pte(*pt, va);
if (*pt & pmap->pmap_bits[PG_V_IDX]) {
rtval = *ptep & PG_FRAME;
rtval |= va & PAGE_MASK;
}
}
}
} else {
/*
* User pages currently do not direct-map the page directory
* and some pages might not used managed PVs. But all PT's
* will have a PV.
*/
pt_pv = pv_find(pmap, pmap_pt_pindex(va));
if (pt_pv) {
ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
rtval = *ptep & PG_FRAME;
rtval |= va & PAGE_MASK;
}
pv_drop(pt_pv);
}
}
return rtval;
}
/*
* Similar to extract but checks protections, SMP-friendly short-cut for
* vm_fault_page[_quick](). Can return NULL to cause the caller to
* fall-through to the real fault code.
*
* The returned page, if not NULL, is held (and not busied).
*/
vm_page_t
pmap_fault_page_quick(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
{
if (pmap && va < VM_MAX_USER_ADDRESS) {
pv_entry_t pt_pv;
pv_entry_t pte_pv;
pt_entry_t *ptep;
pt_entry_t req;
vm_page_t m;
int error;
req = pmap->pmap_bits[PG_V_IDX] |
pmap->pmap_bits[PG_U_IDX];
if (prot & VM_PROT_WRITE)
req |= pmap->pmap_bits[PG_RW_IDX];
pt_pv = pv_find(pmap, pmap_pt_pindex(va));
if (pt_pv == NULL)
return (NULL);
ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
if ((*ptep & req) != req) {
pv_drop(pt_pv);
return (NULL);
}
pte_pv = pv_get_try(pmap, pmap_pte_pindex(va), &error);
if (pte_pv && error == 0) {
m = pte_pv->pv_m;
vm_page_hold(m);
if (prot & VM_PROT_WRITE)
vm_page_dirty(m);
pv_put(pte_pv);
} else if (pte_pv) {
pv_drop(pte_pv);
m = NULL;
} else {
m = NULL;
}
pv_drop(pt_pv);
return(m);
} else {
return(NULL);
}
}
/*
* Extract the physical page address associated kernel virtual address.
*/
vm_paddr_t
pmap_kextract(vm_offset_t va)
{
pd_entry_t pt; /* pt entry in pd */
vm_paddr_t pa;
if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
pa = DMAP_TO_PHYS(va);
} else {
pt = *vtopt(va);
if (pt & kernel_pmap.pmap_bits[PG_PS_IDX]) {
pa = (pt & PG_PS_FRAME) | (va & PDRMASK);
} else {
/*
* Beware of a concurrent promotion that changes the
* PDE at this point! For example, vtopte() must not
* be used to access the PTE because it would use the
* new PDE. It is, however, safe to use the old PDE
* because the page table page is preserved by the
* promotion.
*/
pa = *pmap_pt_to_pte(pt, va);
pa = (pa & PG_FRAME) | (va & PAGE_MASK);
}
}
return pa;
}
/***************************************************
* Low level mapping routines.....
***************************************************/
/*
* Routine: pmap_kenter
* Function:
* Add a wired page to the KVA
* NOTE! note that in order for the mapping to take effect -- you
* should do an invltlb after doing the pmap_kenter().
*/
void
pmap_kenter(vm_offset_t va, vm_paddr_t pa)
{
pt_entry_t *pte;
pt_entry_t npte;
pmap_inval_info info;
pmap_inval_init(&info); /* XXX remove */
npte = pa |
kernel_pmap.pmap_bits[PG_RW_IDX] |
kernel_pmap.pmap_bits[PG_V_IDX];
// pgeflag;
pte = vtopte(va);
pmap_inval_interlock(&info, &kernel_pmap, va); /* XXX remove */
*pte = npte;
pmap_inval_deinterlock(&info, &kernel_pmap); /* XXX remove */
pmap_inval_done(&info); /* XXX remove */
}
/*
* Routine: pmap_kenter_quick
* Function:
* Similar to pmap_kenter(), except we only invalidate the
* mapping on the current CPU.
*/
void
pmap_kenter_quick(vm_offset_t va, vm_paddr_t pa)
{
pt_entry_t *pte;
pt_entry_t npte;
npte = pa |
kernel_pmap.pmap_bits[PG_RW_IDX] |
kernel_pmap.pmap_bits[PG_V_IDX];
// pgeflag;
pte = vtopte(va);
*pte = npte;
cpu_invlpg((void *)va);
}
void
pmap_kenter_sync(vm_offset_t va)
{
pmap_inval_info info;
pmap_inval_init(&info);
pmap_inval_interlock(&info, &kernel_pmap, va);
pmap_inval_deinterlock(&info, &kernel_pmap);
pmap_inval_done(&info);
}
void
pmap_kenter_sync_quick(vm_offset_t va)
{
cpu_invlpg((void *)va);
}
/*
* remove a page from the kernel pagetables
*/
void
pmap_kremove(vm_offset_t va)
{
pt_entry_t *pte;
pmap_inval_info info;
pmap_inval_init(&info);
pte = vtopte(va);
pmap_inval_interlock(&info, &kernel_pmap, va);
(void)pte_load_clear(pte);
pmap_inval_deinterlock(&info, &kernel_pmap);
pmap_inval_done(&info);
}
void
pmap_kremove_quick(vm_offset_t va)
{
pt_entry_t *pte;
pte = vtopte(va);
(void)pte_load_clear(pte);
cpu_invlpg((void *)va);
}
/*
* XXX these need to be recoded. They are not used in any critical path.
*/
void
pmap_kmodify_rw(vm_offset_t va)
{
atomic_set_long(vtopte(va), kernel_pmap.pmap_bits[PG_RW_IDX]);
cpu_invlpg((void *)va);
}
/* NOT USED
void
pmap_kmodify_nc(vm_offset_t va)
{
atomic_set_long(vtopte(va), PG_N);
cpu_invlpg((void *)va);
}
*/
/*
* Used to map a range of physical addresses into kernel virtual
* address space during the low level boot, typically to map the
* dump bitmap, message buffer, and vm_page_array.
*
* These mappings are typically made at some pointer after the end of the
* kernel text+data.
*
* We could return PHYS_TO_DMAP(start) here and not allocate any
* via (*virtp), but then kmem from userland and kernel dumps won't
* have access to the related pointers.
*/
vm_offset_t
pmap_map(vm_offset_t *virtp, vm_paddr_t start, vm_paddr_t end, int prot)
{
vm_offset_t va;
vm_offset_t va_start;
/*return PHYS_TO_DMAP(start);*/
va_start = *virtp;
va = va_start;
while (start < end) {
pmap_kenter_quick(va, start);
va += PAGE_SIZE;
start += PAGE_SIZE;
}
*virtp = va;
return va_start;
}
#define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
/*
* Remove the specified set of pages from the data and instruction caches.
*
* In contrast to pmap_invalidate_cache_range(), this function does not
* rely on the CPU's self-snoop feature, because it is intended for use
* when moving pages into a different cache domain.
*/
void
pmap_invalidate_cache_pages(vm_page_t *pages, int count)
{
vm_offset_t daddr, eva;
int i;
if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
(cpu_feature & CPUID_CLFSH) == 0)
wbinvd();
else {
cpu_mfence();
for (i = 0; i < count; i++) {
daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
eva = daddr + PAGE_SIZE;
for (; daddr < eva; daddr += cpu_clflush_line_size)
clflush(daddr);
}
cpu_mfence();
}
}
void
pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
{
KASSERT((sva & PAGE_MASK) == 0,
("pmap_invalidate_cache_range: sva not page-aligned"));
KASSERT((eva & PAGE_MASK) == 0,
("pmap_invalidate_cache_range: eva not page-aligned"));
if (cpu_feature & CPUID_SS) {
; /* If "Self Snoop" is supported, do nothing. */
} else {
/* Globally invalidate caches */
cpu_wbinvd_on_all_cpus();
}
}
void
pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
{
smp_invlpg_range(pmap->pm_active, sva, eva);
}
/*
* Add a list of wired pages to the kva
* this routine is only used for temporary
* kernel mappings that do not need to have
* page modification or references recorded.
* Note that old mappings are simply written
* over. The page *must* be wired.
*/
void
pmap_qenter(vm_offset_t va, vm_page_t *m, int count)
{
vm_offset_t end_va;
end_va = va + count * PAGE_SIZE;
while (va < end_va) {
pt_entry_t *pte;
pte = vtopte(va);
*pte = VM_PAGE_TO_PHYS(*m) |
kernel_pmap.pmap_bits[PG_RW_IDX] |
kernel_pmap.pmap_bits[PG_V_IDX] |
kernel_pmap.pmap_cache_bits[(*m)->pat_mode];
// pgeflag;
cpu_invlpg((void *)va);
va += PAGE_SIZE;
m++;
}
smp_invltlb();
}
/*
* This routine jerks page mappings from the
* kernel -- it is meant only for temporary mappings.
*
* MPSAFE, INTERRUPT SAFE (cluster callback)
*/
void
pmap_qremove(vm_offset_t va, int count)
{
vm_offset_t end_va;
end_va = va + count * PAGE_SIZE;
while (va < end_va) {
pt_entry_t *pte;
pte = vtopte(va);
(void)pte_load_clear(pte);
cpu_invlpg((void *)va);
va += PAGE_SIZE;
}
smp_invltlb();
}
/*
* Create a new thread and optionally associate it with a (new) process.
* NOTE! the new thread's cpu may not equal the current cpu.
*/
void
pmap_init_thread(thread_t td)
{
/* enforce pcb placement & alignment */
td->td_pcb = (struct pcb *)(td->td_kstack + td->td_kstack_size) - 1;
td->td_pcb = (struct pcb *)((intptr_t)td->td_pcb & ~(intptr_t)0xF);
td->td_savefpu = &td->td_pcb->pcb_save;
td->td_sp = (char *)td->td_pcb; /* no -16 */
}
/*
* This routine directly affects the fork perf for a process.
*/
void
pmap_init_proc(struct proc *p)
{
}
static void
pmap_pinit_defaults(struct pmap *pmap)
{
bcopy(pmap_bits_default, pmap->pmap_bits,
sizeof(pmap_bits_default));
bcopy(protection_codes, pmap->protection_codes,
sizeof(protection_codes));
bcopy(pat_pte_index, pmap->pmap_cache_bits,
sizeof(pat_pte_index));
pmap->pmap_cache_mask = X86_PG_NC_PWT | X86_PG_NC_PCD | X86_PG_PTE_PAT;
pmap->copyinstr = std_copyinstr;
pmap->copyin = std_copyin;
pmap->copyout = std_copyout;
pmap->fubyte = std_fubyte;
pmap->subyte = std_subyte;
pmap->fuword = std_fuword;
pmap->suword = std_suword;
pmap->suword32 = std_suword32;
}
/*
* Initialize pmap0/vmspace0. This pmap is not added to pmap_list because
* it, and IdlePTD, represents the template used to update all other pmaps.
*
* On architectures where the kernel pmap is not integrated into the user
* process pmap, this pmap represents the process pmap, not the kernel pmap.
* kernel_pmap should be used to directly access the kernel_pmap.
*/
void
pmap_pinit0(struct pmap *pmap)
{
pmap->pm_pml4 = (pml4_entry_t *)(PTOV_OFFSET + KPML4phys);
pmap->pm_count = 1;
pmap->pm_active = 0;
pmap->pm_pvhint = NULL;
RB_INIT(&pmap->pm_pvroot);
spin_init(&pmap->pm_spin);
lwkt_token_init(&pmap->pm_token, "pmap_tok");
bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
pmap_pinit_defaults(pmap);
}
/*
* Initialize a preallocated and zeroed pmap structure,
* such as one in a vmspace structure.
*/
static void
pmap_pinit_simple(struct pmap *pmap)
{
/*
* Misc initialization
*/
pmap->pm_count = 1;
pmap->pm_active = 0;
pmap->pm_pvhint = NULL;
pmap->pm_flags = PMAP_FLAG_SIMPLE;
pmap_pinit_defaults(pmap);
/*
* Don't blow up locks/tokens on re-use (XXX fix/use drop code
* for this).
*/
if (pmap->pm_pmlpv == NULL) {
RB_INIT(&pmap->pm_pvroot);
bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
spin_init(&pmap->pm_spin);
lwkt_token_init(&pmap->pm_token, "pmap_tok");
}
}
void
pmap_pinit(struct pmap *pmap)
{
pv_entry_t pv;
int j;
if (pmap->pm_pmlpv) {
if (pmap->pmap_bits[TYPE_IDX] != REGULAR_PMAP) {
pmap_puninit(pmap);
}
}
pmap_pinit_simple(pmap);
pmap->pm_flags &= ~PMAP_FLAG_SIMPLE;
/*
* No need to allocate page table space yet but we do need a valid
* page directory table.
*/
if (pmap->pm_pml4 == NULL) {
pmap->pm_pml4 =
(pml4_entry_t *)kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
}
/*
* Allocate the page directory page, which wires it even though
* it isn't being entered into some higher level page table (it
* being the highest level). If one is already cached we don't
* have to do anything.
*/
if ((pv = pmap->pm_pmlpv) == NULL) {
pv = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
pmap->pm_pmlpv = pv;
pmap_kenter((vm_offset_t)pmap->pm_pml4,
VM_PAGE_TO_PHYS(pv->pv_m));
pv_put(pv);
/*
* Install DMAP and KMAP.
*/
for (j = 0; j < NDMPML4E; ++j) {
pmap->pm_pml4[DMPML4I + j] =
(DMPDPphys + ((vm_paddr_t)j << PML4SHIFT)) |
pmap->pmap_bits[PG_RW_IDX] |
pmap->pmap_bits[PG_V_IDX] |
pmap->pmap_bits[PG_U_IDX];
}
pmap->pm_pml4[KPML4I] = KPDPphys |
pmap->pmap_bits[PG_RW_IDX] |
pmap->pmap_bits[PG_V_IDX] |
pmap->pmap_bits[PG_U_IDX];
/*
* install self-referential address mapping entry
*/
pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pv->pv_m) |
pmap->pmap_bits[PG_V_IDX] |
pmap->pmap_bits[PG_RW_IDX] |
pmap->pmap_bits[PG_A_IDX] |
pmap->pmap_bits[PG_M_IDX];
} else {
KKASSERT(pv->pv_m->flags & PG_MAPPED);
KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
}
KKASSERT(pmap->pm_pml4[255] == 0);
KKASSERT(RB_ROOT(&pmap->pm_pvroot) == pv);
KKASSERT(pv->pv_entry.rbe_left == NULL);
KKASSERT(pv->pv_entry.rbe_right == NULL);
}
/*
* Clean up a pmap structure so it can be physically freed. This routine
* is called by the vmspace dtor function. A great deal of pmap data is
* left passively mapped to improve vmspace management so we have a bit
* of cleanup work to do here.
*/
void
pmap_puninit(pmap_t pmap)
{
pv_entry_t pv;
vm_page_t p;
KKASSERT(pmap->pm_active == 0);
if ((pv = pmap->pm_pmlpv) != NULL) {
if (pv_hold_try(pv) == 0)
pv_lock(pv);
KKASSERT(pv == pmap->pm_pmlpv);
p = pmap_remove_pv_page(pv);
pv_free(pv);
pmap_kremove((vm_offset_t)pmap->pm_pml4);
vm_page_busy_wait(p, FALSE, "pgpun");
KKASSERT(p->flags & (PG_FICTITIOUS|PG_UNMANAGED));
vm_page_unwire(p, 0);
vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
/*
* XXX eventually clean out PML4 static entries and
* use vm_page_free_zero()
*/
vm_page_free(p);
pmap->pm_pmlpv = NULL;
}
if (pmap->pm_pml4) {
KKASSERT(pmap->pm_pml4 != (void *)(PTOV_OFFSET + KPML4phys));
kmem_free(&kernel_map, (vm_offset_t)pmap->pm_pml4, PAGE_SIZE);
pmap->pm_pml4 = NULL;
}
KKASSERT(pmap->pm_stats.resident_count == 0);
KKASSERT(pmap->pm_stats.wired_count == 0);
}
/*
* Wire in kernel global address entries. To avoid a race condition
* between pmap initialization and pmap_growkernel, this procedure
* adds the pmap to the master list (which growkernel scans to update),
* then copies the template.
*/
void
pmap_pinit2(struct pmap *pmap)
{
spin_lock(&pmap_spin);
TAILQ_INSERT_TAIL(&pmap_list, pmap, pm_pmnode);
spin_unlock(&pmap_spin);
}
/*
* This routine is called when various levels in the page table need to
* be populated. This routine cannot fail.
*
* This function returns two locked pv_entry's, one representing the
* requested pv and one representing the requested pv's parent pv. If
* the pv did not previously exist it will be mapped into its parent
* and wired, otherwise no additional wire count will be added.
*/
static
pv_entry_t
pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, pv_entry_t *pvpp)
{
pt_entry_t *ptep;
pv_entry_t pv;
pv_entry_t pvp;
vm_pindex_t pt_pindex;
vm_page_t m;
int isnew;
int ispt;
/*
* If the pv already exists and we aren't being asked for the
* parent page table page we can just return it. A locked+held pv
* is returned. The pv will also have a second hold related to the
* pmap association that we don't have to worry about.
*/
ispt = 0;
pv = pv_alloc(pmap, ptepindex, &isnew);
if (isnew == 0 && pvpp == NULL)
return(pv);
/*
* Special case terminal PVs. These are not page table pages so
* no vm_page is allocated (the caller supplied the vm_page). If
* pvpp is non-NULL we are being asked to also removed the pt_pv
* for this pv.
*
* Note that pt_pv's are only returned for user VAs. We assert that
* a pt_pv is not being requested for kernel VAs.
*/
if (ptepindex < pmap_pt_pindex(0)) {
if (ptepindex >= NUPTE_USER)
KKASSERT(pvpp == NULL);
else
KKASSERT(pvpp != NULL);
if (pvpp) {
pt_pindex = NUPTE_TOTAL + (ptepindex >> NPTEPGSHIFT);
pvp = pmap_allocpte(pmap, pt_pindex, NULL);
if (isnew)
vm_page_wire_quick(pvp->pv_m);
*pvpp = pvp;
} else {
pvp = NULL;
}
return(pv);
}
/*
* Non-terminal PVs allocate a VM page to represent the page table,
* so we have to resolve pvp and calculate ptepindex for the pvp
* and then for the page table entry index in the pvp for
* fall-through.
*/
if (ptepindex < pmap_pd_pindex(0)) {
/*
* pv is PT, pvp is PD
*/
ptepindex = (ptepindex - pmap_pt_pindex(0)) >> NPDEPGSHIFT;
ptepindex += NUPTE_TOTAL + NUPT_TOTAL;
pvp = pmap_allocpte(pmap, ptepindex, NULL);
if (!isnew)
goto notnew;
/*
* PT index in PD
*/
ptepindex = pv->pv_pindex - pmap_pt_pindex(0);
ptepindex &= ((1ul << NPDEPGSHIFT) - 1);
ispt = 1;
} else if (ptepindex < pmap_pdp_pindex(0)) {
/*
* pv is PD, pvp is PDP
*
* SIMPLE PMAP NOTE: Simple pmaps do not allocate above
* the PD.
*/
ptepindex = (ptepindex - pmap_pd_pindex(0)) >> NPDPEPGSHIFT;
ptepindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
KKASSERT(pvpp == NULL);
pvp = NULL;
} else {
pvp = pmap_allocpte(pmap, ptepindex, NULL);
}
if (!isnew)
goto notnew;
/*
* PD index in PDP
*/
ptepindex = pv->pv_pindex - pmap_pd_pindex(0);
ptepindex &= ((1ul << NPDPEPGSHIFT) - 1);
} else if (ptepindex < pmap_pml4_pindex()) {
/*
* pv is PDP, pvp is the root pml4 table
*/
pvp = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
if (!isnew)
goto notnew;
/*
* PDP index in PML4
*/
ptepindex = pv->pv_pindex - pmap_pdp_pindex(0);
ptepindex &= ((1ul << NPML4EPGSHIFT) - 1);
} else {
/*
* pv represents the top-level PML4, there is no parent.
*/
pvp = NULL;
if (!isnew)
goto notnew;
}
/*
* This code is only reached if isnew is TRUE and this is not a
* terminal PV. We need to allocate a vm_page for the page table
* at this level and enter it into the parent page table.
*
* page table pages are marked PG_WRITEABLE and PG_MAPPED.
*/
for (;;) {
m = vm_page_alloc(NULL, pv->pv_pindex,
VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
VM_ALLOC_INTERRUPT);
if (m)
break;
vm_wait(0);
}
vm_page_spin_lock(m);
pmap_page_stats_adding(m);
TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
pv->pv_m = m;
vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE);
vm_page_spin_unlock(m);
vm_page_unmanage(m); /* m must be spinunlocked */
if ((m->flags & PG_ZERO) == 0) {
pmap_zero_page(VM_PAGE_TO_PHYS(m));
}
#ifdef PMAP_DEBUG
else {
pmap_page_assertzero(VM_PAGE_TO_PHYS(m));
}
#endif
m->valid = VM_PAGE_BITS_ALL;
vm_page_flag_clear(m, PG_ZERO);
vm_page_wire(m); /* wire for mapping in parent */
/*
* Wire the page into pvp, bump the wire-count for pvp's page table
* page. Bump the resident_count for the pmap. There is no pvp
* for the top level, address the pm_pml4[] array directly.
*
* If the caller wants the parent we return it, otherwise
* we just put it away.
*
* No interlock is needed for pte 0 -> non-zero.
*
* In the situation where *ptep is valid we might have an unmanaged
* page table page shared from another page table which we need to
* unshare before installing our private page table page.
*/
if (pvp) {
ptep = pv_pte_lookup(pvp, ptepindex);
if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
pt_entry_t pte;
pmap_inval_info info;
if (ispt == 0) {
panic("pmap_allocpte: unexpected pte %p/%d",
pvp, (int)ptepindex);
}
pmap_inval_init(&info);
pmap_inval_interlock(&info, pmap, (vm_offset_t)-1);
pte = pte_load_clear(ptep);
pmap_inval_deinterlock(&info, pmap);
pmap_inval_done(&info);
if (vm_page_unwire_quick(
PHYS_TO_VM_PAGE(pte & PG_FRAME))) {
panic("pmap_allocpte: shared pgtable "
"pg bad wirecount");
}
atomic_add_long(&pmap->pm_stats.resident_count, -1);
} else {
vm_page_wire_quick(pvp->pv_m);
}
*ptep = VM_PAGE_TO_PHYS(m) |
(pmap->pmap_bits[PG_U_IDX] |
pmap->pmap_bits[PG_RW_IDX] |
pmap->pmap_bits[PG_V_IDX] |
pmap->pmap_bits[PG_A_IDX] |
pmap->pmap_bits[PG_M_IDX]);
}
vm_page_wakeup(m);
notnew:
if (pvpp)
*pvpp = pvp;
else if (pvp)
pv_put(pvp);
return (pv);
}
/*
* This version of pmap_allocpte() checks for possible segment optimizations
* that would allow page-table sharing. It can be called for terminal
* page or page table page ptepindex's.
*
* The function is called with page table page ptepindex's for fictitious
* and unmanaged terminal pages. That is, we don't want to allocate a
* terminal pv, we just want the pt_pv. pvpp is usually passed as NULL
* for this case.
*
* This function can return a pv and *pvpp associated with the passed in pmap
* OR a pv and *pvpp associated with the shared pmap. In the latter case
* an unmanaged page table page will be entered into the pass in pmap.
*/
static
pv_entry_t
pmap_allocpte_seg(pmap_t pmap, vm_pindex_t ptepindex, pv_entry_t *pvpp,
vm_map_entry_t entry, vm_offset_t va)
{
struct pmap_inval_info info;
vm_object_t object;
pmap_t obpmap;
pmap_t *obpmapp;
vm_offset_t b;
pv_entry_t pte_pv; /* in original or shared pmap */
pv_entry_t pt_pv; /* in original or shared pmap */
pv_entry_t proc_pd_pv; /* in original pmap */
pv_entry_t proc_pt_pv; /* in original pmap */
pv_entry_t xpv; /* PT in shared pmap */
pd_entry_t *pt; /* PT entry in PD of original pmap */
pd_entry_t opte; /* contents of *pt */
pd_entry_t npte; /* contents of *pt */
vm_page_t m;
retry:
/*
* Basic tests, require a non-NULL vm_map_entry, require proper
* alignment and type for the vm_map_entry, require that the
* underlying object already be allocated.
*
* We allow almost any type of object to use this optimization.
* The object itself does NOT have to be sized to a multiple of the
* segment size, but the memory mapping does.
*
* XXX don't handle devices currently, because VM_PAGE_TO_PHYS()
* won't work as expected.
*/
if (entry == NULL ||
pmap_mmu_optimize == 0 || /* not enabled */
ptepindex >= pmap_pd_pindex(0) || /* not terminal or pt */
entry->inheritance != VM_INHERIT_SHARE || /* not shared */
entry->maptype != VM_MAPTYPE_NORMAL || /* weird map type */
entry->object.vm_object == NULL || /* needs VM object */
entry->object.vm_object->type == OBJT_DEVICE || /* ick */
entry->object.vm_object->type == OBJT_MGTDEVICE || /* ick */
(entry->offset & SEG_MASK) || /* must be aligned */
(entry->start & SEG_MASK)) {
return(pmap_allocpte(pmap, ptepindex, pvpp));
}
/*
* Make sure the full segment can be represented.
*/
b = va & ~(vm_offset_t)SEG_MASK;
if (b < entry->start || b + SEG_SIZE > entry->end)
return(pmap_allocpte(pmap, ptepindex, pvpp));
/*
* If the full segment can be represented dive the VM object's
* shared pmap, allocating as required.
*/
object = entry->object.vm_object;
if (entry->protection & VM_PROT_WRITE)
obpmapp = &object->md.pmap_rw;
else
obpmapp = &object->md.pmap_ro;
#ifdef PMAP_DEBUG2
if (pmap_enter_debug > 0) {
--pmap_enter_debug;
kprintf("pmap_allocpte_seg: va=%jx prot %08x o=%p "
"obpmapp %p %p\n",
va, entry->protection, object,
obpmapp, *obpmapp);
kprintf("pmap_allocpte_seg: entry %p %jx-%jx\n",
entry, entry->start, entry->end);
}
#endif
/*
* We allocate what appears to be a normal pmap but because portions
* of this pmap are shared with other unrelated pmaps we have to
* set pm_active to point to all cpus.
*
* XXX Currently using pmap_spin to interlock the update, can't use
* vm_object_hold/drop because the token might already be held
* shared OR exclusive and we don't know.
*/
while ((obpmap = *obpmapp) == NULL) {
obpmap = kmalloc(sizeof(*obpmap), M_OBJPMAP, M_WAITOK|M_ZERO);
pmap_pinit_simple(obpmap);
pmap_pinit2(obpmap);
spin_lock(&pmap_spin);
if (*obpmapp != NULL) {
/*
* Handle race
*/
spin_unlock(&pmap_spin);
pmap_release(obpmap);
pmap_puninit(obpmap);
kfree(obpmap, M_OBJPMAP);
obpmap = *obpmapp; /* safety */
} else {
obpmap->pm_active = smp_active_mask;
*obpmapp = obpmap;
spin_unlock(&pmap_spin);
}
}
/*
* Layering is: PTE, PT, PD, PDP, PML4. We have to return the
* pte/pt using the shared pmap from the object but also adjust
* the process pmap's page table page as a side effect.
*/
/*
* Resolve the terminal PTE and PT in the shared pmap. This is what
* we will return. This is true if ptepindex represents a terminal
* page, otherwise pte_pv is actually the PT and pt_pv is actually
* the PD.
*/
pt_pv = NULL;
pte_pv = pmap_allocpte(obpmap, ptepindex, &pt_pv);
if (ptepindex >= pmap_pt_pindex(0))
xpv = pte_pv;
else
xpv = pt_pv;
/*
* Resolve the PD in the process pmap so we can properly share the
* page table page. Lock order is bottom-up (leaf first)!
*
* NOTE: proc_pt_pv can be NULL.
*/
proc_pt_pv = pv_get(pmap, pmap_pt_pindex(b));
proc_pd_pv = pmap_allocpte(pmap, pmap_pd_pindex(b), NULL);
#ifdef PMAP_DEBUG2
if (pmap_enter_debug > 0) {
--pmap_enter_debug;
kprintf("proc_pt_pv %p (wc %d) pd_pv %p va=%jx\n",
proc_pt_pv,
(proc_pt_pv ? proc_pt_pv->pv_m->wire_count : -1),
proc_pd_pv,
va);
}
#endif
/*
* xpv is the page table page pv from the shared object
* (for convenience), from above.
*
* Calculate the pte value for the PT to load into the process PD.
* If we have to change it we must properly dispose of the previous
* entry.
*/
pt = pv_pte_lookup(proc_pd_pv, pmap_pt_index(b));
npte = VM_PAGE_TO_PHYS(xpv->pv_m) |
(pmap->pmap_bits[PG_U_IDX] |
pmap->pmap_bits[PG_RW_IDX] |
pmap->pmap_bits[PG_V_IDX] |
pmap->pmap_bits[PG_A_IDX] |
pmap->pmap_bits[PG_M_IDX]);
/*
* Dispose of previous page table page if it was local to the
* process pmap. If the old pt is not empty we cannot dispose of it
* until we clean it out. This case should not arise very often so
* it is not optimized.
*/
if (proc_pt_pv) {
if (proc_pt_pv->pv_m->wire_count != 1) {
pv_put(proc_pd_pv);
pv_put(proc_pt_pv);
pv_put(pt_pv);
pv_put(pte_pv);
pmap_remove(pmap,
va & ~(vm_offset_t)SEG_MASK,
(va + SEG_SIZE) & ~(vm_offset_t)SEG_MASK);
goto retry;
}
pmap_release_pv(proc_pt_pv, proc_pd_pv);
proc_pt_pv = NULL;
/* relookup */
pt = pv_pte_lookup(proc_pd_pv, pmap_pt_index(b));
}
/*
* Handle remaining cases.
*/
if (*pt == 0) {
*pt = npte;
vm_page_wire_quick(xpv->pv_m);
vm_page_wire_quick(proc_pd_pv->pv_m);
atomic_add_long(&pmap->pm_stats.resident_count, 1);
} else if (*pt != npte) {
pmap_inval_init(&info);
pmap_inval_interlock(&info, pmap, (vm_offset_t)-1);
opte = pte_load_clear(pt);
KKASSERT(opte && opte != npte);
*pt = npte;
vm_page_wire_quick(xpv->pv_m); /* pgtable pg that is npte */
/*
* Clean up opte, bump the wire_count for the process
* PD page representing the new entry if it was
* previously empty.
*
* If the entry was not previously empty and we have
* a PT in the proc pmap then opte must match that
* pt. The proc pt must be retired (this is done
* later on in this procedure).
*
* NOTE: replacing valid pte, wire_count on proc_pd_pv
* stays the same.
*/
KKASSERT(opte & pmap->pmap_bits[PG_V_IDX]);
m = PHYS_TO_VM_PAGE(opte & PG_FRAME);
if (vm_page_unwire_quick(m)) {
panic("pmap_allocpte_seg: "
"bad wire count %p",
m);
}
pmap_inval_deinterlock(&info, pmap);
pmap_inval_done(&info);
}
/*
* The existing process page table was replaced and must be destroyed
* here.
*/
if (proc_pd_pv)
pv_put(proc_pd_pv);
if (pvpp)
*pvpp = pt_pv;
else
pv_put(pt_pv);
return (pte_pv);
}
/*
* Release any resources held by the given physical map.
*
* Called when a pmap initialized by pmap_pinit is being released. Should
* only be called if the map contains no valid mappings.
*
* Caller must hold pmap->pm_token
*/
struct pmap_release_info {
pmap_t pmap;
int retry;
};
static int pmap_release_callback(pv_entry_t pv, void *data);
void
pmap_release(struct pmap *pmap)
{
struct pmap_release_info info;
KASSERT(pmap->pm_active == 0,
("pmap still active! %016jx", (uintmax_t)pmap->pm_active));
spin_lock(&pmap_spin);
TAILQ_REMOVE(&pmap_list, pmap, pm_pmnode);
spin_unlock(&pmap_spin);
/*
* Pull pv's off the RB tree in order from low to high and release
* each page.
*/
info.pmap = pmap;
do {
info.retry = 0;
spin_lock(&pmap->pm_spin);
RB_SCAN(pv_entry_rb_tree, &pmap->pm_pvroot, NULL,
pmap_release_callback, &info);
spin_unlock(&pmap->pm_spin);
} while (info.retry);
/*
* One resident page (the pml4 page) should remain.
* No wired pages should remain.
*/
KKASSERT(pmap->pm_stats.resident_count ==
((pmap->pm_flags & PMAP_FLAG_SIMPLE) ? 0 : 1));
KKASSERT(pmap->pm_stats.wired_count == 0);
}
static int
pmap_release_callback(pv_entry_t pv, void *data)
{
struct pmap_release_info *info = data;
pmap_t pmap = info->pmap;
int r;
if (pv_hold_try(pv)) {
spin_unlock(&pmap->pm_spin);
} else {
spin_unlock(&pmap->pm_spin);
pv_lock(pv);
}
if (pv->pv_pmap != pmap) {
pv_put(pv);
spin_lock(&pmap->pm_spin);
info->retry = 1;
return(-1);
}
r = pmap_release_pv(pv, NULL);
spin_lock(&pmap->pm_spin);
return(r);
}
/*
* Called with held (i.e. also locked) pv. This function will dispose of
* the lock along with the pv.
*
* If the caller already holds the locked parent page table for pv it
* must pass it as pvp, allowing us to avoid a deadlock, else it can
* pass NULL for pvp.
*/
static int
pmap_release_pv(pv_entry_t pv, pv_entry_t pvp)
{
vm_page_t p;
/*
* The pmap is currently not spinlocked, pv is held+locked.
* Remove the pv's page from its parent's page table. The
* parent's page table page's wire_count will be decremented.
*/
pmap_remove_pv_pte(pv, pvp, NULL);
/*
* Terminal pvs are unhooked from their vm_pages. Because
* terminal pages aren't page table pages they aren't wired
* by us, so we have to be sure not to unwire them either.
*/
if (pv->pv_pindex < pmap_pt_pindex(0)) {
pmap_remove_pv_page(pv);
goto skip;
}
/*
* We leave the top-level page table page cached, wired, and
* mapped in the pmap until the dtor function (pmap_puninit())
* gets called.
*
* Since we are leaving the top-level pv intact we need
* to break out of what would otherwise be an infinite loop.
*/
if (pv->pv_pindex == pmap_pml4_pindex()) {
pv_put(pv);
return(-1);
}
/*
* For page table pages (other than the top-level page),
* remove and free the vm_page. The representitive mapping
* removed above by pmap_remove_pv_pte() did not undo the
* last wire_count so we have to do that as well.
*/
p = pmap_remove_pv_page(pv);
vm_page_busy_wait(p, FALSE, "pmaprl");
if (p->wire_count != 1) {
kprintf("p->wire_count was %016lx %d\n",
pv->pv_pindex, p->wire_count);
}
KKASSERT(p->wire_count == 1);
KKASSERT(p->flags & PG_UNMANAGED);
vm_page_unwire(p, 0);
KKASSERT(p->wire_count == 0);
/*
* Theoretically this page, if not the pml4 page, should contain
* all-zeros. But its just too dangerous to mark it PG_ZERO. Free
* normally.
*/
vm_page_free(p);
skip:
pv_free(pv);
return 0;
}
/*
* This function will remove the pte associated with a pv from its parent.
* Terminal pv's are supported. The removal will be interlocked if info
* is non-NULL. The caller must dispose of pv instead of just unlocking
* it.
*
* The wire count will be dropped on the parent page table. The wire
* count on the page being removed (pv->pv_m) from the parent page table
* is NOT touched. Note that terminal pages will not have any additional
* wire counts while page table pages will have at least one representing
* the mapping, plus others representing sub-mappings.
*
* NOTE: Cannot be called on kernel page table pages, only KVM terminal
* pages and user page table and terminal pages.
*
* The pv must be locked.
*
* XXX must lock parent pv's if they exist to remove pte XXX
*/
static
void
pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp, struct pmap_inval_info *info)
{
vm_pindex_t ptepindex = pv->pv_pindex;
pmap_t pmap = pv->pv_pmap;
vm_page_t p;
int gotpvp = 0;
KKASSERT(pmap);
if (ptepindex == pmap_pml4_pindex()) {
/*
* We are the top level pml4 table, there is no parent.
*/
p = pmap->pm_pmlpv->pv_m;
} else if (ptepindex >= pmap_pdp_pindex(0)) {
/*
* Remove a PDP page from the pml4e. This can only occur
* with user page tables. We do not have to lock the
* pml4 PV so just ignore pvp.
*/
vm_pindex_t pml4_pindex;
vm_pindex_t pdp_index;
pml4_entry_t *pdp;
pdp_index = ptepindex - pmap_pdp_pindex(0);
if (pvp == NULL) {
pml4_pindex = pmap_pml4_pindex();
pvp = pv_get(pv->pv_pmap, pml4_pindex);
KKASSERT(pvp);
gotpvp = 1;
}
pdp = &pmap->pm_pml4[pdp_index & ((1ul << NPML4EPGSHIFT) - 1)];
KKASSERT((*pdp & pmap->pmap_bits[PG_V_IDX]) != 0);
p = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
*pdp = 0;
KKASSERT(info == NULL);
} else if (ptepindex >= pmap_pd_pindex(0)) {
/*
* Remove a PD page from the pdp
*
* SIMPLE PMAP NOTE: Non-existant pvp's are ok in the case
* of a simple pmap because it stops at
* the PD page.
*/
vm_pindex_t pdp_pindex;
vm_pindex_t pd_index;
pdp_entry_t *pd;
pd_index = ptepindex - pmap_pd_pindex(0);
if (pvp == NULL) {
pdp_pindex = NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
(pd_index >> NPML4EPGSHIFT);
pvp = pv_get(pv->pv_pmap, pdp_pindex);
if (pvp)
gotpvp = 1;
}
if (pvp) {
pd = pv_pte_lookup(pvp, pd_index &
((1ul << NPDPEPGSHIFT) - 1));
KKASSERT((*pd & pmap->pmap_bits[PG_V_IDX]) != 0);
p = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
*pd = 0;
} else {
KKASSERT(pmap->pm_flags & PMAP_FLAG_SIMPLE);
p = pv->pv_m; /* degenerate test later */
}
KKASSERT(info == NULL);
} else if (ptepindex >= pmap_pt_pindex(0)) {
/*
* Remove a PT page from the pd
*/
vm_pindex_t pd_pindex;
vm_pindex_t pt_index;
pd_entry_t *pt;
pt_index = ptepindex - pmap_pt_pindex(0);
if (pvp == NULL) {
pd_pindex = NUPTE_TOTAL + NUPT_TOTAL +
(pt_index >> NPDPEPGSHIFT);
pvp = pv_get(pv->pv_pmap, pd_pindex);
KKASSERT(pvp);
gotpvp = 1;
}
pt = pv_pte_lookup(pvp, pt_index & ((1ul << NPDPEPGSHIFT) - 1));
KKASSERT((*pt & pmap->pmap_bits[PG_V_IDX]) != 0);
p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
*pt = 0;
KKASSERT(info == NULL);
} else {
/*
* Remove a PTE from the PT page
*
* NOTE: pv's must be locked bottom-up to avoid deadlocking.
* pv is a pte_pv so we can safely lock pt_pv.
*
* NOTE: FICTITIOUS pages may have multiple physical mappings
* so PHYS_TO_VM_PAGE() will not necessarily work for
* terminal ptes.
*/
vm_pindex_t pt_pindex;
pt_entry_t *ptep;
pt_entry_t pte;
vm_offset_t va;
pt_pindex = ptepindex >> NPTEPGSHIFT;
va = (vm_offset_t)ptepindex << PAGE_SHIFT;
if (ptepindex >= NUPTE_USER) {
ptep = vtopte(ptepindex << PAGE_SHIFT);
KKASSERT(pvp == NULL);
} else {
if (pvp == NULL) {
pt_pindex = NUPTE_TOTAL +
(ptepindex >> NPDPEPGSHIFT);
pvp = pv_get(pv->pv_pmap, pt_pindex);
KKASSERT(pvp);
gotpvp = 1;
}
ptep = pv_pte_lookup(pvp, ptepindex &
((1ul << NPDPEPGSHIFT) - 1));
}
if (info)
pmap_inval_interlock(info, pmap, va);
pte = pte_load_clear(ptep);
if (info)
pmap_inval_deinterlock(info, pmap);
else
cpu_invlpg((void *)va);
/*
* Now update the vm_page_t
*/
if ((pte & (pmap->pmap_bits[PG_MANAGED_IDX] | pmap->pmap_bits[PG_V_IDX])) !=
(pmap->pmap_bits[PG_MANAGED_IDX]|pmap->pmap_bits[PG_V_IDX])) {
kprintf("remove_pte badpte %016lx %016lx %d\n",
pte, pv->pv_pindex,
pv->pv_pindex < pmap_pt_pindex(0));
}
/* PHYS_TO_VM_PAGE() will not work for FICTITIOUS pages */
/*KKASSERT((pte & (PG_MANAGED|PG_V)) == (PG_MANAGED|PG_V));*/
if (pte & pmap->pmap_bits[PG_DEVICE_IDX])
p = pv->pv_m;
else
p = PHYS_TO_VM_PAGE(pte & PG_FRAME);
/* p = pv->pv_m; */
if (pte & pmap->pmap_bits[PG_M_IDX]) {
if (pmap_track_modified(ptepindex))
vm_page_dirty(p);
}
if (pte & pmap->pmap_bits[PG_A_IDX]) {
vm_page_flag_set(p, PG_REFERENCED);
}
if (pte & pmap->pmap_bits[PG_W_IDX])
atomic_add_long(&pmap->pm_stats.wired_count, -1);
if (pte & pmap->pmap_bits[PG_G_IDX])
cpu_invlpg((void *)va);
}
/*
* Unwire the parent page table page. The wire_count cannot go below
* 1 here because the parent page table page is itself still mapped.
*
* XXX remove the assertions later.
*/
KKASSERT(pv->pv_m == p);
if (pvp && vm_page_unwire_quick(pvp->pv_m))
panic("pmap_remove_pv_pte: Insufficient wire_count");
if (gotpvp)
pv_put(pvp);
}
/*
* Remove the vm_page association to a pv. The pv must be locked.
*/
static
vm_page_t
pmap_remove_pv_page(pv_entry_t pv)
{
vm_page_t m;
m = pv->pv_m;
KKASSERT(m);
vm_page_spin_lock(m);
pv->pv_m = NULL;
TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
pmap_page_stats_deleting(m);
/*
if (m->object)
atomic_add_int(&m->object->agg_pv_list_count, -1);
*/
if (TAILQ_EMPTY(&m->md.pv_list))
vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
vm_page_spin_unlock(m);
return(m);
}
/*
* Grow the number of kernel page table entries, if needed.
*
* This routine is always called to validate any address space
* beyond KERNBASE (for kldloads). kernel_vm_end only governs the address
* space below KERNBASE.
*/
void
pmap_growkernel(vm_offset_t kstart, vm_offset_t kend)
{
vm_paddr_t paddr;
vm_offset_t ptppaddr;
vm_page_t nkpg;
pd_entry_t *pt, newpt;
pdp_entry_t newpd;
int update_kernel_vm_end;
/*
* bootstrap kernel_vm_end on first real VM use
*/
if (kernel_vm_end == 0) {
kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
nkpt = 0;
while ((*pmap_pt(&kernel_pmap, kernel_vm_end) & kernel_pmap.pmap_bits[PG_V_IDX]) != 0) {
kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) &
~(PAGE_SIZE * NPTEPG - 1);
nkpt++;
if (kernel_vm_end - 1 >= kernel_map.max_offset) {
kernel_vm_end = kernel_map.max_offset;
break;
}
}
}
/*
* Fill in the gaps. kernel_vm_end is only adjusted for ranges
* below KERNBASE. Ranges above KERNBASE are kldloaded and we
* do not want to force-fill 128G worth of page tables.
*/
if (kstart < KERNBASE) {
if (kstart > kernel_vm_end)
kstart = kernel_vm_end;
KKASSERT(kend <= KERNBASE);
update_kernel_vm_end = 1;
} else {
update_kernel_vm_end = 0;
}
kstart = rounddown2(kstart, PAGE_SIZE * NPTEPG);
kend = roundup2(kend, PAGE_SIZE * NPTEPG);
if (kend - 1 >= kernel_map.max_offset)
kend = kernel_map.max_offset;
while (kstart < kend) {
pt = pmap_pt(&kernel_pmap, kstart);
if (pt == NULL) {
/* We need a new PDP entry */
nkpg = vm_page_alloc(NULL, nkpt,
VM_ALLOC_NORMAL |
VM_ALLOC_SYSTEM |
VM_ALLOC_INTERRUPT);
if (nkpg == NULL) {
panic("pmap_growkernel: no memory to grow "
"kernel");
}
paddr = VM_PAGE_TO_PHYS(nkpg);
if ((nkpg->flags & PG_ZERO) == 0)
pmap_zero_page(paddr);
vm_page_flag_clear(nkpg, PG_ZERO);
newpd = (pdp_entry_t)
(paddr |
kernel_pmap.pmap_bits[PG_V_IDX] |
kernel_pmap.pmap_bits[PG_RW_IDX] |
kernel_pmap.pmap_bits[PG_A_IDX] |
kernel_pmap.pmap_bits[PG_M_IDX]);
*pmap_pd(&kernel_pmap, kstart) = newpd;
nkpt++;
continue; /* try again */
}
if ((*pt & kernel_pmap.pmap_bits[PG_V_IDX]) != 0) {
kstart = (kstart + PAGE_SIZE * NPTEPG) &
~(PAGE_SIZE * NPTEPG - 1);
if (kstart - 1 >= kernel_map.max_offset) {
kstart = kernel_map.max_offset;
break;
}
continue;
}
/*
* This index is bogus, but out of the way
*/
nkpg = vm_page_alloc(NULL, nkpt,
VM_ALLOC_NORMAL |
VM_ALLOC_SYSTEM |
VM_ALLOC_INTERRUPT);
if (nkpg == NULL)
panic("pmap_growkernel: no memory to grow kernel");
vm_page_wire(nkpg);
ptppaddr = VM_PAGE_TO_PHYS(nkpg);
pmap_zero_page(ptppaddr);
vm_page_flag_clear(nkpg, PG_ZERO);
newpt = (pd_entry_t) (ptppaddr |
kernel_pmap.pmap_bits[PG_V_IDX] |
kernel_pmap.pmap_bits[PG_RW_IDX] |
kernel_pmap.pmap_bits[PG_A_IDX] |
kernel_pmap.pmap_bits[PG_M_IDX]);
*pmap_pt(&kernel_pmap, kstart) = newpt;
nkpt++;
kstart = (kstart + PAGE_SIZE * NPTEPG) &
~(PAGE_SIZE * NPTEPG - 1);
if (kstart - 1 >= kernel_map.max_offset) {
kstart = kernel_map.max_offset;
break;
}
}
/*
* Only update kernel_vm_end for areas below KERNBASE.
*/
if (update_kernel_vm_end && kernel_vm_end < kstart)
kernel_vm_end = kstart;
}
/*
* Add a reference to the specified pmap.
*/
void
pmap_reference(pmap_t pmap)
{
if (pmap != NULL) {
lwkt_gettoken(&pmap->pm_token);
++pmap->pm_count;
lwkt_reltoken(&pmap->pm_token);
}
}
/***************************************************
* page management routines.
***************************************************/
/*
* Hold a pv without locking it
*/
static void
pv_hold(pv_entry_t pv)
{
atomic_add_int(&pv->pv_hold, 1);
}
/*
* Hold a pv_entry, preventing its destruction. TRUE is returned if the pv
* was successfully locked, FALSE if it wasn't. The caller must dispose of
* the pv properly.
*
* Either the pmap->pm_spin or the related vm_page_spin (if traversing a
* pv list via its page) must be held by the caller.
*/
static int
_pv_hold_try(pv_entry_t pv PMAP_DEBUG_DECL)
{
u_int count;
/*
* Critical path shortcut expects pv to already have one ref
* (for the pv->pv_pmap).
*/
if (atomic_cmpset_int(&pv->pv_hold, 1, PV_HOLD_LOCKED | 2)) {
#ifdef PMAP_DEBUG
pv->pv_func = func;
pv->pv_line = lineno;
#endif
return TRUE;
}
for (;;) {
count = pv->pv_hold;
cpu_ccfence();
if ((count & PV_HOLD_LOCKED) == 0) {
if (atomic_cmpset_int(&pv->pv_hold, count,
(count + 1) | PV_HOLD_LOCKED)) {
#ifdef PMAP_DEBUG
pv->pv_func = func;
pv->pv_line = lineno;
#endif
return TRUE;
}
} else {
if (atomic_cmpset_int(&pv->pv_hold, count, count + 1))
return FALSE;
}
/* retry */
}
}
/*
* Drop a previously held pv_entry which could not be locked, allowing its
* destruction.
*
* Must not be called with a spinlock held as we might zfree() the pv if it
* is no longer associated with a pmap and this was the last hold count.
*/
static void
pv_drop(pv_entry_t pv)
{
u_int count;
for (;;) {
count = pv->pv_hold;
cpu_ccfence();
KKASSERT((count & PV_HOLD_MASK) > 0);
KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) !=
(PV_HOLD_LOCKED | 1));
if (atomic_cmpset_int(&pv->pv_hold, count, count - 1)) {
if ((count & PV_HOLD_MASK) == 1) {
#ifdef PMAP_DEBUG2
if (pmap_enter_debug > 0) {
--pmap_enter_debug;
kprintf("pv_drop: free pv %p\n", pv);
}
#endif
KKASSERT(count == 1);
KKASSERT(pv->pv_pmap == NULL);
zfree(pvzone, pv);
}
return;
}
/* retry */
}
}
/*
* Find or allocate the requested PV entry, returning a locked, held pv.
*
* If (*isnew) is non-zero, the returned pv will have two hold counts, one
* for the caller and one representing the pmap and vm_page association.
*
* If (*isnew) is zero, the returned pv will have only one hold count.
*
* Since both associations can only be adjusted while the pv is locked,
* together they represent just one additional hold.
*/
static
pv_entry_t
_pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew PMAP_DEBUG_DECL)
{
pv_entry_t pv;
pv_entry_t pnew = NULL;
spin_lock(&pmap->pm_spin);
for (;;) {
if ((pv = pmap->pm_pvhint) == NULL || pv->pv_pindex != pindex) {
pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot,
pindex);
}
if (pv == NULL) {
if (pnew == NULL) {
spin_unlock(&pmap->pm_spin);
pnew = zalloc(pvzone);
spin_lock(&pmap->pm_spin);
continue;
}
pnew->pv_pmap = pmap;
pnew->pv_pindex = pindex;
pnew->pv_hold = PV_HOLD_LOCKED | 2;
#ifdef PMAP_DEBUG
pnew->pv_func = func;
pnew->pv_line = lineno;
#endif
pv_entry_rb_tree_RB_INSERT(&pmap->pm_pvroot, pnew);
++pmap->pm_generation;
atomic_add_long(&pmap->pm_stats.resident_count, 1);
spin_unlock(&pmap->pm_spin);
*isnew = 1;
return(pnew);
}
if (pnew) {
spin_unlock(&pmap->pm_spin);
zfree(pvzone, pnew);
pnew = NULL;
spin_lock(&pmap->pm_spin);
continue;
}
if (_pv_hold_try(pv PMAP_DEBUG_COPY)) {
spin_unlock(&pmap->pm_spin);
} else {
spin_unlock(&pmap->pm_spin);
_pv_lock(pv PMAP_DEBUG_COPY);
}
if (pv->pv_pmap == pmap && pv->pv_pindex == pindex) {
*isnew = 0;
return(pv);
}
pv_put(pv);
spin_lock(&pmap->pm_spin);
}
}
/*
* Find the requested PV entry, returning a locked+held pv or NULL
*/
static
pv_entry_t
_pv_get(pmap_t pmap, vm_pindex_t pindex PMAP_DEBUG_DECL)
{
pv_entry_t pv;
spin_lock(&pmap->pm_spin);
for (;;) {
/*
* Shortcut cache
*/
if ((pv = pmap->pm_pvhint) == NULL || pv->pv_pindex != pindex) {
pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot,
pindex);
}
if (pv == NULL) {
spin_unlock(&pmap->pm_spin);
return NULL;
}
if (_pv_hold_try(pv PMAP_DEBUG_COPY)) {
spin_unlock(&pmap->pm_spin);
} else {
spin_unlock(&pmap->pm_spin);
_pv_lock(pv PMAP_DEBUG_COPY);
}
if (pv->pv_pmap == pmap && pv->pv_pindex == pindex) {
pv_cache(pv, pindex);
return(pv);
}
pv_put(pv);
spin_lock(&pmap->pm_spin);
}
}
/*
* Lookup, hold, and attempt to lock (pmap,pindex).
*
* If the entry does not exist NULL is returned and *errorp is set to 0
*
* If the entry exists and could be successfully locked it is returned and
* errorp is set to 0.
*
* If the entry exists but could NOT be successfully locked it is returned
* held and *errorp is set to 1.
*/
static
pv_entry_t
pv_get_try(pmap_t pmap, vm_pindex_t pindex, int *errorp)
{
pv_entry_t pv;
spin_lock_shared(&pmap->pm_spin);
if ((pv = pmap->pm_pvhint) == NULL || pv->pv_pindex != pindex)
pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
if (pv == NULL) {
spin_unlock_shared(&pmap->pm_spin);
*errorp = 0;
return NULL;
}
if (pv_hold_try(pv)) {
pv_cache(pv, pindex);
spin_unlock_shared(&pmap->pm_spin);
*errorp = 0;
KKASSERT(pv->pv_pmap == pmap && pv->pv_pindex == pindex);
return(pv); /* lock succeeded */
}
spin_unlock_shared(&pmap->pm_spin);
*errorp = 1;
return (pv); /* lock failed */
}
/*
* Find the requested PV entry, returning a held pv or NULL
*/
static
pv_entry_t
pv_find(pmap_t pmap, vm_pindex_t pindex)
{
pv_entry_t pv;
spin_lock_shared(&pmap->pm_spin);
if ((pv = pmap->pm_pvhint) == NULL || pv->pv_pindex != pindex)
pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
if (pv == NULL) {
spin_unlock_shared(&pmap->pm_spin);
return NULL;
}
pv_hold(pv);
pv_cache(pv, pindex);
spin_unlock_shared(&pmap->pm_spin);
return(pv);
}
/*
* Lock a held pv, keeping the hold count
*/
static
void
_pv_lock(pv_entry_t pv PMAP_DEBUG_DECL)
{
u_int count;
for (;;) {
count = pv->pv_hold;
cpu_ccfence();
if ((count & PV_HOLD_LOCKED) == 0) {
if (atomic_cmpset_int(&pv->pv_hold, count,
count | PV_HOLD_LOCKED)) {
#ifdef PMAP_DEBUG
pv->pv_func = func;
pv->pv_line = lineno;
#endif
return;
}
continue;
}
tsleep_interlock(pv, 0);
if (atomic_cmpset_int(&pv->pv_hold, count,
count | PV_HOLD_WAITING)) {
#ifdef PMAP_DEBUG
kprintf("pv waiting on %s:%d\n",
pv->pv_func, pv->pv_line);
#endif
tsleep(pv, PINTERLOCKED, "pvwait", hz);
}
/* retry */
}
}
/*
* Unlock a held and locked pv, keeping the hold count.
*/
static
void
pv_unlock(pv_entry_t pv)
{
u_int count;
for (;;) {
count = pv->pv_hold;
cpu_ccfence();
KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) >=
(PV_HOLD_LOCKED | 1));
if (atomic_cmpset_int(&pv->pv_hold, count,
count &
~(PV_HOLD_LOCKED | PV_HOLD_WAITING))) {
if (count & PV_HOLD_WAITING)
wakeup(pv);
break;
}
}
}
/*
* Unlock and drop a pv. If the pv is no longer associated with a pmap
* and the hold count drops to zero we will free it.
*
* Caller should not hold any spin locks. We are protected from hold races
* by virtue of holds only occuring only with a pmap_spin or vm_page_spin
* lock held. A pv cannot be located otherwise.
*/
static
void
pv_put(pv_entry_t pv)
{
#ifdef PMAP_DEBUG2
if (pmap_enter_debug > 0) {
--pmap_enter_debug;
kprintf("pv_put pv=%p hold=%08x\n", pv, pv->pv_hold);
}
#endif
/*
* Fast - shortcut most common condition
*/
if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 1))
return;
/*
* Slow
*/
pv_unlock(pv);
pv_drop(pv);
}
/*
* Remove the pmap association from a pv, require that pv_m already be removed,
* then unlock and drop the pv. Any pte operations must have already been
* completed. This call may result in a last-drop which will physically free
* the pv.
*
* Removing the pmap association entails an additional drop.
*
* pv must be exclusively locked on call and will be disposed of on return.
*/
static
void
pv_free(pv_entry_t pv)
{
pmap_t pmap;
KKASSERT(pv->pv_m == NULL);
KKASSERT((pv->pv_hold & PV_HOLD_MASK) >= 2);
if ((pmap = pv->pv_pmap) != NULL) {
spin_lock(&pmap->pm_spin);
pv_entry_rb_tree_RB_REMOVE(&pmap->pm_pvroot, pv);
++pmap->pm_generation;
if (pmap->pm_pvhint == pv)
pmap->pm_pvhint = NULL;
atomic_add_long(&pmap->pm_stats.resident_count, -1);
pv->pv_pmap = NULL;
pv->pv_pindex = 0;
spin_unlock(&pmap->pm_spin);
/*
* Try to shortcut three atomic ops, otherwise fall through
* and do it normally. Drop two refs and the lock all in
* one go.
*/
if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 0)) {
#ifdef PMAP_DEBUG2
if (pmap_enter_debug > 0) {
--pmap_enter_debug;
kprintf("pv_free: free pv %p\n", pv);
}
#endif
zfree(pvzone, pv);
return;
}
pv_drop(pv); /* ref for pv_pmap */
}
pv_put(pv);
}
/*
* This routine is very drastic, but can save the system
* in a pinch.
*/
void
pmap_collect(void)
{
int i;
vm_page_t m;
static int warningdone=0;
if (pmap_pagedaemon_waken == 0)
return;
pmap_pagedaemon_waken = 0;
if (warningdone < 5) {
kprintf("pmap_collect: collecting pv entries -- "
"suggest increasing PMAP_SHPGPERPROC\n");
warningdone++;
}
for (i = 0; i < vm_page_array_size; i++) {
m = &vm_page_array[i];
if (m->wire_count || m->hold_count)
continue;
if (vm_page_busy_try(m, TRUE) == 0) {
if (m->wire_count == 0 && m->hold_count == 0) {
pmap_remove_all(m);
}
vm_page_wakeup(m);
}
}
}
/*
* Scan the pmap for active page table entries and issue a callback.
* The callback must dispose of pte_pv, whos PTE entry is at *ptep in
* its parent page table.
*
* pte_pv will be NULL if the page or page table is unmanaged.
* pt_pv will point to the page table page containing the pte for the page.
*
* NOTE! If we come across an unmanaged page TABLE (verses an unmanaged page),
* we pass a NULL pte_pv and we pass a pt_pv pointing to the passed
* process pmap's PD and page to the callback function. This can be
* confusing because the pt_pv is really a pd_pv, and the target page
* table page is simply aliased by the pmap and not owned by it.
*
* It is assumed that the start and end are properly rounded to the page size.
*
* It is assumed that PD pages and above are managed and thus in the RB tree,
* allowing us to use RB_SCAN from the PD pages down for ranged scans.
*/
struct pmap_scan_info {
struct pmap *pmap;
vm_offset_t sva;
vm_offset_t eva;
vm_pindex_t sva_pd_pindex;
vm_pindex_t eva_pd_pindex;
void (*func)(pmap_t, struct pmap_scan_info *,
pv_entry_t, pv_entry_t, int, vm_offset_t,
pt_entry_t *, void *);
void *arg;
int doinval;
struct pmap_inval_info inval;
};
static int pmap_scan_cmp(pv_entry_t pv, void *data);
static int pmap_scan_callback(pv_entry_t pv, void *data);
static void
pmap_scan(struct pmap_scan_info *info)
{
struct pmap *pmap = info->pmap;
pv_entry_t pd_pv; /* A page directory PV */
pv_entry_t pt_pv; /* A page table PV */
pv_entry_t pte_pv; /* A page table entry PV */
pt_entry_t *ptep;
pt_entry_t oldpte;
struct pv_entry dummy_pv;
int generation;
if (pmap == NULL)
return;
/*
* Hold the token for stability; if the pmap is empty we have nothing
* to do.
*/
lwkt_gettoken(&pmap->pm_token);
#if 0
if (pmap->pm_stats.resident_count == 0) {
lwkt_reltoken(&pmap->pm_token);
return;
}
#endif
pmap_inval_init(&info->inval);
again:
/*
* Special handling for scanning one page, which is a very common
* operation (it is?).
*
* NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4
*/
if (info->sva + PAGE_SIZE == info->eva) {
generation = pmap->pm_generation;
if (info->sva >= VM_MAX_USER_ADDRESS) {
/*
* Kernel mappings do not track wire counts on
* page table pages and only maintain pd_pv and
* pte_pv levels so pmap_scan() works.
*/
pt_pv = NULL;
pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva));
ptep = vtopte(info->sva);
} else {
/*
* User pages which are unmanaged will not have a
* pte_pv. User page table pages which are unmanaged
* (shared from elsewhere) will also not have a pt_pv.
* The func() callback will pass both pte_pv and pt_pv
* as NULL in that case.
*/
pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva));
pt_pv = pv_get(pmap, pmap_pt_pindex(info->sva));
if (pt_pv == NULL) {
KKASSERT(pte_pv == NULL);
pd_pv = pv_get(pmap, pmap_pd_pindex(info->sva));
if (pd_pv) {
ptep = pv_pte_lookup(pd_pv,
pmap_pt_index(info->sva));
if (*ptep) {
info->func(pmap, info,
NULL, pd_pv, 1,
info->sva, ptep,
info->arg);
}
pv_put(pd_pv);
}
goto fast_skip;
}
ptep = pv_pte_lookup(pt_pv, pmap_pte_index(info->sva));
}
/*
* NOTE: *ptep can't be ripped out from under us if we hold
* pte_pv locked, but bits can change. However, there is
* a race where another thread may be inserting pte_pv
* and setting *ptep just after our pte_pv lookup fails.
*
* In this situation we can end up with a NULL pte_pv
* but find that we have a managed *ptep. We explicitly
* check for this race.
*/
oldpte = *ptep;
cpu_ccfence();
if (oldpte == 0) {
/*
* Unlike the pv_find() case below we actually
* acquired a locked pv in this case so any
* race should have been resolved. It is expected
* to not exist.
*/
KKASSERT(pte_pv == NULL);
} else if (pte_pv) {
KASSERT((oldpte & (pmap->pmap_bits[PG_MANAGED_IDX] |
pmap->pmap_bits[PG_V_IDX])) ==
(pmap->pmap_bits[PG_MANAGED_IDX] |
pmap->pmap_bits[PG_V_IDX]),
("badA *ptep %016lx/%016lx sva %016lx pte_pv %p"
"generation %d/%d",
*ptep, oldpte, info->sva, pte_pv,
generation, pmap->pm_generation));
info->func(pmap, info, pte_pv, pt_pv, 0,
info->sva, ptep, info->arg);
} else {
/*
* Check for insertion race
*/
if ((oldpte & pmap->pmap_bits[PG_MANAGED_IDX]) &&
pt_pv) {
pte_pv = pv_find(pmap,
pmap_pte_pindex(info->sva));
if (pte_pv) {
pv_drop(pte_pv);
pv_put(pt_pv);
kprintf("pmap_scan: RACE1 "
"%016jx, %016lx\n",
info->sva, oldpte);
goto again;
}
}
/*
* Didn't race
*/
KASSERT((oldpte & (pmap->pmap_bits[PG_MANAGED_IDX] |
pmap->pmap_bits[PG_V_IDX])) ==
pmap->pmap_bits[PG_V_IDX],
("badB *ptep %016lx/%016lx sva %016lx pte_pv NULL"
"generation %d/%d",
*ptep, oldpte, info->sva,
generation, pmap->pm_generation));
info->func(pmap, info, NULL, pt_pv, 0,
info->sva, ptep, info->arg);
}
if (pt_pv)
pv_put(pt_pv);
fast_skip:
pmap_inval_done(&info->inval);
lwkt_reltoken(&pmap->pm_token);
return;
}
/*
* Nominal scan case, RB_SCAN() for PD pages and iterate from
* there.
*/
info->sva_pd_pindex = pmap_pd_pindex(info->sva);
info->eva_pd_pindex = pmap_pd_pindex(info->eva + NBPDP - 1);
if (info->sva >= VM_MAX_USER_ADDRESS) {
/*
* The kernel does not currently maintain any pv_entry's for
* higher-level page tables.
*/
bzero(&dummy_pv, sizeof(dummy_pv));
dummy_pv.pv_pindex = info->sva_pd_pindex;
spin_lock(&pmap->pm_spin);
while (dummy_pv.pv_pindex < info->eva_pd_pindex) {
pmap_scan_callback(&dummy_pv, info);
++dummy_pv.pv_pindex;
}
spin_unlock(&pmap->pm_spin);
} else {
/*
* User page tables maintain local PML4, PDP, and PD
* pv_entry's at the very least. PT pv's might be
* unmanaged and thus not exist. PTE pv's might be
* unmanaged and thus not exist.
*/
spin_lock(&pmap->pm_spin);
pv_entry_rb_tree_RB_SCAN(&pmap->pm_pvroot,
pmap_scan_cmp, pmap_scan_callback, info);
spin_unlock(&pmap->pm_spin);
}
pmap_inval_done(&info->inval);
lwkt_reltoken(&pmap->pm_token);
}
/*
* WARNING! pmap->pm_spin held
*/
static int
pmap_scan_cmp(pv_entry_t pv, void *data)
{
struct pmap_scan_info *info = data;
if (pv->pv_pindex < info->sva_pd_pindex)
return(-1);
if (pv->pv_pindex >= info->eva_pd_pindex)
return(1);
return(0);
}
/*
* WARNING! pmap->pm_spin held
*/
static int
pmap_scan_callback(pv_entry_t pv, void *data)
{
struct pmap_scan_info *info = data;
struct pmap *pmap = info->pmap;
pv_entry_t pd_pv; /* A page directory PV */
pv_entry_t pt_pv; /* A page table PV */
pv_entry_t pte_pv; /* A page table entry PV */
pt_entry_t *ptep;
pt_entry_t oldpte;
vm_offset_t sva;
vm_offset_t eva;
vm_offset_t va_next;
vm_pindex_t pd_pindex;
int error;
int generation;
/*
* Pull the PD pindex from the pv before releasing the spinlock.
*
* WARNING: pv is faked for kernel pmap scans.
*/
pd_pindex = pv->pv_pindex;
spin_unlock(&pmap->pm_spin);
pv = NULL; /* invalid after spinlock unlocked */
/*
* Calculate the page range within the PD. SIMPLE pmaps are
* direct-mapped for the entire 2^64 address space. Normal pmaps
* reflect the user and kernel address space which requires
* cannonicalization w/regards to converting pd_pindex's back
* into addresses.
*/
sva = (pd_pindex - NUPTE_TOTAL - NUPT_TOTAL) << PDPSHIFT;
if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0 &&
(sva & PML4_SIGNMASK)) {
sva |= PML4_SIGNMASK;
}
eva = sva + NBPDP; /* can overflow */
if (sva < info->sva)
sva = info->sva;
if (eva < info->sva || eva > info->eva)
eva = info->eva;
/*
* NOTE: kernel mappings do not track page table pages, only
* terminal pages.
*
* NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4.
* However, for the scan to be efficient we try to
* cache items top-down.
*/
pd_pv = NULL;
pt_pv = NULL;
for (; sva < eva; sva = va_next) {
if (sva >= VM_MAX_USER_ADDRESS) {
if (pt_pv) {
pv_put(pt_pv);
pt_pv = NULL;
}
goto kernel_skip;
}
/*
* PD cache (degenerate case if we skip). It is possible
* for the PD to not exist due to races. This is ok.
*/
if (pd_pv == NULL) {
pd_pv = pv_get(pmap, pmap_pd_pindex(sva));
} else if (pd_pv->pv_pindex != pmap_pd_pindex(sva)) {
pv_put(pd_pv);
pd_pv = pv_get(pmap, pmap_pd_pindex(sva));
}
if (pd_pv == NULL) {
va_next = (sva + NBPDP) & ~PDPMASK;
if (va_next < sva)
va_next = eva;
continue;
}
/*
* PT cache
*/
if (pt_pv == NULL) {
if (pd_pv) {
pv_put(pd_pv);
pd_pv = NULL;
}
pt_pv = pv_get(pmap, pmap_pt_pindex(sva));
} else if (pt_pv->pv_pindex != pmap_pt_pindex(sva)) {
if (pd_pv) {
pv_put(pd_pv);
pd_pv = NULL;
}
pv_put(pt_pv);
pt_pv = pv_get(pmap, pmap_pt_pindex(sva));
}
/*
* If pt_pv is NULL we either have an shared page table
* page and must issue a callback specific to that case,
* or there is no page table page.
*
* Either way we can skip the page table page.
*/
if (pt_pv == NULL) {
/*
* Possible unmanaged (shared from another pmap)
* page table page.
*/
if (pd_pv == NULL)
pd_pv = pv_get(pmap, pmap_pd_pindex(sva));
KKASSERT(pd_pv != NULL);
ptep = pv_pte_lookup(pd_pv, pmap_pt_index(sva));
if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
info->func(pmap, info, NULL, pd_pv, 1,
sva, ptep, info->arg);
}
/*
* Done, move to next page table page.
*/
va_next = (sva + NBPDR) & ~PDRMASK;
if (va_next < sva)
va_next = eva;
continue;
}
/*
* From this point in the loop testing pt_pv for non-NULL
* means we are in UVM, else if it is NULL we are in KVM.
*
* Limit our scan to either the end of the va represented
* by the current page table page, or to the end of the
* range being removed.
*/
kernel_skip:
va_next = (sva + NBPDR) & ~PDRMASK;
if (va_next < sva)
va_next = eva;
if (va_next > eva)
va_next = eva;
/*
* Scan the page table for pages. Some pages may not be
* managed (might not have a pv_entry).
*
* There is no page table management for kernel pages so
* pt_pv will be NULL in that case, but otherwise pt_pv
* is non-NULL, locked, and referenced.
*/
/*
* At this point a non-NULL pt_pv means a UVA, and a NULL
* pt_pv means a KVA.
*/
if (pt_pv)
ptep = pv_pte_lookup(pt_pv, pmap_pte_index(sva));
else
ptep = vtopte(sva);
while (sva < va_next) {
/*
* Acquire the related pte_pv, if any. If *ptep == 0
* the related pte_pv should not exist, but if *ptep
* is not zero the pte_pv may or may not exist (e.g.
* will not exist for an unmanaged page).
*
* However a multitude of races are possible here.
*
* In addition, the (pt_pv, pte_pv) lock order is
* backwards, so we have to be careful in aquiring
* a properly locked pte_pv.
*/
generation = pmap->pm_generation;
if (pt_pv) {
pte_pv = pv_get_try(pmap, pmap_pte_pindex(sva),
&error);
if (error) {
if (pd_pv) {
pv_put(pd_pv);
pd_pv = NULL;
}
pv_put(pt_pv); /* must be non-NULL */
pt_pv = NULL;
pv_lock(pte_pv); /* safe to block now */
pv_put(pte_pv);
pte_pv = NULL;
pt_pv = pv_get(pmap,
pmap_pt_pindex(sva));
/*
* pt_pv reloaded, need new ptep
*/
KKASSERT(pt_pv != NULL);
ptep = pv_pte_lookup(pt_pv,
pmap_pte_index(sva));
continue;
}
} else {
pte_pv = pv_get(pmap, pmap_pte_pindex(sva));
}
/*
* Ok, if *ptep == 0 we had better NOT have a pte_pv.
*/
oldpte = *ptep;
if (oldpte == 0) {
if (pte_pv) {
kprintf("Unexpected non-NULL pte_pv "
"%p pt_pv %p "
"*ptep = %016lx/%016lx\n",
pte_pv, pt_pv, *ptep, oldpte);
panic("Unexpected non-NULL pte_pv");
}
sva += PAGE_SIZE;
++ptep;
continue;
}
/*
* Ready for the callback. The locked pte_pv (if any)
* is consumed by the callback. pte_pv will exist if
* the page is managed, and will not exist if it
* isn't.
*/
if (pte_pv) {
KASSERT((oldpte & (pmap->pmap_bits[PG_MANAGED_IDX] | pmap->pmap_bits[PG_V_IDX])) ==
(pmap->pmap_bits[PG_MANAGED_IDX] | pmap->pmap_bits[PG_V_IDX]),
("badC *ptep %016lx/%016lx sva %016lx "
"pte_pv %p pm_generation %d/%d",
*ptep, oldpte, sva, pte_pv,
generation, pmap->pm_generation));
info->func(pmap, info, pte_pv, pt_pv, 0,
sva, ptep, info->arg);
} else {
/*
* Check for insertion race. Since there is no
* pte_pv to guard us it is possible for us
* to race another thread doing an insertion.
* Our lookup misses the pte_pv but our *ptep
* check sees the inserted pte.
*
* XXX panic case seems to occur within a
* vm_fork() of /bin/sh, which frankly
* shouldn't happen since no other threads
* should be inserting to our pmap in that
* situation. Removing, possibly. Inserting,
* shouldn't happen.
*/
if ((oldpte & pmap->pmap_bits[PG_MANAGED_IDX]) &&
pt_pv) {
pte_pv = pv_find(pmap,
pmap_pte_pindex(sva));
if (pte_pv) {
pv_drop(pte_pv);
kprintf("pmap_scan: RACE2 "
"%016jx, %016lx\n",
sva, oldpte);
continue;
}
}
/*
* Didn't race
*/
KASSERT((oldpte & (pmap->pmap_bits[PG_MANAGED_IDX] | pmap->pmap_bits[PG_V_IDX])) ==
pmap->pmap_bits[PG_V_IDX],
("badD *ptep %016lx/%016lx sva %016lx "
"pte_pv NULL pm_generation %d/%d",
*ptep, oldpte, sva,
generation, pmap->pm_generation));
info->func(pmap, info, NULL, pt_pv, 0,
sva, ptep, info->arg);
}
pte_pv = NULL;
sva += PAGE_SIZE;
++ptep;
}
lwkt_yield();
}
if (pd_pv) {
pv_put(pd_pv);
pd_pv = NULL;
}
if (pt_pv) {
pv_put(pt_pv);
pt_pv = NULL;
}
lwkt_yield();
/*
* Relock before returning.
*/
spin_lock(&pmap->pm_spin);
return (0);
}
void
pmap_remove(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
{
struct pmap_scan_info info;
info.pmap = pmap;
info.sva = sva;
info.eva = eva;
info.func = pmap_remove_callback;
info.arg = NULL;
info.doinval = 1; /* normal remove requires pmap inval */
pmap_scan(&info);
}
static void
pmap_remove_noinval(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
{
struct pmap_scan_info info;
info.pmap = pmap;
info.sva = sva;
info.eva = eva;
info.func = pmap_remove_callback;
info.arg = NULL;
info.doinval = 0; /* normal remove requires pmap inval */
pmap_scan(&info);
}
static void
pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
pv_entry_t pte_pv, pv_entry_t pt_pv, int sharept,
vm_offset_t va, pt_entry_t *ptep, void *arg __unused)
{
pt_entry_t pte;
if (pte_pv) {
/*
* This will also drop pt_pv's wire_count. Note that
* terminal pages are not wired based on mmu presence.
*/
if (info->doinval)
pmap_remove_pv_pte(pte_pv, pt_pv, &info->inval);
else
pmap_remove_pv_pte(pte_pv, pt_pv, NULL);
pmap_remove_pv_page(pte_pv);
pv_free(pte_pv);
} else if (sharept == 0) {
/*
* Unmanaged page
*
* pt_pv's wire_count is still bumped by unmanaged pages
* so we must decrement it manually.
*/
if (info->doinval)
pmap_inval_interlock(&info->inval, pmap, va);
pte = pte_load_clear(ptep);
if (info->doinval)
pmap_inval_deinterlock(&info->inval, pmap);
if (pte & pmap->pmap_bits[PG_W_IDX])
atomic_add_long(&pmap->pm_stats.wired_count, -1);
atomic_add_long(&pmap->pm_stats.resident_count, -1);
if (vm_page_unwire_quick(pt_pv->pv_m))
panic("pmap_remove: insufficient wirecount");
} else {
/*
* Unmanaged page table, pt_pv is actually the pd_pv
* for our pmap (not the share object pmap).
*
* We have to unwire the target page table page and we
* have to unwire our page directory page.
*/
if (info->doinval)
pmap_inval_interlock(&info->inval, pmap, va);
pte = pte_load_clear(ptep);
if (info->doinval)
pmap_inval_deinterlock(&info->inval, pmap);
atomic_add_long(&pmap->pm_stats.resident_count, -1);
KKASSERT((pte & pmap->pmap_bits[PG_DEVICE_IDX]) == 0);
if (vm_page_unwire_quick(PHYS_TO_VM_PAGE(pte & PG_FRAME)))
panic("pmap_remove: shared pgtable1 bad wirecount");
if (vm_page_unwire_quick(pt_pv->pv_m))
panic("pmap_remove: shared pgtable2 bad wirecount");
}
}
/*
* Removes this physical page from all physical maps in which it resides.
* Reflects back modify bits to the pager.
*
* This routine may not be called from an interrupt.
*/
static
void
pmap_remove_all(vm_page_t m)
{
struct pmap_inval_info info;
pv_entry_t pv;
if (!pmap_initialized /* || (m->flags & PG_FICTITIOUS)*/)
return;
pmap_inval_init(&info);
vm_page_spin_lock(m);
while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
KKASSERT(pv->pv_m == m);
if (pv_hold_try(pv)) {
vm_page_spin_unlock(m);
} else {
vm_page_spin_unlock(m);
pv_lock(pv);
}
if (pv->pv_m != m) {
pv_put(pv);
vm_page_spin_lock(m);
continue;
}
/*
* Holding no spinlocks, pv is locked.
*/
pmap_remove_pv_pte(pv, NULL, &info);
pmap_remove_pv_page(pv);
pv_free(pv);
vm_page_spin_lock(m);
}
KKASSERT((m->flags & (PG_MAPPED|PG_WRITEABLE)) == 0);
vm_page_spin_unlock(m);
pmap_inval_done(&info);
}
/*
* Set the physical protection on the specified range of this map
* as requested. This function is typically only used for debug watchpoints
* and COW pages.
*
* This function may not be called from an interrupt if the map is
* not the kernel_pmap.
*
* NOTE! For shared page table pages we just unmap the page.
*/
void
pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
{
struct pmap_scan_info info;
/* JG review for NX */
if (pmap == NULL)
return;
if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
pmap_remove(pmap, sva, eva);
return;
}
if (prot & VM_PROT_WRITE)
return;
info.pmap = pmap;
info.sva = sva;
info.eva = eva;
info.func = pmap_protect_callback;
info.arg = &prot;
info.doinval = 1;
pmap_scan(&info);
}
static
void
pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
pv_entry_t pte_pv, pv_entry_t pt_pv, int sharept,
vm_offset_t va, pt_entry_t *ptep, void *arg __unused)
{
pt_entry_t pbits;
pt_entry_t cbits;
pt_entry_t pte;
vm_page_t m;
/*
* XXX non-optimal.
*/
pmap_inval_interlock(&info->inval, pmap, va);
again:
pbits = *ptep;
cbits = pbits;
if (pte_pv) {
m = NULL;
if (pbits & pmap->pmap_bits[PG_A_IDX]) {
if ((pbits & pmap->pmap_bits[PG_DEVICE_IDX]) == 0) {
m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
KKASSERT(m == pte_pv->pv_m);
vm_page_flag_set(m, PG_REFERENCED);
}
cbits &= ~pmap->pmap_bits[PG_A_IDX];
}
if (pbits & pmap->pmap_bits[PG_M_IDX]) {
if (pmap_track_modified(pte_pv->pv_pindex)) {
if ((pbits & pmap->pmap_bits[PG_DEVICE_IDX]) == 0) {
if (m == NULL) {
m = PHYS_TO_VM_PAGE(pbits &
PG_FRAME);
}
vm_page_dirty(m);
}
cbits &= ~pmap->pmap_bits[PG_M_IDX];
}
}
} else if (sharept) {
/*
* Unmanaged page table, pt_pv is actually the pd_pv
* for our pmap (not the object's shared pmap).
*
* When asked to protect something in a shared page table
* page we just unmap the page table page. We have to
* invalidate the tlb in this situation.
*
* XXX Warning, shared page tables will not be used for
* OBJT_DEVICE or OBJT_MGTDEVICE (PG_FICTITIOUS) mappings
* so PHYS_TO_VM_PAGE() should be safe here.
*/
pte = pte_load_clear(ptep);
pmap_inval_invltlb(&info->inval);
if (vm_page_unwire_quick(PHYS_TO_VM_PAGE(pte & PG_FRAME)))
panic("pmap_protect: pgtable1 pg bad wirecount");
if (vm_page_unwire_quick(pt_pv->pv_m))
panic("pmap_protect: pgtable2 pg bad wirecount");
ptep = NULL;
}
/* else unmanaged page, adjust bits, no wire changes */
if (ptep) {
cbits &= ~pmap->pmap_bits[PG_RW_IDX];
#ifdef PMAP_DEBUG2
if (pmap_enter_debug > 0) {
--pmap_enter_debug;
kprintf("pmap_protect va=%lx ptep=%p pte_pv=%p "
"pt_pv=%p cbits=%08lx\n",
va, ptep, pte_pv,
pt_pv, cbits
);
}
#endif
if (pbits != cbits && !atomic_cmpset_long(ptep, pbits, cbits)) {
goto again;
}
}
pmap_inval_deinterlock(&info->inval, pmap);
if (pte_pv)
pv_put(pte_pv);
}
/*
* Insert the vm_page (m) at the virtual address (va), replacing any prior
* mapping at that address. Set protection and wiring as requested.
*
* If entry is non-NULL we check to see if the SEG_SIZE optimization is
* possible. If it is we enter the page into the appropriate shared pmap
* hanging off the related VM object instead of the passed pmap, then we
* share the page table page from the VM object's pmap into the current pmap.
*
* NOTE: This routine MUST insert the page into the pmap now, it cannot
* lazy-evaluate.
*/
void
pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
boolean_t wired, vm_map_entry_t entry)
{
pmap_inval_info info;
pv_entry_t pt_pv; /* page table */
pv_entry_t pte_pv; /* page table entry */
pt_entry_t *ptep;
vm_paddr_t opa;
pt_entry_t origpte, newpte;
vm_paddr_t pa;
if (pmap == NULL)
return;
va = trunc_page(va);
#ifdef PMAP_DIAGNOSTIC
if (va >= KvaEnd)
panic("pmap_enter: toobig");
if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
panic("pmap_enter: invalid to pmap_enter page table "
"pages (va: 0x%lx)", va);
#endif
if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
kprintf("Warning: pmap_enter called on UVA with "
"kernel_pmap\n");
#ifdef DDB
db_print_backtrace();
#endif
}
if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
kprintf("Warning: pmap_enter called on KVA without"
"kernel_pmap\n");
#ifdef DDB
db_print_backtrace();
#endif
}
/*
* Get locked PV entries for our new page table entry (pte_pv)
* and for its parent page table (pt_pv). We need the parent
* so we can resolve the location of the ptep.
*
* Only hardware MMU actions can modify the ptep out from
* under us.
*
* if (m) is fictitious or unmanaged we do not create a managing
* pte_pv for it. Any pre-existing page's management state must
* match (avoiding code complexity).
*
* If the pmap is still being initialized we assume existing
* page tables.
*
* Kernel mapppings do not track page table pages (i.e. pt_pv).
*/
if (pmap_initialized == FALSE) {
pte_pv = NULL;
pt_pv = NULL;
ptep = vtopte(va);
origpte = *ptep;
} else if (m->flags & (/*PG_FICTITIOUS |*/ PG_UNMANAGED)) { /* XXX */
pte_pv = NULL;
if (va >= VM_MAX_USER_ADDRESS) {
pt_pv = NULL;
ptep = vtopte(va);
} else {
pt_pv = pmap_allocpte_seg(pmap, pmap_pt_pindex(va),
NULL, entry, va);
ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
}
origpte = *ptep;
cpu_ccfence();
KKASSERT(origpte == 0 ||
(origpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0);
} else {
if (va >= VM_MAX_USER_ADDRESS) {
/*
* Kernel map, pv_entry-tracked.
*/
pt_pv = NULL;
pte_pv = pmap_allocpte(pmap, pmap_pte_pindex(va), NULL);
ptep = vtopte(va);
} else {
/*
* User map
*/
pte_pv = pmap_allocpte_seg(pmap, pmap_pte_pindex(va),
&pt_pv, entry, va);
ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
}
origpte = *ptep;
cpu_ccfence();
KKASSERT(origpte == 0 ||
(origpte & pmap->pmap_bits[PG_MANAGED_IDX]));
}
pa = VM_PAGE_TO_PHYS(m);
opa = origpte & PG_FRAME;
newpte = (pt_entry_t)(pa | pte_prot(pmap, prot) |
pmap->pmap_bits[PG_V_IDX] | pmap->pmap_bits[PG_A_IDX]);
if (wired)
newpte |= pmap->pmap_bits[PG_W_IDX];
if (va < VM_MAX_USER_ADDRESS)
newpte |= pmap->pmap_bits[PG_U_IDX];
if (pte_pv)
newpte |= pmap->pmap_bits[PG_MANAGED_IDX];
// if (pmap == &kernel_pmap)
// newpte |= pgeflag;
newpte |= pmap->pmap_cache_bits[m->pat_mode];
if (m->flags & PG_FICTITIOUS)
newpte |= pmap->pmap_bits[PG_DEVICE_IDX];
/*
* It is possible for multiple faults to occur in threaded
* environments, the existing pte might be correct.
*/
if (((origpte ^ newpte) & ~(pt_entry_t)(pmap->pmap_bits[PG_M_IDX] |
pmap->pmap_bits[PG_A_IDX])) == 0)
goto done;
if ((prot & VM_PROT_NOSYNC) == 0)
pmap_inval_init(&info);
/*
* Ok, either the address changed or the protection or wiring
* changed.
*
* Clear the current entry, interlocking the removal. For managed
* pte's this will also flush the modified state to the vm_page.
* Atomic ops are mandatory in order to ensure that PG_M events are
* not lost during any transition.
*
* WARNING: The caller has busied the new page but not the original
* vm_page which we are trying to replace. Because we hold
* the pte_pv lock, but have not busied the page, PG bits
* can be cleared out from under us.
*/
if (opa) {
if (pte_pv) {
/*
* pmap_remove_pv_pte() unwires pt_pv and assumes
* we will free pte_pv, but since we are reusing
* pte_pv we want to retain the wire count.
*
* pt_pv won't exist for a kernel page (managed or
* otherwise).
*/
if (pt_pv)
vm_page_wire_quick(pt_pv->pv_m);
if (prot & VM_PROT_NOSYNC)
pmap_remove_pv_pte(pte_pv, pt_pv, NULL);
else
pmap_remove_pv_pte(pte_pv, pt_pv, &info);
if (pte_pv->pv_m)
pmap_remove_pv_page(pte_pv);
} else if (prot & VM_PROT_NOSYNC) {
/*
* Unmanaged page, NOSYNC (no mmu sync) requested.
*
* Leave wire count on PT page intact.
*/
(void)pte_load_clear(ptep);
cpu_invlpg((void *)va);
atomic_add_long(&pmap->pm_stats.resident_count, -1);
} else {
/*
* Unmanaged page, normal enter.
*
* Leave wire count on PT page intact.
*/
pmap_inval_interlock(&info, pmap, va);
(void)pte_load_clear(ptep);
pmap_inval_deinterlock(&info, pmap);
atomic_add_long(&pmap->pm_stats.resident_count, -1);
}
KKASSERT(*ptep == 0);
}
#ifdef PMAP_DEBUG2
if (pmap_enter_debug > 0) {
--pmap_enter_debug;
kprintf("pmap_enter: va=%lx m=%p origpte=%lx newpte=%lx ptep=%p"
" pte_pv=%p pt_pv=%p opa=%lx prot=%02x\n",
va, m,
origpte, newpte, ptep,
pte_pv, pt_pv, opa, prot);
}
#endif
if (pte_pv) {
/*
* Enter on the PV list if part of our managed memory.
* Wiring of the PT page is already handled.
*/
KKASSERT(pte_pv->pv_m == NULL);
vm_page_spin_lock(m);
pte_pv->pv_m = m;
pmap_page_stats_adding(m);
TAILQ_INSERT_TAIL(&m->md.pv_list, pte_pv, pv_list);
vm_page_flag_set(m, PG_MAPPED);
vm_page_spin_unlock(m);
} else if (pt_pv && opa == 0) {
/*
* We have to adjust the wire count on the PT page ourselves
* for unmanaged entries. If opa was non-zero we retained
* the existing wire count from the removal.
*/
vm_page_wire_quick(pt_pv->pv_m);
}
/*
* Kernel VMAs (pt_pv == NULL) require pmap invalidation interlocks.
*
* User VMAs do not because those will be zero->non-zero, so no
* stale entries to worry about at this point.
*
* For KVM there appear to still be issues. Theoretically we
* should be able to scrap the interlocks entirely but we
* get crashes.
*/
if ((prot & VM_PROT_NOSYNC) == 0 && pt_pv == NULL)
pmap_inval_interlock(&info, pmap, va);
/*
* Set the pte
*/
*(volatile pt_entry_t *)ptep = newpte;
if ((prot & VM_PROT_NOSYNC) == 0 && pt_pv == NULL)
pmap_inval_deinterlock(&info, pmap);
else if (pt_pv == NULL)
cpu_invlpg((void *)va);
if (wired) {
if (pte_pv) {
atomic_add_long(&pte_pv->pv_pmap->pm_stats.wired_count,
1);
} else {
atomic_add_long(&pmap->pm_stats.wired_count, 1);
}
}
if (newpte & pmap->pmap_bits[PG_RW_IDX])
vm_page_flag_set(m, PG_WRITEABLE);
/*
* Unmanaged pages need manual resident_count tracking.
*/
if (pte_pv == NULL && pt_pv)
atomic_add_long(&pt_pv->pv_pmap->pm_stats.resident_count, 1);
/*
* Cleanup
*/
if ((prot & VM_PROT_NOSYNC) == 0 || pte_pv == NULL)
pmap_inval_done(&info);
done:
KKASSERT((newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0 ||
(m->flags & PG_MAPPED));
/*
* Cleanup the pv entry, allowing other accessors.
*/
if (pte_pv)
pv_put(pte_pv);
if (pt_pv)
pv_put(pt_pv);
}
/*
* This code works like pmap_enter() but assumes VM_PROT_READ and not-wired.
* This code also assumes that the pmap has no pre-existing entry for this
* VA.
*
* This code currently may only be used on user pmaps, not kernel_pmap.
*/
void
pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m)
{
pmap_enter(pmap, va, m, VM_PROT_READ, FALSE, NULL);
}
/*
* Make a temporary mapping for a physical address. This is only intended
* to be used for panic dumps.
*
* The caller is responsible for calling smp_invltlb().
*/
void *
pmap_kenter_temporary(vm_paddr_t pa, long i)
{
pmap_kenter_quick((vm_offset_t)crashdumpmap + (i * PAGE_SIZE), pa);
return ((void *)crashdumpmap);
}
#define MAX_INIT_PT (96)
/*
* This routine preloads the ptes for a given object into the specified pmap.
* This eliminates the blast of soft faults on process startup and
* immediately after an mmap.
*/
static int pmap_object_init_pt_callback(vm_page_t p, void *data);
void
pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_prot_t prot,
vm_object_t object, vm_pindex_t pindex,
vm_size_t size, int limit)
{
struct rb_vm_page_scan_info info;
struct lwp *lp;
vm_size_t psize;
/*
* We can't preinit if read access isn't set or there is no pmap
* or object.
*/
if ((prot & VM_PROT_READ) == 0 || pmap == NULL || object == NULL)
return;
/*
* We can't preinit if the pmap is not the current pmap
*/
lp = curthread->td_lwp;
if (lp == NULL || pmap != vmspace_pmap(lp->lwp_vmspace))
return;
/*
* Misc additional checks
*/
psize = x86_64_btop(size);
if ((object->type != OBJT_VNODE) ||
((limit & MAP_PREFAULT_PARTIAL) && (psize > MAX_INIT_PT) &&
(object->resident_page_count > MAX_INIT_PT))) {
return;
}
if (pindex + psize > object->size) {
if (object->size < pindex)
return;
psize = object->size - pindex;
}
if (psize == 0)
return;
/*
* If everything is segment-aligned do not pre-init here. Instead
* allow the normal vm_fault path to pass a segment hint to
* pmap_enter() which will then use an object-referenced shared
* page table page.
*/
if ((addr & SEG_MASK) == 0 &&
(ctob(psize) & SEG_MASK) == 0 &&
(ctob(pindex) & SEG_MASK) == 0) {
return;
}
/*
* Use a red-black scan to traverse the requested range and load
* any valid pages found into the pmap.
*
* We cannot safely scan the object's memq without holding the
* object token.
*/
info.start_pindex = pindex;
info.end_pindex = pindex + psize - 1;
info.limit = limit;
info.mpte = NULL;
info.addr = addr;
info.pmap = pmap;
vm_object_hold_shared(object);
vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
pmap_object_init_pt_callback, &info);
vm_object_drop(object);
}
static
int
pmap_object_init_pt_callback(vm_page_t p, void *data)
{
struct rb_vm_page_scan_info *info = data;
vm_pindex_t rel_index;
/*
* don't allow an madvise to blow away our really
* free pages allocating pv entries.
*/
if ((info->limit & MAP_PREFAULT_MADVISE) &&
vmstats.v_free_count < vmstats.v_free_reserved) {
return(-1);
}
/*
* Ignore list markers and ignore pages we cannot instantly
* busy (while holding the object token).
*/
if (p->flags & PG_MARKER)
return 0;
if (vm_page_busy_try(p, TRUE))
return 0;
if (((p->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
(p->flags & PG_FICTITIOUS) == 0) {
if ((p->queue - p->pc) == PQ_CACHE)
vm_page_deactivate(p);
rel_index = p->pindex - info->start_pindex;
pmap_enter_quick(info->pmap,
info->addr + x86_64_ptob(rel_index), p);
}
vm_page_wakeup(p);
lwkt_yield();
return(0);
}
/*
* Return TRUE if the pmap is in shape to trivially pre-fault the specified
* address.
*
* Returns FALSE if it would be non-trivial or if a pte is already loaded
* into the slot.
*
* XXX This is safe only because page table pages are not freed.
*/
int
pmap_prefault_ok(pmap_t pmap, vm_offset_t addr)
{
pt_entry_t *pte;
/*spin_lock(&pmap->pm_spin);*/
if ((pte = pmap_pte(pmap, addr)) != NULL) {
if (*pte & pmap->pmap_bits[PG_V_IDX]) {
/*spin_unlock(&pmap->pm_spin);*/
return FALSE;
}
}
/*spin_unlock(&pmap->pm_spin);*/
return TRUE;
}
/*
* Change the wiring attribute for a pmap/va pair. The mapping must already
* exist in the pmap. The mapping may or may not be managed.
*/
void
pmap_change_wiring(pmap_t pmap, vm_offset_t va, boolean_t wired,
vm_map_entry_t entry)
{
pt_entry_t *ptep;
pv_entry_t pv;
if (pmap == NULL)
return;
lwkt_gettoken(&pmap->pm_token);
pv = pmap_allocpte_seg(pmap, pmap_pt_pindex(va), NULL, entry, va);
ptep = pv_pte_lookup(pv, pmap_pte_index(va));
if (wired && !pmap_pte_w(pmap, ptep))
atomic_add_long(&pv->pv_pmap->pm_stats.wired_count, 1);
else if (!wired && pmap_pte_w(pmap, ptep))
atomic_add_long(&pv->pv_pmap->pm_stats.wired_count, -1);
/*
* Wiring is not a hardware characteristic so there is no need to
* invalidate TLB. However, in an SMP environment we must use
* a locked bus cycle to update the pte (if we are not using
* the pmap_inval_*() API that is)... it's ok to do this for simple
* wiring changes.
*/
if (wired)
atomic_set_long(ptep, pmap->pmap_bits[PG_W_IDX]);
else
atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
pv_put(pv);
lwkt_reltoken(&pmap->pm_token);
}
/*
* Copy the range specified by src_addr/len from the source map to
* the range dst_addr/len in the destination map.
*
* This routine is only advisory and need not do anything.
*/
void
pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr,
vm_size_t len, vm_offset_t src_addr)
{
}
/*
* pmap_zero_page:
*
* Zero the specified physical page.
*
* This function may be called from an interrupt and no locking is
* required.
*/
void
pmap_zero_page(vm_paddr_t phys)
{
vm_offset_t va = PHYS_TO_DMAP(phys);
pagezero((void *)va);
}
/*
* pmap_page_assertzero:
*
* Assert that a page is empty, panic if it isn't.
*/
void
pmap_page_assertzero(vm_paddr_t phys)
{
vm_offset_t va = PHYS_TO_DMAP(phys);
size_t i;
for (i = 0; i < PAGE_SIZE; i += sizeof(long)) {
if (*(long *)((char *)va + i) != 0) {
panic("pmap_page_assertzero() @ %p not zero!",
(void *)(intptr_t)va);
}
}
}
/*
* pmap_zero_page:
*
* Zero part of a physical page by mapping it into memory and clearing
* its contents with bzero.
*
* off and size may not cover an area beyond a single hardware page.
*/
void
pmap_zero_page_area(vm_paddr_t phys, int off, int size)
{
vm_offset_t virt = PHYS_TO_DMAP(phys);
bzero((char *)virt + off, size);
}
/*
* pmap_copy_page:
*
* Copy the physical page from the source PA to the target PA.
* This function may be called from an interrupt. No locking
* is required.
*/
void
pmap_copy_page(vm_paddr_t src, vm_paddr_t dst)
{
vm_offset_t src_virt, dst_virt;
src_virt = PHYS_TO_DMAP(src);
dst_virt = PHYS_TO_DMAP(dst);
bcopy((void *)src_virt, (void *)dst_virt, PAGE_SIZE);
}
/*
* pmap_copy_page_frag:
*
* Copy the physical page from the source PA to the target PA.
* This function may be called from an interrupt. No locking
* is required.
*/
void
pmap_copy_page_frag(vm_paddr_t src, vm_paddr_t dst, size_t bytes)
{
vm_offset_t src_virt, dst_virt;
src_virt = PHYS_TO_DMAP(src);
dst_virt = PHYS_TO_DMAP(dst);
bcopy((char *)src_virt + (src & PAGE_MASK),
(char *)dst_virt + (dst & PAGE_MASK),
bytes);
}
/*
* Returns true if the pmap's pv is one of the first 16 pvs linked to from
* this page. This count may be changed upwards or downwards in the future;
* it is only necessary that true be returned for a small subset of pmaps
* for proper page aging.
*/
boolean_t
pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
{
pv_entry_t pv;
int loops = 0;
if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
return FALSE;
vm_page_spin_lock(m);
TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
if (pv->pv_pmap == pmap) {
vm_page_spin_unlock(m);
return TRUE;
}
loops++;
if (loops >= 16)
break;
}
vm_page_spin_unlock(m);
return (FALSE);
}
/*
* Remove all pages from specified address space this aids process exit
* speeds. Also, this code may be special cased for the current process
* only.
*/
void
pmap_remove_pages(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
{
pmap_remove_noinval(pmap, sva, eva);
cpu_invltlb();
}
/*
* pmap_testbit tests bits in pte's note that the testbit/clearbit
* routines are inline, and a lot of things compile-time evaluate.
*/
static
boolean_t
pmap_testbit(vm_page_t m, int bit)
{
pv_entry_t pv;
pt_entry_t *pte;
pmap_t pmap;
if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
return FALSE;
if (TAILQ_FIRST(&m->md.pv_list) == NULL)
return FALSE;
vm_page_spin_lock(m);
if (TAILQ_FIRST(&m->md.pv_list) == NULL) {
vm_page_spin_unlock(m);
return FALSE;
}
TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
#if defined(PMAP_DIAGNOSTIC)
if (pv->pv_pmap == NULL) {
kprintf("Null pmap (tb) at pindex: %"PRIu64"\n",
pv->pv_pindex);
continue;
}
#endif
pmap = pv->pv_pmap;
/*
* If the bit being tested is the modified bit, then
* mark clean_map and ptes as never
* modified.
*
* WARNING! Because we do not lock the pv, *pte can be in a
* state of flux. Despite this the value of *pte
* will still be related to the vm_page in some way
* because the pv cannot be destroyed as long as we
* hold the vm_page spin lock.
*/
if (bit == PG_A_IDX || bit == PG_M_IDX) {
//& (pmap->pmap_bits[PG_A_IDX] | pmap->pmap_bits[PG_M_IDX])) {
if (!pmap_track_modified(pv->pv_pindex))
continue;
}
pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
if (*pte & pmap->pmap_bits[bit]) {
vm_page_spin_unlock(m);
return TRUE;
}
}
vm_page_spin_unlock(m);
return (FALSE);
}
/*
* This routine is used to modify bits in ptes. Only one bit should be
* specified. PG_RW requires special handling.
*
* Caller must NOT hold any spin locks
*/
static __inline
void
pmap_clearbit(vm_page_t m, int bit_index)
{
struct pmap_inval_info info;
pv_entry_t pv;
pt_entry_t *pte;
pt_entry_t pbits;
pmap_t pmap;
if (bit_index == PG_RW_IDX)
vm_page_flag_clear(m, PG_WRITEABLE);
if (!pmap_initialized || (m->flags & PG_FICTITIOUS)) {
return;
}
/*
* PG_M or PG_A case
*
* Loop over all current mappings setting/clearing as appropos If
* setting RO do we need to clear the VAC?
*
* NOTE: When clearing PG_M we could also (not implemented) drop
* through to the PG_RW code and clear PG_RW too, forcing
* a fault on write to redetect PG_M for virtual kernels, but
* it isn't necessary since virtual kernels invalidate the
* pte when they clear the VPTE_M bit in their virtual page
* tables.
*
* NOTE: Does not re-dirty the page when clearing only PG_M.
*
* NOTE: Because we do not lock the pv, *pte can be in a state of
* flux. Despite this the value of *pte is still somewhat
* related while we hold the vm_page spin lock.
*
* *pte can be zero due to this race. Since we are clearing
* bits we basically do no harm when this race ccurs.
*/
if (bit_index != PG_RW_IDX) {
vm_page_spin_lock(m);
TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
#if defined(PMAP_DIAGNOSTIC)
if (pv->pv_pmap == NULL) {
kprintf("Null pmap (cb) at pindex: %"PRIu64"\n",
pv->pv_pindex);
continue;
}
#endif
pmap = pv->pv_pmap;
pte = pmap_pte_quick(pv->pv_pmap,
pv->pv_pindex << PAGE_SHIFT);
pbits = *pte;
if (pbits & pmap->pmap_bits[bit_index])
atomic_clear_long(pte, pmap->pmap_bits[bit_index]);
}
vm_page_spin_unlock(m);
return;
}
/*
* Clear PG_RW. Also clears PG_M and marks the page dirty if PG_M
* was set.
*/
pmap_inval_init(&info);
restart:
vm_page_spin_lock(m);
TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
/*
* don't write protect pager mappings
*/
if (!pmap_track_modified(pv->pv_pindex))
continue;
#if defined(PMAP_DIAGNOSTIC)
if (pv->pv_pmap == NULL) {
kprintf("Null pmap (cb) at pindex: %"PRIu64"\n",
pv->pv_pindex);
continue;
}
#endif
pmap = pv->pv_pmap;
/*
* Skip pages which do not have PG_RW set.
*/
pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
if ((*pte & pmap->pmap_bits[PG_RW_IDX]) == 0)
continue;
/*
* Lock the PV
*/
if (pv_hold_try(pv)) {
vm_page_spin_unlock(m);
} else {
vm_page_spin_unlock(m);
pv_lock(pv); /* held, now do a blocking lock */
}
if (pv->pv_pmap != pmap || pv->pv_m != m) {
pv_put(pv); /* and release */
goto restart; /* anything could have happened */
}
pmap_inval_interlock(&info, pmap,
(vm_offset_t)pv->pv_pindex << PAGE_SHIFT);
KKASSERT(pv->pv_pmap == pmap);
for (;;) {
pbits = *pte;
cpu_ccfence();
if (atomic_cmpset_long(pte, pbits, pbits &
~(pmap->pmap_bits[PG_RW_IDX] |
pmap->pmap_bits[PG_M_IDX]))) {
break;
}
}
pmap_inval_deinterlock(&info, pmap);
vm_page_spin_lock(m);
/*
* If PG_M was found to be set while we were clearing PG_RW
* we also clear PG_M (done above) and mark the page dirty.
* Callers expect this behavior.
*/
if (pbits & pmap->pmap_bits[PG_M_IDX])
vm_page_dirty(m);
pv_put(pv);
}
vm_page_spin_unlock(m);
pmap_inval_done(&info);
}
/*
* Lower the permission for all mappings to a given page.
*
* Page must be busied by caller. Because page is busied by caller this
* should not be able to race a pmap_enter().
*/
void
pmap_page_protect(vm_page_t m, vm_prot_t prot)
{
/* JG NX support? */
if ((prot & VM_PROT_WRITE) == 0) {
if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
/*
* NOTE: pmap_clearbit(.. PG_RW) also clears
* the PG_WRITEABLE flag in (m).
*/
pmap_clearbit(m, PG_RW_IDX);
} else {
pmap_remove_all(m);
}
}
}
vm_paddr_t
pmap_phys_address(vm_pindex_t ppn)
{
return (x86_64_ptob(ppn));
}
/*
* Return a count of reference bits for a page, clearing those bits.
* It is not necessary for every reference bit to be cleared, but it
* is necessary that 0 only be returned when there are truly no
* reference bits set.
*
* XXX: The exact number of bits to check and clear is a matter that
* should be tested and standardized at some point in the future for
* optimal aging of shared pages.
*
* This routine may not block.
*/
int
pmap_ts_referenced(vm_page_t m)
{
pv_entry_t pv;
pt_entry_t *pte;
pmap_t pmap;
int rtval = 0;
if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
return (rtval);
vm_page_spin_lock(m);
TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
if (!pmap_track_modified(pv->pv_pindex))
continue;
pmap = pv->pv_pmap;
pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
if (pte && (*pte & pmap->pmap_bits[PG_A_IDX])) {
atomic_clear_long(pte, pmap->pmap_bits[PG_A_IDX]);
rtval++;
if (rtval > 4)
break;
}
}
vm_page_spin_unlock(m);
return (rtval);
}
/*
* pmap_is_modified:
*
* Return whether or not the specified physical page was modified
* in any physical maps.
*/
boolean_t
pmap_is_modified(vm_page_t m)
{
boolean_t res;
res = pmap_testbit(m, PG_M_IDX);
return (res);
}
/*
* Clear the modify bits on the specified physical page.
*/
void
pmap_clear_modify(vm_page_t m)
{
pmap_clearbit(m, PG_M_IDX);
}
/*
* pmap_clear_reference:
*
* Clear the reference bit on the specified physical page.
*/
void
pmap_clear_reference(vm_page_t m)
{
pmap_clearbit(m, PG_A_IDX);
}
/*
* Miscellaneous support routines follow
*/
static
void
i386_protection_init(void)
{
int *kp, prot;
/* JG NX support may go here; No VM_PROT_EXECUTE ==> set NX bit */
kp = protection_codes;
for (prot = 0; prot < PROTECTION_CODES_SIZE; prot++) {
switch (prot) {
case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE:
/*
* Read access is also 0. There isn't any execute bit,
* so just make it readable.
*/
case VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE:
case VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE:
case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE:
*kp++ = 0;
break;
case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE:
case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE:
case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE:
case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE:
*kp++ = pmap_bits_default[PG_RW_IDX];
break;
}
}
}
/*
* Map a set of physical memory pages into the kernel virtual
* address space. Return a pointer to where it is mapped. This
* routine is intended to be used for mapping device memory,
* NOT real memory.
*
* NOTE: We can't use pgeflag unless we invalidate the pages one at
* a time.
*
* NOTE: The PAT attributes {WRITE_BACK, WRITE_THROUGH, UNCACHED, UNCACHEABLE}
* work whether the cpu supports PAT or not. The remaining PAT
* attributes {WRITE_PROTECTED, WRITE_COMBINING} only work if the cpu
* supports PAT.
*/
void *
pmap_mapdev(vm_paddr_t pa, vm_size_t size)
{
return(pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
}
void *
pmap_mapdev_uncacheable(vm_paddr_t pa, vm_size_t size)
{
return(pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
}
void *
pmap_mapbios(vm_paddr_t pa, vm_size_t size)
{
return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
}
/*
* Map a set of physical memory pages into the kernel virtual
* address space. Return a pointer to where it is mapped. This
* routine is intended to be used for mapping device memory,
* NOT real memory.
*/
void *
pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
{
vm_offset_t va, tmpva, offset;
pt_entry_t *pte;
vm_size_t tmpsize;
offset = pa & PAGE_MASK;
size = roundup(offset + size, PAGE_SIZE);
va = kmem_alloc_nofault(&kernel_map, size, PAGE_SIZE);
if (va == 0)
panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
pa = pa & ~PAGE_MASK;
for (tmpva = va, tmpsize = size; tmpsize > 0;) {
pte = vtopte(tmpva);
*pte = pa |
kernel_pmap.pmap_bits[PG_RW_IDX] |
kernel_pmap.pmap_bits[PG_V_IDX] | /* pgeflag | */
kernel_pmap.pmap_cache_bits[mode];
tmpsize -= PAGE_SIZE;
tmpva += PAGE_SIZE;
pa += PAGE_SIZE;
}
pmap_invalidate_range(&kernel_pmap, va, va + size);
pmap_invalidate_cache_range(va, va + size);
return ((void *)(va + offset));
}
void
pmap_unmapdev(vm_offset_t va, vm_size_t size)
{
vm_offset_t base, offset;
base = va & ~PAGE_MASK;
offset = va & PAGE_MASK;
size = roundup(offset + size, PAGE_SIZE);
pmap_qremove(va, size >> PAGE_SHIFT);
kmem_free(&kernel_map, base, size);
}
/*
* Sets the memory attribute for the specified page.
*/
void
pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
{
m->pat_mode = ma;
/*
* If "m" is a normal page, update its direct mapping. This update
* can be relied upon to perform any cache operations that are
* required for data coherence.
*/
if ((m->flags & PG_FICTITIOUS) == 0)
pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
m->pat_mode);
}
/*
* Change the PAT attribute on an existing kernel memory map. Caller
* must ensure that the virtual memory in question is not accessed
* during the adjustment.
*/
void
pmap_change_attr(vm_offset_t va, vm_size_t count, int mode)
{
pt_entry_t *pte;
vm_offset_t base;
int changed = 0;
if (va == 0)
panic("pmap_change_attr: va is NULL");
base = trunc_page(va);
while (count) {
pte = vtopte(va);
*pte = (*pte & ~(pt_entry_t)(kernel_pmap.pmap_cache_mask)) |
kernel_pmap.pmap_cache_bits[mode];
--count;
va += PAGE_SIZE;
}
changed = 1; /* XXX: not optimal */
/*
* Flush CPU caches if required to make sure any data isn't cached that
* shouldn't be, etc.
*/
if (changed) {
pmap_invalidate_range(&kernel_pmap, base, va);
pmap_invalidate_cache_range(base, va);
}
}
/*
* perform the pmap work for mincore
*/
int
pmap_mincore(pmap_t pmap, vm_offset_t addr)
{
pt_entry_t *ptep, pte;
vm_page_t m;
int val = 0;
lwkt_gettoken(&pmap->pm_token);
ptep = pmap_pte(pmap, addr);
if (ptep && (pte = *ptep) != 0) {
vm_offset_t pa;
val = MINCORE_INCORE;
if ((pte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0)
goto done;
pa = pte & PG_FRAME;
if (pte & pmap->pmap_bits[PG_DEVICE_IDX])
m = NULL;
else
m = PHYS_TO_VM_PAGE(pa);
/*
* Modified by us
*/
if (pte & pmap->pmap_bits[PG_M_IDX])
val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
/*
* Modified by someone
*/
else if (m && (m->dirty || pmap_is_modified(m)))
val |= MINCORE_MODIFIED_OTHER;
/*
* Referenced by us
*/
if (pte & pmap->pmap_bits[PG_A_IDX])
val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
/*
* Referenced by someone
*/
else if (m && ((m->flags & PG_REFERENCED) ||
pmap_ts_referenced(m))) {
val |= MINCORE_REFERENCED_OTHER;
vm_page_flag_set(m, PG_REFERENCED);
}
}
done:
lwkt_reltoken(&pmap->pm_token);
return val;
}
/*
* Replace p->p_vmspace with a new one. If adjrefs is non-zero the new
* vmspace will be ref'd and the old one will be deref'd.
*
* The vmspace for all lwps associated with the process will be adjusted
* and cr3 will be reloaded if any lwp is the current lwp.
*
* The process must hold the vmspace->vm_map.token for oldvm and newvm
*/
void
pmap_replacevm(struct proc *p, struct vmspace *newvm, int adjrefs)
{
struct vmspace *oldvm;
struct lwp *lp;
oldvm = p->p_vmspace;
if (oldvm != newvm) {
if (adjrefs)
sysref_get(&newvm->vm_sysref);
p->p_vmspace = newvm;
KKASSERT(p->p_nthreads == 1);
lp = RB_ROOT(&p->p_lwp_tree);
pmap_setlwpvm(lp, newvm);
if (adjrefs)
sysref_put(&oldvm->vm_sysref);
}
}
/*
* Set the vmspace for a LWP. The vmspace is almost universally set the
* same as the process vmspace, but virtual kernels need to swap out contexts
* on a per-lwp basis.
*
* Caller does not necessarily hold any vmspace tokens. Caller must control
* the lwp (typically be in the context of the lwp). We use a critical
* section to protect against statclock and hardclock (statistics collection).
*/
void
pmap_setlwpvm(struct lwp *lp, struct vmspace *newvm)
{
struct vmspace *oldvm;
struct pmap *pmap;
oldvm = lp->lwp_vmspace;
if (oldvm != newvm) {
crit_enter();
lp->lwp_vmspace = newvm;
if (curthread->td_lwp == lp) {
pmap = vmspace_pmap(newvm);
atomic_set_cpumask(&pmap->pm_active, mycpu->gd_cpumask);
if (pmap->pm_active & CPUMASK_LOCK)
pmap_interlock_wait(newvm);
#if defined(SWTCH_OPTIM_STATS)
tlb_flush_count++;
#endif
if (pmap->pmap_bits[TYPE_IDX] == REGULAR_PMAP) {
curthread->td_pcb->pcb_cr3 = vtophys(pmap->pm_pml4);
} else if (pmap->pmap_bits[TYPE_IDX] == EPT_PMAP) {
curthread->td_pcb->pcb_cr3 = KPML4phys;
} else {
panic("pmap_setlwpvm: unknown pmap type\n");
}
load_cr3(curthread->td_pcb->pcb_cr3);
pmap = vmspace_pmap(oldvm);
atomic_clear_cpumask(&pmap->pm_active, mycpu->gd_cpumask);
}
crit_exit();
}
}
/*
* Called when switching to a locked pmap, used to interlock against pmaps
* undergoing modifications to prevent us from activating the MMU for the
* target pmap until all such modifications have completed. We have to do
* this because the thread making the modifications has already set up its
* SMP synchronization mask.
*
* This function cannot sleep!
*
* No requirements.
*/
void
pmap_interlock_wait(struct vmspace *vm)
{
struct pmap *pmap = &vm->vm_pmap;
if (pmap->pm_active & CPUMASK_LOCK) {
crit_enter();
KKASSERT(curthread->td_critcount >= 2);
DEBUG_PUSH_INFO("pmap_interlock_wait");
while (pmap->pm_active & CPUMASK_LOCK) {
cpu_ccfence();
lwkt_process_ipiq();
}
DEBUG_POP_INFO();
crit_exit();
}
}
vm_offset_t
pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
{
if ((obj == NULL) || (size < NBPDR) ||
((obj->type != OBJT_DEVICE) && (obj->type != OBJT_MGTDEVICE))) {
return addr;
}
addr = (addr + (NBPDR - 1)) & ~(NBPDR - 1);
return addr;
}
/*
* Used by kmalloc/kfree, page already exists at va
*/
vm_page_t
pmap_kvtom(vm_offset_t va)
{
pt_entry_t *ptep = vtopte(va);
KKASSERT((*ptep & kernel_pmap.pmap_bits[PG_DEVICE_IDX]) == 0);
return(PHYS_TO_VM_PAGE(*ptep & PG_FRAME));
}
/*
* Initialize machine-specific shared page directory support. This
* is executed when a VM object is created.
*/
void
pmap_object_init(vm_object_t object)
{
object->md.pmap_rw = NULL;
object->md.pmap_ro = NULL;
}
/*
* Clean up machine-specific shared page directory support. This
* is executed when a VM object is destroyed.
*/
void
pmap_object_free(vm_object_t object)
{
pmap_t pmap;
if ((pmap = object->md.pmap_rw) != NULL) {
object->md.pmap_rw = NULL;
pmap_remove_noinval(pmap,
VM_MIN_USER_ADDRESS, VM_MAX_USER_ADDRESS);
pmap->pm_active = 0;
pmap_release(pmap);
pmap_puninit(pmap);
kfree(pmap, M_OBJPMAP);
}
if ((pmap = object->md.pmap_ro) != NULL) {
object->md.pmap_ro = NULL;
pmap_remove_noinval(pmap,
VM_MIN_USER_ADDRESS, VM_MAX_USER_ADDRESS);
pmap->pm_active = 0;
pmap_release(pmap);
pmap_puninit(pmap);
kfree(pmap, M_OBJPMAP);
}
}
| 25.809137 | 90 | 0.674254 | [
"object",
"shape"
] |
afe950313add1cd23822c8fe222103272fe38699 | 1,912 | h | C | test/TestCache.h | smc314/helix | 9e2fd7d8acdeb09449665585d478c76836866835 | [
"MIT"
] | null | null | null | test/TestCache.h | smc314/helix | 9e2fd7d8acdeb09449665585d478c76836866835 | [
"MIT"
] | null | null | null | test/TestCache.h | smc314/helix | 9e2fd7d8acdeb09449665585d478c76836866835 | [
"MIT"
] | null | null | null | /* ****************************************************************************
Copyright (c): 2015 Hericus Software, Inc.
License: The MIT License (MIT)
Authors: Steven M. Cherry
**************************************************************************** */
#ifndef TESTCACHE_H
#define TESTCACHE_H
#include <map>
using namespace std;
#include <twine.h>
#include <AnException.h>
using namespace SLib;
namespace Helix {
namespace Test {
/**
* This class defines a cache of settings that are used at runtime by the testing
* framework. This is a singleton and can be accessed throughout the test code.
*
*/
class TestCache
{
private:
/** Keep the constructor private so that there's only one instance of this object
* in memory during a run of the test engine.
*/
TestCache();
public:
/** Use this method to get an instance of this class.
*/
static TestCache& getInstance();
/** Shortcut for TestCache.getInstance().GetCacheItem()
*/
static twine& get(const twine& lookupkey);
/** Shortcut for TestCache.getInstance().GetCacheItem()
*/
static int getInt(const twine& lookupkey);
/** Shortcut for TestCache.getInstance().GetCacheItem()
*/
static bool getBool(const twine& lookupkey);
// Standard Destructor
~TestCache();
/// Tests for presence of the item in our cache.
bool HasCacheItem(const twine& lookupkey);
/// Returns the item requested from our cache
twine& GetCacheItem(const twine& lookupkey);
/// Adds the given item to our cache or replaces it if already present
void AddCacheItem(const twine& lookupkey, const twine& value);
/// Replaces all ${...} strings in a value by looking up the names in our cache.
twine& ReplaceVars(twine& value);
protected:
/// This is our cache of strings
map<twine, twine> m_cache;
}; // End TestCache class
} } // End namespace stack
#endif // TESTCACHE_H Defined
| 23.317073 | 83 | 0.643828 | [
"object"
] |
aff23692a32de83928d509136ebdfc2e6add161f | 4,156 | h | C | bsp/essemi/es32f369x/libraries/ES32F36xx_ALD_StdPeriph_Driver/Include/ald_sram.h | rockonedege/rt-thread | 4fe6c709d0bfe719bed6c927f0144ba373bbda5a | [
"Apache-2.0"
] | 7,482 | 2015-01-01T09:23:08.000Z | 2022-03-31T19:34:05.000Z | bsp/essemi/es32f369x/libraries/ES32F36xx_ALD_StdPeriph_Driver/Include/ald_sram.h | ArdaFu/rt-thread | eebb2561ec166e0016187c7b7998ada4f8212b3a | [
"Apache-2.0"
] | 2,543 | 2015-01-09T02:01:34.000Z | 2022-03-31T23:10:14.000Z | bsp/essemi/es32f369x/libraries/ES32F36xx_ALD_StdPeriph_Driver/Include/ald_sram.h | ArdaFu/rt-thread | eebb2561ec166e0016187c7b7998ada4f8212b3a | [
"Apache-2.0"
] | 4,645 | 2015-01-06T07:05:31.000Z | 2022-03-31T18:21:50.000Z | /**
*********************************************************************************
*
* @file ald_sram.h
* @brief Header file of EBI_SRAM driver
*
* @version V1.0
* @date 07 Dec 2019
* @author AE Team
* @note
*
* Copyright (C) Shanghai Eastsoft Microelectronics Co. Ltd. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* 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
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*********************************************************************************
*/
#ifndef __ALD_SRAM_H__
#define __ALD_SRAM_H__
#ifdef __cplusplus
extern "C" {
#endif
#include "ald_ebi.h"
#include "ald_dma.h"
/** @addtogroup ES32FXXX_ALD
* @{
*/
/** @addtogroup SRAM
* @{
*/
/** @defgroup SRAM_Public_Types SRAM Public Types
* @{
*/
/**
* @brief ALD SRAM State structures definition
*/
typedef enum {
ALD_SRAM_STATE_RESET = 0x00U, /**< SRAM not yet initialized or disabled */
ALD_SRAM_STATE_READY = 0x01U, /**< SRAM initialized and ready for use */
ALD_SRAM_STATE_BUSY = 0x02U, /**< SRAM internal process is ongoing */
ALD_SRAM_STATE_ERROR = 0x03U, /**< SRAM error state */
ALD_SRAM_STATE_PROTECTED = 0x04U /**< SRAM peripheral NORSRAM device write protected */
} ald_sram_state_t;
/**
* @brief SRAM handle Structure definition
*/
typedef struct {
EBI_NOR_SRAM_TypeDef *instance; /**< Register base address */
EBI_NOR_SRAM_EXTENDED_TypeDef *ext; /**< Extended mode register base address */
ald_ebi_nor_sram_init_t init; /**< SRAM device control configuration parameters */
lock_state_t lock; /**< SRAM locking object */
__IO ald_sram_state_t state; /**< SRAM device access state */
#ifdef ALD_DMA
dma_handle_t hdma; /**< SRAM DMA Handle parameters */
void(*cplt_cbk)(void *arg); /**< DMA transmit completely callback function */
#endif
} sram_handle_t;
/**
* @}
*/
/** @addtogroup SRAM_Public_Functions
* @{
*/
/** @addtogroup SRAM_Public_Functions_Group1
* @{
*/
/* Initialization functions */
ald_status_t ald_sram_init(sram_handle_t *hperh, ald_ebi_nor_sram_timing_t *timing, ald_ebi_nor_sram_timing_t *ext_timing);
ald_status_t ald_sram_deinit(sram_handle_t *hperh);
/**
* @}
*/
/** @addtogroup SRAM_Public_Functions_Group2
* @{
*/
/* I/O operation functions */
ald_status_t ald_sram_read_8b(sram_handle_t *hperh, uint32_t *addr, uint8_t *buf, uint32_t size);
ald_status_t ald_sram_write_8b(sram_handle_t *hperh, uint32_t *addr, uint8_t *buf, uint32_t size);
ald_status_t ald_sram_read_16b(sram_handle_t *hperh, uint32_t *addr, uint16_t *buf, uint32_t size);
ald_status_t ald_sram_write_16b(sram_handle_t *hperh, uint32_t *addr, uint16_t *buf, uint32_t size);
ald_status_t ald_sram_read_32b(sram_handle_t *hperh, uint32_t *addr, uint32_t *buf, uint32_t size);
ald_status_t ald_sram_write_32b(sram_handle_t *hperh, uint32_t *addr, uint32_t *buf, uint32_t size);
#ifdef ALD_DMA
ald_status_t ald_sram_read_by_dma(sram_handle_t *hperh, uint16_t *addr, uint16_t *buf, uint16_t size, uint8_t ch);
ald_status_t ald_sram_write_by_dma(sram_handle_t *hperh, uint16_t *addr, uint16_t *buf, uint16_t size, uint8_t ch);
#endif
/**
* @}
*/
/** @addtogroup SRAM_Public_Functions_Group3
* @{
*/
/* Control functions */
ald_status_t ald_sram_write_enable(sram_handle_t *hperh);
ald_status_t ald_sram_write_disable(sram_handle_t *hperh);
/**
* @}
*/
/** @addtogroup SRAM_Public_Functions_Group4
* @{
*/
/* State functions */
ald_sram_state_t ald_sram_get_state(sram_handle_t *hperh);
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __ALD_SRAM_H__ */
| 29.475177 | 123 | 0.680221 | [
"object"
] |
aff4630a28b322d72da317ce85b0ee7d75305bfc | 18,734 | c | C | common/libraries/hpm_sdk/samples/tinycrypt/aes_ctr_prng_example/src/aes_ctr_prng_example.c | hpmicro/rtt-bsp-hpm6750evkmini | 55e18a691aa386e3dce10b6c3d25d4a29a585213 | [
"BSD-3-Clause"
] | 8 | 2022-02-11T08:20:49.000Z | 2022-03-22T06:19:59.000Z | common/libraries/hpm_sdk/samples/tinycrypt/aes_ctr_prng_example/src/aes_ctr_prng_example.c | hpmicro/rtt-bsp-hpm6750evkmini | 55e18a691aa386e3dce10b6c3d25d4a29a585213 | [
"BSD-3-Clause"
] | 2 | 2022-03-22T03:22:45.000Z | 2022-03-22T06:09:13.000Z | common/libraries/hpm_sdk/samples/tinycrypt/aes_ctr_prng_example/src/aes_ctr_prng_example.c | hpmicro/rtt-bsp-hpm6750evkmini | 55e18a691aa386e3dce10b6c3d25d4a29a585213 | [
"BSD-3-Clause"
] | 2 | 2022-02-19T10:51:00.000Z | 2022-03-22T03:11:35.000Z | /* test_ctr_prng.c - TinyCrypt implementation of some CTR-PRNG tests */
/*
* Copyright (c) 2016, Chris Morrison, 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 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.
*/
/*
* Copyright(c) 2021 hpmicro
* SPDX-License-Identifier: BSD-3-Clause
*/
/*
DESCRIPTION
This module tests the CTR-PRNG routines
*/
#include "board.h"
#include <tinycrypt/ctr_prng.h>
#include <tinycrypt/aes.h>
#include <tinycrypt/constants.h>
#include <test_utils.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* utility function to convert hex character representation to their nibble (4 bit) values */
static uint8_t nibbleFromChar(char c)
{
if(c >= '0' && c <= '9') return c - '0';
if(c >= 'a' && c <= 'f') return c - 'a' + 10U;
if(c >= 'A' && c <= 'F') return c - 'A' + 10U;
return 255U;
}
/*
* Convert a string of characters representing a hex buffer into a series of
* bytes of that real value
*/
uint8_t *hexStringToBytes(char *inhex)
{
uint8_t *retval;
uint8_t *p;
int len, i;
len = strlen(inhex) / 2;
retval = (uint8_t *)malloc(len+1);
for(i=0, p = (uint8_t *) inhex; i<len; i++) {
retval[i] = (nibbleFromChar(*p) << 4) | nibbleFromChar(*(p+1));
p += 2;
}
retval[len] = 0;
return retval;
}
typedef struct {
char * entropyString;
char * personalizationString; /* may be null */
char * additionalInputString1; /* may be null */
char * additionalInputString2; /* may be null */
char * expectedString;
} PRNG_Vector;
/* vectors taken from NIST CAVS 14.3 CTR_DRBG.rsp */
PRNG_Vector vectors[] = {
/*
* AES-128 no df, PredictionResistance = False, EntropyInputLen = 256,
* NonceLen = 0, PersonalizationStringLen = 0, AdditionalInputLen = 0,
* ReturnedBitsLen = 512
*/
{ /* Count 0 */
"ce50f33da5d4c1d3d4004eb35244b7f2cd7f2e5076fbf6780a7ff634b249a5fc",
0,
0,
0,
"6545c0529d372443b392ceb3ae3a99a30f963eaf313280f1d1a1e87f9db373d361e75d18018266499cccd64d9bbb8de0185f213383080faddec46bae1f784e5a",
},
{ /* Count 1 */
"a385f70a4d450321dfd18d8379ef8e7736fee5fbf0a0aea53b76696094e8aa93",
0,
0,
0,
"1a062553ab60457ed1f1c52f5aca5a3be564a27545358c112ed92c6eae2cb7597cfcc2e0a5dd81c5bfecc941da5e8152a9010d4845170734676c8c1b6b3073a5",
},
/*
* AES-128 no df, PredictionResistance = False, EntropyInputLen = 256,
* NonceLen = 0, PersonalizationStringLen = 0, AdditionalInputLen = 256,
* ReturnedBitsLen = 512
*/
{ /* Count 0 */
"6bd4f2ae649fc99350951ff0c5d460c1a9214154e7384975ee54b34b7cae0704",
0,
"ecd4893b979ac92db1894ae3724518a2f78cf2dbe2f6bbc6fda596df87c7a4ae",
"b23e9188687c88768b26738862c4791fa52f92502e1f94bf66af017c4228a0dc",
"5b2bf7a5c60d8ab6591110cbd61cd387b02de19784f496d1a109123d8b3562a5de2dd6d5d1aef957a6c4f371cecd93c15799d82e34d6a0dba7e915a27d8e65f3",
},
{ /* Count 1 */
"e2addbde2a76e769fc7aa3f45b31402f482b73bbe7067ad6254621f06d3ef68b",
0,
"ad11643b019e31245e4ea41f18f7680458310580fa6efad275c5833e7f800dae",
"b5d849616b3123c9725d188cd0005003220768d1200f9e7cc29ef6d88afb7b9a",
"132d0d50c8477a400bb8935be5928f916a85da9ffcf1a8f6e9f9a14cca861036cda14cf66d8953dab456b632cf687cd539b4b807926561d0b3562b9d3334fb61",
},
/*
* AES-128 no df, PredictionResistance = False, EntropyInputLen = 256,
* NonceLen = 0, PersonalizationStringLen = 256, AdditionalInputLen = 0,
* ReturnedBitsLen = 512
*/
{ /* Count 0 */
"cee23de86a69c7ef57f6e1e12bd16e35e51624226fa19597bf93ec476a44b0f2",
"a2ef16f226ea324f23abd59d5e3c660561c25e73638fe21c87566e86a9e04c3e",
0,
0,
"2a76d71b329f449c98dc08fff1d205a2fbd9e4ade120c7611c225c984eac8531288dd3049f3dc3bb3671501ab8fbf9ad49c86cce307653bd8caf29cb0cf07764",
},
{ /* Count 1 */
"b09eb4a82a39066ec945bb7c6aef6a0682a62c3e674bd900297d4271a5f25b49",
"a3b768adcfe76d61c972d900da8dffeeb2a42e740247aa719ed1c924d2d10bd4",
0,
0,
"5a1c26803f3ffd4daf32042fdcc32c3812bb5ef13bc208cef82ea047d2890a6f5dcecf32bcc32a2585775ac5e1ffaa8de00664c54fe00a7674b985619e953c3a",
},
/*
* AES-128 no df, PredictionResistance = False, EntropyInputLen = 256,
* NonceLen = 0, PersonalizationStringLen = 256, AdditionalInputLen = 256,
* ReturnedBitsLen = 512
*/
{ /* Count 0 */
"50b96542a1f2b8b05074051fe8fb0e45adbbd5560e3594e12d485fe1bfcb741f",
"820c3030f97b3ead81a93b88b871937278fd3d711d2085d9280cba394673b17e",
"1f1632058806d6d8e231288f3b15a3c324e90ccef4891bd595f09c3e80e27469",
"5cadc8bfd86d2a5d44f921f64c7d153001b9bdd7caa6618639b948ebfad5cb8a",
"02b76a66f103e98d450e25e09c35337747d987471d2b3d81e03be24c7e985417a32acd72bc0a6eddd9871410dacb921c659249b4e2b368c4ac8580fb5db559bc",
},
{ /* Count 1 */
"ff5f4b754e8b364f6df0c5effba5f1c036de49c4b38cd8d230ee1f14d7234ef5",
"994eb339f64034005d2e18352899e77df446e285c3430631d557498aac4f4280",
"e1824832d5fc2a6dea544cac2ab73306d6566bde98cc8f9425d064b860a9b218",
"c08b42433a78fd393a34ffc24724d479af08c36882799c134165d98b2866dc0a",
"1efa34aed07dd57bde9741b8d1907d28e8c1ac71601df37ef4295e6ffb67f6a1c4c13e5def65d505e2408aeb82948999ca1f9c9113b99a6b59ff7f0cc3dc6e92",
},
/*
* AES-128 no df, PredictionResistance = False, EntropyInputLen = 256,
* NonceLen = 0, PersonalizationStringLen = 0, AdditionalInputLen = 0,
* ReturnedBitsLen = 512
*/
{ /* Count 0 */
"69a09f6bf5dda15cd4af29e14cf5e0cddd7d07ac39bba587f8bc331104f9c448",
0,
0,
0,
"f78a4919a6ec899f7b6c69381febbbe083315f3d289e70346db0e4ec4360473ae0b3d916e9b6b964309f753ed66ae59de48da316cc1944bc8dfd0e2575d0ff6d",
},
{ /* Count 1 */
"80bfbd340d79888f34f043ed6807a9f28b72b6644d9d9e9d777109482b80788a",
0,
0,
0,
"80db048d2f130d864b19bfc547c92503e580cb1a8e1f74f3d97fdda6501fb1aa81fcedac0dd18b6ccfdc183ca28a44fc9f3a08834ba8751a2f4495367c54a185",
},
/*
* AES-128 no df, PredictionResistance = False, EntropyInputLen = 256,
* NonceLen = 0, PersonalizationStringLen = 0, AdditionalInputLen = 256,
* ReturnedBitsLen = 512
*/
{ /* Count 0 */
"7f40804693552e317523fda6935a5bc814353b1fbb7d334964ac4d1d12ddccce",
0,
"95c04259f64fcd1fe00c183aa3fb76b8a73b4d1243b800d770e38515bc41143c",
"5523102dbd7fe1228436b91a765b165ae6405eb0236e237afad4759cf0888941",
"1abf6bccb4c2d64e5187b1e2e34e493eca204ee4eef0d964267e38228f5f20efba376430a266f3832916d0a45b2703f46401dfd145e447a0a1667ebd8b6ee748",
},
{ /* Count 1 */
"350df677409a1dc297d01d3716a2abdfa6272cd030ab75f76839648582b47113",
0,
"ba5709a12ae6634a5436b7ea06838b48f7b847a237f6654a0e27c776ebee9511",
"f1b2c717c5e3a934127e10471d67accc65f4a45010ca53b35f54c88833dbd8e7",
"1ef1ea279812e8abe54f7ffd12d04c80ae40741f4ccfe232a5fba3a78dfd3e2ed419b88ee9188df724160cbb3aea0f276e84a3c0ff01e3b89fe30ebcfa64cb86",
},
/*
* AES-128 no df, PredictionResistance = False, EntropyInputLen = 256,
* NonceLen = 0, PersonalizationStringLen = 256, AdditionalInputLen = 0,
* ReturnedBitsLen = 512
*/
{ /* Count 0 */
"3fef762f0aa0677f61c65d749eeb10b013ff68ccc6314f150cfee752dcd8f987",
"f56db099240c7590dac396372b8737404d418b2864a3df96a8a397967245735f",
0,
0,
"af0afe0837442136fbb1959a1c91a9291c1d8188ede07c67d0e4dd6541303415e7a67999c302ba0df555324c26077514592a9b6db6be2f153fad2250161164e4",
},
{ /* Count 1 */
"3eebe77db4631862e3eb7e39370515b8baa1cdd71a5b1b0cda79c14d0b5f48ea",
"4be56a9b9c21242739c985ef12aa4d98e8c7da07c4c1dc6829f2e06833cfa148",
0,
0,
"be9e18a753df261927473c8bb5fb7c3ea6e821df5ab49adc566a4ebf44f75fa825b1f9d8c154bcd469134c0bb688e07e3c3e45407ca350d540e1528cc2e64068",
},
/*
* AES-128 no df, PredictionResistance = False, EntropyInputLen = 256,
* NonceLen = 0, PersonalizationStringLen = 256, AdditionalInputLen = 256,
* ReturnedBitsLen = 512
*/
{ /* Count 0 */
"c129c2732003bbf1d1dec244a933cd04cb47199bbce98fe080a1be880afb2155",
"64e2b9ac5c20642e3e3ee454b7463861a7e93e0dd1bbf8c4a0c28a6cb3d811ba",
"f94f0975760d52f47bd490d1623a9907e4df701f601cf2d573aba803a29d2b51",
"6f99720b186e2028a5fcc586b3ea518458e437ff449c7c5a318e6d13f75b5db7",
"7b8b3378b9031ab3101cec8af5b8ba5a9ca2a9af41432cd5f2e5e19716140bb219ed7f4ba88fc37b2d7e146037d2cac1128ffe14131c8691e581067a29cacf80",
},
{ /* Count 1 */
"7667643670254b3530e80a17b16b22406e84efa6a4b5ceef3ebc877495fc6048",
"40b92969953acde756747005117e46eff6893d7132a8311ffb1062280367326b",
"797a02ffbe8ff2c94ed0e5d39ebdc7847adaa762a88238242ed8f71f5635b194",
"d617f0f0e609e90d814192ba2e5214293d485402cdf9f789cc78b05e8c374f18",
"e8d6f89dca9825aed8927b43187492a98ca8648db30f0ac709556d401a8ac2b959c81350fc64332c4c0deb559a286a72e65dbb462bd872f9b28c0728f353dc10",
}
};
static unsigned int executePRNG_TestVector(PRNG_Vector vector, unsigned int idx)
{
unsigned int result = TC_PASS;
uint8_t * entropy = hexStringToBytes(vector.entropyString);
unsigned int entropylen = strlen(vector.entropyString) / 2U;
uint8_t * expected = hexStringToBytes(vector.expectedString);
unsigned int expectedlen = strlen(vector.expectedString) / 2U;
uint8_t * personalization = 0;
unsigned int plen = 0U;
uint8_t * additional_input1 = 0;
unsigned int additionallen1 = 0U;
uint8_t * additional_input2 = 0;
unsigned int additionallen2 = 0U;
uint8_t * output = (uint8_t *)malloc(expectedlen);
unsigned int i;
TCCtrPrng_t ctx;
if (0 != vector.personalizationString) {
personalization = hexStringToBytes(vector.personalizationString);
plen = strlen(vector.personalizationString) / 2U;
}
if (0 != vector.additionalInputString1) {
additional_input1 = hexStringToBytes(vector.additionalInputString1);
additionallen1 = strlen(vector.additionalInputString1) / 2U;
}
if (0 != vector.additionalInputString2) {
additional_input2 = hexStringToBytes(vector.additionalInputString2);
additionallen2 = strlen(vector.additionalInputString2) / 2U;
}
(void)tc_ctr_prng_init(&ctx, entropy, entropylen, personalization, plen);
(void)tc_ctr_prng_generate(&ctx, additional_input1, additionallen1, output, expectedlen);
(void)tc_ctr_prng_generate(&ctx, additional_input2, additionallen2, output, expectedlen);
for (i = 0U; i < expectedlen; i++) {
if (output[i] != expected[i]) {
TC_ERROR("CTR PRNG test #%d failed\n", idx);
result = TC_FAIL;
break;
}
}
free(entropy);
free(expected);
free(personalization);
free(additional_input1);
free(additional_input2);
free(output);
return result;
}
static int test_reseed(void)
{
int result = TC_PASS;
uint8_t entropy[32U] = {0U}; /* value not important */
uint8_t additional_input[32] = {0U};
uint8_t output[32];
TCCtrPrng_t ctx;
int ret;
unsigned int i;
(void)tc_ctr_prng_init(&ctx, entropy, sizeof entropy, 0, 0U);
/* force internal state to max allowed count */
ctx.reseedCount = 0x1000000000000ULL;
ret = tc_ctr_prng_generate(&ctx, 0, 0, output, sizeof output);
if (1 != ret) {
result = TC_FAIL;
goto exitTest;
}
/* expect further attempts to fail due to reaching reseed threshold */
ret = tc_ctr_prng_generate(&ctx, 0, 0, output, sizeof output);
if (-1 != ret) {
result = TC_FAIL;
goto exitTest;
}
/* reseed and confirm generate works again */
/* make entropy different from original value - not really important for the purpose of this test */
memset(entropy, 0xFF, sizeof entropy);
ret = tc_ctr_prng_reseed(&ctx, entropy, sizeof entropy, additional_input, sizeof additional_input);
if (1 != ret) {
result = TC_FAIL;
goto exitTest;
}
ret = tc_ctr_prng_generate(&ctx, 0, 0, output, sizeof output);
if (1 != ret) {
result = TC_FAIL;
goto exitTest;
}
/* confirm entropy and additional_input are being used correctly */
/* first, entropy only */
memset(&ctx, 0x0, sizeof ctx);
for (i = 0U; i < sizeof entropy; i++) {
entropy[i] = i;
}
ret = tc_ctr_prng_reseed(&ctx, entropy, sizeof entropy, 0, 0U);
if (1 != ret) {
result = TC_FAIL;
goto exitTest;
}
{
uint8_t expectedV[] =
{0x7EU, 0xE3U, 0xA0U, 0xCBU, 0x6DU, 0x5CU, 0x4BU, 0xC2U,
0x4BU, 0x7EU, 0x3CU, 0x48U, 0x88U, 0xC3U, 0x69U, 0x70U};
for (i = 0U; i < sizeof expectedV; i++) {
if (ctx.V[i] != expectedV[i]) {
result = TC_FAIL;
goto exitTest;
}
}
}
/* now, entropy and additional_input */
memset(&ctx, 0x0, sizeof ctx);
for (i = 0U; i < sizeof additional_input; i++) {
additional_input[i] = i * 2U;
}
ret = tc_ctr_prng_reseed(&ctx, entropy, sizeof entropy, additional_input, sizeof additional_input);
if (1 != ret) {
result = TC_FAIL;
goto exitTest;
}
{
uint8_t expectedV[] =
{0x5EU, 0xC1U, 0x84U, 0xEDU, 0x45U, 0x76U, 0x67U, 0xECU,
0x7BU, 0x4CU, 0x08U, 0x7EU, 0xB0U, 0xF9U, 0x55U, 0x4EU};
for (i = 0U; i < sizeof expectedV; i++) {
if (ctx.V[i] != expectedV[i]) {
result = TC_FAIL;
goto exitTest;
}
}
}
exitTest:
if (TC_FAIL == result) {
TC_ERROR("CTR PRNG reseed tests failed\n");
}
return result;
}
static int test_uninstantiate(void)
{
unsigned int i;
int result = TC_PASS;
uint8_t entropy[32U] = {0U}; /* value not important */
TCCtrPrng_t ctx;
(void)tc_ctr_prng_init(&ctx, entropy, sizeof entropy, 0, 0U);
tc_ctr_prng_uninstantiate(&ctx);
/* show that state has been zeroised */
for (i = 0U; i < sizeof ctx.V; i++) {
if (0U != ctx.V[i]) {
TC_ERROR("CTR PRNG uninstantiate tests failed\n");
result = TC_FAIL;
break;
}
}
for (i = 0U; i < sizeof ctx.key.words / sizeof ctx.key.words[0]; i++) {
if (0U != ctx.key.words[i]) {
TC_ERROR("CTR PRNG uninstantiate tests failed\n");
result = TC_FAIL;
break;
}
}
if (0U != ctx.reseedCount) {
TC_ERROR("CTR PRNG uninstantiate tests failed\n");
result = TC_FAIL;
}
return result;
}
static int test_robustness(void)
{
int result = TC_PASS;
int ret;
uint8_t entropy[32U] = {0U}; /* value not important */
uint8_t output[32];
TCCtrPrng_t ctx;
/* show that the CTR PRNG is robust to invalid inputs */
tc_ctr_prng_uninstantiate(0);
ret = tc_ctr_prng_generate(&ctx, 0, 0, 0, 0);
if (0 != ret) {
result = TC_FAIL;
goto exitTest;
}
ret = tc_ctr_prng_generate(0, 0, 0, output, sizeof output);
if (0 != ret) {
result = TC_FAIL;
goto exitTest;
}
ret = tc_ctr_prng_generate(0, 0, 0, 0, 0);
if (0 != ret) {
result = TC_FAIL;
goto exitTest;
}
ret = tc_ctr_prng_reseed(&ctx, 0, 0, 0, 0);
if (0 != ret) {
result = TC_FAIL;
goto exitTest;
}
/* too little entropy */
ret = tc_ctr_prng_reseed(&ctx, entropy, (sizeof entropy) - 1U, 0, 0);
if (0 != ret) {
result = TC_FAIL;
goto exitTest;
}
ret = tc_ctr_prng_reseed(0, entropy, sizeof entropy, 0, 0);
if (0 != ret) {
result = TC_FAIL;
goto exitTest;
}
ret = tc_ctr_prng_reseed(0, 0, 0, 0, 0);
if (0 != ret) {
result = TC_FAIL;
goto exitTest;
}
ret = tc_ctr_prng_init(&ctx, 0, 0, 0, 0);
if (0 != ret) {
result = TC_FAIL;
goto exitTest;
}
/* too little entropy */
ret = tc_ctr_prng_init(&ctx, entropy, (sizeof entropy) - 1U, 0, 0);
if (0 != ret) {
result = TC_FAIL;
goto exitTest;
}
ret = tc_ctr_prng_init(0, entropy, sizeof entropy, 0, 0);
if (0 != ret) {
result = TC_FAIL;
goto exitTest;
}
ret = tc_ctr_prng_init(0, 0, 0, 0, 0);
if (0 != ret) {
result = TC_FAIL;
goto exitTest;
}
exitTest:
if (TC_FAIL == result) {
TC_ERROR("CTR PRNG reseed tests failed\n");
}
return result;
}
/*
* Main task to test CTR PRNG
*/
int main(void)
{
int result = TC_PASS;
unsigned int i;
board_init();
TC_START("Performing CTR-PRNG tests:");
for (i = 0U; i < sizeof vectors / sizeof vectors[0]; i++) {
result = executePRNG_TestVector(vectors[i], i);
if (TC_PASS != result) {
goto exitTest;
}
}
if (TC_PASS != test_reseed()) {
goto exitTest;
}
if (TC_PASS != test_uninstantiate()) {
goto exitTest;
}
if (TC_PASS != test_robustness()) {
goto exitTest;
}
TC_PRINT("All CTR PRNG tests succeeded!\n");
exitTest:
TC_END_RESULT(result);
TC_END_REPORT(result);
return result;
}
| 32.524306 | 139 | 0.669798 | [
"vector"
] |
aff6941b3fc5a29c1533e8be762dc720f2e9d44d | 20,260 | h | C | Engine/Source/Runtime/Core/Public/Math/InterpCurve.h | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/Core/Public/Math/InterpCurve.h | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/Core/Public/Math/InterpCurve.h | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreTypes.h"
#include "Misc/AssertionMacros.h"
#include "Containers/Array.h"
#include "Math/UnrealMathUtility.h"
#include "Math/Color.h"
#include "Math/Vector2D.h"
#include "Math/Vector.h"
#include "Math/Quat.h"
#include "Math/TwoVectors.h"
#include "Math/InterpCurvePoint.h"
/**
* Template for interpolation curves.
*
* @see FInterpCurvePoint
* @todo Docs: FInterpCurve needs template and function documentation
*/
template<class T>
class FInterpCurve
{
public:
/** Holds the collection of interpolation points. */
TArray<FInterpCurvePoint<T>> Points;
/** Specify whether the curve is looped or not */
bool bIsLooped;
/** Specify the offset from the last point's input key corresponding to the loop point */
float LoopKeyOffset;
public:
/** Default constructor. */
FInterpCurve()
: bIsLooped(false)
{
}
public:
/**
* Adds a new keypoint to the InterpCurve with the supplied In and Out value.
*
* @param InVal
* @param OutVal
* @return The index of the new key.
*/
int32 AddPoint( const float InVal, const T &OutVal );
/**
* Moves a keypoint to a new In value.
*
* This may change the index of the keypoint, so the new key index is returned.
*
* @param PointIndex
* @param NewInVal
* @return
*/
int32 MovePoint( int32 PointIndex, float NewInVal );
/** Clears all keypoints from InterpCurve. */
void Reset();
/** Set loop key for curve */
void SetLoopKey( float InLoopKey );
/** Clear loop key for curve */
void ClearLoopKey();
/**
* Evaluate the output for an arbitary input value.
* For inputs outside the range of the keys, the first/last key value is assumed.
*/
T Eval( const float InVal, const T& Default = T(ForceInit) ) const;
/**
* Evaluate the derivative at a point on the curve.
*/
T EvalDerivative( const float InVal, const T& Default = T(ForceInit) ) const;
/**
* Evaluate the second derivative at a point on the curve.
*/
T EvalSecondDerivative( const float InVal, const T& Default = T(ForceInit) ) const;
/**
* Find the nearest point on spline to the given point.
*
* @param PointInSpace - the given point
* @param OutDistanceSq - output - the squared distance between the given point and the closest found point.
* @return The key (the 't' parameter) of the nearest point.
*/
float InaccurateFindNearest( const T &PointInSpace, float& OutDistanceSq ) const;
/**
* Find the nearest point (to the given point) on segment between Points[PtIdx] and Points[PtIdx+1]
*
* @param PointInSpace - the given point
* @return The key (the 't' parameter) of the found point.
*/
float InaccurateFindNearestOnSegment( const T &PointInSpace, int32 PtIdx, float& OutSquaredDistance ) const;
/** Automatically set the tangents on the curve based on surrounding points */
void AutoSetTangents(float Tension = 0.0f, bool bStationaryEndpoints = true);
/** Calculate the min/max out value that can be returned by this InterpCurve. */
void CalcBounds(T& OutMin, T& OutMax, const T& Default = T(ForceInit)) const;
public:
/**
* Serializes the interp curve.
*
* @param Ar Reference to the serialization archive.
* @param Curve Reference to the interp curve being serialized.
*
* @return Reference to the Archive after serialization.
*/
friend FArchive& operator<<( FArchive& Ar, FInterpCurve& Curve )
{
// NOTE: This is not used often for FInterpCurves. Most of the time these are serialized
// as inline struct properties in UnClass.cpp!
Ar << Curve.Points;
if (Ar.UE4Ver() >= VER_UE4_INTERPCURVE_SUPPORTS_LOOPING)
{
Ar << Curve.bIsLooped;
Ar << Curve.LoopKeyOffset;
}
return Ar;
}
/**
* Compare equality of two FInterpCurves
*/
friend bool operator==(const FInterpCurve& Curve1, const FInterpCurve& Curve2)
{
return (Curve1.Points == Curve2.Points &&
Curve1.bIsLooped == Curve2.bIsLooped &&
(!Curve1.bIsLooped || Curve1.LoopKeyOffset == Curve2.LoopKeyOffset));
}
/**
* Compare inequality of two FInterpCurves
*/
friend bool operator!=(const FInterpCurve& Curve1, const FInterpCurve& Curve2)
{
return !(Curve1 == Curve2);
}
/**
* Finds the lower index of the two points whose input values bound the supplied input value.
*/
int32 GetPointIndexForInputValue(const float InValue) const;
};
/* FInterpCurve inline functions
*****************************************************************************/
template< class T >
int32 FInterpCurve<T>::AddPoint( const float InVal, const T &OutVal )
{
int32 i=0; for( i=0; i<Points.Num() && Points[i].InVal < InVal; i++);
Points.InsertUninitialized(i);
Points[i] = FInterpCurvePoint< T >(InVal, OutVal);
return i;
}
template< class T >
int32 FInterpCurve<T>::MovePoint( int32 PointIndex, float NewInVal )
{
if( PointIndex < 0 || PointIndex >= Points.Num() )
return PointIndex;
const T OutVal = Points[PointIndex].OutVal;
const EInterpCurveMode Mode = Points[PointIndex].InterpMode;
const T ArriveTan = Points[PointIndex].ArriveTangent;
const T LeaveTan = Points[PointIndex].LeaveTangent;
Points.RemoveAt(PointIndex);
const int32 NewPointIndex = AddPoint( NewInVal, OutVal );
Points[NewPointIndex].InterpMode = Mode;
Points[NewPointIndex].ArriveTangent = ArriveTan;
Points[NewPointIndex].LeaveTangent = LeaveTan;
return NewPointIndex;
}
template< class T >
void FInterpCurve<T>::Reset()
{
Points.Empty();
}
template <class T>
void FInterpCurve<T>::SetLoopKey(float InLoopKey)
{
// Can't set a loop key if there are no points
if (Points.Num() == 0)
{
bIsLooped = false;
return;
}
const float LastInKey = Points.Last().InVal;
if (InLoopKey > LastInKey)
{
// Calculate loop key offset from the input key of the final point
bIsLooped = true;
LoopKeyOffset = InLoopKey - LastInKey;
}
else
{
// Specified a loop key lower than the final point; turn off looping.
bIsLooped = false;
}
}
template <class T>
void FInterpCurve<T>::ClearLoopKey()
{
bIsLooped = false;
}
template< class T >
int32 FInterpCurve<T>::GetPointIndexForInputValue(const float InValue) const
{
const int32 NumPoints = Points.Num();
const int32 LastPoint = NumPoints - 1;
check(NumPoints > 0);
if (InValue < Points[0].InVal)
{
return -1;
}
if (InValue >= Points[LastPoint].InVal)
{
return LastPoint;
}
int32 MinIndex = 0;
int32 MaxIndex = NumPoints;
while (MaxIndex - MinIndex > 1)
{
int32 MidIndex = (MinIndex + MaxIndex) / 2;
if (Points[MidIndex].InVal <= InValue)
{
MinIndex = MidIndex;
}
else
{
MaxIndex = MidIndex;
}
}
return MinIndex;
}
template< class T >
T FInterpCurve<T>::Eval(const float InVal, const T& Default) const
{
const int32 NumPoints = Points.Num();
const int32 LastPoint = NumPoints - 1;
// If no point in curve, return the Default value we passed in.
if (NumPoints == 0)
{
return Default;
}
// Binary search to find index of lower bound of input value
const int32 Index = GetPointIndexForInputValue(InVal);
// If before the first point, return its value
if (Index == -1)
{
return Points[0].OutVal;
}
// If on or beyond the last point, return its value.
if (Index == LastPoint)
{
if (!bIsLooped)
{
return Points[LastPoint].OutVal;
}
else if (InVal >= Points[LastPoint].InVal + LoopKeyOffset)
{
// Looped spline: last point is the same as the first point
return Points[0].OutVal;
}
}
// Somewhere within curve range - interpolate.
check(Index >= 0 && ((bIsLooped && Index < NumPoints) || (!bIsLooped && Index < LastPoint)));
const bool bLoopSegment = (bIsLooped && Index == LastPoint);
const int32 NextIndex = bLoopSegment ? 0 : (Index + 1);
const auto& PrevPoint = Points[Index];
const auto& NextPoint = Points[NextIndex];
const float Diff = bLoopSegment ? LoopKeyOffset : (NextPoint.InVal - PrevPoint.InVal);
if (Diff > 0.0f && PrevPoint.InterpMode != CIM_Constant)
{
const float Alpha = (InVal - PrevPoint.InVal) / Diff;
check(Alpha >= 0.0f && Alpha <= 1.0f);
if (PrevPoint.InterpMode == CIM_Linear)
{
return FMath::Lerp(PrevPoint.OutVal, NextPoint.OutVal, Alpha);
}
else
{
return FMath::CubicInterp(PrevPoint.OutVal, PrevPoint.LeaveTangent * Diff, NextPoint.OutVal, NextPoint.ArriveTangent * Diff, Alpha);
}
}
else
{
return Points[Index].OutVal;
}
}
template< class T >
T FInterpCurve<T>::EvalDerivative(const float InVal, const T& Default) const
{
const int32 NumPoints = Points.Num();
const int32 LastPoint = NumPoints - 1;
// If no point in curve, return the Default value we passed in.
if (NumPoints == 0)
{
return Default;
}
// Binary search to find index of lower bound of input value
const int32 Index = GetPointIndexForInputValue(InVal);
// If before the first point, return its tangent value
if (Index == -1)
{
return Points[0].LeaveTangent;
}
// If on or beyond the last point, return its tangent value.
if (Index == LastPoint)
{
if (!bIsLooped)
{
return Points[LastPoint].ArriveTangent;
}
else if (InVal >= Points[LastPoint].InVal + LoopKeyOffset)
{
// Looped spline: last point is the same as the first point
return Points[0].ArriveTangent;
}
}
// Somewhere within curve range - interpolate.
check(Index >= 0 && ((bIsLooped && Index < NumPoints) || (!bIsLooped && Index < LastPoint)));
const bool bLoopSegment = (bIsLooped && Index == LastPoint);
const int32 NextIndex = bLoopSegment ? 0 : (Index + 1);
const auto& PrevPoint = Points[Index];
const auto& NextPoint = Points[NextIndex];
const float Diff = bLoopSegment ? LoopKeyOffset : (NextPoint.InVal - PrevPoint.InVal);
if (Diff > 0.0f && PrevPoint.InterpMode != CIM_Constant)
{
if (PrevPoint.InterpMode == CIM_Linear)
{
return (NextPoint.OutVal - PrevPoint.OutVal) / Diff;
}
else
{
const float Alpha = (InVal - PrevPoint.InVal) / Diff;
check(Alpha >= 0.0f && Alpha <= 1.0f);
return FMath::CubicInterpDerivative(PrevPoint.OutVal, PrevPoint.LeaveTangent * Diff, NextPoint.OutVal, NextPoint.ArriveTangent * Diff, Alpha) / Diff;
}
}
else
{
// Derivative of a constant is zero
return T(ForceInit);
}
}
template< class T >
T FInterpCurve<T>::EvalSecondDerivative(const float InVal, const T& Default) const
{
const int32 NumPoints = Points.Num();
const int32 LastPoint = NumPoints - 1;
// If no point in curve, return the Default value we passed in.
if (NumPoints == 0)
{
return Default;
}
// Binary search to find index of lower bound of input value
const int32 Index = GetPointIndexForInputValue(InVal);
// If before the first point, return 0
if (Index == -1)
{
return T(ForceInit);
}
// If on or beyond the last point, return 0
if (Index == LastPoint)
{
if (!bIsLooped || (InVal >= Points[LastPoint].InVal + LoopKeyOffset))
{
return T(ForceInit);
}
}
// Somewhere within curve range - interpolate.
check(Index >= 0 && ((bIsLooped && Index < NumPoints) || (!bIsLooped && Index < LastPoint)));
const bool bLoopSegment = (bIsLooped && Index == LastPoint);
const int32 NextIndex = bLoopSegment ? 0 : (Index + 1);
const auto& PrevPoint = Points[Index];
const auto& NextPoint = Points[NextIndex];
const float Diff = bLoopSegment ? LoopKeyOffset : (NextPoint.InVal - PrevPoint.InVal);
if (Diff > 0.0f && PrevPoint.InterpMode != CIM_Constant)
{
if (PrevPoint.InterpMode == CIM_Linear)
{
// No change in tangent, return 0.
return T(ForceInit);
}
else
{
const float Alpha = (InVal - PrevPoint.InVal) / Diff;
check(Alpha >= 0.0f && Alpha <= 1.0f);
return FMath::CubicInterpSecondDerivative(PrevPoint.OutVal, PrevPoint.LeaveTangent * Diff, NextPoint.OutVal, NextPoint.ArriveTangent * Diff, Alpha) / (Diff * Diff);
}
}
else
{
// Second derivative of a constant is zero
return T(ForceInit);
}
}
template< class T >
float FInterpCurve<T>::InaccurateFindNearest(const T &PointInSpace, float& OutDistanceSq) const
{
const int32 NumPoints = Points.Num();
const int32 NumSegments = bIsLooped ? NumPoints : NumPoints - 1;
if (NumPoints > 1)
{
float BestDistanceSq;
float BestResult = InaccurateFindNearestOnSegment(PointInSpace, 0, BestDistanceSq);
for (int32 Segment = 1; Segment < NumSegments; ++Segment)
{
float LocalDistanceSq;
float LocalResult = InaccurateFindNearestOnSegment(PointInSpace, Segment, LocalDistanceSq);
if (LocalDistanceSq < BestDistanceSq)
{
BestDistanceSq = LocalDistanceSq;
BestResult = LocalResult;
}
}
OutDistanceSq = BestDistanceSq;
return BestResult;
}
if (NumPoints == 1)
{
OutDistanceSq = (PointInSpace - Points[0].OutVal).SizeSquared();
return Points[0].InVal;
}
return 0.0f;
}
template< class T >
float FInterpCurve<T>::InaccurateFindNearestOnSegment(const T& PointInSpace, int32 PtIdx, float& OutSquaredDistance) const
{
const int32 NumPoints = Points.Num();
const int32 LastPoint = NumPoints - 1;
const int32 NextPtIdx = (bIsLooped && PtIdx == LastPoint) ? 0 : (PtIdx + 1);
check(PtIdx >= 0 && ((bIsLooped && PtIdx < NumPoints) || (!bIsLooped && PtIdx < LastPoint)));
const float NextInVal = (bIsLooped && PtIdx == LastPoint) ? (Points[LastPoint].InVal + LoopKeyOffset) : Points[NextPtIdx].InVal;
if (CIM_Constant == Points[PtIdx].InterpMode)
{
const float Distance1 = (Points[PtIdx].OutVal - PointInSpace).SizeSquared();
const float Distance2 = (Points[NextPtIdx].OutVal - PointInSpace).SizeSquared();
if (Distance1 < Distance2)
{
OutSquaredDistance = Distance1;
return Points[PtIdx].InVal;
}
OutSquaredDistance = Distance2;
return NextInVal;
}
const float Diff = NextInVal - Points[PtIdx].InVal;
if (CIM_Linear == Points[PtIdx].InterpMode)
{
// like in function: FMath::ClosestPointOnLine
const float A = (Points[PtIdx].OutVal - PointInSpace) | (Points[NextPtIdx].OutVal - Points[PtIdx].OutVal);
const float B = (Points[NextPtIdx].OutVal - Points[PtIdx].OutVal).SizeSquared();
const float V = FMath::Clamp(-A / B, 0.f, 1.f);
OutSquaredDistance = (FMath::Lerp(Points[PtIdx].OutVal, Points[NextPtIdx].OutVal, V) - PointInSpace).SizeSquared();
return V * Diff + Points[PtIdx].InVal;
}
{
const int32 PointsChecked = 3;
const int32 IterationNum = 3;
const float Scale = 0.75;
// Newton's methods is repeated 3 times, starting with t = 0, 0.5, 1.
float ValuesT[PointsChecked];
ValuesT[0] = 0.0f;
ValuesT[1] = 0.5f;
ValuesT[2] = 1.0f;
T InitialPoints[PointsChecked];
InitialPoints[0] = Points[PtIdx].OutVal;
InitialPoints[1] = FMath::CubicInterp(Points[PtIdx].OutVal, Points[PtIdx].LeaveTangent * Diff, Points[NextPtIdx].OutVal, Points[NextPtIdx].ArriveTangent * Diff, ValuesT[1]);
InitialPoints[2] = Points[NextPtIdx].OutVal;
float DistancesSq[PointsChecked];
for (int32 point = 0; point < PointsChecked; ++point)
{
//Algorithm explanation: http://permalink.gmane.org/gmane.games.devel.sweng/8285
T FoundPoint = InitialPoints[point];
float LastMove = 1.0f;
for (int32 iter = 0; iter < IterationNum; ++iter)
{
const T LastBestTangent = FMath::CubicInterpDerivative(Points[PtIdx].OutVal, Points[PtIdx].LeaveTangent * Diff, Points[NextPtIdx].OutVal, Points[NextPtIdx].ArriveTangent * Diff, ValuesT[point]);
const T Delta = (PointInSpace - FoundPoint);
float Move = (LastBestTangent | Delta) / LastBestTangent.SizeSquared();
Move = FMath::Clamp(Move, -LastMove*Scale, LastMove*Scale);
ValuesT[point] += Move;
ValuesT[point] = FMath::Clamp(ValuesT[point], 0.0f, 1.0f);
LastMove = FMath::Abs(Move);
FoundPoint = FMath::CubicInterp(Points[PtIdx].OutVal, Points[PtIdx].LeaveTangent * Diff, Points[NextPtIdx].OutVal, Points[NextPtIdx].ArriveTangent * Diff, ValuesT[point]);
}
DistancesSq[point] = (FoundPoint - PointInSpace).SizeSquared();
ValuesT[point] = ValuesT[point] * Diff + Points[PtIdx].InVal;
}
if (DistancesSq[0] <= DistancesSq[1] && DistancesSq[0] <= DistancesSq[2])
{
OutSquaredDistance = DistancesSq[0];
return ValuesT[0];
}
if (DistancesSq[1] <= DistancesSq[2])
{
OutSquaredDistance = DistancesSq[1];
return ValuesT[1];
}
OutSquaredDistance = DistancesSq[2];
return ValuesT[2];
}
}
template< class T >
void FInterpCurve<T>::AutoSetTangents(float Tension, bool bStationaryEndpoints)
{
const int32 NumPoints = Points.Num();
const int32 LastPoint = NumPoints - 1;
// Iterate over all points in this InterpCurve
for (int32 PointIndex = 0; PointIndex < NumPoints; PointIndex++)
{
const int32 PrevIndex = (PointIndex == 0) ? (bIsLooped ? LastPoint : 0) : (PointIndex - 1);
const int32 NextIndex = (PointIndex == LastPoint) ? (bIsLooped ? 0 : LastPoint) : (PointIndex + 1);
auto& ThisPoint = Points[PointIndex];
const auto& PrevPoint = Points[PrevIndex];
const auto& NextPoint = Points[NextIndex];
if (ThisPoint.InterpMode == CIM_CurveAuto || ThisPoint.InterpMode == CIM_CurveAutoClamped)
{
if (bStationaryEndpoints && (PointIndex == 0 || (PointIndex == LastPoint && !bIsLooped)))
{
// Start and end points get zero tangents if bStationaryEndpoints is true
ThisPoint.ArriveTangent = T(ForceInit);
ThisPoint.LeaveTangent = T(ForceInit);
}
else if (PrevPoint.IsCurveKey())
{
const bool bWantClamping = (ThisPoint.InterpMode == CIM_CurveAutoClamped);
T Tangent;
const float PrevTime = (bIsLooped && PointIndex == 0) ? (ThisPoint.InVal - LoopKeyOffset) : PrevPoint.InVal;
const float NextTime = (bIsLooped && PointIndex == LastPoint) ? (ThisPoint.InVal + LoopKeyOffset) : NextPoint.InVal;
ComputeCurveTangent(
PrevTime, // Previous time
PrevPoint.OutVal, // Previous point
ThisPoint.InVal, // Current time
ThisPoint.OutVal, // Current point
NextTime, // Next time
NextPoint.OutVal, // Next point
Tension, // Tension
bWantClamping, // Want clamping?
Tangent); // Out
ThisPoint.ArriveTangent = Tangent;
ThisPoint.LeaveTangent = Tangent;
}
else
{
// Following on from a line or constant; set curve tangent equal to that so there are no discontinuities
ThisPoint.ArriveTangent = PrevPoint.ArriveTangent;
ThisPoint.LeaveTangent = PrevPoint.LeaveTangent;
}
}
else if (ThisPoint.InterpMode == CIM_Linear)
{
T Tangent = NextPoint.OutVal - ThisPoint.OutVal;
ThisPoint.ArriveTangent = Tangent;
ThisPoint.LeaveTangent = Tangent;
}
else if (ThisPoint.InterpMode == CIM_Constant)
{
ThisPoint.ArriveTangent = T(ForceInit);
ThisPoint.LeaveTangent = T(ForceInit);
}
}
}
template< class T >
void FInterpCurve<T>::CalcBounds(T& OutMin, T& OutMax, const T& Default) const
{
const int32 NumPoints = Points.Num();
if (NumPoints == 0)
{
OutMin = Default;
OutMax = Default;
}
else if (NumPoints == 1)
{
OutMin = Points[0].OutVal;
OutMax = Points[0].OutVal;
}
else
{
OutMin = Points[0].OutVal;
OutMax = Points[0].OutVal;
const int32 NumSegments = bIsLooped ? NumPoints : (NumPoints - 1);
for (int32 Index = 0; Index < NumSegments; Index++)
{
const int32 NextIndex = (Index == NumPoints - 1) ? 0 : (Index + 1);
CurveFindIntervalBounds(Points[Index], Points[NextIndex], OutMin, OutMax, 0.0f);
}
}
}
/* Common type definitions
*****************************************************************************/
#define DEFINE_INTERPCURVE_WRAPPER_STRUCT(Name, ElementType) \
struct Name : FInterpCurve<ElementType> \
{ \
private: \
typedef FInterpCurve<ElementType> Super; \
\
public: \
Name() \
: Super() \
{ \
} \
\
Name(const Super& Other) \
: Super( Other ) \
{ \
} \
}; \
\
template <> \
struct TIsBitwiseConstructible<Name, FInterpCurve<ElementType>> \
{ \
enum { Value = true }; \
}; \
\
template <> \
struct TIsBitwiseConstructible<FInterpCurve<ElementType>, Name> \
{ \
enum { Value = true }; \
};
DEFINE_INTERPCURVE_WRAPPER_STRUCT(FInterpCurveFloat, float)
DEFINE_INTERPCURVE_WRAPPER_STRUCT(FInterpCurveVector2D, FVector2D)
DEFINE_INTERPCURVE_WRAPPER_STRUCT(FInterpCurveVector, FVector)
DEFINE_INTERPCURVE_WRAPPER_STRUCT(FInterpCurveQuat, FQuat)
DEFINE_INTERPCURVE_WRAPPER_STRUCT(FInterpCurveTwoVectors, FTwoVectors)
DEFINE_INTERPCURVE_WRAPPER_STRUCT(FInterpCurveLinearColor, FLinearColor)
| 27.60218 | 198 | 0.690424 | [
"vector"
] |
affd0372ae0c3cf1aa4f2e896c7ff0b9f93e0079 | 2,231 | h | C | Core/Contents/Include/PolyiPhoneCore.h | MattDBell/Polycode | fc66547813a34a2388c9a45ec0b69919ce3253b2 | [
"MIT"
] | 1 | 2020-04-30T23:05:26.000Z | 2020-04-30T23:05:26.000Z | Core/Contents/Include/PolyiPhoneCore.h | MattDBell/Polycode | fc66547813a34a2388c9a45ec0b69919ce3253b2 | [
"MIT"
] | null | null | null | Core/Contents/Include/PolyiPhoneCore.h | MattDBell/Polycode | fc66547813a34a2388c9a45ec0b69919ce3253b2 | [
"MIT"
] | null | null | null | /*
Copyright (C) 2011 by Ivan Safrin
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.
*/
#pragma once
#include "PolyString.h"
#include "PolyGlobals.h"
#include "PolyCore.h"
#include "PolyRectangle.h"
#include <vector>
using std::vector;
namespace Polycode {
class _PolyExport PosixMutex : public CoreMutex {
public:
pthread_mutex_t pMutex;
};
class iPhoneEvent {
public:
int eventGroup;
int eventCode;
int mouseX;
int mouseY;
PolyKEY keyCode;
wchar_t unicodeChar;
char mouseButton;
static const int EVENTBASE_PLATFORMEVENT = 0x300;
static const int INPUT_EVENT = EVENTBASE_PLATFORMEVENT+0;
};
class _PolyExport IPhoneCore : public Core {
public:
IPhoneCore(int frameRate);
virtual ~IPhoneCore();
void enableMouse(bool newval);
unsigned int getTicks();
bool Update();
void setVideoMode(int xRes, int yRes, bool fullScreen, int aaLevel);
void createThread(Threaded *target);
void lockMutex(CoreMutex *mutex);
void unlockMutex(CoreMutex *mutex);
CoreMutex *createMutex();
void checkEvents();
vector<Rectangle> getVideoModes();
int lastMouseY;
int lastMouseX;
CoreMutex *eventMutex;
vector<iPhoneEvent> osxEvents;
private:
};
} | 25.352273 | 77 | 0.747199 | [
"vector"
] |
affdb2f640f380a3d5be15a6dd66d6d54a8c15ae | 14,742 | c | C | aes_nogpu.c | eclay42/aes_gpu | 6dcdd285698f0bdabd556e124c2557b6b684f93d | [
"MIT"
] | 1 | 2017-03-28T11:58:03.000Z | 2017-03-28T11:58:03.000Z | aes_nogpu.c | eclay42/aes_gpu | 6dcdd285698f0bdabd556e124c2557b6b684f93d | [
"MIT"
] | null | null | null | aes_nogpu.c | eclay42/aes_gpu | 6dcdd285698f0bdabd556e124c2557b6b684f93d | [
"MIT"
] | null | null | null | /*
* Byte-oriented AES-256 implementation.
* All lookup tables replaced with 'on the fly' calculations.
*
* Copyright (c) 2007 Ilya O. Levin, http://www.literatecode.com
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#ifndef uint8_t
#define uint8_t unsigned char
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*
typedef struct {
uint8_t key[32];
uint8_t enckey[32];
uint8_t deckey[32];
} aes256_context;
*/
uint8_t ctx_key[32];
uint8_t ctx_enckey[32];
uint8_t ctx_deckey[32];
#ifdef __cplusplus
}
#endif
#define AES_BLOCK_SIZE 16
#define THREADS_PER_BLOCK 256
#define F(x) (((x)<<1) ^ ((((x)>>7) & 1) * 0x1b))
#define FD(x) (((x) >> 1) ^ (((x) & 1) ? 0x8d : 0))
const uint8_t sbox[256] = {
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5,
0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc,
0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a,
0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85,
0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17,
0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88,
0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9,
0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6,
0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94,
0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68,
0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
};
const uint8_t sboxinv[256] = {
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38,
0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87,
0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d,
0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2,
0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16,
0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda,
0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a,
0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02,
0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea,
0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85,
0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89,
0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20,
0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31,
0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d,
0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0,
0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26,
0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d
};
/* -------------------------------------------------------------------------- */
uint8_t rj_xtime(uint8_t x)
{
return (x & 0x80) ? ((x << 1) ^ 0x1b) : (x << 1);
} /* rj_xtime */
/* -------------------------------------------------------------------------- */
void aes_subBytes(uint8_t *buf)
{
register uint8_t i, b;
for (i = 0; i < 16; ++i)
{
b = buf[i];
buf[i] = sbox[b];
}
} /* aes_subBytes */
/* -------------------------------------------------------------------------- */
void aes_subBytes_inv(uint8_t *buf)
{
register uint8_t i, b;
for (i = 0; i < 16; ++i)
{
b = buf[i];
buf[i] = sboxinv[b];
}
} /* aes_subBytes_inv */
/* -------------------------------------------------------------------------- */
void aes_addRoundKey(uint8_t *buf, uint8_t *key)
{
register uint8_t i = 16;
while (i--)
{
buf[i] ^= key[i];
}
} /* aes_addRoundKey */
/* -------------------------------------------------------------------------- */
void aes_addRoundKey_cpy(uint8_t *buf, uint8_t *key, uint8_t *cpk)
{
register uint8_t i = 16;
while (i--)
{
buf[i] ^= (cpk[i] = key[i]);
cpk[16+i] = key[16 + i];
}
} /* aes_addRoundKey_cpy */
/* -------------------------------------------------------------------------- */
void aes_shiftRows(uint8_t *buf)
{
register uint8_t i, j; /* to make it potentially parallelable :) */
i = buf[1];
buf[1] = buf[5];
buf[5] = buf[9];
buf[9] = buf[13];
buf[13] = i;
i = buf[10];
buf[10] = buf[2];
buf[2] = i;
j = buf[3];
buf[3] = buf[15];
buf[15] = buf[11];
buf[11] = buf[7];
buf[7] = j;
j = buf[14];
buf[14] = buf[6];
buf[6] = j;
} /* aes_shiftRows */
/* -------------------------------------------------------------------------- */
void aes_shiftRows_inv(uint8_t *buf)
{
register uint8_t i, j; /* same as above :) */
i = buf[1];
buf[1] = buf[13];
buf[13] = buf[9];
buf[9] = buf[5];
buf[5] = i;
i = buf[2];
buf[2] = buf[10];
buf[10] = i;
j = buf[3];
buf[3] = buf[7];
buf[7] = buf[11];
buf[11] = buf[15];
buf[15] = j;
j = buf[6];
buf[6] = buf[14];
buf[14] = j;
} /* aes_shiftRows_inv */
/* -------------------------------------------------------------------------- */
void aes_mixColumns(uint8_t *buf)
{
register uint8_t i, a, b, c, d, e;
for (i = 0; i < 16; i += 4)
{
a = buf[i];
b = buf[i + 1];
c = buf[i + 2];
d = buf[i + 3];
e = a ^ b ^ c ^ d;
buf[i] ^= e ^ rj_xtime(a^b);
buf[i+1] ^= e ^ rj_xtime(b^c);
buf[i+2] ^= e ^ rj_xtime(c^d);
buf[i+3] ^= e ^ rj_xtime(d^a);
}
} /* aes_mixColumns */
/* -------------------------------------------------------------------------- */
void aes_mixColumns_inv(uint8_t *buf)
{
register uint8_t i, a, b, c, d, e, x, y, z;
for (i = 0; i < 16; i += 4)
{
a = buf[i];
b = buf[i + 1];
c = buf[i + 2];
d = buf[i + 3];
e = a ^ b ^ c ^ d;
z = rj_xtime(e);
x = e ^ rj_xtime(rj_xtime(z^a^c));
y = e ^ rj_xtime(rj_xtime(z^b^d));
buf[i] ^= x ^ rj_xtime(a^b);
buf[i+1] ^= y ^ rj_xtime(b^c);
buf[i+2] ^= x ^ rj_xtime(c^d);
buf[i+3] ^= y ^ rj_xtime(d^a);
}
} /* aes_mixColumns_inv */
/* -------------------------------------------------------------------------- */
void aes_expandEncKey(uint8_t *k, uint8_t *rc, const uint8_t *sb)
{
register uint8_t i;
k[0] ^= sb[k[29]] ^ (*rc);
k[1] ^= sb[k[30]];
k[2] ^= sb[k[31]];
k[3] ^= sb[k[28]];
*rc = F( *rc);
for(i = 4; i < 16; i += 4)
{
k[i] ^= k[i-4];
k[i+1] ^= k[i-3];
k[i+2] ^= k[i-2];
k[i+3] ^= k[i-1];
}
k[16] ^= sb[k[12]];
k[17] ^= sb[k[13]];
k[18] ^= sb[k[14]];
k[19] ^= sb[k[15]];
for(i = 20; i < 32; i += 4)
{
k[i] ^= k[i-4];
k[i+1] ^= k[i-3];
k[i+2] ^= k[i-2];
k[i+3] ^= k[i-1];
}
} /* aes_expandEncKey */
/* -------------------------------------------------------------------------- */
void aes_expandDecKey(uint8_t *k, uint8_t *rc)
{
uint8_t i;
for(i = 28; i > 16; i -= 4)
{
k[i+0] ^= k[i-4];
k[i+1] ^= k[i-3];
k[i+2] ^= k[i-2];
k[i+3] ^= k[i-1];
}
k[16] ^= sbox[k[12]];
k[17] ^= sbox[k[13]];
k[18] ^= sbox[k[14]];
k[19] ^= sbox[k[15]];
for(i = 12; i > 0; i -= 4)
{
k[i+0] ^= k[i-4];
k[i+1] ^= k[i-3];
k[i+2] ^= k[i-2];
k[i+3] ^= k[i-1];
}
*rc = FD(*rc);
k[0] ^= sbox[k[29]] ^ (*rc);
k[1] ^= sbox[k[30]];
k[2] ^= sbox[k[31]];
k[3] ^= sbox[k[28]];
} /* aes_expandDecKey */
/* -------------------------------------------------------------------------- */
void aes256_init(uint8_t *k)
{
uint8_t rcon = 1;
register uint8_t i;
for (i = 0; i < sizeof(ctx_key); i++)
{
ctx_enckey[i] = ctx_deckey[i] = k[i];
}
for (i = 8;--i;)
{
aes_expandEncKey(ctx_deckey, &rcon, sbox);
}
} /* aes256_init */
/* -------------------------------------------------------------------------- */
void aes256_encrypt_ecb(uint8_t *buf, unsigned long offset)
{
uint8_t i, rcon;
uint8_t buf_t[AES_BLOCK_SIZE]; // thread buffer
memcpy(buf_t, &buf[offset], AES_BLOCK_SIZE);
aes_addRoundKey_cpy(buf_t, ctx_enckey, ctx_key);
for(i = 1, rcon = 1; i < 14; ++i)
{
aes_subBytes(buf_t);
aes_shiftRows(buf_t);
aes_mixColumns(buf_t);
if( i & 1 )
{
aes_addRoundKey( buf_t, &ctx_key[16]);
}
else
{
aes_expandEncKey(ctx_key, &rcon, sbox), aes_addRoundKey(buf_t, ctx_key);
}
}
aes_subBytes(buf_t);
aes_shiftRows(buf_t);
aes_expandEncKey(ctx_key, &rcon, sbox);
aes_addRoundKey(buf_t, ctx_key);
/* copy thread buffer back into global memory */
memcpy(&buf[offset], buf_t, AES_BLOCK_SIZE);
} /* aes256_encrypt */
/* -------------------------------------------------------------------------- */
void aes256_decrypt_ecb(uint8_t *buf, unsigned long offset)
{
uint8_t i, rcon;
uint8_t buf_t[AES_BLOCK_SIZE]; // thread buffer
/* copy data from global memory into thread buffer */
memcpy(buf_t, &buf[offset], AES_BLOCK_SIZE);
aes_addRoundKey_cpy(buf_t, ctx_deckey, ctx_key);
aes_shiftRows_inv(buf_t);
aes_subBytes_inv(buf_t);
for (i = 14, rcon = 0x80; --i;)
{
if( ( i & 1 ) )
{
aes_expandDecKey(ctx_key, &rcon);
aes_addRoundKey(buf_t, &ctx_key[16]);
}
else
{
aes_addRoundKey(buf_t, ctx_key);
}
aes_mixColumns_inv(buf_t);
aes_shiftRows_inv(buf_t);
aes_subBytes_inv(buf_t);
}
aes_addRoundKey( buf_t, ctx_key);
/* copy thread back into global memory */
memcpy(&buf[offset], buf_t, AES_BLOCK_SIZE);
} /* aes256_decrypt */
/******************************************************************/
void encrypt(uint8_t key[32], uint8_t *buf, unsigned long numbytes)
{
printf("\nBeginning encryption\n");
aes256_init(key);
unsigned long offset;
//printf("Creating %d threads over %d blocks\n", dimBlock.x*dimGrid.x, dimBlock.x);
for (offset = 0; offset < numbytes; offset += AES_BLOCK_SIZE)
aes256_encrypt_ecb(buf, offset);
}
/******************************************************************/
void decrypt(uint8_t key[32], uint8_t *buf, unsigned long numbytes)
{
printf("\nBeginning decryption\n");
unsigned long offset;
//printf("Creating %d threads over %d blocks\n", dimBlock.x*dimGrid.x, dimBlock.x);
for (offset = 0; offset < numbytes; offset += AES_BLOCK_SIZE)
aes256_decrypt_ecb(buf, offset);
}
/******************************************************************/
int main (int argc, char *argv[])
{
FILE *file;
uint8_t *buf; // file buffer
unsigned long numbytes;
char *fname;
clock_t start, enc_time, dec_time;
int mili_sec, i;
int padding;
//key: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f
/* create a key vector */
uint8_t key[32];
// open input file
++argv, --argc;
if (argc > 0)
fname = argv[0];
else
fname = "input.txt";
file = fopen(fname, "r");
if (file == NULL) {printf("File %s doesn't exist\n", fname); exit(1); }
printf("Opened file %s\n", fname);
fseek(file, 0L, SEEK_END);
numbytes = ftell(file);
printf("Size is %lu\n", numbytes);
// copy file into memory
fseek(file, 0L, SEEK_SET);
buf = (uint8_t*)calloc(numbytes, sizeof(uint8_t));
if(buf == NULL) exit(1);
if (fread(buf, 1, numbytes, file) != numbytes)
{
printf("Unable to read all bytes from file %s\n", fname);
exit(EXIT_FAILURE);
}
fclose(file);
// calculate the padding
padding = numbytes % AES_BLOCK_SIZE;
numbytes += padding;
printf("Padding file with %d bytes for a new size of %lu\n", padding, numbytes);
// generate key
for (i = 0; i < sizeof(key);i++) key[i] = i;
printf("Starting encryption timer\n");
start = clock();
/******************************************************************/
encrypt(key, buf, numbytes);
enc_time = clock() - start;
printf("Stopping encryption timer\n");
// write the ciphertext to file
printf("Writing %lu bytes of encrypted data to cipher.txt\n", numbytes);
file = fopen("cipher.txt", "w");
fwrite(buf, 1, numbytes, file);
fclose(file);
printf("Starting decryption timer\n");
start = clock();
/******************************************************************/
decrypt(key, buf, numbytes);
dec_time = clock() - start;
printf("Stopping decryption timer\n");
mili_sec = enc_time * 1000 / CLOCKS_PER_SEC;
printf("Elapsed encryption time is %d minute(s), %d second(s), and %d millisecond(s).\n", (mili_sec/1000)/60, mili_sec/1000, mili_sec%1000);
mili_sec = dec_time * 1000 / CLOCKS_PER_SEC;
printf("Elapsed decryption time is %d minute(s), %d second(s), and %d millisecond(s).\n", (mili_sec/1000)/60, mili_sec/1000, mili_sec%1000);
printf("Writing %lu bytes of decrypted plaintext to output.txt\n", numbytes-padding);
file = fopen("output.txt", "w");
fwrite(buf, 1, numbytes - padding, file);
fclose(file);
free(buf);
return EXIT_SUCCESS;
} /* main */
| 30.085714 | 142 | 0.540225 | [
"vector"
] |
affe44cb00763ca9b4f7855129f43ecbcacd9ac2 | 895 | h | C | Pods/Headers/Public/SmartDeviceLink-iOS/SDLDimension.h | amarenthe/mobile_weather_sdl | aa8115ab3719804f956fb26a3ca705968519570f | [
"BSD-3-Clause"
] | null | null | null | Pods/Headers/Public/SmartDeviceLink-iOS/SDLDimension.h | amarenthe/mobile_weather_sdl | aa8115ab3719804f956fb26a3ca705968519570f | [
"BSD-3-Clause"
] | null | null | null | Pods/Headers/Public/SmartDeviceLink-iOS/SDLDimension.h | amarenthe/mobile_weather_sdl | aa8115ab3719804f956fb26a3ca705968519570f | [
"BSD-3-Clause"
] | null | null | null | // SDLDimension.h
//
#import "SDLEnum.h"
#import <Foundation/Foundation.h>
/**
* The supported dimensions of the GPS.
*
* @since SDL 2.0
*/
@interface SDLDimension : SDLEnum {
}
/**
* Convert String to SDLDimension
*
* @param value The value of the string to get an object for
*
* @return SDLDimension
*/
+ (SDLDimension *)valueOf:(NSString *)value;
/**
* @abstract Store the enumeration of all possible SDLDimension
*
* @return An array that store all possible SDLDimension
*/
+ (NSArray *)values;
/**
* @abstract No GPS at all
* @return the dimension with value of *NO_FIX*
*/
+ (SDLDimension *)NO_FIX;
/**
* @abstract Longitude and latitude of the GPS
* @return the dimension with value of *2D*
*/
+ (SDLDimension *)_2D;
/**
* @abstract Longitude and latitude and altitude of the GPS
* @return the dimension with value of *3D*
*/
+ (SDLDimension *)_3D;
@end
| 17.211538 | 63 | 0.673743 | [
"object",
"3d"
] |
b3092d0c93f0b1d5b71a337dab38910e6ebfa9ad | 1,897 | h | C | gazebo_ros_pkgs/gazebo_plugins/include/gazebo_plugins/MultiCameraPlugin.h | hect1995/Robotics_intro | 1b687585c20db5f1114d8ca6811a70313d325dd6 | [
"BSD-3-Clause"
] | 24 | 2019-04-28T09:46:24.000Z | 2022-03-22T13:51:51.000Z | gazebo_ros_pkgs/gazebo_plugins/include/gazebo_plugins/MultiCameraPlugin.h | hect1995/Robotics_intro | 1b687585c20db5f1114d8ca6811a70313d325dd6 | [
"BSD-3-Clause"
] | 1 | 2021-04-06T01:22:36.000Z | 2021-04-06T07:39:25.000Z | gazebo_ros_pkgs/gazebo_plugins/include/gazebo_plugins/MultiCameraPlugin.h | hect1995/Robotics_intro | 1b687585c20db5f1114d8ca6811a70313d325dd6 | [
"BSD-3-Clause"
] | 17 | 2019-09-29T10:22:41.000Z | 2021-04-08T12:38:37.000Z | /*
* Copyright 2012 Open Source Robotics Foundation
*
* 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.
*
*/
#ifndef _GAZEBO_MULTI_CAMERA_PLUGIN_HH_
#define _GAZEBO_MULTI_CAMERA_PLUGIN_HH_
#include <string>
#include <vector>
#include <gazebo/common/Plugin.hh>
#include <gazebo/sensors/MultiCameraSensor.hh>
#include <gazebo/rendering/Camera.hh>
#include <gazebo/gazebo.hh>
namespace gazebo
{
class MultiCameraPlugin : public SensorPlugin
{
public: MultiCameraPlugin();
/// \brief Destructor
public: virtual ~MultiCameraPlugin();
public: virtual void Load(sensors::SensorPtr _sensor, sdf::ElementPtr _sdf);
public: virtual void OnNewFrameLeft(const unsigned char *_image,
unsigned int _width, unsigned int _height,
unsigned int _depth, const std::string &_format);
public: virtual void OnNewFrameRight(const unsigned char *_image,
unsigned int _width, unsigned int _height,
unsigned int _depth, const std::string &_format);
protected: sensors::MultiCameraSensorPtr parentSensor;
protected: std::vector<unsigned int> width, height, depth;
protected: std::vector<std::string> format;
protected: std::vector<rendering::CameraPtr> camera;
private: std::vector<event::ConnectionPtr> newFrameConnection;
};
}
#endif
| 33.280702 | 80 | 0.705324 | [
"vector"
] |
b30b2f27ac9f17dee5f20e74f40e18466eec63dd | 909 | h | C | Shape.h | sknjpn/SyLife | b215cba87096db52ac63931db64c967f906b9172 | [
"MIT"
] | 5 | 2022-01-05T10:04:40.000Z | 2022-01-11T13:23:43.000Z | Shape.h | sknjpn/SyLife | b215cba87096db52ac63931db64c967f906b9172 | [
"MIT"
] | 1 | 2022-01-05T10:51:42.000Z | 2022-01-05T13:25:41.000Z | Shape.h | sknjpn/SyLife | b215cba87096db52ac63931db64c967f906b9172 | [
"MIT"
] | null | null | null | #pragma once
#include "Layer.h"
#include "Object.h"
class Shape : public Object, public Array<Layer> {
// 合成されたもの
Polygon m_polygon;
Texture m_preRenderTexture;
public:
void preRender();
bool updateProperties();
const Polygon& getPolygon() const { return m_polygon; }
double getInertia(double mass) const;
double getRadius() const { return Sqrt(2 * getInertia(1.0)); }
Vec2 getCentroid() const { return m_polygon.centroid(); }
RectF getTileSize() const;
const RectF& getBoundingRect() const { return m_polygon.boundingRect(); }
const Texture& getPreRenderTexture() const { return m_preRenderTexture; }
void draw(double a) const {
m_preRenderTexture
.scaled(1.0 / GeneralSetting::GetInstance().m_textureScale)
.draw(m_polygon.boundingRect().pos, ColorF(1.0, a));
}
void load(const JSON& json) override;
void save(JSON& json) const override;
};
| 25.971429 | 77 | 0.70297 | [
"object",
"shape"
] |
b313fca34f7e0666b2f1a6461e10262e07dc9f88 | 1,700 | c | C | lib/obj/rebirth_room.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/obj/rebirth_room.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/obj/rebirth_room.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | #define REBIRTH "/obj/rebirth"
inherit "/room/room";
reset(status arg) {
if(arg) return;
short_desc = "Beside the fountain of life";
add_exit("south", "/wizards/celtron/maze/necro/6");
long_desc =
"The divine fountain of life emits a bright light allover the room.\n"+
"The beams reflect from the white marble of which the walls and ceiling\n"+
"are made. The fountain itself doesn't look so ordinary, yet it contains\n"+
"awesome powers.\n";
}
init() {
::init();
add_action("do_rebirth", "drink");
}
do_rebirth(string arg) {
int i;
object *obje;
if(arg != "fountain" && arg != "from fountain") return 0;
say(this_player()->query_name()+" drinks from the fountain.\n");
if(strlen(this_player()->query_total_string()) < 11) {
write("You drink the water and feel refreshed. Still, you lack anything not ordinary.\n");
return 1;
}
if(this_player()->query_rebirth() == REBIRTH->query_max_rebirth()) {
write("You have already achieved the greatest level of existence.\n");
return 1;
}
if(!REBIRTH->enough_exp(this_player())) {
write("You drink the water and feel refreshed. Still, you lack anything not ordinary.\n");
return 1;
}
write("You drink from the blue deeps of the fountain and feel comsumed by a raw force of heat and cold.\n");
obje = all_inventory(this_player());
while(i<sizeof(obje)) {
if(obje[i] && obje[i]->short()) { destruct(obje[i]); }
i++;
}
this_player()->reinc();
this_player()->do_rebirth();
move_object(this_player(),"/obj/race_selection");
log_file("REBIRTH", ctime(time())+": "+this_player()->query_name()+" was reborn to level "+
this_player()->query_rebirth()+"\n");
return 1;
}
| 29.824561 | 110 | 0.667059 | [
"object"
] |
b318801517dc3414520f57fab84e50cf5feb047d | 6,624 | h | C | eraepub/chmlib/src/chm_lib.h | Mimars-Project/OpenReadEra-20.03.26 | 8db0c096e681947d02fa15c3eaa283e389ccf8a9 | [
"FTL"
] | null | null | null | eraepub/chmlib/src/chm_lib.h | Mimars-Project/OpenReadEra-20.03.26 | 8db0c096e681947d02fa15c3eaa283e389ccf8a9 | [
"FTL"
] | null | null | null | eraepub/chmlib/src/chm_lib.h | Mimars-Project/OpenReadEra-20.03.26 | 8db0c096e681947d02fa15c3eaa283e389ccf8a9 | [
"FTL"
] | 1 | 2021-07-21T07:50:33.000Z | 2021-07-21T07:50:33.000Z | /* $Id: chm_lib.h,v 1.10 2002/10/09 01:16:33 jedwin Exp $ */
/***************************************************************************
* chm_lib.h - CHM archive manipulation routines *
* ------------------- *
* *
* author: Jed Wing <jedwin@ugcs.caltech.edu> *
* version: 0.3 *
* notes: These routines are meant for the manipulation of microsoft *
* .chm (compiled html help) files, but may likely be used *
* for the manipulation of any ITSS archive, if ever ITSS *
* archives are used for any other purpose. *
* *
* Note also that the section names are statically handled. *
* To be entirely correct, the section names should be read *
* from the section names meta-file, and then the various *
* content sections and the "transforms" to apply to the data *
* they contain should be inferred from the section name and *
* the meta-files referenced using that name; however, all of *
* the files I've been able to get my hands on appear to have *
* only two sections: Uncompressed and MSCompressed. *
* Additionally, the ITSS.DLL file included with Windows does *
* not appear to handle any different transforms than the *
* simple LZX-transform. Furthermore, the list of transforms *
* to apply is broken, in that only half the required space *
* is allocated for the list. (It appears as though the *
* space is allocated for ASCII strings, but the strings are *
* written as unicode. As a result, only the first half of *
* the string appears.) So this is probably not too big of *
* a deal, at least until CHM v4 (MS .lit files), which also *
* incorporate encryption, of some description. *
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#ifndef INCLUDED_CHMLIB_H
#define INCLUDED_CHMLIB_H
#ifdef __cplusplus
extern "C" {
#endif
/* RWE 6/12/1002 */
#ifdef PPC_BSTR
#include <wtypes.h>
#endif
#ifdef WIN32
#ifdef __MINGW32__
#define __int64 long long
#endif
typedef unsigned __int64 LONGUINT64;
typedef __int64 LONGINT64;
#else
typedef unsigned long long LONGUINT64;
typedef long long LONGINT64;
#endif
/* the two available spaces in a CHM file */
/* N.B.: The format supports arbitrarily many spaces, but only */
/* two appear to be used at present. */
#define CHM_UNCOMPRESSED (0)
#define CHM_COMPRESSED (1)
/* structure representing an ITS (CHM) file stream */
struct chmFile;
/* structure representing an element from an ITS file stream */
#define CHM_MAX_PATHLEN (512)
struct chmUnitInfo
{
LONGUINT64 start;
LONGUINT64 length;
int space;
int flags;
char path[CHM_MAX_PATHLEN+1];
};
#define CHM_EXTERNAL_STREAM_SUPPORT 1
#ifdef CHM_EXTERNAL_STREAM_SUPPORT
/* external stream interface */
struct chmExternalFileStream {
/** returns file size, in bytes, if opened successfully */
LONGUINT64 (*open)(struct chmExternalFileStream * instance);
/** reads bytes to buffer */
LONGINT64 (*read)( struct chmExternalFileStream * instance, unsigned char * buf, LONGUINT64 pos, LONGINT64 len );
/** closes file */
int (*close)(struct chmExternalFileStream * instance);
};
#endif /*CHM_EXTERNAL_STREAM_SUPPORT*/
/* open an ITS archive */
#ifdef CHM_EXTERNAL_STREAM_SUPPORT
struct chmFile* chm_open(struct chmExternalFileStream * stream);
#else /*CHM_EXTERNAL_STREAM_SUPPORT*/
#ifdef PPC_BSTR
/* RWE 6/12/2003 */
struct chmFile* chm_open(BSTR filename);
#else
struct chmFile* chm_open(const char *filename);
#endif
#endif /*CHM_EXTERNAL_STREAM_SUPPORT*/
/* close an ITS archive */
void chm_close(struct chmFile *h);
/* methods for ssetting tuning parameters for particular file */
#define CHM_PARAM_MAX_BLOCKS_CACHED 0
void chm_set_param(struct chmFile *h,
int paramType,
int paramVal);
/* resolve a particular object from the archive */
#define CHM_RESOLVE_SUCCESS (0)
#define CHM_RESOLVE_FAILURE (1)
int chm_resolve_object(struct chmFile *h,
const char *objPath,
struct chmUnitInfo *ui);
/* retrieve part of an object from the archive */
LONGINT64 chm_retrieve_object(struct chmFile *h,
struct chmUnitInfo *ui,
unsigned char *buf,
LONGUINT64 addr,
LONGINT64 len);
/* enumerate the objects in the .chm archive */
typedef int (*CHM_ENUMERATOR)(struct chmFile *h,
struct chmUnitInfo *ui,
void *context);
#define CHM_ENUMERATE_NORMAL (1)
#define CHM_ENUMERATE_META (2)
#define CHM_ENUMERATE_SPECIAL (4)
#define CHM_ENUMERATE_FILES (8)
#define CHM_ENUMERATE_DIRS (16)
#define CHM_ENUMERATE_ALL (31)
#define CHM_ENUMERATOR_FAILURE (0)
#define CHM_ENUMERATOR_CONTINUE (1)
#define CHM_ENUMERATOR_SUCCESS (2)
int chm_enumerate(struct chmFile *h,
int what,
CHM_ENUMERATOR e,
void *context);
int chm_enumerate_dir(struct chmFile *h,
const char *prefix,
int what,
CHM_ENUMERATOR e,
void *context);
#ifdef __cplusplus
}
#endif
#endif /* INCLUDED_CHMLIB_H */
| 40.638037 | 117 | 0.547856 | [
"object",
"transform"
] |
b31cba1964ed59ef894c524cbab1c79b733143cf | 4,095 | h | C | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/plugins/platforms/mirclient/qmirclientscreen.h | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/plugins/platforms/mirclient/qmirclientscreen.h | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/plugins/platforms/mirclient/qmirclientscreen.h | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2014-2016 Canonical, Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QMIRCLIENTSCREEN_H
#define QMIRCLIENTSCREEN_H
#include <qpa/qplatformscreen.h>
#include <QSurfaceFormat>
#include <mir_toolkit/common.h> // just for MirFormFactor enum
#include "qmirclientcursor.h"
struct MirConnection;
struct MirOutput;
class QMirClientScreen : public QObject, public QPlatformScreen
{
Q_OBJECT
public:
QMirClientScreen(const MirOutput *output, MirConnection *connection);
virtual ~QMirClientScreen();
// QPlatformScreen methods.
QImage::Format format() const override { return mFormat; }
int depth() const override { return mDepth; }
QRect geometry() const override { return mGeometry; }
QRect availableGeometry() const override { return mGeometry; }
QSizeF physicalSize() const override { return mPhysicalSize; }
qreal devicePixelRatio() const override { return mDevicePixelRatio; }
QDpi logicalDpi() const override;
Qt::ScreenOrientation nativeOrientation() const override { return mNativeOrientation; }
Qt::ScreenOrientation orientation() const override { return mNativeOrientation; }
QPlatformCursor *cursor() const override { return const_cast<QMirClientCursor*>(&mCursor); }
// Additional Screen properties from Mir
int mirOutputId() const { return mOutputId; }
MirFormFactor formFactor() const { return mFormFactor; }
float scale() const { return mScale; }
// Internally used methods
void updateMirOutput(const MirOutput *output);
void setAdditionalMirDisplayProperties(float scale, MirFormFactor formFactor, int dpi);
void handleWindowSurfaceResize(int width, int height);
// QObject methods.
void customEvent(QEvent* event) override;
private:
void setMirOutput(const MirOutput *output);
QRect mGeometry, mNativeGeometry;
QSizeF mPhysicalSize;
qreal mDevicePixelRatio;
Qt::ScreenOrientation mNativeOrientation;
Qt::ScreenOrientation mCurrentOrientation;
QImage::Format mFormat;
int mDepth;
int mDpi;
qreal mRefreshRate;
MirFormFactor mFormFactor;
float mScale;
int mOutputId;
QMirClientCursor mCursor;
friend class QMirClientNativeInterface;
};
#endif // QMIRCLIENTSCREEN_H
| 38.271028 | 96 | 0.724298 | [
"geometry"
] |
b31eca22c26d567086c30fd3230cad877c1fa3f8 | 3,965 | h | C | src/3rdParty/ogdf-2020/include/ogdf/graphalg/steiner_tree/Full3ComponentGeneratorModule.h | MichaelTiernan/qvge | aff978d8592e07e24af4b8bab7c3204a7e7fb3fb | [
"MIT"
] | 3 | 2021-09-14T08:11:37.000Z | 2022-03-04T15:42:07.000Z | src/3rdParty/ogdf-2020/include/ogdf/graphalg/steiner_tree/Full3ComponentGeneratorModule.h | MichaelTiernan/qvge | aff978d8592e07e24af4b8bab7c3204a7e7fb3fb | [
"MIT"
] | 2 | 2021-12-04T17:09:53.000Z | 2021-12-16T08:57:25.000Z | src/3rdParty/ogdf-2020/include/ogdf/graphalg/steiner_tree/Full3ComponentGeneratorModule.h | MichaelTiernan/qvge | aff978d8592e07e24af4b8bab7c3204a7e7fb3fb | [
"MIT"
] | 2 | 2021-06-22T08:21:54.000Z | 2021-07-07T06:57:22.000Z | /** \file
* \brief Definition of ogdf::steiner_tree::Full3ComponentGeneratorModule class template
*
* \author Stephan Beyer
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.md in the OGDF root directory for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* 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.
*
* \par
* You should have received a copy of the GNU General Public
* License along with this program; if not, see
* http://www.gnu.org/copyleft/gpl.html
*/
#pragma once
#include <ogdf/graphalg/steiner_tree/EdgeWeightedGraph.h>
namespace ogdf {
namespace steiner_tree {
/**
* Interface for full 3-component generation including auxiliary functions
*
* A full 3-component is basically a tree with *exactly* three terminal leaves
* but no inner terminals. There must be exactly one nonterminal of degree 3,
* the so-called center.
*/
template<typename T>
class Full3ComponentGeneratorModule
{
public:
Full3ComponentGeneratorModule() = default;
virtual ~Full3ComponentGeneratorModule() = default;
//! Generate full components and call \p generateFunction for each full component
virtual void call(
const EdgeWeightedGraph<T> &G,
const List<node> &terminals,
const NodeArray<bool> &isTerminal,
const NodeArray<NodeArray<T>> &distance,
const NodeArray<NodeArray<edge>> &pred,
std::function<void(node, node, node, node, T)> generateFunction) const = 0;
protected:
/*!
* \brief Update center node if it is the best so far. (Just a helper to avoid code duplication.)
* @param x The node to test
* @param center The returned best center node
* @param minCost The returned cost of the component with that node
* @param dist1 SSSP distance vector of the first terminal
* @param dist2 SSSP distance vector of the second terminal
* @param dist3 SSSP distance vector of the third terminal
*/
inline void updateBestCenter(node x, node ¢er, T &minCost, const NodeArray<T> &dist1, const NodeArray<T> &dist2, const NodeArray<T> &dist3) const
{
#ifdef OGDF_FULL_COMPONENT_GENERATION_ALWAYS_SAFE
if (true) {
#else
if (dist1[x] < std::numeric_limits<T>::max()
&& dist2[x] < std::numeric_limits<T>::max()
&& dist3[x] < std::numeric_limits<T>::max()) {
#endif
const T tmp = dist1[x] + dist2[x] + dist3[x];
if (tmp < minCost) {
center = x;
minCost = tmp;
}
}
}
inline void forAllTerminalTriples(
const List<node> &terminals,
const NodeArray<NodeArray<T>> &distance,
std::function<void(node, node, node, const NodeArray<T> &, const NodeArray<T> &, const NodeArray<T> &)> func) const
{
for (ListConstIterator<node> it_u = terminals.begin(); it_u.valid(); ++it_u) {
for (ListConstIterator<node> it_v = it_u.succ(); it_v.valid(); ++it_v) {
for (ListConstIterator<node> it_w = it_v.succ(); it_w.valid(); ++it_w) {
func(*it_u, *it_v, *it_w, distance[*it_u], distance[*it_v], distance[*it_w]);
}
}
}
}
inline void checkAndGenerateFunction(node u, node v, node w, node center, T minCost,
const NodeArray<NodeArray<edge>> &pred,
const NodeArray<bool> &isTerminal,
std::function<void(node, node, node, node, T)> generateFunction) const
{
if (center
&& !isTerminal[center]
&& pred[u][center]
&& pred[v][center]
&& pred[w][center]) {
generateFunction(u, v, w, center, minCost);
}
}
};
}
}
| 33.041667 | 150 | 0.685246 | [
"vector"
] |
b325db6ae8a4c62958460e1ba39c129681d93069 | 3,069 | h | C | vendor/chromium/base/threading/thread_checker_impl.h | thorium-cfx/fivem | 587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c | [
"MIT"
] | 5,411 | 2017-04-14T08:57:56.000Z | 2022-03-30T19:35:15.000Z | vendor/chromium/base/threading/thread_checker_impl.h | thorium-cfx/fivem | 587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c | [
"MIT"
] | 802 | 2017-04-21T14:18:36.000Z | 2022-03-31T21:20:48.000Z | vendor/chromium/base/threading/thread_checker_impl.h | thorium-cfx/fivem | 587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c | [
"MIT"
] | 2,011 | 2017-04-14T09:44:15.000Z | 2022-03-31T15:40:39.000Z | // Copyright (c) 2011 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.
#ifndef BASE_THREADING_THREAD_CHECKER_IMPL_H_
#define BASE_THREADING_THREAD_CHECKER_IMPL_H_
#include "base/base_export.h"
#include "base/compiler_specific.h"
#include "base/sequence_token.h"
#include "base/synchronization/lock.h"
#include "base/thread_annotations.h"
#include "base/threading/platform_thread.h"
namespace base {
// Real implementation of ThreadChecker, for use in debug mode, or for temporary
// use in release mode (e.g. to CHECK on a threading issue seen only in the
// wild).
//
// Note: You should almost always use the ThreadChecker class to get the right
// version for your build configuration.
// Note: This is only a check, not a "lock". It is marked "LOCKABLE" only in
// order to support thread_annotations.h.
class LOCKABLE BASE_EXPORT ThreadCheckerImpl {
public:
ThreadCheckerImpl();
~ThreadCheckerImpl();
// Allow move construct/assign. This must be called on |other|'s associated
// thread and assignment can only be made into a ThreadCheckerImpl which is
// detached or already associated with the current thread. This isn't
// thread-safe (|this| and |other| shouldn't be in use while this move is
// performed). If the assignment was legal, the resulting ThreadCheckerImpl
// will be bound to the current thread and |other| will be detached.
ThreadCheckerImpl(ThreadCheckerImpl&& other);
ThreadCheckerImpl& operator=(ThreadCheckerImpl&& other);
bool CalledOnValidThread() const WARN_UNUSED_RESULT;
// Changes the thread that is checked for in CalledOnValidThread. This may
// be useful when an object may be created on one thread and then used
// exclusively on another thread.
void DetachFromThread();
private:
void EnsureAssignedLockRequired() const EXCLUSIVE_LOCKS_REQUIRED(lock_);
// Members are mutable so that CalledOnValidThread() can set them.
// Synchronizes access to all members.
mutable base::Lock lock_;
// Thread on which CalledOnValidThread() may return true.
mutable PlatformThreadRef thread_id_ GUARDED_BY(lock_);
// TaskToken for which CalledOnValidThread() always returns true. This allows
// CalledOnValidThread() to return true when called multiple times from the
// same task, even if it's not running in a single-threaded context itself
// (allowing usage of ThreadChecker objects on the stack in the scope of one-
// off tasks). Note: CalledOnValidThread() may return true even if the current
// TaskToken is not equal to this.
mutable TaskToken task_token_ GUARDED_BY(lock_);
// SequenceToken for which CalledOnValidThread() may return true. Used to
// ensure that CalledOnValidThread() doesn't return true for ThreadPool
// tasks that happen to run on the same thread but weren't posted to the same
// SingleThreadTaskRunner.
mutable SequenceToken sequence_token_ GUARDED_BY(lock_);
};
} // namespace base
#endif // BASE_THREADING_THREAD_CHECKER_IMPL_H_
| 40.92 | 80 | 0.766048 | [
"object"
] |
b3305fad5ca1778575dca565dc0870c8d4386b65 | 21,520 | c | C | Unix Family/Linux.lrk.e/ssh-2.0.13/apps/ssh/ssh-keygen2.c | fengjixuchui/Family | 2abe167082817d70ff2fd6567104ce4bcf0fe304 | [
"MIT"
] | 3 | 2021-05-15T15:57:13.000Z | 2022-03-16T09:11:05.000Z | Unix Family/Linux.lrk.e/ssh-2.0.13/apps/ssh/ssh-keygen2.c | fengjixuchui/Family | 2abe167082817d70ff2fd6567104ce4bcf0fe304 | [
"MIT"
] | null | null | null | Unix Family/Linux.lrk.e/ssh-2.0.13/apps/ssh/ssh-keygen2.c | fengjixuchui/Family | 2abe167082817d70ff2fd6567104ce4bcf0fe304 | [
"MIT"
] | 3 | 2021-05-15T15:57:15.000Z | 2022-01-08T20:51:04.000Z | /*
ssh-keygen.c
Authors:
Tatu Ylonen <ylo@ssh.fi>
Markku-Juhani Saarinen <mjos@ssh.fi>
Timo J. Rinne <tri@ssh.fi>
Sami Lehtinen <sjl@ssh.fi>
Copyright (C) 1997-1998 SSH Communications Security Oy, Espoo, Finland
All rights reserved.
A tool for generating and manipulating private keys.
*/
/*
* $Log: ssh-keygen2.c,v $
* $EndLog$
*/
#include "sshincludes.h"
#include "ssh2includes.h"
#include "sshuserfiles.h"
#include "sshreadline.h"
#include "readpass.h"
#include "sshuser.h"
#include "sshcrypt.h"
#include "sshcipherlist.h"
#include "ssh2pubkeyencode.h"
#include "sshgetopt.h"
#include <sys/types.h>
#include <pwd.h>
#define SSH_DEBUG_MODULE "SshKeyGen"
/* Standard (assumed) choices.. */
#ifndef KEYGEN_ASSUMED_PUBKEY_LEN
#define KEYGEN_ASSUMED_PUBKEY_LEN 1024
#endif /* KEYGEN_ASSUMED_PUBKEY_LEN */
#ifdef HAVE_LIBWRAP
int allow_severity = SSH_LOG_INFORMATIONAL;
int deny_severity = SSH_LOG_WARNING;
#endif /* HAVE_LIBWRAP */
/* helptext */
const char keygen_helptext[] =
"Usage: ssh-keygen [options]\n"
"\n"
"Where `options' are:\n"
" -b nnn Specify key strength in bits (e.g. 1024)\n"
" -t dsa Choose the key type (only dsa available).\n"
" -h Print this help text.\n"
" -e file Edit the comment/passphrase of the key.\n"
" -c comment Provide the comment.\n"
" -p passphrase Provide passphrase.\n"
" -P Assume empty passphrase.\n"
" -q Suppress the progress indicator.\n"
" -1 Convert a SSH 1.x key. (not implemented)\n"
" -i file Load and display information on `file'. (not implemented)\n"
" -v Print ssh-keygen version number.\n"
" -r Stir data from stdin to random pool.\n";
/* A context structure -- we don't like global variables. */
typedef struct
{
int keybits;
Boolean newkey;
Boolean convert;
Boolean status;
Boolean edit_key;
Boolean read_stdin;
char *keytype;
char *keytypecommon;
char *comment;
char *in_filename;
char *out_filename;
char *passphrase;
Boolean pass_empty;
SshRandomState random_state;
SshPrivateKey private_key;
SshPublicKey public_key;
SshUser user;
Boolean prog_ind;
Boolean have_prog_ind;
} KeyGenCtx;
/* mapping of common names and CryptoLib names. Common names are
not case sensitive.
The first entry in this list will be the preferred (standard)
choice. */
const char *keygen_common_names[][2] =
{
/* Digital Signature Standard */
{ "dsa", SSH_CRYPTO_DSS },
{ "dss", SSH_CRYPTO_DSS },
/* Last entry */
{ NULL, NULL }
};
/* allocate the context */
KeyGenCtx *keygen_init_ctx()
{
KeyGenCtx *kgc;
kgc = ssh_xcalloc(1, sizeof (KeyGenCtx));
kgc->keybits = FALSE;
kgc->newkey = FALSE;
kgc->convert = FALSE;
kgc->status = FALSE;
kgc->read_stdin = FALSE;
kgc->edit_key = FALSE;
kgc->keytype = NULL;
kgc->keytypecommon = NULL;
kgc->comment = NULL;
kgc->out_filename = NULL;
kgc->in_filename = NULL;
kgc->passphrase = NULL;
kgc->pass_empty = FALSE;
kgc->user = ssh_user_initialize(NULL, FALSE);
kgc->random_state = ssh_randseed_open(kgc->user, NULL);
kgc->public_key = NULL;
kgc->private_key = NULL;
kgc->prog_ind = FALSE;
kgc->have_prog_ind = TRUE;
return kgc;
}
/* Zeroize and free a NULL-terminated string, assuming that the pointer
is non-null */
void keygen_free_str(char *s)
{
if (s == NULL)
return;
memset(s, 0, strlen(s));
ssh_xfree(s);
}
/* free the context */
void keygen_free_ctx(KeyGenCtx *kgc)
{
keygen_free_str(kgc->keytype);
keygen_free_str(kgc->keytypecommon);
keygen_free_str(kgc->comment);
keygen_free_str(kgc->in_filename);
keygen_free_str(kgc->out_filename);
keygen_free_str(kgc->passphrase);
if (kgc->public_key != NULL)
ssh_public_key_free(kgc->public_key);
if (kgc->private_key != NULL)
ssh_private_key_free(kgc->private_key);
ssh_randseed_update(kgc->user, kgc->random_state, NULL);
ssh_random_free(kgc->random_state);
if (kgc->user != NULL)
ssh_user_free(kgc->user, FALSE);
if (kgc->prog_ind)
ssh_crypto_library_register_progress_func(NULL, NULL);
memset(kgc, 0, sizeof (KeyGenCtx));
ssh_xfree(kgc);
}
/* Ask for a passphrase twice */
char *ssh_read_passphrase_twice(char *prompt1, char *prompt2, int from_stdin)
{
char *r1, *r2;
for (;;)
{
r1 = ssh_read_passphrase(prompt1, from_stdin);
r2 = ssh_read_passphrase(prompt2, from_stdin);
if (strcmp(r1, r2) != 0)
{
keygen_free_str(r1);
keygen_free_str(r2);
fprintf(stderr, "Passphrases do not match.\n");
}
else
break;
}
keygen_free_str(r2);
return r1;
}
/* Read a string (with echo) from stdin */
char *ssh_askpass_read_stdin(char *prompt)
{
char buf[1024], *p;
if (prompt != NULL)
{
printf("%s", prompt);
fflush(stdout);
}
if (fgets(buf, sizeof (buf)-1, stdin) == NULL)
return ssh_xstrdup("");
for(p = buf; *p >= 32 || *p < 0; p++);
*p = '\0';
p = ssh_xstrdup(buf);
memset(buf, 0, sizeof (buf));
return p;
}
/* Keygen error message */
void keygen_error(KeyGenCtx *kgc, char *expl)
{
fprintf(stderr, "\nError: %s\n", expl);
keygen_free_ctx(kgc);
exit(-1);
}
/* The progress indicator */
void keygen_prog_ind(SshCryptoProgressID id, unsigned int time_value,
void *incr)
{
int i;
i = *((int *) incr);
(*((int *) incr))++;
if (i % 13 == 0)
{
printf("\r %3d ", i / 13 + 1);
}
else
{
switch( i % 4 )
{
case 0:
printf(".");
break;
case 1:
case 3:
printf("o");
break;
case 2:
printf("O");
break;
}
}
fflush(stdout);
}
/* Generate a filename for the private key */
void keygen_choose_filename(KeyGenCtx *kgc)
{
int i;
char buf[1024], *udir;
struct stat st;
if (kgc->out_filename != NULL)
return;
if((udir = ssh_userdir(kgc->user, NULL, TRUE)) == NULL)
{
ssh_warning("Unable to open user ssh2 directory. "
"Saving to current directory.");
udir = ssh_xstrdup(".");
}
for (i = 'a'; i <= 'z'; i++)
{
snprintf(buf, sizeof (buf), "%s/id_%s_%d_%c",
udir, kgc->keytypecommon, kgc->keybits, i);
if (stat(buf, &st) == 0)
continue;
kgc->out_filename = ssh_xstrdup(buf);
goto done;
}
ssh_fatal("Could not find a suitable file name.");
done:
ssh_xfree(udir);
}
/* Generate the key. this is done when kgc->newkey is TRUE. */
int keygen_keygen(KeyGenCtx *kgc)
{
SshCryptoStatus code;
char buf[1024];
int incr;
char *pass = NULL;
int r = 0;
/* Register our progress indicator. */
incr = 0;
if (kgc->prog_ind == FALSE && kgc->have_prog_ind == TRUE)
{
ssh_crypto_library_register_progress_func(keygen_prog_ind, &incr);
kgc->prog_ind = TRUE;
}
printf("Generating %d-bit %s key pair\n",
kgc->keybits,
kgc->keytypecommon);
if ((code = ssh_private_key_generate(kgc->random_state,
&(kgc->private_key),
kgc->keytype,
SSH_PKF_SIZE, kgc->keybits,
SSH_PKF_END)) != SSH_CRYPTO_OK)
{
keygen_error(kgc, (char *) ssh_crypto_status_message(code));
}
printf("\nKey generated.\n");
printf("%s\n", kgc->comment);
/* Ok, now save the private key. */
keygen_choose_filename(kgc);
if ((! kgc->passphrase) || (! (*(kgc->passphrase)))) {
if (!(kgc->pass_empty))
{
pass = ssh_read_passphrase_twice("Passphrase : ",
"Again : ",
FALSE);
}
else
{
pass = ssh_xstrdup("");
}
keygen_free_str(kgc->passphrase);
kgc->passphrase = pass ? pass : ssh_xstrdup("");
}
if (!(*(kgc->passphrase)))
{
ssh_warning("Key is stored with NULL passphrase.");
}
if (ssh_privkey_write(kgc->user,
kgc->out_filename,
kgc->passphrase,
kgc->comment,
kgc->private_key, kgc->random_state, NULL))
{
ssh_warning("Private key not written !");
r++;
}
else
{
printf("Private key saved to %s\n", kgc->out_filename);
}
/* Save the public key */
snprintf(buf, sizeof (buf), "%s.pub", kgc->out_filename);
kgc->public_key = ssh_private_key_derive_public_key(kgc->private_key);
if (kgc->public_key == NULL)
{
ssh_warning("Could not derive public key from private key.");
return r + 1;
}
if (ssh_pubkey_write(kgc->user, buf, kgc->comment, kgc->public_key, NULL))
{
ssh_warning("Public key not written !");
r++;
}
else
{
printf("Public key saved to %s\n", buf);
}
return r;
}
/* Stir in data from stdin */
void stir_stdin(KeyGenCtx *kgc)
{
unsigned char buffer[64];
size_t n, bytes;
bytes = 0;
while (!feof(stdin))
{
n = fread(buffer, 1, sizeof (buffer), stdin);
if (n > 0)
ssh_random_add_noise(kgc->random_state, buffer, n);
bytes += n;
}
memset(buffer, 0, sizeof (buffer));
if (kgc->have_prog_ind)
printf("Stirred in %lu bytes.\n", (unsigned long) bytes);
}
int keygen_convert_key(KeyGenCtx *kgc)
{
ssh_fatal("Key conversion not yet supported.");
return -1;
}
int keygen_edit_key(KeyGenCtx *kgc)
{
SshPrivateKey seckey = NULL;
SshPublicKey pubkey = NULL;
char pubfn[1024];
char outpubfn[1024];
char pubbu[1024];
char secbu[1024];
char *secfn;
char *outsecfn;
int ok;
int ed;
char *oldcomment = NULL;
char *newcomment = NULL;
char *newpass = NULL;
if (!(*(kgc->in_filename)))
{
ssh_warning("Invalid keyfile.");
return 1;
}
else
{
secfn = kgc->in_filename;
snprintf(pubfn, sizeof (pubfn), "%s.pub", secfn);
}
if (!(kgc->out_filename))
{
kgc->out_filename = ssh_xstrdup(kgc->in_filename);
}
outsecfn = kgc->out_filename;
snprintf(outpubfn, sizeof (outpubfn), "%s.pub", outsecfn);
snprintf(secbu, sizeof (secbu), "%s~", kgc->in_filename);
snprintf(pubbu, sizeof (pubbu), "%s~", pubfn);
(void)unlink(secbu);
(void)unlink(pubbu);
pubkey = ssh_pubkey_read(kgc->user, pubfn, &oldcomment, NULL);
if (! pubkey)
{
ssh_warning("Cannot read public keyfile %s.", pubfn);
return 1;
}
if (! oldcomment)
oldcomment = ssh_xstrdup("");
if (kgc->passphrase)
{
seckey = ssh_privkey_read(kgc->user, secfn, kgc->passphrase, NULL, NULL);
}
if (! seckey)
{
seckey = ssh_privkey_read(kgc->user, secfn, "", NULL, NULL);
if (seckey)
{
keygen_free_str(kgc->passphrase);
kgc->passphrase = ssh_xstrdup("");
}
}
if (! kgc->pass_empty)
{
if (! seckey)
{
keygen_free_str(kgc->passphrase);
printf("Passphrase needed for key \"%s\".\n", oldcomment);
kgc->passphrase = ssh_read_passphrase("Passphrase : ", FALSE);
if (kgc->passphrase)
{
seckey = ssh_privkey_read(kgc->user, secfn, kgc->passphrase,
NULL, NULL);
}
}
}
if (! seckey)
{
ssh_warning("Cannot read private keyfile %s.", secfn);
return 1;
}
printf("Do you want to edit key \"%s\" ", oldcomment);
if (! ssh_read_confirmation("(yes or no)? "))
{
printf("Key unedited and unsaved.\n");
keygen_free_str(oldcomment);
return 0;
}
ok = 0;
ed = 0;
while (! ok)
{
if (! newcomment)
newcomment = ssh_xstrdup(oldcomment);
printf("Your key comment is \"%s\". ", newcomment);
if (ssh_read_confirmation("Do you want to edit it (yes or no)? "))
{
if (ssh_readline("New key comment: ",
(unsigned char **)&newcomment,
TRUE) < 0)
{
fprintf(stderr, "Abort! Key unedited and unsaved.\n");
keygen_free_str(newpass);
keygen_free_str(newcomment);
keygen_free_str(oldcomment);
return 1;
}
putchar('\n');
}
if (! newpass)
newpass = ssh_xstrdup(kgc->passphrase);
if (! kgc->pass_empty)
{
if (ssh_read_confirmation("Do you want to edit passphrase (yes or no)? "))
{
keygen_free_str(newpass);
newpass = ssh_read_passphrase_twice("New passphrase : ",
"Again : ",
FALSE);
if (! newpass)
{
fprintf(stderr, "Abort! Key unedited and unsaved.\n");
keygen_free_str(newcomment);
keygen_free_str(oldcomment);
return 0;
}
}
}
printf("Do you want to continue editing key \"%s\" ", newcomment);
if (ssh_read_confirmation("(yes or no)? "))
ok = 0;
else
ok = 1;
}
if ((strcmp(newpass, kgc->passphrase) == 0) &&
(strcmp(newcomment, oldcomment) == 0))
{
printf("Key unedited and unsaved.\n");
keygen_free_str(newpass);
keygen_free_str(newcomment);
keygen_free_str(oldcomment);
return 0;
}
printf("Do you want to save key \"%s\" to file %s ", newcomment, outsecfn);
if (! ssh_read_confirmation("(yes or no)? "))
{
printf("Key unsaved.\n");
keygen_free_str(newpass);
keygen_free_str(newcomment);
keygen_free_str(oldcomment);
return 0;
}
if (strcmp(outsecfn, kgc->in_filename) == 0)
{
if (rename(outsecfn, secbu) != 0)
{
ssh_warning("Unable to backup private key.");
keygen_free_str(newpass);
keygen_free_str(newcomment);
keygen_free_str(oldcomment);
fprintf(stderr, "Abort!\n");
return 1;
}
}
if (strcmp(outpubfn, pubfn) == 0)
{
if (rename(outpubfn, pubbu) != 0)
{
ssh_warning("Unable to backup private key.");
if (strcmp(outsecfn, secfn) == 0)
(void)rename(secbu, outsecfn);
keygen_free_str(newpass);
keygen_free_str(newcomment);
keygen_free_str(oldcomment);
fprintf(stderr, "Abort!\n");
return 1;
}
}
if (ssh_privkey_write(kgc->user,
outsecfn,
newpass,
newcomment,
seckey,
kgc->random_state,
NULL))
{
ssh_warning("Unable to write private key.!");
if (strcmp(outsecfn, secfn) == 0)
(void)rename(secbu, outsecfn);
if (strcmp(outpubfn, pubfn) == 0)
(void)rename(pubbu, outpubfn);
keygen_free_str(newpass);
keygen_free_str(newcomment);
keygen_free_str(oldcomment);
fprintf(stderr, "Abort!\n");
return 1;
}
if (ssh_pubkey_write(kgc->user,
outpubfn,
newcomment,
pubkey,
NULL))
{
ssh_warning("Unable to write public key.!");
unlink(outsecfn);
if (strcmp(outsecfn, secfn) == 0)
(void)rename(secbu, outsecfn);
if (strcmp(outpubfn, pubfn) == 0)
(void)rename(pubbu, outpubfn);
keygen_free_str(newpass);
keygen_free_str(newcomment);
keygen_free_str(oldcomment);
fprintf(stderr, "Abort!\n");
return 1;
}
keygen_free_str(newpass);
keygen_free_str(newcomment);
keygen_free_str(oldcomment);
return 0;
}
/* main for ssh-keygen */
int main(int argc, char **argv)
{
int ch, i;
KeyGenCtx *kgc;
struct passwd *pw;
char *t;
SshTime now;
int r = 0, rr = 0;
/* Initialize the context */
kgc = keygen_init_ctx();
/* try to find the user's home directory */
while ((ch = ssh_getopt(argc, argv, "vhqr?P1:t:b:p:o:i:e:c:", NULL)) != EOF)
{
if (!ssh_optval)
{
printf("%s", keygen_helptext);
keygen_free_ctx(kgc);
exit(1);
}
switch (ch)
{
/* -b: specify the strength of the key */
case 'b':
if (kgc->keybits != 0)
keygen_error(kgc, "Multiple -b parameters");
kgc->keybits = atoi(ssh_optarg);
if (kgc->keybits < 128 || kgc->keybits > 0x10000)
keygen_error(kgc, "Illegal key size.");
break;
/* -t: specify the key type. */
case 't':
/* the kgc->keytype gets the crypto library name of the alg. */
if (kgc->keytype != NULL)
keygen_error(kgc, "multiple key types specified.");
for (i = 0; keygen_common_names[i][0] != NULL; i++)
{
if (strcasecmp(keygen_common_names[i][0], ssh_optarg) == 0)
{
kgc->keytypecommon = ssh_xstrdup(keygen_common_names[i][0]);
kgc->keytype = ssh_xstrdup(keygen_common_names[i][1]);
break;
}
}
if (keygen_common_names[i][0] == NULL)
keygen_error(kgc, "unknown key type.");
break;
/* -c: Comment string. */
case 'c':
kgc->comment = ssh_xstrdup(ssh_optarg);
break;
/* -e: Edit key file. */
case 'e':
kgc->edit_key = TRUE;
kgc->in_filename = ssh_xstrdup(ssh_optarg);
/* -p: Provide passphrase. */
case 'p':
kgc->passphrase = ssh_xstrdup(ssh_optarg);
break;
/* -P: Don't provide passphrase. */
case 'P':
kgc->pass_empty = TRUE;
keygen_free_str(kgc->passphrase);
kgc->passphrase = NULL;
break;
/* -1: Convert a key from SSH1 format to SSH2 format. */
case '1':
kgc->convert = TRUE;
kgc->in_filename = ssh_xstrdup(ssh_optarg);
break;
/* -o: Provide the output filename. */
case 'o':
kgc->out_filename = ssh_xstrdup(ssh_optarg);
break;
/* -v: print the version number */
case 'v':
printf("ssh2-keygen version " SSH2_VERSION
", compiled "__DATE__".\n");
/* XXX more stuff here possibly */
keygen_free_ctx(kgc);
exit(0);
/* -h: print a short help text */
case '?':
case 'h':
printf("%s", keygen_helptext);
keygen_free_ctx(kgc);
exit(0);
/* -q: supress the progress indicator */
case 'q':
kgc->have_prog_ind = FALSE;
break;
/* -r: stir in data from stdin to the random pool */
case 'r':
kgc->read_stdin = TRUE;
break;
/* -i: display (all) information about a key */
case 'i':
ssh_fatal("-i not yet implemented XXX");
}
}
/* Stir in random data from stdin, if requested */
if (kgc->read_stdin)
{
stir_stdin(kgc);
keygen_free_ctx(kgc);
return 0;
}
if (kgc->convert)
{
r = keygen_convert_key(kgc);
}
else if (kgc->edit_key)
{
r = keygen_edit_key(kgc);
}
else
{
kgc->newkey = TRUE;
if (kgc->keybits == 0)
{
kgc->keybits = KEYGEN_ASSUMED_PUBKEY_LEN;
}
if (kgc->keytype == NULL)
{
kgc->keytypecommon = ssh_xstrdup(keygen_common_names[0][0]);
kgc->keytype = ssh_xstrdup(keygen_common_names[0][1]);
}
if (kgc->comment == NULL)
{
char *time_str;
pw = getpwuid(getuid());
if (!pw)
keygen_error(kgc, "Could not get user's password structure.");
t = ssh_xmalloc(64);
gethostname(t, 64);
kgc->comment = ssh_xmalloc(256);
now = ssh_time();
time_str = ssh_readable_time_string(now, TRUE);
snprintf(kgc->comment, 256, "%d-bit %s, %s@%s, %s",
kgc->keybits, kgc->keytypecommon,
pw->pw_name, t, time_str);
ssh_xfree(time_str);
ssh_xfree(t);
}
if (ssh_optind >= argc)
{
/* generate single key. if no file names given, make up one. */
if (kgc->out_filename == NULL)
keygen_choose_filename(kgc);
r = keygen_keygen(kgc);
}
else
{
if (kgc->out_filename != NULL)
keygen_keygen(kgc);
/* iterate over additional filenames */
for (i = ssh_optind; i < argc; i++)
{
if (kgc->out_filename != NULL)
ssh_xfree(kgc->out_filename);
kgc->out_filename = ssh_xstrdup(argv[i]);
rr = keygen_keygen(kgc);
if (rr != 0)
{
if (r == 0)
r = rr;
else
r = -1;
}
}
}
}
keygen_free_ctx(kgc);
return r;
}
| 24.538198 | 84 | 0.542704 | [
"3d"
] |
b3348c020e2a926fce7913ba81407abb3a43236f | 1,357 | h | C | include/motion_lid.h | longsleep/ec | bf579e94e4682b13bd58bab31bc21bbc95572221 | [
"BSD-3-Clause"
] | 4 | 2015-04-10T21:04:12.000Z | 2015-06-01T09:49:56.000Z | include/motion_lid.h | longsleep/ec | bf579e94e4682b13bd58bab31bc21bbc95572221 | [
"BSD-3-Clause"
] | 3 | 2015-06-23T07:52:07.000Z | 2015-06-23T08:06:32.000Z | include/motion_lid.h | r3d4/cb_hddledd | 5296dd7a30c218c0b047135f946bc7b34ad717fa | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* Header for motion_sense.c */
#ifndef __CROS_EC_MOTION_LID_H
#define __CROS_EC_MOTION_LID_H
/* Anything outside of lid angle range [-180, 180] should work. */
#define LID_ANGLE_UNRELIABLE 500.0F
/**
* This structure defines all of the data needed to specify the orientation
* of the base and lid accelerometers in order to calculate the lid angle.
*/
struct accel_orientation {
/* Rotation matrix to rotate positive 90 degrees around the hinge. */
matrix_3x3_t rot_hinge_90;
/*
* Rotation matrix to rotate 180 degrees around the hinge. The value
* here should be rot_hinge_90 ^ 2.
*/
matrix_3x3_t rot_hinge_180;
/* Vector pointing along hinge axis. */
vector_3_t hinge_axis;
};
/* Link global structure for orientation. This must be defined in board.c. */
extern const struct accel_orientation acc_orient;
/**
* Get last calculated lid angle. Note, the lid angle calculated by the EC
* is un-calibrated and is an approximate angle.
*
* @return lid angle in degrees in range [0, 360].
*/
int motion_lid_get_angle(void);
int host_cmd_motion_lid(struct host_cmd_handler_args *args);
void motion_lid_calc(void);
#endif /* __CROS_EC_MOTION_LID_H */
| 26.607843 | 77 | 0.747237 | [
"vector"
] |
6c2d9e8e2a559bb37f1b158a9e77565b8895a720 | 10,252 | h | C | cpp/src/arrow/compute/exec/expression.h | GavinRay97/arrow | 11d2e4863974b95c1fa637e83757b98f291366c3 | [
"Apache-2.0"
] | 1 | 2021-12-03T13:50:32.000Z | 2021-12-03T13:50:32.000Z | cpp/src/arrow/compute/exec/expression.h | GavinRay97/arrow | 11d2e4863974b95c1fa637e83757b98f291366c3 | [
"Apache-2.0"
] | 3 | 2022-02-09T03:24:57.000Z | 2022-02-14T22:26:27.000Z | cpp/src/arrow/compute/exec/expression.h | GavinRay97/arrow | 11d2e4863974b95c1fa637e83757b98f291366c3 | [
"Apache-2.0"
] | 1 | 2020-08-27T22:54:09.000Z | 2020-08-27T22:54:09.000Z | // 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.
// This API is EXPERIMENTAL.
#pragma once
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "arrow/compute/type_fwd.h"
#include "arrow/datum.h"
#include "arrow/type_fwd.h"
#include "arrow/util/small_vector.h"
#include "arrow/util/variant.h"
namespace arrow {
namespace compute {
/// \defgroup expression-core Expressions to describe transformations in execution plans
///
/// @{
/// An unbound expression which maps a single Datum to another Datum.
/// An expression is one of
/// - A literal Datum.
/// - A reference to a single (potentially nested) field of the input Datum.
/// - A call to a compute function, with arguments specified by other Expressions.
class ARROW_EXPORT Expression {
public:
struct Call {
std::string function_name;
std::vector<Expression> arguments;
std::shared_ptr<FunctionOptions> options;
// Cached hash value
size_t hash;
// post-Bind properties:
std::shared_ptr<Function> function;
const Kernel* kernel = NULLPTR;
std::shared_ptr<KernelState> kernel_state;
ValueDescr descr;
void ComputeHash();
};
std::string ToString() const;
bool Equals(const Expression& other) const;
size_t hash() const;
struct Hash {
size_t operator()(const Expression& expr) const { return expr.hash(); }
};
/// Bind this expression to the given input type, looking up Kernels and field types.
/// Some expression simplification may be performed and implicit casts will be inserted.
/// Any state necessary for execution will be initialized and returned.
Result<Expression> Bind(const ValueDescr& in, ExecContext* = NULLPTR) const;
Result<Expression> Bind(const Schema& in_schema, ExecContext* = NULLPTR) const;
// XXX someday
// Clone all KernelState in this bound expression. If any function referenced by this
// expression has mutable KernelState, it is not safe to execute or apply simplification
// passes to it (or copies of it!) from multiple threads. Cloning state produces new
// KernelStates where necessary to ensure that Expressions may be manipulated safely
// on multiple threads.
// Result<ExpressionState> CloneState() const;
// Status SetState(ExpressionState);
/// Return true if all an expression's field references have explicit ValueDescr and all
/// of its functions' kernels are looked up.
bool IsBound() const;
/// Return true if this expression is composed only of Scalar literals, field
/// references, and calls to ScalarFunctions.
bool IsScalarExpression() const;
/// Return true if this expression is literal and entirely null.
bool IsNullLiteral() const;
/// Return true if this expression could evaluate to true.
bool IsSatisfiable() const;
// XXX someday
// Result<PipelineGraph> GetPipelines();
/// Access a Call or return nullptr if this expression is not a call
const Call* call() const;
/// Access a Datum or return nullptr if this expression is not a literal
const Datum* literal() const;
/// Access a FieldRef or return nullptr if this expression is not a field_ref
const FieldRef* field_ref() const;
/// The type and shape to which this expression will evaluate
ValueDescr descr() const;
std::shared_ptr<DataType> type() const { return descr().type; }
// XXX someday
// NullGeneralization::type nullable() const;
struct Parameter {
FieldRef ref;
// post-bind properties
ValueDescr descr;
internal::SmallVector<int, 2> indices;
};
const Parameter* parameter() const;
Expression() = default;
explicit Expression(Call call);
explicit Expression(Datum literal);
explicit Expression(Parameter parameter);
private:
using Impl = util::Variant<Datum, Parameter, Call>;
std::shared_ptr<Impl> impl_;
ARROW_EXPORT friend bool Identical(const Expression& l, const Expression& r);
ARROW_EXPORT friend void PrintTo(const Expression&, std::ostream*);
};
inline bool operator==(const Expression& l, const Expression& r) { return l.Equals(r); }
inline bool operator!=(const Expression& l, const Expression& r) { return !l.Equals(r); }
// Factories
ARROW_EXPORT
Expression literal(Datum lit);
template <typename Arg>
Expression literal(Arg&& arg) {
return literal(Datum(std::forward<Arg>(arg)));
}
ARROW_EXPORT
Expression field_ref(FieldRef ref);
ARROW_EXPORT
Expression call(std::string function, std::vector<Expression> arguments,
std::shared_ptr<FunctionOptions> options = NULLPTR);
template <typename Options, typename = typename std::enable_if<
std::is_base_of<FunctionOptions, Options>::value>::type>
Expression call(std::string function, std::vector<Expression> arguments,
Options options) {
return call(std::move(function), std::move(arguments),
std::make_shared<Options>(std::move(options)));
}
/// Assemble a list of all fields referenced by an Expression at any depth.
ARROW_EXPORT
std::vector<FieldRef> FieldsInExpression(const Expression&);
/// Check if the expression references any fields.
ARROW_EXPORT
bool ExpressionHasFieldRefs(const Expression&);
/// Assemble a mapping from field references to known values.
struct ARROW_EXPORT KnownFieldValues;
ARROW_EXPORT
Result<KnownFieldValues> ExtractKnownFieldValues(
const Expression& guaranteed_true_predicate);
/// @}
/// \defgroup expression-passes Functions for modification of Expressions
///
/// @{
///
/// These transform bound expressions. Some transforms utilize a guarantee, which is
/// provided as an Expression which is guaranteed to evaluate to true. The
/// guaranteed_true_predicate need not be bound, but canonicalization is currently
/// deferred to producers of guarantees. For example in order to be recognized as a
/// guarantee on a field value, an Expression must be a call to "equal" with field_ref LHS
/// and literal RHS. Flipping the arguments, "is_in" with a one-long value_set, ... or
/// other semantically identical Expressions will not be recognized.
/// Weak canonicalization which establishes guarantees for subsequent passes. Even
/// equivalent Expressions may result in different canonicalized expressions.
/// TODO this could be a strong canonicalization
ARROW_EXPORT
Result<Expression> Canonicalize(Expression, ExecContext* = NULLPTR);
/// Simplify Expressions based on literal arguments (for example, add(null, x) will always
/// be null so replace the call with a null literal). Includes early evaluation of all
/// calls whose arguments are entirely literal.
ARROW_EXPORT
Result<Expression> FoldConstants(Expression);
/// Simplify Expressions by replacing with known values of the fields which it references.
ARROW_EXPORT
Result<Expression> ReplaceFieldsWithKnownValues(const KnownFieldValues& known_values,
Expression);
/// Simplify an expression by replacing subexpressions based on a guarantee:
/// a boolean expression which is guaranteed to evaluate to `true`. For example, this is
/// used to remove redundant function calls from a filter expression or to replace a
/// reference to a constant-value field with a literal.
ARROW_EXPORT
Result<Expression> SimplifyWithGuarantee(Expression,
const Expression& guaranteed_true_predicate);
/// @}
// Execution
/// Create an ExecBatch suitable for passing to ExecuteScalarExpression() from a
/// RecordBatch which may have missing or incorrectly ordered columns.
/// Missing fields will be replaced with null scalars.
ARROW_EXPORT Result<ExecBatch> MakeExecBatch(const Schema& full_schema,
const Datum& partial);
/// Execute a scalar expression against the provided state and input ExecBatch. This
/// expression must be bound.
ARROW_EXPORT
Result<Datum> ExecuteScalarExpression(const Expression&, const ExecBatch& input,
ExecContext* = NULLPTR);
/// Convenience function for invoking against a RecordBatch
ARROW_EXPORT
Result<Datum> ExecuteScalarExpression(const Expression&, const Schema& full_schema,
const Datum& partial_input, ExecContext* = NULLPTR);
// Serialization
ARROW_EXPORT
Result<std::shared_ptr<Buffer>> Serialize(const Expression&);
ARROW_EXPORT
Result<Expression> Deserialize(std::shared_ptr<Buffer>);
/// \defgroup expression-convenience Functions convenient expression creation
///
/// @{
ARROW_EXPORT Expression project(std::vector<Expression> values,
std::vector<std::string> names);
ARROW_EXPORT Expression equal(Expression lhs, Expression rhs);
ARROW_EXPORT Expression not_equal(Expression lhs, Expression rhs);
ARROW_EXPORT Expression less(Expression lhs, Expression rhs);
ARROW_EXPORT Expression less_equal(Expression lhs, Expression rhs);
ARROW_EXPORT Expression greater(Expression lhs, Expression rhs);
ARROW_EXPORT Expression greater_equal(Expression lhs, Expression rhs);
ARROW_EXPORT Expression is_null(Expression lhs, bool nan_is_null = false);
ARROW_EXPORT Expression is_valid(Expression lhs);
ARROW_EXPORT Expression and_(Expression lhs, Expression rhs);
ARROW_EXPORT Expression and_(const std::vector<Expression>&);
ARROW_EXPORT Expression or_(Expression lhs, Expression rhs);
ARROW_EXPORT Expression or_(const std::vector<Expression>&);
ARROW_EXPORT Expression not_(Expression operand);
/// @}
} // namespace compute
} // namespace arrow
| 36.483986 | 90 | 0.739173 | [
"shape",
"vector",
"transform"
] |
6c332ae97fa5c4a2b444fdb8e7b12cb041c26ee7 | 10,225 | h | C | deps/museum/5.0.0/art/runtime/base/logging.h | simpleton/profilo | 91ef4ba1a8316bad2b3080210316dfef4761e180 | [
"Apache-2.0"
] | null | null | null | deps/museum/5.0.0/art/runtime/base/logging.h | simpleton/profilo | 91ef4ba1a8316bad2b3080210316dfef4761e180 | [
"Apache-2.0"
] | null | null | null | deps/museum/5.0.0/art/runtime/base/logging.h | simpleton/profilo | 91ef4ba1a8316bad2b3080210316dfef4761e180 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2011 The Android Open Source Project
*
* 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.
*/
#ifndef ART_RUNTIME_BASE_LOGGING_H_
#define ART_RUNTIME_BASE_LOGGING_H_
#include <museum/5.0.0/external/libcxx/cerrno>
#include <museum/5.0.0/external/libcxx/cstring>
#include <museum/5.0.0/external/libcxx/iostream> // NOLINT
#include <museum/5.0.0/external/libcxx/memory>
#include <museum/5.0.0/external/libcxx/sstream>
#include <museum/5.0.0/bionic/libc/signal.h>
#include <museum/5.0.0/external/libcxx/vector>
#include <museum/5.0.0/art/runtime/base/macros.h>
#include <museum/5.0.0/art/runtime/log_severity.h>
#if defined(MUSEUM_NOOP_CHECK_MACROS)
#define __MUSEUM_CHECK_MAYBE_NOOP false
#else
#define __MUSEUM_CHECK_MAYBE_NOOP true
#endif
#define CHECK(x) \
if (UNLIKELY(!(x)) && __MUSEUM_CHECK_MAYBE_NOOP) \
::facebook::museum::MUSEUM_VERSION::art::LogMessage(__FILE__, __LINE__, FATAL, -1).stream() \
<< "Check failed: " #x << " "
#define CHECK_OP(LHS, RHS, OP) \
for (auto _values = ::facebook::museum::MUSEUM_VERSION::art::MakeEagerEvaluator(LHS, RHS); \
UNLIKELY(!(_values.lhs OP _values.rhs)) && __MUSEUM_CHECK_MAYBE_NOOP; /* empty */) \
::facebook::museum::MUSEUM_VERSION::art::LogMessage(__FILE__, __LINE__, FATAL, -1).stream() \
<< "Check failed: " << #LHS << " " << #OP << " " << #RHS \
<< " (" #LHS "=" << _values.lhs << ", " #RHS "=" << _values.rhs << ") "
#define CHECK_EQ(x, y) CHECK_OP(x, y, ==)
#define CHECK_NE(x, y) CHECK_OP(x, y, !=)
#define CHECK_LE(x, y) CHECK_OP(x, y, <=)
#define CHECK_LT(x, y) CHECK_OP(x, y, <)
#define CHECK_GE(x, y) CHECK_OP(x, y, >=)
#define CHECK_GT(x, y) CHECK_OP(x, y, >)
#define CHECK_STROP(s1, s2, sense) \
if (false) \
LOG(FATAL) << "Check failed: " \
<< "\"" << s1 << "\"" \
<< (sense ? " == " : " != ") \
<< "\"" << s2 << "\""
#define CHECK_STREQ(s1, s2) CHECK_STROP(s1, s2, true)
#define CHECK_STRNE(s1, s2) CHECK_STROP(s1, s2, false)
#define CHECK_PTHREAD_CALL(call, args, what) \
do { \
int rc = call args; \
if (rc != 0 && __MUSEUM_CHECK_MAYBE_NOOP) { \
errno = rc; \
PLOG(FATAL) << # call << " failed for " << what; \
} \
} while (false)
// CHECK that can be used in a constexpr function. For example,
// constexpr int half(int n) {
// return
// DCHECK_CONSTEXPR(n >= 0, , 0)
// CHECK_CONSTEXPR((n & 1) == 0), << "Extra debugging output: n = " << n, 0)
// n / 2;
// }
#define CHECK_CONSTEXPR(x, out, dummy) \
(UNLIKELY(!(x)) && __MUSEUM_CHECK_MAYBE_NOOP) ? (LOG(FATAL) << "Check failed: " << #x out, dummy) :
#ifndef NDEBUG
#define DCHECK(x) CHECK(x)
#define DCHECK_EQ(x, y) CHECK_EQ(x, y)
#define DCHECK_NE(x, y) CHECK_NE(x, y)
#define DCHECK_LE(x, y) CHECK_LE(x, y)
#define DCHECK_LT(x, y) CHECK_LT(x, y)
#define DCHECK_GE(x, y) CHECK_GE(x, y)
#define DCHECK_GT(x, y) CHECK_GT(x, y)
#define DCHECK_STREQ(s1, s2) CHECK_STREQ(s1, s2)
#define DCHECK_STRNE(s1, s2) CHECK_STRNE(s1, s2)
#define DCHECK_CONSTEXPR(x, out, dummy) CHECK_CONSTEXPR(x, out, dummy)
#else // NDEBUG
#define DCHECK(condition) \
while (false) \
CHECK(condition)
#define DCHECK_EQ(val1, val2) \
while (false) \
CHECK_EQ(val1, val2)
#define DCHECK_NE(val1, val2) \
while (false) \
CHECK_NE(val1, val2)
#define DCHECK_LE(val1, val2) \
while (false) \
CHECK_LE(val1, val2)
#define DCHECK_LT(val1, val2) \
while (false) \
CHECK_LT(val1, val2)
#define DCHECK_GE(val1, val2) \
while (false) \
CHECK_GE(val1, val2)
#define DCHECK_GT(val1, val2) \
while (false) \
CHECK_GT(val1, val2)
#define DCHECK_STREQ(str1, str2) \
while (false) \
CHECK_STREQ(str1, str2)
#define DCHECK_STRNE(str1, str2) \
while (false) \
CHECK_STRNE(str1, str2)
#define DCHECK_CONSTEXPR(x, out, dummy) \
(false && (x)) ? (dummy) :
#endif
#define LOG(severity) ::facebook::museum::MUSEUM_VERSION::art::LogMessage(__FILE__, __LINE__, severity, -1).stream()
#define PLOG(severity) ::facebook::museum::MUSEUM_VERSION::art::LogMessage(__FILE__, __LINE__, severity, errno).stream()
#define LG LOG(INFO)
#define UNIMPLEMENTED(level) LOG(level) << __PRETTY_FUNCTION__ << " unimplemented "
#define VLOG_IS_ON(module) UNLIKELY(::facebook::museum::MUSEUM_VERSION::art::gLogVerbosity.module)
#define VLOG(module) if (VLOG_IS_ON(module)) ::facebook::museum::MUSEUM_VERSION::art::LogMessage(__FILE__, __LINE__, INFO, -1).stream()
#define VLOG_STREAM(module) ::facebook::museum::MUSEUM_VERSION::art::LogMessage(__FILE__, __LINE__, INFO, -1).stream()
//
// Implementation details beyond this point.
//
namespace facebook { namespace museum { namespace MUSEUM_VERSION { namespace art {
template <typename LHS, typename RHS>
struct EagerEvaluator {
EagerEvaluator(LHS lhs, RHS rhs) : lhs(lhs), rhs(rhs) { }
LHS lhs;
RHS rhs;
};
// We want char*s to be treated as pointers, not strings. If you want them treated like strings,
// you'd need to use CHECK_STREQ and CHECK_STRNE anyway to compare the characters rather than their
// addresses. We could express this more succinctly with std::remove_const, but this is quick and
// easy to understand, and works before we have C++0x. We rely on signed/unsigned warnings to
// protect you against combinations not explicitly listed below.
#define EAGER_PTR_EVALUATOR(T1, T2) \
template <> struct EagerEvaluator<T1, T2> { \
EagerEvaluator(T1 lhs, T2 rhs) \
: lhs(reinterpret_cast<const void*>(lhs)), \
rhs(reinterpret_cast<const void*>(rhs)) { } \
const void* lhs; \
const void* rhs; \
}
EAGER_PTR_EVALUATOR(const char*, const char*);
EAGER_PTR_EVALUATOR(const char*, char*);
EAGER_PTR_EVALUATOR(char*, const char*);
EAGER_PTR_EVALUATOR(char*, char*);
EAGER_PTR_EVALUATOR(const unsigned char*, const unsigned char*);
EAGER_PTR_EVALUATOR(const unsigned char*, unsigned char*);
EAGER_PTR_EVALUATOR(unsigned char*, const unsigned char*);
EAGER_PTR_EVALUATOR(unsigned char*, unsigned char*);
EAGER_PTR_EVALUATOR(const signed char*, const signed char*);
EAGER_PTR_EVALUATOR(const signed char*, signed char*);
EAGER_PTR_EVALUATOR(signed char*, const signed char*);
EAGER_PTR_EVALUATOR(signed char*, signed char*);
template <typename LHS, typename RHS>
EagerEvaluator<LHS, RHS> MakeEagerEvaluator(LHS lhs, RHS rhs) {
return EagerEvaluator<LHS, RHS>(lhs, rhs);
}
// This indirection greatly reduces the stack impact of having
// lots of checks/logging in a function.
struct LogMessageData {
public:
LogMessageData(const char* file, int line, LogSeverity severity, int error);
std::ostringstream buffer;
const char* file;
int line_number;
LogSeverity severity;
int error;
private:
DISALLOW_COPY_AND_ASSIGN(LogMessageData);
};
class LogMessage {
public:
LogMessage(const char* file, int line, LogSeverity severity, int error)
: data_(new LogMessageData(file, line, severity, error)) {
}
~LogMessage(); // TODO: enable LOCKS_EXCLUDED(Locks::logging_lock_).
std::ostream& stream() {
return data_->buffer;
}
private:
static void LogLine(const LogMessageData& data, const char*);
const std::unique_ptr<LogMessageData> data_;
friend void HandleUnexpectedSignal(int signal_number, siginfo_t* info, void* raw_context);
friend class Mutex;
DISALLOW_COPY_AND_ASSIGN(LogMessage);
};
// A convenience to allow any class with a "Dump(std::ostream& os)" member function
// but without an operator<< to be used as if it had an operator<<. Use like this:
//
// os << Dumpable<MyType>(my_type_instance);
//
template<typename T>
class Dumpable {
public:
explicit Dumpable(T& value) : value_(value) {
}
void Dump(std::ostream& os) const {
value_.Dump(os);
}
private:
T& value_;
DISALLOW_COPY_AND_ASSIGN(Dumpable);
};
template<typename T>
std::ostream& operator<<(std::ostream& os, const Dumpable<T>& rhs) {
rhs.Dump(os);
return os;
}
template<typename T>
class ConstDumpable {
public:
explicit ConstDumpable(const T& value) : value_(value) {
}
void Dump(std::ostream& os) const {
value_.Dump(os);
}
private:
const T& value_;
DISALLOW_COPY_AND_ASSIGN(ConstDumpable);
};
template<typename T>
std::ostream& operator<<(std::ostream& os, const ConstDumpable<T>& rhs) {
rhs.Dump(os);
return os;
}
// Helps you use operator<< in a const char*-like context such as our various 'F' methods with
// format strings.
template<typename T>
class ToStr {
public:
explicit ToStr(const T& value) {
std::ostringstream os;
os << value;
s_ = os.str();
}
const char* c_str() const {
return s_.c_str();
}
const std::string& str() const {
return s_;
}
private:
std::string s_;
DISALLOW_COPY_AND_ASSIGN(ToStr);
};
// The members of this struct are the valid arguments to VLOG and VLOG_IS_ON in code,
// and the "-verbose:" command line argument.
struct LogVerbosity {
bool class_linker; // Enabled with "-verbose:class".
bool compiler;
bool gc;
bool heap;
bool jdwp;
bool jni;
bool monitor;
bool profiler;
bool signals;
bool startup;
bool third_party_jni; // Enabled with "-verbose:third-party-jni".
bool threads;
bool verifier;
};
extern LogVerbosity gLogVerbosity;
extern std::vector<std::string> gVerboseMethods;
// Used on fatal exit. Prevents recursive aborts. Allows us to disable
// some error checking to ensure fatal shutdown makes forward progress.
extern unsigned int gAborting;
extern void InitLogging(char* argv[]);
extern const char* GetCmdLine();
extern const char* ProgramInvocationName();
extern const char* ProgramInvocationShortName();
} } } } // namespace facebook::museum::MUSEUM_VERSION::art
#endif // ART_RUNTIME_BASE_LOGGING_H_
| 29.985337 | 135 | 0.69291 | [
"vector"
] |
6c38ae91d0ab0ff0498bc96ec0cfcf7a6516733f | 4,917 | h | C | public/lib/escher/third_party/granite/vk/pipeline_layout.h | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | public/lib/escher/third_party/granite/vk/pipeline_layout.h | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | public/lib/escher/third_party/granite/vk/pipeline_layout.h | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2017 Hans-Kristian Arntzen
*
* 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.
*/
// Based on the following files from the Granite rendering engine:
// - vulkan/shader.hpp
#ifndef LIB_ESCHER_THIRD_PARTY_GRANITE_VK_PIPELINE_LAYOUT_H_
#define LIB_ESCHER_THIRD_PARTY_GRANITE_VK_PIPELINE_LAYOUT_H_
#include <vulkan/vulkan.hpp>
#include "lib/escher/forward_declarations.h"
#include "lib/escher/resources/resource.h"
#include "lib/escher/third_party/granite/vk/descriptor_set_layout.h"
#include "lib/escher/util/debug_print.h"
#include "lib/escher/util/enum_count.h"
#include "lib/escher/util/hash.h"
#include "lib/escher/vk/shader_stage.h"
#include "lib/escher/vk/vulkan_limits.h"
namespace escher {
namespace impl {
// Aggregate the ShaderModuleResourceLayouts of all ShaderModules that are used
// to create a pipeline.
struct PipelineLayoutSpec {
uint32_t attribute_mask = 0;
// TODO(ES-83): document.
uint32_t render_target_mask = 0;
DescriptorSetLayout descriptor_set_layouts[VulkanLimits::kNumDescriptorSets] =
{};
vk::PushConstantRange push_constant_ranges[EnumCount<ShaderStage>()] = {};
uint32_t num_push_constant_ranges = 0;
uint32_t descriptor_set_mask = 0;
// Allows quick comparison to decide whether the push constant ranges have
// changed. If so, all descriptor sets are invalidated.
// TODO(ES-83): I remember reading why this is necessary... we should
// make note of the section of the Vulkan spec that requires this.
Hash push_constant_layout_hash = {0};
bool operator==(const PipelineLayoutSpec& other) const;
};
// TODO(ES-83): extend downward to enclose PipelineLayout. Cannot do this yet
// because there is already a PipelineLayout in impl/vk.
} // namespace impl
// A PipelineLayout encapsulates a VkPipelineLayout object, as well as an array
// of DescriptorSetAllocators that are configured to allocate descriptor sets
// that match the sets required, at each index, by pipelines with this layout.
//
// TODO(ES-83): does this need to be a Resource? If these are always
// reffed by pipelines that use them, then it should suffice to keep those
// pipelines alive, right?
class PipelineLayout : public Resource {
public:
static const ResourceTypeInfo kTypeInfo;
const ResourceTypeInfo& type_info() const override { return kTypeInfo; }
PipelineLayout(ResourceRecycler* resource_recycler,
const impl::PipelineLayoutSpec& spec);
~PipelineLayout();
vk::PipelineLayout vk() const { return pipeline_layout_; }
const impl::PipelineLayoutSpec& spec() const { return spec_; }
impl::DescriptorSetAllocator* GetDescriptorSetAllocator(
unsigned set_index) const {
FXL_DCHECK(set_index < VulkanLimits::kNumDescriptorSets);
return descriptor_set_allocators_[set_index];
}
private:
vk::PipelineLayout pipeline_layout_;
impl::PipelineLayoutSpec spec_;
impl::DescriptorSetAllocator*
descriptor_set_allocators_[VulkanLimits::kNumDescriptorSets] = {};
};
using PipelineLayoutPtr = fxl::RefPtr<PipelineLayout>;
// Inline function definitions.
inline bool impl::PipelineLayoutSpec::operator==(
const impl::PipelineLayoutSpec& other) const {
return attribute_mask == other.attribute_mask &&
render_target_mask == other.render_target_mask &&
descriptor_set_mask == other.descriptor_set_mask &&
push_constant_layout_hash == other.push_constant_layout_hash &&
num_push_constant_ranges == other.num_push_constant_ranges &&
0 == memcmp(descriptor_set_layouts, other.descriptor_set_layouts,
sizeof(descriptor_set_layouts)) &&
0 == memcmp(push_constant_ranges, other.push_constant_ranges,
sizeof(push_constant_ranges));
}
ESCHER_DEBUG_PRINTABLE(impl::PipelineLayoutSpec);
} // namespace escher
#endif // LIB_ESCHER_THIRD_PARTY_GRANITE_VK_PIPELINE_LAYOUT_H_
| 39.97561 | 80 | 0.759813 | [
"object"
] |
6c3bb368ec027299f3af001594bcf1d67864bd08 | 22,313 | c | C | lib/ffmpeg/jni/ffmpeg/libavcodec/imgconvert.c | adachigit/BlueFrog-Cocos2dx | fcf44c0e427aebc6a353a2fa1b89df588c2bbb79 | [
"MIT"
] | null | null | null | lib/ffmpeg/jni/ffmpeg/libavcodec/imgconvert.c | adachigit/BlueFrog-Cocos2dx | fcf44c0e427aebc6a353a2fa1b89df588c2bbb79 | [
"MIT"
] | null | null | null | lib/ffmpeg/jni/ffmpeg/libavcodec/imgconvert.c | adachigit/BlueFrog-Cocos2dx | fcf44c0e427aebc6a353a2fa1b89df588c2bbb79 | [
"MIT"
] | null | null | null | /*
* Misc image conversion routines
* Copyright (c) 2001, 2002, 2003 Fabrice Bellard
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* misc image conversion routines
*/
/* TODO:
* - write 'ffimg' program to test all the image related stuff
* - move all api to slice based system
* - integrate deinterlacing, postprocessing and scaling in the conversion process
*/
#include "avcodec.h"
#include "dsputil.h"
#include "imgconvert.h"
#include "internal.h"
#include "libavutil/avassert.h"
#include "libavutil/colorspace.h"
#include "libavutil/common.h"
#include "libavutil/pixdesc.h"
#include "libavutil/imgutils.h"
#if HAVE_MMX_EXTERNAL
#include "x86/dsputil_mmx.h"
#endif
#define FF_COLOR_NA -1
#define FF_COLOR_RGB 0 /**< RGB color space */
#define FF_COLOR_GRAY 1 /**< gray color space */
#define FF_COLOR_YUV 2 /**< YUV color space. 16 <= Y <= 235, 16 <= U, V <= 240 */
#define FF_COLOR_YUV_JPEG 3 /**< YUV color space. 0 <= Y <= 255, 0 <= U, V <= 255 */
#if HAVE_MMX_EXTERNAL
#define deinterlace_line_inplace ff_deinterlace_line_inplace_mmx
#define deinterlace_line ff_deinterlace_line_mmx
#else
#define deinterlace_line_inplace deinterlace_line_inplace_c
#define deinterlace_line deinterlace_line_c
#endif
#define pixdesc_has_alpha(pixdesc) \
((pixdesc)->nb_components == 2 || (pixdesc)->nb_components == 4 || (pixdesc)->flags & PIX_FMT_PAL)
void avcodec_get_chroma_sub_sample(enum AVPixelFormat pix_fmt, int *h_shift, int *v_shift)
{
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
av_assert0(desc);
*h_shift = desc->log2_chroma_w;
*v_shift = desc->log2_chroma_h;
}
static int get_color_type(const AVPixFmtDescriptor *desc) {
if(desc->nb_components == 1 || desc->nb_components == 2)
return FF_COLOR_GRAY;
if(desc->name && !strncmp(desc->name, "yuvj", 4))
return FF_COLOR_YUV_JPEG;
if(desc->flags & PIX_FMT_RGB)
return FF_COLOR_RGB;
if(desc->nb_components == 0)
return FF_COLOR_NA;
return FF_COLOR_YUV;
}
static int get_pix_fmt_depth(int *min, int *max, enum AVPixelFormat pix_fmt)
{
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
int i;
if (!desc || !desc->nb_components) {
*min = *max = 0;
return AVERROR(EINVAL);
}
*min = INT_MAX, *max = -INT_MAX;
for (i = 0; i < desc->nb_components; i++) {
*min = FFMIN(desc->comp[i].depth_minus1+1, *min);
*max = FFMAX(desc->comp[i].depth_minus1+1, *max);
}
return 0;
}
static int get_pix_fmt_score(enum AVPixelFormat dst_pix_fmt,
enum AVPixelFormat src_pix_fmt,
unsigned *lossp, unsigned consider)
{
const AVPixFmtDescriptor *src_desc = av_pix_fmt_desc_get(src_pix_fmt);
const AVPixFmtDescriptor *dst_desc = av_pix_fmt_desc_get(dst_pix_fmt);
int src_color, dst_color;
int src_min_depth, src_max_depth, dst_min_depth, dst_max_depth;
int ret, loss, i, nb_components;
int score = INT_MAX;
if (dst_pix_fmt >= AV_PIX_FMT_NB || dst_pix_fmt <= AV_PIX_FMT_NONE)
return ~0;
/* compute loss */
*lossp = loss = 0;
if (dst_pix_fmt == src_pix_fmt)
return INT_MAX;
if ((ret = get_pix_fmt_depth(&src_min_depth, &src_max_depth, src_pix_fmt)) < 0)
return ret;
if ((ret = get_pix_fmt_depth(&dst_min_depth, &dst_max_depth, dst_pix_fmt)) < 0)
return ret;
src_color = get_color_type(src_desc);
dst_color = get_color_type(dst_desc);
nb_components = FFMIN(src_desc->nb_components, dst_desc->nb_components);
for (i = 0; i < nb_components; i++)
if (src_desc->comp[i].depth_minus1 > dst_desc->comp[i].depth_minus1 && (consider & FF_LOSS_DEPTH)) {
loss |= FF_LOSS_DEPTH;
score -= 65536 >> dst_desc->comp[i].depth_minus1;
}
if (consider & FF_LOSS_RESOLUTION) {
if (dst_desc->log2_chroma_w > src_desc->log2_chroma_w) {
loss |= FF_LOSS_RESOLUTION;
score -= 256 << dst_desc->log2_chroma_w;
}
if (dst_desc->log2_chroma_h > src_desc->log2_chroma_h) {
loss |= FF_LOSS_RESOLUTION;
score -= 256 << dst_desc->log2_chroma_h;
}
// dont favor 422 over 420 if downsampling is needed, because 420 has much better support on the decoder side
if (dst_desc->log2_chroma_w == 1 && src_desc->log2_chroma_w == 0 &&
dst_desc->log2_chroma_h == 1 && src_desc->log2_chroma_h == 0 ) {
score += 512;
}
}
if(consider & FF_LOSS_COLORSPACE)
switch(dst_color) {
case FF_COLOR_RGB:
if (src_color != FF_COLOR_RGB &&
src_color != FF_COLOR_GRAY)
loss |= FF_LOSS_COLORSPACE;
break;
case FF_COLOR_GRAY:
if (src_color != FF_COLOR_GRAY)
loss |= FF_LOSS_COLORSPACE;
break;
case FF_COLOR_YUV:
if (src_color != FF_COLOR_YUV)
loss |= FF_LOSS_COLORSPACE;
break;
case FF_COLOR_YUV_JPEG:
if (src_color != FF_COLOR_YUV_JPEG &&
src_color != FF_COLOR_YUV &&
src_color != FF_COLOR_GRAY)
loss |= FF_LOSS_COLORSPACE;
break;
default:
/* fail safe test */
if (src_color != dst_color)
loss |= FF_LOSS_COLORSPACE;
break;
}
if(loss & FF_LOSS_COLORSPACE)
score -= (nb_components * 65536) >> FFMIN(dst_desc->comp[0].depth_minus1, src_desc->comp[0].depth_minus1);
if (dst_color == FF_COLOR_GRAY &&
src_color != FF_COLOR_GRAY && (consider & FF_LOSS_CHROMA)) {
loss |= FF_LOSS_CHROMA;
score -= 2 * 65536;
}
if (!pixdesc_has_alpha(dst_desc) && (pixdesc_has_alpha(src_desc) && (consider & FF_LOSS_ALPHA))) {
loss |= FF_LOSS_ALPHA;
score -= 65536;
}
if (dst_pix_fmt == AV_PIX_FMT_PAL8 && (consider & FF_LOSS_COLORQUANT) &&
(src_pix_fmt != AV_PIX_FMT_PAL8 && (src_color != FF_COLOR_GRAY || (pixdesc_has_alpha(src_desc) && (consider & FF_LOSS_ALPHA))))) {
loss |= FF_LOSS_COLORQUANT;
score -= 65536;
}
*lossp = loss;
return score;
}
int avcodec_get_pix_fmt_loss(enum AVPixelFormat dst_pix_fmt,
enum AVPixelFormat src_pix_fmt,
int has_alpha)
{
int loss;
int ret = get_pix_fmt_score(dst_pix_fmt, src_pix_fmt, &loss, has_alpha ? ~0 : ~FF_LOSS_ALPHA);
if (ret < 0)
return ret;
return loss;
}
#if FF_API_FIND_BEST_PIX_FMT
enum AVPixelFormat avcodec_find_best_pix_fmt(int64_t pix_fmt_mask, enum AVPixelFormat src_pix_fmt,
int has_alpha, int *loss_ptr)
{
enum AVPixelFormat dst_pix_fmt;
int i;
if (loss_ptr) /* all losses count (for backward compatibility) */
*loss_ptr = 0;
dst_pix_fmt = AV_PIX_FMT_NONE; /* so first iteration doesn't have to be treated special */
for(i = 0; i< FFMIN(AV_PIX_FMT_NB, 64); i++){
if (pix_fmt_mask & (1ULL << i))
dst_pix_fmt = avcodec_find_best_pix_fmt_of_2(dst_pix_fmt, i, src_pix_fmt, has_alpha, loss_ptr);
}
return dst_pix_fmt;
}
#endif /* FF_API_FIND_BEST_PIX_FMT */
enum AVPixelFormat avcodec_find_best_pix_fmt_of_2(enum AVPixelFormat dst_pix_fmt1, enum AVPixelFormat dst_pix_fmt2,
enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr)
{
enum AVPixelFormat dst_pix_fmt;
int loss1, loss2, loss_mask;
const AVPixFmtDescriptor *desc1 = av_pix_fmt_desc_get(dst_pix_fmt1);
const AVPixFmtDescriptor *desc2 = av_pix_fmt_desc_get(dst_pix_fmt2);
int score1, score2;
loss_mask= loss_ptr?~*loss_ptr:~0; /* use loss mask if provided */
if(!has_alpha)
loss_mask &= ~FF_LOSS_ALPHA;
dst_pix_fmt = AV_PIX_FMT_NONE;
score1 = get_pix_fmt_score(dst_pix_fmt1, src_pix_fmt, &loss1, loss_mask);
score2 = get_pix_fmt_score(dst_pix_fmt2, src_pix_fmt, &loss2, loss_mask);
if (score1 == score2) {
if(av_get_padded_bits_per_pixel(desc2) != av_get_padded_bits_per_pixel(desc1)) {
dst_pix_fmt = av_get_padded_bits_per_pixel(desc2) < av_get_padded_bits_per_pixel(desc1) ? dst_pix_fmt2 : dst_pix_fmt1;
} else {
dst_pix_fmt = desc2->nb_components < desc1->nb_components ? dst_pix_fmt2 : dst_pix_fmt1;
}
} else {
dst_pix_fmt = score1 < score2 ? dst_pix_fmt2 : dst_pix_fmt1;
}
if (loss_ptr)
*loss_ptr = avcodec_get_pix_fmt_loss(dst_pix_fmt, src_pix_fmt, has_alpha);
return dst_pix_fmt;
}
#if AV_HAVE_INCOMPATIBLE_FORK_ABI
enum AVPixelFormat avcodec_find_best_pix_fmt2(enum AVPixelFormat *pix_fmt_list,
enum AVPixelFormat src_pix_fmt,
int has_alpha, int *loss_ptr){
return avcodec_find_best_pix_fmt_of_list(pix_fmt_list, src_pix_fmt, has_alpha, loss_ptr);
}
#else
enum AVPixelFormat avcodec_find_best_pix_fmt2(enum AVPixelFormat dst_pix_fmt1, enum AVPixelFormat dst_pix_fmt2,
enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr)
{
return avcodec_find_best_pix_fmt_of_2(dst_pix_fmt1, dst_pix_fmt2, src_pix_fmt, has_alpha, loss_ptr);
}
#endif
enum AVPixelFormat avcodec_find_best_pix_fmt_of_list(enum AVPixelFormat *pix_fmt_list,
enum AVPixelFormat src_pix_fmt,
int has_alpha, int *loss_ptr){
int i;
enum AVPixelFormat best = AV_PIX_FMT_NONE;
for(i=0; pix_fmt_list[i] != AV_PIX_FMT_NONE; i++)
best = avcodec_find_best_pix_fmt_of_2(best, pix_fmt_list[i], src_pix_fmt, has_alpha, loss_ptr);
return best;
}
/* 2x2 -> 1x1 */
void ff_shrink22(uint8_t *dst, int dst_wrap,
const uint8_t *src, int src_wrap,
int width, int height)
{
int w;
const uint8_t *s1, *s2;
uint8_t *d;
for(;height > 0; height--) {
s1 = src;
s2 = s1 + src_wrap;
d = dst;
for(w = width;w >= 4; w-=4) {
d[0] = (s1[0] + s1[1] + s2[0] + s2[1] + 2) >> 2;
d[1] = (s1[2] + s1[3] + s2[2] + s2[3] + 2) >> 2;
d[2] = (s1[4] + s1[5] + s2[4] + s2[5] + 2) >> 2;
d[3] = (s1[6] + s1[7] + s2[6] + s2[7] + 2) >> 2;
s1 += 8;
s2 += 8;
d += 4;
}
for(;w > 0; w--) {
d[0] = (s1[0] + s1[1] + s2[0] + s2[1] + 2) >> 2;
s1 += 2;
s2 += 2;
d++;
}
src += 2 * src_wrap;
dst += dst_wrap;
}
}
/* 4x4 -> 1x1 */
void ff_shrink44(uint8_t *dst, int dst_wrap,
const uint8_t *src, int src_wrap,
int width, int height)
{
int w;
const uint8_t *s1, *s2, *s3, *s4;
uint8_t *d;
for(;height > 0; height--) {
s1 = src;
s2 = s1 + src_wrap;
s3 = s2 + src_wrap;
s4 = s3 + src_wrap;
d = dst;
for(w = width;w > 0; w--) {
d[0] = (s1[0] + s1[1] + s1[2] + s1[3] +
s2[0] + s2[1] + s2[2] + s2[3] +
s3[0] + s3[1] + s3[2] + s3[3] +
s4[0] + s4[1] + s4[2] + s4[3] + 8) >> 4;
s1 += 4;
s2 += 4;
s3 += 4;
s4 += 4;
d++;
}
src += 4 * src_wrap;
dst += dst_wrap;
}
}
/* 8x8 -> 1x1 */
void ff_shrink88(uint8_t *dst, int dst_wrap,
const uint8_t *src, int src_wrap,
int width, int height)
{
int w, i;
for(;height > 0; height--) {
for(w = width;w > 0; w--) {
int tmp=0;
for(i=0; i<8; i++){
tmp += src[0] + src[1] + src[2] + src[3] + src[4] + src[5] + src[6] + src[7];
src += src_wrap;
}
*(dst++) = (tmp + 32)>>6;
src += 8 - 8*src_wrap;
}
src += 8*src_wrap - 8*width;
dst += dst_wrap - width;
}
}
/* return true if yuv planar */
static inline int is_yuv_planar(const AVPixFmtDescriptor *desc)
{
int i;
int planes[4] = { 0 };
if ( desc->flags & PIX_FMT_RGB
|| !(desc->flags & PIX_FMT_PLANAR))
return 0;
/* set the used planes */
for (i = 0; i < desc->nb_components; i++)
planes[desc->comp[i].plane] = 1;
/* if there is an unused plane, the format is not planar */
for (i = 0; i < desc->nb_components; i++)
if (!planes[i])
return 0;
return 1;
}
int av_picture_crop(AVPicture *dst, const AVPicture *src,
enum AVPixelFormat pix_fmt, int top_band, int left_band)
{
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
int y_shift;
int x_shift;
if (pix_fmt < 0 || pix_fmt >= AV_PIX_FMT_NB)
return -1;
y_shift = desc->log2_chroma_h;
x_shift = desc->log2_chroma_w;
if (is_yuv_planar(desc)) {
dst->data[0] = src->data[0] + (top_band * src->linesize[0]) + left_band;
dst->data[1] = src->data[1] + ((top_band >> y_shift) * src->linesize[1]) + (left_band >> x_shift);
dst->data[2] = src->data[2] + ((top_band >> y_shift) * src->linesize[2]) + (left_band >> x_shift);
} else{
if(top_band % (1<<y_shift) || left_band % (1<<x_shift))
return -1;
if(left_band) //FIXME add support for this too
return -1;
dst->data[0] = src->data[0] + (top_band * src->linesize[0]) + left_band;
}
dst->linesize[0] = src->linesize[0];
dst->linesize[1] = src->linesize[1];
dst->linesize[2] = src->linesize[2];
return 0;
}
int av_picture_pad(AVPicture *dst, const AVPicture *src, int height, int width,
enum AVPixelFormat pix_fmt, int padtop, int padbottom, int padleft, int padright,
int *color)
{
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
uint8_t *optr;
int y_shift;
int x_shift;
int yheight;
int i, y;
if (pix_fmt < 0 || pix_fmt >= AV_PIX_FMT_NB ||
!is_yuv_planar(desc)) return -1;
for (i = 0; i < 3; i++) {
x_shift = i ? desc->log2_chroma_w : 0;
y_shift = i ? desc->log2_chroma_h : 0;
if (padtop || padleft) {
memset(dst->data[i], color[i],
dst->linesize[i] * (padtop >> y_shift) + (padleft >> x_shift));
}
if (padleft || padright) {
optr = dst->data[i] + dst->linesize[i] * (padtop >> y_shift) +
(dst->linesize[i] - (padright >> x_shift));
yheight = (height - 1 - (padtop + padbottom)) >> y_shift;
for (y = 0; y < yheight; y++) {
memset(optr, color[i], (padleft + padright) >> x_shift);
optr += dst->linesize[i];
}
}
if (src) { /* first line */
uint8_t *iptr = src->data[i];
optr = dst->data[i] + dst->linesize[i] * (padtop >> y_shift) +
(padleft >> x_shift);
memcpy(optr, iptr, (width - padleft - padright) >> x_shift);
iptr += src->linesize[i];
optr = dst->data[i] + dst->linesize[i] * (padtop >> y_shift) +
(dst->linesize[i] - (padright >> x_shift));
yheight = (height - 1 - (padtop + padbottom)) >> y_shift;
for (y = 0; y < yheight; y++) {
memset(optr, color[i], (padleft + padright) >> x_shift);
memcpy(optr + ((padleft + padright) >> x_shift), iptr,
(width - padleft - padright) >> x_shift);
iptr += src->linesize[i];
optr += dst->linesize[i];
}
}
if (padbottom || padright) {
optr = dst->data[i] + dst->linesize[i] *
((height - padbottom) >> y_shift) - (padright >> x_shift);
memset(optr, color[i],dst->linesize[i] *
(padbottom >> y_shift) + (padright >> x_shift));
}
}
return 0;
}
#if FF_API_DEINTERLACE
#if !HAVE_MMX_EXTERNAL
/* filter parameters: [-1 4 2 4 -1] // 8 */
static void deinterlace_line_c(uint8_t *dst,
const uint8_t *lum_m4, const uint8_t *lum_m3,
const uint8_t *lum_m2, const uint8_t *lum_m1,
const uint8_t *lum,
int size)
{
uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
int sum;
for(;size > 0;size--) {
sum = -lum_m4[0];
sum += lum_m3[0] << 2;
sum += lum_m2[0] << 1;
sum += lum_m1[0] << 2;
sum += -lum[0];
dst[0] = cm[(sum + 4) >> 3];
lum_m4++;
lum_m3++;
lum_m2++;
lum_m1++;
lum++;
dst++;
}
}
static void deinterlace_line_inplace_c(uint8_t *lum_m4, uint8_t *lum_m3,
uint8_t *lum_m2, uint8_t *lum_m1,
uint8_t *lum, int size)
{
uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
int sum;
for(;size > 0;size--) {
sum = -lum_m4[0];
sum += lum_m3[0] << 2;
sum += lum_m2[0] << 1;
lum_m4[0]=lum_m2[0];
sum += lum_m1[0] << 2;
sum += -lum[0];
lum_m2[0] = cm[(sum + 4) >> 3];
lum_m4++;
lum_m3++;
lum_m2++;
lum_m1++;
lum++;
}
}
#endif /* !HAVE_MMX_EXTERNAL */
/* deinterlacing : 2 temporal taps, 3 spatial taps linear filter. The
top field is copied as is, but the bottom field is deinterlaced
against the top field. */
static void deinterlace_bottom_field(uint8_t *dst, int dst_wrap,
const uint8_t *src1, int src_wrap,
int width, int height)
{
const uint8_t *src_m2, *src_m1, *src_0, *src_p1, *src_p2;
int y;
src_m2 = src1;
src_m1 = src1;
src_0=&src_m1[src_wrap];
src_p1=&src_0[src_wrap];
src_p2=&src_p1[src_wrap];
for(y=0;y<(height-2);y+=2) {
memcpy(dst,src_m1,width);
dst += dst_wrap;
deinterlace_line(dst,src_m2,src_m1,src_0,src_p1,src_p2,width);
src_m2 = src_0;
src_m1 = src_p1;
src_0 = src_p2;
src_p1 += 2*src_wrap;
src_p2 += 2*src_wrap;
dst += dst_wrap;
}
memcpy(dst,src_m1,width);
dst += dst_wrap;
/* do last line */
deinterlace_line(dst,src_m2,src_m1,src_0,src_0,src_0,width);
}
static void deinterlace_bottom_field_inplace(uint8_t *src1, int src_wrap,
int width, int height)
{
uint8_t *src_m1, *src_0, *src_p1, *src_p2;
int y;
uint8_t *buf;
buf = av_malloc(width);
src_m1 = src1;
memcpy(buf,src_m1,width);
src_0=&src_m1[src_wrap];
src_p1=&src_0[src_wrap];
src_p2=&src_p1[src_wrap];
for(y=0;y<(height-2);y+=2) {
deinterlace_line_inplace(buf,src_m1,src_0,src_p1,src_p2,width);
src_m1 = src_p1;
src_0 = src_p2;
src_p1 += 2*src_wrap;
src_p2 += 2*src_wrap;
}
/* do last line */
deinterlace_line_inplace(buf,src_m1,src_0,src_0,src_0,width);
av_free(buf);
}
int avpicture_deinterlace(AVPicture *dst, const AVPicture *src,
enum AVPixelFormat pix_fmt, int width, int height)
{
int i;
if (pix_fmt != AV_PIX_FMT_YUV420P &&
pix_fmt != AV_PIX_FMT_YUVJ420P &&
pix_fmt != AV_PIX_FMT_YUV422P &&
pix_fmt != AV_PIX_FMT_YUVJ422P &&
pix_fmt != AV_PIX_FMT_YUV444P &&
pix_fmt != AV_PIX_FMT_YUV411P &&
pix_fmt != AV_PIX_FMT_GRAY8)
return -1;
if ((width & 3) != 0 || (height & 3) != 0)
return -1;
for(i=0;i<3;i++) {
if (i == 1) {
switch(pix_fmt) {
case AV_PIX_FMT_YUVJ420P:
case AV_PIX_FMT_YUV420P:
width >>= 1;
height >>= 1;
break;
case AV_PIX_FMT_YUV422P:
case AV_PIX_FMT_YUVJ422P:
width >>= 1;
break;
case AV_PIX_FMT_YUV411P:
width >>= 2;
break;
default:
break;
}
if (pix_fmt == AV_PIX_FMT_GRAY8) {
break;
}
}
if (src == dst) {
deinterlace_bottom_field_inplace(dst->data[i], dst->linesize[i],
width, height);
} else {
deinterlace_bottom_field(dst->data[i],dst->linesize[i],
src->data[i], src->linesize[i],
width, height);
}
}
emms_c();
return 0;
}
#endif /* FF_API_DEINTERLACE */
#ifdef TEST
int main(void){
int i;
int err=0;
int skip = 0;
for (i=0; i<AV_PIX_FMT_NB*2; i++) {
AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(i);
if(!desc || !desc->name) {
skip ++;
continue;
}
if (skip) {
av_log(NULL, AV_LOG_INFO, "%3d unused pixel format values\n", skip);
skip = 0;
}
av_log(NULL, AV_LOG_INFO, "pix fmt %s yuv_plan:%d avg_bpp:%d colortype:%d\n", desc->name, is_yuv_planar(desc), av_get_padded_bits_per_pixel(desc), get_color_type(desc));
if ((!(desc->flags & PIX_FMT_ALPHA)) != (desc->nb_components != 2 && desc->nb_components != 4)) {
av_log(NULL, AV_LOG_ERROR, "Alpha flag mismatch\n");
err = 1;
}
}
return err;
}
#endif
| 32.573723 | 177 | 0.564245 | [
"3d"
] |
6c468bfeeffa5b7b32d411c104a3cad2dc893ad9 | 12,161 | h | C | core/vm/arch/posix/posix.h | objeck/objeck-lang | 6d641f80abc1a3443fc156274337d07af1b0c251 | [
"Zlib",
"OpenSSL"
] | 73 | 2015-02-26T22:30:47.000Z | 2022-03-06T22:42:02.000Z | core/vm/arch/posix/posix.h | objeck/objeck-lang | 6d641f80abc1a3443fc156274337d07af1b0c251 | [
"Zlib",
"OpenSSL"
] | 50 | 2015-03-01T22:13:17.000Z | 2022-03-17T16:24:17.000Z | core/vm/arch/posix/posix.h | objeck/objeck-lang | 6d641f80abc1a3443fc156274337d07af1b0c251 | [
"Zlib",
"OpenSSL"
] | 4 | 2015-10-22T20:44:47.000Z | 2022-02-12T03:35:54.000Z | /***************************************************************************
* Provides runtime support for POSIX compliant systems i.e
* Linux, OS X, etc.
*
* Copyright (c) 2008-2013, Randy Hollines
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
* - Neither the name of the Objeck Team nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
#ifndef __POSIX_H__
#define __POSIX_H__
#include "../../common.h"
#include <sys/utsname.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <pwd.h>
#include <grp.h>
#define SOCKET int
/****************************
* File support class
****************************/
class File {
public:
static string FullPathName(const string name) {
char buffer[PATH_MAX] = "";
if(!realpath(name.c_str(), buffer)) {
return "";
}
return buffer;
}
static long FileSize(const char* name) {
struct stat buf;
if(stat(name, &buf)) {
return -1;
}
return buf.st_size;
}
static string TempName() {
char buffer[] = "/tmp/objeck-XXXXXX";
if(mkstemp(buffer) < 0) {
return "";
}
return buffer;
}
static bool FileExists(const char* name) {
struct stat buf;
if(stat(name, &buf)) {
return false;
}
return S_IFREG & buf.st_mode;
}
static bool FileReadOnly(const char* name) {
if(!access(name, R_OK) && access(name, W_OK) == EACCES) {
return true;
}
return false;
}
static bool FileWriteOnly(const char* name) {
if(!access(name, W_OK) && access(name, R_OK) == EACCES) {
return true;
}
return false;
}
static bool FileReadWrite(const char* name) {
if (!access(name, W_OK) && !access(name, R_OK)) {
return true;
}
return false;
}
static time_t FileCreatedTime(const char* name) {
struct stat buf;
if(stat(name, &buf)) {
return -1;
}
return buf.st_ctime;
}
static time_t FileModifiedTime(const char* name) {
struct stat buf;
if(stat(name, &buf)) {
return -1;
}
return buf.st_mtime;
}
static time_t FileAccessedTime(const char* name) {
struct stat buf;
if(stat(name, &buf)) {
return -1;
}
return buf.st_atime;
}
static FILE* FileOpen(const char* name, const char* mode) {
return fopen(name, mode);
}
static wstring FileOwner(const char* name, bool is_account) {
struct stat info;
if(stat(name, &info)) {
return L"";
}
if(is_account) {
struct passwd* account = getpwuid(info.st_uid);
return BytesToUnicode(account->pw_name);
}
struct group * group = getgrgid(info.st_gid);
return BytesToUnicode(group->gr_name);
}
static bool MakeDir(const char* name) {
if(mkdir(name, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0) {
return false;
}
return true;
}
static bool DirExists(const char* name) {
struct stat buf;
if(stat(name, &buf)) {
return false;
}
return S_IFDIR & buf.st_mode;
}
static vector<string> ListDir(const char* path) {
vector<string> files;
struct dirent** names;
int n = scandir(path, &names, 0, alphasort);
if(n > 0) {
while(n--) {
if((strcmp(names[n]->d_name, "..") != 0) && (strcmp(names[n]->d_name, ".") != 0)) {
files.push_back(names[n]->d_name);
}
free(names[n]);
}
free(names);
}
return files;
}
};
/****************************
* IP socket support class
****************************/
class IPSocket {
public:
static vector<string> Resolve(const char* address) {
vector<string> addresses;
struct addrinfo* result;
if(getaddrinfo(address, nullptr, nullptr, &result)) {
freeaddrinfo(result);
return vector<string>();
}
struct addrinfo* res;
for(res = result; res != nullptr; res = res->ai_next) {
char hostname[NI_MAXHOST] = { 0 };
if(getnameinfo(res->ai_addr, (socklen_t)res->ai_addrlen, hostname, NI_MAXHOST, nullptr, 0, 0)) {
freeaddrinfo(result);
return vector<string>();
}
if(*hostname != '\0') {
addresses.push_back(hostname);
}
}
freeaddrinfo(result);
return addresses;
}
static SOCKET Open(const char* address, int port) {
addrinfo* addr;
if(getaddrinfo(address, nullptr, nullptr, &addr)) {
freeaddrinfo(addr);
return -1;
}
SOCKET sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
if(sock < 0) {
freeaddrinfo(addr);
close(sock);
return -1;
}
sockaddr_in pin;
memset(&pin, 0, sizeof(pin));
pin.sin_family = addr->ai_family;
pin.sin_addr.s_addr = *((uint32_t*)&(((sockaddr_in*)addr->ai_addr)->sin_addr));
pin.sin_port = htons(port);
if(connect(sock, (struct sockaddr*)&pin, sizeof(pin)) < 0) {
freeaddrinfo(addr);
close(sock);
return -1;
}
freeaddrinfo(addr);
return sock;
}
static SOCKET Bind(int port) {
SOCKET server = socket(AF_INET, SOCK_STREAM, 0);
if(server < 0) {
return -1;
}
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(port);
if(::bind(server, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
close(server);
return -1;
}
return server;
}
static bool Listen(SOCKET server, int backlog) {
if(listen(server, backlog) < 0) {
return false;
}
return true;
}
static SOCKET Accept(SOCKET server, char* client_address, int &client_port) {
struct sockaddr_in pin;
socklen_t addrlen = sizeof(pin);
SOCKET client = accept(server, (struct sockaddr*)&pin, &addrlen);
if(client < 0) {
client_address[0] = '\0';
client_port = -1;
return -1;
}
char buffer[INET_ADDRSTRLEN] = { 0 };
inet_ntop(AF_INET, &(pin.sin_addr), buffer, INET_ADDRSTRLEN);
strncpy(client_address, buffer, INET_ADDRSTRLEN);
client_port = ntohs(pin.sin_port);
return client;
}
static int WriteByte(const char value, SOCKET sock) {
return send(sock, &value, 1, 0);
}
static int WriteBytes(const char* values, int len, SOCKET sock) {
return send(sock, values, len, 0);
}
static char ReadByte(SOCKET sock, int &status) {
char value;
status = recv(sock, &value, 1, 0);
if(status < 0) {
return '\0';
}
return value;
}
static int ReadBytes(char* values, int len, SOCKET sock) {
return recv(sock, values, len, 0);
}
static void Close(SOCKET sock) {
close(sock);
}
};
/****************************
* IP socket support class
****************************/
class IPSecureSocket {
public:
static bool Open(const char* address, int port, SSL_CTX* &ctx, BIO* &bio, X509* &cert) {
ctx = SSL_CTX_new(SSLv23_client_method());
bio = BIO_new_ssl_connect(ctx);
if(!bio) {
SSL_CTX_free(ctx);
return false;
}
wstring path = GetLibraryPath();
string cert_path(path.begin(), path.end());
cert_path += CACERT_PEM_FILE;
if(!SSL_CTX_load_verify_locations(ctx, cert_path.c_str(), NULL)) {
BIO_free_all(bio);
SSL_CTX_free(ctx);
return false;
}
SSL* ssl;
BIO_get_ssl(bio, &ssl);
SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
string ssl_address = address;
if(ssl_address.size() < 1 || port < 0) {
BIO_free_all(bio);
SSL_CTX_free(ctx);
return false;
}
ssl_address += ":";
ssl_address += UnicodeToBytes(IntToString(port));
BIO_set_conn_hostname(bio, ssl_address.c_str());
if(!SSL_set_tlsext_host_name(ssl, address)) {
BIO_free_all(bio);
SSL_CTX_free(ctx);
return false;
}
if(BIO_do_connect(bio) <= 0) {
BIO_free_all(bio);
SSL_CTX_free(ctx);
return false;
}
if(BIO_do_handshake(bio) <= 0) {
BIO_free_all(bio);
SSL_CTX_free(ctx);
return false;
}
cert = SSL_get_peer_certificate(ssl);
if(!cert) {
BIO_free_all(bio);
SSL_CTX_free(ctx);
return false;
}
const int status = SSL_get_verify_result(ssl);
if(status != X509_V_OK && status != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) {
BIO_free_all(bio);
SSL_CTX_free(ctx);
X509_free(cert);
return false;
}
return true;
}
static void WriteByte(char value, SSL_CTX* ctx, BIO* bio) {
int status = BIO_write(bio, &value, 1);
if(status < 0) {
value = '\0';
}
}
static int WriteBytes(const char* values, int len, SSL_CTX* ctx, BIO* bio) {
int status = BIO_write(bio, values, len);
if(status < 0) {
return -1;
}
return BIO_flush(bio);
}
static char ReadByte(SSL_CTX* ctx, BIO* bio, int &status) {
char value;
status = BIO_read(bio, &value, 1);
if(status < 0) {
return '\0';
}
return value;
}
static int ReadBytes(char* values, int len, SSL_CTX* ctx, BIO* bio) {
int status = BIO_read(bio, values, len);
if(status < 0) {
return -1;
}
return status;
}
static void Close(SSL_CTX* ctx, BIO* bio, X509* cert) {
if(bio) {
BIO_free_all(bio);
}
if(ctx) {
SSL_CTX_free(ctx);
}
if(cert) {
X509_free(cert);
}
}
};
/****************************
* System operations
****************************/
class System {
public:
static vector<string> CommandOutput(const char* c) {
vector<string> output;
// create temporary file
const string tmp_file_name = File::TempName();
FILE* file = File::FileOpen(tmp_file_name.c_str(), "wb");
if(file) {
fclose(file);
string str_cmd(c);
str_cmd += " > ";
str_cmd += tmp_file_name;
// ignoring return value
system(str_cmd.c_str());
// read file output
ifstream file_out(tmp_file_name.c_str());
if(file_out.is_open()) {
string line_out;
while(getline(file_out, line_out)) {
output.push_back(line_out);
}
file_out.close();
// delete file
remove(tmp_file_name.c_str());
}
}
return output;
}
static string GetPlatform() {
string platform;
struct utsname uts;
if(uname(&uts) < 0) {
platform = "Unknown";
}
else {
platform += uts.sysname;
platform += " ";
platform += uts.release;
platform += ", ";
platform += uts.machine;
}
return platform;
}
};
#endif
| 23.613592 | 99 | 0.595921 | [
"vector"
] |
6c49074b6b9d0801fb7902771f748324ecdfada9 | 2,944 | h | C | stl_algos/rotate.h | zcoderz/cppLanguageFeatures | 5881b0e87184162197406c427c1e986b4f3d07dd | [
"BSD-3-Clause"
] | null | null | null | stl_algos/rotate.h | zcoderz/cppLanguageFeatures | 5881b0e87184162197406c427c1e986b4f3d07dd | [
"BSD-3-Clause"
] | null | null | null | stl_algos/rotate.h | zcoderz/cppLanguageFeatures | 5881b0e87184162197406c427c1e986b4f3d07dd | [
"BSD-3-Clause"
] | null | null | null | /* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference, 2nd Edition"
* by Nicolai M. Josuttis, Addison-Wesley, 2012
*
* (C) Copyright Nicolai M. Josuttis 2012.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#include "../library/helper.h"
namespace RotateExample {
using namespace std;
void main() {
vector<int> coll;
INSERT_ELEMENTS(coll, 1, 9);
PRINT_ELEMENTS(coll, "coll: ");
// rotate to make the second element as the first
rotate(coll.begin(), // beginning of range
coll.begin() + 1, // new first element
coll.end()); // end of range
PRINT_ELEMENTS(coll, "second element as new first: ");
// rotate two elements to the right
rotate(coll.begin(), // beginning of range
coll.end() - 2, // new first element
coll.end()); // end of range
PRINT_ELEMENTS(coll, "two right: ");
// rotate so that element with value 4 is the beginning
rotate(coll.begin(), // beginning of range
find(coll.begin(), coll.end(), 4), // new first element
coll.end()); // end of range
PRINT_ELEMENTS(coll, "4 first: ");
}
void exampleTwo()
{
set<int> coll;
INSERT_ELEMENTS(coll,1,9);
PRINT_ELEMENTS(coll);
// print elements rotated one element to the left
set<int>::const_iterator pos = next(coll.cbegin());
rotate_copy(coll.cbegin(), // beginning of source
pos, // new first element
coll.cend(), // end of source
ostream_iterator<int>(cout," ")); // destination
cout << endl;
// print elements rotated two elements to the right
pos = coll.cend();
advance(pos,-2);
rotate_copy(coll.cbegin(), // beginning of source
pos, // new first element
coll.cend(), // end of source
ostream_iterator<int>(cout," ")); // destination
cout << endl;
// print elements rotated so that element with value 4 is the beginning
rotate_copy(coll.cbegin(), // beginning of source
coll.find(4), // new first element
coll.cend(), // end of source
ostream_iterator<int>(cout," ")); // destination
cout << endl;
}
} | 40.328767 | 79 | 0.52072 | [
"vector"
] |
6c4db9a5963e4f504aea9286063b5ddec0f15221 | 13,292 | h | C | 2.4/include/java/lang/ThreadLocal.h | yaohb/J2ObjCAuto | 8b5252896999f367066e3f68226620f78c020923 | [
"MIT"
] | null | null | null | 2.4/include/java/lang/ThreadLocal.h | yaohb/J2ObjCAuto | 8b5252896999f367066e3f68226620f78c020923 | [
"MIT"
] | null | null | null | 2.4/include/java/lang/ThreadLocal.h | yaohb/J2ObjCAuto | 8b5252896999f367066e3f68226620f78c020923 | [
"MIT"
] | null | null | null | //
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: android/platform/libcore/ojluni/src/main/java/java/lang/ThreadLocal.java
//
#include "J2ObjC_header.h"
#pragma push_macro("INCLUDE_ALL_JavaLangThreadLocal")
#ifdef RESTRICT_JavaLangThreadLocal
#define INCLUDE_ALL_JavaLangThreadLocal 0
#else
#define INCLUDE_ALL_JavaLangThreadLocal 1
#endif
#undef RESTRICT_JavaLangThreadLocal
#ifdef INCLUDE_JavaLangThreadLocal_SuppliedThreadLocal
#define INCLUDE_JavaLangThreadLocal 1
#endif
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#if __has_feature(nullability)
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wnullability"
#pragma GCC diagnostic ignored "-Wnullability-completeness"
#endif
#if !defined (JavaLangThreadLocal_) && (INCLUDE_ALL_JavaLangThreadLocal || defined(INCLUDE_JavaLangThreadLocal))
#define JavaLangThreadLocal_
@class JavaLangThread;
@class JavaLangThreadLocal_ThreadLocalMap;
@protocol JavaUtilFunctionSupplier;
/*!
@brief This class provides thread-local variables.These variables differ from
their normal counterparts in that each thread that accesses one (via its
<code>get</code> or <code>set</code> method) has its own, independently initialized
copy of the variable.
<code>ThreadLocal</code> instances are typically private
static fields in classes that wish to associate state with a thread (e.g.,
a user ID or Transaction ID).
<p>For example, the class below generates unique identifiers local to each
thread.
A thread's id is assigned the first time it invokes <code>ThreadId.get()</code>
and remains unchanged on subsequent calls.
@code
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadId {
// Atomic integer containing the next thread ID to be assigned
private static final AtomicInteger nextId = new AtomicInteger(0);
// Thread local variable containing each thread's ID
private static final ThreadLocal<Integer> threadId =
new ThreadLocal<Integer>() {
@Override protected Integer initialValue() {
return nextId.getAndIncrement();
}
};
// Returns the current thread's unique ID, assigning it if necessary
public static int get() {
return threadId.get();
} }
@endcode
<p>Each thread holds an implicit reference to its copy of a thread-local
variable as long as the thread is alive and the <code>ThreadLocal</code>
instance is accessible; after a thread goes away, all of its copies of
thread-local instances are subject to garbage collection (unless other
references to these copies exist).
@author Josh Bloch and Doug Lea
@since 1.2
*/
@interface JavaLangThreadLocal : NSObject
#pragma mark Public
/*!
@brief Creates a thread local variable.
- seealso: #withInitial(java.util.function.Supplier)
*/
- (instancetype __nonnull)init;
/*!
@brief Returns the value in the current thread's copy of this
thread-local variable.If the variable has no value for the
current thread, it is first initialized to the value returned
by an invocation of the <code>initialValue</code> method.
@return the current thread's value of this thread-local
*/
- (id __nullable)get;
/*!
@brief Removes the current thread's value for this thread-local
variable.If this thread-local variable is subsequently
read by the current thread, its value will be
reinitialized by invoking its <code>initialValue</code> method,
unless its value is set by the current thread
in the interim.
This may result in multiple invocations of the
<code>initialValue</code> method in the current thread.
@since 1.5
*/
- (void)remove;
/*!
@brief Sets the current thread's copy of this thread-local variable
to the specified value.Most subclasses will have no need to
override this method, relying solely on the <code>initialValue</code>
method to set the values of thread-locals.
@param value the value to be stored in the current thread's copy of this thread-local.
*/
- (void)setWithId:(id)value;
/*!
@brief Creates a thread local variable.The initial value of the variable is
determined by invoking the <code>get</code> method on the <code>Supplier</code>.
@param supplier the supplier to be used to determine the initial value
@return a new thread local variable
@throw NullPointerExceptionif the specified supplier is null
@since 1.8
*/
+ (JavaLangThreadLocal * __nonnull)withInitialWithJavaUtilFunctionSupplier:(id<JavaUtilFunctionSupplier>)supplier;
#pragma mark Protected
/*!
@brief Returns the current thread's "initial value" for this
thread-local variable.This method will be invoked the first
time a thread accesses the variable with the <code>get</code>
method, unless the thread previously invoked the <code>set</code>
method, in which case the <code>initialValue</code> method will not
be invoked for the thread.
Normally, this method is invoked at
most once per thread, but it may be invoked again in case of
subsequent invocations of <code>remove</code> followed by <code>get</code>.
<p>This implementation simply returns <code>null</code>; if the
programmer desires thread-local variables to have an initial
value other than <code>null</code>, <code>ThreadLocal</code> must be
subclassed, and this method overridden. Typically, an
anonymous inner class will be used.
@return the initial value for this thread-local
*/
- (id __nullable)initialValue OBJC_METHOD_FAMILY_NONE;
#pragma mark Package-Private
/*!
@brief Method childValue is visibly defined in subclass
InheritableThreadLocal, but is internally defined here for the
sake of providing createInheritedMap factory method without
needing to subclass the map class in InheritableThreadLocal.
This technique is preferable to the alternative of embedding
instanceof tests in methods.
*/
- (id)childValueWithId:(id)parentValue;
/*!
@brief Factory method to create map of inherited thread locals.
Designed to be called only from Thread constructor.
@param parentMap the map associated with parent thread
@return a map containing the parent's inheritable bindings
*/
+ (JavaLangThreadLocal_ThreadLocalMap *)createInheritedMapWithJavaLangThreadLocal_ThreadLocalMap:(JavaLangThreadLocal_ThreadLocalMap *)parentMap;
/*!
@brief Create the map associated with a ThreadLocal.Overridden in
InheritableThreadLocal.
@param t the current thread
@param firstValue value for the initial entry of the map
*/
- (void)createMapWithJavaLangThread:(JavaLangThread *)t
withId:(id)firstValue;
/*!
@brief Get the map associated with a ThreadLocal.Overridden in
InheritableThreadLocal.
@param t the current thread
@return the map
*/
- (JavaLangThreadLocal_ThreadLocalMap *)getMapWithJavaLangThread:(JavaLangThread *)t;
@end
J2OBJC_STATIC_INIT(JavaLangThreadLocal)
FOUNDATION_EXPORT JavaLangThreadLocal *JavaLangThreadLocal_withInitialWithJavaUtilFunctionSupplier_(id<JavaUtilFunctionSupplier> supplier);
FOUNDATION_EXPORT void JavaLangThreadLocal_init(JavaLangThreadLocal *self);
FOUNDATION_EXPORT JavaLangThreadLocal *new_JavaLangThreadLocal_init(void) NS_RETURNS_RETAINED;
FOUNDATION_EXPORT JavaLangThreadLocal *create_JavaLangThreadLocal_init(void);
FOUNDATION_EXPORT JavaLangThreadLocal_ThreadLocalMap *JavaLangThreadLocal_createInheritedMapWithJavaLangThreadLocal_ThreadLocalMap_(JavaLangThreadLocal_ThreadLocalMap *parentMap);
J2OBJC_TYPE_LITERAL_HEADER(JavaLangThreadLocal)
#endif
#if !defined (JavaLangThreadLocal_SuppliedThreadLocal_) && (INCLUDE_ALL_JavaLangThreadLocal || defined(INCLUDE_JavaLangThreadLocal_SuppliedThreadLocal))
#define JavaLangThreadLocal_SuppliedThreadLocal_
@protocol JavaUtilFunctionSupplier;
/*!
@brief An extension of ThreadLocal that obtains its initial value from
the specified <code>Supplier</code>.
*/
@interface JavaLangThreadLocal_SuppliedThreadLocal : JavaLangThreadLocal
#pragma mark Protected
- (id)initialValue OBJC_METHOD_FAMILY_NONE;
#pragma mark Package-Private
- (instancetype __nonnull)initWithJavaUtilFunctionSupplier:(id<JavaUtilFunctionSupplier>)supplier;
// Disallowed inherited constructors, do not use.
- (instancetype __nonnull)init NS_UNAVAILABLE;
@end
J2OBJC_EMPTY_STATIC_INIT(JavaLangThreadLocal_SuppliedThreadLocal)
FOUNDATION_EXPORT void JavaLangThreadLocal_SuppliedThreadLocal_initWithJavaUtilFunctionSupplier_(JavaLangThreadLocal_SuppliedThreadLocal *self, id<JavaUtilFunctionSupplier> supplier);
FOUNDATION_EXPORT JavaLangThreadLocal_SuppliedThreadLocal *new_JavaLangThreadLocal_SuppliedThreadLocal_initWithJavaUtilFunctionSupplier_(id<JavaUtilFunctionSupplier> supplier) NS_RETURNS_RETAINED;
FOUNDATION_EXPORT JavaLangThreadLocal_SuppliedThreadLocal *create_JavaLangThreadLocal_SuppliedThreadLocal_initWithJavaUtilFunctionSupplier_(id<JavaUtilFunctionSupplier> supplier);
J2OBJC_TYPE_LITERAL_HEADER(JavaLangThreadLocal_SuppliedThreadLocal)
#endif
#if !defined (JavaLangThreadLocal_ThreadLocalMap_) && (INCLUDE_ALL_JavaLangThreadLocal || defined(INCLUDE_JavaLangThreadLocal_ThreadLocalMap))
#define JavaLangThreadLocal_ThreadLocalMap_
@class JavaLangThreadLocal;
/*!
@brief ThreadLocalMap is a customized hash map suitable only for
maintaining thread local values.No operations are exported
outside of the ThreadLocal class.
The class is package private to
allow declaration of fields in class Thread. To help deal with
very large and long-lived usages, the hash table entries use
WeakReferences for keys. However, since reference queues are not
used, stale entries are guaranteed to be removed only when
the table starts running out of space.
*/
@interface JavaLangThreadLocal_ThreadLocalMap : NSObject
#pragma mark Package-Private
/*!
@brief Construct a new map initially containing (firstKey, firstValue).
ThreadLocalMaps are constructed lazily, so we only create
one when we have at least one entry to put in it.
*/
- (instancetype __nonnull)initWithJavaLangThreadLocal:(JavaLangThreadLocal *)firstKey
withId:(id)firstValue;
// Disallowed inherited constructors, do not use.
- (instancetype __nonnull)init NS_UNAVAILABLE;
@end
J2OBJC_EMPTY_STATIC_INIT(JavaLangThreadLocal_ThreadLocalMap)
FOUNDATION_EXPORT void JavaLangThreadLocal_ThreadLocalMap_initWithJavaLangThreadLocal_withId_(JavaLangThreadLocal_ThreadLocalMap *self, JavaLangThreadLocal *firstKey, id firstValue);
FOUNDATION_EXPORT JavaLangThreadLocal_ThreadLocalMap *new_JavaLangThreadLocal_ThreadLocalMap_initWithJavaLangThreadLocal_withId_(JavaLangThreadLocal *firstKey, id firstValue) NS_RETURNS_RETAINED;
FOUNDATION_EXPORT JavaLangThreadLocal_ThreadLocalMap *create_JavaLangThreadLocal_ThreadLocalMap_initWithJavaLangThreadLocal_withId_(JavaLangThreadLocal *firstKey, id firstValue);
J2OBJC_TYPE_LITERAL_HEADER(JavaLangThreadLocal_ThreadLocalMap)
#endif
#if !defined (JavaLangThreadLocal_ThreadLocalMap_Entry_) && (INCLUDE_ALL_JavaLangThreadLocal || defined(INCLUDE_JavaLangThreadLocal_ThreadLocalMap_Entry))
#define JavaLangThreadLocal_ThreadLocalMap_Entry_
#define RESTRICT_JavaLangRefWeakReference 1
#define INCLUDE_JavaLangRefWeakReference 1
#include "java/lang/ref/WeakReference.h"
@class JavaLangRefReferenceQueue;
@class JavaLangThreadLocal;
/*!
@brief The entries in this hash map extend WeakReference, using
its main ref field as the key (which is always a
ThreadLocal object).Note that null keys (i.e. entry.get()
== null) mean that the key is no longer referenced, so the
entry can be expunged from table.
Such entries are referred to
as "stale entries" in the code that follows.
*/
@interface JavaLangThreadLocal_ThreadLocalMap_Entry : JavaLangRefWeakReference {
@public
/*!
@brief The value associated with this ThreadLocal.
*/
id value_;
}
#pragma mark Public
- (JavaLangThreadLocal *)get;
#pragma mark Package-Private
- (instancetype __nonnull)initWithJavaLangThreadLocal:(JavaLangThreadLocal *)k
withId:(id)v;
// Disallowed inherited constructors, do not use.
- (instancetype __nonnull)initWithId:(id)arg0 NS_UNAVAILABLE;
- (instancetype __nonnull)initWithId:(id)arg0
withJavaLangRefReferenceQueue:(JavaLangRefReferenceQueue *)arg1 NS_UNAVAILABLE;
@end
J2OBJC_EMPTY_STATIC_INIT(JavaLangThreadLocal_ThreadLocalMap_Entry)
J2OBJC_FIELD_SETTER(JavaLangThreadLocal_ThreadLocalMap_Entry, value_, id)
FOUNDATION_EXPORT void JavaLangThreadLocal_ThreadLocalMap_Entry_initWithJavaLangThreadLocal_withId_(JavaLangThreadLocal_ThreadLocalMap_Entry *self, JavaLangThreadLocal *k, id v);
FOUNDATION_EXPORT JavaLangThreadLocal_ThreadLocalMap_Entry *new_JavaLangThreadLocal_ThreadLocalMap_Entry_initWithJavaLangThreadLocal_withId_(JavaLangThreadLocal *k, id v) NS_RETURNS_RETAINED;
FOUNDATION_EXPORT JavaLangThreadLocal_ThreadLocalMap_Entry *create_JavaLangThreadLocal_ThreadLocalMap_Entry_initWithJavaLangThreadLocal_withId_(JavaLangThreadLocal *k, id v);
J2OBJC_TYPE_LITERAL_HEADER(JavaLangThreadLocal_ThreadLocalMap_Entry)
#endif
#if __has_feature(nullability)
#pragma clang diagnostic pop
#endif
#pragma clang diagnostic pop
#pragma pop_macro("INCLUDE_ALL_JavaLangThreadLocal")
| 37.868946 | 196 | 0.803039 | [
"object"
] |
6c50806ad3f7dc478d51080b993ef54b32997927 | 2,134 | h | C | contrib/gitian-builder/inputs/MacOSX.sdk/System/Library/Frameworks/NotificationCenter.framework/Versions/A/Headers/NCWidgetSearchViewController.h | Phikzel2/haroldcoin-main-MacOS | 15c949c8f722d424fd9603fab3c49ec4b2b720eb | [
"MIT"
] | null | null | null | contrib/gitian-builder/inputs/MacOSX.sdk/System/Library/Frameworks/NotificationCenter.framework/Versions/A/Headers/NCWidgetSearchViewController.h | Phikzel2/haroldcoin-main-MacOS | 15c949c8f722d424fd9603fab3c49ec4b2b720eb | [
"MIT"
] | null | null | null | contrib/gitian-builder/inputs/MacOSX.sdk/System/Library/Frameworks/NotificationCenter.framework/Versions/A/Headers/NCWidgetSearchViewController.h | Phikzel2/haroldcoin-main-MacOS | 15c949c8f722d424fd9603fab3c49ec4b2b720eb | [
"MIT"
] | 1 | 2021-08-13T21:12:07.000Z | 2021-08-13T21:12:07.000Z | /*
* NCWidgetSearchViewController.h
* NotificationCenter.framework
* Copyright (c) 2014-2015 Apple Inc. All rights reserved.
*/
#import <AppKit/AppKit.h>
NS_ASSUME_NONNULL_BEGIN
@protocol NCWidgetSearchViewDelegate;
NS_CLASS_AVAILABLE_MAC(10_10)
@interface NCWidgetSearchViewController : NSViewController
/* The delegate is responsible for performing the search based on the
searchTerm provided to it and setting the searchResults array accordingly. */
@property (nullable, weak) IBOutlet id<NCWidgetSearchViewDelegate> delegate;
/* A textual representation of the objects in searchResults will be displayed
using the description property of each object. A different property may be
specified for display using the searchResultKeyPath property. */
@property (nullable, copy) NSArray<id> *searchResults;
/* Specify localized header text for the search view. Defaults to "Search" */
@property (nullable, copy) NSString *searchDescription;
/* Specify a localized placeholder string to display in the list view when no
results are available. */
@property (nullable, copy) NSString *searchResultsPlaceholderString;
/* Specify a key path for the string property to display for each object in
searchResults. By default "description" will be used. */
@property (nullable, copy) NSString *searchResultKeyPath;
@end
@protocol NCWidgetSearchViewDelegate <NSObject>
/* Called as new search terms are typed.
Set the searchResults of the NCSearchViewController in order to display the
results. The max results argument hints at a maximum number of results that
will be displayed. */
- (void)widgetSearch:(NCWidgetSearchViewController *)controller searchForTerm:(NSString *)searchTerm maxResults:(NSUInteger)max;
/* Called when the search term is cleared. */
- (void)widgetSearchTermCleared:(NCWidgetSearchViewController *)controller;
/* Called when the user selects an item from the list of search results.
The search view controller will be dismissed after this method returns. */
- (void)widgetSearch:(NCWidgetSearchViewController *)controller resultSelected:(id)object;
@end
NS_ASSUME_NONNULL_END
| 37.438596 | 128 | 0.79194 | [
"object"
] |
6c580f3a91db89a7242c0697d7b1eec7edf10daa | 1,676 | h | C | modules/audio_processing/aec3/mock/mock_echo_remover.h | gaoxiaoyang/webrtc | 21021f022be36f5d04f8a3a309e345f65c8603a9 | [
"BSD-3-Clause"
] | 305 | 2020-03-31T14:12:50.000Z | 2022-03-19T16:45:49.000Z | modules/audio_processing/aec3/mock/mock_echo_remover.h | gaoxiaoyang/webrtc | 21021f022be36f5d04f8a3a309e345f65c8603a9 | [
"BSD-3-Clause"
] | 31 | 2020-11-17T05:30:13.000Z | 2021-12-14T02:19:00.000Z | modules/audio_processing/aec3/mock/mock_echo_remover.h | gaoxiaoyang/webrtc | 21021f022be36f5d04f8a3a309e345f65c8603a9 | [
"BSD-3-Clause"
] | 122 | 2020-04-17T11:38:56.000Z | 2022-03-25T15:48:42.000Z | /*
* Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef MODULES_AUDIO_PROCESSING_AEC3_MOCK_MOCK_ECHO_REMOVER_H_
#define MODULES_AUDIO_PROCESSING_AEC3_MOCK_MOCK_ECHO_REMOVER_H_
#include <vector>
#include "absl/types/optional.h"
#include "modules/audio_processing/aec3/echo_path_variability.h"
#include "modules/audio_processing/aec3/echo_remover.h"
#include "modules/audio_processing/aec3/render_buffer.h"
#include "test/gmock.h"
namespace webrtc {
namespace test {
class MockEchoRemover : public EchoRemover {
public:
MockEchoRemover();
virtual ~MockEchoRemover();
MOCK_METHOD6(ProcessCapture,
void(EchoPathVariability echo_path_variability,
bool capture_signal_saturation,
const absl::optional<DelayEstimate>& delay_estimate,
RenderBuffer* render_buffer,
std::vector<std::vector<std::vector<float>>>* linear_output,
std::vector<std::vector<std::vector<float>>>* capture));
MOCK_CONST_METHOD0(Delay, absl::optional<int>());
MOCK_METHOD1(UpdateEchoLeakageStatus, void(bool leakage_detected));
MOCK_CONST_METHOD1(GetMetrics, void(EchoControl::Metrics* metrics));
};
} // namespace test
} // namespace webrtc
#endif // MODULES_AUDIO_PROCESSING_AEC3_MOCK_MOCK_ECHO_REMOVER_H_
| 36.434783 | 80 | 0.73568 | [
"vector"
] |
6c5952749dd33d5e0059c209dc14ea755424da23 | 2,064 | h | C | csrc/aio/common/deepspeed_aio_utils.h | ganik/DeepSpeed | 788e1c40e83beacfc4901e7daa1e097d2efb82bb | [
"MIT"
] | 2 | 2021-03-17T12:00:32.000Z | 2021-03-17T12:18:30.000Z | csrc/aio/common/deepspeed_aio_utils.h | ganik/DeepSpeed | 788e1c40e83beacfc4901e7daa1e097d2efb82bb | [
"MIT"
] | null | null | null | csrc/aio/common/deepspeed_aio_utils.h | ganik/DeepSpeed | 788e1c40e83beacfc4901e7daa1e097d2efb82bb | [
"MIT"
] | 1 | 2021-03-08T07:28:37.000Z | 2021-03-08T07:28:37.000Z | /*
Copyright 2020 The Microsoft DeepSpeed Team
Licensed under the MIT license.
Functionality for swapping optimizer tensors to/from (NVMe) storage devices.
*/
#pragma once
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <libaio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <deepspeed_aio_types.h>
#include <cstring>
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
struct io_xfer_ctxt {
const int _fd;
const long long int _base_offset;
const void* _mem_buffer;
const long long int _num_bytes;
io_xfer_ctxt(const int fd,
const long long int file_offset,
const long long int num_bytes,
const void* buffer);
};
struct io_prep_context {
const bool _read_op;
const std::unique_ptr<io_xfer_ctxt>& _xfer_ctxt;
const size_t _block_size;
const std::vector<struct iocb*>* _iocbs;
io_prep_context(const bool read_op,
const std::unique_ptr<io_xfer_ctxt>& xfer_ctxt,
const size_t block_size,
const std::vector<struct iocb*>* iocbs);
void prep_iocbs(const int n_iocbs,
const size_t num_bytes,
const void* start_buffer,
const long long int start_offset);
};
struct io_prep_generator {
const bool _read_op;
const std::unique_ptr<io_xfer_ctxt>& _xfer_ctxt;
const size_t _block_size;
long long int _remaining_bytes;
long long int _num_io_blocks;
long long int _remaining_io_blocks;
long long int _next_iocb_index;
io_prep_generator(const bool read_op,
const std::unique_ptr<io_xfer_ctxt>& xfer_ctxt,
const size_t block_size);
int prep_iocbs(const int n_iocbs, std::vector<struct iocb*>* iocbs);
};
void* ds_page_aligned_alloc(const size_t size, const bool lock = false);
int get_file_size(const char* filename, long long int& size);
| 26.461538 | 76 | 0.66812 | [
"vector"
] |
6c5a301d1a6de4b65e556acd6ff782bb233a30bf | 1,762 | c | C | matsum.c | curiousTauseef/matrixlab | 553170f93d445f30d7c29731a34a1db75bb3dde2 | [
"MIT"
] | null | null | null | matsum.c | curiousTauseef/matrixlab | 553170f93d445f30d7c29731a34a1db75bb3dde2 | [
"MIT"
] | null | null | null | matsum.c | curiousTauseef/matrixlab | 553170f93d445f30d7c29731a34a1db75bb3dde2 | [
"MIT"
] | 1 | 2019-12-02T17:08:28.000Z | 2019-12-02T17:08:28.000Z | #include "matrix.h"
/** \brief Computes element-sum of a matrix
*
* \param[in] A Input matrix
* \return \f$ \textrm{sum}( \mathbf{A} ) \f$
*
*/
mtype mat_sum(MATRIX A)
{
int i, j, m, n;
mtype mn = 0.0;
m = MatCol(A);
n = MatRow(A);
#pragma omp parallel for private(j)
for(i=0; i<n; ++i)
{
for(j=0; j<m; ++j) mn += A[i][j];
}
return mn;
}
/** \brief Computes row-sum of a matrix
*
* \param[in] A Input matrix
* \param[in] result Matrix to store the result
* \return \f$ \mathbf{A} \mathbf{1} \f$
*
*/
MATRIX mat_sum_row(MATRIX A, MATRIX result)
{
int i, j, m, n;
m = MatCol(A);
n = MatRow(A);
if(result==NULL) if((result = mat_creat(n, 1, UNDEFINED))==NULL) mat_error(MAT_MALLOC);
#pragma omp parallel for private(j)
for(i=0; i<n; ++i)
{
result[i][0] = 0.0;
for(j=0; j<m; ++j) result[i][0] += A[i][j];
}
return result;
}
/** \brief Computes column-sum of a matrix
*
* \param[in] A Input matrix
* \param[in] result Matrix to store the result
* \return \f$ \mathbf{1}^T \mathbf{A} \f$
*
*/
MATRIX mat_sum_col(MATRIX A, MATRIX result)
{
int i, j, m, n;
m = MatCol(A);
n = MatRow(A);
if(result==NULL) if((result = mat_creat(1, m, UNDEFINED))==NULL) mat_error(MAT_MALLOC);
for(j=0; j<m; ++j) result[0][j] = 0.0;
#pragma omp parallel for private(j)
for(i=0; i<n; ++i)
{
for(j=0; j<m; ++j) result[0][j] += A[i][j];
}
return result;
}
/** \brief Computes element-sum of an integer vector
*
* \param[in] A Input integer vector
* \return \f$ \textrm{sum}( A ) \f$
*
*/
int int_vec_sum(INT_VECTOR A)
{
int i, m, mn = 0;
m = Int_VecLen(A);
for(i=0; i<m; ++i) mn += A[i];
return mn;
}
| 20.729412 | 91 | 0.547106 | [
"vector"
] |
6c5dd9c542c322f44f09e27ac217d46912d5a1d2 | 225 | h | C | GameJamFall2015/Rock.h | Behemyth/GameJamFall2015 | 68eac44dbdcacddd65ec7006de6b0baa4cb40f60 | [
"MIT"
] | null | null | null | GameJamFall2015/Rock.h | Behemyth/GameJamFall2015 | 68eac44dbdcacddd65ec7006de6b0baa4cb40f60 | [
"MIT"
] | null | null | null | GameJamFall2015/Rock.h | Behemyth/GameJamFall2015 | 68eac44dbdcacddd65ec7006de6b0baa4cb40f60 | [
"MIT"
] | null | null | null | #pragma once
#include "BasicIncludes.h"
#include "Object.h"
#include "Terrain.h"
#include "Camera.h"
class Rock : public Object
{
private:
Terrain* terrain;
public:
Rock(btDiscreteDynamicsWorld*, Terrain*);
~Rock();
};
| 13.235294 | 42 | 0.711111 | [
"object"
] |
6c5efe9abd407870ca9be7a5c9b96bfaa514c1e4 | 10,106 | h | C | src/dag/external/keccak/doc/KeccakDuplex-documentation.h | bcashclassic/bcashclassic | 2a31ac8b617226c8e99a47512013530ba4899f66 | [
"MIT"
] | 4 | 2021-07-28T19:53:27.000Z | 2021-07-29T11:28:20.000Z | src/dag/external/keccak/doc/KeccakDuplex-documentation.h | bcashclassic/bcashclassic | 2a31ac8b617226c8e99a47512013530ba4899f66 | [
"MIT"
] | 1 | 2021-04-18T17:01:41.000Z | 2021-04-18T20:05:20.000Z | src/dag/external/keccak/doc/KeccakDuplex-documentation.h | bcashclassic/bcashclassic | 2a31ac8b617226c8e99a47512013530ba4899f66 | [
"MIT"
] | 2 | 2020-11-08T10:10:39.000Z | 2021-03-29T14:17:41.000Z | /*
Implementation by the Keccak Team, namely, Guido Bertoni, Joan Daemen,
Michaël Peeters, Gilles Van Assche and Ronny Van Keer,
hereby denoted as "the implementer".
For more information, feedback or questions, please refer to our website:
https://keccak.team/
To the extent possible under law, the implementer has waived all copyright
and related or neighboring rights to the source code in this file.
http://creativecommons.org/publicdomain/zero/1.0/
*/
/** General information
*
* The following type and functions are not actually implemented. Their
* documentation is generic, with the prefix Prefix replaced by
* - KeccakWidth200 for a duplex object based on Keccak-f[200]
* - KeccakWidth400 for a duplex object based on Keccak-f[400]
* - KeccakWidth800 for a duplex object based on Keccak-f[800]
* - KeccakWidth1600 for a duplex object based on Keccak-f[1600]
*
* In all these functions, the rate and capacity must sum to the width of the
* chosen permutation. For instance, to use the duplex object
* Keccak[r=1346, c=254], one must use the KeccakWidth1600_Duplex* functions.
*
* The Prefix_DuplexInstance contains the duplex instance attributes for use
* with the Prefix_Duplex* functions.
* It gathers the state processed by the permutation as well as the rate,
* the position of input/output bytes in the state in case of partial
* input or output.
*/
#ifdef DontReallyInclude_DocumentationOnly
/**
* Structure that contains the duplex instance for use with the
* Prefix_Duplex* functions.
* It gathers the state processed by the permutation as well as
* the rate.
*/
typedef struct Prefix_DuplexInstanceStruct {
/** The state processed by the permutation. */
unsigned char state[SnP_stateSizeInBytes];
/** The value of the rate in bits.*/
unsigned int rate;
/** The position in the state of the next byte to be input. */
unsigned int byteInputIndex;
/** The position in the state of the next byte to be output. */
unsigned int byteOutputIndex;
} Prefix_DuplexInstance;
/**
* Function to initialize a duplex object Duplex[Keccak-f[r+c], pad10*1, r].
* @param duplexInstance Pointer to the duplex instance to be initialized.
* @param rate The value of the rate r.
* @param capacity The value of the capacity c.
* @pre One must have r+c equal to the supported width of this implementation.
* @pre 3 ≤ @a rate ≤ width, and otherwise the value of the rate is unrestricted.
* @return Zero if successful, 1 otherwise.
*/
int Prefix_DuplexInitialize(Prefix_DuplexInstance *duplexInstance, unsigned int rate, unsigned int capacity);
/**
* Function to make a duplexing call to the duplex object initialized
* with Prefix_DuplexInitialize().
* @param duplexInstance Pointer to the duplex instance initialized
* by Prefix_DuplexInitialize().
* @param sigmaBegin Pointer to the first part of the input σ given as bytes.
* Trailing bits are given in @a delimitedSigmaEnd.
* @param sigmaBeginByteLen The number of input bytes provided in @a sigmaBegin.
* @param Z Pointer to the buffer where to store the output data Z.
* @param ZByteLen The number of output bytes desired for Z.
* If @a ZByteLen*8 is greater than the rate r,
* the last byte contains only r modulo 8 bits,
* in the least significant bits.
* @param delimitedSigmaEnd Byte containing from 0 to 7 trailing bits that must be
* appended to the input data in @a sigmaBegin.
* These <i>n</i>=|σ| mod 8 bits must be in the least significant bit positions.
* These bits must be delimited with a bit 1 at position <i>n</i>
* (counting from 0=LSB to 7=MSB) and followed by bits 0
* from position <i>n</i>+1 to position 7.
* Some examples:
* - If |σ| is a multiple of 8, then @a delimitedSigmaEnd must be 0x01.
* - If |σ| mod 8 is 1 and the last bit is 1 then @a delimitedSigmaEnd must be 0x03.
* - If |σ| mod 8 is 4 and the last 4 bits are 0,0,0,1 then @a delimitedSigmaEnd must be 0x18.
* - If |σ| mod 8 is 6 and the last 6 bits are 1,1,1,0,0,1 then @a delimitedSigmaEnd must be 0x67.
* .
* @note The input bits σ are the result of the concatenation of
* the bytes given in Prefix_DuplexingFeedPartialInput()
* calls since the last call to Prefix_Duplexing(),
* the bytes in @a sigmaBegin
* and the bits in @a delimitedSigmaEnd before the delimiter.
* @pre @a delimitedSigmaEnd ≠ 0x00
* @pre @a sigmaBeginByteLen*8+<i>n</i> (+ length of previously queued data) ≤ (r-2)
* @pre @a ZByteLen ≤ ceil(r/8)
* @return Zero if successful, 1 otherwise.
*/
int Prefix_Duplexing(Prefix_DuplexInstance *duplexInstance, const unsigned char *sigmaBegin, unsigned int sigmaBeginByteLen, unsigned char *Z, unsigned int ZByteLen, unsigned char delimitedSigmaEnd);
/**
* Function to queue input data that will subsequently used in the next
* call to Prefix_Duplexing().
* @param duplexInstance Pointer to the duplex instance initialized
* by Prefix_DuplexInitialize().
* @param input Pointer to the bytes to queue.
* @param inputByteLen The number of input bytes provided in @a input.
* @pre The total number of input bytes since the last Prefix_Duplexing()
* call must not be higher than floor((r-2)/8).
* @return Zero if successful, 1 otherwise.
*/
int Prefix_DuplexingFeedPartialInput(Prefix_DuplexInstance *duplexInstance, const unsigned char *input, unsigned int inputByteLen);
/**
* Function to queue input data that will subsequently used in the next
* call to Prefix_Duplexing(), where the data here consist of all-zero bytes.
* @param duplexInstance Pointer to the duplex instance initialized
* by Prefix_DuplexInitialize().
* @param inputByteLen The number of input bytes 0x00 to feed.
* @pre The total number of input bytes since the last Prefix_Duplexing()
* call must not be higher than floor((r-2)/8).
* @return Zero if successful, 1 otherwise.
*/
int Prefix_DuplexingFeedZeroes(Prefix_DuplexInstance *duplexInstance, unsigned int inputByteLen);
/**
* Function to queue input data that will subsequently used in the next
* call to Prefix_Duplexing(), with the additional pre-processing that
* the input data is first bitwise added with the output data of the previous duplexing
* call at the same offset.
* In practice, this comes down to overwriting the input data in the state
* of the duplex object.
* @param duplexInstance Pointer to the duplex instance initialized
* by Prefix_DuplexInitialize().
* @param input Pointer to the bytes to queue, before they are XORed.
* @param inputByteLen The number of input bytes provided in @a input.
* @pre The total number of input bytes since the last Prefix_Duplexing()
* call must not be higher than floor((r-2)/8).
* @return Zero if successful, 1 otherwise.
*/
int Prefix_DuplexingOverwritePartialInput(Prefix_DuplexInstance *duplexInstance, const unsigned char *input, unsigned int inputByteLen);
/**
* Function to queue input data for the next call to Prefix_Duplexing() that
* is equal to the output data of the previous duplexing call at the same offset.
* In practice, this comes down to overwriting with zeroes the state
* of the duplex object.
* @param duplexInstance Pointer to the duplex instance initialized
* by Prefix_DuplexInitialize().
* @param inputByteLen The number of bytes to overwrite with zeroes.
* @pre No input data may have been queued since the last call
* to Prefix_Duplexing().
* @pre The total number of input bytes since the last Prefix_Duplexing()
* call must not be higher than floor((r-2)/8).
* @return Zero if successful, 1 otherwise.
*/
int Prefix_DuplexingOverwriteWithZeroes(Prefix_DuplexInstance *duplexInstance, unsigned int inputByteLen);
/**
* Function to fetch output data beyond those that were already output since
* the last call to Prefix_Duplexing().
* @param duplexInstance Pointer to the duplex instance initialized
* by Prefix_DuplexInitialize().
* @param output Pointer to the buffer where to store the output data.
* @param outputByteLen The number of output bytes desired.
* @pre The total number of output bytes, taken since (and including in)
* the last call to Prefix_Duplexing() cannot be higher than ceil(r/8).
* @return Zero if successful, 1 otherwise.
*/
int Prefix_DuplexingGetFurtherOutput(Prefix_DuplexInstance *duplexInstance, unsigned char *out, unsigned int outByteLen);
/**
* Function to fetch output data beyond those that were already output since
* the last call to Prefix_Duplexing(), with the additional post-processing
* that this data is bitwise added with the given input buffer
* before it is stored into the given output buffer.
* @param duplexInstance Pointer to the duplex instance initialized
* by Prefix_DuplexInitialize().
* @param input Pointer to the input buffer.
* @param output Pointer to the output buffer, which may be equal to @a input.
* @param outputByteLen The number of output bytes desired.
* @pre The total number of output bytes, taken since (and including in)
* the last call to Prefix_Duplexing() cannot be higher than ceil(r/8).
* @return Zero if successful, 1 otherwise.
*/
int Prefix_DuplexingGetFurtherOutputAndAdd(Prefix_DuplexInstance *duplexInstance, const unsigned char *input, unsigned char *output, unsigned int outputByteLen);
#endif
| 54.042781 | 199 | 0.690679 | [
"object"
] |
6c62583fb0e9504e0fc0e8ce3e0bbb5633c036b4 | 1,587 | h | C | Plugins/org.mitk.gui.qt.m2.Data/src/internal/m2DataTools.h | ivowolf/M2aia | 03cfe3495bc706cbb0b00a2916b8f0a3cb398e25 | [
"BSD-3-Clause"
] | 7 | 2021-07-22T06:52:01.000Z | 2022-02-17T12:53:31.000Z | Plugins/org.mitk.gui.qt.m2.Data/src/internal/m2DataTools.h | ivowolf/M2aia | 03cfe3495bc706cbb0b00a2916b8f0a3cb398e25 | [
"BSD-3-Clause"
] | 4 | 2021-07-25T22:29:33.000Z | 2022-02-22T13:21:30.000Z | Plugins/org.mitk.gui.qt.m2.Data/src/internal/m2DataTools.h | ivowolf/M2aia | 03cfe3495bc706cbb0b00a2916b8f0a3cb398e25 | [
"BSD-3-Clause"
] | 2 | 2021-06-23T11:53:11.000Z | 2021-07-22T06:14:24.000Z | /*===================================================================
MSI applications for interactive analysis in MITK (M2aia)
Copyright (c) Jonas Cordes.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or https://www.github.com/jtfcordes/m2aia for details.
===================================================================*/
#pragma once
#include "ui_m2DataTools.h"
#include <QThreadPool>
#include <QmitkAbstractView.h>
#include <mitkColorBarAnnotation.h>
#include <mitkTextAnnotation2D.h>
#include <m2SpectrumImageDataInteractor.h>
#include <m2UIUtils.h>
class m2DataTools : public QmitkAbstractView
{
// this is needed for all Qt objects that should have a Qt meta-object
// (everything that derives from QObject and wants to have signal/slots)
Q_OBJECT
public:
static const std::string VIEW_ID;
Ui::imsDataToolsControls *Controls() { return &m_Controls; }
public slots:
void OnEqualizeLW();
void OnApplyTiling();
void OnResetTiling();
void UpdateColorBarAndRenderWindows();
void OnToggleDataInteraction(bool checked);
protected:
void UpdateLevelWindow(const mitk::DataNode *node);
virtual void CreateQtPartControl(QWidget *parent) override;
virtual void SetFocus() override {}
mitk::DataInteractor::Pointer m_DataInteractor;
Ui::imsDataToolsControls m_Controls;
QWidget * m_Parent = nullptr;
QThreadPool m_pool;
std::vector<mitk::ColorBarAnnotation::Pointer> m_ColorBarAnnotations;
};
| 26.016393 | 74 | 0.704474 | [
"object",
"vector"
] |
6c68e14c3d15a13411dc3098763c0639692459ab | 1,278 | h | C | src/decoder-phrasebased/src/native/interpolated-lm/db/ngram_hash.h | ugermann/MMT | 715ad16b4467f44c8103e16165261d1391a69fb8 | [
"Apache-2.0"
] | null | null | null | src/decoder-phrasebased/src/native/interpolated-lm/db/ngram_hash.h | ugermann/MMT | 715ad16b4467f44c8103e16165261d1391a69fb8 | [
"Apache-2.0"
] | null | null | null | src/decoder-phrasebased/src/native/interpolated-lm/db/ngram_hash.h | ugermann/MMT | 715ad16b4467f44c8103e16165261d1391a69fb8 | [
"Apache-2.0"
] | null | null | null | //
// Created by Davide Caroselli on 17/02/17.
//
#ifndef ILM_NGRAM_HASH_H
#define ILM_NGRAM_HASH_H
#include <cstdint>
#include <mmt/sentence.h>
namespace mmt {
namespace ilm {
/* N-Grams hash */
typedef uint64_t ngram_hash_t;
inline ngram_hash_t hash_ngram(const wid_t word) {
return (ngram_hash_t) word;
}
inline ngram_hash_t hash_ngram(const ngram_hash_t current, const wid_t word) {
ngram_hash_t key = ((current * 8978948897894561157ULL) ^
(static_cast<uint64_t>(1 + word) * 17894857484156487943ULL));
return key == 0 ? 1 : key; // key "0" is reserved
}
inline ngram_hash_t hash_ngram(const std::vector<wid_t> &words, const size_t offset, const size_t size) {
ngram_hash_t key = hash_ngram(words[offset]);
for (size_t i = 1; i < size; ++i)
key = hash_ngram(key, words[offset + i]);
return key;
}
inline ngram_hash_t hash_ngram(const std::vector<wid_t> &words, const size_t order) {
const size_t offset = (size_t) std::max(0, (int) (words.size() - order));
return hash_ngram(words, offset, order);
}
}
}
#endif //ILM_NGRAM_HASH_H
| 28.4 | 113 | 0.595462 | [
"vector"
] |
6c76ffc93cd5e7a7c8c58362fdb0e20a26231902 | 13,113 | h | C | apigateway/include/tencentcloud/apigateway/v20180808/model/UsagePlanEnvironment.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | apigateway/include/tencentcloud/apigateway/v20180808/model/UsagePlanEnvironment.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | apigateway/include/tencentcloud/apigateway/v20180808/model/UsagePlanEnvironment.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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.
*/
#ifndef TENCENTCLOUD_APIGATEWAY_V20180808_MODEL_USAGEPLANENVIRONMENT_H_
#define TENCENTCLOUD_APIGATEWAY_V20180808_MODEL_USAGEPLANENVIRONMENT_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Apigateway
{
namespace V20180808
{
namespace Model
{
/**
* 使用计划绑定环境详情。
*/
class UsagePlanEnvironment : public AbstractModel
{
public:
UsagePlanEnvironment();
~UsagePlanEnvironment() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取绑定的服务唯一 ID。
注意:此字段可能返回 null,表示取不到有效值。
* @return ServiceId 绑定的服务唯一 ID。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetServiceId() const;
/**
* 设置绑定的服务唯一 ID。
注意:此字段可能返回 null,表示取不到有效值。
* @param ServiceId 绑定的服务唯一 ID。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetServiceId(const std::string& _serviceId);
/**
* 判断参数 ServiceId 是否已赋值
* @return ServiceId 是否已赋值
*/
bool ServiceIdHasBeenSet() const;
/**
* 获取API 的唯一ID。
注意:此字段可能返回 null,表示取不到有效值。
* @return ApiId API 的唯一ID。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetApiId() const;
/**
* 设置API 的唯一ID。
注意:此字段可能返回 null,表示取不到有效值。
* @param ApiId API 的唯一ID。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetApiId(const std::string& _apiId);
/**
* 判断参数 ApiId 是否已赋值
* @return ApiId 是否已赋值
*/
bool ApiIdHasBeenSet() const;
/**
* 获取API 的名称。
注意:此字段可能返回 null,表示取不到有效值。
* @return ApiName API 的名称。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetApiName() const;
/**
* 设置API 的名称。
注意:此字段可能返回 null,表示取不到有效值。
* @param ApiName API 的名称。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetApiName(const std::string& _apiName);
/**
* 判断参数 ApiName 是否已赋值
* @return ApiName 是否已赋值
*/
bool ApiNameHasBeenSet() const;
/**
* 获取API 的路径。
注意:此字段可能返回 null,表示取不到有效值。
* @return Path API 的路径。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetPath() const;
/**
* 设置API 的路径。
注意:此字段可能返回 null,表示取不到有效值。
* @param Path API 的路径。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetPath(const std::string& _path);
/**
* 判断参数 Path 是否已赋值
* @return Path 是否已赋值
*/
bool PathHasBeenSet() const;
/**
* 获取API 的方法。
注意:此字段可能返回 null,表示取不到有效值。
* @return Method API 的方法。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetMethod() const;
/**
* 设置API 的方法。
注意:此字段可能返回 null,表示取不到有效值。
* @param Method API 的方法。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetMethod(const std::string& _method);
/**
* 判断参数 Method 是否已赋值
* @return Method 是否已赋值
*/
bool MethodHasBeenSet() const;
/**
* 获取已经绑定的环境名称。
注意:此字段可能返回 null,表示取不到有效值。
* @return Environment 已经绑定的环境名称。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetEnvironment() const;
/**
* 设置已经绑定的环境名称。
注意:此字段可能返回 null,表示取不到有效值。
* @param Environment 已经绑定的环境名称。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetEnvironment(const std::string& _environment);
/**
* 判断参数 Environment 是否已赋值
* @return Environment 是否已赋值
*/
bool EnvironmentHasBeenSet() const;
/**
* 获取已经使用的配额。
注意:此字段可能返回 null,表示取不到有效值。
* @return InUseRequestNum 已经使用的配额。
注意:此字段可能返回 null,表示取不到有效值。
*/
int64_t GetInUseRequestNum() const;
/**
* 设置已经使用的配额。
注意:此字段可能返回 null,表示取不到有效值。
* @param InUseRequestNum 已经使用的配额。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetInUseRequestNum(const int64_t& _inUseRequestNum);
/**
* 判断参数 InUseRequestNum 是否已赋值
* @return InUseRequestNum 是否已赋值
*/
bool InUseRequestNumHasBeenSet() const;
/**
* 获取最大请求量。
注意:此字段可能返回 null,表示取不到有效值。
* @return MaxRequestNum 最大请求量。
注意:此字段可能返回 null,表示取不到有效值。
*/
int64_t GetMaxRequestNum() const;
/**
* 设置最大请求量。
注意:此字段可能返回 null,表示取不到有效值。
* @param MaxRequestNum 最大请求量。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetMaxRequestNum(const int64_t& _maxRequestNum);
/**
* 判断参数 MaxRequestNum 是否已赋值
* @return MaxRequestNum 是否已赋值
*/
bool MaxRequestNumHasBeenSet() const;
/**
* 获取每秒最大请求次数。
注意:此字段可能返回 null,表示取不到有效值。
* @return MaxRequestNumPreSec 每秒最大请求次数。
注意:此字段可能返回 null,表示取不到有效值。
*/
int64_t GetMaxRequestNumPreSec() const;
/**
* 设置每秒最大请求次数。
注意:此字段可能返回 null,表示取不到有效值。
* @param MaxRequestNumPreSec 每秒最大请求次数。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetMaxRequestNumPreSec(const int64_t& _maxRequestNumPreSec);
/**
* 判断参数 MaxRequestNumPreSec 是否已赋值
* @return MaxRequestNumPreSec 是否已赋值
*/
bool MaxRequestNumPreSecHasBeenSet() const;
/**
* 获取创建时间。按照 ISO8601 标准表示,并且使用 UTC 时间。格式为:YYYY-MM-DDThh:mm:ssZ。
注意:此字段可能返回 null,表示取不到有效值。
* @return CreatedTime 创建时间。按照 ISO8601 标准表示,并且使用 UTC 时间。格式为:YYYY-MM-DDThh:mm:ssZ。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetCreatedTime() const;
/**
* 设置创建时间。按照 ISO8601 标准表示,并且使用 UTC 时间。格式为:YYYY-MM-DDThh:mm:ssZ。
注意:此字段可能返回 null,表示取不到有效值。
* @param CreatedTime 创建时间。按照 ISO8601 标准表示,并且使用 UTC 时间。格式为:YYYY-MM-DDThh:mm:ssZ。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetCreatedTime(const std::string& _createdTime);
/**
* 判断参数 CreatedTime 是否已赋值
* @return CreatedTime 是否已赋值
*/
bool CreatedTimeHasBeenSet() const;
/**
* 获取最后修改时间。按照 ISO8601 标准表示,并且使用 UTC 时间。格式为:YYYY-MM-DDThh:mm:ssZ。
注意:此字段可能返回 null,表示取不到有效值。
* @return ModifiedTime 最后修改时间。按照 ISO8601 标准表示,并且使用 UTC 时间。格式为:YYYY-MM-DDThh:mm:ssZ。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetModifiedTime() const;
/**
* 设置最后修改时间。按照 ISO8601 标准表示,并且使用 UTC 时间。格式为:YYYY-MM-DDThh:mm:ssZ。
注意:此字段可能返回 null,表示取不到有效值。
* @param ModifiedTime 最后修改时间。按照 ISO8601 标准表示,并且使用 UTC 时间。格式为:YYYY-MM-DDThh:mm:ssZ。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetModifiedTime(const std::string& _modifiedTime);
/**
* 判断参数 ModifiedTime 是否已赋值
* @return ModifiedTime 是否已赋值
*/
bool ModifiedTimeHasBeenSet() const;
/**
* 获取服务名称。
注意:此字段可能返回 null,表示取不到有效值。
* @return ServiceName 服务名称。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetServiceName() const;
/**
* 设置服务名称。
注意:此字段可能返回 null,表示取不到有效值。
* @param ServiceName 服务名称。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetServiceName(const std::string& _serviceName);
/**
* 判断参数 ServiceName 是否已赋值
* @return ServiceName 是否已赋值
*/
bool ServiceNameHasBeenSet() const;
private:
/**
* 绑定的服务唯一 ID。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_serviceId;
bool m_serviceIdHasBeenSet;
/**
* API 的唯一ID。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_apiId;
bool m_apiIdHasBeenSet;
/**
* API 的名称。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_apiName;
bool m_apiNameHasBeenSet;
/**
* API 的路径。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_path;
bool m_pathHasBeenSet;
/**
* API 的方法。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_method;
bool m_methodHasBeenSet;
/**
* 已经绑定的环境名称。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_environment;
bool m_environmentHasBeenSet;
/**
* 已经使用的配额。
注意:此字段可能返回 null,表示取不到有效值。
*/
int64_t m_inUseRequestNum;
bool m_inUseRequestNumHasBeenSet;
/**
* 最大请求量。
注意:此字段可能返回 null,表示取不到有效值。
*/
int64_t m_maxRequestNum;
bool m_maxRequestNumHasBeenSet;
/**
* 每秒最大请求次数。
注意:此字段可能返回 null,表示取不到有效值。
*/
int64_t m_maxRequestNumPreSec;
bool m_maxRequestNumPreSecHasBeenSet;
/**
* 创建时间。按照 ISO8601 标准表示,并且使用 UTC 时间。格式为:YYYY-MM-DDThh:mm:ssZ。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_createdTime;
bool m_createdTimeHasBeenSet;
/**
* 最后修改时间。按照 ISO8601 标准表示,并且使用 UTC 时间。格式为:YYYY-MM-DDThh:mm:ssZ。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_modifiedTime;
bool m_modifiedTimeHasBeenSet;
/**
* 服务名称。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_serviceName;
bool m_serviceNameHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_APIGATEWAY_V20180808_MODEL_USAGEPLANENVIRONMENT_H_
| 32.29803 | 116 | 0.452147 | [
"vector",
"model"
] |
6c7c7ae8e43f621abf69a2ff9736dea052208127 | 36,202 | h | C | RakMagic/raknet/rakpeerinterface.h | ezbooz/RakMagic | 045d7b08e0623ca007c43c010635f4c9c8ae0a54 | [
"MIT"
] | 11 | 2020-08-04T05:01:39.000Z | 2022-03-16T06:15:38.000Z | RakMagic/raknet/rakpeerinterface.h | ezbooz/RakMagic | 045d7b08e0623ca007c43c010635f4c9c8ae0a54 | [
"MIT"
] | 2 | 2021-03-09T10:23:52.000Z | 2022-02-08T01:51:35.000Z | RakMagic/raknet/rakpeerinterface.h | ezbooz/RakMagic | 045d7b08e0623ca007c43c010635f4c9c8ae0a54 | [
"MIT"
] | 5 | 2020-11-15T12:44:36.000Z | 2021-12-17T09:50:34.000Z | /// \file
/// \brief An interface for RakPeer. Simply contains all user functions as pure virtuals.
///
/// This file is part of RakNet Copyright 2003 Kevin Jenkins.
///
/// Usage of RakNet is subject to the appropriate license agreement.
/// Creative Commons Licensees are subject to the
/// license found at
/// http://creativecommons.org/licenses/by-nc/2.5/
/// Single application licensees are subject to the license found at
/// http://www.rakkarsoft.com/SingleApplicationLicense.html
/// Custom license users are subject to the terms therein.
/// GPL license users are subject to 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.
#ifndef __RAK_PEER_INTERFACE_H
#define __RAK_PEER_INTERFACE_H
#include "PacketPriority.h"
#include "NetworkTypes.h"
#include "Export.h"
// Forward declarations
namespace RakNet
{
class BitStream;
}
class PluginInterface;
struct RPCMap;
struct RakNetStatisticsStruct;
class RouterInterface;
/// The primary interface for RakNet, RakPeer contains all major functions for the library.
/// See the individual functions for what the class can do.
/// \brief The main interface for network communications
class RAK_DLL_EXPORT RakPeerInterface
{
public:
///Destructor
virtual ~RakPeerInterface() {}
// --------------------------------------------------------------------------------------------Major Low Level Functions - Functions needed by most users--------------------------------------------------------------------------------------------
/// \brief Starts the network threads, opens the listen port.
/// You must call this before calling Connect().
/// Multiple calls while already active are ignored. To call this function again with different settings, you must first call Disconnect().
/// \note Call SetMaximumIncomingConnections if you want to accept incoming connections
/// \param[in] maxConnections The maximum number of connections between this instance of RakPeer and another instance of RakPeer. Required so the network can preallocate and for thread safety. A pure client would set this to 1. A pure server would set it to the number of allowed clients.- A hybrid would set it to the sum of both types of connections
/// \param[in] localPort The port to listen for connections on.
/// \param[in] _threadSleepTimer How many ms to Sleep each internal update cycle (30 to give the game priority, 0 for regular (recommended), -1 to not Sleep() (may be slower))
/// \param[in] forceHostAddress Can force RakNet to use a particular IP to host on. Pass 0 to automatically pick an IP
/// \return False on failure (can't create socket or thread), true on success.
virtual bool Initialize( unsigned short maxConnections, unsigned short localPort, int _threadSleepTimer, const char *forceHostAddress=0 )=0;
/// Secures connections though a combination of SHA1, AES128, SYN Cookies, and RSA to prevent connection spoofing, replay attacks, data eavesdropping, packet tampering, and MitM attacks.
/// There is a significant amount of processing and a slight amount of bandwidth overhead for this feature.
/// If you accept connections, you must call this or else secure connections will not be enabled for incoming connections.
/// If you are connecting to another system, you can call this with values for the (e and p,q) public keys before connecting to prevent MitM
/// \pre Must be called while offline
/// \param[in] pubKeyE A pointer to the public keys from the RSACrypt class.
/// \param[in] pubKeyN A pointer to the public keys from the RSACrypt class.
/// \param[in] privKeyP Public key generated from the RSACrypt class.
/// \param[in] privKeyQ Public key generated from the RSACrypt class. If the private keys are 0, then a new key will be generated when this function is called@see the Encryption sample
virtual void InitializeSecurity(const char *pubKeyE, const char *pubKeyN, const char *privKeyP, const char *privKeyQ )=0;
/// Disables all security.
/// \note Must be called while offline
virtual void DisableSecurity( void )=0;
/// Sets how many incoming connections are allowed. If this is less than the number of players currently connected,
/// no more players will be allowed to connect. If this is greater than the maximum number of peers allowed,
/// it will be reduced to the maximum number of peers allowed. Defaults to 0.
/// \param[in] numberAllowed Maximum number of incoming connections allowed.
virtual void SetMaximumIncomingConnections( unsigned short numberAllowed )=0;
/// Returns the value passed to SetMaximumIncomingConnections()
/// \return the maximum number of incoming connections, which is always <= maxConnections
virtual unsigned short GetMaximumIncomingConnections( void ) const=0;
/// Sets the password incoming connections must match in the call to Connect (defaults to none). Pass 0 to passwordData to specify no password
/// This is a way to set a low level password for all incoming connections. To selectively reject connections, implement your own scheme using CloseConnection() to remove unwanted connections
/// \param[in] passwordData A data block that incoming connections must match. This can be just a password, or can be a stream of data. Specify 0 for no password data
/// \param[in] passwordDataLength The length in bytes of passwordData
virtual void SetIncomingPassword( const char* passwordData, int passwordDataLength )=0;
/// Gets the password passed to SetIncomingPassword
/// \param[out] passwordData Should point to a block large enough to hold the password data you passed to SetIncomingPassword()
/// \param[in,out] passwordDataLength Maximum size of the array passwordData. Modified to hold the number of bytes actually written
virtual void GetIncomingPassword( char* passwordData, int *passwordDataLength )=0;
/// \brief Connect to the specified host (ip or domain name) and server port.
/// Calling Connect and not calling SetMaximumIncomingConnections acts as a dedicated client.
/// Calling both acts as a true peer. This is a non-blocking connection.
/// You know the connection is successful when IsConnected() returns true or Receive() gets a message with the type identifier ID_CONNECTION_ACCEPTED.
/// If the connection is not successful, such as a rejected connection or no response then neither of these things will happen.
/// \pre Requires that you first call Initialize
/// \param[in] host Either a dotted IP address or a domain name
/// \param[in] remotePort Which port to connect to on the remote machine.
/// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password.
/// \param[in] passwordDataLength The length in bytes of passwordData
/// \return True on successful initiation. False on incorrect parameters, internal error, or too many existing peers. Returning true does not mean you connected!
virtual bool Connect( const char* host, unsigned short remotePort, char* passwordData, int passwordDataLength )=0;
/// \brief Stops the network threads and closes all connections.
/// \param[in] blockDuration How long you should wait for all remaining messages to go out, including ID_DISCONNECTION_NOTIFICATION. If 0, it doesn't wait at all.
/// \param[in] orderingChannel If blockDuration > 0, ID_DISCONNECTION_NOTIFICATION will be sent on this channel
/// If you set it to 0 then the disconnection notification won't be sent
virtual void Disconnect( unsigned int blockDuration, unsigned char orderingChannel=0 )=0;
/// Returns if the network thread is running
/// \return true if the network thread is running, false otherwise
virtual bool IsActive( void ) const=0;
/// Fills the array remoteSystems with the SystemID of all the systems we are connected to
/// \param[out] remoteSystems An array of PlayerID structures to be filled with the PlayerIDs of the systems we are connected to. Pass 0 to remoteSystems to only get the number of systems we are connected to
/// \param[in, out] numberOfSystems As input, the size of remoteSystems array. As output, the number of elements put into the array
virtual bool GetConnectionList( PlayerID *remoteSystems, unsigned short *numberOfSystems ) const=0;
/// Sends a block of data to the specified system that you are connected to.
/// This function only works while the connected
/// \param[in] data The block of data to send
/// \param[in] length The size in bytes of the data to send
/// \param[in] priority What priority level to send on. See PacketPriority.h
/// \param[in] reliability How reliability to send this data. See PacketPriority.h
/// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream
/// \param[in] playerId Who to send this packet to, or in the case of broadcasting who not to send it to. Use UNASSIGNED_PLAYER_ID to specify none
/// \param[in] broadcast True to send this packet to all connected systems. If true, then playerId specifies who not to send the packet to.
/// \return False if we are not connected to the specified recipient. True otherwise
virtual bool Send( const char *data, const int length, PacketPriority priority, PacketReliability reliability, char orderingChannel, PlayerID playerId, bool broadcast )=0;
/// Sends a block of data to the specified system that you are connected to. Same as the above version, but takes a BitStream as input.
/// \param[in] bitStream The bitstream to send
/// \param[in] priority What priority level to send on. See PacketPriority.h
/// \param[in] reliability How reliability to send this data. See PacketPriority.h
/// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream
/// \param[in] playerId Who to send this packet to, or in the case of broadcasting who not to send it to. Use UNASSIGNED_PLAYER_ID to specify none
/// \param[in] broadcast True to send this packet to all connected systems. If true, then playerId specifies who not to send the packet to.
/// \return False if we are not connected to the specified recipient. True otherwise
virtual bool Send( RakNet::BitStream * bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, PlayerID playerId, bool broadcast )=0;
/// Gets a message from the incoming message queue.
/// Use DeallocatePacket() to deallocate the message after you are done with it.
/// User-thread functions, such as RPC calls and the plugin function PluginInterface::Update occur here.
/// \return 0 if no packets are waiting to be handled, otherwise a pointer to a packet.
/// sa NetworkTypes.h contains struct Packet
virtual Packet* Receive( void )=0;
/// Call this to deallocate a message returned by Receive() when you are done handling it.
/// \param[in] packet The message to deallocate.
virtual void DeallocatePacket( Packet *packet )=0;
/// Return the total number of connections we are allowed
// TODO - rename for RakNet 3.0
virtual unsigned short GetMaximumNumberOfPeers( void ) const=0;
// --------------------------------------------------------------------------------------------Remote Procedure Call Functions - Functions to initialize and perform RPC--------------------------------------------------------------------------------------------
/// \ingroup RAKNET_RPC
/// Register a C or static member function as available for calling as a remote procedure call
/// \param[in] uniqueID A null-terminated unique string to identify this procedure. See RegisterClassMemberRPC() for class member functions.
/// \param[in] functionPointer(...) The name of the function to be used as a function pointer. This can be called whether active or not, and registered functions stay registered unless unregistered
virtual void RegisterAsRemoteProcedureCall( int* uniqueID, void ( *functionPointer ) ( RPCParameters *rpcParms ) )=0;
/// \ingroup RAKNET_RPC
/// Register a C++ member function as available for calling as a remote procedure call.
/// \param[in] uniqueID A null terminated string to identify this procedure. Recommended you use the macro REGISTER_CLASS_MEMBER_RPC to create the string. Use RegisterAsRemoteProcedureCall() for static functions.
/// \param[in] functionPointer The name of the function to be used as a function pointer. This can be called whether active or not, and registered functions stay registered unless unregistered with UnregisterAsRemoteProcedureCall
/// \sa The sample ObjectMemberRPC.cpp
virtual void RegisterClassMemberRPC( int* uniqueID, void *functionPointer )=0;
/// \ingroup RAKNET_RPC
/// Unregisters a C function as available for calling as a remote procedure call that was formerly registered with RegisterAsRemoteProcedureCall. Only call offline.
/// \param[in] uniqueID A string of only letters to identify this procedure. Recommended you use the macro CLASS_MEMBER_ID for class member functions.
virtual void UnregisterAsRemoteProcedureCall( int* uniqueID )=0;
/// \ingroup RAKNET_RPC
/// Calls a C function on the remote system that was already registered using RegisterAsRemoteProcedureCall().
/// \param[in] uniqueID A NULL terminated string identifying the function to call. Recommended you use the macro CLASS_MEMBER_ID for class member functions.
/// \param[in] data The data to send
/// \param[in] bitLength The number of bits of \a data
/// \param[in] priority What priority level to send on. See PacketPriority.h.
/// \param[in] reliability How reliability to send this data. See PacketPriority.h.
/// \param[in] orderingChannel When using ordered or sequenced message, what channel to order these on.
/// \param[in] playerId Who to send this message to, or in the case of broadcasting who not to send it to. Use UNASSIGNED_PLAYER_ID to specify none
/// \param[in] broadcast True to send this packet to all connected systems. If true, then playerId specifies who not to send the packet to.
/// \param[in] shiftTimestamp True to add a timestamp to your data, such that the first byte is ID_TIMESTAMP and the next sizeof(RakNetTime) is the timestamp.
/// \param[in] networkID For static functions, pass UNASSIGNED_NETWORK_ID. For member functions, you must derive from NetworkIDGenerator and pass the value returned by NetworkIDGenerator::GetNetworkID for that object.
/// \param[in] replyFromTarget If 0, this function is non-blocking. Otherwise it will block while waiting for a reply from the target procedure, which should be remotely written to RPCParameters::replyToSender and copied to replyFromTarget. The block will return early on disconnect or if the sent packet is unreliable and more than 3X the ping has elapsed.
/// \return True on a successful packet send (this does not indicate the recipient performed the call), false on failure
virtual bool RPC( int* uniqueID, const char *data, unsigned int bitLength, PacketPriority priority, PacketReliability reliability, char orderingChannel, PlayerID playerId, bool broadcast, bool shiftTimestamp, NetworkID networkID, RakNet::BitStream *replyFromTarget )=0;
/// \ingroup RAKNET_RPC
/// Calls a C function on the remote system that was already registered using RegisterAsRemoteProcedureCall.
/// If you want that function to return data you should call RPC from that system in the same wayReturns true on a successful packet
/// send (this does not indicate the recipient performed the call), false on failure
/// \param[in] uniqueID A NULL terminated string identifying the function to call. Recommended you use the macro CLASS_MEMBER_ID for class member functions.
/// \param[in] data The data to send
/// \param[in] bitLength The number of bits of \a data
/// \param[in] priority What priority level to send on. See PacketPriority.h.
/// \param[in] reliability How reliability to send this data. See PacketPriority.h.
/// \param[in] orderingChannel When using ordered or sequenced message, what channel to order these on.
/// \param[in] playerId Who to send this message to, or in the case of broadcasting who not to send it to. Use UNASSIGNED_PLAYER_ID to specify none
/// \param[in] broadcast True to send this packet to all connected systems. If true, then playerId specifies who not to send the packet to.
/// \param[in] shiftTimestamp True to add a timestamp to your data, such that the first byte is ID_TIMESTAMP and the next sizeof(RakNetTime) is the timestamp.
/// \param[in] networkID For static functions, pass UNASSIGNED_NETWORK_ID. For member functions, you must derive from NetworkIDGenerator and pass the value returned by NetworkIDGenerator::GetNetworkID for that object.
/// \param[in] replyFromTarget If 0, this function is non-blocking. Otherwise it will block while waiting for a reply from the target procedure, which should be remotely written to RPCParameters::replyToSender and copied to replyFromTarget. The block will return early on disconnect or if the sent packet is unreliable and more than 3X the ping has elapsed.
/// \return True on a successful packet send (this does not indicate the recipient performed the call), false on failure
virtual bool RPC( int* uniqueID, RakNet::BitStream *bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, PlayerID playerId, bool broadcast, bool shiftTimestamp, NetworkID networkID, RakNet::BitStream *replyFromTarget )=0;
// -------------------------------------------------------------------------------------------- Connection Management Functions--------------------------------------------------------------------------------------------
/// Close the connection to another host (if we initiated the connection it will disconnect, if they did it will kick them out).
/// \param[in] target Which system to close the connection to.
/// \param[in] sendDisconnectionNotification True to send ID_DISCONNECTION_NOTIFICATION to the recipient. False to close it silently.
/// \param[in] channel Which ordering channel to send the disconnection notification on, if any
virtual void CloseConnection( const PlayerID target, bool sendDisconnectionNotification, unsigned char orderingChannel=0 )=0;
/// Given a playerID, returns an index from 0 to the maximum number of players allowed - 1.
/// \param[in] playerId The PlayerID we are referring to
/// \return The index of this PlayerID or -1 on system not found.
virtual int GetIndexFromPlayerID( const PlayerID playerId )=0;
/// This function is only useful for looping through all systems
/// Given an index, will return a PlayerID.
/// \param[in] index Index should range between 0 and the maximum number of players allowed - 1.
/// \return The PlayerID
virtual PlayerID GetPlayerIDFromIndex( int index )=0;
/// Bans an IP from connecting. Banned IPs persist between connections but are not saved on shutdown nor loaded on startup.
/// param[in] IP Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will ban all IP addresses starting with 128.0.0
/// \param[in] milliseconds how many ms for a temporary ban. Use 0 for a permanent ban
virtual void AddToBanList( const char *IP, RakNetTime milliseconds=0 )=0;
/// Allows a previously banned IP to connect.
/// param[in] Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will banAll IP addresses starting with 128.0.0
virtual void RemoveFromBanList( const char *IP )=0;
/// Allows all previously banned IPs to connect.
virtual void ClearBanList( void )=0;
/// Returns true or false indicating if a particular IP is banned.
/// \param[in] IP - Dotted IP address.
/// \return true if IP matches any IPs in the ban list, accounting for any wildcards. False otherwise.
virtual bool IsBanned( const char *IP )=0;
// --------------------------------------------------------------------------------------------Pinging Functions - Functions dealing with the automatic ping mechanism--------------------------------------------------------------------------------------------
/// Send a ping to the specified connected system.
/// \pre The sender and recipient must already be started via a successful call to Initialize()
/// \param[in] target Which system to ping
virtual void Ping( const PlayerID target )=0;
/// Send a ping to the specified unconnected system. The remote system, if it is Initialized, will respond with ID_PONG. The final ping time will be encoded in the following sizeof(RakNetTime) bytes. (Default is 4 bytes - See __GET_TIME_64BIT in NetworkTypes.h
/// \param[in] host Either a dotted IP address or a domain name. Can be 255.255.255.255 for LAN broadcast.
/// \param[in] remotePort Which port to connect to on the remote machine.
/// \param[in] onlyReplyOnAcceptingConnections Only request a reply if the remote system is accepting connections
virtual void Ping( const char* host, unsigned short remotePort, bool onlyReplyOnAcceptingConnections )=0;
/// Returns the average of all ping times read for the specific system or -1 if none read yet
/// \param[in] playerId Which system we are referring to
/// \return The ping time for this system, or -1
virtual int GetAveragePing( const PlayerID playerId )=0;
/// Returns the last ping time read for the specific system or -1 if none read yet
/// \param[in] playerId Which system we are referring to
/// \return The last ping time for this system, or -1
virtual int GetLastPing( const PlayerID playerId ) const=0;
/// Returns the lowest ping time read or -1 if none read yet
/// \param[in] playerId Which system we are referring to
/// \return The lowest ping time for this system, or -1
virtual int GetLowestPing( const PlayerID playerId ) const=0;
/// Ping the remote systems every so often, or not. This is off by default. Can be called anytime.
/// \param[in] doPing True to start occasional pings. False to stop them.
virtual void SetOccasionalPing( bool doPing )=0;
// --------------------------------------------------------------------------------------------Static Data Functions - Functions dealing with API defined synchronized memory--------------------------------------------------------------------------------------------
/// All systems have a block of data associated with them, for user use. This block of data can be used to easily
/// specify typical system data that you want to know on connection, such as the player's name.
/// \param[in] playerId Which system you are referring to. Pass the value returned by GetInternalID to refer to yourself
/// \return The data passed to SetRemoteStaticData stored as a bitstream
virtual RakNet::BitStream * GetRemoteStaticData( const PlayerID playerId )=0;
/// All systems have a block of data associated with them, for user use. This block of data can be used to easily
/// specify typical system data that you want to know on connection, such as the player's name.
/// \param[in] playerId Whose static data to change. Use your own playerId to change your own static data
/// \param[in] data a block of data to store
/// \param[in] length The length of data in bytes
virtual void SetRemoteStaticData( const PlayerID playerId, const char *data, const int length )=0;
/// Sends your static data to the specified system. This is automatically done on connection.
/// You should call this when you change your static data.To send the static data of another system (such as relaying their data) you should do this
/// normally with Send)
/// \param[in] target Who to send your static data to. Specify UNASSIGNED_PLAYER_ID to broadcast to all
virtual void SendStaticData( const PlayerID target )=0;
/// Sets the data to send along with a LAN server discovery or offline ping reply.
/// \a length should be under 400 bytes, as a security measure against flood attacks
/// \param[in] data a block of data to store, or 0 for none
/// \param[in] length The length of data in bytes, or 0 for none
/// \sa Ping.cpp
virtual void SetOfflinePingResponse( const char *data, const unsigned int length )=0;
//--------------------------------------------------------------------------------------------Network Functions - Functions dealing with the network in general--------------------------------------------------------------------------------------------
/// Return the unique address identifier that represents you on the the network and is based on your local IP / port.
/// \return the identifier of your system internally, which may not be how other systems see if you if you are behind a NAT or proxy
virtual PlayerID GetInternalID( void ) const=0;
/// Return the unique address identifier that represents you on the the network and is based on your externalIP / port
/// (the IP / port the specified player uses to communicate with you)
/// \param[in] target Which remote system you are referring to for your external ID. Usually the same for all systems, unless you have two or more network cards.
virtual PlayerID GetExternalID( const PlayerID target ) const=0;
/// Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable message.
/// Default time is 10,000 or 10 seconds in release and 30,000 or 30 seconds in debug.
/// \param[in] timeMS Time, in MS
/// \param[in] target Which system to do this for
virtual void SetTimeoutTime( RakNetTime timeMS, const PlayerID target )=0;
/// Set the MTU per datagram. It's important to set this correctly - otherwise packets will be needlessly split, decreasing performance and throughput.
/// Maximum allowed size is MAXIMUM_MTU_SIZE.
/// Too high of a value will cause packets not to arrive at worst and be fragmented at best.
/// Too low of a value will split packets unnecessarily.
/// Recommended size is 1500
/// sa MTUSize.h
/// \pre Can only be called when not connected.
/// \return false on failure (we are connected), else true
virtual bool SetMTUSize( int size )=0;
/// Returns the current MTU size
/// \return The current MTU size
virtual int GetMTUSize( void ) const=0;
/// Returns the number of IP addresses this system has internally. Get the actual addresses from GetLocalIP()
virtual unsigned GetNumberOfAddresses( void )=0;
/// Returns an IP address at index 0 to GetNumberOfAddresses-1
virtual const char* GetLocalIP( unsigned int index )=0;
/// TODO - depreciate this
/// Returns the dotted IP address for the specified playerId
/// \param[in] playerId Any player ID other than UNASSIGNED_PLAYER_ID, even if that player is not currently connected
virtual const char* PlayerIDToDottedIP( const PlayerID playerId ) const=0;
// TODO - depreciate this
/// Converts a dotted IP to a playerId
/// \param[in] host Either a dotted IP address or a domain name
/// \param[in] remotePort Which port to connect to on the remote machine.
/// \param[out] playerId The result of this operation
virtual void IPToPlayerID( const char* host, unsigned short remotePort, PlayerID *playerId )=0;
/// Allow or disallow connection responses from any IP. Normally this should be false, but may be necessary
/// when connecting to servers with multiple IP addresses.
/// \param[in] allow - True to allow this behavior, false to not allow. Defaults to false. Value persists between connections
virtual void AllowConnectionResponseIPMigration( bool allow )=0;
/// Sends a one byte message ID_ADVERTISE_SYSTEM to the remote unconnected system.
/// This will tell the remote system our external IP outside the LAN along with some user data.
/// \pre The sender and recipient must already be started via a successful call to Initialize
/// \param[in] host Either a dotted IP address or a domain name
/// \param[in] remotePort Which port to connect to on the remote machine.
/// \param[in] data Optional data to append to the packet.
/// \param[in] dataLength length of data in bytes. Use 0 if no data.
virtual void AdvertiseSystem( const char *host, unsigned short remotePort, const char *data, int dataLength )=0;
/// Controls how often to return ID_DOWNLOAD_PROGRESS for large message downloads.
/// ID_DOWNLOAD_PROGRESS is returned to indicate a new partial message chunk, roughly the MTU size, has arrived
/// As it can be slow or cumbersome to get this notification for every chunk, you can set the interval at which it is returned.
/// Defaults to 0 (never return this notification)
/// \param[in] interval How many messages to use as an interval
virtual void SetSplitMessageProgressInterval(int interval)=0;
/// Set how long to wait before giving up on sending an unreliable message
/// Useful if the network is clogged up.
/// Set to 0 or less to never timeout. Defaults to 0.
/// \param[in] timeoutMS How many ms to wait before simply not sending an unreliable message.
virtual void SetUnreliableTimeout(RakNetTime timeoutMS)=0;
// --------------------------------------------------------------------------------------------Compression Functions - Functions related to the compression layer--------------------------------------------------------------------------------------------
/// Enables or disables frequency table tracking. This is required to get a frequency table, which is used in GenerateCompressionLayer()
/// This value persists between connect calls and defaults to false (no frequency tracking)
/// \pre You can call this at any time - however you SHOULD only call it when disconnected. Otherwise you will only trackpart of the values sent over the network.
/// \param[in] doCompile True to enable tracking
virtual void SetCompileFrequencyTable( bool doCompile )=0;
/// Returns the frequency of outgoing bytes into output frequency table
/// The purpose is to save to file as either a master frequency table from a sample game session for passing to
/// GenerateCompressionLayer()
/// \pre You should only call this when disconnected. Requires that you first enable data frequency tracking by calling SetCompileFrequencyTable(true)
/// \param[out] outputFrequencyTable The frequency of each corresponding byte
/// \return False (failure) if connected or if frequency table tracking is not enabled. Otherwise true (success)
virtual bool GetOutgoingFrequencyTable( unsigned int outputFrequencyTable[ 256 ] )=0;
/// This is an optional function to generate the compression layer based on the input frequency table.
/// If you want to use it you should call this twice - once with inputLayer as true and once as false.
/// The frequency table passed here with inputLayer=true should match the frequency table on the recipient with inputLayer=false.
/// Likewise, the frequency table passed here with inputLayer=false should match the frequency table on the recipient with inputLayer=true.
/// Calling this function when there is an existing layer will overwrite the old layer.
/// \pre You should only call this when disconnected
/// \param[in] inputFrequencyTable A frequency table for your data
/// \param[in] inputLayer Is this the input layer?
/// \return false (failure) if connected. Otherwise true (success)
/// \sa Compression.cpp
virtual bool GenerateCompressionLayer( unsigned int inputFrequencyTable[ 256 ], bool inputLayer )=0;
/// Delete the output or input layer as specified. This is not necessary to call and is only valuable for freeing memory.
/// \pre You should only call this when disconnected
/// \param[in] inputLayer True to mean the inputLayer, false to mean the output layer
/// \return false (failure) if connected. Otherwise true (success)
virtual bool DeleteCompressionLayer( bool inputLayer )=0;
/// Returns the compression ratio. A low compression ratio is good. Compression is for outgoing data
/// \return The compression ratio
virtual float GetCompressionRatio( void ) const=0;
///Returns the decompression ratio. A high decompression ratio is good. Decompression is for incoming data
/// \return The decompression ratio
virtual float GetDecompressionRatio( void ) const=0;
// -------------------------------------------------------------------------------------------- Plugin Functions--------------------------------------------------------------------------------------------
/// Attatches a Plugin interface to run code automatically on message receipt in the Receive call
/// \note If plugins have dependencies on each other then the order does matter - for example the router plugin should go first because it might route messages for other plugins
/// \param[in] messageHandler Pointer to a plugin to attach
virtual void AttachPlugin( PluginInterface *plugin )=0;
/// Detaches a Plugin interface to run code automatically on message receipt
/// \param[in] messageHandler Pointer to a plugin to detach
virtual void DetachPlugin( PluginInterface *messageHandler )=0;
// --------------------------------------------------------------------------------------------Miscellaneous Functions--------------------------------------------------------------------------------------------
/// Put a message back at the end of the receive queue in case you don't want to deal with it immediately
/// \param[in] packet The packet you want to push back.
/// \param[in] pushAtHead True to push the packet so that the next receive call returns it. False to push it at the end of the queue (obviously pushing it at the end makes the packets out of order)
virtual void PushBackPacket( Packet *packet, bool pushAtHead )=0;
/// \Internal
// \param[in] routerInterface The router to use to route messages to systems not directly connected to this system.
virtual void SetRouterInterface( RouterInterface *routerInterface )=0;
/// \Internal
// \param[in] routerInterface The router to use to route messages to systems not directly connected to this system.
virtual void RemoveRouterInterface( RouterInterface *routerInterface )=0;
// --------------------------------------------------------------------------------------------Network Simulator Functions--------------------------------------------------------------------------------------------
/// Adds simulated ping and packet loss to the outgoing data flow.
/// To simulate bi-directional ping and packet loss, you should call this on both the sender and the recipient, with half the total ping and maxSendBPS value on each.
/// You can exclude network simulator code with the _RELEASE #define to decrease code size
/// \param[in] maxSendBPS Maximum bits per second to send. Packetloss grows linearly. 0 to disable.
/// \param[in] minExtraPing The minimum time to delay sends.
/// \param[in] extraPingVariance The additional random time to delay sends.
virtual void ApplyNetworkSimulator( double maxSendBPS, unsigned short minExtraPing, unsigned short extraPingVariance)=0;
/// Returns if you previously called ApplyNetworkSimulator
/// \return If you previously called ApplyNetworkSimulator
virtual bool IsNetworkSimulatorActive( void )=0;
// --------------------------------------------------------------------------------------------Statistical Functions - Functions dealing with API performance--------------------------------------------------------------------------------------------
/// Returns a structure containing a large set of network statistics for the specified system.
/// You can map this data to a string using the C style StatisticsToString() function
/// \param[in] playerId: Which connected system to get statistics for
/// \return 0 on can't find the specified system. A pointer to a set of data otherwise.
/// \sa RakNetStatistics.h
virtual RakNetStatisticsStruct * const GetStatistics( const PlayerID playerId )=0;
// --------------------------------------------------------------------------------------------EVERYTHING AFTER THIS COMMENT IS FOR INTERNAL USE ONLY--------------------------------------------------------------------------------------------
/// \internal
virtual RPCMap *GetRPCMap( const PlayerID playerId)=0;
};
#endif
| 76.536998 | 360 | 0.719822 | [
"object"
] |
6c87655611322da4c14e9be0da172b90abe43710 | 7,679 | h | C | copasi/core/CDataObject.h | tobiaselsaesser/COPASI | 7e61c1b1667b0f4acf8f3865fe557603f221c472 | [
"Artistic-2.0"
] | null | null | null | copasi/core/CDataObject.h | tobiaselsaesser/COPASI | 7e61c1b1667b0f4acf8f3865fe557603f221c472 | [
"Artistic-2.0"
] | null | null | null | copasi/core/CDataObject.h | tobiaselsaesser/COPASI | 7e61c1b1667b0f4acf8f3865fe557603f221c472 | [
"Artistic-2.0"
] | null | null | null | // Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.
/**
* Class CDataObject
*
* This class is the base class for all global accessible objects in COPASI.
*
* Copyright Stefan Hoops 2002
*/
#ifndef COPASI_CDataObject
#define COPASI_CDataObject
#define NO_PARENT static_cast< CDataContainer * >((void *) 0)
#define INHERIT_PARENT static_cast< CDataContainer * >((void *) -1)
#include <string>
#include <list>
#include "copasi/core/CObjectInterface.h"
#include "copasi/core/CFlags.h"
#include "copasi/undo/CUndoObjectInterface.h"
#include "copasi/utilities/CValidity.h"
class CDataObject;
class CDataContainer;
class CModel;
class CDataModel;
class CUnit;
template <class CType> class CDataObjectReference;
//********************************************************************************
class CDataObject: public CObjectInterface, public CUndoObjectInterface
{
public:
typedef std::set< const CDataObject * > DataObjectSet;
enum Flag
{
Container,
Vector,
Matrix,
NameVector,
Reference,
ValueBool,
ValueInt,
ValueInt64,
ValueDbl,
NonUniqueName,
StaticString,
ValueString,
Separator,
DisplayName,
ModelEntity,
Array,
DataModel,
Root,
Gui,
__SIZE
};
protected:
//Operations
CDataObject();
CDataObject(const std::string & name,
const CDataContainer * pParent = NO_PARENT,
const std::string & type = "CN",
const CFlags< Flag > & flag = CFlags< Flag >::None);
public:
/**
* Static method to create a CDataObject based on the provided data
* @param const CData & data
* @return CDataObject * pDataObject
*/
static CDataObject * fromData(const CData & data, CUndoObjectInterface * pParent);
/**
* Destruct the object
*/
virtual void destruct();
/**
* Retrieve the data describing the object
* @return CData data
*/
virtual CData toData() const;
/**
* Apply the provided data to the object
* @param const CData & data
* @return bool success
*/
virtual bool applyData(const CData & data, CUndoData::ChangeSet & changes);
/**
* Create the undo data which represents the changes recording the
* differences between the provided oldData and the current data.
* @param CUndoData & undoData
* @param const CUndoData::Type & type
* @param const CData & oldData (default: empty data)
* @param const CCore::Framework & framework (default: CCore::Framework::ParticleNumbers)
* @return CUndoData undoData
*/
virtual void createUndoData(CUndoData & undoData,
const CUndoData::Type & type,
const CData & oldData = CData(),
const CCore::Framework & framework = CCore::Framework::ParticleNumbers) const;
static void sanitizeObjectName(std::string & name);
CDataObject(const CDataObject & src,
const CDataContainer * pParent = NULL);
virtual ~CDataObject();
/**
* Calculate the objects value.
*/
virtual void calculateValue();
/**
* Retrieve the CN of the object
* @return CCommonName
*/
virtual CCommonName getCN() const;
/**
* Retrieve a descendant object by its CN.
* @param const CCommonName & cn
* @return const CObjectInterface * pObject
*/
virtual const CObjectInterface * getObject(const CCommonName & cn) const;
/**
* Retrieve the prerequisites, i.e., the objects which need to be evaluated
* before this.
* @return const CObjectInterface::ObjectSet & prerequisites
*/
virtual const CObjectInterface::ObjectSet & getPrerequisites() const;
/**
* Check whether a given object is a prerequisite for a context.
* @param const CObjectInterface * pObject
* @param const CCore::SimulationContextFlag & context
* @param const CObjectInterface::ObjectSet & changedObjects
* @return bool isPrerequisiteForContext
*/
virtual bool isPrerequisiteForContext(const CObjectInterface * pObject,
const CCore::SimulationContextFlag & context,
const CObjectInterface::ObjectSet & changedObjects) const;
/**
* This is the output method for any object. The default implementation
* provided with CDataObject uses the ostream operator<< of the object
* to print the object.To override this default behavior one needs to
* reimplement the virtual print function.
* @param std::ostream * ostream
*/
virtual void print(std::ostream * ostream) const;
/**
* Retrieve a pointer to the value of the object
*/
virtual void * getValuePointer() const;
/**
* Retrieve a pointer to the data object
* @return const DATA_OBJECT * dataObject
*/
virtual const CDataObject * getDataObject() const;
/**
* Retrieve the display name of the object
* @param bool regular (default: true)
* @param bool richtext (default: false)
* @return std::string objectDisplayName
*/
virtual std::string getObjectDisplayName() const;
/**
* Get the aggregation of any issues associated with this object
* @return const CValidity & validity
*/
virtual const CValidity & getValidity() const;
/**
* This method is called whenever the validity of the object or a contained object changes.
* @param const CValidity & changedValidity
*/
void validityChanged(const CValidity & changedValidity);
/**
* This method is called whenever the validity of a contained object is removed.
* @param const CValidity & changedValidity
*/
void validityRemoved(const CValidity & changedValidity);
/**
* Set the name of the object.
* Note: An attempt set the name to "" results in the name
* being set to "No Name".
* @param const std::string & name
* @return success
*/
bool setObjectName(const std::string & name);
const std::string & getObjectName() const;
const std::string & getObjectType() const;
virtual bool setObjectParent(const CDataContainer * pParent);
CDataContainer * getObjectParent() const;
void addReference(const CDataContainer * pReference);
void removeReference(const CDataContainer * pReference);
/**
* Returns a pointer to the CDataModel the element belongs to.
* If there is no instance of CDataModel in the ancestor tree, NULL
* is returned.
*/
CDataModel* getObjectDataModel() const;
CDataContainer * getObjectAncestor(const std::string & type) const;
bool prerequisitsContains(const DataObjectSet & objects) const;
/**
* Retrieve the units of the object.
* @return std::string units
*/
virtual const std::string getUnits() const;
bool hasFlag(const Flag & flag) const;
virtual const CDataObject * getValueObject() const;
friend std::ostream &operator<<(std::ostream &os, const CDataObject & o);
virtual const std::string & getKey() const;
const CObjectInterface * getObjectFromCN(const CCommonName & cn) const;
void addIssue(const CIssue & issue);
void removeIssue(const CIssue & issue);
private:
void refreshAggregateValidity();
std::string mObjectName;
std::string mObjectType;
CDataContainer * mpObjectParent;
mutable std::string mObjectDisplayName;
mutable CDataObjectReference< std::string > * mpObjectDisplayName;
CFlags< Flag > mObjectFlag;
std::set< const CValidity * > mReferencedValidities;
CValidity mAggregateValidity;
protected:
std::set< CDataContainer * > mReferences;
ObjectSet mPrerequisits;
};
#endif // COPASI_CDataObject
| 27.425 | 108 | 0.68186 | [
"object",
"vector"
] |
6c88d172b59dde4ce34618b210eeddf2efa3591e | 1,068 | h | C | DEM/Game/src/AI/SmartObj/Actions/ActionUseSmartObj.h | niello/deusexmachina | 2f698054fe82d8b40a0a0e58b86d64ffed0de06c | [
"MIT"
] | 15 | 2019-05-07T11:26:13.000Z | 2022-01-12T18:26:45.000Z | DEM/Game/src/AI/SmartObj/Actions/ActionUseSmartObj.h | niello/deusexmachina | 2f698054fe82d8b40a0a0e58b86d64ffed0de06c | [
"MIT"
] | 16 | 2021-10-04T17:15:31.000Z | 2022-03-20T09:34:29.000Z | DEM/Game/src/AI/SmartObj/Actions/ActionUseSmartObj.h | niello/deusexmachina | 2f698054fe82d8b40a0a0e58b86d64ffed0de06c | [
"MIT"
] | 2 | 2019-04-28T23:27:48.000Z | 2019-05-07T11:26:18.000Z | #pragma once
#include <AI/Behaviour/Action.h>
#include <Data/StringID.h>
// Performs action on smart object.
// Custom Use actions are highly extendable and flexible, allowing designers to implement
// any specific logic without touching C++. All setup is done with params and scripts.
namespace Prop
{
class CPropSmartObject;
}
namespace AI
{
class CActionUseSmartObj: public CAction
{
FACTORY_CLASS_DECL;
private:
CStrID TargetID;
CStrID ActionID;
float Duration;
float Progress;
bool WasDone;
UPTR SetDone(CActor* pActor, Prop::CPropSmartObject* pSO, const class CSmartAction& ActTpl);
public:
void Init(CStrID Target, CStrID Action) { TargetID = Target; ActionID = Action; }
virtual bool Activate(CActor* pActor);
virtual UPTR Update(CActor* pActor);
virtual void Deactivate(CActor* pActor);
virtual bool IsValid(CActor* pActor) const;
//virtual void GetDebugString(std::string& Out) const { Out.Format("%s(%s, %s)", GetClassName().CStr(), TargetID.CStr(), ActionID.CStr()); }
};
typedef Ptr<CActionUseSmartObj> PActionUseSmartObj;
}
| 23.733333 | 141 | 0.75 | [
"object"
] |
6c896f0e57a1b9c203fd3525479522d3fbe377dc | 14,256 | h | C | src/appleseed/foundation/utility/iesparser.h | oktomus/appleseed | 067d2ed3483d97ed58058efbe418299e9dc8ca4f | [
"MIT"
] | 1,907 | 2015-01-04T00:13:22.000Z | 2022-03-30T15:14:00.000Z | src/appleseed/foundation/utility/iesparser.h | oktomus/appleseed | 067d2ed3483d97ed58058efbe418299e9dc8ca4f | [
"MIT"
] | 1,196 | 2015-01-04T10:50:01.000Z | 2022-03-04T09:18:22.000Z | src/appleseed/foundation/utility/iesparser.h | oktomus/appleseed | 067d2ed3483d97ed58058efbe418299e9dc8ca4f | [
"MIT"
] | 373 | 2015-01-06T10:08:53.000Z | 2022-03-12T10:25:57.000Z |
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2017-2018 Artem Bishev, 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.
//
#pragma once
// appleseed.foundation headers.
#include "foundation/core/exceptions/exception.h"
#include "foundation/string/string.h"
#include "foundation/utility/test.h"
// Boost headers.
#include "boost/algorithm/string.hpp"
// Standard headers.
#include <string>
#include <unordered_map>
#include <vector>
DECLARE_TEST_CASE(Foundation_Utility_Iesparser, ParseFormat);
DECLARE_TEST_CASE(Foundation_Utility_Iesparser, ReadLine_IgnoreEmptyLines);
DECLARE_TEST_CASE(Foundation_Utility_Iesparser, ReadLine_DoNotIgnoreEmptyLines);
DECLARE_TEST_CASE(Foundation_Utility_Iesparser, CheckEmpty);
DECLARE_TEST_CASE(Foundation_Utility_Iesparser, ParseKeywords);
DECLARE_TEST_CASE(Foundation_Utility_Iesparser, ParseToVector_Empty);
DECLARE_TEST_CASE(Foundation_Utility_Iesparser, ParseToVector_Good);
DECLARE_TEST_CASE(Foundation_Utility_Iesparser, ParseToVector_Bad);
namespace foundation
{
//
// Class for parsing IESNA LM-63 Photometric Data File
// and storing its contents.
//
class IESParser
{
public:
// Constructor.
IESParser();
// Exception that can store erroneous line number.
class Exception
: public foundation::Exception
{
public:
Exception(const char* message, const int line);
virtual int line() const
{
return m_line_number;
}
protected:
int m_line_number;
};
// Exception thrown when file format violates the IES specifications.
class ParsingException : public Exception
{
public:
ParsingException(const char* message, int line)
: Exception(message, line)
{
}
};
// Exception thrown when the feature of IES file is not supported by this parser.
class NotSupportedException : public Exception
{
public:
NotSupportedException(const char* message, int line)
: Exception(message, line)
{
}
};
// Dictionary containing IES file keywords and corresponding values.
typedef std::unordered_map<std::string, std::string> KeywordsDictionary;
// Type of IES file format.
enum Format
{
UnknownFormat,
Format1986,
Format1991,
Format1995,
Format2002,
};
// How TILT information is specified in the file.
enum TiltSpecification
{
IncludeTilt, // TILT is included in this IES file
TiltFromFile, // TILT is specified in the separate file
NoTilt // the lamp output does not vary as a function
// of the luminaire tilt angle (and TILT is not specified)
};
// Lamp-to-luminaire geometry types.
// For more information, see the IESNA LM-63 specifications
enum LampToLuminaireGeometry
{
GeometryNotSpecified,
VerticalGeometry,
HorizontalInvariantGeometry,
HorizontalNonInvariantGeometry
};
// Photometric types.
enum PhotometricType
{
PhotometricTypeNotSpecified,
PhotometricTypeC,
PhotometricTypeB,
PhotometricTypeA
};
// Types of symmetry that candela values have with respect to horziontal angle
enum SymmetryType
{
NoSymmetry,
SymmetricHalvesX, // bilaterally symmetric about the 0-180 degree axis
SymmetricHalvesY, // bilaterally symmetric about the 90-270 degree axis
SymmetricQuadrants, // symmetric in each quadrant
FullySymmetric // full rotational symmetry
};
// Shape of luminous opening.
struct LuminousOpeningShape
{
enum UnitsType
{
Feet,
Meters
};
UnitsType m_units_type;
double m_width;
double m_length;
double m_height;
};
typedef std::vector<std::vector<double>> PhotometricGrid;
//
// Options.
//
bool m_ignore_allowed_keywords; // if true, all keywors are allowed not depending on format version
bool m_ignore_required_keywords; // if true, some required keywors can be missing
bool m_ignore_empty_lines; // if true, than the file can contain whitespace lines
bool m_ignore_tilt; // if true, TILT section is not parsed
//
// Main methods.
//
// Parse input stream containing IESNA LM-63 Photometric Data.
void parse(std::istream& input_stream);
// Check if the keyword is allowed by IESNA LM-63-2002 standard.
static bool is_keyword_allowed_by_iesna02(const std::string& keyword);
// Check if the keyword is allowed by IESNA LM-63-95 standard.
static bool is_keyword_allowed_by_iesna95(const std::string& keyword);
// Check if the keyword is allowed by IESNA LM-63-91 standard.
static bool is_keyword_allowed_by_iesna91(const std::string& keyword);
//
// Getters.
//
Format get_format() const
{
return m_format;
}
LampToLuminaireGeometry get_lamp_to_luminaire_geometry() const
{
return m_lamp_to_luminaire_geometry;
}
const std::vector<double>& get_tilt_angles() const
{
return m_tilt_angles;
}
const std::vector<double>& get_tilt_multiplying_factors() const
{
return m_tilt_multiplying_factors;
}
int get_number_of_lamps() const
{
return m_number_of_lamps;
}
double get_lumens_per_lamp() const
{
return m_lumens_per_lamp;
}
bool is_absolute_photometry() const
{
return m_absolute_photometry;
}
double get_candela_multiplier() const
{
return m_candela_multiplier;
}
int get_number_of_vertical_angles() const
{
return m_number_of_vertical_angles;
}
int get_number_of_horizontal_angles() const
{
return m_number_of_horizontal_angles;
}
PhotometricType get_photometric_type() const
{
return m_photometric_type;
}
const LuminousOpeningShape& get_luminous_opening() const
{
return m_luminous_opening;
}
double get_ballast_factor() const
{
return m_ballast_factor;
}
double get_ballast_lamp_photometric_factor() const
{
return m_ballast_lamp_photometric_factor;
}
double get_input_watts() const
{
return m_input_watts;
}
SymmetryType get_symmetry() const
{
return m_symmetry;
}
const std::vector<double>& get_vertical_angles() const
{
return m_vertical_angles;
}
const std::vector<double>& get_horizontal_angles() const
{
return m_horizontal_angles;
}
const PhotometricGrid& get_candela_values() const
{
return m_candela_values;
}
const KeywordsDictionary& get_keywords_dictionary() const
{
return m_keywords_dictionary;
}
const std::string& get_keyword_value(const std::string& keyword) const
{
return m_keywords_dictionary.at(keyword);
}
private:
GRANT_ACCESS_TO_TEST_CASE(Foundation_Utility_Iesparser, ParseFormat);
GRANT_ACCESS_TO_TEST_CASE(Foundation_Utility_Iesparser, ReadLine_IgnoreEmptyLines);
GRANT_ACCESS_TO_TEST_CASE(Foundation_Utility_Iesparser, ReadLine_DoNotIgnoreEmptyLines);
GRANT_ACCESS_TO_TEST_CASE(Foundation_Utility_Iesparser, CheckEmpty);
GRANT_ACCESS_TO_TEST_CASE(Foundation_Utility_Iesparser, ParseKeywords);
GRANT_ACCESS_TO_TEST_CASE(Foundation_Utility_Iesparser, ParseToVector_Empty);
GRANT_ACCESS_TO_TEST_CASE(Foundation_Utility_Iesparser, ParseToVector_Good);
GRANT_ACCESS_TO_TEST_CASE(Foundation_Utility_Iesparser, ParseToVector_Bad);
static const char* const KeywordLineRegex;
static const char* const TiltLineRegex;
// Reset parser.
void reset(std::istream& input_stream);
// Read line and increase the counter.
void read_line(std::istream& input_stream);
// Read line, trim it and increase the counter.
// When ignore_empty_lines set to true this method
// ignores all lines consisting of whitespace characters.
void read_trimmed_line(std::istream& input_stream);
// Retrieve format version.
// LM_63_1986 is set if this line is not one of supported version strings.
void parse_format_version(std::istream& input_stream);
// Parse all data before TILT=<...> line
// and store keywords and corresponding values.
void parse_keywords_and_tilt(std::istream& input_stream);
// Parse TILT section.
void parse_tilt_data(std::istream& input_stream);
// Parse all photometric data after the TILT section
void parse_photometric_data(std::istream& input_stream);
void parse_angles(std::istream& input_stream);
void parse_candela_values(std::istream& input_stream);
// Check if the line defines a valid keyword-value pair.
static bool is_keyword_line(const std::string& line);
// Check if the line is a valid TILT=<...> line.
static bool is_tilt_line(const std::string& line);
// Parse the line containing keyword-value pair
// and store this pair in the dictionary.
void parse_keyword_line(const std::string& line);
// Parse TILT=<...> line.
void parse_tilt_line(const std::string& line);
// Process BLOCK and ENDBLOCK keywords.
void process_block_keyword(const std::string& keyword);
// Check if the specified standard allows this keyword.
void accept_keyword(const std::string& keyword);
// Check if all required keywords were found.
void check_required_keywords() const;
void check_iesna02_required_keywords() const;
void check_iesna91_required_keywords() const;
// Check if line is not empty and EOF is not reached.
void check_empty(std::istream& input_stream) const;
// Read lines, split each line and write the values to the vector,
// until the total number of values does not exceed the specified size.
// If number of values in the last parsed line it too large, raise a ParsingException.
// Can also raise a boost::bad_cast exception, when a token cannot be converted
// to the value of specified type.
template <typename ValueType>
std::vector<ValueType> parse_to_vector(std::istream& input_stream, size_t count)
{
std::vector<ValueType> output;
output.reserve(count);
while (output.size() < count)
{
check_empty(input_stream);
std::vector<std::string> tokens;
boost::split(tokens, m_line, isspace, boost::token_compress_on);
if (output.size() + tokens.size() > count)
{
const std::string expected_number_of_values = to_string(count - output.size());
static const char* ErrorMsg = "Too many values in the line, expected {0}";
throw ParsingException(
format(ErrorMsg, expected_number_of_values).c_str(), m_line_counter);
}
for (const std::string& token : tokens)
output.push_back(from_string<ValueType>(token));
read_trimmed_line(input_stream);
}
return output;
}
//
// All information retrieved from file:
//
// File format.
Format m_format;
// TILT specification.
TiltSpecification m_tilt_specification;
std::string m_tilt_specification_filename;
// TILT section.
LampToLuminaireGeometry m_lamp_to_luminaire_geometry;
std::vector<double> m_tilt_angles;
std::vector<double> m_tilt_multiplying_factors;
// Photometric information.
int m_number_of_lamps;
double m_lumens_per_lamp;
bool m_absolute_photometry;
double m_candela_multiplier;
int m_number_of_vertical_angles;
int m_number_of_horizontal_angles;
PhotometricType m_photometric_type;
LuminousOpeningShape m_luminous_opening;
double m_ballast_factor;
double m_ballast_lamp_photometric_factor;
double m_input_watts;
SymmetryType m_symmetry;
std::vector<double> m_vertical_angles;
std::vector<double> m_horizontal_angles;
PhotometricGrid m_candela_values;
// Keywords.
KeywordsDictionary m_keywords_dictionary;
//
// Variables that describe the current parsing state:
//
KeywordsDictionary::iterator m_last_added_keyword;
int m_line_counter;
std::string m_line;
};
} // namespace foundation
| 31.263158 | 107 | 0.665825 | [
"geometry",
"shape",
"vector"
] |
6c922669ffe35cf1030c578b5d78d670d088d7ca | 5,108 | c | C | oskar/sky/src/oskar_sky_from_image.c | davepallot/OSKAR | cadde89d692f853250abf4f736bcac17c99df7d7 | [
"BSD-3-Clause"
] | 1 | 2019-02-01T03:05:58.000Z | 2019-02-01T03:05:58.000Z | oskar/sky/src/oskar_sky_from_image.c | davepallot/OSKAR | cadde89d692f853250abf4f736bcac17c99df7d7 | [
"BSD-3-Clause"
] | 1 | 2019-04-18T05:47:43.000Z | 2019-04-18T05:47:43.000Z | oskar/sky/src/oskar_sky_from_image.c | davepallot/OSKAR | cadde89d692f853250abf4f736bcac17c99df7d7 | [
"BSD-3-Clause"
] | 1 | 2019-10-17T03:39:46.000Z | 2019-10-17T03:39:46.000Z | /*
* Copyright (c) 2016-2018, The University of Oxford
* 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 the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "sky/oskar_sky.h"
#include "convert/oskar_convert_relative_directions_to_lon_lat.h"
#include "math/oskar_cmath.h"
#ifdef __cplusplus
extern "C" {
#endif
static void set_pixel(oskar_Sky* sky, int i, int x, int y, double val,
const double crval[2], const double crpix[2], const double cdelt[2],
double image_freq_hz, double spectral_index, int* status);
oskar_Sky* oskar_sky_from_image(int precision, const oskar_Mem* image,
const int image_size[2], const double image_crval_deg[2],
const double image_crpix[2], double image_cellsize_deg,
double image_freq_hz, double spectral_index, int* status)
{
int i, type, x, y;
double crval[2], cdelt[2], val;
oskar_Sky* sky = 0;
/* Check if safe to proceed. */
if (*status) return 0;
/* Check pixel size has been defined. */
if (image_cellsize_deg == 0.0)
{
*status = OSKAR_ERR_OUT_OF_RANGE;
fprintf(stderr, "Unknown image pixel size. "
"(Ensure all WCS headers are present.)\n");
return 0;
}
/* Get reference pixels and reference values in radians. */
crval[0] = image_crval_deg[0] * M_PI / 180.0;
crval[1] = image_crval_deg[1] * M_PI / 180.0;
/* Compute sine of pixel deltas for inverse orthographic projection. */
cdelt[0] = -sin(image_cellsize_deg * M_PI / 180.0);
cdelt[1] = -cdelt[0];
/* Create a sky model. */
sky = oskar_sky_create(precision, OSKAR_CPU, 0, status);
/* Store the image pixels. */
type = oskar_mem_precision(image);
if (type == OSKAR_SINGLE)
{
const float *img = oskar_mem_float_const(image, status);
for (y = 0, i = 0; y < image_size[1]; ++y)
{
for (x = 0; x < image_size[0]; ++x)
{
/* Check pixel value. */
val = (double) (img[image_size[0] * y + x]);
if (val == 0.0)
continue;
set_pixel(sky, i++, x, y, val, crval, image_crpix, cdelt,
image_freq_hz, spectral_index, status);
}
}
}
else
{
const double *img = oskar_mem_double_const(image, status);
for (y = 0, i = 0; y < image_size[1]; ++y)
{
for (x = 0; x < image_size[0]; ++x)
{
/* Check pixel value. */
val = img[image_size[0] * y + x];
if (val == 0.0)
continue;
set_pixel(sky, i++, x, y, val, crval, image_crpix, cdelt,
image_freq_hz, spectral_index, status);
}
}
}
/* Return the sky model. */
oskar_sky_resize(sky, i, status);
return sky;
}
static void set_pixel(oskar_Sky* sky, int i, int x, int y, double val,
const double crval[2], const double crpix[2], const double cdelt[2],
double image_freq_hz, double spectral_index, int* status)
{
double ra, dec, l, m;
/* Convert pixel positions to RA and Dec values. */
l = cdelt[0] * (x + 1 - crpix[0]);
m = cdelt[1] * (y + 1 - crpix[1]);
oskar_convert_relative_directions_to_lon_lat_2d_d(1,
&l, &m, crval[0], crval[1], &ra, &dec);
/* Store pixel data in sky model. */
if (oskar_sky_num_sources(sky) <= i)
oskar_sky_resize(sky, i + 1000, status);
oskar_sky_set_source(sky, i, ra, dec, val, 0.0, 0.0, 0.0,
image_freq_hz, spectral_index, 0.0, 0.0, 0.0, 0.0, status);
}
#ifdef __cplusplus
}
#endif
| 36.748201 | 79 | 0.631167 | [
"model"
] |
6c9ffb1a99edee8602ada6c4800359bba7c19aac | 4,981 | h | C | src/3rdparty/khtml/src/html/html_miscimpl.h | afarcat/QtHtmlView | fff12b6f5c08c2c6db15dd73e4f0b55421827b39 | [
"Apache-2.0"
] | null | null | null | src/3rdparty/khtml/src/html/html_miscimpl.h | afarcat/QtHtmlView | fff12b6f5c08c2c6db15dd73e4f0b55421827b39 | [
"Apache-2.0"
] | null | null | null | src/3rdparty/khtml/src/html/html_miscimpl.h | afarcat/QtHtmlView | fff12b6f5c08c2c6db15dd73e4f0b55421827b39 | [
"Apache-2.0"
] | null | null | null | /*
* This file is part of the DOM implementation for KDE.
*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library 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
* 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.
*
*/
#ifndef HTML_MISCIMPL_H
#define HTML_MISCIMPL_H
#include "html_elementimpl.h"
#include "xml/dom_nodelistimpl.h"
#include "misc/shared.h"
namespace DOM
{
class Node;
class DOMString;
class HTMLCollection;
class HTMLBaseFontElementImpl : public HTMLElementImpl
{
public:
HTMLBaseFontElementImpl(DocumentImpl *doc);
~HTMLBaseFontElementImpl();
Id id() const override;
};
// -------------------------------------------------------------------------
class HTMLCollectionImpl : public DynamicNodeListImpl
{
friend class DOM::HTMLCollection;
public:
enum Type {
// from HTMLDocument
DOC_IMAGES = LAST_NODE_LIST + 1, // all IMG elements in the document
DOC_APPLETS, // all OBJECT and APPLET elements
DOC_FORMS, // all FORMS
DOC_LAYERS, // all LAYERS
DOC_LINKS, // all A _and_ AREA elements with a value for href
DOC_ANCHORS, // all A elements with a value for name
DOC_SCRIPTS, // all SCRIPT elements
// from HTMLTable, HTMLTableSection, HTMLTableRow
TABLE_ROWS, // all rows in this table
TABLE_TBODIES, // all TBODY elements in this table
TSECTION_ROWS, // all rows elements in this table section
TR_CELLS, // all CELLS in this row
// from SELECT
SELECT_OPTIONS,
// from HTMLMap
MAP_AREAS,
FORMLESS_INPUT, // input elements that do not have form associated w/them
DOC_ALL, // "all" elements (IE)
NODE_CHILDREN, // first-level children (IE)
FORM_ELEMENTS, // input elements in a form
WINDOW_NAMED_ITEMS,
DOCUMENT_NAMED_ITEMS,
LAST_TYPE
};
HTMLCollectionImpl(NodeImpl *_base, int _tagId);
NodeImpl *item(unsigned long index) const override;
// obsolete and not domtree changes save
virtual NodeImpl *firstItem() const;
virtual NodeImpl *nextItem() const;
virtual NodeImpl *namedItem(const DOMString &name) const;
// In case of multiple items named the same way
virtual NodeImpl *nextNamedItem(const DOMString &name) const;
QList<NodeImpl *> namedItems(const DOMString &name) const;
int getType() const
{
return type;
}
NodeImpl *base()
{
return m_refNode;
}
protected:
unsigned long calcLength(NodeImpl *start) const override;
// The collection list the following elements
int type: 8;
// Reimplemented from DynamicNodeListImpl
bool nodeMatches(NodeImpl *testNode, bool &doRecurse) const override;
// Helper for name iteration: checks whether ID matches,
// and inserts any name-matching things into namedItemsWithName
bool checkForNameMatch(NodeImpl *node, const DOMString &name) const;
};
// this whole class is just a big hack to find form elements even in
// malformed HTML elements
// the famous <table><tr><form><td> problem
class HTMLFormCollectionImpl : public HTMLCollectionImpl
{
public:
// base must inherit HTMLGenericFormElementImpl or this won't work
HTMLFormCollectionImpl(NodeImpl *_base);
~HTMLFormCollectionImpl() { }
NodeImpl *item(unsigned long index) const override;
NodeImpl *namedItem(const DOMString &name) const override;
// In case of multiple items named the same way
NodeImpl *nextNamedItem(const DOMString &name) const override;
protected:
unsigned long calcLength(NodeImpl *start) const override;
private:
mutable unsigned currentNamePos;
mutable unsigned currentNameImgPos;
mutable bool foundInput;
};
/*
Special collection for items of given name/id under document. or window.; but using
iteration interface
*/
class HTMLMappedNameCollectionImpl : public HTMLCollectionImpl
{
public:
HTMLMappedNameCollectionImpl(NodeImpl *_base, int type, const DOMString &name);
bool nodeMatches(NodeImpl *testNode, bool &doRecurse) const override;
static bool matchesName(ElementImpl *el, int type, const DOMString &name);
private:
DOMString name;
};
} //namespace
#endif
| 31.327044 | 84 | 0.695041 | [
"object"
] |
6ca0204907c29c09400acf1b870159c4d56a65ac | 833 | h | C | Engine/Source/Runtime/Engine/Classes/Materials/MaterialExpressionTextureSampleParameter2D.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Runtime/Engine/Classes/Materials/MaterialExpressionTextureSampleParameter2D.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Runtime/Engine/Classes/Materials/MaterialExpressionTextureSampleParameter2D.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "Materials/MaterialExpressionTextureSampleParameter.h"
#include "MaterialExpressionTextureSampleParameter2D.generated.h"
UCLASS(collapsecategories, hidecategories=Object)
class ENGINE_API UMaterialExpressionTextureSampleParameter2D : public UMaterialExpressionTextureSampleParameter
{
GENERATED_UCLASS_BODY()
// Begin UMaterialExpression Interface
virtual void GetCaption(TArray<FString>& OutCaptions) const override;
// End UMaterialExpression Interface
// Begin UMaterialExpressionTextureSampleParameter Interface
virtual bool TextureIsValid( UTexture* InTexture ) override;
virtual const TCHAR* GetRequirements() override;
virtual void SetDefaultTexture() override;
// End UMaterialExpressionTextureSampleParameter Interface
};
| 30.851852 | 111 | 0.837935 | [
"object"
] |
6ca30a68299f982e1b7979c232adbb5c3707659d | 3,936 | h | C | gui/similaritymatrixview.h | Maurice189/eye-slitscan | a8ea2402936122f9e5c98152460bd16a4ba97740 | [
"MIT"
] | 5 | 2018-07-12T12:32:51.000Z | 2021-04-06T12:13:37.000Z | gui/similaritymatrixview.h | Maurice189/eye-slitscan | a8ea2402936122f9e5c98152460bd16a4ba97740 | [
"MIT"
] | null | null | null | gui/similaritymatrixview.h | Maurice189/eye-slitscan | a8ea2402936122f9e5c98152460bd16a4ba97740 | [
"MIT"
] | null | null | null | #ifndef SIMILARITYMATRIXVIEW_H
#define SIMILARITYMATRIXVIEW_H
#include <QObject>
#include <QColor>
#include <QList>
#include <QString>
#include <QGraphicsRectItem>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QWheelEvent>
#include <QGraphicsDropShadowEffect>
#include <vector>
#include <functional>
#include "constants.h"
#include "dendrogramitem.h"
struct ColorScheme3 {
QString title;
QColor class01;
QColor class02;
QColor class03;
};
class SimilarityMatrixView : public QGraphicsView
{
Q_OBJECT
public:
SimilarityMatrixView(QWidget * parent = 0);
void build(const QList<SimilarityMatrix> &matrices, const ClusteringResult &result);
void build(SimilarityMatrix &matrix, const ClusteringResult &result);
QPixmap getImageOfColorSchemeSample(int width, int height, int sampleSize);
private:
void buildCmpBlock(const QList<SimilarityMatrix> &matrices, int i, int j, const QRectF &bounds);
void buildKeyBlock(const QList<SimilarityMatrix> &matrices, const QRectF &bounds);
std::function<QColor(double)> createColorTransformation(const QList<SimilarityMatrix> &matrices, const QColor &baseColor);
std::function<QColor(double)> createColorTransformation(const SimilarityMatrix &matrix, const ColorScheme3 &colorScheme);
std::function<QColor(double)> createOrderedTransformation(std::vector<double> &values, const ColorScheme3 &colorScheme);
std::function<int(double)> createQuantileTransformation(const SimilarityMatrix &matrix);
void updateBoxes();
protected:
virtual void keyPressEvent(QKeyEvent* event) override;
private:
int baseColorIndex;
QGraphicsScene *scene;
std::vector<std::function<QColor(double)>> toColorBaseRed;
std::vector<std::function<QColor(double)>> toColorBaseGreen;
std::vector<std::function<QColor(double)>> toColorBaseBlue;
std::vector<std::function<int(double)>> withinQuantile;
QList<QString> labelNames;
QList<QGraphicsRectItem*> boxes;
int _numScheduledScalings = 0;
int currLowerQuantile = 0;
int currUpperQuantile = 100;
std::vector<QColor> baseColors = {QColor::fromRgb(255, 126, 126), // red
QColor::fromRgb(122, 255, 159), // green
QColor::fromRgb(122, 177, 255) // blue
};
QList<ColorScheme3> colorSchemes = {
{"YlOrRd", QColor::fromRgb(255, 237, 160), QColor::fromRgb(254, 178, 76), QColor::fromRgb(240, 59, 32)},
{"GnBu", QColor::fromRgb(224, 243, 219), QColor::fromRgb(168, 221, 181), QColor::fromRgb(67, 162, 202)},
{"BuGn", QColor::fromRgb(229, 245, 249), QColor::fromRgb(153, 216, 201), QColor::fromRgb(44, 162, 95)},
};
private:
class BoxItem : public QGraphicsRectItem {
public:
BoxItem(const QRectF &rect, QGraphicsItem * parent = 0) : QGraphicsRectItem(rect, parent)
{
setAcceptHoverEvents(true);
}
protected:
virtual void hoverEnterEvent(QGraphicsSceneHoverEvent * event) override
{
auto color = brush().color().lighter(150);
setPen(QPen(color, 10));
update();
}
virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent * event) override
{
auto color = brush().color();
setPen(QPen(color, 0));
update();
}
};
signals:
void boxSelected(QPair<QString, QString> participants, QString method, QString value);
public slots:
void boxSelectionChanged();
void scalingTime(qreal x);
void animFinished();
void lowerQuantileChanged(int lowerQuantile);
void upperQuantileChanged(int upperQuantile);
void baseColorChanged(int baseColorIndex);
};
#endif // SIMILARITYMATRIXVIEW_H
| 34.831858 | 144 | 0.658283 | [
"vector"
] |
6ca638088456e0700e6c0cf42e51f34297bbb5d3 | 2,251 | h | C | xedInc/xed-patch.h | joshwatson/arch-x86 | ed3b79cbd333ceb23b00a3b574f9c7b68117e637 | [
"Apache-2.0"
] | 26 | 2020-10-27T17:26:18.000Z | 2021-05-25T00:45:54.000Z | xedInc/xed-patch.h | joshwatson/arch-x86 | ed3b79cbd333ceb23b00a3b574f9c7b68117e637 | [
"Apache-2.0"
] | 27 | 2020-10-27T17:56:13.000Z | 2022-03-08T15:13:58.000Z | xedInc/xed-patch.h | joshwatson/arch-x86 | ed3b79cbd333ceb23b00a3b574f9c7b68117e637 | [
"Apache-2.0"
] | 5 | 2020-10-29T22:10:48.000Z | 2021-12-15T01:06:24.000Z | /*BEGIN_LEGAL
Copyright (c) 2020 Intel Corporation
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.
END_LEGAL */
#ifndef XED_PATCH_H
# define XED_PATCH_H
#include "xed-encoder-hl.h"
/// @name Patching decoded instructions
//@{
/// Replace a memory displacement.
/// The widths of original displacement and replacement must match.
/// @param xedd A decoded instruction.
/// @param itext The corresponding encoder output, byte array.
/// @param disp A xed_enc_displacement_t object describing the new displacement.
/// @returns xed_bool_t 1=success, 0=failure
/// @ingroup ENCHLPATCH
XED_DLL_EXPORT xed_bool_t
xed_patch_disp(xed_decoded_inst_t* xedd,
xed_uint8_t* itext,
xed_enc_displacement_t disp);
/// Replace a branch displacement.
/// The widths of original displacement and replacement must match.
/// @param xedd A decoded instruction.
/// @param itext The corresponding encoder output, byte array.
/// @param disp A xed_encoder_operand_t object describing the new displacement.
/// @returns xed_bool_t 1=success, 0=failure
/// @ingroup ENCHLPATCH
XED_DLL_EXPORT xed_bool_t
xed_patch_relbr(xed_decoded_inst_t* xedd,
xed_uint8_t* itext,
xed_encoder_operand_t disp);
/// Replace an imm0 immediate value.
/// The widths of original immediate and replacement must match.
/// @param xedd A decoded instruction.
/// @param itext The corresponding encoder output, byte array.
/// @param imm0 A xed_encoder_operand_t object describing the new immediate.
/// @returns xed_bool_t 1=success, 0=failure
/// @ingroup ENCHLPATCH
XED_DLL_EXPORT xed_bool_t
xed_patch_imm0(xed_decoded_inst_t* xedd,
xed_uint8_t* itext,
xed_encoder_operand_t imm0);
//@}
#endif
| 35.171875 | 81 | 0.741892 | [
"object"
] |
6ca764e7c46497a4d4544506e890154d3d2ed12e | 44,646 | c | C | tdfc2/src/common/construct/redeclare.c | dj3vande/tendra | 86981ad5574f55821853e3bdf5f82e373f91edb2 | [
"BSD-3-Clause"
] | null | null | null | tdfc2/src/common/construct/redeclare.c | dj3vande/tendra | 86981ad5574f55821853e3bdf5f82e373f91edb2 | [
"BSD-3-Clause"
] | null | null | null | tdfc2/src/common/construct/redeclare.c | dj3vande/tendra | 86981ad5574f55821853e3bdf5f82e373f91edb2 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2002-2011, The TenDRA Project.
* Copyright 1997, United Kingdom Secretary of State for Defence.
*
* See doc/copyright/ for the full copyright terms.
*/
#include <stdio.h>
#include <string.h>
#include <shared/check.h>
#include <shared/error.h>
#include <shared/string.h>
#include <tdf/bitstream.h>
#include <utility/config.h>
#include "c_types.h"
#include <utility/error.h>
#include <utility/catalog.h>
#include <utility/option.h>
#include <utility/buffer.h>
#include <utility/ustring.h>
#include <syntax/syntax.h>
#include <parse/char.h>
#include <parse/constant.h>
#include <parse/file.h>
#include <parse/literal.h>
#include <parse/predict.h>
#include <parse/preproc.h>
#include <construct/access.h>
#include <construct/basetype.h>
#include <construct/check.h>
#include <construct/chktype.h>
#include <construct/class.h>
#include <construct/copy.h>
#include <construct/declare.h>
#include <construct/derive.h>
#include <construct/function.h>
#include <construct/identifier.h>
#include <construct/instance.h>
#include <construct/namespace.h>
#include <construct/overload.h>
#include <construct/redeclare.h>
#include <construct/template.h>
#include <construct/tokdef.h>
#include <construct/token.h>
#include <construct/link.h>
#include <output/compile.h>
#include <output/dump.h>
#include "ctype_ops.h"
#include "err_ops.h"
#include "exp_ops.h"
#include "graph_ops.h"
#include "hashid_ops.h"
#include "id_ops.h"
#include "member_ops.h"
#include "off_ops.h"
#include "nspace_ops.h"
#include "str_ops.h"
#include "tok_ops.h"
#include "type_ops.h"
/*
The current linkage specifier is handled by means of this global
variable. The default, of no linkage being given, is interpreted
according to the source language.
*/
DECL_SPEC crt_linkage = dspec_none;
DECL_SPEC new_linkage = dspec_none;
/*
This routine translates the string literal expression e into a linkage
specifier. The only recognised strings are "C" and "C++".
*/
DECL_SPEC
find_linkage(EXP e)
{
STRING s = DEREF_str(exp_string_lit_str(e));
unsigned kind = DEREF_unsigned(str_simple_kind(s));
/* Can only occur in namespace scope */
if (in_function_defn || in_class_defn) {
report(crt_loc, ERR_dcl_link_scope());
}
/* Check the linkage string */
if (kind == STRING_NONE) {
char *t = strlit(DEREF_string(str_simple_text(s)));
unsigned long len = DEREF_ulong(str_simple_len(s));
if (len == 1 && streq(t, "C")) {
return dspec_c;
}
if (len == 3 && streq(t, "C++")) {
return dspec_cpp;
}
}
/* Report unknown strings */
report(crt_loc, ERR_dcl_link_unknown(s));
return crt_linkage;
}
/*
This routine returns the string corresponding to the linkage specifiers
given by ds and cv.
*/
string
linkage_string(DECL_SPEC ds, CV_SPEC cv)
{
const char *str;
if ((ds & dspec_c) || (cv & cv_c)) {
str = "C";
} else {
str = "C++";
}
return ustrlit(str);
}
/*
This routine adds the current language specifier to the declaration
specifier ds. mem is true for a member declaration (which always
has C++ linkage). ds may contain a language specifier from a
previous declaration, otherwise it is deduced from crt_linkage.
*/
DECL_SPEC
adjust_linkage(DECL_SPEC ds, int mem)
{
DECL_SPEC rs = (ds & ~dspec_language);
if (mem) {
/* Members have C++ linkage */
rs |= dspec_cpp;
} else if (rs & dspec_linkage) {
/* Only applies to objects with linkage */
DECL_SPEC ln = (ds | crt_linkage);
if (ln & dspec_c) {
rs |= dspec_c;
} else {
rs |= dspec_cpp;
}
}
return rs;
}
/*
This routine checks the identifier id declared with C linkage. Objects
with C linkage in different namespaces are actually the same.
*/
void
c_linkage(IDENTIFIER id, int def)
{
TYPE t = NULL_type;
unsigned tag = TAG_id(id);
if (tag == id_function_tag) {
/* Template functions can't have C linkage */
t = DEREF_type(id_function_type(id));
if (IS_type_templ(t)) {
report(decl_loc, ERR_temp_decl_linkage());
}
} else if (tag == id_variable_tag) {
t = DEREF_type(id_variable_type(id));
}
if (!IS_NULL_type(t)) {
NAMESPACE ns = c_namespace;
if (!IS_NULL_nspace(ns)) {
HASHID nm = DEREF_hashid(id_name(id));
MEMBER mem = search_member(ns, nm, 1);
IDENTIFIER pid = DEREF_id(member_id(mem));
if (!IS_NULL_id(pid) && !EQ_id(id, pid)) {
NAMESPACE cns = DEREF_nspace(id_parent(id));
NAMESPACE pns = DEREF_nspace(id_parent(pid));
if (!EQ_nspace(cns, pns)) {
DECL_SPEC cl = crt_linkage;
QUALIFIER cq = crt_id_qualifier;
DECL_SPEC ds = DEREF_dspec(id_storage(id));
crt_linkage = (ds & dspec_language);
crt_id_qualifier = qual_none;
pid = redecl_id(ds, t, pid, 3, -1);
if (!IS_NULL_id(pid)) {
/* Set up alias */
if (IS_id_function(pid)) {
TYPE s = DEREF_type(id_function_type(pid));
s = redecl_func_type(pid, s, t, def, 0);
COPY_type(id_function_type(pid), s);
}
ds |= dspec_alias;
COPY_dspec(id_storage(id), ds);
pid = DEREF_id(id_alias(pid));
COPY_id(id_alias(id), pid);
if (do_dump) {
dump_alias(id, pid, &decl_loc);
}
id = pid;
}
crt_id_qualifier = cq;
crt_linkage = cl;
}
}
COPY_id(member_id(mem), id);
}
}
return;
}
/*
If a declaration in block scope is declared extern then it has external
linkage unless the declaration matches a visible declaration of namespace
scope. This routine finds such a declaration for the identifier id
of type t.
*/
IDENTIFIER
find_previous(TYPE t, IDENTIFIER id)
{
if (crt_id_qualifier == qual_none) {
NAMESPACE ns = nonblock_namespace;
HASHID nm = DEREF_hashid(id_name(id));
IDENTIFIER pid = find_extern_id(nm, ns, 0);
if (!IS_NULL_id(pid)) {
TYPE s;
DECL_SPEC st;
switch (TAG_id(pid)) {
case id_variable_tag:
/* Variables may be redeclared */
s = DEREF_type(id_variable_type(pid));
break;
case id_function_tag: {
/* Functions may be redeclared */
#if LANGUAGE_CPP
int eq = 0;
LIST(IDENTIFIER) pids = NULL_list(IDENTIFIER);
pid = resolve_func(pid, t, 0, 0, pids, &eq);
if (IS_NULL_id(pid)) {
return NULL_id;
}
if (!IS_id_function(pid)) {
return NULL_id;
}
#endif
s = DEREF_type(id_function_type(pid));
break;
}
default:
/* Nothing else can be redeclared */
return NULL_id;
}
st = DEREF_dspec(id_storage(pid));
if (st & dspec_linkage) {
/* Previous declaration must have linkage */
s = type_composite(s, t, 0, 0, KILL_err, 0);
if (!IS_NULL_type(s)) {
return pid;
}
}
}
}
return NULL_id;
}
/*
This routine checks the identifier id, which is a variable declared
extern in a block, against conflicts with the namespace ns into
which it is injected. p gives all the other extern block identifiers
declared before id. The routine returns any previous identifier.
*/
IDENTIFIER
unify_extern(IDENTIFIER id, TYPE t, NAMESPACE ns, LIST(IDENTIFIER) p)
{
IDENTIFIER pid = NULL_id;
HASHID nm = DEREF_hashid(id_name(id));
LIST(IDENTIFIER) pids = NULL_list(IDENTIFIER);
while (!IS_NULL_list(p)) {
/* Check other block externs */
IDENTIFIER bid = DEREF_id(HEAD_list(p));
HASHID bnm = DEREF_hashid(id_name(bid));
if (EQ_hashid(bnm, nm)) {
bid = DEREF_id(id_alias(bid));
CONS_id(bid, pids, pids);
}
p = TAIL_list(p);
}
if (!IS_NULL_nspace(ns)) {
/* Check actual namespace */
MEMBER mem = search_member(ns, nm, 0);
if (!IS_NULL_member(mem)) {
IDENTIFIER bid = DEREF_id(member_id(mem));
if (!IS_NULL_id(bid)) {
bid = DEREF_id(id_alias(bid));
CONS_id(bid, pids, pids);
}
}
}
if (!IS_NULL_list(pids)) {
/* Match found */
if (IS_NULL_type(t)) {
if (IS_NULL_list(TAIL_list(pids))) {
pid = DEREF_id(HEAD_list(pids));
DESTROY_list(pids, SIZE_id);
} else {
DECL_SPEC ds;
pids = REVERSE_list(pids);
ds = find_ambig_dspec(pids);
MAKE_id_ambig(nm, ds, ns, crt_loc, pids, 1,
pid);
}
} else {
LIST(IDENTIFIER) qids;
DECL_SPEC cl = crt_linkage;
QUALIFIER cq = crt_id_qualifier;
DECL_SPEC ds = DEREF_dspec(id_storage(id));
crt_linkage = (ds & dspec_language);
crt_id_qualifier = qual_none;
DEREF_loc(id_loc(id), decl_loc);
pids = REVERSE_list(pids);
qids = pids;
while (!IS_NULL_list(qids)) {
IDENTIFIER qid = DEREF_id(HEAD_list(qids));
qid = DEREF_id(id_alias(qid));
if (IS_type_func(t)) {
/* Check function redeclaration */
IDENTIFIER over = NULL_id;
unsigned tag = TAG_id(id);
qid = redecl_func(ds, t, qid, tag,
&over, -1);
} else {
/* Check variable redeclaration */
qid = redecl_id(ds, t, qid, 0, -1);
}
if (!IS_NULL_id(qid)) {
pid = qid;
}
qids = TAIL_list(qids);
}
DESTROY_list(pids, SIZE_id);
crt_id_qualifier = cq;
crt_linkage = cl;
}
}
return pid;
}
/*
This routine is used to unify the external block declaration id of
type t with its previous declaration pid (as returned by find_previous).
def is true is id is a function definition. The routine returns id.
If there is no previous declaration then one is created and added to
the extra identifier list of the enclosing non-block namespace.
*/
IDENTIFIER
unify_previous(IDENTIFIER id, TYPE t, IDENTIFIER pid, int def)
{
/* Unify external linkage */
if (IS_NULL_id(pid)) {
LIST(IDENTIFIER) p;
NAMESPACE ns = nonblock_namespace;
p = DEREF_list(nspace_named_etc_extra(ns));
pid = unify_extern(id, t, ns, p);
if (IS_NULL_id(pid)) {
if (!is_templ_depend(t)) {
/* Declare new external object */
DECL_SPEC ds;
pid = copy_id(id, 0);
ds = DEREF_dspec(id_storage(pid));
if (!(ds & dspec_linkage)) {
ds |= dspec_extern;
}
ds &= ~dspec_alias;
COPY_dspec(id_storage(pid), ds);
COPY_nspace(id_parent(pid), ns);
COPY_id(id_alias(pid), pid);
CONS_id(pid, p, p);
COPY_list(nspace_named_etc_extra(ns), p);
}
/* Check object type */
if (!is_global_type(t)) {
report(crt_loc, ERR_basic_link_none(t, id));
}
}
}
/* Alias id to be pid */
if (!IS_NULL_id(pid)) {
if (IS_id_function_etc(pid)) {
TYPE s = DEREF_type(id_function_etc_type(pid));
s = redecl_func_type(pid, s, t, def, 0);
COPY_type(id_function_etc_type(pid), s);
}
pid = DEREF_id(id_alias(pid));
COPY_id(id_alias(id), pid);
}
return id;
}
/*
This routine is used to unify the external declaration id of type
t with any previous external block declaration of the same object.
def is true if id is a function definition. The routine returns id.
*/
IDENTIFIER
unify_subsequent(IDENTIFIER id, TYPE t, int def)
{
NAMESPACE ns = DEREF_nspace(id_parent(id));
if (IS_nspace_named_etc(ns)) {
LIST(IDENTIFIER) p;
p = DEREF_list(nspace_named_etc_extra(ns));
if (!IS_NULL_list(p)) {
IDENTIFIER pid = unify_extern(id, t, NULL_nspace, p);
if (!IS_NULL_id(pid)) {
/* Alias id to be pid */
if (IS_id_function_etc(pid)) {
TYPE s = DEREF_type(id_function_etc_type(pid));
s = redecl_func_type(pid, s, t, def, 0);
COPY_type(id_function_etc_type(pid), s);
}
pid = DEREF_id(id_alias(pid));
COPY_id(id_alias(id), pid);
}
}
}
return id;
}
/*
This routine checks whether the typedef name id behaves like a class
or an object with respect to name hiding. It is not entirely clear
whether it is just original class and enumeration names or all class
and enumeration names (including those introduced using typedef)
which behave in this way.
*/
int
is_tagged_type(IDENTIFIER id)
{
switch (TAG_id(id)) {
case id_class_name_tag:
case id_enum_name_tag:
/* Original class and enumeration names */
return 1;
case id_class_alias_tag:
case id_enum_alias_tag:
case id_type_alias_tag:
/* Type aliases */
return 0;
}
return 0;
}
/*
This routine reports the overloading error err for the function id
which cannot be overloaded for the reason corresponding to reason.
It returns the severity of the error.
*/
static int
overload_error(IDENTIFIER id, ERROR err, int reason)
{
int sev = ERR_NONE;
switch (reason) {
case 1:
/* Two functions with C linkage */
err = concat_error(err, ERR_dcl_link_over());
break;
case 2:
/* Two functions with indistinguishable parameters */
err = concat_error(err, ERR_over_load_pars());
break;
case 3: {
/* Two objects with C linkage */
PTR(LOCATION)loc = id_loc(id);
HASHID nm = DEREF_hashid(id_name(id));
err = concat_error(err, ERR_dcl_link_redecl(nm, loc));
break;
}
}
if (!IS_NULL_err(err)) {
sev = DEREF_int(err_severity(err));
report(decl_loc, err);
}
return sev;
}
/*
This routine checks the redeclaration of the identifier id as an object
with declaration specifiers ds and type t. It returns id for a valid
redeclaration and the null identifier otherwise, reporting any errors
if necessary. Note that it is possible to reserve an identifier using
the reserve declaration specifier. At present this is only done for
the fields of an anonymous union and enumerators. Also a class or
enumeration name can be hidden by an object in the same scope. A
redeclared identifier will be marked as defined according to whether
the redeclaration is a definition. Whether the initial declaration
was a definition may be determined from the initialiser expression.
*/
IDENTIFIER
redecl_id(DECL_SPEC ds, TYPE t, IDENTIFIER id, int reason, int def)
{
TYPE s;
DECL_SPEC ln;
PTR(TYPE) pt;
int changed = 0;
int is_member = 0;
int is_function = 0;
ERROR err = NULL_err;
DECL_SPEC ds_old, ln_old;
/* Check previous definition */
switch (TAG_id(id)) {
case id_variable_tag:
/* Variables may be redeclared */
pt = id_variable_type(id);
break;
case id_function_tag:
/* Functions may be redeclared */
is_function = 1;
pt = id_function_type(id);
break;
case id_class_name_tag:
case id_enum_name_tag:
case id_class_alias_tag:
case id_enum_alias_tag:
case id_type_alias_tag: {
/* Unqualified class and enumeration names can be hidden */
PTR(LOCATION)loc;
if (!is_tagged_type(id)) {
loc = id_loc(id);
report(decl_loc, ERR_basic_odr_diff(id, loc));
return NULL_id;
}
if (crt_id_qualifier == qual_none) {
/* Check for templates */
ds_old = DEREF_dspec(id_storage(id));
if (!(ds_old & dspec_template)) {
return NULL_id;
}
}
loc = id_loc(id);
report(decl_loc, ERR_basic_odr_diff(id, loc));
return NULL_id;
}
case id_stat_member_tag:
/* Members may be defined outside their class */
is_member = 1;
if (crt_id_qualifier == qual_none) {
goto error_lab;
}
pt = id_stat_member_type(id);
break;
case id_mem_func_tag:
case id_stat_mem_func_tag:
/* Members may be defined outside their class */
is_member = 1;
is_function = 1;
if (crt_id_qualifier == qual_none) {
goto error_lab;
}
pt = id_function_etc_type(id);
break;
case id_member_tag:
/* Non-static members cannot be redeclared */
is_member = 1;
if (crt_id_qualifier == qual_none) {
goto error_lab;
}
report(decl_loc, ERR_class_mem_def(id));
return NULL_id;
case id_token_tag:
/* Allow for token definitions */
return NULL_id;
case id_undef_tag:
case id_ambig_tag:
/* Allow for error propagation */
return NULL_id;
default:
error_lab:
/* No other identifiers can be redeclared */
if (is_member) {
/* Member redeclaration */
err = ERR_class_mem_redecl(id, id_loc(id));
} else {
/* Object redeclaration */
err = ERR_basic_odr_decl(id, id_loc(id));
}
IGNORE overload_error(id, err, reason);
return NULL_id;
}
/* Check declaration specifiers */
ds_old = DEREF_dspec(id_storage(id));
if ((ds | ds_old) & dspec_reserve) {
/* Reserved names can't be redeclared */
reason = 0;
goto error_lab;
}
/* Check for objects with no linkage */
ln = (ds & dspec_linkage);
ln_old = (ds_old & dspec_linkage);
if (ln == dspec_none || ln_old == dspec_none) {
/* Can't redeclare objects with no linkage */
if (!is_function) {
reason = 0;
goto error_lab;
}
}
/* Check previous type */
s = DEREF_type(pt);
s = check_compatible(s, t, 0, &err, 1);
if (!IS_NULL_err(err)) {
/* Incompatible declaration */
PTR(LOCATION) loc = id_loc(id);
err = concat_error(err, ERR_basic_link_decl_type(id, loc));
if ((ds | ds_old) & dspec_token) {
/* Allow for interface declarations */
err = set_severity(err, OPT_interf_incompat, -1);
}
if (overload_error(id, err, reason) == ERR_SERIOUS) {
return NULL_id;
}
}
if (is_function) {
/* Sanity check for error types */
if (type_tag(s) != type_func_tag) {
return NULL_id;
}
} else {
if (type_tag(s) == type_func_tag) {
return NULL_id;
}
}
if (def >= 0) {
COPY_type(pt, s);
}
/* Check for redeclaration of aliases */
if ((ds | ds_old) & dspec_alias) {
PTR(LOCATION) loc = id_loc(id);
report(decl_loc, ERR_dcl_nspace_udecl_redecl(id, loc));
}
/* Check for inconsistent linkage */
if (ln != ln_old) {
ERROR err1;
DECL_SPEC ln_new;
PTR(LOCATION) loc = id_loc(id);
if (ln_old == dspec_static) {
err1 = ERR_dcl_stc_internal(id, loc);
} else {
err1 = ERR_dcl_stc_external(id, loc);
if (is_member) {
/* Members have external linkage */
ERROR err2 = ERR_basic_link_mem_extern(id);
err1 = concat_error(err2, err1);
}
}
if (reason == 3) {
/* Identification of objects with C linkage */
HASHID nm = DEREF_hashid(id_name(id));
ERROR err2 = ERR_dcl_link_redecl(nm, loc);
err1 = concat_error(err1, err2);
}
if (def == -1 && option(OPT_link_internal) == OPTION_OFF) {
ln_new = dspec_extern;
} else {
ln_new = dspec_static;
}
ds_old = (ln_new | (ds_old & ~dspec_linkage));
report(decl_loc, err1);
changed = 1;
}
/* Check language specifier */
ln = crt_linkage;
if (ln != dspec_none) {
/* Check against the current language */
ln_old = (ds_old & dspec_language);
if ((ds_old & dspec_extern) && ln != ln_old) {
/* Report inconsistent linkage */
if (!is_member) {
/* Should this only apply to functions? */
PTR(LOCATION) loc = id_loc(id);
string lang = linkage_string(ln_old, cv_none);
report(decl_loc,
ERR_dcl_link_lang(id, lang, loc));
ds_old = adjust_linkage(ds_old, is_member);
changed = 1;
}
}
}
/* Check for inline specifier */
if (ds & dspec_inline) {
ds_old |= dspec_inline;
changed = 1;
}
/* Mark whether this declaration is a definition */
if (def >= 0) {
if (ds & dspec_defn) {
ds_old |= dspec_defn;
} else {
ds_old &= ~dspec_defn;
}
}
/* Compatible redeclaration */
COPY_dspec(id_storage(id), ds_old);
if (changed) {
update_tag(id, 0);
}
return id;
}
/*
This routine is similar to redecl_id except that it allows for function
overloading. As before it returns id if this is a redeclaration of an
existing function, and the null identifier otherwise. However in the
latter case any functions overloaded by the declaration are returned
via over.
*/
IDENTIFIER
redecl_func(DECL_SPEC ds, TYPE t, IDENTIFIER id, unsigned tag,
IDENTIFIER *over, int def)
{
int reason = 0;
IDENTIFIER fid = id;
#if LANGUAGE_CPP
if (IS_id_function_etc(fid)) {
DECL_SPEC ds_old;
*over = fid;
/* Scan through overloaded functions for a match */
while (!IS_NULL_id(fid)) {
int m;
TYPE s;
int mq = 1;
if ((ds & dspec_extern) && crt_linkage == dspec_c) {
/* Two functions with C linkage are the same */
ds_old = DEREF_dspec(id_storage(fid));
if ((ds_old & dspec_c) && IS_id_function(fid)) {
reason = 1;
break;
}
}
/* Two functions with the same parameters are the
* same */
s = DEREF_type(id_function_etc_type(fid));
if (tag == id_stat_mem_func_tag) {
mq = 0;
}
if (IS_id_stat_mem_func(fid)) {
mq = 0;
}
m = eq_func_type(t, s, mq, 0);
if (m) {
/* Function types basically match */
if (m == 1) {
/* Return types don't match */
reason = 2;
}
break;
}
fid = DEREF_id(id_function_etc_over(fid));
}
if (IS_NULL_id(fid)) {
/* No match found */
IDENTIFIER tid = find_template(id, 0);
if (!IS_NULL_id(tid)) {
/* Must have match with template
* specialisation */
report(decl_loc, ERR_temp_spec_type(t, id));
return NULL_id;
}
if (crt_id_qualifier != qual_none) {
/* Must have match with qualified identifier */
if (def == -2 && tag == id_function_tag) {
/* Allow for name injection */
/* EMPTY */
} else {
report(decl_loc,
ERR_basic_link_unmatch(t, id));
}
return NULL_id;
}
if (reason == 0) {
return NULL_id;
}
fid = id;
}
/* Match found */
ds_old = DEREF_dspec(id_storage(fid));
if ((ds_old & dspec_implicit) && !(ds & dspec_implicit)) {
if (IS_id_mem_func(fid)) {
/* Matches implicitly declared member
* function */
report(decl_loc, ERR_class_special_decl(fid));
return NULL_id;
}
}
if (ds_old & dspec_inherit) {
/* Inherited functions (including aliases) are hidden */
return NULL_id;
}
/* *over = NULL_id ; */
}
#else
/* Don't check overloading in C */
*over = NULL_id;
UNUSED(tag);
#endif
/* Redeclare id */
fid = redecl_id(ds, t, fid, reason, def);
if (!IS_NULL_id(fid)) {
TYPE form = DEREF_type(id_function_etc_form(id));
if (def >= 0) {
/* Allow for default arguments etc. */
TYPE s = DEREF_type(id_function_etc_type(fid));
s = redecl_func_type(fid, s, t, def, 1);
COPY_type(id_function_etc_type(fid), s);
}
if (!IS_NULL_type(form) && IS_type_token(form)) {
IDENTIFIER ext = DEREF_id(type_token_tok(form));
if (!IS_NULL_id(ext) && IS_id_token(ext)) {
/* Check for tokenised functions */
ds = DEREF_dspec(id_storage(ext));
ds |= dspec_explicit;
COPY_dspec(id_storage(ext), ds);
if (def) {
/* Check for token definitions */
IGNORE define_func_token(ext, fid);
if (ds & dspec_pure) {
report(decl_loc,
ERR_token_def_not(ext));
}
}
}
}
}
return fid;
}
/*
This routine is used to allow for declarations of class members to
override any inherited value of the member. id gives the inherited
value, mem is true for a member declaration, fn is true for a function
declaration or a declaration which can't coexist with a function
declaration. The null identifier is returned to indicate that id is
to be overridden.
*/
IDENTIFIER
redecl_inherit(IDENTIFIER id, QUALIFIER qual, int mem, int fn)
{
if (!IS_NULL_id(id)) {
DECL_SPEC ds = DEREF_dspec(id_storage(id));
if (ds & dspec_alias) {
if (fn && IS_id_function_etc(id)) {
/* Everything is a function */
return id;
}
if (mem && IS_id_class_name(id)) {
/* Allow for injected type names */
if (ds & dspec_implicit) {
return id;
}
}
if (qual == qual_none) {
/* New declaration */
PTR(LOCATION) loc = id_loc(id);
report(decl_loc,
ERR_dcl_nspace_udecl_multi(id, loc));
return NULL_id;
}
}
if (ds & dspec_inherit) {
NAMESPACE ns;
if (mem) {
return NULL_id;
}
ns = DEREF_nspace(id_parent(id));
id = DEREF_id(id_alias(id));
report(decl_loc, ERR_lookup_qual_decl(id, ns));
}
}
return id;
}
/*
This routine creates a copy of the identifier id. If type is 1
then any type components in id are copied using copy_typedef, if it
is 2 they are further expanded using expand_type.
*/
IDENTIFIER
copy_id(IDENTIFIER id, int type)
{
TYPE t;
ulong no;
ulong dno;
HASHID nm;
unsigned tag;
LOCATION loc;
NAMESPACE ns;
DECL_SPEC ds;
IDENTIFIER lid;
IDENTIFIER cid = id;
/* Examine various cases */
if (IS_NULL_id(cid)) {
return NULL_id;
}
tag = TAG_id(cid);
switch (tag) {
case id_class_name_tag:
case id_class_alias_tag:
case id_enum_name_tag:
case id_enum_alias_tag:
case id_type_alias_tag: {
/* Types */
BASE_TYPE bt;
DECONS_id_class_name_etc(nm, ds, ns, loc, lid, no, dno, t, bt,
cid);
if (type) {
t = copy_typedef(cid, t, cv_none);
if (type == 2) {
t = expand_type(t, 1);
if (tag == id_class_name_tag) {
/* Name already copied by copy_class */
CLASS_TYPE ct;
while (IS_type_templ(t)) {
t = DEREF_type(type_templ_defn(t));
}
ct = DEREF_ctype(type_compound_defn(t));
cid = DEREF_id(ctype_name(ct));
if (!EQ_id(cid, id)) {
COPY_hashid(id_name(cid), nm);
COPY_dspec(id_storage(cid), ds);
COPY_nspace(id_parent(cid), ns);
COPY_loc(id_loc(cid), loc);
break;
}
}
if (tag != id_enum_name_tag) {
/* Find type alias tag */
unsigned ta = type_tag(t);
if (ta == type_compound_tag) {
tag = id_class_alias_tag;
} else if (ta == type_enumerate_tag) {
tag = id_enum_alias_tag;
} else {
tag = id_type_alias_tag;
}
}
}
}
MAKE_id_class_name_etc(tag, nm, ds, ns, loc, t, cid);
COPY_btype(id_class_name_etc_rep(cid), bt);
break;
}
case id_variable_tag:
case id_parameter_tag:
case id_stat_member_tag: {
/* Objects */
EXP a, b;
DECONS_id_variable_etc(nm, ds, ns, loc, lid, no, dno, t,
a, b, cid);
if (type) {
t = copy_typedef(cid, t, cv_none);
if (type == 2) {
t = expand_type(t, 1);
}
}
MAKE_id_variable_etc(tag, nm, ds, ns, loc, t, cid);
COPY_exp(id_variable_etc_init(cid), a);
COPY_exp(id_variable_etc_term(cid), b);
break;
}
case id_function_tag:
case id_mem_func_tag:
case id_stat_mem_func_tag: {
/* Functions */
EXP a;
TYPE form;
IDENTIFIER over;
LIST(CLASS_TYPE)fr;
DECONS_id_function_etc(nm, ds, ns, loc, lid, no, dno, t,
over, form, fr, a, cid);
if (type) {
t = copy_typedef(cid, t, cv_none);
if (type == 2) {
t = expand_type(t, 1);
}
}
MAKE_id_function_etc(tag, nm, ds, ns, loc, t, over, cid);
COPY_type(id_function_etc_form(cid), form);
COPY_exp(id_function_etc_defn(cid), a);
if (type == 2) {
/* Copy friend classes */
while (!IS_NULL_list(fr)) {
TYPE r = NULL_type;
CLASS_TYPE cr = DEREF_ctype(HEAD_list(fr));
cr = expand_ctype(cr, 2, &r);
friend_function(cr, cid, 0);
fr = TAIL_list(fr);
}
} else {
COPY_list(id_function_etc_chums(cid), fr);
}
break;
}
case id_member_tag: {
/* Members */
GRAPH gr;
OFFSET off;
DECONS_id_member(nm, ds, ns, loc, lid, no, dno, t, off, gr,
cid);
if (type) {
t = copy_typedef(cid, t, cv_none);
if (type == 2) {
if (IS_hashid_anon(nm)) {
/* Allow for anonymous bitfields */
expand_anon_bitfield = 1;
}
t = expand_type(t, 1);
expand_anon_bitfield = 0;
}
}
MAKE_id_member(nm, ds, ns, loc, t, cid);
COPY_graph(id_member_base(cid), gr);
COPY_off(id_member_off(cid), off);
break;
}
case id_enumerator_tag: {
/* Enumerators */
EXP a;
ERROR err = NULL_err;
DECONS_id_enumerator(nm, ds, ns, loc, lid, no, dno, t, a, cid);
if (type == 2) {
/* Copy enumerator value */
TYPE s = expand_type(t, 1);
a = copy_exp(a, t, s);
IGNORE make_nat_exp(a, &err);
t = s;
}
MAKE_id_enumerator(nm, ds, ns, loc, t, a, cid);
if (!IS_NULL_err(err)) {
err = concat_error(err, ERR_dcl_enum_const(cid));
report(crt_loc, err);
}
break;
}
case id_token_tag: {
/* Tokens */
TOKEN sort;
IDENTIFIER alt;
DECONS_id_token(nm, ds, ns, loc, lid, no, dno, sort, alt, cid);
if (type == 2) {
/* Expand token sort */
sort = expand_sort(sort, 1, 1);
}
MAKE_id_token(nm, ds, ns, loc, sort, alt, cid);
break;
}
default:
/* Don't copy other identifiers */
return cid;
}
if (type != 2) {
COPY_id(id_alias(cid), lid);
COPY_ulong(id_no(cid), no);
COPY_ulong(id_dump(cid), dno);
}
return cid;
}
/*
This routine creates an alias for the identifier id in the namespace
ns. fn gives a list of function which the alias will overload if
it is a function.
*/
IDENTIFIER
alias_id(IDENTIFIER id, NAMESPACE ns, IDENTIFIER fn, int rec)
{
IDENTIFIER cid = copy_id(id, 1);
if (!EQ_id(cid, id)) {
DECL_SPEC ds = DEREF_dspec(id_storage(cid));
DECL_SPEC acc = (ds & dspec_access);
if (acc) {
IDENTIFIER sid = DEREF_id(nspace_name(ns));
immediate_access(sid, cid);
}
ds = ((ds & ~dspec_access) | dspec_alias | crt_access);
COPY_dspec(id_storage(cid), ds);
COPY_nspace(id_parent(cid), ns);
if (do_dump) {
dump_alias(cid, id, &crt_loc);
}
if (IS_id_function_etc(cid)) {
/* Deal with overloaded functions */
IDENTIFIER over;
if (rec) {
over = DEREF_id(id_function_etc_over(cid));
if (IS_NULL_id(over)) {
over = fn;
} else {
over = alias_id(over, ns, fn, rec);
}
} else {
over = fn;
}
COPY_id(id_function_etc_over(cid), over);
}
}
return cid;
}
/*
This value is used as a dummy declaration specifier in the adjusting
of overloaded functions.
*/
#define dspec_mark ((DECL_SPEC)0x7fffffff)
/*
This routine adjusts the set of overloaded functions id by removing
any with storage field equal to dspec_mark.
*/
static IDENTIFIER
remove_functions(IDENTIFIER id)
{
if (!IS_NULL_id(id)) {
DECL_SPEC ds = DEREF_dspec(id_storage(id));
IDENTIFIER over = DEREF_id(id_function_etc_over(id));
over = remove_functions(over);
if (ds == dspec_mark) {
id = over;
} else {
COPY_id(id_function_etc_over(id), over);
}
}
return id;
}
/*
This routine compares two functions id and over, one declared in the
normal fashion and the other by a using-declaration. It returns
true if the former overrides the latter.
*/
static int
compare_functions(IDENTIFIER id, IDENTIFIER over, int mem)
{
TYPE t = DEREF_type(id_function_etc_type(id));
TYPE s = DEREF_type(id_function_etc_type(over));
int eq = eq_func_type(t, s, 1, 0);
if (eq) {
/* Equal parameter types */
if (mem) {
return 1;
}
}
if (eq >= 2) {
/* Equal types */
PTR(LOCATION)loc = id_loc(over);
report(crt_loc, ERR_dcl_nspace_udecl_multi(over, loc));
return 1;
}
return 0;
}
/*
This routine marks any functions which hide, or are hidden by, id in
its set of overloaded functions. mem is true for member functions.
Any hidden function is marked by setting its storage field to the
value dspec_mark.
*/
static int
mark_functions(IDENTIFIER id, int mem)
{
int ret = 0;
DECL_SPEC ds = DEREF_dspec(id_storage(id));
if (ds != dspec_mark) {
IDENTIFIER over = DEREF_id(id_function_etc_over(id));
while (!IS_NULL_id(over)) {
DECL_SPEC pds = DEREF_dspec(id_storage(over));
if (pds != dspec_mark) {
if (ds & dspec_alias) {
if (pds & dspec_alias) {
/* Both are using declarations */
IDENTIFIER a = DEREF_id(id_alias(id));
IDENTIFIER b = DEREF_id(id_alias(over));
if (EQ_id(a, b)) {
/* Duplicate declarations */
if (mem) {
ERROR err;
PTR(LOCATION) loc = id_loc(over);
err = ERR_class_mem_redecl(over, loc);
report(crt_loc, err);
}
COPY_dspec(id_storage(over), dspec_mark);
ret++;
}
} else {
/* The first is a using declaration */
if (compare_functions(id, over, mem)) {
COPY_dspec(id_storage(id), dspec_mark);
ret++;
}
}
} else if (pds & dspec_alias) {
/* The second is a using declaration */
if (compare_functions(id, over, mem)) {
COPY_dspec(id_storage(over), dspec_mark);
ret++;
break;
}
}
}
over = DEREF_id(id_function_etc_over(over));
}
}
return ret;
}
/*
The interaction of using declarations with the hiding and overriding
of member functions is somewhat complex. It is implemented by this
routine which adjusts the declarations of the overloaded functions id
up to the existing declarations over. mem is true for member functions.
*/
IDENTIFIER
hide_functions(IDENTIFIER id, IDENTIFIER over, int mem)
{
if (!IS_NULL_id(over)) {
int marked = 0;
IDENTIFIER pid = id;
while (!EQ_id(pid, over)) {
marked += mark_functions(pid, mem);
pid = DEREF_id(id_function_etc_over(pid));
}
if (marked) {
id = remove_functions(id);
}
pid = id;
while (!IS_NULL_id(pid)) {
/* Mark template functions */
DECL_SPEC ds = DEREF_dspec(id_storage(pid));
if (ds & dspec_template) {
templ_func_decl(id);
break;
}
pid = DEREF_id(id_function_etc_over(pid));
}
}
return id;
}
/*
A member name in a using declaration should be visible from a direct
base class. This routine checks whether the member id meets this
criterion by comparing it with its look-up in the direct base
classes, pid.
*/
static int
using_visible(IDENTIFIER id, IDENTIFIER pid)
{
while (!IS_NULL_id(pid)) {
IDENTIFIER qid = DEREF_id(id_alias(pid));
if (EQ_id(qid, id)) {
return 1;
}
switch (TAG_id(pid)) {
case id_function_tag:
case id_mem_func_tag:
case id_stat_mem_func_tag:
/* Check overloaded functions */
pid = DEREF_id(id_function_etc_over(pid));
break;
case id_ambig_tag: {
/* Check ambiguous identifiers */
LIST(IDENTIFIER)pids;
pids = DEREF_list(id_ambig_ids(pid));
while (!IS_NULL_list(pids)) {
pid = DEREF_id(HEAD_list(pids));
if (using_visible(id, pid)) {
return 1;
}
pids = TAIL_list(pids);
}
return 0;
}
default:
/* Other identifiers */
return 0;
}
}
return 0;
}
/*
This routine processes a using-declaration of the identifier id in
the case when this declaration is a member-declaration.
*/
static IDENTIFIER
using_member(IDENTIFIER id, int type)
{
MEMBER mem;
IDENTIFIER aid;
IDENTIFIER pid;
/* Check the identifier */
NAMESPACE cns = crt_namespace;
HASHID nm = DEREF_hashid(id_name(id));
GRAPH gr = is_subfield(cns, id);
if (IS_NULL_graph(gr)) {
/* id is not a member of a base class */
CLASS_TYPE ct = crt_class;
report(crt_loc, ERR_dcl_nspace_udecl_base(id, ct));
return NULL_id;
} else {
GRAPH gu = DEREF_graph(graph_up(gr));
GRAPH gt = DEREF_graph(graph_top(gr));
if (EQ_graph(gt, gr)) {
/* id is a member of the current class */
report(crt_loc, ERR_dcl_nspace_udecl_mem(id));
return id;
}
if (!EQ_graph(gt, gu)) {
/* Not a member of a direct base class */
IDENTIFIER bid = search_base_field(cns, nm, type, 0);
aid = id;
while (!IS_NULL_id(aid)) {
IDENTIFIER qid = find_template(aid, 1);
if (IS_NULL_id(qid)) {
qid = aid;
}
qid = DEREF_id(id_alias(qid));
if (!using_visible(qid, bid)) {
CLASS_TYPE ct = crt_class;
report(crt_loc, ERR_dcl_nspace_udecl_vis(aid, ct));
break;
}
if (!IS_id_function_etc(aid)) {
break;
}
aid = DEREF_id(id_function_etc_over(aid));
}
}
}
/* Check declarations */
mem = search_member(cns, nm, 1);
if (type) {
DECL_SPEC ds = DEREF_dspec(id_storage(id));
if (ds & dspec_template) {
pid = DEREF_id(member_id(mem));
} else {
pid = type_member(mem, 3);
}
} else {
pid = DEREF_id(member_id(mem));
if (!IS_NULL_id(pid) && is_tagged_type(pid)) {
/* Allow hiding of non-template classes */
DECL_SPEC ds = DEREF_dspec(id_storage(pid));
if (!(ds & dspec_template)) {
pid = NULL_id;
}
}
}
if (!IS_NULL_id(pid)) {
DECL_SPEC ds = DEREF_dspec(id_storage(pid));
if ((ds & dspec_inherit) && !(ds & dspec_alias)) {
/* Ignore inherited members */
pid = NULL_id;
} else {
IDENTIFIER rid = DEREF_id(id_alias(id));
IDENTIFIER qid = DEREF_id(id_alias(pid));
if (EQ_id(rid, qid)) {
/* Redeclaration of existing meaning */
if (!type) {
PTR(LOCATION)loc = id_loc(pid);
ERROR err =
ERR_class_mem_redecl(pid, loc);
report(crt_loc, err);
}
adjust_access(pid, crt_access, 1);
return pid;
}
if (IS_id_function_etc(id) && IS_id_function_etc(pid)) {
/* Both new and old meanings are functions */
/* EMPTY */
} else {
/* One meaning is not a function */
PTR(LOCATION) loc = id_loc(pid);
ERROR err =
ERR_dcl_nspace_udecl_multi(pid, loc);
report(crt_loc, err);
return NULL_id;
}
}
}
/* Find inherited member */
id = search_subfield(cns, gr, id);
aid = alias_id(id, cns, pid, 1);
if (!IS_NULL_id(pid)) {
/* Deal with function hiding */
aid = hide_functions(aid, pid, 1);
}
adjust_access(id, crt_access, 1);
if (type) {
set_type_member(mem, aid);
} else {
set_member(mem, aid);
}
return aid;
}
/*
This routine processes a using-declaration of the identifier id in
the case when this declaration is not a member-declaration.
*/
static IDENTIFIER
using_name(IDENTIFIER id)
{
int type;
HASHID nm;
MEMBER mem;
IDENTIFIER pid;
/* Check the identifier */
NAMESPACE cns = crt_namespace;
NAMESPACE ns = DEREF_nspace(id_parent(id));
if (IS_nspace_ctype(ns)) {
/* id denotes a class member */
report(crt_loc, ERR_dcl_nspace_udecl_id(id));
switch (TAG_id(id)) {
case id_member_tag:
case id_stat_member_tag:
case id_mem_func_tag:
case id_stat_mem_func_tag:
/* Don't even try in these cases */
return NULL_id;
}
}
/* Check declarations */
nm = DEREF_hashid(id_name(id));
mem = search_member(cns, nm, 1);
type = is_tagged_type(id);
if (type) {
DECL_SPEC ds = DEREF_dspec(id_storage(id));
if (ds & dspec_template) {
pid = DEREF_id(member_id(mem));
} else {
pid = type_member(mem, 3);
}
} else {
pid = DEREF_id(member_id(mem));
if (!IS_id_nspace_name_etc(id)) {
if (!IS_NULL_id(pid) && is_tagged_type(pid)) {
/* Allow hiding of non-template classes */
DECL_SPEC ds = DEREF_dspec(id_storage(pid));
if (!(ds & dspec_template)) {
pid = NULL_id;
}
}
}
}
if (!IS_NULL_id(pid)) {
IDENTIFIER qid = DEREF_id(id_alias(pid));
if (EQ_id(id, qid)) {
/* Redeclaration of existing meaning */
if (EQ_id(id, pid)) {
report(crt_loc, ERR_dcl_nspace_udecl_mem(id));
}
return pid;
}
if (IS_id_function_etc(id) && IS_id_function_etc(pid)) {
/* Both new and old meanings are functions */
/* EMPTY */
} else {
/* Invalid redeclaration */
PTR(LOCATION) loc = id_loc(pid);
ERROR err = ERR_dcl_nspace_udecl_multi(pid, loc);
report(crt_loc, err);
pid = NULL_id;
}
}
/* Create the alias */
id = alias_id(id, cns, pid, 1);
if (!IS_NULL_id(pid)) {
/* Deal with function hiding */
id = hide_functions(id, pid, 0);
}
if (type) {
set_type_member(mem, id);
} else {
set_member(mem, id);
}
return id;
}
/*
This routine processes a using-declaration of the identifier id. Note
that this includes the access declarations used to modify access to
class members.
*/
IDENTIFIER
using_identifier(IDENTIFIER id)
{
/* Identifier must be qualified */
MEMBER mem;
HASHID unm;
IDENTIFIER cid;
IDENTIFIER uid = id;
NAMESPACE uns = DEREF_nspace(id_parent(uid));
uid = constr_name(uns, uid);
unm = DEREF_hashid(id_name(uid));
if (crt_id_qualifier == qual_none) {
report(crt_loc, ERR_dcl_nspace_udecl_unqual());
return uid;
}
/* Report undefined and ambiguous identifiers */
switch (TAG_id(uid)) {
case id_ambig_tag: {
/* Introduce all the ambiguous meanings */
LIST(IDENTIFIER) pids = DEREF_list(id_ambig_ids(uid));
while (!IS_NULL_list(pids)) {
IDENTIFIER pid = DEREF_id(HEAD_list(pids));
IGNORE using_identifier(pid);
pids = TAIL_list(pids);
}
uid = find_qual_id(crt_namespace, unm, 0, 0);
return uid;
}
case id_undef_tag:
/* Report undeclared identifiers */
report(crt_loc, ERR_lookup_qual_undef(unm, uns));
return uid;
}
/* Can have constructors or destructors */
switch (TAG_hashid(unm)) {
case hashid_constr_tag:
case hashid_destr_tag:
report(crt_loc, ERR_dcl_nspace_udecl_constr(uid));
return uid;
}
/* Check for hidden type names */
mem = search_member(uns, unm, 0);
cid = type_member(mem, 1);
if (EQ_id(cid, uid)) {
cid = NULL_id;
}
/* Process the declaration */
if (in_class_defn) {
if (!IS_NULL_id(cid)) {
IGNORE using_member(cid, 1);
}
uid = using_member(uid, 0);
} else {
if (!IS_NULL_id(cid)) {
cid = DEREF_id(id_alias(cid));
IGNORE using_name(cid);
}
uid = DEREF_id(id_alias(uid));
uid = using_name(uid);
}
if (IS_NULL_id(uid)) {
uid = id;
} else {
/* Check for hiding */
if (option(OPT_decl_hide)) {
switch (TAG_id(id)) {
case id_variable_tag:
case id_function_tag:
check_hiding(uid);
break;
}
}
}
return uid;
}
/*
This routine processes a using-declaration involving the type t
declared using typename.
*/
void
using_typename(TYPE t)
{
UNUSED(t);
return;
}
/*
This routine redeclares the identifier id in the namespace ns.
*/
IDENTIFIER
redeclare_id(NAMESPACE ns, IDENTIFIER id)
{
IDENTIFIER old_id;
int cl = is_tagged_type(id);
HASHID nm = DEREF_hashid(id_name(id));
MEMBER mem = search_member(ns, nm, 1);
DECL_SPEC ds = DEREF_dspec(id_storage(id));
if (cl) {
old_id = type_member(mem, 3);
} else {
old_id = DEREF_id(member_id(mem));
}
if (!IS_NULL_id(old_id)) {
PTR(LOCATION) loc = id_loc(old_id);
report(crt_loc, ERR_basic_odr_decl(old_id, loc));
}
if (cl) {
set_type_member(mem, id);
} else {
set_member(mem, id);
}
ds |= dspec_reserve;
COPY_dspec(id_storage(id), ds);
COPY_nspace(id_parent(id), ns);
return id;
}
/*
This routine checks whether the identifier id is member of an
anonymous union.
*/
int
is_anon_member(IDENTIFIER id)
{
DECL_SPEC ds = DEREF_dspec(id_storage(id));
if (ds & dspec_reserve) {
IDENTIFIER pid = DEREF_id(id_alias(id));
if (!EQ_id(pid, id)) {
TYPE s = DEREF_type(id_variable_etc_type(pid));
if (IS_type_compound(s)) {
TYPE t = DEREF_type(id_variable_etc_type(id));
if (!eq_type(s, t)) {
return 1;
}
}
}
}
return 0;
}
/*
This routine redeclares the member id of an anonymous union. The
remaining arguments are as in redecl_anon_union.
*/
static IDENTIFIER
redecl_anon_member(IDENTIFIER id, CLASS_TYPE ct, DECL_SPEC ds, IDENTIFIER obj)
{
IDENTIFIER pid = NULL_id;
HASHID nm = DEREF_hashid(id_name(id));
if (!IS_hashid_anon(nm)) {
switch (TAG_id(id)) {
case id_member_tag: {
/* Redeclare a type member */
TYPE t = DEREF_type(id_member_type(id));
DEREF_loc(id_loc(id), crt_loc);
if (IS_id_member(obj)) {
NAMESPACE cns = crt_namespace;
OFFSET off1 = DEREF_off(id_member_off(id));
OFFSET off2 = DEREF_off(id_member_off(obj));
id = find_id(nm);
id = constr_name(cns, id);
id = make_member_decl(ds, t, id, 0);
MAKE_off_plus(off2, off1, off1);
COPY_off(id_member_off(id), off1);
} else {
id = make_object_decl(ds, t, id, 0);
obj = DEREF_id(id_alias(obj));
COPY_id(id_alias(id), obj);
}
pid = id;
break;
}
case id_class_name_tag: {
/* Redeclare a class name */
int templ = 0;
CLASS_TYPE cs;
TYPE t = DEREF_type(id_class_name_defn(id));
while (IS_type_templ(t)) {
templ = 1;
t = DEREF_type(type_templ_defn(t));
}
cs = DEREF_ctype(type_compound_defn(t));
if (!eq_ctype(ct, cs)) {
NAMESPACE cns = crt_namespace;
if (templ) {
/* Shouldn't be a template class */
LOCATION loc;
DEREF_loc(id_loc(id), loc);
report(loc, ERR_temp_decl_bad());
}
pid = redeclare_id(cns, id);
}
break;
}
case id_enum_name_tag:
case id_class_alias_tag:
case id_enum_alias_tag:
case id_type_alias_tag:
case id_enumerator_tag: {
/* Redeclare other identifiers */
NAMESPACE cns = crt_namespace;
pid = redeclare_id(cns, id);
break;
}
}
}
return pid;
}
/*
This routine redeclares all the members of the anonymous union obj of
type ct in the current namespace using the declaration specifiers ds.
The routine returns false if there are no members to redeclare. The
redeclared members are added to the extra field of the namespace given
by ct.
*/
int
redecl_anon_union(CLASS_TYPE ct, DECL_SPEC ds, IDENTIFIER obj)
{
int ok = 0;
MEMBER mem;
NAMESPACE ns;
LOCATION old_loc;
bad_crt_loc++;
old_loc = crt_loc;
ds |= dspec_reserve;
crt_id_qualifier = qual_none;
crt_templ_qualifier = 0;
ns = DEREF_nspace(ctype_member(ct));
mem = DEREF_member(nspace_ctype_first(ns));
while (!IS_NULL_member(mem)) {
IDENTIFIER id = DEREF_id(member_id(mem));
IDENTIFIER aid = DEREF_id(member_alt(mem));
if (!IS_NULL_id(aid) && !EQ_id(aid, id)) {
aid = redecl_anon_member(aid, ct, ds, obj);
if (!IS_NULL_id(aid)) {
ok = 1;
}
}
if (!IS_NULL_id(id)) {
id = redecl_anon_member(id, ct, ds, obj);
if (!IS_NULL_id(id)) {
ok = 1;
}
}
mem = DEREF_member(member_next(mem));
}
crt_loc = old_loc;
bad_crt_loc--;
return ok;
}
| 24.370087 | 78 | 0.655736 | [
"object"
] |
6cabbcc9cfeac742a9a9001a428f2f18a04fa619 | 4,937 | h | C | tpm/attestation/common/tpm_utility_v1.h | Keneral/asystem | df12381b72ef3d629c8efc61100cc8c714195320 | [
"Unlicense"
] | null | null | null | tpm/attestation/common/tpm_utility_v1.h | Keneral/asystem | df12381b72ef3d629c8efc61100cc8c714195320 | [
"Unlicense"
] | null | null | null | tpm/attestation/common/tpm_utility_v1.h | Keneral/asystem | df12381b72ef3d629c8efc61100cc8c714195320 | [
"Unlicense"
] | null | null | null | //
// Copyright (C) 2015 The Android Open Source Project
//
// 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.
//
#ifndef ATTESTATION_COMMON_TPM_UTILITY_V1_H_
#define ATTESTATION_COMMON_TPM_UTILITY_V1_H_
#include "attestation/common/tpm_utility.h"
#include <string>
#include <base/macros.h>
#include <trousers/scoped_tss_type.h>
#include <trousers/tss.h>
namespace attestation {
// A TpmUtility implementation for TPM v1.2 modules.
class TpmUtilityV1 : public TpmUtility {
public:
TpmUtilityV1() = default;
~TpmUtilityV1() override;
// Initializes a TpmUtilityV1 instance. This method must be called
// successfully before calling any other methods.
bool Initialize();
// TpmUtility methods.
bool IsTpmReady() override;
bool ActivateIdentity(const std::string& delegate_blob,
const std::string& delegate_secret,
const std::string& identity_key_blob,
const std::string& asym_ca_contents,
const std::string& sym_ca_attestation,
std::string* credential) override;
bool CreateCertifiedKey(KeyType key_type,
KeyUsage key_usage,
const std::string& identity_key_blob,
const std::string& external_data,
std::string* key_blob,
std::string* public_key,
std::string* public_key_tpm_format,
std::string* key_info,
std::string* proof) override;
bool SealToPCR0(const std::string& data, std::string* sealed_data) override;
bool Unseal(const std::string& sealed_data, std::string* data) override;
bool GetEndorsementPublicKey(std::string* public_key) override;
bool Unbind(const std::string& key_blob,
const std::string& bound_data,
std::string* data) override;
bool Sign(const std::string& key_blob,
const std::string& data_to_sign,
std::string* signature) override;
private:
// Populates |context_handle| with a valid TSS_HCONTEXT and |tpm_handle| with
// its matching TPM object iff the context can be created and a TPM object
// exists in the TSS. Returns true on success.
bool ConnectContext(trousers::ScopedTssContext* context_handle,
TSS_HTPM* tpm_handle);
// Populates |context_handle| with a valid TSS_HCONTEXT and |tpm_handle| with
// its matching TPM object authorized by the given |delegate_blob| and
// |delegate_secret|. Returns true on success.
bool ConnectContextAsDelegate(const std::string& delegate_blob,
const std::string& delegate_secret,
trousers::ScopedTssContext* context,
TSS_HTPM* tpm);
// Sets up srk_handle_ if necessary. Returns true iff the SRK is ready.
bool SetupSrk();
// Loads the storage root key (SRK) and populates |srk_handle|. The
// |context_handle| must be connected and valid. Returns true on success.
bool LoadSrk(TSS_HCONTEXT context_handle, trousers::ScopedTssKey* srk_handle);
// Loads a key in the TPM given a |key_blob| and a |parent_key_handle|. The
// |context_handle| must be connected and valid. Returns true and populates
// |key_handle| on success.
bool LoadKeyFromBlob(const std::string& key_blob,
TSS_HCONTEXT context_handle,
TSS_HKEY parent_key_handle,
trousers::ScopedTssKey* key_handle);
// Retrieves a |data| attribute defined by |flag| and |sub_flag| from a TSS
// |object_handle|. The |context_handle| is only used for TSS memory
// management.
bool GetDataAttribute(TSS_HCONTEXT context_handle,
TSS_HOBJECT object_handle,
TSS_FLAG flag,
TSS_FLAG sub_flag,
std::string* data);
// Converts a public in TPM_PUBKEY format to a DER-encoded RSAPublicKey.
bool ConvertPublicKeyToDER(const std::string& public_key,
std::string* public_key_der);
bool is_ready_{false};
trousers::ScopedTssContext context_handle_;
TSS_HTPM tpm_handle_{0};
trousers::ScopedTssKey srk_handle_{0};
DISALLOW_COPY_AND_ASSIGN(TpmUtilityV1);
};
} // namespace attestation
#endif // ATTESTATION_COMMON_TPM_UTILITY_V1_H_
| 40.801653 | 80 | 0.660523 | [
"object"
] |
6cb568fd409cbf773b219a4f2e3e1bb1d40b6ae3 | 38,101 | c | C | src/cpp/qpsolver/cvxopt/src/C/misc_solvers.c | Hap-Hugh/quicksel | 10eee90b759638d5c54ba19994ae8e36e90e12b8 | [
"Apache-2.0"
] | 15 | 2020-07-07T16:32:53.000Z | 2022-03-16T14:23:23.000Z | src/cpp/qpsolver/cvxopt/src/C/misc_solvers.c | Hap-Hugh/quicksel | 10eee90b759638d5c54ba19994ae8e36e90e12b8 | [
"Apache-2.0"
] | 2 | 2020-09-02T15:25:39.000Z | 2020-09-24T08:37:18.000Z | src/cpp/qpsolver/cvxopt/src/C/misc_solvers.c | Hap-Hugh/quicksel | 10eee90b759638d5c54ba19994ae8e36e90e12b8 | [
"Apache-2.0"
] | 6 | 2020-08-14T22:02:07.000Z | 2021-03-31T07:08:29.000Z | /*
* Copyright 2012-2016 M. Andersen and L. Vandenberghe.
* Copyright 2010-2011 L. Vandenberghe.
* Copyright 2004-2009 J. Dahl and L. Vandenberghe.
*
* This file is part of CVXOPT.
*
* CVXOPT is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* CVXOPT is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Python.h"
#include "cvxopt.h"
#include "misc.h"
#include "math.h"
#include "float.h"
PyDoc_STRVAR(misc_solvers__doc__, "Miscellaneous functions used by the "
"CVXOPT solvers.");
extern void dcopy_(int *n, double *x, int *incx, double *y, int *incy);
extern double dnrm2_(int *n, double *x, int *incx);
extern double ddot_(int *n, double *x, int *incx, double *y, int *incy);
extern void dscal_(int *n, double *alpha, double *x, int *incx);
extern void daxpy_(int *n, double *alpha, double *x, int *incx, double *y,
int *incy);
extern void dtbmv_(char *uplo, char *trans, char *diag, int *n, int *k,
double *A, int *lda, double *x, int *incx);
extern void dtbsv_(char *uplo, char *trans, char *diag, int *n, int *k,
double *A, int *lda, double *x, int *incx);
extern void dgemv_(char* trans, int *m, int *n, double *alpha, double *A,
int *lda, double *x, int *incx, double *beta, double *y, int *incy);
extern void dger_(int *m, int *n, double *alpha, double *x, int *incx,
double *y, int *incy, double *A, int *lda);
extern void dtrmm_(char *side, char *uplo, char *transa, char *diag,
int *m, int *n, double *alpha, double *A, int *lda, double *B,
int *ldb);
extern void dsyr2k_(char *uplo, char *trans, int *n, int *k, double *alpha,
double *A, int *lda, double *B, int *ldb, double *beta, double *C,
int *ldc);
extern void dlacpy_(char *uplo, int *m, int *n, double *A, int *lda,
double *B, int *ldb);
extern void dsyevr_(char *jobz, char *range, char *uplo, int *n, double *A,
int *ldA, double *vl, double *vu, int *il, int *iu, double *abstol,
int *m, double *W, double *Z, int *ldZ, int *isuppz, double *work,
int *lwork, int *iwork, int *liwork, int *info);
extern void dsyevd_(char *jobz, char *uplo, int *n, double *A, int *ldA,
double *W, double *work, int *lwork, int *iwork, int *liwork,
int *info);
static char doc_scale[] =
"Applies Nesterov-Todd scaling or its inverse.\n\n"
"scale(x, W, trans = 'N', inverse = 'N')\n\n"
"Computes\n\n"
" x := W*x (trans is 'N', inverse = 'N')\n"
" x := W^T*x (trans is 'T', inverse = 'N')\n"
" x := W^{-1}*x (trans is 'N', inverse = 'I')\n"
" x := W^{-T}*x (trans is 'T', inverse = 'I').\n\n"
"x is a dense 'd' matrix.\n\n"
"W is a dictionary with entries:\n\n"
"- W['dnl']: positive vector\n"
"- W['dnli']: componentwise inverse of W['dnl']\n"
"- W['d']: positive vector\n"
"- W['di']: componentwise inverse of W['d']\n"
"- W['v']: lists of 2nd order cone vectors with unit hyperbolic \n"
" norms\n"
"- W['beta']: list of positive numbers\n"
"- W['r']: list of square matrices\n"
"- W['rti']: list of square matrices. rti[k] is the inverse\n"
" transpose of r[k]. \n\n"
"The 'dnl' and 'dnli' entries are optional, and only present when \n"
"the function is called from the nonlinear solver.";
static PyObject* scale(PyObject *self, PyObject *args, PyObject *kwrds)
{
matrix *x, *d, *vk, *rk;
PyObject *W, *v, *beta, *r, *betak;
#if PY_MAJOR_VERSION >= 3
int trans = 'N', inverse = 'N';
#else
char trans = 'N', inverse = 'N';
#endif
int m, n, xr, xc, ind = 0, int0 = 0, int1 = 1, i, k, inc, len, ld,
maxn, N;
double b, dbl0 = 0.0, dbl1 = 1.0, dblm1 = -1.0, dbl2 = 2.0, dbl5 = 0.5,
*wrk;
char *kwlist[] = {"x", "W", "trans", "inverse", NULL};
#if PY_MAJOR_VERSION >= 3
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO|CC", kwlist,
&x, &W, &trans, &inverse)) return NULL;
#else
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO|cc", kwlist,
&x, &W, &trans, &inverse)) return NULL;
#endif
xr = x->nrows;
xc = x->ncols;
/*
* Scaling for nonlinear component xk is xk := dnl .* xk; inverse is
* xk ./ dnl = dnli .* xk, where dnl = W['dnl'], dnli = W['dnli'].
*/
if ((d = (inverse == 'N') ? (matrix *) PyDict_GetItemString(W, "dnl") :
(matrix *) PyDict_GetItemString(W, "dnli"))){
m = len(d);
for (i = 0; i < xc; i++)
dtbmv_("L", "N", "N", &m, &int0, MAT_BUFD(d), &int1,
MAT_BUFD(x) + i*xr, &int1);
ind += m;
}
/*
* Scaling for 'l' component xk is xk := d .* xk; inverse scaling is
* xk ./ d = di .* xk, where d = W['d'], di = W['di'].
*/
if (!(d = (inverse == 'N') ? (matrix *) PyDict_GetItemString(W, "d") :
(matrix *) PyDict_GetItemString(W, "di"))){
PyErr_SetString(PyExc_KeyError, "missing item W['d'] or W['di']");
return NULL;
}
m = len(d);
for (i = 0; i < xc; i++)
dtbmv_("L", "N", "N", &m, &int0, MAT_BUFD(d), &int1, MAT_BUFD(x)
+ i*xr + ind, &int1);
ind += m;
/*
* Scaling for 'q' component is
*
* xk := beta * (2*v*v' - J) * xk
* = beta * (2*v*(xk'*v)' - J*xk)
*
* where beta = W['beta'][k], v = W['v'][k], J = [1, 0; 0, -I].
*
* Inverse scaling is
*
* xk := 1/beta * (2*J*v*v'*J - J) * xk
* = 1/beta * (-J) * (2*v*((-J*xk)'*v)' + xk).
*/
v = PyDict_GetItemString(W, "v");
beta = PyDict_GetItemString(W, "beta");
N = (int) PyList_Size(v);
if (!(wrk = (double *) calloc(xc, sizeof(double))))
return PyErr_NoMemory();
for (k = 0; k < N; k++){
vk = (matrix *) PyList_GetItem(v, (Py_ssize_t) k);
m = vk->nrows;
if (inverse == 'I')
dscal_(&xc, &dblm1, MAT_BUFD(x) + ind, &xr);
ld = MAX(xr, 1);
dgemv_("T", &m, &xc, &dbl1, MAT_BUFD(x) + ind, &ld, MAT_BUFD(vk),
&int1, &dbl0, wrk, &int1);
dscal_(&xc, &dblm1, MAT_BUFD(x) + ind, &xr);
dger_(&m, &xc, &dbl2, MAT_BUFD(vk), &int1, wrk, &int1,
MAT_BUFD(x) + ind, &ld);
if (inverse == 'I')
dscal_(&xc, &dblm1, MAT_BUFD(x) + ind, &xr);
betak = PyList_GetItem(beta, (Py_ssize_t) k);
b = PyFloat_AS_DOUBLE(betak);
if (inverse == 'I') b = 1.0 / b;
for (i = 0; i < xc; i++)
dscal_(&m, &b, MAT_BUFD(x) + ind + i*xr, &int1);
ind += m;
}
free(wrk);
/*
* Scaling for 's' component xk is
*
* xk := vec( r' * mat(xk) * r ) if trans = 'N'
* xk := vec( r * mat(xk) * r' ) if trans = 'T'.
*
* r is kth element of W['r'].
*
* Inverse scaling is
*
* xk := vec( rti * mat(xk) * rti' ) if trans = 'N'
* xk := vec( rti' * mat(xk) * rti ) if trans = 'T'.
*
* rti is kth element of W['rti'].
*/
r = (inverse == 'N') ? PyDict_GetItemString(W, "r") :
PyDict_GetItemString(W, "rti");
N = (int) PyList_Size(r);
for (k = 0, maxn = 0; k < N; k++){
rk = (matrix *) PyList_GetItem(r, (Py_ssize_t) k);
maxn = MAX(maxn, rk->nrows);
}
if (!(wrk = (double *) calloc(maxn*maxn, sizeof(double))))
return PyErr_NoMemory();
for (k = 0; k < N; k++){
rk = (matrix *) PyList_GetItem(r, (Py_ssize_t) k);
n = rk->nrows;
for (i = 0; i < xc; i++){
/* scale diagonal of rk by 0.5 */
inc = n + 1;
dscal_(&n, &dbl5, MAT_BUFD(x) + ind + i*xr, &inc);
/* wrk = r*tril(x) if inverse is 'N' and trans is 'T' or
* inverse is 'I' and trans is 'N'
* wrk = tril(x)*r otherwise. */
len = n*n;
dcopy_(&len, MAT_BUFD(rk), &int1, wrk, &int1);
ld = MAX(1, n);
dtrmm_( (( inverse == 'N' && trans == 'T') || ( inverse == 'I'
&& trans == 'N')) ? "R" : "L", "L", "N", "N", &n, &n,
&dbl1, MAT_BUFD(x) + ind + i*xr, &ld, wrk, &ld);
/* x := (r*wrk' + wrk*r') if inverse is 'N' and trans is 'T'
* or inverse is 'I' and trans is 'N'
* x := (r'*wrk + wrk'*r) otherwise. */
dsyr2k_("L", ((inverse == 'N' && trans == 'T') ||
(inverse == 'I' && trans == 'N')) ? "N" : "T", &n, &n,
&dbl1, MAT_BUFD(rk), &ld, wrk, &ld, &dbl0, MAT_BUFD(x) +
ind + i*xr, &ld);
}
ind += n*n;
}
free(wrk);
return Py_BuildValue("");
}
static char doc_scale2[] =
"Multiplication with square root of the Hessian.\n\n"
"scale2(lmbda, x, dims, mnl = 0, inverse = 'N')\n\n"
"Computes\n\n"
"Evaluates\n\n"
" x := H(lambda^{1/2}) * x (inverse is 'N')\n"
" x := H(lambda^{-1/2}) * x (inverse is 'I').\n\n"
"H is the Hessian of the logarithmic barrier.";
static PyObject* scale2(PyObject *self, PyObject *args, PyObject *kwrds)
{
matrix *lmbda, *x;
PyObject *dims, *O, *Ok;
#if PY_MAJOR_VERSION >= 3
int inverse = 'N';
#else
char inverse = 'N';
#endif
double a, lx, x0, b, *c = NULL, *sql = NULL;
int m = 0, mk, i, j, len, int0 = 0, int1 = 1, maxn = 0, ind2;
char *kwlist[] = {"lmbda", "x", "dims", "mnl", "inverse", NULL};
#if PY_MAJOR_VERSION >= 3
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OOO|iC", kwlist, &lmbda,
&x, &dims, &m, &inverse)) return NULL;
#else
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OOO|ic", kwlist, &lmbda,
&x, &dims, &m, &inverse)) return NULL;
#endif
/*
* For nonlinear and 'l' blocks:
*
* xk := xk ./ l (invers is 'N')
* xk := xk .* l (invers is 'I')
*
* where l is the first mnl + dims['l'] components of lmbda.
*/
O = PyDict_GetItemString(dims, "l");
#if PY_MAJOR_VERSION >= 3
m += (int) PyLong_AsLong(O);
#else
m += (int) PyInt_AsLong(O);
#endif
if (inverse == 'N')
dtbsv_("L", "N", "N", &m, &int0, MAT_BUFD(lmbda), &int1,
MAT_BUFD(x), &int1);
else
dtbmv_("L", "N", "N", &m, &int0, MAT_BUFD(lmbda), &int1,
MAT_BUFD(x), &int1);
/*
* For 'q' blocks, if inverse is 'N',
*
* xk := 1/a * [ l'*J*xk;
* xk[1:] - (xk[0] + l'*J*xk) / (l[0] + 1) * l[1:] ].
*
* If inverse is 'I',
*
* xk := a * [ l'*xk;
* xk[1:] + (xk[0] + l'*xk) / (l[0] + 1) * l[1:] ].
*
* a = sqrt(lambda_k' * J * lambda_k), l = lambda_k / a.
*/
O = PyDict_GetItemString(dims, "q");
for (i = 0; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
mk = (int) PyLong_AsLong(Ok);
#else
mk = (int) PyInt_AsLong(Ok);
#endif
len = mk - 1;
a = dnrm2_(&len, MAT_BUFD(lmbda) + m + 1, &int1);
a = sqrt(MAT_BUFD(lmbda)[m] + a) * sqrt(MAT_BUFD(lmbda)[m] - a);
if (inverse == 'N')
lx = ( MAT_BUFD(lmbda)[m] * MAT_BUFD(x)[m] -
ddot_(&len, MAT_BUFD(lmbda) + m + 1, &int1, MAT_BUFD(x) + m
+ 1, &int1) ) / a;
else
lx = ddot_(&mk, MAT_BUFD(lmbda) + m, &int1, MAT_BUFD(x) + m,
&int1) / a;
x0 = MAT_BUFD(x)[m];
MAT_BUFD(x)[m] = lx;
b = (x0 + lx) / (MAT_BUFD(lmbda)[m]/a + 1.0) / a;
if (inverse == 'N') b *= -1.0;
daxpy_(&len, &b, MAT_BUFD(lmbda) + m + 1, &int1,
MAT_BUFD(x) + m + 1, &int1);
if (inverse == 'N') a = 1.0 / a;
dscal_(&mk, &a, MAT_BUFD(x) + m, &int1);
m += mk;
}
/*
* For the 's' blocks, if inverse is 'N',
*
* xk := vec( diag(l)^{-1/2} * mat(xk) * diag(k)^{-1/2}).
*
* If inverse is 'I',
*
* xk := vec( diag(l)^{1/2} * mat(xk) * diag(k)^{1/2}).
*
* where l is kth block of lambda.
*
* We scale upper and lower triangular part of mat(xk) because the
* inverse operation will be applied to nonsymmetric matrices.
*/
O = PyDict_GetItemString(dims, "s");
for (i = 0; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
maxn = MAX(maxn, (int) PyLong_AsLong(Ok));
#else
maxn = MAX(maxn, (int) PyInt_AsLong(Ok));
#endif
}
if (!(c = (double *) calloc(maxn, sizeof(double))) ||
!(sql = (double *) calloc(maxn, sizeof(double)))){
free(c); free(sql);
return PyErr_NoMemory();
}
ind2 = m;
for (i = 0; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
mk = (int) PyLong_AsLong(Ok);
#else
mk = (int) PyInt_AsLong(Ok);
#endif
for (j = 0; j < mk; j++)
sql[j] = sqrt(MAT_BUFD(lmbda)[ind2 + j]);
for (j = 0; j < mk; j++){
dcopy_(&mk, sql, &int1, c, &int1);
b = sqrt(MAT_BUFD(lmbda)[ind2 + j]);
dscal_(&mk, &b, c, &int1);
if (inverse == 'N')
dtbsv_("L", "N", "N", &mk, &int0, c, &int1, MAT_BUFD(x) +
m + j*mk, &int1);
else
dtbmv_("L", "N", "N", &mk, &int0, c, &int1, MAT_BUFD(x) +
m + j*mk, &int1);
}
m += mk*mk;
ind2 += mk;
}
free(c); free(sql);
return Py_BuildValue("");
}
static char doc_pack[] =
"Copy x to y using packed storage.\n\n"
"pack(x, y, dims, mnl = 0, offsetx = 0, offsety = 0)\n\n"
"The vector x is an element of S, with the 's' components stored in\n"
"unpacked storage. On return, x is copied to y with the 's' \n"
"components stored in packed storage and the off-diagonal entries \n"
"scaled by sqrt(2).";
static PyObject* pack(PyObject *self, PyObject *args, PyObject *kwrds)
{
matrix *x, *y;
PyObject *O, *Ok, *dims;
double a;
int i, k, nlq = 0, ox = 0, oy = 0, np, iu, ip, int1 = 1, len, n;
char *kwlist[] = {"x", "y", "dims", "mnl", "offsetx", "offsety", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OOO|iii", kwlist, &x,
&y, &dims, &nlq, &ox, &oy)) return NULL;
O = PyDict_GetItemString(dims, "l");
#if PY_MAJOR_VERSION >= 3
nlq += (int) PyLong_AsLong(O);
#else
nlq += (int) PyInt_AsLong(O);
#endif
O = PyDict_GetItemString(dims, "q");
for (i = 0; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
nlq += (int) PyLong_AsLong(Ok);
#else
nlq += (int) PyInt_AsLong(Ok);
#endif
}
dcopy_(&nlq, MAT_BUFD(x) + ox, &int1, MAT_BUFD(y) + oy, &int1);
O = PyDict_GetItemString(dims, "s");
for (i = 0, np = 0, iu = ox + nlq, ip = oy + nlq; i < (int)
PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
n = (int) PyLong_AsLong(Ok);
#else
n = (int) PyInt_AsLong(Ok);
#endif
for (k = 0; k < n; k++){
len = n-k;
dcopy_(&len, MAT_BUFD(x) + iu + k*(n+1), &int1, MAT_BUFD(y) +
ip, &int1);
MAT_BUFD(y)[ip] /= sqrt(2.0);
ip += len;
}
np += n*(n+1)/2;
iu += n*n;
}
a = sqrt(2.0);
dscal_(&np, &a, MAT_BUFD(y) + oy + nlq, &int1);
return Py_BuildValue("");
}
static char doc_pack2[] =
"In-place version of pack().\n\n"
"pack2(x, dims, mnl = 0)\n\n"
"In-place version of pack(), which also accepts matrix arguments x.\n"
"The columns of x are elements of S, with the 's' components stored\n"
"in unpacked storage. On return, the 's' components are stored in\n"
"packed storage and the off-diagonal entries are scaled by sqrt(2).";
static PyObject* pack2(PyObject *self, PyObject *args, PyObject *kwrds)
{
matrix *x;
PyObject *O, *Ok, *dims;
double a = sqrt(2.0), *wrk;
int i, j, k, nlq = 0, iu, ip, len, n, maxn, xr, xc;
char *kwlist[] = {"x", "dims", "mnl", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO|i", kwlist, &x,
&dims, &nlq)) return NULL;
xr = x->nrows;
xc = x->ncols;
O = PyDict_GetItemString(dims, "l");
#if PY_MAJOR_VERSION >= 3
nlq += (int) PyLong_AsLong(O);
#else
nlq += (int) PyInt_AsLong(O);
#endif
O = PyDict_GetItemString(dims, "q");
for (i = 0; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
nlq += (int) PyLong_AsLong(Ok);
#else
nlq += (int) PyInt_AsLong(Ok);
#endif
}
O = PyDict_GetItemString(dims, "s");
for (i = 0, maxn = 0; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
maxn = MAX(maxn, (int) PyLong_AsLong(Ok));
#else
maxn = MAX(maxn, (int) PyInt_AsLong(Ok));
#endif
}
if (!maxn) return Py_BuildValue("");
if (!(wrk = (double *) calloc(maxn * xc, sizeof(double))))
return PyErr_NoMemory();
for (i = 0, iu = nlq, ip = nlq; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
n = (int) PyLong_AsLong(Ok);
#else
n = (int) PyInt_AsLong(Ok);
#endif
for (k = 0; k < n; k++){
len = n-k;
dlacpy_(" ", &len, &xc, MAT_BUFD(x) + iu + k*(n+1), &xr, wrk,
&maxn);
for (j = 1; j < len; j++)
dscal_(&xc, &a, wrk + j, &maxn);
dlacpy_(" ", &len, &xc, wrk, &maxn, MAT_BUFD(x) + ip, &xr);
ip += len;
}
iu += n*n;
}
free(wrk);
return Py_BuildValue("");
}
static char doc_unpack[] =
"Unpacks x into y.\n\n"
"unpack(x, y, dims, mnl = 0, offsetx = 0, offsety = 0)\n\n"
"The vector x is an element of S, with the 's' components stored in\n"
"unpacked storage and off-diagonal entries scaled by sqrt(2).\n"
"On return, x is copied to y with the 's' components stored in\n"
"unpacked storage.";
static PyObject* unpack(PyObject *self, PyObject *args, PyObject *kwrds)
{
matrix *x, *y;
PyObject *O, *Ok, *dims;
double a = 1.0 / sqrt(2.0);
int m = 0, ox = 0, oy = 0, int1 = 1, iu, ip, len, i, k, n;
char *kwlist[] = {"x", "y", "dims", "mnl", "offsetx", "offsety", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OOO|iii", kwlist, &x,
&y, &dims, &m, &ox, &oy)) return NULL;
O = PyDict_GetItemString(dims, "l");
#if PY_MAJOR_VERSION >= 3
m += (int) PyLong_AsLong(O);
#else
m += (int) PyInt_AsLong(O);
#endif
O = PyDict_GetItemString(dims, "q");
for (i = 0; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
m += (int) PyLong_AsLong(Ok);
#else
m += (int) PyInt_AsLong(Ok);
#endif
}
dcopy_(&m, MAT_BUFD(x) + ox, &int1, MAT_BUFD(y) + oy, &int1);
O = PyDict_GetItemString(dims, "s");
for (i = 0, ip = ox + m, iu = oy + m; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
n = (int) PyLong_AsLong(Ok);
#else
n = (int) PyInt_AsLong(Ok);
#endif
for (k = 0; k < n; k++){
len = n-k;
dcopy_(&len, MAT_BUFD(x) + ip, &int1, MAT_BUFD(y) + iu +
k*(n+1), &int1);
ip += len;
len -= 1;
dscal_(&len, &a, MAT_BUFD(y) + iu + k*(n+1) + 1, &int1);
}
iu += n*n;
}
return Py_BuildValue("");
}
static char doc_symm[] =
"Converts lower triangular matrix to symmetric.\n\n"
"symm(x, n, offset = 0)\n\n"
"Fills in the upper triangular part of the symmetric matrix stored\n"
"in x[offset : offset+n*n] using 'L' storage.";
static PyObject* symm(PyObject *self, PyObject *args, PyObject *kwrds)
{
matrix *x;
int n, ox = 0, k, len, int1 = 1;
char *kwlist[] = {"x", "n", "offset", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "Oi|i", kwlist, &x, &n,
&ox)) return NULL;
if (n > 1) for (k = 0; k < n; k++){
len = n-k-1;
dcopy_(&len, MAT_BUFD(x) + ox + k*(n+1) + 1, &int1, MAT_BUFD(x) +
ox + (k+1)*(n+1)-1, &n);
}
return Py_BuildValue("");
}
static char doc_sprod[] =
"The product x := (y o x).\n\n"
"sprod(x, y, dims, mnl = 0, diag = 'N')\n\n"
"If diag is 'D', the 's' part of y is diagonal and only the diagonal\n"
"is stored.";
static PyObject* sprod(PyObject *self, PyObject *args, PyObject *kwrds)
{
matrix *x, *y;
PyObject *dims, *O, *Ok;
int i, j, k, mk, len, maxn, ind = 0, ind2, int0 = 0, int1 = 1, ld;
double a, *A = NULL, dbl2 = 0.5, dbl0 = 0.0;
#if PY_MAJOR_VERSION >= 3
int diag = 'N';
#else
char diag = 'N';
#endif
char *kwlist[] = {"x", "y", "dims", "mnl", "diag", NULL};
#if PY_MAJOR_VERSION >= 3
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OOO|iC", kwlist, &x, &y,
&dims, &ind, &diag)) return NULL;
#else
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OOO|ic", kwlist, &x, &y,
&dims, &ind, &diag)) return NULL;
#endif
/*
* For nonlinear and 'l' blocks:
*
* yk o xk = yk .* xk
*/
O = PyDict_GetItemString(dims, "l");
#if PY_MAJOR_VERSION >= 3
ind += (int) PyLong_AsLong(O);
#else
ind += (int) PyInt_AsLong(O);
#endif
dtbmv_("L", "N", "N", &ind, &int0, MAT_BUFD(y), &int1, MAT_BUFD(x),
&int1);
/*
* For 'q' blocks:
*
* [ l0 l1' ]
* yk o xk = [ ] * xk
* [ l1 l0*I ]
*
* where yk = (l0, l1).
*/
O = PyDict_GetItemString(dims, "q");
for (i = 0; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
mk = (int) PyLong_AsLong(Ok);
#else
mk = (int) PyInt_AsLong(Ok);
#endif
a = ddot_(&mk, MAT_BUFD(y) + ind, &int1, MAT_BUFD(x) + ind, &int1);
len = mk - 1;
dscal_(&len, MAT_BUFD(y) + ind, MAT_BUFD(x) + ind + 1, &int1);
daxpy_(&len, MAT_BUFD(x) + ind, MAT_BUFD(y) + ind + 1, &int1,
MAT_BUFD(x) + ind + 1, &int1);
MAT_BUFD(x)[ind] = a;
ind += mk;
}
/*
* For the 's' blocks:
*
* yk o sk = .5 * ( Yk * mat(xk) + mat(xk) * Yk )
*
* where Yk = mat(yk) if diag is 'N' and Yk = diag(yk) if diag is 'D'.
*/
O = PyDict_GetItemString(dims, "s");
for (i = 0, maxn = 0; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
maxn = MAX(maxn, (int) PyLong_AsLong(Ok));
#else
maxn = MAX(maxn, (int) PyInt_AsLong(Ok));
#endif
}
if (diag == 'N'){
if (!(A = (double *) calloc(maxn * maxn, sizeof(double))))
return PyErr_NoMemory();
for (i = 0; i < (int) PyList_Size(O); ind += mk*mk, i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
mk = (int) PyLong_AsLong(Ok);
#else
mk = (int) PyInt_AsLong(Ok);
#endif
len = mk*mk;
dcopy_(&len, MAT_BUFD(x) + ind, &int1, A, &int1);
if (mk > 1) for (k = 0; k < mk; k++){
len = mk - k - 1;
dcopy_(&len, A + k*(mk+1) + 1, &int1, A + (k+1)*(mk+1)-1,
&mk);
dcopy_(&len, MAT_BUFD(y) + ind + k*(mk+1) + 1, &int1,
MAT_BUFD(y) + ind + (k+1)*(mk+1)-1, &mk);
}
ld = MAX(1, mk);
dsyr2k_("L", "N", &mk, &mk, &dbl2, A, &ld, MAT_BUFD(y) + ind,
&ld, &dbl0, MAT_BUFD(x) + ind, &ld);
}
}
else {
if (!(A = (double *) calloc(maxn, sizeof(double))))
return PyErr_NoMemory();
for (i = 0, ind2 = ind; i < (int) PyList_Size(O); ind += mk*mk,
ind2 += mk, i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
mk = (int) PyLong_AsLong(Ok);
#else
mk = (int) PyInt_AsLong(Ok);
#endif
for (k = 0; k < mk; k++){
len = mk - k;
dcopy_(&len, MAT_BUFD(y) + ind2 + k, &int1, A, &int1);
for (j = 0; j < len; j++) A[j] += MAT_BUFD(y)[ind2 + k];
dscal_(&len, &dbl2, A, &int1);
dtbmv_("L", "N", "N", &len, &int0, A, &int1, MAT_BUFD(x) +
ind + k * (mk+1), &int1);
}
}
}
free(A);
return Py_BuildValue("");
}
static char doc_sinv[] =
"The inverse of the product x := (y o x) when the 's' components of \n"
"y are diagonal.\n\n"
"sinv(x, y, dims, mnl = 0)";
static PyObject* sinv(PyObject *self, PyObject *args, PyObject *kwrds)
{
matrix *x, *y;
PyObject *dims, *O, *Ok;
int i, j, k, mk, len, maxn, ind = 0, ind2, int0 = 0, int1 = 1;
double a, c, d, alpha, *A = NULL, dbl2 = 0.5;
char *kwlist[] = {"x", "y", "dims", "mnl", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OOO|i", kwlist, &x, &y,
&dims, &ind)) return NULL;
/*
* For nonlinear and 'l' blocks:
*
* yk o\ xk = yk .\ xk
*/
O = PyDict_GetItemString(dims, "l");
#if PY_MAJOR_VERSION >= 3
ind += (int) PyLong_AsLong(O);
#else
ind += (int) PyInt_AsLong(O);
#endif
dtbsv_("L", "N", "N", &ind, &int0, MAT_BUFD(y), &int1, MAT_BUFD(x),
&int1);
/*
* For 'q' blocks:
*
* [ l0 -l1' ]
* yk o\ xk = 1/a^2 * [ ] * xk
* [ -l1 (a*I + l1*l1')/l0 ]
*
* where yk = (l0, l1) and a = l0^2 - l1'*l1.
*/
O = PyDict_GetItemString(dims, "q");
for (i = 0; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
mk = (int) PyLong_AsLong(Ok);
#else
mk = (int) PyInt_AsLong(Ok);
#endif
len = mk - 1;
a = dnrm2_(&len, MAT_BUFD(y) + ind + 1, &int1);
a = (MAT_BUFD(y)[ind] + a) * (MAT_BUFD(y)[ind] - a);
c = MAT_BUFD(x)[ind];
d = ddot_(&len, MAT_BUFD(x) + ind + 1, &int1,
MAT_BUFD(y) + ind + 1, &int1);
MAT_BUFD(x)[ind] = c * MAT_BUFD(y)[ind] - d;
alpha = a / MAT_BUFD(y)[ind];
dscal_(&len, &alpha, MAT_BUFD(x) + ind + 1, &int1);
alpha = d / MAT_BUFD(y)[ind] - c;
daxpy_(&len, &alpha, MAT_BUFD(y) + ind + 1, &int1, MAT_BUFD(x) +
ind + 1, &int1);
alpha = 1.0 / a;
dscal_(&mk, &alpha, MAT_BUFD(x) + ind, &int1);
ind += mk;
}
/*
* For the 's' blocks:
*
* yk o\ sk = xk ./ gamma
*
* where gammaij = .5 * (yk_i + yk_j).
*/
O = PyDict_GetItemString(dims, "s");
for (i = 0, maxn = 0; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
maxn = MAX(maxn, (int) PyLong_AsLong(Ok));
#else
maxn = MAX(maxn, (int) PyInt_AsLong(Ok));
#endif
}
if (!(A = (double *) calloc(maxn, sizeof(double))))
return PyErr_NoMemory();
for (i = 0, ind2 = ind; i < (int) PyList_Size(O); ind += mk*mk,
ind2 += mk, i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
mk = (int) PyLong_AsLong(Ok);
#else
mk = (int) PyInt_AsLong(Ok);
#endif
for (k = 0; k < mk; k++){
len = mk - k;
dcopy_(&len, MAT_BUFD(y) + ind2 + k, &int1, A, &int1);
for (j = 0; j < len; j++) A[j] += MAT_BUFD(y)[ind2 + k];
dscal_(&len, &dbl2, A, &int1);
dtbsv_("L", "N", "N", &len, &int0, A, &int1, MAT_BUFD(x) + ind
+ k * (mk+1), &int1);
}
}
free(A);
return Py_BuildValue("");
}
static char doc_trisc[] =
"Sets the upper triangular part of the 's' components of x equal to\n"
"zero and scales the strictly lower triangular part\n\n"
"trisc(x, dims, offset = 0)";
static PyObject* trisc(PyObject *self, PyObject *args, PyObject *kwrds)
{
matrix *x;
double dbl0 = 0.0, dbl2 = 2.0;
int ox = 0, i, k, nk, len, int1 = 1;
PyObject *dims, *O, *Ok;
char *kwlist[] = {"x", "dims", "offset", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO|i", kwlist, &x,
&dims, &ox)) return NULL;
O = PyDict_GetItemString(dims, "l");
#if PY_MAJOR_VERSION >= 3
ox += (int) PyLong_AsLong(O);
#else
ox += (int) PyInt_AsLong(O);
#endif
O = PyDict_GetItemString(dims, "q");
for (i = 0; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
ox += (int) PyLong_AsLong(Ok);
#else
ox += (int) PyInt_AsLong(Ok);
#endif
}
O = PyDict_GetItemString(dims, "s");
for (k = 0; k < (int) PyList_Size(O); k++){
Ok = PyList_GetItem(O, (Py_ssize_t) k);
#if PY_MAJOR_VERSION >= 3
nk = (int) PyLong_AsLong(Ok);
#else
nk = (int) PyInt_AsLong(Ok);
#endif
for (i = 1; i < nk; i++){
len = nk - i;
dscal_(&len, &dbl0, MAT_BUFD(x) + ox + i*(nk+1) - 1, &nk);
dscal_(&len, &dbl2, MAT_BUFD(x) + ox + nk*(i-1) + i, &int1);
}
ox += nk*nk;
}
return Py_BuildValue("");
}
static char doc_triusc[] =
"Scales the strictly lower triangular part of the 's' components of\n"
"x by 0.5.\n\n"
"triusc(x, dims, offset = 0)";
static PyObject* triusc(PyObject *self, PyObject *args, PyObject *kwrds)
{
matrix *x;
double dbl5 = 0.5;
int ox = 0, i, k, nk, len, int1 = 1;
PyObject *dims, *O, *Ok;
char *kwlist[] = {"x", "dims", "offset", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO|i", kwlist, &x,
&dims, &ox)) return NULL;
O = PyDict_GetItemString(dims, "l");
#if PY_MAJOR_VERSION >= 3
ox += (int) PyLong_AsLong(O);
#else
ox += (int) PyInt_AsLong(O);
#endif
O = PyDict_GetItemString(dims, "q");
for (i = 0; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
ox += (int) PyLong_AsLong(Ok);
#else
ox += (int) PyInt_AsLong(Ok);
#endif
}
O = PyDict_GetItemString(dims, "s");
for (k = 0; k < (int) PyList_Size(O); k++){
Ok = PyList_GetItem(O, (Py_ssize_t) k);
#if PY_MAJOR_VERSION >= 3
nk = (int) PyLong_AsLong(Ok);
#else
nk = (int) PyInt_AsLong(Ok);
#endif
for (i = 1; i < nk; i++){
len = nk - i;
dscal_(&len, &dbl5, MAT_BUFD(x) + ox + nk*(i-1) + i, &int1);
}
ox += nk*nk;
}
return Py_BuildValue("");
}
static char doc_sdot[] =
"Inner product of two vectors in S.\n\n"
"sdot(x, y, dims, mnl= 0)";
static PyObject* sdot(PyObject *self, PyObject *args, PyObject *kwrds)
{
matrix *x, *y;
int m = 0, int1 = 1, i, k, nk, inc, len;
double a;
PyObject *dims, *O, *Ok;
char *kwlist[] = {"x", "y", "dims", "mnl", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OOO|i", kwlist, &x, &y,
&dims, &m)) return NULL;
O = PyDict_GetItemString(dims, "l");
#if PY_MAJOR_VERSION >= 3
m += (int) PyLong_AsLong(O);
#else
m += (int) PyInt_AsLong(O);
#endif
O = PyDict_GetItemString(dims, "q");
for (i = 0; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
m += (int) PyLong_AsLong(Ok);
#else
m += (int) PyInt_AsLong(Ok);
#endif
}
a = ddot_(&m, MAT_BUFD(x), &int1, MAT_BUFD(y), &int1);
O = PyDict_GetItemString(dims, "s");
for (k = 0; k < (int) PyList_Size(O); k++){
Ok = PyList_GetItem(O, (Py_ssize_t) k);
#if PY_MAJOR_VERSION >= 3
nk = (int) PyLong_AsLong(Ok);
#else
nk = (int) PyInt_AsLong(Ok);
#endif
inc = nk+1;
a += ddot_(&nk, MAT_BUFD(x) + m, &inc, MAT_BUFD(y) + m, &inc);
for (i = 1; i < nk; i++){
len = nk - i;
a += 2.0 * ddot_(&len, MAT_BUFD(x) + m + i, &inc,
MAT_BUFD(y) + m + i, &inc);
}
m += nk*nk;
}
return Py_BuildValue("d", a);
}
static char doc_max_step[] =
"Returns min {t | x + t*e >= 0}\n\n."
"max_step(x, dims, mnl = 0, sigma = None)\n\n"
"e is defined as follows\n\n"
"- For the nonlinear and 'l' blocks: e is the vector of ones.\n"
"- For the 'q' blocks: e is the first unit vector.\n"
"- For the 's' blocks: e is the identity matrix.\n\n"
"When called with the argument sigma, also returns the eigenvalues\n"
"(in sigma) and the eigenvectors (in x) of the 's' components of x.\n";
static PyObject* max_step(PyObject *self, PyObject *args, PyObject *kwrds)
{
matrix *x, *sigma = NULL;
PyObject *dims, *O, *Ok;
int i, mk, len, maxn, ind = 0, ind2, int1 = 1, ld, Ns = 0, info, lwork,
*iwork = NULL, liwork, iwl, m;
double t = -FLT_MAX, dbl0 = 0.0, *work = NULL, wl, *Q = NULL,
*w = NULL;
char *kwlist[] = {"x", "dims", "mnl", "sigma", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO|iO", kwlist, &x,
&dims, &ind, &sigma)) return NULL;
O = PyDict_GetItemString(dims, "l");
#if PY_MAJOR_VERSION >= 3
ind += (int) PyLong_AsLong(O);
#else
ind += (int) PyInt_AsLong(O);
#endif
for (i = 0; i < ind; i++) t = MAX(t, -MAT_BUFD(x)[i]);
O = PyDict_GetItemString(dims, "q");
for (i = 0; i < (int) PyList_Size(O); i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
mk = (int) PyLong_AsLong(Ok);
#else
mk = (int) PyInt_AsLong(Ok);
#endif
len = mk - 1;
t = MAX(t, dnrm2_(&len, MAT_BUFD(x) + ind + 1, &int1) -
MAT_BUFD(x)[ind]);
ind += mk;
}
O = PyDict_GetItemString(dims, "s");
Ns = (int) PyList_Size(O);
for (i = 0, maxn = 0; i < Ns; i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
maxn = MAX(maxn, (int) PyLong_AsLong(Ok));
#else
maxn = MAX(maxn, (int) PyInt_AsLong(Ok));
#endif
}
if (!maxn) return Py_BuildValue("d", (ind) ? t : 0.0);
lwork = -1;
liwork = -1;
ld = MAX(1, maxn);
if (sigma){
dsyevd_("V", "L", &maxn, NULL, &ld, NULL, &wl, &lwork, &iwl,
&liwork, &info);
}
else {
if (!(Q = (double *) calloc(maxn * maxn, sizeof(double))) ||
!(w = (double *) calloc(maxn, sizeof(double)))){
free(Q); free(w);
return PyErr_NoMemory();
}
dsyevr_("N", "I", "L", &maxn, NULL, &ld, &dbl0, &dbl0, &int1,
&int1, &dbl0, &maxn, NULL, NULL, &int1, NULL, &wl, &lwork,
&iwl, &liwork, &info);
}
lwork = (int) wl;
liwork = iwl;
if (!(work = (double *) calloc(lwork, sizeof(double))) ||
(!(iwork = (int *) calloc(liwork, sizeof(int))))){
free(Q); free(w); free(work); free(iwork);
return PyErr_NoMemory();
}
for (i = 0, ind2 = 0; i < Ns; i++){
Ok = PyList_GetItem(O, (Py_ssize_t) i);
#if PY_MAJOR_VERSION >= 3
mk = (int) PyLong_AsLong(Ok);
#else
mk = (int) PyInt_AsLong(Ok);
#endif
if (mk){
if (sigma){
dsyevd_("V", "L", &mk, MAT_BUFD(x) + ind, &mk,
MAT_BUFD(sigma) + ind2, work, &lwork, iwork, &liwork,
&info);
t = MAX(t, -MAT_BUFD(sigma)[ind2]);
}
else {
len = mk*mk;
dcopy_(&len, MAT_BUFD(x) + ind, &int1, Q, &int1);
ld = MAX(1, mk);
dsyevr_("N", "I", "L", &mk, Q, &mk, &dbl0, &dbl0, &int1,
&int1, &dbl0, &m, w, NULL, &int1, NULL, work, &lwork,
iwork, &liwork, &info);
t = MAX(t, -w[0]);
}
}
ind += mk*mk;
ind2 += mk;
}
free(work); free(iwork); free(Q); free(w);
return Py_BuildValue("d", (ind) ? t : 0.0);
}
static PyMethodDef misc_solvers_functions[] = {
{"scale", (PyCFunction) scale, METH_VARARGS|METH_KEYWORDS, doc_scale},
{"scale2", (PyCFunction) scale2, METH_VARARGS|METH_KEYWORDS,
doc_scale2},
{"pack", (PyCFunction) pack, METH_VARARGS|METH_KEYWORDS, doc_pack},
{"pack2", (PyCFunction) pack2, METH_VARARGS|METH_KEYWORDS, doc_pack2},
{"unpack", (PyCFunction) unpack, METH_VARARGS|METH_KEYWORDS,
doc_unpack},
{"symm", (PyCFunction) symm, METH_VARARGS|METH_KEYWORDS, doc_symm},
{"trisc", (PyCFunction) trisc, METH_VARARGS|METH_KEYWORDS, doc_trisc},
{"triusc", (PyCFunction) triusc, METH_VARARGS|METH_KEYWORDS,
doc_triusc},
{"sdot", (PyCFunction) sdot, METH_VARARGS|METH_KEYWORDS, doc_sdot},
{"sprod", (PyCFunction) sprod, METH_VARARGS|METH_KEYWORDS, doc_sprod},
{"sinv", (PyCFunction) sinv, METH_VARARGS|METH_KEYWORDS, doc_sinv},
{"max_step", (PyCFunction) max_step, METH_VARARGS|METH_KEYWORDS,
doc_max_step},
{NULL} /* Sentinel */
};
#if PY_MAJOR_VERSION >= 3
static PyModuleDef misc_solvers_module = {
PyModuleDef_HEAD_INIT,
"misc_solvers",
misc_solvers__doc__,
-1,
misc_solvers_functions,
NULL, NULL, NULL, NULL
};
PyMODINIT_FUNC PyInit_misc_solvers(void)
{
PyObject *m;
if (!(m = PyModule_Create(&misc_solvers_module))) return NULL;
if (import_cvxopt() < 0) return NULL;
return m;
}
#else
PyMODINIT_FUNC initmisc_solvers(void)
{
PyObject *m;
m = Py_InitModule3("cvxopt.misc_solvers", misc_solvers_functions,
misc_solvers__doc__);
if (import_cvxopt() < 0) return;
}
#endif
| 31.619087 | 75 | 0.515183 | [
"vector"
] |
6cb751f38b9e6b66dcff495465f8debe595b3a65 | 1,060 | h | C | cc/resources/software_rasterizer.h | rafaelw/mojo | d3495a129dcbe679e2d5ac729c85a58acf38f8c4 | [
"BSD-3-Clause"
] | 5 | 2015-04-30T00:13:21.000Z | 2019-07-10T02:17:24.000Z | cc/resources/software_rasterizer.h | rafaelw/mojo | d3495a129dcbe679e2d5ac729c85a58acf38f8c4 | [
"BSD-3-Clause"
] | null | null | null | cc/resources/software_rasterizer.h | rafaelw/mojo | d3495a129dcbe679e2d5ac729c85a58acf38f8c4 | [
"BSD-3-Clause"
] | 2 | 2020-04-04T13:34:56.000Z | 2020-11-04T07:17:52.000Z | // Copyright 2015 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.
#ifndef CC_RESOURCES_SOFTWARE_RASTERIZER_H_
#define CC_RESOURCES_SOFTWARE_RASTERIZER_H_
#include <vector>
#include "cc/base/cc_export.h"
#include "cc/resources/rasterizer.h"
namespace cc {
// This class only returns |PrepareTilesMode::RASTERIZE_PRIORITIZED_TILES| in
// |GetPrepareTilesMode()| to tell rasterize as scheduled tasks.
class CC_EXPORT SoftwareRasterizer : public Rasterizer {
public:
~SoftwareRasterizer() override;
static scoped_ptr<SoftwareRasterizer> Create();
PrepareTilesMode GetPrepareTilesMode() override;
void RasterizeTiles(
const TileVector& tiles,
ResourcePool* resource_pool,
ResourceFormat resource_format,
const UpdateTileDrawInfoCallback& update_tile_draw_info) override;
private:
SoftwareRasterizer();
DISALLOW_COPY_AND_ASSIGN(SoftwareRasterizer);
};
} // namespace cc
#endif // CC_RESOURCES_SOFTWARE_RASTERIZER_H_
| 27.179487 | 77 | 0.783962 | [
"vector"
] |
6cb8515a3c20e697cb15263d768e15bffb45da94 | 127,906 | c | C | mapmssql2008.c | juliensam/mapserver | 59821b7c4bcb748b1e51cb29276ae1bba94f24a3 | [
"Unlicense"
] | null | null | null | mapmssql2008.c | juliensam/mapserver | 59821b7c4bcb748b1e51cb29276ae1bba94f24a3 | [
"Unlicense"
] | 1 | 2021-06-07T17:49:05.000Z | 2021-06-07T18:07:15.000Z | mapmssql2008.c | wetransform-os/MapServer | 54708d8830950d02b6dd037e87351b3952ac661e | [
"Unlicense"
] | null | null | null | /******************************************************************************
* $Id$
*
* Project: MapServer
* Purpose: MS SQL Server Layer Connector
* Author: Richard Hillman - based on PostGIS and SpatialDB connectors
* Tamas Szekeres - maintenance
*
******************************************************************************
* Copyright (c) 2007 IS Consulting (www.mapdotnet.com)
*
* 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 of this Software or works derived from this 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.
******************************************************************************
*
* Revision 1.0 2007/7/1
* Created.
*
*/
#ifndef _WIN32
#define _GNU_SOURCE
#endif
#define _CRT_SECURE_NO_WARNINGS 1
/* $Id$ */
#include <assert.h>
#include "mapserver.h"
#include "maptime.h"
#include "mapows.h"
#ifdef USE_MSSQL2008
#ifdef _WIN32
#include <windows.h>
#endif
#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <string.h>
#include <ctype.h> /* tolower() */
/* SqlGeometry/SqlGeography serialization format
Simple Point (SerializationProps & IsSinglePoint)
[SRID][0x01][SerializationProps][Point][z][m]
Simple Line Segment (SerializationProps & IsSingleLineSegment)
[SRID][0x01][SerializationProps][Point1][Point2][z1][z2][m1][m2]
Complex Geometries
[SRID][VersionAttribute][SerializationProps][NumPoints][Point1]..[PointN][z1]..[zN][m1]..[mN]
[NumFigures][Figure]..[Figure][NumShapes][Shape]..[Shape]
Complex Geometries (FigureAttribute == Curve)
[SRID][VersionAttribute][SerializationProps][NumPoints][Point1]..[PointN][z1]..[zN][m1]..[mN]
[NumFigures][Figure]..[Figure][NumShapes][Shape]..[Shape][NumSegments][SegmentType]..[SegmentType]
VersionAttribute (1 byte)
0x01 = Katmai (MSSQL2008+)
0x02 = Denali (MSSQL2012+)
SRID
Spatial Reference Id (4 bytes)
SerializationProps (bitmask) 1 byte
0x01 = HasZValues
0x02 = HasMValues
0x04 = IsValid
0x08 = IsSinglePoint
0x10 = IsSingleLineSegment
0x20 = IsLargerThanAHemisphere
Point (2-4)x8 bytes, size depends on SerializationProps & HasZValues & HasMValues
[x][y] - SqlGeometry
[latitude][longitude] - SqlGeography
Figure
[FigureAttribute][PointOffset]
FigureAttribute - Katmai (1 byte)
0x00 = Interior Ring
0x01 = Stroke
0x02 = Exterior Ring
FigureAttribute - Denali (1 byte)
0x00 = None
0x01 = Line
0x02 = Arc
0x03 = Curve
Shape
[ParentFigureOffset][FigureOffset][ShapeType]
ShapeType (1 byte)
0x00 = Unknown
0x01 = Point
0x02 = LineString
0x03 = Polygon
0x04 = MultiPoint
0x05 = MultiLineString
0x06 = MultiPolygon
0x07 = GeometryCollection
-- Denali
0x08 = CircularString
0x09 = CompoundCurve
0x0A = CurvePolygon
0x0B = FullGlobe
SegmentType (1 byte)
0x00 = Line
0x01 = Arc
0x02 = FirstLine
0x03 = FirstArc
*/
/* Native geometry parser macros */
/* parser error codes */
#define NOERROR 0
#define NOT_ENOUGH_DATA 1
#define CORRUPT_DATA 2
#define UNSUPPORTED_GEOMETRY_TYPE 3
/* geometry format to transfer geometry column */
#define MSSQLGEOMETRY_NATIVE 0
#define MSSQLGEOMETRY_WKB 1
#define MSSQLGEOMETRY_WKT 2
/* geometry column types */
#define MSSQLCOLTYPE_GEOMETRY 0
#define MSSQLCOLTYPE_GEOGRAPHY 1
#define MSSQLCOLTYPE_BINARY 2
#define MSSQLCOLTYPE_TEXT 3
#define SP_NONE 0
#define SP_HASZVALUES 1
#define SP_HASMVALUES 2
#define SP_ISVALID 4
#define SP_ISSINGLEPOINT 8
#define SP_ISSINGLELINESEGMENT 0x10
#define SP_ISLARGERTHANAHEMISPHERE 0x20
#define ST_UNKNOWN 0
#define ST_POINT 1
#define ST_LINESTRING 2
#define ST_POLYGON 3
#define ST_MULTIPOINT 4
#define ST_MULTILINESTRING 5
#define ST_MULTIPOLYGON 6
#define ST_GEOMETRYCOLLECTION 7
#define ST_CIRCULARSTRING 8
#define ST_COMPOUNDCURVE 9
#define ST_CURVEPOLYGON 10
#define ST_FULLGLOBE 11
#define SMT_LINE 0
#define SMT_ARC 1
#define SMT_FIRSTLINE 2
#define SMT_FIRSTARC 3
#define ReadInt32(nPos) (*((unsigned int*)(gpi->pszData + (nPos))))
#define ReadByte(nPos) (gpi->pszData[nPos])
#define ReadDouble(nPos) (*((double*)(gpi->pszData + (nPos))))
#define ParentOffset(iShape) (ReadInt32(gpi->nShapePos + (iShape) * 9 ))
#define FigureOffset(iShape) (ReadInt32(gpi->nShapePos + (iShape) * 9 + 4))
#define ShapeType(iShape) (ReadByte(gpi->nShapePos + (iShape) * 9 + 8))
#define SegmentType(iSegment) (ReadByte(gpi->nSegmentPos + (iSegment)))
#define NextFigureOffset(iShape) (iShape + 1 < gpi->nNumShapes? FigureOffset((iShape) +1) : gpi->nNumFigures)
#define FigureAttribute(iFigure) (ReadByte(gpi->nFigurePos + (iFigure) * 5))
#define PointOffset(iFigure) (ReadInt32(gpi->nFigurePos + (iFigure) * 5 + 1))
#define NextPointOffset(iFigure) (iFigure + 1 < gpi->nNumFigures? PointOffset((iFigure) +1) : gpi->nNumPoints)
#define ReadX(iPoint) (ReadDouble(gpi->nPointPos + 16 * (iPoint)))
#define ReadY(iPoint) (ReadDouble(gpi->nPointPos + 16 * (iPoint) + 8))
#define ReadZ(iPoint) (ReadDouble(gpi->nPointPos + 16 * gpi->nNumPoints + 8 * (iPoint)))
#define ReadM(iPoint) (ReadDouble(gpi->nPointPos + 24 * gpi->nNumPoints + 8 * (iPoint)))
#define FP_EPSILON 1e-12
#define SEGMENT_ANGLE 5.0
#define SEGMENT_MINPOINTS 10
/* Native geometry parser struct */
typedef struct msGeometryParserInfo_t {
unsigned char* pszData;
int nLen;
/* version */
char chVersion;
/* serialization properties */
char chProps;
/* point array */
int nPointSize;
int nPointPos;
int nNumPoints;
int nNumPointsRead;
/* figure array */
int nFigurePos;
int nNumFigures;
/* shape array */
int nShapePos;
int nNumShapes;
int nSRSId;
/* segment array */
int nSegmentPos;
int nNumSegments;
/* geometry or geography */
int nColType;
/* bounds */
double minx;
double miny;
double maxx;
double maxy;
} msGeometryParserInfo;
/* Structure for connection to an ODBC database (Microsoft preferred way to connect to SQL Server 2005 from c/c++) */
typedef struct msODBCconn_t {
SQLHENV henv; /* ODBC HENV */
SQLHDBC hdbc; /* ODBC HDBC */
SQLHSTMT hstmt; /* ODBC HSTMNT */
char errorMessage[1024]; /* Last error message if any */
} msODBCconn;
typedef struct ms_MSSQL2008_layer_info_t {
char *sql; /* sql query to send to DB */
long row_num; /* what row is the NEXT to be read (for random access) */
char *geom_column; /* name of the actual geometry column parsed from the LAYER's DATA field */
char *geom_column_type; /* the type of the geometry column */
char *geom_table; /* the table name or sub-select decalred in the LAYER's DATA field */
char *urid_name; /* name of user-specified unique identifier or OID */
char *user_srid; /* zero length = calculate, non-zero means using this value! */
char *index_name; /* hopefully this isn't necessary - but if the optimizer ain't cuttin' it... */
char *sort_spec; /* the sort by specification which should be applied to the generated select statement */
int mssqlversion_major; /* the sql server major version number */
int paging; /* Driver handling of pagination, enabled by default */
SQLSMALLINT *itemtypes; /* storing the sql field types for further reference */
msODBCconn * conn; /* Connection to db */
msGeometryParserInfo gpi; /* struct for the geometry parser */
int geometry_format; /* Geometry format to be retrieved from the database */
tokenListNodeObjPtr current_node; /* filter expression translation */
} msMSSQL2008LayerInfo;
#define SQL_COLUMN_NAME_MAX_LENGTH 128
#define SQL_TABLE_NAME_MAX_LENGTH 128
#define DATA_ERROR_MESSAGE \
"%s" \
"Error with MSSQL2008 data variable. You specified '%s'.<br>\n" \
"Standard ways of specifiying are : <br>\n(1) 'geometry_column from geometry_table' <br>\n(2) 'geometry_column from (<sub query>) as foo using unique <column name> using SRID=<srid#>' <br><br>\n\n" \
"Make sure you utilize the 'using unique <column name>' and 'using with <index name>' clauses in.\n\n<br><br>" \
"For more help, please see http://www.mapdotnet.com \n\n<br><br>" \
"mapmssql2008.c - version of 2007/7/1.\n"
/* Native geometry parser code */
void ReadPoint(msGeometryParserInfo* gpi, pointObj* p, int iPoint)
{
if (gpi->nColType == MSSQLCOLTYPE_GEOGRAPHY) {
p->x = ReadY(iPoint);
p->y = ReadX(iPoint);
} else {
p->x = ReadX(iPoint);
p->y = ReadY(iPoint);
}
/* calculate bounds */
if (gpi->nNumPointsRead++ == 0) {
gpi->minx = gpi->maxx = p->x;
gpi->miny = gpi->maxy = p->y;
} else {
if (gpi->minx > p->x) gpi->minx = p->x;
else if (gpi->maxx < p->x) gpi->maxx = p->x;
if (gpi->miny > p->y) gpi->miny = p->y;
else if (gpi->maxy < p->y) gpi->maxy = p->y;
}
#ifdef USE_POINT_Z_M
if ((gpi->chProps & SP_HASZVALUES) && (gpi->chProps & SP_HASMVALUES))
{
p->z = ReadZ(iPoint);
p->m = ReadM(iPoint);
}
else if (gpi->chProps & SP_HASZVALUES)
{
p->z = ReadZ(iPoint);
p->m = 0.0;
}
else if (gpi->chProps & SP_HASMVALUES)
{
p->z = 0.0;
p->m = ReadZ(iPoint);
}
else
{
p->z = 0.0;
p->m = 0.0;
}
#endif
}
int StrokeArcToLine(msGeometryParserInfo* gpi, lineObj* line, int index)
{
if (index > 1) {
double x, y, x1, y1, x2, y2, x3, y3, dxa, dya, sxa, sya, dxb, dyb;
double d, sxb, syb, ox, oy, a1, a3, sa, da, a, radius;
int numpoints;
#ifdef USE_POINT_Z_M
double z;
z = line->point[index].z; /* must be equal for arc segments */
#endif
/* first point */
x1 = line->point[index - 2].x;
y1 = line->point[index - 2].y;
/* second point */
x2 = line->point[index - 1].x;
y2 = line->point[index - 1].y;
/* third point */
x3 = line->point[index].x;
y3 = line->point[index].y;
sxa = (x1 + x2);
sya = (y1 + y2);
dxa = x2 - x1;
dya = y2 - y1;
sxb = (x2 + x3);
syb = (y2 + y3);
dxb = x3 - x2;
dyb = y3 - y2;
d = (dxa * dyb - dya * dxb) * 2;
if (fabs(d) < FP_EPSILON) {
/* points are colinear, nothing to do here */
return index;
}
/* calculating the center of circle */
ox = ((sya - syb) * dya * dyb + sxa * dyb * dxa - sxb * dya * dxb) / d;
oy = ((sxb - sxa) * dxa * dxb + syb * dyb * dxa - sya * dya * dxb) / d;
radius = sqrt((x1 - ox) * (x1 - ox) + (y1 - oy) * (y1 - oy));
/* calculating the angle to be used */
a1 = atan2(y1 - oy, x1 - ox);
a3 = atan2(y3 - oy, x3 - ox);
if (d > 0) {
/* draw counterclockwise */
if (a3 > a1) /* Wrapping past 180? */
sa = a3 - a1;
else
sa = a3 - a1 + 2.0 * M_PI ;
}
else {
if (a3 > a1) /* Wrapping past 180? */
sa = a3 - a1 + 2.0 * M_PI;
else
sa = a3 - a1;
}
numpoints = (int)floor(fabs(sa) * 180 / SEGMENT_ANGLE / M_PI);
if (numpoints < SEGMENT_MINPOINTS)
numpoints = SEGMENT_MINPOINTS;
da = sa / numpoints;
/* extend the point array */
line->numpoints += numpoints - 2;
line->point = msSmallRealloc(line->point, sizeof(pointObj) * line->numpoints);
--index;
a = a1 + da;
while (numpoints > 1) {
line->point[index].x = x = ox + radius * cos(a);
line->point[index].y = y = oy + radius * sin(a);
#ifdef USE_POINT_Z_M
line->point[index].z = z;
#endif
/* calculate bounds */
if (gpi->minx > x) gpi->minx = x;
else if (gpi->maxx < x) gpi->maxx = x;
if (gpi->miny > y) gpi->miny = y;
else if (gpi->maxy < y) gpi->maxy = y;
a += da;
++index;
--numpoints;
}
/* set last point */
line->point[index].x = x3;
line->point[index].y = y3;
#ifdef USE_POINT_Z_M
line->point[index].z = z;
#endif
}
return index;
}
int ParseSqlGeometry(msMSSQL2008LayerInfo* layerinfo, shapeObj *shape)
{
msGeometryParserInfo* gpi = &layerinfo->gpi;
gpi->nNumPointsRead = 0;
if (gpi->nLen < 10) {
msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
return NOT_ENOUGH_DATA;
}
/* store the SRS id for further use */
gpi->nSRSId = ReadInt32(0);
gpi->chVersion = ReadByte(4);
if (gpi->chVersion > 2) {
msDebug("ParseSqlGeometry CORRUPT_DATA\n");
return CORRUPT_DATA;
}
gpi->chProps = ReadByte(5);
gpi->nPointSize = 16;
if ( gpi->chProps & SP_HASMVALUES )
gpi->nPointSize += 8;
if ( gpi->chProps & SP_HASZVALUES )
gpi->nPointSize += 8;
if ( gpi->chProps & SP_ISSINGLEPOINT ) {
// single point geometry
gpi->nNumPoints = 1;
if (gpi->nLen < 6 + gpi->nPointSize) {
msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
return NOT_ENOUGH_DATA;
}
shape->type = MS_SHAPE_POINT;
shape->line = (lineObj *) msSmallMalloc(sizeof(lineObj));
shape->numlines = 1;
shape->line[0].point = (pointObj *) msSmallMalloc(sizeof(pointObj));
shape->line[0].numpoints = 1;
gpi->nPointPos = 6;
ReadPoint(gpi, &shape->line[0].point[0], 0);
} else if ( gpi->chProps & SP_ISSINGLELINESEGMENT ) {
// single line segment with 2 points
gpi->nNumPoints = 2;
if (gpi->nLen < 6 + 2 * gpi->nPointSize) {
msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
return NOT_ENOUGH_DATA;
}
shape->type = MS_SHAPE_LINE;
shape->line = (lineObj *) msSmallMalloc(sizeof(lineObj));
shape->numlines = 1;
shape->line[0].point = (pointObj *) msSmallMalloc(sizeof(pointObj) * 2);
shape->line[0].numpoints = 2;
gpi->nPointPos = 6;
ReadPoint(gpi, &shape->line[0].point[0], 0);
ReadPoint(gpi, &shape->line[0].point[1], 1);
} else {
int iShape, iFigure, iSegment = 0;
// complex geometries
gpi->nNumPoints = ReadInt32(6);
if ( gpi->nNumPoints <= 0 ) {
return NOERROR;
}
// position of the point array
gpi->nPointPos = 10;
// position of the figures
gpi->nFigurePos = gpi->nPointPos + gpi->nPointSize * gpi->nNumPoints + 4;
if (gpi->nLen < gpi->nFigurePos) {
msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
return NOT_ENOUGH_DATA;
}
gpi->nNumFigures = ReadInt32(gpi->nFigurePos - 4);
if ( gpi->nNumFigures <= 0 ) {
return NOERROR;
}
// position of the shapes
gpi->nShapePos = gpi->nFigurePos + 5 * gpi->nNumFigures + 4;
if (gpi->nLen < gpi->nShapePos) {
msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
return NOT_ENOUGH_DATA;
}
gpi->nNumShapes = ReadInt32(gpi->nShapePos - 4);
if (gpi->nLen < gpi->nShapePos + 9 * gpi->nNumShapes) {
msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
return NOT_ENOUGH_DATA;
}
if ( gpi->nNumShapes <= 0 ) {
return NOERROR;
}
// pick up the root shape
if ( ParentOffset(0) != 0xFFFFFFFF) {
msDebug("ParseSqlGeometry CORRUPT_DATA\n");
return CORRUPT_DATA;
}
// determine the shape type
for (iShape = 0; iShape < gpi->nNumShapes; iShape++) {
unsigned char shapeType = ShapeType(iShape);
if (shapeType == ST_POINT || shapeType == ST_MULTIPOINT) {
shape->type = MS_SHAPE_POINT;
break;
} else if (shapeType == ST_LINESTRING || shapeType == ST_MULTILINESTRING ||
shapeType == ST_CIRCULARSTRING || shapeType == ST_COMPOUNDCURVE) {
shape->type = MS_SHAPE_LINE;
break;
} else if (shapeType == ST_POLYGON || shapeType == ST_MULTIPOLYGON ||
shapeType == ST_CURVEPOLYGON)
{
shape->type = MS_SHAPE_POLYGON;
break;
}
}
shape->line = (lineObj *) msSmallMalloc(sizeof(lineObj) * gpi->nNumFigures);
shape->numlines = gpi->nNumFigures;
gpi->nNumSegments = 0;
// read figures
for (iFigure = 0; iFigure < gpi->nNumFigures; iFigure++) {
int iPoint, iNextPoint, i;
iPoint = PointOffset(iFigure);
iNextPoint = NextPointOffset(iFigure);
shape->line[iFigure].point = (pointObj *) msSmallMalloc(sizeof(pointObj)*(iNextPoint - iPoint));
shape->line[iFigure].numpoints = iNextPoint - iPoint;
i = 0;
if (gpi->chVersion == 0x02 && FigureAttribute(iFigure) >= 0x02) {
int nPointPrepared = 0;
lineObj* line = &shape->line[iFigure];
if (FigureAttribute(iFigure) == 0x03) {
if (gpi->nNumSegments == 0) {
/* position of the segment types */
gpi->nSegmentPos = gpi->nShapePos + 9 * gpi->nNumShapes + 4;
gpi->nNumSegments = ReadInt32(gpi->nSegmentPos - 4);
if (gpi->nLen < gpi->nSegmentPos + gpi->nNumSegments) {
msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
return NOT_ENOUGH_DATA;
}
iSegment = 0;
}
while (iPoint < iNextPoint && iSegment < gpi->nNumSegments) {
ReadPoint(gpi, &line->point[i], iPoint);
++iPoint;
++nPointPrepared;
if (nPointPrepared == 2 && (SegmentType(iSegment) == SMT_FIRSTLINE || SegmentType(iSegment) == SMT_LINE)) {
++iSegment;
nPointPrepared = 1;
}
else if (nPointPrepared == 3 && (SegmentType(iSegment) == SMT_FIRSTARC || SegmentType(iSegment) == SMT_ARC)) {
i = StrokeArcToLine(gpi, line, i);
++iSegment;
nPointPrepared = 1;
}
++i;
}
}
else {
while (iPoint < iNextPoint) {
ReadPoint(gpi, &line->point[i], iPoint);
++iPoint;
++nPointPrepared;
if (nPointPrepared == 3) {
i = StrokeArcToLine(gpi, line, i);
nPointPrepared = 1;
}
++i;
}
}
}
else {
while (iPoint < iNextPoint) {
ReadPoint(gpi, &shape->line[iFigure].point[i], iPoint);
++iPoint;
++i;
}
}
}
}
/* set bounds */
shape->bounds.minx = gpi->minx;
shape->bounds.miny = gpi->miny;
shape->bounds.maxx = gpi->maxx;
shape->bounds.maxy = gpi->maxy;
return NOERROR;
}
/* MS SQL driver code*/
msMSSQL2008LayerInfo *getMSSQL2008LayerInfo(const layerObj *layer)
{
return layer->layerinfo;
}
void setMSSQL2008LayerInfo(layerObj *layer, msMSSQL2008LayerInfo *MSSQL2008layerinfo)
{
layer->layerinfo = (void*) MSSQL2008layerinfo;
}
void handleSQLError(layerObj *layer)
{
SQLCHAR SqlState[6], Msg[SQL_MAX_MESSAGE_LENGTH];
SQLINTEGER NativeError;
SQLSMALLINT i, MsgLen;
SQLRETURN rc;
msMSSQL2008LayerInfo *layerinfo = getMSSQL2008LayerInfo(layer);
if (layerinfo == NULL)
return;
// Get the status records.
i = 1;
while ((rc = SQLGetDiagRec(SQL_HANDLE_STMT, layerinfo->conn->hstmt, i, SqlState, &NativeError,
Msg, sizeof(Msg), &MsgLen)) != SQL_NO_DATA) {
if(layer->debug) {
msDebug("SQLError: %s\n", Msg);
}
i++;
}
}
/* TODO Take a look at glibc's strcasestr */
static char *strstrIgnoreCase(const char *haystack, const char *needle)
{
char *hay_lower;
char *needle_lower;
size_t len_hay,len_need, match;
int found = MS_FALSE;
int t;
char *loc;
len_hay = strlen(haystack);
len_need = strlen(needle);
hay_lower = (char*) msSmallMalloc(len_hay + 1);
needle_lower =(char*) msSmallMalloc(len_need + 1);
for(t = 0; t < len_hay; t++) {
hay_lower[t] = (char)tolower(haystack[t]);
}
hay_lower[t] = 0;
for(t = 0; t < len_need; t++) {
needle_lower[t] = (char)tolower(needle[t]);
}
needle_lower[t] = 0;
loc = strstr(hay_lower, needle_lower);
if(loc) {
match = loc - hay_lower;
found = MS_TRUE;
}
msFree(hay_lower);
msFree(needle_lower);
return (char *) (found == MS_FALSE ? NULL : haystack + match);
}
static int msMSSQL2008LayerParseData(layerObj *layer, char **geom_column_name, char **geom_column_type, char **table_name, char **urid_name, char **user_srid, char **index_name, char **sort_spec, int debug);
/* Close connection and handles */
static void msMSSQL2008CloseConnection(void *conn_handle)
{
msODBCconn * conn = (msODBCconn *) conn_handle;
if (!conn) {
return;
}
if (conn->hstmt) {
SQLFreeHandle(SQL_HANDLE_STMT, conn->hstmt);
}
if (conn->hdbc) {
SQLDisconnect(conn->hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, conn->hdbc);
}
if (conn->henv) {
SQLFreeHandle(SQL_HANDLE_ENV, conn->henv);
}
msFree(conn);
}
/* Set the error string for the connection */
static void setConnError(msODBCconn *conn)
{
SQLSMALLINT len;
SQLGetDiagField(SQL_HANDLE_DBC, conn->hdbc, 1, SQL_DIAG_MESSAGE_TEXT, (SQLPOINTER) conn->errorMessage, sizeof(conn->errorMessage), &len);
conn->errorMessage[len] = 0;
}
/* Connect to db */
static msODBCconn * mssql2008Connect(char * connString)
{
SQLCHAR outConnString[1024];
SQLSMALLINT outConnStringLen;
SQLRETURN rc;
msODBCconn * conn = msSmallMalloc(sizeof(msODBCconn));
memset(conn, 0, sizeof(*conn));
SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &conn->henv);
SQLSetEnvAttr(conn->henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, 0);
SQLAllocHandle(SQL_HANDLE_DBC, conn->henv, &conn->hdbc);
if (strcasestr(connString, "DRIVER=") == 0)
{
SQLCHAR fullConnString[1024];
snprintf((char*)fullConnString, sizeof(fullConnString), "DRIVER={SQL Server};%s", connString);
rc = SQLDriverConnect(conn->hdbc, NULL, fullConnString, SQL_NTS, outConnString, 1024, &outConnStringLen, SQL_DRIVER_NOPROMPT);
}
else
{
rc = SQLDriverConnect(conn->hdbc, NULL, (SQLCHAR*)connString, SQL_NTS, outConnString, 1024, &outConnStringLen, SQL_DRIVER_NOPROMPT);
}
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
setConnError(conn);
return conn;
}
SQLAllocHandle(SQL_HANDLE_STMT, conn->hdbc, &conn->hstmt);
return conn;
}
/* Set the error string for the statement execution */
static void setStmntError(msODBCconn *conn)
{
SQLSMALLINT len;
SQLGetDiagField(SQL_HANDLE_STMT, conn->hstmt, 1, SQL_DIAG_MESSAGE_TEXT, (SQLPOINTER) conn->errorMessage, sizeof(conn->errorMessage), &len);
conn->errorMessage[len] = 0;
}
/* Execute SQL against connection. Set error string if failed */
static int executeSQL(msODBCconn *conn, const char * sql)
{
SQLRETURN rc;
SQLCloseCursor(conn->hstmt);
rc = SQLExecDirect(conn->hstmt, (SQLCHAR *) sql, SQL_NTS);
if (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) {
return 1;
} else {
setStmntError(conn);
return 0;
}
}
/* Get columns name from query results */
static int columnName(msODBCconn *conn, int index, char *buffer, int bufferLength, layerObj *layer, char pass_field_def, SQLSMALLINT *itemType)
{
SQLRETURN rc;
SQLCHAR columnName[SQL_COLUMN_NAME_MAX_LENGTH + 1];
SQLSMALLINT columnNameLen;
SQLSMALLINT dataType;
SQLULEN columnSize;
SQLSMALLINT decimalDigits;
SQLSMALLINT nullable;
rc = SQLDescribeCol(
conn->hstmt,
(SQLUSMALLINT)index,
columnName,
SQL_COLUMN_NAME_MAX_LENGTH,
&columnNameLen,
&dataType,
&columnSize,
&decimalDigits,
&nullable);
if (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) {
if (bufferLength < SQL_COLUMN_NAME_MAX_LENGTH + 1)
strlcpy(buffer, (const char *)columnName, bufferLength);
else
strlcpy(buffer, (const char *)columnName, SQL_COLUMN_NAME_MAX_LENGTH + 1);
*itemType = dataType;
if (pass_field_def) {
char md_item_name[256];
char gml_width[32], gml_precision[32];
const char *gml_type = NULL;
gml_width[0] = '\0';
gml_precision[0] = '\0';
switch( dataType ) {
case SQL_INTEGER:
case SQL_SMALLINT:
case SQL_TINYINT:
gml_type = "Integer";
break;
case SQL_BIGINT:
gml_type = "Long";
break;
case SQL_REAL:
case SQL_FLOAT:
case SQL_DOUBLE:
case SQL_DECIMAL:
case SQL_NUMERIC:
gml_type = "Real";
if( decimalDigits > 0 )
sprintf( gml_precision, "%d", decimalDigits );
break;
case SQL_TYPE_DATE:
gml_type = "Date";
break;
case SQL_TYPE_TIME:
gml_type = "Time";
break;
case SQL_TYPE_TIMESTAMP:
gml_type = "DateTime";
break;
case SQL_BIT:
gml_type = "Boolean";
break;
default:
gml_type = "Character";
break;
}
if( columnSize > 0 )
sprintf( gml_width, "%u", (unsigned int)columnSize );
snprintf( md_item_name, sizeof(md_item_name), "gml_%s_type", buffer );
if( msOWSLookupMetadata(&(layer->metadata), "G", "type") == NULL )
msInsertHashTable(&(layer->metadata), md_item_name, gml_type );
snprintf( md_item_name, sizeof(md_item_name), "gml_%s_width", buffer );
if( strlen(gml_width) > 0
&& msOWSLookupMetadata(&(layer->metadata), "G", "width") == NULL )
msInsertHashTable(&(layer->metadata), md_item_name, gml_width );
snprintf( md_item_name, sizeof(md_item_name), "gml_%s_precision",buffer );
if( strlen(gml_precision) > 0
&& msOWSLookupMetadata(&(layer->metadata), "G", "precision")==NULL )
msInsertHashTable(&(layer->metadata), md_item_name, gml_precision );
snprintf( md_item_name, sizeof(md_item_name), "gml_%s_nillable",buffer );
if( nullable > 0 )
msInsertHashTable(&(layer->metadata), md_item_name, "true" );
}
return 1;
} else {
setStmntError(conn);
return 0;
}
}
/* open up a connection to the MS SQL 2008 database using the connection string in layer->connection */
/* ie. "driver=<driver>;server=<server>;database=<database>;integrated security=?;user id=<username>;password=<password>" */
int msMSSQL2008LayerOpen(layerObj *layer)
{
msMSSQL2008LayerInfo *layerinfo;
char *index, *maskeddata;
int i, count;
char *conn_decrypted = NULL;
if(layer->debug) {
msDebug("msMSSQL2008LayerOpen called datastatement: %s\n", layer->data);
}
if(getMSSQL2008LayerInfo(layer)) {
if(layer->debug) {
msDebug("msMSSQL2008LayerOpen :: layer is already open!!\n");
}
return MS_SUCCESS; /* already open */
}
if(!layer->data) {
msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerOpen()", "", "Error parsing MSSQL2008 data variable: nothing specified in DATA statement.<br><br>\n\nMore Help:<br><br>\n\n");
return MS_FAILURE;
}
if(!layer->connection) {
msSetError( MS_QUERYERR, "MSSQL connection parameter not specified.", "msMSSQL2008LayerOpen()");
return MS_FAILURE;
}
/* have to setup a connection to the database */
layerinfo = (msMSSQL2008LayerInfo*) msSmallMalloc(sizeof(msMSSQL2008LayerInfo));
layerinfo->sql = NULL; /* calc later */
layerinfo->row_num = 0;
layerinfo->geom_column = NULL;
layerinfo->geom_column_type = NULL;
layerinfo->geom_table = NULL;
layerinfo->urid_name = NULL;
layerinfo->user_srid = NULL;
layerinfo->index_name = NULL;
layerinfo->sort_spec = NULL;
layerinfo->conn = NULL;
layerinfo->itemtypes = NULL;
layerinfo->mssqlversion_major = 0;
layerinfo->paging = MS_TRUE;
layerinfo->conn = (msODBCconn *) msConnPoolRequest(layer);
if(!layerinfo->conn) {
if(layer->debug) {
msDebug("MSMSSQL2008LayerOpen -- shared connection not available.\n");
}
/* Decrypt any encrypted token in connection and attempt to connect */
conn_decrypted = msDecryptStringTokens(layer->map, layer->connection);
if (conn_decrypted == NULL) {
return(MS_FAILURE); /* An error should already have been produced */
}
layerinfo->conn = mssql2008Connect(conn_decrypted);
msFree(conn_decrypted);
conn_decrypted = NULL;
if(!layerinfo->conn || layerinfo->conn->errorMessage[0]) {
char *errMess = "Out of memory";
msDebug("FAILURE!!!");
maskeddata = (char *)msSmallMalloc(strlen(layer->connection) + 1);
strcpy(maskeddata, layer->connection);
index = strstr(maskeddata, "password=");
if(index != NULL) {
index = (char *)(index + 9);
count = (int)(strstr(index, " ") - index);
for(i = 0; i < count; i++) {
strlcpy(index, "*", (int)1);
index++;
}
}
if (layerinfo->conn) {
errMess = layerinfo->conn->errorMessage;
}
msSetError(MS_QUERYERR,
"Couldnt make connection to MS SQL Server 2008 with connect string '%s'.\n<br>\n"
"Error reported was '%s'.\n<br>\n\n"
"This error occured when trying to make a connection to the specified SQL server. \n"
"<br>\nMost commonly this is caused by <br>\n"
"(1) incorrect connection string <br>\n"
"(2) you didn't specify a 'user id=...' in your connection string <br>\n"
"(3) SQL server isnt running <br>\n"
"(4) TCPIP not enabled for SQL Client or server <br>\n\n",
"msMSSQL2008LayerOpen()", maskeddata, errMess);
msFree(maskeddata);
msMSSQL2008CloseConnection(layerinfo->conn);
msFree(layerinfo);
return MS_FAILURE;
}
msConnPoolRegister(layer, layerinfo->conn, msMSSQL2008CloseConnection);
}
setMSSQL2008LayerInfo(layer, layerinfo);
if (msMSSQL2008LayerParseData(layer, &layerinfo->geom_column, &layerinfo->geom_column_type, &layerinfo->geom_table, &layerinfo->urid_name, &layerinfo->user_srid, &layerinfo->index_name, &layerinfo->sort_spec, layer->debug) != MS_SUCCESS) {
msSetError( MS_QUERYERR, "Could not parse the layer data", "msMSSQL2008LayerOpen()");
return MS_FAILURE;
}
/* identify the geometry transfer type */
if (msLayerGetProcessingKey( layer, "MSSQL_READ_WKB" ) != NULL)
layerinfo->geometry_format = MSSQLGEOMETRY_WKB;
else {
layerinfo->geometry_format = MSSQLGEOMETRY_NATIVE;
if (strcasecmp(layerinfo->geom_column_type, "geography") == 0)
layerinfo->gpi.nColType = MSSQLCOLTYPE_GEOGRAPHY;
else
layerinfo->gpi.nColType = MSSQLCOLTYPE_GEOMETRY;
}
return MS_SUCCESS;
}
/* Return MS_TRUE if layer is open, MS_FALSE otherwise. */
int msMSSQL2008LayerIsOpen(layerObj *layer)
{
return getMSSQL2008LayerInfo(layer) ? MS_TRUE : MS_FALSE;
}
/* Free the itemindexes array in a layer. */
void msMSSQL2008LayerFreeItemInfo(layerObj *layer)
{
if(layer->debug) {
msDebug("msMSSQL2008LayerFreeItemInfo called\n");
}
if(layer->iteminfo) {
msFree(layer->iteminfo);
}
layer->iteminfo = NULL;
}
/* allocate the iteminfo index array - same order as the item list */
int msMSSQL2008LayerInitItemInfo(layerObj *layer)
{
int i;
int *itemindexes ;
if (layer->debug) {
msDebug("msMSSQL2008LayerInitItemInfo called\n");
}
if(layer->numitems == 0) {
return MS_SUCCESS;
}
msFree(layer->iteminfo);
layer->iteminfo = (int *) msSmallMalloc(sizeof(int) * layer->numitems);
itemindexes = (int*)layer->iteminfo;
for(i = 0; i < layer->numitems; i++) {
itemindexes[i] = i; /* last one is always the geometry one - the rest are non-geom */
}
return MS_SUCCESS;
}
static int getMSSQLMajorVersion(layerObj* layer)
{
msMSSQL2008LayerInfo *layerinfo = getMSSQL2008LayerInfo(layer);
if (layerinfo == NULL)
return 0;
if (layerinfo->mssqlversion_major == 0) {
char* mssqlversion_major = msLayerGetProcessingKey(layer, "MSSQL_VERSION_MAJOR");
if (mssqlversion_major != NULL) {
layerinfo->mssqlversion_major = atoi(mssqlversion_major);
}
else {
/* need to query from database */
if (executeSQL(layerinfo->conn, "SELECT SERVERPROPERTY('ProductVersion')")) {
SQLRETURN rc = SQLFetch(layerinfo->conn->hstmt);
if (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) {
/* process results */
char result_data[256];
SQLLEN retLen = 0;
rc = SQLGetData(layerinfo->conn->hstmt, 1, SQL_C_CHAR, result_data, sizeof(result_data), &retLen);
if (rc != SQL_ERROR) {
result_data[retLen] = 0;
layerinfo->mssqlversion_major = atoi(result_data);
}
}
}
}
}
return layerinfo->mssqlversion_major;
}
static int addFilter(layerObj *layer, char **query)
{
if (layer->filter.native_string) {
(*query) = msStringConcatenate(*query, " WHERE (");
(*query) = msStringConcatenate(*query, layer->filter.native_string);
(*query) = msStringConcatenate(*query, ")");
return MS_TRUE;
}
else if (msLayerGetProcessingKey(layer, "NATIVE_FILTER") != NULL) {
(*query) = msStringConcatenate(*query, " WHERE (");
(*query) = msStringConcatenate(*query, msLayerGetProcessingKey(layer, "NATIVE_FILTER"));
(*query) = msStringConcatenate(*query, ")");
return MS_TRUE;
}
return MS_FALSE;
}
/* Get the layer extent as specified in the mapfile or a largest area */
/* covering all features */
int msMSSQL2008LayerGetExtent(layerObj *layer, rectObj *extent)
{
msMSSQL2008LayerInfo *layerinfo;
char *query = 0;
char result_data[256];
SQLLEN retLen;
SQLRETURN rc;
if(layer->debug) {
msDebug("msMSSQL2008LayerGetExtent called\n");
}
if (!(layer->extent.minx == -1.0 && layer->extent.miny == -1.0 &&
layer->extent.maxx == -1.0 && layer->extent.maxy == -1.0)) {
/* extent was already set */
extent->minx = layer->extent.minx;
extent->miny = layer->extent.miny;
extent->maxx = layer->extent.maxx;
extent->maxy = layer->extent.maxy;
}
layerinfo = getMSSQL2008LayerInfo(layer);
if (!layerinfo) {
msSetError(MS_QUERYERR, "GetExtent called with layerinfo = NULL", "msMSSQL2008LayerGetExtent()");
return MS_FAILURE;
}
/* set up statement */
if (getMSSQLMajorVersion(layer) >= 11) {
if (strcasecmp(layerinfo->geom_column_type, "geography") == 0) {
query = msStringConcatenate(query, "WITH extent(extentcol) AS (SELECT geometry::EnvelopeAggregate(geometry::STGeomFromWKB(");
query = msStringConcatenate(query, layerinfo->geom_column);
query = msStringConcatenate(query, ".STAsBinary(), ");
query = msStringConcatenate(query, layerinfo->geom_column);
query = msStringConcatenate(query, ".STSrid)");
}
else {
query = msStringConcatenate(query, "WITH extent(extentcol) AS (SELECT geometry::EnvelopeAggregate(");
query = msStringConcatenate(query, layerinfo->geom_column);
}
query = msStringConcatenate(query, ") AS extentcol FROM ");
query = msStringConcatenate(query, layerinfo->geom_table);
/* adding attribute filter */
addFilter(layer, &query);
query = msStringConcatenate(query, ") SELECT extentcol.STPointN(1).STX, extentcol.STPointN(1).STY, extentcol.STPointN(3).STX, extentcol.STPointN(3).STY FROM extent");
}
else {
if (strcasecmp(layerinfo->geom_column_type, "geography") == 0) {
query = msStringConcatenate(query, "WITH ENVELOPE as (SELECT geometry::STGeomFromWKB(");
query = msStringConcatenate(query, layerinfo->geom_column);
query = msStringConcatenate(query, ".STAsBinary(), ");
query = msStringConcatenate(query, layerinfo->geom_column);
query = msStringConcatenate(query, ".STSrid)");
}
else {
query = msStringConcatenate(query, "WITH ENVELOPE as (SELECT ");
query = msStringConcatenate(query, layerinfo->geom_column);
}
query = msStringConcatenate(query, ".STEnvelope() as envelope from ");
query = msStringConcatenate(query, layerinfo->geom_table);
/* adding attribute filter */
addFilter(layer, &query);
query = msStringConcatenate(query, "), CORNERS as (SELECT envelope.STPointN(1) as point from ENVELOPE UNION ALL select envelope.STPointN(3) from ENVELOPE) SELECT MIN(point.STX), MIN(point.STY), MAX(point.STX), MAX(point.STY) FROM CORNERS");
}
if (!executeSQL(layerinfo->conn, query)) {
msFree(query);
return MS_FAILURE;
}
msFree(query);
/* process results */
rc = SQLFetch(layerinfo->conn->hstmt);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
if (layer->debug) {
msDebug("msMSSQL2008LayerGetExtent: No results found.\n");
}
return MS_FAILURE;
}
rc = SQLGetData(layerinfo->conn->hstmt, 1, SQL_C_CHAR, result_data, sizeof(result_data), &retLen);
if (rc == SQL_ERROR || retLen < 0) {
msSetError(MS_QUERYERR, "Failed to get MinX value", "msMSSQL2008LayerGetExtent()");
return MS_FAILURE;
}
result_data[retLen] = 0;
extent->minx = atof(result_data);
rc = SQLGetData(layerinfo->conn->hstmt, 2, SQL_C_CHAR, result_data, sizeof(result_data), &retLen);
if (rc == SQL_ERROR || retLen < 0) {
msSetError(MS_QUERYERR, "Failed to get MinY value", "msMSSQL2008LayerGetExtent()");
return MS_FAILURE;
}
result_data[retLen] = 0;
extent->miny = atof(result_data);
rc = SQLGetData(layerinfo->conn->hstmt, 3, SQL_C_CHAR, result_data, sizeof(result_data), &retLen);
if (rc == SQL_ERROR || retLen < 0) {
msSetError(MS_QUERYERR, "Failed to get MaxX value", "msMSSQL2008LayerGetExtent()");
return MS_FAILURE;
}
result_data[retLen] = 0;
extent->maxx = atof(result_data);
rc = SQLGetData(layerinfo->conn->hstmt, 4, SQL_C_CHAR, result_data, sizeof(result_data), &retLen);
if (rc == SQL_ERROR || retLen < 0) {
msSetError(MS_QUERYERR, "Failed to get MaxY value", "msMSSQL2008LayerGetExtent()");
return MS_FAILURE;
}
result_data[retLen] = 0;
extent->maxy = atof(result_data);
return MS_SUCCESS;
}
/* Get the layer feature count */
int msMSSQL2008LayerGetNumFeatures(layerObj *layer)
{
msMSSQL2008LayerInfo *layerinfo;
char *query = 0;
char result_data[256];
SQLLEN retLen;
SQLRETURN rc;
if (layer->debug) {
msDebug("msMSSQL2008LayerGetNumFeatures called\n");
}
layerinfo = getMSSQL2008LayerInfo(layer);
if (!layerinfo) {
msSetError(MS_QUERYERR, "GetNumFeatures called with layerinfo = NULL", "msMSSQL2008LayerGetNumFeatures()");
return -1;
}
/* set up statement */
query = msStringConcatenate(query, "SELECT count(*) FROM ");
query = msStringConcatenate(query, layerinfo->geom_table);
/* adding attribute filter */
addFilter(layer, &query);
if (!executeSQL(layerinfo->conn, query)) {
msFree(query);
return -1;
}
msFree(query);
rc = SQLFetch(layerinfo->conn->hstmt);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
if (layer->debug) {
msDebug("msMSSQL2008LayerGetNumFeatures: No results found.\n");
}
return -1;
}
rc = SQLGetData(layerinfo->conn->hstmt, 1, SQL_C_CHAR, result_data, sizeof(result_data), &retLen);
if (rc == SQL_ERROR) {
msSetError(MS_QUERYERR, "Failed to get feature count", "msMSSQL2008LayerGetNumFeatures()");
return -1;
}
result_data[retLen] = 0;
return atoi(result_data);
}
/* Prepare and execute the SQL statement for this layer */
static int prepare_database(layerObj *layer, rectObj rect, char **query_string)
{
msMSSQL2008LayerInfo *layerinfo;
char *query = 0;
char *data_source = 0;
char *f_table_name = 0;
char *geom_table = 0;
char *tmp = 0;
char *paging_query = 0;
/*
"Geometry::STGeomFromText('POLYGON(())',)" + terminator = 40 chars
Plus 10 formatted doubles (15 digits of precision, a decimal point, a space/comma delimiter each = 17 chars each)
Plus SRID + comma - if SRID is a long...we'll be safe with 10 chars
or for geography columns
"Geography::STGeomFromText('CURVEPOLYGON(())',)" + terminator = 46 chars
Plus 18 formatted doubles (15 digits of precision, a decimal point, a space/comma delimiter each = 17 chars each)
Plus SRID + comma - if SRID is a long...we'll be safe with 10 chars
*/
char box3d[46 + 18 * 22 + 11];
int t;
char *pos_from, *pos_ftab, *pos_space, *pos_paren;
int hasFilter = MS_FALSE;
const rectObj rectInvalid = MS_INIT_INVALID_RECT;
const int bIsValidRect = memcmp(&rect, &rectInvalid, sizeof(rect)) != 0;
layerinfo = getMSSQL2008LayerInfo(layer);
/* Extract the proper f_table_name from the geom_table string.
* We are expecting the geom_table to be either a single word
* or a sub-select clause that possibly includes a join --
*
* (select column[,column[,...]] from ftab[ natural join table2]) as foo
*
* We are expecting whitespace or a ')' after the ftab name.
*
*/
geom_table = msStrdup(layerinfo->geom_table);
pos_from = strstrIgnoreCase(geom_table, " from ");
if(!pos_from) {
f_table_name = (char *) msSmallMalloc(strlen(geom_table) + 1);
strcpy(f_table_name, geom_table);
} else { /* geom_table is a sub-select clause */
pos_ftab = pos_from + 6; /* This should be the start of the ftab name */
pos_space = strstr(pos_ftab, " "); /* First space */
/* TODO strrchr is POSIX and C99, rindex is neither */
#if defined(_WIN32) && !defined(__CYGWIN__)
pos_paren = strrchr(pos_ftab, ')');
#else
pos_paren = rindex(pos_ftab, ')');
#endif
if(!pos_space || !pos_paren) {
msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "prepare_database()", geom_table, "Error parsing MSSQL2008 data variable: Something is wrong with your subselect statement.<br><br>\n\nMore Help:<br><br>\n\n");
return MS_FAILURE;
}
if (pos_paren < pos_space) { /* closing parenthesis preceeds any space */
f_table_name = (char *) msSmallMalloc(pos_paren - pos_ftab + 1);
strlcpy(f_table_name, pos_ftab, pos_paren - pos_ftab + 1);
} else {
f_table_name = (char *) msSmallMalloc(pos_space - pos_ftab + 1);
strlcpy(f_table_name, pos_ftab, pos_space - pos_ftab + 1);
}
}
if (rect.minx == rect.maxx || rect.miny == rect.maxy) {
/* create point shape for rectangles with zero area */
sprintf(box3d, "%s::STGeomFromText('POINT(%.15g %.15g)',%s)", /* %s.STSrid)", */
layerinfo->geom_column_type, rect.minx, rect.miny, layerinfo->user_srid);
} else if (strcasecmp(layerinfo->geom_column_type, "geography") == 0) {
/* SQL Server has a problem when x is -180 or 180 */
double minx = rect.minx <= -180? -179.999: rect.minx;
double maxx = rect.maxx >= 180? 179.999: rect.maxx;
double miny = rect.miny < -90? -90: rect.miny;
double maxy = rect.maxy > 90? 90: rect.maxy;
sprintf(box3d, "Geography::STGeomFromText('CURVEPOLYGON((%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g))',%s)", /* %s.STSrid)", */
minx, miny,
minx + (maxx - minx) / 2, miny,
maxx, miny,
maxx, miny + (maxy - miny) / 2,
maxx, maxy,
minx + (maxx - minx) / 2, maxy,
minx, maxy,
minx, miny + (maxy - miny) / 2,
minx, miny,
layerinfo->user_srid);
} else {
sprintf(box3d, "Geometry::STGeomFromText('POLYGON((%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g))',%s)", /* %s.STSrid)", */
rect.minx, rect.miny,
rect.maxx, rect.miny,
rect.maxx, rect.maxy,
rect.minx, rect.maxy,
rect.minx, rect.miny,
layerinfo->user_srid
);
}
/* substitute token '!BOX!' in geom_table with the box3d - do an unlimited # of subs */
/* to not undo the work here, we need to make sure that data_source is malloc'd here */
if (!strstr(geom_table, "!BOX!")) {
data_source = (char *)msSmallMalloc(strlen(geom_table) + 1);
strcpy(data_source, geom_table);
}
else {
char* result = NULL;
while (strstr(geom_table, "!BOX!")) {
/* need to do a substition */
char *start, *end;
char *oldresult = result;
start = strstr(geom_table, "!BOX!");
end = start + 5;
result = (char *)msSmallMalloc((start - geom_table) + strlen(box3d) + strlen(end) + 1);
strlcpy(result, geom_table, start - geom_table + 1);
strcpy(result + (start - geom_table), box3d);
strcat(result, end);
geom_table = result;
msFree(oldresult);
}
/* if we're here, this will be a malloc'd string, so no need to copy it */
data_source = (char *)geom_table;
}
/* start creating the query */
query = msStringConcatenate(query, "SELECT ");
if (layerinfo->paging && (layer->maxfeatures >= 0 || layer->startindex > 0))
paging_query = msStringConcatenate(paging_query, "SELECT ");
/* adding items to the select list */
for (t = 0; t < layer->numitems; t++) {
#ifdef USE_ICONV
query = msStringConcatenate(query, "convert(nvarchar(max), [");
#else
query = msStringConcatenate(query, "convert(varchar(max), [");
#endif
query = msStringConcatenate(query, layer->items[t]);
query = msStringConcatenate(query, "]) '");
tmp = msIntToString(t);
query = msStringConcatenate(query, tmp);
if (paging_query) {
paging_query = msStringConcatenate(paging_query, "[");
paging_query = msStringConcatenate(paging_query, tmp);
paging_query = msStringConcatenate(paging_query, "], ");
}
msFree(tmp);
query = msStringConcatenate(query, "',");
}
/* adding geometry column */
query = msStringConcatenate(query, "[");
query = msStringConcatenate(query, layerinfo->geom_column);
if (layerinfo->geometry_format == MSSQLGEOMETRY_NATIVE)
query = msStringConcatenate(query, "] 'geom',");
else {
query = msStringConcatenate(query, "].STAsBinary() 'geom',");
}
/* adding id column */
query = msStringConcatenate(query, "convert(varchar(36), [");
query = msStringConcatenate(query, layerinfo->urid_name);
if (paging_query) {
paging_query = msStringConcatenate(paging_query, "[geom], [id] FROM (");
query = msStringConcatenate(query, "]) 'id', row_number() over (");
if (layerinfo->sort_spec) {
query = msStringConcatenate(query, layerinfo->sort_spec);
}
if (layer->sortBy.nProperties > 0) {
tmp = msLayerBuildSQLOrderBy(layer);
if (layerinfo->sort_spec) {
query = msStringConcatenate(query, ", ");
}
else {
query = msStringConcatenate(query, " ORDER BY ");
}
query = msStringConcatenate(query, tmp);
msFree(tmp);
}
else {
if (!layerinfo->sort_spec) {
// use the unique Id as the default sort for paging
query = msStringConcatenate(query, "ORDER BY ");
query = msStringConcatenate(query, layerinfo->urid_name);
}
}
query = msStringConcatenate(query, ") 'rownum' FROM ");
}
else {
query = msStringConcatenate(query, "]) 'id' FROM ");
}
/* adding the source */
query = msStringConcatenate(query, data_source);
msFree(data_source);
msFree(f_table_name);
/* use the index hint if provided */
if (layerinfo->index_name) {
query = msStringConcatenate(query, " WITH (INDEX(");
query = msStringConcatenate(query, layerinfo->index_name);
query = msStringConcatenate(query, "))");
}
/* adding attribute filter */
hasFilter = addFilter(layer, &query);
if( bIsValidRect ) {
/* adding spatial filter */
if (hasFilter == MS_FALSE)
query = msStringConcatenate(query, " WHERE ");
else
query = msStringConcatenate(query, " AND ");
query = msStringConcatenate(query, layerinfo->geom_column);
query = msStringConcatenate(query, ".STIntersects(");
query = msStringConcatenate(query, box3d);
query = msStringConcatenate(query, ") = 1 ");
}
if (paging_query) {
paging_query = msStringConcatenate(paging_query, query);
paging_query = msStringConcatenate(paging_query, ") tbl where [rownum] ");
if (layer->startindex > 0) {
tmp = msIntToString(layer->startindex);
paging_query = msStringConcatenate(paging_query, ">= ");
paging_query = msStringConcatenate(paging_query, tmp);
if (layer->maxfeatures >= 0) {
msFree(tmp);
tmp = msIntToString(layer->startindex + layer->maxfeatures);
paging_query = msStringConcatenate(paging_query, " and [rownum] < ");
paging_query = msStringConcatenate(paging_query, tmp);
}
}
else {
tmp = msIntToString(layer->maxfeatures);
paging_query = msStringConcatenate(paging_query, "< ");
paging_query = msStringConcatenate(paging_query, tmp);
}
msFree(tmp);
msFree(query);
query = paging_query;
}
else {
if (layerinfo->sort_spec) {
query = msStringConcatenate(query, layerinfo->sort_spec);
}
/* Add extra sort by */
if (layer->sortBy.nProperties > 0) {
char* pszTmp = msLayerBuildSQLOrderBy(layer);
if (layerinfo->sort_spec)
query = msStringConcatenate(query, ", ");
else
query = msStringConcatenate(query, " ORDER BY ");
query = msStringConcatenate(query, pszTmp);
msFree(pszTmp);
}
}
if (layer->debug) {
msDebug("query:%s\n", query);
}
if (executeSQL(layerinfo->conn, query)) {
char pass_field_def = 0;
int t;
const char *value;
*query_string = query;
/* collect result information */
if ((value = msOWSLookupMetadata(&(layer->metadata), "G", "types")) != NULL
&& strcasecmp(value, "auto") == 0)
pass_field_def = 1;
msFree(layerinfo->itemtypes);
layerinfo->itemtypes = msSmallMalloc(sizeof(SQLSMALLINT) * (layer->numitems + 1));
for (t = 0; t < layer->numitems; t++) {
char colBuff[256];
SQLSMALLINT itemType = 0;
columnName(layerinfo->conn, t + 1, colBuff, sizeof(colBuff), layer, pass_field_def, &itemType);
layerinfo->itemtypes[t] = itemType;
}
return MS_SUCCESS;
}
else {
msSetError(MS_QUERYERR, "Error executing MSSQL2008 SQL statement: %s\n-%s\n", "msMSSQL2008LayerGetShape()", query, layerinfo->conn->errorMessage);
msFree(query);
return MS_FAILURE;
}
}
/* Execute SQL query for this layer */
int msMSSQL2008LayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
{
msMSSQL2008LayerInfo *layerinfo = 0;
char *query_str = 0;
int set_up_result;
if(layer->debug) {
msDebug("msMSSQL2008LayerWhichShapes called\n");
}
layerinfo = getMSSQL2008LayerInfo(layer);
if(!layerinfo) {
/* layer not opened yet */
msSetError(MS_QUERYERR, "msMSSQL2008LayerWhichShapes called on unopened layer (layerinfo = NULL)", "msMSSQL2008LayerWhichShapes()");
return MS_FAILURE;
}
if(!layer->data) {
msSetError(MS_QUERYERR, "Missing DATA clause in MSSQL2008 Layer definition. DATA statement must contain 'geometry_column from table_name' or 'geometry_column from (sub-query) as foo'.", "msMSSQL2008LayerWhichShapes()");
return MS_FAILURE;
}
set_up_result = prepare_database(layer, rect, &query_str);
if(set_up_result != MS_SUCCESS) {
msFree(query_str);
return set_up_result; /* relay error */
}
msFree(layerinfo->sql);
layerinfo->sql = query_str;
layerinfo->row_num = 0;
return MS_SUCCESS;
}
/* Close the MSSQL2008 record set and connection */
int msMSSQL2008LayerClose(layerObj *layer)
{
msMSSQL2008LayerInfo *layerinfo;
layerinfo = getMSSQL2008LayerInfo(layer);
if(layer->debug) {
char *data = "";
if (layer->data) {
data = layer->data;
}
msDebug("msMSSQL2008LayerClose datastatement: %s\n", data);
}
if(layer->debug && !layerinfo) {
msDebug("msMSSQL2008LayerClose -- layerinfo is NULL\n");
}
if(layerinfo) {
msConnPoolRelease(layer, layerinfo->conn);
layerinfo->conn = NULL;
if(layerinfo->user_srid) {
msFree(layerinfo->user_srid);
layerinfo->user_srid = NULL;
}
if(layerinfo->urid_name) {
msFree(layerinfo->urid_name);
layerinfo->urid_name = NULL;
}
if(layerinfo->index_name) {
msFree(layerinfo->index_name);
layerinfo->index_name = NULL;
}
if(layerinfo->sort_spec) {
msFree(layerinfo->sort_spec);
layerinfo->sort_spec = NULL;
}
if(layerinfo->sql) {
msFree(layerinfo->sql);
layerinfo->sql = NULL;
}
if(layerinfo->geom_column) {
msFree(layerinfo->geom_column);
layerinfo->geom_column = NULL;
}
if(layerinfo->geom_column_type) {
msFree(layerinfo->geom_column_type);
layerinfo->geom_column_type = NULL;
}
if(layerinfo->geom_table) {
msFree(layerinfo->geom_table);
layerinfo->geom_table = NULL;
}
if(layerinfo->itemtypes) {
msFree(layerinfo->itemtypes);
layerinfo->itemtypes = NULL;
}
setMSSQL2008LayerInfo(layer, NULL);
msFree(layerinfo);
}
return MS_SUCCESS;
}
/* ******************************************************* */
/* wkb is assumed to be 2d (force_2d) */
/* and wkb is a GEOMETRYCOLLECTION (force_collection) */
/* and wkb is in the endian of this computer (asbinary(...,'[XN]DR')) */
/* each of the sub-geom inside the collection are point,linestring, or polygon */
/* */
/* also, int is 32bits long */
/* double is 64bits long */
/* ******************************************************* */
/* convert the wkb into points */
/* points -> pass through */
/* lines-> constituent points */
/* polys-> treat ring like line and pull out the consituent points */
static int force_to_points(char *wkb, shapeObj *shape)
{
/* we're going to make a 'line' for each entity (point, line or ring) in the geom collection */
int offset = 0;
int ngeoms;
int t, u, v;
int type, nrings, npoints;
lineObj line = {0, NULL};
shape->type = MS_SHAPE_NULL; /* nothing in it */
memcpy(&ngeoms, &wkb[5], 4);
offset = 9; /* were the first geometry is */
for(t=0; t < ngeoms; t++) {
memcpy(&type, &wkb[offset + 1], 4); /* type of this geometry */
if(type == 1) {
/* Point */
shape->type = MS_SHAPE_POINT;
line.numpoints = 1;
line.point = (pointObj *) msSmallMalloc(sizeof(pointObj));
memcpy(&line.point[0].x, &wkb[offset + 5], 8);
memcpy(&line.point[0].y, &wkb[offset + 5 + 8], 8);
offset += 5 + 16;
msAddLine(shape, &line);
msFree(line.point);
} else if(type == 2) {
/* Linestring */
shape->type = MS_SHAPE_POINT;
memcpy(&line.numpoints, &wkb[offset+5], 4); /* num points */
line.point = (pointObj *) msSmallMalloc(sizeof(pointObj) * line.numpoints);
for(u = 0; u < line.numpoints; u++) {
memcpy( &line.point[u].x, &wkb[offset+9 + (16 * u)], 8);
memcpy( &line.point[u].y, &wkb[offset+9 + (16 * u)+8], 8);
}
offset += 9 + 16 * line.numpoints; /* length of object */
msAddLine(shape, &line);
msFree(line.point);
} else if(type == 3) {
/* Polygon */
shape->type = MS_SHAPE_POINT;
memcpy(&nrings, &wkb[offset+5],4); /* num rings */
/* add a line for each polygon ring */
offset += 9; /* now points at 1st linear ring */
for(u = 0; u < nrings; u++) {
/* for each ring, make a line */
memcpy(&npoints, &wkb[offset], 4); /* num points */
line.numpoints = npoints;
line.point = (pointObj *) msSmallMalloc(sizeof(pointObj)* npoints);
/* point struct */
for(v = 0; v < npoints; v++) {
memcpy(&line.point[v].x, &wkb[offset + 4 + (16 * v)], 8);
memcpy(&line.point[v].y, &wkb[offset + 4 + (16 * v) + 8], 8);
}
/* make offset point to next linear ring */
msAddLine(shape, &line);
msFree(line.point);
offset += 4 + 16 *npoints;
}
}
}
return MS_SUCCESS;
}
/* convert the wkb into lines */
/* points-> remove */
/* lines -> pass through */
/* polys -> treat rings as lines */
static int force_to_lines(char *wkb, shapeObj *shape)
{
int offset = 0;
int ngeoms;
int t, u, v;
int type, nrings, npoints;
lineObj line = {0, NULL};
shape->type = MS_SHAPE_NULL; /* nothing in it */
memcpy(&ngeoms, &wkb[5], 4);
offset = 9; /* were the first geometry is */
for(t=0; t < ngeoms; t++) {
memcpy(&type, &wkb[offset + 1], 4); /* type of this geometry */
/* cannot do anything with a point */
if(type == 2) {
/* Linestring */
shape->type = MS_SHAPE_LINE;
memcpy(&line.numpoints, &wkb[offset + 5], 4);
line.point = (pointObj*) msSmallMalloc(sizeof(pointObj) * line.numpoints );
for(u=0; u < line.numpoints; u++) {
memcpy(&line.point[u].x, &wkb[offset + 9 + (16 * u)], 8);
memcpy(&line.point[u].y, &wkb[offset + 9 + (16 * u)+8], 8);
}
offset += 9 + 16 * line.numpoints; /* length of object */
msAddLine(shape, &line);
msFree(line.point);
} else if(type == 3) {
/* polygon */
shape->type = MS_SHAPE_LINE;
memcpy(&nrings, &wkb[offset + 5], 4); /* num rings */
/* add a line for each polygon ring */
offset += 9; /* now points at 1st linear ring */
for(u = 0; u < nrings; u++) {
/* for each ring, make a line */
memcpy(&npoints, &wkb[offset], 4);
line.numpoints = npoints;
line.point = (pointObj*) msSmallMalloc(sizeof(pointObj) * npoints);
/* point struct */
for(v = 0; v < npoints; v++) {
memcpy(&line.point[v].x, &wkb[offset + 4 + (16 * v)], 8);
memcpy(&line.point[v].y, &wkb[offset + 4 + (16 * v) + 8], 8);
}
/* make offset point to next linear ring */
msAddLine(shape, &line);
msFree(line.point);
offset += 4 + 16 * npoints;
}
}
}
return MS_SUCCESS;
}
/* point -> reject */
/* line -> reject */
/* polygon -> lines of linear rings */
static int force_to_polygons(char *wkb, shapeObj *shape)
{
int offset = 0;
int ngeoms;
int t, u, v;
int type, nrings, npoints;
lineObj line = {0, NULL};
shape->type = MS_SHAPE_NULL; /* nothing in it */
memcpy(&ngeoms, &wkb[5], 4);
offset = 9; /* were the first geometry is */
for(t = 0; t < ngeoms; t++) {
memcpy(&type, &wkb[offset + 1], 4); /* type of this geometry */
if(type == 3) {
/* polygon */
shape->type = MS_SHAPE_POLYGON;
memcpy(&nrings, &wkb[offset + 5], 4); /* num rings */
/* add a line for each polygon ring */
offset += 9; /* now points at 1st linear ring */
for(u=0; u < nrings; u++) {
/* for each ring, make a line */
memcpy(&npoints, &wkb[offset], 4); /* num points */
line.numpoints = npoints;
line.point = (pointObj*) msSmallMalloc(sizeof(pointObj) * npoints);
for(v=0; v < npoints; v++) {
memcpy(&line.point[v].x, &wkb[offset + 4 + (16 * v)], 8);
memcpy(&line.point[v].y, &wkb[offset + 4 + (16 * v) + 8], 8);
}
/* make offset point to next linear ring */
msAddLine(shape, &line);
msFree(line.point);
offset += 4 + 16 * npoints;
}
}
}
return MS_SUCCESS;
}
/* if there is any polygon in wkb, return force_polygon */
/* if there is any line in wkb, return force_line */
/* otherwise return force_point */
static int dont_force(char *wkb, shapeObj *shape)
{
int offset =0;
int ngeoms;
int type, t;
int best_type;
best_type = MS_SHAPE_NULL; /* nothing in it */
memcpy(&ngeoms, &wkb[5], 4);
offset = 9; /* were the first geometry is */
for(t = 0; t < ngeoms; t++) {
memcpy(&type, &wkb[offset + 1], 4); /* type of this geometry */
if(type == 3) {
best_type = MS_SHAPE_POLYGON;
} else if(type ==2 && best_type != MS_SHAPE_POLYGON) {
best_type = MS_SHAPE_LINE;
} else if(type == 1 && best_type == MS_SHAPE_NULL) {
best_type = MS_SHAPE_POINT;
}
}
if(best_type == MS_SHAPE_POINT) {
return force_to_points(wkb, shape);
}
if(best_type == MS_SHAPE_LINE) {
return force_to_lines(wkb, shape);
}
if(best_type == MS_SHAPE_POLYGON) {
return force_to_polygons(wkb, shape);
}
return MS_FAILURE; /* unknown type */
}
#if 0
/* ******************************************************* */
/* wkb assumed to be same endian as this machine. */
/* Should be in little endian (default if created by Microsoft platforms) */
/* ******************************************************* */
/* convert the wkb into points */
/* points -> pass through */
/* lines-> constituent points */
/* polys-> treat ring like line and pull out the consituent points */
static int force_to_shapeType(char *wkb, shapeObj *shape, int msShapeType)
{
int offset = 0;
int ngeoms = 1;
int u, v;
int type, nrings, npoints;
lineObj line = {0, NULL};
shape->type = MS_SHAPE_NULL; /* nothing in it */
do {
ngeoms--;
memcpy(&type, &wkb[offset + 1], 4); /* type of this geometry */
if (type == 1) {
/* Point */
shape->type = msShapeType;
line.numpoints = 1;
line.point = (pointObj *) msSmallMalloc(sizeof(pointObj));
memcpy(&line.point[0].x, &wkb[offset + 5], 8);
memcpy(&line.point[0].y, &wkb[offset + 5 + 8], 8);
offset += 5 + 16;
if (msShapeType == MS_SHAPE_POINT) {
msAddLine(shape, &line);
}
msFree(line.point);
} else if(type == 2) {
/* Linestring */
shape->type = msShapeType;
memcpy(&line.numpoints, &wkb[offset+5], 4); /* num points */
line.point = (pointObj *) msSmallMalloc(sizeof(pointObj) * line.numpoints);
for(u = 0; u < line.numpoints; u++) {
memcpy( &line.point[u].x, &wkb[offset+9 + (16 * u)], 8);
memcpy( &line.point[u].y, &wkb[offset+9 + (16 * u)+8], 8);
}
offset += 9 + 16 * line.numpoints; /* length of object */
if ((msShapeType == MS_SHAPE_POINT) || (msShapeType == MS_SHAPE_LINE)) {
msAddLine(shape, &line);
}
msFree(line.point);
} else if(type == 3) {
/* Polygon */
shape->type = msShapeType;
memcpy(&nrings, &wkb[offset+5],4); /* num rings */
/* add a line for each polygon ring */
offset += 9; /* now points at 1st linear ring */
for(u = 0; u < nrings; u++) {
/* for each ring, make a line */
memcpy(&npoints, &wkb[offset], 4); /* num points */
line.numpoints = npoints;
line.point = (pointObj *) msSmallMalloc(sizeof(pointObj)* npoints);
/* point struct */
for(v = 0; v < npoints; v++) {
memcpy(&line.point[v].x, &wkb[offset + 4 + (16 * v)], 8);
memcpy(&line.point[v].y, &wkb[offset + 4 + (16 * v) + 8], 8);
}
/* make offset point to next linear ring */
msAddLine(shape, &line);
msFree(line.point);
offset += 4 + 16 *npoints;
}
} else if(type >= 4 && type <= 7) {
int cnt = 0;
offset += 5;
memcpy(&cnt, &wkb[offset], 4);
offset += 4; /* were the first geometry is */
ngeoms += cnt;
}
} while (ngeoms > 0);
return MS_SUCCESS;
}
#endif
///* if there is any polygon in wkb, return force_polygon */
///* if there is any line in wkb, return force_line */
///* otherwise return force_point */
//static int dont_force(char *wkb, shapeObj *shape)
//{
// int offset =0;
// int ngeoms = 1;
// int type;
// int best_type;
// int u;
// int nrings, npoints;
//
// best_type = MS_SHAPE_NULL; /* nothing in it */
//
// do
// {
// ngeoms--;
//
// memcpy(&type, &wkb[offset + 1], 4); /* type of this geometry */
//
// if(type == 3) {
// best_type = MS_SHAPE_POLYGON;
// } else if(type ==2 && best_type != MS_SHAPE_POLYGON) {
// best_type = MS_SHAPE_LINE;
// } else if(type == 1 && best_type == MS_SHAPE_NULL) {
// best_type = MS_SHAPE_POINT;
// }
//
// if (type == 1)
// {
// /* Point */
// offset += 5 + 16;
// }
// else if(type == 2)
// {
// int numPoints;
//
// memcpy(&numPoints, &wkb[offset+5], 4); /* num points */
// /* Linestring */
// offset += 9 + 16 * numPoints; /* length of object */
// }
// else if(type == 3)
// {
// /* Polygon */
// memcpy(&nrings, &wkb[offset+5],4); /* num rings */
// offset += 9; /* now points at 1st linear ring */
// for(u = 0; u < nrings; u++) {
// /* for each ring, make a line */
// memcpy(&npoints, &wkb[offset], 4); /* num points */
// offset += 4 + 16 *npoints;
// }
// }
// else if(type >= 4 && type <= 7)
// {
// int cnt = 0;
//
// offset += 5;
//
// memcpy(&cnt, &wkb[offset], 4);
// offset += 4; /* were the first geometry is */
//
// ngeoms += cnt;
// }
// }
// while (ngeoms > 0);
//
// return force_to_shapeType(wkb, shape, best_type);
//}
//
/* find the bounds of the shape */
static void find_bounds(shapeObj *shape)
{
int t, u;
int first_one = 1;
for(t = 0; t < shape->numlines; t++) {
for(u = 0; u < shape->line[t].numpoints; u++) {
if(first_one) {
shape->bounds.minx = shape->line[t].point[u].x;
shape->bounds.maxx = shape->line[t].point[u].x;
shape->bounds.miny = shape->line[t].point[u].y;
shape->bounds.maxy = shape->line[t].point[u].y;
first_one = 0;
} else {
if(shape->line[t].point[u].x < shape->bounds.minx) {
shape->bounds.minx = shape->line[t].point[u].x;
}
if(shape->line[t].point[u].x > shape->bounds.maxx) {
shape->bounds.maxx = shape->line[t].point[u].x;
}
if(shape->line[t].point[u].y < shape->bounds.miny) {
shape->bounds.miny = shape->line[t].point[u].y;
}
if(shape->line[t].point[u].y > shape->bounds.maxy) {
shape->bounds.maxy = shape->line[t].point[u].y;
}
}
}
}
}
/* Used by NextShape() to access a shape in the query set */
int msMSSQL2008LayerGetShapeRandom(layerObj *layer, shapeObj *shape, long *record)
{
msMSSQL2008LayerInfo *layerinfo;
SQLLEN needLen = 0;
SQLLEN retLen = 0;
char dummyBuffer[1];
char *wkbBuffer;
char *valueBuffer;
char oidBuffer[ 16 ]; /* assuming the OID will always be a long this should be enough */
long record_oid;
int t;
/* for coercing single types into geometry collections */
char *wkbTemp;
int geomType;
layerinfo = getMSSQL2008LayerInfo(layer);
if(!layerinfo) {
msSetError(MS_QUERYERR, "GetShape called with layerinfo = NULL", "msMSSQL2008LayerGetShape()");
return MS_FAILURE;
}
if(!layerinfo->conn) {
msSetError(MS_QUERYERR, "NextShape called on MSSQL2008 layer with no connection to DB.", "msMSSQL2008LayerGetShape()");
return MS_FAILURE;
}
shape->type = MS_SHAPE_NULL;
while(shape->type == MS_SHAPE_NULL) {
/* SQLRETURN rc = SQLFetchScroll(layerinfo->conn->hstmt, SQL_FETCH_ABSOLUTE, (SQLLEN) (*record) + 1); */
/* We only do forward fetches. the parameter 'record' is ignored, but is incremented */
SQLRETURN rc = SQLFetch(layerinfo->conn->hstmt);
/* Any error assume out of recordset bounds */
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
handleSQLError(layer);
return MS_DONE;
}
/* retreive an item */
{
/* have to retrieve shape attributes */
shape->values = (char **) msSmallMalloc(sizeof(char *) * layer->numitems);
shape->numvalues = layer->numitems;
for(t=0; t < layer->numitems; t++) {
/* figure out how big the buffer needs to be */
rc = SQLGetData(layerinfo->conn->hstmt, (SQLUSMALLINT)(t + 1), SQL_C_BINARY, dummyBuffer, 0, &needLen);
if (rc == SQL_ERROR)
handleSQLError(layer);
if (needLen > 0) {
/* allocate the buffer - this will be a null-terminated string so alloc for the null too */
valueBuffer = (char*) msSmallMalloc( needLen + 2 );
if ( valueBuffer == NULL ) {
msSetError( MS_QUERYERR, "Could not allocate value buffer.", "msMSSQL2008LayerGetShapeRandom()" );
return MS_FAILURE;
}
/* Now grab the data */
rc = SQLGetData(layerinfo->conn->hstmt, (SQLUSMALLINT)(t + 1), SQL_C_BINARY, valueBuffer, needLen, &retLen);
if (rc == SQL_ERROR || rc == SQL_SUCCESS_WITH_INFO)
handleSQLError(layer);
/* Terminate the buffer */
valueBuffer[retLen] = 0; /* null terminate it */
/* Pop the value into the shape's value array */
#ifdef USE_ICONV
valueBuffer[retLen + 1] = 0;
shape->values[t] = msConvertWideStringToUTF8((wchar_t*)valueBuffer, "UCS-2LE");
msFree(valueBuffer);
#else
shape->values[t] = valueBuffer;
#endif
} else
/* Copy empty sting for NULL values */
shape->values[t] = msStrdup("");
}
/* Get shape geometry */
{
/* Set up to request the size of the buffer needed */
rc = SQLGetData(layerinfo->conn->hstmt, (SQLUSMALLINT)(layer->numitems + 1), SQL_C_BINARY, dummyBuffer, 0, &needLen);
if (rc == SQL_ERROR)
handleSQLError(layer);
/* allow space for coercion to geometry collection if needed*/
wkbTemp = (char*)msSmallMalloc(needLen+9);
/* write data above space allocated for geometry collection coercion */
wkbBuffer = wkbTemp + 9;
if ( wkbBuffer == NULL ) {
msSetError( MS_QUERYERR, "Could not allocate value buffer.", "msMSSQL2008LayerGetShapeRandom()" );
return MS_FAILURE;
}
/* Grab the WKB */
rc = SQLGetData(layerinfo->conn->hstmt, (SQLUSMALLINT)(layer->numitems + 1), SQL_C_BINARY, wkbBuffer, needLen, &retLen);
if (rc == SQL_ERROR || rc == SQL_SUCCESS_WITH_INFO)
handleSQLError(layer);
if (layerinfo->geometry_format == MSSQLGEOMETRY_NATIVE) {
layerinfo->gpi.pszData = (unsigned char*)wkbBuffer;
layerinfo->gpi.nLen = (int)retLen;
if (!ParseSqlGeometry(layerinfo, shape)) {
switch(layer->type) {
case MS_LAYER_POINT:
shape->type = MS_SHAPE_POINT;
break;
case MS_LAYER_LINE:
shape->type = MS_SHAPE_LINE;
break;
case MS_LAYER_POLYGON:
shape->type = MS_SHAPE_POLYGON;
break;
default:
break;
}
}
} else {
memcpy(&geomType, wkbBuffer + 1, 4);
/* is this a single type? */
if (geomType < 4) {
/* copy byte order marker (although we don't check it) */
wkbTemp[0] = wkbBuffer[0];
wkbBuffer = wkbTemp;
/* indicate type is geometry collection (although geomType + 3 would also work) */
wkbBuffer[1] = (char)7;
wkbBuffer[2] = (char)0;
wkbBuffer[3] = (char)0;
wkbBuffer[4] = (char)0;
/* indicate 1 shape */
wkbBuffer[5] = (char)1;
wkbBuffer[6] = (char)0;
wkbBuffer[7] = (char)0;
wkbBuffer[8] = (char)0;
}
switch(layer->type) {
case MS_LAYER_POINT:
/*result =*/ force_to_points(wkbBuffer, shape);
break;
case MS_LAYER_LINE:
/*result =*/ force_to_lines(wkbBuffer, shape);
break;
case MS_LAYER_POLYGON:
/*result =*/ force_to_polygons(wkbBuffer, shape);
break;
case MS_LAYER_QUERY:
case MS_LAYER_CHART:
/*result =*/ dont_force(wkbBuffer, shape);
break;
case MS_LAYER_RASTER:
msDebug( "Ignoring MS_LAYER_RASTER in mapMSSQL2008.c\n" );
break;
case MS_LAYER_CIRCLE:
msDebug( "Ignoring MS_LAYER_CIRCLE in mapMSSQL2008.c\n" );
break;
default:
msDebug( "Unsupported layer type in msMSSQL2008LayerNextShape()!" );
break;
}
find_bounds(shape);
}
//free(wkbBuffer);
msFree(wkbTemp);
}
/* Next get unique id for row - since the OID shouldn't be larger than a long we'll assume billions as a limit */
rc = SQLGetData(layerinfo->conn->hstmt, (SQLUSMALLINT)(layer->numitems + 2), SQL_C_BINARY, oidBuffer, sizeof(oidBuffer) - 1, &retLen);
if (rc == SQL_ERROR || rc == SQL_SUCCESS_WITH_INFO)
handleSQLError(layer);
if (retLen < sizeof(oidBuffer))
{
oidBuffer[retLen] = 0;
record_oid = strtol(oidBuffer, NULL, 10);
shape->index = record_oid;
}
else
{
/* non integer fid column, use single pass */
shape->index = -1;
}
shape->resultindex = (*record);
(*record)++; /* move to next shape */
if(shape->type != MS_SHAPE_NULL) {
return MS_SUCCESS;
} else {
msDebug("msMSSQL2008LayerGetShapeRandom bad shape: %ld\n", *record);
}
/* if (layer->type == MS_LAYER_POINT) {return MS_DONE;} */
}
}
msFreeShape(shape);
return MS_FAILURE;
}
/* find the next shape with the appropriate shape type (convert it if necessary) */
/* also, load in the attribute data */
/* MS_DONE => no more data */
int msMSSQL2008LayerNextShape(layerObj *layer, shapeObj *shape)
{
int result;
msMSSQL2008LayerInfo *layerinfo;
layerinfo = getMSSQL2008LayerInfo(layer);
if(!layerinfo) {
msSetError(MS_QUERYERR, "NextShape called with layerinfo = NULL", "msMSSQL2008LayerNextShape()");
return MS_FAILURE;
}
result = msMSSQL2008LayerGetShapeRandom(layer, shape, &(layerinfo->row_num));
/* getshaperandom will increment the row_num */
/* layerinfo->row_num ++; */
return result;
}
/* Execute a query on the DB based on the query result. */
int msMSSQL2008LayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
{
char *query_str;
char *columns_wanted = 0;
msMSSQL2008LayerInfo *layerinfo;
int t;
char buffer[32000] = "";
long shapeindex = record->shapeindex;
long resultindex = record->resultindex;
if(layer->debug) {
msDebug("msMSSQL2008LayerGetShape called for shapeindex = %ld\n", shapeindex);
}
layerinfo = getMSSQL2008LayerInfo(layer);
if(!layerinfo) {
/* Layer not open */
msSetError(MS_QUERYERR, "msMSSQL2008LayerGetShape called on unopened layer (layerinfo = NULL)", "msMSSQL2008LayerGetShape()");
return MS_FAILURE;
}
if (resultindex >= 0 && layerinfo->sql) {
/* trying to provide the result from the current resultset (single-pass query) */
if( resultindex < layerinfo->row_num) {
/* re-issue the query */
if (!executeSQL(layerinfo->conn, layerinfo->sql)) {
msSetError(MS_QUERYERR, "Error executing MSSQL2008 SQL statement: %s\n-%s\n", "msMSSQL2008LayerGetShape()", layerinfo->sql, layerinfo->conn->errorMessage);
return MS_FAILURE;
}
layerinfo->row_num = 0;
}
while( layerinfo->row_num < resultindex ) {
/* move forward until we reach the desired index */
if (msMSSQL2008LayerGetShapeRandom(layer, shape, &(layerinfo->row_num)) != MS_SUCCESS)
return MS_FAILURE;
}
return msMSSQL2008LayerGetShapeRandom(layer, shape, &(layerinfo->row_num));
}
/* non single-pass case, fetch the record from the database */
if(layer->numitems == 0) {
if (layerinfo->geometry_format == MSSQLGEOMETRY_NATIVE)
snprintf(buffer, sizeof(buffer), "%s, convert(varchar(36), %s)", layerinfo->geom_column, layerinfo->urid_name);
else
snprintf(buffer, sizeof(buffer), "%s.STAsBinary(), convert(varchar(36), %s)", layerinfo->geom_column, layerinfo->urid_name);
columns_wanted = msStrdup(buffer);
} else {
for(t = 0; t < layer->numitems; t++) {
snprintf(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), "convert(varchar(max), %s),", layer->items[t]);
}
if (layerinfo->geometry_format == MSSQLGEOMETRY_NATIVE)
snprintf(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), "%s, convert(varchar(36), %s)", layerinfo->geom_column, layerinfo->urid_name);
else
snprintf(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), "%s.STAsBinary(), convert(varchar(36), %s)", layerinfo->geom_column, layerinfo->urid_name);
columns_wanted = msStrdup(buffer);
}
/* index_name is ignored here since the hint should be for the spatial index, not the PK index */
snprintf(buffer, sizeof(buffer), "select %s from %s where %s = %ld", columns_wanted, layerinfo->geom_table, layerinfo->urid_name, shapeindex);
query_str = msStrdup(buffer);
if(layer->debug) {
msDebug("msMSSQL2008LayerGetShape: %s \n", query_str);
}
msFree(columns_wanted);
if (!executeSQL(layerinfo->conn, query_str)) {
msSetError(MS_QUERYERR, "Error executing MSSQL2008 SQL statement: %s\n-%s\n", "msMSSQL2008LayerGetShape()",
query_str, layerinfo->conn->errorMessage);
msFree(query_str);
return MS_FAILURE;
}
/* we don't preserve the query string in this case (cannot be re-used) */
msFree(query_str);
layerinfo->row_num = 0;
return msMSSQL2008LayerGetShapeRandom(layer, shape, &(layerinfo->row_num));
}
/*
** Returns the number of shapes that match the potential filter and extent.
* rectProjection is the projection in which rect is expressed, or can be NULL if
* rect should be considered in the layer projection.
* This should be equivalent to calling msLayerWhichShapes() and counting the
* number of shapes returned by msLayerNextShape(), honouring layer->maxfeatures
* limitation if layer->maxfeatures>=0, and honouring layer->startindex if
* layer->startindex >= 1 and paging is enabled.
* Returns -1 in case of failure.
*/
int msMSSQL2008LayerGetShapeCount(layerObj *layer, rectObj rect, projectionObj *rectProjection)
{
msMSSQL2008LayerInfo *layerinfo;
char *query = 0;
char result_data[256];
char box3d[40 + 10 * 22 + 11];
SQLLEN retLen;
SQLRETURN rc;
int hasFilter = MS_FALSE;
const rectObj rectInvalid = MS_INIT_INVALID_RECT;
const int bIsValidRect = memcmp(&rect, &rectInvalid, sizeof(rect)) != 0;
rectObj searchrectInLayerProj = rect;
if (layer->debug) {
msDebug("msMSSQL2008LayerGetShapeCount called.\n");
}
layerinfo = getMSSQL2008LayerInfo(layer);
if (!layerinfo) {
/* Layer not open */
msSetError(MS_QUERYERR, "msMSSQL2008LayerGetShapeCount called on unopened layer (layerinfo = NULL)", "msMSSQL2008LayerGetShapeCount()");
return MS_FAILURE;
}
// Special processing if the specified projection for the rect is different from the layer projection
// We want to issue a WHERE that includes
// ((the_geom && rect_reprojected_in_layer_SRID) AND NOT ST_Disjoint(ST_Transform(the_geom, rect_SRID), rect))
if (rectProjection != NULL && layer->project &&
msProjectionsDiffer(&(layer->projection), rectProjection))
{
// If we cannot guess the EPSG code of the rectProjection, fallback on slow implementation
if (rectProjection->numargs < 1 ||
strncasecmp(rectProjection->args[0], "init=epsg:", (int)strlen("init=epsg:")) != 0)
{
if (layer->debug) {
msDebug("msMSSQL2008LayerGetShapeCount(): cannot find EPSG code of rectProjection. Falling back on client-side feature count.\n");
}
return LayerDefaultGetShapeCount(layer, rect, rectProjection);
}
// Reproject the passed rect into the layer projection and get
// the SRID from the rectProjection
msProjectRect(rectProjection, &(layer->projection), &searchrectInLayerProj); /* project the searchrect to source coords */
}
if (searchrectInLayerProj.minx == searchrectInLayerProj.maxx ||
searchrectInLayerProj.miny == searchrectInLayerProj.maxy) {
/* create point shape for rectangles with zero area */
snprintf(box3d, sizeof(box3d), "%s::STGeomFromText('POINT(%.15g %.15g)',%s)", /* %s.STSrid)", */
layerinfo->geom_column_type, searchrectInLayerProj.minx, searchrectInLayerProj.miny, layerinfo->user_srid);
}
else {
snprintf(box3d, sizeof(box3d), "%s::STGeomFromText('POLYGON((%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g))',%s)", /* %s.STSrid)", */
layerinfo->geom_column_type,
searchrectInLayerProj.minx, searchrectInLayerProj.miny,
searchrectInLayerProj.maxx, searchrectInLayerProj.miny,
searchrectInLayerProj.maxx, searchrectInLayerProj.maxy,
searchrectInLayerProj.minx, searchrectInLayerProj.maxy,
searchrectInLayerProj.minx, searchrectInLayerProj.miny,
layerinfo->user_srid
);
}
msLayerTranslateFilter(layer, &layer->filter, layer->filteritem);
/* set up statement */
query = msStringConcatenate(query, "SELECT count(*) FROM ");
query = msStringConcatenate(query, layerinfo->geom_table);
/* adding attribute filter */
hasFilter = addFilter(layer, &query);
if( bIsValidRect ) {
/* adding spatial filter */
if (hasFilter == MS_FALSE)
query = msStringConcatenate(query, " WHERE ");
else
query = msStringConcatenate(query, " AND ");
query = msStringConcatenate(query, layerinfo->geom_column);
query = msStringConcatenate(query, ".STIntersects(");
query = msStringConcatenate(query, box3d);
query = msStringConcatenate(query, ") = 1 ");
}
if (layer->debug) {
msDebug("query:%s\n", query);
}
if (!executeSQL(layerinfo->conn, query)) {
msFree(query);
return -1;
}
msFree(query);
rc = SQLFetch(layerinfo->conn->hstmt);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
if (layer->debug) {
msDebug("msMSSQL2008LayerGetShapeCount: No results found.\n");
}
return -1;
}
rc = SQLGetData(layerinfo->conn->hstmt, 1, SQL_C_CHAR, result_data, sizeof(result_data), &retLen);
if (rc == SQL_ERROR) {
msSetError(MS_QUERYERR, "Failed to get feature count", "msMSSQL2008LayerGetShapeCount()");
return -1;
}
result_data[retLen] = 0;
return atoi(result_data);
}
/* Query the DB for info about the requested table */
int msMSSQL2008LayerGetItems(layerObj *layer)
{
msMSSQL2008LayerInfo *layerinfo;
char *sql = NULL;
size_t sqlSize;
char found_geom = 0;
int t, item_num;
SQLSMALLINT cols = 0;
const char *value;
/*
* Pass the field definitions through to the layer metadata in the
* "gml_[item]_{type,width,precision}" set of metadata items for
* defining fields.
*/
char pass_field_def = 0;
if(layer->debug) {
msDebug("in msMSSQL2008LayerGetItems (find column names)\n");
}
layerinfo = getMSSQL2008LayerInfo(layer);
if(!layerinfo) {
/* layer not opened yet */
msSetError(MS_QUERYERR, "msMSSQL2008LayerGetItems called on unopened layer", "msMSSQL2008LayerGetItems()");
return MS_FAILURE;
}
if(!layerinfo->conn) {
msSetError(MS_QUERYERR, "msMSSQL2008LayerGetItems called on MSSQL2008 layer with no connection to DB.", "msMSSQL2008LayerGetItems()");
return MS_FAILURE;
}
sqlSize = strlen(layerinfo->geom_table) + 30;
sql = msSmallMalloc(sizeof(char *) * sqlSize);
snprintf(sql, sqlSize, "SELECT top 0 * FROM %s", layerinfo->geom_table);
if (!executeSQL(layerinfo->conn, sql)) {
msFree(sql);
return MS_FAILURE;
}
msFree(sql);
SQLNumResultCols (layerinfo->conn->hstmt, &cols);
layer->numitems = cols - 1; /* dont include the geometry column */
layer->items = msSmallMalloc(sizeof(char *) * (layer->numitems + 1)); /* +1 in case there is a problem finding goeometry column */
layerinfo->itemtypes = msSmallMalloc(sizeof(SQLSMALLINT) * (layer->numitems + 1));
/* it will return an error if there is no geometry column found, */
/* so this isnt a problem */
found_geom = 0; /* havent found the geom field */
item_num = 0;
/* consider populating the field definitions in metadata */
if((value = msOWSLookupMetadata(&(layer->metadata), "G", "types")) != NULL
&& strcasecmp(value,"auto") == 0 )
pass_field_def = 1;
for(t = 0; t < cols; t++) {
char colBuff[256];
SQLSMALLINT itemType = 0;
columnName(layerinfo->conn, t + 1, colBuff, sizeof(colBuff), layer, pass_field_def, &itemType);
if(strcmp(colBuff, layerinfo->geom_column) != 0) {
/* this isnt the geometry column */
layer->items[item_num] = (char *) msSmallMalloc(strlen(colBuff) + 1);
strcpy(layer->items[item_num], colBuff);
layerinfo->itemtypes[item_num] = itemType;
item_num++;
} else {
found_geom = 1;
}
}
if(!found_geom) {
msSetError(MS_QUERYERR, "msMSSQL2008LayerGetItems: tried to find the geometry column in the results from the database, but couldnt find it. Is it miss-capitialized? '%s'", "msMSSQL2008LayerGetItems()", layerinfo->geom_column);
return MS_FAILURE;
}
return msMSSQL2008LayerInitItemInfo(layer);
}
/* Get primary key column of table */
int msMSSQL2008LayerRetrievePK(layerObj *layer, char **urid_name, char* table_name, int debug)
{
char sql[1024];
msMSSQL2008LayerInfo *layerinfo = 0;
SQLRETURN rc;
snprintf(sql, sizeof(sql),
"SELECT convert(varchar(50), sys.columns.name) AS ColumnName, sys.indexes.name "
"FROM sys.columns INNER JOIN "
" sys.indexes INNER JOIN "
" sys.tables ON sys.indexes.object_id = sys.tables.object_id INNER JOIN "
" sys.index_columns ON sys.indexes.object_id = sys.index_columns.object_id AND sys.indexes.index_id = sys.index_columns.index_id ON "
" sys.columns.object_id = sys.index_columns.object_id AND sys.columns.column_id = sys.index_columns.column_id "
"WHERE (sys.indexes.is_primary_key = 1) AND (sys.tables.name = N'%s') ",
table_name);
if (debug) {
msDebug("msMSSQL2008LayerRetrievePK: query = %s\n", sql);
}
layerinfo = (msMSSQL2008LayerInfo *) layer->layerinfo;
if(layerinfo->conn == NULL) {
msSetError(MS_QUERYERR, "Layer does not have a MSSQL2008 connection.", "msMSSQL2008LayerRetrievePK()");
return(MS_FAILURE);
}
/* error somewhere above here in this method */
if(!executeSQL(layerinfo->conn, sql)) {
char *tmp1;
char *tmp2 = NULL;
tmp1 = "Error executing MSSQL2008 statement (msMSSQL2008LayerRetrievePK():";
tmp2 = (char *)msSmallMalloc(sizeof(char)*(strlen(tmp1) + strlen(sql) + 1));
strcpy(tmp2, tmp1);
strcat(tmp2, sql);
msSetError(MS_QUERYERR, "%s", "msMSSQL2008LayerRetrievePK()", tmp2);
msFree(tmp2);
return(MS_FAILURE);
}
rc = SQLFetch(layerinfo->conn->hstmt);
if(rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
if(debug) {
msDebug("msMSSQL2008LayerRetrievePK: No results found.\n");
}
return MS_FAILURE;
}
{
char buff[100];
SQLLEN retLen;
rc = SQLGetData(layerinfo->conn->hstmt, 1, SQL_C_BINARY, buff, sizeof(buff), &retLen);
rc = SQLFetch(layerinfo->conn->hstmt);
if(rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) {
if(debug) {
msDebug("msMSSQL2008LayerRetrievePK: Multiple primary key columns are not supported in MapServer\n");
}
return MS_FAILURE;
}
buff[retLen] = 0;
*urid_name = msStrdup(buff);
}
return MS_SUCCESS;
}
/* Function to parse the Mapserver DATA parameter for geometry
* column name, table name and name of a column to serve as a
* unique record id
*/
static int msMSSQL2008LayerParseData(layerObj *layer, char **geom_column_name, char **geom_column_type, char **table_name, char **urid_name, char **user_srid, char **index_name, char **sort_spec, int debug)
{
char *pos_opt, *pos_scn, *tmp, *pos_srid, *pos_urid, *pos_geomtype, *pos_geomtype2, *pos_indexHint, *data, *pos_order;
size_t slength;
data = msStrdup(layer->data);
/* replace tabs with spaces */
msReplaceChar(data, '\t', ' ');
/* given a string of the from 'geom from ctivalues' or 'geom from () as foo'
* return geom_column_name as 'geom'
* and table name as 'ctivalues' or 'geom from () as foo'
*/
/* First look for the optional ' using unique ID' string */
pos_urid = strstrIgnoreCase(data, " using unique ");
if(pos_urid) {
/* CHANGE - protect the trailing edge for thing like 'using unique ftab_id using srid=33' */
tmp = strstr(pos_urid + 14, " ");
if(!tmp) {
tmp = pos_urid + strlen(pos_urid);
}
*urid_name = (char *) msSmallMalloc((tmp - (pos_urid + 14)) + 1);
strlcpy(*urid_name, pos_urid + 14, (tmp - (pos_urid + 14)) + 1);
}
/* Find the srid */
pos_srid = strstrIgnoreCase(data, " using SRID=");
if(!pos_srid) {
*user_srid = (char *) msSmallMalloc(2);
(*user_srid)[0] = '0';
(*user_srid)[1] = 0;
} else {
slength = strspn(pos_srid + 12, "-0123456789");
if(!slength) {
msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerParseData()", "Error parsing MSSQL2008 data variable: You specified 'using SRID=#' but didn't have any numbers!<br><br>\n\nMore Help:<br><br>\n\n", data);
msFree(data);
return MS_FAILURE;
} else {
*user_srid = (char *) msSmallMalloc(slength + 1);
strlcpy(*user_srid, pos_srid + 12, slength+1);
}
}
pos_indexHint = strstrIgnoreCase(data, " using index ");
if(pos_indexHint) {
/* CHANGE - protect the trailing edge for thing like 'using unique ftab_id using srid=33' */
tmp = strstr(pos_indexHint + 13, " ");
if(!tmp) {
tmp = pos_indexHint + strlen(pos_indexHint);
}
*index_name = (char *) msSmallMalloc((tmp - (pos_indexHint + 13)) + 1);
strlcpy(*index_name, pos_indexHint + 13, tmp - (pos_indexHint + 13)+1);
}
/* this is a little hack so the rest of the code works. If the ' using SRID=' comes before */
/* the ' using unique ', then make sure pos_opt points to where the ' using SRID' starts! */
pos_opt = pos_urid;
if ( !pos_opt || ( pos_srid && pos_srid < pos_opt ) ) pos_opt = pos_srid;
if ( !pos_opt || ( pos_indexHint && pos_indexHint < pos_opt ) ) pos_opt = pos_indexHint;
if ( !pos_opt ) pos_opt = data + strlen(data);
/* Scan for the table or sub-select clause */
pos_scn = strstrIgnoreCase(data, " from ");
if(!pos_scn) {
msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerParseData()", "Error parsing MSSQL2008 data variable. Must contain 'geometry_column from table_name' or 'geom from (subselect) as foo' (couldn't find ' from '). More help: <br><br>\n\n", data);
msFree(data);
return MS_FAILURE;
}
/* Scanning the geometry column type */
pos_geomtype = data;
while (pos_geomtype < pos_scn && *pos_geomtype != '(' && *pos_geomtype != 0)
++pos_geomtype;
if(*pos_geomtype == '(') {
pos_geomtype2 = pos_geomtype;
while (pos_geomtype2 < pos_scn && *pos_geomtype2 != ')' && *pos_geomtype2 != 0)
++pos_geomtype2;
if (*pos_geomtype2 != ')' || pos_geomtype2 == pos_geomtype) {
msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerParseData()", "Error parsing MSSQL2008 data variable. Invalid syntax near geometry column type.", data);
msFree(data);
return MS_FAILURE;
}
*geom_column_name = (char *) msSmallMalloc((pos_geomtype - data) + 1);
strlcpy(*geom_column_name, data, pos_geomtype - data + 1);
*geom_column_type = (char *) msSmallMalloc(pos_geomtype2 - pos_geomtype);
strlcpy(*geom_column_type, pos_geomtype + 1, pos_geomtype2 - pos_geomtype);
} else {
/* Copy the geometry column name */
*geom_column_name = (char *) msSmallMalloc((pos_scn - data) + 1);
strlcpy(*geom_column_name, data, pos_scn - data + 1);
*geom_column_type = msStrdup("geometry");
}
/* Copy out the table name or sub-select clause */
*table_name = (char *) msSmallMalloc((pos_opt - (pos_scn + 6)) + 1);
strlcpy(*table_name, pos_scn + 6, pos_opt - (pos_scn + 6) + 1);
if(strlen(*table_name) < 1 || strlen(*geom_column_name) < 1) {
msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerParseData()", "Error parsing MSSQL2008 data variable. Must contain 'geometry_column from table_name' or 'geom from (subselect) as foo' (couldnt find a geometry_column or table/subselect). More help: <br><br>\n\n", data);
msFree(data);
return MS_FAILURE;
}
if( !pos_urid ) {
if( msMSSQL2008LayerRetrievePK(layer, urid_name, *table_name, debug) != MS_SUCCESS ) {
msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerParseData()", "No primary key defined for table, or primary key contains more that one column\n\n",
*table_name);
msFree(data);
return MS_FAILURE;
}
}
/* Find the order by */
pos_order = strstrIgnoreCase(pos_opt, " order by ");
if (pos_order) {
*sort_spec = msStrdup(pos_order);
}
if(debug) {
msDebug("msMSSQL2008LayerParseData: unique column = %s, srid='%s', geom_column_name = %s, table_name=%s\n", *urid_name, *user_srid, *geom_column_name, *table_name);
}
msFree(data);
return MS_SUCCESS;
}
char *msMSSQL2008LayerEscapePropertyName(layerObj *layer, const char* pszString)
{
char* pszEscapedStr=NULL;
int i, j = 0;
if (pszString && strlen(pszString) > 0) {
size_t nLength = strlen(pszString);
pszEscapedStr = (char*) msSmallMalloc( 1 + nLength + 1 + 1);
pszEscapedStr[j++] = '[';
for (i=0; i<nLength; i++)
pszEscapedStr[j++] = pszString[i];
pszEscapedStr[j++] = ']';
pszEscapedStr[j++] = 0;
}
return pszEscapedStr;
}
char *msMSSQL2008LayerEscapeSQLParam(layerObj *layer, const char *pszString)
{
char *pszEscapedStr=NULL;
if (pszString) {
int nSrcLen;
char c;
int i=0, j=0;
nSrcLen = (int)strlen(pszString);
pszEscapedStr = (char*) msSmallMalloc( 2 * nSrcLen + 1);
for(i = 0, j = 0; i < nSrcLen; i++) {
c = pszString[i];
if (c == '\'') {
pszEscapedStr[j++] = '\'';
pszEscapedStr[j++] = '\'';
} else
pszEscapedStr[j++] = c;
}
pszEscapedStr[j] = 0;
}
return pszEscapedStr;
}
int msMSSQL2008GetPaging(layerObj *layer)
{
msMSSQL2008LayerInfo *layerinfo = NULL;
if (!msMSSQL2008LayerIsOpen(layer))
return MS_TRUE;
assert(layer->layerinfo != NULL);
layerinfo = (msMSSQL2008LayerInfo *)layer->layerinfo;
return layerinfo->paging;
}
void msMSSQL2008EnablePaging(layerObj *layer, int value)
{
msMSSQL2008LayerInfo *layerinfo = NULL;
if (!msMSSQL2008LayerIsOpen(layer))
msMSSQL2008LayerOpen(layer);
assert(layer->layerinfo != NULL);
layerinfo = (msMSSQL2008LayerInfo *)layer->layerinfo;
layerinfo->paging = value;
}
int process_node(layerObj* layer, expressionObj *filter)
{
char *snippet = NULL;
char *strtmpl = NULL;
char *stresc = NULL;
msMSSQL2008LayerInfo *layerinfo = (msMSSQL2008LayerInfo *) layer->layerinfo;
if (!layerinfo->current_node)
{
msSetError(MS_MISCERR, "Unecpected end of expression", "msMSSQL2008LayerTranslateFilter()");
return 0;
}
switch(layerinfo->current_node->token) {
case '(':
filter->native_string = msStringConcatenate(filter->native_string, "(");
/* process subexpression */
layerinfo->current_node = layerinfo->current_node->next;
while (layerinfo->current_node != NULL) {
if (!process_node(layer, filter))
return 0;
if (!layerinfo->current_node)
break;
if (layerinfo->current_node->token == ')')
break;
layerinfo->current_node = layerinfo->current_node->next;
}
break;
case ')':
filter->native_string = msStringConcatenate(filter->native_string, ")");
break;
/* argument separator */
case ',':
break;
/* literal tokens */
case MS_TOKEN_LITERAL_BOOLEAN:
if(layerinfo->current_node->tokenval.dblval == MS_TRUE)
filter->native_string = msStringConcatenate(filter->native_string, "1");
else
filter->native_string = msStringConcatenate(filter->native_string, "0");
break;
case MS_TOKEN_LITERAL_NUMBER:
strtmpl = "%lf";
snippet = (char *) msSmallMalloc(strlen(strtmpl) + 16);
sprintf(snippet, strtmpl, layerinfo->current_node->tokenval.dblval);
filter->native_string = msStringConcatenate(filter->native_string, snippet);
msFree(snippet);
break;
case MS_TOKEN_LITERAL_STRING:
strtmpl = "'%s'";
stresc = msMSSQL2008LayerEscapeSQLParam(layer, layerinfo->current_node->tokenval.strval);
snippet = (char *) msSmallMalloc(strlen(strtmpl) + strlen(stresc));
sprintf(snippet, strtmpl, stresc);
filter->native_string = msStringConcatenate(filter->native_string, snippet);
msFree(snippet);
msFree(stresc);
break;
case MS_TOKEN_LITERAL_TIME:
{
int resolution = msTimeGetResolution(layerinfo->current_node->tokensrc);
snippet = (char *) msSmallMalloc(128);
switch(resolution) {
case TIME_RESOLUTION_YEAR:
sprintf(snippet, "'%d'", (layerinfo->current_node->tokenval.tmval.tm_year+1900));
break;
case TIME_RESOLUTION_MONTH:
sprintf(snippet, "'%d-%02d-01'", (layerinfo->current_node->tokenval.tmval.tm_year+1900),
(layerinfo->current_node->tokenval.tmval.tm_mon+1));
break;
case TIME_RESOLUTION_DAY:
sprintf(snippet, "'%d-%02d-%02d'", (layerinfo->current_node->tokenval.tmval.tm_year+1900),
(layerinfo->current_node->tokenval.tmval.tm_mon+1),
layerinfo->current_node->tokenval.tmval.tm_mday);
break;
case TIME_RESOLUTION_HOUR:
sprintf(snippet, "'%d-%02d-%02d %02d:00'", (layerinfo->current_node->tokenval.tmval.tm_year+1900),
(layerinfo->current_node->tokenval.tmval.tm_mon+1),
layerinfo->current_node->tokenval.tmval.tm_mday,
layerinfo->current_node->tokenval.tmval.tm_hour);
break;
case TIME_RESOLUTION_MINUTE:
sprintf(snippet, "%d-%02d-%02d %02d:%02d'", (layerinfo->current_node->tokenval.tmval.tm_year+1900),
(layerinfo->current_node->tokenval.tmval.tm_mon+1),
layerinfo->current_node->tokenval.tmval.tm_mday,
layerinfo->current_node->tokenval.tmval.tm_hour,
layerinfo->current_node->tokenval.tmval.tm_min);
break;
case TIME_RESOLUTION_SECOND:
sprintf(snippet, "'%d-%02d-%02d %02d:%02d:%02d'", (layerinfo->current_node->tokenval.tmval.tm_year+1900),
(layerinfo->current_node->tokenval.tmval.tm_mon+1),
layerinfo->current_node->tokenval.tmval.tm_mday,
layerinfo->current_node->tokenval.tmval.tm_hour,
layerinfo->current_node->tokenval.tmval.tm_min,
layerinfo->current_node->tokenval.tmval.tm_sec);
break;
}
filter->native_string = msStringConcatenate(filter->native_string, snippet);
msFree(snippet);
}
break;
case MS_TOKEN_LITERAL_SHAPE:
if (strcasecmp(layerinfo->geom_column_type, "geography") == 0)
filter->native_string = msStringConcatenate(filter->native_string, "geography::STGeomFromText('");
else
filter->native_string = msStringConcatenate(filter->native_string, "geometry::STGeomFromText('");
filter->native_string = msStringConcatenate(filter->native_string, msShapeToWKT(layerinfo->current_node->tokenval.shpval));
filter->native_string = msStringConcatenate(filter->native_string, "'");
if(layerinfo->user_srid && strcmp(layerinfo->user_srid, "") != 0) {
filter->native_string = msStringConcatenate(filter->native_string, ", ");
filter->native_string = msStringConcatenate(filter->native_string, layerinfo->user_srid);
}
filter->native_string = msStringConcatenate(filter->native_string, ")");
break;
case MS_TOKEN_BINDING_TIME:
case MS_TOKEN_BINDING_DOUBLE:
case MS_TOKEN_BINDING_INTEGER:
case MS_TOKEN_BINDING_STRING:
if(layerinfo->current_node->next->token == MS_TOKEN_COMPARISON_IRE)
strtmpl = "LOWER(%s)";
else
strtmpl = "%s";
stresc = msMSSQL2008LayerEscapePropertyName(layer, layerinfo->current_node->tokenval.bindval.item);
snippet = (char *) msSmallMalloc(strlen(strtmpl) + strlen(stresc));
sprintf(snippet, strtmpl, stresc);
filter->native_string = msStringConcatenate(filter->native_string, snippet);
msFree(snippet);
msFree(stresc);
break;
case MS_TOKEN_BINDING_SHAPE:
filter->native_string = msStringConcatenate(filter->native_string, layerinfo->geom_column);
break;
case MS_TOKEN_BINDING_MAP_CELLSIZE:
strtmpl = "%lf";
snippet = (char *) msSmallMalloc(strlen(strtmpl) + 16);
sprintf(snippet, strtmpl, layer->map->cellsize);
filter->native_string = msStringConcatenate(filter->native_string, snippet);
msFree(snippet);
break;
/* comparisons */
case MS_TOKEN_COMPARISON_IN:
filter->native_string = msStringConcatenate(filter->native_string, " IN ");
break;
case MS_TOKEN_COMPARISON_RE:
case MS_TOKEN_COMPARISON_IRE:
case MS_TOKEN_COMPARISON_LIKE: {
/* process regexp */
size_t i = 0, j = 0;
char c;
char c_next;
int bCaseInsensitive = (layerinfo->current_node->token == MS_TOKEN_COMPARISON_IRE);
int nEscapeLen = 0;
if (bCaseInsensitive)
filter->native_string = msStringConcatenate(filter->native_string, " LIKE LOWER(");
else
filter->native_string = msStringConcatenate(filter->native_string, " LIKE ");
layerinfo->current_node = layerinfo->current_node->next;
if (layerinfo->current_node->token != MS_TOKEN_LITERAL_STRING) return 0;
strtmpl = msStrdup(layerinfo->current_node->tokenval.strval);
if (strtmpl[0] == '/') {
stresc = strtmpl + 1;
strtmpl[strlen(strtmpl) - 1] = '\0';
}
else if (strtmpl[0] == '^')
stresc = strtmpl + 1;
else
stresc = strtmpl;
while (*stresc) {
c = stresc[i];
if (c == '%' || c == '_' || c == '[' || c == ']' || c == '^') {
nEscapeLen++;
}
stresc++;
}
snippet = (char *)msSmallMalloc(strlen(strtmpl) + nEscapeLen + 3);
snippet[j++] = '\'';
while (i < strlen(strtmpl)) {
c = strtmpl[i];
c_next = strtmpl[i+1];
if (i == 0 && c == '^') {
i++;
continue;
}
if( c == '$' && c_next == 0 && strtmpl[0] == '^' )
break;
if (c == '\\') {
i++;
c = c_next;
}
if (c == '%' || c == '_' || c == '[' || c == ']' || c == '^') {
snippet[j++] = '\\';
}
if (c == '.' && c_next == '*') {
i++;
c = '%';
}
else if (c == '.')
c = '_';
snippet[j++] = c;
i++;
}
snippet[j++] = '\'';
snippet[j] = '\0';
filter->native_string = msStringConcatenate(filter->native_string, snippet);
msFree(strtmpl);
msFree(snippet);
if (bCaseInsensitive)
filter->native_string = msStringConcatenate(filter->native_string, ")");
if (nEscapeLen > 0)
filter->native_string = msStringConcatenate(filter->native_string, " ESCAPE '\\'");
}
break;
case MS_TOKEN_COMPARISON_EQ:
filter->native_string = msStringConcatenate(filter->native_string, " = ");
break;
case MS_TOKEN_COMPARISON_NE:
filter->native_string = msStringConcatenate(filter->native_string, " != ");
break;
case MS_TOKEN_COMPARISON_GT:
filter->native_string = msStringConcatenate(filter->native_string, " > ");
break;
case MS_TOKEN_COMPARISON_GE:
filter->native_string = msStringConcatenate(filter->native_string, " >= ");
break;
case MS_TOKEN_COMPARISON_LT:
filter->native_string = msStringConcatenate(filter->native_string, " < ");
break;
case MS_TOKEN_COMPARISON_LE:
filter->native_string = msStringConcatenate(filter->native_string, " <= ");
break;
/* logical ops */
case MS_TOKEN_LOGICAL_AND:
filter->native_string = msStringConcatenate(filter->native_string, " AND ");
break;
case MS_TOKEN_LOGICAL_OR:
filter->native_string = msStringConcatenate(filter->native_string, " OR ");
break;
case MS_TOKEN_LOGICAL_NOT:
filter->native_string = msStringConcatenate(filter->native_string, " NOT ");
break;
/* spatial comparison tokens */
case MS_TOKEN_COMPARISON_INTERSECTS:
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (!process_node(layer, filter))
return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
filter->native_string = msStringConcatenate(filter->native_string, ".STIntersects(");
if (!process_node(layer, filter))
return 0;
break;
case MS_TOKEN_COMPARISON_DISJOINT:
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (!process_node(layer, filter))
return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
filter->native_string = msStringConcatenate(filter->native_string, ".STDisjoint(");
if (!process_node(layer, filter))
return 0;
break;
case MS_TOKEN_COMPARISON_TOUCHES:
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (!process_node(layer, filter))
return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
filter->native_string = msStringConcatenate(filter->native_string, ".STTouches(");
if (!process_node(layer, filter))
return 0;
break;
case MS_TOKEN_COMPARISON_OVERLAPS:
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (!process_node(layer, filter))
return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
filter->native_string = msStringConcatenate(filter->native_string, ".STOverlaps(");
if (!process_node(layer, filter))
return 0;
break;
case MS_TOKEN_COMPARISON_CROSSES:
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (!process_node(layer, filter))
return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
filter->native_string = msStringConcatenate(filter->native_string, ".STCrosses(");
if (!process_node(layer, filter))
return 0;
break;
case MS_TOKEN_COMPARISON_WITHIN:
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (!process_node(layer, filter))
return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
filter->native_string = msStringConcatenate(filter->native_string, ".STWithin(");
if (!process_node(layer, filter))
return 0;
break;
case MS_TOKEN_COMPARISON_CONTAINS:
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (!process_node(layer, filter))
return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
filter->native_string = msStringConcatenate(filter->native_string, ".STContains(");
if (!process_node(layer, filter))
return 0;
break;
case MS_TOKEN_COMPARISON_EQUALS:
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (!process_node(layer, filter))
return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
filter->native_string = msStringConcatenate(filter->native_string, ".STEquals(");
if (!process_node(layer, filter))
return 0;
break;
case MS_TOKEN_COMPARISON_BEYOND:
msSetError(MS_MISCERR, "Beyond operator is unsupported.", "msMSSQL2008LayerTranslateFilter()");
return 0;
case MS_TOKEN_COMPARISON_DWITHIN:
msSetError(MS_MISCERR, "DWithin operator is unsupported.", "msMSSQL2008LayerTranslateFilter()");
return 0;
/* spatial functions */
case MS_TOKEN_FUNCTION_AREA:
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (!process_node(layer, filter))
return 0;
filter->native_string = msStringConcatenate(filter->native_string, ".STArea()");
break;
case MS_TOKEN_FUNCTION_BUFFER:
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (!process_node(layer, filter))
return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
filter->native_string = msStringConcatenate(filter->native_string, ".STBuffer(");
if (!process_node(layer, filter))
return 0;
filter->native_string = msStringConcatenate(filter->native_string, ")");
break;
case MS_TOKEN_FUNCTION_DIFFERENCE:
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (!process_node(layer, filter))
return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
if (layerinfo->current_node->next) layerinfo->current_node = layerinfo->current_node->next;
else return 0;
filter->native_string = msStringConcatenate(filter->native_string, ".STDifference(");
if (!process_node(layer, filter))
return 0;
filter->native_string = msStringConcatenate(filter->native_string, ")");
break;
case MS_TOKEN_FUNCTION_FROMTEXT:
if (strcasecmp(layerinfo->geom_column_type, "geography") == 0)
filter->native_string = msStringConcatenate(filter->native_string, "geography::STGeomFromText");
else
filter->native_string = msStringConcatenate(filter->native_string, "geometry::STGeomFromText");
break;
case MS_TOKEN_FUNCTION_LENGTH:
filter->native_string = msStringConcatenate(filter->native_string, "len");
break;
case MS_TOKEN_FUNCTION_ROUND:
filter->native_string = msStringConcatenate(filter->native_string, "round");
break;
case MS_TOKEN_FUNCTION_TOSTRING:
break;
case MS_TOKEN_FUNCTION_COMMIFY:
break;
case MS_TOKEN_FUNCTION_SIMPLIFY:
filter->native_string = msStringConcatenate(filter->native_string, ".Reduce");
break;
case MS_TOKEN_FUNCTION_SIMPLIFYPT:
break;
case MS_TOKEN_FUNCTION_GENERALIZE:
filter->native_string = msStringConcatenate(filter->native_string, ".Reduce");
break;
default:
msSetError(MS_MISCERR, "Translation to native SQL failed.","msMSSQL2008LayerTranslateFilter()");
if (layer->debug) {
msDebug("Token not caught, exiting: Token is %i\n", layerinfo->current_node->token);
}
return 0;
}
return 1;
}
/* Translate filter expression to native msssql filter */
int msMSSQL2008LayerTranslateFilter(layerObj *layer, expressionObj *filter, char *filteritem)
{
char *snippet = NULL;
char *strtmpl = NULL;
char *stresc = NULL;
msMSSQL2008LayerInfo *layerinfo = (msMSSQL2008LayerInfo *) layer->layerinfo;
if(!filter->string) return MS_SUCCESS;
msFree(filter->native_string);
filter->native_string = NULL;
if(filter->type == MS_STRING && filter->string && filteritem) { /* item/value pair */
stresc = msMSSQL2008LayerEscapePropertyName(layer, filteritem);
if(filter->flags & MS_EXP_INSENSITIVE) {
filter->native_string = msStringConcatenate(filter->native_string, "upper(");
filter->native_string = msStringConcatenate(filter->native_string, stresc);
filter->native_string = msStringConcatenate(filter->native_string, ") = upper(");
} else {
filter->native_string = msStringConcatenate(filter->native_string, stresc);
filter->native_string = msStringConcatenate(filter->native_string, " = ");
}
msFree(stresc);
strtmpl = "'%s'"; /* don't have a type for the righthand literal so assume it's a string and we quote */
snippet = (char *) msSmallMalloc(strlen(strtmpl) + strlen(filter->string));
sprintf(snippet, strtmpl, filter->string); // TODO: escape filter->string
filter->native_string = msStringConcatenate(filter->native_string, snippet);
free(snippet);
if(filter->flags & MS_EXP_INSENSITIVE)
filter->native_string = msStringConcatenate(filter->native_string, ")");
} else if(filter->type == MS_REGEX && filter->string && filteritem) { /* item/regex pair */
/* NOTE: regex is not supported by MSSQL natively. We should install it in CLR UDF
according to https://msdn.microsoft.com/en-us/magazine/cc163473.aspx*/
filter->native_string = msStringConcatenate(filter->native_string, "dbo.RegexMatch(");
if(filter->flags & MS_EXP_INSENSITIVE) {
filter->native_string = msStringConcatenate(filter->native_string, "'(?i)");
}
filter->native_string = msStrdup(filteritem);
filter->native_string = msStringConcatenate(filter->native_string, ", ");
strtmpl = "'%s'";
snippet = (char *) msSmallMalloc(strlen(strtmpl) + strlen(filter->string));
sprintf(snippet, strtmpl, filter->string); // TODO: escape filter->string
filter->native_string = msStringConcatenate(filter->native_string, snippet);
filter->native_string = msStringConcatenate(filter->native_string, "')");
free(snippet);
} else if(filter->type == MS_EXPRESSION) {
if(layer->debug >= 2)
msDebug("msMSSQL2008LayerTranslateFilter. String: %s.\n", filter->string);
if(!filter->tokens) {
if(layer->debug >= 2)
msDebug("msMSSQL2008LayerTranslateFilter. There are tokens to process... \n");
return MS_SUCCESS;
}
/* start processing nodes */
layerinfo->current_node = filter->tokens;
while (layerinfo->current_node != NULL) {
if (!process_node(layer, filter))
{
msFree(filter->native_string);
filter->native_string = 0;
return MS_FAILURE;
}
if (!layerinfo->current_node)
break;
layerinfo->current_node = layerinfo->current_node->next;
}
}
return MS_SUCCESS;
}
#else
/* prototypes if MSSQL2008 isnt supposed to be compiled */
int msMSSQL2008LayerOpen(layerObj *layer)
{
msSetError(MS_QUERYERR, "msMSSQL2008LayerOpen called but unimplemented! (mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerOpen()");
return MS_FAILURE;
}
int msMSSQL2008LayerIsOpen(layerObj *layer)
{
msSetError(MS_QUERYERR, "msMSSQL2008IsLayerOpen called but unimplemented! (mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerIsOpen()");
return MS_FALSE;
}
void msMSSQL2008LayerFreeItemInfo(layerObj *layer)
{
msSetError(MS_QUERYERR, "msMSSQL2008LayerFreeItemInfo called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerFreeItemInfo()");
}
int msMSSQL2008LayerInitItemInfo(layerObj *layer)
{
msSetError(MS_QUERYERR, "msMSSQL2008LayerInitItemInfo called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerInitItemInfo()");
return MS_FAILURE;
}
int msMSSQL2008LayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
{
msSetError(MS_QUERYERR, "msMSSQL2008LayerWhichShapes called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerWhichShapes()");
return MS_FAILURE;
}
int msMSSQL2008LayerClose(layerObj *layer)
{
msSetError(MS_QUERYERR, "msMSSQL2008LayerClose called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerClose()");
return MS_FAILURE;
}
int msMSSQL2008LayerNextShape(layerObj *layer, shapeObj *shape)
{
msSetError(MS_QUERYERR, "msMSSQL2008LayerNextShape called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerNextShape()");
return MS_FAILURE;
}
int msMSSQL2008LayerGetShape(layerObj *layer, shapeObj *shape, long record)
{
msSetError(MS_QUERYERR, "msMSSQL2008LayerGetShape called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerGetShape()");
return MS_FAILURE;
}
int msMSSQL2008LayerGetShapeCount(layerObj *layer, rectObj rect, projectionObj *rectProjection)
{
msSetError(MS_QUERYERR, "msMSSQL2008LayerGetShapeCount called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerGetShapeCount()");
return MS_FAILURE;
}
int msMSSQL2008LayerGetExtent(layerObj *layer, rectObj *extent)
{
msSetError(MS_QUERYERR, "msMSSQL2008LayerGetExtent called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerGetExtent()");
return MS_FAILURE;
}
int msMSSQL2008LayerGetNumFeatures(layerObj *layer)
{
msSetError(MS_QUERYERR, "msMSSQL2008LayerGetNumFeatures called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerGetNumFeatures()");
return -1;
}
int msMSSQL2008LayerGetShapeRandom(layerObj *layer, shapeObj *shape, long *record)
{
msSetError(MS_QUERYERR, "msMSSQL2008LayerGetShapeRandom called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerGetShapeRandom()");
return MS_FAILURE;
}
int msMSSQL2008LayerGetItems(layerObj *layer)
{
msSetError(MS_QUERYERR, "msMSSQL2008LayerGetItems called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerGetItems()");
return MS_FAILURE;
}
void msMSSQL2008EnablePaging(layerObj *layer, int value)
{
msSetError(MS_QUERYERR, "msMSSQL2008EnablePaging called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008EnablePaging()");
return;
}
int msMSSQL2008GetPaging(layerObj *layer)
{
msSetError(MS_QUERYERR, "msMSSQL2008GetPaging called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008GetPaging()");
return MS_FAILURE;
}
int msMSSQL2008LayerTranslateFilter(layerObj *layer, expressionObj *filter, char *filteritem)
{
msSetError(MS_QUERYERR, "msMSSQL2008LayerTranslateFilter called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerTranslateFilter()");
return MS_FAILURE;
}
char *msMSSQL2008LayerEscapeSQLParam(layerObj *layer, const char *pszString)
{
msSetError(MS_QUERYERR, "msMSSQL2008EscapeSQLParam called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerEscapeSQLParam()");
return NULL;
}
char *msMSSQL2008LayerEscapePropertyName(layerObj *layer, const char *pszString)
{
msSetError(MS_QUERYERR, "msMSSQL2008LayerEscapePropertyName called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerEscapePropertyName()");
return NULL;
}
/* end above's #ifdef USE_MSSQL2008 */
#endif
#ifdef USE_MSSQL2008_PLUGIN
MS_DLL_EXPORT int PluginInitializeVirtualTable(layerVTableObj* vtable, layerObj *layer)
{
assert(layer != NULL);
assert(vtable != NULL);
vtable->LayerEnablePaging = msMSSQL2008EnablePaging;
vtable->LayerGetPaging = msMSSQL2008GetPaging;
vtable->LayerTranslateFilter = msMSSQL2008LayerTranslateFilter;
vtable->LayerEscapeSQLParam = msMSSQL2008LayerEscapeSQLParam;
vtable->LayerEscapePropertyName = msMSSQL2008LayerEscapePropertyName;
vtable->LayerInitItemInfo = msMSSQL2008LayerInitItemInfo;
vtable->LayerFreeItemInfo = msMSSQL2008LayerFreeItemInfo;
vtable->LayerOpen = msMSSQL2008LayerOpen;
vtable->LayerIsOpen = msMSSQL2008LayerIsOpen;
vtable->LayerWhichShapes = msMSSQL2008LayerWhichShapes;
vtable->LayerNextShape = msMSSQL2008LayerNextShape;
vtable->LayerGetShape = msMSSQL2008LayerGetShape;
vtable->LayerGetShapeCount = msMSSQL2008LayerGetShapeCount;
vtable->LayerClose = msMSSQL2008LayerClose;
vtable->LayerGetItems = msMSSQL2008LayerGetItems;
vtable->LayerGetExtent = msMSSQL2008LayerGetExtent;
vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
/* vtable->LayerGetAutoStyle, not supported for this layer */
vtable->LayerCloseConnection = msMSSQL2008LayerClose;
vtable->LayerSetTimeFilter = msLayerMakeBackticsTimeFilter;
/* vtable->LayerCreateItems, use default */
vtable->LayerGetNumFeatures = msMSSQL2008LayerGetNumFeatures;
/* layer->vtable->LayerGetAutoProjection, use defaut*/
return MS_SUCCESS;
}
#endif
int
msMSSQL2008LayerInitializeVirtualTable(layerObj *layer)
{
assert(layer != NULL);
assert(layer->vtable != NULL);
layer->vtable->LayerEnablePaging = msMSSQL2008EnablePaging;
layer->vtable->LayerGetPaging = msMSSQL2008GetPaging;
layer->vtable->LayerTranslateFilter = msMSSQL2008LayerTranslateFilter;
layer->vtable->LayerEscapeSQLParam = msMSSQL2008LayerEscapeSQLParam;
layer->vtable->LayerEscapePropertyName = msMSSQL2008LayerEscapePropertyName;
layer->vtable->LayerInitItemInfo = msMSSQL2008LayerInitItemInfo;
layer->vtable->LayerFreeItemInfo = msMSSQL2008LayerFreeItemInfo;
layer->vtable->LayerOpen = msMSSQL2008LayerOpen;
layer->vtable->LayerIsOpen = msMSSQL2008LayerIsOpen;
layer->vtable->LayerWhichShapes = msMSSQL2008LayerWhichShapes;
layer->vtable->LayerNextShape = msMSSQL2008LayerNextShape;
layer->vtable->LayerGetShape = msMSSQL2008LayerGetShape;
layer->vtable->LayerGetShapeCount = msMSSQL2008LayerGetShapeCount;
layer->vtable->LayerClose = msMSSQL2008LayerClose;
layer->vtable->LayerGetItems = msMSSQL2008LayerGetItems;
layer->vtable->LayerGetExtent = msMSSQL2008LayerGetExtent;
layer->vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
/* layer->vtable->LayerGetAutoStyle, not supported for this layer */
layer->vtable->LayerCloseConnection = msMSSQL2008LayerClose;
layer->vtable->LayerSetTimeFilter = msLayerMakeBackticsTimeFilter;
/* layer->vtable->LayerCreateItems, use default */
layer->vtable->LayerGetNumFeatures = msMSSQL2008LayerGetNumFeatures;
return MS_SUCCESS;
}
| 33.748285 | 287 | 0.63456 | [
"geometry",
"object",
"shape"
] |
6cba6b446fad160745ea7b6fda64e0e6d60f521c | 13,950 | h | C | libpfkfb/Btree.h | flipk/pfkutils | d8f6c22720b6fcc44a882927c745a822282d1f69 | [
"Unlicense"
] | 4 | 2015-06-12T05:08:56.000Z | 2017-11-13T11:34:27.000Z | libpfkfb/Btree.h | flipk/pfkutils | d8f6c22720b6fcc44a882927c745a822282d1f69 | [
"Unlicense"
] | null | null | null | libpfkfb/Btree.h | flipk/pfkutils | d8f6c22720b6fcc44a882927c745a822282d1f69 | [
"Unlicense"
] | 1 | 2021-10-20T02:04:53.000Z | 2021-10-20T02:04:53.000Z | /* -*- Mode:c++; eval:(c-set-style "BSD"); c-basic-offset:4; indent-tabs-mode:nil; tab-width:8 -*- */
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org>
*/
/** \file Btree.h
* \brief definition of Btree access methods.
*/
#ifndef __BTREE_H__
#define __BTREE_H__
#include "FileBlock_iface.h"
#include "bst.h"
class BtreeInternal;
/** helper class for Btree::printinfo. the user should populate
* one of these before calling Btree::printinfo to help it decide
* how to format the data.
*/
class BtreeIterator {
public:
BtreeIterator(void) { wantPrinting = false; }
virtual ~BtreeIterator(void) { /* placeholder */ }
virtual bool handle_item( uint8_t * keydata, uint32_t keylen,
FB_AUID_T data_fbn ) = 0;
virtual void print( const char * format, ... )
__attribute__ ((format( printf, 2, 3 ))) = 0;
bool wantPrinting; // derived constructor should populate this
};
/** The interface to a Btree file with FileBlockInterface backend.
* The constructor is not public, because the user should not construct
* these with 'new'. Instead the user should call Btree::open method,
* which is static. This will create a BtreeInternal object and downcast
* it to the Btree object and return it. This is to enforce compliance to
* a simple interface and to minimize the impact on the user's name space.
*/
class Btree {
protected:
FileBlockInterface * fbi; /**< this is how Btree accesses the file. */
/** user not allowed to create Btrees; call Btree::open instead. */
Btree( void ) { }
/** internal implementation of file opener; used by
* openFile and createFile.
* \param filename the full path to the filename to open.
* \param max_bytes the number of bytes to allocate for the cache.
* \param create indicate whether you are trying to create the file
* or open an existing file.
* \param mode the file mode, see open(2); ignored if create==false.
* \param order if creating the file, this is the btree order of the
* new file. ignored if create==false.
* \return a pointer to a new Btree object that can be used to access
* the file, or NULL if the file could not be created or opened. */
static Btree * _openFile( const char * filename, int max_bytes,
bool create, int mode, int order );
public:
/** check the file for the required signatures and then
* return a new Btree object. If the file does not contain the required
* signatures, the file cannot be opened, and this function returns NULL.
* \param fbi the FileBlockInterface used to access the file; this will
* be stored inside the Btree object.
* \return a Btree object if the open was successfull, or NULL if not. */
static Btree * open( FileBlockInterface * fbi );
/** take a file without a Btree in it, and add the required signatures.
* after this, the Btree::open method will be able to open the file.
* \param fbi the FileBlockInterface to access the file.
* \param order the desired order of the btree; must be odd, greator
* than 1, and less than BtreeInternal::MAX_ORDER.
* \return true if the init was successful, false if error. */
static bool init_file( FileBlockInterface * fbi, int order );
/** open an existing btree file. this function will open a file
* descriptor, create a PageIO, create a BlockCache, create a
* FileBlockInterface, and then create the Btree.
* \param filename the existing file to open.
* \param max_bytes the size of cache to allocate.
* \return a pointer to a Btree object or NULL if the file could not
* be found. */
static Btree * openFile( const char * filename, int max_bytes ) {
return _openFile(filename,max_bytes,false,0,0);
}
/** create a new btree file. this function will open a file
* descriptor, create a PageIO, create a BlockCache, create a
* FileBlockInterface, and then create the Btree.
* \param filename the existing file to open.
* \param max_bytes the size of cache to allocate.
* \param mode the file mode during create, see open(2).
* \param order the order of the Btree to create.
* \return a pointer to a Btree object or NULL if the file could not
* be created. */
static Btree * createFile( const char * filename, int max_bytes,
int mode, int order ) {
return _openFile(filename,max_bytes,true,mode,order);
}
/** check if a file is a valid btree file.
* \param fbi the FileBlockInterface to access the file.
* \return true if the file appears to be a valid btree file,
* false if not. */
static bool valid_file( FileBlockInterface * fbi );
/** Return a pointer to the FileBlockInterface backend. This allows the
* user of Btree to store their own data directly in the file without
* going only through the Btree API.
* \see BtreeInternal::valid_file
* \return a pointer to the FileBlockInterface object. */
FileBlockInterface * get_fbi(void) { return fbi; }
/** the destructor closes the Btree portion of the file.
* \note This destructor ALSO deletes the FileBlockInterface! */
virtual ~Btree( void ) { }
/** search the Btree looking for the key. if found, return the data field
* associated with this key.
* \param key pointer to key data.
* \param keylen length of the key data.
* \param data_id pointer to the user's variable that will be populated
* with the data corresponding to the key. this data will
* exactly match the data specified to the put method when
* this key was put in the database. it can be an FBN id,
* but the Btree API makes no assumptions about it.
* \return true if the data was found (and the 'data_id' parameter will be
* populated with the relevant data), or false if the data was
* not found (key not present).*/
virtual bool get( uint8_t * key, int keylen, FB_AUID_T * data_id ) = 0;
/** a version of the get method which understands BST data structures.
* this method will encode the BST bytestream and then call the
* pointer/length version of the get method.
* \param key the key data, in BST form.
* \param data_id a pointer to the data that will be returned
* if the search was successful.
* \return true if the key was found or false if it was not found.
*/
bool get( BST * key, FB_AUID_T * data_id ) {
int keylen = 0;
uint8_t * keybuf = key->bst_encode( &keylen );
bool retval = false;
if (keybuf)
{
retval = get( keybuf, keylen, data_id );
delete[] keybuf;
}
return retval;
}
/** store the key and data into the file. If the given key already exists
* in the file, the behavior depends on the replace argument. If replace
* is false, this function will return false. If replace is true, the
* old data will be put into *old_data_id, and *replaced will be set
* to true. this API does not make any assumptions about the meaning
* of the data_id or old_data_id-- the user may specify any 32 bit data
* which is meaningful to the application. the assumption is that the
* most common usage is to place FileBlockInterface FBN numbers in this
* field. in this case, when a data is replaced, the disposition of the
* old FBN is left to the user, for example to call
* get_fbi()->free(old_data_id) or place the old_data_id in some other
* data structure if the data is still relevant.
* \param key pointer to the key data.
* \param keylen length of the key data.
* \param data_id user data to associate with the key.
* \param replace indicate whether to replace (overwrite) or fail.
* \param replaced a pointer to a user's bool; if a matching key was
* found in the btree, the corresponding data will be returned, the
* new data_id will replace it, and *replaced will be set to true.
* if the key was new in the database, *replaced will be set to false.
* \param old_data_id a pointer to a user's variable. if *replaced is
* set to true (see the replaced param above) then *old_data_id will
* contain the old data associated with the key prior to replacement.
* \return true if the item was put in the database; false if the key
* already exists and replace argument is false. */
virtual bool put( uint8_t * key, int keylen, FB_AUID_T data_id,
bool replace=false, bool *replaced=NULL,
FB_AUID_T *old_data_id=NULL ) = 0;
/** a version of the put method which supports key in BST form.
* \param key the key data in BST form. this key will be encoded into
* a temporary buffer before calling the pointer/length form of put.
* \param data_id the data the user wishes to associate with the key.
* \param replace if a matching key is found, this argument indicates
* whether it will replace the old data_id, or just fail.
* \param replaced a pointer to a user's bool; if a matching key was
* found in the btree, the corresponding data will be returned, the
* new data_id will replace it, and *replaced will be set to true.
* if the key was new in the database, *replaced will be set to false.
* \param old_data_id a pointer to a user's variable. if *replaced is
* set to true (see the replaced param above) then *old_data_id will
* contain the old data associated with the key prior to replacement.
* \return true if put was successful, or false if an error or if the
* key already exists and replace==false. */
bool put( BST * key, FB_AUID_T data_id, bool replace=false,
bool *replaced=NULL, FB_AUID_T *old_data_id=NULL ) {
int keylen = 0;
uint8_t * keybuf = key->bst_encode( &keylen );
bool retval = false;
if (keybuf)
{
retval = put( keybuf, keylen, data_id, replace,
replaced, old_data_id );
delete[] keybuf;
}
return retval;
}
/** delete an item from the database given only the key.
* this function will search for the key/data pair using the key,
* and then free all disk space associated with the key. if the data
* is a FB_AUID_T, this API does not know or assume that, and does NOT
* free the associated data block.
* \param key pointer to the key data.
* \param keylen length of the key data.
* \param old_data_id if the matching key was found, and the record
* is deleted, *old_data_id will be populated with the data value
* that was present in the btree. the disposition of this data is
* left to the user, i.e. if it was being used to store FBN numbers,
* presumably the user will wish to free the associated file block.
* \return true if the item was deleted, false if not found or error. */
virtual bool del ( uint8_t * key, int keylen, FB_AUID_T *old_data_id ) = 0;
/** a BST version of del.
* \param key the key data to delete.
* \param old_data_id if the matching key was found, and the record
* is deleted, *old_data_id will be populated with the data value
* that was present in the btree. the disposition of this data is
* left to the user, i.e. if it was being used to store FBN numbers,
* presumably the user will wish to free the associated file block.
* \return true if the key/data was deleted or false if not. */
bool del( BST * key, FB_AUID_T *old_data_id ) {
int keylen = 0;
uint8_t * keybuf = key->bst_encode( &keylen );
bool retval = false;
if (keybuf)
{
retval = del( keybuf, keylen, old_data_id );
delete[] keybuf;
}
return retval;
}
/** iterate over an entire btree, producing debug data and then
* calling a user supplied function once for each item in the tree.
* the tree is walked in key-order. the user-supplied function must
* return 'true' if the walk is to continue; if it ever returns 'false',
* the walk is terminated at its current point.
* \param bti the user's BtreeIterator object
* \return true if the entire btree was walked, or false if it was aborted
* due to BtreeIterator::handle_item returning false.
*/
virtual bool iterate( BtreeIterator * bti ) = 0;
};
#endif /* __BTREE_H__ */
| 52.052239 | 101 | 0.668602 | [
"object"
] |
6cbb5de057feb8851d830c945212e09339adef77 | 227,002 | c | C | westeros-sink/v4l2/westeros-sink-soc.c | johnrobinsn/westeros-1 | 7f130816b434261fe1cafd771eb6bf3551f7983a | [
"Apache-2.0"
] | null | null | null | westeros-sink/v4l2/westeros-sink-soc.c | johnrobinsn/westeros-1 | 7f130816b434261fe1cafd771eb6bf3551f7983a | [
"Apache-2.0"
] | null | null | null | westeros-sink/v4l2/westeros-sink-soc.c | johnrobinsn/westeros-1 | 7f130816b434261fe1cafd771eb6bf3551f7983a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2016 RDK Management
*
* 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;
* version 2.1 of the License.
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include <stdio.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include <poll.h>
#ifdef USE_GST_VIDEO
#include <gst/video/video-color.h>
#endif
#ifdef USE_GST_AFD
#include "gst/video/video-anc.h"
#ifndef gst_buffer_get_video_afd_meta
#undef USE_GST_AFD
#endif
#endif
#ifdef USE_GST_ALLOCATORS
#include <gst/allocators/gstdmabuf.h>
#endif
#include "westeros-sink.h"
#define DEFAULT_DEVICE_NAME "/dev/video10"
#define DEFAULT_VIDEO_SERVER "video"
#define DEFAULT_FRAME_WIDTH (640)
#define DEFAULT_FRAME_HEIGHT (360)
#define NUM_INPUT_BUFFERS (2)
#define MIN_INPUT_BUFFERS (1)
#define NUM_OUTPUT_BUFFERS (6)
#define MIN_OUTPUT_BUFFERS (3)
#define QOS_INTERVAL (120)
#define DEFAULT_OVERSCAN (0)
#define IOCTL ioctl_wrapper
#ifdef GLIB_VERSION_2_32
#define LOCK_SOC( sink ) g_mutex_lock( &((sink)->soc.mutex) );
#define UNLOCK_SOC( sink ) g_mutex_unlock( &((sink)->soc.mutex) );
#else
#define LOCK_SOC( sink ) g_mutex_lock( (sink)->soc.mutex );
#define UNLOCK_SOC( sink ) g_mutex_unlock( (sink)->soc.mutex );
#endif
GST_DEBUG_CATEGORY_EXTERN (gst_westeros_sink_debug);
#define GST_CAT_DEFAULT gst_westeros_sink_debug
#define INT_FRAME(FORMAT, ...) frameLog( "FRAME: " FORMAT "\n", __VA_ARGS__)
#define FRAME(...) INT_FRAME(__VA_ARGS__, "")
#define postDecodeError( sink, description ) \
{ \
GThread *temp= sink->soc.videoOutputThread; \
postErrorMessage( (sink), GST_STREAM_ERROR_DECODE, "video decode error", description); \
sink->soc.videoOutputThread= 0; \
wstSinkSocStopVideo( sink ); \
sink->soc.videoOutputThread= temp; \
}
enum
{
PROP_DEVICE= PROP_SOC_BASE,
PROP_FRAME_STEP_ON_PREROLL,
#ifdef USE_AMLOGIC_MESON_MSYNC
PROP_AVSYNC_SESSION,
PROP_AVSYNC_MODE,
#endif
PROP_LOW_MEMORY_MODE,
PROP_FORCE_ASPECT_RATIO,
PROP_WINDOW_SHOW,
PROP_ZOOM_MODE,
PROP_OVERSCAN_SIZE,
PROP_ENABLE_TEXTURE,
PROP_REPORT_DECODE_ERRORS,
PROP_QUEUED_FRAMES
};
enum
{
SIGNAL_FIRSTFRAME,
SIGNAL_UNDERFLOW,
SIGNAL_NEWTEXTURE,
SIGNAL_DECODEERROR,
SIGNAL_TIMECODE,
MAX_SIGNAL
};
enum
{
ZOOM_NONE,
ZOOM_DIRECT,
ZOOM_NORMAL,
ZOOM_16_9_STRETCH,
ZOOM_4_3_PILLARBOX,
ZOOM_ZOOM
};
#define needBounds(sink) ( sink->soc.forceAspectRatio || (sink->soc.zoomMode != ZOOM_NONE) )
static bool g_frameDebug= false;
static const char *gDeviceName= DEFAULT_DEVICE_NAME;
static guint g_signals[MAX_SIGNAL]= {0};
static gboolean (*queryOrg)(GstElement *element, GstQuery *query)= 0;
static void wstSinkSocStopVideo( GstWesterosSink *sink );
static void wstBuildSinkCaps( GstWesterosSinkClass *klass, GstWesterosSink *dummySink );
static void wstDiscoverVideoDecoder( GstWesterosSinkClass *klass );
static void wstStartEvents( GstWesterosSink *sink );
static void wstStopEvents( GstWesterosSink *sink );
static void wstProcessEvents( GstWesterosSink *sink );
static void wstGetMaxFrameSize( GstWesterosSink *sink );
static bool wstGetInputFormats( GstWesterosSink *sink );
static bool wstGetOutputFormats( GstWesterosSink *sink );
static bool wstSetInputFormat( GstWesterosSink *sink );
static bool wstSetOutputFormat( GstWesterosSink *sink );
static bool wstSetupInputBuffers( GstWesterosSink *sink );
static void wstTearDownInputBuffers( GstWesterosSink *sink );
static bool wstSetupOutputBuffers( GstWesterosSink *sink );
static bool wstSetupOutputBuffersMMap( GstWesterosSink *sink );
static bool wstSetupOutputBuffersDmabuf( GstWesterosSink *sink );
static void wstTearDownOutputBuffers( GstWesterosSink *sink );
static void wstTearDownOutputBuffersDmabuf( GstWesterosSink *sink );
static void wstTearDownOutputBuffersMMap( GstWesterosSink *sink );
static void wstSetInputMemMode( GstWesterosSink *sink, int mode );
static void wstSetupInput( GstWesterosSink *sink );
static int wstGetInputBuffer( GstWesterosSink *sink );
static void wstSetOutputMemMode( GstWesterosSink *sink, int mode );
static void wstSetupOutput( GstWesterosSink *sink );
static int wstGetOutputBuffer( GstWesterosSink *sink );
static int wstFindOutputBuffer( GstWesterosSink *sink, int fd );
static void wstLockOutputBuffer( GstWesterosSink *sink, int buffIndex );
static bool wstUnlockOutputBuffer( GstWesterosSink *sink, int buffIndex );
static void wstRequeueOutputBuffer( GstWesterosSink *sink, int buffIndex );
static WstVideoClientConnection *wstCreateVideoClientConnection( GstWesterosSink *sink, const char *name );
static void wstDestroyVideoClientConnection( WstVideoClientConnection *conn );
static void wstSendFlushVideoClientConnection( WstVideoClientConnection *conn );
static bool wstSendFrameVideoClientConnection( WstVideoClientConnection *conn, int buffIndex );
static void wstSendFrameAdvanceVideoClientConnection( WstVideoClientConnection *conn );
static void wstSendRectVideoClientConnection( WstVideoClientConnection *conn );
static void wstDecoderReset( GstWesterosSink *sink, bool hard );
static void wstGetVideoBounds( GstWesterosSink *sink, int *x, int *y, int *w, int *h );
static void wstSetTextureCrop( GstWesterosSink *sink, int vx, int vy, int vw, int vh );
static void wstProcessTextureSignal( GstWesterosSink *sink, int buffIndex );
static bool wstProcessTextureWayland( GstWesterosSink *sink, int buffIndex );
static int wstFindVideoBuffer( GstWesterosSink *sink, int frameNumber );
static int wstFindCurrentVideoBuffer( GstWesterosSink *sink );
static gpointer wstVideoOutputThread(gpointer data);
static gpointer wstEOSDetectionThread(gpointer data);
static gpointer wstDispatchThread(gpointer data);
static void postErrorMessage( GstWesterosSink *sink, int errorCode, const char *errorText, const char *description );
static GstFlowReturn prerollSinkSoc(GstBaseSink *base_sink, GstBuffer *buffer);
static int ioctl_wrapper( int fd, int request, void* arg );
static bool swIsSWDecode( GstWesterosSink *sink );
#ifdef ENABLE_SW_DECODE
static bool swInit( GstWesterosSink *sink );
static void swTerm( GstWesterosSink *sink );
static void swLink( GstWesterosSink *sink );
static void swUnLink( GstWesterosSink *sink );
static void swEvent( GstWesterosSink *sink, int id, int p1, void *p2 );
static void swDisplay( GstWesterosSink *sink, SWFrame *frame );
#endif
static int sinkAcquireResources( GstWesterosSink *sink );
static void sinkReleaseResources( GstWesterosSink *sink );
static int sinkAcquireVideo( GstWesterosSink *sink );
static void sinkReleaseVideo( GstWesterosSink *sink );
#ifdef USE_AMLOGIC_MESON
#include "meson_drm.h"
#include <xf86drm.h>
#ifdef USE_AMLOGIC_MESON_MSYNC
#define INVALID_SESSION_ID (16)
#include "gstamlclock.h"
#include "gstamlhalasink_new.h"
#endif
#include "svp/aml-meson/svp-util.c"
#endif
static long long getCurrentTimeMillis(void)
{
struct timeval tv;
long long utcCurrentTimeMillis;
gettimeofday(&tv,0);
utcCurrentTimeMillis= tv.tv_sec*1000LL+(tv.tv_usec/1000LL);
return utcCurrentTimeMillis;
}
static gint64 getGstClockTime( GstWesterosSink *sink )
{
gint64 time= 0;
GstElement *element= GST_ELEMENT(sink);
GstClock *clock= GST_ELEMENT_CLOCK(element);
if ( clock )
{
time= gst_clock_get_time(clock);
}
return time;
}
static void frameLog( const char *fmt, ... )
{
if ( g_frameDebug )
{
va_list argptr;
fprintf( stderr, "%lld: ", getCurrentTimeMillis());
va_start( argptr, fmt );
vfprintf( stderr, fmt, argptr );
va_end( argptr );
}
}
static FILE *gAvProgOut= 0;
static void avProgInit()
{
const char *env= getenv("AV_PROGRESSION");
if ( env )
{
int len= strlen(env);
if ( (len == 1) && !strncmp( "1", env, len) )
{
gAvProgOut= stderr;
}
else
{
gAvProgOut= fopen( env, "at" );
}
}
}
static void avProgLog( long long nanoTime, int syncGroup, const char *edge, const char *desc )
{
if ( gAvProgOut )
{
struct timespec tp;
long long pts= -1LL;
if ( GST_CLOCK_TIME_IS_VALID(nanoTime) )
{
pts= ((nanoTime / GST_SECOND) * 90000)+(((nanoTime % GST_SECOND) * 90000) / GST_SECOND);
}
clock_gettime(CLOCK_MONOTONIC, &tp);
fprintf(gAvProgOut, "AVPROG: [%6u.%06u] %lld %d %c %s %s\n", tp.tv_sec, tp.tv_nsec/1000, pts, syncGroup, 'V', edge, desc);
}
}
static void avProgTerm()
{
if ( gAvProgOut )
{
if ( gAvProgOut != stderr )
{
fclose( gAvProgOut );
}
gAvProgOut= 0;
}
}
static char *wstInFullness( GstWesterosSink *sink )
{
static char desc[64];
if ( gAvProgOut )
{
sprintf(desc,"(%d of %d)", sink->soc.inQueuedCount, sink->soc.numBuffersIn );
return desc;
}
return NULL;
}
static char *wstOutFullness( GstWesterosSink *sink )
{
static char desc[64];
if ( gAvProgOut )
{
sprintf(desc,"(%d of %d)", sink->soc.outQueuedCount, sink->soc.numBuffersOut );
return desc;
}
return NULL;
}
static bool wstApproxEqual( double v1, double v2 )
{
bool result= false;
if ( v1 >= v2 )
{
if ( (v1-v2) < 0.001 )
{
result= true;
}
}
else
{
if ( (v2-v1) < 0.001 )
{
result= true;
}
}
return result;
}
static void sbFormat(void *data, struct wl_sb *wl_sb, uint32_t format)
{
WESTEROS_UNUSED(wl_sb);
GstWesterosSink *sink= (GstWesterosSink*)data;
WESTEROS_UNUSED(sink);
printf("westeros-sink-soc: registry: sbFormat: %X\n", format);
}
static const struct wl_sb_listener sbListener = {
sbFormat
};
static void wstPushPixelAspectRatio( GstWesterosSink *sink, double pixelAspectRatio, int frameWidth, int frameHeight )
{
if ( sink->soc.parNextCount >= sink->soc.parNextCapacity )
{
int newCapacity= sink->soc.parNextCapacity*2+3;
WstPARInfo *newParNext= (WstPARInfo*)calloc( newCapacity, sizeof(WstPARInfo) );
if ( newParNext )
{
if ( sink->soc.parNext && sink->soc.parNextCount )
{
memcpy( newParNext, sink->soc.parNext, sink->soc.parNextCount*sizeof(WstPARInfo) );
free( sink->soc.parNext );
sink->soc.parNext= 0;
}
sink->soc.parNext= newParNext;
sink->soc.parNextCapacity= newCapacity;
}
else
{
GST_ERROR("Failed to expand pixel-aspect-ratio stack from size %d to %d", sink->soc.parNextCapacity, newCapacity );
}
}
if ( sink->soc.parNext && (sink->soc.parNextCount < sink->soc.parNextCapacity) )
{
double parPrev;
int widthPrev, heightPrev;
if ( sink->soc.parNextCount == 0 )
{
parPrev= sink->soc.pixelAspectRatio;
widthPrev= sink->soc.frameWidth;
heightPrev= sink->soc.frameHeight;
}
else
{
parPrev= sink->soc.parNext[sink->soc.parNextCount-1].par;
widthPrev= sink->soc.parNext[sink->soc.parNextCount-1].frameWidth;
heightPrev= sink->soc.parNext[sink->soc.parNextCount-1].frameHeight;
}
if ( (parPrev != pixelAspectRatio) ||
(widthPrev != frameWidth) ||
(heightPrev != frameHeight) )
{
sink->soc.parNext[sink->soc.parNextCount].frameNumber= sink->soc.frameInCount;
sink->soc.parNext[sink->soc.parNextCount].par= pixelAspectRatio;
sink->soc.parNext[sink->soc.parNextCount].frameWidth= frameWidth;
sink->soc.parNext[sink->soc.parNextCount].frameHeight= frameHeight;
++sink->soc.parNextCount;
GST_DEBUG("push pixelAspectRatio %f (%dx%d) count %d capactiy %d",
pixelAspectRatio, frameWidth, frameHeight, sink->soc.parNextCount, sink->soc.parNextCapacity);
}
}
}
static double wstPopPixelAspectRatio( GstWesterosSink *sink )
{
double pixelAspectRatio;
pixelAspectRatio= sink->soc.pixelAspectRatio;
if ( sink->soc.parNextCount > 0 )
{
pixelAspectRatio= sink->soc.parNext[0].par;
GST_DEBUG("pop pixelAspectRatio %f",
pixelAspectRatio, sink->soc.parNext[0].frameWidth, sink->soc.parNext[0].frameHeight);
if ( --sink->soc.parNextCount > 0 )
{
memmove( &sink->soc.parNext[0], &sink->soc.parNext[1], sink->soc.parNextCount*sizeof(WstPARInfo) );
}
}
return pixelAspectRatio;
}
static void wstUpdatePixelAspectRatio( GstWesterosSink *sink )
{
switch( sink->soc.inputFormat )
{
case V4L2_PIX_FMT_MPEG:
case V4L2_PIX_FMT_MPEG1:
case V4L2_PIX_FMT_MPEG2:
case V4L2_PIX_FMT_MPEG4:
break;
default:
return;
}
if ( sink->soc.parNextCount > 0 )
{
WstPARInfo *check= &sink->soc.parNext[0];
if ( sink->soc.frameDecodeCount >= check->frameNumber )
{
sink->soc.pixelAspectRatioChanged= TRUE;
sink->soc.pixelAspectRatio= wstPopPixelAspectRatio( sink );
}
}
}
static void wstFlushPixelAspectRatio( GstWesterosSink *sink, bool full )
{
sink->soc.parNextCount= 0;
GST_DEBUG("flush pixelAspectRatio");
if ( full && sink->soc.parNext )
{
free( sink->soc.parNext );
sink->soc.parNext= 0;
sink->soc.parNextCapacity= 0;
}
}
#ifdef USE_GST_AFD
static void wstAddAFDInfo( GstWesterosSink *sink, GstBuffer *buffer )
{
GstVideoAFDMeta* afd;
GstVideoBarMeta* bar;
afd= gst_buffer_get_video_afd_meta(buffer);
bar= gst_buffer_get_video_bar_meta(buffer);
if ( afd || bar )
{
WstAFDInfo *afdCurr= &sink->soc.afdActive;
bool needNew= false;
if ( sink->soc.afdInfoCount > 0 )
{
afdCurr= &sink->soc.afdInfo[sink->soc.afdInfoCount-1];
}
if ( afd )
{
if ( afd->afd != afdCurr->afd )
{
needNew= true;
}
}
if ( bar )
{
if ( !afdCurr->haveBar )
{
needNew= true;
}
else if ( (afdCurr->isLetterbox != bar->is_letterbox) ||
(afdCurr->d1 != bar->bar_data1) ||
(afdCurr->d2 != bar->bar_data2) )
{
needNew= true;
}
}
if ( needNew )
{
WstAFDInfo *afdAdd= 0;
if ( sink->soc.afdInfoCount >= sink->soc.afdInfoCapacity )
{
int newCapacity= sink->soc.afdInfoCapacity*2+3;
WstAFDInfo *afdInfoNew= (WstAFDInfo*)calloc( newCapacity, sizeof(WstAFDInfo) );
if ( afdInfoNew )
{
if ( sink->soc.afdInfo && sink->soc.afdInfoCount )
{
memcpy( afdInfoNew, sink->soc.afdInfo, sink->soc.afdInfoCount*sizeof(WstAFDInfo) );
free( sink->soc.afdInfo );
sink->soc.afdInfo= 0;
}
sink->soc.afdInfo= afdInfoNew;
sink->soc.afdInfoCapacity= newCapacity;
}
else
{
GST_ERROR("Failed to expand AFD info queue from size %d to %d", sink->soc.afdInfoCapacity, newCapacity );
}
}
if ( sink->soc.afdInfo && (sink->soc.afdInfoCount < sink->soc.afdInfoCapacity) )
{
gint64 pts= -1;
if ( GST_BUFFER_PTS_IS_VALID(buffer) )
{
pts= GST_BUFFER_PTS(buffer);
}
afdAdd= &sink->soc.afdInfo[sink->soc.afdInfoCount];
++sink->soc.afdInfoCount;
memset( afdAdd, 0, sizeof(WstAFDInfo));
afdAdd->pts= pts;
afdAdd->frameNumber= sink->soc.frameInCount;
if ( afd )
{
afdAdd->spec= afd->spec;
afdAdd->afd= afd->afd;
afdAdd->field= afd->field;
}
if ( bar )
{
afdAdd->haveBar= true;
afdAdd->isLetterbox= bar->is_letterbox;
afdAdd->d1= bar->bar_data1;
afdAdd->d2= bar->bar_data2;
afdAdd->f= bar->field;
}
GST_DEBUG("add AFD pts %lld frame %d afd %d field %d/%d", afdAdd->pts, afdAdd->frameNumber, afdAdd->afd, afdAdd->field, afdAdd->f);
}
}
}
}
static void wstUpdateAFDInfo( GstWesterosSink *sink )
{
if ( sink->soc.afdInfoCount > 0 )
{
bool needUpdate= false;
WstAFDInfo *check= &sink->soc.afdInfo[0];
if ( check->pts != -1LL )
{
if ( sink->soc.prevDecodedTimestamp >= GST_TIME_AS_USECONDS(check->pts) )
{
needUpdate= true;
}
}
else if ( sink->soc.frameDecodeCount >= check->frameNumber )
{
needUpdate= true;
}
if ( needUpdate )
{
sink->soc.afdActive= *check;
GST_DEBUG("active AFD afd %d haveBar %d isLetterbox %d d1 %d d2 %d",
check->afd, check->haveBar, check->isLetterbox, check->d1, check->d2 );
if ( --sink->soc.afdInfoCount > 0 )
{
memmove( &sink->soc.afdInfo[0], &sink->soc.afdInfo[1], sink->soc.afdInfoCount*sizeof(WstAFDInfo) );
}
sink->soc.pixelAspectRatioChanged= TRUE;
}
}
}
static void wstFlushAFDInfo( GstWesterosSink *sink, bool full )
{
sink->soc.afdInfoCount= 0;
GST_DEBUG("flush AFD info");
if ( full && sink->soc.afdInfo )
{
free( sink->soc.afdInfo );
sink->soc.afdInfo= 0;
sink->soc.afdInfoCapacity= 0;
}
memset( &sink->soc.afdActive, 0, sizeof(WstAFDInfo));
}
#endif
#ifdef USE_GST1
static GstFlowReturn wstChain(GstPad *pad, GstObject *parent, GstBuffer *buf)
{
GstWesterosSink *sink= GST_WESTEROS_SINK(parent);
long long pts, duration;
if ( buf )
{
pts= GST_BUFFER_PTS(buf);
duration= GST_BUFFER_DURATION(buf);
if ( !GST_CLOCK_TIME_IS_VALID(duration) )
{
if ( sink->soc.frameRate != 0 )
{
duration= GST_SECOND / sink->soc.frameRate;
GST_BUFFER_DURATION(buf)= duration;
}
else
{
GST_LOG("wstChain: buffer duration not available");
}
}
if ( GST_CLOCK_TIME_IS_VALID(duration) && GST_CLOCK_TIME_IS_VALID(pts) &&
(pts+duration <= sink->segment.start) )
{
GST_LOG("wstChain: accept buf %p pts %lld segment start %lld", buf, pts, sink->segment.start);
GST_BASE_SINK_PREROLL_LOCK(GST_BASE_SINK(sink));
gst_westeros_sink_soc_render( sink, buf );
GST_BASE_SINK_PREROLL_UNLOCK(GST_BASE_SINK(sink));
}
}
return sink->soc.chainOrg( pad, parent, buf );
}
#endif
void gst_westeros_sink_soc_class_init(GstWesterosSinkClass *klass)
{
GObjectClass *gobject_class= (GObjectClass *) klass;
GstBaseSinkClass *gstbasesink_class= (GstBaseSinkClass *) klass;
gst_element_class_set_static_metadata( GST_ELEMENT_CLASS(klass),
"Westeros Sink",
"Codec/Decoder/Video/Sink/Video",
"Writes buffers to the westeros wayland compositor",
"Comcast" );
wstDiscoverVideoDecoder(klass);
gstbasesink_class->preroll= GST_DEBUG_FUNCPTR(prerollSinkSoc);
g_object_class_install_property (gobject_class, PROP_DEVICE,
g_param_spec_string ("device",
"device location",
"Location of the device", gDeviceName, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_FRAME_STEP_ON_PREROLL,
g_param_spec_boolean ("frame-step-on-preroll",
"frame step on preroll",
"allow frame stepping on preroll into pause", FALSE, G_PARAM_READWRITE));
#ifdef USE_AMLOGIC_MESON_MSYNC
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_AVSYNC_SESSION,
g_param_spec_int ("avsync-session", "avsync session",
"avsync session id to link video and audio. If set, this sink won't look for it from audio sink",
G_MININT, G_MAXINT, 0, G_PARAM_WRITABLE));
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_AVSYNC_MODE,
g_param_spec_int ("avsync-mode", "avsync mode",
"Vmaster(0) Amaster(1) PCRmaster(2) IPTV(3) FreeRun(4)",
G_MININT, G_MAXINT, 0, G_PARAM_WRITABLE));
#endif
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_LOW_MEMORY_MODE,
g_param_spec_boolean ("low-memory", "low memory mode",
"Reduce memory usage if possible",
FALSE, G_PARAM_WRITABLE));
g_object_class_install_property (gobject_class, PROP_ENABLE_TEXTURE,
g_param_spec_boolean ("enable-texture",
"enable texture signal",
"0: disable; 1: enable", FALSE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_FORCE_ASPECT_RATIO,
g_param_spec_boolean ("force-aspect-ratio",
"force aspect ratio",
"When enabled scaling respects source aspect ratio", FALSE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_WINDOW_SHOW,
g_param_spec_boolean ("show-video-window",
"make video window visible",
"true: visible, false: hidden", TRUE, G_PARAM_WRITABLE));
g_object_class_install_property (gobject_class, PROP_ZOOM_MODE,
g_param_spec_int ("zoom-mode",
"zoom-mode",
"Set zoom mode: 0-none, 1-direct, 2-normal, 3-16x9 stretch, 4-4x3 pillar box, 5-zoom",
ZOOM_NONE, ZOOM_ZOOM, ZOOM_NONE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_OVERSCAN_SIZE,
g_param_spec_int ("overscan-size",
"overscan-size",
"Set overscan size to be used with applicable zoom-modes",
0, 10, DEFAULT_OVERSCAN, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_REPORT_DECODE_ERRORS,
g_param_spec_boolean ("report-decode-errors",
"enable decodoe error signal",
"0: disable; 1: enable", FALSE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_QUEUED_FRAMES,
g_param_spec_uint ("queued-frames",
"queued frames",
"Get number for frames that are decoded and queued for rendering",
0, G_MAXUINT32, 0, G_PARAM_READABLE ));
g_signals[SIGNAL_FIRSTFRAME]= g_signal_new( "first-video-frame-callback",
G_TYPE_FROM_CLASS(GST_ELEMENT_CLASS(klass)),
(GSignalFlags) (G_SIGNAL_RUN_LAST),
0, /* class offset */
NULL, /* accumulator */
NULL, /* accu data */
g_cclosure_marshal_VOID__UINT_POINTER,
G_TYPE_NONE,
2,
G_TYPE_UINT,
G_TYPE_POINTER );
g_signals[SIGNAL_UNDERFLOW]= g_signal_new( "buffer-underflow-callback",
G_TYPE_FROM_CLASS(GST_ELEMENT_CLASS(klass)),
(GSignalFlags) (G_SIGNAL_RUN_LAST),
0, // class offset
NULL, // accumulator
NULL, // accu data
g_cclosure_marshal_VOID__UINT_POINTER,
G_TYPE_NONE,
2,
G_TYPE_UINT,
G_TYPE_POINTER );
g_signals[SIGNAL_NEWTEXTURE]= g_signal_new( "new-video-texture-callback",
G_TYPE_FROM_CLASS(GST_ELEMENT_CLASS(klass)),
(GSignalFlags) (G_SIGNAL_RUN_LAST),
0, /* class offset */
NULL, /* accumulator */
NULL, /* accu data */
NULL,
G_TYPE_NONE,
15,
G_TYPE_UINT, /* format: fourcc */
G_TYPE_UINT, /* pixel width */
G_TYPE_UINT, /* pixel height */
G_TYPE_INT, /* plane 0 fd */
G_TYPE_UINT, /* plane 0 byte length */
G_TYPE_UINT, /* plane 0 stride */
G_TYPE_POINTER, /* plane 0 data */
G_TYPE_INT, /* plane 1 fd */
G_TYPE_UINT, /* plane 1 byte length */
G_TYPE_UINT, /* plane 1 stride */
G_TYPE_POINTER, /* plane 1 data */
G_TYPE_INT, /* plane 2 fd */
G_TYPE_UINT, /* plane 2 byte length */
G_TYPE_UINT, /* plane 2 stride */
G_TYPE_POINTER /* plane 2 data */
);
g_signals[SIGNAL_DECODEERROR]= g_signal_new( "decode-error-callback",
G_TYPE_FROM_CLASS(GST_ELEMENT_CLASS(klass)),
(GSignalFlags) (G_SIGNAL_RUN_LAST),
0, // class offset
NULL, // accumulator
NULL, // accu data
g_cclosure_marshal_VOID__UINT_POINTER,
G_TYPE_NONE,
2,
G_TYPE_UINT,
G_TYPE_POINTER );
#ifdef USE_GST_VIDEO
g_signals[SIGNAL_TIMECODE]= g_signal_new( "timecode-callback",
G_TYPE_FROM_CLASS(GST_ELEMENT_CLASS(klass)),
(GSignalFlags) (G_SIGNAL_RUN_LAST),
0, /* class offset */
NULL, /* accumulator */
NULL, /* accu data */
NULL,
G_TYPE_NONE,
3,
G_TYPE_UINT, /* hours */
G_TYPE_UINT, /* minutes */
G_TYPE_UINT /* seconds */
);
#endif
klass->canUseResMgr= 0;
{
const char *env= getenv("WESTEROS_SINK_USE_ESSRMGR");
if ( env && (atoi(env) != 0) )
{
klass->canUseResMgr= 1;
}
}
}
gboolean gst_westeros_sink_soc_init( GstWesterosSink *sink )
{
gboolean result= FALSE;
const char *env;
#ifdef GLIB_VERSION_2_32
g_mutex_init( &sink->soc.mutex );
#else
sink->soc.mutex= g_mutex_new();
#endif
sink->soc.sb= 0;
sink->soc.activeBuffers= 0;
sink->soc.frameRate= 0.0;
sink->soc.frameRateFractionNum= 0;
sink->soc.frameRateFractionDenom= 0;
sink->soc.frameRateChanged= FALSE;
sink->soc.pixelAspectRatio= 1.0;
sink->soc.parNext= 0;
sink->soc.parNextCapacity= 0;
sink->soc.parNextCount= 0;
sink->soc.havePixelAspectRatio= FALSE;
sink->soc.pixelAspectRatioChanged= FALSE;
#ifdef USE_GST_AFD
memset( &sink->soc.afdActive, 0, sizeof(WstAFDInfo));
sink->soc.afdInfo= 0;
sink->soc.afdInfoCount= 0;
sink->soc.afdInfoCapacity= 0;
#endif
sink->soc.showChanged= FALSE;
sink->soc.zoomModeUser= FALSE;
sink->soc.zoomMode= ZOOM_NONE;
sink->soc.overscanSize= DEFAULT_OVERSCAN;
sink->soc.frameWidth= -1;
sink->soc.frameHeight= -1;
sink->soc.frameWidthStream= -1;
sink->soc.frameHeightStream= -1;
sink->soc.frameInCount= 0;
sink->soc.frameOutCount= 0;
sink->soc.videoStartTime= 0;
sink->soc.frameDecodeCount= 0;
sink->soc.frameDisplayCount= 0;
sink->soc.expectNoLastFrame= FALSE;
sink->soc.decoderLastFrame= 0;
sink->soc.decoderEOS= 0;
sink->soc.numDropped= 0;
sink->soc.inputFormat= 0;
sink->soc.outputFormat= WL_SB_FORMAT_NV12;
sink->soc.interlaced= FALSE;
sink->soc.prevDecodedTimestamp= 0;
sink->soc.currentInputPTS= 0;
sink->soc.devname= strdup(gDeviceName);
sink->soc.enableTextureSignal= FALSE;
sink->soc.v4l2Fd= -1;
sink->soc.caps= {0};
sink->soc.deviceCaps= 0;
sink->soc.isMultiPlane= FALSE;
sink->soc.preferNV12M= TRUE;
sink->soc.inputMemMode= V4L2_MEMORY_MMAP;
sink->soc.outputMemMode= V4L2_MEMORY_MMAP;
sink->soc.numInputFormats= 0;
sink->soc.inputFormats= 0;
sink->soc.numOutputFormats= 0;
sink->soc.outputFormats= 0;
sink->soc.fmtIn= {0};
sink->soc.fmtOut= {0};
sink->soc.formatsSet= FALSE;
sink->soc.updateSession= FALSE;
sink->soc.syncType= -1;
#ifdef USE_AMLOGIC_MESON_MSYNC
sink->soc.sessionId= -1;
#else
sink->soc.sessionId= 0;
#endif
sink->soc.bufferCohort= 0;
sink->soc.inQueuedCount= 0;
sink->soc.minBuffersIn= 0;
sink->soc.minBuffersOut= 0;
sink->soc.numBuffersIn= 0;
sink->soc.inBuffers= 0;
sink->soc.outQueuedCount= 0;
sink->soc.numBuffersOut= 0;
sink->soc.bufferIdOutBase= 0;
sink->soc.outBuffers= 0;
sink->soc.quitVideoOutputThread= FALSE;
sink->soc.quitEOSDetectionThread= FALSE;
sink->soc.quitDispatchThread= FALSE;
sink->soc.videoOutputThread= NULL;
sink->soc.eosDetectionThread= NULL;
sink->soc.dispatchThread= NULL;
sink->soc.videoPlaying= FALSE;
sink->soc.videoPaused= FALSE;
sink->soc.hasEvents= FALSE;
sink->soc.hasEOSEvents= FALSE;
sink->soc.needCaptureRestart= FALSE;
sink->soc.emitFirstFrameSignal= FALSE;
sink->soc.emitUnderflowSignal= FALSE;
sink->soc.decodeError= FALSE;
sink->soc.nextFrameFd= -1;
sink->soc.prevFrame1Fd= -1;
sink->soc.prevFrame2Fd= -1;
sink->soc.resubFd= -1;
sink->soc.captureEnabled= FALSE;
sink->soc.useCaptureOnly= FALSE;
sink->soc.frameAdvance= FALSE;
sink->soc.pauseException= FALSE;
sink->soc.pauseGetGfxFrame= FALSE;
sink->soc.useGfxSync= FALSE;
sink->soc.pauseGfxBuffIndex= -1;
sink->soc.hideVideoFramesDelay= 2;
sink->soc.hideGfxFramesDelay= 1;
sink->soc.framesBeforeHideVideo= 0;
sink->soc.framesBeforeHideGfx= 0;
sink->soc.prevFrameTimeGfx= 0;
sink->soc.prevFramePTSGfx= 0;
sink->soc.videoX= sink->windowX;
sink->soc.videoY= sink->windowY;
sink->soc.videoWidth= sink->windowWidth;
sink->soc.videoHeight= sink->windowHeight;
sink->soc.prerollBuffer= 0;
sink->soc.frameStepOnPreroll= FALSE;
sink->soc.lowMemoryMode= FALSE;
sink->soc.forceAspectRatio= FALSE;
sink->soc.secureVideo= FALSE;
sink->soc.useDmabufOutput= FALSE;
sink->soc.dwMode= -1;
sink->soc.drmFd= -1;
sink->soc.haveColorimetry= FALSE;
sink->soc.haveMasteringDisplay= FALSE;
sink->soc.haveContentLightLevel= FALSE;
#ifdef ENABLE_SW_DECODE
sink->soc.firstFrameThread= NULL;
sink->soc.nextSWBuffer= 0;
sink->swInit= swInit;
sink->swTerm= swTerm;
sink->swLink= swLink;
sink->swUnLink= swUnLink;
sink->swEvent= swEvent;
sink->swDisplay= swDisplay;
{
int i;
for( i= 0; i < WST_NUM_SW_BUFFERS; ++i )
{
sink->soc.swBuffer[i].width= -1;
sink->soc.swBuffer[i].height= -1;
sink->soc.swBuffer[i].fd0= -1;
sink->soc.swBuffer[i].fd1= -1;
sink->soc.swBuffer[i].handle0= 0;
sink->soc.swBuffer[i].handle1= 0;
}
}
#endif
sink->useSegmentPosition= TRUE;
#ifdef USE_GST1
sink->soc.chainOrg= 0;
if ( GST_BASE_SINK(sink)->sinkpad )
{
sink->soc.chainOrg= GST_BASE_SINK(sink)->sinkpad->chainfunc;
gst_pad_set_chain_function( GST_BASE_SINK(sink)->sinkpad, wstChain );
}
else
{
GST_ERROR("unable to access sink pad" );
}
#endif
sink->acquireResources= sinkAcquireVideo;
sink->releaseResources= sinkReleaseVideo;
/* Request caps updates */
sink->passCaps= TRUE;
if ( getenv("WESTEROS_SINK_USE_FREERUN") )
{
gst_base_sink_set_sync(GST_BASE_SINK(sink), FALSE);
printf("westeros-sink: using freerun\n");
}
else
{
gst_base_sink_set_sync(GST_BASE_SINK(sink), TRUE);
}
gst_base_sink_set_async_enabled(GST_BASE_SINK(sink), TRUE);
if ( getenv("WESTEROS_SINK_USE_NV21") )
{
sink->soc.outputFormat= WL_SB_FORMAT_NV21;
}
if ( getenv("WESTEROS_SINK_USE_GFX") )
{
sink->soc.useCaptureOnly= TRUE;
sink->soc.captureEnabled= TRUE;
printf("westeros-sink: capture only\n");
}
if ( getenv("WESTEROS_SINK_LOW_MEM_MODE") )
{
sink->soc.lowMemoryMode= TRUE;
printf("westeros-sink: low memory mode\n");
}
#ifdef USE_AMLOGIC_MESON_MSYNC
printf("westeros-sink: msync enabled\n");
#endif
env= getenv( "WESTEROS_SINK_DEBUG_FRAME" );
if ( env )
{
int level= atoi( env );
g_frameDebug= (level > 0 ? true : false);
}
result= TRUE;
return result;
}
void gst_westeros_sink_soc_term( GstWesterosSink *sink )
{
if ( sink->soc.devname )
{
free( sink->soc.devname );
}
#ifdef GLIB_VERSION_2_32
g_mutex_clear( &sink->soc.mutex );
#else
g_mutex_free( sink->soc.mutex );
#endif
}
void gst_westeros_sink_soc_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec)
{
GstWesterosSink *sink = GST_WESTEROS_SINK(object);
WESTEROS_UNUSED(pspec);
switch (prop_id)
{
case PROP_DEVICE:
{
const gchar *s= g_value_get_string (value);
if ( s )
{
sink->soc.devname= strdup(s);
}
}
break;
case PROP_FRAME_STEP_ON_PREROLL:
{
sink->soc.frameStepOnPreroll= g_value_get_boolean(value);
GST_WARNING("Set frameStepOnPreroll to %d", sink->soc.frameStepOnPreroll);
if (sink->soc.frameStepOnPreroll)
{
GST_DEBUG("Current need preroll %d have_preroll %d",
GST_BASE_SINK(sink)->need_preroll,
GST_BASE_SINK(sink)->have_preroll);
if (sink->soc.frameOutCount && sink->soc.conn)
{
GST_DEBUG("Frame already out, just send advance message");
LOCK(sink);
wstSendFrameAdvanceVideoClientConnection( sink->soc.conn );
UNLOCK(sink);
}
else
{
GstBaseSink *basesink;
basesink= GST_BASE_SINK(sink);
GST_BASE_SINK_PREROLL_LOCK(basesink);
if ( GST_BASE_SINK(sink)->need_preroll &&
GST_BASE_SINK(sink)->have_preroll )
{
GST_DEBUG("Already prerolled, set frameAdvanced");
LOCK(sink);
sink->soc.frameAdvance= TRUE;
UNLOCK(sink);
GST_BASE_SINK(sink)->need_preroll= FALSE;
GST_BASE_SINK(sink)->have_preroll= TRUE;
}
GST_BASE_SINK_PREROLL_UNLOCK(basesink);
}
}
break;
}
#ifdef USE_AMLOGIC_MESON_MSYNC
case PROP_AVSYNC_SESSION:
{
int id= g_value_get_int(value);
if (id >= 0)
{
sink->soc.userSession= TRUE;
sink->soc.sessionId= id;
GST_WARNING("AV sync session %d", id);
}
break;
}
case PROP_AVSYNC_MODE:
{
int mode= g_value_get_int(value);
if (mode >= 0)
{
sink->soc.syncType= mode;
GST_WARNING("AV sync mode %d", mode);
}
break;
}
#endif
case PROP_LOW_MEMORY_MODE:
{
sink->soc.lowMemoryMode= g_value_get_boolean(value);
break;
}
case PROP_FORCE_ASPECT_RATIO:
{
sink->soc.forceAspectRatio= g_value_get_boolean(value);
break;
}
case PROP_WINDOW_SHOW:
{
gboolean show= g_value_get_boolean(value);
if ( sink->show != show )
{
GST_DEBUG("set show-video-window to %d", show);
sink->soc.showChanged= TRUE;
sink->show= show;
sink->visible= sink->show;
}
}
break;
case PROP_ZOOM_MODE:
{
gint zoom= g_value_get_int(value);
if ( !sink->soc.zoomModeUser || (sink->soc.zoomMode != zoom) )
{
GST_DEBUG("set zoom-mode to %d", zoom);
sink->soc.zoomMode= zoom;
sink->soc.zoomModeUser= TRUE;
}
}
break;
case PROP_OVERSCAN_SIZE:
{
gint overscan= g_value_get_int(value);
if ( sink->soc.overscanSize != overscan )
{
GST_DEBUG("set overscan-size to %d", overscan);
sink->soc.overscanSize= overscan;
}
}
break;
case PROP_ENABLE_TEXTURE:
{
sink->soc.enableTextureSignal= g_value_get_boolean(value);
if ( sink->soc.enableTextureSignal && sink->soc.lowMemoryMode )
{
sink->soc.enableTextureSignal= FALSE;
g_print("NOTE: attempt to enable texture signal in low memory mode ignored\n");
}
}
break;
case PROP_REPORT_DECODE_ERRORS:
{
sink->soc.enableDecodeErrorSignal= g_value_get_boolean(value);
break;
}
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
break;
}
}
void gst_westeros_sink_soc_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
{
GstWesterosSink *sink = GST_WESTEROS_SINK(object);
WESTEROS_UNUSED(pspec);
switch (prop_id)
{
case PROP_DEVICE:
g_value_set_string(value, sink->soc.devname);
break;
case PROP_FRAME_STEP_ON_PREROLL:
g_value_set_boolean(value, sink->soc.frameStepOnPreroll);
break;
#ifdef USE_AMLOGIC_MESON_MSYNC
case PROP_AVSYNC_SESSION:
g_value_set_int(value, sink->soc.sessionId);
break;
case PROP_AVSYNC_MODE:
g_value_set_int(value, sink->soc.syncType);
break;
#endif
case PROP_LOW_MEMORY_MODE:
g_value_set_boolean(value, sink->soc.lowMemoryMode);
break;
case PROP_FORCE_ASPECT_RATIO:
g_value_set_boolean(value, sink->soc.forceAspectRatio);
break;
case PROP_WINDOW_SHOW:
g_value_set_boolean(value, sink->show);
break;
case PROP_ZOOM_MODE:
g_value_set_int(value, sink->soc.zoomMode);
break;
case PROP_OVERSCAN_SIZE:
g_value_set_int(value, sink->soc.overscanSize);
break;
case PROP_ENABLE_TEXTURE:
g_value_set_boolean(value, sink->soc.enableTextureSignal);
break;
case PROP_REPORT_DECODE_ERRORS:
g_value_set_boolean(value, sink->soc.enableDecodeErrorSignal);
break;
case PROP_QUEUED_FRAMES:
{
guint queuedFrames= 0;
/*
* An app would use the property to gauge buffering. Hence
* we need to set need_preroll to FALSE and signal preroll
* to allow further bufferig while in paused state. This is
* because westerossink does both the decoding and the display
*/
GstBaseSink *basesink;
basesink = GST_BASE_SINK(sink);
GST_BASE_SINK_PREROLL_LOCK(basesink);
if ( GST_BASE_SINK(sink)->need_preroll && GST_BASE_SINK(sink)->have_preroll )
{
GST_BASE_SINK(sink)->need_preroll= FALSE;
GST_BASE_SINK(sink)->have_preroll= FALSE;
GST_BASE_SINK_PREROLL_SIGNAL(basesink);
}
GST_BASE_SINK_PREROLL_UNLOCK(basesink);
LOCK(sink);
if ( (sink->soc.frameInCount > sink->soc.frameDecodeCount) &&
(sink->soc.frameOutCount - sink->soc.frameDisplayCount >= 1) )
{
queuedFrames= sink->soc.frameInCount - sink->soc.frameDecodeCount;
}
UNLOCK(sink);
GST_DEBUG("queuedFrames %d (in %d out %d dec %d disp %d)", queuedFrames, sink->soc.frameInCount, sink->soc.frameOutCount, sink->soc.frameDecodeCount, sink->soc.frameDisplayCount);
g_value_set_uint(value, queuedFrames);
}
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
break;
}
}
void gst_westeros_sink_soc_registryHandleGlobal( GstWesterosSink *sink,
struct wl_registry *registry, uint32_t id,
const char *interface, uint32_t version)
{
WESTEROS_UNUSED(version);
int len;
len= strlen(interface);
if ((len==5) && (strncmp(interface, "wl_sb", len) == 0))
{
sink->soc.sb= (struct wl_sb*)wl_registry_bind(registry, id, &wl_sb_interface, version);
printf("westeros-sink-soc: registry: sb %p\n", (void*)sink->soc.sb);
wl_proxy_set_queue((struct wl_proxy*)sink->soc.sb, sink->queue);
wl_sb_add_listener(sink->soc.sb, &sbListener, sink);
printf("westeros-sink-soc: registry: done add sb listener\n");
}
if ( sink->soc.useCaptureOnly )
{
/* Don't use vpc when capture only */
if ( sink->vpc )
{
wl_vpc_destroy( sink->vpc );
sink->vpc= 0;
}
}
}
void gst_westeros_sink_soc_registryHandleGlobalRemove( GstWesterosSink *sink,
struct wl_registry *registry,
uint32_t name)
{
WESTEROS_UNUSED(sink);
WESTEROS_UNUSED(registry);
WESTEROS_UNUSED(name);
}
gboolean gst_westeros_sink_soc_null_to_ready( GstWesterosSink *sink, gboolean *passToDefault )
{
gboolean result= FALSE;
WESTEROS_UNUSED(passToDefault);
avProgInit();
result= TRUE;
return result;
}
gboolean gst_westeros_sink_soc_ready_to_paused( GstWesterosSink *sink, gboolean *passToDefault )
{
gboolean result= FALSE;
WESTEROS_UNUSED(passToDefault);
if ( sinkAcquireResources( sink ) )
{
wstStartEvents( sink );
if ( !sink->soc.useCaptureOnly )
{
sink->soc.conn= wstCreateVideoClientConnection( sink, DEFAULT_VIDEO_SERVER );
if ( !sink->soc.conn )
{
GST_ERROR("unable to connect to video server (%s)", DEFAULT_VIDEO_SERVER );
sink->soc.useCaptureOnly= TRUE;
sink->soc.captureEnabled= TRUE;
printf("westeros-sink: no video server - capture only\n");
if ( sink->vpc )
{
wl_vpc_destroy( sink->vpc );
sink->vpc= 0;
}
}
}
LOCK(sink);
sink->startAfterCaps= TRUE;
sink->soc.videoPlaying= TRUE;
sink->soc.videoPaused= TRUE;
UNLOCK(sink);
result= TRUE;
}
else
{
GST_ERROR("gst_westeros_sink_ready_to_paused: sinkAcquireResources failed");
}
return result;
}
gboolean gst_westeros_sink_soc_paused_to_playing( GstWesterosSink *sink, gboolean *passToDefault )
{
WESTEROS_UNUSED(passToDefault);
LOCK( sink );
sink->soc.videoPlaying= TRUE;
sink->soc.videoPaused= FALSE;
#ifdef USE_AMLOGIC_MESON_MSYNC
if ( !sink->soc.userSession )
#endif
{
sink->soc.updateSession= TRUE;
}
UNLOCK( sink );
return TRUE;
}
gboolean gst_westeros_sink_soc_playing_to_paused( GstWesterosSink *sink, gboolean *passToDefault )
{
LOCK( sink );
sink->soc.videoPlaying= FALSE;
sink->soc.videoPaused= TRUE;
UNLOCK( sink );
if (gst_base_sink_is_async_enabled(GST_BASE_SINK(sink)))
{
/* To complete transition to paused state in async_enabled mode, we need a preroll buffer pushed to the pad;
This is a workaround to avoid the need for preroll buffer. */
GstBaseSink *basesink;
basesink = GST_BASE_SINK(sink);
GST_BASE_SINK_PREROLL_LOCK (basesink);
basesink->have_preroll = 1;
GST_BASE_SINK_PREROLL_UNLOCK (basesink);
*passToDefault= true;
}
else
{
*passToDefault = false;
}
return TRUE;
}
gboolean gst_westeros_sink_soc_paused_to_ready( GstWesterosSink *sink, gboolean *passToDefault )
{
wstSinkSocStopVideo( sink );
LOCK( sink );
sink->videoStarted= FALSE;
UNLOCK( sink );
if (gst_base_sink_is_async_enabled(GST_BASE_SINK(sink)))
{
*passToDefault= true;
}
else
{
*passToDefault= false;
}
return TRUE;
}
gboolean gst_westeros_sink_soc_ready_to_null( GstWesterosSink *sink, gboolean *passToDefault )
{
WESTEROS_UNUSED(sink);
wstSinkSocStopVideo( sink );
avProgTerm();
*passToDefault= false;
return TRUE;
}
gboolean gst_westeros_sink_soc_accept_caps( GstWesterosSink *sink, GstCaps *caps )
{
bool result= FALSE;
GstStructure *structure;
const gchar *mime;
int len;
bool frameSizeChange= false;
gchar *str= gst_caps_to_string(caps);
g_print("westeros-sink: caps: (%s)\n", str);
g_free( str );
structure= gst_caps_get_structure(caps, 0);
if( structure )
{
mime= gst_structure_get_name(structure);
if ( mime )
{
len= strlen(mime);
if ( (len == 12) && !strncmp("video/x-h264", mime, len) )
{
sink->soc.inputFormat= V4L2_PIX_FMT_H264;
result= TRUE;
}
else if ( (len == 10) && !strncmp("video/mpeg", mime, len) )
{
int version;
sink->soc.inputFormat= V4L2_PIX_FMT_MPEG;
if ( gst_structure_get_int(structure, "mpegversion", &version) )
{
switch( version )
{
case 1:
sink->soc.inputFormat= V4L2_PIX_FMT_MPEG1;
break;
default:
case 2:
sink->soc.inputFormat= V4L2_PIX_FMT_MPEG2;
break;
case 4:
sink->soc.inputFormat= V4L2_PIX_FMT_MPEG4;
break;
}
}
result= TRUE;
}
#ifdef V4L2_PIX_FMT_HEVC
else if ( (len == 12) && !strncmp("video/x-h265", mime, len) )
{
sink->soc.inputFormat= V4L2_PIX_FMT_HEVC;
result= TRUE;
}
#endif
#ifdef V4L2_PIX_FMT_VP9
else if ( (len == 11) && !strncmp("video/x-vp9", mime, len) )
{
sink->soc.inputFormat= V4L2_PIX_FMT_VP9;
result= TRUE;
}
#endif
#ifdef V4L2_PIX_FMT_AV1
else if ( (len == 11) && !strncmp("video/x-av1", mime, len)
#ifdef ENABLE_AV1_DOLBYVISION
|| (len == 23) && !strncmp("video/x-gst-fourcc-dav1", mime, len)
#endif
)
{
sink->soc.inputFormat= V4L2_PIX_FMT_AV1;
result= TRUE;
}
#endif
else
{
GST_ERROR("gst_westeros_sink_soc_accept_caps: not accepting caps (%s)", mime );
}
}
if ( result == TRUE )
{
gint num, denom, width, height;
double pixelAspectRatioNext;
if ( gst_structure_get_fraction( structure, "framerate", &num, &denom ) )
{
if ( denom == 0 ) denom= 1;
sink->soc.frameRate= (double)num/(double)denom;
if ( sink->soc.frameRate <= 0.0 )
{
g_print("westeros-sink: caps have framerate of 0 - assume 60\n");
sink->soc.frameRate= 60.0;
}
if ( (sink->soc.frameRateFractionNum != num) || (sink->soc.frameRateFractionDenom != denom) )
{
sink->soc.frameRateFractionNum= num;
sink->soc.frameRateFractionDenom= denom;
sink->soc.frameRateChanged= TRUE;
}
}
if ( (sink->soc.frameRate == 0.0) && (sink->soc.frameRateFractionDenom == 0) )
{
sink->soc.frameRateFractionDenom= 1;
sink->soc.frameRateChanged= TRUE;
}
width= -1;
if ( gst_structure_get_int( structure, "width", &width ) )
{
if ( (sink->soc.frameWidth != -1) && (sink->soc.frameWidth != width) )
{
frameSizeChange= true;
}
if ( (sink->soc.frameWidth == -1) || (sink->soc.hasEvents == FALSE) )
{
sink->soc.frameWidth= width;
}
sink->soc.frameWidthStream= width;
}
height= -1;
if ( gst_structure_get_int( structure, "height", &height ) )
{
if ( (sink->soc.frameHeight != -1) && (sink->soc.frameHeight != height) )
{
frameSizeChange= true;
}
if ( (sink->soc.frameHeight == -1) || (sink->soc.hasEvents == FALSE) )
{
sink->soc.frameHeight= height;
}
sink->soc.frameHeightStream= height;
}
pixelAspectRatioNext= 1.0;
if ( gst_structure_get_fraction( structure, "pixel-aspect-ratio", &num, &denom ) )
{
if ( (num <= 0) || (denom <= 0))
{
num= denom= 1;
}
pixelAspectRatioNext= (double)num/(double)denom;
sink->soc.havePixelAspectRatio= TRUE;
}
wstPushPixelAspectRatio( sink, pixelAspectRatioNext, width, height );
sink->soc.interlaced= FALSE;
if ( gst_structure_has_field(structure, "interlace-mode") )
{
const char *mode= gst_structure_get_string(structure,"interlace-mode");
if ( mode )
{
int len= strlen(mode);
if ( (len == 11) && !strncmp( mode, "progressive", len) )
{
sink->soc.interlaced= FALSE;
}
else
{
sink->soc.interlaced= TRUE;
}
}
}
if ( gst_structure_has_field(structure, "colorimetry") )
{
const char *colorimetry= gst_structure_get_string(structure,"colorimetry");
if ( colorimetry )
{
#ifdef USE_GST_VIDEO
GstVideoColorimetry vci;
if ( gst_video_colorimetry_from_string( &vci, colorimetry ) )
{
sink->soc.haveColorimetry= TRUE;
sink->soc.hdrColorimetry[0]= (int)vci.range;
sink->soc.hdrColorimetry[1]= (int)vci.matrix;
sink->soc.hdrColorimetry[2]= (int)vci.transfer;
sink->soc.hdrColorimetry[3]= (int)vci.primaries;
}
#else
if ( sscanf( colorimetry, "%d:%d:%d:%d",
&sink->soc.hdrColorimetry[0],
&sink->soc.hdrColorimetry[1],
&sink->soc.hdrColorimetry[2],
&sink->soc.hdrColorimetry[3] ) == 4 )
{
sink->soc.haveColorimetry= TRUE;
}
#endif
if ( sink->soc.haveColorimetry )
{
GST_DEBUG("colorimetry: [%d,%d,%d,%d]",
sink->soc.hdrColorimetry[0],
sink->soc.hdrColorimetry[1],
sink->soc.hdrColorimetry[2],
sink->soc.hdrColorimetry[3] );
}
}
}
if ( gst_structure_has_field(structure, "mastering-display-metadata") )
{
const char *masteringDisplay= gst_structure_get_string(structure,"mastering-display-metadata");
if ( masteringDisplay &&
sscanf( masteringDisplay, "%f:%f:%f:%f:%f:%f:%f:%f:%f:%f",
&sink->soc.hdrMasteringDisplay[0],
&sink->soc.hdrMasteringDisplay[1],
&sink->soc.hdrMasteringDisplay[2],
&sink->soc.hdrMasteringDisplay[3],
&sink->soc.hdrMasteringDisplay[4],
&sink->soc.hdrMasteringDisplay[5],
&sink->soc.hdrMasteringDisplay[6],
&sink->soc.hdrMasteringDisplay[7],
&sink->soc.hdrMasteringDisplay[8],
&sink->soc.hdrMasteringDisplay[9] ) == 10 )
{
sink->soc.haveMasteringDisplay= TRUE;
GST_DEBUG("mastering display [%f,%f,%f,%f,%f,%f,%f,%f,%f,%f]",
sink->soc.hdrMasteringDisplay[0],
sink->soc.hdrMasteringDisplay[1],
sink->soc.hdrMasteringDisplay[2],
sink->soc.hdrMasteringDisplay[3],
sink->soc.hdrMasteringDisplay[4],
sink->soc.hdrMasteringDisplay[5],
sink->soc.hdrMasteringDisplay[6],
sink->soc.hdrMasteringDisplay[7],
sink->soc.hdrMasteringDisplay[8],
sink->soc.hdrMasteringDisplay[9] );
}
}
if ( gst_structure_has_field(structure, "content-light-level") )
{
const char *contentLightLevel= gst_structure_get_string(structure,"content-light-level");
if ( contentLightLevel &&
sscanf( contentLightLevel, "%d:%d",
&sink->soc.hdrContentLightLevel[0],
&sink->soc.hdrContentLightLevel[1] ) == 2 )
{
GST_DEBUG("content light level: [%d,%d])",
sink->soc.hdrContentLightLevel[0],
sink->soc.hdrContentLightLevel[1] );
sink->soc.haveContentLightLevel= TRUE;
}
}
if ( frameSizeChange && (sink->soc.hasEvents == FALSE) )
{
g_print("westeros-sink: frame size change : %dx%d\n", sink->soc.frameWidth, sink->soc.frameHeight);
wstDecoderReset( sink, true );
if ( sink->soc.v4l2Fd >= 0 )
{
wstSetupInput( sink );
}
}
}
}
return result;
}
void gst_westeros_sink_soc_set_startPTS( GstWesterosSink *sink, gint64 pts )
{
WESTEROS_UNUSED(sink);
WESTEROS_UNUSED(pts);
}
void gst_westeros_sink_soc_render( GstWesterosSink *sink, GstBuffer *buffer )
{
#ifdef ENABLE_SW_DECODE
if ( swIsSWDecode( sink ) )
{
wstsw_render( sink, buffer );
return;
}
#endif
if ( sink->soc.prerollBuffer )
{
bool alreadyRendered= false;
if ( buffer == sink->soc.prerollBuffer )
{
alreadyRendered= true;
}
sink->soc.prerollBuffer= 0;
if ( alreadyRendered )
{
return;
}
}
if ( (sink->soc.v4l2Fd >= 0) && !sink->flushStarted )
{
gint64 nanoTime;
gint64 duration;
int rc, buffIndex;
int inSize, offset, avail, copylen;
unsigned char *inData;
int memMode= V4L2_MEMORY_MMAP;
#ifdef USE_GST_AFD
wstAddAFDInfo( sink, buffer );
#endif
#ifdef USE_GST_ALLOCATORS
GstMemory *mem;
mem= gst_buffer_peek_memory( buffer, 0 );
#endif
if ( !sink->soc.formatsSet )
{
#ifdef USE_GST_ALLOCATORS
if ( gst_is_dmabuf_memory(mem) )
{
GST_DEBUG("using dma-buf for input");
memMode= V4L2_MEMORY_DMABUF;
}
else
{
memMode= V4L2_MEMORY_MMAP;
}
#endif
wstSetInputMemMode( sink, memMode );
wstSetupInput( sink );
}
#ifdef USE_GST_ALLOCATORS
inSize= gst_memory_get_sizes( mem, NULL, NULL );
if ( sink->soc.inputMemMode == V4L2_MEMORY_DMABUF )
{
GST_LOG("gst_westeros_sink_soc_render: buffer %p, len %d timestamp: %lld", buffer, inSize, GST_BUFFER_PTS(buffer) );
}
#endif
avProgLog( GST_BUFFER_PTS(buffer), 0, "GtoS", "");
if ( GST_BUFFER_PTS_IS_VALID(buffer) )
{
guint64 prevPTS;
nanoTime= GST_BUFFER_PTS(buffer);
duration= GST_BUFFER_DURATION(buffer);
if ( !GST_CLOCK_TIME_IS_VALID(duration) )
{
duration= 0;
}
{
guint64 gstNow= getGstClockTime(sink);
if ( gstNow <= nanoTime )
FRAME("in: frame PTS %lld gst clock %lld: lead time %lld us", nanoTime, gstNow, (nanoTime-gstNow)/1000LL);
else
FRAME("in: frame PTS %lld gst clock %lld: lead time %lld us", nanoTime, gstNow, (gstNow-nanoTime)/1000LL);
}
LOCK(sink)
if ( nanoTime+duration >= sink->segment.start )
{
if ( sink->prevPositionSegmentStart == 0xFFFFFFFFFFFFFFFFLL )
{
sink->soc.currentInputPTS= 0;
}
prevPTS= sink->soc.currentInputPTS;
sink->soc.currentInputPTS= ((nanoTime / GST_SECOND) * 90000)+(((nanoTime % GST_SECOND) * 90000) / GST_SECOND);
if (sink->prevPositionSegmentStart != sink->positionSegmentStart)
{
sink->firstPTS= sink->soc.currentInputPTS;
sink->prevPositionSegmentStart = sink->positionSegmentStart;
GST_DEBUG("SegmentStart changed! Updating first PTS to %lld ", sink->firstPTS);
}
if ( sink->soc.currentInputPTS != 0 || sink->soc.frameInCount == 0 )
{
if ( (sink->soc.currentInputPTS < sink->firstPTS) && (sink->soc.currentInputPTS > 90000) )
{
/* If we have hit a discontinuity that doesn't look like rollover, then
treat this as the case of looping a short clip. Adjust our firstPTS
to keep our running time correct. */
sink->firstPTS= sink->firstPTS-(prevPTS-sink->soc.currentInputPTS);
}
}
}
UNLOCK(sink);
}
#ifdef USE_GST_ALLOCATORS
if ( sink->soc.inputMemMode == V4L2_MEMORY_DMABUF )
{
uint32_t bytesused;
gsize dataOffset, maxSize;
buffIndex= wstGetInputBuffer( sink );
if ( (buffIndex < 0) && !sink->flushStarted )
{
GST_ERROR("gst_westeros_sink_soc_render: unable to get input buffer");
goto exit;
}
LOCK(sink);
if ( !sink->soc.inBuffers )
{
UNLOCK(sink);
goto exit;
}
if ( sink->soc.inBuffers[buffIndex].gstbuf )
{
gst_buffer_unref( sink->soc.inBuffers[buffIndex].gstbuf );
sink->soc.inBuffers[buffIndex].gstbuf= 0;
}
if ( sink->flushStarted )
{
UNLOCK(sink);
goto exit;
}
if (GST_BUFFER_PTS_IS_VALID(buffer) )
{
GstClockTime timestamp= GST_BUFFER_PTS(buffer) + 500LL;
GST_TIME_TO_TIMEVAL( timestamp, sink->soc.inBuffers[buffIndex].buf.timestamp );
}
inSize= gst_memory_get_sizes( mem, &dataOffset, &maxSize );
sink->soc.inBuffers[buffIndex].buf.bytesused= dataOffset+inSize;
if ( sink->soc.isMultiPlane )
{
sink->soc.inBuffers[buffIndex].buf.m.planes[0].m.fd= gst_dmabuf_memory_get_fd(mem);
sink->soc.inBuffers[buffIndex].buf.m.planes[0].bytesused= dataOffset+inSize;
sink->soc.inBuffers[buffIndex].buf.m.planes[0].length= maxSize;
sink->soc.inBuffers[buffIndex].buf.m.planes[0].data_offset= dataOffset;
}
else
{
sink->soc.inBuffers[buffIndex].buf.m.fd= gst_dmabuf_memory_get_fd(mem);
sink->soc.inBuffers[buffIndex].buf.length= maxSize;
}
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_QBUF, &sink->soc.inBuffers[buffIndex].buf );
UNLOCK(sink);
if ( rc < 0 )
{
GST_ERROR("gst_westeros_sink_soc_render: queuing input buffer failed: rc %d errno %d", rc, errno );
goto exit;
}
++sink->soc.inQueuedCount;
avProgLog( GST_BUFFER_PTS(buffer), 0, "StoD", wstInFullness(sink));
sink->soc.inBuffers[buffIndex].queued= true;
sink->soc.inBuffers[buffIndex].gstbuf= gst_buffer_ref(buffer);
}
else
#endif
if ( sink->soc.inputMemMode == V4L2_MEMORY_MMAP )
{
#ifdef USE_GST1
GstMapInfo map;
gst_buffer_map(buffer, &map, (GstMapFlags)GST_MAP_READ);
inSize= map.size;
inData= map.data;
#else
inSize= (int)GST_BUFFER_SIZE(buffer);
inData= GST_BUFFER_DATA(buffer);
#endif
GST_LOG("gst_westeros_sink_soc_render: buffer %p, len %d timestamp: %lld", buffer, inSize, GST_BUFFER_PTS(buffer) );
if ( inSize )
{
avail= inSize;
offset= 0;
while( offset < inSize )
{
buffIndex= wstGetInputBuffer( sink );
if ( (buffIndex < 0) && !sink->flushStarted )
{
GST_ERROR("gst_westeros_sink_soc_render: unable to get input buffer");
goto exit;
}
if ( sink->flushStarted )
{
goto exit;
}
LOCK(sink);
if ( !sink->soc.inBuffers )
{
UNLOCK(sink);
goto exit;
}
copylen= sink->soc.inBuffers[buffIndex].capacity;
if ( copylen > avail )
{
copylen= avail;
}
memcpy( sink->soc.inBuffers[buffIndex].start, &inData[offset], copylen );
offset += copylen;
avail -= copylen;
if (GST_BUFFER_PTS_IS_VALID(buffer) )
{
GstClockTime timestamp= GST_BUFFER_PTS(buffer) + 500LL;
GST_TIME_TO_TIMEVAL( timestamp, sink->soc.inBuffers[buffIndex].buf.timestamp );
}
sink->soc.inBuffers[buffIndex].buf.bytesused= copylen;
if ( sink->soc.isMultiPlane )
{
sink->soc.inBuffers[buffIndex].buf.m.planes[0].bytesused= copylen;
}
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_QBUF, &sink->soc.inBuffers[buffIndex].buf );
if ( rc < 0 )
{
UNLOCK(sink);
GST_ERROR("gst_westeros_sink_soc_render: queuing input buffer failed: rc %d errno %d", rc, errno );
goto exit;
}
++sink->soc.inQueuedCount;
sink->soc.inBuffers[buffIndex].queued= true;
UNLOCK(sink);
avProgLog( GST_BUFFER_PTS(buffer), 0, "StoD", wstInFullness(sink));
}
}
#ifdef USE_GST1
gst_buffer_unmap( buffer, &map);
#endif
}
++sink->soc.frameInCount;
LOCK(sink);
if ( !sink->videoStarted && (!sink->rm || sink->resAssignedId >= 0) )
{
int len;
GST_DEBUG("gst_westeros_sink_soc_render: issue input VIDIOC_STREAMON");
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_STREAMON, &sink->soc.fmtIn.type );
if ( rc < 0 )
{
UNLOCK(sink);
GST_ERROR("streamon failed for input: rc %d errno %d", rc, errno );
goto exit;
}
len= strlen( (char*)sink->soc.caps.driver );
if ( (len == 13) && !strncmp( (char*)sink->soc.caps.driver, "bcm2835-codec", len) )
{
GST_DEBUG("Setup output prior to source change for (%s)", sink->soc.caps.driver);
sink->soc.expectNoLastFrame= TRUE;
wstSetupOutput( sink );
}
if ( !gst_westeros_sink_soc_start_video( sink ) )
{
GST_ERROR("gst_westeros_sink_soc_render: gst_westeros_sink_soc_start_video failed");
}
}
UNLOCK(sink);
}
exit:
return;
}
void gst_westeros_sink_soc_flush( GstWesterosSink *sink )
{
GST_DEBUG("gst_westeros_sink_soc_flush");
if ( sink->videoStarted )
{
wstDecoderReset( sink, true );
}
LOCK(sink);
sink->soc.frameInCount= 0;
sink->soc.frameOutCount= 0;
sink->soc.frameDecodeCount= 0;
sink->soc.frameDisplayCount= 0;
sink->soc.numDropped= 0;
sink->soc.frameDisplayCount= 0;
sink->soc.decoderLastFrame= 0;
sink->soc.decoderEOS= 0;
sink->soc.videoStartTime= 0;
sink->soc.prerollBuffer= 0;
wstFlushPixelAspectRatio( sink, false );
#ifdef USE_GST_AFD
wstFlushAFDInfo( sink, false );
#endif
UNLOCK(sink);
}
gboolean gst_westeros_sink_soc_start_video( GstWesterosSink *sink )
{
gboolean result= FALSE;
int rc;
sink->soc.videoStartTime= g_get_monotonic_time();
sink->soc.frameOutCount= 0;
sink->soc.frameDecodeCount= 0;
sink->soc.frameDisplayCount= 0;
sink->soc.numDropped= 0;
sink->soc.frameDisplayCount= 0;
sink->soc.decoderLastFrame= 0;
sink->soc.decoderEOS= 0;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_STREAMON, &sink->soc.fmtIn.type );
if ( rc < 0 )
{
GST_ERROR("streamon failed for input: rc %d errno %d", rc, errno );
goto exit;
}
if ( sink->display )
{
sink->soc.quitDispatchThread= FALSE;
if ( sink->soc.dispatchThread == NULL )
{
GST_DEBUG_OBJECT(sink, "gst_westeros_sink_soc_start_video: starting westeros_sink_dispatch thread");
sink->soc.dispatchThread= g_thread_new("westeros_sink_dispatch", wstDispatchThread, sink);
}
}
sink->soc.quitVideoOutputThread= FALSE;
if ( sink->soc.videoOutputThread == NULL )
{
GST_DEBUG_OBJECT(sink, "gst_westeros_sink_soc_start_video: starting westeros_sink_video_output thread");
sink->soc.videoOutputThread= g_thread_new("westeros_sink_video_output", wstVideoOutputThread, sink);
}
sink->soc.quitEOSDetectionThread= FALSE;
if ( sink->soc.eosDetectionThread == NULL )
{
GST_DEBUG_OBJECT(sink, "gst_westeros_sink_soc_start_video: starting westeros_sink_eos thread");
sink->soc.eosDetectionThread= g_thread_new("westeros_sink_eos", wstEOSDetectionThread, sink);
}
sink->videoStarted= TRUE;
result= TRUE;
exit:
return result;
}
void gst_westeros_sink_soc_eos_event( GstWesterosSink *sink )
{
WESTEROS_UNUSED(sink);
if ( swIsSWDecode( sink ) )
{
g_print("westeros-sink: EOS detected\n");
gst_westeros_sink_eos_detected( sink );
return;
}
GST_DEBUG("hasEOSEvents %d frameInCount %d", sink->soc.hasEOSEvents, sink->soc.frameInCount);
if ( !sink->soc.hasEOSEvents || (sink->soc.frameInCount <= 2) )
{
GST_DEBUG("set decoderEOS");
sink->soc.decoderEOS= 1;
}
else
{
int rc;
struct v4l2_decoder_cmd dcmd;
memset( &dcmd, 0, sizeof(dcmd));
GST_DEBUG("got eos: issuing decoder stop");
dcmd.cmd= V4L2_DEC_CMD_STOP;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_DECODER_CMD, &dcmd );
if ( rc )
{
GST_DEBUG("VIDIOC_DECODER_CMD V4L2_DEC_CMD_STOP rc %d errno %d",rc, errno);
}
}
}
void gst_westeros_sink_soc_set_video_path( GstWesterosSink *sink, bool useGfxPath )
{
if ( useGfxPath && sink->soc.lowMemoryMode )
{
g_print("NOTE: Attempt to use video textures in low memory mode ignored\n");
useGfxPath= false;
}
if ( useGfxPath && !sink->soc.captureEnabled )
{
sink->soc.captureEnabled= TRUE;
sink->soc.framesBeforeHideVideo= sink->soc.hideVideoFramesDelay;
if ( sink->soc.videoPaused )
{
sink->soc.pauseException= TRUE;
sink->soc.pauseGetGfxFrame= TRUE;
}
}
else if ( !useGfxPath && sink->soc.captureEnabled )
{
sink->soc.captureEnabled= FALSE;
sink->soc.prevFrame1Fd= -1;
sink->soc.prevFrame2Fd= -1;
sink->soc.nextFrameFd= -1;
if ( sink->soc.videoPaused )
{
if ( sink->soc.pauseGfxBuffIndex >= 0 )
{
LOCK(sink);
if ( wstUnlockOutputBuffer( sink, sink->soc.pauseGfxBuffIndex ) )
{
wstRequeueOutputBuffer( sink, sink->soc.pauseGfxBuffIndex );
}
sink->soc.pauseGfxBuffIndex= -1;
UNLOCK(sink);
}
}
sink->soc.framesBeforeHideGfx= sink->soc.hideGfxFramesDelay;
}
if ( needBounds(sink) && sink->vpcSurface )
{
/* Use nominal display size provided to us by
* the compositor to calculate the video bounds
* we should use when we transition to graphics path.
* Save and restore current HW video rectangle. */
int vx, vy, vw, vh;
int tx, ty, tw, th;
tx= sink->soc.videoX;
ty= sink->soc.videoY;
tw= sink->soc.videoWidth;
th= sink->soc.videoHeight;
sink->soc.videoX= sink->windowX;
sink->soc.videoY= sink->windowY;
sink->soc.videoWidth= sink->windowWidth;
sink->soc.videoHeight= sink->windowHeight;
wstGetVideoBounds( sink, &vx, &vy, &vw, &vh );
wstSetTextureCrop( sink, vx, vy, vw, vh );
sink->soc.videoX= tx;
sink->soc.videoY= ty;
sink->soc.videoWidth= tw;
sink->soc.videoHeight= th;
}
}
void gst_westeros_sink_soc_update_video_position( GstWesterosSink *sink )
{
if ( sink->windowSizeOverride )
{
sink->soc.videoX= ((sink->windowX*sink->scaleXNum)/sink->scaleXDenom) + sink->transX;
sink->soc.videoY= ((sink->windowY*sink->scaleYNum)/sink->scaleYDenom) + sink->transY;
sink->soc.videoWidth= (sink->windowWidth*sink->scaleXNum)/sink->scaleXDenom;
sink->soc.videoHeight= (sink->windowHeight*sink->scaleYNum)/sink->scaleYDenom;
}
else
{
sink->soc.videoX= sink->transX;
sink->soc.videoY= sink->transY;
sink->soc.videoWidth= (sink->outputWidth*sink->scaleXNum)/sink->scaleXDenom;
sink->soc.videoHeight= (sink->outputHeight*sink->scaleYNum)/sink->scaleYDenom;
}
if ( !sink->soc.captureEnabled )
{
/* Send a buffer to compositor to update hole punch geometry */
if ( sink->soc.sb )
{
struct wl_buffer *buff;
buff= wl_sb_create_buffer( sink->soc.sb,
0,
sink->windowWidth,
sink->windowHeight,
sink->windowWidth*4,
WL_SB_FORMAT_ARGB8888 );
wl_surface_attach( sink->surface, buff, sink->windowX, sink->windowY );
wl_surface_damage( sink->surface, 0, 0, sink->windowWidth, sink->windowHeight );
wl_surface_commit( sink->surface );
}
if ( sink->soc.videoPaused )
{
wstSendRectVideoClientConnection(sink->soc.conn);
}
}
}
gboolean gst_westeros_sink_soc_query( GstWesterosSink *sink, GstQuery *query )
{
WESTEROS_UNUSED(sink);
WESTEROS_UNUSED(query);
return FALSE;
}
static void wstSinkSocStopVideo( GstWesterosSink *sink )
{
LOCK(sink);
if ( sink->soc.conn )
{
wstDestroyVideoClientConnection( sink->soc.conn );
sink->soc.conn= 0;
}
if ( sink->soc.videoOutputThread || sink->soc.eosDetectionThread || sink->soc.dispatchThread )
{
sink->soc.quitVideoOutputThread= TRUE;
sink->soc.quitEOSDetectionThread= TRUE;
sink->soc.quitDispatchThread= TRUE;
if ( sink->display )
{
int fd= wl_display_get_fd( sink->display );
if ( fd >= 0 )
{
shutdown( fd, SHUT_RDWR );
}
}
wstStopEvents( sink );
wstTearDownInputBuffers( sink );
wstTearDownOutputBuffers( sink );
}
if ( sink->soc.v4l2Fd >= 0 )
{
int fdToClose= sink->soc.v4l2Fd;
sink->soc.v4l2Fd= -1;
close( fdToClose );
}
sink->soc.prevFrame1Fd= -1;
sink->soc.prevFrame2Fd= -1;
sink->soc.nextFrameFd= -1;
sink->soc.formatsSet= FALSE;
sink->soc.frameWidth= -1;
sink->soc.frameHeight= -1;
sink->soc.frameWidthStream= -1;
sink->soc.frameHeightStream= -1;
sink->soc.frameAdvance= FALSE;
sink->soc.frameRate= 0.0;
sink->soc.frameRateFractionNum= 0;
sink->soc.frameRateFractionDenom= 0;
sink->soc.pixelAspectRatio= 1.0;
wstFlushPixelAspectRatio( sink, true );
#ifdef USE_GST_AFD
wstFlushAFDInfo( sink, true );
#endif
sink->soc.havePixelAspectRatio= FALSE;
sink->soc.pauseGfxBuffIndex= -1;
sink->soc.syncType= -1;
sink->soc.haveColorimetry= FALSE;
sink->soc.haveMasteringDisplay= FALSE;
sink->soc.haveContentLightLevel= FALSE;
sink->soc.emitFirstFrameSignal= FALSE;
sink->soc.emitUnderflowSignal= FALSE;
sink->soc.decodeError= FALSE;
if ( sink->soc.inputFormats )
{
free( sink->soc.inputFormats );
sink->soc.inputFormats= 0;
}
if ( sink->soc.outputFormats )
{
free( sink->soc.outputFormats );
sink->soc.outputFormats= 0;
}
sink->videoStarted= FALSE;
UNLOCK(sink);
if ( sink->soc.videoOutputThread )
{
sink->soc.quitVideoOutputThread= TRUE;
g_thread_join( sink->soc.videoOutputThread );
sink->soc.videoOutputThread= NULL;
}
if ( sink->soc.eosDetectionThread )
{
sink->soc.quitEOSDetectionThread= TRUE;
g_thread_join( sink->soc.eosDetectionThread );
sink->soc.eosDetectionThread= NULL;
}
if ( sink->soc.dispatchThread )
{
sink->soc.quitDispatchThread= TRUE;
g_thread_join( sink->soc.dispatchThread );
sink->soc.dispatchThread= NULL;
}
LOCK(sink);
if ( sink->soc.sb )
{
wl_sb_destroy( sink->soc.sb );
sink->soc.sb= 0;
}
UNLOCK(sink);
}
static void wstBuildSinkCaps( GstWesterosSinkClass *klass, GstWesterosSink *dummySink )
{
GstCaps *caps= 0;
GstCaps *capsTemp= 0;
GstPadTemplate *padTemplate= 0;
int i;
caps= gst_caps_new_empty();
if ( caps )
{
for( i= 0; i < dummySink->soc.numInputFormats; ++i )
{
switch( dummySink->soc.inputFormats[i].pixelformat )
{
case V4L2_PIX_FMT_MPEG:
capsTemp= gst_caps_from_string(
"video/mpeg, " \
"systemstream = (boolean) true ; "
);
break;
case V4L2_PIX_FMT_MPEG1:
capsTemp= gst_caps_from_string(
"video/mpeg, " \
"mpegversion=(int) 1, " \
"parsed=(boolean) true, " \
"systemstream = (boolean) false ; "
);
break;
case V4L2_PIX_FMT_MPEG2:
capsTemp= gst_caps_from_string(
"video/mpeg, " \
"mpegversion=(int) 2, " \
"parsed=(boolean) true, " \
"systemstream = (boolean) false ; "
);
break;
case V4L2_PIX_FMT_MPEG4:
capsTemp= gst_caps_from_string(
"video/mpeg, " \
"mpegversion=(int) 4, " \
"parsed=(boolean) true, " \
"systemstream = (boolean) false ; "
);
break;
case V4L2_PIX_FMT_H264:
capsTemp= gst_caps_from_string(
"video/x-h264, " \
"parsed=(boolean) true, " \
"alignment=(string) au, " \
"stream-format=(string) byte-stream, " \
"width=(int) [1,MAX], " "height=(int) [1,MAX] ; " \
"video/x-h264(memory:DMABuf) ; "
);
break;
#ifdef V4L2_PIX_FMT_VP9
case V4L2_PIX_FMT_VP9:
capsTemp= gst_caps_from_string(
"video/x-vp9, " \
"width=(int) [1,MAX], " \
"height=(int) [1,MAX] ; " \
"video/x-vp9(memory:DMABuf) ; "
);
break;
#endif
#ifdef V4L2_PIX_FMT_AV1
case V4L2_PIX_FMT_AV1:
capsTemp= gst_caps_from_string(
"video/x-av1, " \
"width=(int) [1,MAX], " \
"height=(int) [1,MAX] ; " \
"video/x-av1(memory:DMABuf) ; "
);
#ifdef ENABLE_AV1_DOLBYVISION
gst_caps_append( caps, capsTemp );
capsTemp= 0;
capsTemp= gst_caps_from_string(
"video/x-gst-fourcc-dav1, " \
"width=(int) [1,MAX], " \
"height=(int) [1,MAX] ; " \
"video/x-gst-fourcc-dav1(memory:DMABuf) ; "
);
#endif
break;
#endif
#ifdef V4L2_PIX_FMT_HEVC
case V4L2_PIX_FMT_HEVC:
capsTemp= gst_caps_from_string(
"video/x-h265, " \
"parsed=(boolean) true, " \
"alignment=(string) au, " \
"stream-format=(string) byte-stream, " \
"width=(int) [1,MAX], " \
"height=(int) [1,MAX] ; " \
"video/x-h265(memory:DMABuf) ; "
);
break;
#endif
default:
break;
}
if ( capsTemp )
{
gst_caps_append( caps, capsTemp );
capsTemp =0;
}
}
padTemplate= gst_pad_template_new( "sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
caps );
if ( padTemplate )
{
GstElementClass *gstelement_class= (GstElementClass *)klass;
gst_element_class_add_pad_template(gstelement_class, padTemplate);
padTemplate= 0;
}
else
{
GST_ERROR("wstBuildSinkCaps: gst_pad_template_new failed");
}
gst_caps_unref( caps );
}
else
{
GST_ERROR("wstBuildSinkCaps: gst_caps_new_empty failed");
}
}
static void wstDiscoverVideoDecoder( GstWesterosSinkClass *klass )
{
int rc, len, i, fd;
bool acceptsCompressed;
GstWesterosSink dummySink;
struct v4l2_exportbuffer eb;
struct dirent *dirent;
memset( &dummySink, 0, sizeof(dummySink) );
DIR *dir= opendir("/dev");
if ( dir )
{
for( ; ; )
{
fd= -1;
dirent= readdir( dir );
if ( dirent == 0 ) break;
len= strlen(dirent->d_name);
if ( (len == 1) && !strncmp( dirent->d_name, ".", len) )
{
continue;
}
else if ( (len == 2) && !strncmp( dirent->d_name, "..", len) )
{
continue;
}
if ( (len > 5) && !strncmp( dirent->d_name, "video", 5 ) )
{
char name[256+10];
struct v4l2_capability caps;
uint32_t deviceCaps;
strcpy( name, "/dev/" );
strcat( name, dirent->d_name );
GST_DEBUG("checking device: %s", name);
fd= open( name, O_RDWR | O_CLOEXEC );
if ( fd < 0 )
{
goto done_check;
}
rc= IOCTL( fd, VIDIOC_QUERYCAP, &caps );
if ( rc < 0 )
{
goto done_check;
}
deviceCaps= (caps.capabilities & V4L2_CAP_DEVICE_CAPS ) ? caps.device_caps : caps.capabilities;
if ( !(deviceCaps & (V4L2_CAP_VIDEO_M2M | V4L2_CAP_VIDEO_M2M_MPLANE) ))
{
goto done_check;
}
if ( !(deviceCaps & V4L2_CAP_STREAMING) )
{
goto done_check;
}
eb.type= V4L2_BUF_TYPE_VIDEO_CAPTURE;
eb.index= -1;
eb.plane= -1;
eb.flags= (O_RDWR|O_CLOEXEC);
IOCTL( fd, VIDIOC_EXPBUF, &eb );
if ( errno == ENOTTY )
{
goto done_check;
}
dummySink.soc.v4l2Fd= fd;
if ( (deviceCaps & V4L2_CAP_VIDEO_M2M_MPLANE) && !(deviceCaps & V4L2_CAP_VIDEO_M2M) )
{
dummySink.soc.isMultiPlane= TRUE;
}
wstGetInputFormats( &dummySink );
acceptsCompressed= false;
for( i= 0; i < dummySink.soc.numInputFormats; ++i)
{
if ( dummySink.soc.inputFormats[i].flags & V4L2_FMT_FLAG_COMPRESSED )
{
acceptsCompressed= true;
wstBuildSinkCaps( klass, &dummySink );
break;
}
}
if ( dummySink.soc.inputFormats )
{
free( dummySink.soc.inputFormats );
}
dummySink.soc.numInputFormats;
if ( !acceptsCompressed )
{
goto done_check;
}
gDeviceName= strdup(name );
printf("westeros-sink: discover decoder: %s\n", gDeviceName);
close( fd );
break;
done_check:
if ( fd >= 0 )
{
close( fd );
fd= -1;
}
}
}
closedir( dir );
}
}
static void wstStartEvents( GstWesterosSink *sink )
{
int rc;
struct v4l2_event_subscription evtsub;
memset( &evtsub, 0, sizeof(evtsub));
evtsub.type= V4L2_EVENT_SOURCE_CHANGE;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_SUBSCRIBE_EVENT, &evtsub );
if ( rc == 0 )
{
sink->soc.hasEvents= TRUE;
}
else
{
GST_ERROR("wstStartEvents: event subscribe failed rc %d (errno %d)", rc, errno);
}
memset( &evtsub, 0, sizeof(evtsub));
evtsub.type= V4L2_EVENT_EOS;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_SUBSCRIBE_EVENT, &evtsub );
if ( rc == 0 )
{
sink->soc.hasEOSEvents= TRUE;
}
else
{
GST_ERROR("wstStartEvents: event subcribe for eos failed rc %d (errno %d)", rc, errno );
}
}
static void wstStopEvents( GstWesterosSink *sink )
{
int rc;
struct v4l2_event_subscription evtsub;
memset( &evtsub, 0, sizeof(evtsub));
evtsub.type= V4L2_EVENT_ALL;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_UNSUBSCRIBE_EVENT, &evtsub );
if ( rc != 0 )
{
GST_ERROR("wstStopEvents: event unsubscribe failed rc %d (errno %d)", rc, errno);
}
}
static void wstProcessEvents( GstWesterosSink *sink )
{
int rc;
struct v4l2_event event;
LOCK(sink);
for( ; ; )
{
memset( &event, 0, sizeof(event));
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_DQEVENT, &event );
if ( rc == 0 )
{
if ( (event.type == V4L2_EVENT_SOURCE_CHANGE) &&
(event.u.src_change.changes & V4L2_EVENT_SRC_CH_RESOLUTION) )
{
struct v4l2_format fmtIn, fmtOut;
int32_t bufferType;
avProgLog( 0, 0, "DtoS", "source change start");
g_print("westeros-sink: source change event\n");
memset( &fmtIn, 0, sizeof(fmtIn));
bufferType= (sink->soc.isMultiPlane ? V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE : V4L2_BUF_TYPE_VIDEO_OUTPUT);
fmtIn.type= bufferType;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_G_FMT, &fmtIn );
if ( (sink->soc.isMultiPlane && fmtIn.fmt.pix_mp.field == V4L2_FIELD_INTERLACED) ||
(!sink->soc.isMultiPlane && fmtIn.fmt.pix.field == V4L2_FIELD_INTERLACED) )
{
if ( !sink->soc.interlaced )
{
GST_DEBUG("v4l2 driver indicates content is interlaced, but caps did not : using interlaced");
}
sink->soc.interlaced= TRUE;
}
GST_DEBUG("source is interlaced: %d", sink->soc.interlaced);
memset( &fmtOut, 0, sizeof(fmtOut));
bufferType= (sink->soc.isMultiPlane ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE : V4L2_BUF_TYPE_VIDEO_CAPTURE);
fmtOut.type= bufferType;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_G_FMT, &fmtOut );
if ( (sink->soc.numBuffersOut == 0) ||
(sink->soc.isMultiPlane &&
( (fmtOut.fmt.pix_mp.width != sink->soc.fmtOut.fmt.pix_mp.width) ||
(fmtOut.fmt.pix_mp.height != sink->soc.fmtOut.fmt.pix_mp.height) ) ) ||
(!sink->soc.isMultiPlane &&
( (fmtOut.fmt.pix.width != sink->soc.fmtOut.fmt.pix.width) ||
(fmtOut.fmt.pix.height != sink->soc.fmtOut.fmt.pix.height) ) ) ||
(sink->soc.frameOutCount > 0) )
{
int vx, vy, vw, vh;
wstTearDownOutputBuffers( sink );
if ( sink->soc.isMultiPlane )
{
sink->soc.frameWidth= fmtOut.fmt.pix_mp.width;
sink->soc.frameHeight= fmtOut.fmt.pix_mp.height;
}
else
{
sink->soc.frameWidth= fmtOut.fmt.pix.width;
sink->soc.frameHeight= fmtOut.fmt.pix.height;
}
#ifdef WESTEROS_SINK_SVP
wstSVPSetInputMemMode( sink, sink->soc.inputMemMode );
#endif
wstSetupOutput( sink );
if ( sink->soc.havePixelAspectRatio )
{
sink->soc.pixelAspectRatioChanged= TRUE;
sink->soc.pixelAspectRatio= wstPopPixelAspectRatio( sink );
}
if ( needBounds(sink) && sink->vpcSurface )
{
wstGetVideoBounds( sink, &vx, &vy, &vw, &vh );
wstSetTextureCrop( sink, vx, vy, vw, vh );
}
sink->soc.nextFrameFd= -1;
sink->soc.prevFrame1Fd= -1;
sink->soc.prevFrame2Fd= -1;
sink->soc.needCaptureRestart= TRUE;
}
}
else if ( event.type == V4L2_EVENT_EOS )
{
g_print("westeros-sink: v4l2 eos event\n");
sink->soc.decoderEOS= 1;
}
if ( event.pending < 1 )
{
break;
}
}
else
{
break;
}
}
UNLOCK(sink);
}
static void wstGetMaxFrameSize( GstWesterosSink *sink )
{
struct v4l2_frmsizeenum framesize;
int rc;
int maxWidth= 0, maxHeight= 0;
memset( &framesize, 0, sizeof(struct v4l2_frmsizeenum) );
framesize.index= 0;
framesize.pixel_format= ((sink->soc.inputFormat != 0) ? sink->soc.inputFormat : V4L2_PIX_FMT_H264);
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_ENUM_FRAMESIZES, &framesize);
if ( rc == 0 )
{
if ( framesize.type == V4L2_FRMSIZE_TYPE_DISCRETE )
{
maxWidth= framesize.discrete.width;
maxHeight= framesize.discrete.height;
while ( rc == 0 )
{
++framesize.index;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_ENUM_FRAMESIZES, &framesize);
if ( rc == 0 )
{
if ( framesize.discrete.width > maxWidth )
{
maxWidth= framesize.discrete.width;
}
if ( framesize.discrete.height > maxHeight )
{
maxHeight= framesize.discrete.height;
}
}
else
{
break;
}
}
}
else if ( framesize.type == V4L2_FRMSIZE_TYPE_STEPWISE )
{
maxWidth= framesize.stepwise.max_width;
maxHeight= framesize.stepwise.max_height;
}
}
else
{
GST_ERROR("wstGetMaxFrameSize: VIDIOC_ENUM_FRAMESIZES error %d", rc);
maxWidth= 1920;
maxHeight= 1080;
}
if ( (maxWidth > 0) && (maxHeight > 0) )
{
g_print("westeros-sink: max frame (%dx%d)\n", maxWidth, maxHeight);
sink->maxWidth= maxWidth;
sink->maxHeight= maxHeight;
}
}
static bool wstGetInputFormats( GstWesterosSink *sink )
{
bool result= false;
struct v4l2_fmtdesc format;
int i, rc;
int32_t bufferType;
bufferType= (sink->soc.isMultiPlane ? V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE : V4L2_BUF_TYPE_VIDEO_OUTPUT);
i= 0;
for( ; ; )
{
format.index= i;
format.type= bufferType;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_ENUM_FMT, &format);
if ( rc < 0 )
{
if ( errno == EINVAL )
{
GST_DEBUG("Found %d input formats", i);
sink->soc.numInputFormats= i;
break;
}
goto exit;
}
++i;
}
sink->soc.inputFormats= (struct v4l2_fmtdesc*)calloc( sink->soc.numInputFormats, sizeof(struct v4l2_format) );
if ( !sink->soc.inputFormats )
{
GST_ERROR("getInputFormats: no memory for inputFormats");
sink->soc.numInputFormats= 0;
goto exit;
}
for( i= 0; i < sink->soc.numInputFormats; ++i)
{
sink->soc.inputFormats[i].index= i;
sink->soc.inputFormats[i].type= bufferType;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_ENUM_FMT, &sink->soc.inputFormats[i]);
if ( rc < 0 )
{
goto exit;
}
GST_DEBUG("input format %d: flags %08x pixelFormat: %x desc: %s",
i, sink->soc.inputFormats[i].flags, sink->soc.inputFormats[i].pixelformat, sink->soc.inputFormats[i].description );
}
result= true;
exit:
return result;
}
static bool wstGetOutputFormats( GstWesterosSink *sink )
{
bool result= false;
struct v4l2_fmtdesc format;
int i, rc;
int32_t bufferType;
bool haveNV12= false;
bufferType= (sink->soc.isMultiPlane ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE : V4L2_BUF_TYPE_VIDEO_CAPTURE);
i= 0;
for( ; ; )
{
format.index= i;
format.type= bufferType;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_ENUM_FMT, &format);
if ( rc < 0 )
{
if ( errno == EINVAL )
{
GST_DEBUG("Found %d output formats", i);
sink->soc.numOutputFormats= i;
break;
}
goto exit;
}
++i;
}
sink->soc.outputFormats= (struct v4l2_fmtdesc*)calloc( sink->soc.numOutputFormats, sizeof(struct v4l2_format) );
if ( !sink->soc.outputFormats )
{
GST_DEBUG("getOutputFormats: no memory for outputFormats");
sink->soc.numOutputFormats= 0;
goto exit;
}
for( i= 0; i < sink->soc.numOutputFormats; ++i)
{
sink->soc.outputFormats[i].index= i;
sink->soc.outputFormats[i].type= bufferType;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_ENUM_FMT, &sink->soc.outputFormats[i]);
if ( rc < 0 )
{
goto exit;
}
if ( (sink->soc.outputFormats[i].pixelformat == V4L2_PIX_FMT_NV12) ||
(sink->soc.outputFormats[i].pixelformat == V4L2_PIX_FMT_NV12M) )
{
haveNV12= true;
}
GST_DEBUG("output format %d: flags %08x pixelFormat: %x desc: %s",
i, sink->soc.outputFormats[i].flags, sink->soc.outputFormats[i].pixelformat, sink->soc.outputFormats[i].description );
}
if ( !haveNV12 )
{
GST_WARNING("no support for NV12/NV12M output detected");
}
result= true;
exit:
return result;
}
static bool wstSetInputFormat( GstWesterosSink *sink )
{
bool result= false;
int rc;
int32_t bufferType;
int bufferSize;
bufferType= (sink->soc.isMultiPlane ? V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE : V4L2_BUF_TYPE_VIDEO_OUTPUT);
if (sink->soc.lowMemoryMode)
{
bufferSize= 1*1024*1024;
}
else
{
bufferSize= 4*1024*1024;
}
memset( &sink->soc.fmtIn, 0, sizeof(struct v4l2_format) );
sink->soc.fmtIn.type= bufferType;
if ( sink->soc.frameWidthStream != -1 )
{
sink->soc.frameWidth= sink->soc.frameWidthStream;
}
if ( sink->soc.frameHeightStream != -1 )
{
sink->soc.frameHeight= sink->soc.frameHeightStream;
}
if ( sink->soc.isMultiPlane )
{
sink->soc.fmtIn.fmt.pix_mp.pixelformat= sink->soc.inputFormat;
sink->soc.fmtIn.fmt.pix_mp.width= sink->soc.frameWidth;
sink->soc.fmtIn.fmt.pix_mp.height= sink->soc.frameHeight;
sink->soc.fmtIn.fmt.pix_mp.num_planes= 1;
sink->soc.fmtIn.fmt.pix_mp.plane_fmt[0].sizeimage= bufferSize;
sink->soc.fmtIn.fmt.pix_mp.plane_fmt[0].bytesperline= 0;
sink->soc.fmtIn.fmt.pix_mp.field= V4L2_FIELD_NONE;
}
else
{
sink->soc.fmtIn.fmt.pix.pixelformat= sink->soc.inputFormat;
sink->soc.fmtIn.fmt.pix.width= sink->soc.frameWidth;
sink->soc.fmtIn.fmt.pix.height= sink->soc.frameHeight;
sink->soc.fmtIn.fmt.pix.sizeimage= bufferSize;
sink->soc.fmtIn.fmt.pix.field= V4L2_FIELD_NONE;
}
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_S_FMT, &sink->soc.fmtIn );
if ( rc < 0 )
{
GST_DEBUG("wstSetInputFormat: failed to set format for input: rc %d errno %d", rc, errno);
goto exit;
}
result= true;
exit:
return result;
}
static bool wstSetOutputFormat( GstWesterosSink *sink )
{
bool result= false;
int rc;
int32_t bufferType;
bufferType= (sink->soc.isMultiPlane ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE : V4L2_BUF_TYPE_VIDEO_CAPTURE);
memset( &sink->soc.fmtOut, 0, sizeof(struct v4l2_format) );
sink->soc.fmtOut.type= bufferType;
/* Get current settings from driver */
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_G_FMT, &sink->soc.fmtOut );
if ( rc < 0 )
{
GST_DEBUG("wstSetOutputFormat: initV4l2: failed get format for output: rc %d errno %d", rc, errno);
}
if ( sink->soc.isMultiPlane )
{
int i;
uint32_t pixelFormat= V4L2_PIX_FMT_NV12;
if ( sink->soc.preferNV12M )
{
for( i= 0; i < sink->soc.numOutputFormats; ++i)
{
if ( sink->soc.outputFormats[i].pixelformat == V4L2_PIX_FMT_NV12M )
{
pixelFormat= V4L2_PIX_FMT_NV12M;
break;
}
}
}
if ( pixelFormat == V4L2_PIX_FMT_NV12 )
{
sink->soc.fmtOut.fmt.pix_mp.num_planes= 1;
}
else
{
sink->soc.fmtOut.fmt.pix_mp.num_planes= 2;
}
if ( sink->soc.frameWidthStream != -1 )
{
sink->soc.frameWidth= sink->soc.frameWidthStream;
}
if ( sink->soc.frameHeightStream != -1 )
{
sink->soc.frameHeight= sink->soc.frameHeightStream;
}
sink->soc.fmtOut.fmt.pix_mp.pixelformat= pixelFormat;
sink->soc.fmtOut.fmt.pix_mp.width= sink->soc.frameWidth;
sink->soc.fmtOut.fmt.pix_mp.height= sink->soc.frameHeight;
sink->soc.fmtOut.fmt.pix_mp.plane_fmt[0].sizeimage= sink->soc.frameWidth*sink->soc.frameHeight;
sink->soc.fmtOut.fmt.pix_mp.plane_fmt[0].bytesperline= sink->soc.frameWidth;
sink->soc.fmtOut.fmt.pix_mp.plane_fmt[1].sizeimage= sink->soc.frameWidth*sink->soc.frameHeight/2;
sink->soc.fmtOut.fmt.pix_mp.plane_fmt[1].bytesperline= sink->soc.frameWidth;
sink->soc.fmtOut.fmt.pix_mp.field= V4L2_FIELD_ANY;
}
else
{
sink->soc.fmtOut.fmt.pix.pixelformat= V4L2_PIX_FMT_NV12;
sink->soc.fmtOut.fmt.pix.width= sink->soc.frameWidth;
sink->soc.fmtOut.fmt.pix.height= sink->soc.frameHeight;
sink->soc.fmtOut.fmt.pix.sizeimage= (sink->soc.fmtOut.fmt.pix.width*sink->soc.fmtOut.fmt.pix.height*3)/2;
sink->soc.fmtOut.fmt.pix.field= V4L2_FIELD_ANY;
}
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_S_FMT, &sink->soc.fmtOut );
if ( rc < 0 )
{
GST_DEBUG("wstSetOutputFormat: initV4l2: failed to set format for output: rc %d errno %d", rc, errno);
goto exit;
}
result= true;
exit:
return result;
}
static bool wstSetupInputBuffers( GstWesterosSink *sink )
{
bool result= false;
int rc, neededBuffers;
struct v4l2_control ctl;
struct v4l2_requestbuffers reqbuf;
struct v4l2_buffer *bufIn;
void *bufStart;
int32_t bufferType;
uint32_t memOffset, memLength, memBytesUsed;
int i, j;
bufferType= (sink->soc.isMultiPlane ? V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE : V4L2_BUF_TYPE_VIDEO_OUTPUT);
neededBuffers= NUM_INPUT_BUFFERS;
memset( &ctl, 0, sizeof(ctl));
ctl.id= V4L2_CID_MIN_BUFFERS_FOR_OUTPUT;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_G_CTRL, &ctl );
if ( rc == 0 )
{
sink->soc.minBuffersIn= ctl.value;
if ( sink->soc.minBuffersIn != 0 )
{
neededBuffers= sink->soc.minBuffersIn;
}
}
if ( sink->soc.minBuffersIn == 0 )
{
sink->soc.minBuffersIn= MIN_INPUT_BUFFERS;
}
memset( &reqbuf, 0, sizeof(reqbuf) );
reqbuf.count= neededBuffers;
reqbuf.type= bufferType;
reqbuf.memory= sink->soc.inputMemMode;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_REQBUFS, &reqbuf );
if ( rc < 0 )
{
GST_ERROR("wstSetupInputBuffers: failed to request %d mmap buffers for input: rc %d errno %d", neededBuffers, rc, errno);
goto exit;
}
sink->soc.numBuffersIn= reqbuf.count;
if ( reqbuf.count < sink->soc.minBuffersIn )
{
GST_ERROR("wstSetupInputBuffers: insufficient buffers: (%d versus %d)", reqbuf.count, neededBuffers );
goto exit;
}
sink->soc.inBuffers= (WstBufferInfo*)calloc( reqbuf.count, sizeof(WstBufferInfo) );
if ( !sink->soc.inBuffers )
{
GST_ERROR("wstSetupInputBuffers: no memory for WstBufferInfo" );
goto exit;
}
for( i= 0; i < reqbuf.count; ++i )
{
bufIn= &sink->soc.inBuffers[i].buf;
bufIn->type= bufferType;
bufIn->index= i;
bufIn->memory= sink->soc.inputMemMode;
if ( sink->soc.isMultiPlane )
{
memset( sink->soc.inBuffers[i].planes, 0, sizeof(struct v4l2_plane)*WST_MAX_PLANES);
bufIn->m.planes= sink->soc.inBuffers[i].planes;
bufIn->length= 3;
}
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_QUERYBUF, bufIn );
if ( rc < 0 )
{
GST_ERROR("wstSetupInputBuffers: failed to query input buffer %d: rc %d errno %d", i, rc, errno);
goto exit;
}
if ( sink->soc.inputMemMode == V4L2_MEMORY_MMAP )
{
if ( sink->soc.isMultiPlane )
{
if ( bufIn->length != 1 )
{
GST_ERROR("wstSetupInputBuffers: num planes expected to be 1 for compressed input but is %d", bufIn->length);
goto exit;
}
sink->soc.inBuffers[i].planeCount= 0;
memOffset= bufIn->m.planes[0].m.mem_offset;
memLength= bufIn->m.planes[0].length;
memBytesUsed= bufIn->m.planes[0].bytesused;
}
else
{
memOffset= bufIn->m.offset;
memLength= bufIn->length;
memBytesUsed= bufIn->bytesused;
}
bufStart= mmap( NULL,
memLength,
PROT_READ | PROT_WRITE,
MAP_SHARED,
sink->soc.v4l2Fd,
memOffset );
if ( bufStart == MAP_FAILED )
{
GST_ERROR("wstSetupInputBuffers: failed to mmap input buffer %d: errno %d", i, errno);
goto exit;
}
GST_DEBUG("Input buffer: %d", i);
GST_DEBUG(" index: %d start: %p bytesUsed %d offset %d length %d flags %08x",
bufIn->index, bufStart, memBytesUsed, memOffset, memLength, bufIn->flags );
sink->soc.inBuffers[i].start= bufStart;
sink->soc.inBuffers[i].capacity= memLength;
}
else if ( sink->soc.inputMemMode == V4L2_MEMORY_DMABUF )
{
for ( j= 0; j < WST_MAX_PLANES; ++j )
{
sink->soc.inBuffers[i].planes[j].m.fd= -1;
}
}
sink->soc.inBuffers[i].fd= -1;
}
result= true;
exit:
if ( !result )
{
wstTearDownInputBuffers( sink );
}
return result;
}
static void wstTearDownInputBuffers( GstWesterosSink *sink )
{
int rc, i;
struct v4l2_requestbuffers reqbuf;
int32_t bufferType;
bufferType= (sink->soc.isMultiPlane ? V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE : V4L2_BUF_TYPE_VIDEO_OUTPUT);
if ( sink->soc.inBuffers )
{
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_STREAMOFF, &sink->soc.fmtIn.type );
if ( rc < 0 )
{
GST_ERROR("wstTearDownInputBuffers: streamoff failed for input: rc %d errno %d", rc, errno );
}
for( i= 0; i < sink->soc.numBuffersIn; ++i )
{
if ( sink->soc.inBuffers[i].start )
{
munmap( sink->soc.inBuffers[i].start, sink->soc.inBuffers[i].capacity );
}
#ifdef USE_GST_ALLOCATORS
if ( sink->soc.inBuffers[i].gstbuf )
{
gst_buffer_unref( sink->soc.inBuffers[i].gstbuf );
sink->soc.inBuffers[i].gstbuf= 0;
}
#endif
}
free( sink->soc.inBuffers );
sink->soc.inBuffers= 0;
sink->soc.inQueuedCount= 0;
}
if ( sink->soc.numBuffersIn )
{
memset( &reqbuf, 0, sizeof(reqbuf) );
reqbuf.count= 0;
reqbuf.type= bufferType;
reqbuf.memory= sink->soc.inputMemMode;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_REQBUFS, &reqbuf );
if ( rc < 0 )
{
GST_ERROR("wstTearDownInputBuffers: failed to release v4l2 buffers for input: rc %d errno %d", rc, errno);
}
sink->soc.numBuffersIn= 0;
}
}
static bool wstSetupOutputBuffers( GstWesterosSink *sink )
{
bool result= false;
int rc, neededBuffers;
struct v4l2_control ctl;
struct v4l2_requestbuffers reqbuf;
int32_t bufferType;
int i, j;
bufferType= (sink->soc.isMultiPlane ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE : V4L2_BUF_TYPE_VIDEO_CAPTURE);
neededBuffers= NUM_OUTPUT_BUFFERS;
memset( &ctl, 0, sizeof(ctl));
ctl.id= V4L2_CID_MIN_BUFFERS_FOR_CAPTURE;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_G_CTRL, &ctl );
if ( rc == 0 )
{
sink->soc.minBuffersOut= ctl.value;
if ( (sink->soc.minBuffersOut != 0) && (sink->soc.minBuffersOut > NUM_OUTPUT_BUFFERS) )
{
neededBuffers= sink->soc.minBuffersOut+1;
}
}
if ( sink->soc.minBuffersOut == 0 )
{
sink->soc.minBuffersOut= MIN_OUTPUT_BUFFERS;
}
memset( &reqbuf, 0, sizeof(reqbuf) );
reqbuf.count= neededBuffers;
reqbuf.type= bufferType;
reqbuf.memory= sink->soc.outputMemMode;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_REQBUFS, &reqbuf );
if ( rc < 0 )
{
GST_ERROR("wstSetupOutputBuffers: failed to request %d mmap buffers for output: rc %d errno %d", neededBuffers, rc, errno);
goto exit;
}
sink->soc.numBuffersOut= reqbuf.count;
if ( reqbuf.count < sink->soc.minBuffersOut )
{
GST_ERROR("wstSetupOutputBuffers: insufficient buffers: (%d versus %d)", reqbuf.count, neededBuffers );
goto exit;
}
sink->soc.outBuffers= (WstBufferInfo*)calloc( reqbuf.count, sizeof(WstBufferInfo) );
if ( !sink->soc.outBuffers )
{
GST_ERROR("wstSetupOutputBuffers: no memory for WstBufferInfo" );
goto exit;
}
for( i= 0; i < reqbuf.count; ++i )
{
sink->soc.outBuffers[i].bufferId= sink->soc.bufferIdOutBase+i;
sink->soc.outBuffers[i].fd= -1;
for( j= 0; j < 3; ++j )
{
sink->soc.outBuffers[i].planeInfo[j].fd= -1;
}
}
if ( sink->soc.outputMemMode == V4L2_MEMORY_DMABUF )
{
result= wstSetupOutputBuffersDmabuf( sink );
}
else if ( sink->soc.outputMemMode == V4L2_MEMORY_MMAP )
{
result= wstSetupOutputBuffersMMap( sink );
}
else
{
GST_ERROR("Unsupported memory mode for output: %d", sink->soc.outputMemMode );
}
result= true;
exit:
if ( !result )
{
wstTearDownOutputBuffers( sink );
}
return result;
}
static bool wstSetupOutputBuffersMMap( GstWesterosSink *sink )
{
bool result= false;
int32_t bufferType;
struct v4l2_buffer *bufOut;
struct v4l2_exportbuffer expbuf;
void *bufStart;
int rc, i, j;
bufferType= (sink->soc.isMultiPlane ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE : V4L2_BUF_TYPE_VIDEO_CAPTURE);
for( i= 0; i < sink->soc.numBuffersOut; ++i )
{
bufOut= &sink->soc.outBuffers[i].buf;
bufOut->type= bufferType;
bufOut->index= i;
bufOut->memory= sink->soc.outputMemMode;
if ( sink->soc.isMultiPlane )
{
memset( sink->soc.outBuffers[i].planes, 0, sizeof(struct v4l2_plane)*WST_MAX_PLANES);
bufOut->m.planes= sink->soc.outBuffers[i].planes;
bufOut->length= sink->soc.fmtOut.fmt.pix_mp.num_planes;
}
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_QUERYBUF, bufOut );
if ( rc < 0 )
{
GST_ERROR("wstSetupOutputBuffers: failed to query input buffer %d: rc %d errno %d", i, rc, errno);
goto exit;
}
if ( sink->soc.isMultiPlane )
{
sink->soc.outBuffers[i].planeCount= bufOut->length;
for( j= 0; j < sink->soc.outBuffers[i].planeCount; ++j )
{
GST_DEBUG("Output buffer: %d", i);
GST_DEBUG(" index: %d bytesUsed %d offset %d length %d flags %08x",
bufOut->index, bufOut->m.planes[j].bytesused, bufOut->m.planes[j].m.mem_offset, bufOut->m.planes[j].length, bufOut->flags );
memset( &expbuf, 0, sizeof(expbuf) );
expbuf.type= bufOut->type;
expbuf.index= i;
expbuf.plane= j;
expbuf.flags= O_CLOEXEC;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_EXPBUF, &expbuf );
if ( rc < 0 )
{
GST_ERROR("wstSetupOutputBuffers: failed to export v4l2 output buffer %d: plane: %d rc %d errno %d", i, j, rc, errno);
}
GST_DEBUG(" plane %d index %d export fd %d", j, expbuf.index, expbuf.fd );
sink->soc.outBuffers[i].planeInfo[j].fd= expbuf.fd;
sink->soc.outBuffers[i].planeInfo[j].capacity= bufOut->m.planes[j].length;
if ( !sink->display )
{
bufStart= mmap( NULL,
bufOut->m.planes[j].length,
PROT_READ,
MAP_SHARED,
sink->soc.v4l2Fd,
bufOut->m.planes[j].m.mem_offset );
if ( bufStart != MAP_FAILED )
{
sink->soc.outBuffers[i].planeInfo[j].start= bufStart;
}
else
{
GST_ERROR("wstSetupOutputBuffers: failed to mmap input buffer %d: errno %d", i, errno);
}
}
}
/* Use fd of first plane to identify buffer */
sink->soc.outBuffers[i].fd= sink->soc.outBuffers[i].planeInfo[0].fd;
}
else
{
GST_DEBUG("Output buffer: %d", i);
GST_DEBUG(" index: %d bytesUsed %d offset %d length %d flags %08x",
bufOut->index, bufOut->bytesused, bufOut->m.offset, bufOut->length, bufOut->flags );
memset( &expbuf, 0, sizeof(expbuf) );
expbuf.type= bufOut->type;
expbuf.index= i;
expbuf.flags= O_CLOEXEC;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_EXPBUF, &expbuf );
if ( rc < 0 )
{
GST_ERROR("wstSetupOutputBuffers: failed to export v4l2 output buffer %d: rc %d errno %d", i, rc, errno);
}
GST_DEBUG(" index %d export fd %d", expbuf.index, expbuf.fd );
sink->soc.outBuffers[i].fd= expbuf.fd;
sink->soc.outBuffers[i].capacity= bufOut->length;
if ( !sink->display )
{
bufStart= mmap( NULL,
bufOut->length,
PROT_READ,
MAP_SHARED,
sink->soc.v4l2Fd,
bufOut->m.offset );
if ( bufStart != MAP_FAILED )
{
sink->soc.outBuffers[i].start= bufStart;
}
else
{
GST_ERROR("wstSetupOutputBuffers: failed to mmap input buffer %d: errno %d", i, errno);
}
}
}
}
exit:
return result;
}
static bool wstSetupOutputBuffersDmabuf( GstWesterosSink *sink )
{
bool result= false;
#ifdef WESTEROS_SINK_SVP
result= wstSVPSetupOutputBuffersDmabuf( sink );
#endif
return result;
}
static void wstTearDownOutputBuffers( GstWesterosSink *sink )
{
int rc;
struct v4l2_requestbuffers reqbuf;
int32_t bufferType;
++sink->soc.bufferCohort;
bufferType= (sink->soc.isMultiPlane ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE : V4L2_BUF_TYPE_VIDEO_CAPTURE);
if ( sink->soc.outBuffers )
{
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_STREAMOFF, &sink->soc.fmtOut.type );
if ( rc < 0 )
{
GST_ERROR("wstTearDownOutputBuffers: streamoff failed for output: rc %d errno %d", rc, errno );
}
sink->soc.bufferIdOutBase += sink->soc.numBuffersOut;
if ( sink->soc.outputMemMode == V4L2_MEMORY_DMABUF )
{
wstTearDownOutputBuffersDmabuf( sink );
}
else if ( sink->soc.outputMemMode == V4L2_MEMORY_MMAP )
{
wstTearDownOutputBuffersMMap( sink );
}
free( sink->soc.outBuffers );
sink->soc.outBuffers= 0;
sink->soc.outQueuedCount= 0;
}
if ( sink->soc.numBuffersOut )
{
memset( &reqbuf, 0, sizeof(reqbuf) );
reqbuf.count= 0;
reqbuf.type= bufferType;
reqbuf.memory= sink->soc.outputMemMode;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_REQBUFS, &reqbuf );
if ( rc < 0 )
{
GST_ERROR("wstTearDownOutputBuffers: failed to release v4l2 buffers for output: rc %d errno %d", rc, errno);
}
sink->soc.numBuffersOut= 0;
}
}
static void wstTearDownOutputBuffersDmabuf( GstWesterosSink *sink )
{
#ifdef WESTEROS_SINK_SVP
wstSVPTearDownOutputBuffersDmabuf( sink );
#endif
}
static void wstTearDownOutputBuffersMMap( GstWesterosSink *sink )
{
int i, j;
for( i= 0; i < sink->soc.numBuffersOut; ++i )
{
if ( sink->soc.outBuffers[i].planeCount )
{
for( j= 0; j < sink->soc.outBuffers[i].planeCount; ++j )
{
if ( sink->soc.outBuffers[i].planeInfo[j].fd >= 0 )
{
close( sink->soc.outBuffers[i].planeInfo[j].fd );
sink->soc.outBuffers[i].planeInfo[j].fd= -1;
}
if ( sink->soc.outBuffers[i].planeInfo[j].start )
{
munmap( sink->soc.outBuffers[i].planeInfo[j].start, sink->soc.outBuffers[i].planeInfo[j].capacity );
}
}
sink->soc.outBuffers[i].fd= -1;
sink->soc.outBuffers[i].planeCount= 0;
}
if ( sink->soc.outBuffers[i].start )
{
munmap( sink->soc.outBuffers[i].start, sink->soc.outBuffers[i].capacity );
}
if ( sink->soc.outBuffers[i].fd >= 0 )
{
close( sink->soc.outBuffers[i].fd );
sink->soc.outBuffers[i].fd= -1;
}
}
}
static void wstSetInputMemMode( GstWesterosSink *sink, int mode )
{
sink->soc.inputMemMode= mode;
}
static void wstSetupInput( GstWesterosSink *sink )
{
if ( sink->soc.formatsSet == FALSE )
{
if ( (sink->soc.frameWidth < 0) &&
(sink->soc.frameHeight < 0) &&
(sink->soc.hasEvents == TRUE) )
{
/* Set defaults and update on source change event */
sink->soc.frameWidth= sink->soc.frameWidthStream= DEFAULT_FRAME_WIDTH;
sink->soc.frameHeight= sink->soc.frameHeightStream= DEFAULT_FRAME_HEIGHT;
}
if ( (sink->soc.frameWidth > 0) &&
(sink->soc.frameHeight > 0) )
{
wstGetMaxFrameSize( sink );
#ifdef WESTEROS_SINK_SVP
wstSVPSetInputMemMode( sink, sink->soc.inputMemMode );
#endif
wstSetInputFormat( sink );
wstSetupInputBuffers( sink );
sink->soc.formatsSet= TRUE;
}
}
}
static int wstGetInputBuffer( GstWesterosSink *sink )
{
int bufferIndex= -1;
int i;
LOCK(sink);
if (!sink->soc.inBuffers)
{
UNLOCK(sink);
return bufferIndex;
}
for( i= 0; i < sink->soc.numBuffersIn; ++i )
{
if ( !sink->soc.inBuffers[i].queued )
{
bufferIndex= i;
break;
}
}
if ( bufferIndex < 0 )
{
int rc;
struct v4l2_buffer buf;
struct v4l2_plane planes[WST_MAX_PLANES];
memset( &buf, 0, sizeof(buf));
buf.type= sink->soc.fmtIn.type;
buf.memory= sink->soc.inputMemMode;
if ( sink->soc.isMultiPlane )
{
buf.length= 1;
buf.m.planes= planes;
}
UNLOCK(sink);
GST_BASE_SINK_PREROLL_UNLOCK(GST_BASE_SINK(sink));
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_DQBUF, &buf );
GST_BASE_SINK_PREROLL_LOCK(GST_BASE_SINK(sink));
LOCK(sink);
if ( rc == 0 )
{
if ( !sink->soc.inBuffers )
{
UNLOCK(sink);
GST_WARNING("lost soc.inBuffers");
return -1;
}
bufferIndex= buf.index;
if ( sink->soc.isMultiPlane )
{
memcpy( sink->soc.inBuffers[bufferIndex].buf.m.planes, buf.m.planes, sizeof(struct v4l2_plane)*WST_MAX_PLANES);
buf.m.planes= sink->soc.inBuffers[bufferIndex].buf.m.planes;
}
sink->soc.inBuffers[bufferIndex].buf= buf;
sink->soc.inBuffers[bufferIndex].queued= false;
--sink->soc.inQueuedCount;
}
}
if ( bufferIndex >= 0 )
{
sink->soc.inBuffers[bufferIndex].buf.timestamp.tv_sec= -1;
sink->soc.inBuffers[bufferIndex].buf.timestamp.tv_usec= 0;
}
UNLOCK(sink);
return bufferIndex;
}
static void wstSetOutputMemMode( GstWesterosSink *sink, int mode )
{
int rc;
int32_t bufferType= (sink->soc.isMultiPlane ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE : V4L2_BUF_TYPE_VIDEO_CAPTURE);
memset( &sink->soc.fmtOut, 0, sizeof(struct v4l2_format) );
sink->soc.fmtOut.type= bufferType;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_G_FMT, &sink->soc.fmtOut );
if ( rc < 0 )
{
GST_DEBUG("wstSetOutputMemMode: initV4l2: failed get format for output: rc %d errno %d", rc, errno);
}
sink->soc.outputMemMode= mode;
#ifdef WESTEROS_SINK_SVP
wstSVPSetOutputMemMode( sink, mode );
#endif
}
static void wstSetupOutput( GstWesterosSink *sink )
{
int memMode;
memMode= (sink->soc.useDmabufOutput ? V4L2_MEMORY_DMABUF : V4L2_MEMORY_MMAP);
wstSetOutputMemMode( sink, memMode );
wstSetOutputFormat( sink );
wstSetupOutputBuffers( sink );
}
static int wstGetOutputBuffer( GstWesterosSink *sink )
{
int bufferIndex= -1;
int rc;
struct v4l2_buffer buf;
struct v4l2_plane planes[WST_MAX_PLANES];
if ( sink->soc.decoderLastFrame )
{
goto exit;
}
memset( &buf, 0, sizeof(buf));
buf.type= sink->soc.fmtOut.type;
buf.memory= sink->soc.outputMemMode;
if ( sink->soc.isMultiPlane )
{
buf.length= sink->soc.outBuffers[0].planeCount;
buf.m.planes= planes;
}
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_DQBUF, &buf );
if ( rc == 0 )
{
bufferIndex= buf.index;
if ( sink->soc.isMultiPlane )
{
memcpy( sink->soc.outBuffers[bufferIndex].buf.m.planes, buf.m.planes, sizeof(struct v4l2_plane)*WST_MAX_PLANES);
buf.m.planes= sink->soc.outBuffers[bufferIndex].buf.m.planes;
}
sink->soc.outBuffers[bufferIndex].buf= buf;
sink->soc.outBuffers[bufferIndex].queued= false;
--sink->soc.outQueuedCount;
}
else
{
GST_ERROR("failed to de-queue output buffer: rc %d errno %d", rc, errno);
if ( errno == EPIPE )
{
/* Decoding is done: no more capture buffers can be dequeued */
sink->soc.decoderLastFrame= 1;
}
}
exit:
return bufferIndex;
}
static int wstFindOutputBuffer( GstWesterosSink *sink, int fd )
{
int bufferIndex= -1;
int i;
for( i= 0; i < sink->soc.numBuffersOut; ++i )
{
if ( sink->soc.outBuffers[i].fd == fd )
{
bufferIndex= i;
break;
}
}
return bufferIndex;
}
static void wstLockOutputBuffer( GstWesterosSink *sink, int buffIndex )
{
sink->soc.outBuffers[buffIndex].locked= true;
++sink->soc.outBuffers[buffIndex].lockCount;
}
static bool wstUnlockOutputBuffer( GstWesterosSink *sink, int buffIndex )
{
bool unlocked= false;
if ( !sink->soc.outBuffers[buffIndex].locked )
{
GST_ERROR("attempt to unlock buffer that is not locked: index %d", buffIndex);
}
if ( sink->soc.outBuffers[buffIndex].lockCount > 0 )
{
if ( --sink->soc.outBuffers[buffIndex].lockCount == 0 )
{
sink->soc.outBuffers[buffIndex].locked= false;
unlocked= true;
}
}
return unlocked;
}
static void wstRequeueOutputBuffer( GstWesterosSink *sink, int buffIndex )
{
if ( !sink->soc.outBuffers[buffIndex].locked )
{
int rc;
sink->soc.outBuffers[buffIndex].drop= false;
sink->soc.outBuffers[buffIndex].frameNumber= -1;
FRAME("out: requeue buffer %d (%d)", sink->soc.outBuffers[buffIndex].bufferId, buffIndex);
GST_LOG( "%lld: requeue: buffer %d (%d)", getCurrentTimeMillis(), sink->soc.outBuffers[buffIndex].bufferId, buffIndex);
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_QBUF, &sink->soc.outBuffers[buffIndex].buf );
if ( rc < 0 )
{
GST_ERROR("wstRequeueOutputBuffer: failed to re-queue output buffer index %d: rc %d errno %d", buffIndex, rc, errno);
}
else
{
++sink->soc.outQueuedCount;
sink->soc.outBuffers[buffIndex].queued= true;
}
}
}
static WstVideoClientConnection *wstCreateVideoClientConnection( GstWesterosSink *sink, const char *name )
{
WstVideoClientConnection *conn= 0;
int rc;
bool error= true;
const char *workingDir;
int pathNameLen, addressSize;
conn= (WstVideoClientConnection*)calloc( 1, sizeof(WstVideoClientConnection));
if ( conn )
{
conn->socketFd= -1;
conn->name= name;
conn->sink= sink;
workingDir= getenv("XDG_RUNTIME_DIR");
if ( !workingDir )
{
GST_ERROR("wstCreateVideoClientConnection: XDG_RUNTIME_DIR is not set");
goto exit;
}
pathNameLen= strlen(workingDir)+strlen("/")+strlen(conn->name)+1;
if ( pathNameLen > (int)sizeof(conn->addr.sun_path) )
{
GST_ERROR("wstCreateVideoClientConnection: name for server unix domain socket is too long: %d versus max %d",
pathNameLen, (int)sizeof(conn->addr.sun_path) );
goto exit;
}
conn->addr.sun_family= AF_LOCAL;
strcpy( conn->addr.sun_path, workingDir );
strcat( conn->addr.sun_path, "/" );
strcat( conn->addr.sun_path, conn->name );
conn->socketFd= socket( PF_LOCAL, SOCK_STREAM|SOCK_CLOEXEC, 0 );
if ( conn->socketFd < 0 )
{
GST_ERROR("wstCreateVideoClientConnection: unable to open socket: errno %d", errno );
goto exit;
}
addressSize= pathNameLen + offsetof(struct sockaddr_un, sun_path);
rc= connect(conn->socketFd, (struct sockaddr *)&conn->addr, addressSize );
if ( rc < 0 )
{
GST_ERROR("wstCreateVideoClientConnection: connect failed for socket: errno %d", errno );
goto exit;
}
error= false;
}
exit:
if ( error )
{
wstDestroyVideoClientConnection( conn );
conn= 0;
}
return conn;
}
static void wstDestroyVideoClientConnection( WstVideoClientConnection *conn )
{
if ( conn )
{
conn->addr.sun_path[0]= '\0';
if ( conn->socketFd >= 0 )
{
close( conn->socketFd );
conn->socketFd= -1;
}
free( conn );
}
}
static unsigned int getU32( unsigned char *p )
{
unsigned n;
n= (p[0]<<24)|(p[1]<<16)|(p[2]<<8)|(p[3]);
return n;
}
static int putU32( unsigned char *p, unsigned n )
{
p[0]= (n>>24);
p[1]= (n>>16);
p[2]= (n>>8);
p[3]= (n&0xFF);
return 4;
}
static gint64 getS64( unsigned char *p )
{
gint64 n;
n= ((((gint64)(p[0]))<<56) |
(((gint64)(p[1]))<<48) |
(((gint64)(p[2]))<<40) |
(((gint64)(p[3]))<<32) |
(((gint64)(p[4]))<<24) |
(((gint64)(p[5]))<<16) |
(((gint64)(p[6]))<<8) |
(p[7]) );
return n;
}
static int putS64( unsigned char *p, gint64 n )
{
p[0]= (((guint64)n)>>56);
p[1]= (((guint64)n)>>48);
p[2]= (((guint64)n)>>40);
p[3]= (((guint64)n)>>32);
p[4]= (((guint64)n)>>24);
p[5]= (((guint64)n)>>16);
p[6]= (((guint64)n)>>8);
p[7]= (((guint64)n)&0xFF);
return 8;
}
static void wstSendFlushVideoClientConnection( WstVideoClientConnection *conn )
{
if ( conn )
{
struct msghdr msg;
struct iovec iov[1];
unsigned char mbody[4];
int len;
int sentLen;
msg.msg_name= NULL;
msg.msg_namelen= 0;
msg.msg_iov= iov;
msg.msg_iovlen= 1;
msg.msg_control= 0;
msg.msg_controllen= 0;
msg.msg_flags= 0;
len= 0;
mbody[len++]= 'V';
mbody[len++]= 'S';
mbody[len++]= 1;
mbody[len++]= 'S';
iov[0].iov_base= (char*)mbody;
iov[0].iov_len= len;
do
{
sentLen= sendmsg( conn->socketFd, &msg, MSG_NOSIGNAL );
}
while ( (sentLen < 0) && (errno == EINTR));
if ( sentLen == len )
{
GST_LOG("sent flush to video server");
FRAME("sent flush to video server");
}
}
}
static void wstSendPauseVideoClientConnection( WstVideoClientConnection *conn, bool pause )
{
if ( conn )
{
struct msghdr msg;
struct iovec iov[1];
unsigned char mbody[7];
int len;
int sentLen;
msg.msg_name= NULL;
msg.msg_namelen= 0;
msg.msg_iov= iov;
msg.msg_iovlen= 1;
msg.msg_control= 0;
msg.msg_controllen= 0;
msg.msg_flags= 0;
len= 0;
mbody[len++]= 'V';
mbody[len++]= 'S';
mbody[len++]= 2;
mbody[len++]= 'P';
mbody[len++]= (pause ? 1 : 0);
iov[0].iov_base= (char*)mbody;
iov[0].iov_len= len;
do
{
sentLen= sendmsg( conn->socketFd, &msg, MSG_NOSIGNAL );
}
while ( (sentLen < 0) && (errno == EINTR));
if ( sentLen == len )
{
GST_LOG("sent pause %d to video server", pause);
FRAME("sent pause %d to video server", pause);
}
}
}
static void wstSendHideVideoClientConnection( WstVideoClientConnection *conn, bool hide )
{
if ( conn )
{
struct msghdr msg;
struct iovec iov[1];
unsigned char mbody[7];
int len;
int sentLen;
msg.msg_name= NULL;
msg.msg_namelen= 0;
msg.msg_iov= iov;
msg.msg_iovlen= 1;
msg.msg_control= 0;
msg.msg_controllen= 0;
msg.msg_flags= 0;
len= 0;
mbody[len++]= 'V';
mbody[len++]= 'S';
mbody[len++]= 2;
mbody[len++]= 'H';
mbody[len++]= (hide ? 1 : 0);
iov[0].iov_base= (char*)mbody;
iov[0].iov_len= len;
do
{
sentLen= sendmsg( conn->socketFd, &msg, MSG_NOSIGNAL );
}
while ( (sentLen < 0) && (errno == EINTR));
if ( sentLen == len )
{
GST_LOG("sent hide %d to video server", hide);
FRAME("sent hide %d to video server", hide);
}
}
}
static void wstSendSessionInfoVideoClientConnection( WstVideoClientConnection *conn )
{
if ( conn )
{
GstWesterosSink *sink= conn->sink;
struct msghdr msg;
struct iovec iov[1];
unsigned char mbody[9];
int len;
int sentLen;
msg.msg_name= NULL;
msg.msg_namelen= 0;
msg.msg_iov= iov;
msg.msg_iovlen= 1;
msg.msg_control= 0;
msg.msg_controllen= 0;
msg.msg_flags= 0;
len= 0;
mbody[len++]= 'V';
mbody[len++]= 'S';
mbody[len++]= 6;
mbody[len++]= 'I';
mbody[len++]= sink->soc.syncType;
len += putU32( &mbody[len], conn->sink->soc.sessionId );
iov[0].iov_base= (char*)mbody;
iov[0].iov_len= len;
do
{
sentLen= sendmsg( conn->socketFd, &msg, MSG_NOSIGNAL );
}
while ( (sentLen < 0) && (errno == EINTR));
if ( sentLen == len )
{
GST_DEBUG("sent session info: type %d sessionId %d to video server", sink->soc.syncType, sink->soc.sessionId);
g_print("sent session info: type %d sessionId %d to video server\n", sink->soc.syncType, sink->soc.sessionId);
}
}
}
static void wstSendFrameAdvanceVideoClientConnection( WstVideoClientConnection *conn )
{
if ( conn )
{
struct msghdr msg;
struct iovec iov[1];
unsigned char mbody[4];
int len;
int sentLen;
msg.msg_name= NULL;
msg.msg_namelen= 0;
msg.msg_iov= iov;
msg.msg_iovlen= 1;
msg.msg_control= 0;
msg.msg_controllen= 0;
msg.msg_flags= 0;
len= 0;
mbody[len++]= 'V';
mbody[len++]= 'S';
mbody[len++]= 1;
mbody[len++]= 'A';
iov[0].iov_base= (char*)mbody;
iov[0].iov_len= len;
do
{
sentLen= sendmsg( conn->socketFd, &msg, MSG_NOSIGNAL );
}
while ( (sentLen < 0) && (errno == EINTR));
if ( sentLen == len )
{
GST_LOG("sent frame adavnce to video server");
FRAME("sent frame advance to video server");
}
}
}
static void wstSendRectVideoClientConnection( WstVideoClientConnection *conn )
{
if ( conn )
{
struct msghdr msg;
struct iovec iov[1];
unsigned char mbody[20];
int len;
int sentLen;
int vx, vy, vw, vh;
GstWesterosSink *sink= conn->sink;
vx= sink->soc.videoX;
vy= sink->soc.videoY;
vw= sink->soc.videoWidth;
vh= sink->soc.videoHeight;
if ( needBounds(sink) )
{
wstGetVideoBounds( sink, &vx, &vy, &vw, &vh );
}
msg.msg_name= NULL;
msg.msg_namelen= 0;
msg.msg_iov= iov;
msg.msg_iovlen= 1;
msg.msg_control= 0;
msg.msg_controllen= 0;
msg.msg_flags= 0;
len= 0;
mbody[len++]= 'V';
mbody[len++]= 'S';
mbody[len++]= 17;
mbody[len++]= 'W';
len += putU32( &mbody[len], vx );
len += putU32( &mbody[len], vy );
len += putU32( &mbody[len], vw );
len += putU32( &mbody[len], vh );
iov[0].iov_base= (char*)mbody;
iov[0].iov_len= len;
do
{
sentLen= sendmsg( conn->socketFd, &msg, MSG_NOSIGNAL );
}
while ( (sentLen < 0) && (errno == EINTR));
if ( sentLen == len )
{
GST_LOG("sent position to video server");
FRAME("sent position to video server");
}
}
}
static void wstSendRateVideoClientConnection( WstVideoClientConnection *conn )
{
if ( conn )
{
struct msghdr msg;
struct iovec iov[1];
unsigned char mbody[12];
int len;
int sentLen;
GstWesterosSink *sink= conn->sink;
msg.msg_name= NULL;
msg.msg_namelen= 0;
msg.msg_iov= iov;
msg.msg_iovlen= 1;
msg.msg_control= 0;
msg.msg_controllen= 0;
msg.msg_flags= 0;
len= 0;
mbody[len++]= 'V';
mbody[len++]= 'S';
mbody[len++]= 9;
mbody[len++]= 'R';
len += putU32( &mbody[len], sink->soc.frameRateFractionNum );
len += putU32( &mbody[len], sink->soc.frameRateFractionDenom );
iov[0].iov_base= (char*)mbody;
iov[0].iov_len= len;
do
{
sentLen= sendmsg( conn->socketFd, &msg, MSG_NOSIGNAL );
}
while ( (sentLen < 0) && (errno == EINTR));
if ( sentLen == len )
{
GST_LOG("sent frame rate to video server: %d/%d", sink->soc.frameRateFractionNum, sink->soc.frameRateFractionDenom);
FRAME("sent frame rate to video server: %d/%d", sink->soc.frameRateFractionNum, sink->soc.frameRateFractionDenom);
}
}
}
#ifdef USE_AMLOGIC_MESON
static GstElement* wstFindAudioSink( GstWesterosSink *sink )
{
GstElement *audioSink= 0;
GstElement *pipeline= 0;
GstElement *element, *elementPrev= 0;
GstIterator *iterator;
element= GST_ELEMENT_CAST(sink);
do
{
if ( elementPrev )
{
gst_object_unref( elementPrev );
}
element= GST_ELEMENT_CAST(gst_element_get_parent( element ));
if ( element )
{
elementPrev= pipeline;
pipeline= element;
}
}
while( element != 0 );
if ( pipeline )
{
GstIterator *iterElement= gst_bin_iterate_recurse( GST_BIN(pipeline) );
if ( iterElement )
{
GValue itemElement= G_VALUE_INIT;
while( gst_iterator_next( iterElement, &itemElement ) == GST_ITERATOR_OK )
{
element= (GstElement*)g_value_get_object( &itemElement );
if ( element && !GST_IS_BIN(element) )
{
int numSrcPads= 0;
GstIterator *iterPad= gst_element_iterate_src_pads( element );
if ( iterPad )
{
GValue itemPad= G_VALUE_INIT;
while( gst_iterator_next( iterPad, &itemPad ) == GST_ITERATOR_OK )
{
GstPad *pad= (GstPad*)g_value_get_object( &itemPad );
if ( pad )
{
++numSrcPads;
}
g_value_reset( &itemPad );
}
gst_iterator_free(iterPad);
}
if ( numSrcPads == 0 )
{
GstElementClass *ec= GST_ELEMENT_GET_CLASS(element);
if ( ec )
{
const gchar *meta= gst_element_class_get_metadata( ec, GST_ELEMENT_METADATA_KLASS);
if ( meta && strstr(meta, "Sink") && strstr(meta, "Audio") )
{
audioSink= (GstElement*)gst_object_ref( element );
gchar *name= gst_element_get_name( element );
if ( name )
{
GST_DEBUG( "detected audio sink: name (%s)", name);
g_free( name );
}
g_value_reset( &itemElement );
break;
}
}
}
}
g_value_reset( &itemElement );
}
gst_iterator_free(iterElement);
}
gst_object_unref(pipeline);
}
return audioSink;
}
#endif
static void wstSetSessionInfo( GstWesterosSink *sink )
{
#ifdef USE_AMLOGIC_MESON
if ( sink->soc.conn )
{
GstElement *audioSink= 0;
GstElement *element= GST_ELEMENT(sink);
GstClock *clock= GST_ELEMENT_CLOCK(element);
int syncTypePrev= sink->soc.syncType;
int sessionIdPrev= sink->soc.sessionId;
#ifdef USE_AMLOGIC_MESON_MSYNC
if ( sink->soc.userSession )
{
syncTypePrev= -1;
sessionIdPrev= -1;
}
else
{
sink->soc.syncType= 0;
sink->soc.sessionId= INVALID_SESSION_ID;
if ( sink->segment.applied_rate == 1.0 )
{
audioSink= wstFindAudioSink( sink );
}
if ( audioSink )
{
GstClock* amlclock= gst_aml_hal_asink_get_clock( audioSink );
if (amlclock)
{
sink->soc.syncType= 1;
sink->soc.sessionId= gst_aml_clock_get_session_id( amlclock );
gst_object_unref( amlclock );
}
else
{
GST_WARNING ("no clock: vmaster mode");
}
gst_object_unref( audioSink );
GST_WARNING("AmlHalAsink detected, sesison_id: %d", sink->soc.sessionId);
}
}
#else
sink->soc.syncType= 0;
sink->soc.sessionId= 0;
audioSink= wstFindAudioSink( sink );
if ( audioSink )
{
sink->soc.syncType= 1;
gst_object_unref( audioSink );
}
if ( clock )
{
const char *socClockName;
gchar *clockName;
clockName= gst_object_get_name(GST_OBJECT_CAST(clock));
if ( clockName )
{
int sclen;
int len= strlen(clockName);
socClockName= getenv("WESTEROS_SINK_CLOCK");
if ( !socClockName )
{
socClockName= "GstAmlSinkClock";
}
sclen= strlen(socClockName);
if ( (len == sclen) && !strncmp(clockName, socClockName, len) )
{
sink->soc.syncType= 1;
/* TBD: set sessionid */
}
g_free( clockName );
}
}
if ( sink->resAssignedId >= 0 )
{
sink->soc.sessionId= sink->resAssignedId;
}
#endif
if ( (syncTypePrev != sink->soc.syncType) || (sessionIdPrev != sink->soc.sessionId) )
{
wstSendSessionInfoVideoClientConnection( sink->soc.conn );
}
}
#endif
}
static void wstProcessMessagesVideoClientConnection( WstVideoClientConnection *conn )
{
if ( conn )
{
GstWesterosSink *sink= conn->sink;
struct pollfd pfd;
int rc;
pfd.fd= conn->socketFd;
pfd.events= POLLIN;
pfd.revents= 0;
rc= poll( &pfd, 1, 0);
if ( rc == 1 )
{
struct msghdr msg;
struct iovec iov[1];
unsigned char mbody[256];
unsigned char *m= mbody;
int len;
iov[0].iov_base= (char*)mbody;
iov[0].iov_len= sizeof(mbody);
msg.msg_name= NULL;
msg.msg_namelen= 0;
msg.msg_iov= iov;
msg.msg_iovlen= 1;
msg.msg_control= 0;
msg.msg_controllen= 0;
msg.msg_flags= 0;
do
{
len= recvmsg( conn->socketFd, &msg, 0 );
}
while ( (len < 0) && (errno == EINTR));
while ( len >= 4 )
{
if ( (m[0] == 'V') && (m[1] == 'S') )
{
int mlen, id;
mlen= m[2];
if ( len >= (mlen+3) )
{
id= m[3];
switch( id )
{
case 'R':
if ( mlen >= 5)
{
int rate= getU32( &m[4] );
GST_DEBUG("got rate %d from video server", rate);
conn->serverRefreshRate= rate;
if ( rate )
{
conn->serverRefreshPeriod= 1000000LL/rate;
}
FRAME("got rate %d (period %lld us) from video server", rate, conn->serverRefreshPeriod);
}
break;
case 'B':
if ( mlen >= 5)
{
int bid= getU32( &m[4] );
if ( (bid >= sink->soc.bufferIdOutBase) && (bid < sink->soc.bufferIdOutBase+sink->soc.numBuffersOut) )
{
int bi= bid-sink->soc.bufferIdOutBase;
if ( sink->soc.outBuffers[bi].locked )
{
FRAME("out: release received for buffer %d (%d)", bid, bi);
if ( sink->soc.useGfxSync &&
!sink->soc.videoPaused &&
(bi != sink->soc.pauseGfxBuffIndex) &&
(sink->soc.enableTextureSignal ||
(sink->soc.captureEnabled && sink->soc.sb)) )
{
int buffIndex= wstFindVideoBuffer( sink, sink->soc.outBuffers[bi].frameNumber+3 );
if ( buffIndex >= 0 )
{
if ( sink->soc.enableTextureSignal )
{
wstProcessTextureSignal( sink, buffIndex );
}
else if ( sink->soc.captureEnabled && sink->soc.sb )
{
wstProcessTextureWayland( sink, buffIndex );
}
}
}
if ( wstUnlockOutputBuffer( sink, bi ) )
{
wstRequeueOutputBuffer( sink, bi );
}
}
else
{
GST_ERROR("release received for non-locked buffer %d (%d)", bid, bi );
FRAME("out: error: release received for non-locked buffer %d (%d)", bid, bi);
}
}
else
{
GST_DEBUG("release received for stale buffer %d", bid );
FRAME("out: note: release received for stale buffer %d", bid);
}
}
break;
case 'S':
if ( mlen >= 13)
{
/* set position from frame currently presented by the video server */
guint64 frameTime= getS64( &m[4] );
sink->soc.numDropped= getU32( &m[12] );
FRAME( "out: status received: frameTime %lld numDropped %d", frameTime, sink->soc.numDropped);
if ( sink->prevPositionSegmentStart != 0xFFFFFFFFFFFFFFFFLL )
{
gint64 currentNano= frameTime*1000LL;
gint64 firstNano= ((sink->firstPTS/90LL)*GST_MSECOND)+((sink->firstPTS%90LL)*GST_MSECOND/90LL);
sink->position= sink->positionSegmentStart + currentNano - firstNano;
sink->currentPTS= currentNano / (GST_SECOND/90000LL);
GST_DEBUG("receive frameTime: %lld position %lld PTS %lld", currentNano, sink->position, sink->currentPTS);
if (sink->soc.frameDisplayCount == 0)
{
sink->soc.emitFirstFrameSignal= TRUE;
}
++sink->soc.frameDisplayCount;
if ( sink->timeCodePresent && sink->enableTimeCodeSignal )
{
sink->timeCodePresent( sink, sink->position, g_signals[SIGNAL_TIMECODE] );
}
}
}
break;
case 'U':
if ( mlen >= 9 )
{
guint64 frameTime= getS64( &m[4] );
GST_INFO( "underflow received: frameTime %lld eosEventSeen %d", frameTime, sink->eosEventSeen);
FRAME( "out: underflow received: frameTime %lld", frameTime);
if ( !sink->eosEventSeen )
{
sink->soc.emitUnderflowSignal= TRUE;
}
}
break;
case 'Z':
if ( mlen >= 5)
{
int zoomMode= getU32( &m[4] );
GST_DEBUG("got zoom-mode %d from video server", zoomMode);
if ( sink->soc.zoomModeUser == FALSE )
{
if ( (zoomMode >= ZOOM_NONE) && (zoomMode <= ZOOM_ZOOM) )
{
sink->soc.zoomMode= zoomMode;
sink->soc.pixelAspectRatioChanged= TRUE;
}
}
else
{
GST_DEBUG("user zoom mode set: ignore server value");
}
}
break;
case 'D':
if ( mlen >= 5)
{
int debugLevel= getU32( &m[4] );
GST_DEBUG("got video-debug-level %d from video server", debugLevel);
if ( (debugLevel >= 0) && (debugLevel <= 7) )
{
if ( debugLevel == 0 )
{
gst_debug_category_reset_threshold( gst_westeros_sink_debug );
}
else
{
gst_debug_category_set_threshold( gst_westeros_sink_debug, (GstDebugLevel)debugLevel );
}
}
}
break;
default:
break;
}
m += (mlen+3);
len -= (mlen+3);
}
else
{
len= 0;
}
}
else
{
len= 0;
}
}
}
}
}
static bool wstSendFrameVideoClientConnection( WstVideoClientConnection *conn, int buffIndex )
{
bool result= false;
GstWesterosSink *sink= conn->sink;
int sentLen;
if ( conn )
{
struct msghdr msg;
struct cmsghdr *cmsg;
struct iovec iov[1];
unsigned char mbody[4+64];
char cmbody[CMSG_SPACE(3*sizeof(int))];
int i, len;
int *fd;
int numFdToSend;
int frameFd0= -1, frameFd1= -1, frameFd2= -1;
int fdToSend0= -1, fdToSend1= -1, fdToSend2= -1;
int offset0, offset1, offset2;
int stride0, stride1, stride2;
uint32_t pixelFormat;
int bufferId= -1;
int vx, vy, vw, vh;
wstProcessMessagesVideoClientConnection( conn );
if ( buffIndex >= 0 )
{
sink->soc.resubFd= -1;
bufferId= sink->soc.outBuffers[buffIndex].bufferId;
numFdToSend= 1;
offset0= offset1= offset2= 0;
stride0= stride1= stride2= sink->soc.frameWidth;
if ( sink->soc.outBuffers[buffIndex].planeCount > 1 )
{
frameFd0= sink->soc.outBuffers[buffIndex].planeInfo[0].fd;
stride0= sink->soc.fmtOut.fmt.pix_mp.plane_fmt[0].bytesperline;
frameFd1= sink->soc.outBuffers[buffIndex].planeInfo[1].fd;
stride1= sink->soc.fmtOut.fmt.pix_mp.plane_fmt[1].bytesperline;
if ( frameFd1 < 0 )
{
offset1= sink->soc.frameWidth*sink->soc.fmtOut.fmt.pix.height;
stride1= stride0;
}
frameFd2= sink->soc.outBuffers[buffIndex].planeInfo[2].fd;
stride2= sink->soc.fmtOut.fmt.pix_mp.plane_fmt[2].bytesperline;
if ( frameFd2 < 0 )
{
offset2= offset1+(sink->soc.frameWidth*sink->soc.fmtOut.fmt.pix.height)/2;
stride2= stride0;
}
}
else
{
frameFd0= sink->soc.outBuffers[buffIndex].fd;
if ( sink->soc.isMultiPlane )
stride0= sink->soc.fmtOut.fmt.pix_mp.plane_fmt[0].bytesperline;
else
stride0= sink->soc.fmtOut.fmt.pix.bytesperline;
offset1= stride0*sink->soc.fmtOut.fmt.pix.height;
stride1= stride0;
offset2= 0;
stride2= 0;
}
pixelFormat= conn->sink->soc.fmtOut.fmt.pix.pixelformat;
switch( pixelFormat )
{
case V4L2_PIX_FMT_NV12:
case V4L2_PIX_FMT_NV12M:
pixelFormat= V4L2_PIX_FMT_NV12;
break;
default:
GST_WARNING("unsupported pixel format: %X", conn->sink->soc.fmtOut.fmt.pix.pixelformat);
break;
}
fdToSend0= fcntl( frameFd0, F_DUPFD_CLOEXEC, 0 );
if ( fdToSend0 < 0 )
{
GST_ERROR("wstSendFrameVideoClientConnection: failed to dup fd0");
goto exit;
}
if ( frameFd1 >= 0 )
{
fdToSend1= fcntl( frameFd1, F_DUPFD_CLOEXEC, 0 );
if ( fdToSend1 < 0 )
{
GST_ERROR("wstSendFrameVideoClientConnection: failed to dup fd1");
goto exit;
}
++numFdToSend;
}
if ( frameFd2 >= 0 )
{
fdToSend2= fcntl( frameFd2, F_DUPFD_CLOEXEC, 0 );
if ( fdToSend2 < 0 )
{
GST_ERROR("wstSendFrameVideoClientConnection: failed to dup fd2");
goto exit;
}
++numFdToSend;
}
vx= sink->soc.videoX;
vy= sink->soc.videoY;
vw= sink->soc.videoWidth;
vh= sink->soc.videoHeight;
if ( needBounds(sink) )
{
wstGetVideoBounds( sink, &vx, &vy, &vw, &vh );
}
i= 0;
mbody[i++]= 'V';
mbody[i++]= 'S';
mbody[i++]= 65;
mbody[i++]= 'F';
i += putU32( &mbody[i], conn->sink->soc.frameWidth );
i += putU32( &mbody[i], conn->sink->soc.frameHeight );
i += putU32( &mbody[i], pixelFormat );
i += putU32( &mbody[i], vx );
i += putU32( &mbody[i], vy );
i += putU32( &mbody[i], vw );
i += putU32( &mbody[i], vh );
i += putU32( &mbody[i], offset0 );
i += putU32( &mbody[i], stride0 );
i += putU32( &mbody[i], offset1 );
i += putU32( &mbody[i], stride1 );
i += putU32( &mbody[i], offset2 );
i += putU32( &mbody[i], stride2 );
i += putU32( &mbody[i], bufferId );
i += putS64( &mbody[i], sink->soc.outBuffers[buffIndex].frameTime );
iov[0].iov_base= (char*)mbody;
iov[0].iov_len= i;
cmsg= (struct cmsghdr*)cmbody;
cmsg->cmsg_len= CMSG_LEN(numFdToSend*sizeof(int));
cmsg->cmsg_level= SOL_SOCKET;
cmsg->cmsg_type= SCM_RIGHTS;
msg.msg_name= NULL;
msg.msg_namelen= 0;
msg.msg_iov= iov;
msg.msg_iovlen= 1;
msg.msg_control= cmsg;
msg.msg_controllen= cmsg->cmsg_len;
msg.msg_flags= 0;
fd= (int*)CMSG_DATA(cmsg);
fd[0]= fdToSend0;
if ( fdToSend1 >= 0 )
{
fd[1]= fdToSend1;
}
if ( fdToSend2 >= 0 )
{
fd[2]= fdToSend2;
}
GST_LOG( "%lld: send frame: %d, fd (%d, %d, %d [%d, %d, %d])", getCurrentTimeMillis(), buffIndex, frameFd0, frameFd1, frameFd2, fdToSend0, fdToSend1, fdToSend2);
wstLockOutputBuffer( sink, buffIndex );
FRAME("out: send frame %d buffer %d (%d)", conn->sink->soc.frameOutCount-1, conn->sink->soc.outBuffers[buffIndex].bufferId, buffIndex);
avProgLog( sink->soc.outBuffers[buffIndex].frameTime*1000L, 0, "WtoW", "");
do
{
sentLen= sendmsg( conn->socketFd, &msg, 0 );
}
while ( (sentLen < 0) && (errno == EINTR));
conn->sink->soc.outBuffers[buffIndex].frameNumber= conn->sink->soc.frameOutCount-1;
if ( sentLen == iov[0].iov_len )
{
result= true;
}
else
{
FRAME("out: failed send frame %d buffer %d (%d)", conn->sink->soc.frameOutCount-1, conn->sink->soc.outBuffers[buffIndex].bufferId, buffIndex);
wstUnlockOutputBuffer( sink, buffIndex );
}
}
exit:
if ( fdToSend0 >= 0 )
{
close( fdToSend0 );
}
if ( fdToSend1 >= 0 )
{
close( fdToSend1 );
}
if ( fdToSend2 >= 0 )
{
close( fdToSend2 );
}
}
return result;
}
static void wstDecoderReset( GstWesterosSink *sink, bool hard )
{
long long delay;
sink->soc.quitVideoOutputThread= TRUE;
delay= ((sink->soc.frameRate > 0) ? 1000000/sink->soc.frameRate : 1000000/60);
usleep( delay );
LOCK(sink);
wstTearDownInputBuffers( sink );
wstTearDownOutputBuffers( sink );
UNLOCK(sink);
if ( sink->soc.videoOutputThread )
{
g_thread_join( sink->soc.videoOutputThread );
sink->soc.videoOutputThread= NULL;
}
if ( hard )
{
if ( sink->soc.v4l2Fd >= 0 )
{
int fdToClose= sink->soc.v4l2Fd;
sink->soc.v4l2Fd= -1;
close( fdToClose );
}
sink->soc.v4l2Fd= open( sink->soc.devname, O_RDWR | O_CLOEXEC );
if ( sink->soc.v4l2Fd < 0 )
{
GST_ERROR("failed to open device (%s)", sink->soc.devname );
}
wstStartEvents( sink );
}
LOCK(sink);
sink->videoStarted= FALSE;
UNLOCK(sink);
sink->startAfterCaps= TRUE;
sink->soc.prevFrameTimeGfx= 0;
sink->soc.prevFramePTSGfx= 0;
sink->soc.prevFrame1Fd= -1;
sink->soc.prevFrame2Fd= -1;
sink->soc.nextFrameFd= -1;
sink->soc.formatsSet= FALSE;
}
typedef struct bufferInfo
{
GstWesterosSink *sink;
int buffIndex;
int cohort;
} bufferInfo;
static void buffer_release( void *data, struct wl_buffer *buffer )
{
int rc;
bufferInfo *binfo= (bufferInfo*)data;
GstWesterosSink *sink= binfo->sink;
if ( (sink->soc.v4l2Fd >= 0) &&
(binfo->buffIndex >= 0) &&
(binfo->cohort == sink->soc.bufferCohort) )
{
FRAME("out: wayland release received for buffer %d", binfo->buffIndex);
LOCK(sink);
if ( !sink->soc.conn )
{
++sink->soc.frameDisplayCount;
}
if ( binfo->buffIndex == sink->soc.pauseGfxBuffIndex )
{
sink->soc.pauseGfxBuffIndex= -1;
}
if ( wstUnlockOutputBuffer( sink, binfo->buffIndex ) )
{
wstRequeueOutputBuffer( sink, binfo->buffIndex );
}
UNLOCK(sink);
}
--sink->soc.activeBuffers;
wl_buffer_destroy( buffer );
free( binfo );
}
static struct wl_buffer_listener wl_buffer_listener=
{
buffer_release
};
static bool wstLocalRateControl( GstWesterosSink *sink, int buffIndex )
{
bool drop= false;
WstVideoClientConnection *conn= sink->soc.conn;
gint64 framePTS;
gint64 currFrameTime;
if ( !sink->soc.outBuffers )
{
goto exit;
}
framePTS= sink->soc.outBuffers[buffIndex].frameTime;
if ( framePTS < sink->segment.start/1000LL )
{
FRAME("out: drop out-of-segment frame");
drop= true;
goto exit;
}
if ( !sink->soc.conn || !sink->soc.useGfxSync )
{
if ( sink->soc.enableTextureSignal ||
(sink->soc.captureEnabled && sink->soc.sb) )
{
if ( conn )
{
gint64 interval= (sink->soc.prevFramePTSGfx != 0LL) ? framePTS-sink->soc.prevFramePTSGfx : 0LL;
/*
* If the stream frame rate is greater than the display
* refresh rate reported by the server, drop frames as necessary
*/
if ( conn->serverRefreshRate && (buffIndex >= 0) )
{
if ( (sink->soc.prevFramePTSGfx != 0LL) && (interval < conn->serverRefreshPeriod) )
{
FRAME("set drop true: interval %lld refresh period %lld gfx", interval, conn->serverRefreshPeriod);
drop= true;
goto exit;
}
}
}
currFrameTime= g_get_monotonic_time();
if ( sink->soc.prevFrameTimeGfx && sink->soc.prevFramePTSGfx )
{
gint64 framePeriod= currFrameTime-sink->soc.prevFrameTimeGfx;
gint64 nominalFramePeriod= framePTS-sink->soc.prevFramePTSGfx;
gint64 delay= (nominalFramePeriod-framePeriod)/1000;
if ( (delay > 2) && (delay <= nominalFramePeriod) )
{
usleep( (delay-1)*1000 );
currFrameTime= g_get_monotonic_time();
}
}
sink->soc.prevFrameTimeGfx= currFrameTime;
sink->soc.prevFramePTSGfx= framePTS;
}
}
exit:
return drop;
}
static void wstGetVideoBounds( GstWesterosSink *sink, int *x, int *y, int *w, int *h )
{
int vx, vy, vw, vh;
int frameWidth, frameHeight;
double contentWidth, contentHeight;
double roix, roiy, roiw, roih;
double arf, ard;
double hfactor= 1.0, vfactor= 1.0;
vx= sink->soc.videoX;
vy= sink->soc.videoY;
vw= sink->soc.videoWidth;
vh= sink->soc.videoHeight;
if ( sink->soc.pixelAspectRatioChanged ) GST_DEBUG("pixelAspectRatio: %f zoom-mode %d overscan-size %d", sink->soc.pixelAspectRatio, sink->soc.zoomMode, sink->soc.overscanSize );
frameWidth= sink->soc.frameWidth;
frameHeight= sink->soc.frameHeight;
contentWidth= frameWidth*sink->soc.pixelAspectRatio;
contentHeight= frameHeight;
if ( sink->soc.pixelAspectRatioChanged ) GST_DEBUG("frame %dx%d contentWidth: %f contentHeight %f", frameWidth, frameHeight, contentWidth, contentHeight );
ard= (double)sink->soc.videoWidth/(double)sink->soc.videoHeight;
arf= (double)contentWidth/(double)contentHeight;
/* Establish region of interest */
roix= 0;
roiy= 0;
roiw= contentWidth;
roih= contentHeight;
if ( sink->soc.pixelAspectRatioChanged ) GST_DEBUG("ard %f arf %f", ard, arf);
switch( sink->soc.zoomMode )
{
case ZOOM_NORMAL:
{
if ( arf >= ard )
{
vw= sink->soc.videoWidth * (1.0+(2.0*sink->soc.overscanSize/100.0));
vh= (roih * vw) / roiw;
vx= vx+(sink->soc.videoWidth-vw)/2;
vy= vy+(sink->soc.videoHeight-vh)/2;
}
else
{
vh= sink->soc.videoHeight * (1.0+(2.0*sink->soc.overscanSize/100.0));
vw= (roiw * vh) / roih;
vx= vx+(sink->soc.videoWidth-vw)/2;
vy= vy+(sink->soc.videoHeight-vh)/2;
}
}
break;
case ZOOM_NONE:
case ZOOM_DIRECT:
{
if ( arf >= ard )
{
vh= (contentHeight * sink->soc.videoWidth) / contentWidth;
vy= vy+(sink->soc.videoHeight-vh)/2;
}
else
{
vw= (contentWidth * sink->soc.videoHeight) / contentHeight;
vx= vx+(sink->soc.videoWidth-vw)/2;
}
}
break;
case ZOOM_16_9_STRETCH:
{
if ( wstApproxEqual(arf, ard) && wstApproxEqual(arf, 1.777) )
{
/* For 16:9 content on a 16:9 display, stretch as though 4:3 */
hfactor= 4.0/3.0;
if ( sink->soc.pixelAspectRatioChanged ) GST_DEBUG("stretch apply vfactor %f hfactor %f", vfactor, hfactor);
}
vh= sink->soc.videoHeight * (1.0+(2.0*sink->soc.overscanSize/100.0));
vw= vh*hfactor*16/9;
vx= vx+(sink->soc.videoWidth-vw)/2;
vy= vy+(sink->soc.videoHeight-vh)/2;
}
break;
case ZOOM_4_3_PILLARBOX:
{
vh= sink->soc.videoHeight * (1.0+(2.0*sink->soc.overscanSize/100.0));
vw= vh*4/3;
vx= vx+(sink->soc.videoWidth-vw)/2;
vy= vy+(sink->soc.videoHeight-vh)/2;
}
break;
case ZOOM_ZOOM:
{
#ifdef USE_GST_AFD
/* Adjust region of interest based on AFD+Bars */
if ( sink->soc.pixelAspectRatioChanged ) GST_DEBUG("afd %d haveBar %d isLetterbox %d d1 %d d2 %d", sink->soc.afdActive.afd, sink->soc.afdActive.haveBar,
sink->soc.afdActive.isLetterbox, sink->soc.afdActive.d1, sink->soc.afdActive.d2 );
switch ( sink->soc.afdActive.afd )
{
case GST_VIDEO_AFD_4_3_FULL_16_9_FULL: /* AFD 8 (1000) */
/* 16:9 and 4:3 content are full frame */
break;
case GST_VIDEO_AFD_14_9_LETTER_14_9_PILLAR: /* AFD 11 (1011) */
/* 4:3 contains 14:9 letterbox vertically centered */
/* 16:9 contains 14:9 pillarbox horizontally centered */
break;
case GST_VIDEO_AFD_4_3_FULL_14_9_CENTER: /* AFD 13 (1101) */
/* 4:3 content is full frame */
/* 16:9 contains 4:3 pillarbox */
break;
case GST_VIDEO_AFD_GREATER_THAN_16_9: /* AFD 4 (0100) */
/* 4:3 contains letterbox image with aspect ratio > 16:9 vertically centered */
/* 16:9 contains letterbox image with aspect ratio > 16:9 */
/* should be accompanied by bar data */
if ( sink->soc.afdActive.haveBar )
{
int activeHeight= roih-sink->soc.afdActive.d1;
if ( activeHeight > 0 )
{
/* ignore bar data for now
hfactor= 1.0;
vfactor= roiw/activeHeight;
arf= ard;
*/
}
}
break;
case GST_VIDEO_AFD_4_3_FULL_4_3_PILLAR: /* AFD 9 (1001) */
/* 4:3 content is full frame */
/* 16:9 content is 4:3 roi horizontally centered */
if ( arf > (4.0/3.0) )
{
hfactor= 1.0;
vfactor= 1.0;
arf= ard;
}
break;
case GST_VIDEO_AFD_16_9_LETTER_16_9_FULL: /* AFD 10 (1010) */
case GST_VIDEO_AFD_16_9_LETTER_14_9_CENTER: /* AFD 14 (1110) */
case GST_VIDEO_AFD_16_9_LETTER_4_3_CENTER: /* AFD 15 (1111) */
/* 4:3 content has 16:9 letterbox roi vertically centered */
/* 16:9 content is full frame 16:9 */
if ( arf < (16.0/9.0) )
{
hfactor= 1.0;
vfactor= 4.0/3.0;
arf= ard;
}
break;
default:
break;
}
#endif
if ( arf >= ard )
{
if ( wstApproxEqual(arf, ard) && wstApproxEqual( arf, 1.777) )
{
/* For 16:9 content on a 16:9 display, enlarge as though 4:3 */
vfactor= 4.0/3.0;
hfactor= 1.0;
if ( sink->soc.pixelAspectRatioChanged ) GST_DEBUG("zoom apply vfactor %f hfactor %f", vfactor, hfactor);
}
vh= sink->soc.videoHeight * vfactor * (1.0+(2.0*sink->soc.overscanSize/100.0));
vw= (roiw * vh) * hfactor / roih;
vx= vx+(sink->soc.videoWidth-vw)/2;
vy= vy+(sink->soc.videoHeight-vh)/2;
}
else
{
vw= sink->soc.videoWidth * (1.0+(2.0*sink->soc.overscanSize/100.0));
vh= (roih * vw) / roiw;
vx= vx+(sink->soc.videoWidth-vw)/2;
vy= vy+(sink->soc.videoHeight-vh)/2;
}
}
break;
}
if ( sink->soc.pixelAspectRatioChanged ) GST_DEBUG("vrect %d, %d, %d, %d", vx, vy, vw, vh);
if ( sink->soc.pixelAspectRatioChanged )
{
if ( sink->display && sink->vpcSurface )
{
wl_vpc_surface_set_geometry( sink->vpcSurface, vx, vy, vw, vh );
wl_display_flush(sink->display);
}
}
sink->soc.pixelAspectRatioChanged= FALSE;
*x= vx;
*y= vy;
*w= vw;
*h= vh;
}
static void wstSetTextureCrop( GstWesterosSink *sink, int vx, int vy, int vw, int vh )
{
GST_DEBUG("wstSetTextureCrop: vx %d vy %d vw %d vh %d window(%d, %d, %d, %d) display(%dx%d)",
vx, vy, vw, vh, sink->windowX, sink->windowY, sink->windowWidth, sink->windowHeight, sink->displayWidth, sink->displayHeight);
if ( (sink->displayWidth != -1) && (sink->displayHeight != -1) &&
( (vx < 0) || (vx+vw > sink->displayWidth) ||
(vy < 0) || (vy+vh > sink->displayHeight) ) )
{
int cropx, cropy, cropw, croph;
int wx1, wx2, wy1, wy2;
cropx= 0;
cropw= sink->windowWidth;
cropy= 0;
croph= sink->windowHeight;
if ( (vx < sink->windowX) || (vx+vw > sink->windowX+sink->windowWidth) )
{
GST_LOG("wstSetTextureCrop: CX1");
cropx= (sink->windowX-vx)*sink->windowWidth/vw;
cropw= (sink->windowX+sink->windowWidth-vx)*sink->windowWidth/vw - cropx;
}
else if ( vx < 0 )
{
GST_LOG("wstSetTextureCrop: CX2");
cropx= -vx*sink->windowWidth/vw;
cropw= (vw+vx)*sink->windowWidth/vw;
}
else if ( vx+vw > sink->windowWidth )
{
GST_LOG("wstSetTextureCrop: CX3");
cropx= 0;
cropw= (sink->windowWidth-vx)*sink->windowWidth/vw;
}
if ( (vy < sink->windowY) || (vy+vh > sink->windowY+sink->windowHeight) )
{
GST_LOG("wstSetTextureCrop: CY1");
cropy= (sink->windowY-vy)*sink->windowHeight/vh;
croph= (sink->windowY+sink->windowHeight-vy)*sink->windowHeight/vh - cropy;
}
else if ( vy < 0 )
{
GST_LOG("wstSetTextureCrop: CY2");
cropy= -vy*sink->windowHeight/vh;
croph= (vh+vy)*sink->windowHeight/vh;
}
else if ( vy+vh > sink->windowHeight )
{
GST_LOG("wstSetTextureCrop: CY3");
cropy= 0;
croph= (sink->windowHeight-vy)*sink->windowHeight/vh;
}
wx1= vx;
wx2= vx+vw;
wy1= vy;
wy2= vy+vh;
vx= sink->windowX;
vy= sink->windowY;
vw= sink->windowWidth;
vh= sink->windowHeight;
if ( (wx1 > vx) && (wx1 > 0) )
{
GST_LOG("wstSetTextureCrop: WX1");
vx= wx1;
}
else if ( (wx1 >= vx) && (wx1 < 0) )
{
GST_LOG("wstSetTextureCrop: WX2");
vw += wx1;
vx= 0;
}
else if ( wx2 < vx+vw )
{
GST_LOG("wstSetTextureCrop: WX3");
vw= wx2-vx;
}
if ( (wx1 >= 0) && (wx2 > vw) )
{
GST_LOG("wstSetTextureCrop: WX4");
vw= vw-wx1;
}
else if ( wx2 < vx+vw )
{
GST_LOG("wstSetTextureCrop: WX5");
vw= wx2-vx;
}
if ( (wy1 > vy) && (wy1 > 0) )
{
GST_LOG("wstSetTextureCrop: WY1");
vy= wy1;
}
else if ( (wy1 >= vy) && (wy1 < 0) )
{
GST_LOG("wstSetTextureCrop: WY2");
vy= 0;
}
else if ( (wy1 < vy) && (wy1 > 0) )
{
GST_LOG("wstSetTextureCrop: WY3");
vh -= wy1;
}
if ( (wy1 >= 0) && (wy2 > vh) )
{
GST_LOG("wstSetTextureCrop: WY4");
vh= vh-wy1;
}
else if ( wy2 < vy+vh )
{
GST_LOG("wstSetTextureCrop: WY5");
vh= wy2-vy;
}
if ( vw < 0 ) vw= 0;
if ( vh < 0 ) vh= 0;
cropx= (cropx*WL_VPC_SURFACE_CROP_DENOM)/sink->windowWidth;
cropy= (cropy*WL_VPC_SURFACE_CROP_DENOM)/sink->windowHeight;
cropw= (cropw*WL_VPC_SURFACE_CROP_DENOM)/sink->windowWidth;
croph= (croph*WL_VPC_SURFACE_CROP_DENOM)/sink->windowHeight;
GST_DEBUG("wstSetTextureCrop: %d, %d, %d, %d - %d, %d, %d, %d", vx, vy, vw, vh, cropx, cropy, cropw, croph);
wl_vpc_surface_set_geometry_with_crop( sink->vpcSurface, vx, vy, vw, vh, cropx, cropy, cropw, croph );
}
else
{
wl_vpc_surface_set_geometry( sink->vpcSurface, vx, vy, vw, vh );
}
}
static void wstProcessTextureSignal( GstWesterosSink *sink, int buffIndex )
{
int fd0, l0, s0, fd1, l1, fd2, s1, l2, s2;
void *p0, *p1, *p2;
if ( sink->soc.outBuffers[buffIndex].planeCount > 1 )
{
fd0= sink->soc.outBuffers[buffIndex].planeInfo[0].fd;
fd1= sink->soc.outBuffers[buffIndex].planeInfo[1].fd;
fd2= -1;
s0= sink->soc.fmtOut.fmt.pix_mp.plane_fmt[0].bytesperline;
s1= sink->soc.fmtOut.fmt.pix_mp.plane_fmt[1].bytesperline;
s2= 0;
l0= s0*sink->soc.fmtOut.fmt.pix.height;
l1= s0*sink->soc.fmtOut.fmt.pix.height/2;
l2= 0;
p0= sink->soc.outBuffers[buffIndex].planeInfo[0].start;
p1= sink->soc.outBuffers[buffIndex].planeInfo[1].start;
p2= 0;
}
else
{
fd0= sink->soc.outBuffers[buffIndex].fd;
fd1= fd0;
fd2= -1;
if ( sink->soc.isMultiPlane )
s0= sink->soc.fmtOut.fmt.pix_mp.plane_fmt[0].bytesperline;
else
s0= sink->soc.fmtOut.fmt.pix.bytesperline;
s1= s0;
s2= 0;
l0= s0*sink->soc.fmtOut.fmt.pix.height;
l1= s0*sink->soc.fmtOut.fmt.pix.height/2;
l2= 0;
p0= sink->soc.outBuffers[buffIndex].start;
p1= (char*)p0 + s0*sink->soc.fmtOut.fmt.pix.height;
p2= 0;
}
g_signal_emit( G_OBJECT(sink),
g_signals[SIGNAL_NEWTEXTURE],
0,
sink->soc.outputFormat,
sink->soc.frameWidth,
sink->soc.frameHeight,
fd0, l0, s0, p0,
fd1, l1, s1, p1,
fd2, l2, s2, p2
);
}
static bool wstProcessTextureWayland( GstWesterosSink *sink, int buffIndex )
{
bool result= false;
bufferInfo *binfo;
if ( !sink->show ) return result;
GST_LOG("Video out: fd %d", sink->soc.outBuffers[buffIndex].fd );
binfo= (bufferInfo*)malloc( sizeof(bufferInfo) );
if ( binfo )
{
binfo->sink= sink;
binfo->buffIndex= buffIndex;
binfo->cohort= sink->soc.bufferCohort;
struct wl_buffer *wlbuff;
if ( sink->soc.outBuffers[buffIndex].planeCount > 1 )
{
int fd0, fd1, fd2;
int stride0, stride1, stride2;
int offset1= 0;
fd0= sink->soc.outBuffers[buffIndex].planeInfo[0].fd;
fd1= sink->soc.outBuffers[buffIndex].planeInfo[1].fd;
fd2= sink->soc.outBuffers[buffIndex].planeInfo[2].fd;
stride0= sink->soc.fmtOut.fmt.pix_mp.plane_fmt[0].bytesperline;
stride1= sink->soc.fmtOut.fmt.pix_mp.plane_fmt[1].bytesperline;
stride2= sink->soc.fmtOut.fmt.pix_mp.plane_fmt[2].bytesperline;
if ( fd1 < 0 )
{
fd1= fd0;
stride1= stride0;
offset1= stride0*sink->soc.fmtOut.fmt.pix.height;
}
if ( fd2 < 0 ) fd2= fd0;
wlbuff= wl_sb_create_planar_buffer_fd2( sink->soc.sb,
fd0,
fd1,
fd2,
sink->soc.frameWidth,
sink->soc.frameHeight,
sink->soc.outputFormat,
0, /* offset0 */
offset1, /* offset1 */
0, /* offset2 */
stride0, /* stride0 */
stride1, /* stride1 */
0 /* stride2 */
);
}
else
{
int stride;
if ( sink->soc.isMultiPlane )
stride= sink->soc.fmtOut.fmt.pix_mp.plane_fmt[0].bytesperline;
else
stride= sink->soc.fmtOut.fmt.pix.bytesperline;
wlbuff= wl_sb_create_planar_buffer_fd( sink->soc.sb,
sink->soc.outBuffers[buffIndex].fd,
sink->soc.frameWidth,
sink->soc.frameHeight,
sink->soc.outputFormat,
0, /* offset0 */
stride*sink->soc.fmtOut.fmt.pix.height, /* offset1 */
0, /* offset2 */
stride, /* stride0 */
stride, /* stride1 */
0 /* stride2 */
);
}
if ( wlbuff )
{
FRAME("out: wayland send frame %d buffer %d (%d)", sink->soc.frameOutCount-1, sink->soc.outBuffers[buffIndex].bufferId, buffIndex);
wl_buffer_add_listener( wlbuff, &wl_buffer_listener, binfo );
wl_surface_attach( sink->surface, wlbuff, sink->windowX, sink->windowY );
wl_surface_damage( sink->surface, 0, 0, sink->windowWidth, sink->windowHeight );
wl_surface_commit( sink->surface );
wl_display_flush( sink->display );
wstLockOutputBuffer( sink, buffIndex );
++sink->soc.activeBuffers;
result= true;;
/* Advance any frames sent to video server towards requeueing to decoder */
sink->soc.resubFd= sink->soc.prevFrame2Fd;
sink->soc.prevFrame2Fd=sink->soc.prevFrame1Fd;
sink->soc.prevFrame1Fd= sink->soc.nextFrameFd;
sink->soc.nextFrameFd= -1;
if ( sink->soc.framesBeforeHideVideo )
{
if ( --sink->soc.framesBeforeHideVideo == 0 )
{
wstSendHideVideoClientConnection( sink->soc.conn, true );
if ( !sink->soc.useGfxSync )
{
wstSendFlushVideoClientConnection( sink->soc.conn );
}
}
}
}
else
{
free( binfo );
}
}
return result;
}
static int wstFindVideoBuffer( GstWesterosSink *sink, int frameNumber )
{
int buffIndex= -1;
int i;
for( i= 0; i < sink->soc.numBuffersOut; ++i )
{
if ( sink->soc.outBuffers[i].locked )
{
if ( sink->soc.outBuffers[i].frameNumber == frameNumber )
{
buffIndex= i;
break;
}
}
}
return buffIndex;
}
static int wstFindCurrentVideoBuffer( GstWesterosSink *sink )
{
int buffIndex= -1;
int i, oldestFrame= INT_MAX;
for( i= 0; i < sink->soc.numBuffersOut; ++i )
{
if ( sink->soc.outBuffers[i].locked )
{
if ( (sink->soc.outBuffers[i].frameNumber >= 0) && (sink->soc.outBuffers[i].frameNumber < oldestFrame) )
{
oldestFrame= sink->soc.outBuffers[i].frameNumber;
buffIndex= i;
}
}
}
return buffIndex;
}
static gpointer wstVideoOutputThread(gpointer data)
{
GstWesterosSink *sink= (GstWesterosSink*)data;
struct v4l2_selection selection;
int i, j, buffIndex, rc;
int32_t bufferType;
bool wasPaused= false;
bool havePriEvent;
GST_DEBUG("wstVideoOutputThread: enter");
capture_start:
havePriEvent= false;
if ( sink->soc.numBuffersOut )
{
LOCK(sink);
if ( (sink->soc.v4l2Fd == -1) || (sink->soc.outBuffers == 0) || sink->soc.quitVideoOutputThread )
{
UNLOCK(sink);
if ( !sink->soc.quitVideoOutputThread )
{
GST_ERROR("wstVideoOutputThread: v4l2Fd %d outBuffers %p", sink->soc.v4l2Fd, sink->soc.outBuffers);
postDecodeError( sink, "no dev/no outBuffers" );
}
goto exit;
}
for( i= 0; i < sink->soc.numBuffersOut; ++i )
{
if ( sink->soc.isMultiPlane )
{
for( j= 0; j < sink->soc.outBuffers[i].planeCount; ++j )
{
sink->soc.outBuffers[i].buf.m.planes[j].bytesused= sink->soc.outBuffers[i].buf.m.planes[j].length;
}
}
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_QBUF, &sink->soc.outBuffers[i].buf );
if ( rc < 0 )
{
GST_ERROR("wstVideoOutputThread: failed to queue output buffer: rc %d errno %d", rc, errno);
UNLOCK(sink);
postDecodeError( sink, "output enqueue error" );
goto exit;
}
++sink->soc.outQueuedCount;
sink->soc.outBuffers[i].queued= true;
}
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_STREAMON, &sink->soc.fmtOut.type );
if ( rc < 0 )
{
GST_ERROR("wstVideoOutputThread: streamon failed for output: rc %d errno %d", rc, errno );
UNLOCK(sink);
postDecodeError( sink, "STREAMON failure" );
goto exit;
}
sink->soc.decoderLastFrame= 0;
bufferType= sink->soc.isMultiPlane ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE :V4L2_BUF_TYPE_VIDEO_CAPTURE;
memset( &selection, 0, sizeof(selection) );
selection.type= bufferType;
selection.target= V4L2_SEL_TGT_COMPOSE_DEFAULT;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_G_SELECTION, &selection );
if ( rc < 0 )
{
bufferType= V4L2_BUF_TYPE_VIDEO_CAPTURE;
memset( &selection, 0, sizeof(selection) );
selection.type= bufferType;
selection.target= V4L2_SEL_TGT_COMPOSE_DEFAULT;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_G_SELECTION, &selection );
if ( rc < 0 )
{
GST_WARNING("wstVideoOutputThread: failed to get compose rect: rc %d errno %d", rc, errno );
}
}
GST_DEBUG("Out compose default: (%d, %d, %d, %d)", selection.r.left, selection.r.top, selection.r.width, selection.r.height );
memset( &selection, 0, sizeof(selection) );
selection.type= bufferType;
selection.target= V4L2_SEL_TGT_COMPOSE;
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_G_SELECTION, &selection );
if ( rc < 0 )
{
GST_WARNING("wstVideoOutputThread: failed to get compose rect: rc %d errno %d", rc, errno );
}
GST_DEBUG("Out compose: (%d, %d, %d, %d)", selection.r.left, selection.r.top, selection.r.width, selection.r.height );
if ( rc == 0 )
{
sink->soc.frameWidth= selection.r.width;
sink->soc.frameHeight= selection.r.height;
}
wstSetSessionInfo( sink );
UNLOCK(sink);
g_print("westeros-sink: frame size %dx%d\n", sink->soc.frameWidth, sink->soc.frameHeight);
if ( sink->segment.applied_rate != 1.0 )
{
GST_DEBUG("applied rate %f : force calculation of framerate", sink->segment.applied_rate);
sink->soc.frameRate= 0.0;
sink->soc.frameRateFractionNum= 0;
sink->soc.frameRateFractionDenom= 1;
sink->soc.frameRateChanged= TRUE;
sink->queryPositionFromPeer= FALSE;
}
}
for( ; ; )
{
if ( sink->soc.emitFirstFrameSignal )
{
sink->soc.emitFirstFrameSignal= FALSE;
GST_DEBUG("wstVideoOutputThread: emit first frame signal");
g_signal_emit (G_OBJECT (sink), g_signals[SIGNAL_FIRSTFRAME], 0, 2, NULL);
}
if ( sink->soc.emitUnderflowSignal )
{
sink->soc.emitUnderflowSignal= FALSE;
GST_DEBUG("wstVideoOutputThread: emit underflow signal");
g_signal_emit (G_OBJECT (sink), g_signals[SIGNAL_UNDERFLOW], 0, 0, NULL);
}
if ( sink->soc.quitVideoOutputThread )
{
break;
}
else if ( sink->soc.videoPaused && !sink->soc.frameAdvance )
{
if ( !wasPaused )
{
LOCK(sink);
wstSendPauseVideoClientConnection( sink->soc.conn, true);
UNLOCK(sink);
}
wasPaused= true;
if ( sink->windowChange )
{
sink->windowChange= false;
gst_westeros_sink_soc_update_video_position( sink );
}
if ( sink->soc.pauseException )
{
LOCK(sink);
sink->soc.pauseException= FALSE;
if ( sink->soc.useGfxSync && sink->soc.pauseGetGfxFrame )
{
sink->soc.pauseGetGfxFrame= FALSE;
buffIndex= wstFindCurrentVideoBuffer( sink );
if ( buffIndex >= 0 )
{
sink->soc.pauseGfxBuffIndex= buffIndex;
if ( sink->soc.enableTextureSignal )
{
wstProcessTextureSignal( sink, buffIndex );
}
else if ( sink->soc.captureEnabled && sink->soc.sb )
{
wstProcessTextureWayland( sink, buffIndex );
}
}
}
UNLOCK(sink);
}
if ( sink->soc.hasEvents )
{
struct pollfd pfd;
pfd.fd= sink->soc.v4l2Fd;
pfd.events= POLLIN | POLLRDNORM | POLLPRI;
pfd.revents= 0;
poll( &pfd, 1, 0);
if ( sink->soc.quitVideoOutputThread ) break;
/* check events if streaming is starting or we have reached last frame */
if ( (!sink->soc.numBuffersOut || (sink->soc.decoderLastFrame || sink->soc.expectNoLastFrame)) &&
(havePriEvent || (pfd.revents & POLLPRI)) )
{
havePriEvent= false;
wstProcessEvents( sink );
if ( sink->soc.needCaptureRestart )
{
break;
}
}
if ( sink->soc.quitVideoOutputThread ) break;
if ( pfd.revents & (POLLIN|POLLRDNORM) )
{
goto capture_ready;
}
}
usleep( 1000 );
}
else
{
int rc;
LOCK(sink);
wstProcessMessagesVideoClientConnection( sink->soc.conn );
if ( sink->windowChange )
{
sink->windowChange= false;
gst_westeros_sink_soc_update_video_position( sink );
if ( !sink->soc.captureEnabled )
{
wstSendRectVideoClientConnection(sink->soc.conn);
}
}
if ( sink->soc.showChanged )
{
sink->soc.showChanged= FALSE;
if ( !sink->soc.captureEnabled )
{
wstSendHideVideoClientConnection( sink->soc.conn, !sink->show );
}
}
if ( sink->soc.frameRateChanged )
{
sink->soc.frameRateChanged= FALSE;
wstSendRateVideoClientConnection( sink->soc.conn );
}
if ( wasPaused && !sink->soc.videoPaused )
{
#ifdef USE_AMLOGIC_MESON_MSYNC
if ( !sink->soc.userSession )
#endif
{
sink->soc.updateSession= TRUE;
}
wstSendPauseVideoClientConnection( sink->soc.conn, false);
wasPaused= false;
}
if ( sink->soc.updateSession )
{
sink->soc.updateSession= FALSE;
wstSetSessionInfo( sink );
}
UNLOCK(sink);
if ( sink->soc.hasEvents )
{
struct pollfd pfd;
pfd.fd= sink->soc.v4l2Fd;
pfd.events= POLLIN | POLLRDNORM | POLLPRI;
pfd.revents= 0;
poll( &pfd, 1, 0);
if ( sink->soc.quitVideoOutputThread ) break;
if ( (pfd.revents & (POLLIN|POLLRDNORM)) == 0 )
{
/* check events if streaming is starting or we have reached last frame */
if ( (!sink->soc.numBuffersOut || (sink->soc.decoderLastFrame || sink->soc.expectNoLastFrame)) &&
(havePriEvent || (pfd.revents & POLLPRI)) )
{
pfd.revents &= ~POLLPRI;
havePriEvent= false;
wstProcessEvents( sink );
if ( sink->soc.needCaptureRestart )
{
break;
}
}
if ( (sink->soc.frameDecodeCount == 0) && (sink->soc.frameInCount > 0) && !sink->soc.videoPaused && !sink->soc.decodeError )
{
gint64 now= g_get_monotonic_time();
float frameRate= (sink->soc.frameRate != 0.0 ? sink->soc.frameRate : 30.0);
float frameDelay= sink->soc.frameInCount / frameRate;
if ( (frameDelay > 1.0) && (now-sink->soc.videoStartTime > 3000000LL) )
{
sink->soc.decodeError= TRUE;
postDecodeError( sink, "no output from decoder" );
goto exit;
}
}
usleep( 1000 );
continue;
}
if ( pfd.revents & POLLPRI )
{
havePriEvent= true;
}
}
capture_ready:
buffIndex= wstGetOutputBuffer( sink );
if ( sink->soc.quitVideoOutputThread ) break;
if ( buffIndex < 0 )
{
usleep( 1000 );
continue;
}
if ( (sink->soc.outBuffers[buffIndex].buf.flags & V4L2_BUF_FLAG_LAST) &&
(sink->soc.outBuffers[buffIndex].buf.bytesused == 0) )
{
/* last frame has been indicated. */
GST_DEBUG("skip empty last buffer");
sink->soc.decoderLastFrame= 1;
if ( havePriEvent )
{
havePriEvent= false;
wstProcessEvents( sink );
if ( sink->soc.needCaptureRestart )
{
break;
}
}
continue;
}
++sink->soc.frameDecodeCount;
{
gint64 currFramePTS= 0;
bool gfxFrame= false;
sink->soc.resubFd= -1;
if ( sink->soc.outBuffers[buffIndex].buf.timestamp.tv_sec != -1 )
{
currFramePTS= sink->soc.outBuffers[buffIndex].buf.timestamp.tv_sec * 1000000LL + sink->soc.outBuffers[buffIndex].buf.timestamp.tv_usec;
}
if ( (currFramePTS == 0) && (sink->soc.frameDecodeCount > 1) )
{
double rate= (sink->soc.interlaced ? sink->soc.frameRate*2 : sink->soc.frameRate);
currFramePTS= sink->soc.prevDecodedTimestamp + 1000000LL/rate;
sink->soc.outBuffers[buffIndex].buf.timestamp.tv_sec= currFramePTS / 1000000LL;
sink->soc.outBuffers[buffIndex].buf.timestamp.tv_usec= currFramePTS % 1000000LL;
}
if ( (sink->soc.frameRateFractionNum == 0) && (sink->soc.frameDecodeCount > 1) )
{
long long period= currFramePTS - sink->soc.prevDecodedTimestamp;
if ( period > 0 )
{
double rate= 1000000.0/period;
sink->soc.frameRateFractionNum= rate*1000;
sink->soc.frameRateFractionDenom= 1000;
sink->soc.frameRateChanged= TRUE;
g_print("westeros-sink: infer rate of %f: %d/%d\n", rate, sink->soc.frameRateFractionNum, sink->soc.frameRateFractionDenom );
}
}
sink->soc.prevDecodedTimestamp= currFramePTS;
guint64 frameTime= sink->soc.outBuffers[buffIndex].buf.timestamp.tv_sec * 1000000000LL + sink->soc.outBuffers[buffIndex].buf.timestamp.tv_usec * 1000LL;
FRAME("out: frame %d buffer %d (%d) PTS %lld decoded", sink->soc.frameOutCount, sink->soc.outBuffers[buffIndex].bufferId, buffIndex, frameTime);
avProgLog( frameTime, 0, "DtoS", wstOutFullness(sink));
wstUpdatePixelAspectRatio( sink );
#ifdef USE_GST_AFD
wstUpdateAFDInfo( sink );
#endif
sink->soc.outBuffers[buffIndex].frameTime= currFramePTS;
LOCK(sink);
if ( wstLocalRateControl( sink, buffIndex ) )
{
wstRequeueOutputBuffer( sink, buffIndex );
UNLOCK(sink);
continue;
}
if ( !sink->soc.conn )
{
/* If we are not connected to a video server, set position here */
gint64 firstNano= ((sink->firstPTS/90LL)*GST_MSECOND)+((sink->firstPTS%90LL)*GST_MSECOND/90LL);
sink->position= sink->positionSegmentStart + frameTime - firstNano;
sink->currentPTS= frameTime / (GST_SECOND/90000LL);
if ( sink->timeCodePresent && sink->enableTimeCodeSignal )
{
sink->timeCodePresent( sink, sink->position, g_signals[SIGNAL_TIMECODE] );
}
}
if ( sink->soc.quitVideoOutputThread )
{
UNLOCK(sink);
break;
}
if ( !sink->soc.conn && (sink->soc.frameOutCount == 0))
{
sink->soc.emitFirstFrameSignal= TRUE;
}
++sink->soc.frameOutCount;
if ( !sink->soc.useGfxSync || !sink->soc.conn )
{
if ( sink->soc.enableTextureSignal )
{
gfxFrame= true;
wstProcessTextureSignal( sink, buffIndex );
}
else if ( sink->soc.captureEnabled && sink->soc.sb )
{
if ( wstProcessTextureWayland( sink, buffIndex ) )
{
gfxFrame= true;
buffIndex= -1;
}
}
}
if ( sink->soc.conn && !gfxFrame )
{
sink->soc.resubFd= sink->soc.prevFrame2Fd;
sink->soc.prevFrame2Fd= sink->soc.prevFrame1Fd;
sink->soc.prevFrame1Fd= sink->soc.nextFrameFd;
sink->soc.nextFrameFd= sink->soc.outBuffers[buffIndex].fd;
if ( wstSendFrameVideoClientConnection( sink->soc.conn, buffIndex ) )
{
buffIndex= -1;
}
if ( sink->soc.framesBeforeHideGfx )
{
if ( --sink->soc.framesBeforeHideGfx == 0 )
{
wl_surface_attach( sink->surface, 0, sink->windowX, sink->windowY );
wl_surface_damage( sink->surface, 0, 0, sink->windowWidth, sink->windowHeight );
wl_surface_commit( sink->surface );
wl_display_flush(sink->display);
UNLOCK(sink);
wl_display_dispatch_queue_pending(sink->display, sink->queue);
LOCK(sink);
if ( sink->show )
{
wstSendHideVideoClientConnection( sink->soc.conn, false );
}
}
}
}
if ( sink->soc.resubFd >= 0 )
{
buffIndex= wstFindOutputBuffer( sink, sink->soc.resubFd );
GST_LOG( "%lld: resub: frame fd %d index %d", getCurrentTimeMillis(), sink->soc.resubFd, buffIndex);
sink->soc.resubFd= -1;
}
if ( buffIndex >= 0 )
{
wstRequeueOutputBuffer( sink, buffIndex );
}
if ( ((sink->soc.frameDecodeCount % QOS_INTERVAL) == 0) && sink->soc.frameInCount )
{
GstMessage *msg= gst_message_new_qos( GST_OBJECT_CAST(sink),
FALSE, /* live */
(sink->position-sink->positionSegmentStart), /* running time */
(sink->position-sink->positionSegmentStart), /* stream time */
sink->position, /* timestamp */
16000000UL /* duration */ );
if ( msg )
{
gst_message_set_qos_stats( msg,
GST_FORMAT_BUFFERS,
sink->soc.frameInCount,
sink->soc.numDropped );
GST_INFO("post QoS: processed %u dropped %u", sink->soc.frameInCount, sink->soc.numDropped);
if ( !gst_element_post_message( GST_ELEMENT(sink), msg ) )
{
GST_WARNING("unable to post QoS");
gst_message_unref( msg );
}
}
}
if ( sink->soc.frameAdvance )
{
sink->soc.frameAdvance= FALSE;
wstSendFrameAdvanceVideoClientConnection( sink->soc.conn );
}
UNLOCK(sink);
}
}
}
if ( sink->soc.needCaptureRestart )
{
sink->soc.needCaptureRestart= FALSE;
goto capture_start;
}
exit:
LOCK(sink);
wstSendFlushVideoClientConnection( sink->soc.conn );
UNLOCK(sink);
GST_DEBUG("wstVideoOutputThread: exit");
return NULL;
}
static gpointer wstEOSDetectionThread(gpointer data)
{
GstWesterosSink *sink= (GstWesterosSink*)data;
int outputFrameCount, count, eosCountDown;
int decoderEOS, displayCount;
bool videoPlaying;
bool eosEventSeen;
double frameRate;
GST_DEBUG("wstVideoEOSThread: enter");
eosCountDown= 10;
LOCK(sink)
outputFrameCount= sink->soc.frameOutCount;
frameRate= (sink->soc.frameRate > 0.0 ? sink->soc.frameRate : 30.0);
UNLOCK(sink);
while( !sink->soc.quitEOSDetectionThread )
{
usleep( 1000000/frameRate );
if ( !sink->soc.quitEOSDetectionThread )
{
LOCK(sink)
count= sink->soc.frameOutCount;
displayCount= sink->soc.frameDisplayCount + sink->soc.numDropped;
decoderEOS= sink->soc.decoderEOS;
videoPlaying= sink->soc.videoPlaying;
eosEventSeen= sink->eosEventSeen;
UNLOCK(sink)
if ( videoPlaying && eosEventSeen && decoderEOS && (count == displayCount) && (outputFrameCount == count) )
{
--eosCountDown;
if ( eosCountDown == 0 )
{
g_print("westeros-sink: EOS detected\n");
if ( swIsSWDecode( sink ) )
{
GST_DEBUG_OBJECT(sink, "gst_westeros_sink_eos_detected: posting EOS");
gst_element_post_message (GST_ELEMENT_CAST(sink), gst_message_new_eos(GST_OBJECT_CAST(sink)));
}
else
{
gst_westeros_sink_eos_detected( sink );
}
break;
}
}
else
{
outputFrameCount= count;
eosCountDown= 10;
}
}
}
if ( !sink->soc.quitEOSDetectionThread )
{
GThread *thread= sink->soc.eosDetectionThread;
g_thread_unref( sink->soc.eosDetectionThread );
sink->soc.eosDetectionThread= NULL;
}
GST_DEBUG("wstVideoEOSThread: exit");
return NULL;
}
static gpointer wstDispatchThread(gpointer data)
{
GstWesterosSink *sink= (GstWesterosSink*)data;
if ( sink->display )
{
GST_DEBUG("dispatchThread: enter");
while( !sink->soc.quitDispatchThread )
{
if ( wl_display_dispatch_queue( sink->display, sink->queue ) == -1 )
{
break;
}
}
GST_DEBUG("dispatchThread: exit");
}
return NULL;
}
static void postErrorMessage( GstWesterosSink *sink, int errorCode, const char *errorText, const char *description )
{
GError *error= g_error_new_literal(GST_STREAM_ERROR, errorCode, errorText);
g_print("westeros-sink: postErrorMessage: code %d (%s) (%s)\n", errorCode, errorText, description);
if ( error )
{
GstElement *parent= GST_ELEMENT_PARENT(GST_ELEMENT(sink));
GstMessage *msg= gst_message_new_error( GST_OBJECT(parent), error, errorText );
if ( msg )
{
if ( !gst_element_post_message( GST_ELEMENT(sink), msg ) )
{
GST_ERROR( "Error: gst_element_post_message failed for errorCode %d errorText (%s)", errorCode, errorText);
}
}
else
{
GST_ERROR( "Error: gst_message_new_error failed for errorCode %d errorText (%s)", errorCode, errorText);
}
}
else
{
GST_ERROR("Error: g_error_new_literal failed for errorCode %d errorText (%s)", errorCode, errorText );
}
}
static GstFlowReturn prerollSinkSoc(GstBaseSink *base_sink, GstBuffer *buffer)
{
GstWesterosSink *sink= GST_WESTEROS_SINK(base_sink);
if ( swIsSWDecode( sink ) )
{
goto done;
}
sink->soc.videoPlaying= TRUE;
if ( GST_BASE_SINK(sink)->need_preroll && !GST_BASE_SINK(sink)->have_preroll )
{
if ( sink->soc.prerollBuffer != buffer )
{
gst_westeros_sink_soc_render( sink, buffer );
sink->soc.prerollBuffer= buffer;
}
}
if ( sink->soc.frameStepOnPreroll )
{
LOCK(sink);
sink->soc.frameAdvance= TRUE;
UNLOCK(sink);
GST_BASE_SINK(sink)->need_preroll= FALSE;
GST_BASE_SINK(sink)->have_preroll= TRUE;
}
done:
GST_INFO("preroll ok");
return GST_FLOW_OK;
}
static int sinkAcquireVideo( GstWesterosSink *sink )
{
int result= 0;
int rc, len;
struct v4l2_exportbuffer eb;
LOCK(sink);
GST_DEBUG("sinkAcquireVideo: enter");
if ( sink->rm && sink->resAssignedId >= 0 )
{
if ( swIsSWDecode( sink ) )
{
result= 1;
goto exit;
}
}
sink->soc.v4l2Fd= open( sink->soc.devname, O_RDWR | O_CLOEXEC );
if ( sink->soc.v4l2Fd < 0 )
{
GST_ERROR("failed to open device (%s)", sink->soc.devname );
goto exit;
}
rc= IOCTL( sink->soc.v4l2Fd, VIDIOC_QUERYCAP, &sink->soc.caps );
if ( rc < 0 )
{
GST_ERROR("failed query caps: %d errno %d", rc, errno);
goto exit;
}
GST_DEBUG("driver (%s) card(%s) bus_info(%s) version %d capabilities %X device_caps %X",
sink->soc.caps.driver, sink->soc.caps.card, sink->soc.caps.bus_info, sink->soc.caps.version, sink->soc.caps.capabilities, sink->soc.caps.device_caps );
sink->soc.deviceCaps= (sink->soc.caps.capabilities & V4L2_CAP_DEVICE_CAPS ) ? sink->soc.caps.device_caps : sink->soc.caps.capabilities;
if ( !(sink->soc.deviceCaps & (V4L2_CAP_VIDEO_M2M | V4L2_CAP_VIDEO_M2M_MPLANE) ))
{
GST_ERROR("device (%s) is not a M2M device", sink->soc.devname );
goto exit;
}
if ( !(sink->soc.deviceCaps & V4L2_CAP_STREAMING) )
{
GST_ERROR("device (%s) does not support dmabuf: no V4L2_CAP_STREAMING", sink->soc.devname );
goto exit;
}
if ( (sink->soc.deviceCaps & V4L2_CAP_VIDEO_M2M_MPLANE) && !(sink->soc.deviceCaps & V4L2_CAP_VIDEO_M2M) )
{
GST_DEBUG("device is multiplane");
sink->soc.isMultiPlane= TRUE;
}
len= strlen( (char*)sink->soc.caps.driver );
if ( (len == 14) && !strncmp( (char*)sink->soc.caps.driver, "aml-vcodec-dec", len) )
{
sink->soc.hideVideoFramesDelay= 2;
sink->soc.hideGfxFramesDelay= 3;
sink->soc.useGfxSync= TRUE;
}
eb.type= V4L2_BUF_TYPE_VIDEO_CAPTURE;
eb.index= -1;
eb.plane= -1;
eb.flags= (O_RDWR|O_CLOEXEC);
IOCTL( sink->soc.v4l2Fd, VIDIOC_EXPBUF, &eb );
if ( errno == ENOTTY )
{
GST_ERROR("device (%s) does not support dmabuf: no VIDIOC_EXPBUF", sink->soc.devname );
goto exit;
}
wstGetInputFormats( sink );
wstGetOutputFormats( sink );
wstGetMaxFrameSize( sink );
result= 1;
exit:
GST_DEBUG("sinkAcquireVideo: exit: %d", result);
UNLOCK(sink);
return result;
}
static void sinkReleaseVideo( GstWesterosSink *sink )
{
GST_DEBUG("sinkReleaseVideo: enter");
wstSinkSocStopVideo( sink );
GST_DEBUG("sinkReleaseVideo: exit");
}
static bool swIsSWDecode( GstWesterosSink *sink )
{
bool result= false;
#ifdef ENABLE_SW_DECODE
if ( sink->rm && sink->resAssignedId >= 0 )
{
if ( sink->resCurrCaps.capabilities & EssRMgrVidCap_software )
{
result= true;
}
}
#endif
return result;
}
#ifdef ENABLE_SW_DECODE
static void swFreeSWBuffer( GstWesterosSink *sink, int buffIndex )
{
int i;
for( i= 0; i < 2; ++i )
{
int *fd, *handle;
if ( i == 0 )
{
fd= &sink->soc.swBuffer[buffIndex].fd0;
handle= &sink->soc.swBuffer[buffIndex].handle0;
}
else
{
fd= &sink->soc.swBuffer[buffIndex].fd1;
handle= &sink->soc.swBuffer[buffIndex].handle1;
}
if ( *fd >= 0 )
{
close( *fd );
*fd= -1;
}
if ( *handle )
{
struct drm_mode_destroy_dumb destroyDumb;
destroyDumb.handle= *handle;
ioctl( sink->soc.drmFd, DRM_IOCTL_MODE_DESTROY_DUMB, &destroyDumb );
*handle= 0;
}
}
}
static bool swAllocSWBuffer( GstWesterosSink *sink, int buffIndex, int width, int height )
{
bool result= false;
WstSWBuffer *swBuff= 0;
if ( buffIndex < WST_NUM_SW_BUFFERS )
{
struct drm_mode_create_dumb createDumb;
struct drm_mode_map_dumb mapDumb;
int i, rc;
swBuff= &sink->soc.swBuffer[buffIndex];
swBuff->width= width;
swBuff->height= height;
memset( &createDumb, 0, sizeof(createDumb) );
createDumb.width= width;
createDumb.height= height;
createDumb.bpp= 8;
rc= ioctl( sink->soc.drmFd, DRM_IOCTL_MODE_CREATE_DUMB, &createDumb );
if ( rc )
{
GST_ERROR("DRM_IOCTL_MODE_CREATE_DUMB failed: rc %d errno %d", rc, errno);
goto exit;
}
memset( &mapDumb, 0, sizeof(mapDumb) );
mapDumb.handle= createDumb.handle;
rc= ioctl( sink->soc.drmFd, DRM_IOCTL_MODE_MAP_DUMB, &mapDumb );
if ( rc )
{
GST_ERROR("DRM_IOCTL_MODE_MAP_DUMB failed: rc %d errno %d", rc, errno);
goto exit;
}
swBuff->handle0= createDumb.handle;
swBuff->pitch0= createDumb.pitch;
swBuff->size0= createDumb.size;
swBuff->offset0= mapDumb.offset;
rc= drmPrimeHandleToFD( sink->soc.drmFd, swBuff->handle0, DRM_CLOEXEC | DRM_RDWR, &swBuff->fd0 );
if ( rc )
{
GST_ERROR("drmPrimeHandleToFD failed: rc %d errno %d", rc, errno);
goto exit;
}
memset( &createDumb, 0, sizeof(createDumb) );
createDumb.width= width;
createDumb.height= height/2;
createDumb.bpp= 8;
rc= ioctl( sink->soc.drmFd, DRM_IOCTL_MODE_CREATE_DUMB, &createDumb );
if ( rc )
{
GST_ERROR("DRM_IOCTL_MODE_CREATE_DUMB failed: rc %d errno %d", rc, errno);
goto exit;
}
memset( &mapDumb, 0, sizeof(mapDumb) );
mapDumb.handle= createDumb.handle;
rc= ioctl( sink->soc.drmFd, DRM_IOCTL_MODE_MAP_DUMB, &mapDumb );
if ( rc )
{
GST_ERROR("DRM_IOCTL_MODE_MAP_DUMB failed: rc %d errno %d", rc, errno);
goto exit;
}
swBuff->handle1= createDumb.handle;
swBuff->pitch1= createDumb.pitch;
swBuff->size1= createDumb.size;
swBuff->offset1= mapDumb.offset;
rc= drmPrimeHandleToFD( sink->soc.drmFd, swBuff->handle1, DRM_CLOEXEC | DRM_RDWR, &swBuff->fd1 );
if ( rc )
{
GST_ERROR("drmPrimeHandleToFD failed: rc %d errno %d", rc, errno);
goto exit;
}
result= true;
}
exit:
if ( !result )
{
swFreeSWBuffer( sink, buffIndex );
}
return result;
}
WstSWBuffer *swGetSWBuffer( GstWesterosSink *sink, int buffIndex, int width, int height )
{
WstSWBuffer *swBuff= 0;
if ( buffIndex < WST_NUM_SW_BUFFERS )
{
swBuff= &sink->soc.swBuffer[buffIndex];
if ( (swBuff->width != width) || (swBuff->height != height) )
{
swFreeSWBuffer( sink, buffIndex );
if ( !swAllocSWBuffer( sink, buffIndex, width, height ) )
{
swBuff= 0;
}
}
}
return swBuff;
}
static gpointer swFirstFrameThread(gpointer data)
{
GstWesterosSink *sink= (GstWesterosSink*)data;
if ( sink )
{
GST_DEBUG("swFirstFrameThread: emit first frame signal");
g_signal_emit (G_OBJECT (sink), g_signals[SIGNAL_FIRSTFRAME], 0, 2, NULL);
g_thread_unref( sink->soc.firstFrameThread );
sink->soc.firstFrameThread= NULL;
}
return NULL;
}
static bool swInit( GstWesterosSink *sink )
{
GST_DEBUG("swInit");
sink->soc.drmFd= open( "/dev/dri/card0", O_RDWR | O_CLOEXEC);
if ( sink->soc.drmFd < 0 )
{
GST_ERROR("Failed to open drm render node: %d", errno);
goto exit;
}
exit:
return true;
}
static void swTerm( GstWesterosSink *sink )
{
int i;
GST_DEBUG("swTerm");
if ( sink->soc.eosDetectionThread )
{
sink->soc.quitEOSDetectionThread= TRUE;
g_thread_join( sink->soc.eosDetectionThread );
sink->soc.eosDetectionThread= NULL;
}
if ( sink->soc.dispatchThread )
{
sink->soc.quitDispatchThread= TRUE;
g_thread_join( sink->soc.dispatchThread );
sink->soc.dispatchThread= NULL;
}
for( i= 0; i < WST_NUM_SW_BUFFERS; ++i )
{
swFreeSWBuffer( sink, i );
}
if ( sink->soc.drmFd >= 0 )
{
close( sink->soc.drmFd );
sink->soc.drmFd= 1;
}
}
static void swLink( GstWesterosSink *sink )
{
WESTEROS_UNUSED(sink);
GST_DEBUG("swLink");
}
static void swUnLink( GstWesterosSink *sink )
{
GST_DEBUG("swUnLink");
if ( sink->display )
{
int fd= wl_display_get_fd( sink->display );
if ( fd >= 0 )
{
shutdown( fd, SHUT_RDWR );
}
}
}
static void swEvent( GstWesterosSink *sink, int id, int p1, void *p2 )
{
WESTEROS_UNUSED(p2);
GST_DEBUG("swEvent: id %d p1 %d p2 %p", id, p1, p2 );
switch( id )
{
case SWEvt_pause:
LOCK(sink);
sink->soc.videoPlaying= !(bool)p1;
UNLOCK(sink);
break;
default:
break;
}
}
void swDisplay( GstWesterosSink *sink, SWFrame *frame )
{
WstSWBuffer *swBuff= 0;
int bi;
GST_LOG("swDisplay: enter");
if ( sink->display )
{
if ( sink->soc.dispatchThread == NULL )
{
sink->soc.quitDispatchThread= FALSE;
GST_DEBUG_OBJECT(sink, "swDisplay: starting westeros_sink_dispatch thread");
sink->soc.dispatchThread= g_thread_new("westeros_sink_dispatch", wstDispatchThread, sink);
}
}
if ( sink->soc.eosDetectionThread == NULL )
{
sink->soc.videoPlaying= TRUE;;
sink->eosEventSeen= TRUE;
sink->soc.quitEOSDetectionThread= FALSE;
GST_DEBUG_OBJECT(sink, "swDisplay: starting westeros_sink_eos thread");
sink->soc.eosDetectionThread= g_thread_new("westeros_sink_eos", wstEOSDetectionThread, sink);
}
bi= sink->soc.nextSWBuffer;
if ( ++sink->soc.nextSWBuffer >= WST_NUM_SW_BUFFERS )
{
sink->soc.nextSWBuffer= 0;
}
swBuff= swGetSWBuffer( sink, bi, frame->width, frame->height );
if ( swBuff )
{
unsigned char *data;
data= (unsigned char*)mmap( NULL, swBuff->size0, PROT_READ | PROT_WRITE, MAP_SHARED, sink->soc.drmFd, swBuff->offset0 );
if ( data )
{
int row;
unsigned char *destRow= data;
unsigned char *srcYRow= frame->Y;
for( row= 0; row < frame->height; ++row )
{
memcpy( destRow, srcYRow, frame->Ystride );
destRow += swBuff->pitch0;
srcYRow += frame->Ystride;
}
munmap( data, swBuff->size0 );
}
data= (unsigned char*)mmap( NULL, swBuff->size1, PROT_READ | PROT_WRITE, MAP_SHARED, sink->soc.drmFd, swBuff->offset1 );
if ( data )
{
int row, col;
unsigned char *dest, *destRow= data;
unsigned char *srcU, *srcURow= frame->U;
unsigned char *srcV, *srcVRow= frame->V;
for( row= 0; row < frame->height; row += 2 )
{
dest= destRow;
srcU= srcURow;
srcV= srcVRow;
for( col= 0; col < frame->width; col += 2 )
{
*dest++= *srcU++;
*dest++= *srcV++;
}
destRow += swBuff->pitch1;
srcURow += frame->Ustride;
srcVRow += frame->Vstride;
}
munmap( data, swBuff->size1 );
}
if ( frame->frameNumber == 0 )
{
sink->soc.firstFrameThread= g_thread_new("westeros_first_frame", swFirstFrameThread, sink);
}
if ( needBounds(sink) && sink->vpcSurface )
{
int vx, vy, vw, vh;
sink->soc.videoX= sink->windowX;
sink->soc.videoY= sink->windowY;
sink->soc.videoWidth= sink->windowWidth;
sink->soc.videoHeight= sink->windowHeight;
sink->soc.frameWidth= frame->width;
sink->soc.frameHeight= frame->height;
wstGetVideoBounds( sink, &vx, &vy, &vw, &vh );
wstSetTextureCrop( sink, vx, vy, vw, vh );
}
if ( sink->soc.enableTextureSignal )
{
int fd0, l0, s0, fd1, l1, fd2, s1, l2, s2;
void *p0, *p1, *p2;
fd0= swBuff->fd0;
fd1= swBuff->fd1;
fd2= -1;
s0= swBuff->pitch0;
s1= swBuff->pitch1;
s2= 0;
l0= swBuff->size0;
l1= swBuff->size1;
l2= 0;
p0= 0;
p1= 0;
p2= 0;
g_signal_emit( G_OBJECT(sink),
g_signals[SIGNAL_NEWTEXTURE],
0,
sink->soc.outputFormat,
sink->soc.frameWidth,
sink->soc.frameHeight,
fd0, l0, s0, p0,
fd1, l1, s1, p1,
fd2, l2, s2, p2
);
}
else if ( sink->soc.sb )
{
bufferInfo *binfo;
binfo= (bufferInfo*)malloc( sizeof(bufferInfo) );
if ( binfo )
{
struct wl_buffer *wlbuff;
int fd0, fd1, fd2;
int stride0, stride1;
int offset1= 0;
fd0= swBuff->fd0;
fd1= swBuff->fd1;
fd2= fd0;
stride0= swBuff->pitch0;
stride1= swBuff->pitch1;
binfo->sink= sink;
binfo->buffIndex= bi;
wlbuff= wl_sb_create_planar_buffer_fd2( sink->soc.sb,
fd0,
fd1,
fd2,
swBuff->width,
swBuff->height,
WL_SB_FORMAT_NV12,
0, /* offset0 */
offset1, /* offset1 */
0, /* offset2 */
stride0, /* stride0 */
stride1, /* stride1 */
0 /* stride2 */
);
if ( wlbuff )
{
wl_buffer_add_listener( wlbuff, &wl_buffer_listener, binfo );
wl_surface_attach( sink->surface, wlbuff, sink->windowX, sink->windowY );
wl_surface_damage( sink->surface, 0, 0, sink->windowWidth, sink->windowHeight );
wl_surface_commit( sink->surface );
wl_display_flush(sink->display);
}
else
{
free( binfo );
}
}
}
}
LOCK(sink);
++sink->soc.frameOutCount;
UNLOCK(sink);
GST_LOG("swDisplay: exit");
}
#endif
static int sinkAcquireResources( GstWesterosSink *sink )
{
int result= 0;
result= sinkAcquireVideo( sink );
return result;
}
static void sinkReleaseResources( GstWesterosSink *sink )
{
sinkReleaseVideo( sink );
}
static int ioctl_wrapper( int fd, int request, void* arg )
{
const char *req= 0;
int rc;
GstDebugLevel level;
level= gst_debug_category_get_threshold( gst_westeros_sink_debug );
if ( level >= GST_LEVEL_LOG )
{
switch( request )
{
case VIDIOC_QUERYCAP: req= "VIDIOC_QUERYCAP"; break;
case VIDIOC_ENUM_FMT: req= "VIDIOC_ENUM_FMT"; break;
case VIDIOC_G_FMT: req= "VIDIOC_G_FMT"; break;
case VIDIOC_S_FMT: req= "VIDIOC_S_FMT"; break;
case VIDIOC_REQBUFS: req= "VIDIOC_REQBUFS"; break;
case VIDIOC_QUERYBUF: req= "VIDIOC_QUERYBUF"; break;
case VIDIOC_G_FBUF: req= "VIDIOC_G_FBUF"; break;
case VIDIOC_S_FBUF: req= "VIDIOC_S_FBUF"; break;
case VIDIOC_OVERLAY: req= "VIDIOC_OVERLAY"; break;
case VIDIOC_QBUF: req= "VIDIOC_QBUF"; break;
case VIDIOC_EXPBUF: req= "VIDIOC_EXPBUF"; break;
case VIDIOC_DQBUF: req= "VIDIOC_DQBUF"; break;
case VIDIOC_DQEVENT: req= "VIDIOC_DQEVENT"; break;
case VIDIOC_STREAMON: req= "VIDIOC_STREAMON"; break;
case VIDIOC_STREAMOFF: req= "VIDIOC_STREAMOFF"; break;
case VIDIOC_G_PARM: req= "VIDIOC_G_PARM"; break;
case VIDIOC_S_PARM: req= "VIDIOC_S_PARM"; break;
case VIDIOC_G_STD: req= "VIDIOC_G_STD"; break;
case VIDIOC_S_STD: req= "VIDIOC_S_STD"; break;
case VIDIOC_ENUMSTD: req= "VIDIOC_ENUMSTD"; break;
case VIDIOC_ENUMINPUT: req= "VIDIOC_ENUMINPUT"; break;
case VIDIOC_G_CTRL: req= "VIDIOC_G_CTRL"; break;
case VIDIOC_S_CTRL: req= "VIDIOC_S_CTRL"; break;
case VIDIOC_QUERYCTRL: req= "VIDIOC_QUERYCTRL"; break;
case VIDIOC_ENUM_FRAMESIZES: req= "VIDIOC_ENUM_FRAMESIZES"; break;
case VIDIOC_TRY_FMT: req= "VIDIOC_TRY_FMT"; break;
case VIDIOC_CROPCAP: req= "VIDIOC_CROPCAP"; break;
case VIDIOC_CREATE_BUFS: req= "VIDIOC_CREATE_BUFS"; break;
case VIDIOC_G_SELECTION: req= "VIDIOC_G_SELECTION"; break;
case VIDIOC_SUBSCRIBE_EVENT: req= "VIDIOC_SUBSCRIBE_EVENT"; break;
case VIDIOC_UNSUBSCRIBE_EVENT: req= "VIDIOC_UNSUBSCRIBE_EVENT"; break;
case VIDIOC_DECODER_CMD: req= "VIDIOC_DECODER_CMD"; break;
default: req= "NA"; break;
}
g_print("westerossink-ioctl: ioct( %d, %x ( %s ) )\n", fd, request, req );
if ( request == (int)VIDIOC_S_FMT )
{
struct v4l2_format *format= (struct v4l2_format*)arg;
g_print("westerossink-ioctl: : type %d\n", format->type);
if ( (format->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) ||
(format->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) )
{
g_print("westerossink-ioctl: pix_mp: pixelFormat %X w %d h %d field %d cs %d flg %x num_planes %d p0: sz %d bpl %d p1: sz %d bpl %d\n",
format->fmt.pix_mp.pixelformat,
format->fmt.pix_mp.width,
format->fmt.pix_mp.height,
format->fmt.pix_mp.field,
format->fmt.pix_mp.colorspace,
format->fmt.pix_mp.flags,
format->fmt.pix_mp.num_planes,
format->fmt.pix_mp.plane_fmt[0].sizeimage,
format->fmt.pix_mp.plane_fmt[0].bytesperline,
format->fmt.pix_mp.plane_fmt[1].sizeimage,
format->fmt.pix_mp.plane_fmt[1].bytesperline
);
}
else if ( (format->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) ||
(format->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) )
{
g_print("westerossink-ioctl: pix: pixelFormat %X w %d h %d field %d bpl %d\n",
format->fmt.pix.pixelformat,
format->fmt.pix.width,
format->fmt.pix.height,
format->fmt.pix.field,
format->fmt.pix.bytesperline
);
}
}
else if ( request == (int)VIDIOC_REQBUFS )
{
struct v4l2_requestbuffers *rb= (struct v4l2_requestbuffers*)arg;
g_print("westerossink-ioctl: count %d type %d mem %d\n", rb->count, rb->type, rb->memory);
}
else if ( request == (int)VIDIOC_QUERYBUF )
{
struct v4l2_buffer *buf= (struct v4l2_buffer*)arg;
g_print("westerossink-ioctl: index %d type %d mem %d\n", buf->index, buf->type, buf->memory);
}
else if ( request == (int)VIDIOC_S_CTRL )
{
struct v4l2_control *control= (struct v4l2_control*)arg;
g_print("westerossink-ioctl: ctrl id %d value %d\n", control->id, control->value);
}
else if ( request == (int)VIDIOC_CREATE_BUFS )
{
struct v4l2_create_buffers *cb= (struct v4l2_create_buffers*)arg;
struct v4l2_format *format= &cb->format;
g_print("westerossink-ioctl: count %d mem %d\n", cb->count, cb->memory);
g_print("westerossink-ioctl: pix_mp: pixelFormat %X w %d h %d num_planes %d p0: sz %d bpl %d p1: sz %d bpl %d\n",
format->fmt.pix_mp.pixelformat,
format->fmt.pix_mp.width,
format->fmt.pix_mp.height,
format->fmt.pix_mp.num_planes,
format->fmt.pix_mp.plane_fmt[0].sizeimage,
format->fmt.pix_mp.plane_fmt[0].bytesperline,
format->fmt.pix_mp.plane_fmt[1].sizeimage,
format->fmt.pix_mp.plane_fmt[1].bytesperline
);
}
else if ( request == (int)VIDIOC_QBUF )
{
struct v4l2_buffer *buf= (struct v4l2_buffer*)arg;
g_print("westerossink-ioctl: buff: index %d q: type %d bytesused %d flags %X field %d mem %x length %d timestamp sec %ld usec %ld\n",
buf->index, buf->type, buf->bytesused, buf->flags, buf->field, buf->memory, buf->length, buf->timestamp.tv_sec, buf->timestamp.tv_usec);
if ( buf->m.planes &&
( (buf->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) ||
(buf->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) ) )
{
if ( buf->memory == V4L2_MEMORY_DMABUF )
{
g_print("westerossink-ioctl: buff: p0 bu %d len %d fd %d doff %d p1 bu %d len %d fd %d doff %d\n",
buf->m.planes[0].bytesused, buf->m.planes[0].length, buf->m.planes[0].m.fd, buf->m.planes[0].data_offset,
buf->m.planes[1].bytesused, buf->m.planes[1].length, buf->m.planes[1].m.fd, buf->m.planes[1].data_offset );
}
else
{
g_print("westerossink-ioctl: buff: p0: bu %d len %d moff %d doff %d p1: bu %d len %d moff %d doff %d\n",
buf->m.planes[0].bytesused, buf->m.planes[0].length, buf->m.planes[0].m.mem_offset, buf->m.planes[0].data_offset,
buf->m.planes[1].bytesused, buf->m.planes[1].length, buf->m.planes[1].m.mem_offset, buf->m.planes[1].data_offset );
}
}
}
else if ( request == (int)VIDIOC_DQBUF )
{
struct v4l2_buffer *buf= (struct v4l2_buffer*)arg;
g_print("westerossink-ioctl: buff: index %d s dq: type %d bytesused %d flags %X field %d mem %x length %d timestamp sec %ld usec %ld\n",
buf->index, buf->type, buf->bytesused, buf->flags, buf->field, buf->memory, buf->length, buf->timestamp.tv_sec, buf->timestamp.tv_usec);
if ( buf->m.planes &&
( (buf->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) ||
(buf->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) ) )
{
g_print("westerossink-ioctl: buff: p0: bu %d len %d moff %d doff %d p1: bu %d len %d moff %d doff %d\n",
buf->m.planes[0].bytesused, buf->m.planes[0].length, buf->m.planes[0].m.mem_offset, buf->m.planes[0].data_offset,
buf->m.planes[1].bytesused, buf->m.planes[1].length, buf->m.planes[1].m.mem_offset, buf->m.planes[1].data_offset );
}
}
else if ( (request == (int)VIDIOC_STREAMON) || (request == (int)VIDIOC_STREAMOFF) )
{
int *type= (int*)arg;
g_print("westerossink-ioctl: : type %d\n", *type);
}
else if ( request == (int)VIDIOC_SUBSCRIBE_EVENT )
{
struct v4l2_event_subscription *evtsub= (struct v4l2_event_subscription*)arg;
g_print("westerossink-ioctl: type %d\n", evtsub->type);
}
else if ( request == (int)VIDIOC_DECODER_CMD )
{
struct v4l2_decoder_cmd *dcmd= (struct v4l2_decoder_cmd*)arg;
g_print("westerossink-ioctl: cmd %d\n", dcmd->cmd);
}
}
rc= ioctl( fd, request, arg );
if ( level >= GST_LEVEL_LOG )
{
if ( rc < 0 )
{
g_print("westerossink-ioctl: ioct( %d, %x ) rc %d errno %d\n", fd, request, rc, errno );
}
else
{
g_print("westerossink-ioctl: ioct( %d, %x ) rc %d\n", fd, request, rc );
if ( (request == (int)VIDIOC_G_FMT) || (request == (int)VIDIOC_S_FMT) )
{
struct v4l2_format *format= (struct v4l2_format*)arg;
if ( (format->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) ||
(format->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) )
{
g_print("westerossink-ioctl: pix_mp: pixelFormat %X w %d h %d field %d cs %d flg %x num_planes %d p0: sz %d bpl %d p1: sz %d bpl %d\n",
format->fmt.pix_mp.pixelformat,
format->fmt.pix_mp.width,
format->fmt.pix_mp.height,
format->fmt.pix_mp.field,
format->fmt.pix_mp.colorspace,
format->fmt.pix_mp.flags,
format->fmt.pix_mp.num_planes,
format->fmt.pix_mp.plane_fmt[0].sizeimage,
format->fmt.pix_mp.plane_fmt[0].bytesperline,
format->fmt.pix_mp.plane_fmt[1].sizeimage,
format->fmt.pix_mp.plane_fmt[1].bytesperline
);
}
else if ( (format->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) ||
(format->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) )
{
g_print("westerossink-ioctl: pix: pixelFormat %X w %d h %d field %d bpl %d\n",
format->fmt.pix.pixelformat,
format->fmt.pix.width,
format->fmt.pix.height,
format->fmt.pix.field,
format->fmt.pix.bytesperline
);
}
}
else if ( request == (int)VIDIOC_REQBUFS )
{
struct v4l2_requestbuffers *rb= (struct v4l2_requestbuffers*)arg;
g_print("westerossink-ioctl: count %d type %d mem %d\n", rb->count, rb->type, rb->memory);
}
else if ( request == (int)VIDIOC_CREATE_BUFS )
{
struct v4l2_create_buffers *cb= (struct v4l2_create_buffers*)arg;
g_print("westerossink-ioctl: index %d count %d mem %d\n", cb->index, cb->count, cb->memory);
}
else if ( request == (int)VIDIOC_QUERYBUF )
{
struct v4l2_buffer *buf= (struct v4l2_buffer*)arg;
g_print("westerossink-ioctl: index %d type %d flags %X mem %d\n", buf->index, buf->type, buf->flags, buf->memory);
}
else if ( request == (int)VIDIOC_G_CTRL )
{
struct v4l2_control *ctrl= (struct v4l2_control*)arg;
g_print("westerossink-ioctl: id %d value %d\n", ctrl->id, ctrl->value);
}
else if ( request == (int)VIDIOC_DQBUF )
{
struct v4l2_buffer *buf= (struct v4l2_buffer*)arg;
g_print("westerossink-ioctl: buff: index %d f dq: type %d bytesused %d flags %X field %d mem %x length %d seq %d timestamp sec %ld usec %ld\n",
buf->index, buf->type, buf->bytesused, buf->flags, buf->field, buf->memory, buf->length, buf->sequence, buf->timestamp.tv_sec, buf->timestamp.tv_usec);
if ( buf->m.planes &&
( (buf->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) ||
(buf->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) ) )
{
if ( buf->memory == V4L2_MEMORY_MMAP )
{
g_print("westerossink-ioctl: buff: p0: bu %d len %d moff %d doff %d p1: bu %d len %d moff %d doff %d\n",
buf->m.planes[0].bytesused, buf->m.planes[0].length, buf->m.planes[0].m.mem_offset, buf->m.planes[0].data_offset,
buf->m.planes[1].bytesused, buf->m.planes[1].length, buf->m.planes[1].m.mem_offset, buf->m.planes[1].data_offset );
}
else if ( buf->memory == V4L2_MEMORY_DMABUF )
{
g_print("westerossink-ioctl: buff: p0: bu %d len %d fd %d doff %d p1: bu %d len %d fd %d doff %d\n",
buf->m.planes[0].bytesused, buf->m.planes[0].length, buf->m.planes[0].m.fd, buf->m.planes[0].data_offset,
buf->m.planes[1].bytesused, buf->m.planes[1].length, buf->m.planes[1].m.fd, buf->m.planes[1].data_offset );
}
}
}
else if ( request == (int)VIDIOC_ENUM_FRAMESIZES )
{
struct v4l2_frmsizeenum *frmsz= (struct v4l2_frmsizeenum*)arg;
g_print("westerossink-ioctl: fmt %x idx %d type %d\n", frmsz->pixel_format, frmsz->index, frmsz->type);
if ( frmsz->type == V4L2_FRMSIZE_TYPE_DISCRETE )
{
g_print("westerossink-ioctl: discrete %dx%d\n", frmsz->discrete.width, frmsz->discrete.height);
}
else if ( frmsz->type == V4L2_FRMSIZE_TYPE_STEPWISE )
{
g_print("westerossink-ioctl: stepwise minw %d maxw %d stepw %d minh %d maxh %d steph %d\n",
frmsz->stepwise.min_width, frmsz->stepwise.max_width, frmsz->stepwise.step_width,
frmsz->stepwise.min_height, frmsz->stepwise.max_height, frmsz->stepwise.step_height );
}
else
{
g_print("westerossink-ioctl: continuous\n");
}
}
else if ( request == (int)VIDIOC_DQEVENT )
{
struct v4l2_event *event= (struct v4l2_event*)arg;
g_print("westerossink-ioctl: event: type %d pending %d\n", event->type, event->pending);
if ( event->type == V4L2_EVENT_SOURCE_CHANGE )
{
g_print("westerossink-ioctl: changes %X\n", event->u.src_change.changes );
}
}
}
}
return rc;
}
| 32.770608 | 191 | 0.540427 | [
"geometry",
"render",
"object"
] |
6cbecce53c8830a564bb4636063a21b281d12b6e | 3,038 | h | C | ZMClass/mp_framework/mpsdk_remotemanagement.framework/Headers/CmsDNotification.h | zziazm/ZMClass | 096bf05660ea937a4c5f321313f495c882fc4afb | [
"MIT"
] | null | null | null | ZMClass/mp_framework/mpsdk_remotemanagement.framework/Headers/CmsDNotification.h | zziazm/ZMClass | 096bf05660ea937a4c5f321313f495c882fc4afb | [
"MIT"
] | null | null | null | ZMClass/mp_framework/mpsdk_remotemanagement.framework/Headers/CmsDNotification.h | zziazm/ZMClass | 096bf05660ea937a4c5f321313f495c882fc4afb | [
"MIT"
] | null | null | null | /**
* Copyright (c) 2018, MasterCard International Incorporated and/or its
* affiliates. All rights reserved.
*
* The contents of this file may only be used subject to the MasterCard
* Mobile Payment SDK for MCBP and/or MasterCard Mobile MPP UI SDK
* Materials License.
*
* Please refer to the file LICENSE.TXT for full details.
*
* TO THE EXTENT PERMITTED BY LAW, THE SOFTWARE IS PROVIDED "AS IS", WITHOUT
* WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NON INFRINGEMENT. TO THE EXTENT PERMITTED BY LAW, IN NO EVENT SHALL
* MASTERCARD OR ITS AFFILIATES 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.
**/
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from CmsDNotification.djinni
#import <Foundation/Foundation.h>
@class CmsDNotification;
@class CmsDNotification;
/**
* Auto-generated Djinni interface for ::mpsdk::remotemanagement::json::encrypted::CmsDNotification_t
*
* Represents the remote notification message from CMS-D.
*
*/
@interface CmsDNotification : NSObject
- (id _Nonnull)init;
/**
*
* @returns String-The host that the Mobile Payment App should route requests to. This allows
* Cms-D to
* control requests related to a specific conversation to the desired location.
*
*/
- (NSString* _Nonnull)getResponseHost;
/**
*
* @param responseHost The host that the Mobile Payment App should route requests to. This
* allows Cms-D to control requests related to a specific conversation to
* the desired location.
*
*/
- (void)setResponseHost:(NSString* _Nonnull)responseHost;
/**
*
* @returns String-Identifies the Mobile Keys used for this remote management session
*
*/
- (NSString* _Nonnull)getMobileKeysetId;
/**
*
* @param mobileKeysetId String-Identifies the Mobile Keys used for this remote management
* session
*
*/
- (void)setMobileKeysetId:(NSString* _Nonnull)mobileKeysetId;
/**
*
* Returns equivalent CmsDNotification_t
* object from given json string.
* @param data Json string.
* @returns CmsDNotification_t object.
*
*/
+ (CmsDNotification* _Nonnull)valueOf:(NSString* _Nonnull)data;
/**
*
* Returns json string.
* @returns Json string.
*
*/
- (NSString* _Nonnull)toJsonString;
/**
*
* @returns String-the protected RemoteManagementSessionData object.
* The plaintext data is prepended with a random 16-byte value before it is protected by the
* Mobile Transport Key using CBC mode padded with '80' followed by '00' utils until the end
* of the block. The MAC is then computed over the output, which is appended to the end
*
*/
- (NSString* _Nonnull)getEncryptedData;
/**
*
* @param encryptedData as String
*
*/
- (void)setEncryptedData:(NSString* _Nonnull)encryptedData;
- (NSString* _Nonnull)toString;
@end
| 27.618182 | 101 | 0.733048 | [
"object"
] |
8c13a689b7bc6e94c243116530e058cd09be90e6 | 8,824 | c | C | gpvdm_core/liblight/light_dump_verbose_1d.c | roderickmackenzie/gpvdm | 914fd2ee93e7202339853acaec1d61d59b789987 | [
"BSD-3-Clause"
] | 12 | 2016-09-13T08:58:13.000Z | 2022-01-17T07:04:52.000Z | gpvdm_core/liblight/light_dump_verbose_1d.c | roderickmackenzie/gpvdm | 914fd2ee93e7202339853acaec1d61d59b789987 | [
"BSD-3-Clause"
] | 3 | 2017-11-11T12:33:02.000Z | 2019-03-08T00:48:08.000Z | gpvdm_core/liblight/light_dump_verbose_1d.c | roderickmackenzie/gpvdm | 914fd2ee93e7202339853acaec1d61d59b789987 | [
"BSD-3-Clause"
] | 6 | 2019-01-03T06:17:12.000Z | 2022-01-01T15:59:00.000Z | //
// General-purpose Photovoltaic Device Model gpvdm.com - a drift diffusion
// base/Shockley-Read-Hall model for 1st, 2nd and 3rd generation solarcells.
// The model can simulate OLEDs, Perovskite cells, and OFETs.
//
// Copyright 2008-2022 Roderick C. I. MacKenzie https://www.gpvdm.com
// r.c.i.mackenzie at googlemail.com
//
// 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.
//
/** @file ligh_dump_verbose_1d.c
@brief Dumps 1D optical fields from light model.
*/
#include <string.h>
#include <sys/stat.h>
#include "util.h"
#include "gpvdm_const.h"
#include "dump_ctrl.h"
#include "light.h"
#include "dat_file.h"
#include <cal_path.h>
#include <lang.h>
void light_dump_verbose_1d(struct simulation *sim,struct light *li, int l,char *ext)
{
return;
char line[1024];
char temp[1024];
char name_photons[200];
char name_light_1d_Ep[200];
char name_light_1d_En[200];
char name_pointing[200];
char name_E_tot[200];
char name_r[200];
char name_t[200];
char name[200];
int x=0;
int z=0;
int y=0;
struct epitaxy *epi=li->epi;
long double device_start=epi->device_start;
//int max=0;
struct dat_file data_photons;
struct dat_file data_light_1d_Ep;
struct dat_file data_light_1d_En;
//struct dat_file data_pointing;
//struct dat_file data_E_tot;
struct dat_file data_r;
struct dat_file data_t;
struct dat_file buf;
struct dim_light *dim=&li->dim;
buffer_init(&data_light_1d_Ep);
buffer_init(&data_light_1d_En);
//buffer_init(&data_pointing);
//buffer_init(&data_E_tot);
buffer_init(&buf);
buffer_init(&data_r);
buffer_init(&data_t);
buffer_init(&data_photons);
buffer_malloc(&data_photons);
buffer_malloc(&data_light_1d_Ep);
buffer_malloc(&data_light_1d_En);
//buffer_malloc(&data_pointing);
//buffer_malloc(&data_E_tot);
buffer_malloc(&data_r);
buffer_malloc(&data_t);
sprintf(name_photons,"light_1d_%.0Lf_photons%s.dat",dim->l[l]*1e9,ext);
sprintf(name_light_1d_Ep,"light_1d_%.0Lf_Ep%s.dat",dim->l[l]*1e9,ext);
sprintf(name_light_1d_En,"light_1d_%.0Lf_En%s.dat",dim->l[l]*1e9,ext);
sprintf(name_pointing,"light_1d_%.0Lf_pointing%s.dat",dim->l[l]*1e9,ext);
sprintf(name_E_tot,"light_1d_%.0Lf_E_tot%s.dat",dim->l[l]*1e9,ext);
sprintf(name_r,"light_1d_%.0Lf_r%s.dat",dim->l[l]*1e9,ext);
sprintf(name_t,"light_1d_%.0Lf_t%s.dat",dim->l[l]*1e9,ext);
//
for (y=0;y<dim->ylen;y++)
{
sprintf(line,"%Le %e\n",dim->y[y]-device_start,li->photons[z][x][y][l]);
buffer_add_string(&data_photons,line);
sprintf(line,"%Le %e %e %e\n",dim->y[y]-device_start,pow(pow(li->Ep[z][x][y][l],2.0)+pow(li->Epz[z][x][y][l],2.0),0.5),li->Ep[z][x][y][l],li->Epz[z][x][y][l]);
buffer_add_string(&data_light_1d_Ep,line);
sprintf(line,"%Le %e %e %e\n",dim->y[y]-device_start,pow(pow(li->En[z][x][y][l],2.0)+pow(li->Enz[z][x][y][l],2.0),0.5),li->En[z][x][y][l],li->Enz[z][x][y][l]);
buffer_add_string(&data_light_1d_En,line);
//sprintf(line,"%Le %e\n",dim->y[y]-device_start,li->pointing_vector[z][x][y][l]);
//buffer_add_string(&data_pointing,line);
//sprintf(line,"%Le %e %e\n",dim->y[y]-device_start,li->E_tot_r[z][x][y][l],li->E_tot_i[z][x][y][l]);
//buffer_add_string(&data_E_tot,line);
sprintf(line,"%Le %Le %Le %Le\n",dim->y[y]-device_start,gcabs(li->r[z][x][y][l]),gcreal(li->r[z][x][y][l]),gcimag(li->r[z][x][y][l]));
buffer_add_string(&data_r,line);
sprintf(line,"%Le %Le %Le %Le\n",dim->y[y]-device_start,gcabs(li->t[z][x][y][l]),gcreal(li->t[z][x][y][l]),gcimag(li->t[z][x][y][l]));
buffer_add_string(&data_t,line);
}
buffer_dump_path(sim,li->dump_dir,name_photons,&data_photons);
buffer_dump_path(sim,li->dump_dir,name_light_1d_Ep,&data_light_1d_Ep);
buffer_dump_path(sim,li->dump_dir,name_light_1d_En,&data_light_1d_En);
//buffer_dump_path(sim,li->dump_dir,name_pointing,&data_pointing);
//buffer_dump_path(sim,li->dump_dir,name_E_tot,&data_E_tot);
buffer_dump_path(sim,li->dump_dir,name_r,&data_r);
buffer_dump_path(sim,li->dump_dir,name_t,&data_t);
buffer_free(&data_photons);
buffer_free(&data_light_1d_Ep);
buffer_free(&data_light_1d_En);
//buffer_free(&data_pointing);
//buffer_free(&data_E_tot);
buffer_free(&data_r);
buffer_free(&data_t);
buffer_malloc(&buf);
dim_light_info_to_buf(&buf,dim);
strcpy(buf.title,"Real refractive index (n) vs position");
strcpy(buf.type,"xy");
strcpy(buf.data_label,_("Real refractive index"));
strcpy(buf.data_units,"au");
buf.x=1;
buf.y=dim->ylen;
buf.z=1;
buffer_add_info(sim,&buf);
sprintf(temp,"#data\n");
buffer_add_string(&buf,temp);
for (y=0;y<dim->ylen;y++)
{
sprintf(line,"%Le %e\n",dim->y[y],li->n[0][0][y][l]);
buffer_add_string(&buf,line);
}
sprintf(temp,"#end\n");
buffer_add_string(&buf,temp);
sprintf(name,"light_1d_%.0Lf_n%s.dat",dim->l[l]*1e9,ext);
buffer_dump_path(sim,li->dump_dir,name,&buf);
buffer_free(&buf);
buffer_malloc(&buf);
dim_light_info_to_buf(&buf,dim);
strcpy(buf.title,"Absorption vs position");
strcpy(buf.type,"xy");
strcpy(buf.data_label,_("Absorption"));
strcpy(buf.data_units,"m^{-1}");
buf.x=1;
buf.y=dim->ylen;
buf.z=1;
buffer_add_info(sim,&buf);
sprintf(temp,"#data\n");
buffer_add_string(&buf,temp);
for (y=0;y<dim->ylen;y++)
{
sprintf(line,"%Le %e\n",dim->y[y],li->alpha[0][0][y][l]);
buffer_add_string(&buf,line);
}
sprintf(temp,"#end\n");
buffer_add_string(&buf,temp);
sprintf(name,"light_1d_%.0Lf_alpha%s.dat",dim->l[l]*1e9,ext);
buffer_dump_path(sim,li->dump_dir,name,&buf);
buffer_free(&buf);
buffer_malloc(&buf);
buf.y_mul=1.0;
buf.x_mul=1e9;
strcpy(buf.title,"|Electric field| vs position");
strcpy(buf.type,"xy");
strcpy(buf.x_label,_("Position"));
strcpy(buf.data_label,_("|Electric field|"));
strcpy(buf.x_units,"nm");
strcpy(buf.data_units,"V/m");
buf.logscale_x=0;
buf.logscale_y=0;
buf.x=1;
buf.y=dim->ylen;
buf.z=1;
buffer_add_info(sim,&buf);
sprintf(temp,"#data\n");
buffer_add_string(&buf,temp);
for (y=0;y<dim->ylen;y++)
{
sprintf(line,"%Le %Le\n",dim->y[y]-device_start,gpow(gpow(li->Ep[z][x][y][l]+li->En[z][x][y][l],2.0)+gpow(li->Enz[z][x][y][l]+li->Epz[z][x][y][l],2.0),0.5));
buffer_add_string(&buf,line);
}
sprintf(temp,"#end\n");
buffer_add_string(&buf,temp);
sprintf(temp,"light_1d_%.0Lf_E%s.dat",dim->l[l]*1e9,ext);
buffer_dump_path(sim,li->dump_dir,temp,&buf);
buffer_free(&buf);
buffer_malloc(&buf);
buf.y_mul=1.0;
buf.x_mul=1e9;
strcpy(buf.title,"Transmittance vs position");
strcpy(buf.type,"xy");
strcpy(buf.x_label,_("Position"));
strcpy(buf.data_label,_("Transmittance"));
strcpy(buf.x_units,"nm");
strcpy(buf.data_units,"au");
buf.logscale_x=0;
buf.logscale_y=0;
buf.x=1;
buf.y=dim->ylen;
buf.z=1;
buffer_add_info(sim,&buf);
sprintf(temp,"#data\n");
buffer_add_string(&buf,temp);
for (y=0;y<dim->ylen;y++)
{
sprintf(line,"%Le %Le\n",dim->y[y]-device_start,gcabs(li->t[z][x][y][l]));
buffer_add_string(&buf,line);
}
sprintf(temp,"#end\n");
buffer_add_string(&buf,temp);
sprintf(temp,"light_1d_%.0Lf_t%s.dat",dim->l[l]*1e9,ext);
buffer_dump_path(sim,li->dump_dir,temp,&buf);
buffer_free(&buf);
buffer_malloc(&buf);
buf.y_mul=1.0;
buf.x_mul=1e9;
strcpy(buf.title,"Reflectance vs position");
strcpy(buf.type,"xy");
strcpy(buf.x_label,_("Position"));
strcpy(buf.data_label,_("Reflectance"));
strcpy(buf.x_units,"nm");
strcpy(buf.data_units,"au");
buf.logscale_x=0;
buf.logscale_y=0;
buf.x=1;
buf.y=dim->ylen;
buf.z=1;
buffer_add_info(sim,&buf);
sprintf(temp,"#data\n");
buffer_add_string(&buf,temp);
for (y=0;y<dim->ylen;y++)
{
sprintf(line,"%Le %Le\n",dim->y[y]-device_start,gcabs(li->r[z][x][y][l]));
buffer_add_string(&buf,line);
}
sprintf(temp,"#end\n");
buffer_add_string(&buf,temp);
sprintf(temp,"light_1d_%.0Lf_r%s.dat",dim->l[l]*1e9,ext);
buffer_dump_path(sim,li->dump_dir,temp,&buf);
buffer_free(&buf);
}
| 28.37299 | 161 | 0.69685 | [
"model"
] |
8c13e38d190ca21eff2fd103d15c1d27d4edad6e | 4,821 | h | C | geometrytools.h | ASentientTomato/NEA_Engine | 75a96cbfdad3a650f5d706a63a830b3e22707134 | [
"MIT",
"Unlicense"
] | null | null | null | geometrytools.h | ASentientTomato/NEA_Engine | 75a96cbfdad3a650f5d706a63a830b3e22707134 | [
"MIT",
"Unlicense"
] | null | null | null | geometrytools.h | ASentientTomato/NEA_Engine | 75a96cbfdad3a650f5d706a63a830b3e22707134 | [
"MIT",
"Unlicense"
] | null | null | null | #pragma once
#include "shapes.h"
#include <iostream>
#include <array>
namespace geo {
//--------------------------------------------VECTOR MATHS--------------------------------------------
//calculates the dot product of two vectors.
inline double dot(vec a, vec b);
//calculates the magnitude of a vector.
inline double magnitude(vec A);
//prints a vector (for testing).
void printVec(vec A);
//rotates a vector by t radians.
vec rotate(vec v, float t);
//--------------------------------------------MATRIX MATHS--------------------------------------------
//prints a matrix (for testing).
void printMatrix(std::array<double, 3> M);
//calculates the determinant of a 2x2 matrix.
double det2x2(std::array <double, 4> M);
//calculates the determinant of a 3x3 matrix.
double det3x3(std::array <double, 9> M);
//finds the matrix of cofactors for a 3x3 matrix.
std::array<double, 9> cofactorsPlus(std::array<double, 9> M);
//inverts a 3x3 matrix.
std::array < double, 9 > invert3x3(std::array<double, 9> M);
//multiplies a 3x3 matrix by a 3x1 matrix (or 3x1 vector).
std::array <double, 3> multiply3x3X3x1(std::array<double, 9> A, std::array<double, 3> B);
template <class T> class Matrix3D {
// {0,1,2}
// {3,4,5}
// {6,7,8}
//TODO: this can be made more efficient since we don't actually need the bottom row.
public:
std::array<std::array<T, 3>, 3> fields;
Matrix3D() {};
Matrix3D(T floats[9]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
fields[i][j] = floats[i * 3 + j];
}
}
}
Matrix3D(std::array<std::array<T, 3>, 3> floats) {
this->fields = floats;
}
Matrix3D operator*(Matrix3D mat) {
std::array<std::array<T, 3>, 3> result = { {0} };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
result[i][j] += this->fields[i][k] * mat.fields[k][j];
}
}
}
result[2][2] = 1;
return Matrix3D(result);
}
void operator *= (Matrix3D mat) {
this->fields = (this->operator*(mat)).fields;
}
void print() {
for (std::array<float, 3> i : this->fields) {
for (int j = 0; j < 3; j++) {
std::cout << i[j] << " ";
}
std::cout << std::endl;
}
}
float& operator[] (int position) {
return this->fields[position];
}
//ignoring bottom row...
geo::vec operator*(geo::vec vector) {
geo::vec vecc;
vecc.x = (this->fields[0][0] * vector.x + this->fields[0][1] * vector.y + this->fields[0][2]);
vecc.y = (this->fields[1][0] * vector.x + this->fields[1][1] * vector.y + this->fields[1][2]);
return vecc;
}
};
//------------------------------------------UTILITY FUNCTIONS------------------------------------------
//Calculates the v-value of a point Q over a line AB.
double getV(vec A, vec B, vec Q);
//Calculates the closest point on a line AB to a point Q.
vec closestPoint(vec A, vec B, vec Q);
//Returns the point in A which has the greatest dot product with d.
int support(const convex& A, const vec& d);
//Returns the difference between support(A,d) and support(b,-d).
vec minkowskiDifference(const convex& A, const convex& B, const vec d);
//returns True if V contains an instance of v.
bool contains(std::vector<vec>& V, vec v);
//Runs EPA, returning the collision normal for two shapes that are colliding.
vec epa(const convex& A, const convex& B, simplexVec S);
/* Calculates which vertex is most perpendicular to penetrationNormal:
A[v+1]-A[v] or A[v]-A[v-1]. Considers circular nature of shapes. */
int mostPerpendicular(const convex& A, const int v, const vec penetrationNormal);
//Returns true if Q is on the left of the line AB.
bool onLeftOfLine(const vec A, const vec B, const vec Q, bool clockwise);
/* Gets the indices of the next and previous points to a in a shape of size "size".
Considers the cyclical nature of shapes - the two ends of the shape are connected. */
vec getNextAndPrevious(int a, int size);
/* returns true if p is inside the convex shape A. "startpoint1" and "startpoint2"
represent the indices of a likely separating axis, allowing the function to return
early. They can, however, be set arbitrarily. */
bool isPointInside(vec p, const convex* A, int startpoint1 = 0, int startpoint2 = 1);
/* rearranges two vertices (which it takes by reference), a and b, in a shape of size
"size" so that the index of b is greater than the index of a. Considers the fact
that shapes are cyclical. */
void putInOrder(int& a, int& b, int size);
/* returns a manifold containing information about the collision between A and B.
When impulses are calculated, remember that the collision normal points from A to B! */
vec getCollisionData(const convex& A, const convex& B, collision& man, line& incline, line& refline);
} | 31.717105 | 104 | 0.617507 | [
"shape",
"vector"
] |
8c1c9531140a8e2e8af39fbb48f7b36e20d06c40 | 1,650 | h | C | dcdn/include/alibabacloud/dcdn/model/DescribeDcdnWafDomainResult.h | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | dcdn/include/alibabacloud/dcdn/model/DescribeDcdnWafDomainResult.h | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | dcdn/include/alibabacloud/dcdn/model/DescribeDcdnWafDomainResult.h | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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.
*/
#ifndef ALIBABACLOUD_DCDN_MODEL_DESCRIBEDCDNWAFDOMAINRESULT_H_
#define ALIBABACLOUD_DCDN_MODEL_DESCRIBEDCDNWAFDOMAINRESULT_H_
#include <string>
#include <vector>
#include <utility>
#include <alibabacloud/core/ServiceResult.h>
#include <alibabacloud/dcdn/DcdnExport.h>
namespace AlibabaCloud
{
namespace Dcdn
{
namespace Model
{
class ALIBABACLOUD_DCDN_EXPORT DescribeDcdnWafDomainResult : public ServiceResult
{
public:
struct OutPutDomain
{
int status;
int aclStatus;
int ccStatus;
std::string domain;
int wafStatus;
};
DescribeDcdnWafDomainResult();
explicit DescribeDcdnWafDomainResult(const std::string &payload);
~DescribeDcdnWafDomainResult();
int getTotalCount()const;
std::vector<OutPutDomain> getOutPutDomains()const;
protected:
void parse(const std::string &payload);
private:
int totalCount_;
std::vector<OutPutDomain> outPutDomains_;
};
}
}
}
#endif // !ALIBABACLOUD_DCDN_MODEL_DESCRIBEDCDNWAFDOMAINRESULT_H_ | 27.04918 | 84 | 0.74303 | [
"vector",
"model"
] |
8c1de29475a8d9dc4088294b7572443e5d85fe16 | 7,274 | h | C | deps/include/CEGUI/RenderedStringWordWrapper.h | mirzazulfan/Xenro-Engine | 0e9383b113ec09a24daf5e92f9a5b84febaffb1b | [
"MIT"
] | 13 | 2019-02-21T09:05:11.000Z | 2021-12-03T09:11:00.000Z | deps/include/CEGUI/RenderedStringWordWrapper.h | mirzazulfan/Xenro-Engine | 0e9383b113ec09a24daf5e92f9a5b84febaffb1b | [
"MIT"
] | 18 | 2018-02-28T21:34:30.000Z | 2018-12-01T19:07:43.000Z | deps/include/CEGUI/RenderedStringWordWrapper.h | mirzazulfan/Xenro-Engine | 0e9383b113ec09a24daf5e92f9a5b84febaffb1b | [
"MIT"
] | 15 | 2015-02-23T16:35:28.000Z | 2022-03-25T13:40:33.000Z | /***********************************************************************
created: 25/05/2009
author: Paul Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
*
* 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 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.
***************************************************************************/
#ifndef _CEGUIRenderedStringWordWrapper_h_
#define _CEGUIRenderedStringWordWrapper_h_
#include "CEGUI/FormattedRenderedString.h"
#include "CEGUI/JustifiedRenderedString.h"
#include "CEGUI/Vector.h"
#include <vector>
// Start of CEGUI namespace section
namespace CEGUI
{
/*!
\brief
Class that handles wrapping of a rendered string into sub-strings. Each
sub-string is rendered using the FormattedRenderedString based class 'T'.
*/
template <typename T>
class RenderedStringWordWrapper : public FormattedRenderedString
{
public:
//! Constructor.
RenderedStringWordWrapper(const RenderedString& string);
//! Destructor.
~RenderedStringWordWrapper();
// implementation of base interface
void format(const Window* ref_wnd, const Sizef& area_size);
void draw(const Window* ref_wnd, GeometryBuffer& buffer,
const Vector2f& position, const ColourRect* mod_colours,
const Rectf* clip_rect) const;
size_t getFormattedLineCount() const;
float getHorizontalExtent(const Window* ref_wnd) const;
float getVerticalExtent(const Window* ref_wnd) const;
protected:
//! Delete the current formatters and associated RenderedStrings
void deleteFormatters();
//! type of collection used to track the formatted lines.
typedef std::vector<FormattedRenderedString*
CEGUI_VECTOR_ALLOC(FormattedRenderedString*)> LineList;
//! collection of lines.
LineList d_lines;
};
//! specialised version of format used with Justified text
template <> CEGUIEXPORT
void RenderedStringWordWrapper<JustifiedRenderedString>::format(const Window* ref_wnd,
const Sizef& area_size);
//----------------------------------------------------------------------------//
template <typename T>
RenderedStringWordWrapper<T>::RenderedStringWordWrapper(
const RenderedString& string) :
FormattedRenderedString(string)
{
}
//----------------------------------------------------------------------------//
template <typename T>
RenderedStringWordWrapper<T>::~RenderedStringWordWrapper()
{
deleteFormatters();
}
//----------------------------------------------------------------------------//
template <typename T>
void RenderedStringWordWrapper<T>::format(const Window* ref_wnd,
const Sizef& area_size)
{
deleteFormatters();
RenderedString rstring, lstring;
rstring = *d_renderedString;
float rs_width;
T* frs;
for (size_t line = 0; line < rstring.getLineCount(); ++line)
{
while ((rs_width = rstring.getPixelSize(ref_wnd, line).d_width) > 0)
{
// skip line if no wrapping occurs
if (rs_width <= area_size.d_width)
break;
// split rstring at width into lstring and remaining rstring
rstring.split(ref_wnd, line, area_size.d_width, lstring);
frs = CEGUI_NEW_AO T(*new RenderedString(lstring));
frs->format(ref_wnd, area_size);
d_lines.push_back(frs);
line = 0;
}
}
// last line.
frs = CEGUI_NEW_AO T(*new RenderedString(rstring));
frs->format(ref_wnd, area_size);
d_lines.push_back(frs);
}
//----------------------------------------------------------------------------//
template <typename T>
void RenderedStringWordWrapper<T>::draw(const Window* ref_wnd,
GeometryBuffer& buffer,
const Vector2f& position,
const ColourRect* mod_colours,
const Rectf* clip_rect) const
{
Vector2f line_pos(position);
typename LineList::const_iterator i = d_lines.begin();
for (; i != d_lines.end(); ++i)
{
(*i)->draw(ref_wnd, buffer, line_pos, mod_colours, clip_rect);
line_pos.d_y += (*i)->getVerticalExtent(ref_wnd);
}
}
//----------------------------------------------------------------------------//
template <typename T>
size_t RenderedStringWordWrapper<T>::getFormattedLineCount() const
{
return d_lines.size();
}
//----------------------------------------------------------------------------//
template <typename T>
float RenderedStringWordWrapper<T>::getHorizontalExtent(const Window* ref_wnd) const
{
// TODO: Cache at format time.
float w = 0;
typename LineList::const_iterator i = d_lines.begin();
for (; i != d_lines.end(); ++i)
{
const float cur_width = (*i)->getHorizontalExtent(ref_wnd);
if (cur_width > w)
w = cur_width;
}
return w;
}
//----------------------------------------------------------------------------//
template <typename T>
float RenderedStringWordWrapper<T>::getVerticalExtent(const Window* ref_wnd) const
{
// TODO: Cache at format time.
float h = 0;
typename LineList::const_iterator i = d_lines.begin();
for (; i != d_lines.end(); ++i)
h += (*i)->getVerticalExtent(ref_wnd);
return h;
}
//----------------------------------------------------------------------------//
template <typename T>
void RenderedStringWordWrapper<T>::deleteFormatters()
{
for (size_t i = 0; i < d_lines.size(); ++i)
{
// get the rendered string back from rthe formatter
const RenderedString* rs = &d_lines[i]->getRenderedString();
// delete the formatter
CEGUI_DELETE_AO d_lines[i];
// delete the rendered string.
CEGUI_DELETE_AO rs;
}
d_lines.clear();
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
#endif // end of guard _CEGUIRenderedStringWordWrapper_h_
| 35.482927 | 88 | 0.572725 | [
"vector"
] |
8c1e9657b8d27a83604092a8b379324ad87bf1aa | 397 | c | C | zsh-3.0.8.1/Src/Win32/zz_ntb2.c | oldfaber/wzsh | ca391603df474797851b58fc2b6618676e8d75cb | [
"BSD-3-Clause"
] | 13 | 2015-01-18T04:54:10.000Z | 2021-12-11T14:23:28.000Z | zsh-3.0.8.1/Src/Win32/zz_ntb2.c | oldfaber/wzsh | ca391603df474797851b58fc2b6618676e8d75cb | [
"BSD-3-Clause"
] | 2 | 2015-03-26T09:49:17.000Z | 2015-11-01T20:57:09.000Z | zsh-3.0.8.1/Src/Win32/zz_ntb2.c | oldfaber/wzsh | ca391603df474797851b58fc2b6618676e8d75cb | [
"BSD-3-Clause"
] | 3 | 2020-04-25T13:49:05.000Z | 2022-01-01T20:37:26.000Z | /*
* No copyright. This trivial file is offered as-is, without any warranty.
*/
/*
* NOTE
* This file must be the _LAST_ object file linked in the application.
* The name starting with zz_ helps when is no other way to specify a
* link order
*/
/* marks end of memory to be copied to child */
unsigned long bookcommon2;
unsigned long bookbss2=0;
unsigned long bookdata2=1L;
| 24.8125 | 75 | 0.700252 | [
"object"
] |
8c2cdb7f273ad10b84b6b688bce3995a5939f45c | 1,371 | h | C | 13_OCR/header/controlador.h | eduherminio/Academic_ArtificialIntelligence | f0ec4d35cef64a1bf6841ea7ecf1d33017b3745f | [
"MIT"
] | 3 | 2017-05-16T22:25:16.000Z | 2019-05-07T16:12:21.000Z | 13_OCR/header/controlador.h | eduherminio/Academic_ArtificialIntelligence | f0ec4d35cef64a1bf6841ea7ecf1d33017b3745f | [
"MIT"
] | null | null | null | 13_OCR/header/controlador.h | eduherminio/Academic_ArtificialIntelligence | f0ec4d35cef64a1bf6841ea7ecf1d33017b3745f | [
"MIT"
] | null | null | null | #ifndef CONTROLADOR_H_INCLUDED
#define CONTROLADOR_H_INCLUDED
#include "../header/vista.h" // Nuestra clase vista
#include "../header/knn.h"
#include "../header/mnist.h"
#include "../header/sf_extension.h"
#include "../MNIST/include/MNIST/mnist_reader.h"
#include "../MNIST/include/MNIST/mnist_utils.h"
#include <thread>
#include <chrono>
#include <atomic>
#include <mutex>
#include <condition_variable>
#include <queue>
namespace parche
{
template < typename T > std::string to_string(const T& n)
{
std::ostringstream stm;
stm << n;
return stm.str();
}
}
namespace controlador
{
class Controlador
{
public:
Controlador(Vista &vista, Knn<std::vector<uint8_t>, uint8_t> &knn, Mnist &mnist) :vista(vista), knn(knn), mnist(mnist)
{
registra_observadores();
}
void ejecutar();
private:
Vista &vista;
Knn<std::vector<uint8_t>, uint8_t> &knn;
Mnist &mnist;
std::thread hilo_vista;
std::thread hilo_modelo;
std::atomic<bool> inicio_vista;
std::atomic<bool> fin_vista;
std::atomic<bool> inicio_algoritmo;
std::atomic<bool> fin_algoritmo;
std::mutex barrera_knn;
std::condition_variable c_v_barrera_knn;
void registra_observadores();
bool carga_imagenes_mnist();
void inicia_programa();
void finaliza_programa();
void ejecuta_knn(); //Hilo sa_tsp
void detiene_knn();
};
}
#endif // CONTROLADOR_H_INCLUDED
| 20.161765 | 120 | 0.711889 | [
"vector"
] |
8c3a06f187c60c288e9b1241da189b4db6e0d6e2 | 22,890 | h | C | Engine/Wintab/wintab.h | OGRECave/scape | 9c95ec7b6d8372a7a2a4eb6b96dcb5f2219e2bf2 | [
"BSD-2-Clause"
] | 48 | 2018-06-18T01:38:41.000Z | 2022-03-25T10:29:27.000Z | Engine/Wintab/wintab.h | OGRECave/scape | 9c95ec7b6d8372a7a2a4eb6b96dcb5f2219e2bf2 | [
"BSD-2-Clause"
] | 32 | 2018-07-23T14:17:23.000Z | 2020-11-02T23:28:48.000Z | Engine/Wintab/wintab.h | OGRECave/scape | 9c95ec7b6d8372a7a2a4eb6b96dcb5f2219e2bf2 | [
"BSD-2-Clause"
] | 7 | 2018-07-23T09:34:06.000Z | 2022-02-15T09:54:16.000Z | /* -------------------------------- wintab.h -------------------------------- */
/* Combined 16 & 32-bit version. */
/*------------------------------------------------------------------------------
The text and information contained in this file may be freely used,
copied, or distributed without compensation or licensing restrictions.
This file is copyright 1991-1998 by LCS/Telegraphics.
------------------------------------------------------------------------------*/
#ifndef _INC_WINTAB /* prevent multiple includes */
#define _INC_WINTAB
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* -------------------------------------------------------------------------- */
/* Messages */
#ifndef NOWTMESSAGES
#define WT_DEFBASE 0x7FF0
#define WT_MAXOFFSET 0xF
#define _WT_PACKET(b) ((b) + 0)
#define _WT_CTXOPEN(b) ((b) + 1)
#define _WT_CTXCLOSE(b) ((b) + 2)
#define _WT_CTXUPDATE(b) ((b) + 3)
#define _WT_CTXOVERLAP(b) ((b) + 4)
#define _WT_PROXIMITY(b) ((b) + 5)
#define _WT_INFOCHANGE(b) ((b) + 6)
#define _WT_CSRCHANGE(b) ((b) + 7) /* 1.1 */
#define _WT_MAX(b) ((b) + WT_MAXOFFSET)
#define WT_PACKET _WT_PACKET(WT_DEFBASE)
#define WT_CTXOPEN _WT_CTXOPEN(WT_DEFBASE)
#define WT_CTXCLOSE _WT_CTXCLOSE(WT_DEFBASE)
#define WT_CTXUPDATE _WT_CTXUPDATE(WT_DEFBASE)
#define WT_CTXOVERLAP _WT_CTXOVERLAP(WT_DEFBASE)
#define WT_PROXIMITY _WT_PROXIMITY(WT_DEFBASE)
#define WT_INFOCHANGE _WT_INFOCHANGE(WT_DEFBASE)
#define WT_CSRCHANGE _WT_CSRCHANGE(WT_DEFBASE) /* 1.1 */
#define WT_MAX _WT_MAX(WT_DEFBASE)
#endif
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
/* Data Types */
/* -------------------------------------------------------------------------- */
/* COMMON DATA DEFS */
DECLARE_HANDLE(HMGR); /* manager handle */
DECLARE_HANDLE(HCTX); /* context handle */
DECLARE_HANDLE(HWTHOOK); /* hook handle */
typedef DWORD WTPKT; /* packet mask */
#ifndef NOWTPKT
/* WTPKT bits */
#define PK_CONTEXT 0x0001 /* reporting context */
#define PK_STATUS 0x0002 /* status bits */
#define PK_TIME 0x0004 /* time stamp */
#define PK_CHANGED 0x0008 /* change bit vector */
#define PK_SERIAL_NUMBER 0x0010 /* packet serial number */
#define PK_CURSOR 0x0020 /* reporting cursor */
#define PK_BUTTONS 0x0040 /* button information */
#define PK_X 0x0080 /* x axis */
#define PK_Y 0x0100 /* y axis */
#define PK_Z 0x0200 /* z axis */
#define PK_NORMAL_PRESSURE 0x0400 /* normal or tip pressure */
#define PK_TANGENT_PRESSURE 0x0800 /* tangential or barrel pressure */
#define PK_ORIENTATION 0x1000 /* orientation info: tilts */
#define PK_ROTATION 0x2000 /* rotation info; 1.1 */
#endif
typedef DWORD FIX32; /* fixed-point arithmetic type */
#ifndef NOFIX32
#define INT(x) HIWORD(x)
#define FRAC(x) LOWORD(x)
#define CASTFIX32(x) ((FIX32)((x)*65536L))
#define ROUND(x) (INT(x) + (FRAC(x) > (WORD)0x8000))
#define FIX_MUL(c, a, b) \
(c = (((DWORD)FRAC(a) * FRAC(b)) >> 16) + (DWORD)INT(a) * FRAC(b) + (DWORD)INT(b) * FRAC(a) + \
((DWORD)INT(a) * INT(b) << 16))
#ifdef _WINDLL
#define FIX_DIV_SC static
#else
#define FIX_DIV_SC
#endif
#define FIX_DIV(c, a, b) \
{ \
FIX_DIV_SC DWORD temp, rem, btemp; \
\
/* fraction done bytewise */ \
temp = ((a / b) << 16); \
rem = a % b; \
btemp = b; \
if (INT(btemp) < 256) \
{ \
rem <<= 8; \
} \
else \
{ \
btemp >>= 8; \
} \
temp += ((rem / btemp) << 8); \
rem %= btemp; \
rem <<= 8; \
temp += rem / btemp; \
c = temp; \
}
#endif
/* -------------------------------------------------------------------------- */
/* INFO DATA DEFS */
#ifndef NOWTINFO
#ifndef NOWTAXIS
typedef struct tagAXIS
{
LONG axMin;
LONG axMax;
UINT axUnits;
FIX32 axResolution;
} AXIS, *PAXIS, NEAR *NPAXIS, FAR *LPAXIS;
/* unit specifiers */
#define TU_NONE 0
#define TU_INCHES 1
#define TU_CENTIMETERS 2
#define TU_CIRCLE 3
#endif
#ifndef NOWTSYSBUTTONS
/* system button assignment values */
#define SBN_NONE 0x00
#define SBN_LCLICK 0x01
#define SBN_LDBLCLICK 0x02
#define SBN_LDRAG 0x03
#define SBN_RCLICK 0x04
#define SBN_RDBLCLICK 0x05
#define SBN_RDRAG 0x06
#define SBN_MCLICK 0x07
#define SBN_MDBLCLICK 0x08
#define SBN_MDRAG 0x09
/* for Pen Windows */
#define SBN_PTCLICK 0x10
#define SBN_PTDBLCLICK 0x20
#define SBN_PTDRAG 0x30
#define SBN_PNCLICK 0x40
#define SBN_PNDBLCLICK 0x50
#define SBN_PNDRAG 0x60
#define SBN_P1CLICK 0x70
#define SBN_P1DBLCLICK 0x80
#define SBN_P1DRAG 0x90
#define SBN_P2CLICK 0xA0
#define SBN_P2DBLCLICK 0xB0
#define SBN_P2DRAG 0xC0
#define SBN_P3CLICK 0xD0
#define SBN_P3DBLCLICK 0xE0
#define SBN_P3DRAG 0xF0
#endif
#ifndef NOWTCAPABILITIES
/* hardware capabilities */
#define HWC_INTEGRATED 0x0001
#define HWC_TOUCH 0x0002
#define HWC_HARDPROX 0x0004
#define HWC_PHYSID_CURSORS 0x0008 /* 1.1 */
#endif
#ifndef NOWTIFC
#ifndef NOWTCURSORS
/* cursor capabilities */
#define CRC_MULTIMODE 0x0001 /* 1.1 */
#define CRC_AGGREGATE 0x0002 /* 1.1 */
#define CRC_INVERT 0x0004 /* 1.1 */
#endif
/* info categories */
#define WTI_INTERFACE 1
#define IFC_WINTABID 1
#define IFC_SPECVERSION 2
#define IFC_IMPLVERSION 3
#define IFC_NDEVICES 4
#define IFC_NCURSORS 5
#define IFC_NCONTEXTS 6
#define IFC_CTXOPTIONS 7
#define IFC_CTXSAVESIZE 8
#define IFC_NEXTENSIONS 9
#define IFC_NMANAGERS 10
#define IFC_MAX 10
#endif
#ifndef NOWTSTATUS
#define WTI_STATUS 2
#define STA_CONTEXTS 1
#define STA_SYSCTXS 2
#define STA_PKTRATE 3
#define STA_PKTDATA 4
#define STA_MANAGERS 5
#define STA_SYSTEM 6
#define STA_BUTTONUSE 7
#define STA_SYSBTNUSE 8
#define STA_MAX 8
#endif
#ifndef NOWTDEFCONTEXT
#define WTI_DEFCONTEXT 3
#define WTI_DEFSYSCTX 4
#define WTI_DDCTXS 400 /* 1.1 */
#define WTI_DSCTXS 500 /* 1.1 */
#define CTX_NAME 1
#define CTX_OPTIONS 2
#define CTX_STATUS 3
#define CTX_LOCKS 4
#define CTX_MSGBASE 5
#define CTX_DEVICE 6
#define CTX_PKTRATE 7
#define CTX_PKTDATA 8
#define CTX_PKTMODE 9
#define CTX_MOVEMASK 10
#define CTX_BTNDNMASK 11
#define CTX_BTNUPMASK 12
#define CTX_INORGX 13
#define CTX_INORGY 14
#define CTX_INORGZ 15
#define CTX_INEXTX 16
#define CTX_INEXTY 17
#define CTX_INEXTZ 18
#define CTX_OUTORGX 19
#define CTX_OUTORGY 20
#define CTX_OUTORGZ 21
#define CTX_OUTEXTX 22
#define CTX_OUTEXTY 23
#define CTX_OUTEXTZ 24
#define CTX_SENSX 25
#define CTX_SENSY 26
#define CTX_SENSZ 27
#define CTX_SYSMODE 28
#define CTX_SYSORGX 29
#define CTX_SYSORGY 30
#define CTX_SYSEXTX 31
#define CTX_SYSEXTY 32
#define CTX_SYSSENSX 33
#define CTX_SYSSENSY 34
#define CTX_MAX 34
#endif
#ifndef NOWTDEVICES
#define WTI_DEVICES 100
#define DVC_NAME 1
#define DVC_HARDWARE 2
#define DVC_NCSRTYPES 3
#define DVC_FIRSTCSR 4
#define DVC_PKTRATE 5
#define DVC_PKTDATA 6
#define DVC_PKTMODE 7
#define DVC_CSRDATA 8
#define DVC_XMARGIN 9
#define DVC_YMARGIN 10
#define DVC_ZMARGIN 11
#define DVC_X 12
#define DVC_Y 13
#define DVC_Z 14
#define DVC_NPRESSURE 15
#define DVC_TPRESSURE 16
#define DVC_ORIENTATION 17
#define DVC_ROTATION 18 /* 1.1 */
#define DVC_PNPID 19 /* 1.1 */
#define DVC_MAX 19
#endif
#ifndef NOWTCURSORS
#define WTI_CURSORS 200
#define CSR_NAME 1
#define CSR_ACTIVE 2
#define CSR_PKTDATA 3
#define CSR_BUTTONS 4
#define CSR_BUTTONBITS 5
#define CSR_BTNNAMES 6
#define CSR_BUTTONMAP 7
#define CSR_SYSBTNMAP 8
#define CSR_NPBUTTON 9
#define CSR_NPBTNMARKS 10
#define CSR_NPRESPONSE 11
#define CSR_TPBUTTON 12
#define CSR_TPBTNMARKS 13
#define CSR_TPRESPONSE 14
#define CSR_PHYSID 15 /* 1.1 */
#define CSR_MODE 16 /* 1.1 */
#define CSR_MINPKTDATA 17 /* 1.1 */
#define CSR_MINBUTTONS 18 /* 1.1 */
#define CSR_CAPABILITIES 19 /* 1.1 */
#define CSR_TYPE 20 /* 1.2 */
#define CSR_MAX 20
#endif
#ifndef NOWTEXTENSIONS
#define WTI_EXTENSIONS 300
#define EXT_NAME 1
#define EXT_TAG 2
#define EXT_MASK 3
#define EXT_SIZE 4
#define EXT_AXES 5
#define EXT_DEFAULT 6
#define EXT_DEFCONTEXT 7
#define EXT_DEFSYSCTX 8
#define EXT_CURSORS 9
#define EXT_MAX 109 /* Allow 100 cursors */
#endif
#endif
/* -------------------------------------------------------------------------- */
/* CONTEXT DATA DEFS */
#define LCNAMELEN 40
#define LC_NAMELEN 40
#ifdef WIN32
typedef struct tagLOGCONTEXTA
{
char lcName[LCNAMELEN];
UINT lcOptions;
UINT lcStatus;
UINT lcLocks;
UINT lcMsgBase;
UINT lcDevice;
UINT lcPktRate;
WTPKT lcPktData;
WTPKT lcPktMode;
WTPKT lcMoveMask;
DWORD lcBtnDnMask;
DWORD lcBtnUpMask;
LONG lcInOrgX;
LONG lcInOrgY;
LONG lcInOrgZ;
LONG lcInExtX;
LONG lcInExtY;
LONG lcInExtZ;
LONG lcOutOrgX;
LONG lcOutOrgY;
LONG lcOutOrgZ;
LONG lcOutExtX;
LONG lcOutExtY;
LONG lcOutExtZ;
FIX32 lcSensX;
FIX32 lcSensY;
FIX32 lcSensZ;
BOOL lcSysMode;
int lcSysOrgX;
int lcSysOrgY;
int lcSysExtX;
int lcSysExtY;
FIX32 lcSysSensX;
FIX32 lcSysSensY;
} LOGCONTEXTA, *PLOGCONTEXTA, NEAR *NPLOGCONTEXTA, FAR *LPLOGCONTEXTA;
typedef struct tagLOGCONTEXTW
{
WCHAR lcName[LCNAMELEN];
UINT lcOptions;
UINT lcStatus;
UINT lcLocks;
UINT lcMsgBase;
UINT lcDevice;
UINT lcPktRate;
WTPKT lcPktData;
WTPKT lcPktMode;
WTPKT lcMoveMask;
DWORD lcBtnDnMask;
DWORD lcBtnUpMask;
LONG lcInOrgX;
LONG lcInOrgY;
LONG lcInOrgZ;
LONG lcInExtX;
LONG lcInExtY;
LONG lcInExtZ;
LONG lcOutOrgX;
LONG lcOutOrgY;
LONG lcOutOrgZ;
LONG lcOutExtX;
LONG lcOutExtY;
LONG lcOutExtZ;
FIX32 lcSensX;
FIX32 lcSensY;
FIX32 lcSensZ;
BOOL lcSysMode;
int lcSysOrgX;
int lcSysOrgY;
int lcSysExtX;
int lcSysExtY;
FIX32 lcSysSensX;
FIX32 lcSysSensY;
} LOGCONTEXTW, *PLOGCONTEXTW, NEAR *NPLOGCONTEXTW, FAR *LPLOGCONTEXTW;
#ifdef UNICODE
typedef LOGCONTEXTW LOGCONTEXT;
typedef PLOGCONTEXTW PLOGCONTEXT;
typedef NPLOGCONTEXTW NPLOGCONTEXT;
typedef LPLOGCONTEXTW LPLOGCONTEXT;
#else
typedef LOGCONTEXTA LOGCONTEXT;
typedef PLOGCONTEXTA PLOGCONTEXT;
typedef NPLOGCONTEXTA NPLOGCONTEXT;
typedef LPLOGCONTEXTA LPLOGCONTEXT;
#endif /* UNICODE */
#else /* WIN32 */
typedef struct tagLOGCONTEXT
{
char lcName[LCNAMELEN];
UINT lcOptions;
UINT lcStatus;
UINT lcLocks;
UINT lcMsgBase;
UINT lcDevice;
UINT lcPktRate;
WTPKT lcPktData;
WTPKT lcPktMode;
WTPKT lcMoveMask;
DWORD lcBtnDnMask;
DWORD lcBtnUpMask;
LONG lcInOrgX;
LONG lcInOrgY;
LONG lcInOrgZ;
LONG lcInExtX;
LONG lcInExtY;
LONG lcInExtZ;
LONG lcOutOrgX;
LONG lcOutOrgY;
LONG lcOutOrgZ;
LONG lcOutExtX;
LONG lcOutExtY;
LONG lcOutExtZ;
FIX32 lcSensX;
FIX32 lcSensY;
FIX32 lcSensZ;
BOOL lcSysMode;
int lcSysOrgX;
int lcSysOrgY;
int lcSysExtX;
int lcSysExtY;
FIX32 lcSysSensX;
FIX32 lcSysSensY;
} LOGCONTEXT, *PLOGCONTEXT, NEAR *NPLOGCONTEXT, FAR *LPLOGCONTEXT;
#endif /* WIN32 */
/* context option values */
#define CXO_SYSTEM 0x0001
#define CXO_PEN 0x0002
#define CXO_MESSAGES 0x0004
#define CXO_MARGIN 0x8000
#define CXO_MGNINSIDE 0x4000
#define CXO_CSRMESSAGES 0x0008 /* 1.1 */
/* context status values */
#define CXS_DISABLED 0x0001
#define CXS_OBSCURED 0x0002
#define CXS_ONTOP 0x0004
/* context lock values */
#define CXL_INSIZE 0x0001
#define CXL_INASPECT 0x0002
#define CXL_SENSITIVITY 0x0004
#define CXL_MARGIN 0x0008
#define CXL_SYSOUT 0x0010
/* -------------------------------------------------------------------------- */
/* EVENT DATA DEFS */
/* For packet structure definition, see pktdef.h */
/* packet status values */
#define TPS_PROXIMITY 0x0001
#define TPS_QUEUE_ERR 0x0002
#define TPS_MARGIN 0x0004
#define TPS_GRAB 0x0008
#define TPS_INVERT 0x0010 /* 1.1 */
typedef struct tagORIENTATION
{
int orAzimuth;
int orAltitude;
int orTwist;
} ORIENTATION, *PORIENTATION, NEAR *NPORIENTATION, FAR *LPORIENTATION;
typedef struct tagROTATION
{ /* 1.1 */
int roPitch;
int roRoll;
int roYaw;
} ROTATION, *PROTATION, NEAR *NPROTATION, FAR *LPROTATION;
// grandfather in obsolete member names.
#define rotPitch roPitch
#define rotRoll roRoll
#define rotYaw roYaw
/* relative buttons */
#define TBN_NONE 0
#define TBN_UP 1
#define TBN_DOWN 2
/* -------------------------------------------------------------------------- */
/* DEVICE CONFIG CONSTANTS */
#ifndef NOWTDEVCFG
#define WTDC_NONE 0
#define WTDC_CANCEL 1
#define WTDC_OK 2
#define WTDC_RESTART 3
#endif
/* -------------------------------------------------------------------------- */
/* HOOK CONSTANTS */
#ifndef NOWTHOOKS
#define WTH_PLAYBACK 1
#define WTH_RECORD 2
#define WTHC_GETLPLPFN (-3)
#define WTHC_LPLPFNNEXT (-2)
#define WTHC_LPFNNEXT (-1)
#define WTHC_ACTION 0
#define WTHC_GETNEXT 1
#define WTHC_SKIP 2
#endif
/* -------------------------------------------------------------------------- */
/* PREFERENCE FUNCTION CONSTANTS */
#ifndef NOWTPREF
#define WTP_LPDEFAULT ((LPVOID)-1L)
#define WTP_DWDEFAULT ((DWORD)-1L)
#endif
/* -------------------------------------------------------------------------- */
/* EXTENSION TAGS AND CONSTANTS */
#ifndef NOWTEXTENSIONS
/* constants for use with pktdef.h */
#define PKEXT_ABSOLUTE 1
#define PKEXT_RELATIVE 2
/* Extension tags. */
#define WTX_OBT 0 /* Out of bounds tracking */
#define WTX_FKEYS 1 /* Function keys */
#define WTX_TILT 2 /* Raw Cartesian tilt; 1.1 */
#define WTX_CSRMASK 3 /* select input by cursor type; 1.1 */
#define WTX_XBTNMASK 4 /* Extended button mask; 1.1 */
#define WTX_EXPKEYS 5 /* ExpressKeys; 1.3 */
typedef struct tagXBTNMASK
{
BYTE xBtnDnMask[32];
BYTE xBtnUpMask[32];
} XBTNMASK;
typedef struct tagTILT
{ /* 1.1 */
int tiltX;
int tiltY;
} TILT;
#endif
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
/* Functions */
#ifndef API
#ifndef WINAPI
#define API FAR PASCAL
#else
#define API WINAPI
#endif
#endif
#ifndef NOWTCALLBACKS
#ifndef CALLBACK
#define CALLBACK FAR PASCAL
#endif
#ifndef NOWTMANAGERFXNS
/* callback function types */
typedef BOOL(WINAPI* WTENUMPROC)(HCTX, LPARAM); /* changed CALLBACK->WINAPI, 1.1 */
typedef BOOL(WINAPI* WTCONFIGPROC)(HCTX, HWND);
typedef LRESULT(WINAPI* WTHOOKPROC)(int, WPARAM, LPARAM);
typedef WTHOOKPROC FAR* LPWTHOOKPROC;
#endif
#endif
#ifndef NOWTFUNCTIONS
#ifndef NOWTBASICFXNS
/* BASIC FUNCTIONS */
#ifdef WIN32
UINT API WTInfoA(UINT, UINT, LPVOID);
#define ORD_WTInfoA 20
UINT API WTInfoW(UINT, UINT, LPVOID);
#define ORD_WTInfoW 1020
#ifdef UNICODE
#define WTInfo WTInfoW
#define ORD_WTInfo ORD_WTInfoW
#else
#define WTInfo WTInfoA
#define ORD_WTInfo ORD_WTInfoA
#endif /* !UNICODE */
#else
UINT API WTInfo(UINT, UINT, LPVOID);
#define ORD_WTInfo 20
#endif
#ifdef WIN32
HCTX API WTOpenA(HWND, LPLOGCONTEXTA, BOOL);
#define ORD_WTOpenA 21
HCTX API WTOpenW(HWND, LPLOGCONTEXTW, BOOL);
#define ORD_WTOpenW 1021
#ifdef UNICODE
#define WTOpen WTOpenW
#define ORD_WTOpen ORD_WTOpenW
#else
#define WTOpen WTOpenA
#define ORD_WTOpen ORD_WTOpenA
#endif /* !UNICODE */
#else
HCTX API WTOpen(HWND, LPLOGCONTEXT, BOOL);
#define ORD_WTOpen 21
#endif
BOOL API WTClose(HCTX);
#define ORD_WTClose 22
int API WTPacketsGet(HCTX, int, LPVOID);
#define ORD_WTPacketsGet 23
BOOL API WTPacket(HCTX, UINT, LPVOID);
#define ORD_WTPacket 24
#endif
#ifndef NOWTVISIBILITYFXNS
/* VISIBILITY FUNCTIONS */
BOOL API WTEnable(HCTX, BOOL);
#define ORD_WTEnable 40
BOOL API WTOverlap(HCTX, BOOL);
#define ORD_WTOverlap 41
#endif
#ifndef NOWTCTXEDITFXNS
/* CONTEXT EDITING FUNCTIONS */
BOOL API WTConfig(HCTX, HWND);
#define ORD_WTConfig 60
#ifdef WIN32
BOOL API WTGetA(HCTX, LPLOGCONTEXTA);
#define ORD_WTGetA 61
BOOL API WTGetW(HCTX, LPLOGCONTEXTW);
#define ORD_WTGetW 1061
#ifdef UNICODE
#define WTGet WTGetW
#define ORD_WTGet ORD_WTGetW
#else
#define WTGet WTGetA
#define ORD_WTGet ORD_WTGetA
#endif /* !UNICODE */
#else
BOOL API WTGet(HCTX, LPLOGCONTEXT);
#define ORD_WTGet 61
#endif
#ifdef WIN32
BOOL API WTSetA(HCTX, LPLOGCONTEXTA);
#define ORD_WTSetA 62
BOOL API WTSetW(HCTX, LPLOGCONTEXTW);
#define ORD_WTSetW 1062
#ifdef UNICODE
#define WTSet WTSetW
#define ORD_WTSet ORD_WTSetW
#else
#define WTSet WTSetA
#define ORD_WTSet ORD_WTSetA
#endif /* !UNICODE */
#else
BOOL API WTSet(HCTX, LPLOGCONTEXT);
#define ORD_WTSet 62
#endif
BOOL API WTExtGet(HCTX, UINT, LPVOID);
#define ORD_WTExtGet 63
BOOL API WTExtSet(HCTX, UINT, LPVOID);
#define ORD_WTExtSet 64
BOOL API WTSave(HCTX, LPVOID);
#define ORD_WTSave 65
HCTX API WTRestore(HWND, LPVOID, BOOL);
#define ORD_WTRestore 66
#endif
#ifndef NOWTQUEUEFXNS
/* ADVANCED PACKET AND QUEUE FUNCTIONS */
int API WTPacketsPeek(HCTX, int, LPVOID);
#define ORD_WTPacketsPeek 80
int API WTDataGet(HCTX, UINT, UINT, int, LPVOID, LPINT);
#define ORD_WTDataGet 81
int API WTDataPeek(HCTX, UINT, UINT, int, LPVOID, LPINT);
#define ORD_WTDataPeek 82
#ifndef WIN32
/* OBSOLETE IN WIN32! */
DWORD API WTQueuePackets(HCTX);
#define ORD_WTQueuePackets 83
#endif
int API WTQueueSizeGet(HCTX);
#define ORD_WTQueueSizeGet 84
BOOL API WTQueueSizeSet(HCTX, int);
#define ORD_WTQueueSizeSet 85
#endif
#ifndef NOWTHMGRFXNS
/* MANAGER HANDLE FUNCTIONS */
HMGR API WTMgrOpen(HWND, UINT);
#define ORD_WTMgrOpen 100
BOOL API WTMgrClose(HMGR);
#define ORD_WTMgrClose 101
#endif
#ifndef NOWTMGRCTXFXNS
/* MANAGER CONTEXT FUNCTIONS */
BOOL API WTMgrContextEnum(HMGR, WTENUMPROC, LPARAM);
#define ORD_WTMgrContextEnum 120
HWND API WTMgrContextOwner(HMGR, HCTX);
#define ORD_WTMgrContextOwner 121
HCTX API WTMgrDefContext(HMGR, BOOL);
#define ORD_WTMgrDefContext 122
HCTX API WTMgrDefContextEx(HMGR, UINT, BOOL); /* 1.1 */
#define ORD_WTMgrDefContextEx 206
#endif
#ifndef NOWTMGRCONFIGFXNS
/* MANAGER CONFIG BOX FUNCTIONS */
UINT API WTMgrDeviceConfig(HMGR, UINT, HWND);
#define ORD_WTMgrDeviceConfig 140
#ifndef WIN32
/* OBSOLETE IN WIN32! */
BOOL API WTMgrConfigReplace(HMGR, BOOL, WTCONFIGPROC);
#define ORD_WTMgrConfigReplace 141
#endif
#endif
#ifndef NOWTMGRHOOKFXNS
/* MANAGER PACKET HOOK FUNCTIONS */
#ifndef WIN32
/* OBSOLETE IN WIN32! */
WTHOOKPROC API WTMgrPacketHook(HMGR, BOOL, int, WTHOOKPROC);
#define ORD_WTMgrPacketHook 160
LRESULT API WTMgrPacketHookDefProc(int, WPARAM, LPARAM, LPWTHOOKPROC);
#define ORD_WTMgrPacketHookDefProc 161
#endif
#endif
#ifndef NOWTMGRPREFFXNS
/* MANAGER PREFERENCE DATA FUNCTIONS */
BOOL API WTMgrExt(HMGR, UINT, LPVOID);
#define ORD_WTMgrExt 180
BOOL API WTMgrCsrEnable(HMGR, UINT, BOOL);
#define ORD_WTMgrCsrEnable 181
BOOL API WTMgrCsrButtonMap(HMGR, UINT, LPBYTE, LPBYTE);
#define ORD_WTMgrCsrButtonMap 182
BOOL API WTMgrCsrPressureBtnMarks(HMGR, UINT, DWORD, DWORD);
#define ORD_WTMgrCsrPressureBtnMarks 183
BOOL API WTMgrCsrPressureResponse(HMGR, UINT, UINT FAR*, UINT FAR*);
#define ORD_WTMgrCsrPressureResponse 184
BOOL API WTMgrCsrExt(HMGR, UINT, UINT, LPVOID);
#define ORD_WTMgrCsrExt 185
#endif
/* Win32 replacements for non-portable functions. */
#ifndef NOWTQUEUEFXNS
/* ADVANCED PACKET AND QUEUE FUNCTIONS */
BOOL API WTQueuePacketsEx(HCTX, UINT FAR*, UINT FAR*);
#define ORD_WTQueuePacketsEx 200
#endif
#ifndef NOWTMGRCONFIGFXNS
/* MANAGER CONFIG BOX FUNCTIONS */
#ifdef WIN32
BOOL API WTMgrConfigReplaceExA(HMGR, BOOL, LPSTR, LPSTR);
#define ORD_WTMgrConfigReplaceExA 202
BOOL API WTMgrConfigReplaceExW(HMGR, BOOL, LPWSTR, LPSTR);
#define ORD_WTMgrConfigReplaceExW 1202
#ifdef UNICODE
#define WTMgrConfigReplaceEx WTMgrConfigReplaceExW
#define ORD_WTMgrConfigReplaceEx ORD_WTMgrConfigReplaceExW
#else
#define WTMgrConfigReplaceEx WTMgrConfigReplaceExA
#define ORD_WTMgrConfigReplaceEx ORD_WTMgrConfigReplaceExA
#endif /* !UNICODE */
#else
BOOL API WTMgrConfigReplaceEx(HMGR, BOOL, LPSTR, LPSTR);
#define ORD_WTMgrConfigReplaceEx 202
#endif
#endif
#ifndef NOWTMGRHOOKFXNS
/* MANAGER PACKET HOOK FUNCTIONS */
#ifdef WIN32
HWTHOOK API WTMgrPacketHookExA(HMGR, int, LPSTR, LPSTR);
#define ORD_WTMgrPacketHookExA 203
HWTHOOK API WTMgrPacketHookExW(HMGR, int, LPWSTR, LPSTR);
#define ORD_WTMgrPacketHookExW 1203
#ifdef UNICODE
#define WTMgrPacketHookEx WTMgrPacketHookExW
#define ORD_WTMgrPacketHookEx ORD_WTMgrPacketHookExW
#else
#define WTMgrPacketHookEx WTMgrPacketHookExA
#define ORD_WTMgrPacketHookEx ORD_WTMgrPacketHookExA
#endif /* !UNICODE */
#else
HWTHOOK API WTMgrPacketHookEx(HMGR, int, LPSTR, LPSTR);
#define ORD_WTMgrPacketHookEx 203
#endif
BOOL API WTMgrPacketUnhook(HWTHOOK);
#define ORD_WTMgrPacketUnhook 204
LRESULT API WTMgrPacketHookNext(HWTHOOK, int, WPARAM, LPARAM);
#define ORD_WTMgrPacketHookNext 205
#endif
#ifndef NOWTMGRPREFFXNS
/* MANAGER PREFERENCE DATA FUNCTIONS */
BOOL API WTMgrCsrPressureBtnMarksEx(HMGR, UINT, UINT FAR*, UINT FAR*);
#define ORD_WTMgrCsrPressureBtnMarksEx 201
#endif
#endif
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* #define _INC_WINTAB */
| 26.370968 | 108 | 0.639231 | [
"vector"
] |
8c3d0f00b289c7b660f6563264f5a4affdb9c236 | 1,330 | h | C | sniper/common/core/memory_subsystem/cache/onchip_undo_buffer.h | kleberkruger/PiCL | 918213cc6143d38a2f55b3ea0ba283119829199d | [
"MIT"
] | null | null | null | sniper/common/core/memory_subsystem/cache/onchip_undo_buffer.h | kleberkruger/PiCL | 918213cc6143d38a2f55b3ea0ba283119829199d | [
"MIT"
] | null | null | null | sniper/common/core/memory_subsystem/cache/onchip_undo_buffer.h | kleberkruger/PiCL | 918213cc6143d38a2f55b3ea0ba283119829199d | [
"MIT"
] | null | null | null | #ifndef ONCHIP_UNDO_BUFFER_H
#define ONCHIP_UNDO_BUFFER_H
#include <queue>
#include <vector>
#include "cache_block_info.h"
#include "mem_component.h"
class UndoEntry
{
public:
UndoEntry(UInt64 system_eid, CacheBlockInfo *cache_block_info);
UndoEntry(const UndoEntry &orig);
virtual ~UndoEntry();
IntPtr getTag() const { return m_tag; }
UInt64 getValidFromEID() const { return m_valid_from_eid; }
UInt64 getValidTillEID() const { return m_valid_till_eid; }
private:
IntPtr m_tag;
UInt64 m_valid_from_eid;
UInt64 m_valid_till_eid;
// UInt64 data;
};
class OnChipUndoBuffer
{
public:
OnChipUndoBuffer(UInt32 num_entries = 0);
virtual ~OnChipUndoBuffer();
bool isFull();
void insertUndoEntry(UInt64 system_eid, CacheBlockInfo *cache_block_info);
std::queue<UndoEntry> removeOldEntries(UInt64 acs_eid);
std::queue<UndoEntry> removeOldEntries();
std::queue<UndoEntry> removeAllEntries();
UInt32 getNumEntries() const { return m_num_entries; }
String getName(void) const { return "On-Chip Undo Buffer"; }
MemComponent::component_t getMemComponent() const { return MemComponent::ONCHIP_UNDO_BUFFER; }
void print();
private:
const UInt32 m_num_entries; // Set 0 to an ilimited buffer
std::vector<UndoEntry> m_buffer;
};
#endif /* ONCHIP_UNDO_BUFFER_H */
| 25.576923 | 97 | 0.741353 | [
"vector"
] |
8c3fd5718036752c18a30e41553f2a047bde9080 | 211,357 | h | C | libigl/include/CGAL/Arrangement_2/Arrangement_on_surface_2_impl.h | sjokic/WallDestruction | 2e1c000096df4aa027a91ff1732ce50a205b221a | [
"MIT"
] | 1 | 2021-11-03T11:30:05.000Z | 2021-11-03T11:30:05.000Z | libigl/include/CGAL/Arrangement_2/Arrangement_on_surface_2_impl.h | sjokic/WallDestruction | 2e1c000096df4aa027a91ff1732ce50a205b221a | [
"MIT"
] | null | null | null | libigl/include/CGAL/Arrangement_2/Arrangement_on_surface_2_impl.h | sjokic/WallDestruction | 2e1c000096df4aa027a91ff1732ce50a205b221a | [
"MIT"
] | null | null | null | // Copyright (c) 2005,2006,2007,2008,2009,2010,2011,2012,2013 Tel-Aviv University (Israel).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
//
// $URL$
// $Id$
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial
//
//
// Author(s) : Ron Wein <wein@post.tau.ac.il>
// Efi Fogel <efif@post.tau.ac.il>
// Eric Berberich <eric.berberich@cgal.org>
// (based on old version by: Iddo Hanniel,
// Eyal Flato,
// Oren Nechushtan,
// Ester Ezra,
// Shai Hirsch,
// and Eugene Lipovetsky)
#ifndef CGAL_ARRANGEMENT_ON_SURFACE_2_IMPL_H
#define CGAL_ARRANGEMENT_ON_SURFACE_2_IMPL_H
#include <CGAL/license/Arrangement_on_surface_2.h>
#ifndef CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
#define CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE 0
#endif
/*! \file
* Member-function definitions for the Arrangement_2<GeomTraits, TopTraits>
* class-template.
*/
#include <CGAL/function_objects.h>
#include <CGAL/use.h>
namespace CGAL {
//-----------------------------------------------------------------------------
// Default constructor.
//
template <typename GeomTraits, typename TopTraits>
Arrangement_on_surface_2<GeomTraits, TopTraits>::Arrangement_on_surface_2() :
m_topol_traits()
{
typedef has_Left_side_category<GeomTraits> Cond_left;
typedef internal::Validate_left_side_category<GeomTraits, Cond_left::value>
Validate_left_side_category;
void (Validate_left_side_category::*pleft)(void) =
&Validate_left_side_category::template missing__Left_side_category<int>;
(void)pleft;
typedef has_Bottom_side_category<GeomTraits> Cond_bottom;
typedef internal::Validate_bottom_side_category<GeomTraits,
Cond_bottom::value>
Validate_bottom_side_category;
void (Validate_bottom_side_category::*pbottom)(void) =
&Validate_bottom_side_category::template missing__Bottom_side_category<int>;
(void)pbottom;
typedef has_Top_side_category<GeomTraits> Cond_top;
typedef internal::Validate_top_side_category<GeomTraits, Cond_top::value>
Validate_top_side_category;
void (Validate_top_side_category::*ptop)(void) =
&Validate_top_side_category::template missing__Top_side_category<int>;
(void)ptop;
typedef has_Right_side_category<GeomTraits> Cond_right;
typedef internal::Validate_right_side_category<GeomTraits, Cond_right::value>
Validate_right_side_category;
void (Validate_right_side_category::*pright)(void) =
&Validate_right_side_category::template missing__Right_side_category<int>;
(void)pright;
// Initialize the DCEL structure to represent an empty arrangement.
m_topol_traits.init_dcel();
// Allocate the traits.
m_geom_traits = new Traits_adaptor_2;
m_own_traits = true;
}
//-----------------------------------------------------------------------------
// Copy constructor.
//
template <typename GeomTraits, typename TopTraits>
Arrangement_on_surface_2<GeomTraits, TopTraits>::
Arrangement_on_surface_2(const Self& arr) :
m_geom_traits(nullptr),
m_own_traits(false)
{
assign(arr);
}
//-----------------------------------------------------------------------------
// Constructor given a traits object.
//
template <typename GeomTraits, typename TopTraits>
Arrangement_on_surface_2<GeomTraits, TopTraits>::
Arrangement_on_surface_2(const Geometry_traits_2* geom_traits) :
m_topol_traits(geom_traits)
{
typedef has_Left_side_category<GeomTraits> Cond_left;
typedef internal::Validate_left_side_category<GeomTraits, Cond_left::value>
Validate_left_side_category;
void (Validate_left_side_category::*pleft)(void) =
&Validate_left_side_category::template missing__Left_side_category<int>;
(void)pleft;
typedef has_Bottom_side_category<GeomTraits> Cond_bottom;
typedef internal::Validate_bottom_side_category<GeomTraits,
Cond_bottom::value>
Validate_bottom_side_category;
void (Validate_bottom_side_category::*pbottom)(void) =
&Validate_bottom_side_category::template missing__Bottom_side_category<int>;
(void)pbottom;
typedef has_Top_side_category<GeomTraits> Cond_top;
typedef internal::Validate_top_side_category<GeomTraits, Cond_top::value>
Validate_top_side_category;
void (Validate_top_side_category::*ptop)(void) =
&Validate_top_side_category::template missing__Top_side_category<int>;
(void)ptop;
typedef has_Right_side_category<GeomTraits> Cond_right;
typedef internal::Validate_right_side_category<GeomTraits, Cond_right::value>
Validate_right_side_category;
void (Validate_right_side_category::*pright)(void) =
&Validate_right_side_category::template missing__Right_side_category<int>;
(void)pright;
// Initialize the DCEL structure to represent an empty arrangement.
m_topol_traits.init_dcel();
// Set the traits.
m_geom_traits = static_cast<const Traits_adaptor_2*>(geom_traits);
m_own_traits = false;
}
//-----------------------------------------------------------------------------
// Assignment operator.
//
template <typename GeomTraits, typename TopTraits>
Arrangement_on_surface_2<GeomTraits, TopTraits>&
Arrangement_on_surface_2<GeomTraits, TopTraits>::operator=(const Self& arr)
{
if (this == &arr) return (*this); // handle self-assignment
assign(arr);
return (*this);
}
//-----------------------------------------------------------------------------
// Assign an arrangement.
//
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::assign(const Self& arr)
{
// Clear the current contents of the arrangement.
clear();
// Notify the observers that an assignment is to take place.
_notify_before_assign(arr);
// Assign the topology-traits object.
m_topol_traits.assign(arr.m_topol_traits);
// Go over the vertices and create duplicates of the stored points.
Point_2* dup_p;
DVertex* p_v;
typename Dcel::Vertex_iterator vit;
for (vit = _dcel().vertices_begin(); vit != _dcel().vertices_end(); ++vit) {
p_v = &(*vit);
if (! p_v->has_null_point()) {
// Create the duplicate point and store it in the points container.
dup_p = _new_point(p_v->point());
// Associate the vertex with the duplicated point.
p_v->set_point(dup_p);
}
}
// Go over the edge and create duplicates of the stored curves.
typename Dcel::Edge_iterator eit;
for (eit = _dcel().edges_begin(); eit != _dcel().edges_end(); ++eit) {
DHalfedge* p_e = &(*eit);
if (! p_e->has_null_curve()) {
// Create the duplicate curve and store it in the curves container.
X_monotone_curve_2* dup_cv = _new_curve(p_e->curve());
// Associate the halfedge (and its twin) with the duplicated curve.
p_e->set_curve(dup_cv);
}
}
// Take care of the traits object.
if (m_own_traits && (m_geom_traits != nullptr)) {
delete m_geom_traits;
m_geom_traits = nullptr;
}
m_geom_traits = (arr.m_own_traits) ? new Traits_adaptor_2 : arr.m_geom_traits;
m_own_traits = arr.m_own_traits;
// Notify the observers that the assignment has been performed.
_notify_after_assign();
}
//-----------------------------------------------------------------------------
// Destructor.
//
template <typename GeomTraits, typename TopTraits>
Arrangement_on_surface_2<GeomTraits, TopTraits>::~Arrangement_on_surface_2()
{
// Free all stored points.
typename Dcel::Vertex_iterator vit;
for (vit = _dcel().vertices_begin(); vit != _dcel().vertices_end(); ++vit)
if (! vit->has_null_point())
_delete_point(vit->point());
// Free all stores curves.
typename Dcel::Edge_iterator eit;
for (eit = _dcel().edges_begin(); eit != _dcel().edges_end(); ++eit)
if (! eit->has_null_curve())
_delete_curve(eit->curve());
// Free the traits object, if necessary.
if (m_own_traits && (m_geom_traits != nullptr)) {
delete m_geom_traits;
m_geom_traits = nullptr;
}
// Detach all observers still attached to the arrangement.
Observers_iterator iter = m_observers.begin();
Observers_iterator next;
Observers_iterator end = m_observers.end();
while (iter != end) {
next = iter;
++next;
(*iter)->detach();
iter = next;
}
}
//-----------------------------------------------------------------------------
// Clear the arrangement.
//
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::clear()
{
// Notify the observers that we are about to clear the arragement.
_notify_before_clear();
// Free all stored points.
typename Dcel::Vertex_iterator vit;
for (vit = _dcel().vertices_begin(); vit != _dcel().vertices_end(); ++vit)
if (! vit->has_null_point()) _delete_point(vit->point());
// Free all stores curves.
typename Dcel::Edge_iterator eit;
for (eit = _dcel().edges_begin(); eit != _dcel().edges_end(); ++eit)
if (! eit->has_null_curve()) _delete_curve(eit->curve());
// Clear the DCEL and construct an empty arrangement.
_dcel().delete_all();
m_topol_traits.init_dcel();
// Notify the observers that we have just cleared the arragement.
_notify_after_clear();
}
//-----------------------------------------------------------------------------
// Insert a point as an isolated vertex in the interior of a given face.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::Vertex_handle
Arrangement_on_surface_2<GeomTraits, TopTraits>::
insert_in_face_interior(const Point_2& p, Face_handle f)
{
DFace* p_f = _face(f);
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "Aos_2: insert_in_face_interior (interface)" << std::endl;
std::cout << "pt : " << p << std::endl;
std::cout << "face : " << &(*f) << std::endl;
#endif
// Create a new vertex associated with the given point.
// We assume the point has no boundary conditions.
DVertex* v = _create_vertex(p);
Vertex_handle vh(v);
// Insert v as an isolated vertex inside the given face.
_insert_isolated_vertex(p_f, v);
// Return a handle to the new isolated vertex.
return vh;
}
//-----------------------------------------------------------------------------
// Insert an x-monotone curve into the arrangement as a new hole (inner
// component) inside the given face.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::Halfedge_handle
Arrangement_on_surface_2<GeomTraits, TopTraits>::
insert_in_face_interior(const X_monotone_curve_2& cv, Face_handle f)
{
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "Aos_2: insert_in_face_interior (interface)" << std::endl;
std::cout << "cv : " << cv << std::endl;
std::cout << "face : " << &(*f) << std::endl;
#endif
DFace* p_f = _face(f);
// Check if cv's left end has boundary conditions, and obtain a vertex v1
// that corresponds to this end.
const Arr_parameter_space ps_x1 =
m_geom_traits->parameter_space_in_x_2_object()(cv, ARR_MIN_END);
const Arr_parameter_space ps_y1 =
m_geom_traits->parameter_space_in_y_2_object()(cv, ARR_MIN_END);
DHalfedge* fict_prev1 = nullptr;
DVertex* v1 = ((ps_x1 == ARR_INTERIOR) && (ps_y1 == ARR_INTERIOR)) ?
// The curve has a valid left endpoint: Create a new vertex associated
// with the curve's left endpoint.
_create_vertex(m_geom_traits->construct_min_vertex_2_object()(cv)) :
// Locate the DCEL features that will be used for inserting the curve's
// left end.
_place_and_set_curve_end(p_f, cv, ARR_MIN_END, ps_x1, ps_y1, &fict_prev1);
// Check if cv's right end has boundary conditions, and obtain a vertex v2
// that corresponds to this end.
const Arr_parameter_space ps_x2 =
m_geom_traits->parameter_space_in_x_2_object()(cv, ARR_MAX_END);
const Arr_parameter_space ps_y2 =
m_geom_traits->parameter_space_in_y_2_object()(cv, ARR_MAX_END);
DHalfedge* fict_prev2 = nullptr;
DVertex* v2 = ((ps_x2 == ARR_INTERIOR) && (ps_y2 == ARR_INTERIOR)) ?
// The curve has a valid right endpoint: Create a new vertex associated
// with the curve's right endpoint.
_create_vertex(m_geom_traits->construct_max_vertex_2_object()(cv)) :
// Locate the DCEL features that will be used for inserting the curve's
// right end.
_place_and_set_curve_end(p_f, cv, ARR_MAX_END, ps_x2, ps_y2, &fict_prev2);
// Create the edge connecting the two vertices (note we know v1 is
// lexicographically smaller than v2).
DHalfedge* new_he;
if ((fict_prev1 == nullptr) && (fict_prev2 == nullptr))
// Both vertices represent valid points.
new_he = _insert_in_face_interior(p_f, cv, ARR_LEFT_TO_RIGHT, v1, v2);
else if ((fict_prev1 == nullptr) && (fict_prev2 != nullptr)) {
// v1 represents a valid point and v2 is inserted using its predecessor.
new_he = _insert_from_vertex(fict_prev2, cv, ARR_RIGHT_TO_LEFT, v1);
new_he = new_he->opposite();
}
else if ((fict_prev1 != nullptr) && (fict_prev2 == nullptr))
// v1 is inserted using its predecessor and v2 represents a valid point.
new_he = _insert_from_vertex(fict_prev1, cv, ARR_LEFT_TO_RIGHT, v2);
else {
// Both vertices are inserted using their predecessor halfedges.
// Comment:
// In case the inserted curve has two vertical asymptotes at the top
// it happens that fict_prev1 is split by the max end and becomes the
// prev edge, which is fict_prev2. Since both pointers are equal they
// both point to the max end. Thus, we advance fict_prev1 by one
// such that it points to the min end again.
// Note that this only happens at the top. At the bottom everything
// goes fine since the insertion order is reverted with respect to the
// orientation of the edges.
//
// In the other function such a fix is not needed, as at most one
// curve-end reaches the boundary. It is also not possible to delay
// it to _insert_at_vertices, as that expects the two predecessor
// halfedges as input. An early detecting is also not possible
// (i.e.~in _place_and_set_curve_end), as that needs to know to be
// called from here!
if (fict_prev1 == fict_prev2) fict_prev1 = fict_prev1->next();
// Note that in this case we may create a new face.
bool new_face_created = false;
bool check_swapped_predecessors = false;
new_he = _insert_at_vertices(fict_prev1, cv, ARR_LEFT_TO_RIGHT,
fict_prev2->next(), new_face_created,
check_swapped_predecessors);
// Comment EBEB 2012-10-21: Swapping does not take place as there is no local minumum so far
CGAL_assertion(!check_swapped_predecessors);
// usually one would expect to have an new_he (and its twin) lying on the
// same _inner_ CCB ...
if (new_face_created) {
// ... but in case that a new face got created new_he should lie on an
// outer CCB
CGAL_assertion(new_he->is_on_outer_ccb());
// Note! new_he is not needed to define the new outer CCB of the new face
// Here, it can be the outer ccb of the old face, as there is also not
// swapping taking place!
// In case a new face has been created (pointed by the new halfedge we
// obtained), we have to examine the holes and isolated vertices in the
// existing face (pointed by the twin halfedge) and move the relevant
// holes and isolated vertices into the new face.
_relocate_in_new_face(new_he);
}
}
// Return a handle to the new halfedge directed from left to right.
CGAL_postcondition(new_he->direction() == ARR_LEFT_TO_RIGHT);
return (Halfedge_handle(new_he));
}
//-----------------------------------------------------------------------------
// Insert an x-monotone curve into the arrangement, such that its left
// endpoint corresponds to a given arrangement vertex.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::Halfedge_handle
Arrangement_on_surface_2<GeomTraits, TopTraits>::
insert_from_left_vertex(const X_monotone_curve_2& cv,
Vertex_handle v,
Face_handle f)
{
CGAL_precondition_code
(const bool at_obnd1 =
!m_geom_traits->is_closed_2_object()(cv, ARR_MIN_END));
CGAL_precondition_msg
((! at_obnd1 &&
m_geom_traits->equal_2_object()
(v->point(),
m_geom_traits->construct_min_vertex_2_object()(cv))) ||
(at_obnd1 && v->is_at_open_boundary()),
"The input vertex should be the left curve end.");
// Check if cv's right end has boundary conditions. If not, create a vertex
// that corresponds to the right endpoint.
const Arr_parameter_space ps_x2 =
m_geom_traits->parameter_space_in_x_2_object()(cv, ARR_MAX_END);
const Arr_parameter_space ps_y2 =
m_geom_traits->parameter_space_in_y_2_object()(cv, ARR_MAX_END);
DVertex* v2 = nullptr;
DHalfedge* fict_prev2 = nullptr;
if ((ps_x2 == ARR_INTERIOR) && (ps_y2 == ARR_INTERIOR))
// The curve has a valid right endpoint: Create a new vertex associated
// with the curve's right endpoint.
v2 = _create_vertex(m_geom_traits->construct_max_vertex_2_object()(cv));
// Check if the given vertex, corresponding to the left curve end, has no
// incident edges.
if (v->degree() == 0) {
// The given vertex is an isolated one: We should in fact insert the curve
// in the interior of the face containing this vertex.
DVertex* v1 = _vertex(v);
DIso_vertex* iv = nullptr;
DFace* p_f = nullptr;
if (v->is_isolated()) {
// Obtain the face from the isolated vertex.
iv = v1->isolated_vertex();
p_f = iv->face();
}
else {
// In this case the face that contains v should be provided by the user.
CGAL_precondition(f != Face_handle());
p_f = _face(f);
}
// If the vertex that corresponds to cv's right end has boundary
// conditions, create it now.
if (v2 == nullptr)
// Locate the DCEL features that will be used for inserting the curve's
// right end.
v2 = _place_and_set_curve_end(p_f, cv, ARR_MAX_END, ps_x2, ps_y2,
&fict_prev2);
if (iv != nullptr) {
// Remove the isolated vertex v1, as it will not be isolated any more.
p_f->erase_isolated_vertex(iv);
_dcel().delete_isolated_vertex(iv);
}
// Create the edge connecting the two vertices (note that we know that
// v1 is smaller than v2).
DHalfedge* new_he;
if (fict_prev2 == nullptr)
new_he = _insert_in_face_interior(p_f, cv, ARR_LEFT_TO_RIGHT, v1, v2);
else {
new_he = _insert_from_vertex(fict_prev2, cv, ARR_RIGHT_TO_LEFT, v1);
new_he = new_he->opposite();
}
// Return a handle to the new halfedge directed from v1 to v2.
CGAL_postcondition(new_he->direction() == ARR_LEFT_TO_RIGHT);
return (Halfedge_handle(new_he));
}
// Go over the incident halfedges around v and find the halfedge after
// which the new curve should be inserted.
DHalfedge* prev1 = _locate_around_vertex(_vertex(v), cv, ARR_MIN_END);
CGAL_assertion_msg
(prev1 != nullptr,
"The inserted curve cannot be located in the arrangement.");
DFace* f1 = prev1->is_on_inner_ccb() ? prev1->inner_ccb()->face() :
prev1->outer_ccb()->face();
// If the vertex that corresponds to cv's right end has boundary conditions,
// create it now.
if (v2 == nullptr)
// Locate the DCEL features that will be used for inserting the curve's
// right end.
v2 =
_place_and_set_curve_end(f1, cv, ARR_MAX_END, ps_x2, ps_y2, &fict_prev2);
// Perform the insertion (note that we know that prev1->vertex is smaller
// than v2).
DHalfedge* new_he;
if (fict_prev2 == nullptr)
// Insert the halfedge given the predecessor halfedge of v1.
new_he = _insert_from_vertex(prev1, cv, ARR_LEFT_TO_RIGHT, v2);
else {
// Insert the halfedge given the two predecessor halfedges.
// Note that in this case we may create a new face.
bool new_face_created = false;
bool check_swapped_predecessors = false;
new_he = _insert_at_vertices(prev1, cv, ARR_LEFT_TO_RIGHT,
fict_prev2->next(),
new_face_created, check_swapped_predecessors);
// Comment EBEB 2012-10-21: Swapping does not take place as the insertion
// merges the CCB as an "interior" extension into an outer CCB of a face
// incident the parameter space's boundary.
CGAL_assertion(!check_swapped_predecessors);
if (new_face_created) {
CGAL_assertion(new_he->is_on_outer_ccb());
// Note! new_he is not needed to define the new outer CCB of the new face
// Here, it can be the outer ccb of the old face, as there is also not
// swapping taking place!
// In case a new face has been created (pointed by the new halfedge we
// obtained), we have to examine the holes and isolated vertices in the
// existing face (pointed by the twin halfedge) and move the relevant
// holes and isolated vertices into the new face.
_relocate_in_new_face(new_he);
}
}
// Return a handle to the halfedge directed toward the new vertex v2.
CGAL_postcondition(new_he->direction() == ARR_LEFT_TO_RIGHT);
return (Halfedge_handle(new_he));
}
//-----------------------------------------------------------------------------
// Insert an x-monotone curve into the arrangement, such that one its left
// endpoint corresponds to a given arrangement vertex, given the exact place
// for the curve in the circular list around this vertex.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::Halfedge_handle
Arrangement_on_surface_2<GeomTraits, TopTraits>::
insert_from_left_vertex(const X_monotone_curve_2& cv, Halfedge_handle prev)
{
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "Aos_2: insert_from_left_vertex (interface)" << std::endl;
std::cout << "cv : " << cv << std::endl;
if (!prev->is_fictitious()) {
std::cout << "prev : " << prev ->curve() << std::endl;
} else {
std::cout << "prev : fictitious" << std::endl;
}
std::cout << "dir : " << prev->direction() << std::endl;
#endif
CGAL_precondition_code
(const bool at_obnd1 =
!m_geom_traits->is_closed_2_object()(cv, ARR_MIN_END));
CGAL_precondition_msg
((! at_obnd1 &&
m_geom_traits->equal_2_object()
(prev->target()->point(),
m_geom_traits->construct_min_vertex_2_object()(cv))) ||
(at_obnd1 && prev->target()->is_at_open_boundary()),
"The target of the input halfedge should be the left curve end.");
CGAL_precondition_msg
(at_obnd1 || _locate_around_vertex(_vertex(prev->target()),
cv, ARR_MIN_END) == _halfedge(prev),
"In the clockwise order of curves around the vertex, "
" cv must succeed the curve of prev.");
// Get the predecessor halfedge for the insertion of the left curve end.
DHalfedge* prev1 = _halfedge(prev);
DFace* f1 = _face(prev->face());
// Check if cv's right end has boundary conditions, and obtain a vertex
// that corresponds to this end.
const Arr_parameter_space ps_x2 =
m_geom_traits->parameter_space_in_x_2_object()(cv, ARR_MAX_END);
const Arr_parameter_space ps_y2 =
m_geom_traits->parameter_space_in_y_2_object()(cv, ARR_MAX_END);
DHalfedge* fict_prev2 = nullptr;
DVertex* v2 = ((ps_x2 == ARR_INTERIOR) && (ps_y2 == ARR_INTERIOR)) ?
// The curve has a valid right endpoint: Create a new vertex associated
// with the curve's right endpoint.
_create_vertex(m_geom_traits->construct_max_vertex_2_object()(cv)) :
// Locate the DCEL features that will be used for inserting the curve's
// right end.
_place_and_set_curve_end(f1, cv, ARR_MAX_END, ps_x2, ps_y2, &fict_prev2);
// Perform the insertion (note that we know that prev1->vertex is smaller
// than v2).
DHalfedge* new_he;
if (fict_prev2 == nullptr)
// Insert the halfedge given the predecessor halfedge of the left vertex.
new_he = _insert_from_vertex(prev1, cv, ARR_LEFT_TO_RIGHT, v2);
else {
// Insert the halfedge given the two predecessor halfedges.
// Note that in this case we may create a new face.
bool new_face_created = false;
bool check_swapped_predecessors = false;
new_he = _insert_at_vertices(prev1, cv, ARR_LEFT_TO_RIGHT,
fict_prev2->next(), new_face_created,
check_swapped_predecessors);
// Comment EBEB 2012-10-21: Swapping does not take place as the insertion
// merges the CCB as an "interior" extension into an outer CCB of a face
// incident the parameter space's boundary.
CGAL_assertion(!check_swapped_predecessors);
if (new_face_created) {
CGAL_assertion(new_he->is_on_outer_ccb());
// Note! new_he is not needed to define the new outer CCB of the new face
// Here, it can be the outer ccb of the old face, as there is also not
// swapping taking place!
// In case a new face has been created (pointed by the new halfedge we
// obtained), we have to examine the holes and isolated vertices in the
// existing face (pointed by the twin halfedge) and move the relevant
// holes and isolated vertices into the new face.
_relocate_in_new_face(new_he);
}
}
// Return a handle to the halfedge directed toward the new vertex v2.
CGAL_postcondition(new_he->direction() == ARR_LEFT_TO_RIGHT);
return (Halfedge_handle(new_he));
}
//-----------------------------------------------------------------------------
// Insert an x-monotone curve into the arrangement, such that its right
// endpoint corresponds to a given arrangement vertex.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::Halfedge_handle
Arrangement_on_surface_2<GeomTraits, TopTraits>::
insert_from_right_vertex(const X_monotone_curve_2& cv,
Vertex_handle v, Face_handle f)
{
CGAL_precondition_code
(const bool at_obnd2 =
!m_geom_traits->is_closed_2_object()(cv, ARR_MAX_END));
CGAL_precondition_msg
((! at_obnd2 &&
m_geom_traits->equal_2_object()
(v->point(),
m_geom_traits->construct_max_vertex_2_object()(cv))) ||
(at_obnd2 && v->is_at_open_boundary()),
"The input vertex should be the right curve end.");
// Check if cv's left end has boundary conditions. If not, create a vertex
// that corresponds to the left endpoint.
const Arr_parameter_space ps_x1 =
m_geom_traits->parameter_space_in_x_2_object()(cv, ARR_MIN_END);
const Arr_parameter_space ps_y1 =
m_geom_traits->parameter_space_in_y_2_object()(cv, ARR_MIN_END);
DVertex* v1 = nullptr;
DHalfedge* fict_prev1 = nullptr;
if ((ps_x1 == ARR_INTERIOR) && (ps_y1 == ARR_INTERIOR))
// The curve has a valid left endpoint: Create a new vertex associated
// with the curve's left endpoint.
v1 = _create_vertex(m_geom_traits->construct_min_vertex_2_object()(cv));
// Check if the given vertex, corresponding to the right curve end, has no
// incident edges.
if (v->degree() == 0) {
// The given vertex is an isolated one: We should in fact insert the curve
// in the interior of the face containing this vertex.
DVertex* v2 = _vertex(v);
DIso_vertex* iv = nullptr;
DFace* p_f = nullptr;
if (v->is_isolated()) {
// Obtain the face from the isolated vertex.
iv = v2->isolated_vertex();
p_f = iv->face();
}
else {
// In this case the face that contains v should be provided by the user.
CGAL_precondition(f != Face_handle());
p_f = _face(f);
}
// If the vertex that corresponds to cv's left end has boundary
// conditions, create it now.
if (v1 == nullptr)
// Locate the DCEL features that will be used for inserting the curve's
// left end.
v1 = _place_and_set_curve_end(p_f, cv, ARR_MIN_END, ps_x1, ps_y1,
&fict_prev1);
if (iv != nullptr) {
// Remove the isolated vertex v2, as it will not be isolated any more.
p_f->erase_isolated_vertex(iv);
_dcel().delete_isolated_vertex(iv);
}
// Create the edge connecting the two vertices (note that we know that
// v1 is smaller than v2).
DHalfedge* new_he = (fict_prev1 == nullptr) ?
_insert_in_face_interior(p_f, cv, ARR_LEFT_TO_RIGHT, v1, v2) :
_insert_from_vertex(fict_prev1, cv, ARR_LEFT_TO_RIGHT, v2);
// Return a handle to the new halfedge whose target is the new vertex v1.
CGAL_postcondition(new_he->opposite()->direction() == ARR_RIGHT_TO_LEFT);
return (Halfedge_handle(new_he->opposite()));
}
// Go over the incident halfedges around v and find the halfedge after
// which the new curve should be inserted.
DHalfedge* prev2 = _locate_around_vertex(_vertex(v), cv, ARR_MAX_END);
CGAL_assertion_msg
(prev2 != nullptr, "The inserted curve cannot be located in the arrangement.");
DFace* f2 = prev2->is_on_inner_ccb() ? prev2->inner_ccb()->face() :
prev2->outer_ccb()->face();
// If the vertex that corresponds to cv's left end has boundary conditions,
// create it now.
if (v1 == nullptr)
// Locate the DCEL features that will be used for inserting the curve's
// left end.
v1 =
_place_and_set_curve_end(f2, cv, ARR_MIN_END, ps_x1, ps_y1, &fict_prev1);
// Perform the insertion (note that we know that prev2->vertex is larger
// than v1).
DHalfedge* new_he;
if (fict_prev1 == nullptr)
// Insert the halfedge given the predecessor halfedge of v2.
new_he = _insert_from_vertex(prev2, cv, ARR_RIGHT_TO_LEFT, v1);
else {
// Insert the halfedge given the two predecessor halfedges.
// Note that in this case we may create a new face.
bool new_face_created = false;
bool check_swapped_predecessors = false;
new_he = _insert_at_vertices(prev2, cv, ARR_RIGHT_TO_LEFT,
fict_prev1->next(), new_face_created,
check_swapped_predecessors);
// Comment EBEB 2012-10-21: Swapping does not take place as the insertion
// merges the CCB as an "interior" extension into an outer CCB of a face
// incident the parameter space's boundary.
CGAL_assertion(!check_swapped_predecessors);
if (new_face_created) {
CGAL_assertion(new_he->is_on_outer_ccb());
// Note! new_he is not needed to define the new outer CCB of the new face
// Here, it can be the outer ccb of the old face, as there is also not
// swapping taking place!
// In case a new face has been created (pointed by the new halfedge we
// obtained), we have to examine the holes and isolated vertices in the
// existing face (pointed by the twin halfedge) and move the relevant
// holes and isolated vertices into the new face.
_relocate_in_new_face(new_he);
}
}
// Return a handle to the halfedge directed toward the new vertex v1.
CGAL_postcondition(new_he->direction() == ARR_RIGHT_TO_LEFT);
return (Halfedge_handle(new_he));
}
//-----------------------------------------------------------------------------
// Insert an x-monotone curve into the arrangement, such that its right
// endpoint corresponds to a given arrangement vertex, given the exact place
// for the curve in the circular list around this vertex.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::Halfedge_handle
Arrangement_on_surface_2<GeomTraits, TopTraits>::
insert_from_right_vertex(const X_monotone_curve_2& cv,
Halfedge_handle prev)
{
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "Aos_2: insert_from_right_vertex (interface)" << std::endl;
std::cout << "cv : " << cv << std::endl;
if (!prev->is_fictitious())
std::cout << "prev : " << prev ->curve() << std::endl;
else
std::cout << "prev : fictitious" << std::endl;
std::cout << "dir : " << prev->direction() << std::endl;
#endif
CGAL_precondition_code
(const bool at_obnd2 =
!m_geom_traits->is_closed_2_object()(cv, ARR_MAX_END));
CGAL_precondition_msg
((! at_obnd2 &&
m_geom_traits->equal_2_object()
(prev->target()->point(),
m_geom_traits->construct_max_vertex_2_object()(cv))) ||
(at_obnd2 && prev->target()->is_at_open_boundary()),
"The input vertex should be the right curve end.");
CGAL_precondition_msg
(at_obnd2 ||
(_locate_around_vertex(_vertex(prev->target()), cv, ARR_MAX_END) ==
_halfedge(prev)),
"In the clockwise order of curves around the vertex, "
" cv must succeed the curve of prev.");
// Get the predecessor halfedge for the insertion of the right curve end.
DHalfedge* prev2 = _halfedge(prev);
DFace* f2 = _face(prev->face());
// Check if cv's left end has boundary conditions, and obtain a vertex v1
// that corresponds to this end.
const Arr_parameter_space ps_x1 =
m_geom_traits->parameter_space_in_x_2_object()(cv, ARR_MIN_END);
const Arr_parameter_space ps_y1 =
m_geom_traits->parameter_space_in_y_2_object()(cv, ARR_MIN_END);
DHalfedge* fict_prev1 = nullptr;
DVertex* v1 = ((ps_x1 == ARR_INTERIOR) && (ps_y1 == ARR_INTERIOR)) ?
// The curve has a valid left endpoint: Create a new vertex associated
// with the curve's left endpoint.
_create_vertex(m_geom_traits->construct_min_vertex_2_object()(cv)) :
// Locate the DCEL features that will be used for inserting the curve's
// left end.
_place_and_set_curve_end(f2, cv, ARR_MIN_END, ps_x1, ps_y1, &fict_prev1);
// Perform the insertion (note that we know that prev2->vertex is larger
// than v1).
DHalfedge* new_he;
if (fict_prev1 == nullptr)
// Insert the halfedge given the predecessor halfedge of the right vertex.
new_he = _insert_from_vertex(prev2, cv, ARR_RIGHT_TO_LEFT, v1);
else {
// Insert the halfedge given the two predecessor halfedges.
// Note that in this case we may create a new face.
bool new_face_created = false;
bool check_swapped_predecessors = false;
new_he = _insert_at_vertices(prev2, cv, ARR_RIGHT_TO_LEFT,
fict_prev1->next(), new_face_created,
check_swapped_predecessors);
// Comment EBEB 2012-10-21: Swapping does not take place as the insertion
// merges the CCB as an "interior" extension into an outer CCB of a face
// incident the parameter space's boundary.
CGAL_assertion(!check_swapped_predecessors);
if (new_face_created) {
CGAL_assertion(new_he->is_on_outer_ccb());
// Note! new_he is not needed to define the new outer CCB of the new face
// Here, it can be the outer ccb of the old face, as there is also not
// swapping taking place!
// In case a new face has been created (pointed by the new halfedge we
// obtained), we have to examine the holes and isolated vertices in the
// existing face (pointed by the twin halfedge) and move the relevant
// holes and isolated vertices into the new face.
_relocate_in_new_face(new_he);
}
}
// Return a handle to the halfedge directed toward the new vertex v1.
CGAL_postcondition(new_he->direction() == ARR_RIGHT_TO_LEFT);
return (Halfedge_handle(new_he));
}
//-----------------------------------------------------------------------------
// Insert an x-monotone curve into the arrangement, such that both its
// endpoints corresponds to a given arrangement vertex.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::Halfedge_handle
Arrangement_on_surface_2<GeomTraits, TopTraits>::
insert_at_vertices(const X_monotone_curve_2& cv,
Vertex_handle v1, Vertex_handle v2,
Face_handle f)
{
CGAL_USE(f);
// Determine which one of the given vertices matches the left end of the
// given curve.
const bool at_obnd1 = !m_geom_traits->is_closed_2_object()(cv, ARR_MIN_END);
const bool at_obnd2 = !m_geom_traits->is_closed_2_object()(cv, ARR_MAX_END);
Arr_curve_end ind1;
Arr_curve_end ind2;
if (! at_obnd1) {
CGAL_precondition_code(Vertex_handle v_right);
if (! v1->is_at_open_boundary() &&
m_geom_traits->equal_2_object()
(v1->point(),
m_geom_traits->construct_min_vertex_2_object()(cv)))
{
ind1 = ARR_MIN_END;
ind2 = ARR_MAX_END;
CGAL_precondition_code(v_right = v2);
}
else {
CGAL_precondition_msg
(! v2->is_at_open_boundary() &&
m_geom_traits->equal_2_object()
(v2->point(),
m_geom_traits->construct_min_vertex_2_object()(cv)),
"One of the input vertices should be the left curve end.");
ind1 = ARR_MAX_END;
ind2 = ARR_MIN_END;
CGAL_precondition_code(v_right = v1);
}
CGAL_precondition_msg
((! at_obnd2 &&
m_geom_traits->equal_2_object()
(v_right->point(),
m_geom_traits->construct_max_vertex_2_object()(cv))) ||
(at_obnd2 && v_right->is_at_open_boundary()),
"One of the input vertices should be the right curve end.");
}
else {
if (! at_obnd2) {
CGAL_precondition_code(Vertex_handle v_left);
if (! v1->is_at_open_boundary() &&
m_geom_traits->equal_2_object()
(v1->point(),
m_geom_traits->construct_max_vertex_2_object()(cv)))
{
ind1 = ARR_MAX_END;
ind2 = ARR_MIN_END;
CGAL_precondition_code(v_left = v2);
}
else {
CGAL_precondition_msg
(! v2->is_at_open_boundary() &&
m_geom_traits->equal_2_object()
(v2->point(),
m_geom_traits->construct_max_vertex_2_object()(cv)),
"One of the input vertices should be the right curve end.");
ind1 = ARR_MIN_END;
ind2 = ARR_MAX_END;
CGAL_precondition_code(v_left = v1);
}
CGAL_precondition_msg
(at_obnd1 && v_left->is_at_open_boundary(),
"One of the input vertices should be the left curve end.");
}
else {
Arr_parameter_space ps_x1 =
m_geom_traits->parameter_space_in_x_2_object()(cv, ARR_MIN_END);
Arr_parameter_space ps_y1 =
m_geom_traits->parameter_space_in_y_2_object()(cv, ARR_MIN_END);
// Check which vertex should be associated with the minimal curve-end
// (so the other is associated with the maximal curve-end).
if (m_topol_traits.are_equal(_vertex(v1), cv, ARR_MIN_END, ps_x1, ps_y1))
{
CGAL_assertion
(m_topol_traits.are_equal
(_vertex(v2), cv, ARR_MAX_END,
m_geom_traits->parameter_space_in_x_2_object()(cv, ARR_MAX_END),
m_geom_traits->parameter_space_in_y_2_object()(cv, ARR_MAX_END)));
ind1 = ARR_MIN_END;
ind2 = ARR_MAX_END;
}
else {
CGAL_assertion(m_topol_traits.are_equal
(_vertex(v2), cv, ARR_MIN_END, ps_x1, ps_y1));
CGAL_assertion
(m_topol_traits.are_equal
(_vertex(v1), cv, ARR_MAX_END,
m_geom_traits->parameter_space_in_x_2_object()(cv, ARR_MAX_END),
m_geom_traits->parameter_space_in_y_2_object()(cv, ARR_MAX_END)));
ind1 = ARR_MAX_END;
ind2 = ARR_MIN_END;
}
}
}
// Check whether one of the vertices has no incident halfedges.
if (v1->degree() == 0) {
// Get the face containing the isolated vertex v1.
DVertex* p_v1 = _vertex(v1);
DIso_vertex* iv1 = nullptr;
DFace* f1 = nullptr;
if (p_v1->is_isolated()) {
// Obtain the containing face from the isolated vertex record.
iv1 = p_v1->isolated_vertex();
f1 = iv1->face();
// Remove the isolated vertex v1, as it will not be isolated any more.
f1->erase_isolated_vertex(iv1);
_dcel().delete_isolated_vertex(iv1);
}
// Check whether the other vertex also has no incident halfedges.
if (v2->degree() == 0) {
// Both end-vertices are isolated. Make sure they are contained inside
// the same face.
DVertex* p_v2 = _vertex(v2);
DIso_vertex* iv2 = nullptr;
DFace* f2 = nullptr;
if (p_v2->is_isolated()) {
// Obtain the containing face from the isolated vertex record.
iv2 = p_v2->isolated_vertex();
f2 = iv2->face();
CGAL_assertion_msg
((f1 == nullptr) || (f1 == f2),
"The two isolated vertices must be located inside the same face.");
// Remove the isolated vertex v2, as it will not be isolated any more.
f2->erase_isolated_vertex(iv2);
_dcel().delete_isolated_vertex(iv2);
}
else if (f1 == nullptr)
// In this case the containing face must be given by the user.
CGAL_precondition(f != Face_handle());
// Perform the insertion.
Arr_halfedge_direction cv_dir =
(ind1 == ARR_MIN_END) ? ARR_LEFT_TO_RIGHT : ARR_RIGHT_TO_LEFT;
DHalfedge* new_he = _insert_in_face_interior(f1, cv, cv_dir, p_v1, p_v2);
return (Halfedge_handle(new_he));
}
// Go over the incident halfedges around v2 and find the halfedge after
// which the new curve should be inserted.
DHalfedge* prev2 = _locate_around_vertex(_vertex(v2), cv, ind2);
CGAL_assertion_msg
(prev2 != nullptr,
"The inserted curve cannot be located in the arrangement.");
CGAL_assertion_code
(DFace* f2 = prev2->is_on_inner_ccb() ? prev2->inner_ccb()->face() :
prev2->outer_ccb()->face());
CGAL_assertion_msg
((f1 == nullptr) || (f1 == f2),
"The inserted curve should not intersect the existing arrangement.");
// Perform the insertion. Note that the returned halfedge is directed
// toward v1 (and not toward v2), so we return its twin.
Arr_halfedge_direction cv_dir =
(ind2 == ARR_MIN_END) ? ARR_LEFT_TO_RIGHT : ARR_RIGHT_TO_LEFT;
DHalfedge* new_he = _insert_from_vertex(prev2, cv, cv_dir, p_v1);
return (Halfedge_handle(new_he->opposite()));
}
else if (v2->degree() == 0) {
// Get the face containing the isolated vertex v2.
DVertex* p_v2 = _vertex(v2);
DIso_vertex* iv2 = nullptr;
DFace* f2 = nullptr;
if (v2->is_isolated()) {
// Obtain the containing face from the isolated vertex record.
iv2 = p_v2->isolated_vertex();
f2 = iv2->face();
// Remove the isolated vertex v2, as it will not be isolated any more.
f2->erase_isolated_vertex(iv2);
_dcel().delete_isolated_vertex(iv2);
}
// Go over the incident halfedges around v1 and find the halfedge after
// which the new curve should be inserted.
DHalfedge* prev1 = _locate_around_vertex(_vertex(v1), cv, ind1);
CGAL_assertion_msg
(prev1 != nullptr,
"The inserted curve cannot be located in the arrangement.");
CGAL_assertion_code
(DFace* f1 = prev1->is_on_inner_ccb() ? prev1->inner_ccb()->face() :
prev1->outer_ccb()->face());
CGAL_assertion_msg
((f2 == nullptr) || (f2 == f1),
"The inserted curve should not intersect the existing arrangement.");
// Perform the insertion.
Arr_halfedge_direction cv_dir =
(ind1 == ARR_MIN_END) ? ARR_LEFT_TO_RIGHT : ARR_RIGHT_TO_LEFT;
DHalfedge* new_he = _insert_from_vertex(prev1, cv, cv_dir, p_v2);
return (Halfedge_handle(new_he));
}
// Go over the incident halfedges around v1 and v2 and find the two
// halfedges after which the new curve should be inserted, respectively.
DHalfedge* prev1 = _locate_around_vertex(_vertex(v1), cv, ind1);
DHalfedge* prev2 = _locate_around_vertex(_vertex(v2), cv, ind2);
CGAL_assertion_msg
(((prev1 != nullptr) && (prev2 != nullptr)),
"The inserted curve cannot be located in the arrangement.");
// Perform the insertion.
return insert_at_vertices(cv, Halfedge_handle(prev1), Halfedge_handle(prev2));
}
//-----------------------------------------------------------------------------
// Insert an x-monotone curve into the arrangement, such that both its
// endpoints correspond to given arrangement vertices, given the exact
// place for the curve in one of the circular lists around a vertex.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::Halfedge_handle
Arrangement_on_surface_2<GeomTraits, TopTraits>::
insert_at_vertices(const X_monotone_curve_2& cv,
Halfedge_handle prev1,
Vertex_handle v2)
{
// Determine which one of the given vertices matches the left end of the
// given curve.
const bool at_obnd1 = !m_geom_traits->is_closed_2_object()(cv, ARR_MIN_END);
const bool at_obnd2 = !m_geom_traits->is_closed_2_object()(cv, ARR_MAX_END);
Arr_curve_end ind2;
if (! at_obnd1) {
CGAL_precondition_code(Vertex_handle v_right);
if (! prev1->target()->is_at_open_boundary() &&
m_geom_traits->equal_2_object()
(prev1->target()->point(),
m_geom_traits->construct_min_vertex_2_object()(cv)))
{
ind2 = ARR_MAX_END;
CGAL_precondition_code(v_right = v2);
}
else {
CGAL_precondition_msg
(! v2->is_at_open_boundary() &&
m_geom_traits->equal_2_object()
(v2->point(),
m_geom_traits->construct_min_vertex_2_object()(cv)),
"One of the input vertices should be the left curve end.");
ind2 = ARR_MIN_END;
CGAL_precondition_code(v_right = prev1->target());
}
CGAL_precondition_msg
((! at_obnd2 &&
m_geom_traits->equal_2_object()
(v_right->point(),
m_geom_traits->construct_max_vertex_2_object()(cv))) ||
(at_obnd2 && v_right->is_at_open_boundary()),
"One of the input vertices should be the right curve end.");
}
else {
if (! at_obnd2) {
CGAL_precondition_code(Vertex_handle v_left);
if (! prev1->target()->is_at_open_boundary() &&
m_geom_traits->equal_2_object()
(prev1->target()->point(),
m_geom_traits->construct_max_vertex_2_object()(cv)))
{
ind2 = ARR_MIN_END;
CGAL_precondition_code(v_left = v2);
}
else {
CGAL_precondition_msg
(! v2->is_at_open_boundary() &&
m_geom_traits->equal_2_object()
(v2->point(),
m_geom_traits->construct_max_vertex_2_object()(cv)),
"One of the input vertices should be the right curve end.");
ind2 = ARR_MAX_END;
CGAL_precondition_code(v_left = prev1->target());
}
CGAL_precondition_msg
(at_obnd1 && v_left->is_at_open_boundary(),
"One of the input vertices should be the left curve end.");
}
else {
Arr_parameter_space ps_x1 =
m_geom_traits->parameter_space_in_x_2_object()(cv, ARR_MIN_END);
Arr_parameter_space ps_y1 =
m_geom_traits->parameter_space_in_y_2_object()(cv, ARR_MIN_END);
// Check which vertex should be associated with the minimal curve-end
// (so the other is associated with the maximal curve-end).
if (m_topol_traits.are_equal(_vertex(prev1->target()),
cv, ARR_MIN_END, ps_x1, ps_y1))
{
CGAL_assertion
(m_topol_traits.are_equal
(_vertex(v2), cv, ARR_MAX_END,
m_geom_traits->parameter_space_in_x_2_object()(cv, ARR_MAX_END),
m_geom_traits->parameter_space_in_y_2_object()(cv, ARR_MAX_END)));
ind2 = ARR_MAX_END;
}
else {
CGAL_assertion(m_topol_traits.are_equal
(_vertex(v2), cv, ARR_MIN_END, ps_x1, ps_y1));
CGAL_assertion
(m_topol_traits.are_equal
(_vertex(prev1->target()), cv, ARR_MAX_END,
m_geom_traits->parameter_space_in_x_2_object()(cv, ARR_MAX_END),
m_geom_traits->parameter_space_in_y_2_object()(cv, ARR_MAX_END)));
ind2 = ARR_MIN_END;
}
}
}
// Check whether v2 is has no incident edges.
if (v2->degree() == 0) {
// Get the face containing the isolated vertex v2.
DVertex* p_v2 = _vertex(v2);
DIso_vertex* iv2 = nullptr;
DFace* f2 = nullptr;
if (v2->is_isolated()) {
iv2 = p_v2->isolated_vertex();
f2 = iv2->face();
CGAL_assertion_msg
(f2 == _face(prev1->face()),
"The inserted curve should not intersect the existing arrangement.");
// Remove the isolated vertex v2, as it will not be isolated any more.
f2->erase_isolated_vertex(iv2);
_dcel().delete_isolated_vertex(iv2);
}
// Perform the insertion.
Arr_halfedge_direction cv_dir =
(ind2 == ARR_MAX_END) ? ARR_LEFT_TO_RIGHT : ARR_RIGHT_TO_LEFT;
DHalfedge* new_he = _insert_from_vertex(_halfedge(prev1), cv, cv_dir, p_v2);
return (Halfedge_handle(new_he));
}
// Go over the incident halfedges around v2 and find the halfedge after
// which the new curve should be inserted.
DHalfedge* prev2 = _locate_around_vertex(_vertex(v2), cv, ind2);
CGAL_assertion_msg
(prev2 != nullptr, "The inserted curve cannot be located in the arrangement.");
// Perform the insertion.
return (insert_at_vertices(cv, prev1, Halfedge_handle(prev2)));
}
//-----------------------------------------------------------------------------
// Insert an x-monotone curve into the arrangement, such that both its
// endpoints correspond to given arrangement vertices, given the exact
// place for the curve in both circular lists around these two vertices.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::Halfedge_handle
Arrangement_on_surface_2<GeomTraits, TopTraits>::
insert_at_vertices(const X_monotone_curve_2& cv,
Halfedge_handle prev1,
Halfedge_handle prev2)
{
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "Aos_2: insert_at_vertices (interface)" << std::endl;
std::cout << "cv : " << cv << std::endl;
if (!prev1->is_fictitious())
std::cout << "prev1: " << prev1->curve() << std::endl;
else
std::cout << "prev1: fictitious" << std::endl;
std::cout << "dir1 : " << prev1->direction() << std::endl;
if (!prev2->is_fictitious())
std::cout << "prev2: " << prev2->curve() << std::endl;
else
std::cout << "prev2: fictitious" << std::endl;
std::cout << "dir2 : " << prev2->direction() << std::endl;
#endif
// Determine which one of the given vertices (the target vertices of the
// given halfedges) matches the left end of the given curve.
// Thus, we can determine the comparison result between prev1->target()
// and prev2->target().
const bool at_obnd1 = !m_geom_traits->is_closed_2_object()(cv, ARR_MIN_END);
const bool at_obnd2 = !m_geom_traits->is_closed_2_object()(cv, ARR_MAX_END);
Comparison_result res;
if (! at_obnd1) {
CGAL_precondition_code(Vertex_handle v_right);
if (! prev1->target()->is_at_open_boundary() &&
m_geom_traits->equal_2_object()
(prev1->target()->point(),
m_geom_traits->construct_min_vertex_2_object()(cv)))
{
res = SMALLER;
CGAL_precondition_code(v_right = prev2->target());
}
else {
CGAL_precondition_msg
(! prev2->target()->is_at_open_boundary() &&
m_geom_traits->equal_2_object()
(prev2->target()->point(),
m_geom_traits->construct_min_vertex_2_object()(cv)),
"One of the input vertices should be the left curve end.");
res = LARGER;
CGAL_precondition_code(v_right = prev1->target());
}
CGAL_precondition_msg
((! at_obnd2 &&
m_geom_traits->equal_2_object()
(v_right->point(),
m_geom_traits->construct_max_vertex_2_object()(cv))) ||
(at_obnd2 && v_right->is_at_open_boundary()),
"One of the input vertices should be the right curve end.");
}
else {
if (! at_obnd2) {
CGAL_precondition_code(Vertex_handle v_left);
if (! prev1->target()->is_at_open_boundary() &&
m_geom_traits->equal_2_object()
(prev1->target()->point(),
m_geom_traits->construct_max_vertex_2_object()(cv)))
{
res = LARGER;
CGAL_precondition_code(v_left = prev2->target());
}
else {
CGAL_precondition_msg
(! prev2->target()->is_at_open_boundary() &&
m_geom_traits->equal_2_object()
(prev2->target()->point(),
m_geom_traits->construct_max_vertex_2_object()(cv)),
"One of the input vertices should be the right curve end.");
res = SMALLER;
CGAL_precondition_code(v_left = prev1->target());
}
CGAL_precondition_msg
(at_obnd1 && v_left->is_at_open_boundary(),
"One of the input vertices should be the left curve end.");
}
else {
Arr_parameter_space ps_x1 =
m_geom_traits->parameter_space_in_x_2_object()(cv, ARR_MIN_END);
Arr_parameter_space ps_y1 =
m_geom_traits->parameter_space_in_y_2_object()(cv, ARR_MIN_END);
// Check which vertex should be associated with the minimal curve-end
// (so the other is associated with the maximal curve-end), and
// determine the comparison result of the two vertices accordingly.
if (m_topol_traits.are_equal(_vertex(prev1->target()),
cv, ARR_MIN_END, ps_x1, ps_y1))
{
CGAL_assertion
(m_topol_traits.are_equal
(_vertex(prev2->target()), cv, ARR_MAX_END,
m_geom_traits->parameter_space_in_x_2_object()(cv, ARR_MAX_END),
m_geom_traits->parameter_space_in_y_2_object()(cv, ARR_MAX_END)));
res = SMALLER;
}
else {
CGAL_assertion
(m_topol_traits.are_equal
(_vertex(prev2->target()), cv, ARR_MIN_END,
m_geom_traits->parameter_space_in_x_2_object()(cv, ARR_MIN_END),
m_geom_traits->parameter_space_in_y_2_object()(cv, ARR_MIN_END)));
CGAL_assertion
(m_topol_traits.are_equal
(_vertex(prev1->target()), cv, ARR_MAX_END,
m_geom_traits->parameter_space_in_x_2_object()(cv, ARR_MAX_END),
m_geom_traits->parameter_space_in_y_2_object()(cv, ARR_MAX_END)));
res = LARGER;
}
}
}
// Check if e1 and e2 are on the same connected component.
DHalfedge* p_prev1 = _halfedge(prev1);
DHalfedge* p_prev2 = _halfedge(prev2);
// Note that in this case we may create a new face.
bool new_face_created = false;
bool swapped_predecessors = false;
DHalfedge* new_he =
_insert_at_vertices(p_prev1, cv,
(res == SMALLER ? ARR_LEFT_TO_RIGHT : ARR_RIGHT_TO_LEFT),
p_prev2->next(), new_face_created,
swapped_predecessors);
if (new_face_created)
// Comment EBEB 2012-10-21: Here we allow swapping, as there might be
// a local minima (or other needs), and thus new_he can lie on an inner CCB.
// In fact we cannot expect new_he to lie on an inner or on an outer CCB.
// In case a new face has been created (pointed by the new halfedge we
// obtained), we have to examine the holes and isolated vertices in the
// existing face (pointed by the twin halfedge) and move the relevant
// holes and isolated vertices into the new face.
_relocate_in_new_face(new_he);
// Return a handle to the new halfedge directed from prev1's target to
// prev2's target. Note that this may be the twin halfedge of the one
// returned by _insert_at_vertices();
if (swapped_predecessors) new_he = new_he->opposite();
return (Halfedge_handle(new_he));
}
//-----------------------------------------------------------------------------
// Replace the point associated with the given vertex.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::Vertex_handle
Arrangement_on_surface_2<GeomTraits, TopTraits>::
modify_vertex(Vertex_handle vh, const Point_2& p)
{
CGAL_precondition_msg
(! vh->is_at_open_boundary(),
"The modified vertex must not lie on open boundary.");
CGAL_precondition_msg(m_geom_traits->equal_2_object()(vh->point(), p),
"The new point is different from the current one.");
// Modify the vertex.
_modify_vertex(_vertex(vh), p);
// Return a handle to the modified vertex.
return vh;
}
//-----------------------------------------------------------------------------
// Remove an isolated vertex from the interior of a given face.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::Face_handle
Arrangement_on_surface_2<GeomTraits, TopTraits>::
remove_isolated_vertex(Vertex_handle v)
{
CGAL_precondition(v->is_isolated());
// Get the face containing v.
DVertex* p_v = _vertex(v);
DIso_vertex* iv = p_v->isolated_vertex();
DFace* p_f = iv->face();
Face_handle f = Face_handle(p_f);
// Notify the observers that we are abount to remove a vertex.
_notify_before_remove_vertex(v);
// Remove the isolated vertex from the face that contains it.
p_f->erase_isolated_vertex(iv);
_dcel().delete_isolated_vertex(iv);
// Delete the vertex.
_delete_point(p_v->point());
_dcel().delete_vertex(p_v);
// Notify the observers that the vertex has been removed.
_notify_after_remove_vertex();
// Return a handle for the face that used to contain the deleted vertex.
return f;
}
//-----------------------------------------------------------------------------
// Replace the x-monotone curve associated with the given edge.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::Halfedge_handle
Arrangement_on_surface_2<GeomTraits, TopTraits>::
modify_edge(Halfedge_handle e, const X_monotone_curve_2& cv)
{
CGAL_precondition_msg(! e->is_fictitious(),
"The edge must be a valid one.");
CGAL_precondition_msg(m_geom_traits->equal_2_object()(e->curve(), cv),
"The new curve is different from the current one.");
// Modify the edge.
_modify_edge(_halfedge(e), cv);
// Return a handle to the modified halfedge.
return e;
}
//-----------------------------------------------------------------------------
// Split a given edge into two, and associate the given x-monotone
// curves with the split edges.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::Halfedge_handle
Arrangement_on_surface_2<GeomTraits, TopTraits>::
split_edge(Halfedge_handle e,
const X_monotone_curve_2& cv1, const X_monotone_curve_2& cv2)
{
CGAL_precondition_msg(! e->is_fictitious(), "The edge must be a valid one.");
// Get the split halfedge and its twin, its source and target.
DHalfedge* he1 = _halfedge(e);
DHalfedge* he2 = he1->opposite();
DVertex* source = he2->vertex();
CGAL_precondition_code(DVertex* target = he1->vertex());
// Determine the point where we split the halfedge. We also determine which
// curve should be associated with he1 (and he2), which is the curve who
// has an endpoint that equals e's source, and which should be associated
// with the new pair of halfedges we are about to split (the one who has
// an endpoint which equals e's target).
if ((m_geom_traits->parameter_space_in_x_2_object()(cv1, ARR_MAX_END) ==
ARR_INTERIOR) &&
(m_geom_traits->parameter_space_in_y_2_object()(cv1, ARR_MAX_END) ==
ARR_INTERIOR))
{
const Point_2 & cv1_right =
m_geom_traits->construct_max_vertex_2_object()(cv1);
if ((m_geom_traits->parameter_space_in_x_2_object()(cv2, ARR_MIN_END) ==
ARR_INTERIOR) &&
(m_geom_traits->parameter_space_in_y_2_object()(cv2, ARR_MIN_END) ==
ARR_INTERIOR) &&
m_geom_traits->equal_2_object()(m_geom_traits->
construct_min_vertex_2_object()(cv2),
cv1_right))
{
// cv1's right endpoint and cv2's left endpoint are equal, so this should
// be the split point. Now we check whether cv1 is incident to e's source
// and cv2 to its target, or vice versa.
if (_are_equal(source, cv1, ARR_MIN_END)) {
CGAL_precondition_msg
(_are_equal(target, cv2, ARR_MAX_END),
"The subcurve endpoints must match e's end vertices.");
return (Halfedge_handle(_split_edge(he1, cv1_right, cv1, cv2)));
}
CGAL_precondition_msg
(_are_equal(source, cv2, ARR_MAX_END) &&
_are_equal(target, cv1, ARR_MIN_END),
"The subcurve endpoints must match e's end vertices.");
return (Halfedge_handle(_split_edge(he1, cv1_right, cv2, cv1)));
}
}
if ((m_geom_traits->parameter_space_in_x_2_object()(cv1, ARR_MIN_END) ==
ARR_INTERIOR) &&
(m_geom_traits->parameter_space_in_y_2_object()(cv1, ARR_MIN_END) ==
ARR_INTERIOR))
{
const Point_2 & cv1_left =
m_geom_traits->construct_min_vertex_2_object()(cv1);
if ((m_geom_traits->parameter_space_in_x_2_object()(cv2, ARR_MAX_END) ==
ARR_INTERIOR) &&
(m_geom_traits->parameter_space_in_y_2_object()(cv2, ARR_MAX_END) ==
ARR_INTERIOR) &&
m_geom_traits->equal_2_object()(m_geom_traits->
construct_max_vertex_2_object()(cv2),
cv1_left))
{
// cv1's left endpoint and cv2's right endpoint are equal, so this should
// be the split point. Now we check whether cv1 is incident to e's source
// and cv2 to its target, or vice versa.
if (_are_equal(source, cv2, ARR_MIN_END)) {
CGAL_precondition_msg
(_are_equal(target, cv1, ARR_MAX_END),
"The subcurve endpoints must match e's end vertices.");
return (Halfedge_handle(_split_edge(he1, cv1_left, cv2, cv1)));
}
CGAL_precondition_msg
(_are_equal(source, cv1, ARR_MAX_END) &&
_are_equal(target, cv2, ARR_MIN_END),
"The subcurve endpoints must match e's end vertices.");
return (Halfedge_handle(_split_edge(he1, cv1_left, cv1, cv2)));
}
}
CGAL_error_msg("The two subcurves must have a common endpoint.");
return Halfedge_handle();
}
//-----------------------------------------------------------------------------
// Merge two edges to form a single edge, and associate the given x-monotone
// curve with the merged edge.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::Halfedge_handle
Arrangement_on_surface_2<GeomTraits, TopTraits>::
merge_edge(Halfedge_handle e1, Halfedge_handle e2,
const X_monotone_curve_2& cv)
{
CGAL_precondition_msg(! e1->is_fictitious() && ! e2->is_fictitious(),
"The edges must be a valid.");
// Assign pointers to the existing halfedges, such that we have:
//
// he1 he3
// -------> ------->
// (.) (.)v (.)
// <------- <-------
// he2 he4
//
DHalfedge* _e1 = _halfedge(e1);
DHalfedge* _e2 = _halfedge(e2);
DHalfedge* he1 = nullptr;
DHalfedge* he2 = nullptr;
DHalfedge* he3 = nullptr;
DHalfedge* he4 = nullptr;
if (_e1->vertex() == _e2->opposite()->vertex()) {
he1 = _e1;
he2 = he1->opposite();
he3 = _e2;
he4 = he3->opposite();
}
else if (_e1->opposite()->vertex() == _e2->opposite()->vertex()) {
he2 = _e1;
he1 = he2->opposite();
he3 = _e2;
he4 = he3->opposite();
}
else if (_e1->vertex() == _e2->vertex()) {
he1 = _e1;
he2 = he1->opposite();
he4 = _e2;
he3 = he4->opposite();
}
else if (_e1->opposite()->vertex() == _e2->vertex()) {
he2 = _e1;
he1 = he2->opposite();
he4 = _e2;
he3 = he4->opposite();
}
else {
CGAL_precondition_msg(false,
"The input edges do not share a common vertex.");
return Halfedge_handle();
}
// The vertex we are about to delete is now he1's target vertex.
// Make sure that he1 and he4 are the only halfedges directed to v.
DVertex* v = he1->vertex();
CGAL_precondition_msg
(! v->has_null_point(),
"The vertex removed by the merge must not lie on open boundary.");
CGAL_precondition_msg
(he1->next()->opposite() == he4 &&
he4->next()->opposite() == he1,
"The degree of the deleted vertex is greater than 2.");
// Make sure the curve ends match the end vertices of the merged edge.
CGAL_precondition_msg
((_are_equal(he2->vertex(), cv, ARR_MIN_END) &&
_are_equal(he3->vertex(), cv, ARR_MAX_END)) ||
(_are_equal(he3->vertex(), cv, ARR_MIN_END) &&
_are_equal(he2->vertex(), cv, ARR_MAX_END)),
"The endpoints of the merged curve must match the end vertices.");
// Keep pointers to the components that contain two halfedges he3 and he2,
// pointing at the end vertices of the merged halfedge.
DInner_ccb* ic1 = (he3->is_on_inner_ccb()) ? he3->inner_ccb() : nullptr;
DOuter_ccb* oc1 = (ic1 == nullptr) ? he3->outer_ccb() : nullptr;
DInner_ccb* ic2 = (he4->is_on_inner_ccb()) ? he4->inner_ccb() : nullptr;
DOuter_ccb* oc2 = (ic2 == nullptr) ? he4->outer_ccb() : nullptr;
// Notify the observers that we are about to merge an edge.
_notify_before_merge_edge(e1, e2, cv);
// As he1 and he2 will evetually represent the merged edge, while he3 and he4
// will be deleted, check if the deleted halfedges are represantatives of a
// the CCBs they belong to. If so, replace he3 by he1 and he4 by he2. Note
// that as we just change the component representatives, we do not have to
// notify the observers on the change.
if (oc1 != nullptr && oc1->halfedge() == he3)
oc1->set_halfedge(he1);
else if (ic1 != nullptr && ic1->halfedge() == he3)
ic1->set_halfedge(he1);
if (oc2 != nullptr && oc2->halfedge() == he4)
oc2->set_halfedge(he2);
else if (ic2 != nullptr && ic2->halfedge() == he4)
ic2->set_halfedge(he2);
// If he3 is the incident halfedge to its target, replace it by he1.
if (he3->vertex()->halfedge() == he3)
he3->vertex()->set_halfedge(he1);
// Disconnect he3 and he4 from the edge list.
if (he3->next() == he4) {
// he3 and he4 form an "antenna", so he1 and he2 must be connected
// together.
he1->set_next(he2);
}
else {
he1->set_next(he3->next());
he4->prev()->set_next(he2);
}
// Note that he1 (and its twin) is going to represent the merged edge while
// he3 (and its twin) is going to be removed. We therefore associate the
// merged curve with he1 and delete the curve associated with he3.
he1->curve() = cv;
_delete_curve(he3->curve());
// Set the properties of the merged edge.
he1->set_vertex(he3->vertex());
// Notify the observers that we are about to delete a vertex.
_notify_before_remove_vertex(Vertex_handle(v));
// Delete the point associated with the merged vertex.
_delete_point(v->point());
// Delete the merged vertex.
_dcel().delete_vertex(v);
// Notify the observers that the vertex has been deleted.
_notify_after_remove_vertex();
// Delete the redundant halfedge pair.
_dcel().delete_edge(he3);
// Create a handle for one of the merged halfedges.
Halfedge_handle hh(he1);
// Notify the observers that the edge has been merge.
_notify_after_merge_edge(hh);
// Return a handle for one of the merged halfedges.
return hh;
}
//-----------------------------------------------------------------------------
// Remove an edge from the arrangement.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::Face_handle
Arrangement_on_surface_2<GeomTraits, TopTraits>::
remove_edge(Halfedge_handle e, bool remove_source, bool remove_target)
{
// Comment EBEB 2012-08-06: this has become a simple forwarding function
// the intelligence of whether to swap he with he->opposite()
// has been moved to _remove_edge itself, as additional computed
// data is reused there
CGAL_precondition_msg(! e->is_fictitious(),
"The edge must be a valid one.");
DHalfedge* he1 = _halfedge(e);
DFace* f = _remove_edge(he1, remove_source, remove_target);
return Face_handle(f);
}
//-----------------------------------------------------------------------------
// Protected member functions (for internal use).
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Locate the place for the given curve around the given vertex.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::DHalfedge*
Arrangement_on_surface_2<GeomTraits, TopTraits>::
_locate_around_vertex(DVertex* v,
const X_monotone_curve_2& cv, Arr_curve_end ind) const
{
// Check if the given curve-end has boundary conditions.
const Arr_parameter_space ps_x =
m_geom_traits->parameter_space_in_x_2_object()(cv, ind);
const Arr_parameter_space ps_y =
m_geom_traits->parameter_space_in_y_2_object()(cv, ind);
if ((ps_x != ARR_INTERIOR) || (ps_y != ARR_INTERIOR))
// Use the topology-traits class to locate the predecessor halfedge for
// cv around the given vertex.
return m_topol_traits.locate_around_boundary_vertex(v, cv, ind, ps_x, ps_y);
// In case of a non-boundary vertex, we look for the predecessor around v.
// Get the first incident halfedge around v and the next halfedge.
DHalfedge* first = v->halfedge();
DHalfedge* curr = first;
if (curr == nullptr) return nullptr;
DHalfedge* next = curr->next()->opposite();
// In case there is only one halfedge incident to v, return this halfedge.
if (curr == next) return curr;
// Otherwise, we traverse the halfedges around v until we find the pair
// of adjacent halfedges between which we should insert cv.
typename Traits_adaptor_2::Is_between_cw_2 is_between_cw =
m_geom_traits->is_between_cw_2_object();
bool eq_curr, eq_next;
while (! is_between_cw(cv, (ind == ARR_MIN_END),
curr->curve(),
(curr->direction() == ARR_RIGHT_TO_LEFT),
next->curve(),
(next->direction() == ARR_RIGHT_TO_LEFT),
v->point(), eq_curr, eq_next))
{
// If cv equals one of the curves associated with the halfedges, it is
// an illegal input curve, as it already exists in the arrangement.
if (eq_curr || eq_next) return nullptr;
// Move to the next pair of incident halfedges.
curr = next;
next = curr->next()->opposite();
// If we completed a full traversal around v without locating the
// place for cv, it follows that cv overlaps and existing curve.
if (curr == first) return nullptr;
}
// Return the halfedge we have located.
return curr;
}
//-----------------------------------------------------------------------------
// Compute the distance (in halfedges) between two halfedges.
//
template <typename GeomTraits, typename TopTraits>
unsigned int
Arrangement_on_surface_2<GeomTraits, TopTraits>::
_halfedge_distance(const DHalfedge* e1, const DHalfedge* e2) const
{
CGAL_precondition(e1 != e2);
if (e1 == e2) return (0);
// Traverse the halfedge chain from e1 until reaching e2.
const DHalfedge* curr = e1->next();
unsigned int dist = 1;
while (curr != e2) {
// If we have returned to e1, e2 is not reachable from e1.
if (curr == e1) {
CGAL_error();
return (0);
}
curr = curr->next();
++dist;
}
// We have located e2 along the boundary of e1's component - return the
// distance (number of halfedges) between e1 and e2.
return (dist);
}
//-----------------------------------------------------------------------------
//Compare the length of the induced paths from e1 to e2 and from e2 to e1.
// return SMALLER if e1 to e2 is shorter, EQUAL if paths lengths are equal,
// o/w LARGER
//
template <typename GeomTraits, typename TopTraits>
Comparison_result
Arrangement_on_surface_2<GeomTraits, TopTraits>::
_compare_induced_path_length(const DHalfedge* e1, const DHalfedge* e2) const
{
CGAL_precondition(e1 != e2);
if (e1 == e2) return EQUAL;
// Traverse the halfedge chain from e1 until reaching e2.
const DHalfedge* curr1 = e1->next();
// Traverse the halfedge chain from e2 until reaching e1.
const DHalfedge* curr2 = e2->next();
while ((curr1 != e2) && (curr2 != e1)) {
// If we have returned to e1, e2 is not reachable from e1.
if (curr1 == e1) {
CGAL_error();
return EQUAL;
}
// If we have returned to e2, e1 is not reachable from e2.
if (curr2 == e2) {
CGAL_error();
return EQUAL;
}
curr1 = curr1->next();
curr2 = curr2->next();
}
// Return SMALLER if e1 to e2 is shorter than e2 to e1,
// EQUAL if their lengths are equal, or LARGER if e2 to e1 is longer.
Comparison_result res =
(curr1 == e2) ? ((curr2 != e1) ? SMALLER : EQUAL) : LARGER;
CGAL_postcondition_code(int dist1 = _halfedge_distance(e1,e2));
CGAL_postcondition_code(int dist2 = _halfedge_distance(e2,e1));
CGAL_postcondition(((dist1 < dist2) && (res == SMALLER)) ||
((dist1 == dist2) && (res == EQUAL)) ||
((dist1 > dist2) && (res == LARGER)));
return res;
}
//-----------------------------------------------------------------------------
// Move a given outer CCB from one face to another.
//
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::
_move_outer_ccb(DFace* from_face, DFace* to_face, DHalfedge* he)
{
// Get the DCEL record that represents the outer CCB.
DOuter_ccb* oc = he->outer_ccb();
CGAL_assertion(oc->face() == from_face);
// Notify the observers that we are about to move an outer CCB.
Ccb_halfedge_circulator circ = (Halfedge_handle(he))->ccb();
_notify_before_move_outer_ccb(Face_handle(from_face), Face_handle(to_face),
circ);
// Remove the hole from the current face.
from_face->erase_outer_ccb(oc);
// Modify the component that represents the hole.
oc->set_face(to_face);
to_face->add_outer_ccb(oc, he);
// Notify the observers that we have moved the outer CCB.
_notify_after_move_outer_ccb(circ);
}
//-----------------------------------------------------------------------------
// Move a given inner CCB (hole) from one face to another.
//
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::
_move_inner_ccb(DFace* from_face, DFace* to_face, DHalfedge* he)
{
// Get the DCEL record that represents the inner CCB.
DInner_ccb* ic = he->inner_ccb();
CGAL_assertion(ic->face() == from_face);
// Notify the observers that we are about to move an inner CCB.
Ccb_halfedge_circulator circ = (Halfedge_handle(he))->ccb();
_notify_before_move_inner_ccb(Face_handle(from_face), Face_handle(to_face),
circ);
// Remove the hole from the current face.
from_face->erase_inner_ccb(ic);
// Modify the component that represents the hole.
ic->set_face(to_face);
to_face->add_inner_ccb(ic, he);
// Notify the observers that we have moved the inner CCB.
_notify_after_move_inner_ccb(circ);
}
//-----------------------------------------------------------------------------
// Move all inner CCBs (holes) from one face to another.
//
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::
_move_all_inner_ccb(DFace* from_face, DFace* to_face)
{
// Comment EFEF 2015-09-28: The following loop and the loop at the end of this
// function should be replaced with a pair of notifiers, respectively,
// function_notify_before_move_all_inner_ccb();
// function_notify_after_move_all_inner_ccb();
DInner_ccb_iter ic_it = from_face->inner_ccbs_begin();
while (ic_it != from_face->inner_ccbs_end()) {
DHalfedge* he = *ic_it++;
Ccb_halfedge_circulator circ = (Halfedge_handle(he))->ccb();
_notify_before_move_inner_ccb(Face_handle(from_face), Face_handle(to_face),
circ);
}
ic_it = to_face->splice_inner_ccbs(*from_face);
while (ic_it != to_face->inner_ccbs_end()) {
DHalfedge* he = *ic_it++;
Ccb_halfedge_circulator circ = (Halfedge_handle(he))->ccb();
_notify_after_move_inner_ccb(circ);
}
}
//-----------------------------------------------------------------------------
// Insert the given vertex as an isolated vertex inside the given face.
//
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::
_insert_isolated_vertex(DFace* f, DVertex* v)
{
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "Aos_2: _insert_isolated_vertex (internal)" << std::endl;
if (!v->has_null_point())
std::cout << "v->point: " << v->point() << std::endl;
std::cout << "face : " << f << std::endl;
#endif
Face_handle fh(f);
Vertex_handle vh(v);
// Notify the observers that we are about to insert an isolated vertex
// inside f.
_notify_before_add_isolated_vertex(fh, vh);
// Create an isolated vertex-information object,
DIso_vertex* iv = _dcel().new_isolated_vertex();
// Set a pointer to the face containing the vertex.
iv->set_face(f);
// Initiate a new hole inside the given face.
f->add_isolated_vertex(iv, v);
// Associate the information with the vertex.
v->set_isolated_vertex(iv);
// Notify the observers that we have formed a new isolated vertex.
_notify_after_add_isolated_vertex(vh);
}
//-----------------------------------------------------------------------------
// Move a given isolated vertex from one face to another.
//
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::
_move_isolated_vertex(DFace* from_face, DFace* to_face, DVertex* v)
{
// Get the DCEL isolated-vertex record.
DIso_vertex* iv = v->isolated_vertex();
// Notify the observers that we are about to move an isolated vertex.
Vertex_handle vh(v);
_notify_before_move_isolated_vertex(Face_handle(from_face),
Face_handle(to_face), vh);
// Set the new face is the isolated vertex-information object.
iv->set_face(to_face);
// Move the isolated vertex from the first face to the other.
from_face->erase_isolated_vertex(iv);
to_face->add_isolated_vertex(iv, v);
// Notify the observers that we have moved the isolated vertex.
_notify_after_move_isolated_vertex(vh);
}
//-----------------------------------------------------------------------------
// Move all isolated vertices from one face to another.
//
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::
_move_all_isolated_vertices(DFace* from_face, DFace* to_face)
{
// Comment EFEF 2015-09-28: The following loop and the loop at the end of this
// function should be replaced with a pair of notifiers, respectively,
// function_notify_before_move_all_isolated_vertices();
// function_notify_after_move_all_isolated_vertices();
DIso_vertex_iter iv_it = from_face->isolated_vertices_begin();
while (iv_it != from_face->isolated_vertices_end()) {
DVertex* v = &(*iv_it++);
Vertex_handle vh(v);
_notify_before_move_isolated_vertex(Face_handle(from_face),
Face_handle(to_face),
vh);
}
iv_it = to_face->splice_isolated_vertices(*from_face);
while (iv_it != to_face->isolated_vertices_end()) {
DVertex* v = &(*iv_it++);
Vertex_handle vh(v);
_notify_after_move_isolated_vertex(vh);
}
}
//-----------------------------------------------------------------------------
// Create a new vertex and associate it with the given point.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::DVertex*
Arrangement_on_surface_2<GeomTraits, TopTraits>::
_create_vertex(const Point_2& p)
{
// Notify the observers that we are about to create a new vertex.
Point_2* p_p = _new_point(p);
_notify_before_create_vertex(*p_p);
// Create a new vertex and associate it with the given point.
DVertex* v = _dcel().new_vertex();
v->set_point(p_p);
v->set_boundary(ARR_INTERIOR, ARR_INTERIOR);
// Notify the observers that we have just created a new vertex.
Vertex_handle vh(v);
_notify_after_create_vertex(vh);
return v;
}
//-----------------------------------------------------------------------------
// Create a new vertex on boundary
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::DVertex*
Arrangement_on_surface_2<GeomTraits, TopTraits>::
_create_boundary_vertex(const X_monotone_curve_2& cv, Arr_curve_end ind,
Arr_parameter_space ps_x, Arr_parameter_space ps_y)
{
CGAL_precondition((ps_x != ARR_INTERIOR) || (ps_y != ARR_INTERIOR));
// Notify the observers that we are about to create a new boundary vertex.
_notify_before_create_boundary_vertex(cv, ind, ps_x, ps_y);
// Create a new vertex and set its boundary conditions.
DVertex* v = _dcel().new_vertex();
v->set_boundary(ps_x, ps_y);
// Act according to the boundary type if there is one:
if (is_open(ps_x, ps_y))
// The curve-end lies on open boundary so the vertex is not associated
// with a valid point.
v->set_point(nullptr);
else {
// Create a boundary vertex associated with a valid point.
Point_2* p_p = (ind == ARR_MIN_END) ?
_new_point(m_geom_traits->construct_min_vertex_2_object()(cv)) :
_new_point(m_geom_traits->construct_max_vertex_2_object()(cv));
v->set_point(p_p);
}
// Notify the observers that we have just created a new boundary vertex.
Vertex_handle vh(v);
_notify_after_create_boundary_vertex(vh);
return v;
}
//-----------------------------------------------------------------------------
// Locate the DCEL features that will be used for inserting the given curve
// end, which has a boundary condition, and set the proper vertex there.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::DVertex*
Arrangement_on_surface_2<GeomTraits, TopTraits>::
_place_and_set_curve_end(DFace* f,
const X_monotone_curve_2& cv, Arr_curve_end ind,
Arr_parameter_space ps_x, Arr_parameter_space ps_y,
DHalfedge** p_pred)
{
// Use the topology traits to locate the DCEL feature that contains the
// given curve end.
CGAL::Object obj =
m_topol_traits.place_boundary_vertex(f, cv, ind, ps_x, ps_y);
DVertex* v;
DHalfedge* fict_he;
// Act according to the result type.
if (CGAL::assign(fict_he, obj)) {
// The curve end is located on a fictitious edge. We first create a new
// vertex that corresponds to the curve end.
v = _create_boundary_vertex(cv, ind, ps_x, ps_y);
// Split the fictitious halfedge at the newly created vertex.
// The returned halfedge is the predecessor for the insertion of the curve
// end around v.
_notify_before_split_fictitious_edge(Halfedge_handle(fict_he),
Vertex_handle(v));
*p_pred = m_topol_traits.split_fictitious_edge(fict_he, v);
_notify_after_split_fictitious_edge(Halfedge_handle(*p_pred),
Halfedge_handle((*p_pred)->next()));
}
else if (CGAL::assign(v, obj)) {
// In this case we are given an existing vertex that represents the curve
// end. We now have to locate the predecessor edge for the insertion of cv
// around this vertex.
*p_pred =
m_topol_traits.locate_around_boundary_vertex(v, cv, ind, ps_x, ps_y);
}
else {
CGAL_assertion(obj.is_empty());
// In this case we have to create a new vertex that reprsents the given
// curve end.
v = _create_boundary_vertex(cv, ind, ps_x, ps_y);
// Notify the topology traits on the creation of the boundary vertex.
m_topol_traits.notify_on_boundary_vertex_creation(v, cv, ind, ps_x, ps_y);
// There are no edges incident to v, therefore no predecessor halfedge.
*p_pred = nullptr;
}
// Return the vertex that represents the curve end.
return v;
}
//-----------------------------------------------------------------------------
// Insert an x-monotone curve into the arrangement, such that both its
// endpoints correspond to free arrangement vertices (newly created vertices
// or existing isolated vertices), so a new inner CCB is formed in the face
// that contains the two vertices.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::DHalfedge*
Arrangement_on_surface_2<GeomTraits, TopTraits>::
_insert_in_face_interior(DFace* f,
const X_monotone_curve_2& cv,
Arr_halfedge_direction cv_dir,
DVertex* v1, DVertex* v2)
{
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "Aos_2: _insert_in_face_interior (internal)" << std::endl;
std::cout << "face : " << f << std::endl;
std::cout << "cv : " << cv << std::endl;
std::cout << "cv_dir: " << cv_dir << std::endl;
if (!v1->has_null_point())
std::cout << "v1->point: " << v1->point() << std::endl;
if (!v2->has_null_point())
std::cout << "v2->point: " << v2->point() << std::endl;
#endif
// Notify the observers that we are about to create a new edge.
_notify_before_create_edge(cv, Vertex_handle(v1), Vertex_handle(v2));
// Create a pair of twin halfedges connecting the two vertices,
// and link them together to form a new connected component, a hole in f.
DHalfedge* he1 = _dcel().new_edge();
DHalfedge* he2 = he1->opposite();
DInner_ccb* ic = _dcel().new_inner_ccb();
X_monotone_curve_2* dup_cv = _new_curve(cv);
ic->set_face(f);
he1->set_curve(dup_cv);
he1->set_next(he2);
he1->set_vertex(v1);
he1->set_inner_ccb(ic);
he2->set_next(he1);
he2->set_vertex(v2);
he2->set_inner_ccb(ic);
// Assign the incident halfedges of the two new vertices.
v1->set_halfedge(he1);
v2->set_halfedge(he2);
// Set the direction of the halfedges
he2->set_direction(cv_dir);
// Create a handle to the new halfedge pointing at the curve target.
Halfedge_handle hh(he2);
// Notify the observers that we have created a new edge.
_notify_after_create_edge(hh);
// Notify the observers that we are about to form a new inner CCB inside f.
_notify_before_add_inner_ccb(Face_handle(f), hh);
// Initiate a new inner CCB inside the given face.
f->add_inner_ccb(ic, he2);
// Notify the observers that we have formed a new inner CCB.
_notify_after_add_inner_ccb(hh->ccb());
return he2;
}
//-----------------------------------------------------------------------------
// Insert an x-monotone curve into the arrangement, such that one of its
// endpoints corresponds to a given arrangement vertex, given the exact
// place for the curve in the circular list around this vertex. The other
// endpoint corrsponds to a free vertex (a newly created vertex or an
// isolated vertex).
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::DHalfedge*
Arrangement_on_surface_2<GeomTraits, TopTraits>::
_insert_from_vertex(DHalfedge* he_to, const X_monotone_curve_2& cv,
Arr_halfedge_direction cv_dir,
DVertex* v)
{
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "Aos_2: _insert_from_vertex (internal)" << std::endl;
if (!he_to->has_null_curve())
std::cout << "he_to: " << he_to->curve() << std::endl;
else
std::cout << "he_to: fictitious" << std::endl;
std::cout << "f_to: " << (he_to->is_on_inner_ccb() ?
he_to->inner_ccb()->face() :
he_to->outer_ccb()->face()) << std::endl;
std::cout << "cv : " << cv << std::endl;
std::cout << "cv_dir: " << cv_dir << std::endl;
if (!v->has_null_point())
std::cout << "v->point: " << v->point() << std::endl;
#endif
// Get the incident face of the previous halfedge. Note that this will also
// be the incident face of the two new halfedges we are about to create.
DInner_ccb* ic = (he_to->is_on_inner_ccb()) ? he_to->inner_ccb() : nullptr;
DOuter_ccb* oc = (ic == nullptr) ? he_to->outer_ccb() : nullptr;
// The first vertex is the one that the he_to halfedge points to.
// The second vertex is given by v.
DVertex* v1 = he_to->vertex();
DVertex* v2 = v;
// Notify the observers that we are about to create a new edge.
_notify_before_create_edge(cv, Vertex_handle(v1), Vertex_handle(v2));
// Create a pair of twin halfedges connecting the two vertices,
// and associate them with the given curve.
DHalfedge* he1 = _dcel().new_edge();
DHalfedge* he2 = he1->opposite();
X_monotone_curve_2* dup_cv = _new_curve(cv);
he1->set_curve(dup_cv);
he1->set_vertex(v1);
he2->set_vertex(v2);
// Set the component for the new halfedge pair.
if (oc != nullptr) {
// On an outer component:
he1->set_outer_ccb(oc);
he2->set_outer_ccb(oc);
}
else {
// On an inner component:
he1->set_inner_ccb(ic);
he2->set_inner_ccb(ic);
}
// Associate the incident halfedge of the new vertex.
v2->set_halfedge(he2);
// Link the new halfedges around the existing vertex v1.
he2->set_next(he1);
he1->set_next(he_to->next());
he_to->set_next(he2);
// Set the direction of the halfedges
he2->set_direction(cv_dir);
// Notify the observers that we have created a new edge.
_notify_after_create_edge(Halfedge_handle(he2));
// Return a pointer to the new halfedge whose target is the free vertex v.
return he2;
}
//-----------------------------------------------------------------------------
// Insert an x-monotone curve into the arrangement, where the end vertices
// are given by the target points of two given halfedges.
// The two halfedges should be given such that in case a new face is formed,
// it will be the incident face of the halfedge directed from the first
// vertex to the second vertex.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::DHalfedge*
Arrangement_on_surface_2<GeomTraits, TopTraits>::
_insert_at_vertices(DHalfedge* he_to,
const X_monotone_curve_2& cv,
Arr_halfedge_direction cv_dir,
DHalfedge* he_away,
bool& new_face,
bool& swapped_predecessors,
bool allow_swap_of_predecessors /* = true */)
{
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "_insert_at_vertices: " << cv << std::endl;
#endif
// Comment: This is how the situation looks
// ----to---> >>cv_dir>> ---away--->
// o ===cv=== 0
// <-tonext-- <-awaynext-
// or to be read from right to left ...
// this way, he_to and he_away lie
// BEFORE insertion on the same inner ccb and
// AFTER insertion on the same outer ccb
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "Aos_2: _insert_at_vertices (internal)" << std::endl;
if (!he_to->has_null_curve())
std::cout << "he_to: " << he_to->curve() << std::endl;
else
std::cout << "he_to: fictitious" << std::endl;
std::cout << "dir1 : " << he_to->direction() << std::endl;
std::cout << "f_to : " << (he_to->is_on_inner_ccb() ?
he_to->inner_ccb()->face() :
he_to->outer_ccb()->face()) << std::endl;
std::cout << "cv : " << cv << std::endl;
std::cout << "cv_dir: " << cv_dir << std::endl;
if (!he_away->has_null_curve())
std::cout << "he_away: " << he_away->curve() << std::endl;
else
std::cout << "he_away: fictitious" << std::endl;
std::cout << "dir 2 : " << he_away->direction() << std::endl;
std::cout << "f_away: " << (he_away->is_on_inner_ccb() ?
he_away->inner_ccb()->face() :
he_away->outer_ccb()->face()) << std::endl;
#endif
CGAL_precondition(he_to != nullptr);
CGAL_precondition(he_away != nullptr);
// TODO EBEB 2012-10-21 rewrite the code in terms of he_to and he_away instead of prev1 and prev2
// the remainder of the function we deal with this situation adds he1 and
// he2 in this way:
// ----prev1---> ( --he2--> ) ---p2next--->
// o ===cv=== 0
// <---p1next--- ( <--he1-- ) <---prev2----
DHalfedge* prev1 = he_to;
DHalfedge* prev2 = he_away->prev();
CGAL_precondition(prev1 != nullptr);
CGAL_precondition(prev2 != nullptr);
CGAL_precondition(prev1 != prev2);
// in general we do not swap ...
swapped_predecessors = false;
// default values for signs
std::pair<Sign, Sign> signs1(ZERO, ZERO);
std::pair<Sign, Sign> signs2(ZERO, ZERO);
// Remark: signs1 and signs2 are only used later when hole1==hole2
// Comment: This also checks which is the 'cheaper' (previously the
// 'shorter') way to insert the curve. Now cheaper means checking
// less local minima!
if (allow_swap_of_predecessors) {
bool swap_predecessors = false;
// Comment EBEB 2012-08-05 hole1/hole2 appear later as ic1/ic2, but we keep
// them here, as the usage is rather local to decide swapping
DInner_ccb* hole1 = (prev1->is_on_inner_ccb()) ? prev1->inner_ccb() : nullptr;
DInner_ccb* hole2 = (prev2->is_on_inner_ccb()) ? prev2->inner_ccb() : nullptr;
if ((hole1 == hole2) && (hole1 != nullptr)) {
// .. only in this special case, we have to check whether swapping should
// take place
// EBEB 2012-07-26 the following code enables optimizations:
// - avoid length-test
// - search only local minima to find leftmost vertex
// - re-use of signs of ccbs
// signs1/2 are only used when hole1 == hole2,
// thus we have to init them now
Arr_halfedge_direction cv_dir1 = cv_dir;
std::list<std::pair<const DHalfedge*, int> > local_mins1;
signs1 =
_compute_signs_and_local_minima(prev1, cv, cv_dir1, prev2->next(),
std::back_inserter(local_mins1));
Arr_halfedge_direction cv_dir2 = (cv_dir == ARR_LEFT_TO_RIGHT) ?
CGAL::ARR_RIGHT_TO_LEFT : CGAL::ARR_LEFT_TO_RIGHT;
std::list< std::pair< const DHalfedge*, int > > local_mins2;
signs2 =
_compute_signs_and_local_minima(prev2, cv, cv_dir2, prev1->next(),
std::back_inserter(local_mins2));
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "signs1.x: " << signs1.first << std::endl;
std::cout << "signs1.y: " << signs1.second << std::endl;
std::cout << "signs2.x: " << signs2.first << std::endl;
std::cout << "signs2.y: " << signs2.second << std::endl;
std::cout << "#local_mins1: " << local_mins1.size() << std::endl;
std::cout << "#local_mins2: " << local_mins2.size() << std::endl;
#endif
if (!m_topol_traits.let_me_decide_the_outer_ccb(signs1, signs2,
swap_predecessors))
{
// COMMENT: The previous solution needed O(min(length1, length2)) steps
// to determine which path is shorter and the search for the
// leftmost vertex on a path needs O(#local_mins) geometric
// comparison. This solution saves the initial loop to
// determine the shorter path and will only need O(min(#local
// _mins1, #local_mins2)) geometric comparisons to determine
// the leftmost vertex on a path.
// If there are no local minima in one the paths, it is expected
// that the topology traits (or its adapter) do decide the outer ccb.
CGAL_assertion(local_mins1.size() > 0);
CGAL_assertion(local_mins2.size() > 0);
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "decide swap" << std::endl;
#endif
swap_predecessors =
!((local_mins1.size() < local_mins2.size()) ?
( _defines_outer_ccb_of_new_face(prev1, cv, prev2->next(),
local_mins1.begin(),
local_mins1.end())) :
(! _defines_outer_ccb_of_new_face(prev2, cv, prev1->next(),
local_mins2.begin(),
local_mins2.end())));
}
// perform the swap
if (swap_predecessors) {
std::swap(prev1, prev2);
cv_dir = (cv_dir == ARR_LEFT_TO_RIGHT) ?
CGAL::ARR_RIGHT_TO_LEFT : CGAL::ARR_LEFT_TO_RIGHT;
std::swap(signs1, signs2);
std::swap(local_mins1, local_mins2);
// and store the value
swapped_predecessors = true;
}
}
// EBEB: For now, local_mins1/2 are local to this pre-check
// Idea: Use it later, however, this spoils uses of _insert_at_vertices
// where allow_swap = false
// On the other hand: this would allow to set representative
// halfedge of ccbs to point to minimal vertex
} // allow_swap_of_predecessors
// Get the vertices that match cv's endpoints.
DVertex* v1 = prev1->vertex();
DVertex* v2 = prev2->vertex();
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "Aos_2: _insert_at_vertices (internal)" << std::endl;
std::cout << "cv : " << cv << std::endl;
if (!prev1->has_null_curve())
std::cout << "prev1: " << prev1->curve() << std::endl;
else
std::cout << "prev1: fictitious" << std::endl;
std::cout << "dir1 : " << prev1->direction() << std::endl;
std::cout << "pref: " << (prev1->is_on_inner_ccb() ?
prev1->inner_ccb()->face() :
prev1->outer_ccb()->face()) << std::endl;
if (!prev2->has_null_curve())
std::cout << "prev2: " << prev2->curve() << std::endl;
else
std::cout << "prev2: fictitious" << std::endl;
std::cout << "dir 2: " << prev2->direction() << std::endl;
std::cout << "pref2: " << (prev2->is_on_inner_ccb() ?
prev2->inner_ccb()->face() :
prev2->outer_ccb()->face()) << std::endl;
std::cout << "cv_dir: " << cv_dir << std::endl;
#endif
// Get the components containing the two previous halfedges and the incident
// face (which should be the same for the two components).
DInner_ccb* ic1 = (prev1->is_on_inner_ccb()) ? prev1->inner_ccb() : nullptr;
DOuter_ccb* oc1 = (ic1 == nullptr) ? prev1->outer_ccb() : nullptr;
DFace* f = (ic1 != nullptr) ? ic1->face() : oc1->face();
DInner_ccb* ic2 = (prev2->is_on_inner_ccb()) ? prev2->inner_ccb() : nullptr;
DOuter_ccb* oc2 = (ic2 == nullptr) ? prev2->outer_ccb() : nullptr;
CGAL_precondition_code(DFace* f2 = (ic2 != nullptr) ? ic2->face() : oc2->face());
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "ic1: " << ic1 << std::endl;
std::cout << "ic2: " << ic2 << std::endl;
std::cout << "oc1: " << oc1 << std::endl;
std::cout << "oc2: " << oc2 << std::endl;
std::cout << "f1: " << &(*f) << std::endl;
#if 0
DHalfedge* curr = prev1;
if (curr != curr->next()) {
curr = curr->next();
while (curr != prev1) {
if (!curr->has_null_curve())
std::cout << "curr: " << curr->curve() << std::endl;
else
std::cout << "curr: fictitious" << std::endl;
std::cout << "dir: "
<< (curr->direction() == CGAL::ARR_LEFT_TO_RIGHT ?
"L2R" : "R2L")
<< std::endl;
curr = curr->next();
}
} else {
std::cout << "only prev1" << std::endl;
}
#endif
CGAL_precondition_code(std::cout << "f2: " << &(*f2) << std::endl);
#if 0
curr = prev2;
if (curr != curr->next()) {
curr = curr->next();
while (curr != prev2) {
if (!curr->has_null_curve())
std::cout << "curr: " << curr->curve() << std::endl;
else
std::cout << "curr: fictitious" << std::endl;
std::cout << "dir: "
<< (curr->direction() == CGAL::ARR_LEFT_TO_RIGHT ?
"L2R" : "R2L")
<< std::endl;
curr = curr->next();
}
} else
std::cout << "only prev2" << std::endl;
#endif
#endif // CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
CGAL_precondition_msg
(f == f2, "The two halfedges must share the same incident face.");
// In case the two previous halfedges lie on the same inner component inside
// the face f, we use the topology-traits class to determine whether we have
// to create a new face by splitting f, and if so - whether new face is
// contained in the existing face or just adjacent to it.
bool split_new_face = true;
bool is_split_face_contained = false;
if ((ic1 != nullptr) && (ic1 == ic2)) {
// EBEB 2012-08-06:
// This is new code. It relies on the (computed) signs and replaces to
// trace the ccb again (in particular for torical arrangements)
// TODO EBEB 2012-08-06:
// Check what to do here, when allow_swap_of_predecessors = false and thus
// signs1 and signs2 set to DEFAULT (=ZERO) values.
// swapping is currently only disabled when _insert_at_vertices is called
// from Arr_construction_ss_visitor, which however uses the
// 'swap_predecessors' member of the topology traits' construction helper.
// So it's questionable whether we can combine the light-weigth swap
// information with the slightly more expensive sign computations, to keep
// efficient translated code after compile-time.
std::pair<bool, bool> res =
m_topol_traits.face_split_after_edge_insertion(signs1, signs2);
split_new_face = res.first;
is_split_face_contained = res.second;
// The result <false, true> is illegal:
CGAL_assertion(split_new_face || ! is_split_face_contained);
}
// Notify the observers that we are about to create a new edge.
_notify_before_create_edge(cv, Vertex_handle(v1), Vertex_handle(v2));
// Create a pair of twin halfedges connecting v1 and v2 and associate them
// with the given curve.
DHalfedge* he1 = _dcel().new_edge();
DHalfedge* he2 = he1->opposite();
X_monotone_curve_2* dup_cv = _new_curve(cv);
he1->set_curve(dup_cv);
he1->set_vertex(v1);
he2->set_vertex(v2);
// Connect the new halfedges to the existing halfedges around the two
// incident vertices.
he1->set_next(prev1->next());
he2->set_next(prev2->next());
prev1->set_next(he2);
prev2->set_next(he1);
he2->set_direction(cv_dir);
// Check the various cases of insertion (in the design document: the
// various sub-cases of case 3 in the insertion procedure).
if (((ic1 != nullptr) || (ic2 != nullptr)) && (ic1 != ic2)) {
// In case we have to connect two disconnected components, no new face
// is created.
new_face = false;
// Check whether both halfedges are inner components (holes) in the same
// face, or whether one is a hole and the other is on the outer boundary
// of the face.
Face_handle fh(f);
if ((ic1 != nullptr) && (ic2 != nullptr)) {
// In this case (3.1) we have to connect to inner CCBs (holes) inside f.
// Notify the observers that we are about to merge two holes in the face.
_notify_before_merge_inner_ccb(fh,
(Halfedge_handle(prev1))->ccb(),
(Halfedge_handle(prev2))->ccb(),
Halfedge_handle(he1));
// Remove the inner component prev2 belongs to, and unite it with the
// inner component that prev1 belongs to.
f->erase_inner_ccb(ic2);
// Set the merged component for the two new halfedges.
he1->set_inner_ccb(ic1);
he2->set_inner_ccb(ic1);
// Make all halfedges along ic2 to point to ic1.
DHalfedge* curr;
for (curr = he2->next(); curr != he1; curr = curr->next())
curr->set_inner_ccb(ic1);
// Delete the redundant inner CCB.
_dcel().delete_inner_ccb(ic2);
// Notify the observers that we have merged the two inner CCBs.
_notify_after_merge_inner_ccb(fh, (Halfedge_handle(he1))->ccb());
}
else {
// In this case (3.2) we connect a hole (inner CCB) with an outer CCB
// of the face that contains it. We remove the hole and associate the
// pair of new halfedges with the outer boundary of the face f.
DInner_ccb* del_ic;
DOuter_ccb* oc;
DHalfedge* ccb_first;
DHalfedge* ccb_last;
if (ic1 != nullptr) {
// We remove the inner CCB ic1 and merge in with the outer CCB oc2.
del_ic = ic1;
oc = oc2;
ccb_first = he1->next();
ccb_last = he2;
}
else {
// We remove the inner CCB ic2 and merge in with the outer CCB oc1.
del_ic = ic2;
oc = oc1;
ccb_first = he2->next();
ccb_last = he1;
}
he1->set_outer_ccb(oc);
he2->set_outer_ccb(oc);
// Notify the observers that we are about to remove an inner CCB from
// the face.
_notify_before_remove_inner_ccb(fh, (Halfedge_handle(ccb_first))->ccb());
// Remove the inner CCB from the face, as we have just connected it to
// the outer boundary of its incident face.
f->erase_inner_ccb(del_ic);
// Make all halfedges along the inner CCB to point to the outer CCB of f.
DHalfedge* curr;
for (curr = ccb_first; curr != ccb_last; curr = curr->next())
curr->set_outer_ccb(oc);
// Delete the redundant hole.
_dcel().delete_inner_ccb(del_ic);
// Notify the observers that we have removed an inner ccb.
_notify_after_remove_inner_ccb(fh);
}
}
else if (! split_new_face) {
// RWRW: NEW!
CGAL_assertion((ic1 == ic2) && (ic1 != nullptr));
// Handle the special case where we close an inner CCB, such that
// we form two outer CCBs of the same face.
Face_handle fh(f);
// Notify the obserers we are about to remove an inner CCB from f.
_notify_before_remove_inner_ccb(fh, (Halfedge_handle(he1))->ccb());
// Erase the inner CCB from the incident face and delete the
// corresponding component.
f->erase_inner_ccb(ic1);
_dcel().delete_inner_ccb(ic1);
// Notify the observers that the inner CCB has been removed.
_notify_after_remove_inner_ccb(fh);
// Handle the first split outer CCB (the one containing he1):
// Notify the obserers we are about to add an outer CCB to f.
_notify_before_add_outer_ccb(fh, Halfedge_handle(he1));
// Create a new outer CCB that for the face f, and make he1 the
// representative halfedge of this component.
DOuter_ccb* f_oc1 = _dcel().new_outer_ccb();
f->add_outer_ccb(f_oc1, he1);
f_oc1->set_face(f);
he1->set_outer_ccb(f_oc1);
// Set the component of all halfedges that used to belong to he1's CCB.
DHalfedge* curr;
for (curr = he1->next(); curr != he1; curr = curr->next())
curr->set_outer_ccb(f_oc1);
// Notify the observers that we have added an outer CCB to f.
_notify_after_add_outer_ccb((Halfedge_handle(he1))->ccb());
// Handle the second split outer CCB (the one containing he2):
// Notify the obserers we are about to add an outer CCB to f.
_notify_before_add_outer_ccb(fh, Halfedge_handle(he2));
// Create a new outer CCB that for the face f, and make he2 the
// representative halfedge of this component.
DOuter_ccb* f_oc2 = _dcel().new_outer_ccb();
f->add_outer_ccb(f_oc2, he2);
f_oc2->set_face(f);
he2->set_outer_ccb(f_oc2);
// Set the component of all halfedges that used to belong to he2's CCB.
for (curr = he2->next(); curr != he2; curr = curr->next())
curr->set_outer_ccb(f_oc2);
// Notify the observers that we have added an outer CCB to f.
_notify_after_add_outer_ccb((Halfedge_handle(he2))->ccb());
// Mark that in this case no new face is created:
new_face = false;
}
else if ((ic1 == ic2) && (oc1 == oc2)) {
// In this case we created a pair of halfedge that connect halfedges that
// already belong to the same component. This means we have to cretae a
// new face by splitting the existing face f.
// Notify the observers that we are about to split a face.
Face_handle fh(f);
_notify_before_split_face(fh, Halfedge_handle(he1));
// Create the new face and create a single outer component which should
// point to he2.
DFace* new_f = _dcel().new_face();
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "new face: " << new_f << std::endl;
#endif
DOuter_ccb* new_oc = _dcel().new_outer_ccb();
new_face = true;
new_f->add_outer_ccb(new_oc, he2);
new_oc->set_face(new_f);
// Set the components of the new halfedge he2, which should be the new
// outer comoponent of the new face.
// Note that there are several cases for setting he1's component, so we
// do not do it yet.
he2->set_outer_ccb(new_oc);
// Set the component of all halfedges that used to belong to he2's CCB.
DHalfedge* curr;
for (curr = he2->next(); curr != he2; curr = curr->next())
curr->set_outer_ccb(new_oc);
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "(=> prev1=" << &(*prev1) << ") he2= " << &(*he2)
<< " defines new outer CCB" << std::endl;
std::cout << "he2dir : " << he2->direction() << std::endl;
std::cout << "prev1->face(): " << (prev1->is_on_inner_ccb() ?
prev1->inner_ccb()->face() :
prev1->outer_ccb()->face())
<< std::endl;
std::cout << "signs1: " << signs1.first << "," << signs1.second
<< std::endl;
#endif
// Check whether the two previous halfedges lie on the same innder CCB
// or on the same outer CCB (distinguish case 3.3 and case 3.4).
bool is_hole;
if (ic1 != nullptr) {
// In this case (3.3) we have two distinguish two sub-cases.
if (is_split_face_contained) {
// Comment: This is true for all non-identification topologies
// The halfedges prev1 and prev2 belong to the same inner component
// (hole) inside the face f, such that the new edge creates a new
// face that is contained in f (case 3.3.1).
is_hole = true;
// In this case, he1 lies on an inner CCB of f.
he1->set_inner_ccb(ic1);
// Note that the current representative of the inner CCB may not
// belong to the hole any more. In this case we replace the hole
// representative by he1.
if (! ic1->halfedge()->is_on_inner_ccb())
ic1->set_halfedge(he1);
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "(=> prev2=" << &(*prev2) << ") he1= " << &(*he1)
<< " defines new inner CCB" << std::endl;
std::cout << "he1dir : " << he1->direction() << std::endl;
std::cout << "prev2->face(): " << (prev2->is_on_inner_ccb() ?
prev2->inner_ccb()->face() :
prev2->outer_ccb()->face())
<< std::endl;
std::cout << "signs2: " << signs2.first << "," << signs2.second
<< std::endl;
#endif
}
else {
// Comment: This case can only occur in identification topologies
// The new face we have created should be adjacent to the existing
// face (case 3.3.2).
is_hole = false;
// Notify the obserers we are about to add an outer CCB to f.
_notify_before_add_outer_ccb(fh, Halfedge_handle(he1));
// Create a new outer CCB that for the face f, and make he1 the
// representative halfedge of this component.
DOuter_ccb* f_oc = _dcel().new_outer_ccb();
f->add_outer_ccb(f_oc, he1);
f_oc->set_face(f);
he1->set_outer_ccb(f_oc);
// Set the component of all halfedges that used to belong to he1's
// CCB.
for (curr = he1->next(); curr != he1; curr = curr->next())
curr->set_outer_ccb(f_oc);
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "(=> prev2=" << &(*prev2) << ") he1= " << &(*he1) << " defines new outer CCB" << std::endl;
std::cout << "he1dir : " << he1->direction() << std::endl;
std::cout << "prev2->face(): " << (prev2->is_on_inner_ccb() ?
prev2->inner_ccb()->face() :
prev2->outer_ccb()->face())
<< std::endl;
std::cout << "signs2: " << signs2.first << "," << signs2.second
<< std::endl;
#endif
// Notify the observers that we have added an outer CCB to f.
_notify_after_add_outer_ccb((Halfedge_handle(he1))->ccb());
// Go over all other outer CCBs of f and check whether they should be
// moved to be outer CCBs of the new face.
DOuter_ccb_iter oc_it = f->outer_ccbs_begin();
DOuter_ccb_iter oc_to_move;
while (oc_it != f->outer_ccbs_end()) {
// Use the topology traits to determine whether the representative
// of the current outer CCB should belong to the same face as he2
// (which is on the outer boundary of the new face).
bool increment = true;
if (*oc_it != he1) {
// he2 is supposed to be a perimetric path and so all of the oc_its,
// we only have to detect which one. We do so by comparing signs of
// ccbs:
// IDEA EBEB 2012-07-28
// store signs of CCB with CCB in DCEL and use them here
// *oc_it is already closed, so we do a full round
// (default = false)
std::pair<Sign, Sign> signs_oc =
_compute_signs(*oc_it, Has_identified_sides_category());
bool move = false;
// TODO EBEB 2013-07-15 refactor into own function
// TODO EBEB 2012-08-07 this either compares signs in left-right
// direction OR signs in bottom-top direction, which will probably
// not work for torus!
if ((signs2.first != CGAL::ZERO) && (signs_oc.first != CGAL::ZERO))
{
if (signs2.first != signs_oc.first) move = true;
}
else if ((signs2.second != CGAL::ZERO) &&
(signs_oc.second != CGAL::ZERO))
{
if (signs2.second != signs_oc.second) move = true;
}
if (move) {
// We increment the itrator before moving the outer CCB, because
// this operation invalidates the iterator.
increment = false;
oc_to_move = oc_it;
++oc_it;
_move_outer_ccb(f, new_f, *oc_to_move);
}
}
if (increment) ++oc_it;
}
}
}
else {
// In this case the face f is simply split into two (case 3.4).
is_hole = false;
// In this case, he1 lies on an outer CCB of f.
he1->set_outer_ccb(oc1);
// As the outer component of the exisitng face f may associated with
// one of the halfedges along the boundary of the new face, we set it
// to be he1.
oc1->set_halfedge(he1);
}
// Check whether we should mark the original face and the new face as
// bounded or as unbounded faces.
if (! f->is_unbounded())
// The original face is bounded, so the new face split from it is
// obviously bounded.
new_f->set_unbounded(false);
else if (is_hole)
// The new face is a hole inside the original face, so it must be
// bounded.
new_f->set_unbounded(false);
else {
// Use the topology traits to determine whether each of the split
// faces is unbounded. Note that if the new face is bounded, then f
// obviously reamins unbounded and there is no need for further checks.
new_f->set_unbounded(m_topol_traits.is_unbounded(new_f));
if (new_f->is_unbounded())
f->set_unbounded(m_topol_traits.is_unbounded(f));
}
// Notify the observers that we have split the face.
_notify_after_split_face(fh, Face_handle(new_f), is_hole);
}
else {
CGAL_assertion((oc1 != nullptr) && (oc2 != nullptr) && (oc1 != oc2));
// In case prev1 and prev2 belong to different outer CCBs of the same
// face f (case 3.5), we have to merge this ccbs into one. Note that we
// do not create a new face.
new_face = false;
// Notify the observers that we are about to merge two outer CCBs.
Face_handle fh(f);
_notify_before_merge_outer_ccb(fh,
(Halfedge_handle(prev1))->ccb(),
(Halfedge_handle(prev2))->ccb(),
Halfedge_handle(he1));
// Remove the outer component prev2 belongs to, and unite it with the
// outer component that prev1 belongs to.
f->erase_outer_ccb(oc2);
// Set the merged component for the two new halfedges.
he1->set_outer_ccb(oc1);
he2->set_outer_ccb(oc1);
// Make all halfedges along oc2 to point to oc1.
DHalfedge* curr;
for (curr = he2->next(); curr != he1; curr = curr->next())
curr->set_outer_ccb(oc1);
// Delete the redundant outer CCB.
_dcel().delete_outer_ccb(oc2);
// Notify the observers that we have merged the two CCBs.
_notify_after_merge_outer_ccb(fh, (Halfedge_handle(he1))->ccb());
}
// Notify the observers that we have created a new edge.
_notify_after_create_edge(Halfedge_handle(he2));
// TODO EBEB 2012-08-08 add postcondition that checks sanity
#if 0
{
DHalfedge* he1 = he2->opposite();
DInner_ccb* ic1 = (he1->is_on_inner_ccb()) ? he1->inner_ccb() : nullptr;
DOuter_ccb* oc1 = (ic1 == nullptr) ? he1->outer_ccb() : nullptr;
DFace* f1 = (ic1 != nullptr) ? ic1->face() : oc1->face();
DInner_ccb* ic2 = (he2->is_on_inner_ccb()) ? he2->inner_ccb() : nullptr;
DOuter_ccb* oc2 = (ic2 == nullptr) ? he2->outer_ccb() : nullptr;
DFace* f2 = (ic2 != nullptr) ? ic2->face() : oc2->face();
CGAL_postcondition((ic1 != ic2) || (f1 == f2));
}
#endif
// Return the halfedge directed from v1 to v2.
return he2;
}
//-----------------------------------------------------------------------------
// Relocate all inner CCBs (holes) to their proper position,
// immediately after a face has split due to the insertion of a new halfedge.
//
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::
_relocate_inner_ccbs_in_new_face(DHalfedge* new_he)
{
// The given halfedge points to the new face, while its twin points to the
// old face (the one that has just been split).
DFace* new_face = (new_he->is_on_inner_ccb()) ?
new_he->inner_ccb()->face() : new_he->outer_ccb()->face();
DHalfedge* opp_he = new_he->opposite();
const bool opp_on_inner_ccb = opp_he->is_on_inner_ccb();
DFace* old_face = opp_on_inner_ccb ? opp_he->inner_ccb()->face() :
opp_he->outer_ccb()->face();
CGAL_assertion(new_face != old_face);
// Examine the inner CCBs inside the existing old face and move the relevant
// ones into the new face.
DInner_ccb_iter ic_it = old_face->inner_ccbs_begin();
while (ic_it != old_face->inner_ccbs_end()) {
// In case the new edge represents the current component in the old face
// (note we take the opposite halfedge, as it is incident to the old face),
// then the new face already forms a hole in the old face, and we do not
// need to move it.
CGAL_assertion((*ic_it)->is_on_inner_ccb());
if (opp_on_inner_ccb && ((*ic_it)->inner_ccb() == opp_he->inner_ccb())) {
++ic_it;
continue;
}
// Check whether the current inner CCB is inside new face (we actually
// check if a representative vertex is located in the new face).
if (m_topol_traits.is_in_face(new_face, (*ic_it)->vertex()->point(),
(*ic_it)->vertex()))
{
// We store the current iterator which get then incremented before it
// gets moved, as the move operation invalidates the iterator.
DInner_ccb_iter ic_to_move = ic_it;
++ic_it;
_move_inner_ccb(old_face, new_face, *ic_to_move); // move the hole
}
else
++ic_it;
}
}
//-----------------------------------------------------------------------------
// Relocate all isolated vertices to their proper position,
// immediately after a face has split due to the insertion of a new halfedge.
//
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::
_relocate_isolated_vertices_in_new_face(DHalfedge* new_he)
{
// The given halfedge points to the new face, while its twin points to the
// old face (the one that has just been split).
DFace* new_face = (new_he->is_on_inner_ccb()) ?
new_he->inner_ccb()->face() :
new_he->outer_ccb()->face();
DHalfedge* opp_he = new_he->opposite();
DFace* old_face = (opp_he->is_on_inner_ccb()) ?
opp_he->inner_ccb()->face() :
opp_he->outer_ccb()->face();
CGAL_assertion(new_face != old_face);
// Examine the isolated vertices inside the existing old face and move the
// relevant ones into the new face.
DIso_vertex_iter iv_it;
DIso_vertex_iter iv_to_move;
iv_it = old_face->isolated_vertices_begin();
while (iv_it != old_face->isolated_vertices_end()) {
// Check whether the isolated vertex lies inside the new face.
if (m_topol_traits.is_in_face(new_face, iv_it->point(), &(*iv_it))) {
// We increment the isolated vertices itrator before moving the vertex,
// because this operation invalidates the iterator.
iv_to_move = iv_it;
++iv_it;
// Move the isolated vertex.
_move_isolated_vertex(old_face, new_face, &(*iv_to_move));
}
else
++iv_it;
}
}
//-----------------------------------------------------------------------------
// Relocate all holes (inner CCBs) and isolated vertices to their proper
// position, immediately after a face has split due to the insertion of a new
// halfedge.
//
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::
_relocate_in_new_face(DHalfedge* new_he)
{
_relocate_inner_ccbs_in_new_face(new_he);
_relocate_isolated_vertices_in_new_face(new_he);
}
//-----------------------------------------------------------------------------
// Replace the point associated with the given vertex.
//
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::
_modify_vertex(DVertex* v, const Point_2& p)
{
// Notify the observers that we are about to modify a vertex.
Vertex_handle vh(v);
_notify_before_modify_vertex(vh, p);
// Modify the point associated with the vertex.
v->point() = p;
// Notify the observers that we have modified the vertex.
_notify_after_modify_vertex(vh);
}
//-----------------------------------------------------------------------------
// Replace the x-monotone curve associated with the given edge.
//
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::
_modify_edge(DHalfedge* he, const X_monotone_curve_2& cv)
{
// Notify the observers that we are about to modify an edge.
Halfedge_handle e(he);
_notify_before_modify_edge(e, cv);
// Modify the curve associated with the halfedge.
he->curve() = cv;
// Notify the observers that we have modified the edge.
_notify_after_modify_edge(e);
}
//-----------------------------------------------------------------------------
// Check if the given vertex represents one of the ends of a given curve.
//
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_are_equal(const DVertex* v,
const X_monotone_curve_2& cv, Arr_curve_end ind) const
{
// In case the given curve end has boundary conditions, use the topology
// traits to determine whether it is equivalent to v.
const Arr_parameter_space ps_x =
m_geom_traits->parameter_space_in_x_2_object()(cv, ind);
const Arr_parameter_space ps_y =
m_geom_traits->parameter_space_in_y_2_object()(cv, ind);
if ((ps_x != ARR_INTERIOR) || (ps_y != ARR_INTERIOR))
return (m_topol_traits.are_equal(v, cv, ind, ps_x, ps_y));
// Otherwise, the curve end is a valid endpoint. Check that v is also
// associated with a valid point that equals this endpoint.
if (v->has_null_point()) return false;
return (ind == ARR_MIN_END) ?
(m_geom_traits->equal_2_object()
(m_geom_traits->construct_min_vertex_2_object()(cv), v->point())) :
(m_geom_traits->equal_2_object()
(m_geom_traits->construct_max_vertex_2_object()(cv), v->point()));
}
//-----------------------------------------------------------------------------
// Split a given edge into two at a given point, and associate the given
// x-monotone curves with the split edges.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::DHalfedge*
Arrangement_on_surface_2<GeomTraits, TopTraits>::
_split_edge(DHalfedge* e, const Point_2& p,
const X_monotone_curve_2& cv1, const X_monotone_curve_2& cv2)
{
// Allocate a new vertex and associate it with the split point.
// Note that this point must not have any boundary conditions.
DVertex* v = _create_vertex(p);
// Split the edge from the given vertex.
return (_split_edge(e, v, cv1, cv2));
}
//-----------------------------------------------------------------------------
// Split a given edge into two at a given vertex, and associate the given
// x-monotone curves with the split edges.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::DHalfedge*
Arrangement_on_surface_2<GeomTraits, TopTraits>::
_split_edge(DHalfedge* e, DVertex* v,
const X_monotone_curve_2& cv1, const X_monotone_curve_2& cv2)
{
// Get the split halfedge and its twin, its source and target.
DHalfedge* he1 = e;
DHalfedge* he2 = he1->opposite();
DInner_ccb* ic1 = (he1->is_on_inner_ccb()) ? he1->inner_ccb() : nullptr;
DOuter_ccb* oc1 = (ic1 == nullptr) ? he1->outer_ccb() : nullptr;
DInner_ccb* ic2 = (he2->is_on_inner_ccb()) ? he2->inner_ccb() : nullptr;
DOuter_ccb* oc2 = (ic2 == nullptr) ? he2->outer_ccb() : nullptr;
// Notify the observers that we are about to split an edge.
_notify_before_split_edge(Halfedge_handle(e), Vertex_handle(v), cv1, cv2);
// Allocate a pair of new halfedges.
DHalfedge* he3 = _dcel().new_edge();
DHalfedge* he4 = he3->opposite();
// Connect the new halfedges:
//
// he1 he3
// -------> ------->
// (.) (.)v (.)
// <------- <-------
// he2 he4
//
v->set_halfedge(he4);
if (he1->next() != he2) {
// Connect e3 between e1 and its successor.
he3->set_next(he1->next());
// Insert he4 between he2 and its predecessor.
he2->prev()->set_next(he4);
}
else
// he1 and he2 form an "antenna", so he4 becomes he3's successor.
he3->set_next(he4);
if (oc1 != nullptr)
he3->set_outer_ccb(oc1);
else
he3->set_inner_ccb(ic1);
he3->set_vertex(he1->vertex());
he4->set_vertex(v);
he4->set_next(he2);
if (oc2 != nullptr)
he4->set_outer_ccb(oc2);
else
he4->set_inner_ccb(ic2);
if (he1->vertex()->halfedge() == he1)
// If he1 is the incident halfedge to its target, he3 replaces it.
he1->vertex()->set_halfedge(he3);
// Update the properties of the twin halfedges we have just split.
he1->set_next(he3);
he1->set_vertex(v);
// The direction of he3 is the same as he1's (and the direction of he4 is
// the same as he2).
he3->set_direction(he1->direction());
// Associate cv1 with he1 (and its twin). We allocate a new curve for cv2
// and associate it with he3 (and its twin).
X_monotone_curve_2* dup_cv2 = _new_curve(cv2);
he1->curve() = cv1;
he3->set_curve(dup_cv2);
// Notify the observers that we have split an edge into two.
_notify_after_split_edge(Halfedge_handle(he1), Halfedge_handle(he3));
// Return a handle for one of the existing halfedge that is incident to the
// split point.
return he1;
}
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::
_compute_indices(Arr_parameter_space /* ps_x_curr */,
Arr_parameter_space /* ps_y_curr */,
Arr_parameter_space /* ps_x_next */,
Arr_parameter_space /* ps_y_next */,
int& /* x_index */, int& /* y_index */,
boost::mpl::bool_<false>) const
{ /* nothing if no identification */ }
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::
_compute_indices(Arr_parameter_space ps_x_curr, Arr_parameter_space ps_y_curr,
Arr_parameter_space ps_x_next, Arr_parameter_space ps_y_next,
int& x_index, int& y_index, boost::mpl::bool_<true>) const
{
// If we cross the identification curve in x, then we must update the
// x_index. Note that a crossing takes place in the following cases:
// . .
// . .
// . .
// . v he he . v
// <-------(.)<--------- -------->(.)------->
// . .
// (BEFORE) . (AFTER) (BEFORE) . (AFTER)
// x_index-1. x_index x_index . x_index+1
//
if ((ps_x_curr == ARR_LEFT_BOUNDARY) && (ps_x_next == ARR_RIGHT_BOUNDARY)) {
CGAL_assertion(is_identified(Left_side_category()) &&
is_identified(Right_side_category()));
--x_index; // in "negative" u-direction
}
else if ((ps_x_curr == ARR_RIGHT_BOUNDARY) &&
(ps_x_next == ARR_LEFT_BOUNDARY))
{
CGAL_assertion(is_identified(Left_side_category()) &&
is_identified(Right_side_category()));
++x_index; // in "positive" u-direction
}
// Check if we cross the identification curve in y.
if ((ps_y_curr == ARR_BOTTOM_BOUNDARY) && (ps_y_next == ARR_TOP_BOUNDARY)) {
CGAL_assertion(is_identified(Bottom_side_category()) &&
is_identified(Top_side_category()));
--y_index; // in "negative" v-direction
}
else if ((ps_y_curr == ARR_TOP_BOUNDARY) &&
(ps_y_next == ARR_BOTTOM_BOUNDARY))
{
CGAL_assertion(is_identified(Bottom_side_category()) &&
is_identified(Top_side_category()));
++y_index; // in "positive" v-direction
}
}
// Computes signs and locale minima of an open path to be closed by a
// newly inserted curve.
//
// Precondition The OutputIterator must be a back inserter.
// Precondition The traveresed ccb is an inner ccb; thus, it cannot be
// on an open boundary.
// Postcondition If nullptr is a local minimum, it is inserted first.
// No other local minima can be nullptr.
template <typename GeomTraits, typename TopTraits>
template <typename OutputIterator>
std::pair<Sign, Sign>
Arrangement_on_surface_2<GeomTraits, TopTraits>::
_compute_signs_and_local_minima(const DHalfedge* he_to,
const X_monotone_curve_2& cv,
Arr_halfedge_direction cv_dir,
const DHalfedge* he_away,
OutputIterator local_mins_it) const
{
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "he_to: " << he_to->opposite()->vertex()->point()
<< " => " << he_to->vertex()->point() << std::endl;
std::cout << "cv: " << cv << std::endl;
std::cout << "cv_dir: " << cv_dir << std::endl;
std::cout << "he_away: " << he_away->opposite()->vertex()->point()
<< " => " << he_away->vertex()->point() << std::endl;
#endif
// We go over the sequence of vertices, starting from he_away's target
// vertex, until reaching he_to's source vertex, and find the leftmost
// one. Note that we do this carefully, keeping track of the number of
// times we crossed the identification curve in x or in y (if they exist).
// Note that the path must not be incident to any vertex on open boundary.
typename Traits_adaptor_2::Parameter_space_in_x_2 parameter_space_in_x =
m_geom_traits->parameter_space_in_x_2_object();
typename Traits_adaptor_2::Parameter_space_in_y_2 parameter_space_in_y =
m_geom_traits->parameter_space_in_y_2_object();
// TODO 2012-09-20 check "correction" here too (as in "other" function of this kind
int x_index = 0;
int y_index = 0;
// Obtain the parameter space pair of cv.
Arr_curve_end cv_to_end =
(cv_dir == ARR_LEFT_TO_RIGHT) ? ARR_MIN_END : ARR_MAX_END;
Arr_parameter_space ps_x_cv_to = parameter_space_in_x(cv, cv_to_end);
Arr_parameter_space ps_y_cv_to = parameter_space_in_y(cv, cv_to_end);
Arr_curve_end cv_away_end =
(cv_dir == ARR_LEFT_TO_RIGHT) ? ARR_MAX_END : ARR_MIN_END;
Arr_parameter_space ps_x_cv_away = parameter_space_in_x(cv, cv_away_end);
Arr_parameter_space ps_y_cv_away = parameter_space_in_y(cv, cv_away_end);
// Obtain the parameter space pair of he_to and he_away
Arr_curve_end he_to_tgt_end =
(he_to->direction() == ARR_LEFT_TO_RIGHT) ? ARR_MAX_END : ARR_MIN_END;
Arr_parameter_space ps_x_he_to =
parameter_space_in_x(he_to->curve(), he_to_tgt_end);
Arr_parameter_space ps_y_he_to =
parameter_space_in_y(he_to->curve(), he_to_tgt_end);
Arr_curve_end he_away_src_end =
(he_away->direction() == ARR_LEFT_TO_RIGHT) ? ARR_MIN_END : ARR_MAX_END;
Arr_parameter_space ps_x_he_away =
parameter_space_in_x(he_away->curve(), he_away_src_end);
Arr_parameter_space ps_y_he_away =
parameter_space_in_y(he_away->curve(), he_away_src_end);
Arr_curve_end he_away_tgt_end =
(he_away->direction() == ARR_LEFT_TO_RIGHT) ? ARR_MAX_END : ARR_MIN_END;
Arr_parameter_space ps_x_he_away_tgt =
parameter_space_in_x(he_away->curve(), he_away_tgt_end);
Arr_parameter_space ps_y_he_away_tgt =
parameter_space_in_y(he_away->curve(), he_away_tgt_end);
Arr_parameter_space ps_x_curr, ps_y_curr;
Arr_parameter_space ps_x_next, ps_y_next;
Arr_parameter_space ps_x_save, ps_y_save;
ps_x_curr = ps_x_cv_away;
ps_y_curr = ps_y_cv_away;
ps_x_next = ps_x_he_away;
ps_y_next = ps_y_he_away;
ps_x_save = ps_x_he_away_tgt;
ps_y_save = ps_y_he_away_tgt;
CGAL_assertion(!is_open(ps_x_curr, ps_y_curr));
CGAL_assertion(!is_open(ps_x_next, ps_y_next));
if ((cv_dir == ARR_RIGHT_TO_LEFT) &&
(he_away->direction() == ARR_LEFT_TO_RIGHT)) {
const DHalfedge* null_he = nullptr;
*local_mins_it++ = std::make_pair(null_he, x_index);
}
_compute_indices(ps_x_curr, ps_y_curr, ps_x_next, ps_y_next,
x_index, y_index, Has_identified_sides_category());
const DHalfedge* he = he_away;
while (he != he_to) {
ps_x_curr = ps_x_save;
ps_y_curr = ps_y_save;
CGAL_assertion(!is_open(ps_x_curr, ps_y_curr));
Arr_curve_end he_next_src_end, he_next_tgt_end;
if (he->next()->direction() == ARR_LEFT_TO_RIGHT) {
he_next_src_end = ARR_MIN_END;
he_next_tgt_end = ARR_MAX_END;
}
else {
he_next_src_end = ARR_MAX_END;
he_next_tgt_end = ARR_MIN_END;
}
ps_x_next = parameter_space_in_x(he->next()->curve(), he_next_src_end);
ps_y_next = parameter_space_in_y(he->next()->curve(), he_next_src_end);
CGAL_assertion(!is_open(ps_x_next, ps_y_next));
ps_x_save = parameter_space_in_x(he->next()->curve(), he_next_tgt_end);
ps_y_save = parameter_space_in_y(he->next()->curve(), he_next_tgt_end);
// If the halfedge is directed from right to left and its successor is
// directed from left to right, the target vertex might be the smallest:
if ((he->direction() == ARR_RIGHT_TO_LEFT) &&
(he->next()->direction() == ARR_LEFT_TO_RIGHT))
*local_mins_it++ = std::make_pair(he, x_index);
_compute_indices(ps_x_curr, ps_y_curr, ps_x_next, ps_y_next,
x_index, y_index, Has_identified_sides_category());
// Move to the next halfedge.
he = he->next();
}
ps_x_curr = ps_x_he_to;
ps_y_curr = ps_y_he_to;
ps_x_next = ps_x_cv_to;
ps_y_next = ps_y_cv_to;
CGAL_assertion(!is_open(ps_x_curr, ps_y_curr));
CGAL_assertion(!is_open(ps_x_next, ps_y_next));
if ((he_to->direction() == ARR_RIGHT_TO_LEFT) &&
(cv_dir == ARR_LEFT_TO_RIGHT))
*local_mins_it++ = std::make_pair(he_to, x_index);
_compute_indices(ps_x_curr, ps_y_curr, ps_x_next, ps_y_next, x_index, y_index,
Has_identified_sides_category());
return (std::make_pair(CGAL::sign(x_index), CGAL::sign(y_index)));
}
// Computes the signs of a closed ccb (loop) when deleting he_anchor and its
// opposite belonging to different faces for the case where non of the
// boundaries is identified, thus, return the pair (ZERO, ZERO)
template <typename GeomTraits, typename TopTraits>
std::pair<Sign, Sign>
Arrangement_on_surface_2<GeomTraits, TopTraits>::
_compute_signs(const DHalfedge* /* he_anchor */, boost::mpl::bool_<false>) const
{ return (std::make_pair(ZERO, ZERO)); }
// Computes the signs of a closed ccb (loop) when deleting he_anchor and its
// opposite belonging to different faces.
template <typename GeomTraits, typename TopTraits>
std::pair<Sign, Sign>
Arrangement_on_surface_2<GeomTraits, TopTraits>::
_compute_signs(const DHalfedge* he_anchor, boost::mpl::bool_<true>) const
{
// We go over the sequence of vertices, starting from he_before's target
// vertex, until reaching he_after's source vertex, and find the leftmost
// one. Note that we do this carefully, keeping track of the number of
// times we crossed the identification curve in x or in y (if they exist).
// Note that the path must not be incident to any vertex on open boundary.
typename Traits_adaptor_2::Parameter_space_in_x_2 parameter_space_in_x =
m_geom_traits->parameter_space_in_x_2_object();
typename Traits_adaptor_2::Parameter_space_in_y_2 parameter_space_in_y =
m_geom_traits->parameter_space_in_y_2_object();
// typename Traits_adaptor_2::Compare_y_at_x_right_2 compare_y_at_x_right_2 =
// m_geom_traits->compare_y_at_x_right_2_object();
// IDEA EBEB 2012-07-28 store indices of local_minima with CCB in DCEL:
// - determine values upon insertion of a curve
// - or if this is not possible, perform the following computation
// on-demand only
// init with edges at first link
// assuming that he_anchor has been removed
const DHalfedge* he_curr = he_anchor;
CGAL_assertion(! he_curr->has_null_curve());
const DHalfedge* he_next = he_anchor->next();
// init edge where loop should end
const DHalfedge* he_end = he_anchor;
int x_index = 0;
int y_index = 0;
// obtain the parameter space pair of he_curr
Arr_curve_end he_curr_tgt_end =
(he_curr->direction() == ARR_LEFT_TO_RIGHT) ? ARR_MAX_END : ARR_MIN_END;
Arr_parameter_space ps_x_save =
parameter_space_in_x(he_curr->curve(), he_curr_tgt_end);
Arr_parameter_space ps_y_save =
parameter_space_in_y(he_curr->curve(), he_curr_tgt_end);
Arr_parameter_space ps_x_curr, ps_y_curr;
Arr_parameter_space ps_x_next, ps_y_next;
// start loop
do {
ps_x_curr = ps_x_save;
ps_y_curr = ps_y_save;
CGAL_assertion(!is_open(ps_x_curr, ps_y_curr));
Arr_curve_end he_next_src_end =
(he_next->direction() == ARR_LEFT_TO_RIGHT) ? ARR_MIN_END : ARR_MAX_END;
ps_x_next = parameter_space_in_x(he_next->curve(), he_next_src_end);
ps_y_next = parameter_space_in_y(he_next->curve(), he_next_src_end);
CGAL_assertion(!is_open(ps_x_next, ps_y_next));
Arr_curve_end he_next_tgt_end =
(he_next->direction() == ARR_LEFT_TO_RIGHT) ? ARR_MAX_END : ARR_MIN_END;
ps_x_save = parameter_space_in_x(he_next->curve(), he_next_tgt_end);
ps_y_save = parameter_space_in_y(he_next->curve(), he_next_tgt_end);
_compute_indices(ps_x_curr, ps_y_curr, ps_x_next, ps_y_next,
x_index, y_index, Has_identified_sides_category());
// iterate
he_curr = he_next;
he_next = he_next->next();
} while (he_curr != he_end);
// Return the leftmost vertex and its x_index (with respect to he_before).
return (std::make_pair(CGAL::sign(x_index), CGAL::sign(y_index)));
}
// Computes the halfedge that points at the smallest vertex in a closed ccb
// when deleting he_anchor and its opposite belonging to same face
// (loop-about-to-split).
template <typename GeomTraits, typename TopTraits>
std::pair<std::pair<Sign, Sign>,
const typename Arrangement_on_surface_2<GeomTraits,
TopTraits>::DHalfedge*>
Arrangement_on_surface_2<GeomTraits, TopTraits>::
_compute_signs_and_min(const DHalfedge* he_anchor,
Arr_parameter_space& ps_x_min,
Arr_parameter_space& ps_y_min,
int& index_min) const
{
// Initialize
const DHalfedge* he_min = nullptr;
ps_x_min = ARR_INTERIOR;
ps_y_min = ARR_INTERIOR;
index_min = 0;
// We go over the sequence of vertices, starting from he_before's target
// vertex, until reaching he_after's source vertex, and find the leftmost
// one. Note that we do this carefully, keeping track of the number of
// times we crossed the identification curve in x or in y (if they exist).
// Note that the path must not be incident to any vertex on open boundary.
typename Traits_adaptor_2::Parameter_space_in_x_2 parameter_space_in_x =
m_geom_traits->parameter_space_in_x_2_object();
typename Traits_adaptor_2::Parameter_space_in_y_2 parameter_space_in_y =
m_geom_traits->parameter_space_in_y_2_object();
// init with edges at first link.
// assuming that he_anchor has been removed
const DHalfedge* he_curr = he_anchor->opposite()->prev();
const DHalfedge* he_next = he_anchor->next();
// init edge where loop should end
const DHalfedge* he_end = he_anchor->opposite();
int x_index = 0;
int y_index = 0;
// obtain the parameter space pair of he_curr
Arr_parameter_space ps_x_save, ps_y_save;
if (he_curr->has_null_curve()) {
ps_x_save = he_curr->vertex()->parameter_space_in_x();
ps_y_save = he_curr->vertex()->parameter_space_in_y();
}
else {
Arr_curve_end he_curr_tgt_end =
(he_curr->direction() == ARR_LEFT_TO_RIGHT) ? ARR_MAX_END : ARR_MIN_END;
ps_x_save = parameter_space_in_x(he_curr->curve(), he_curr_tgt_end);
ps_y_save = parameter_space_in_y(he_curr->curve(), he_curr_tgt_end);
}
// TODO EBEB 2012-09-20 check whether this fix is correct
// EBEB 2012-08-22 the 'start' of one (out of two) loops might
// be directed towards the identification.
// In this cases, we have to adapt the index:
int x_correction = 0;
if (ps_x_save == ARR_RIGHT_BOUNDARY) {
x_correction--;
}
Arr_parameter_space ps_x_curr, ps_y_curr;
Arr_parameter_space ps_x_next, ps_y_next;
// Start loop
do {
ps_x_curr = ps_x_save;
ps_y_curr = ps_y_save;
if (he_next->has_null_curve()) {
ps_x_next = he_next->opposite()->vertex()->parameter_space_in_x();
ps_y_next = he_next->opposite()->vertex()->parameter_space_in_y();
ps_x_save = he_next->vertex()->parameter_space_in_x();
ps_y_save = he_next->vertex()->parameter_space_in_y();
}
else {
Arr_curve_end he_next_src_end =
(he_next->direction() == ARR_LEFT_TO_RIGHT) ? ARR_MIN_END : ARR_MAX_END;
ps_x_next = parameter_space_in_x(he_next->curve(), he_next_src_end);
ps_y_next = parameter_space_in_y(he_next->curve(), he_next_src_end);
Arr_curve_end he_next_tgt_end =
(he_next->direction() == ARR_LEFT_TO_RIGHT) ? ARR_MAX_END : ARR_MIN_END;
ps_x_save = parameter_space_in_x(he_next->curve(), he_next_tgt_end);
ps_y_save = parameter_space_in_y(he_next->curve(), he_next_tgt_end);
}
// If the halfedge is directed from right to left and its successor is
// directed from left to right, the target vertex might be the smallest:
if ((he_curr->direction() == ARR_RIGHT_TO_LEFT) &&
(he_next->direction() == ARR_LEFT_TO_RIGHT))
{
const int index_curr = x_index + x_correction;
// Test the halfedge incident to the leftmost vertex.
// Note that we may visit the same vertex several times.
if ((he_min == nullptr) ||
(index_curr < index_min) ||
((index_curr == index_min) &&
((he_curr->vertex() != he_min->vertex()) &&
_is_smaller(he_curr, ps_x_curr, ps_y_curr,
he_min, ps_x_min, ps_y_min,
Are_all_sides_oblivious_category()))))
{
index_min = index_curr;
ps_x_min = ps_x_curr;
ps_y_min = ps_y_curr;
he_min = he_curr;
}
}
_compute_indices(ps_x_curr, ps_y_curr, ps_x_next, ps_y_next,
x_index, y_index, Has_identified_sides_category());
// iterate
he_curr = he_next;
he_next = he_next->next();
CGAL_assertion(he_curr != he_anchor);
} while (he_next != he_end);
// Return the leftmost vertex and the signs.
return std::make_pair(std::make_pair(CGAL::sign(x_index), CGAL::sign(y_index)), he_min);
}
/* This is the implementation for the case where all 4 boundary sides are
* oblivious.
*/
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_is_smaller(const DHalfedge* he1,
Arr_parameter_space /* ps_x1 */, Arr_parameter_space /* ps_y1 */,
const DHalfedge* he2,
Arr_parameter_space /* ps_x2 */, Arr_parameter_space /* ps_y2 */,
Arr_all_sides_oblivious_tag) const
{
CGAL_precondition(he1->direction() == ARR_RIGHT_TO_LEFT);
CGAL_precondition(he2->direction() == ARR_RIGHT_TO_LEFT);
CGAL_precondition(he1->vertex() != he2->vertex());
return
(m_geom_traits->compare_xy_2_object()(he1->vertex()->point(),
he2->vertex()->point()) == SMALLER);
}
/* This is a wrapper for the case where any boundary side is not
* necessarily oblivious.
*/
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_is_smaller(const DHalfedge* he1,
Arr_parameter_space ps_x1, Arr_parameter_space ps_y1,
const DHalfedge* he2,
Arr_parameter_space ps_x2, Arr_parameter_space ps_y2,
Arr_not_all_sides_oblivious_tag tag) const
{
CGAL_precondition(he1->direction() == ARR_RIGHT_TO_LEFT);
CGAL_precondition(he2->direction() == ARR_RIGHT_TO_LEFT);
CGAL_precondition(he1->vertex() != he2->vertex());
/* If he1 points to a vertex on the left or the bottom boundary, then it
* is the smaller.
*/
if ((ps_x1 == ARR_LEFT_BOUNDARY) || (ps_y1 == ARR_BOTTOM_BOUNDARY))
return true;
/* If he2 points to a vertex on the left or the bottom boundary, then it
* is the smaller.
*/
if ((ps_x2 == ARR_LEFT_BOUNDARY) || (ps_y2 == ARR_BOTTOM_BOUNDARY))
return false;
return _is_smaller(he1->curve(), he1->vertex()->point(), ps_x1, ps_y1,
he2->curve(), he2->vertex()->point(), ps_x2, ps_y2, tag);
}
/* This is the implementation for the case where all 4 boundary sides are
* oblivious.
*/
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_is_smaller(const X_monotone_curve_2& /* cv1 */, const Point_2& p1,
Arr_parameter_space /* ps_x1 */, Arr_parameter_space /* ps_y1 */,
const X_monotone_curve_2& /* cv2 */, const Point_2& p2,
Arr_parameter_space /* ps_x2 */, Arr_parameter_space /* ps_y2 */,
Arr_all_sides_oblivious_tag) const
{
CGAL_precondition(! m_geom_traits->equal_2_object()(p1, p2));
return (m_geom_traits->compare_xy_2_object()(p1, p2) == SMALLER);
}
/*! This is the implementation for the case where any boundary side is not
* necessarily oblivious.
* This can be further refined as the combination of LEFT and LEFT can occur
* only when the right and left boundary sides are identified.
*/
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_is_smaller(const X_monotone_curve_2& cv1, const Point_2& p1,
Arr_parameter_space ps_x1, Arr_parameter_space ps_y1,
const X_monotone_curve_2& cv2, const Point_2& p2,
Arr_parameter_space ps_x2, Arr_parameter_space ps_y2,
Arr_not_all_sides_oblivious_tag) const
{
CGAL_precondition(! m_geom_traits->equal_2_object()(p1, p2));
if (ps_x2 == ARR_INTERIOR) {
if (ps_x1 == ARR_INTERIOR) {
if (ps_y2 == ARR_INTERIOR) {
if (ps_y1 == ARR_INTERIOR)
return (m_geom_traits->compare_xy_2_object()(p1,p2) == SMALLER);
// ps1 == {INTERIOR, !INTERIOR}, ps2 == {INTERIOR,INTERIOR},
Comparison_result res =
m_geom_traits->compare_x_on_boundary_2_object()(p2, cv1, ARR_MIN_END);
return
(res == EQUAL) ? (ps_y1 == ARR_BOTTOM_BOUNDARY) : (res == LARGER);
}
if (ps_y1 == ARR_INTERIOR) {
// ps1 == {INTERIOR,INTERIOR}, ps2 == {INTERIOR,!INTERIOR}
Comparison_result res =
m_geom_traits->compare_x_on_boundary_2_object()(p1, cv2, ARR_MIN_END);
return (res == EQUAL) ? (ps_y2 == ARR_TOP_BOUNDARY) : (res == SMALLER);
}
// ps1 == {INTERIOR,!INTERIOR}, ps2 == {INTERIOR,!INTERIOR}
Comparison_result res =
m_geom_traits->compare_x_on_boundary_2_object()(cv1, ARR_MIN_END,
cv2, ARR_MIN_END);
return (res == EQUAL) ?
((ps_y1 == ARR_BOTTOM_BOUNDARY) && (ps_y2 == ARR_TOP_BOUNDARY)) :
(res == SMALLER);
}
// ps_x2 == ARR_INTERIOR, ps_x == ARR_LEFT_BOUNDARY
CGAL_assertion(ps_x1 == ARR_LEFT_BOUNDARY);
return true;
}
if (ps_x1 == ARR_INTERIOR)
// ps_x2 == ARR_LEFT_BOUNDARY, ps_x == ARR_INTERIOR
return false;
// ps_x2 == ARR_LEFT_BOUNDARY, ps_x == ARR_LEFT_BOUNDARY
Comparison_result res =
m_geom_traits->compare_y_on_boundary_2_object()(p1, p2);
return (res == SMALLER);
}
/* This is the implementation for the case where all 4 boundary sides are
* oblivious.
*/
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_is_smaller_near_right(const X_monotone_curve_2& cv1,
const X_monotone_curve_2& cv2,
const Point_2& p,
Arr_parameter_space /* ps_x */,
Arr_parameter_space /* ps_y */,
Arr_all_sides_oblivious_tag) const
{
return
(m_geom_traits->compare_y_at_x_right_2_object()(cv1, cv2, p) == SMALLER);
}
/*! This is the implementation for the case where any one of the 4 boundary
* sides can be of any type.
*/
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_is_smaller_near_right(const X_monotone_curve_2& cv1,
const X_monotone_curve_2& cv2,
const Point_2& p,
Arr_parameter_space ps_x, Arr_parameter_space ps_y,
Arr_not_all_sides_oblivious_tag) const
{
CGAL_precondition((ps_x == ARR_INTERIOR) || (ps_x == ARR_LEFT_BOUNDARY));
CGAL_precondition((ps_y == ARR_INTERIOR) || (ps_x == ARR_BOTTOM_BOUNDARY));
if ((ps_x == ARR_INTERIOR) && (ps_y == ARR_INTERIOR))
return
(m_geom_traits->compare_y_at_x_right_2_object()(cv1, cv2, p) == SMALLER);
return
(m_geom_traits->compare_y_near_boundary_2_object()(cv1, cv2, ARR_MIN_END) ==
SMALLER);
}
//-----------------------------------------------------------------------------
// Determine whether a given subsequence (halfedge, curve, halfedge)
// lies in the interior of a new face we are about to create
// Comment: This is how the situation looks
// ----to---> >>cv_dir>> ---away--->
// o ===cv=== 0
// <-tonext-- <-awaynext-
// or to be read from right to left ... this way, he_to and he_away lie
// BEFORE insertion on the same inner ccb and
// AFTER insertion on the same outer ccb
//
// Precondition: The range of local minima [lm_begin,lm_end) is greater than 0.
// That is, there is at least one local minimum, which might be the leftend
// of cv itself.
// Precondition: If the leftend of cv is a local minimum, it must be the first
// in the range.
template <typename GeomTraits, typename TopTraits>
template <typename InputIterator>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_defines_outer_ccb_of_new_face(const DHalfedge* he_to,
const X_monotone_curve_2& cv,
const DHalfedge* he_away,
InputIterator lm_begin,
InputIterator lm_end) const
{
// Search for the leftmost vertex among the local minima
typename Traits_adaptor_2::Parameter_space_in_x_2 parameter_space_in_x =
m_geom_traits->parameter_space_in_x_2_object();
typename Traits_adaptor_2::Parameter_space_in_y_2 parameter_space_in_y =
m_geom_traits->parameter_space_in_y_2_object();
// check all reported local minima
InputIterator lm_it = lm_begin;
int index_min = lm_it->second;
const DHalfedge* he_min = lm_it->first;
const DVertex* v_min =
(he_min == nullptr) ? he_away->opposite()->vertex() : he_min->vertex();
const X_monotone_curve_2* cv_min =
(he_min == nullptr) ? &cv : &(he_min->curve());
Arr_parameter_space ps_x_min = parameter_space_in_x(*cv_min, ARR_MIN_END);
Arr_parameter_space ps_y_min = parameter_space_in_y(*cv_min, ARR_MIN_END);
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "1 set global min to " << *cv_min << std::endl;
#endif
for (++lm_it; lm_it != lm_end; ++lm_it) {
const DHalfedge* he = lm_it->first;
CGAL_assertion(he->direction() == CGAL::ARR_RIGHT_TO_LEFT);
int index = lm_it->second;
Arr_parameter_space ps_x_he_min =
parameter_space_in_x(he->curve(), ARR_MIN_END);
Arr_parameter_space ps_y_he_min =
parameter_space_in_y(he->curve(), ARR_MIN_END);
// If the following condition is met, the vertex is indeed the smallest:
// The current x_index is smaller than the x_index of the smallest
// recorded, or
// The current x_index is equivalent to the recorded x_index, and
// - No smallest has bin recorded so far, or
// - The current target vertex and the recorded vertex are the same and
// * The current curve is smaller than the recorded curve, or
// - The current curve end is smaller then the recorded curve end.
// smaller than its source, so we should check whether it is also smaller
// Note that we compare the vertices lexicographically: first by the
// indices, then by x, then by y.
if ((index < index_min) ||
((index == index_min) &&
((v_min == he->vertex()) ?
_is_smaller_near_right(he->curve(), *cv_min,
v_min->point(), ps_x_min, ps_y_min,
Are_all_sides_oblivious_category()) :
_is_smaller(he->curve(), he->vertex()->point(),
ps_x_he_min, ps_y_he_min,
*cv_min, v_min->point(), ps_x_min, ps_y_min,
Are_all_sides_oblivious_category()))))
{
index_min = index;
cv_min = &(he->curve());
ps_x_min = ps_x_he_min;
ps_y_min = ps_y_he_min;
he_min = he;
v_min = he->vertex();
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "2 set global min to " << *cv_min << std::endl;
#endif
}
}
CGAL_assertion(v_min != nullptr);
CGAL_assertion(!v_min->has_null_point());
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "v_min: " << v_min->point() << std::endl;
std::cout << "he_min: ";
if (he_min)
std::cout << he_min->opposite()->vertex()->point()
<< " => " << he_min->vertex()->point();
else std::cout << "nullptr";
std::cout << std::endl;
#endif
CGAL_assertion(! he_min || (he_min->direction() == ARR_RIGHT_TO_LEFT));
// Note that the curves of the leftmost edge and its successor are defined
// to the right of the leftmost vertex. We compare them to the right of this
// point to determine whether he_to (the curve) and he_away are incident to
// the hole to be created or not.
const X_monotone_curve_2& cv_next = (he_min == nullptr) ?
he_away->curve() : ((he_min == he_to) ? cv : he_min->next()->curve());
return _is_above(*cv_min, cv_next, v_min->point(), ps_y_min,
Top_or_bottom_sides_category());
}
// Is the first given x-monotone curve above the second given?
// This function is invoked when the bottom and top boundaries are neither
// identified nor contracted
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_is_above(const X_monotone_curve_2& xcv1, const X_monotone_curve_2& xcv2,
const Point_2& point,
Arr_parameter_space /* ps_y1 */,
Arr_boundary_cond_tag) const
{
return (m_geom_traits->compare_y_at_x_right_2_object()(xcv1, xcv2, point) ==
LARGER);
}
// Is the first given x-monotone curve above the second given?
// This function is invoked when the bottom and top boundaries are identified
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_is_above(const X_monotone_curve_2& xcv1, const X_monotone_curve_2& xcv2,
const Point_2& point,
Arr_parameter_space ps_y1,
Arr_has_identified_side_tag) const
{
// Check whether the vertex lies on the identification curve in y,
// in which case special care must be taken.
if ((ps_y1 == ARR_BOTTOM_BOUNDARY) || (ps_y1 == ARR_TOP_BOUNDARY)) {
// TODO EBEB 2010-10-08 is this code really executed or should it be part
// of top traits?
// Both current and next curves are incident to the identification curve.
// As v_min is the leftmost vertex, we know that their left ends must have
// a boundary condition of type identification in y.
Arr_parameter_space ps_y2 =
m_geom_traits->parameter_space_in_y_2_object()(xcv2, ARR_MIN_END);
// Check if the curves lie on opposite sides of the identification curve.
if ((ps_y1 == ARR_BOTTOM_BOUNDARY) && (ps_y2 == ARR_TOP_BOUNDARY))
// In this case the current curve is "above" the next one to the right
// of v_min, in a cyclic order around the identification curve.
return true;
if ((ps_y1 == ARR_TOP_BOUNDARY) && (ps_y2 == ARR_BOTTOM_BOUNDARY))
// In this case the current curve is "below" the next one to the right
// of v_min, in a cyclic order around the identification curve.
return false;
// If both curves are on the same side of the identification curve, we
// continue to compare them to the right of v_min.
CGAL_assertion(((ps_y1 == ARR_BOTTOM_BOUNDARY) &&
(ps_y2 == ARR_BOTTOM_BOUNDARY)) ||
((ps_y1 == ARR_TOP_BOUNDARY) &&
(ps_y2 == ARR_TOP_BOUNDARY)));
}
return _is_above(xcv1, xcv2, point, ps_y1, Arr_all_sides_oblivious_tag());
}
// Is the first given x-monotone curve above the second given?
// This function is invoked when the bottom or top boundaries are contracted
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_is_above(const X_monotone_curve_2& xcv1, const X_monotone_curve_2& xcv2,
const Point_2& point,
Arr_parameter_space ps_y1,
Arr_has_contracted_side_tag) const
{
// Check whether the leftmost vertex is a contraction point in y,
// in which case special care must be taken.
if (((ps_y1 == ARR_TOP_BOUNDARY) && is_contracted(Bottom_side_category())) ||
((ps_y1 == ARR_BOTTOM_BOUNDARY) && is_contracted(Top_side_category())))
{
// Compare the horizontal position of the two curve-ends at the point
// of contraction.
Comparison_result x_res =
m_geom_traits->compare_x_curve_ends_2_object()(xcv1, ARR_MIN_END,
xcv2, ARR_MIN_END);
// Observe that if x_res == EQUAL the given subsequence is always exterior.
return (((ps_y1 == ARR_BOTTOM_BOUNDARY) && (x_res == SMALLER)) ||
((ps_y1 == ARR_TOP_BOUNDARY) && (x_res == LARGER)));
}
return _is_above(xcv1, xcv2, point, ps_y1, Arr_all_sides_oblivious_tag());
}
//-----------------------------------------------------------------------------
// Remove a pair of twin halfedges from the arrangement.
// In case the removal causes the creation of a new hole, the given halfedge
// should point at this hole.
//
template <typename GeomTraits, typename TopTraits>
typename Arrangement_on_surface_2<GeomTraits, TopTraits>::DFace*
Arrangement_on_surface_2<GeomTraits, TopTraits>::
_remove_edge(DHalfedge* e, bool remove_source, bool remove_target)
{
// Obtain the pair of twin edges to be removed, the connected components they
// belong to and their incident faces.
DHalfedge* he1 = e;
DHalfedge* he2 = e->opposite();
DInner_ccb* ic1 = (he1->is_on_inner_ccb()) ? he1->inner_ccb() : nullptr;
DOuter_ccb* oc1 = (ic1 == nullptr) ? he1->outer_ccb() : nullptr;
DFace* f1 = (oc1 != nullptr) ? oc1->face() : ic1->face();
DInner_ccb* ic2 = (he2->is_on_inner_ccb()) ? he2->inner_ccb() : nullptr;
DOuter_ccb* oc2 = (ic2 == nullptr) ? he2->outer_ccb() : nullptr;
DFace* f2 = (oc2 != nullptr) ? oc2->face() : ic2->face();
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
#if 0
std::cout << "before swap" << std::endl;
std::cout << "he1c: " << he1->curve() << ", " << he1->direction()
<< std::endl;
std::cout << "he2c: " << he2->curve() << ", " << he2->direction()
<< std::endl;
std::cout << "he1: " << he1 << std::endl;
std::cout << "he2: " << he2 << std::endl;
std::cout << "ic1: " << ic1 << std::endl;
std::cout << "ic2: " << ic2 << std::endl;
std::cout << "oc1: " << oc1 << std::endl;
std::cout << "oc2: " << oc2 << std::endl;
std::cout << "f1 : " << f1 << std::endl;
std::cout << "f2 : " << f2 << std::endl;
#endif
#endif
// will be used for "_hole_creation_on_edge_removal"
std::pair< CGAL::Sign, CGAL::Sign > signs1(ZERO, ZERO);
std::pair< CGAL::Sign, CGAL::Sign > signs2(ZERO, ZERO);
bool swap_he1_he2 = false;
if (f1 != f2) {
// If f1 != f2, the removal of he1 (and its twin halfedge) will cause
// the two incident faces to merge. Thus, swapping is not needed. However,
// it is more efficient to retain the face that has a larger number of
// inner ccbs.
// f1 is the face to be kept by default. If f2 has more holes it is more
// efficient to kept f2
if (f1->number_of_inner_ccbs() < f2->number_of_inner_ccbs())
swap_he1_he2 = true;
}
else {
// If f1 == f2 (same_face-case), then we consider two loops that occur when
// he1 and he2 get removed; if f1 != f2, then he1 and he2 separates the two
// faces that will be merged upon their removal---here both he1 and he2
// belong to a full cycle, and THAT IS WHY we give the f1 == f2 test to
// determine whether end of loop should be he1->opposite() and
// he2->opposite(), respectively.
// If the removal of he1 (and its twin halfedge) form an "antenna", there
// is neither a need to compute signs and nor swapping of the halfedges
if ((he1->next() != he2) && (he2->next() != he1)) {
// In this case one of the following can happen: (a) a new hole will be
// created by the removal of the edge (case 3.2.1 of the removal
// procedure), or (b) an outer CCB will be split into two (case 3.2.2).
// We begin by locating the leftmost vertex along the path from he1 to its
// twin he2 and the leftmost vertex point along the path from the twin to
// he1 (both paths do not include he1 and he2 themselves).
// Comment EFEF 2013-05-31: if we ever find the need to use signs1 and
// signs2 out of this scope (for the non-planar case), the code must be
// dispatched, so that the planar case is not affected.
// Compute signs of ccbs for he1 and he2 used later for
// _hole_creation_on_edge_removal
// Compute the signs and minimum along ccb of he1:
Arr_parameter_space ps_x_min1, ps_y_min1;
int index_min1;
std::pair<std::pair<Sign, Sign>, const DHalfedge*> res1 =
_compute_signs_and_min(he1, ps_x_min1, ps_y_min1, index_min1);
signs1 = res1.first;
const DHalfedge* he_min1 = res1.second;
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "signs1.x: " << signs1.first << std::endl;
std::cout << "signs1.y: " << signs1.second << std::endl;
if (! he_min1->has_null_curve())
std::cout << "he_min1: " << he_min1->curve() << std::endl;
else std::cout << "he_min1 fictitious" << std::endl;
#endif
// Compute the signs and minimum along ccb of he2:
Arr_parameter_space ps_x_min2, ps_y_min2;
int index_min2;
std::pair<std::pair<Sign, Sign>, const DHalfedge*> res2 =
_compute_signs_and_min(he2, ps_x_min2, ps_y_min2, index_min2);
signs2 = res2.first;
const DHalfedge* he_min2 = res2.second;
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "signs2.x: " << signs2.first << std::endl;
std::cout << "signs2.y: " << signs2.second << std::endl;
if (! he_min2->has_null_curve())
std::cout << "he_min2: " << he_min2->curve() << std::endl;
else std::cout << "he_min2 fictitious" << std::endl;
#endif
// TODO EBEB 2012-07-29
// is this the right thing to do for torus, or let TopTraits decide?
bool is_perimetric1 = signs1.first || signs1.second;
bool is_perimetric2 = signs2.first || signs2.second;
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << std::endl
<< "index 1: " << index_min1
<< ", ps_x_min1: " << ps_x_min1
<< ", ps_y_min1: " << ps_y_min1
<< ", is_perimetric1: " << is_perimetric1
<< std::endl;
std::cout << "index 2: " << index_min2
<< ", ps_x_min2: " << ps_x_min2
<< ", ps_y_min2: " << ps_y_min2
<< ", is_perimetric2: " << is_perimetric2
<< std::endl;
#endif
if (is_perimetric1 || is_perimetric2) {
#if 1 // this is old code
swap_he1_he2 =
(! is_perimetric1) ? false :
((! is_perimetric2) ? true : false);
// We are in case (a) and he1 is directed to the new hole to be
// created or
// We are in case (a) and he2 is directed to the new hole to be
// created.
// Both paths are perimetric; thus, we are in case (b).
#else // THIS IS NEW CODE 2012-08-06 which is much easier to read
swap_he1_he2 = !is_perimetric2;
#endif
}
else {
// const DVertex* v_min1 = he_min1->vertex(); const DVertex* v_min2 =
// he_min2->vertex(); Both paths from he1 to he2 and back from he2 to
// he1 are not perimetric, so we are in case (a). As we want to
// determine which halfedge points to the new hole to be created (he1
// or he2), we have to compare the two leftmost vertices
// lexicographically, first by the indices then by x and y. v_min2
// lies to the left of v_min1 if and only if he1 points at the hole we
// are about to create.
//
// +---------------------+
// | |
// | he1 +----+ |
// +--------->+ | |
// | +----+ |
// | v_min1 |
// | |
// v_min2 +---------------------+
//
// Note that if one of the paths we have examined ends at a boundary
// side of the parameter space (and only of the paths may end at a
// boundary side of the parameter space), then the other path becomes
// a hole in a face bounded by the parameter-space boundary.
// TODO EBEB 2012-08-22 check whether this fix is correct
// EBEB 2012-08-22 the 'start' of the two loops might lie
// on different sides of the identification, which is only
// problematic when either he1 or he2 points to the
// identification. In these cases, we have to adapt the indices:
typename Traits_adaptor_2::Parameter_space_in_x_2
parameter_space_in_x =
m_geom_traits->parameter_space_in_x_2_object();
Arr_curve_end he1_tgt_end =
(he1->direction() == ARR_LEFT_TO_RIGHT ? ARR_MAX_END : ARR_MIN_END);
Arr_parameter_space ps_x_he1_tgt =
parameter_space_in_x(he1->curve(), he1_tgt_end);
if (ps_x_he1_tgt == ARR_RIGHT_BOUNDARY) index_min2 -= 1;
Arr_curve_end he2_tgt_end =
(he2->direction() == ARR_LEFT_TO_RIGHT ? ARR_MAX_END : ARR_MIN_END);
Arr_parameter_space ps_x_he2_tgt =
parameter_space_in_x(he2->curve(), he2_tgt_end);
if (ps_x_he2_tgt == ARR_RIGHT_BOUNDARY) index_min1 -= 1;
swap_he1_he2 =
(index_min1 > index_min2) ? false :
((index_min1 < index_min2) ? true :
_is_smaller(he_min1, ps_x_min1, ps_y_min1,
he_min2, ps_x_min2, ps_y_min2,
Are_all_sides_oblivious_category()));
}
}
}
// swapping?
if (swap_he1_he2) {
// swap all entries
std::swap(he1, he2);
std::swap(ic1, ic2);
std::swap(oc1, oc2);
std::swap(f1 , f2);
// not needed below here std::swap(local_mins1, local_mins2);
std::swap(signs1, signs2);
}
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
#if 0
std::cout << "after swap" << std::endl;
std::cout << "he1c: " << he1->curve() << ", " << he1->direction()
<< std::endl;
std::cout << "he1c: " << he2->curve() << ", " << he2->direction()
<< std::endl;
std::cout << "he1: " << he1 << std::endl;
std::cout << "he2: " << he2 << std::endl;
std::cout << "ic1: " << ic1 << std::endl;
std::cout << "ic2: " << ic2 << std::endl;
std::cout << "oc1: " << oc1 << std::endl;
std::cout << "oc2: " << oc2 << std::endl;
std::cout << "f1 : " << f1 << std::endl;
std::cout << "f2 : " << f2 << std::endl;
#endif
#endif
// Now the real removal starts.
DHalfedge* prev1 = nullptr;
DHalfedge* prev2 = nullptr;
// Notify the observers that we are about to remove an edge.
Halfedge_handle hh(e);
_notify_before_remove_edge(hh);
// Check if the two incident faces are equal, in which case no face will be
// merged and deleted (and a hole may be created).
if (f1 == f2) {
// Check whether the two halfedges are successors along the face boundary.
if ((he1->next() == he2) && (he2->next() == he1)) {
CGAL_assertion((ic1 != nullptr) && (ic1 == ic2));
// The two halfedges form a "singleton" hole inside the incident face
// (case 1 of the removal procedure, as detailed in the design document),
// so we simply have to remove it.
// Notify before the removal of this hole (inner CCB).
// Erase the inner CCB from the incident face.
// Delete the corresponding component.
// Notify after the removal.
Face_handle fh(f1);
_notify_before_remove_inner_ccb(fh, (Halfedge_handle(he1))->ccb());
f1->erase_inner_ccb(ic1);
_dcel().delete_inner_ccb(ic1);
_notify_after_remove_inner_ccb(fh);
DVertex* v1 = he1->vertex();
DVertex* v2 = he2->vertex();
_delete_curve(he1->curve());
_dcel().delete_edge(he1);
#ifndef CGAL_NON_SYMETRICAL_OBSERVER_EDGE_REMOVAL_BACKWARD_COMPATIBILITY
_notify_after_remove_edge();
#endif
// Remove the end-vertices, if necessary.
if (remove_target) {
if ((v1->parameter_space_in_x() != ARR_INTERIOR) ||
(v1->parameter_space_in_y() != ARR_INTERIOR))
{
v1->set_halfedge(nullptr); // disconnect the end vertex
_remove_vertex_if_redundant(v1, f1);
}
else {
// Delete the he1's target vertex and its associated point.
_notify_before_remove_vertex(Vertex_handle(v1));
_delete_point(v1->point());
_dcel().delete_vertex(v1);
_notify_after_remove_vertex();
}
}
else
// The remaining target vertex now becomes an isolated vertex inside
// the containing face:
_insert_isolated_vertex(f1, v1);
if (remove_source) {
if ((v2->parameter_space_in_x() != ARR_INTERIOR) ||
(v2->parameter_space_in_y() != ARR_INTERIOR))
{
v2->set_halfedge(nullptr); // disconnect the end vertex
_remove_vertex_if_redundant(v2, f1);
}
else {
// Delete the he1's source vertex and its associated point.
_notify_before_remove_vertex(Vertex_handle(v2));
_delete_point(v2->point());
_dcel().delete_vertex(v2);
_notify_after_remove_vertex();
}
}
else
// The remaining source vertex now becomes an isolated vertex inside
// the containing face:
_insert_isolated_vertex(f1, v2);
#ifdef CGAL_NON_SYMETRICAL_OBSERVER_EDGE_REMOVAL_BACKWARD_COMPATIBILITY
_notify_after_remove_edge();
#endif
// Return the face that used to contain the hole.
return f1;
}
if ((he1->next() == he2) || (he2->next() == he1)) {
CGAL_assertion((oc1 == oc2) && (ic1 == ic2));
// In this case the two halfedges form an "antenna" (case 2).
// Make he1 point at the tip of this "antenna" (swap the pointer if
// necessary).
bool remove_tip_vertex = remove_target;
if (he2->next() == he1) {
he1 = he2;
he2 = he1->opposite();
remove_tip_vertex = remove_source;
}
// Remove the two halfedges from the boundary chain by connecting
// he1's predecessor with he2's successor.
prev1 = he1->prev();
prev1->set_next(he2->next());
// In case the halfedges to be deleted are represantatives of their
// CCB (note that noth should belong to the same CCB, be it an outer
// CCB or an inner one), make prev1 the components representative.
if ((oc1 != nullptr) &&
((oc1->halfedge() == he1) || (oc1->halfedge() == he2)))
oc1->set_halfedge(prev1);
else if ((ic1 != nullptr) &&
((ic1->halfedge() == he1) || (ic1->halfedge() == he2)))
ic1->set_halfedge(prev1);
// In case he2 is the representative halfedge of its target vertex,
// replace it by prev1 (which also points at this vertex).
if (he2->vertex()->halfedge() == he2)
he2->vertex()->set_halfedge(prev1);
DVertex* v1 = he1->vertex();
DVertex* v2 = he2->vertex();
_delete_curve(he1->curve());
_dcel().delete_edge(he1);
#ifndef CGAL_NON_SYMETRICAL_OBSERVER_EDGE_REMOVAL_BACKWARD_COMPATIBILITY
_notify_after_remove_edge();
#endif
// Try to temove the base vertex, in case it has boundary conditions.
if ((v2->parameter_space_in_x() != ARR_INTERIOR) ||
(v2->parameter_space_in_y() != ARR_INTERIOR))
_remove_vertex_if_redundant(v2, f1);
// Remove the redundant tip vertex, if necessary.
if (remove_tip_vertex) {
if ((v1->parameter_space_in_x() != ARR_INTERIOR) ||
(v1->parameter_space_in_y() != ARR_INTERIOR))
{
v1->set_halfedge(nullptr); // disconnect the end vertex
_remove_vertex_if_redundant(v1, f1);
}
else {
// Delete the vertex that forms the tip of the "antenna".
_notify_before_remove_vertex(Vertex_handle(v1));
_delete_point(v1->point());
_dcel().delete_vertex(v1);
_notify_after_remove_vertex();
}
}
else
// The remaining "antenna" tip now becomes an isolated vertex inside
// the containing face:
_insert_isolated_vertex(f1, v1);
#ifdef CGAL_NON_SYMETRICAL_OBSERVER_EDGE_REMOVAL_BACKWARD_COMPATIBILITY
_notify_after_remove_edge();
#endif
// Return the incident face.
return f1;
}
// In this case the degree of both end-vertices is at least 2, so we
// can use the two predecessor halfedges of he1 and he2.
bool add_inner_ccb = false;
prev1 = he1->prev();
prev2 = he2->prev();
if ((ic1 != nullptr) && (ic1 == ic2)) {
// If both halfedges lie on the same inner component (hole) inside the
// face (case 3.1), we have to split this component into two holes.
//
// +-----------------------------+
// | prev1 |
// | +----+ / +----+ |
// | | +......+ | |
// | +----+ +----+ |
// | |
// +-----------------------------+
//
// Notify the observers we are about to split an inner CCB.
_notify_before_split_inner_ccb(Face_handle(f1),
(Halfedge_handle
(*(ic1->iterator())))->ccb(),
Halfedge_handle(he1));
// We first make prev1 the new representative halfedge of the first
// inner CCB.
ic1->set_halfedge(prev1);
// Create a new component that represents the new hole we split.
DInner_ccb* new_ic = _dcel().new_inner_ccb();
f1->add_inner_ccb(new_ic, prev2);
new_ic->set_face(f1);
// Associate all halfedges along the hole boundary with the new inner
// component.
DHalfedge* curr;
for (curr = he1->next(); curr != he2; curr = curr->next())
curr->set_inner_ccb(new_ic);
// Notify the observers that the hole has been split.
_notify_after_split_inner_ccb(Face_handle(f1),
(Halfedge_handle(prev1))->ccb(),
(Halfedge_handle(prev2))->ccb());
}
else if (oc1 != oc2) {
// RWRW: NEW!
CGAL_assertion((oc1 != nullptr) && (oc2 != nullptr));
// In case both halfegdes he1 and he2 are incident to the same face
// but lie on different outer CCBs of this face, removing this pair of
// halfedge causes the two components two merge and to become an
// inner CCB in the face.
// We first remove the outer CCB oc1 from f, and inform the observers
// on doing so.
Face_handle fh(f1);
_notify_before_remove_outer_ccb(fh, (Halfedge_handle(he1))->ccb());
f1->erase_outer_ccb(oc1);
_dcel().delete_outer_ccb(oc1);
_notify_after_remove_outer_ccb(fh);
// We now remove the outer CCBs oc2 from f, and inform the observers
// on doing so.
_notify_before_remove_outer_ccb(fh, (Halfedge_handle(he2))->ccb());
f2->erase_outer_ccb(oc2);
_dcel().delete_outer_ccb(oc2);
_notify_after_remove_outer_ccb(fh);
// Mark that we should eventually add a new inner CCB inside the face.
add_inner_ccb = true;
}
else {
CGAL_assertion((oc1 != nullptr) && (oc1 == oc2));
// If both halfedges are incident to the same outer CCB of their
// face (case 3.2), we have to distinguish two sub-cases:
// TODO EBEB 2012-07-30 replace with signs
if (_hole_creation_on_edge_removal(signs1, signs2, true)) {
// We have to create a new hole in the interior of the incident face
// (case 3.2.1):
//
// +-----------------------------+
// | prev1 |
// v +----+ |
// +........>+ | |
// | he1 +----+ |
// | |
// +-----------------------------+
//
// Note that it is guaranteed that he1 points at this new hole, while
// he2 points at the boundary of the face that contains this hole.
// First notify the observers we are about to form a new inner
// CCB inside f1.
_notify_before_add_inner_ccb(Face_handle(f1),
Halfedge_handle(he1->next()));
// Create a new component that represents the new hole.
DInner_ccb* new_ic = _dcel().new_inner_ccb();
f1->add_inner_ccb(new_ic, he1->next());
new_ic->set_face(f1);
// Associate all halfedges along the hole boundary with the new inner
// component.
DHalfedge* curr;
for (curr = he1->next(); curr != he2; curr = curr->next())
curr->set_inner_ccb(new_ic);
// As the outer CCB of f1 may be represented by any of the
// halfedges in between he1 -> ... -> he2 (the halfedges in between
// represent the outer boundary of the new hole that is formed),
// We represent the outer boundary of f1 by prev1, which definitely
// stays on the outer boundary.
oc1->set_halfedge(prev1);
// Notify the observers that a new hole has been formed.
Ccb_halfedge_circulator hccb = (Halfedge_handle(he1->next()))->ccb();
_notify_after_add_inner_ccb(hccb);
}
else {
// We have to split the outer CCB into two outer components
// (case 3.2.2), such that the number of outer CCBs of the face is
// incremented.
//
// +----------------------------+
// | |
// | prev1 |
// +<........+<.................|
// | | |
// | | |
// | | |
// | | |
// | prev2 | |
// +........>+..................|
// | |
// +----------------------------+
//
// First we notify the observers that we are about to split an outer
// component.
_notify_before_split_outer_ccb(Face_handle(f1),
Halfedge_handle(he1)->ccb(),
Halfedge_handle(he1));
// Create a new outer component.
DOuter_ccb* new_oc = _dcel().new_outer_ccb();
f1->add_outer_ccb(new_oc, he1->next());
new_oc->set_face(f1);
// Associate all halfedges from he1 until he2 with the new CCB.
DHalfedge* curr;
for (curr = he1->next(); curr != he2; curr = curr->next())
curr->set_outer_ccb(new_oc);
// As the outer CCB of f1 may be represented by any of the
// halfedges in between he1 -> ... -> he2 (the halfedges in between
// are on the new outer CCB we have just created), we represent the
// former outer CCB by prev1, which definitely stays on it.
oc1->set_halfedge(prev1);
// Notify the observers that a new outer CCB has been formed.
_notify_after_split_outer_ccb(Face_handle(f1),
Halfedge_handle(he1->next())->ccb(),
Halfedge_handle(prev1)->ccb());
}
}
// Disconnect the two halfedges we are about to delete from the edge list.
prev1->set_next(he2->next());
prev2->set_next(he1->next());
// If one of these edges is an incident halfedge of its target vertex,
// replace it by the appropriate predecessor.
if (he1->vertex()->halfedge() == he1)
he1->vertex()->set_halfedge(prev2);
if (he2->vertex()->halfedge() == he2)
he2->vertex()->set_halfedge(prev1);
DVertex* v1 = he1->vertex();
DVertex* v2 = he2->vertex();
_delete_curve(he1->curve());
_dcel().delete_edge(he1);
// RWRW: NEW!
// In case we have to create a new inner CCB inside the face (new removal
// case), do it now.
if (add_inner_ccb) {
// Notify the observers that we are about to create a new inner CCB
// inside the merged face.
Halfedge_handle hh(prev1);
_notify_before_add_inner_ccb(Face_handle(f1), hh);
// Initiate a new inner CCB inside the given face.
DInner_ccb* new_ic = _dcel().new_inner_ccb();
f1->add_inner_ccb(new_ic, prev1);
new_ic->set_face(f1);
// Set the innser CCB of the halfedges along the component boundary.
DHalfedge* curr = prev1;
do {
curr->set_inner_ccb(new_ic);
curr = curr->next();
} while (curr != prev1);
// Notify the observers that we have formed a new inner CCB.
_notify_after_add_inner_ccb(hh->ccb());
}
#ifndef CGAL_NON_SYMETRICAL_OBSERVER_EDGE_REMOVAL_BACKWARD_COMPATIBILITY
_notify_after_remove_edge();
#endif
// Remove the end vertices, in case they become redundant.
// We defer the removal of the end vertices (in case they are indeed
// redundant) to occur after the observer is notified that the edge has
// been removed, to match the case where the end vertices are associated
// with concrete points, and need to be removed as they became isolated
// vertices, and the user has requested the removal of isolated end vertices.
if ((v1->parameter_space_in_x() != ARR_INTERIOR) ||
(v1->parameter_space_in_y() != ARR_INTERIOR))
_remove_vertex_if_redundant(v1, f1);
if ((v2->parameter_space_in_x() != ARR_INTERIOR) ||
(v2->parameter_space_in_y() != ARR_INTERIOR))
_remove_vertex_if_redundant(v2, f1);
#ifdef CGAL_NON_SYMETRICAL_OBSERVER_EDGE_REMOVAL_BACKWARD_COMPATIBILITY
_notify_after_remove_edge();
#endif
// Return the incident face.
return f1;
}
CGAL_assertion(f1 != f2);
// The two incident faces are not the same - in this case, the edge we are
// about to delete separates these two faces. We therefore have to delete
// one of these faces and merge it with the other face.
// First notify the observers we are about to merge the two faces.
_notify_before_merge_face(Face_handle(f1), Face_handle(f2),
Halfedge_handle(he1));
// We begin by checking whether one of the faces is a hole inside the other
// face.
DHalfedge* curr;
prev1 = he1->prev();
prev2 = he2->prev();
CGAL_assertion((ic1 == nullptr) || (ic2 == nullptr));
if ((ic1 == nullptr) && (ic2 == nullptr)) {
bool add_inner_ccb = false;
// Comment EFEF 2013-05-31: if we ever find the need to use signs1 and
// signs2 out of this scope (for the non-planar case), the code must be
// dispatched, so that the planar case is not affected.
// Compute the signs of the ccbs for he1 and he2.
// The signs are computed here, a sub case of (f1 != f2), in addition to
// the case (f1 == f2) above. This way unnecessary computations of the
// signs are avoided.
// EFEF 2013-07-29. The call to _compute_signs() is dispatched.
// Currently, only 2 cases are supported, namely, the case where non of
// the boundaries are identified and the case where at least one pair of
// opposite boundaries are identified. However, the code for the latter
// assumes that non of the (other) boundaries is open. A 3rd version
// that supports the remaining case, (for example the cylinder), should
// be developed and used.
signs1 = _compute_signs(he1, Has_identified_sides_category());
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "signs1.x: " << signs1.first << std::endl;
std::cout << "signs1.y: " << signs1.second << std::endl;
#endif
signs2 = _compute_signs(he2, Has_identified_sides_category());
#if CGAL_ARRANGEMENT_ON_SURFACE_INSERT_VERBOSE
std::cout << "signs2.x: " << signs2.first << std::endl;
std::cout << "signs2.y: " << signs2.second << std::endl;
#endif
// Both halfedges lie on the outer boundary of their incident faces
// (case 3.4). We have to distinguish two possible sub-cases.
// TODO EBEB 2012-07-30 replace with signs
if (_hole_creation_on_edge_removal(signs1, signs2, false)) {
// We have to remove the outer CCBs of f1 and f2 that he1 and he2 lie
// on, and create a new hole in the merged face (case 3.4.2).
// We first remove the outer CCB oc1 from f1, and inform the observers
// on doing so.
_notify_before_remove_outer_ccb(Face_handle(f1),
(Halfedge_handle(he1))->ccb());
f1->erase_outer_ccb(oc1);
_dcel().delete_outer_ccb(oc1);
_notify_after_remove_outer_ccb(Face_handle(f1));
// We now remove the outer CCBs oc2 from f2, and inform the observers
// on doing so.
_notify_before_remove_outer_ccb(Face_handle(f2),
(Halfedge_handle(he2))->ccb());
f2->erase_outer_ccb(oc2);
_dcel().delete_outer_ccb(oc2);
_notify_after_remove_outer_ccb(Face_handle(f2));
// Mark that we should eventually add a new inner CCB in the merged face.
add_inner_ccb = true;
}
else {
// f1 and f2 are two adjacent faces (case 3.4.1), so we simply merge
// them.
// We first set the connected component of f2's outer-boundary halfedges
// to be the same as f1's outer component.
for (curr = he2->next(); curr != he2; curr = curr->next())
curr->set_outer_ccb(oc1);
}
_move_all_inner_ccb(f2, f1); // move all inner CCBs from f2 to f1
// In case he1, which is about to be deleted, is a representative
// halfedge of outer component of f1, we replace it by its predecessor.
if (oc1->halfedge() == he1)
oc1->set_halfedge(prev1);
_move_all_isolated_vertices(f2, f1); // move all iso vertices from f2 to f1
// If he1 or he2 are the incident halfedges to their target vertices,
// we replace them by the appropriate predecessors.
if (he1->vertex()->halfedge() == he1)
he1->vertex()->set_halfedge(prev2);
if (he2->vertex()->halfedge() == he2)
he2->vertex()->set_halfedge(prev1);
// Disconnect the two halfedges we are about to delete from the edge
// list.
prev1->set_next(he2->next());
prev2->set_next(he1->next());
// If the face f2 we have just merged with f1 is unbounded, then the
// merged face is also unbounded.
if (f2->is_unbounded())
f1->set_unbounded(true);
// Delete the face f2.
_dcel().delete_face(f2);
// Notify the observers that the faces have been merged.
_notify_after_merge_face(Face_handle(f1));
DVertex* v1 = he1->vertex();
DVertex* v2 = he2->vertex();
_delete_curve(he1->curve());
_dcel().delete_edge(he1);
// In case we have to create a new inner CCB inside the merged face
// (case 3.4.1), do it now.
if (add_inner_ccb) {
// Notify the observers that we are about to create a new inner CCB
// inside the merged face.
Halfedge_handle hh(prev1);
_notify_before_add_inner_ccb(Face_handle(f1), hh);
// Initiate a new inner CCB inside the given face.
DInner_ccb* new_ic = _dcel().new_inner_ccb();
f1->add_inner_ccb(new_ic, prev1);
new_ic->set_face(f1);
// Set the innser CCB of the halfedges along the component boundary.
curr = prev1;
do {
curr->set_inner_ccb(new_ic);
curr = curr->next();
} while (curr != prev1);
// Notify the observers that we have formed a new inner CCB.
_notify_after_add_inner_ccb(hh->ccb());
}
#ifndef CGAL_NON_SYMETRICAL_OBSERVER_EDGE_REMOVAL_BACKWARD_COMPATIBILITY
_notify_after_remove_edge();
#endif
// Remove the end vertices, in case they become redundant.
// We defer the removal of the end vertices (in case they are indeed
// redundant) to occur after the observer is notified that the edge has
// been removed, to match the case where the end vertices are associated
// with concrete points, and need to be removed as they became isolated
// vertices, and the user has requested the removal of isolated end vertices.
if ((v1->parameter_space_in_x() != ARR_INTERIOR) ||
(v1->parameter_space_in_y() != ARR_INTERIOR))
_remove_vertex_if_redundant(v1, f1);
if ((v2->parameter_space_in_x() != ARR_INTERIOR) ||
(v2->parameter_space_in_y() != ARR_INTERIOR))
_remove_vertex_if_redundant(v2, f1);
#ifdef CGAL_NON_SYMETRICAL_OBSERVER_EDGE_REMOVAL_BACKWARD_COMPATIBILITY
_notify_after_remove_edge();
#endif
// Return the merged face.
return f1;
}
// In this case we merge a face with another face that now forms a hole
// inside it (case 3.3). We first make sure that f1 contains the hole f2, so
// we can merge f2 with it (we swap roles between the halfedges if
// necessary).
if (ic2 != nullptr) {
he1 = he2;
he2 = he1->opposite();
ic1 = ic2;
ic2 = nullptr;
oc2 = oc1;
oc1 = nullptr;
DFace* tf = f1;
f1 = f2;
f2 = tf;
prev1 = he1->prev();
prev2 = he2->prev();
}
// By removing the edge we open a closed face f2 contained in f1. By doing
// this, the outer boundary of f2 unites with the hole boundary that ic1
// represents. We therefore have to set the component of all halfedges
// along the boundary of f2 to be ic1.
for (curr = he2->next(); curr != he2; curr = curr->next())
curr->set_inner_ccb(ic1);
_move_all_inner_ccb(f2, f1); // move the inner CCBs from f2 to f1
_move_all_isolated_vertices(f2, f1); // move all iso vertices from f2 to f1
// Notice that f2 will be merged with f1, but its boundary will still be
// a hole inside this face. In case he1 is a represantative of this hole,
// replace it by its predecessor.
if (ic1->halfedge() == he1)
ic1->set_halfedge(prev1);
// If he1 or he2 are the incident halfedges to their target vertices,
// we replace them by the appropriate predecessors.
if (he1->vertex()->halfedge() == he1)
he1->vertex()->set_halfedge(prev2);
if (he2->vertex()->halfedge() == he2)
he2->vertex()->set_halfedge(prev1);
// Disconnect the two halfedges we are about to delete from the edge
// list.
prev1->set_next(he2->next());
prev2->set_next(he1->next());
// If the face f2 we have just merged with f1 is unbounded, then the merged
// face is also unbounded.
if (f2->is_unbounded())
f1->set_unbounded(true);
// Delete the face f2.
_dcel().delete_face(f2);
// Notify the observers that the faces have been merged.
_notify_after_merge_face(Face_handle(f1));
DVertex* v1 = he1->vertex();
DVertex* v2 = he2->vertex();
_delete_curve(he1->curve());
_dcel().delete_edge(he1);
#ifndef CGAL_NON_SYMETRICAL_OBSERVER_EDGE_REMOVAL_BACKWARD_COMPATIBILITY
_notify_after_remove_edge();
#endif
// Remove the end vertices, in case they become redundant.
// We defer the removal of the end vertices (in case they are indeed
// redundant) to occur after the observer is notified that the edge has
// been removed, to match the case where the end vertices are associated
// with concrete points, and need to be removed as they became isolated
// vertices, and the user has requested the removal of isolated end vertices.
if ((v1->parameter_space_in_x() != ARR_INTERIOR) ||
(v1->parameter_space_in_y() != ARR_INTERIOR))
_remove_vertex_if_redundant(v1, f1);
if ((v2->parameter_space_in_x() != ARR_INTERIOR) ||
(v2->parameter_space_in_y() != ARR_INTERIOR))
_remove_vertex_if_redundant(v2, f1);
#ifdef CGAL_NON_SYMETRICAL_OBSERVER_EDGE_REMOVAL_BACKWARD_COMPATIBILITY
_notify_after_remove_edge();
#endif
// Return the merged face.
return f1;
// TODO EBEB 2012-08-06 it seems that a torus case is missing
}
// Decide whether a hole is created
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_hole_creation_on_edge_removal(std::pair< CGAL::Sign, CGAL::Sign > signs1,
std::pair< CGAL::Sign, CGAL::Sign > signs2,
bool same_face) {
// EBEB 2013-07-16 Remark: For tiled surfaces, this function has to respect the
// topology of the tiled surface
// TODO EBEB 2013-07-16 Add code for torus (double identification)
CGAL::Sign sign1 = signs1.first;
CGAL::Sign sign2 = signs2.first;
if (same_face) return true;
return ((CGAL::ZERO != sign1) && (sign1 == opposite(sign2)));
}
//-----------------------------------------------------------------------------
// Remove a vertex in case it becomes redundant after the deletion of an
// incident edge.
//
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::
_remove_vertex_if_redundant(DVertex* v, DFace* f)
{
CGAL_precondition((v->parameter_space_in_x() != ARR_INTERIOR) ||
(v->parameter_space_in_y() != ARR_INTERIOR));
// In case the vertex has no incident halfedges, remove it if it is
// redundant. Otherwise, make it an isolated vertex.
if (v->halfedge() == nullptr) {
if (m_topol_traits.is_redundant(v)) {
// Remove the vertex and notify the observers on doing so.
_notify_before_remove_vertex(Vertex_handle(v));
m_topol_traits.erase_redundant_vertex(v);
// Note the topology traits do not free the vertex - we now do it.
if (! v->has_null_point())
_delete_point(v->point());
_dcel().delete_vertex(v);
_notify_after_remove_vertex();
}
else
// Keep the vertex as an isolated one.
_insert_isolated_vertex(f, v);
return;
}
// Get the first two incident halfedges of v.
DHalfedge* he1 = v->halfedge();
DHalfedge* he2 = he1->next()->opposite();
if (he2->next()->opposite() != he1)
// In this case there are more than two incident edges, so v obviously
// cannot be removed.
return;
if (! he1->has_null_curve() || ! he2->has_null_curve())
// We can only merge fictitious halfedges.
return;
// Now check if the vertex is redundant. If it is, remove it by merging
// its two incident fictitious halfedges.
if (m_topol_traits.is_redundant(v)) {
// Use the topology traits to merge the two fictitious halfedges.
_notify_before_merge_fictitious_edge(Halfedge_handle(he1),
Halfedge_handle(he2));
he1 = m_topol_traits.erase_redundant_vertex(v);
_notify_after_merge_fictitious_edge(Halfedge_handle(he1));
// Note the topology traits do not free the vertex - we now do it.
_notify_before_remove_vertex(Vertex_handle(v));
if (! v->has_null_point())
_delete_point(v->point());
_dcel().delete_vertex(v);
_notify_after_remove_vertex();
}
}
//-----------------------------------------------------------------------------
// Remove an isolated vertex from the interior of a given face (but not from
// the DCEL).
//
template <typename GeomTraits, typename TopTraits>
void Arrangement_on_surface_2<GeomTraits, TopTraits>::
_remove_isolated_vertex(DVertex* v)
{
// Remove the isolated vertex from the face and delete its record.
DIso_vertex* iv = v->isolated_vertex();
DFace* f = iv->face();
f->erase_isolated_vertex(iv);
_dcel().delete_isolated_vertex(iv);
}
//---------------------------------------------------------------------------
// Check whether the arrangement is valid. In particular, check the
// validity of each vertex, halfedge, and face.
//
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::is_valid() const
{
Vertex_const_iterator vit;
bool is_vertex_valid;
for (vit = vertices_begin(); vit != vertices_end(); ++vit) {
is_vertex_valid = _is_valid(vit);
if (!is_vertex_valid) {
CGAL_warning_msg(is_vertex_valid, "Invalid vertex.");
return false;
}
}
Halfedge_const_iterator heit;
bool is_halfedge_valid;
for (heit = halfedges_begin(); heit != halfedges_end(); ++heit) {
is_halfedge_valid = _is_valid(heit);
if (! is_halfedge_valid) {
CGAL_warning_msg(is_halfedge_valid, "Invalid halfedge.");
return false;
}
}
Face_const_iterator fit;
bool is_face_valid;
for (fit = faces_begin(); fit != faces_end(); ++fit) {
is_face_valid = _is_valid(fit);
if (! is_face_valid) {
CGAL_warning_msg(is_face_valid, "Invalid face.");
return false;
}
}
bool are_vertices_unique = _are_vertices_unique();
if (! are_vertices_unique) {
CGAL_warning_msg(are_vertices_unique,
"Found two vertices with the same geometric point.");
return false;
}
// If we reached here, the arrangement is valid.
return true;
}
//---------------------------------------------------------------------------
// Check the validity of a vertex.
//
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_is_valid(Vertex_const_handle v) const
{
// Do not check isolated vertices, as they have no incident halfedges.
if (v->is_isolated()) return true;
// Make sure that the vertex is the target of all its incident halfedges.
Halfedge_around_vertex_const_circulator circ = v->incident_halfedges();
Halfedge_around_vertex_const_circulator start = circ;
do {
if (circ->target() != v) return false;
++circ;
} while (circ != start);
// In case of a non-boundary vertex, make sure the curves are correctly
// ordered around this vertex.
if ((v->parameter_space_in_x() == ARR_INTERIOR) &&
(v->parameter_space_in_y() == ARR_INTERIOR))
{
if (! _are_curves_ordered_cw_around_vertrex(v)) return false;
}
return true;
}
//---------------------------------------------------------------------------
// Check the validity of a halfedge.
//
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_is_valid(Halfedge_const_handle he) const
{
// Check relations with the previous and the next halfedges.
if (he->prev()->target() != he->source()) return false;
if (he->target() != he->next()->source()) return false;
// Check relations with the twin.
if (he != he->twin()->twin()) return false;
if (he->source() != he->twin()->target() ||
he->target() != he->twin()->source())
return false;
if (he->direction() == he->twin()->direction()) return false;
// Stop here in case of a fictitious edge.
if (he->is_fictitious()) return true;
// Check that the end points of the curve associated with the halfedge
// really equal the source and target vertices of this halfedge.
const X_monotone_curve_2& cv = he->curve();
const DVertex* source = _vertex(he->source());
const DVertex* target = _vertex(he->target());
Comparison_result res = ((source->parameter_space_in_x() == ARR_INTERIOR) &&
(source->parameter_space_in_y() == ARR_INTERIOR) &&
(target->parameter_space_in_x() == ARR_INTERIOR) &&
(target->parameter_space_in_y() == ARR_INTERIOR)) ?
m_geom_traits->compare_xy_2_object()(source->point(), target->point()) :
((he->direction() == ARR_LEFT_TO_RIGHT) ? SMALLER : LARGER);
if (res == SMALLER) {
if (he->direction() != ARR_LEFT_TO_RIGHT)
return false;
return (_are_equal(_vertex(he->source()), cv, ARR_MIN_END) &&
_are_equal(_vertex(he->target()), cv, ARR_MAX_END));
}
else if (res == LARGER) {
if (he->direction() != ARR_RIGHT_TO_LEFT)
return false;
return (_are_equal(_vertex(he->source()), cv, ARR_MAX_END) &&
_are_equal(_vertex(he->target()), cv, ARR_MIN_END));
}
// In that case, the source and target of the halfedge are equal.
return false;
}
//---------------------------------------------------------------------------
// Check the validity of a face.
//
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_is_valid(Face_const_handle f) const
{
// Check if all outer components of the face refer to f.
const DFace* p_f = _face(f);
DOuter_ccb_const_iter oc_it;
const DHalfedge* he;
const DOuter_ccb* oc;
for (oc_it = p_f->outer_ccbs_begin(); oc_it != p_f->outer_ccbs_end(); ++oc_it)
{
he = *oc_it;
if (he->is_on_inner_ccb()) return false;
oc = he->outer_ccb();
if (oc->face() != p_f) return false;
if (! _is_outer_ccb_valid(oc, he)) return false;
}
// Check if all inner components of the face refer to f.
DInner_ccb_const_iter ic_it;
const DInner_ccb* ic;
for (ic_it = p_f->inner_ccbs_begin(); ic_it != p_f->inner_ccbs_end(); ++ic_it)
{
he = *ic_it;
if (! he->is_on_inner_ccb()) return false;
ic = he->inner_ccb();
if (ic->face() != p_f) return false;
if (! _is_inner_ccb_valid(ic, he)) return false;
}
// Check if all isolated vertices inside the face refer to f.
DIso_vertex_const_iter iv_it;
const DVertex* v;
const DIso_vertex* iv;
for (iv_it = p_f->isolated_vertices_begin();
iv_it != p_f->isolated_vertices_end(); ++iv_it)
{
v = &(*iv_it);
if (! v->is_isolated()) return false;
iv = v->isolated_vertex();
if (iv->face() != p_f) return false;
}
// If we reached here, the face is valid.
return true;
}
//---------------------------------------------------------------------------
// Check the validity of an outer CCB.
//
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_is_outer_ccb_valid(const DOuter_ccb* oc, const DHalfedge* first) const
{
// Make sure that all halfedges along the CCB refer to the same component.
const DHalfedge* curr = first;
bool found_rep = false;
do {
if (curr->is_on_inner_ccb()) return false;
if (oc != curr->outer_ccb()) return false;
if (! found_rep && oc->halfedge() == curr) found_rep = true;
curr = curr->next();
} while (curr != first);
// Return if we found the CCB representative along the outer CCB.
return found_rep;
}
//---------------------------------------------------------------------------
// Check the validity of an inner CCB.
//
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_is_inner_ccb_valid(const DInner_ccb* ic, const DHalfedge* first) const
{
// Make sure that all halfedges along the CCB refer to the same component.
const DHalfedge* curr = first;
bool found_rep = false;
do {
if (! curr->is_on_inner_ccb()) return false;
if (ic != curr->inner_ccb()) return false;
if (! found_rep && ic->halfedge() == curr) found_rep = true;
curr = curr->next();
} while (curr != first);
// Return if we found the CCB representative along the inner CCB.
return found_rep;
}
//---------------------------------------------------------------------------
// Check that all vertices are unique (no two vertices with the same
// geometric point).
//
template <typename GeomTraits, typename TopTraits>
bool
Arrangement_on_surface_2<GeomTraits, TopTraits>::_are_vertices_unique() const
{
if (number_of_vertices() < 2) return true;
// Store all points associated with non-boundary vertices.
std::vector<Point_2> points_vec(number_of_vertices());
Vertex_const_iterator vit;
unsigned int i = 0;
for (vit = vertices_begin(); vit != vertices_end(); ++vit) {
if ((vit->parameter_space_in_x() == ARR_INTERIOR) &&
(vit->parameter_space_in_y() == ARR_INTERIOR))
{
points_vec[i] = vit->point();
++i;
}
}
points_vec.resize(i);
// Sort the vector of points and make sure no two adjacent points in the
// sorted vector are equal.
typedef typename Traits_adaptor_2::Compare_xy_2 Compare_xy_2;
typedef typename Traits_adaptor_2::Equal_2 Equal_2;
Equal_2 equal = m_geom_traits->equal_2_object();
Compare_xy_2 compare_xy = m_geom_traits->compare_xy_2_object();
Compare_to_less<Compare_xy_2> cmp = compare_to_less(compare_xy);
std::sort(points_vec.begin(), points_vec.end(), cmp);
for (i = 1; i < points_vec.size(); ++i) {
if (equal(points_vec[i-1], points_vec[i])) return false;
}
return true;
}
//---------------------------------------------------------------------------
// Check that the curves around a given vertex are ordered clockwise.
//
template <typename GeomTraits, typename TopTraits>
bool Arrangement_on_surface_2<GeomTraits, TopTraits>::
_are_curves_ordered_cw_around_vertrex(Vertex_const_handle v) const
{
if (v->degree() < 3) return true;
typename Traits_adaptor_2::Is_between_cw_2 is_between_cw =
m_geom_traits->is_between_cw_2_object();
Halfedge_around_vertex_const_circulator circ = v->incident_halfedges();
Halfedge_around_vertex_const_circulator first = circ;
Halfedge_around_vertex_const_circulator prev, next;
bool eq1, eq2;
do {
prev = circ; --prev;
next = circ; ++next;
if (!is_between_cw(circ->curve(), (circ->direction() == ARR_RIGHT_TO_LEFT),
prev->curve(), (prev->direction() == ARR_RIGHT_TO_LEFT),
next->curve(), (next->direction() == ARR_RIGHT_TO_LEFT),
v->point(), eq1, eq2))
return false;
if (eq1 || eq2) return false;
++circ;
} while (circ != first);
return true;
}
} // namespace CGAL
#endif
| 38.261586 | 113 | 0.642165 | [
"object",
"vector"
] |
8c43baf8418c8faf93349fb9be2e6a6ff5f480f4 | 735 | h | C | cases/spherical_surfers/param/post/objects/surfer__us_1o0__surftimeconst_6o0__reorientationtime_2o0/pz/choice.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | cases/spherical_surfers/param/post/objects/surfer__us_1o0__surftimeconst_6o0__reorientationtime_2o0/pz/choice.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | cases/spherical_surfers/param/post/objects/surfer__us_1o0__surftimeconst_6o0__reorientationtime_2o0/pz/choice.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | #ifndef C0P_PARAM_POST_OBJECTS_SURFER__US_1O0__SURFTIMECONST_6O0__REORIENTATIONTIME_2O0_PZ_CHOICE_H
#define C0P_PARAM_POST_OBJECTS_SURFER__US_1O0__SURFTIMECONST_6O0__REORIENTATIONTIME_2O0_PZ_CHOICE_H
#pragma once
// choose your post processing
#include "core/post/objects/object/post/group/all/core.h"
#include "param/post/objects/surfer__us_1o0__surftimeconst_6o0__reorientationtime_2o0/pz/group/all/parameters.h"
namespace c0p {
template<typename TypeSurferUs1O0Surftimeconst6O0Reorientationtime2O0Step>
using PostSurferUs1O0Surftimeconst6O0Reorientationtime2O0Pz = PostPostGroupAll<PostSurferUs1O0Surftimeconst6O0Reorientationtime2O0PzGroupAllParameters, TypeSurferUs1O0Surftimeconst6O0Reorientationtime2O0Step>;
}
#endif
| 52.5 | 213 | 0.89932 | [
"object"
] |
8c4a853a594040dfc67eff753cfd73ada5bd69de | 8,052 | h | C | src/kudu/util/blocking_queue.h | attilabukor/kudu | d4942c43880a7b0324388630ff640fe66f16c4b5 | [
"Apache-2.0"
] | 1,538 | 2016-08-08T22:34:30.000Z | 2022-03-29T05:23:36.000Z | src/kudu/util/blocking_queue.h | attilabukor/kudu | d4942c43880a7b0324388630ff640fe66f16c4b5 | [
"Apache-2.0"
] | 17 | 2017-05-18T16:05:14.000Z | 2022-03-18T22:17:13.000Z | src/kudu/util/blocking_queue.h | attilabukor/kudu | d4942c43880a7b0324388630ff640fe66f16c4b5 | [
"Apache-2.0"
] | 612 | 2016-08-12T04:09:37.000Z | 2022-03-29T16:57:46.000Z | // 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.
#pragma once
#include <unistd.h>
#include <algorithm>
#include <deque>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "kudu/gutil/basictypes.h"
#include "kudu/util/condition_variable.h"
#include "kudu/util/monotime.h"
#include "kudu/util/mutex.h"
#include "kudu/util/status.h"
namespace kudu {
// Return values for BlockingQueue::Put()
enum QueueStatus {
QUEUE_SUCCESS = 0,
QUEUE_SHUTDOWN = 1,
QUEUE_FULL = 2
};
// Default logical length implementation: always returns 1.
struct DefaultLogicalSize {
template<typename T>
static size_t logical_size(const T& /* unused */) {
return 1;
}
};
template <typename T, class LOGICAL_SIZE = DefaultLogicalSize>
class BlockingQueue {
public:
// If T is a pointer, this will be the base type. If T is not a pointer, you
// can ignore this and the functions which make use of it.
// Template substitution failure is not an error.
typedef typename std::remove_pointer<T>::type T_VAL;
explicit BlockingQueue(size_t max_size)
: max_size_(max_size),
size_(0),
shutdown_(false),
not_empty_(&lock_),
not_full_(&lock_) {
}
// If the queue holds a bare pointer, it must be empty on destruction, since
// it may have ownership of the pointer.
~BlockingQueue() {
DCHECK(queue_.empty() || !std::is_pointer<T>::value)
<< "BlockingQueue holds bare pointers at destruction time";
}
// Gets an element from the queue; if the queue is empty, blocks until the
// queue becomes non-empty, or until the deadline passes.
//
// If the queue has been shut down but there are still elements in the queue,
// it returns those elements as if the queue were not yet shut down.
//
// Returns:
// - OK if successful
// - TimedOut if the deadline passed
// - Aborted if the queue shut down
Status BlockingGet(T* out, MonoTime deadline = {}) {
MutexLock l(lock_);
while (true) {
if (!queue_.empty()) {
*out = std::move(queue_.front());
queue_.pop_front();
decrement_size_unlocked(*out);
l.Unlock();
not_full_.Signal();
return Status::OK();
}
if (PREDICT_FALSE(shutdown_)) {
return Status::Aborted("");
}
if (!deadline.Initialized()) {
not_empty_.Wait();
} else if (PREDICT_FALSE(!not_empty_.WaitUntil(deadline))) {
return Status::TimedOut("");
}
}
}
// Get all elements from the queue and append them to a vector.
//
// If 'deadline' passes and no elements have been returned from the
// queue, returns Status::TimedOut(). If 'deadline' is uninitialized,
// no deadline is used.
//
// If the queue has been shut down, but there are still elements waiting,
// then it returns those elements as if the queue were not yet shut down.
//
// Returns:
// - OK if successful
// - TimedOut if the deadline passed
// - Aborted if the queue shut down
Status BlockingDrainTo(std::vector<T>* out, MonoTime deadline = {}) {
MutexLock l(lock_);
while (true) {
if (!queue_.empty()) {
out->reserve(queue_.size());
for (const T& elt : queue_) {
decrement_size_unlocked(elt);
}
std::move(queue_.begin(), queue_.end(), std::back_inserter(*out));
queue_.clear();
l.Unlock();
not_full_.Signal();
return Status::OK();
}
if (PREDICT_FALSE(shutdown_)) {
return Status::Aborted("");
}
if (!deadline.Initialized()) {
not_empty_.Wait();
} else if (PREDICT_FALSE(!not_empty_.WaitUntil(deadline))) {
return Status::TimedOut("");
}
}
}
// Attempts to put the given value in the queue.
// Returns:
// QUEUE_SUCCESS: if successfully enqueued
// QUEUE_FULL: if the queue has reached max_size
// QUEUE_SHUTDOWN: if someone has already called Shutdown()
//
// The templatized approach is for perfect forwarding while providing both
// Put(const T&) and Put(T&&) signatures for the method. See
// https://en.cppreference.com/w/cpp/utility/forward for details.
template<typename U>
QueueStatus Put(U&& val) {
MutexLock l(lock_);
if (PREDICT_FALSE(shutdown_)) {
return QUEUE_SHUTDOWN;
}
if (size_ >= max_size_) {
return QUEUE_FULL;
}
increment_size_unlocked(val);
queue_.emplace_back(std::forward<U>(val));
l.Unlock();
not_empty_.Signal();
return QUEUE_SUCCESS;
}
// Puts an element onto the queue; if the queue is full, blocks until space
// becomes available, or until the deadline passes.
//
// NOTE: unlike BlockingGet() and BlockingDrainTo(), which succeed as long as
// there are elements in the queue (regardless of deadline), if the deadline
// has passed, an error will be returned even if there is space in the queue.
//
// Returns:
// - OK if successful
// - TimedOut if the deadline passed
// - Aborted if the queue shut down
//
// The templatized approach is for perfect forwarding while providing both
// BlockingPut(const T&) and BlockingPut(T&&) signatures for the method. See
// https://en.cppreference.com/w/cpp/utility/forward for details.
template<typename U>
Status BlockingPut(U&& val, MonoTime deadline = {}) {
if (PREDICT_FALSE(deadline.Initialized() && MonoTime::Now() > deadline)) {
return Status::TimedOut("");
}
MutexLock l(lock_);
while (true) {
if (PREDICT_FALSE(shutdown_)) {
return Status::Aborted("");
}
if (size_ < max_size_) {
increment_size_unlocked(val);
queue_.emplace_back(std::forward<U>(val));
l.Unlock();
not_empty_.Signal();
return Status::OK();
}
if (!deadline.Initialized()) {
not_full_.Wait();
} else if (PREDICT_FALSE(!not_full_.WaitUntil(deadline))) {
return Status::TimedOut("");
}
}
}
// Shuts down the queue.
//
// When a blocking queue is shut down, no more elements can be added to it,
// and Put() will return QUEUE_SHUTDOWN.
//
// Existing elements will drain out of it, and then BlockingGet will start
// returning false.
void Shutdown() {
MutexLock l(lock_);
shutdown_ = true;
not_full_.Broadcast();
not_empty_.Broadcast();
}
bool empty() const {
MutexLock l(lock_);
return queue_.empty();
}
size_t max_size() const {
return max_size_;
}
size_t size() const {
MutexLock l(lock_);
return size_;
}
std::string ToString() const {
std::string ret;
MutexLock l(lock_);
for (const T& t : queue_) {
ret.append(t->ToString());
ret.append("\n");
}
return ret;
}
private:
// Increments queue size. Must be called when 'lock_' is held.
void increment_size_unlocked(const T& t) {
size_ += LOGICAL_SIZE::logical_size(t);
}
// Decrements queue size. Must be called when 'lock_' is held.
void decrement_size_unlocked(const T& t) {
size_ -= LOGICAL_SIZE::logical_size(t);
}
const size_t max_size_;
size_t size_;
bool shutdown_;
mutable Mutex lock_;
ConditionVariable not_empty_;
ConditionVariable not_full_;
std::deque<T> queue_;
};
} // namespace kudu
| 29.712177 | 79 | 0.654993 | [
"vector"
] |
8c4ac2117b093e838116c4c9b718f196fa87b30b | 3,446 | h | C | include/JPetGeantScinHits.h | skscurious/Geant4_JPET | a5846af20b8b4b886f33c54552631623e1749fac | [
"Apache-2.0"
] | null | null | null | include/JPetGeantScinHits.h | skscurious/Geant4_JPET | a5846af20b8b4b886f33c54552631623e1749fac | [
"Apache-2.0"
] | null | null | null | include/JPetGeantScinHits.h | skscurious/Geant4_JPET | a5846af20b8b4b886f33c54552631623e1749fac | [
"Apache-2.0"
] | null | null | null | #ifndef JPetGeantScinHits_h
#define JPetGeantScinHits_h
#include "TObject.h"
#include <vector>
#include "TVector3.h"
/**
* \class JPetGeantScinHits
* \brief class is containing the hits registered in scintillators created by Geant software
*
*/
class JPetGeantScinHits : public TObject
{
public:
JPetGeantScinHits();
JPetGeantScinHits(int evID, int scinID, int trkID, int trkPDG,
int nInter, float ene, float time, TVector3 hit);
JPetGeantScinHits(int evID, int scinID, int trkID, int trkPDG,
int nInter, float ene, float time, TVector3 hit,
TVector3 polIn, TVector3 polOut,
TVector3 momeIn, TVector3 momeOut);
void Fill(int evID, int scinID, int trkID, int trkPDG,
int nInter, float ene, float time);
void Fill(int evID, int scinID, int trkID, int trkPDG,
int nInter, float ene, float time, TVector3 hit,
TVector3 polIn, TVector3 polOut,
TVector3 momeIn, TVector3 momeOut);
~JPetGeantScinHits();
void Clean();
// setters
void SetEvtID(int x){fEvtID = x;};
void SetScinID(int x){fScinID =x;};
void SetTrackID(int x){fTrackID = x;};
void SetTrackPDG(int x){fTrackPDGencoding=x;};
void SetNumOfInteractions(int x){fNumOfInteractions=x;};
void SetEneDepos(float x){fEneDep=x;};
void SetTime(float x){fTime=x;};
void SetHitPosition(TVector3 x){fPosition=x;};
void SetHitPosition(float x, float y, float z){fPosition.SetXYZ(x,y,z);};
void SetPolarizationIn(TVector3 x){fPolarizationIn=x;};
void SetPolarizationIn(float x, float y, float z){fPolarizationIn.SetXYZ(x,y,z);};
void SetPolarizationOut(TVector3 x){fPolarizationOut=x;};
void SetPolarizationOut(float x, float y, float z){fPolarizationOut.SetXYZ(x,y,z);};
void SetMomentumIn(TVector3 x){fMomentumIn=x;};
void SetMomentumIn(float x, float y, float z){fMomentumIn.SetXYZ(x,y,z);};
void SetMomentumOut(TVector3 x){fMomentumOut=x;};
void SetMomentumOut(float x, float y, float z){fMomentumOut.SetXYZ(x,y,z);};
// getters
int GetEvtID(){return fEvtID;};
int GetScinID(){return fScinID;};
int GetTrackID(){return fTrackID;};
int GetTrackPDG(){return fTrackPDGencoding;};
int GetNumOfInteractions(){return fNumOfInteractions;};
float GetEneDepos(){return fEneDep;};
float GetTime(){return fTime;};
TVector3 GetHitPosition(){return fPosition;};
TVector3 GetPolarizationIn(){return fPolarizationIn;};
TVector3 GetPolarizationOut(){return fPolarizationOut;};
TVector3 GetMomentumIn(){return fMomentumIn;};
TVector3 GetMomentumOut(){return fMomentumOut;};
private:
int fEvtID;
int fScinID;
int fTrackID;
int fTrackPDGencoding;
int fNumOfInteractions; ///< number of interaction taking place in single scintillator whish was classified as single hit; it may be a big number since electron deposits energy in many steps
float fEneDep;
float fTime;
TVector3 fPosition;
TVector3 fPolarizationIn;
TVector3 fPolarizationOut;
TVector3 fMomentumIn;
TVector3 fMomentumOut;
ClassDef(JPetGeantScinHits,1)
};
#endif
| 35.163265 | 198 | 0.645096 | [
"vector"
] |
8c5712d453e4317e9eb85df4eff572bdb7b47e57 | 2,666 | h | C | model/ezsigntemplatepackage_get_object_v1_response_m_payload.h | ezmaxinc/eZmax-SDK-c | 725eab79d6311127a2d5bd731b978bce94142d69 | [
"curl",
"MIT"
] | null | null | null | model/ezsigntemplatepackage_get_object_v1_response_m_payload.h | ezmaxinc/eZmax-SDK-c | 725eab79d6311127a2d5bd731b978bce94142d69 | [
"curl",
"MIT"
] | null | null | null | model/ezsigntemplatepackage_get_object_v1_response_m_payload.h | ezmaxinc/eZmax-SDK-c | 725eab79d6311127a2d5bd731b978bce94142d69 | [
"curl",
"MIT"
] | null | null | null | /*
* ezsigntemplatepackage_get_object_v1_response_m_payload.h
*
* Payload for GET /1/object/ezsigntemplatepackage/{pkiEzsigntemplatepackageID}
*/
#ifndef _ezsigntemplatepackage_get_object_v1_response_m_payload_H_
#define _ezsigntemplatepackage_get_object_v1_response_m_payload_H_
#include <string.h>
#include "../external/cJSON.h"
#include "../include/list.h"
#include "../include/keyValuePair.h"
#include "../include/binary.h"
typedef struct ezsigntemplatepackage_get_object_v1_response_m_payload_t ezsigntemplatepackage_get_object_v1_response_m_payload_t;
#include "ezsigntemplatepackage_response_compound.h"
#include "ezsigntemplatepackagemembership_response_compound.h"
#include "ezsigntemplatepackagesigner_response_compound.h"
typedef struct ezsigntemplatepackage_get_object_v1_response_m_payload_t {
int pki_ezsigntemplatepackage_id; //numeric
int fki_ezsignfoldertype_id; //numeric
int fki_language_id; //numeric
char *s_language_name_x; // string
char *s_ezsigntemplatepackage_description; // string
int b_ezsigntemplatepackage_adminonly; //boolean
int b_ezsigntemplatepackage_needvalidation; //boolean
int b_ezsigntemplatepackage_isactive; //boolean
char *s_ezsignfoldertype_name_x; // string
list_t *a_obj_ezsigntemplatepackagesigner; //nonprimitive container
list_t *a_obj_ezsigntemplatepackagemembership; //nonprimitive container
} ezsigntemplatepackage_get_object_v1_response_m_payload_t;
ezsigntemplatepackage_get_object_v1_response_m_payload_t *ezsigntemplatepackage_get_object_v1_response_m_payload_create(
int pki_ezsigntemplatepackage_id,
int fki_ezsignfoldertype_id,
int fki_language_id,
char *s_language_name_x,
char *s_ezsigntemplatepackage_description,
int b_ezsigntemplatepackage_adminonly,
int b_ezsigntemplatepackage_needvalidation,
int b_ezsigntemplatepackage_isactive,
char *s_ezsignfoldertype_name_x,
list_t *a_obj_ezsigntemplatepackagesigner,
list_t *a_obj_ezsigntemplatepackagemembership
);
void ezsigntemplatepackage_get_object_v1_response_m_payload_free(ezsigntemplatepackage_get_object_v1_response_m_payload_t *ezsigntemplatepackage_get_object_v1_response_m_payload);
ezsigntemplatepackage_get_object_v1_response_m_payload_t *ezsigntemplatepackage_get_object_v1_response_m_payload_parseFromJSON(cJSON *ezsigntemplatepackage_get_object_v1_response_m_payloadJSON);
cJSON *ezsigntemplatepackage_get_object_v1_response_m_payload_convertToJSON(ezsigntemplatepackage_get_object_v1_response_m_payload_t *ezsigntemplatepackage_get_object_v1_response_m_payload);
#endif /* _ezsigntemplatepackage_get_object_v1_response_m_payload_H_ */
| 43.704918 | 194 | 0.862716 | [
"object"
] |
8c58e2328b76310432e7d6592624dfbfe1c1c9c5 | 5,640 | h | C | impl/op/vtm/Transactional.h | mvoronoy/OP.MagicTrie | be7a303d8f8d65a0bed81daf5d28f429a059f8ca | [
"Apache-2.0"
] | null | null | null | impl/op/vtm/Transactional.h | mvoronoy/OP.MagicTrie | be7a303d8f8d65a0bed81daf5d28f429a059f8ca | [
"Apache-2.0"
] | null | null | null | impl/op/vtm/Transactional.h | mvoronoy/OP.MagicTrie | be7a303d8f8d65a0bed81daf5d28f429a059f8ca | [
"Apache-2.0"
] | null | null | null | #ifndef _OP_TR_TRANSACTIONAL__H_
#define _OP_TR_TRANSACTIONAL__H_
#include <type_traits>
#include <iostream>
#include <unordered_map>
#include <string>
#include <typeinfo>
namespace OP
{
namespace vtm{
/**Exception is raised when imposible to obtain lock over memory block*/
struct ConcurentLockException : public OP::trie::Exception
{
ConcurentLockException() :
Exception(OP::trie::er_transaction_concurent_lock){}
ConcurentLockException(const char* debug) :
Exception(OP::trie::er_transaction_concurent_lock, debug){}
};
/**Handler allows intercept end of transaction*/
struct BeforeTransactionEnd
{
virtual ~BeforeTransactionEnd() = default;
virtual void on_commit() = 0;
virtual void on_rollback() = 0;
};
/**
* Declare general definition of transaction as identifiable object with pair of operations commit/rollback
*/
struct Transaction
{
typedef std::uint64_t transaction_id_t;
friend struct TransactionGuard;
Transaction() = delete;
Transaction(const Transaction&) = delete;
Transaction& operator = (const Transaction&) = delete;
Transaction& operator = (Transaction&& other) = delete;
Transaction(Transaction && other) OP_NOEXCEPT :
_transaction_id(other._transaction_id)
{
}
virtual ~Transaction() OP_NOEXCEPT
{
}
virtual transaction_id_t transaction_id() const
{
return _transaction_id;
}
/**Register handler that is invoked during rollback/commit process*/
virtual void register_handle(std::unique_ptr<BeforeTransactionEnd> handler) = 0;
virtual void rollback() = 0;
virtual void commit() = 0;
protected:
Transaction(transaction_id_t id) :
_transaction_id(id)
{
}
private:
const transaction_id_t _transaction_id;
};
typedef std::shared_ptr<Transaction> transaction_ptr_t;
/**
* Guard wrapper that grants transaction accomplishment.
* Destructor is responsible to rollback transaction if user did not commit it explictly before.
*/
struct TransactionGuard
{
template <class Sh>
TransactionGuard(Sh && instance, bool do_commit_on_close = false)
: _instance(std::forward<Sh>(instance))
, _is_closed(!_instance)//be polite to null transactions
, _do_commit_on_close(do_commit_on_close)
{}
TransactionGuard(const TransactionGuard&) = delete;
TransactionGuard& operator = (const TransactionGuard&) = delete;
void commit()
{
if (!!_instance)
{
assert(!_is_closed);//be polite to null transactions
_instance->commit();
_is_closed = true;
}
}
void rollback()
{
if (!!_instance)
{
assert(!_is_closed);//be polite to null transactions
_instance->rollback();
_is_closed = true;
}
}
~TransactionGuard()
{
if (!_is_closed)
_do_commit_on_close ? _instance->commit() : _instance->rollback();
}
private:
transaction_ptr_t _instance;
bool _is_closed;
bool _do_commit_on_close;
};
/**
* Utility to repeat some operation after ConcurentLockException has been raised.
* Number of repeating peformed by N template parameter, after this number
* exceeding ConcurentLockException exception just propagated to caller
*/
template <std::uint16_t N, typename F, typename ... Args>
inline typename std::result_of<F && (Args &&...)>::type transactional_retry_n(F && f, Args&& ... ax)
{
for (auto i = 0; i < N; ++i)
{
try
{
return std::forward<F>(f)(std::forward<Args>(ax)...);
}
catch (const OP::vtm::ConcurentLockException &e)
{
/*ignore exception for a while*/
e.what();
}
}
throw OP::vtm::ConcurentLockException("10");
}
template <std::uint16_t N, typename F, typename ... Args>
inline typename std::result_of<F && (Args &&...)>::type transactional_yield_retry_n(F && f, Args&& ... ax)
{
for (auto i = 0; i < N; ++i)
{
try
{
return std::forward<F>(f)(std::forward<Args>(ax)...);
}
catch (const OP::vtm::ConcurentLockException &)
{
/*ignore exception for a while*/
std::this_thread::yield();
}
}
throw OP::vtm::ConcurentLockException("10");
}
} //namespace vtm
} //end of namespace OP
#endif //_OP_TR_TRANSACTIONAL__H_
| 35.25 | 117 | 0.508865 | [
"object"
] |
8c5ef63df0832bdd1e80fec6dbe824d41aacc4d7 | 2,985 | h | C | libtensor/block_tensor/impl/btod_ewmult2_impl.h | maxscheurer/libtensor | 288ed0596b24356d187d2fa40c05b0dacd00b413 | [
"BSL-1.0"
] | 33 | 2016-02-08T06:05:17.000Z | 2021-11-17T01:23:11.000Z | libtensor/block_tensor/impl/btod_ewmult2_impl.h | maxscheurer/libtensor | 288ed0596b24356d187d2fa40c05b0dacd00b413 | [
"BSL-1.0"
] | 11 | 2020-12-04T20:26:12.000Z | 2021-12-03T08:07:09.000Z | libtensor/block_tensor/impl/btod_ewmult2_impl.h | maxscheurer/libtensor | 288ed0596b24356d187d2fa40c05b0dacd00b413 | [
"BSL-1.0"
] | 12 | 2016-05-19T18:09:38.000Z | 2021-02-24T17:35:21.000Z | #ifndef LIBTENSOR_BTOD_EWMULT2_IMPL_H
#define LIBTENSOR_BTOD_EWMULT2_IMPL_H
#include <libtensor/gen_block_tensor/gen_bto_aux_add.h>
#include <libtensor/gen_block_tensor/gen_bto_aux_copy.h>
#include "../btod_ewmult2.h"
namespace libtensor {
template<size_t N, size_t M, size_t K>
const char btod_ewmult2<N, M, K>::k_clazz[] = "btod_ewmult2<N, M, K>";
template<size_t N, size_t M, size_t K>
btod_ewmult2<N, M, K>::btod_ewmult2(block_tensor_rd_i<NA, double> &bta,
block_tensor_rd_i<NB, double> &btb, double d) :
m_gbto(bta, tensor_transf<NA, double>(), btb, tensor_transf<NB, double>(),
tensor_transf<NC, double>(permutation<NC>(),
scalar_transf<double>(d))) {
}
template<size_t N, size_t M, size_t K>
btod_ewmult2<N, M, K>::btod_ewmult2(
block_tensor_rd_i<NA, double> &bta, const permutation<NA> &perma,
block_tensor_rd_i<NB, double> &btb, const permutation<NB> &permb,
const permutation<NC> &permc, double d) :
m_gbto(bta, tensor_transf<NA, double>(perma),
btb, tensor_transf<NB, double>(permb),
tensor_transf_type(permc, scalar_transf<double>(d))) {
}
template<size_t N, size_t M, size_t K>
btod_ewmult2<N, M, K>::btod_ewmult2(
block_tensor_rd_i<NA, double> &bta, const tensor_transf<NA, double> &tra,
block_tensor_rd_i<NB, double> &btb, const tensor_transf<NB, double> &trb,
const tensor_transf_type &trc) :
m_gbto(bta, tra, btb, trb, trc) {
}
template<size_t N, size_t M, size_t K>
void btod_ewmult2<N, M, K>::perform(gen_block_stream_i<NC, bti_traits> &out) {
m_gbto.perform(out);
}
template<size_t N, size_t M, size_t K>
void btod_ewmult2<N, M, K>::perform(gen_block_tensor_i<NC, bti_traits> &btc) {
gen_bto_aux_copy<N + M + K, btod_traits> out(get_symmetry(), btc);
out.open();
m_gbto.perform(out);
out.close();
}
template<size_t N, size_t M, size_t K>
void btod_ewmult2<N, M, K>::perform(gen_block_tensor_i<NC, bti_traits> &btc,
const scalar_transf<double> &d) {
typedef typename btod_traits::bti_traits bti_traits;
gen_block_tensor_rd_ctrl<NC, bti_traits> cc(btc);
std::vector<size_t> nzblkc;
cc.req_nonzero_blocks(nzblkc);
addition_schedule<NC, btod_traits> asch(get_symmetry(),
cc.req_const_symmetry());
asch.build(get_schedule(), nzblkc);
gen_bto_aux_add<NC, btod_traits> out(get_symmetry(), asch, btc, d);
out.open();
m_gbto.perform(out);
out.close();
}
template<size_t N, size_t M, size_t K>
void btod_ewmult2<N, M, K>::perform(
block_tensor_i<NC, double> &btc, double d) {
perform(btc, scalar_transf<double>(d));
}
template<size_t N, size_t M, size_t K>
void btod_ewmult2<N, M, K>::compute_block(
bool zero,
const index<NC> &idx,
const tensor_transf<NC, double> &tr,
dense_tensor_wr_i<NC, double> &blk) {
m_gbto.compute_block(zero, idx, tr, blk);
}
} // namespace libtensor
#endif // LIBTENSOR_BTOD_EWMULT2_IMPL_H
| 27.897196 | 78 | 0.687437 | [
"vector"
] |
8c5f90a25cf04af4a7de45f46db2fb2942c8aec0 | 65,375 | c | C | network/wlan/WDI/PLATFORM/NdisComm/NdisComm.c | ixjf/Windows-driver-samples | 38985ba91feb685095754775e101389ad90c2aa6 | [
"MS-PL"
] | 3,084 | 2015-03-18T04:40:32.000Z | 2019-05-06T17:14:33.000Z | network/wlan/WDI/PLATFORM/NdisComm/NdisComm.c | ixjf/Windows-driver-samples | 38985ba91feb685095754775e101389ad90c2aa6 | [
"MS-PL"
] | 275 | 2015-03-19T18:44:41.000Z | 2019-05-06T14:13:26.000Z | network/wlan/WDI/PLATFORM/NdisComm/NdisComm.c | ixjf/Windows-driver-samples | 38985ba91feb685095754775e101389ad90c2aa6 | [
"MS-PL"
] | 3,091 | 2015-03-19T00:08:54.000Z | 2019-05-06T16:42:01.000Z | #include "Mp_Precomp.h"
#if WPP_SOFTWARE_TRACE
#include "NdisComm.tmh"
#endif
//
// Description:
// Translate RT_STATUS to Ndis Status.
// Arguments:
// [in] rtStatus -
// RT defined status.
// Return:
// NDIS_STATU_XXX
// Remark:
// This function translates some known RT status to NDIS_STATUS_XXX.
// If the input RT status is unrecognized, return NDIS_STATUS_FAILURE.
// By Bruce, 2012-03-07.
//
NDIS_STATUS
NdisStatusFromRtStatus(
IN u4Byte rtStatus
)
{
switch(rtStatus)
{
default:
return NDIS_STATUS_FAILURE;
case RT_STATUS_SUCCESS:
return NDIS_STATUS_SUCCESS;
case RT_STATUS_FAILURE:
return NDIS_STATUS_FAILURE;
case RT_STATUS_PENDING:
return NDIS_STATUS_PENDING;
case RT_STATUS_RESOURCE:
return NDIS_STATUS_RESOURCES;
case RT_STATUS_INVALID_CONTEXT:
case RT_STATUS_INVALID_PARAMETER:
case RT_STATUS_MALFORMED_PKT:
return NDIS_STATUS_INVALID_DATA;
case RT_STATUS_NOT_SUPPORT:
return NDIS_STATUS_NOT_SUPPORTED;
case RT_STATUS_BUFFER_TOO_SHORT:
return NDIS_STATUS_BUFFER_TOO_SHORT;
case RT_STATUS_INVALID_LENGTH:
return NDIS_STATUS_INVALID_LENGTH;
case RT_STATUS_NOT_RECOGNIZED:
return NDIS_STATUS_NOT_RECOGNIZED;
case RT_STATUS_MEDIA_BUSY:
return NDIS_STATUS_MEDIA_BUSY;
case RT_STATUS_INVALID_DATA:
return NDIS_STATUS_INVALID_DATA;
}
}
VOID
_PlatformInitializeSpinLock(
PVOID Adapter,
RT_SPINLOCK_TYPE type
)
{
PADAPTER pDefaultAdapter = GetDefaultAdapter((PADAPTER)Adapter);
PNDIS_ADAPTER_TYPE pDevice = GET_NDIS_ADAPTER(pDefaultAdapter);
switch(type)
{
case RT_RX_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->RxSpinLock) );
pDefaultAdapter->bRxLocked = FALSE;
break;
case RT_RX_CONTROL_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->RxControlSpinLock));
break;
case RT_RX_QUEUE_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->RxQueueSpinLock));
break;
case RT_TX_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->TxSpinLock) );
pDefaultAdapter->bTxLocked = FALSE;
break;
case RT_RM_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->RmSpinLock) );
break;
case RT_CAM_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->CamSpinLock) );
break;
case RT_SCAN_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->ScanSpinLock) );
break;
case RT_LOG_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->LogSpinLock) );
break;
case RT_BW_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->BwSpinLock) );
break;
case RT_CHNLOP_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->ChnlOpSpinLock) );
break;
case RT_RF_OPERATE_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->RFWriteSpinLock));
break;
case RT_INITIAL_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->InitialSpinLock));
break;
case RT_RF_STATE_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->RFStateSpinLock));
break;
case RT_PORT_SPINLOCK:
NdisAllocateSpinLock(&(pDevice->PortLock) );
break;
case RT_H2C_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->H2CSpinLock));
break;
#if VISTA_USB_RX_REVISE
case RT_USBRX_CONTEXT_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->UsbRxContextLock) );
break;
case RT_USBRX_POSTPROC_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->UsbRxIndicateLock) );
break;
#endif
case RT_WAPI_OPTION_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->WapiOptionSpinLock));
break;
case RT_WAPI_RX_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->WapiRxSpinLock));
break;
case RT_BUFFER_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->BufferSpinLock));
break;
case RT_GEN_TEMP_BUF_SPINLOCK:
NdisAllocateSpinLock(&(pDevice->GenBufSpinLock));
break;
case RT_AWB_SPINLOCK:
NdisAllocateSpinLock(&(pDevice->AwbSpinLock));
break;
case RT_FW_PS_SPINLOCK:
NdisAllocateSpinLock(&(pDevice->FwPSSpinLock));
break;
case RT_HW_TIMER_SPIN_LOCK:
NdisAllocateSpinLock(&(pDevice->HwTimerSpinLock));
break;
case RT_P2P_SPIN_LOCK:
NdisAllocateSpinLock(&(pDevice->P2PSpinLock));
break;
case RT_MPT_WI_SPINLOCK:
NdisAllocateSpinLock(&(pDevice->MptWorkItemSpinLock));
break;
case RT_DBG_SPIN_LOCK:
NdisAllocateSpinLock(&(pDevice->ndisDbgWorkItemSpinLock));
break;
case RT_IQK_SPINLOCK:
NdisAllocateSpinLock(&(pDevice->IQKSpinLock));
break;
case RT_DYN_TXPWRTBL_SPINLOCK:
NdisAllocateSpinLock(&(pDevice->DynTxPwrTblSpinLock));
break;
case RT_CHNLLIST_SPINLOCK:
NdisAllocateSpinLock(&(pDevice->ChnlListSpinLock));
break;
case RT_PENDED_OID_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->PendedOidSpinLock));
break;
case RT_INDIC_SPINLOCK:
NdisAllocateSpinLock(&(pDevice->IndicSpinLock));
break;
case RT_RFD_SPINLOCK:
NdisAllocateSpinLock(&(pDevice->RfdSpinLock));
break;
#if DRV_LOG_REGISTRY
case RT_DRV_STATE_SPINLOCK:
NdisAllocateSpinLock(&(pDevice->DrvStateSpinLock));
break;
#endif
#if (AUTO_CHNL_SEL_NHM == 1)
case RT_ACS_SPINLOCK:
NdisAllocateSpinLock(&(pDevice->AcsSpinLock));
break;
#endif
case RT_RX_REF_CNT_SPINLOCK:
NdisAllocateSpinLock(&(pDevice->RxRefCntSpinLock));
break;
case RT_SYNC_IO_CNT_SPINLOCK:
NdisAllocateSpinLock( &(pDevice->SyncIoCntSpinLock));
break;
default:
break;
}
}
VOID
_PlatformFreeSpinLock(
PVOID Adapter,
RT_SPINLOCK_TYPE type
)
{
PADAPTER pDefaultAdapter = GetDefaultAdapter((PADAPTER)Adapter);
PNDIS_ADAPTER_TYPE pDevice = GET_NDIS_ADAPTER(pDefaultAdapter);
switch(type)
{
case RT_RX_SPINLOCK:
NdisFreeSpinLock( &(pDevice->RxSpinLock) );
break;
case RT_RX_CONTROL_SPINLOCK:
NdisFreeSpinLock( &(pDevice->RxControlSpinLock));
break;
case RT_RX_QUEUE_SPINLOCK:
NdisFreeSpinLock( &(pDevice->RxQueueSpinLock));
break;
case RT_TX_SPINLOCK:
NdisFreeSpinLock( &(pDevice->TxSpinLock) );
break;
case RT_RM_SPINLOCK:
NdisFreeSpinLock( &(pDevice->RmSpinLock) );
break;
case RT_CAM_SPINLOCK:
NdisFreeSpinLock( &(pDevice->CamSpinLock) );
break;
case RT_SCAN_SPINLOCK:
NdisFreeSpinLock( &(pDevice->ScanSpinLock) );
break;
case RT_LOG_SPINLOCK:
NdisFreeSpinLock( &(pDevice->LogSpinLock) );
break;
case RT_BW_SPINLOCK:
NdisFreeSpinLock( &(pDevice->BwSpinLock) );
break;
case RT_CHNLOP_SPINLOCK:
NdisFreeSpinLock( &(pDevice->ChnlOpSpinLock) );
break;
case RT_RF_OPERATE_SPINLOCK:
NdisFreeSpinLock( &(pDevice->RFWriteSpinLock));
break;
case RT_INITIAL_SPINLOCK:
NdisFreeSpinLock( &(pDevice->InitialSpinLock));
break;
case RT_RF_STATE_SPINLOCK:
NdisFreeSpinLock( &(pDevice->RFStateSpinLock));
break;
case RT_PORT_SPINLOCK:
NdisFreeSpinLock(&(pDevice->PortLock) );
break;
case RT_H2C_SPINLOCK:
NdisFreeSpinLock( &(pDevice->H2CSpinLock));
break;
#if VISTA_USB_RX_REVISE
case RT_USBRX_CONTEXT_SPINLOCK:
NdisFreeSpinLock( &(pDevice->UsbRxContextLock) );
break;
case RT_USBRX_POSTPROC_SPINLOCK:
NdisFreeSpinLock( &(pDevice->UsbRxIndicateLock) );
break;
#endif
case RT_WAPI_OPTION_SPINLOCK:
NdisFreeSpinLock( &(pDevice->WapiOptionSpinLock));
break;
case RT_WAPI_RX_SPINLOCK:
NdisFreeSpinLock( &(pDevice->WapiRxSpinLock));
break;
case RT_BUFFER_SPINLOCK:
NdisFreeSpinLock( &(pDevice->BufferSpinLock) );
break;
case RT_AWB_SPINLOCK:
NdisFreeSpinLock(&(pDevice->AwbSpinLock));
break;
case RT_FW_PS_SPINLOCK:
NdisFreeSpinLock(&(pDevice->FwPSSpinLock));
break;
case RT_HW_TIMER_SPIN_LOCK:
NdisFreeSpinLock(&(pDevice->HwTimerSpinLock));
break;
case RT_P2P_SPIN_LOCK:
NdisFreeSpinLock(&(pDevice->P2PSpinLock));
break;
case RT_MPT_WI_SPINLOCK:
NdisFreeSpinLock(&(pDevice->MptWorkItemSpinLock));
break;
case RT_DBG_SPIN_LOCK:
NdisFreeSpinLock(&(pDevice->ndisDbgWorkItemSpinLock));
break;
case RT_IQK_SPINLOCK:
NdisFreeSpinLock(&(pDevice->IQKSpinLock));
break;
case RT_DYN_TXPWRTBL_SPINLOCK:
NdisFreeSpinLock(&(pDevice->DynTxPwrTblSpinLock));
break;
case RT_CHNLLIST_SPINLOCK:
NdisFreeSpinLock(&(pDevice->ChnlListSpinLock));
break;
case RT_PENDED_OID_SPINLOCK:
NdisFreeSpinLock( &(pDevice->PendedOidSpinLock));
break;
case RT_RFD_SPINLOCK:
NdisFreeSpinLock(&(pDevice->RfdSpinLock));
break;
case RT_INDIC_SPINLOCK:
NdisFreeSpinLock(&(pDevice->IndicSpinLock));
break;
#if DRV_LOG_REGISTRY
case RT_DRV_STATE_SPINLOCK:
NdisFreeSpinLock(&(pDevice->DrvStateSpinLock));
break;
#endif
#if (AUTO_CHNL_SEL_NHM == 1)
case RT_ACS_SPINLOCK:
NdisFreeSpinLock(&(pDevice->AcsSpinLock));
break;
#endif
case RT_RX_REF_CNT_SPINLOCK:
NdisFreeSpinLock(&(pDevice->RxRefCntSpinLock));
break;
case RT_SYNC_IO_CNT_SPINLOCK:
NdisFreeSpinLock( &(pDevice->SyncIoCntSpinLock));
break;
default:
break;
}
}
#pragma warning( disable: 28167 ) // Prefast says we don't annotated the change.
_IRQL_raises_(DISPATCH_LEVEL)
VOID
_PlatformAcquireSpinLock(
PVOID Adapter,
RT_SPINLOCK_TYPE type
)
{
PADAPTER pDefaultAdapter = GetDefaultAdapter((PADAPTER)Adapter);
PNDIS_ADAPTER_TYPE pDevice = GET_NDIS_ADAPTER(pDefaultAdapter);
switch(type)
{
case RT_RX_SPINLOCK:
NdisAcquireSpinLock( &(pDevice->RxSpinLock) );
pDefaultAdapter->bRxLocked = TRUE;
break;
case RT_RX_CONTROL_SPINLOCK:
NdisAcquireSpinLock( &(pDevice->RxControlSpinLock));
break;
case RT_RX_QUEUE_SPINLOCK:
NdisAcquireSpinLock( &(pDevice->RxQueueSpinLock));
break;
case RT_TX_SPINLOCK:
NdisAcquireSpinLock( &(pDevice->TxSpinLock) );
pDefaultAdapter->bTxLocked = TRUE;
break;
case RT_RM_SPINLOCK:
NdisAcquireSpinLock( &(pDevice->RmSpinLock) );
break;
case RT_CAM_SPINLOCK:
NdisAcquireSpinLock( &(pDevice->CamSpinLock) );
break;
case RT_SCAN_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->ScanSpinLock) );
break;
case RT_LOG_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->LogSpinLock) );
break;
case RT_BW_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->BwSpinLock) );
break;
case RT_CHNLOP_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->ChnlOpSpinLock) );
break;
case RT_RF_OPERATE_SPINLOCK:
NdisAcquireSpinLock( &(pDevice->RFWriteSpinLock));
break;
case RT_INITIAL_SPINLOCK:
NdisAcquireSpinLock( &(pDevice->InitialSpinLock));
break;
case RT_RF_STATE_SPINLOCK:
NdisAcquireSpinLock( &(pDevice->RFStateSpinLock));
break;
case RT_PORT_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->PortLock) );
break;
case RT_H2C_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->H2CSpinLock) );
break;
#if VISTA_USB_RX_REVISE
case RT_USBRX_CONTEXT_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->UsbRxContextLock) );
break;
case RT_USBRX_POSTPROC_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->UsbRxIndicateLock) );
break;
#endif
case RT_WAPI_OPTION_SPINLOCK:
NdisAcquireSpinLock( &(pDevice->WapiOptionSpinLock));
break;
case RT_WAPI_RX_SPINLOCK:
NdisAcquireSpinLock( &(pDevice->WapiRxSpinLock));
break;
case RT_BUFFER_SPINLOCK:
NdisAcquireSpinLock( &(pDevice->BufferSpinLock) );
break;
case RT_GEN_TEMP_BUF_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->GenBufSpinLock));
break;
case RT_AWB_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->AwbSpinLock));
break;
case RT_FW_PS_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->FwPSSpinLock));
break;
case RT_HW_TIMER_SPIN_LOCK:
NdisAcquireSpinLock(&(pDevice->HwTimerSpinLock));
break;
case RT_P2P_SPIN_LOCK:
NdisAcquireSpinLock(&(pDevice->P2PSpinLock));
break;
case RT_MPT_WI_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->MptWorkItemSpinLock));
break;
case RT_DBG_SPIN_LOCK:
NdisAcquireSpinLock(&(pDevice->ndisDbgWorkItemSpinLock));
break;
case RT_IQK_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->IQKSpinLock));
break;
case RT_DYN_TXPWRTBL_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->DynTxPwrTblSpinLock));
break;
case RT_CHNLLIST_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->ChnlListSpinLock));
break;
case RT_PENDED_OID_SPINLOCK:
NdisAcquireSpinLock( &(pDevice->PendedOidSpinLock));
break;
case RT_INDIC_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->IndicSpinLock));
break;
case RT_RFD_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->RfdSpinLock));
break;
#if DRV_LOG_REGISTRY
case RT_DRV_STATE_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->DrvStateSpinLock));
break;
#endif
#if (AUTO_CHNL_SEL_NHM == 1)
case RT_ACS_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->AcsSpinLock));
break;
#endif
case RT_RX_REF_CNT_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->RxRefCntSpinLock));
break;
case RT_SYNC_IO_CNT_SPINLOCK:
NdisAcquireSpinLock( &(pDevice->SyncIoCntSpinLock));
break;
case RT_CUSTOM_SCAN_SPINLOCK:
NdisAcquireSpinLock(&(pDevice->CustomScanSpinLock));
break;
default:
break;
}
}
#pragma warning( disable: 28167 ) // Prefast says we don't annotated the change.
_IRQL_requires_(DISPATCH_LEVEL)
VOID
_PlatformReleaseSpinLock(
PVOID Adapter,
RT_SPINLOCK_TYPE type
)
{
PADAPTER pDefaultAdapter = GetDefaultAdapter((PADAPTER)Adapter);
PNDIS_ADAPTER_TYPE pDevice = GET_NDIS_ADAPTER(pDefaultAdapter);
switch(type)
{
case RT_RX_SPINLOCK:
pDefaultAdapter->bRxLocked = FALSE;
NdisReleaseSpinLock( &(pDevice->RxSpinLock) );
break;
case RT_RX_CONTROL_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->RxControlSpinLock));
break;
case RT_RX_QUEUE_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->RxQueueSpinLock));
break;
case RT_TX_SPINLOCK:
pDefaultAdapter->bTxLocked = FALSE;
NdisReleaseSpinLock( &(pDevice->TxSpinLock) );
break;
case RT_RM_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->RmSpinLock) );
break;
case RT_CAM_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->CamSpinLock) );
break;
case RT_SCAN_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->ScanSpinLock) );
break;
case RT_LOG_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->LogSpinLock) );
break;
case RT_BW_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->BwSpinLock) );
break;
case RT_CHNLOP_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->ChnlOpSpinLock) );
break;
case RT_RF_OPERATE_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->RFWriteSpinLock));
break;
case RT_INITIAL_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->InitialSpinLock));
break;
case RT_RF_STATE_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->RFStateSpinLock));
break;
case RT_PORT_SPINLOCK:
NdisReleaseSpinLock(&(pDevice->PortLock) );
break;
case RT_H2C_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->H2CSpinLock));
break;
#if VISTA_USB_RX_REVISE
case RT_USBRX_CONTEXT_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->UsbRxContextLock) );
break;
case RT_USBRX_POSTPROC_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->UsbRxIndicateLock) );
break;
#endif
case RT_WAPI_OPTION_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->WapiOptionSpinLock));
break;
case RT_WAPI_RX_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->WapiRxSpinLock));
break;
case RT_BUFFER_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->BufferSpinLock) );
break;
case RT_GEN_TEMP_BUF_SPINLOCK:
NdisReleaseSpinLock(&(pDevice->GenBufSpinLock));
break;
case RT_AWB_SPINLOCK:
NdisReleaseSpinLock(&(pDevice->AwbSpinLock));
break;
case RT_FW_PS_SPINLOCK:
NdisReleaseSpinLock(&(pDevice->FwPSSpinLock));
break;
case RT_HW_TIMER_SPIN_LOCK:
NdisReleaseSpinLock(&(pDevice->HwTimerSpinLock));
break;
case RT_P2P_SPIN_LOCK:
NdisReleaseSpinLock(&(pDevice->P2PSpinLock));
break;
case RT_MPT_WI_SPINLOCK:
NdisReleaseSpinLock(&(pDevice->MptWorkItemSpinLock));
break;
case RT_DBG_SPIN_LOCK:
NdisReleaseSpinLock(&(pDevice->ndisDbgWorkItemSpinLock));
break;
case RT_IQK_SPINLOCK:
NdisReleaseSpinLock(&(pDevice->IQKSpinLock));
break;
case RT_DYN_TXPWRTBL_SPINLOCK:
NdisReleaseSpinLock(&(pDevice->DynTxPwrTblSpinLock));
break;
case RT_CHNLLIST_SPINLOCK:
NdisReleaseSpinLock(&(pDevice->ChnlListSpinLock));
break;
case RT_PENDED_OID_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->PendedOidSpinLock));
break;
case RT_RFD_SPINLOCK:
NdisReleaseSpinLock(&(pDevice->RfdSpinLock));
break;
case RT_INDIC_SPINLOCK:
NdisReleaseSpinLock(&(pDevice->IndicSpinLock));
break;
#if DRV_LOG_REGISTRY
case RT_DRV_STATE_SPINLOCK:
NdisReleaseSpinLock(&(pDevice->DrvStateSpinLock));
break;
#endif
#if (AUTO_CHNL_SEL_NHM == 1)
case RT_ACS_SPINLOCK:
NdisReleaseSpinLock(&(pDevice->AcsSpinLock));
break;
#endif
case RT_RX_REF_CNT_SPINLOCK:
NdisReleaseSpinLock(&(pDevice->RxRefCntSpinLock));
break;
case RT_SYNC_IO_CNT_SPINLOCK:
NdisReleaseSpinLock( &(pDevice->SyncIoCntSpinLock));
break;
case RT_CUSTOM_SCAN_SPINLOCK:
NdisReleaseSpinLock(&(pDevice->CustomScanSpinLock));
break;
default:
break;
}
}
u4Byte
PlatformAtomicExchange(
pu4Byte target,
u4Byte value
)
{
return InterlockedExchange(target, value);
}
// 20100211 Joseph: Since there is no support to InterlockedAnd() and InterlockedOr() function for XP platform,
// we just implement the same function as DDK does.
u4Byte
PlatformAtomicAnd(
pu1Byte target,
u1Byte value
)
{
u4Byte i, j;
u4Byte tmp = (0xffffff00|value);
j = *target;
do {
i = j;
j = InterlockedCompareExchange((pu4Byte)target, (i&tmp), i);
} while (i != j);
return j;
}
// 20100211 Joseph: Since there is no support to InterlockedAnd() and InterlockedOr() function for XP platform,
// we just implement the same function as DDK does.
u4Byte
PlatformAtomicOr(
pu1Byte target,
u1Byte value
)
{
u4Byte i, j;
u4Byte tmp = (0x00000000|value);
j = *target;
do {
i = j;
j = InterlockedCompareExchange((pu4Byte)target, (i|tmp), i);
} while (i != j);
return j;
}
VOID
PlatformInitializeMutex(
IN PPlatformMutex Mutex
)
{
KeInitializeMutex(Mutex, 0);
}
VOID
PlatformAcquireMutex(
IN PPlatformMutex Mutex
)
{
LARGE_INTEGER lTimeout;
if (KeGetCurrentIrql() == DISPATCH_LEVEL)
{
lTimeout.QuadPart = 0;
KeWaitForMutexObject(Mutex, Executive, KernelMode, FALSE, &lTimeout);
}
else
KeWaitForMutexObject(Mutex, Executive, KernelMode, FALSE, NULL);
}
VOID
PlatformReleaseMutex(
IN PPlatformMutex Mutex
)
{
KeReleaseMutex(Mutex, FALSE);
}
VOID
PlatformCriticalSectionEnter(
IN PADAPTER pAdapter,
IN PPlatformMutex Mutex,
IN RT_SPINLOCK_TYPE Spinlock
)
{
PlatformAcquireMutex(Mutex);
}
VOID
PlatformCriticalSectionLeave(
IN PADAPTER pAdapter,
IN PPlatformMutex Mutex,
IN RT_SPINLOCK_TYPE Spinlock
)
{
PlatformReleaseMutex(Mutex);
}
//=========================================================================
//
// Get the unused instance index, if there is no index found, return 0xff
//
//=========================================================================
u8Byte
PlatformDivision64(
IN u8Byte x,
IN u8Byte y
)
{
return ((x) / (y));
}
u8Byte
PlatformModular64(
IN u8Byte x,
IN u8Byte y
)
{
return ((x) % (y));
}
//==========================================================================
//Platform function about Thread Create and Free
//==========================================================================
VOID
Ndis6EventTrigerThreadCallback(
IN PVOID pContext
)
{
PRT_THREAD pRtThread = (PRT_THREAD)pContext;
PADAPTER Adapter = ((PRT_THREAD)pContext)->Adapter;
PRT_NDIS_COMMON pNdisCommon = Adapter->pNdisCommon;
PRT_THREAD_PLATFORM_EXT pPlatformExt = (PRT_THREAD_PLATFORM_EXT)pRtThread->pPlatformExt;
if( pPlatformExt == NULL )
return;
NdisAcquireSpinLock(&(pPlatformExt->Lock));
if(pRtThread->Status & RT_THREAD_STATUS_CANCEL)
{
RT_TRACE(COMP_INIT, DBG_LOUD, ("Ndis6EventTrigerThreadCallback CANCEL! \n"));
NdisReleaseSpinLock(&(pPlatformExt->Lock));
goto Exit;
}
pRtThread->Status |=RT_THREAD_STATUS_FIRED;
NdisReleaseSpinLock(&(pPlatformExt->Lock));
while(!RT_DRIVER_STOP(Adapter))
{
NdisAcquireSpinLock(&(pPlatformExt->Lock));
if(pRtThread->Status & RT_THREAD_STATUS_CANCEL)
{
NdisReleaseSpinLock(&(pPlatformExt->Lock));
break;
}
else
NdisReleaseSpinLock(&(pPlatformExt->Lock));
if(NdisWaitEvent(&pPlatformExt->TrigerEvent, pPlatformExt->Period))
{
NdisAcquireSpinLock(&(pPlatformExt->Lock));
NdisResetEvent(&(pPlatformExt->TrigerEvent));
if(pRtThread->Status & RT_THREAD_STATUS_CANCEL)
{
NdisReleaseSpinLock(&(pPlatformExt->Lock));
break;
}
else
NdisReleaseSpinLock(&(pPlatformExt->Lock));
pRtThread->CallbackFunc(pRtThread);
NdisAcquireSpinLock(&(pPlatformExt->Lock));
pRtThread->ScheduleCnt++;
NdisReleaseSpinLock(&(pPlatformExt->Lock));
}
}
Exit:
if(pRtThread->PreTheradExitCb != NULL)
{
pRtThread->PreTheradExitCb(pRtThread);
}
NdisAcquireSpinLock(&(pPlatformExt->Lock));
pRtThread->RefCnt--;
pRtThread->Status &= ~RT_THREAD_STATUS_FIRED;
pRtThread->Status &= ~RT_THREAD_STATUS_SET;
NdisSetEvent(&(pPlatformExt->CompleteEvent));
NdisReleaseSpinLock(&(pPlatformExt->Lock));
if(Adapter->bSWInitReady)
{
NdisAcquireSpinLock(&(pNdisCommon->ThreadLock));
pNdisCommon->OutStandingThreadCnt--;
//
// Check if driver is waiting us to unload.
//
if(pNdisCommon->OutStandingThreadCnt == 0)
{
NdisReleaseSpinLock(&(pNdisCommon->ThreadLock));
NdisSetEvent(&(pNdisCommon->AllThreadCompletedEvent));
}
else
{
NdisReleaseSpinLock(&(pNdisCommon->ThreadLock));
}
}
PsTerminateSystemThread(STATUS_SUCCESS);// terminate the thread.
}
VOID
Ndis6ThreadCallback(
IN PVOID pContext
)
{
PRT_THREAD pRtThread = (PRT_THREAD)pContext;
PADAPTER Adapter = ((PRT_THREAD)pContext)->Adapter;
PRT_NDIS_COMMON pNdisCommon = Adapter->pNdisCommon;
PRT_THREAD_PLATFORM_EXT pPlatformExt = (PRT_THREAD_PLATFORM_EXT)pRtThread->pPlatformExt;
if( pPlatformExt == NULL )
return;
NdisAcquireSpinLock(&(pPlatformExt->Lock));
if(pRtThread->Status & RT_THREAD_STATUS_CANCEL)
{
NdisReleaseSpinLock(&(pPlatformExt->Lock));
goto Exit;
}
pRtThread->Status |=RT_THREAD_STATUS_FIRED;
NdisReleaseSpinLock(&(pPlatformExt->Lock));
if(!RT_DRIVER_STOP(Adapter))
{
pRtThread->CallbackFunc(pRtThread);
NdisAcquireSpinLock(&(pPlatformExt->Lock));
pRtThread->ScheduleCnt++;
NdisReleaseSpinLock(&(pPlatformExt->Lock));
}
Exit:
NdisAcquireSpinLock(&(pPlatformExt->Lock));
pRtThread->RefCnt--;
pRtThread->Status &= ~RT_THREAD_STATUS_FIRED;
pRtThread->Status &= ~RT_THREAD_STATUS_SET;
NdisSetEvent(&(pPlatformExt->CompleteEvent));
NdisReleaseSpinLock(&(pPlatformExt->Lock));
NdisAcquireSpinLock(&(pNdisCommon->ThreadLock));
pNdisCommon->OutStandingThreadCnt--;
//
// Check if driver is waiting us to unload.
//
if(pNdisCommon->OutStandingThreadCnt == 0)
{
NdisReleaseSpinLock(&(pNdisCommon->ThreadLock));
NdisSetEvent(&(pNdisCommon->AllThreadCompletedEvent));
}
else
{
NdisReleaseSpinLock(&(pNdisCommon->ThreadLock));
}
PsTerminateSystemThread(STATUS_SUCCESS);// terminate the thread.
}
RT_STATUS
PlatformInitializeThread(
IN PADAPTER Adapter,
IN PRT_THREAD pRtThread,
IN RT_THREAD_CALL_BACK CallBackFunc,
IN const char* szID,
IN BOOLEAN EventTriger,
IN u4Byte Period,
IN PVOID pContext
)
{
PRT_NDIS_COMMON pNdisCommon = Adapter->pNdisCommon;
PRT_THREAD_PLATFORM_EXT pPlatformExt =NULL;
RT_STATUS status = RT_STATUS_SUCCESS;
pRtThread->pPlatformExt = NULL;
status = PlatformAllocateMemory(Adapter, (PVOID*)(&pPlatformExt), sizeof(RT_THREAD_PLATFORM_EXT) );
if (status != RT_STATUS_SUCCESS)
{
RT_TRACE(COMP_DBG, DBG_SERIOUS, ("PlatformInitializeThread(): failed to allocate memory: %s\n", szID));
return RT_STATUS_RESOURCE;
}
PlatformZeroMemory( pPlatformExt, sizeof(RT_THREAD_PLATFORM_EXT) );
pRtThread->pPlatformExt = pPlatformExt;
NdisAllocateSpinLock(&(pPlatformExt->Lock));
NdisInitializeEvent(&(pPlatformExt->CompleteEvent));
NdisSetEvent(&(pPlatformExt->CompleteEvent));
NdisInitializeEvent(&(pPlatformExt->TrigerEvent));
NdisSetEvent(&(pPlatformExt->TrigerEvent));
pPlatformExt->Period = Period;
pRtThread->bEventTriger = EventTriger;
pRtThread->Adapter= Adapter;
pRtThread->Status = RT_THREAD_STATUS_INITIALIZED;
pRtThread->RefCnt = 1;
pRtThread->ScheduleCnt = 0;
pRtThread->CallbackFunc = CallBackFunc;
pRtThread->PreTheradExitCb = NULL;
if(szID != NULL)
{
ASCII_STR_COPY(pRtThread->szID, szID, 36);
}
pRtThread->Argc = 0;
pRtThread->pContext = pContext;
return RT_STATUS_SUCCESS;
}
RT_STATUS
PlatformInitializeThreadEx(
IN PADAPTER Adapter,
IN PRT_THREAD pRtThread,
IN RT_THREAD_CALL_BACK CallBackFunc,
IN RT_THREAD_CALL_BACK PreThreadExitCb,
IN const char* szID,
IN BOOLEAN EventTriger,
IN u4Byte Period,
IN PVOID pContext
)
{
RT_STATUS status = RT_STATUS_SUCCESS;
status = PlatformInitializeThread(Adapter, pRtThread, CallBackFunc, szID, EventTriger, Period, pContext);
if(RT_STATUS_SUCCESS == status)
{
pRtThread->PreTheradExitCb = PreThreadExitCb;
}
return status;
}
VOID
PlatformSetEventToTrigerThread(
IN PADAPTER Adapter,
IN PRT_THREAD pRtThread
)
{
PRT_NDIS_COMMON pNdisCommon = Adapter->pNdisCommon;
PRT_THREAD_PLATFORM_EXT pPlatformExt = (PRT_THREAD_PLATFORM_EXT)pRtThread->pPlatformExt;
if( pPlatformExt == NULL )
return;
NdisAcquireSpinLock(&(pPlatformExt->Lock));
if(pRtThread->Status & RT_THREAD_STATUS_CANCEL)
{
NdisReleaseSpinLock(&(pPlatformExt->Lock));
return;
}
NdisSetEvent(&(pPlatformExt->TrigerEvent));
NdisReleaseSpinLock(&(pPlatformExt->Lock));
return;
}
RT_STATUS
PlatformSetEventTrigerThread(
IN PADAPTER Adapter,
IN PRT_THREAD pRtThread,
IN RT_THREAD_LEVEL Priority,
IN PVOID pContext
)
{
HANDLE ThreadHandle;
NDIS_STATUS Status;
OBJECT_ATTRIBUTES ObjectAttribs;
PRT_NDIS_COMMON pNdisCommon = Adapter->pNdisCommon;
PRT_THREAD_PLATFORM_EXT pPlatformExt = (PRT_THREAD_PLATFORM_EXT)pRtThread->pPlatformExt;
if( pPlatformExt == NULL )
return RT_STATUS_FAILURE;
if(RT_DRIVER_HALT(Adapter))
{
RT_TRACE(COMP_SYSTEM, DBG_LOUD,
("driver is halted pRtThread(%s) cannot schedule !!!\n", pRtThread->szID));
return RT_STATUS_FAILURE;
}
NdisAcquireSpinLock(&(pPlatformExt->Lock));
if(pRtThread->Status & RT_THREAD_STATUS_RELEASED)
{
RT_TRACE(COMP_SYSTEM, DBG_WARNING,
("pRtThread(%s) is alreadyreleased!!!\n", pRtThread->szID));
NdisReleaseSpinLock(&(pPlatformExt->Lock));
return RT_STATUS_FAILURE;
}
if(!(pRtThread->Status & RT_THREAD_STATUS_INITIALIZED))
{
RT_TRACE(COMP_SYSTEM, DBG_WARNING,
("pRtThread(%s) is not yet initialized!!! Status 0x%x\n", pRtThread->szID, pRtThread->Status));
NdisReleaseSpinLock(&(pPlatformExt->Lock));
return RT_STATUS_FAILURE;
}
NdisReleaseSpinLock(&(pPlatformExt->Lock));
if(!NdisWaitEvent(&(pPlatformExt->CompleteEvent),2000))
{
RT_TRACE(COMP_SYSTEM, DBG_LOUD,
("pRtThread(%s) is not Complete, cannot set again!!!\n", pRtThread->szID));
return RT_STATUS_FAILURE;
}
NdisAcquireSpinLock(&(pPlatformExt->Lock));
NdisResetEvent(&(pPlatformExt->CompleteEvent));
NdisReleaseSpinLock(&(pPlatformExt->Lock));
do
{
InitializeObjectAttributes(&ObjectAttribs,
NULL, // ObjectName
OBJ_KERNEL_HANDLE,
NULL, // RootDir
NULL); // Security Desc
NdisAcquireSpinLock(&(pPlatformExt->Lock));
pRtThread->RefCnt++;
pRtThread->Status |= RT_THREAD_STATUS_SET;
pRtThread->pContext = pContext;
NdisReleaseSpinLock(&(pPlatformExt->Lock));
NdisAcquireSpinLock(&(pNdisCommon->ThreadLock));
pNdisCommon->OutStandingThreadCnt++;
NdisReleaseSpinLock(&(pNdisCommon->ThreadLock));
Status = PsCreateSystemThread(&ThreadHandle,
THREAD_ALL_ACCESS,
&ObjectAttribs,
NULL, // ProcessHandle
NULL, // ClientId
Ndis6EventTrigerThreadCallback,
pRtThread);
if (!NT_SUCCESS(Status))
{
RT_TRACE(COMP_INIT, DBG_SERIOUS, ("Worker Thread creation failed with 0x%lx\n", Status));
NdisAcquireSpinLock(&(pPlatformExt->Lock));
pRtThread->RefCnt--;
pRtThread->Status &= ~RT_THREAD_STATUS_SET;
NdisReleaseSpinLock(&(pPlatformExt->Lock));
if(Adapter->bSWInitReady)
{
NdisAcquireSpinLock(&(pNdisCommon->ThreadLock));
pNdisCommon->OutStandingThreadCnt--;
if(pNdisCommon->OutStandingThreadCnt == 0)
NdisSetEvent(&(pNdisCommon->AllThreadCompletedEvent));
NdisReleaseSpinLock(&(pNdisCommon->ThreadLock));
}
NdisAcquireSpinLock(&(pPlatformExt->Lock));
NdisSetEvent(&(pPlatformExt->CompleteEvent));
NdisReleaseSpinLock(&(pPlatformExt->Lock));
break;
}
Status = ObReferenceObjectByHandle(ThreadHandle,
THREAD_ALL_ACCESS,
NULL,
KernelMode,
&pPlatformExt->Thread,
NULL);
//Need to check status return;
if (Priority != 0)
{
KeSetPriorityThread(pPlatformExt->Thread, (KPRIORITY)Priority);
}
ZwClose(ThreadHandle);
}while(FALSE);
return RT_STATUS_SUCCESS;
}
RT_STATUS
PlatformRunThread(
IN PADAPTER Adapter,
IN PRT_THREAD pRtThread,
IN RT_THREAD_LEVEL Priority,
IN PVOID pContext
)
{
HANDLE ThreadHandle;
NDIS_STATUS Status;
OBJECT_ATTRIBUTES ObjectAttribs;
PRT_NDIS_COMMON pNdisCommon = Adapter->pNdisCommon;
PRT_THREAD_PLATFORM_EXT pPlatformExt = (PRT_THREAD_PLATFORM_EXT)pRtThread->pPlatformExt;
if( pPlatformExt == NULL )
return RT_STATUS_FAILURE;
if(RT_DRIVER_HALT(Adapter))
{
RT_TRACE(COMP_SYSTEM, DBG_LOUD,
("driver is halted pRtThread(%s) cannot schedule !!!\n", pRtThread->szID));
return RT_STATUS_FAILURE;
}
NdisAcquireSpinLock(&(pPlatformExt->Lock));
if(pRtThread->Status & RT_THREAD_STATUS_RELEASED)
{
RT_TRACE(COMP_SYSTEM, DBG_WARNING, ("pRtThread(%s) is alreadyreleased!!!\n", pRtThread->szID));
NdisReleaseSpinLock(&(pPlatformExt->Lock));
return RT_STATUS_FAILURE;
}
if(!(pRtThread->Status & RT_THREAD_STATUS_INITIALIZED))
{
RT_ASSERT(FALSE, ("pRtThread(%s) is not yet initialized!!! Status 0x%x\n", pRtThread->szID, pRtThread->Status));
NdisReleaseSpinLock(&(pPlatformExt->Lock));
return RT_STATUS_FAILURE;
}
NdisReleaseSpinLock(&(pPlatformExt->Lock));
if(!NdisWaitEvent(&(pPlatformExt->CompleteEvent),2000))
{
RT_TRACE(COMP_SYSTEM, DBG_WARNING,
("pRtThread(%s) is not Complete, cannot set again!!!\n", pRtThread->szID));
return RT_STATUS_FAILURE;
}
NdisAcquireSpinLock(&(pPlatformExt->Lock));
NdisResetEvent(&(pPlatformExt->CompleteEvent));
NdisReleaseSpinLock(&(pPlatformExt->Lock));
do
{
InitializeObjectAttributes(&ObjectAttribs,
NULL, // ObjectName
OBJ_KERNEL_HANDLE,
NULL, // RootDir
NULL); // Security Desc
NdisAcquireSpinLock(&(pPlatformExt->Lock));
pRtThread->RefCnt++;
pRtThread->Status |= RT_THREAD_STATUS_SET;
pRtThread->pContext = pContext;
NdisReleaseSpinLock(&(pPlatformExt->Lock));
NdisAcquireSpinLock(&(pNdisCommon->ThreadLock));
pNdisCommon->OutStandingThreadCnt++;
NdisReleaseSpinLock(&(pNdisCommon->ThreadLock));
Status = PsCreateSystemThread(&ThreadHandle,
THREAD_ALL_ACCESS,
&ObjectAttribs,
NULL, // ProcessHandle
NULL, // ClientId
Ndis6ThreadCallback,
pRtThread);
if (!NT_SUCCESS(Status))
{
RT_TRACE(COMP_SYSTEM, DBG_SERIOUS, ("Worker Thread creation failed with 0x%lx\n", Status));
NdisAcquireSpinLock(&(pPlatformExt->Lock));
pRtThread->RefCnt--;
pRtThread->Status &= ~RT_THREAD_STATUS_SET;
NdisReleaseSpinLock(&(pPlatformExt->Lock));
NdisAcquireSpinLock(&(pNdisCommon->ThreadLock));
pNdisCommon->OutStandingThreadCnt--;
if(pNdisCommon->OutStandingThreadCnt == 0)
NdisSetEvent(&(pNdisCommon->AllThreadCompletedEvent));
NdisReleaseSpinLock(&(pNdisCommon->ThreadLock));
NdisAcquireSpinLock(&(pPlatformExt->Lock));
NdisSetEvent(&(pPlatformExt->CompleteEvent));
NdisReleaseSpinLock(&(pPlatformExt->Lock));
break;
}
Status = ObReferenceObjectByHandle(ThreadHandle,
THREAD_ALL_ACCESS,
NULL,
KernelMode,
&pPlatformExt->Thread,
NULL);
//Need to check status return;
if (Priority != 0)
{
KeSetPriorityThread(pPlatformExt->Thread, (KPRIORITY)Priority);
}
ZwClose(ThreadHandle);
}while(FALSE);
return RT_STATUS_SUCCESS;
}
VOID
PlatformCancelThread(
IN PADAPTER pAdapter,
IN PRT_THREAD pRtThread)
{
PRT_NDIS_COMMON pNdisCommon = pAdapter->pNdisCommon;
PRT_THREAD_PLATFORM_EXT pPlatformExt = (PRT_THREAD_PLATFORM_EXT)pRtThread->pPlatformExt;
if( pPlatformExt == NULL )
return ;
NdisAcquireSpinLock(&(pPlatformExt->Lock));
if(pRtThread->Status & RT_THREAD_STATUS_RELEASED ||
(!(pRtThread->Status & RT_THREAD_STATUS_INITIALIZED)))
{
NdisReleaseSpinLock(&(pPlatformExt->Lock));
return;
}
if(pRtThread->Status & RT_THREAD_STATUS_FIRED) // already fired and not finish. waiting for the thread complete.
{
pRtThread->Status |= RT_THREAD_STATUS_CANCEL;
NdisReleaseSpinLock(&(pPlatformExt->Lock));
NdisSetEvent(&(pPlatformExt->TrigerEvent));
NdisWaitEvent(&(pPlatformExt->CompleteEvent),0);
}
else if(pRtThread->Status & RT_THREAD_STATUS_SET) // set but not fired. This thread would not be fired
{
pRtThread->Status |= RT_THREAD_STATUS_CANCEL;
NdisReleaseSpinLock(&(pPlatformExt->Lock));
NdisSetEvent(&(pPlatformExt->TrigerEvent));
NdisWaitEvent(&(pPlatformExt->CompleteEvent),0);
}
else
{
NdisReleaseSpinLock(&(pPlatformExt->Lock));
// thread been canceled
NdisAcquireSpinLock(&(pNdisCommon->ThreadLock));
if(pNdisCommon->OutStandingThreadCnt == 0)
NdisSetEvent(&(pNdisCommon->AllThreadCompletedEvent));
NdisReleaseSpinLock(&(pNdisCommon->ThreadLock));
}
}
VOID
PlatformWaitThreadEnd(
IN PADAPTER pAdapter,
IN PRT_THREAD pRtThread)
{
PRT_THREAD_PLATFORM_EXT pPlatformExt = (PRT_THREAD_PLATFORM_EXT)pRtThread->pPlatformExt;
u4Byte i = 0;
if( pPlatformExt == NULL )
return ;
NdisAcquireSpinLock(&(pPlatformExt->Lock));
if(pRtThread->Status & RT_THREAD_STATUS_RELEASED ||
(!(pRtThread->Status & RT_THREAD_STATUS_INITIALIZED)))
{
NdisReleaseSpinLock(&(pPlatformExt->Lock));
return;
}
if( !(pRtThread->Status & RT_THREAD_STATUS_SET) )
{
NdisReleaseSpinLock(&(pPlatformExt->Lock));
return;
}
NdisReleaseSpinLock(&(pPlatformExt->Lock));
KeWaitForSingleObject(pPlatformExt->Thread,Executive, KernelMode, FALSE, NULL);
ObDereferenceObject(pPlatformExt->Thread);
}
VOID
PlatformReleaseThread(
IN PADAPTER pAdapter,
IN PRT_THREAD pRtThread)
{
PRT_THREAD_PLATFORM_EXT pPlatformExt = (PRT_THREAD_PLATFORM_EXT)pRtThread->pPlatformExt;
if( pPlatformExt == NULL )
return ;
NdisAcquireSpinLock(&(pPlatformExt->Lock));
if(pRtThread->Status & RT_THREAD_STATUS_RELEASED ||
(!(pRtThread->Status & RT_THREAD_STATUS_INITIALIZED)))
{
NdisReleaseSpinLock(&(pPlatformExt->Lock));
return;
}
pRtThread->Status |= RT_THREAD_STATUS_RELEASED;
//Fix S3 BSOD, by YJ,120719
pRtThread->pPlatformExt = NULL;
NdisReleaseSpinLock(&(pPlatformExt->Lock));
NdisFreeSpinLock(&(pPlatformExt->Lock)); // may have some issue?
PlatformFreeMemory( pPlatformExt, sizeof(RT_THREAD_PLATFORM_EXT) );
}
//
// Description:
// This routine initializes a semaphore object with a specified count and
// specifies an upper limit that the count can attain.
//
// Created by Roger, 2011.01.17.
//
VOID
PlatformInitializeSemaphore(
IN PPlatformSemaphore Sema,
IN u4Byte InitCnt
)
{
//
// We create this semaphore with an initial count of zero to block access to the protected resource
// while the application is being initialized. After initialization, we can use ReleaseSemaphore to increment
// the count to the maximum value.
//
KeInitializeSemaphore(
Sema,
InitCnt, // Count
SEMA_UPBND); // Limit
}
//
// Description:
// This routine waits for the semaphore object state to become signaled.
//
// Created by Roger, 2011.01.17.
//
RT_STATUS
PlatformAcquireSemaphore(
IN PPlatformSemaphore Sema
)
{
RT_STATUS status = RT_STATUS_FAILURE;
if( STATUS_SUCCESS == KeWaitForSingleObject(Sema, Executive, KernelMode, TRUE, NULL) )
status = RT_STATUS_SUCCESS;
return status;
}
//
// Description:
// This routine increases a semaphore's count by a specified amount.
//
// Created by Roger, 2011.01.17.
//
VOID
PlatformReleaseSemaphore(
IN PPlatformSemaphore Sema
)
{
if (Sema->Header.Type == 0)
return;
KeReleaseSemaphore(
Sema,
IO_NETWORK_INCREMENT, // Priority increment
1, // Adjustment, a value to be added
FALSE ); // Will not be followed immediately by a call to one of the KeWaitXxx routines
}
//
// Description:
// This routine frees a semaphore object
//
// Created by Roger, 2011.01.17.
//
VOID
PlatformFreeSemaphore(
IN PPlatformSemaphore Sema
)
{
if (Sema->Header.Type == 0)
return;
}
//
// Description:
// This routine initializes a event object
//
// Created by Cosa, 2012.01.09.
//
VOID
PlatformInitializeEvent(
IN PPlatformEvent pEvent
)
{
NdisInitializeEvent(pEvent);
}
VOID
PlatformResetEvent(
IN PPlatformEvent pEvent
)
{
NdisResetEvent(pEvent);
}
VOID
PlatformSetEvent(
IN PPlatformEvent pEvent
)
{
NdisSetEvent(pEvent);
}
VOID
PlatformFreeEvent(
IN PPlatformEvent pEvent
)
{
}
BOOLEAN
PlatformWaitEvent(
IN PPlatformEvent pEvent,
IN u4Byte msToWait
)
{
return NdisWaitEvent(pEvent, msToWait);
}
//
// 2011/04/08 MH Merge for return pending packet for WINDOWS.
//
VOID
PlatformReturnAllPendingTxPackets(
IN PADAPTER pAdapter
)
{
N6SdioReturnAllPendingTxPackets(pAdapter);
}
VOID
PlatformRestoreLastInitSetting(
IN PADAPTER pAdapter
)
{
N6RestoreLastInitSettingAterWakeUP(pAdapter);
}
BOOLEAN
PlatformIsOverrideAddress(
IN PADAPTER Adapter
)
{
PRT_NDIS_COMMON pNdisCommon = Adapter->pNdisCommon;
if(pNdisCommon->bOverrideAddress)
{
u1Byte nulladdr[6] = {0, 0, 0, 0, 0, 0};
if(PlatformCompareMemory(nulladdr, pNdisCommon->CurrentAddress, 6) == 0)
return FALSE;
}
return pNdisCommon->bOverrideAddress;
}
pu1Byte
PlatformGetOverrideAddress(
IN PADAPTER Adapter
)
{
PRT_NDIS_COMMON pNdisCommon = Adapter->pNdisCommon;
return pNdisCommon->CurrentAddress;
}
//===================================
// If we are goting to stop vwifi support, then it will drop
// all connections connected with the vwifi and indicate
// to OS that can't support anymore. Otherwise, when we
// need to support vwifi again, we need to
// indicate to OS that we can sustain vwifi.
//===================================
VOID
PlatformExtApSupport(
IN PADAPTER Adapter,
IN BOOLEAN bSupport
)
{
PADAPTER pExtAdapter;
pExtAdapter = GetFirstExtAdapter(Adapter);
if( NULL != pExtAdapter)
{
if(!bSupport)
{
N62CStopApMode(pExtAdapter);
}
else
{
N62CApIndicateCanSustainAp(pExtAdapter);
}
}
}
BOOLEAN
PlatformInitReady(
IN PADAPTER Adapter
)
{
if(!N6_INIT_READY(Adapter))
{
return FALSE;
}
else
return TRUE;
}
VOID
Dot11_UpdateDefaultSetting(
IN PADAPTER pAdapter
)
{
PMGNT_INFO pMgntInfo = &(pAdapter->MgntInfo);
PRT_CHANNEL_INFO pChnlInfo = pMgntInfo->pChannelInfo;
PRT_NDIS_COMMON pNdisCommon = pAdapter->pNdisCommon;
EXTCHNL_OFFSET extchnl = EXTCHNL_OFFSET_NO_EXT;
// SSID.
CopySsid(pMgntInfo->Ssid.Octet, pMgntInfo->Ssid.Length, pNdisCommon->RegSSID.Octet, pNdisCommon->RegSSID.Length);
// Default wireless mode.
pAdapter->RegOrigWirelessMode = (WIRELESS_MODE)(pNdisCommon->RegWirelessMode);
pAdapter->RegHTMode = (HT_MODE)(pNdisCommon->RegHTMode);
if(pAdapter->RegHTMode == HT_MODE_UNDEFINED)
{
pAdapter->RegWirelessMode = pAdapter->RegOrigWirelessMode;
pAdapter->RegOrigWirelessMode = 0xFFFF;
pAdapter->RegHTMode = HT_MODE_VHT;
}
else
{
if(IS_WIRELESS_MODE_A_ONLY(pAdapter->RegOrigWirelessMode)) // A only
{
if(IS_VHT_SUPPORTED(pAdapter))
pAdapter->RegWirelessMode = WIRELESS_MODE_AC_5G;
else if(IS_HT_SUPPORTED(pAdapter))
pAdapter->RegWirelessMode = WIRELESS_MODE_N_5G;
else
pAdapter->RegWirelessMode = WIRELESS_MODE_A;
}
else if(IS_WIRELESS_MODE_B_ONLY(pAdapter->RegOrigWirelessMode)) // B only
{
pAdapter->RegWirelessMode = WIRELESS_MODE_B;
pAdapter->RegHTMode = HT_MODE_DISABLE;
}
else if(IS_WIRELESS_MODE_G_AND_BG(pAdapter->RegOrigWirelessMode)) // G only, B/G
{
if(IS_HT_SUPPORTED(pAdapter))
pAdapter->RegWirelessMode = WIRELESS_MODE_N_24G;
else
pAdapter->RegWirelessMode = WIRELESS_MODE_G;
}
else
{
pAdapter->RegWirelessMode = WIRELESS_MODE_AUTO; // A/G, A/B/G
}
}
{
pMgntInfo->Regdot11ChannelNumber = (u1Byte)(pNdisCommon->RegChannel);
if(pMgntInfo->Regdot11ChannelNumber <= 14)
{
if(IS_5G_WIRELESS_MODE(pAdapter->RegWirelessMode))
pMgntInfo->Regdot11ChannelNumber = 36;
}
else
{
if(IS_24G_WIRELESS_MODE(pAdapter->RegWirelessMode))
pMgntInfo->Regdot11ChannelNumber = 10;
}
}
if(GetDefaultAdapter(pAdapter)->bInHctTest)
pMgntInfo->Regdot11ChannelNumber = 10;
pMgntInfo->dot11CurrentChannelNumber = pMgntInfo->Regdot11ChannelNumber;
pChnlInfo->PrimaryChannelNumber = pMgntInfo->dot11CurrentChannelNumber;
pChnlInfo->CurrentChannelCenterFrequency = pMgntInfo->dot11CurrentChannelNumber;
if(pAdapter->bInHctTest)
pChnlInfo->RegBWSetting = CHANNEL_WIDTH_20;
else
pChnlInfo->RegBWSetting = pNdisCommon->RegBWSetting;
// Auto select channel.
pMgntInfo->bAutoSelChnl = (BOOLEAN)pNdisCommon->RegAutoSelChnl;
pMgntInfo->ChnlWeightMode = (u1Byte)pNdisCommon->RegChnlWeight;
// Force Tx rate.
pMgntInfo->ForcedDataRate = pNdisCommon->RegForcedDataRate;
// Set the BeaconType By Bruce, 2011-01-18.
pAdapter->HalFunc.SetHalDefVarHandler(pAdapter, HAL_DEF_HW_BEACON_SUPPORT, (pu1Byte)&(pNdisCommon->RegEnableSwBeacon));
// AP mode related. 2005.05.30, by rcnjko.
pMgntInfo->Regdot11BeaconPeriod = (u2Byte)(pNdisCommon->RegBeaconPeriod);
pMgntInfo->dot11BeaconPeriod = pMgntInfo->Regdot11BeaconPeriod;
pMgntInfo->Regdot11DtimPeriod = (u1Byte)(pNdisCommon->RegDtimPeriod);
pMgntInfo->dot11DtimPeriod = pMgntInfo->Regdot11DtimPeriod;
pMgntInfo->RegPreambleMode = (u1Byte)(pNdisCommon->RegPreambleMode);
pMgntInfo->dot11CurrentPreambleMode = pMgntInfo->RegPreambleMode;
#if 0
// Channel / BW setting
if(pChnlInfo->RegBWSetting == CHANNEL_WIDTH_20)
extchnl = EXTCHNL_OFFSET_NO_EXT;
else
{
if(CHNL_IsLegal5GChannel(pAdapter, pMgntInfo ->Regdot11ChannelNumber))
extchnl = CHNL_GetExt20OffsetOf5G(pMgntInfo->dot11CurrentChannelNumber);
else if(pChnlInfo->RegBWSetting == CHANNEL_WIDTH_80)
{
if(pMgntInfo->dot11CurrentChannelNumber == 1 || pMgntInfo->dot11CurrentChannelNumber == 9)
extchnl = EXTCHNL_OFFSET_UPPER;
else
extchnl = EXTCHNL_OFFSET_LOWER;
}
else
extchnl =(pMgntInfo->dot11CurrentChannelNumber<=7)? EXTCHNL_OFFSET_UPPER:EXTCHNL_OFFSET_LOWER;
}
pMgntInfo->SettingBeforeScan.ChannelNumber = pMgntInfo->Regdot11ChannelNumber;
pMgntInfo->SettingBeforeScan.ChannelBandwidth = pChnlInfo->RegBWSetting;
pMgntInfo->SettingBeforeScan.Ext20MHzChnlOffsetOf40MHz = extchnl;
pMgntInfo->SettingBeforeScan.Ext40MHzChnlOffsetOf80MHz = extchnl;
pMgntInfo->SettingBeforeScan.CenterFrequencyIndex1 = CHNL_GetCenterFrequency(pMgntInfo->SettingBeforeScan.ChannelNumber, pChnlInfo->RegBWSetting, extchnl);
#endif
}
VOID
HT_UpdateDefaultSetting(
IN PADAPTER pAdapter
)
{
PMGNT_INFO pMgntInfo = &(pAdapter->MgntInfo);
PRT_HIGH_THROUGHPUT pHTInfo = GET_HT_INFO(pMgntInfo);
PRT_NDIS_COMMON pNdisCommon = pAdapter->pNdisCommon;
BOOLEAN bHwLDPCSupport = FALSE, bHwSTBCSupport = FALSE;
BOOLEAN bHwSupportBeamformer = FALSE, bHwSupportBeamformee = FALSE;
if(pMgntInfo->bWiFiConfg)
pHTInfo->bBssCoexist = TRUE;
else
pHTInfo->bBssCoexist = FALSE;
pHTInfo->bRegBW40MHzFor2G = pNdisCommon->bRegBW40MHzFor2G;
pHTInfo->bRegBW40MHzFor5G = pNdisCommon->bRegBW40MHzFor5G;
// 11n adhoc support
pMgntInfo->bReg11nAdhoc = pNdisCommon->bReg11nAdhoc;
// 11ac Bcm 256QAM support
pMgntInfo->bRegIOTBcm256QAM = pNdisCommon->bRegIOTBcm256QAM;
// CCK rate support in 40MHz channel
if(pNdisCommon->RegBWSetting)
pHTInfo->bRegSuppCCK = pNdisCommon->bRegHT_EnableCck;
else
pHTInfo->bRegSuppCCK = TRUE;
// AMSDU related
pHTInfo->nAMSDU_MaxSize = (u2Byte)pNdisCommon->RegAMSDU_MaxSize;
pHTInfo->bAMSDU_Support = (BOOLEAN)pNdisCommon->RegAMSDU;
pHTInfo->bHWAMSDU_Support = (BOOLEAN)pNdisCommon->RegHWAMSDU;
// AMPDU related
if(pAdapter->bInHctTest)
pHTInfo->bAMPDUEnable = FALSE;
else
pHTInfo->bAMPDUEnable = (BOOLEAN)pNdisCommon->bRegAMPDUEnable;
pHTInfo->AMPDU_Factor = (u1Byte)pNdisCommon->RegAMPDU_Factor;
pHTInfo->MPDU_Density = (u1Byte)pNdisCommon->RegMPDU_Density;
// Accept ADDBA Request
pHTInfo->bAcceptAddbaReq = (BOOLEAN)(pNdisCommon->bRegAcceptAddbaReq);
// MIMO Power Save
pHTInfo->SelfMimoPs = (u1Byte)pNdisCommon->RegMimoPs;
if(pHTInfo->SelfMimoPs == 2)
pHTInfo->SelfMimoPs = 3;
// For Rx Reorder Control
// bRegRxReorderEnable default is FALSE if Rxreorder is swithed by TP since TP should be low as media just connect.
pHTInfo->bRegRxReorderEnable = ((pMgntInfo->RegRxReorder = pNdisCommon->RegRxReorder) ==2) ? FALSE : pNdisCommon->RegRxReorder;
pHTInfo->RxReorderWinSize = pMgntInfo->RegRxReorder_WinSize = pNdisCommon->RegRxReorder_WinSize;
pHTInfo->RxReorderPendingTime = pMgntInfo->RegRxReorder_PendTime = pNdisCommon->RegRxReorder_PendTime;
pHTInfo->bRegShortGI40MHz = TEST_FLAG(pNdisCommon->RegShortGISupport, BIT1) ? TRUE : FALSE;
pHTInfo->bRegShortGI20MHz = TEST_FLAG(pNdisCommon->RegShortGISupport, BIT0) ? TRUE : FALSE;
pHTInfo->b40Intolerant = pNdisCommon->bReg40Intolerant;
pHTInfo->bAMPDUManual = pNdisCommon->bRegAMPDUManual;
pHTInfo->nTxSPStream = pNdisCommon->RegTxSPStream;
//IOT issue with Atheros AP. If set incorrect, the Rx rate will always be MCS4.
if(pHTInfo->nRxSPStream == 0)
{
u1Byte Rf_Type = RT_GetRFType(pAdapter);
if(Rf_Type == RF_1T2R || Rf_Type == RF_2T2R)
pHTInfo->nRxSPStream = 2;
else if(Rf_Type == RF_3T3R || Rf_Type == RF_2T4R || Rf_Type == RF_4T4R || Rf_Type == RF_2T3R)
pHTInfo->nRxSPStream = 3;
else
pHTInfo->nRxSPStream = 1;
}
if(pHTInfo->nTxSPStream == 0)
{
u1Byte Rf_Type = RT_GetRFType(pAdapter);
if(Rf_Type == RF_1T2R || Rf_Type == RF_1T1R)
pHTInfo->nTxSPStream = 1;
else if(Rf_Type == RF_3T3R || Rf_Type == RF_4T4R)
pHTInfo->nTxSPStream = 3;
else
pHTInfo->nTxSPStream = 2;
}
// LDPC support
CLEAR_FLAGS(pHTInfo->HtLdpcCap);
// LDPC - Tx
pAdapter->HalFunc.GetHalDefVarHandler(pAdapter, HAL_DEF_TX_LDPC, (PBOOLEAN)&bHwLDPCSupport);
if(bHwLDPCSupport)
{
if(TEST_FLAG(pNdisCommon->RegLdpc, BIT5))
SET_FLAG(pHTInfo->HtLdpcCap, LDPC_HT_ENABLE_TX);
}
// LDPC - Rx
pAdapter->HalFunc.GetHalDefVarHandler(pAdapter, HAL_DEF_RX_LDPC, (PBOOLEAN)&bHwLDPCSupport);
if(bHwLDPCSupport)
{
if(TEST_FLAG(pNdisCommon->RegLdpc, BIT4))
SET_FLAG(pHTInfo->HtLdpcCap, LDPC_HT_ENABLE_RX);
}
RT_TRACE_F(COMP_HT, DBG_LOUD, ("[HT] Support LDOC = 0x%02X\n", pHTInfo->HtLdpcCap));
// STBC
if(pMgntInfo->bWiFiConfg)
bHwSTBCSupport = FALSE;
else
pAdapter->HalFunc.GetHalDefVarHandler(pAdapter, HAL_DEF_TX_STBC, (PBOOLEAN)&bHwSTBCSupport);
CLEAR_FLAGS(pHTInfo->HtStbcCap);
if(bHwSTBCSupport)
{
if(TEST_FLAG(pNdisCommon->RegStbc, BIT5))
SET_FLAG(pHTInfo->HtStbcCap, STBC_HT_ENABLE_TX);
}
if(pMgntInfo->bWiFiConfg)
bHwSTBCSupport = FALSE;
else
pAdapter->HalFunc.GetHalDefVarHandler(pAdapter, HAL_DEF_RX_STBC, (PBOOLEAN)&bHwSTBCSupport);
if(bHwSTBCSupport)
{
if(TEST_FLAG(pNdisCommon->RegStbc, BIT4))
SET_FLAG(pHTInfo->HtStbcCap, STBC_HT_ENABLE_RX);
}
RT_TRACE_F(COMP_HT, DBG_LOUD, ("[HT] Support STBC = 0x%02X\n", pHTInfo->HtStbcCap));
}
VOID
VHT_UpdateDefaultSetting(
IN PADAPTER pAdapter
)
{
PMGNT_INFO pMgntInfo = &(pAdapter->MgntInfo);
PRT_VERY_HIGH_THROUGHPUT pVHTInfo = GET_VHT_INFO(pMgntInfo);
PRT_NDIS_COMMON pNdisCommon = pAdapter->pNdisCommon;
BOOLEAN bHwLDPCSupport = FALSE, bHwSTBCSupport = FALSE;
BOOLEAN bHwSupportBeamformer = FALSE, bHwSupportBeamformee = FALSE;
BOOLEAN bHwSupportMuMimoAp = FALSE, bHwSupportMuMimoSta = FALSE;
if(pNdisCommon->RegBWSetting == 2)
{
pVHTInfo->bRegBW80MHz = TRUE;
pVHTInfo->bRegShortGI80MHz = TEST_FLAG(pNdisCommon->RegShortGISupport, BIT2) ? TRUE : FALSE;
}
else
{
pVHTInfo->bRegBW80MHz = FALSE;
pVHTInfo->bRegShortGI80MHz = FALSE;
}
//pVHTInfo->bRegShortGI80MHz = TEST_FLAG(pNdisCommon->RegShortGISupport, BIT2) ? TRUE : FALSE;
RT_TRACE(COMP_INIT, DBG_LOUD, ("bRegShortGI80MHz = %d\n", pVHTInfo->bRegShortGI80MHz));
pVHTInfo->nTxSPStream = pNdisCommon->RegTxSPStream;
pVHTInfo->nRxSPStream = pNdisCommon->RegRxSPStream;
//IOT issue with Atheros AP. If set incorrect, the Rx rate will always be MCS4.
if(pVHTInfo->nRxSPStream == 0)
{
u1Byte Rf_Type = RT_GetRFType(pAdapter);
if(Rf_Type == RF_1T2R || Rf_Type == RF_2T2R)
pVHTInfo->nRxSPStream = 2;
else if(Rf_Type == RF_3T3R || Rf_Type == RF_2T4R || Rf_Type == RF_4T4R || Rf_Type == RF_2T3R)
pVHTInfo->nRxSPStream = 3;
else
pVHTInfo->nRxSPStream = 1;
}
if(pVHTInfo->nTxSPStream == 0)
{
u1Byte Rf_Type = RT_GetRFType(pAdapter);
if(Rf_Type == RF_1T2R || Rf_Type == RF_1T1R)
pVHTInfo->nTxSPStream = 1;
else if(Rf_Type == RF_3T3R || Rf_Type == RF_4T4R)
pVHTInfo->nTxSPStream = 3;
else
pVHTInfo->nTxSPStream = 2;
}
// LDPC support
CLEAR_FLAGS(pVHTInfo->VhtLdpcCap);
// LDPC - Tx
pAdapter->HalFunc.GetHalDefVarHandler(pAdapter, HAL_DEF_TX_LDPC, (PBOOLEAN)&bHwLDPCSupport);
if(bHwLDPCSupport)
{
if(TEST_FLAG(pNdisCommon->RegLdpc, BIT1))
SET_FLAG(pVHTInfo->VhtLdpcCap, LDPC_VHT_ENABLE_TX);
}
// LDPC - Rx
pAdapter->HalFunc.GetHalDefVarHandler(pAdapter, HAL_DEF_RX_LDPC, (PBOOLEAN)&bHwLDPCSupport);
if(bHwLDPCSupport)
{
if(TEST_FLAG(pNdisCommon->RegLdpc, BIT0))
SET_FLAG(pVHTInfo->VhtLdpcCap, LDPC_VHT_ENABLE_RX);
}
RT_TRACE_F(COMP_INIT, DBG_LOUD, ("[VHT] Support LDPC = 0x%02X\n", pVHTInfo->VhtLdpcCap));
// STBC
pAdapter->HalFunc.GetHalDefVarHandler(pAdapter, HAL_DEF_TX_STBC, (PBOOLEAN)&bHwSTBCSupport);
CLEAR_FLAGS(pVHTInfo->VhtStbcCap);
if(bHwSTBCSupport)
{
if(TEST_FLAG(pNdisCommon->RegStbc, BIT1))
SET_FLAG(pVHTInfo->VhtStbcCap, STBC_VHT_ENABLE_TX);
}
pAdapter->HalFunc.GetHalDefVarHandler(pAdapter, HAL_DEF_RX_STBC, (PBOOLEAN)&bHwSTBCSupport);
if(bHwSTBCSupport)
{
if(TEST_FLAG(pNdisCommon->RegStbc, BIT0))
SET_FLAG(pVHTInfo->VhtStbcCap, STBC_VHT_ENABLE_RX);
}
RT_TRACE_F(COMP_INIT, DBG_LOUD, ("[VHT] Support STBC = 0x%02X\n", pVHTInfo->VhtStbcCap));
}
VOID
PSC_UpdateDefaultSetting(
IN PADAPTER pAdapter
)
{
PMGNT_INFO pMgntInfo = &(pAdapter->MgntInfo);
PRT_NDIS_COMMON pNdisCommon = pAdapter->pNdisCommon;
PRT_POWER_SAVE_CONTROL pPSC = GET_POWER_SAVE_CONTROL(pMgntInfo);
// For SDIO DPC ISR WHQL test setting.
// We should enable power saving mode to pass DPC USR test.
pMgntInfo->bSdioDpcIsr = (BOOLEAN)pNdisCommon->RegSdioDpcIsr;
//3 All Power Save Mechanism.
if((pAdapter->bInHctTest || pMgntInfo->bWiFiConfg) && !pMgntInfo->bSdioDpcIsr)
{
#if 0
if(pAdapter->bDPCISRTest)
{
pPSC->bInactivePs = TRUE;
pPSC->bLeisurePs = TRUE;
pMgntInfo->keepAliveLevel =pNdisCommon->RegKeepAliveLevel;
pPSC->bFwCtrlLPS = TRUE;
pPSC->FWCtrlPSMode = FW_PS_MIN_MODE;
DbgPrint("test set leisurePS and inactivePS to TRUE\n");
}
else
#endif
{
pPSC->bInactivePs = FALSE;
pNdisCommon->RegInactivePsMode = eIpsOff;
pPSC->bLeisurePs = FALSE;
pNdisCommon->RegLeisurePsMode = eLpsOff;
pMgntInfo->keepAliveLevel =0;
pPSC->bFwCtrlLPS = FALSE;
pNdisCommon->bRegFwCtrlLPS =0;
pPSC->bLeisurePsModeBackup = FALSE;
pPSC->FWCtrlPSMode = FW_PS_ACTIVE_MODE;
}
}
else
{
RT_TRACE(COMP_INIT, DBG_LOUD, ("pNdisCommon->RegInactivePsMode = %d\n", pNdisCommon->RegInactivePsMode));
if(pNdisCommon->RegInactivePsMode == eIpsAuto)
pPSC->bInactivePs = FALSE;
else
pPSC->bInactivePs = pNdisCommon->RegInactivePsMode;
pPSC->bLeisurePsModeBackup = FALSE;
//2008.08.25
if( (pNdisCommon->RegLeisurePsMode==eLpsOn) && (pMgntInfo->dot11PowerSaveMode == eActive) )
{
RT_TRACE(COMP_INIT, DBG_LOUD, ("LeisurePs On!!\n"));
pPSC->bLeisurePs = TRUE;
}
else if( (pNdisCommon->RegLeisurePsMode==eLpsAuto) && (pMgntInfo->dot11PowerSaveMode == eActive) )
{
RT_TRACE(COMP_INIT, DBG_LOUD, ("LeisurePs Off!!\n"));
pPSC->bLeisurePs = FALSE;
}
else
{
RT_TRACE(COMP_INIT, DBG_LOUD, ("LeisurePs Off!!\n"));
pPSC->bLeisurePs = FALSE;
}
pMgntInfo->keepAliveLevel =pNdisCommon->RegKeepAliveLevel;
//Fw Control LPS mode
if(pNdisCommon->bRegFwCtrlLPS == 0)
pPSC->bFwCtrlLPS = FALSE;
else
pPSC->bFwCtrlLPS = TRUE;
// We need to assign the FW PS mode value even if we do not enable LPS mode. 2012.03.05. by tynli.
if(pNdisCommon->bRegFwCtrlLPS == 0)
pPSC->FWCtrlPSMode = FW_PS_ACTIVE_MODE;
else if(pNdisCommon->bRegFwCtrlLPS == 1)
pPSC->FWCtrlPSMode = FW_PS_MIN_MODE;
else if(pNdisCommon->bRegFwCtrlLPS == 2)
pPSC->FWCtrlPSMode = FW_PS_MAX_MODE;
else if(pNdisCommon->bRegFwCtrlLPS == 3)
pPSC->FWCtrlPSMode = FW_PS_SELF_DEFINED_MODE;
//LPS 32K Support and Enable Deep Sleep
//by sherry 20150910
if((pNdisCommon->RegLeisurePsMode != eLpsOff) && (pNdisCommon->bRegLowPowerEnable) && (pNdisCommon->bRegLPSDeepSleepEnable))
{
RT_TRACE(COMP_INIT,DBG_LOUD,("PSC_UpdateDefaultSetting: Enable LPS Deep Sleep \n"));
FwLPSDeepSleepInit(pAdapter);
}
}
pPSC->bIPSModeBackup = pPSC->bInactivePs;
pPSC->bLeisurePsModeBackup = pPSC->bLeisurePs;
pPSC->RegMaxLPSAwakeIntvl = pNdisCommon->RegLPSMaxIntvl;
pPSC->RegAdvancedLPs = pNdisCommon->RegAdvancedLPs;
pPSC->bGpioRfSw = pNdisCommon->bRegGpioRfSw;
pPSC->RegLeisurePsMode = pNdisCommon->RegLeisurePsMode;
pPSC->RegPowerSaveMode = pNdisCommon->RegPowerSaveMode;
#if((USB_TX_THREAD_ENABLE && RTL8723_USB_IO_THREAD_ENABLE) || RTL8723_SDIO_IO_THREAD_ENABLE)
pPSC->bLowPowerEnable = (BOOLEAN)pNdisCommon->bRegLowPowerEnable;
#else
pPSC->bLowPowerEnable = 0;
#endif
//Set WoWLAN mode. 2009.09.01. by tynli
if(pNdisCommon->bRegWakeOnMagicPacket)
{
if(pNdisCommon->bRegWakeOnPattern)
pPSC->WoWLANMode = eWakeOnBothTypePacket;
else
pPSC->WoWLANMode = eWakeOnMagicPacketOnly;
}
else if(pNdisCommon->bRegWakeOnPattern)
{
pPSC->WoWLANMode = eWakeOnPatternMatchOnly;
}
else
{
pPSC->WoWLANMode = eWoWLANDisable;
}
pPSC->bWakeOnDisconnect = pNdisCommon->bRegWakeOnDisconnect;
if(pNdisCommon->bRegPacketCoalescing)
pMgntInfo->bSupportPacketCoalescing = TRUE;
else
pMgntInfo->bSupportPacketCoalescing = FALSE;
pPSC->APOffloadEnable = pNdisCommon->RegAPOffloadEnable;
pPSC->WoWLANLPSLevel = pNdisCommon->RegWoWLANLPSLevel ;
pPSC->WoWLANS5Support = pNdisCommon->RegWoWLANS5Support;
pPSC->D2ListenIntvl = pNdisCommon->RegD2ListenIntvl;
pPSC->bFakeWoWLAN = pNdisCommon->bRegFakeWoWLAN;
pPSC->RegARPOffloadEnable = pNdisCommon->bRegARPOffloadEnable;
pPSC->RegGTKOffloadEnable = pNdisCommon->bRegGTKOffloadEnable ; // support GTK offload after NDIS620.
pPSC->ProtocolOffloadDecision = pNdisCommon->RegProtocolOffloadDecision;
pPSC->RegNSOffloadEnable = pNdisCommon->bRegNSOffloadEnable;
pPSC->FSSDetection = pNdisCommon->RegFSSDetection;
pMgntInfo->bIntelPatchPNP = pNdisCommon->RegIntelPatchPNP;
pPSC->DxNLOEnable = pNdisCommon->RegNLOEnable;
pMgntInfo->bRegPnpKeepLink = (BOOLEAN)pNdisCommon->RegPnpKeepLink;
pPSC->bFwCtrlPwrOff = (BOOLEAN)pNdisCommon->RegFwCtrlPwrOff;
pPSC->CardDisableInLowClk = (BOOLEAN)pNdisCommon->RegCardDisableInLowClk;
pPSC->FwIPSLevel = pNdisCommon->RegFwIPSLevel;
// WoWLAN setting for DTM test.
if(pAdapter->bInHctTest)
{
// Do not enable WoWLAN LPS in DTM test.
pPSC->WoWLANLPSLevel = 0;
}
pAdapter->bRxPsWorkAround = (BOOLEAN)pNdisCommon->RegRxPsWorkAround;
RT_TRACE(COMP_POWER, DBG_LOUD, ("bRegFwCtrlLPS %d bRegLeisurePs %d", pNdisCommon->bRegFwCtrlLPS, pNdisCommon->RegLeisurePsMode));
RT_TRACE(COMP_POWER, DBG_LOUD, ("bFwCtrlLPS %d bLeisurePs %d", pPSC->bFwCtrlLPS, pPSC->bLeisurePs));
}
//
// Description:
// Read common registry value under LOCAL_MACHINE\SYSTEM\CurrentControlSet\Service\RtlWlanx
// 2014.12.15, by Sean.
//
// PASSIVE_LEVEL ONLY!!!!!!!!!!!!!!!!!!!!!!!!!
NTSTATUS
PlatformReadCommonDwordRegistry(
IN PWCHAR registryName,
OUT pu4Byte resultValue)
{
OBJECT_ATTRIBUTES objectAttributes = {0};
HANDLE driverKey = NULL;
NTSTATUS ntStatus = STATUS_SUCCESS;
UNICODE_STRING ValueName;
UNICODE_STRING RegistryPath;
KEY_VALUE_PARTIAL_INFORMATION result;
ULONG resultLength;
do
{
RtlInitUnicodeString(&RegistryPath,GlobalRtDriverContext.NdisContext.RegistryPath);
//DbgPrint("PATH: %wZ length:%d MAX :%d \n",&RegistryPath,RegistryPath.Length,RegistryPath.MaximumLength);
InitializeObjectAttributes(&objectAttributes,
&RegistryPath,
OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
NULL,
NULL);
if(STATUS_SUCCESS != (ntStatus = ZwOpenKey(&driverKey, KEY_READ, &objectAttributes)))
{
DbgPrint("ZwOpenKey Failed = 0x%x\n", ntStatus);
break;
}
RtlInitUnicodeString(&ValueName, registryName);
ntStatus = ZwQueryValueKey(driverKey,&ValueName,KeyValuePartialInformation,&result,sizeof(KEY_VALUE_PARTIAL_INFORMATION),&resultLength);
if(STATUS_SUCCESS != ntStatus)
{
DbgPrint("ZwQueryValueKey Failed = 0x%x\n", ntStatus);
break;
}
memcpy(resultValue,result.Data,sizeof(u4Byte));
//DbgPrint("Test result:%d Length:%d type:%d\n",*resultValue, result.DataLength, result.Type);
}while(FALSE);
if(driverKey)
{
ZwClose(driverKey);
driverKey = NULL;
}
return ntStatus;
}
//
// Description:
// Write common registry value under LOCAL_MACHINE\SYSTEM\CurrentControlSet\Service\RtlWlanx
// 2014.12.16, by Sean.
//
// PASSIVE_LEVEL ONLY!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
NTSTATUS
PlatformWriteCommonDwordRegistry(
IN PWCHAR registryName,
IN pu4Byte Value)
{
OBJECT_ATTRIBUTES objectAttributes = {0};
HANDLE driverKey = NULL;
NTSTATUS ntStatus = STATUS_SUCCESS;
UNICODE_STRING ValueName;
UNICODE_STRING RegistryPath;
do
{
RtlInitUnicodeString(&RegistryPath,GlobalRtDriverContext.NdisContext.RegistryPath);
InitializeObjectAttributes(&objectAttributes,
&RegistryPath,
OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
NULL,
NULL);
if(STATUS_SUCCESS != (ntStatus = ZwOpenKey(&driverKey, KEY_WRITE, &objectAttributes)))
{
DbgPrint("ZwOpenKey Failed = 0x%x\n", ntStatus);
break;
}
RtlInitUnicodeString(&ValueName, registryName);
ntStatus = ZwSetValueKey(driverKey,&ValueName,0,REG_DWORD,Value,sizeof(u4Byte));
if(STATUS_SUCCESS != ntStatus)
{
DbgPrint("ZwSetValueKey Failed = 0x%x\n", ntStatus);
break;
}
}while(FALSE);
if(driverKey)
{
ZwClose(driverKey);
driverKey = NULL;
}
return ntStatus;
}
NTSTATUS
PlatformWriteBTAntPosDwordRegistry(
IN PWCHAR registryName,
IN pu4Byte Value)
{
OBJECT_ATTRIBUTES objectAttributes = {0};
HANDLE driverKey = NULL;
NTSTATUS ntStatus = STATUS_SUCCESS;
UNICODE_STRING ValueName;
UNICODE_STRING RegistryPath;
ANSI_STRING AnsiString;
RT_TRACE(COMP_INIT, DBG_LOUD, ("### test\n"));
do
{
//RtlInitUnicodeString(&RegistryPath,registryPath);
RtlInitString(&AnsiString,"\\REGISTRY\\MACHINE\\SYSTEM\\ControlSet001\\Services\\RtlWlans\\Parameters");
RtlAnsiStringToUnicodeString(&RegistryPath,&AnsiString,TRUE);
RT_TRACE(COMP_INIT, DBG_LOUD, ("### PlatformWriteBTAntPosDwordRegistry(): RegistryPath = %wZ\n", &RegistryPath));
InitializeObjectAttributes(&objectAttributes,
&RegistryPath,
OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
NULL,
NULL);
if(STATUS_SUCCESS != (ntStatus = ZwOpenKey(&driverKey, KEY_WRITE, &objectAttributes)))
{
DbgPrint("ZwOpenKey Failed = 0x%x\n", ntStatus);
break;
}
RtlInitUnicodeString(&ValueName, registryName);
ntStatus = ZwSetValueKey(driverKey,&ValueName,0,REG_DWORD,Value,sizeof(u4Byte));
if(STATUS_SUCCESS != ntStatus)
{
DbgPrint("ZwSetValueKey Failed = 0x%x\n", ntStatus);
break;
}
}while(FALSE);
if(driverKey)
{
ZwClose(driverKey);
driverKey = NULL;
}
RtlFreeUnicodeString(&RegistryPath);
return ntStatus;
}
#if READ_BT_REGISTRY
NTSTATUS
PlatformReadBTFWLoaderDwordRegistry(
IN PWCHAR registryName,
OUT pu1Byte resultValue)
{
OBJECT_ATTRIBUTES objectAttributes = {0};
HANDLE driverKey = NULL;
NTSTATUS ntStatus = STATUS_SUCCESS;
UNICODE_STRING ValueName;
UNICODE_STRING RegistryPath;
ANSI_STRING AnsiString;
KEY_VALUE_PARTIAL_INFORMATION result;
ULONG resultLength;
do
{
RtlInitString(&AnsiString,"\\REGISTRY\\MACHINE\\Software\\Realtek\\Bluetooth\\service");
RtlAnsiStringToUnicodeString(&RegistryPath,&AnsiString,TRUE);
RT_TRACE(COMP_INIT, DBG_LOUD, ("### PlatformReadBTFWLoaderDwordRegistry(): RegistryPath = %wZ\n", &RegistryPath));
InitializeObjectAttributes(&objectAttributes,
&RegistryPath,
OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
NULL,
NULL);
if(STATUS_SUCCESS != (ntStatus = ZwOpenKey(&driverKey, KEY_READ, &objectAttributes)))
{
DbgPrint("ZwOpenKey Failed = 0x%x\n", ntStatus);
break;
}
RtlInitUnicodeString(&ValueName, registryName);
ntStatus = ZwQueryValueKey(driverKey,&ValueName,KeyValuePartialInformation,&result,sizeof(KEY_VALUE_PARTIAL_INFORMATION),&resultLength);
if(STATUS_SUCCESS != ntStatus)
{
DbgPrint("ZwQueryValueKey Failed = 0x%x\n", ntStatus);
break;
}
memcpy(resultValue,result.Data,sizeof(u4Byte));
//DbgPrint("Test result:%d Length:%d type:%d\n",*resultValue, result.DataLength, result.Type);
}while(FALSE);
if(driverKey)
{
ZwClose(driverKey);
driverKey = NULL;
}
return ntStatus;
}
#endif
| 25.94246 | 157 | 0.692665 | [
"object"
] |
8c6aaa9173945eb8f2b5d35d5c91ad9de3ddbf09 | 12,794 | h | C | Modules/Segmentation/OGRProcessing/include/otbStreamingImageToOGRLayerSegmentationFilter.h | heralex/OTB | c52b504b64dc89c8fe9cac8af39b8067ca2c3a57 | [
"Apache-2.0"
] | 317 | 2015-01-19T08:40:58.000Z | 2022-03-17T11:55:48.000Z | Modules/Segmentation/OGRProcessing/include/otbStreamingImageToOGRLayerSegmentationFilter.h | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 18 | 2015-07-29T14:13:45.000Z | 2021-03-29T12:36:24.000Z | Modules/Segmentation/OGRProcessing/include/otbStreamingImageToOGRLayerSegmentationFilter.h | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 132 | 2015-02-21T23:57:25.000Z | 2022-03-25T16:03:16.000Z | /*
* Copyright (C) 1999-2011 Insight Software Consortium
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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.
*/
#ifndef otbStreamingImageToOGRLayerSegmentationFilter_h
#define otbStreamingImageToOGRLayerSegmentationFilter_h
#include "itkExtractImageFilter.h"
#include "otbPersistentFilterStreamingDecorator.h"
#include "otbPersistentImageToOGRLayerFilter.h"
#include "otbRelabelComponentImageFilter.h"
#include "itkMultiplyImageFilter.h"
#include "otbLabeledOutputAccessor.h"
#include "otbMeanShiftSmoothingImageFilter.h"
#include <string>
namespace otb
{
/**
* \class LabeledOutputAccessor
* \brief Specialized class to get the index of the labeled output image in mean shift filter (new version).
*
* \ingroup OTBOGRProcessing
*/
template <class TInputImage, class TOutputImage, class TOutputImage2, class TKernelType>
class LabeledOutputAccessor<MeanShiftSmoothingImageFilter<TInputImage, TOutputImage, TOutputImage2, TKernelType>>
{
public:
typedef typename MeanShiftSmoothingImageFilter<TInputImage, TOutputImage, TOutputImage2, TKernelType>::OutputLabelImageType LabelImageType;
itkStaticConstMacro(LabeledOutputIndex, unsigned int, 0);
};
/** \class PersistentStreamingLabelImageToOGRDataFilter
* \brief This filter is a framework for large scale segmentation.
* For a detailed description @see StreamingImageToOGRLayerSegmentationFilter
*
* \ingroup OTBOGRProcessing
*/
template <class TImageType, class TSegmentationFilter>
class PersistentImageToOGRLayerSegmentationFilter : public otb::PersistentImageToOGRLayerFilter<TImageType>
{
public:
/** Standard Self typedef */
typedef PersistentImageToOGRLayerSegmentationFilter Self;
typedef PersistentImageToOGRLayerFilter<TImageType> Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef typename Superclass::InputImageType InputImageType;
typedef typename Superclass::InputImagePointer InputImagePointerType;
typedef TSegmentationFilter SegmentationFilterType;
typedef typename LabeledOutputAccessor<SegmentationFilterType>::LabelImageType LabelImageType;
typedef typename LabelImageType::PixelType LabelPixelType;
typedef otb::LabelImageToOGRDataSourceFilter<LabelImageType> LabelImageToOGRDataSourceFilterType;
typedef typename Superclass::OGRDataSourceType OGRDataSourceType;
typedef typename Superclass::OGRDataSourcePointerType OGRDataSourcePointerType;
typedef typename Superclass::OGRLayerType OGRLayerType;
typedef RelabelComponentImageFilter<LabelImageType, LabelImageType> RelabelComponentImageFilterType;
typedef itk::MultiplyImageFilter<LabelImageType, LabelImageType, LabelImageType> MultiplyImageFilterType;
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Runtime information support. */
itkTypeMacro(PersistentImageToOGRLayerSegmentationFilter, PersistentImageToOGRLayerFilter);
/** Return a pointer to the segmentation filter used. */
itkGetObjectMacro(SegmentationFilter, SegmentationFilterType);
itkSetStringMacro(FieldName);
itkGetStringMacro(FieldName);
/** Set the first Label value (default is 1). Incremental step is 1.*/
void SetStartLabel(const LabelPixelType& label)
{
m_StartLabel = label;
m_TileMaxLabel = label;
}
/** Return the first label value*/
itkGetMacro(StartLabel, LabelPixelType);
/**
* Set the value of 8-connected neighborhood option used in \c LabelImageToOGRDataSourceFilter
*/
itkSetMacro(Use8Connected, bool);
/**
* Get the value of 8-connected neighborhood option used in \c LabelImageToOGRDataSourceFilter
*/
itkGetMacro(Use8Connected, bool);
/** Set the option for filtering small objects. Default to false. */
itkSetMacro(FilterSmallObject, bool);
/** Return the value of filter small objects option.*/
itkGetMacro(FilterSmallObject, bool);
/** Set the minimum object size (in pixels) in case FilterSmallObject option is true.*/
itkSetMacro(MinimumObjectSize, unsigned int);
/** Get the minimum object size.*/
itkGetMacro(MinimumObjectSize, unsigned int);
/** Option for simplifying geometries. Default to false.*/
itkSetMacro(Simplify, bool);
itkGetMacro(Simplify, bool);
/** Set the tolerance value for simplifying geometries.
* \sa \c OGRGeometry::Simplify() \c OGRGeometry::SimplifyPreserveTopology()
*/
itkSetMacro(SimplificationTolerance, double);
/** Get the tolerance value for simplifying geometries.
* \sa \c OGRGeometry::Simplify() \c OGRGeometry::SimplifyPreserveTopology()
*/
itkGetMacro(SimplificationTolerance, double);
/** Set/Get the input mask image.
* All pixels in the mask with a value of 0 will not be considered
* suitable for vectorization.
*/
virtual void SetInputMask(const LabelImageType* mask);
virtual const LabelImageType* GetInputMask(void);
protected:
PersistentImageToOGRLayerSegmentationFilter();
~PersistentImageToOGRLayerSegmentationFilter() override;
private:
PersistentImageToOGRLayerSegmentationFilter(const Self&) = delete;
void operator=(const Self&) = delete;
OGRDataSourcePointerType ProcessTile() override;
int m_TileMaxLabel;
LabelPixelType m_StartLabel;
typename SegmentationFilterType::Pointer m_SegmentationFilter;
std::string m_FieldName;
unsigned int m_TileNumber;
bool m_Use8Connected;
bool m_FilterSmallObject;
unsigned int m_MinimumObjectSize;
bool m_Simplify;
double m_SimplificationTolerance;
};
/** \class StreamingImageToOGRLayerSegmentationFilter
* \brief This filter is a framework for large scale segmentation.
* It is a persistent filter that process the input image tile by tile.
* This filter is templated over the segmentation filter. This later is used to segment each tile of the input image.
* Each segmentation result (for each tile) is then vectorized using \c LabelImageToOGRDataSourceFilter
* (based on \c GDALPolygonize()).
* The output \c OGRDataSource of the \c LabelImageToOGRDataSourceFilter is a "memory" DataSource
* (ie all features of a tile are kept in memory). From here some optional processing can be done,
* depending on input parameters :
* - Simplify option : If set to true, the SimplificationTolerance parameter is used to simplify all geometries,
* using the \c OGRGeometry::Simplify() method, based on Douglas-Peuker algorithm.
* - FilterSmallObject option : if set to true, polygons with a size less than MinimumObjectSize (in pixels)
* are discarded.
* Finally all features contained in the "memory" DataSource are copied into the input Layer,
* in the layer specified with the \c SetLayerName() method.
*
* \note The Use8Connected parameter can be turn on and it will be used in \c GDALPolygonize(). But be carreful, it
* can create cross polygons !
* \note The input mask can be used to exclude pixels from vectorization process.
* All pixels with a value of 0 in the input mask image will not be suitable for vectorization.
*
* \ingroup OTBOGRProcessing
*/
template <class TImageType, class TSegmentationFilter>
class ITK_EXPORT StreamingImageToOGRLayerSegmentationFilter
: public PersistentFilterStreamingDecorator<PersistentImageToOGRLayerSegmentationFilter<TImageType, TSegmentationFilter>>
{
public:
/** Standard Self typedef */
typedef StreamingImageToOGRLayerSegmentationFilter Self;
typedef PersistentFilterStreamingDecorator<PersistentImageToOGRLayerSegmentationFilter<TImageType, TSegmentationFilter>> Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Type macro */
itkNewMacro(Self);
/** Creation through object factory macro */
itkTypeMacro(StreamingImageToOGRLayerSegmentationFilter, PersistentFilterStreamingDecorator);
typedef TSegmentationFilter SegmentationFilterType;
typedef TImageType InputImageType;
typedef typename PersistentImageToOGRLayerSegmentationFilter<TImageType, TSegmentationFilter>::LabelPixelType LabelPixelType;
typedef typename PersistentImageToOGRLayerSegmentationFilter<TImageType, TSegmentationFilter>::LabelImageType LabelImageType;
typedef typename PersistentImageToOGRLayerSegmentationFilter<TImageType, TSegmentationFilter>::OGRDataSourcePointerType OGRDataSourcePointerType;
typedef typename PersistentImageToOGRLayerSegmentationFilter<TImageType, TSegmentationFilter>::OGRLayerType OGRLayerType;
typedef typename InputImageType::SizeType SizeType;
/** Set the input image. */
using Superclass::SetInput;
void SetInput(InputImageType* input)
{
this->GetFilter()->SetInput(input);
}
const InputImageType* GetInput()
{
return this->GetFilter()->GetInput();
}
/** Set/Get the input mask image.
* All pixels in the mask with a value of 0 will not be considered
* suitable for vectorization.
*/
void SetInputMask(LabelImageType* mask)
{
this->GetFilter()->SetInputMask(mask);
}
const LabelImageType* GetInputMask()
{
return this->GetFilter()->GetInputMask();
}
/** Set the \c ogr::Layer in which the layer LayerName will be created. */
void SetOGRLayer(const OGRLayerType& ogrLayer)
{
this->GetFilter()->SetOGRLayer(ogrLayer);
}
void SetFieldName(const std::string& fieldName)
{
this->GetFilter()->SetFieldName(fieldName);
}
const std::string& GetFieldName() const
{
return this->GetFilter()->GetFieldName();
}
SegmentationFilterType* GetSegmentationFilter()
{
return this->GetFilter()->GetSegmentationFilter();
}
/** Set the first Label value (default is 1). Incremental step is 1.*/
void SetStartLabel(const LabelPixelType& label)
{
this->GetFilter()->SetStartLabel(label);
}
/** Return the first label value*/
const LabelPixelType& GetStartLabel()
{
return this->GetFilter()->GetStartLabel();
}
/** Retrieve the actual streamsize used */
SizeType GetStreamSize()
{
return this->GetFilter()->GetStreamSize();
}
void Initialize()
{
this->GetFilter()->Initialize();
}
/**
* Set the value of 8-connected neighborhood option used in \c LabelImageToOGRDataSourceFilter
*/
void SetUse8Connected(bool flag)
{
this->GetFilter()->SetUse8Connected(flag);
}
bool GetUse8Connected()
{
return this->GetFilter()->GetUse8Connected();
}
/** Set the option for filtering small objects. Default to false. */
void SetFilterSmallObject(bool flag)
{
this->GetFilter()->SetFilterSmallObject(flag);
}
bool GetFilterSmallObject()
{
return this->GetFilter()->GetFilterSmallObject();
}
/** Set the minimum object size (in pixels) in case FilterSmallObject option is true.*/
void SetMinimumObjectSize(const unsigned int& size)
{
this->GetFilter()->SetMinimumObjectSize(size);
}
unsigned int GetMinimumObjectSize()
{
return this->GetFilter()->GetMinimumObjectSize();
}
/** Option for simplifying geometries. Default to false.*/
void SetSimplify(bool flag)
{
this->GetFilter()->SetSimplify(flag);
}
bool GetSimplify()
{
return this->GetFilter()->GetSimplify();
}
/** Set the tolerance value for simplifying geometries.
* \sa \c OGRGeometry::Simplify() \c OGRGeometry::SimplifyPreserveTopology()
*/
void SetSimplificationTolerance(const double& tol)
{
this->GetFilter()->SetSimplificationTolerance(tol);
}
double GetSimplificationTolerance()
{
return this->GetFilter()->GetSimplificationTolerance();
}
protected:
/** Constructor */
StreamingImageToOGRLayerSegmentationFilter()
{
}
/** Destructor */
~StreamingImageToOGRLayerSegmentationFilter() override
{
}
private:
StreamingImageToOGRLayerSegmentationFilter(const Self&) = delete;
void operator=(const Self&) = delete;
};
}
#ifndef OTB_MANUAL_INSTANTIATION
#include "otbStreamingImageToOGRLayerSegmentationFilter.hxx"
#endif
#endif
| 35.342541 | 147 | 0.750508 | [
"object"
] |
8c6ba497d3024d9dbc2860a2d7d7f4ea11852fc6 | 327 | h | C | Client/PlayerAttack.h | sangshub/55231 | 1f31ab8610999856e932bac9327255475f56e4d4 | [
"Unlicense"
] | null | null | null | Client/PlayerAttack.h | sangshub/55231 | 1f31ab8610999856e932bac9327255475f56e4d4 | [
"Unlicense"
] | null | null | null | Client/PlayerAttack.h | sangshub/55231 | 1f31ab8610999856e932bac9327255475f56e4d4 | [
"Unlicense"
] | null | null | null | #pragma once
#include "Effect.h"
class CPlayerAttack : public CEffect
{
public:
CPlayerAttack(void);
~CPlayerAttack(void);
public:
virtual HRESULT Initialize();
virtual const int Progress();
virtual void Render();
private:
void SetPlayerMatrix(const D3DXVECTOR3& vScale);
void SetEffactScale(D3DXVECTOR3& vScale);
}; | 17.210526 | 49 | 0.75841 | [
"render"
] |
8c72647fe1ab0220bf9ba2718c496e9a27c4a9aa | 121,641 | c | C | riscv/llvm/3.5/binutils-2.21.1/binutils/dlltool.c | tangyibin/goblin-core | 1940db6e95908c81687b2b22ddd9afbc8db9cdfe | [
"BSD-3-Clause"
] | null | null | null | riscv/llvm/3.5/binutils-2.21.1/binutils/dlltool.c | tangyibin/goblin-core | 1940db6e95908c81687b2b22ddd9afbc8db9cdfe | [
"BSD-3-Clause"
] | null | null | null | riscv/llvm/3.5/binutils-2.21.1/binutils/dlltool.c | tangyibin/goblin-core | 1940db6e95908c81687b2b22ddd9afbc8db9cdfe | [
"BSD-3-Clause"
] | 1 | 2021-03-24T06:40:32.000Z | 2021-03-24T06:40:32.000Z | /* dlltool.c -- tool to generate stuff for PE style DLLs
Copyright 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
This file is part of GNU Binutils.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
02110-1301, USA. */
/* This program allows you to build the files necessary to create
DLLs to run on a system which understands PE format image files.
(eg, Windows NT)
See "Peering Inside the PE: A Tour of the Win32 Portable Executable
File Format", MSJ 1994, Volume 9 for more information.
Also see "Microsoft Portable Executable and Common Object File Format,
Specification 4.1" for more information.
A DLL contains an export table which contains the information
which the runtime loader needs to tie up references from a
referencing program.
The export table is generated by this program by reading
in a .DEF file or scanning the .a and .o files which will be in the
DLL. A .o file can contain information in special ".drectve" sections
with export information.
A DEF file contains any number of the following commands:
NAME <name> [ , <base> ]
The result is going to be <name>.EXE
LIBRARY <name> [ , <base> ]
The result is going to be <name>.DLL
EXPORTS ( ( ( <name1> [ = <name2> ] )
| ( <name1> = <module-name> . <external-name>))
[ @ <integer> ] [ NONAME ] [CONSTANT] [DATA] [PRIVATE] ) *
Declares name1 as an exported symbol from the
DLL, with optional ordinal number <integer>.
Or declares name1 as an alias (forward) of the function <external-name>
in the DLL <module-name>.
IMPORTS ( ( <internal-name> = <module-name> . <integer> )
| ( [ <internal-name> = ] <module-name> . <external-name> )) *
Declares that <external-name> or the exported function whose ordinal number
is <integer> is to be imported from the file <module-name>. If
<internal-name> is specified then this is the name that the imported
function will be refereed to in the body of the DLL.
DESCRIPTION <string>
Puts <string> into output .exp file in the .rdata section
[STACKSIZE|HEAPSIZE] <number-reserve> [ , <number-commit> ]
Generates --stack|--heap <number-reserve>,<number-commit>
in the output .drectve section. The linker will
see this and act upon it.
[CODE|DATA] <attr>+
SECTIONS ( <sectionname> <attr>+ )*
<attr> = READ | WRITE | EXECUTE | SHARED
Generates --attr <sectionname> <attr> in the output
.drectve section. The linker will see this and act
upon it.
A -export:<name> in a .drectve section in an input .o or .a
file to this program is equivalent to a EXPORTS <name>
in a .DEF file.
The program generates output files with the prefix supplied
on the command line, or in the def file, or taken from the first
supplied argument.
The .exp.s file contains the information necessary to export
the routines in the DLL. The .lib.s file contains the information
necessary to use the DLL's routines from a referencing program.
Example:
file1.c:
asm (".section .drectve");
asm (".ascii \"-export:adef\"");
void adef (char * s)
{
printf ("hello from the dll %s\n", s);
}
void bdef (char * s)
{
printf ("hello from the dll and the other entry point %s\n", s);
}
file2.c:
asm (".section .drectve");
asm (".ascii \"-export:cdef\"");
asm (".ascii \"-export:ddef\"");
void cdef (char * s)
{
printf ("hello from the dll %s\n", s);
}
void ddef (char * s)
{
printf ("hello from the dll and the other entry point %s\n", s);
}
int printf (void)
{
return 9;
}
themain.c:
int main (void)
{
cdef ();
return 0;
}
thedll.def
LIBRARY thedll
HEAPSIZE 0x40000, 0x2000
EXPORTS bdef @ 20
cdef @ 30 NONAME
SECTIONS donkey READ WRITE
aardvark EXECUTE
# Compile up the parts of the dll and the program
gcc -c file1.c file2.c themain.c
# Optional: put the dll objects into a library
# (you don't have to, you could name all the object
# files on the dlltool line)
ar qcv thedll.in file1.o file2.o
ranlib thedll.in
# Run this tool over the DLL's .def file and generate an exports
# file (thedll.o) and an imports file (thedll.a).
# (You may have to use -S to tell dlltool where to find the assembler).
dlltool --def thedll.def --output-exp thedll.o --output-lib thedll.a
# Build the dll with the library and the export table
ld -o thedll.dll thedll.o thedll.in
# Link the executable with the import library
gcc -o themain.exe themain.o thedll.a
This example can be extended if relocations are needed in the DLL:
# Compile up the parts of the dll and the program
gcc -c file1.c file2.c themain.c
# Run this tool over the DLL's .def file and generate an imports file.
dlltool --def thedll.def --output-lib thedll.lib
# Link the executable with the import library and generate a base file
# at the same time
gcc -o themain.exe themain.o thedll.lib -Wl,--base-file -Wl,themain.base
# Run this tool over the DLL's .def file and generate an exports file
# which includes the relocations from the base file.
dlltool --def thedll.def --base-file themain.base --output-exp thedll.exp
# Build the dll with file1.o, file2.o and the export table
ld -o thedll.dll thedll.exp file1.o file2.o */
/* .idata section description
The .idata section is the import table. It is a collection of several
subsections used to keep the pieces for each dll together: .idata$[234567].
IE: Each dll's .idata$2's are catenated together, each .idata$3's, etc.
.idata$2 = Import Directory Table
= array of IMAGE_IMPORT_DESCRIPTOR's.
DWORD Import Lookup Table; - pointer to .idata$4
DWORD TimeDateStamp; - currently always 0
DWORD ForwarderChain; - currently always 0
DWORD Name; - pointer to dll's name
PIMAGE_THUNK_DATA FirstThunk; - pointer to .idata$5
.idata$3 = null terminating entry for .idata$2.
.idata$4 = Import Lookup Table
= array of array of pointers to hint name table.
There is one for each dll being imported from, and each dll's set is
terminated by a trailing NULL.
.idata$5 = Import Address Table
= array of array of pointers to hint name table.
There is one for each dll being imported from, and each dll's set is
terminated by a trailing NULL.
Initially, this table is identical to the Import Lookup Table. However,
at load time, the loader overwrites the entries with the address of the
function.
.idata$6 = Hint Name Table
= Array of { short, asciz } entries, one for each imported function.
The `short' is the function's ordinal number.
.idata$7 = dll name (eg: "kernel32.dll"). (.idata$6 for ppc). */
/* AIX requires this to be the first thing in the file. */
#ifndef __GNUC__
# ifdef _AIX
#pragma alloca
#endif
#endif
#define show_allnames 0
#include "sysdep.h"
#include "bfd.h"
#include "libiberty.h"
#include "getopt.h"
#include "demangle.h"
#include "dyn-string.h"
#include "bucomm.h"
#include "dlltool.h"
#include "safe-ctype.h"
#include <time.h>
#include <sys/stat.h>
#include <stdarg.h>
#include <assert.h>
#ifdef DLLTOOL_ARM
#include "coff/arm.h"
#include "coff/internal.h"
#endif
#ifdef DLLTOOL_DEFAULT_MX86_64
#include "coff/x86_64.h"
#endif
#ifdef DLLTOOL_DEFAULT_I386
#include "coff/i386.h"
#endif
#ifndef COFF_PAGE_SIZE
#define COFF_PAGE_SIZE ((bfd_vma) 4096)
#endif
#ifndef PAGE_MASK
#define PAGE_MASK ((bfd_vma) (- COFF_PAGE_SIZE))
#endif
/* Get current BFD error message. */
#define bfd_get_errmsg() (bfd_errmsg (bfd_get_error ()))
/* Forward references. */
static char *look_for_prog (const char *, const char *, int);
static char *deduce_name (const char *);
#ifdef DLLTOOL_MCORE_ELF
static void mcore_elf_cache_filename (const char *);
static void mcore_elf_gen_out_file (void);
#endif
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#else /* ! HAVE_SYS_WAIT_H */
#if ! defined (_WIN32) || defined (__CYGWIN32__)
#ifndef WIFEXITED
#define WIFEXITED(w) (((w) & 0377) == 0)
#endif
#ifndef WIFSIGNALED
#define WIFSIGNALED(w) (((w) & 0377) != 0177 && ((w) & ~0377) == 0)
#endif
#ifndef WTERMSIG
#define WTERMSIG(w) ((w) & 0177)
#endif
#ifndef WEXITSTATUS
#define WEXITSTATUS(w) (((w) >> 8) & 0377)
#endif
#else /* defined (_WIN32) && ! defined (__CYGWIN32__) */
#ifndef WIFEXITED
#define WIFEXITED(w) (((w) & 0xff) == 0)
#endif
#ifndef WIFSIGNALED
#define WIFSIGNALED(w) (((w) & 0xff) != 0 && ((w) & 0xff) != 0x7f)
#endif
#ifndef WTERMSIG
#define WTERMSIG(w) ((w) & 0x7f)
#endif
#ifndef WEXITSTATUS
#define WEXITSTATUS(w) (((w) & 0xff00) >> 8)
#endif
#endif /* defined (_WIN32) && ! defined (__CYGWIN32__) */
#endif /* ! HAVE_SYS_WAIT_H */
/* ifunc and ihead data structures: ttk@cygnus.com 1997
When IMPORT declarations are encountered in a .def file the
function import information is stored in a structure referenced by
the global variable IMPORT_LIST. The structure is a linked list
containing the names of the dll files each function is imported
from and a linked list of functions being imported from that dll
file. This roughly parallels the structure of the .idata section
in the PE object file.
The contents of .def file are interpreted from within the
process_def_file function. Every time an IMPORT declaration is
encountered, it is broken up into its component parts and passed to
def_import. IMPORT_LIST is initialized to NULL in function main. */
typedef struct ifunct
{
char * name; /* Name of function being imported. */
char * its_name; /* Optional import table symbol name. */
int ord; /* Two-byte ordinal value associated with function. */
struct ifunct *next;
} ifunctype;
typedef struct iheadt
{
char * dllname; /* Name of dll file imported from. */
long nfuncs; /* Number of functions in list. */
struct ifunct *funchead; /* First function in list. */
struct ifunct *functail; /* Last function in list. */
struct iheadt *next; /* Next dll file in list. */
} iheadtype;
/* Structure containing all import information as defined in .def file
(qv "ihead structure"). */
static iheadtype *import_list = NULL;
static char *as_name = NULL;
static char * as_flags = "";
static char *tmp_prefix;
static int no_idata4;
static int no_idata5;
static char *exp_name;
static char *imp_name;
static char *delayimp_name;
static char *identify_imp_name;
static bfd_boolean identify_strict;
/* Types used to implement a linked list of dllnames associated
with the specified import lib. Used by the identify_* code.
The head entry is acts as a sentinal node and is always empty
(head->dllname is NULL). */
typedef struct dll_name_list_node_t
{
char * dllname;
struct dll_name_list_node_t * next;
} dll_name_list_node_type;
typedef struct dll_name_list_t
{
dll_name_list_node_type * head;
dll_name_list_node_type * tail;
} dll_name_list_type;
/* Types used to pass data to iterator functions. */
typedef struct symname_search_data_t
{
const char * symname;
bfd_boolean found;
} symname_search_data_type;
typedef struct identify_data_t
{
dll_name_list_type * list;
bfd_boolean ms_style_implib;
} identify_data_type;
static char *head_label;
static char *imp_name_lab;
static char *dll_name;
static int add_indirect = 0;
static int add_underscore = 0;
static int add_stdcall_underscore = 0;
/* This variable can hold three different values. The value
-1 (default) means that default underscoring should be used,
zero means that no underscoring should be done, and one
indicates that underscoring should be done. */
static int leading_underscore = -1;
static int dontdeltemps = 0;
/* TRUE if we should export all symbols. Otherwise, we only export
symbols listed in .drectve sections or in the def file. */
static bfd_boolean export_all_symbols;
/* TRUE if we should exclude the symbols in DEFAULT_EXCLUDES when
exporting all symbols. */
static bfd_boolean do_default_excludes = TRUE;
static bfd_boolean use_nul_prefixed_import_tables = FALSE;
/* Default symbols to exclude when exporting all the symbols. */
static const char *default_excludes = "DllMain@12,DllEntryPoint@0,impure_ptr";
/* TRUE if we should add __imp_<SYMBOL> to import libraries for backward
compatibility to old Cygwin releases. */
static bfd_boolean create_compat_implib;
/* TRUE if we have to write PE+ import libraries. */
static bfd_boolean create_for_pep;
static char *def_file;
extern char * program_name;
static int machine;
static int killat;
static int add_stdcall_alias;
static const char *ext_prefix_alias;
static int verbose;
static FILE *output_def;
static FILE *base_file;
#ifdef DLLTOOL_DEFAULT_ARM
static const char *mname = "arm";
#endif
#ifdef DLLTOOL_DEFAULT_ARM_EPOC
static const char *mname = "arm-epoc";
#endif
#ifdef DLLTOOL_DEFAULT_ARM_WINCE
static const char *mname = "arm-wince";
#endif
#ifdef DLLTOOL_DEFAULT_I386
static const char *mname = "i386";
#endif
#ifdef DLLTOOL_DEFAULT_MX86_64
static const char *mname = "i386:x86-64";
#endif
#ifdef DLLTOOL_DEFAULT_PPC
static const char *mname = "ppc";
#endif
#ifdef DLLTOOL_DEFAULT_SH
static const char *mname = "sh";
#endif
#ifdef DLLTOOL_DEFAULT_MIPS
static const char *mname = "mips";
#endif
#ifdef DLLTOOL_DEFAULT_MCORE
static const char * mname = "mcore-le";
#endif
#ifdef DLLTOOL_DEFAULT_MCORE_ELF
static const char * mname = "mcore-elf";
static char * mcore_elf_out_file = NULL;
static char * mcore_elf_linker = NULL;
static char * mcore_elf_linker_flags = NULL;
#define DRECTVE_SECTION_NAME ((machine == MMCORE_ELF || machine == MMCORE_ELF_LE) ? ".exports" : ".drectve")
#endif
#ifndef DRECTVE_SECTION_NAME
#define DRECTVE_SECTION_NAME ".drectve"
#endif
/* What's the right name for this ? */
#define PATHMAX 250
/* External name alias numbering starts here. */
#define PREFIX_ALIAS_BASE 20000
char *tmp_asm_buf;
char *tmp_head_s_buf;
char *tmp_head_o_buf;
char *tmp_tail_s_buf;
char *tmp_tail_o_buf;
char *tmp_stub_buf;
#define TMP_ASM dlltmp (&tmp_asm_buf, "%sc.s")
#define TMP_HEAD_S dlltmp (&tmp_head_s_buf, "%sh.s")
#define TMP_HEAD_O dlltmp (&tmp_head_o_buf, "%sh.o")
#define TMP_TAIL_S dlltmp (&tmp_tail_s_buf, "%st.s")
#define TMP_TAIL_O dlltmp (&tmp_tail_o_buf, "%st.o")
#define TMP_STUB dlltmp (&tmp_stub_buf, "%ss")
/* This bit of assembly does jmp * .... */
static const unsigned char i386_jtab[] =
{
0xff, 0x25, 0x00, 0x00, 0x00, 0x00, 0x90, 0x90
};
static const unsigned char i386_dljtab[] =
{
0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, /* jmp __imp__function */
0xB8, 0x00, 0x00, 0x00, 0x00, /* mov eax, offset __imp__function */
0xE9, 0x00, 0x00, 0x00, 0x00 /* jmp __tailMerge__dllname */
};
static const unsigned char arm_jtab[] =
{
0x00, 0xc0, 0x9f, 0xe5, /* ldr ip, [pc] */
0x00, 0xf0, 0x9c, 0xe5, /* ldr pc, [ip] */
0, 0, 0, 0
};
static const unsigned char arm_interwork_jtab[] =
{
0x04, 0xc0, 0x9f, 0xe5, /* ldr ip, [pc] */
0x00, 0xc0, 0x9c, 0xe5, /* ldr ip, [ip] */
0x1c, 0xff, 0x2f, 0xe1, /* bx ip */
0, 0, 0, 0
};
static const unsigned char thumb_jtab[] =
{
0x40, 0xb4, /* push {r6} */
0x02, 0x4e, /* ldr r6, [pc, #8] */
0x36, 0x68, /* ldr r6, [r6] */
0xb4, 0x46, /* mov ip, r6 */
0x40, 0xbc, /* pop {r6} */
0x60, 0x47, /* bx ip */
0, 0, 0, 0
};
static const unsigned char mcore_be_jtab[] =
{
0x71, 0x02, /* lrw r1,2 */
0x81, 0x01, /* ld.w r1,(r1,0) */
0x00, 0xC1, /* jmp r1 */
0x12, 0x00, /* nop */
0x00, 0x00, 0x00, 0x00 /* <address> */
};
static const unsigned char mcore_le_jtab[] =
{
0x02, 0x71, /* lrw r1,2 */
0x01, 0x81, /* ld.w r1,(r1,0) */
0xC1, 0x00, /* jmp r1 */
0x00, 0x12, /* nop */
0x00, 0x00, 0x00, 0x00 /* <address> */
};
/* This is the glue sequence for PowerPC PE. There is a
tocrel16-tocdefn reloc against the first instruction.
We also need a IMGLUE reloc against the glue function
to restore the toc saved by the third instruction in
the glue. */
static const unsigned char ppc_jtab[] =
{
0x00, 0x00, 0x62, 0x81, /* lwz r11,0(r2) */
/* Reloc TOCREL16 __imp_xxx */
0x00, 0x00, 0x8B, 0x81, /* lwz r12,0(r11) */
0x04, 0x00, 0x41, 0x90, /* stw r2,4(r1) */
0xA6, 0x03, 0x89, 0x7D, /* mtctr r12 */
0x04, 0x00, 0x4B, 0x80, /* lwz r2,4(r11) */
0x20, 0x04, 0x80, 0x4E /* bctr */
};
#ifdef DLLTOOL_PPC
/* The glue instruction, picks up the toc from the stw in
the above code: "lwz r2,4(r1)". */
static bfd_vma ppc_glue_insn = 0x80410004;
#endif
static const char i386_trampoline[] =
"\tpushl %%ecx\n"
"\tpushl %%edx\n"
"\tpushl %%eax\n"
"\tpushl $__DELAY_IMPORT_DESCRIPTOR_%s\n"
"\tcall ___delayLoadHelper2@8\n"
"\tpopl %%edx\n"
"\tpopl %%ecx\n"
"\tjmp *%%eax\n";
struct mac
{
const char *type;
const char *how_byte;
const char *how_short;
const char *how_long;
const char *how_asciz;
const char *how_comment;
const char *how_jump;
const char *how_global;
const char *how_space;
const char *how_align_short;
const char *how_align_long;
const char *how_default_as_switches;
const char *how_bfd_target;
enum bfd_architecture how_bfd_arch;
const unsigned char *how_jtab;
int how_jtab_size; /* Size of the jtab entry. */
int how_jtab_roff; /* Offset into it for the ind 32 reloc into idata 5. */
const unsigned char *how_dljtab;
int how_dljtab_size; /* Size of the dljtab entry. */
int how_dljtab_roff1; /* Offset for the ind 32 reloc into idata 5. */
int how_dljtab_roff2; /* Offset for the ind 32 reloc into idata 5. */
int how_dljtab_roff3; /* Offset for the ind 32 reloc into idata 5. */
const char *trampoline;
};
static const struct mac
mtable[] =
{
{
#define MARM 0
"arm", ".byte", ".short", ".long", ".asciz", "@",
"ldr\tip,[pc]\n\tldr\tpc,[ip]\n\t.long",
".global", ".space", ".align\t2",".align\t4", "-mapcs-32",
"pe-arm-little", bfd_arch_arm,
arm_jtab, sizeof (arm_jtab), 8,
0, 0, 0, 0, 0, 0
}
,
{
#define M386 1
"i386", ".byte", ".short", ".long", ".asciz", "#",
"jmp *", ".global", ".space", ".align\t2",".align\t4", "",
"pe-i386",bfd_arch_i386,
i386_jtab, sizeof (i386_jtab), 2,
i386_dljtab, sizeof (i386_dljtab), 2, 7, 12, i386_trampoline
}
,
{
#define MPPC 2
"ppc", ".byte", ".short", ".long", ".asciz", "#",
"jmp *", ".global", ".space", ".align\t2",".align\t4", "",
"pe-powerpcle",bfd_arch_powerpc,
ppc_jtab, sizeof (ppc_jtab), 0,
0, 0, 0, 0, 0, 0
}
,
{
#define MTHUMB 3
"thumb", ".byte", ".short", ".long", ".asciz", "@",
"push\t{r6}\n\tldr\tr6, [pc, #8]\n\tldr\tr6, [r6]\n\tmov\tip, r6\n\tpop\t{r6}\n\tbx\tip",
".global", ".space", ".align\t2",".align\t4", "-mthumb-interwork",
"pe-arm-little", bfd_arch_arm,
thumb_jtab, sizeof (thumb_jtab), 12,
0, 0, 0, 0, 0, 0
}
,
#define MARM_INTERWORK 4
{
"arm_interwork", ".byte", ".short", ".long", ".asciz", "@",
"ldr\tip,[pc]\n\tldr\tip,[ip]\n\tbx\tip\n\t.long",
".global", ".space", ".align\t2",".align\t4", "-mthumb-interwork",
"pe-arm-little", bfd_arch_arm,
arm_interwork_jtab, sizeof (arm_interwork_jtab), 12,
0, 0, 0, 0, 0, 0
}
,
{
#define MMCORE_BE 5
"mcore-be", ".byte", ".short", ".long", ".asciz", "//",
"lrw r1,[1f]\n\tld.w r1,(r1,0)\n\tjmp r1\n\tnop\n1:.long",
".global", ".space", ".align\t2",".align\t4", "",
"pe-mcore-big", bfd_arch_mcore,
mcore_be_jtab, sizeof (mcore_be_jtab), 8,
0, 0, 0, 0, 0, 0
}
,
{
#define MMCORE_LE 6
"mcore-le", ".byte", ".short", ".long", ".asciz", "//",
"lrw r1,[1f]\n\tld.w r1,(r1,0)\n\tjmp r1\n\tnop\n1:.long",
".global", ".space", ".align\t2",".align\t4", "-EL",
"pe-mcore-little", bfd_arch_mcore,
mcore_le_jtab, sizeof (mcore_le_jtab), 8,
0, 0, 0, 0, 0, 0
}
,
{
#define MMCORE_ELF 7
"mcore-elf-be", ".byte", ".short", ".long", ".asciz", "//",
"lrw r1,[1f]\n\tld.w r1,(r1,0)\n\tjmp r1\n\tnop\n1:.long",
".global", ".space", ".align\t2",".align\t4", "",
"elf32-mcore-big", bfd_arch_mcore,
mcore_be_jtab, sizeof (mcore_be_jtab), 8,
0, 0, 0, 0, 0, 0
}
,
{
#define MMCORE_ELF_LE 8
"mcore-elf-le", ".byte", ".short", ".long", ".asciz", "//",
"lrw r1,[1f]\n\tld.w r1,(r1,0)\n\tjmp r1\n\tnop\n1:.long",
".global", ".space", ".align\t2",".align\t4", "-EL",
"elf32-mcore-little", bfd_arch_mcore,
mcore_le_jtab, sizeof (mcore_le_jtab), 8,
0, 0, 0, 0, 0, 0
}
,
{
#define MARM_EPOC 9
"arm-epoc", ".byte", ".short", ".long", ".asciz", "@",
"ldr\tip,[pc]\n\tldr\tpc,[ip]\n\t.long",
".global", ".space", ".align\t2",".align\t4", "",
"epoc-pe-arm-little", bfd_arch_arm,
arm_jtab, sizeof (arm_jtab), 8,
0, 0, 0, 0, 0, 0
}
,
{
#define MARM_WINCE 10
"arm-wince", ".byte", ".short", ".long", ".asciz", "@",
"ldr\tip,[pc]\n\tldr\tpc,[ip]\n\t.long",
".global", ".space", ".align\t2",".align\t4", "-mapcs-32",
"pe-arm-wince-little", bfd_arch_arm,
arm_jtab, sizeof (arm_jtab), 8,
0, 0, 0, 0, 0, 0
}
,
{
#define MX86 11
"i386:x86-64", ".byte", ".short", ".long", ".asciz", "#",
"jmp *", ".global", ".space", ".align\t2",".align\t4", "",
"pe-x86-64",bfd_arch_i386,
i386_jtab, sizeof (i386_jtab), 2,
i386_dljtab, sizeof (i386_dljtab), 2, 7, 12, i386_trampoline
}
,
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
typedef struct dlist
{
char *text;
struct dlist *next;
}
dlist_type;
typedef struct export
{
const char *name;
const char *internal_name;
const char *import_name;
const char *its_name;
int ordinal;
int constant;
int noname; /* Don't put name in image file. */
int private; /* Don't put reference in import lib. */
int data;
int hint;
int forward; /* Number of forward label, 0 means no forward. */
struct export *next;
}
export_type;
/* A list of symbols which we should not export. */
struct string_list
{
struct string_list *next;
char *string;
};
static struct string_list *excludes;
static const char *rvaafter (int);
static const char *rvabefore (int);
static const char *asm_prefix (int, const char *);
static void process_def_file (const char *);
static void new_directive (char *);
static void append_import (const char *, const char *, int, const char *);
static void run (const char *, char *);
static void scan_drectve_symbols (bfd *);
static void scan_filtered_symbols (bfd *, void *, long, unsigned int);
static void add_excludes (const char *);
static bfd_boolean match_exclude (const char *);
static void set_default_excludes (void);
static long filter_symbols (bfd *, void *, long, unsigned int);
static void scan_all_symbols (bfd *);
static void scan_open_obj_file (bfd *);
static void scan_obj_file (const char *);
static void dump_def_info (FILE *);
static int sfunc (const void *, const void *);
static void flush_page (FILE *, bfd_vma *, bfd_vma, int);
static void gen_def_file (void);
static void generate_idata_ofile (FILE *);
static void assemble_file (const char *, const char *);
static void gen_exp_file (void);
static const char *xlate (const char *);
static char *make_label (const char *, const char *);
static char *make_imp_label (const char *, const char *);
static bfd *make_one_lib_file (export_type *, int, int);
static bfd *make_head (void);
static bfd *make_tail (void);
static bfd *make_delay_head (void);
static void gen_lib_file (int);
static void dll_name_list_append (dll_name_list_type *, bfd_byte *);
static int dll_name_list_count (dll_name_list_type *);
static void dll_name_list_print (dll_name_list_type *);
static void dll_name_list_free_contents (dll_name_list_node_type *);
static void dll_name_list_free (dll_name_list_type *);
static dll_name_list_type * dll_name_list_create (void);
static void identify_dll_for_implib (void);
static void identify_search_archive
(bfd *, void (*) (bfd *, bfd *, void *), void *);
static void identify_search_member (bfd *, bfd *, void *);
static bfd_boolean identify_process_section_p (asection *, bfd_boolean);
static void identify_search_section (bfd *, asection *, void *);
static void identify_member_contains_symname (bfd *, bfd *, void *);
static int pfunc (const void *, const void *);
static int nfunc (const void *, const void *);
static void remove_null_names (export_type **);
static void process_duplicates (export_type **);
static void fill_ordinals (export_type **);
static void mangle_defs (void);
static void usage (FILE *, int);
static void inform (const char *, ...) ATTRIBUTE_PRINTF_1;
static void set_dll_name_from_def (const char *name, char is_dll);
static char *
prefix_encode (char *start, unsigned code)
{
static char alpha[26] = "abcdefghijklmnopqrstuvwxyz";
static char buf[32];
char *p;
strcpy (buf, start);
p = strchr (buf, '\0');
do
*p++ = alpha[code % sizeof (alpha)];
while ((code /= sizeof (alpha)) != 0);
*p = '\0';
return buf;
}
static char *
dlltmp (char **buf, const char *fmt)
{
if (!*buf)
{
*buf = malloc (strlen (tmp_prefix) + 64);
sprintf (*buf, fmt, tmp_prefix);
}
return *buf;
}
static void
inform VPARAMS ((const char * message, ...))
{
VA_OPEN (args, message);
VA_FIXEDARG (args, const char *, message);
if (!verbose)
return;
report (message, args);
VA_CLOSE (args);
}
static const char *
rvaafter (int mach)
{
switch (mach)
{
case MARM:
case M386:
case MX86:
case MPPC:
case MTHUMB:
case MARM_INTERWORK:
case MMCORE_BE:
case MMCORE_LE:
case MMCORE_ELF:
case MMCORE_ELF_LE:
case MARM_EPOC:
case MARM_WINCE:
break;
default:
/* xgettext:c-format */
fatal (_("Internal error: Unknown machine type: %d"), mach);
break;
}
return "";
}
static const char *
rvabefore (int mach)
{
switch (mach)
{
case MARM:
case M386:
case MX86:
case MPPC:
case MTHUMB:
case MARM_INTERWORK:
case MMCORE_BE:
case MMCORE_LE:
case MMCORE_ELF:
case MMCORE_ELF_LE:
case MARM_EPOC:
case MARM_WINCE:
return ".rva\t";
default:
/* xgettext:c-format */
fatal (_("Internal error: Unknown machine type: %d"), mach);
break;
}
return "";
}
static const char *
asm_prefix (int mach, const char *name)
{
switch (mach)
{
case MARM:
case MPPC:
case MTHUMB:
case MARM_INTERWORK:
case MMCORE_BE:
case MMCORE_LE:
case MMCORE_ELF:
case MMCORE_ELF_LE:
case MARM_EPOC:
case MARM_WINCE:
break;
case M386:
case MX86:
/* Symbol names starting with ? do not have a leading underscore. */
if ((name && *name == '?') || leading_underscore == 0)
break;
else
return "_";
default:
/* xgettext:c-format */
fatal (_("Internal error: Unknown machine type: %d"), mach);
break;
}
return "";
}
#define ASM_BYTE mtable[machine].how_byte
#define ASM_SHORT mtable[machine].how_short
#define ASM_LONG mtable[machine].how_long
#define ASM_TEXT mtable[machine].how_asciz
#define ASM_C mtable[machine].how_comment
#define ASM_JUMP mtable[machine].how_jump
#define ASM_GLOBAL mtable[machine].how_global
#define ASM_SPACE mtable[machine].how_space
#define ASM_ALIGN_SHORT mtable[machine].how_align_short
#define ASM_RVA_BEFORE rvabefore (machine)
#define ASM_RVA_AFTER rvaafter (machine)
#define ASM_PREFIX(NAME) asm_prefix (machine, (NAME))
#define ASM_ALIGN_LONG mtable[machine].how_align_long
#define HOW_BFD_READ_TARGET 0 /* Always default. */
#define HOW_BFD_WRITE_TARGET mtable[machine].how_bfd_target
#define HOW_BFD_ARCH mtable[machine].how_bfd_arch
#define HOW_JTAB (delay ? mtable[machine].how_dljtab \
: mtable[machine].how_jtab)
#define HOW_JTAB_SIZE (delay ? mtable[machine].how_dljtab_size \
: mtable[machine].how_jtab_size)
#define HOW_JTAB_ROFF (delay ? mtable[machine].how_dljtab_roff1 \
: mtable[machine].how_jtab_roff)
#define HOW_JTAB_ROFF2 (delay ? mtable[machine].how_dljtab_roff2 : 0)
#define HOW_JTAB_ROFF3 (delay ? mtable[machine].how_dljtab_roff3 : 0)
#define ASM_SWITCHES mtable[machine].how_default_as_switches
static char **oav;
static void
process_def_file (const char *name)
{
FILE *f = fopen (name, FOPEN_RT);
if (!f)
/* xgettext:c-format */
fatal (_("Can't open def file: %s"), name);
yyin = f;
/* xgettext:c-format */
inform (_("Processing def file: %s"), name);
yyparse ();
inform (_("Processed def file"));
}
/**********************************************************************/
/* Communications with the parser. */
static int d_nfuncs; /* Number of functions exported. */
static int d_named_nfuncs; /* Number of named functions exported. */
static int d_low_ord; /* Lowest ordinal index. */
static int d_high_ord; /* Highest ordinal index. */
static export_type *d_exports; /* List of exported functions. */
static export_type **d_exports_lexically; /* Vector of exported functions in alpha order. */
static dlist_type *d_list; /* Descriptions. */
static dlist_type *a_list; /* Stuff to go in directives. */
static int d_nforwards = 0; /* Number of forwarded exports. */
static int d_is_dll;
static int d_is_exe;
int
yyerror (const char * err ATTRIBUTE_UNUSED)
{
/* xgettext:c-format */
non_fatal (_("Syntax error in def file %s:%d"), def_file, linenumber);
return 0;
}
void
def_exports (const char *name, const char *internal_name, int ordinal,
int noname, int constant, int data, int private,
const char *its_name)
{
struct export *p = (struct export *) xmalloc (sizeof (*p));
p->name = name;
p->internal_name = internal_name ? internal_name : name;
p->its_name = its_name;
p->import_name = name;
p->ordinal = ordinal;
p->constant = constant;
p->noname = noname;
p->private = private;
p->data = data;
p->next = d_exports;
d_exports = p;
d_nfuncs++;
if ((internal_name != NULL)
&& (strchr (internal_name, '.') != NULL))
p->forward = ++d_nforwards;
else
p->forward = 0; /* no forward */
}
static void
set_dll_name_from_def (const char *name, char is_dll)
{
const char *image_basename = lbasename (name);
if (image_basename != name)
non_fatal (_("%s: Path components stripped from image name, '%s'."),
def_file, name);
/* Append the default suffix, if none specified. */
if (strchr (image_basename, '.') == 0)
{
const char * suffix = is_dll ? ".dll" : ".exe";
dll_name = xmalloc (strlen (image_basename) + strlen (suffix) + 1);
sprintf (dll_name, "%s%s", image_basename, suffix);
}
else
dll_name = xstrdup (image_basename);
}
void
def_name (const char *name, int base)
{
/* xgettext:c-format */
inform (_("NAME: %s base: %x"), name, base);
if (d_is_dll)
non_fatal (_("Can't have LIBRARY and NAME"));
/* If --dllname not provided, use the one in the DEF file.
FIXME: Is this appropriate for executables? */
if (!dll_name)
set_dll_name_from_def (name, 0);
d_is_exe = 1;
}
void
def_library (const char *name, int base)
{
/* xgettext:c-format */
inform (_("LIBRARY: %s base: %x"), name, base);
if (d_is_exe)
non_fatal (_("Can't have LIBRARY and NAME"));
/* If --dllname not provided, use the one in the DEF file. */
if (!dll_name)
set_dll_name_from_def (name, 1);
d_is_dll = 1;
}
void
def_description (const char *desc)
{
dlist_type *d = (dlist_type *) xmalloc (sizeof (dlist_type));
d->text = xstrdup (desc);
d->next = d_list;
d_list = d;
}
static void
new_directive (char *dir)
{
dlist_type *d = (dlist_type *) xmalloc (sizeof (dlist_type));
d->text = xstrdup (dir);
d->next = a_list;
a_list = d;
}
void
def_heapsize (int reserve, int commit)
{
char b[200];
if (commit > 0)
sprintf (b, "-heap 0x%x,0x%x ", reserve, commit);
else
sprintf (b, "-heap 0x%x ", reserve);
new_directive (xstrdup (b));
}
void
def_stacksize (int reserve, int commit)
{
char b[200];
if (commit > 0)
sprintf (b, "-stack 0x%x,0x%x ", reserve, commit);
else
sprintf (b, "-stack 0x%x ", reserve);
new_directive (xstrdup (b));
}
/* append_import simply adds the given import definition to the global
import_list. It is used by def_import. */
static void
append_import (const char *symbol_name, const char *dllname, int func_ordinal,
const char *its_name)
{
iheadtype **pq;
iheadtype *q;
for (pq = &import_list; *pq != NULL; pq = &(*pq)->next)
{
if (strcmp ((*pq)->dllname, dllname) == 0)
{
q = *pq;
q->functail->next = xmalloc (sizeof (ifunctype));
q->functail = q->functail->next;
q->functail->ord = func_ordinal;
q->functail->name = xstrdup (symbol_name);
q->functail->its_name = (its_name ? xstrdup (its_name) : NULL);
q->functail->next = NULL;
q->nfuncs++;
return;
}
}
q = xmalloc (sizeof (iheadtype));
q->dllname = xstrdup (dllname);
q->nfuncs = 1;
q->funchead = xmalloc (sizeof (ifunctype));
q->functail = q->funchead;
q->next = NULL;
q->functail->name = xstrdup (symbol_name);
q->functail->its_name = (its_name ? xstrdup (its_name) : NULL);
q->functail->ord = func_ordinal;
q->functail->next = NULL;
*pq = q;
}
/* def_import is called from within defparse.y when an IMPORT
declaration is encountered. Depending on the form of the
declaration, the module name may or may not need ".dll" to be
appended to it, the name of the function may be stored in internal
or entry, and there may or may not be an ordinal value associated
with it. */
/* A note regarding the parse modes:
In defparse.y we have to accept import declarations which follow
any one of the following forms:
<func_name_in_app> = <dll_name>.<func_name_in_dll>
<func_name_in_app> = <dll_name>.<number>
<dll_name>.<func_name_in_dll>
<dll_name>.<number>
Furthermore, the dll's name may or may not end with ".dll", which
complicates the parsing a little. Normally the dll's name is
passed to def_import() in the "module" parameter, but when it ends
with ".dll" it gets passed in "module" sans ".dll" and that needs
to be reappended.
def_import gets five parameters:
APP_NAME - the name of the function in the application, if
present, or NULL if not present.
MODULE - the name of the dll, possibly sans extension (ie, '.dll').
DLLEXT - the extension of the dll, if present, NULL if not present.
ENTRY - the name of the function in the dll, if present, or NULL.
ORD_VAL - the numerical tag of the function in the dll, if present,
or NULL. Exactly one of <entry> or <ord_val> must be
present (i.e., not NULL). */
void
def_import (const char *app_name, const char *module, const char *dllext,
const char *entry, int ord_val, const char *its_name)
{
const char *application_name;
char *buf;
if (entry != NULL)
application_name = entry;
else
{
if (app_name != NULL)
application_name = app_name;
else
application_name = "";
}
if (dllext != NULL)
{
buf = (char *) alloca (strlen (module) + strlen (dllext) + 2);
sprintf (buf, "%s.%s", module, dllext);
module = buf;
}
append_import (application_name, module, ord_val, its_name);
}
void
def_version (int major, int minor)
{
printf ("VERSION %d.%d\n", major, minor);
}
void
def_section (const char *name, int attr)
{
char buf[200];
char atts[5];
char *d = atts;
if (attr & 1)
*d++ = 'R';
if (attr & 2)
*d++ = 'W';
if (attr & 4)
*d++ = 'X';
if (attr & 8)
*d++ = 'S';
*d++ = 0;
sprintf (buf, "-attr %s %s", name, atts);
new_directive (xstrdup (buf));
}
void
def_code (int attr)
{
def_section ("CODE", attr);
}
void
def_data (int attr)
{
def_section ("DATA", attr);
}
/**********************************************************************/
static void
run (const char *what, char *args)
{
char *s;
int pid, wait_status;
int i;
const char **argv;
char *errmsg_fmt, *errmsg_arg;
char *temp_base = choose_temp_base ();
inform ("run: %s %s", what, args);
/* Count the args */
i = 0;
for (s = args; *s; s++)
if (*s == ' ')
i++;
i++;
argv = alloca (sizeof (char *) * (i + 3));
i = 0;
argv[i++] = what;
s = args;
while (1)
{
while (*s == ' ')
++s;
argv[i++] = s;
while (*s != ' ' && *s != 0)
s++;
if (*s == 0)
break;
*s++ = 0;
}
argv[i++] = NULL;
pid = pexecute (argv[0], (char * const *) argv, program_name, temp_base,
&errmsg_fmt, &errmsg_arg, PEXECUTE_ONE | PEXECUTE_SEARCH);
if (pid == -1)
{
inform ("%s", strerror (errno));
fatal (errmsg_fmt, errmsg_arg);
}
pid = pwait (pid, & wait_status, 0);
if (pid == -1)
{
/* xgettext:c-format */
fatal (_("wait: %s"), strerror (errno));
}
else if (WIFSIGNALED (wait_status))
{
/* xgettext:c-format */
fatal (_("subprocess got fatal signal %d"), WTERMSIG (wait_status));
}
else if (WIFEXITED (wait_status))
{
if (WEXITSTATUS (wait_status) != 0)
/* xgettext:c-format */
non_fatal (_("%s exited with status %d"),
what, WEXITSTATUS (wait_status));
}
else
abort ();
}
/* Look for a list of symbols to export in the .drectve section of
ABFD. Pass each one to def_exports. */
static void
scan_drectve_symbols (bfd *abfd)
{
asection * s;
int size;
char * buf;
char * p;
char * e;
/* Look for .drectve's */
s = bfd_get_section_by_name (abfd, DRECTVE_SECTION_NAME);
if (s == NULL)
return;
size = bfd_get_section_size (s);
buf = xmalloc (size);
bfd_get_section_contents (abfd, s, buf, 0, size);
/* xgettext:c-format */
inform (_("Sucking in info from %s section in %s"),
DRECTVE_SECTION_NAME, bfd_get_filename (abfd));
/* Search for -export: strings. The exported symbols can optionally
have type tags (eg., -export:foo,data), so handle those as well.
Currently only data tag is supported. */
p = buf;
e = buf + size;
while (p < e)
{
if (p[0] == '-'
&& CONST_STRNEQ (p, "-export:"))
{
char * name;
char * c;
flagword flags = BSF_FUNCTION;
p += 8;
/* Do we have a quoted export? */
if (*p == '"')
{
p++;
name = p;
while (p < e && *p != '"')
++p;
}
else
{
name = p;
while (p < e && *p != ',' && *p != ' ' && *p != '-')
p++;
}
c = xmalloc (p - name + 1);
memcpy (c, name, p - name);
c[p - name] = 0;
/* Advance over trailing quote. */
if (p < e && *p == '"')
++p;
if (p < e && *p == ',') /* found type tag. */
{
char *tag_start = ++p;
while (p < e && *p != ' ' && *p != '-')
p++;
if (CONST_STRNEQ (tag_start, "data"))
flags &= ~BSF_FUNCTION;
}
/* FIXME: The 5th arg is for the `constant' field.
What should it be? Not that it matters since it's not
currently useful. */
def_exports (c, 0, -1, 0, 0, ! (flags & BSF_FUNCTION), 0, NULL);
if (add_stdcall_alias && strchr (c, '@'))
{
int lead_at = (*c == '@') ;
char *exported_name = xstrdup (c + lead_at);
char *atsym = strchr (exported_name, '@');
*atsym = '\0';
/* Note: stdcall alias symbols can never be data. */
def_exports (exported_name, xstrdup (c), -1, 0, 0, 0, 0, NULL);
}
}
else
p++;
}
free (buf);
}
/* Look through the symbols in MINISYMS, and add each one to list of
symbols to export. */
static void
scan_filtered_symbols (bfd *abfd, void *minisyms, long symcount,
unsigned int size)
{
asymbol *store;
bfd_byte *from, *fromend;
store = bfd_make_empty_symbol (abfd);
if (store == NULL)
bfd_fatal (bfd_get_filename (abfd));
from = (bfd_byte *) minisyms;
fromend = from + symcount * size;
for (; from < fromend; from += size)
{
asymbol *sym;
const char *symbol_name;
sym = bfd_minisymbol_to_symbol (abfd, FALSE, from, store);
if (sym == NULL)
bfd_fatal (bfd_get_filename (abfd));
symbol_name = bfd_asymbol_name (sym);
if (bfd_get_symbol_leading_char (abfd) == symbol_name[0])
++symbol_name;
def_exports (xstrdup (symbol_name) , 0, -1, 0, 0,
! (sym->flags & BSF_FUNCTION), 0, NULL);
if (add_stdcall_alias && strchr (symbol_name, '@'))
{
int lead_at = (*symbol_name == '@');
char *exported_name = xstrdup (symbol_name + lead_at);
char *atsym = strchr (exported_name, '@');
*atsym = '\0';
/* Note: stdcall alias symbols can never be data. */
def_exports (exported_name, xstrdup (symbol_name), -1, 0, 0, 0, 0, NULL);
}
}
}
/* Add a list of symbols to exclude. */
static void
add_excludes (const char *new_excludes)
{
char *local_copy;
char *exclude_string;
local_copy = xstrdup (new_excludes);
exclude_string = strtok (local_copy, ",:");
for (; exclude_string; exclude_string = strtok (NULL, ",:"))
{
struct string_list *new_exclude;
new_exclude = ((struct string_list *)
xmalloc (sizeof (struct string_list)));
new_exclude->string = (char *) xmalloc (strlen (exclude_string) + 2);
/* Don't add a leading underscore for fastcall symbols. */
if (*exclude_string == '@')
sprintf (new_exclude->string, "%s", exclude_string);
else
sprintf (new_exclude->string, "%s%s", (!leading_underscore ? "" : "_"),
exclude_string);
new_exclude->next = excludes;
excludes = new_exclude;
/* xgettext:c-format */
inform (_("Excluding symbol: %s"), exclude_string);
}
free (local_copy);
}
/* See if STRING is on the list of symbols to exclude. */
static bfd_boolean
match_exclude (const char *string)
{
struct string_list *excl_item;
for (excl_item = excludes; excl_item; excl_item = excl_item->next)
if (strcmp (string, excl_item->string) == 0)
return TRUE;
return FALSE;
}
/* Add the default list of symbols to exclude. */
static void
set_default_excludes (void)
{
add_excludes (default_excludes);
}
/* Choose which symbols to export. */
static long
filter_symbols (bfd *abfd, void *minisyms, long symcount, unsigned int size)
{
bfd_byte *from, *fromend, *to;
asymbol *store;
store = bfd_make_empty_symbol (abfd);
if (store == NULL)
bfd_fatal (bfd_get_filename (abfd));
from = (bfd_byte *) minisyms;
fromend = from + symcount * size;
to = (bfd_byte *) minisyms;
for (; from < fromend; from += size)
{
int keep = 0;
asymbol *sym;
sym = bfd_minisymbol_to_symbol (abfd, FALSE, (const void *) from, store);
if (sym == NULL)
bfd_fatal (bfd_get_filename (abfd));
/* Check for external and defined only symbols. */
keep = (((sym->flags & BSF_GLOBAL) != 0
|| (sym->flags & BSF_WEAK) != 0
|| bfd_is_com_section (sym->section))
&& ! bfd_is_und_section (sym->section));
keep = keep && ! match_exclude (sym->name);
if (keep)
{
memcpy (to, from, size);
to += size;
}
}
return (to - (bfd_byte *) minisyms) / size;
}
/* Export all symbols in ABFD, except for ones we were told not to
export. */
static void
scan_all_symbols (bfd *abfd)
{
long symcount;
void *minisyms;
unsigned int size;
/* Ignore bfds with an import descriptor table. We assume that any
such BFD contains symbols which are exported from another DLL,
and we don't want to reexport them from here. */
if (bfd_get_section_by_name (abfd, ".idata$4"))
return;
if (! (bfd_get_file_flags (abfd) & HAS_SYMS))
{
/* xgettext:c-format */
non_fatal (_("%s: no symbols"), bfd_get_filename (abfd));
return;
}
symcount = bfd_read_minisymbols (abfd, FALSE, &minisyms, &size);
if (symcount < 0)
bfd_fatal (bfd_get_filename (abfd));
if (symcount == 0)
{
/* xgettext:c-format */
non_fatal (_("%s: no symbols"), bfd_get_filename (abfd));
return;
}
/* Discard the symbols we don't want to export. It's OK to do this
in place; we'll free the storage anyway. */
symcount = filter_symbols (abfd, minisyms, symcount, size);
scan_filtered_symbols (abfd, minisyms, symcount, size);
free (minisyms);
}
/* Look at the object file to decide which symbols to export. */
static void
scan_open_obj_file (bfd *abfd)
{
if (export_all_symbols)
scan_all_symbols (abfd);
else
scan_drectve_symbols (abfd);
/* FIXME: we ought to read in and block out the base relocations. */
/* xgettext:c-format */
inform (_("Done reading %s"), bfd_get_filename (abfd));
}
static void
scan_obj_file (const char *filename)
{
bfd * f = bfd_openr (filename, 0);
if (!f)
/* xgettext:c-format */
fatal (_("Unable to open object file: %s: %s"), filename, bfd_get_errmsg ());
/* xgettext:c-format */
inform (_("Scanning object file %s"), filename);
if (bfd_check_format (f, bfd_archive))
{
bfd *arfile = bfd_openr_next_archived_file (f, 0);
while (arfile)
{
if (bfd_check_format (arfile, bfd_object))
scan_open_obj_file (arfile);
bfd_close (arfile);
arfile = bfd_openr_next_archived_file (f, arfile);
}
#ifdef DLLTOOL_MCORE_ELF
if (mcore_elf_out_file)
inform (_("Cannot produce mcore-elf dll from archive file: %s"), filename);
#endif
}
else if (bfd_check_format (f, bfd_object))
{
scan_open_obj_file (f);
#ifdef DLLTOOL_MCORE_ELF
if (mcore_elf_out_file)
mcore_elf_cache_filename (filename);
#endif
}
bfd_close (f);
}
static void
dump_def_info (FILE *f)
{
int i;
export_type *exp;
fprintf (f, "%s ", ASM_C);
for (i = 0; oav[i]; i++)
fprintf (f, "%s ", oav[i]);
fprintf (f, "\n");
for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
{
fprintf (f, "%s %d = %s %s @ %d %s%s%s%s%s%s\n",
ASM_C,
i,
exp->name,
exp->internal_name,
exp->ordinal,
exp->noname ? "NONAME " : "",
exp->private ? "PRIVATE " : "",
exp->constant ? "CONSTANT" : "",
exp->data ? "DATA" : "",
exp->its_name ? " ==" : "",
exp->its_name ? exp->its_name : "");
}
}
/* Generate the .exp file. */
static int
sfunc (const void *a, const void *b)
{
if (*(const bfd_vma *) a == *(const bfd_vma *) b)
return 0;
return ((*(const bfd_vma *) a > *(const bfd_vma *) b) ? 1 : -1);
}
static void
flush_page (FILE *f, bfd_vma *need, bfd_vma page_addr, int on_page)
{
int i;
/* Flush this page. */
fprintf (f, "\t%s\t0x%08x\t%s Starting RVA for chunk\n",
ASM_LONG,
(int) page_addr,
ASM_C);
fprintf (f, "\t%s\t0x%x\t%s Size of block\n",
ASM_LONG,
(on_page * 2) + (on_page & 1) * 2 + 8,
ASM_C);
for (i = 0; i < on_page; i++)
{
bfd_vma needed = need[i];
if (needed)
{
if (!create_for_pep)
{
/* Relocation via HIGHLOW. */
needed = ((needed - page_addr) | 0x3000) & 0xffff;
}
else
{
/* Relocation via DIR64. */
needed = ((needed - page_addr) | 0xa000) & 0xffff;
}
}
fprintf (f, "\t%s\t0x%lx\n", ASM_SHORT, (long) needed);
}
/* And padding */
if (on_page & 1)
fprintf (f, "\t%s\t0x%x\n", ASM_SHORT, 0 | 0x0000);
}
static void
gen_def_file (void)
{
int i;
export_type *exp;
inform (_("Adding exports to output file"));
fprintf (output_def, ";");
for (i = 0; oav[i]; i++)
fprintf (output_def, " %s", oav[i]);
fprintf (output_def, "\nEXPORTS\n");
for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
{
char *quote = strchr (exp->name, '.') ? "\"" : "";
char *res = cplus_demangle (exp->internal_name, DMGL_ANSI | DMGL_PARAMS);
if (res)
{
fprintf (output_def,";\t%s\n", res);
free (res);
}
if (strcmp (exp->name, exp->internal_name) == 0)
{
fprintf (output_def, "\t%s%s%s @ %d%s%s%s%s%s\n",
quote,
exp->name,
quote,
exp->ordinal,
exp->noname ? " NONAME" : "",
exp->private ? "PRIVATE " : "",
exp->data ? " DATA" : "",
exp->its_name ? " ==" : "",
exp->its_name ? exp->its_name : "");
}
else
{
char * quote1 = strchr (exp->internal_name, '.') ? "\"" : "";
/* char *alias = */
fprintf (output_def, "\t%s%s%s = %s%s%s @ %d%s%s%s%s%s\n",
quote,
exp->name,
quote,
quote1,
exp->internal_name,
quote1,
exp->ordinal,
exp->noname ? " NONAME" : "",
exp->private ? "PRIVATE " : "",
exp->data ? " DATA" : "",
exp->its_name ? " ==" : "",
exp->its_name ? exp->its_name : "");
}
}
inform (_("Added exports to output file"));
}
/* generate_idata_ofile generates the portable assembly source code
for the idata sections. It appends the source code to the end of
the file. */
static void
generate_idata_ofile (FILE *filvar)
{
iheadtype *headptr;
ifunctype *funcptr;
int headindex;
int funcindex;
int nheads;
if (import_list == NULL)
return;
fprintf (filvar, "%s Import data sections\n", ASM_C);
fprintf (filvar, "\n\t.section\t.idata$2\n");
fprintf (filvar, "\t%s\tdoi_idata\n", ASM_GLOBAL);
fprintf (filvar, "doi_idata:\n");
nheads = 0;
for (headptr = import_list; headptr != NULL; headptr = headptr->next)
{
fprintf (filvar, "\t%slistone%d%s\t%s %s\n",
ASM_RVA_BEFORE, nheads, ASM_RVA_AFTER,
ASM_C, headptr->dllname);
fprintf (filvar, "\t%s\t0\n", ASM_LONG);
fprintf (filvar, "\t%s\t0\n", ASM_LONG);
fprintf (filvar, "\t%sdllname%d%s\n",
ASM_RVA_BEFORE, nheads, ASM_RVA_AFTER);
fprintf (filvar, "\t%slisttwo%d%s\n\n",
ASM_RVA_BEFORE, nheads, ASM_RVA_AFTER);
nheads++;
}
fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* NULL record at */
fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* end of idata$2 */
fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* section */
fprintf (filvar, "\t%s\t0\n", ASM_LONG);
fprintf (filvar, "\t%s\t0\n", ASM_LONG);
fprintf (filvar, "\n\t.section\t.idata$4\n");
headindex = 0;
for (headptr = import_list; headptr != NULL; headptr = headptr->next)
{
fprintf (filvar, "listone%d:\n", headindex);
for (funcindex = 0; funcindex < headptr->nfuncs; funcindex++)
{
if (create_for_pep)
fprintf (filvar, "\t%sfuncptr%d_%d%s\n%s\t0\n",
ASM_RVA_BEFORE, headindex, funcindex, ASM_RVA_AFTER,
ASM_LONG);
else
fprintf (filvar, "\t%sfuncptr%d_%d%s\n",
ASM_RVA_BEFORE, headindex, funcindex, ASM_RVA_AFTER);
}
if (create_for_pep)
fprintf (filvar, "\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
else
fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* NULL terminating list. */
headindex++;
}
fprintf (filvar, "\n\t.section\t.idata$5\n");
headindex = 0;
for (headptr = import_list; headptr != NULL; headptr = headptr->next)
{
fprintf (filvar, "listtwo%d:\n", headindex);
for (funcindex = 0; funcindex < headptr->nfuncs; funcindex++)
{
if (create_for_pep)
fprintf (filvar, "\t%sfuncptr%d_%d%s\n%s\t0\n",
ASM_RVA_BEFORE, headindex, funcindex, ASM_RVA_AFTER,
ASM_LONG);
else
fprintf (filvar, "\t%sfuncptr%d_%d%s\n",
ASM_RVA_BEFORE, headindex, funcindex, ASM_RVA_AFTER);
}
if (create_for_pep)
fprintf (filvar, "\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
else
fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* NULL terminating list. */
headindex++;
}
fprintf (filvar, "\n\t.section\t.idata$6\n");
headindex = 0;
for (headptr = import_list; headptr != NULL; headptr = headptr->next)
{
funcindex = 0;
for (funcptr = headptr->funchead; funcptr != NULL;
funcptr = funcptr->next)
{
fprintf (filvar,"funcptr%d_%d:\n", headindex, funcindex);
fprintf (filvar,"\t%s\t%d\n", ASM_SHORT,
((funcptr->ord) & 0xFFFF));
fprintf (filvar,"\t%s\t\"%s\"\n", ASM_TEXT,
(funcptr->its_name ? funcptr->its_name : funcptr->name));
fprintf (filvar,"\t%s\t0\n", ASM_BYTE);
funcindex++;
}
headindex++;
}
fprintf (filvar, "\n\t.section\t.idata$7\n");
headindex = 0;
for (headptr = import_list; headptr != NULL; headptr = headptr->next)
{
fprintf (filvar,"dllname%d:\n", headindex);
fprintf (filvar,"\t%s\t\"%s\"\n", ASM_TEXT, headptr->dllname);
fprintf (filvar,"\t%s\t0\n", ASM_BYTE);
headindex++;
}
}
/* Assemble the specified file. */
static void
assemble_file (const char * source, const char * dest)
{
char * cmd;
cmd = (char *) alloca (strlen (ASM_SWITCHES) + strlen (as_flags)
+ strlen (source) + strlen (dest) + 50);
sprintf (cmd, "%s %s -o %s %s", ASM_SWITCHES, as_flags, dest, source);
run (as_name, cmd);
}
static void
gen_exp_file (void)
{
FILE *f;
int i;
export_type *exp;
dlist_type *dl;
/* xgettext:c-format */
inform (_("Generating export file: %s"), exp_name);
f = fopen (TMP_ASM, FOPEN_WT);
if (!f)
/* xgettext:c-format */
fatal (_("Unable to open temporary assembler file: %s"), TMP_ASM);
/* xgettext:c-format */
inform (_("Opened temporary file: %s"), TMP_ASM);
dump_def_info (f);
if (d_exports)
{
fprintf (f, "\t.section .edata\n\n");
fprintf (f, "\t%s 0 %s Allways 0\n", ASM_LONG, ASM_C);
fprintf (f, "\t%s 0x%lx %s Time and date\n", ASM_LONG,
(unsigned long) time(0), ASM_C);
fprintf (f, "\t%s 0 %s Major and Minor version\n", ASM_LONG, ASM_C);
fprintf (f, "\t%sname%s %s Ptr to name of dll\n", ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
fprintf (f, "\t%s %d %s Starting ordinal of exports\n", ASM_LONG, d_low_ord, ASM_C);
fprintf (f, "\t%s %d %s Number of functions\n", ASM_LONG, d_high_ord - d_low_ord + 1, ASM_C);
fprintf(f,"\t%s named funcs %d, low ord %d, high ord %d\n",
ASM_C,
d_named_nfuncs, d_low_ord, d_high_ord);
fprintf (f, "\t%s %d %s Number of names\n", ASM_LONG,
show_allnames ? d_high_ord - d_low_ord + 1 : d_named_nfuncs, ASM_C);
fprintf (f, "\t%safuncs%s %s Address of functions\n", ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
fprintf (f, "\t%sanames%s %s Address of Name Pointer Table\n",
ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
fprintf (f, "\t%sanords%s %s Address of ordinals\n", ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
fprintf (f, "name: %s \"%s\"\n", ASM_TEXT, dll_name);
fprintf(f,"%s Export address Table\n", ASM_C);
fprintf(f,"\t%s\n", ASM_ALIGN_LONG);
fprintf (f, "afuncs:\n");
i = d_low_ord;
for (exp = d_exports; exp; exp = exp->next)
{
if (exp->ordinal != i)
{
while (i < exp->ordinal)
{
fprintf(f,"\t%s\t0\n", ASM_LONG);
i++;
}
}
if (exp->forward == 0)
{
if (exp->internal_name[0] == '@')
fprintf (f, "\t%s%s%s\t%s %d\n", ASM_RVA_BEFORE,
exp->internal_name, ASM_RVA_AFTER, ASM_C, exp->ordinal);
else
fprintf (f, "\t%s%s%s%s\t%s %d\n", ASM_RVA_BEFORE,
ASM_PREFIX (exp->internal_name),
exp->internal_name, ASM_RVA_AFTER, ASM_C, exp->ordinal);
}
else
fprintf (f, "\t%sf%d%s\t%s %d\n", ASM_RVA_BEFORE,
exp->forward, ASM_RVA_AFTER, ASM_C, exp->ordinal);
i++;
}
fprintf (f,"%s Export Name Pointer Table\n", ASM_C);
fprintf (f, "anames:\n");
for (i = 0; (exp = d_exports_lexically[i]); i++)
{
if (!exp->noname || show_allnames)
fprintf (f, "\t%sn%d%s\n",
ASM_RVA_BEFORE, exp->ordinal, ASM_RVA_AFTER);
}
fprintf (f,"%s Export Ordinal Table\n", ASM_C);
fprintf (f, "anords:\n");
for (i = 0; (exp = d_exports_lexically[i]); i++)
{
if (!exp->noname || show_allnames)
fprintf (f, "\t%s %d\n", ASM_SHORT, exp->ordinal - d_low_ord);
}
fprintf(f,"%s Export Name Table\n", ASM_C);
for (i = 0; (exp = d_exports_lexically[i]); i++)
{
if (!exp->noname || show_allnames)
fprintf (f, "n%d: %s \"%s\"\n",
exp->ordinal, ASM_TEXT,
(exp->its_name ? exp->its_name : xlate (exp->name)));
if (exp->forward != 0)
fprintf (f, "f%d: %s \"%s\"\n",
exp->forward, ASM_TEXT, exp->internal_name);
}
if (a_list)
{
fprintf (f, "\t.section %s\n", DRECTVE_SECTION_NAME);
for (dl = a_list; dl; dl = dl->next)
{
fprintf (f, "\t%s\t\"%s\"\n", ASM_TEXT, dl->text);
}
}
if (d_list)
{
fprintf (f, "\t.section .rdata\n");
for (dl = d_list; dl; dl = dl->next)
{
char *p;
int l;
/* We don't output as ascii because there can
be quote characters in the string. */
l = 0;
for (p = dl->text; *p; p++)
{
if (l == 0)
fprintf (f, "\t%s\t", ASM_BYTE);
else
fprintf (f, ",");
fprintf (f, "%d", *p);
if (p[1] == 0)
{
fprintf (f, ",0\n");
break;
}
if (++l == 10)
{
fprintf (f, "\n");
l = 0;
}
}
}
}
}
/* Add to the output file a way of getting to the exported names
without using the import library. */
if (add_indirect)
{
fprintf (f, "\t.section\t.rdata\n");
for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
if (!exp->noname || show_allnames)
{
/* We use a single underscore for MS compatibility, and a
double underscore for backward compatibility with old
cygwin releases. */
if (create_compat_implib)
fprintf (f, "\t%s\t__imp_%s\n", ASM_GLOBAL, exp->name);
fprintf (f, "\t%s\t_imp_%s%s\n", ASM_GLOBAL,
(!leading_underscore ? "" : "_"), exp->name);
if (create_compat_implib)
fprintf (f, "__imp_%s:\n", exp->name);
fprintf (f, "_imp_%s%s:\n", (!leading_underscore ? "" : "_"), exp->name);
fprintf (f, "\t%s\t%s\n", ASM_LONG, exp->name);
}
}
/* Dump the reloc section if a base file is provided. */
if (base_file)
{
bfd_vma addr;
bfd_vma need[COFF_PAGE_SIZE];
bfd_vma page_addr;
bfd_size_type numbytes;
int num_entries;
bfd_vma *copy;
int j;
int on_page;
fprintf (f, "\t.section\t.init\n");
fprintf (f, "lab:\n");
fseek (base_file, 0, SEEK_END);
numbytes = ftell (base_file);
fseek (base_file, 0, SEEK_SET);
copy = xmalloc (numbytes);
if (fread (copy, 1, numbytes, base_file) < numbytes)
fatal (_("failed to read the number of entries from base file"));
num_entries = numbytes / sizeof (bfd_vma);
fprintf (f, "\t.section\t.reloc\n");
if (num_entries)
{
int src;
int dst = 0;
bfd_vma last = (bfd_vma) -1;
qsort (copy, num_entries, sizeof (bfd_vma), sfunc);
/* Delete duplicates */
for (src = 0; src < num_entries; src++)
{
if (last != copy[src])
last = copy[dst++] = copy[src];
}
num_entries = dst;
addr = copy[0];
page_addr = addr & PAGE_MASK; /* work out the page addr */
on_page = 0;
for (j = 0; j < num_entries; j++)
{
addr = copy[j];
if ((addr & PAGE_MASK) != page_addr)
{
flush_page (f, need, page_addr, on_page);
on_page = 0;
page_addr = addr & PAGE_MASK;
}
need[on_page++] = addr;
}
flush_page (f, need, page_addr, on_page);
/* fprintf (f, "\t%s\t0,0\t%s End\n", ASM_LONG, ASM_C);*/
}
}
generate_idata_ofile (f);
fclose (f);
/* Assemble the file. */
assemble_file (TMP_ASM, exp_name);
if (dontdeltemps == 0)
unlink (TMP_ASM);
inform (_("Generated exports file"));
}
static const char *
xlate (const char *name)
{
int lead_at = (*name == '@');
int is_stdcall = (!lead_at && strchr (name, '@') != NULL);
if (!lead_at && (add_underscore
|| (add_stdcall_underscore && is_stdcall)))
{
char *copy = xmalloc (strlen (name) + 2);
copy[0] = '_';
strcpy (copy + 1, name);
name = copy;
}
if (killat)
{
char *p;
name += lead_at;
/* PR 9766: Look for the last @ sign in the name. */
p = strrchr (name, '@');
if (p && ISDIGIT (p[1]))
*p = 0;
}
return name;
}
typedef struct
{
int id;
const char *name;
int flags;
int align;
asection *sec;
asymbol *sym;
asymbol **sympp;
int size;
unsigned char *data;
} sinfo;
#ifndef DLLTOOL_PPC
#define TEXT 0
#define DATA 1
#define BSS 2
#define IDATA7 3
#define IDATA5 4
#define IDATA4 5
#define IDATA6 6
#define NSECS 7
#define TEXT_SEC_FLAGS \
(SEC_ALLOC | SEC_LOAD | SEC_CODE | SEC_READONLY | SEC_HAS_CONTENTS)
#define DATA_SEC_FLAGS (SEC_ALLOC | SEC_LOAD | SEC_DATA)
#define BSS_SEC_FLAGS SEC_ALLOC
#define INIT_SEC_DATA(id, name, flags, align) \
{ id, name, flags, align, NULL, NULL, NULL, 0, NULL }
static sinfo secdata[NSECS] =
{
INIT_SEC_DATA (TEXT, ".text", TEXT_SEC_FLAGS, 2),
INIT_SEC_DATA (DATA, ".data", DATA_SEC_FLAGS, 2),
INIT_SEC_DATA (BSS, ".bss", BSS_SEC_FLAGS, 2),
INIT_SEC_DATA (IDATA7, ".idata$7", SEC_HAS_CONTENTS, 2),
INIT_SEC_DATA (IDATA5, ".idata$5", SEC_HAS_CONTENTS, 2),
INIT_SEC_DATA (IDATA4, ".idata$4", SEC_HAS_CONTENTS, 2),
INIT_SEC_DATA (IDATA6, ".idata$6", SEC_HAS_CONTENTS, 1)
};
#else
/* Sections numbered to make the order the same as other PowerPC NT
compilers. This also keeps funny alignment thingies from happening. */
#define TEXT 0
#define PDATA 1
#define RDATA 2
#define IDATA5 3
#define IDATA4 4
#define IDATA6 5
#define IDATA7 6
#define DATA 7
#define BSS 8
#define NSECS 9
static sinfo secdata[NSECS] =
{
{ TEXT, ".text", SEC_CODE | SEC_HAS_CONTENTS, 3},
{ PDATA, ".pdata", SEC_HAS_CONTENTS, 2},
{ RDATA, ".reldata", SEC_HAS_CONTENTS, 2},
{ IDATA5, ".idata$5", SEC_HAS_CONTENTS, 2},
{ IDATA4, ".idata$4", SEC_HAS_CONTENTS, 2},
{ IDATA6, ".idata$6", SEC_HAS_CONTENTS, 1},
{ IDATA7, ".idata$7", SEC_HAS_CONTENTS, 2},
{ DATA, ".data", SEC_DATA, 2},
{ BSS, ".bss", 0, 2}
};
#endif
/* This is what we're trying to make. We generate the imp symbols with
both single and double underscores, for compatibility.
.text
.global _GetFileVersionInfoSizeW@8
.global __imp_GetFileVersionInfoSizeW@8
_GetFileVersionInfoSizeW@8:
jmp * __imp_GetFileVersionInfoSizeW@8
.section .idata$7 # To force loading of head
.long __version_a_head
# Import Address Table
.section .idata$5
__imp_GetFileVersionInfoSizeW@8:
.rva ID2
# Import Lookup Table
.section .idata$4
.rva ID2
# Hint/Name table
.section .idata$6
ID2: .short 2
.asciz "GetFileVersionInfoSizeW"
For the PowerPC, here's the variation on the above scheme:
# Rather than a simple "jmp *", the code to get to the dll function
# looks like:
.text
lwz r11,[tocv]__imp_function_name(r2)
# RELOC: 00000000 TOCREL16,TOCDEFN __imp_function_name
lwz r12,0(r11)
stw r2,4(r1)
mtctr r12
lwz r2,4(r11)
bctr */
static char *
make_label (const char *prefix, const char *name)
{
int len = strlen (ASM_PREFIX (name)) + strlen (prefix) + strlen (name);
char *copy = xmalloc (len + 1);
strcpy (copy, ASM_PREFIX (name));
strcat (copy, prefix);
strcat (copy, name);
return copy;
}
static char *
make_imp_label (const char *prefix, const char *name)
{
int len;
char *copy;
if (name[0] == '@')
{
len = strlen (prefix) + strlen (name);
copy = xmalloc (len + 1);
strcpy (copy, prefix);
strcat (copy, name);
}
else
{
len = strlen (ASM_PREFIX (name)) + strlen (prefix) + strlen (name);
copy = xmalloc (len + 1);
strcpy (copy, prefix);
strcat (copy, ASM_PREFIX (name));
strcat (copy, name);
}
return copy;
}
static bfd *
make_one_lib_file (export_type *exp, int i, int delay)
{
bfd * abfd;
asymbol * exp_label;
asymbol * iname = 0;
asymbol * iname2;
asymbol * iname_lab;
asymbol ** iname_lab_pp;
asymbol ** iname_pp;
#ifdef DLLTOOL_PPC
asymbol ** fn_pp;
asymbol ** toc_pp;
#define EXTRA 2
#endif
#ifndef EXTRA
#define EXTRA 0
#endif
asymbol * ptrs[NSECS + 4 + EXTRA + 1];
flagword applicable;
char * outname = xmalloc (strlen (TMP_STUB) + 10);
int oidx = 0;
sprintf (outname, "%s%05d.o", TMP_STUB, i);
abfd = bfd_openw (outname, HOW_BFD_WRITE_TARGET);
if (!abfd)
/* xgettext:c-format */
fatal (_("bfd_open failed open stub file: %s: %s"),
outname, bfd_get_errmsg ());
/* xgettext:c-format */
inform (_("Creating stub file: %s"), outname);
bfd_set_format (abfd, bfd_object);
bfd_set_arch_mach (abfd, HOW_BFD_ARCH, 0);
#ifdef DLLTOOL_ARM
if (machine == MARM_INTERWORK || machine == MTHUMB)
bfd_set_private_flags (abfd, F_INTERWORK);
#endif
applicable = bfd_applicable_section_flags (abfd);
/* First make symbols for the sections. */
for (i = 0; i < NSECS; i++)
{
sinfo *si = secdata + i;
if (si->id != i)
abort ();
si->sec = bfd_make_section_old_way (abfd, si->name);
bfd_set_section_flags (abfd,
si->sec,
si->flags & applicable);
bfd_set_section_alignment(abfd, si->sec, si->align);
si->sec->output_section = si->sec;
si->sym = bfd_make_empty_symbol(abfd);
si->sym->name = si->sec->name;
si->sym->section = si->sec;
si->sym->flags = BSF_LOCAL;
si->sym->value = 0;
ptrs[oidx] = si->sym;
si->sympp = ptrs + oidx;
si->size = 0;
si->data = NULL;
oidx++;
}
if (! exp->data)
{
exp_label = bfd_make_empty_symbol (abfd);
exp_label->name = make_imp_label ("", exp->name);
/* On PowerPC, the function name points to a descriptor in
the rdata section, the first element of which is a
pointer to the code (..function_name), and the second
points to the .toc. */
#ifdef DLLTOOL_PPC
if (machine == MPPC)
exp_label->section = secdata[RDATA].sec;
else
#endif
exp_label->section = secdata[TEXT].sec;
exp_label->flags = BSF_GLOBAL;
exp_label->value = 0;
#ifdef DLLTOOL_ARM
if (machine == MTHUMB)
bfd_coff_set_symbol_class (abfd, exp_label, C_THUMBEXTFUNC);
#endif
ptrs[oidx++] = exp_label;
}
/* Generate imp symbols with one underscore for Microsoft
compatibility, and with two underscores for backward
compatibility with old versions of cygwin. */
if (create_compat_implib)
{
iname = bfd_make_empty_symbol (abfd);
iname->name = make_imp_label ("___imp", exp->name);
iname->section = secdata[IDATA5].sec;
iname->flags = BSF_GLOBAL;
iname->value = 0;
}
iname2 = bfd_make_empty_symbol (abfd);
iname2->name = make_imp_label ("__imp_", exp->name);
iname2->section = secdata[IDATA5].sec;
iname2->flags = BSF_GLOBAL;
iname2->value = 0;
iname_lab = bfd_make_empty_symbol (abfd);
iname_lab->name = head_label;
iname_lab->section = (asection *) &bfd_und_section;
iname_lab->flags = 0;
iname_lab->value = 0;
iname_pp = ptrs + oidx;
if (create_compat_implib)
ptrs[oidx++] = iname;
ptrs[oidx++] = iname2;
iname_lab_pp = ptrs + oidx;
ptrs[oidx++] = iname_lab;
#ifdef DLLTOOL_PPC
/* The symbol referring to the code (.text). */
{
asymbol *function_name;
function_name = bfd_make_empty_symbol(abfd);
function_name->name = make_label ("..", exp->name);
function_name->section = secdata[TEXT].sec;
function_name->flags = BSF_GLOBAL;
function_name->value = 0;
fn_pp = ptrs + oidx;
ptrs[oidx++] = function_name;
}
/* The .toc symbol. */
{
asymbol *toc_symbol;
toc_symbol = bfd_make_empty_symbol (abfd);
toc_symbol->name = make_label (".", "toc");
toc_symbol->section = (asection *)&bfd_und_section;
toc_symbol->flags = BSF_GLOBAL;
toc_symbol->value = 0;
toc_pp = ptrs + oidx;
ptrs[oidx++] = toc_symbol;
}
#endif
ptrs[oidx] = 0;
for (i = 0; i < NSECS; i++)
{
sinfo *si = secdata + i;
asection *sec = si->sec;
arelent *rel, *rel2 = 0, *rel3 = 0;
arelent **rpp;
switch (i)
{
case TEXT:
if (! exp->data)
{
si->size = HOW_JTAB_SIZE;
si->data = xmalloc (HOW_JTAB_SIZE);
memcpy (si->data, HOW_JTAB, HOW_JTAB_SIZE);
/* Add the reloc into idata$5. */
rel = xmalloc (sizeof (arelent));
rpp = xmalloc (sizeof (arelent *) * (delay ? 4 : 2));
rpp[0] = rel;
rpp[1] = 0;
rel->address = HOW_JTAB_ROFF;
rel->addend = 0;
if (delay)
{
rel2 = xmalloc (sizeof (arelent));
rpp[1] = rel2;
rel2->address = HOW_JTAB_ROFF2;
rel2->addend = 0;
rel3 = xmalloc (sizeof (arelent));
rpp[2] = rel3;
rel3->address = HOW_JTAB_ROFF3;
rel3->addend = 0;
rpp[3] = 0;
}
if (machine == MPPC)
{
rel->howto = bfd_reloc_type_lookup (abfd,
BFD_RELOC_16_GOTOFF);
rel->sym_ptr_ptr = iname_pp;
}
else if (machine == MX86)
{
rel->howto = bfd_reloc_type_lookup (abfd,
BFD_RELOC_32_PCREL);
rel->sym_ptr_ptr = iname_pp;
}
else
{
rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
rel->sym_ptr_ptr = secdata[IDATA5].sympp;
}
if (delay)
{
rel2->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
rel2->sym_ptr_ptr = rel->sym_ptr_ptr;
rel3->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32_PCREL);
rel3->sym_ptr_ptr = iname_lab_pp;
}
sec->orelocation = rpp;
sec->reloc_count = delay ? 3 : 1;
}
break;
case IDATA5:
if (delay)
{
si->data = xmalloc (4);
si->size = 4;
sec->reloc_count = 1;
memset (si->data, 0, si->size);
si->data[0] = 6;
rel = xmalloc (sizeof (arelent));
rpp = xmalloc (sizeof (arelent *) * 2);
rpp[0] = rel;
rpp[1] = 0;
rel->address = 0;
rel->addend = 0;
rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
rel->sym_ptr_ptr = secdata[TEXT].sympp;
sec->orelocation = rpp;
break;
}
/* else fall through */
case IDATA4:
/* An idata$4 or idata$5 is one word long, and has an
rva to idata$6. */
if (create_for_pep)
{
si->data = xmalloc (8);
si->size = 8;
if (exp->noname)
{
si->data[0] = exp->ordinal ;
si->data[1] = exp->ordinal >> 8;
si->data[2] = exp->ordinal >> 16;
si->data[3] = exp->ordinal >> 24;
si->data[4] = 0;
si->data[5] = 0;
si->data[6] = 0;
si->data[7] = 0x80;
}
else
{
sec->reloc_count = 1;
memset (si->data, 0, si->size);
rel = xmalloc (sizeof (arelent));
rpp = xmalloc (sizeof (arelent *) * 2);
rpp[0] = rel;
rpp[1] = 0;
rel->address = 0;
rel->addend = 0;
rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_RVA);
rel->sym_ptr_ptr = secdata[IDATA6].sympp;
sec->orelocation = rpp;
}
}
else
{
si->data = xmalloc (4);
si->size = 4;
if (exp->noname)
{
si->data[0] = exp->ordinal ;
si->data[1] = exp->ordinal >> 8;
si->data[2] = exp->ordinal >> 16;
si->data[3] = 0x80;
}
else
{
sec->reloc_count = 1;
memset (si->data, 0, si->size);
rel = xmalloc (sizeof (arelent));
rpp = xmalloc (sizeof (arelent *) * 2);
rpp[0] = rel;
rpp[1] = 0;
rel->address = 0;
rel->addend = 0;
rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_RVA);
rel->sym_ptr_ptr = secdata[IDATA6].sympp;
sec->orelocation = rpp;
}
}
break;
case IDATA6:
if (!exp->noname)
{
/* This used to add 1 to exp->hint. I don't know
why it did that, and it does not match what I see
in programs compiled with the MS tools. */
int idx = exp->hint;
if (exp->its_name)
si->size = strlen (exp->its_name) + 3;
else
si->size = strlen (xlate (exp->import_name)) + 3;
si->data = xmalloc (si->size);
si->data[0] = idx & 0xff;
si->data[1] = idx >> 8;
if (exp->its_name)
strcpy ((char *) si->data + 2, exp->its_name);
else
strcpy ((char *) si->data + 2, xlate (exp->import_name));
}
break;
case IDATA7:
if (delay)
break;
si->size = 4;
si->data = xmalloc (4);
memset (si->data, 0, si->size);
rel = xmalloc (sizeof (arelent));
rpp = xmalloc (sizeof (arelent *) * 2);
rpp[0] = rel;
rel->address = 0;
rel->addend = 0;
rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_RVA);
rel->sym_ptr_ptr = iname_lab_pp;
sec->orelocation = rpp;
sec->reloc_count = 1;
break;
#ifdef DLLTOOL_PPC
case PDATA:
{
/* The .pdata section is 5 words long.
Think of it as:
struct
{
bfd_vma BeginAddress, [0x00]
EndAddress, [0x04]
ExceptionHandler, [0x08]
HandlerData, [0x0c]
PrologEndAddress; [0x10]
}; */
/* So this pdata section setups up this as a glue linkage to
a dll routine. There are a number of house keeping things
we need to do:
1. In the name of glue trickery, the ADDR32 relocs for 0,
4, and 0x10 are set to point to the same place:
"..function_name".
2. There is one more reloc needed in the pdata section.
The actual glue instruction to restore the toc on
return is saved as the offset in an IMGLUE reloc.
So we need a total of four relocs for this section.
3. Lastly, the HandlerData field is set to 0x03, to indicate
that this is a glue routine. */
arelent *imglue, *ba_rel, *ea_rel, *pea_rel;
/* Alignment must be set to 2**2 or you get extra stuff. */
bfd_set_section_alignment(abfd, sec, 2);
si->size = 4 * 5;
si->data = xmalloc (si->size);
memset (si->data, 0, si->size);
rpp = xmalloc (sizeof (arelent *) * 5);
rpp[0] = imglue = xmalloc (sizeof (arelent));
rpp[1] = ba_rel = xmalloc (sizeof (arelent));
rpp[2] = ea_rel = xmalloc (sizeof (arelent));
rpp[3] = pea_rel = xmalloc (sizeof (arelent));
rpp[4] = 0;
/* Stick the toc reload instruction in the glue reloc. */
bfd_put_32(abfd, ppc_glue_insn, (char *) &imglue->address);
imglue->addend = 0;
imglue->howto = bfd_reloc_type_lookup (abfd,
BFD_RELOC_32_GOTOFF);
imglue->sym_ptr_ptr = fn_pp;
ba_rel->address = 0;
ba_rel->addend = 0;
ba_rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
ba_rel->sym_ptr_ptr = fn_pp;
bfd_put_32 (abfd, 0x18, si->data + 0x04);
ea_rel->address = 4;
ea_rel->addend = 0;
ea_rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
ea_rel->sym_ptr_ptr = fn_pp;
/* Mark it as glue. */
bfd_put_32 (abfd, 0x03, si->data + 0x0c);
/* Mark the prolog end address. */
bfd_put_32 (abfd, 0x0D, si->data + 0x10);
pea_rel->address = 0x10;
pea_rel->addend = 0;
pea_rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
pea_rel->sym_ptr_ptr = fn_pp;
sec->orelocation = rpp;
sec->reloc_count = 4;
break;
}
case RDATA:
/* Each external function in a PowerPC PE file has a two word
descriptor consisting of:
1. The address of the code.
2. The address of the appropriate .toc
We use relocs to build this. */
si->size = 8;
si->data = xmalloc (8);
memset (si->data, 0, si->size);
rpp = xmalloc (sizeof (arelent *) * 3);
rpp[0] = rel = xmalloc (sizeof (arelent));
rpp[1] = xmalloc (sizeof (arelent));
rpp[2] = 0;
rel->address = 0;
rel->addend = 0;
rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
rel->sym_ptr_ptr = fn_pp;
rel = rpp[1];
rel->address = 4;
rel->addend = 0;
rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
rel->sym_ptr_ptr = toc_pp;
sec->orelocation = rpp;
sec->reloc_count = 2;
break;
#endif /* DLLTOOL_PPC */
}
}
{
bfd_vma vma = 0;
/* Size up all the sections. */
for (i = 0; i < NSECS; i++)
{
sinfo *si = secdata + i;
bfd_set_section_size (abfd, si->sec, si->size);
bfd_set_section_vma (abfd, si->sec, vma);
}
}
/* Write them out. */
for (i = 0; i < NSECS; i++)
{
sinfo *si = secdata + i;
if (i == IDATA5 && no_idata5)
continue;
if (i == IDATA4 && no_idata4)
continue;
bfd_set_section_contents (abfd, si->sec,
si->data, 0,
si->size);
}
bfd_set_symtab (abfd, ptrs, oidx);
bfd_close (abfd);
abfd = bfd_openr (outname, HOW_BFD_READ_TARGET);
if (!abfd)
/* xgettext:c-format */
fatal (_("bfd_open failed reopen stub file: %s: %s"),
outname, bfd_get_errmsg ());
return abfd;
}
static bfd *
make_head (void)
{
FILE *f = fopen (TMP_HEAD_S, FOPEN_WT);
bfd *abfd;
if (f == NULL)
{
fatal (_("failed to open temporary head file: %s"), TMP_HEAD_S);
return NULL;
}
fprintf (f, "%s IMAGE_IMPORT_DESCRIPTOR\n", ASM_C);
fprintf (f, "\t.section\t.idata$2\n");
fprintf (f,"\t%s\t%s\n", ASM_GLOBAL, head_label);
fprintf (f, "%s:\n", head_label);
fprintf (f, "\t%shname%s\t%sPtr to image import by name list\n",
ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
fprintf (f, "\t%sthis should be the timestamp, but NT sometimes\n", ASM_C);
fprintf (f, "\t%sdoesn't load DLLs when this is set.\n", ASM_C);
fprintf (f, "\t%s\t0\t%s loaded time\n", ASM_LONG, ASM_C);
fprintf (f, "\t%s\t0\t%s Forwarder chain\n", ASM_LONG, ASM_C);
fprintf (f, "\t%s__%s_iname%s\t%s imported dll's name\n",
ASM_RVA_BEFORE,
imp_name_lab,
ASM_RVA_AFTER,
ASM_C);
fprintf (f, "\t%sfthunk%s\t%s pointer to firstthunk\n",
ASM_RVA_BEFORE,
ASM_RVA_AFTER, ASM_C);
fprintf (f, "%sStuff for compatibility\n", ASM_C);
if (!no_idata5)
{
fprintf (f, "\t.section\t.idata$5\n");
if (use_nul_prefixed_import_tables)
{
if (create_for_pep)
fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
else
fprintf (f,"\t%s\t0\n", ASM_LONG);
}
fprintf (f, "fthunk:\n");
}
if (!no_idata4)
{
fprintf (f, "\t.section\t.idata$4\n");
if (use_nul_prefixed_import_tables)
{
if (create_for_pep)
fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
else
fprintf (f,"\t%s\t0\n", ASM_LONG);
}
fprintf (f, "hname:\n");
}
fclose (f);
assemble_file (TMP_HEAD_S, TMP_HEAD_O);
abfd = bfd_openr (TMP_HEAD_O, HOW_BFD_READ_TARGET);
if (abfd == NULL)
/* xgettext:c-format */
fatal (_("failed to open temporary head file: %s: %s"),
TMP_HEAD_O, bfd_get_errmsg ());
return abfd;
}
bfd *
make_delay_head (void)
{
FILE *f = fopen (TMP_HEAD_S, FOPEN_WT);
bfd *abfd;
if (f == NULL)
{
fatal (_("failed to open temporary head file: %s"), TMP_HEAD_S);
return NULL;
}
/* Output the __tailMerge__xxx function */
fprintf (f, "%s Import trampoline\n", ASM_C);
fprintf (f, "\t.section\t.text\n");
fprintf(f,"\t%s\t%s\n", ASM_GLOBAL, head_label);
fprintf (f, "%s:\n", head_label);
fprintf (f, mtable[machine].trampoline, imp_name_lab);
/* Output the delay import descriptor */
fprintf (f, "\n%s DELAY_IMPORT_DESCRIPTOR\n", ASM_C);
fprintf (f, ".section\t.text$2\n");
fprintf (f,"%s __DELAY_IMPORT_DESCRIPTOR_%s\n", ASM_GLOBAL,imp_name_lab);
fprintf (f, "__DELAY_IMPORT_DESCRIPTOR_%s:\n", imp_name_lab);
fprintf (f, "\t%s 1\t%s grAttrs\n", ASM_LONG, ASM_C);
fprintf (f, "\t%s__%s_iname%s\t%s rvaDLLName\n",
ASM_RVA_BEFORE, imp_name_lab, ASM_RVA_AFTER, ASM_C);
fprintf (f, "\t%s__DLL_HANDLE_%s%s\t%s rvaHmod\n",
ASM_RVA_BEFORE, imp_name_lab, ASM_RVA_AFTER, ASM_C);
fprintf (f, "\t%s__IAT_%s%s\t%s rvaIAT\n",
ASM_RVA_BEFORE, imp_name_lab, ASM_RVA_AFTER, ASM_C);
fprintf (f, "\t%s__INT_%s%s\t%s rvaINT\n",
ASM_RVA_BEFORE, imp_name_lab, ASM_RVA_AFTER, ASM_C);
fprintf (f, "\t%s\t0\t%s rvaBoundIAT\n", ASM_LONG, ASM_C);
fprintf (f, "\t%s\t0\t%s rvaUnloadIAT\n", ASM_LONG, ASM_C);
fprintf (f, "\t%s\t0\t%s dwTimeStamp\n", ASM_LONG, ASM_C);
/* Output the dll_handle */
fprintf (f, "\n.section .data\n");
fprintf (f, "__DLL_HANDLE_%s:\n", imp_name_lab);
fprintf (f, "\t%s\t0\t%s Handle\n", ASM_LONG, ASM_C);
fprintf (f, "\n");
fprintf (f, "%sStuff for compatibility\n", ASM_C);
if (!no_idata5)
{
fprintf (f, "\t.section\t.idata$5\n");
/* NULL terminating list. */
#ifdef DLLTOOL_MX86_64
fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
#else
fprintf (f,"\t%s\t0\n", ASM_LONG);
#endif
fprintf (f, "__IAT_%s:\n", imp_name_lab);
}
if (!no_idata4)
{
fprintf (f, "\t.section\t.idata$4\n");
fprintf (f, "\t%s\t0\n", ASM_LONG);
fprintf (f, "\t.section\t.idata$4\n");
fprintf (f, "__INT_%s:\n", imp_name_lab);
}
fprintf (f, "\t.section\t.idata$2\n");
fclose (f);
assemble_file (TMP_HEAD_S, TMP_HEAD_O);
abfd = bfd_openr (TMP_HEAD_O, HOW_BFD_READ_TARGET);
if (abfd == NULL)
/* xgettext:c-format */
fatal (_("failed to open temporary head file: %s: %s"),
TMP_HEAD_O, bfd_get_errmsg ());
return abfd;
}
static bfd *
make_tail (void)
{
FILE *f = fopen (TMP_TAIL_S, FOPEN_WT);
bfd *abfd;
if (f == NULL)
{
fatal (_("failed to open temporary tail file: %s"), TMP_TAIL_S);
return NULL;
}
if (!no_idata4)
{
fprintf (f, "\t.section\t.idata$4\n");
if (create_for_pep)
fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
else
fprintf (f,"\t%s\t0\n", ASM_LONG); /* NULL terminating list. */
}
if (!no_idata5)
{
fprintf (f, "\t.section\t.idata$5\n");
if (create_for_pep)
fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
else
fprintf (f,"\t%s\t0\n", ASM_LONG); /* NULL terminating list. */
}
#ifdef DLLTOOL_PPC
/* Normally, we need to see a null descriptor built in idata$3 to
act as the terminator for the list. The ideal way, I suppose,
would be to mark this section as a comdat type 2 section, so
only one would appear in the final .exe (if our linker supported
comdat, that is) or cause it to be inserted by something else (say
crt0). */
fprintf (f, "\t.section\t.idata$3\n");
fprintf (f, "\t%s\t0\n", ASM_LONG);
fprintf (f, "\t%s\t0\n", ASM_LONG);
fprintf (f, "\t%s\t0\n", ASM_LONG);
fprintf (f, "\t%s\t0\n", ASM_LONG);
fprintf (f, "\t%s\t0\n", ASM_LONG);
#endif
#ifdef DLLTOOL_PPC
/* Other PowerPC NT compilers use idata$6 for the dllname, so I
do too. Original, huh? */
fprintf (f, "\t.section\t.idata$6\n");
#else
fprintf (f, "\t.section\t.idata$7\n");
#endif
fprintf (f, "\t%s\t__%s_iname\n", ASM_GLOBAL, imp_name_lab);
fprintf (f, "__%s_iname:\t%s\t\"%s\"\n",
imp_name_lab, ASM_TEXT, dll_name);
fclose (f);
assemble_file (TMP_TAIL_S, TMP_TAIL_O);
abfd = bfd_openr (TMP_TAIL_O, HOW_BFD_READ_TARGET);
if (abfd == NULL)
/* xgettext:c-format */
fatal (_("failed to open temporary tail file: %s: %s"),
TMP_TAIL_O, bfd_get_errmsg ());
return abfd;
}
static void
gen_lib_file (int delay)
{
int i;
export_type *exp;
bfd *ar_head;
bfd *ar_tail;
bfd *outarch;
bfd * head = 0;
unlink (imp_name);
outarch = bfd_openw (imp_name, HOW_BFD_WRITE_TARGET);
if (!outarch)
/* xgettext:c-format */
fatal (_("Can't create .lib file: %s: %s"),
imp_name, bfd_get_errmsg ());
/* xgettext:c-format */
inform (_("Creating library file: %s"), imp_name);
bfd_set_format (outarch, bfd_archive);
outarch->has_armap = 1;
outarch->is_thin_archive = 0;
/* Work out a reasonable size of things to put onto one line. */
if (delay)
{
ar_head = make_delay_head ();
}
else
{
ar_head = make_head ();
}
ar_tail = make_tail();
if (ar_head == NULL || ar_tail == NULL)
return;
for (i = 0; (exp = d_exports_lexically[i]); i++)
{
bfd *n;
/* Don't add PRIVATE entries to import lib. */
if (exp->private)
continue;
n = make_one_lib_file (exp, i, delay);
n->archive_next = head;
head = n;
if (ext_prefix_alias)
{
export_type alias_exp;
assert (i < PREFIX_ALIAS_BASE);
alias_exp.name = make_imp_label (ext_prefix_alias, exp->name);
alias_exp.internal_name = exp->internal_name;
alias_exp.its_name = exp->its_name;
alias_exp.import_name = exp->name;
alias_exp.ordinal = exp->ordinal;
alias_exp.constant = exp->constant;
alias_exp.noname = exp->noname;
alias_exp.private = exp->private;
alias_exp.data = exp->data;
alias_exp.hint = exp->hint;
alias_exp.forward = exp->forward;
alias_exp.next = exp->next;
n = make_one_lib_file (&alias_exp, i + PREFIX_ALIAS_BASE, delay);
n->archive_next = head;
head = n;
}
}
/* Now stick them all into the archive. */
ar_head->archive_next = head;
ar_tail->archive_next = ar_head;
head = ar_tail;
if (! bfd_set_archive_head (outarch, head))
bfd_fatal ("bfd_set_archive_head");
if (! bfd_close (outarch))
bfd_fatal (imp_name);
while (head != NULL)
{
bfd *n = head->archive_next;
bfd_close (head);
head = n;
}
/* Delete all the temp files. */
if (dontdeltemps == 0)
{
unlink (TMP_HEAD_O);
unlink (TMP_HEAD_S);
unlink (TMP_TAIL_O);
unlink (TMP_TAIL_S);
}
if (dontdeltemps < 2)
{
char *name;
name = (char *) alloca (strlen (TMP_STUB) + 10);
for (i = 0; (exp = d_exports_lexically[i]); i++)
{
/* Don't delete non-existent stubs for PRIVATE entries. */
if (exp->private)
continue;
sprintf (name, "%s%05d.o", TMP_STUB, i);
if (unlink (name) < 0)
/* xgettext:c-format */
non_fatal (_("cannot delete %s: %s"), name, strerror (errno));
if (ext_prefix_alias)
{
sprintf (name, "%s%05d.o", TMP_STUB, i + PREFIX_ALIAS_BASE);
if (unlink (name) < 0)
/* xgettext:c-format */
non_fatal (_("cannot delete %s: %s"), name, strerror (errno));
}
}
}
inform (_("Created lib file"));
}
/* Append a copy of data (cast to char *) to list. */
static void
dll_name_list_append (dll_name_list_type * list, bfd_byte * data)
{
dll_name_list_node_type * entry;
/* Error checking. */
if (! list || ! list->tail)
return;
/* Allocate new node. */
entry = ((dll_name_list_node_type *)
xmalloc (sizeof (dll_name_list_node_type)));
/* Initialize its values. */
entry->dllname = xstrdup ((char *) data);
entry->next = NULL;
/* Add to tail, and move tail. */
list->tail->next = entry;
list->tail = entry;
}
/* Count the number of entries in list. */
static int
dll_name_list_count (dll_name_list_type * list)
{
dll_name_list_node_type * p;
int count = 0;
/* Error checking. */
if (! list || ! list->head)
return 0;
p = list->head;
while (p && p->next)
{
count++;
p = p->next;
}
return count;
}
/* Print each entry in list to stdout. */
static void
dll_name_list_print (dll_name_list_type * list)
{
dll_name_list_node_type * p;
/* Error checking. */
if (! list || ! list->head)
return;
p = list->head;
while (p && p->next && p->next->dllname && *(p->next->dllname))
{
printf ("%s\n", p->next->dllname);
p = p->next;
}
}
/* Free all entries in list, and list itself. */
static void
dll_name_list_free (dll_name_list_type * list)
{
if (list)
{
dll_name_list_free_contents (list->head);
list->head = NULL;
list->tail = NULL;
free (list);
}
}
/* Recursive function to free all nodes entry->next->next...
as well as entry itself. */
static void
dll_name_list_free_contents (dll_name_list_node_type * entry)
{
if (entry)
{
if (entry->next)
{
dll_name_list_free_contents (entry->next);
entry->next = NULL;
}
if (entry->dllname)
{
free (entry->dllname);
entry->dllname = NULL;
}
free (entry);
}
}
/* Allocate and initialize a dll_name_list_type object,
including its sentinel node. Caller is responsible
for calling dll_name_list_free when finished with
the list. */
static dll_name_list_type *
dll_name_list_create (void)
{
/* Allocate list. */
dll_name_list_type * list = xmalloc (sizeof (dll_name_list_type));
/* Allocate and initialize sentinel node. */
list->head = xmalloc (sizeof (dll_name_list_node_type));
list->head->dllname = NULL;
list->head->next = NULL;
/* Bookkeeping for empty list. */
list->tail = list->head;
return list;
}
/* Search the symbol table of the suppled BFD for a symbol whose name matches
OBJ (where obj is cast to const char *). If found, set global variable
identify_member_contains_symname_result TRUE. It is the caller's
responsibility to set the result variable FALSE before iterating with
this function. */
static void
identify_member_contains_symname (bfd * abfd,
bfd * archive_bfd ATTRIBUTE_UNUSED,
void * obj)
{
long storage_needed;
asymbol ** symbol_table;
long number_of_symbols;
long i;
symname_search_data_type * search_data = (symname_search_data_type *) obj;
/* If we already found the symbol in a different member,
short circuit. */
if (search_data->found)
return;
storage_needed = bfd_get_symtab_upper_bound (abfd);
if (storage_needed <= 0)
return;
symbol_table = xmalloc (storage_needed);
number_of_symbols = bfd_canonicalize_symtab (abfd, symbol_table);
if (number_of_symbols < 0)
{
free (symbol_table);
return;
}
for (i = 0; i < number_of_symbols; i++)
{
if (strncmp (symbol_table[i]->name,
search_data->symname,
strlen (search_data->symname)) == 0)
{
search_data->found = TRUE;
break;
}
}
free (symbol_table);
}
/* This is the main implementation for the --identify option.
Given the name of an import library in identify_imp_name, first determine
if the import library is a GNU binutils-style one (where the DLL name is
stored in an .idata$7 (.idata$6 on PPC) section, or if it is a MS-style
one (where the DLL name, along with much other data, is stored in the
.idata$6 section). We determine the style of import library by searching
for the DLL-structure symbol inserted by MS tools:
__NULL_IMPORT_DESCRIPTOR.
Once we know which section to search, evaluate each section for the
appropriate properties that indicate it may contain the name of the
associated DLL (this differs depending on the style). Add the contents
of all sections which meet the criteria to a linked list of dll names.
Finally, print them all to stdout. (If --identify-strict, an error is
reported if more than one match was found). */
static void
identify_dll_for_implib (void)
{
bfd * abfd = NULL;
int count = 0;
identify_data_type identify_data;
symname_search_data_type search_data;
/* Initialize identify_data. */
identify_data.list = dll_name_list_create ();
identify_data.ms_style_implib = FALSE;
/* Initialize search_data. */
search_data.symname = "__NULL_IMPORT_DESCRIPTOR";
search_data.found = FALSE;
bfd_init ();
abfd = bfd_openr (identify_imp_name, 0);
if (abfd == NULL)
/* xgettext:c-format */
fatal (_("Can't open .lib file: %s: %s"),
identify_imp_name, bfd_get_errmsg ());
if (! bfd_check_format (abfd, bfd_archive))
{
if (! bfd_close (abfd))
bfd_fatal (identify_imp_name);
fatal (_("%s is not a library"), identify_imp_name);
}
/* Detect if this a Microsoft import library. */
identify_search_archive (abfd,
identify_member_contains_symname,
(void *)(& search_data));
if (search_data.found)
identify_data.ms_style_implib = TRUE;
/* Rewind the bfd. */
if (! bfd_close (abfd))
bfd_fatal (identify_imp_name);
abfd = bfd_openr (identify_imp_name, 0);
if (abfd == NULL)
bfd_fatal (identify_imp_name);
if (!bfd_check_format (abfd, bfd_archive))
{
if (!bfd_close (abfd))
bfd_fatal (identify_imp_name);
fatal (_("%s is not a library"), identify_imp_name);
}
/* Now search for the dll name. */
identify_search_archive (abfd,
identify_search_member,
(void *)(& identify_data));
if (! bfd_close (abfd))
bfd_fatal (identify_imp_name);
count = dll_name_list_count (identify_data.list);
if (count > 0)
{
if (identify_strict && count > 1)
{
dll_name_list_free (identify_data.list);
identify_data.list = NULL;
fatal (_("Import library `%s' specifies two or more dlls"),
identify_imp_name);
}
dll_name_list_print (identify_data.list);
dll_name_list_free (identify_data.list);
identify_data.list = NULL;
}
else
{
dll_name_list_free (identify_data.list);
identify_data.list = NULL;
fatal (_("Unable to determine dll name for `%s' (not an import library?)"),
identify_imp_name);
}
}
/* Loop over all members of the archive, applying the supplied function to
each member that is a bfd_object. The function will be called as if:
func (member_bfd, abfd, user_storage) */
static void
identify_search_archive (bfd * abfd,
void (* operation) (bfd *, bfd *, void *),
void * user_storage)
{
bfd * arfile = NULL;
bfd * last_arfile = NULL;
char ** matching;
while (1)
{
arfile = bfd_openr_next_archived_file (abfd, arfile);
if (arfile == NULL)
{
if (bfd_get_error () != bfd_error_no_more_archived_files)
bfd_fatal (bfd_get_filename (abfd));
break;
}
if (bfd_check_format_matches (arfile, bfd_object, &matching))
(*operation) (arfile, abfd, user_storage);
else
{
bfd_nonfatal (bfd_get_filename (arfile));
free (matching);
}
if (last_arfile != NULL)
bfd_close (last_arfile);
last_arfile = arfile;
}
if (last_arfile != NULL)
{
bfd_close (last_arfile);
}
}
/* Call the identify_search_section() function for each section of this
archive member. */
static void
identify_search_member (bfd *abfd,
bfd *archive_bfd ATTRIBUTE_UNUSED,
void *obj)
{
bfd_map_over_sections (abfd, identify_search_section, obj);
}
/* This predicate returns true if section->name matches the desired value.
By default, this is .idata$7 (.idata$6 on PPC, or if the import
library is ms-style). */
static bfd_boolean
identify_process_section_p (asection * section, bfd_boolean ms_style_implib)
{
static const char * SECTION_NAME =
#ifdef DLLTOOL_PPC
/* dllname is stored in idata$6 on PPC */
".idata$6";
#else
".idata$7";
#endif
static const char * MS_SECTION_NAME = ".idata$6";
const char * section_name =
(ms_style_implib ? MS_SECTION_NAME : SECTION_NAME);
if (strcmp (section_name, section->name) == 0)
return TRUE;
return FALSE;
}
/* If *section has contents and its name is .idata$7 (.data$6 on PPC or if
import lib ms-generated) -- and it satisfies several other constraints
-- then add the contents of the section to obj->list. */
static void
identify_search_section (bfd * abfd, asection * section, void * obj)
{
bfd_byte *data = 0;
bfd_size_type datasize;
identify_data_type * identify_data = (identify_data_type *)obj;
bfd_boolean ms_style = identify_data->ms_style_implib;
if ((section->flags & SEC_HAS_CONTENTS) == 0)
return;
if (! identify_process_section_p (section, ms_style))
return;
/* Binutils import libs seem distinguish the .idata$7 section that contains
the DLL name from other .idata$7 sections by the absence of the
SEC_RELOC flag. */
if (!ms_style && ((section->flags & SEC_RELOC) == SEC_RELOC))
return;
/* MS import libs seem to distinguish the .idata$6 section
that contains the DLL name from other .idata$6 sections
by the presence of the SEC_DATA flag. */
if (ms_style && ((section->flags & SEC_DATA) == 0))
return;
if ((datasize = bfd_section_size (abfd, section)) == 0)
return;
data = (bfd_byte *) xmalloc (datasize + 1);
data[0] = '\0';
bfd_get_section_contents (abfd, section, data, 0, datasize);
data[datasize] = '\0';
/* Use a heuristic to determine if data is a dll name.
Possible to defeat this if (a) the library has MANY
(more than 0x302f) imports, (b) it is an ms-style
import library, but (c) it is buggy, in that the SEC_DATA
flag is set on the "wrong" sections. This heuristic might
also fail to record a valid dll name if the dllname uses
a multibyte or unicode character set (is that valid?).
This heuristic is based on the fact that symbols names in
the chosen section -- as opposed to the dll name -- begin
at offset 2 in the data. The first two bytes are a 16bit
little-endian count, and start at 0x0000. However, the dll
name begins at offset 0 in the data. We assume that the
dll name does not contain unprintable characters. */
if (data[0] != '\0' && ISPRINT (data[0])
&& ((datasize < 2) || ISPRINT (data[1])))
dll_name_list_append (identify_data->list, data);
free (data);
}
/* Run through the information gathered from the .o files and the
.def file and work out the best stuff. */
static int
pfunc (const void *a, const void *b)
{
export_type *ap = *(export_type **) a;
export_type *bp = *(export_type **) b;
if (ap->ordinal == bp->ordinal)
return 0;
/* Unset ordinals go to the bottom. */
if (ap->ordinal == -1)
return 1;
if (bp->ordinal == -1)
return -1;
return (ap->ordinal - bp->ordinal);
}
static int
nfunc (const void *a, const void *b)
{
export_type *ap = *(export_type **) a;
export_type *bp = *(export_type **) b;
const char *an = ap->name;
const char *bn = bp->name;
if (ap->its_name)
an = ap->its_name;
if (bp->its_name)
an = bp->its_name;
if (killat)
{
an = (an[0] == '@') ? an + 1 : an;
bn = (bn[0] == '@') ? bn + 1 : bn;
}
return (strcmp (an, bn));
}
static void
remove_null_names (export_type **ptr)
{
int src;
int dst;
for (dst = src = 0; src < d_nfuncs; src++)
{
if (ptr[src])
{
ptr[dst] = ptr[src];
dst++;
}
}
d_nfuncs = dst;
}
static void
process_duplicates (export_type **d_export_vec)
{
int more = 1;
int i;
while (more)
{
more = 0;
/* Remove duplicates. */
qsort (d_export_vec, d_nfuncs, sizeof (export_type *), nfunc);
for (i = 0; i < d_nfuncs - 1; i++)
{
if (strcmp (d_export_vec[i]->name,
d_export_vec[i + 1]->name) == 0)
{
export_type *a = d_export_vec[i];
export_type *b = d_export_vec[i + 1];
more = 1;
/* xgettext:c-format */
inform (_("Warning, ignoring duplicate EXPORT %s %d,%d"),
a->name, a->ordinal, b->ordinal);
if (a->ordinal != -1
&& b->ordinal != -1)
/* xgettext:c-format */
fatal (_("Error, duplicate EXPORT with ordinals: %s"),
a->name);
/* Merge attributes. */
b->ordinal = a->ordinal > 0 ? a->ordinal : b->ordinal;
b->constant |= a->constant;
b->noname |= a->noname;
b->data |= a->data;
d_export_vec[i] = 0;
}
remove_null_names (d_export_vec);
}
}
/* Count the names. */
for (i = 0; i < d_nfuncs; i++)
if (!d_export_vec[i]->noname)
d_named_nfuncs++;
}
static void
fill_ordinals (export_type **d_export_vec)
{
int lowest = -1;
int i;
char *ptr;
int size = 65536;
qsort (d_export_vec, d_nfuncs, sizeof (export_type *), pfunc);
/* Fill in the unset ordinals with ones from our range. */
ptr = (char *) xmalloc (size);
memset (ptr, 0, size);
/* Mark in our large vector all the numbers that are taken. */
for (i = 0; i < d_nfuncs; i++)
{
if (d_export_vec[i]->ordinal != -1)
{
ptr[d_export_vec[i]->ordinal] = 1;
if (lowest == -1 || d_export_vec[i]->ordinal < lowest)
lowest = d_export_vec[i]->ordinal;
}
}
/* Start at 1 for compatibility with MS toolchain. */
if (lowest == -1)
lowest = 1;
/* Now fill in ordinals where the user wants us to choose. */
for (i = 0; i < d_nfuncs; i++)
{
if (d_export_vec[i]->ordinal == -1)
{
int j;
/* First try within or after any user supplied range. */
for (j = lowest; j < size; j++)
if (ptr[j] == 0)
{
ptr[j] = 1;
d_export_vec[i]->ordinal = j;
goto done;
}
/* Then try before the range. */
for (j = lowest; j >0; j--)
if (ptr[j] == 0)
{
ptr[j] = 1;
d_export_vec[i]->ordinal = j;
goto done;
}
done:;
}
}
free (ptr);
/* And resort. */
qsort (d_export_vec, d_nfuncs, sizeof (export_type *), pfunc);
/* Work out the lowest and highest ordinal numbers. */
if (d_nfuncs)
{
if (d_export_vec[0])
d_low_ord = d_export_vec[0]->ordinal;
if (d_export_vec[d_nfuncs-1])
d_high_ord = d_export_vec[d_nfuncs-1]->ordinal;
}
}
static void
mangle_defs (void)
{
/* First work out the minimum ordinal chosen. */
export_type *exp;
int i;
int hint = 0;
export_type **d_export_vec = xmalloc (sizeof (export_type *) * d_nfuncs);
inform (_("Processing definitions"));
for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
d_export_vec[i] = exp;
process_duplicates (d_export_vec);
fill_ordinals (d_export_vec);
/* Put back the list in the new order. */
d_exports = 0;
for (i = d_nfuncs - 1; i >= 0; i--)
{
d_export_vec[i]->next = d_exports;
d_exports = d_export_vec[i];
}
/* Build list in alpha order. */
d_exports_lexically = (export_type **)
xmalloc (sizeof (export_type *) * (d_nfuncs + 1));
for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
d_exports_lexically[i] = exp;
d_exports_lexically[i] = 0;
qsort (d_exports_lexically, i, sizeof (export_type *), nfunc);
/* Fill exp entries with their hint values. */
for (i = 0; i < d_nfuncs; i++)
if (!d_exports_lexically[i]->noname || show_allnames)
d_exports_lexically[i]->hint = hint++;
inform (_("Processed definitions"));
}
static void
usage (FILE *file, int status)
{
/* xgetext:c-format */
fprintf (file, _("Usage %s <option(s)> <object-file(s)>\n"), program_name);
/* xgetext:c-format */
fprintf (file, _(" -m --machine <machine> Create as DLL for <machine>. [default: %s]\n"), mname);
fprintf (file, _(" possible <machine>: arm[_interwork], i386, mcore[-elf]{-le|-be}, ppc, thumb\n"));
fprintf (file, _(" -e --output-exp <outname> Generate an export file.\n"));
fprintf (file, _(" -l --output-lib <outname> Generate an interface library.\n"));
fprintf (file, _(" -y --output-delaylib <outname> Create a delay-import library.\n"));
fprintf (file, _(" -a --add-indirect Add dll indirects to export file.\n"));
fprintf (file, _(" -D --dllname <name> Name of input dll to put into interface lib.\n"));
fprintf (file, _(" -d --input-def <deffile> Name of .def file to be read in.\n"));
fprintf (file, _(" -z --output-def <deffile> Name of .def file to be created.\n"));
fprintf (file, _(" --export-all-symbols Export all symbols to .def\n"));
fprintf (file, _(" --no-export-all-symbols Only export listed symbols\n"));
fprintf (file, _(" --exclude-symbols <list> Don't export <list>\n"));
fprintf (file, _(" --no-default-excludes Clear default exclude symbols\n"));
fprintf (file, _(" -b --base-file <basefile> Read linker generated base file.\n"));
fprintf (file, _(" -x --no-idata4 Don't generate idata$4 section.\n"));
fprintf (file, _(" -c --no-idata5 Don't generate idata$5 section.\n"));
fprintf (file, _(" --use-nul-prefixed-import-tables Use zero prefixed idata$4 and idata$5.\n"));
fprintf (file, _(" -U --add-underscore Add underscores to all symbols in interface library.\n"));
fprintf (file, _(" --add-stdcall-underscore Add underscores to stdcall symbols in interface library.\n"));
fprintf (file, _(" --no-leading-underscore All symbols shouldn't be prefixed by an underscore.\n"));
fprintf (file, _(" --leading-underscore All symbols should be prefixed by an underscore.\n"));
fprintf (file, _(" -k --kill-at Kill @<n> from exported names.\n"));
fprintf (file, _(" -A --add-stdcall-alias Add aliases without @<n>.\n"));
fprintf (file, _(" -p --ext-prefix-alias <prefix> Add aliases with <prefix>.\n"));
fprintf (file, _(" -S --as <name> Use <name> for assembler.\n"));
fprintf (file, _(" -f --as-flags <flags> Pass <flags> to the assembler.\n"));
fprintf (file, _(" -C --compat-implib Create backward compatible import library.\n"));
fprintf (file, _(" -n --no-delete Keep temp files (repeat for extra preservation).\n"));
fprintf (file, _(" -t --temp-prefix <prefix> Use <prefix> to construct temp file names.\n"));
fprintf (file, _(" -I --identify <implib> Report the name of the DLL associated with <implib>.\n"));
fprintf (file, _(" --identify-strict Causes --identify to report error when multiple DLLs.\n"));
fprintf (file, _(" -v --verbose Be verbose.\n"));
fprintf (file, _(" -V --version Display the program version.\n"));
fprintf (file, _(" -h --help Display this information.\n"));
fprintf (file, _(" @<file> Read options from <file>.\n"));
#ifdef DLLTOOL_MCORE_ELF
fprintf (file, _(" -M --mcore-elf <outname> Process mcore-elf object files into <outname>.\n"));
fprintf (file, _(" -L --linker <name> Use <name> as the linker.\n"));
fprintf (file, _(" -F --linker-flags <flags> Pass <flags> to the linker.\n"));
#endif
if (REPORT_BUGS_TO[0] && status == 0)
fprintf (file, _("Report bugs to %s\n"), REPORT_BUGS_TO);
exit (status);
}
#define OPTION_EXPORT_ALL_SYMS 150
#define OPTION_NO_EXPORT_ALL_SYMS (OPTION_EXPORT_ALL_SYMS + 1)
#define OPTION_EXCLUDE_SYMS (OPTION_NO_EXPORT_ALL_SYMS + 1)
#define OPTION_NO_DEFAULT_EXCLUDES (OPTION_EXCLUDE_SYMS + 1)
#define OPTION_ADD_STDCALL_UNDERSCORE (OPTION_NO_DEFAULT_EXCLUDES + 1)
#define OPTION_USE_NUL_PREFIXED_IMPORT_TABLES \
(OPTION_ADD_STDCALL_UNDERSCORE + 1)
#define OPTION_IDENTIFY_STRICT (OPTION_USE_NUL_PREFIXED_IMPORT_TABLES + 1)
#define OPTION_NO_LEADING_UNDERSCORE (OPTION_IDENTIFY_STRICT + 1)
#define OPTION_LEADING_UNDERSCORE (OPTION_NO_LEADING_UNDERSCORE + 1)
static const struct option long_options[] =
{
{"no-delete", no_argument, NULL, 'n'},
{"dllname", required_argument, NULL, 'D'},
{"no-idata4", no_argument, NULL, 'x'},
{"no-idata5", no_argument, NULL, 'c'},
{"use-nul-prefixed-import-tables", no_argument, NULL,
OPTION_USE_NUL_PREFIXED_IMPORT_TABLES},
{"output-exp", required_argument, NULL, 'e'},
{"output-def", required_argument, NULL, 'z'},
{"export-all-symbols", no_argument, NULL, OPTION_EXPORT_ALL_SYMS},
{"no-export-all-symbols", no_argument, NULL, OPTION_NO_EXPORT_ALL_SYMS},
{"exclude-symbols", required_argument, NULL, OPTION_EXCLUDE_SYMS},
{"no-default-excludes", no_argument, NULL, OPTION_NO_DEFAULT_EXCLUDES},
{"output-lib", required_argument, NULL, 'l'},
{"def", required_argument, NULL, 'd'}, /* for compatibility with older versions */
{"input-def", required_argument, NULL, 'd'},
{"add-underscore", no_argument, NULL, 'U'},
{"add-stdcall-underscore", no_argument, NULL, OPTION_ADD_STDCALL_UNDERSCORE},
{"no-leading-underscore", no_argument, NULL, OPTION_NO_LEADING_UNDERSCORE},
{"leading-underscore", no_argument, NULL, OPTION_LEADING_UNDERSCORE},
{"kill-at", no_argument, NULL, 'k'},
{"add-stdcall-alias", no_argument, NULL, 'A'},
{"ext-prefix-alias", required_argument, NULL, 'p'},
{"identify", required_argument, NULL, 'I'},
{"identify-strict", no_argument, NULL, OPTION_IDENTIFY_STRICT},
{"verbose", no_argument, NULL, 'v'},
{"version", no_argument, NULL, 'V'},
{"help", no_argument, NULL, 'h'},
{"machine", required_argument, NULL, 'm'},
{"add-indirect", no_argument, NULL, 'a'},
{"base-file", required_argument, NULL, 'b'},
{"as", required_argument, NULL, 'S'},
{"as-flags", required_argument, NULL, 'f'},
{"mcore-elf", required_argument, NULL, 'M'},
{"compat-implib", no_argument, NULL, 'C'},
{"temp-prefix", required_argument, NULL, 't'},
{"output-delaylib", required_argument, NULL, 'y'},
{NULL,0,NULL,0}
};
int main (int, char **);
int
main (int ac, char **av)
{
int c;
int i;
char *firstarg = 0;
program_name = av[0];
oav = av;
#if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
setlocale (LC_MESSAGES, "");
#endif
#if defined (HAVE_SETLOCALE)
setlocale (LC_CTYPE, "");
#endif
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
expandargv (&ac, &av);
while ((c = getopt_long (ac, av,
#ifdef DLLTOOL_MCORE_ELF
"m:e:l:aD:d:z:b:xp:cCuUkAS:f:nI:vVHhM:L:F:",
#else
"m:e:l:y:aD:d:z:b:xp:cCuUkAS:f:nI:vVHh",
#endif
long_options, 0))
!= EOF)
{
switch (c)
{
case OPTION_EXPORT_ALL_SYMS:
export_all_symbols = TRUE;
break;
case OPTION_NO_EXPORT_ALL_SYMS:
export_all_symbols = FALSE;
break;
case OPTION_EXCLUDE_SYMS:
add_excludes (optarg);
break;
case OPTION_NO_DEFAULT_EXCLUDES:
do_default_excludes = FALSE;
break;
case OPTION_USE_NUL_PREFIXED_IMPORT_TABLES:
use_nul_prefixed_import_tables = TRUE;
break;
case OPTION_ADD_STDCALL_UNDERSCORE:
add_stdcall_underscore = 1;
break;
case OPTION_NO_LEADING_UNDERSCORE:
leading_underscore = 0;
break;
case OPTION_LEADING_UNDERSCORE:
leading_underscore = 1;
break;
case OPTION_IDENTIFY_STRICT:
identify_strict = 1;
break;
case 'x':
no_idata4 = 1;
break;
case 'c':
no_idata5 = 1;
break;
case 'S':
as_name = optarg;
break;
case 't':
tmp_prefix = optarg;
break;
case 'f':
as_flags = optarg;
break;
/* Ignored for compatibility. */
case 'u':
break;
case 'a':
add_indirect = 1;
break;
case 'z':
output_def = fopen (optarg, FOPEN_WT);
break;
case 'D':
dll_name = (char*) lbasename (optarg);
if (dll_name != optarg)
non_fatal (_("Path components stripped from dllname, '%s'."),
optarg);
break;
case 'l':
imp_name = optarg;
break;
case 'e':
exp_name = optarg;
break;
case 'H':
case 'h':
usage (stdout, 0);
break;
case 'm':
mname = optarg;
break;
case 'I':
identify_imp_name = optarg;
break;
case 'v':
verbose = 1;
break;
case 'V':
print_version (program_name);
break;
case 'U':
add_underscore = 1;
break;
case 'k':
killat = 1;
break;
case 'A':
add_stdcall_alias = 1;
break;
case 'p':
ext_prefix_alias = optarg;
break;
case 'd':
def_file = optarg;
break;
case 'n':
dontdeltemps++;
break;
case 'b':
base_file = fopen (optarg, FOPEN_RB);
if (!base_file)
/* xgettext:c-format */
fatal (_("Unable to open base-file: %s"), optarg);
break;
#ifdef DLLTOOL_MCORE_ELF
case 'M':
mcore_elf_out_file = optarg;
break;
case 'L':
mcore_elf_linker = optarg;
break;
case 'F':
mcore_elf_linker_flags = optarg;
break;
#endif
case 'C':
create_compat_implib = 1;
break;
case 'y':
delayimp_name = optarg;
break;
default:
usage (stderr, 1);
break;
}
}
if (!tmp_prefix)
tmp_prefix = prefix_encode ("d", getpid ());
for (i = 0; mtable[i].type; i++)
if (strcmp (mtable[i].type, mname) == 0)
break;
if (!mtable[i].type)
/* xgettext:c-format */
fatal (_("Machine '%s' not supported"), mname);
machine = i;
/* Check if we generated PE+. */
create_for_pep = strcmp (mname, "i386:x86-64") == 0;
{
/* Check the default underscore */
int u = leading_underscore; /* Underscoring mode. -1 for use default. */
if (u == -1)
bfd_get_target_info (mtable[machine].how_bfd_target, NULL,
NULL, &u, NULL);
if (u != -1)
leading_underscore = (u != 0 ? TRUE : FALSE);
}
if (!dll_name && exp_name)
{
/* If we are inferring dll_name from exp_name,
strip off any path components, without emitting
a warning. */
const char* exp_basename = lbasename (exp_name);
const int len = strlen (exp_basename) + 5;
dll_name = xmalloc (len);
strcpy (dll_name, exp_basename);
strcat (dll_name, ".dll");
}
if (as_name == NULL)
as_name = deduce_name ("as");
/* Don't use the default exclude list if we're reading only the
symbols in the .drectve section. The default excludes are meant
to avoid exporting DLL entry point and Cygwin32 impure_ptr. */
if (! export_all_symbols)
do_default_excludes = FALSE;
if (do_default_excludes)
set_default_excludes ();
if (def_file)
process_def_file (def_file);
while (optind < ac)
{
if (!firstarg)
firstarg = av[optind];
scan_obj_file (av[optind]);
optind++;
}
mangle_defs ();
if (exp_name)
gen_exp_file ();
if (imp_name)
{
/* Make imp_name safe for use as a label. */
char *p;
imp_name_lab = xstrdup (imp_name);
for (p = imp_name_lab; *p; p++)
{
if (!ISALNUM (*p))
*p = '_';
}
head_label = make_label("_head_", imp_name_lab);
gen_lib_file (0);
}
if (delayimp_name)
{
/* Make delayimp_name safe for use as a label. */
char *p;
if (mtable[machine].how_dljtab == 0)
{
inform (_("Warning, machine type (%d) not supported for "
"delayimport."), machine);
}
else
{
killat = 1;
imp_name = delayimp_name;
imp_name_lab = xstrdup (imp_name);
for (p = imp_name_lab; *p; p++)
{
if (!ISALNUM (*p))
*p = '_';
}
head_label = make_label("__tailMerge_", imp_name_lab);
gen_lib_file (1);
}
}
if (output_def)
gen_def_file ();
if (identify_imp_name)
{
identify_dll_for_implib ();
}
#ifdef DLLTOOL_MCORE_ELF
if (mcore_elf_out_file)
mcore_elf_gen_out_file ();
#endif
return 0;
}
/* Look for the program formed by concatenating PROG_NAME and the
string running from PREFIX to END_PREFIX. If the concatenated
string contains a '/', try appending EXECUTABLE_SUFFIX if it is
appropriate. */
static char *
look_for_prog (const char *prog_name, const char *prefix, int end_prefix)
{
struct stat s;
char *cmd;
cmd = xmalloc (strlen (prefix)
+ strlen (prog_name)
#ifdef HAVE_EXECUTABLE_SUFFIX
+ strlen (EXECUTABLE_SUFFIX)
#endif
+ 10);
strcpy (cmd, prefix);
sprintf (cmd + end_prefix, "%s", prog_name);
if (strchr (cmd, '/') != NULL)
{
int found;
found = (stat (cmd, &s) == 0
#ifdef HAVE_EXECUTABLE_SUFFIX
|| stat (strcat (cmd, EXECUTABLE_SUFFIX), &s) == 0
#endif
);
if (! found)
{
/* xgettext:c-format */
inform (_("Tried file: %s"), cmd);
free (cmd);
return NULL;
}
}
/* xgettext:c-format */
inform (_("Using file: %s"), cmd);
return cmd;
}
/* Deduce the name of the program we are want to invoke.
PROG_NAME is the basic name of the program we want to run,
eg "as" or "ld". The catch is that we might want actually
run "i386-pe-as" or "ppc-pe-ld".
If argv[0] contains the full path, then try to find the program
in the same place, with and then without a target-like prefix.
Given, argv[0] = /usr/local/bin/i586-cygwin32-dlltool,
deduce_name("as") uses the following search order:
/usr/local/bin/i586-cygwin32-as
/usr/local/bin/as
as
If there's an EXECUTABLE_SUFFIX, it'll use that as well; for each
name, it'll try without and then with EXECUTABLE_SUFFIX.
Given, argv[0] = i586-cygwin32-dlltool, it will not even try "as"
as the fallback, but rather return i586-cygwin32-as.
Oh, and given, argv[0] = dlltool, it'll return "as".
Returns a dynamically allocated string. */
static char *
deduce_name (const char *prog_name)
{
char *cmd;
char *dash, *slash, *cp;
dash = NULL;
slash = NULL;
for (cp = program_name; *cp != '\0'; ++cp)
{
if (*cp == '-')
dash = cp;
if (
#if defined(__DJGPP__) || defined (__CYGWIN__) || defined(__WIN32__)
*cp == ':' || *cp == '\\' ||
#endif
*cp == '/')
{
slash = cp;
dash = NULL;
}
}
cmd = NULL;
if (dash != NULL)
{
/* First, try looking for a prefixed PROG_NAME in the
PROGRAM_NAME directory, with the same prefix as PROGRAM_NAME. */
cmd = look_for_prog (prog_name, program_name, dash - program_name + 1);
}
if (slash != NULL && cmd == NULL)
{
/* Next, try looking for a PROG_NAME in the same directory as
that of this program. */
cmd = look_for_prog (prog_name, program_name, slash - program_name + 1);
}
if (cmd == NULL)
{
/* Just return PROG_NAME as is. */
cmd = xstrdup (prog_name);
}
return cmd;
}
#ifdef DLLTOOL_MCORE_ELF
typedef struct fname_cache
{
const char * filename;
struct fname_cache * next;
}
fname_cache;
static fname_cache fnames;
static void
mcore_elf_cache_filename (const char * filename)
{
fname_cache * ptr;
ptr = & fnames;
while (ptr->next != NULL)
ptr = ptr->next;
ptr->filename = filename;
ptr->next = (fname_cache *) malloc (sizeof (fname_cache));
if (ptr->next != NULL)
ptr->next->next = NULL;
}
#define MCORE_ELF_TMP_OBJ "mcoreelf.o"
#define MCORE_ELF_TMP_EXP "mcoreelf.exp"
#define MCORE_ELF_TMP_LIB "mcoreelf.lib"
static void
mcore_elf_gen_out_file (void)
{
fname_cache * ptr;
dyn_string_t ds;
/* Step one. Run 'ld -r' on the input object files in order to resolve
any internal references and to generate a single .exports section. */
ptr = & fnames;
ds = dyn_string_new (100);
dyn_string_append_cstr (ds, "-r ");
if (mcore_elf_linker_flags != NULL)
dyn_string_append_cstr (ds, mcore_elf_linker_flags);
while (ptr->next != NULL)
{
dyn_string_append_cstr (ds, ptr->filename);
dyn_string_append_cstr (ds, " ");
ptr = ptr->next;
}
dyn_string_append_cstr (ds, "-o ");
dyn_string_append_cstr (ds, MCORE_ELF_TMP_OBJ);
if (mcore_elf_linker == NULL)
mcore_elf_linker = deduce_name ("ld");
run (mcore_elf_linker, ds->s);
dyn_string_delete (ds);
/* Step two. Create a .exp file and a .lib file from the temporary file.
Do this by recursively invoking dlltool... */
ds = dyn_string_new (100);
dyn_string_append_cstr (ds, "-S ");
dyn_string_append_cstr (ds, as_name);
dyn_string_append_cstr (ds, " -e ");
dyn_string_append_cstr (ds, MCORE_ELF_TMP_EXP);
dyn_string_append_cstr (ds, " -l ");
dyn_string_append_cstr (ds, MCORE_ELF_TMP_LIB);
dyn_string_append_cstr (ds, " " );
dyn_string_append_cstr (ds, MCORE_ELF_TMP_OBJ);
if (verbose)
dyn_string_append_cstr (ds, " -v");
if (dontdeltemps)
{
dyn_string_append_cstr (ds, " -n");
if (dontdeltemps > 1)
dyn_string_append_cstr (ds, " -n");
}
/* XXX - FIME: ought to check/copy other command line options as well. */
run (program_name, ds->s);
dyn_string_delete (ds);
/* Step four. Feed the .exp and object files to ld -shared to create the dll. */
ds = dyn_string_new (100);
dyn_string_append_cstr (ds, "-shared ");
if (mcore_elf_linker_flags)
dyn_string_append_cstr (ds, mcore_elf_linker_flags);
dyn_string_append_cstr (ds, " ");
dyn_string_append_cstr (ds, MCORE_ELF_TMP_EXP);
dyn_string_append_cstr (ds, " ");
dyn_string_append_cstr (ds, MCORE_ELF_TMP_OBJ);
dyn_string_append_cstr (ds, " -o ");
dyn_string_append_cstr (ds, mcore_elf_out_file);
run (mcore_elf_linker, ds->s);
dyn_string_delete (ds);
if (dontdeltemps == 0)
unlink (MCORE_ELF_TMP_EXP);
if (dontdeltemps < 2)
unlink (MCORE_ELF_TMP_OBJ);
}
#endif /* DLLTOOL_MCORE_ELF */
| 27.001332 | 113 | 0.621065 | [
"object",
"vector"
] |
8c734aff62cf1c0bdf9d09b2d97c6b57350ffcf4 | 2,127 | h | C | mcrouter/McrouterLogger.h | PPC64/mcrouter | 76edd6c9c18a291845476a8b1d9a3e2df4716018 | [
"BSD-3-Clause"
] | 1 | 2015-06-16T14:58:48.000Z | 2015-06-16T14:58:48.000Z | mcrouter/McrouterLogger.h | PPC64/mcrouter | 76edd6c9c18a291845476a8b1d9a3e2df4716018 | [
"BSD-3-Clause"
] | null | null | null | mcrouter/McrouterLogger.h | PPC64/mcrouter | 76edd6c9c18a291845476a8b1d9a3e2df4716018 | [
"BSD-3-Clause"
] | null | null | null | /*
* 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.
*
*/
#pragma once
#include <atomic>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
namespace facebook { namespace memcache { namespace mcrouter {
class McrouterInstance;
class stat_t;
class AdditionalLoggerIf {
public:
virtual ~AdditionalLoggerIf() {}
virtual void log(const std::vector<stat_t>& stats) = 0;
};
class McrouterLogger {
public:
/*
* Constructs a McrouterLogger for the specified router.
*
* @param router The router to log for.
* @param additionalLogger Additional logger that is called everytime a log
* is written.
*/
explicit McrouterLogger(
McrouterInstance* router,
std::unique_ptr<AdditionalLoggerIf> additionalLogger = nullptr);
~McrouterLogger();
/**
* Starts the logger thread.
*
* @return True if logger thread was successfully started, false otherwise.
*/
bool start();
/**
* Tells whether the logger thread is running.
*
* @return True if logger thread is running, false otherwise.
*/
bool running() const;
/**
* Stops the logger thread and join it.
* Note: this is a blocking call.
*/
void stop();
private:
McrouterInstance* router_;
std::unique_ptr<AdditionalLoggerIf> additionalLogger_;
/**
* File paths of stats we want to touch and keep their mtimes up-to-date
*/
std::vector<std::string> touchStatsFilepaths_;
pid_t pid_;
std::thread loggerThread_;
std::mutex loggerThreadMutex_;
std::condition_variable loggerThreadCv_;
std::atomic<bool> running_{false};
void loggerThreadRun();
void loggerThreadSleep();
/**
* Writes router's logs.
*/
void log();
/**
* Writes startup options.
*/
void logStartupOptions();
};
}}} // facebook::memcache::mcrouter
| 21.927835 | 79 | 0.685472 | [
"vector"
] |
9685aa7ebbc4844957e883e5f9630542b1374e0d | 892 | h | C | src/c2integer-utils.h | cran/cnum | aa53d8ad2826333ddbf3bb537d7b8b0e45b74cdb | [
"MIT"
] | 8 | 2020-05-03T20:27:15.000Z | 2021-05-04T03:19:49.000Z | src/c2integer-utils.h | cran/cnum | aa53d8ad2826333ddbf3bb537d7b8b0e45b74cdb | [
"MIT"
] | 1 | 2021-10-05T01:53:44.000Z | 2021-10-05T01:53:44.000Z | src/c2integer-utils.h | cran/cnum | aa53d8ad2826333ddbf3bb537d7b8b0e45b74cdb | [
"MIT"
] | 2 | 2020-05-03T20:27:03.000Z | 2021-02-19T16:48:50.000Z | #include <Rcpp.h>
#include <string>
#include "utils.h"
// Function to calulate 10 to the power of given exponent
long long pow10(const int exp)
{
long long result = 1;
for (int i = 1; i <= exp; ++i)
result *= 10;
return result;
}
// Function to return index of a matching element in a character vector
int subset_chr(const Rcpp::CharacterVector x, const std::string y)
{
int index = 0;
for (int i = 0; i < x.size(); ++i) {
if (x[i] == y) {
index = i;
break;
}
}
return index;
}
// Function to return the corresponding chr of df$n given c of df$c
std::string subset_df(const Rcpp::DataFrame df, const std::string c)
{
const Rcpp::NumericVector n_col = df["n"];
const Rcpp::CharacterVector c_col = df["c"];
if (!contains(c_col, c))
return "";
int index = subset_chr(c_col, c);
int output = n_col[index];
return std::to_string(output);
}
| 23.473684 | 71 | 0.640135 | [
"vector"
] |
9686afe48fae8349a7616d912d08cf7841c9ac66 | 3,821 | h | C | melodic/src/rviz/src/rviz/panel.h | disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA | 3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0 | [
"BSD-3-Clause"
] | 2 | 2021-07-14T12:33:55.000Z | 2021-11-21T07:14:13.000Z | melodic/src/rviz/src/rviz/panel.h | disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA | 3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0 | [
"BSD-3-Clause"
] | null | null | null | melodic/src/rviz/src/rviz/panel.h | disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA | 3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RVIZ_PANEL_H
#define RVIZ_PANEL_H
#include <QWidget>
#include "rviz/config.h"
#include "rviz/rviz_export.h"
namespace rviz
{
class VisualizationManager;
class RVIZ_EXPORT Panel: public QWidget
{
Q_OBJECT
public:
Panel( QWidget* parent = 0 );
virtual ~Panel();
/** Initialize the panel with a VisualizationManager. Called by
* VisualizationFrame during setup. */
void initialize( VisualizationManager* manager );
/**
* Override to do initialization which depends on the
* VisualizationManager being available. This base implementation
* does nothing.
*/
virtual void onInitialize() {}
virtual QString getName() const { return name_; }
virtual void setName( const QString& name ) { name_ = name; }
/** @brief Return a description of this Panel. */
virtual QString getDescription() const { return description_; }
/** @brief Set a description of this Panel. Called by the factory which creates it. */
virtual void setDescription( const QString& description ) { description_ = description; }
/** @brief Return the class identifier which was used to create this
* instance. This version just returns whatever was set with
* setClassId(). */
virtual QString getClassId() const { return class_id_; }
/** @brief Set the class identifier used to create this instance.
* Typically this will be set by the factory object which created it. */
virtual void setClassId( const QString& class_id ) { class_id_ = class_id; }
/** @brief Override to load configuration data. This version loads the name of the panel. */
virtual void load( const Config& config );
/** @brief Override to save configuration data. This version saves the name and class ID of the panel. */
virtual void save( Config config ) const;
Q_SIGNALS:
/** @brief Subclasses must emit this whenever a configuration change
* happens.
*
* This is used to let the system know that changes have been made
* since the last time the config was saved. */
void configChanged();
protected:
VisualizationManager* vis_manager_;
private:
QString class_id_;
QString name_;
QString description_;
};
} // end namespace rviz
#endif // RVIZ_PANEL_H
| 36.740385 | 108 | 0.733316 | [
"object"
] |
9689b3fd3cb662f06257192b9c9b9562e31acf19 | 6,622 | c | C | sort-psrs.c | dbader13/PMedian | a46ea79d24894ccb48fce8d7a97265608a8f8cc5 | [
"BSD-3-Clause"
] | null | null | null | sort-psrs.c | dbader13/PMedian | a46ea79d24894ccb48fce8d7a97265608a8f8cc5 | [
"BSD-3-Clause"
] | null | null | null | sort-psrs.c | dbader13/PMedian | a46ea79d24894ccb48fce8d7a97265608a8f8cc5 | [
"BSD-3-Clause"
] | null | null | null | #include "sort-psrs.h"
#include "sorting.h"
#define OVERSMP 1
#define DEBUG 0
void all_sort_psrs_check_i(int *A, int A_size) {
int i;
for (i=1 ; i<A_size ; i++)
if (A[i] < A[i-1])
fprintf(stderr,"(PE%3d)ERROR: A[%8d] < A[%8d] (%12d %12d)\n",
MYPROC, i, i-1, A[i], A[i-1]);
MPI_fprintf(stderr,"HERE CHECKED\n");
}
int *findpos (int *base, int size, int key) {
/* find position of key (or next larger) in sorted array */
int done = 0, *l, *u, *m, *end;
l = base;
u = end = base + size - 1;
while (! done && size > 0) {
m = l + size/2;
if (key == *m)
done = 1;
else {
size /= 2;
if (key > *m)
l = m+1;
else
u = m-1;
}
}
while (m < end && key > *m)
++m;
return (m);
}
int all_sort_psrs_i(int *A, int A_size, int *B) {
int i, B_size;
int
*recv_cnt, /* number of keys to receive from each PN */
*send_cnt, /* number of keys to send to PNs */
*recv_off,
*send_off;
int no_samples, /* number of samples to take from sorted data */
*pivbuffer, /* array of pivots */
pivdist, /* distance between pivots in set of samples */
possmp, /* position of pivot in set of all samples */
**prtbound, /* boundaries for partitioning local data */
*recv_buf, /* incoming data to merge */
*smpbuffer, /* array of local samples */
*smpallbuf, /* array of global samples */
smpdist, /* distance between consecutive samples */
trecv;
MPI_Status stat;
prtbound = (int **) malloc((PROCS+1)*sizeof(int *));
assert_malloc(prtbound);
send_cnt = (int *)malloc(PROCS*sizeof(int));
assert_malloc(send_cnt);
send_off = (int *)malloc(PROCS*sizeof(int));
assert_malloc(send_off);
recv_off = (int *)malloc(PROCS*sizeof(int));
assert_malloc(recv_off);
recv_cnt = (int *)malloc(PROCS*sizeof(int));
assert_malloc(recv_cnt);
pivbuffer = (int *)malloc((PROCS-1)*sizeof(int));
assert_malloc(pivbuffer);
/*------------------------------------------------------------
- Phase 2: Sort
*------------------------------------------------------------*/
fastsort(A, A_size);
/*------------------------------------------------------------
- Phase 3: Find pivots
*------------------------------------------------------------*/
/*
- Sample the sorted array
*/
no_samples = OVERSMP*PROCS - 1;
smpdist = A_size / (no_samples + 1);
smpbuffer = (int *)malloc(no_samples*sizeof(int));
assert_malloc(smpbuffer);
for (i=0; i<no_samples; i++)
smpbuffer[i] = A[(i+1)*smpdist];
#if DEBUG
MPI_Barrier(MPI_COMM_WORLD);
for (i=0 ; i<no_samples ; i++)
MPI_fprintf(stderr,"(s %5d) smp[%5d]: %12d\n",
no_samples, i, smpbuffer[i]);
MPI_Barrier(MPI_COMM_WORLD);
#endif
/*
- Concatenate samples, sort and select pivots
*/
smpallbuf = (int *)malloc(PROCS*no_samples*sizeof(int));
assert_malloc(smpallbuf);
MPI_Gather(smpbuffer, no_samples, MPI_INT,
smpallbuf, no_samples, MPI_INT,
0, MPI_COMM_WORLD);
#if 0
MPI_Barrier(MPI_COMM_WORLD);
if (MYPROC==0)
for (i=0 ; i<no_samples*PROCS ; i++)
fprintf(stderr,"(PE%3d) sample[%5d]: %12d\n",
MYPROC, i, smpallbuf[i]);
MPI_Barrier(MPI_COMM_WORLD);
#endif
fastsort(smpallbuf, PROCS*no_samples);
#if 0
MPI_Barrier(MPI_COMM_WORLD);
if (MYPROC==0)
for (i=0 ; i<no_samples*PROCS ; i++)
fprintf(stderr,"(PE%3d) SAMPLE[%5d]: %12d\n",
MYPROC, i, smpallbuf[i]);
MPI_Barrier(MPI_COMM_WORLD);
#endif
if (MYPROC==0) {
pivdist = PROCS*no_samples/(PROCS-1);
possmp = pivdist/2;
for (i=0; i<PROCS-1; i++) {
pivbuffer[i] = smpallbuf[possmp];
possmp += pivdist;
}
}
MPI_Bcast(pivbuffer, PROCS-1, MPI_INT, 0, MPI_COMM_WORLD);
#if DEBUG
MPI_Barrier(MPI_COMM_WORLD);
if (MYPROC==0)
fprintf(stderr,"pivdist: %12d\n",pivdist);
for (i=0 ; i<PROCS-1 ; i++)
MPI_fprintf(stderr,"pivbuffer[%5d]: %12d\n", i, pivbuffer[i]);
MPI_Barrier(MPI_COMM_WORLD);
#endif
/*
- Search for pivots in local buffer
*/
prtbound[0] = A;
for (i=1; i<PROCS; i++)
prtbound[i] = findpos (A, A_size, pivbuffer[i-1]);
prtbound[PROCS] = A + A_size;
#if DEBUG
MPI_Barrier(MPI_COMM_WORLD);
for (i=0 ; i<=PROCS ; i++)
MPI_fprintf(stderr,"prtbound[%3d]: %5d\n",i,prtbound[i]-A);
MPI_Barrier(MPI_COMM_WORLD);
#endif
free (smpbuffer);
free (smpallbuf);
free (pivbuffer);
/*------------------------------------------------------------
- Phase 4: Redistribution
*------------------------------------------------------------*/
/*
- Find out how many keys have to be sent to each PN
*/
for (i=0; i<PROCS; i++)
send_cnt[i] = max(0, prtbound[i+1] - 1 - prtbound[i]);
/*
- Find out how many keys have to be received from each PN
-
- communication pattern: at iteration i,
- send send_cnt to PN distant i ahead and
- receive recv_cnt from PN distant i behind
-
*/
#if DEBUG
MPI_Barrier(MPI_COMM_WORLD);
for (i=0 ; i<PROCS ; i++)
MPI_fprintf(stderr,"send_cnt[%3d]: %5d\n",i,send_cnt[i]);
MPI_Barrier(MPI_COMM_WORLD);
#endif
MPI_Alltoall(send_cnt, 1, MPI_INT,
recv_cnt, 1, MPI_INT,
MPI_COMM_WORLD);
#if DEBUG
MPI_Barrier(MPI_COMM_WORLD);
for (i=0 ; i<PROCS ; i++)
MPI_fprintf(stderr,"recv_cnt[%3d]: %5d\n",i,recv_cnt[i]);
MPI_Barrier(MPI_COMM_WORLD);
#endif
/*
- allocate space for incoming data
*/
send_off[0] = 0;
recv_off[0] = 0;
for (i=1 ; i<PROCS ; i++) {
send_off[i] = send_off[i-1] + send_cnt[i-1];
recv_off[i] = recv_off[i-1] + recv_cnt[i-1];
}
trecv = recv_off[PROCS-1] + recv_cnt[PROCS-1];
if (trecv>0) {
recv_buf = (int *)malloc(trecv*sizeof(int));
assert_malloc(recv_buf);
}
else {
recv_buf = NULL;
}
/*
- send and receive keys
*/
MPI_Alltoallv(A, send_cnt, send_off, MPI_INT,
recv_buf, recv_cnt, recv_off, MPI_INT,
MPI_COMM_WORLD);
/*-----------------------------------------------------------
* Phase 5: Merge received keys
*-----------------------------------------------------------*/
/*
- in this version, simply sort again
- (to be substituted by an p-way merge function)
*/
B_size = trecv;
bcopy(recv_buf, B, B_size*sizeof(int));
fastsort(B, B_size);
MPI_Barrier(MPI_COMM_WORLD);
free(recv_buf);
free(recv_off);
free(send_off);
free(send_cnt);
free(recv_cnt);
free(prtbound);
return (B_size);
}
| 23.734767 | 69 | 0.551344 | [
"3d"
] |
9689e61ae799b59703ec59e061cd7ba3230b9f01 | 21,541 | h | C | lib/Ogre/include/CEGUI/elements/CEGUIFrameWindow.h | Misterblue/LookingGlass-Viewer | c80120e3e5cc8ed699280763c95ca8bb8db8174b | [
"BSD-3-Clause"
] | 3 | 2018-10-14T18:06:33.000Z | 2021-07-23T15:00:10.000Z | include/CEGUI/elements/CEGUIFrameWindow.h | chen0040/cpp-ogre-mllab | b85305cd7e95559a178664577c8e858a5b9dd05b | [
"MIT"
] | null | null | null | include/CEGUI/elements/CEGUIFrameWindow.h | chen0040/cpp-ogre-mllab | b85305cd7e95559a178664577c8e858a5b9dd05b | [
"MIT"
] | 6 | 2019-05-05T22:29:55.000Z | 2022-01-03T14:18:54.000Z | /***********************************************************************
filename: CEGUIFrameWindow.h
created: 13/4/2004
author: Paul D Turner
purpose: Interface to base class for FrameWindow
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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.
***************************************************************************/
#ifndef _CEGUIFrameWindow_h_
#define _CEGUIFrameWindow_h_
#include "CEGUIBase.h"
#include "CEGUIWindow.h"
#include "elements/CEGUIFrameWindowProperties.h"
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4251)
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
/*!
\brief
Abstract base class for a movable, sizable, window with a title-bar and a frame.
*/
class CEGUIEXPORT FrameWindow : public Window
{
public:
static const String EventNamespace; //!< Namespace for global events
static const String WidgetTypeName; //!< Window factory name
/*************************************************************************
Constants
*************************************************************************/
// additional event names for this window
static const String EventRollupToggled; //!< Fired when the rollup (shade) state of the window changes
static const String EventCloseClicked; //!< Fired when the close button for the window is clicked.
// other bits
static const float DefaultSizingBorderSize; //!< Default size for the sizing border (in pixels)
/*************************************************************************
Child Widget name suffix constants
*************************************************************************/
static const String TitlebarNameSuffix; //!< Widget name suffix for the titlebar component.
static const String CloseButtonNameSuffix; //!< Widget name suffix for the close button component.
/*!
\brief
Enumeration that defines the set of possible locations for the mouse on a frame windows sizing border.
*/
enum SizingLocation {
SizingNone, //!< Position is not a sizing location.
SizingTopLeft, //!< Position will size from the top-left.
SizingTopRight, //!< Position will size from the top-right.
SizingBottomLeft, //!< Position will size from the bottom left.
SizingBottomRight, //!< Position will size from the bottom right.
SizingTop, //!< Position will size from the top.
SizingLeft, //!< Position will size from the left.
SizingBottom, //!< Position will size from the bottom.
SizingRight //!< Position will size from the right.
};
/*!
\brief
Initialises the Window based object ready for use.
\note
This must be called for every window created. Normally this is handled automatically by the WindowFactory for each Window type.
\return
Nothing
*/
virtual void initialiseComponents(void);
/*!
\brief
Return whether this window is sizable. Note that this requires that the window have an enabled frame and that sizing itself is enabled
\return
true if the window can be sized, false if the window can not be sized
*/
bool isSizingEnabled(void) const {return d_sizingEnabled && isFrameEnabled();}
/*!
\brief
Return whether the frame for this window is enabled.
\return
true if the frame for this window is enabled, false if the frame for this window is disabled.
*/
bool isFrameEnabled(void) const {return d_frameEnabled;}
/*!
\brief
Return whether the title bar for this window is enabled.
\return
true if the window has a title bar and it is enabled, false if the window has no title bar or if the title bar is disabled.
*/
bool isTitleBarEnabled(void) const;
/*!
\brief
Return whether this close button for this window is enabled.
\return
true if the window has a close button and it is enabled, false if the window either has no close button or if the close button is disabled.
*/
bool isCloseButtonEnabled(void) const;
/*!
\brief
Return whether roll up (a.k.a shading) is enabled for this window.
\return
true if roll up is enabled, false if roll up is disabled.
*/
bool isRollupEnabled(void) const {return d_rollupEnabled;}
/*!
\brief
Return whether the window is currently rolled up (a.k.a shaded).
\return
true if the window is rolled up, false if the window is not rolled up.
*/
bool isRolledup(void) const {return d_rolledup;}
/*!
\brief
Return the thickness of the sizing border.
\return
float value describing the thickness of the sizing border in screen pixels.
*/
float getSizingBorderThickness(void) const {return d_borderSize;}
/*!
\brief
Enables or disables sizing for this window.
\param setting
set to true to enable sizing (also requires frame to be enabled), or false to disable sizing.
\return
nothing
*/
void setSizingEnabled(bool setting);
/*!
\brief
Enables or disables the frame for this window.
\param setting
set to true to enable the frame for this window, or false to disable the frame for this window.
\return
Nothing.
*/
void setFrameEnabled(bool setting);
/*!
\brief
Enables or disables the title bar for the frame window.
\param setting
set to true to enable the title bar (if one is attached), or false to disable the title bar.
\return
Nothing.
*/
void setTitleBarEnabled(bool setting);
/*!
\brief
Enables or disables the close button for the frame window.
\param setting
Set to true to enable the close button (if one is attached), or false to disable the close button.
\return
Nothing.
*/
void setCloseButtonEnabled(bool setting);
/*!
\brief
Enables or disables roll-up (shading) for this window.
\param setting
Set to true to enable roll-up for the frame window, or false to disable roll-up.
\return
Nothing.
*/
void setRollupEnabled(bool setting);
/*!
\brief
Toggles the state of the window between rolled-up (shaded) and normal sizes. This requires roll-up to be enabled.
\return
Nothing
*/
void toggleRollup(void);
/*!
\brief
Set the size of the sizing border for this window.
\param pixels
float value specifying the thickness for the sizing border in screen pixels.
\return
Nothing.
*/
void setSizingBorderThickness(float pixels) {d_borderSize = pixels;}
/*!
\brief
Move the window by the pixel offsets specified in \a offset.
This is intended for internal system use - it is the method by which the title bar moves the frame window.
\param offset
Vector2 object containing the offsets to apply (offsets are in screen pixels).
\return
Nothing.
*/
void offsetPixelPosition(const Vector2& offset);
/*!
\brief
Return whether this FrameWindow can be moved by dragging the title bar.
\return
true if the Window will move when the user drags the title bar, false if the window will not move.
*/
bool isDragMovingEnabled(void) const {return d_dragMovable;}
/*!
\brief
Set whether this FrameWindow can be moved by dragging the title bar.
\param setting
true if the Window should move when the user drags the title bar, false if the window should not move.
\return
Nothing.
*/
void setDragMovingEnabled(bool setting);
/*!
\brief
Return a pointer to the currently set Image to be used for the north-south
sizing mouse cursor.
\return
Pointer to an Image object, or 0 for none.
*/
const Image* getNSSizingCursorImage() const;
/*!
\brief
Return a pointer to the currently set Image to be used for the east-west
sizing mouse cursor.
\return
Pointer to an Image object, or 0 for none.
*/
const Image* getEWSizingCursorImage() const;
/*!
\brief
Return a pointer to the currently set Image to be used for the northwest-southeast
sizing mouse cursor.
\return
Pointer to an Image object, or 0 for none.
*/
const Image* getNWSESizingCursorImage() const;
/*!
\brief
Return a pointer to the currently set Image to be used for the northeast-southwest
sizing mouse cursor.
\return
Pointer to an Image object, or 0 for none.
*/
const Image* getNESWSizingCursorImage() const;
/*!
\brief
Set the Image to be used for the north-south sizing mouse cursor.
\param image
Pointer to an Image object, or 0 for none.
\return
Nothing.
*/
void setNSSizingCursorImage(const Image* image);
/*!
\brief
Set the Image to be used for the east-west sizing mouse cursor.
\param image
Pointer to an Image object, or 0 for none.
\return
Nothing.
*/
void setEWSizingCursorImage(const Image* image);
/*!
\brief
Set the Image to be used for the northwest-southeast sizing mouse cursor.
\param image
Pointer to an Image object, or 0 for none.
\return
Nothing.
*/
void setNWSESizingCursorImage(const Image* image);
/*!
\brief
Set the Image to be used for the northeast-southwest sizing mouse cursor.
\param image
Pointer to an Image object, or 0 for none.
\return
Nothing.
*/
void setNESWSizingCursorImage(const Image* image);
/*!
\brief
Set the image to be used for the north-south sizing mouse cursor.
\param imageset
String holding the name of the Imageset containing the Image to be used.
\param image
String holding the name of the Image to be used.
\return
Nothing.
\exception UnknownObjectException thrown if either \a imageset or \a image refer to non-existant entities.
*/
void setNSSizingCursorImage(const String& imageset, const String& image);
/*!
\brief
Set the image to be used for the east-west sizing mouse cursor.
\param imageset
String holding the name of the Imageset containing the Image to be used.
\param image
String holding the name of the Image to be used.
\return
Nothing.
\exception UnknownObjectException thrown if either \a imageset or \a image refer to non-existant entities.
*/
void setEWSizingCursorImage(const String& imageset, const String& image);
/*!
\brief
Set the image to be used for the northwest-southeast sizing mouse cursor.
\param imageset
String holding the name of the Imageset containing the Image to be used.
\param image
String holding the name of the Image to be used.
\return
Nothing.
\exception UnknownObjectException thrown if either \a imageset or \a image refer to non-existant entities.
*/
void setNWSESizingCursorImage(const String& imageset, const String& image);
/*!
\brief
Set the image to be used for the northeast-southwest sizing mouse cursor.
\param imageset
String holding the name of the Imageset containing the Image to be used.
\param image
String holding the name of the Image to be used.
\return
Nothing.
\exception UnknownObjectException thrown if either \a imageset or \a image refer to non-existant entities.
*/
void setNESWSizingCursorImage(const String& imageset, const String& image);
// overridden from Window class
bool isHit(const Point& position) const { return Window::isHit(position) && !d_rolledup; }
/*!
\brief
Return a pointer to the Titlebar component widget for this FrameWindow.
\return
Pointer to a Titlebar object.
\exception UnknownObjectException
Thrown if the Titlebar component does not exist.
*/
Titlebar* getTitlebar() const;
/*!
\brief
Return a pointer to the close button component widget for this
FrameWindow.
\return
Pointer to a PushButton object.
\exception UnknownObjectException
Thrown if the close button component does not exist.
*/
PushButton* getCloseButton() const;
/*************************************************************************
Construction / Destruction
*************************************************************************/
/*!
\brief
Constructor for FrameWindow objects.
*/
FrameWindow(const String& name, const String& type);
/*!
\brief
Destructor for FramwWindow objects.
*/
virtual ~FrameWindow(void);
protected:
/*************************************************************************
Implementation Functions
*************************************************************************/
/*!
\brief
move the window's left edge by 'delta'. The rest of the window does not move, thus this changes the size of the Window.
\param delta
float value that specifies the amount to move the window edge, and in which direction. Positive values make window smaller.
*/
void moveLeftEdge(float delta);
/*!
\brief
move the window's right edge by 'delta'. The rest of the window does not move, thus this changes the size of the Window.
\param delta
float value that specifies the amount to move the window edge, and in which direction. Positive values make window larger.
*/
void moveRightEdge(float delta);
/*!
\brief
move the window's top edge by 'delta'. The rest of the window does not move, thus this changes the size of the Window.
\param delta
float value that specifies the amount to move the window edge, and in which direction. Positive values make window smaller.
*/
void moveTopEdge(float delta);
/*!
\brief
move the window's bottom edge by 'delta'. The rest of the window does not move, thus this changes the size of the Window.
\param delta
float value that specifies the amount to move the window edge, and in which direction. Positive values make window larger.
*/
void moveBottomEdge(float delta);
/*!
\brief
check local pixel co-ordinate point 'pt' and return one of the
SizingLocation enumerated values depending where the point falls on
the sizing border.
\param pt
Point object describing, in pixels, the window relative offset to check.
\return
One of the SizingLocation enumerated values that describe which part of
the sizing border that \a pt corresponded to, if any.
*/
SizingLocation getSizingBorderAtPoint(const Point& pt) const;
/*!
\brief
return true if given SizingLocation is on left edge.
\param loc
SizingLocation value to be checked.
\return
true if \a loc is on the left edge. false if \a loc is not on the left edge.
*/
bool isLeftSizingLocation(SizingLocation loc) const {return ((loc == SizingLeft) || (loc == SizingTopLeft) || (loc == SizingBottomLeft));}
/*!
\brief
return true if given SizingLocation is on right edge.
\param loc
SizingLocation value to be checked.
\return
true if \a loc is on the right edge. false if \a loc is not on the right edge.
*/
bool isRightSizingLocation(SizingLocation loc) const {return ((loc == SizingRight) || (loc == SizingTopRight) || (loc == SizingBottomRight));}
/*!
\brief
return true if given SizingLocation is on top edge.
\param loc
SizingLocation value to be checked.
\return
true if \a loc is on the top edge. false if \a loc is not on the top edge.
*/
bool isTopSizingLocation(SizingLocation loc) const {return ((loc == SizingTop) || (loc == SizingTopLeft) || (loc == SizingTopRight));}
/*!
\brief
return true if given SizingLocation is on bottom edge.
\param loc
SizingLocation value to be checked.
\return
true if \a loc is on the bottom edge. false if \a loc is not on the bottom edge.
*/
bool isBottomSizingLocation(SizingLocation loc) const {return ((loc == SizingBottom) || (loc == SizingBottomLeft) || (loc == SizingBottomRight));}
/*!
\brief
Method to respond to close button click events and fire our close event
*/
bool closeClickHandler(const EventArgs& e);
/*!
\brief
Set the appropriate mouse cursor for the given window-relative pixel point.
*/
void setCursorForPoint(const Point& pt) const;
/*!
\brief
Return a Rect that describes, in window relative pixel co-ordinates, the outer edge of the sizing area for this window.
*/
virtual Rect getSizingRect(void) const {return Rect(0, 0, d_pixelSize.d_width, d_pixelSize.d_height);}
/*!
\brief
Return whether this window was inherited from the given class name at some point in the inheritance hierarchy.
\param class_name
The class name that is to be checked.
\return
true if this window was inherited from \a class_name. false if not.
*/
virtual bool testClassName_impl(const String& class_name) const
{
if (class_name=="FrameWindow") return true;
return Window::testClassName_impl(class_name);
}
/*************************************************************************
New events for Frame Windows
*************************************************************************/
/*!
\brief
Event generated internally whenever the roll-up / shade state of the window
changes.
*/
virtual void onRollupToggled(WindowEventArgs& e);
/*!
\brief
Event generated internally whenever the close button is clicked.
*/
virtual void onCloseClicked(WindowEventArgs& e);
/*************************************************************************
Overridden event handlers
*************************************************************************/
virtual void onMouseMove(MouseEventArgs& e);
virtual void onMouseButtonDown(MouseEventArgs& e);
virtual void onMouseButtonUp(MouseEventArgs& e);
virtual void onCaptureLost(WindowEventArgs& e);
virtual void onTextChanged(WindowEventArgs& e);
virtual void onActivated(ActivationEventArgs& e);
virtual void onDeactivated(ActivationEventArgs& e);
/*************************************************************************
Implementation Data
*************************************************************************/
// frame data
bool d_frameEnabled; //!< true if window frame should be drawn.
// window roll-up data
bool d_rollupEnabled; //!< true if roll-up of window is allowed.
bool d_rolledup; //!< true if window is rolled up.
// drag-sizing data
bool d_sizingEnabled; //!< true if sizing is enabled for this window.
bool d_beingSized; //!< true if window is being sized.
float d_borderSize; //!< thickness of the sizing border around this window
Point d_dragPoint; //!< point window is being dragged at.
// images for cursor when on sizing border
const Image* d_nsSizingCursor; //!< North/South sizing cursor image.
const Image* d_ewSizingCursor; //!< East/West sizing cursor image.
const Image* d_nwseSizingCursor; //!< North-West/South-East cursor image.
const Image* d_neswSizingCursor; //!< North-East/South-West cursor image.
bool d_dragMovable; //!< true if the window will move when dragged by the title bar.
private:
/*************************************************************************
Static Properties for this class
*************************************************************************/
static FrameWindowProperties::SizingEnabled d_sizingEnabledProperty;
static FrameWindowProperties::FrameEnabled d_frameEnabledProperty;
static FrameWindowProperties::TitlebarEnabled d_titlebarEnabledProperty;
static FrameWindowProperties::CloseButtonEnabled d_closeButtonEnabledProperty;
static FrameWindowProperties::RollUpState d_rollUpStateProperty;
static FrameWindowProperties::RollUpEnabled d_rollUpEnabledProperty;
static FrameWindowProperties::DragMovingEnabled d_dragMovingEnabledProperty;
static FrameWindowProperties::SizingBorderThickness d_sizingBorderThicknessProperty;
static FrameWindowProperties::NSSizingCursorImage d_nsSizingCursorProperty;
static FrameWindowProperties::EWSizingCursorImage d_ewSizingCursorProperty;
static FrameWindowProperties::NWSESizingCursorImage d_nwseSizingCursorProperty;
static FrameWindowProperties::NESWSizingCursorImage d_neswSizingCursorProperty;
/*************************************************************************
Private methods
*************************************************************************/
void addFrameWindowProperties(void);
};
} // End of CEGUI namespace section
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif // end of guard _CEGUIFrameWindow_h_
| 29.307483 | 148 | 0.663293 | [
"object"
] |
968ca8b68e8fe61b7cf379481caf25a1dae2ed93 | 4,197 | h | C | src/sub/Realign.h | LeaveYeah/Sniffles | d3380a53842b71e8adad02143c454ea63e62a0cf | [
"MIT"
] | null | null | null | src/sub/Realign.h | LeaveYeah/Sniffles | d3380a53842b71e8adad02143c454ea63e62a0cf | [
"MIT"
] | null | null | null | src/sub/Realign.h | LeaveYeah/Sniffles | d3380a53842b71e8adad02143c454ea63e62a0cf | [
"MIT"
] | null | null | null | //
// Created by Ye Wu on 9/15/2019.
//
#ifndef SNIFFLES_REALIGN_H
#define SNIFFLES_REALIGN_H
#include <vector>
#include <string>
#include <map>
#include "../print/IPrinter.h"
#include "../Alignment.h"
#include "Breakpoint.h"
#include "../bioio.hpp"
#include "../tree/IntervallTree.h"
#include <fstream>
struct hist_str{
long position;
int hits;
std::vector<std::string> names;
};
struct tra_str{
long position;
int hits;
int sameStrand_hits = 0;
int diffStrand_hits = 0;
std::map<long, std::vector<long>> map_pos;
std::vector<std::string> names;
};
struct BpRln{
// int originalSupport;
bool denovo;
bool clipped;
bool processed;
bool isSameStrand;
pair<long, long> coordinate;
pair<long, long> chr_pos;
pair<std::string, std::string> chr;
pair<int, int> chr_idx;
Breakpoint * bp;
std::map<std::string,read_str> reads;
BpRln(bool strand, pair<long, long> coordinates, const RefVector ref, Breakpoint * breakpoint){
denovo = false;
this->isSameStrand = strand;
this->coordinate = coordinates;
chr_pos.first = IPrinter::calc_pos(coordinate.first, ref, chr_idx.first);
chr_pos.second = IPrinter::calc_pos(coordinate.second, ref, chr_idx.second);
chr.first = ref[chr_idx.first].RefName;
chr.second =ref[chr_idx.second].RefName;
bp = breakpoint;
}
bool operator < (const BpRln& bp) const {
if (chr.first == bp.chr.first)
return chr_pos.first < bp.chr_pos.first;
else return chr_idx.first < bp.chr_idx.first;
}
};
struct rln_str {
bool strand;
bool side;
pair<string, string> ref;
pair<long, long> ref_pos;
pair<long, long> coordinate;
long diff;
long read_pos;
Breakpoint * bp;
};
class ClippedRead {
public:
long ref_stop;
long ref_start;
std::string bases;
int RefId;
ClippedRead(){
this->bases = "";
}
void setChrId(int RefId);
void setBases(std::string bases);
void set_ref_pos(vector<aln_str> split_events);
std::vector<rln_str> events_rln;
};
void fix_mismatch_read_pos(vector<differences_str> &event_aln, int i, Alignment * tmp_aln);
void detect_bp_for_realn(Breakpoint *breakpoint, const RefVector ref, vector<BpRln> &bp_rlns, bool denovo);
void store_tra_pos(vector<tra_str> &positions, read_str read, std::string read_name, bool start);
long get_max_pos(map<long, vector<long>> map_pos, int &max);
long get_max_opp_pos(vector<long> opp_pos, int &max);
bool cal_high_error_side(vector<differences_str> &event_aln, long pos, long distance, Alignment * tmp_aln);
int map_read(Alignment * tmp_aln, BpRln bp, int distance, const bioio::FastaIndex index, std::ifstream & fasta);
int map_clipped_read(rln_str event_rln, int distance, const bioio::FastaIndex index, std::ifstream & fasta, string bases);
void add_realign_read(BpRln bp_realign, Alignment * tmp_aln);
void add_realign_read(string name, rln_str event_rln);
bool detect_gap(Alignment* tmp_aln, vector<aln_str> split_events, long ref_pos, int distance, RefVector ref);
void detect_clipped_reads_rln(BpRln bp_realign, Alignment* tmp_aln,
RefVector ref, std::map<std::string, ClippedRead> &mapClippedRead, ofstream &fasta_out);
void realign_across_read(BpRln bp_realign, vector<differences_str> &event_aln, Alignment* tmp_aln,
const bioio::FastaIndex index, std::ifstream & fasta, RefVector ref, ofstream &fasta_out);
void add_clipped_reads(Alignment *& tmp, std::vector<aln_str> events, short type, RefVector ref, IntervallTree& bst, TNode *&root, long read_id);
long get_ref_lengths(int id, RefVector ref);
bool add_missed_tra(vector<aln_str> split_events, BpRln bpRln, Alignment* tmp_aln, RefVector ref);
void add_high_error_reads(Alignment *& tmp, RefVector ref, IntervallTree& bst, TNode *&root, long read_id) ;
void detect_bps_for_realn(vector<Breakpoint*> breakpoints, vector<Breakpoint*> breakpoints_rln, const RefVector ref, vector<BpRln> &bp_rlns);
void minimap2(string target_path, string query_path, RefVector ref, IntervallTree & bst_rln_denovo, TNode * &root_rln_denovo);
#endif //SNIFFLES_REALIGN_H
| 35.268908 | 145 | 0.712175 | [
"vector"
] |
969ec99694f6db7e27e9a28fac3208f9f240f7fb | 11,102 | h | C | src/third_party/ssba/Math/v3d_linear_utils.h | jackyspeed/libmv | aae2e0b825b1c933d6e8ec796b8bb0214a508a84 | [
"MIT"
] | 160 | 2015-01-16T19:35:28.000Z | 2022-03-16T02:55:30.000Z | src/third_party/ssba/Math/v3d_linear_utils.h | rgkoo/libmv-blender | cdf65edbb80d8904e2df9a20116d02546df93a81 | [
"MIT"
] | 3 | 2015-04-04T17:54:35.000Z | 2015-12-15T18:09:03.000Z | src/third_party/ssba/Math/v3d_linear_utils.h | rgkoo/libmv-blender | cdf65edbb80d8904e2df9a20116d02546df93a81 | [
"MIT"
] | 51 | 2015-01-12T08:38:12.000Z | 2022-02-19T06:37:25.000Z | // -*- C++ -*-
/*
Copyright (c) 2008 University of North Carolina at Chapel Hill
This file is part of SSBA (Simple Sparse Bundle Adjustment).
SSBA 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 3 of the License, or (at your option) any
later version.
SSBA 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 SSBA. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef V3D_LINEAR_UTILS_H
#define V3D_LINEAR_UTILS_H
#include "Math/v3d_linear.h"
#include <iostream>
namespace V3D
{
template <typename Elem, int Size>
struct InlineVector : public InlineVectorBase<Elem, Size>
{
}; // end struct InlineVector
template <typename Elem>
struct Vector : public VectorBase<Elem>
{
Vector()
: VectorBase<Elem>()
{ }
Vector(unsigned int size)
: VectorBase<Elem>(size)
{ }
Vector(unsigned int size, Elem * values)
: VectorBase<Elem>(size, values)
{ }
Vector(Vector<Elem> const& a)
: VectorBase<Elem>(a)
{ }
Vector<Elem>& operator=(Vector<Elem> const& a)
{
(VectorBase<Elem>::operator=)(a);
return *this;
}
Vector<Elem>& operator+=(Vector<Elem> const& rhs)
{
addVectorsIP(rhs, *this);
return *this;
}
Vector<Elem>& operator*=(Elem scale)
{
scaleVectorsIP(scale, *this);
return *this;
}
Vector<Elem> operator+(Vector<Elem> const& rhs) const
{
Vector<Elem> res(this->size());
addVectors(*this, rhs, res);
return res;
}
Vector<Elem> operator-(Vector<Elem> const& rhs) const
{
Vector<Elem> res(this->size());
subtractVectors(*this, rhs, res);
return res;
}
Elem operator*(Vector<Elem> const& rhs) const
{
return innerProduct(*this, rhs);
}
}; // end struct Vector
template <typename Elem, int Rows, int Cols>
struct InlineMatrix : public InlineMatrixBase<Elem, Rows, Cols>
{
}; // end struct InlineMatrix
template <typename Elem>
struct Matrix : public MatrixBase<Elem>
{
Matrix()
: MatrixBase<Elem>()
{ }
Matrix(unsigned int rows, unsigned int cols)
: MatrixBase<Elem>(rows, cols)
{ }
Matrix(unsigned int rows, unsigned int cols, Elem * values)
: MatrixBase<Elem>(rows, cols, values)
{ }
Matrix(Matrix<Elem> const& a)
: MatrixBase<Elem>(a)
{ }
Matrix<Elem>& operator=(Matrix<Elem> const& a)
{
(MatrixBase<Elem>::operator=)(a);
return *this;
}
Matrix<Elem>& operator+=(Matrix<Elem> const& rhs)
{
addMatricesIP(rhs, *this);
return *this;
}
Matrix<Elem>& operator*=(Elem scale)
{
scaleMatrixIP(scale, *this);
return *this;
}
Matrix<Elem> operator+(Matrix<Elem> const& rhs) const
{
Matrix<Elem> res(this->num_rows(), this->num_cols());
addMatrices(*this, rhs, res);
return res;
}
Matrix<Elem> operator-(Matrix<Elem> const& rhs) const
{
Matrix<Elem> res(this->num_rows(), this->num_cols());
subtractMatrices(*this, rhs, res);
return res;
}
}; // end struct Matrix
//----------------------------------------------------------------------
typedef InlineVector<float, 2> Vector2f;
typedef InlineVector<double, 2> Vector2d;
typedef InlineVector<float, 3> Vector3f;
typedef InlineVector<double, 3> Vector3d;
typedef InlineVector<float, 4> Vector4f;
typedef InlineVector<double, 4> Vector4d;
typedef InlineMatrix<float, 2, 2> Matrix2x2f;
typedef InlineMatrix<double, 2, 2> Matrix2x2d;
typedef InlineMatrix<float, 3, 3> Matrix3x3f;
typedef InlineMatrix<double, 3, 3> Matrix3x3d;
typedef InlineMatrix<float, 4, 4> Matrix4x4f;
typedef InlineMatrix<double, 4, 4> Matrix4x4d;
typedef InlineMatrix<float, 2, 3> Matrix2x3f;
typedef InlineMatrix<double, 2, 3> Matrix2x3d;
typedef InlineMatrix<float, 3, 4> Matrix3x4f;
typedef InlineMatrix<double, 3, 4> Matrix3x4d;
template <typename Elem>
struct VectorArray
{
VectorArray(unsigned count, unsigned size)
: _count(count), _size(size), _values(0), _vectors(0)
{
unsigned const nTotal = _count * _size;
if (count > 0) _vectors = new Vector<Elem>[count];
if (nTotal > 0) _values = new Elem[nTotal];
for (unsigned i = 0; i < _count; ++i) new (&_vectors[i]) Vector<Elem>(_size, _values + i*_size);
}
VectorArray(unsigned count, unsigned size, Elem initVal)
: _count(count), _size(size), _values(0), _vectors(0)
{
unsigned const nTotal = _count * _size;
if (count > 0) _vectors = new Vector<Elem>[count];
if (nTotal > 0) _values = new Elem[nTotal];
for (unsigned i = 0; i < _count; ++i) new (&_vectors[i]) Vector<Elem>(_size, _values + i*_size);
std::fill(_values, _values + nTotal, initVal);
}
~VectorArray()
{
delete [] _values;
delete [] _vectors;
}
unsigned count() const { return _count; }
unsigned size() const { return _size; }
//! Get the submatrix at position ix
Vector<Elem> const& operator[](unsigned ix) const
{
return _vectors[ix];
}
//! Get the submatrix at position ix
Vector<Elem>& operator[](unsigned ix)
{
return _vectors[ix];
}
protected:
unsigned _count, _size;
Elem * _values;
Vector<Elem> * _vectors;
private:
VectorArray(VectorArray const&);
void operator=(VectorArray const&);
};
template <typename Elem>
struct MatrixArray
{
MatrixArray(unsigned count, unsigned nRows, unsigned nCols)
: _count(count), _rows(nRows), _columns(nCols), _values(0), _matrices(0)
{
unsigned const nTotal = _count * _rows * _columns;
if (count > 0) _matrices = new Matrix<Elem>[count];
if (nTotal > 0) _values = new double[nTotal];
for (unsigned i = 0; i < _count; ++i)
new (&_matrices[i]) Matrix<Elem>(_rows, _columns, _values + i*(_rows*_columns));
}
~MatrixArray()
{
delete [] _matrices;
delete [] _values;
}
//! Get the submatrix at position ix
Matrix<Elem> const& operator[](unsigned ix) const
{
return _matrices[ix];
}
//! Get the submatrix at position ix
Matrix<Elem>& operator[](unsigned ix)
{
return _matrices[ix];
}
unsigned count() const { return _count; }
unsigned num_rows() const { return _rows; }
unsigned num_cols() const { return _columns; }
protected:
unsigned _count, _rows, _columns;
double * _values;
Matrix<Elem> * _matrices;
private:
MatrixArray(MatrixArray const&);
void operator=(MatrixArray const&);
};
//----------------------------------------------------------------------
template <typename Elem, int Size>
inline InlineVector<Elem, Size>
operator+(InlineVector<Elem, Size> const& v, InlineVector<Elem, Size> const& w)
{
InlineVector<Elem, Size> res;
addVectors(v, w, res);
return res;
}
template <typename Elem, int Size>
inline InlineVector<Elem, Size>
operator-(InlineVector<Elem, Size> const& v, InlineVector<Elem, Size> const& w)
{
InlineVector<Elem, Size> res;
subtractVectors(v, w, res);
return res;
}
template <typename Elem, int Size>
inline InlineVector<Elem, Size>
operator*(Elem scale, InlineVector<Elem, Size> const& v)
{
InlineVector<Elem, Size> res;
scaleVector(scale, v, res);
return res;
}
template <typename Elem, int Rows, int Cols>
inline InlineVector<Elem, Rows>
operator*(InlineMatrix<Elem, Rows, Cols> const& A, InlineVector<Elem, Cols> const& v)
{
InlineVector<Elem, Rows> res;
multiply_A_v(A, v, res);
return res;
}
template <typename Elem, int RowsA, int ColsA, int ColsB>
inline InlineMatrix<Elem, RowsA, ColsB>
operator*(InlineMatrix<Elem, RowsA, ColsA> const& A, InlineMatrix<Elem, ColsA, ColsB> const& B)
{
InlineMatrix<Elem, RowsA, ColsB> res;
multiply_A_B(A, B, res);
return res;
}
template <typename Elem, int Rows, int Cols>
inline InlineMatrix<Elem, Cols, Rows>
transposedMatrix(InlineMatrix<Elem, Rows, Cols> const& A)
{
InlineMatrix<Elem, Cols, Rows> At;
makeTransposedMatrix(A, At);
return At;
}
template <typename Elem>
inline InlineMatrix<Elem, 3, 3>
invertedMatrix(InlineMatrix<Elem, 3, 3> const& A)
{
Elem a = A[0][0], b = A[0][1], c = A[0][2];
Elem d = A[1][0], e = A[1][1], f = A[1][2];
Elem g = A[2][0], h = A[2][1], i = A[2][2];
Elem const det = a*e*i + b*f*g + c*d*h - c*e*g - b*d*i - a*f*h;
InlineMatrix<Elem, 3, 3> res;
res[0][0] = e*i-f*h; res[0][1] = c*h-b*i; res[0][2] = b*f-c*e;
res[1][0] = f*g-d*i; res[1][1] = a*i-c*g; res[1][2] = c*d-a*f;
res[2][0] = d*h-e*g; res[2][1] = b*g-a*h; res[2][2] = a*e-b*d;
scaleMatrixIP(1.0/det, res);
return res;
}
template <typename Elem>
inline InlineVector<Elem, 2>
makeVector2(Elem a, Elem b)
{
InlineVector<Elem, 2> res;
res[0] = a; res[1] = b;
return res;
}
template <typename Elem>
inline InlineVector<Elem, 3>
makeVector3(Elem a, Elem b, Elem c)
{
InlineVector<Elem, 3> res;
res[0] = a; res[1] = b; res[2] = c;
return res;
}
template <typename Vec>
inline void
displayVector(Vec const& v)
{
using namespace std;
for (int r = 0; r < v.size(); ++r)
cout << v[r] << " ";
cout << endl;
}
template <typename Mat>
inline void
displayMatrix(Mat const& A)
{
using namespace std;
for (int r = 0; r < A.num_rows(); ++r)
{
for (int c = 0; c < A.num_cols(); ++c)
cout << A[r][c] << " ";
cout << endl;
}
}
} // end namespace V3D
#endif
| 28.321429 | 108 | 0.556747 | [
"vector"
] |
96ac427f2472a0ca74abff3fa9d84d9c3fdf8b60 | 9,520 | h | C | OGDF/include/ogdf/internal/energybased/ArrayGraph.h | shahnidhi/MetaCarvel | f3bea5fdbbecec4c9becc6bbdc9585a939eb5481 | [
"MIT"
] | 13 | 2017-12-21T03:35:41.000Z | 2022-01-31T13:45:25.000Z | OGDF/include/ogdf/internal/energybased/ArrayGraph.h | shahnidhi/MetaCarvel | f3bea5fdbbecec4c9becc6bbdc9585a939eb5481 | [
"MIT"
] | 7 | 2017-09-13T01:31:24.000Z | 2021-12-14T00:31:50.000Z | OGDF/include/ogdf/internal/energybased/ArrayGraph.h | shahnidhi/MetaCarvel | f3bea5fdbbecec4c9becc6bbdc9585a939eb5481 | [
"MIT"
] | 15 | 2017-09-07T18:28:55.000Z | 2022-01-18T14:17:43.000Z | /** \file
* \brief Declaration of class ArrayGraph.
*
* \author Martin Gronemann
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.txt in the root directory of the OGDF installation for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* 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.
*
* \par
* 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.
*
* \see http://www.gnu.org/copyleft/gpl.html
***************************************************************/
#ifndef OGDF_ARRAY_GRAPH_H
#define OGDF_ARRAY_GRAPH_H
#include <ogdf/basic/GraphAttributes.h>
namespace ogdf {
//! struct which keeps information aboout incident edges (16 bytes)
struct NodeAdjInfo
{
uint32_t degree; // total count of pairs where is either the first or second node
uint32_t firstEntry; // the first pair in the edges chain
uint32_t lastEntry; // the last pair in the edges chain
uint32_t unused; // not used yet
};
//! struct which keeps information about an edge (16 bytes)
struct EdgeAdjInfo
{
uint32_t a; // first node of the pair
uint32_t b; // second node of the pair
uint32_t a_next;// next pair in the chain of the first node
uint32_t b_next;// next pair in the chain of the second node
};
class ArrayGraph
{
public:
ArrayGraph();
ArrayGraph(uint32_t maxNumNodes, uint32_t maxNumEdges);
ArrayGraph(const GraphAttributes& GA, const EdgeArray<float>& edgeLength, const NodeArray<float>& nodeSize);
~ArrayGraph();
//! returns the number of nodes
/**
* \return the number of nodes
*/
inline uint32_t numNodes() const { return m_numNodes; }
//! returns the number of nodes
/**
* \return the number of nodes
*/
inline uint32_t numEdges() const { return m_numEdges; }
//! updates an array graph from GraphAttributes with the given edge lenghts and node sizes and creates the edges;
/**
* The nodes and edges are ordered in the same way like in the Graph instance.
* @param GA the GraphAttributes to read from
* @param edgeLength the desired edge length
*/
void readFrom(const GraphAttributes& GA, const EdgeArray<float>& edgeLength, const NodeArray<float>& nodeSize);
//! updates an array graph with the given positions, edge lenghts and node sizes and creates the edges
/**
* The nodes and edges are ordered in the same way like in the Graph instance.
* @param G the Graph to traverse
* @param xPos the x coordinate for each node
* @param yPos the y coordinate for each node
* @param nodeSize the x coordinate for each node in G
* @param edgeLength the desired edge length for each edge
*/
template<typename C_T, typename E_T, typename S_T>
void readFrom(const Graph& G, NodeArray<C_T>& xPos, NodeArray<C_T>& yPos, const EdgeArray<E_T>& edgeLength, const NodeArray<S_T>& nodeSize)
{
m_numNodes = 0;
m_numEdges = 0;
NodeArray<uint32_t> nodeIndex(G);
m_numNodes = 0;
m_numEdges = 0;
m_desiredAvgEdgeLength = 0;
m_avgNodeSize = 0;
for(node v : G.nodes)
{
m_nodeXPos[m_numNodes] = (float)xPos[v];
m_nodeYPos[m_numNodes] = (float)yPos[v];
m_nodeSize[m_numNodes] = (float)nodeSize[v];
m_avgNodeSize += nodeSize[v];
nodeIndex[v] = m_numNodes;
m_numNodes++;
}
m_avgNodeSize = m_avgNodeSize / (double)m_numNodes;
for(edge e : G.edges)
{
pushBackEdge(nodeIndex[e->source()], nodeIndex[e->target()], (float)edgeLength[e]);
}
m_desiredAvgEdgeLength = m_desiredAvgEdgeLength / (double)m_numEdges;
}
//! writes the data back to GraphAttributes
/**
* The function does not require to be the same Graph, only the order of nodes and edges
* is important
* @param GA the GraphAttributes to update
*/
void writeTo(GraphAttributes& GA);
//! writes the data back to node arrays with the given coordinate type
/**
* The function does not require to be the same Graph, only the order of nodes and edges
* is important
* @param xPos the x coordinate array to update
* @param yPos the y coordinate array to update
*/
template<typename C_T>
void writeTo(const Graph& G, NodeArray<C_T>& xPos, NodeArray<C_T>& yPos)
{
uint32_t i = 0;
for(node v : G.nodes)
{
xPos[v] = m_nodeXPos[i];
yPos[v] = m_nodeYPos[i];
i++;
}
}
//! returns the adjacency information for a node
inline NodeAdjInfo& nodeInfo(uint32_t i) { return m_nodeAdj[i]; }
//! returns the adjacency information for a node
inline const NodeAdjInfo& nodeInfo(uint32_t i) const { return m_nodeAdj[i]; }
//! returns the adjacency information for an edge
inline EdgeAdjInfo& edgeInfo(uint32_t i) { return m_edgeAdj[i]; }
//! returns the adjacency information for an edge
inline const EdgeAdjInfo& edgeInfo(uint32_t i) const { return m_edgeAdj[i]; }
//! returns the NodeAdjInfo array for all nodes
/**
* The array is 16 byte aligned
*/
inline NodeAdjInfo* nodeInfo() { return m_nodeAdj; }
//! returns the NodeAdjInfo array for all nodes
/**
* The array is 16 byte aligned
*/
inline const NodeAdjInfo* nodeInfo() const { return m_nodeAdj; }
//! returns the EdgeAdjInfo array for all edges
/**
* The array is 16 byte aligned
*/
inline EdgeAdjInfo* edgeInfo() { return m_edgeAdj; }
//! returns the EdgeAdjInfo array for all edges
/**
* The array is 16 byte aligned
*/
inline const EdgeAdjInfo* edgeInfo() const { return m_edgeAdj; }
//! returns the x coord array for all nodes
/**
* The array is 16 byte aligned
*/
inline float* nodeXPos() { return m_nodeXPos; }
//! returns the x coord array for all nodes
/**
* The array is 16 byte aligned
*/
inline const float* nodeXPos() const { return m_nodeXPos; }
//! returns the y coord array for all nodes
/**
* The array is 16 byte aligned
*/
inline float* nodeYPos() { return m_nodeYPos; }
//! returns the y coord array for all nodes
/**
* The array is 16 byte aligned
*/
inline const float* nodeYPos() const { return m_nodeYPos; }
//! returns the node size array for all nodes
/**
* The array is 16 byte aligned
*/
inline float* nodeSize() { return m_nodeSize; }
//! returns the node movement radius array for all nodes
/**
* The array is 16 byte aligned
*/
inline float* nodeMoveRadius() { return m_nodeMoveRadius; }
//! returns the node size array for all nodes
/**
* The array is 16 byte aligned
*/
inline const float* nodeSize() const { return m_nodeSize; }
//! returns the edge length array for all edges
/**
* The array is 16 byte aligned
*/
inline float* desiredEdgeLength() { return m_desiredEdgeLength; }
//! returns the edge length array for all edges
/**
* The array is 16 byte aligned
*/
inline const float* desiredEdgeLength() const { return m_desiredEdgeLength; }
//! returns the index of the first pair of node node
inline uint32_t firstEdgeAdjIndex(uint32_t nodeIndex) const
{
return nodeInfo(nodeIndex).firstEntry;
};
//! returns the index of the next pair of curr for node a
inline uint32_t nextEdgeAdjIndex(uint32_t currEdgeAdjIndex, uint32_t nodeIndex) const
{
const EdgeAdjInfo& currInfo = edgeInfo(currEdgeAdjIndex);
if (currInfo.a == nodeIndex)
return currInfo.a_next;
return currInfo.b_next;
}
//! returns the other node a is paired with in pair with the given index
inline uint32_t twinNodeIndex(uint32_t currEdgeAdjIndex, uint32_t nodeIndex) const
{
const EdgeAdjInfo& currInfo = edgeInfo(currEdgeAdjIndex);
if (currInfo.a == nodeIndex)
return currInfo.b;
return currInfo.a;
}
template<typename Func>
void for_all_nodes(uint32_t begin, uint32_t end, Func func)
{
for(uint32_t i=begin; i <=end; i++)
func(i);
}
inline float avgDesiredEdgeLength() const { return (float)m_desiredAvgEdgeLength; }
inline float avgNodeSize() const { return (float)m_avgNodeSize; }
void transform(float translate, float scale);
void centerGraph();
private:
//! internal function used by readFrom
void pushBackEdge(uint32_t a, uint32_t b, float desiredEdgeLength);
//! internal function used allocate all arrays
void allocate(uint32_t numNodes, uint32_t numEdges);
//! internal function used allocate all arrays
void deallocate();
//! internal function used to clear the arrays
void clear()
{
for (uint32_t i=0; i < m_numNodes; i++)
nodeInfo(i).degree = 0;
m_numNodes = 0;
m_numEdges = 0;
}
//! number of nodes in the graph
uint32_t m_numNodes;
//! number of edges in the graph
uint32_t m_numEdges;
//! x coordinates
float* m_nodeXPos;
//! x coordinates
float* m_nodeYPos;
//! size of the node
float* m_nodeSize;
//! avg node size
double m_avgNodeSize;
//! maximum node movement length
float* m_nodeMoveRadius;
//! edge length
float* m_desiredEdgeLength;
//! avg edge length
double m_desiredAvgEdgeLength;
//! information about adjacent edges
NodeAdjInfo* m_nodeAdj;
//! information about adjacent nodes
EdgeAdjInfo* m_edgeAdj;
};
} // end of namespace ogdf
#endif
| 27.836257 | 140 | 0.709874 | [
"transform"
] |
96acd1a0bec7943a4024b066e037aa3ded4dbc4b | 3,497 | h | C | Source/Lib/Decoder/Codec/EbDecParseHelper.h | CoreySeeVCD/SVT-AV1 | a29d766d8ccf6c971640358be133d489872b2ce5 | [
"BSD-2-Clause-Patent",
"BSD-2-Clause"
] | 1 | 2019-08-01T06:11:30.000Z | 2019-08-01T06:11:30.000Z | Source/Lib/Decoder/Codec/EbDecParseHelper.h | CoreySeeVCD/SVT-AV1 | a29d766d8ccf6c971640358be133d489872b2ce5 | [
"BSD-2-Clause-Patent",
"BSD-2-Clause"
] | null | null | null | Source/Lib/Decoder/Codec/EbDecParseHelper.h | CoreySeeVCD/SVT-AV1 | a29d766d8ccf6c971640358be133d489872b2ce5 | [
"BSD-2-Clause-Patent",
"BSD-2-Clause"
] | 1 | 2020-09-09T12:26:08.000Z | 2020-09-09T12:26:08.000Z | /*
* Copyright(c) 2019 Netflix, Inc.
* SPDX - License - Identifier: BSD - 2 - Clause - Patent
*/
#ifndef EbDecParseHelper_h
#define EbDecParseHelper_h
#include "EbObuParse.h"
#include "EbDecParseFrame.h"
#include "EbUtility.h"
#define ACCT_STR __func__
#define ZERO_ARRAY(dest, n) memset(dest, 0, n * sizeof(*(dest)))
typedef struct MvCount {
uint8_t newmv_count;
uint8_t num_mv_found[MODE_CTX_REF_FRAMES];
uint8_t found_above_match;
uint8_t found_left_match;
} MvCount;
static INLINE CflAllowedType is_cfl_allowed(PartitionInfo *xd, EbColorConfig *color_cfg,
uint8_t *lossless_array) {
const BlockModeInfo *mbmi = xd->mi;
const BlockSize bsize = mbmi->sb_type;
assert(bsize < BlockSizeS_ALL);
if (lossless_array[mbmi->segment_id]) {
// In lossless, CfL is available when the partition size is equal to the
// transform size.
const int ssx = color_cfg->subsampling_x;
const int ssy = color_cfg->subsampling_y;
const int plane_bsize = get_plane_block_size(bsize, ssx, ssy);
return (CflAllowedType)(plane_bsize == BLOCK_4X4);
}
// Spec: CfL is available to luma partitions lesser than or equal to 32x32
return (CflAllowedType)(block_size_wide[bsize] <= 32 && block_size_high[bsize] <= 32);
}
//extern int is_inter_block(const BlockModeInfo *mbmi);
static INLINE int allow_palette(int allow_screen_content_tools, BlockSize sb_type) {
return allow_screen_content_tools && block_size_wide[sb_type] <= 64 &&
block_size_high[sb_type] <= 64 && sb_type >= BLOCK_8X8;
}
static INLINE int max_block_wide(PartitionInfo *part_info, int plane_bsize, int subx) {
int max_blocks_wide = block_size_wide[plane_bsize];
if (part_info->mb_to_right_edge < 0)
max_blocks_wide += part_info->mb_to_right_edge >> (3 + subx);
//Scale width in the transform block unit.
return max_blocks_wide >> tx_size_wide_log2[0];
}
static INLINE int max_block_high(PartitionInfo *part_info, int plane_bsize, int suby) {
int max_blocks_high = block_size_high[plane_bsize];
if (part_info->mb_to_bottom_edge < 0)
max_blocks_high += part_info->mb_to_bottom_edge >> (3 + suby);
// Scale the height in the transform block unit.
return max_blocks_high >> tx_size_high_log2[0];
}
TxSize read_selected_tx_size(PartitionInfo *xd, ParseCtxt *parse_ctxt);
PredictionMode read_intra_mode(SvtReader *r, AomCdfProb *cdf);
UvPredictionMode read_intra_mode_uv(FRAME_CONTEXT *ec_ctx, SvtReader *r, CflAllowedType cfl_allowed,
PredictionMode y_mode);
IntMv gm_get_motion_vector(const GlobalMotionParams *gm, int allow_hp, BlockSize bsize, int mi_col,
int mi_row, int is_integer);
void set_segment_id(EbDecHandle *dec_handle, int mi_offset, int x_mis, int y_mis, int segment_id);
void update_tx_context(ParseCtxt *parse_ctxt, PartitionInfo *pi, BlockSize bsize, TxSize tx_size,
int blk_row, int blk_col);
int neg_deinterleave(const int diff, int ref, int max);
int get_intra_inter_context(PartitionInfo *xd);
int get_comp_reference_type_context(const PartitionInfo *xd);
int seg_feature_active(SegmentationParams *seg, int segment_id, SEG_LVL_FEATURES feature_id);
int find_warp_samples(EbDecHandle *dec_handle, TileInfo *tile, PartitionInfo *pi, int *pts,
int *pts_inref);
#endif // EbDecParseHelper_h
| 42.646341 | 100 | 0.714041 | [
"transform"
] |
96adaff154c49736cec781bc93a9caddea9e3ae7 | 577 | h | C | WDZSDK/Classes/headers/WDZAlarmSettingDeviceTableViewCell.h | DanielOYC/WDZSDK | 6ef97eabfd0e9094b857a87a563b8029db04b0e5 | [
"MIT"
] | null | null | null | WDZSDK/Classes/headers/WDZAlarmSettingDeviceTableViewCell.h | DanielOYC/WDZSDK | 6ef97eabfd0e9094b857a87a563b8029db04b0e5 | [
"MIT"
] | null | null | null | WDZSDK/Classes/headers/WDZAlarmSettingDeviceTableViewCell.h | DanielOYC/WDZSDK | 6ef97eabfd0e9094b857a87a563b8029db04b0e5 | [
"MIT"
] | null | null | null | //
// WDZAlarmSettingDeviceTableViewCell.h
// WDZForAppStore
//
// Created by ovopark_iOS1 on 2018/3/21.
// Copyright © 2018年 Wandianzhang. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "WDZAlarmShopDeviceModel.h"
@protocol WDZAlarmSettingDeviceTableViewCellDelegate <NSObject>
-(void)WDZAlarmSettingDeviceTableViewCellDidSelected;
@end
@interface WDZAlarmSettingDeviceTableViewCell : UITableViewCell
@property (nonatomic , strong)WDZAlarmShopDeviceModel *model;
@property (nonatomic , weak)id<WDZAlarmSettingDeviceTableViewCellDelegate > delegate;
@end
| 23.08 | 85 | 0.804159 | [
"model"
] |
96ae7a8e3aabd621d37429f48efe5db86a411065 | 8,067 | c | C | nitan/adm/daemons/punishd.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | 1 | 2019-03-27T07:25:16.000Z | 2019-03-27T07:25:16.000Z | nitan/adm/daemons/punishd.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | nitan/adm/daemons/punishd.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | // punish the berays user
#include <ansi.h>
#pragma optimize
#pragma save_binary
inherit F_DBASE;
void create()
{
seteuid(ROOT_UID);
set("channel_id", "執法精靈");
CHANNEL_D->do_channel( this_object(), "sys", "執法精靈已經啟動。");
remove_call_out("monitor");
call_out("monitor", 1);
}
int clean_up() { return 1; }
void family_punish();
string *punishers = ({
CLASS_D("xiakedao") + "/zhangsan",
CLASS_D("xiakedao") + "/lisi",
});
string *catchers = ({
CLASS_D("misc") + "/zhang",
});
mapping family_punishers = ([
"武當派" : ({ CLASS_D("misc") + "/chongxu" }),
"少林寺" : ({ CLASS_D("misc") + "/fangsheng" }),
"華山派" : ({ CLASS_D("misc") + "/murenqing" }),
"華山劍宗" : ({ CLASS_D("misc") + "/murenqing" }),
"峨嵋派" : ({ CLASS_D("misc") + "/guoxiang" }),
"桃花島" : ({ CLASS_D("misc") + "/taogu" }),
"神龍教" : ({ CLASS_D("misc") + "/zhong" }),
"丐幫" : ({ CLASS_D("misc") + "/wangjiantong" }),
"古墓派" : ({ CLASS_D("misc") + "/popo" }),
"全真教" : ({ CLASS_D("misc") + "/laodao" }),
"星宿派" : ({ CLASS_D("misc") + "/xiaoxian" }),
"逍遙派" : ({ CLASS_D("misc") + "/liqiushui" }),
"雪山寺" : ({ CLASS_D("misc") + "/laoseng" }),
"血刀門" : ({ CLASS_D("misc") + "/hongri" }),
"靈鷲宮" : ({ CLASS_D("misc") + "/tonglao" }),
"慕容世家" : ({ CLASS_D("misc") + "/furen" }),
"歐陽世家" : ({ CLASS_D("misc") + "/laonu" }),
"關外胡家" : ({ CLASS_D("misc") + "/huyidao" }),
"段氏皇族" : ({ CLASS_D("misc") + "/duansh" }),
"嵩山" : ({ CLASS_D("misc") + "/songshan" }),
"衡山" : ({ CLASS_D("misc") + "/hengshan" }),
"明教" : ({ CLASS_D("misc") + "/bosi" }),
"魔教" : ({ CLASS_D("misc") + "/chiyou" }),
"紅花會" : ({ CLASS_D("misc") + "/yuwanting" }),
"日月神教" : ({ CLASS_D("misc") + "/zhanglao" }),
// add by wuji
"五毒教" : ({ CLASS_D("misc") + "/wudu" }),
"唐門世家" : ({ CLASS_D("misc") + "/tangmen" }),
"凌霄城" : ({ CLASS_D("misc") + "/lingxiao" }),
"鐵掌幫" : ({ CLASS_D("misc") + "/tiezhang" }),
"絕情谷" : ({ CLASS_D("misc") + "/jueqing" }),
"崑崙派" : ({ CLASS_D("misc") + "/kunlun" }),
]);
void monitor()
{
int i;
object *obs;
string *aviable;
string punisher;
string catcher;
string msg;
remove_call_out("monitor");
call_out("monitor", 180 + random(60));
/*
if (VERSION_D->is_boot_synchronizing())
// 正在啟動中同步版本?那麼不啟動懲罰系統
return;
*/
// when the pking was going, I won't let the punisher out,
// because the competitor may in PKD.
if (PK_D->is_pking())
return;
CHANNEL_D->do_channel(this_object(), "sys",
"各大門派掃描所有在線玩家。");
// search all the player for punishing
obs = filter_array(users(),
(: query("combat_exp", $1) >= 100000 &&
query("pk_score", $1) >= 8 &&
! $1->is_in_prison() &&
! $1->is_ghost() &&
! wizardp($1) &&
environment($1) :));
if (sizeof(obs))
{
obs = sort_array(obs, (: query("combat_exp", $2) -
query("combat_exp", $1):));
aviable = filter_array(catchers, (: ! find_object($1) :));
i = 0;
while (sizeof(aviable) && i < sizeof(obs))
{
punisher = aviable[random(sizeof(aviable))];
punisher->catch_ob(obs[i]);
aviable -= ({ punisher });
i++;
}
}
// search all the player for killing
obs = filter_array(users(),
(: query("combat_exp", $1) >= 100000 &&
query("combat/need_punish", $1) &&
! $1->is_in_prison() &&
! $1->is_ghost() &&
! wizardp($1) &&
environment($1) :));
if (sizeof(obs))
{
obs = sort_array(obs, (: query("combat_exp", $2) -
query("combat_exp", $1):));
aviable = filter_array(punishers, (: ! find_object($1) :));
i = 0;
while (sizeof(aviable) && i < sizeof(obs))
{
msg=query("combat/need_punish", obs[i]);
punisher = aviable[random(sizeof(aviable))];
punisher->start_punish(obs[i], msg);
aviable -= ({ punisher });
i++;
}
}
// search all the player for catching
obs = filter_array(users(),
(: query("combat_exp", $1)<300000 &&
$1->query_condition("killer") &&
! $1->is_ghost() &&
! $1->is_in_prison() &&
! wizardp($1) &&
environment($1) :));
if (sizeof(obs))
{
obs = sort_array(obs, (: query("combat_exp", $2) -
query("combat_exp", $1):));
aviable = filter_array(catchers, (: ! find_object($1) :));
i = 0;
while (sizeof(aviable) && i < sizeof(obs))
{
punisher = aviable[random(sizeof(aviable))];
punisher->start_catch(obs[i]);
aviable -= ({ punisher });
i++;
}
}
// Normal I won't check the player
if (random(10) == 0 || 1)
family_punish();
}
void family_punish()
{
object ob;
object *obs;
mapping betrayer;
string *punishers;
string punisher;
string key;
obs = filter_array(users(), (: query("combat_exp", $1) >= 100000 &&
environment($1) &&
!query("no_fight", environment($1)) &&
mapp(query("betrayer", $1)):));
if (! sizeof(obs))
return;
foreach (ob in obs)
{
betrayer=query("betrayer", ob);
foreach (key in keys(betrayer))
{
if (key == "times") continue;
if (! arrayp(punishers = family_punishers[key]))
{
addn("detach/"+key, 1, ob);
addn("detach/times", 1, ob);
betrayer["times"] -= betrayer[key];
map_delete(betrayer, key);
if (betrayer["times"] < 1)
delete("betrayer", ob);
continue;
}
punishers = filter_array(punishers, (: ! find_object($1) :));
if (! sizeof(punishers))
// No punishers aviable now
continue;
punisher = punishers[random(sizeof(punishers))];
if (file_size(punisher + ".c") < 0)
{
log_file("static/log", "can not find punisher: "
+ punisher + "\n");
break;
}
punisher->start_punish(ob, key);
break;
}
}
}
| 36.502262 | 85 | 0.379323 | [
"object"
] |
96afec6e3227bb4827b9c7a08d52c66d72802c9b | 169,682 | h | C | Source/GeneratedServices/DisplayVideo/GTLRDisplayVideoQuery.h | karimhm/google-api-objectivec-client-for-rest | bc2d7b0a05cd54d6f4843d587e2bc31d0ab1629e | [
"Apache-2.0"
] | null | null | null | Source/GeneratedServices/DisplayVideo/GTLRDisplayVideoQuery.h | karimhm/google-api-objectivec-client-for-rest | bc2d7b0a05cd54d6f4843d587e2bc31d0ab1629e | [
"Apache-2.0"
] | null | null | null | Source/GeneratedServices/DisplayVideo/GTLRDisplayVideoQuery.h | karimhm/google-api-objectivec-client-for-rest | bc2d7b0a05cd54d6f4843d587e2bc31d0ab1629e | [
"Apache-2.0"
] | null | null | null | // NOTE: This file was generated by the ServiceGenerator.
// ----------------------------------------------------------------------------
// API:
// Display & Video 360 API (displayvideo/v1)
// Description:
// Display & Video 360 API allows users to manage and create campaigns and
// reports.
// Documentation:
// https://developers.google.com/display-video/
#if GTLR_BUILT_AS_FRAMEWORK
#import "GTLR/GTLRQuery.h"
#else
#import "GTLRQuery.h"
#endif
#if GTLR_RUNTIME_VERSION != 3000
#error This file was generated by a different version of ServiceGenerator which is incompatible with this GTLR library source.
#endif
@class GTLRDisplayVideo_Advertiser;
@class GTLRDisplayVideo_AssignedTargetingOption;
@class GTLRDisplayVideo_BulkEditLineItemAssignedTargetingOptionsRequest;
@class GTLRDisplayVideo_Campaign;
@class GTLRDisplayVideo_CreateAssetRequest;
@class GTLRDisplayVideo_CreateSdfDownloadTaskRequest;
@class GTLRDisplayVideo_Creative;
@class GTLRDisplayVideo_FloodlightGroup;
@class GTLRDisplayVideo_InsertionOrder;
@class GTLRDisplayVideo_LineItem;
// Generated comments include content from the discovery document; avoid them
// causing warnings since clang's checks are some what arbitrary.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdocumentation"
NS_ASSUME_NONNULL_BEGIN
// ----------------------------------------------------------------------------
// Constants - For some of the query classes' properties below.
// ----------------------------------------------------------------------------
// targetingType
/** Value: "TARGETING_TYPE_AGE_RANGE" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeAgeRange;
/** Value: "TARGETING_TYPE_APP" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeApp;
/** Value: "TARGETING_TYPE_APP_CATEGORY" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeAppCategory;
/** Value: "TARGETING_TYPE_AUDIENCE_GROUP" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeAudienceGroup;
/** Value: "TARGETING_TYPE_AUTHORIZED_SELLER_STATUS" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeAuthorizedSellerStatus;
/** Value: "TARGETING_TYPE_BROWSER" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeBrowser;
/** Value: "TARGETING_TYPE_CARRIER_AND_ISP" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeCarrierAndIsp;
/** Value: "TARGETING_TYPE_CATEGORY" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeCategory;
/** Value: "TARGETING_TYPE_CHANNEL" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeChannel;
/** Value: "TARGETING_TYPE_CONTENT_INSTREAM_POSITION" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeContentInstreamPosition;
/** Value: "TARGETING_TYPE_CONTENT_OUTSTREAM_POSITION" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeContentOutstreamPosition;
/** Value: "TARGETING_TYPE_DAY_AND_TIME" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeDayAndTime;
/** Value: "TARGETING_TYPE_DEVICE_MAKE_MODEL" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceMakeModel;
/** Value: "TARGETING_TYPE_DEVICE_TYPE" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceType;
/** Value: "TARGETING_TYPE_DIGITAL_CONTENT_LABEL_EXCLUSION" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeDigitalContentLabelExclusion;
/** Value: "TARGETING_TYPE_ENVIRONMENT" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeEnvironment;
/** Value: "TARGETING_TYPE_EXCHANGE" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeExchange;
/** Value: "TARGETING_TYPE_GENDER" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeGender;
/** Value: "TARGETING_TYPE_GEO_REGION" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeGeoRegion;
/** Value: "TARGETING_TYPE_HOUSEHOLD_INCOME" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeHouseholdIncome;
/** Value: "TARGETING_TYPE_INVENTORY_SOURCE" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySource;
/** Value: "TARGETING_TYPE_INVENTORY_SOURCE_GROUP" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySourceGroup;
/** Value: "TARGETING_TYPE_KEYWORD" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeKeyword;
/** Value: "TARGETING_TYPE_LANGUAGE" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeLanguage;
/** Value: "TARGETING_TYPE_NEGATIVE_KEYWORD_LIST" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeNegativeKeywordList;
/** Value: "TARGETING_TYPE_ON_SCREEN_POSITION" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeOnScreenPosition;
/** Value: "TARGETING_TYPE_OPERATING_SYSTEM" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeOperatingSystem;
/** Value: "TARGETING_TYPE_PARENTAL_STATUS" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeParentalStatus;
/** Value: "TARGETING_TYPE_PROXIMITY_LOCATION" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocation;
/** Value: "TARGETING_TYPE_PROXIMITY_LOCATION_LIST" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocationList;
/** Value: "TARGETING_TYPE_REGIONAL_LOCATION_LIST" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeRegionalLocationList;
/** Value: "TARGETING_TYPE_SENSITIVE_CATEGORY_EXCLUSION" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeSensitiveCategoryExclusion;
/** Value: "TARGETING_TYPE_SUB_EXCHANGE" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeSubExchange;
/** Value: "TARGETING_TYPE_THIRD_PARTY_VERIFIER" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeThirdPartyVerifier;
/** Value: "TARGETING_TYPE_UNSPECIFIED" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeUnspecified;
/** Value: "TARGETING_TYPE_URL" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeUrl;
/** Value: "TARGETING_TYPE_USER_REWARDED_CONTENT" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeUserRewardedContent;
/** Value: "TARGETING_TYPE_VIDEO_PLAYER_SIZE" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeVideoPlayerSize;
/** Value: "TARGETING_TYPE_VIEWABILITY" */
FOUNDATION_EXTERN NSString * const kGTLRDisplayVideoTargetingTypeTargetingTypeViewability;
// ----------------------------------------------------------------------------
// Query Classes
//
/**
* Parent class for other Display Video query classes.
*/
@interface GTLRDisplayVideoQuery : GTLRQuery
/** Selector specifying which fields to include in a partial response. */
@property(nonatomic, copy, nullable) NSString *fields;
@end
/**
* Uploads an asset.
* Returns the ID of the newly uploaded asset if successful.
* The asset file size should be no more than 10 MB for images, 200 MB for
* ZIP files, and 1 GB for videos.
*
* Method: displayvideo.advertisers.assets.upload
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersAssetsUpload : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersAssetsUploadWithObject:advertiserId:]
/** Required. The ID of the advertiser this asset belongs to. */
@property(nonatomic, assign) long long advertiserId;
/**
* Fetches a @c GTLRDisplayVideo_CreateAssetResponse.
*
* Uploads an asset.
* Returns the ID of the newly uploaded asset if successful.
* The asset file size should be no more than 10 MB for images, 200 MB for
* ZIP files, and 1 GB for videos.
*
* @param object The @c GTLRDisplayVideo_CreateAssetRequest to include in the
* query.
* @param advertiserId Required. The ID of the advertiser this asset belongs
* to.
* @param uploadParameters The media to include in this query. Accepted MIME
* type: * / *
*
* @return GTLRDisplayVideoQuery_AdvertisersAssetsUpload
*/
+ (instancetype)queryWithObject:(GTLRDisplayVideo_CreateAssetRequest *)object
advertiserId:(long long)advertiserId
uploadParameters:(nullable GTLRUploadParameters *)uploadParameters;
@end
/**
* Creates a new campaign.
* Returns the newly created campaign if successful.
*
* Method: displayvideo.advertisers.campaigns.create
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersCampaignsCreate : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersCampaignsCreateWithObject:advertiserId:]
/** Output only. The unique ID of the advertiser the campaign belongs to. */
@property(nonatomic, assign) long long advertiserId;
/**
* Fetches a @c GTLRDisplayVideo_Campaign.
*
* Creates a new campaign.
* Returns the newly created campaign if successful.
*
* @param object The @c GTLRDisplayVideo_Campaign to include in the query.
* @param advertiserId Output only. The unique ID of the advertiser the
* campaign belongs to.
*
* @return GTLRDisplayVideoQuery_AdvertisersCampaignsCreate
*/
+ (instancetype)queryWithObject:(GTLRDisplayVideo_Campaign *)object
advertiserId:(long long)advertiserId;
@end
/**
* Permanently deletes a campaign. A deleted campaign cannot be recovered.
* The campaign should be archived first, i.e. set
* entity_status to `ENTITY_STATUS_ARCHIVED`, to be
* able to delete it.
*
* Method: displayvideo.advertisers.campaigns.delete
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersCampaignsDelete : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersCampaignsDeleteWithadvertiserId:campaignId:]
/** The ID of the advertiser this campaign belongs to. */
@property(nonatomic, assign) long long advertiserId;
/** The ID of the campaign we need to delete. */
@property(nonatomic, assign) long long campaignId;
/**
* Fetches a @c GTLRDisplayVideo_Empty.
*
* Permanently deletes a campaign. A deleted campaign cannot be recovered.
* The campaign should be archived first, i.e. set
* entity_status to `ENTITY_STATUS_ARCHIVED`, to be
* able to delete it.
*
* @param advertiserId The ID of the advertiser this campaign belongs to.
* @param campaignId The ID of the campaign we need to delete.
*
* @return GTLRDisplayVideoQuery_AdvertisersCampaignsDelete
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId
campaignId:(long long)campaignId;
@end
/**
* Gets a campaign.
*
* Method: displayvideo.advertisers.campaigns.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersCampaignsGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersCampaignsGetWithadvertiserId:campaignId:]
/** Required. The ID of the advertiser this campaign belongs to. */
@property(nonatomic, assign) long long advertiserId;
/** Required. The ID of the campaign to fetch. */
@property(nonatomic, assign) long long campaignId;
/**
* Fetches a @c GTLRDisplayVideo_Campaign.
*
* Gets a campaign.
*
* @param advertiserId Required. The ID of the advertiser this campaign belongs
* to.
* @param campaignId Required. The ID of the campaign to fetch.
*
* @return GTLRDisplayVideoQuery_AdvertisersCampaignsGet
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId
campaignId:(long long)campaignId;
@end
/**
* Lists campaigns in an advertiser.
* The order is defined by the order_by
* parameter.
* If a filter by
* entity_status is not specified, campaigns with
* `ENTITY_STATUS_ARCHIVED` will not be included in the results.
*
* Method: displayvideo.advertisers.campaigns.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersCampaignsList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersCampaignsListWithadvertiserId:]
/** The ID of the advertiser to list campaigns for. */
@property(nonatomic, assign) long long advertiserId;
/**
* Allows filtering by campaign properties.
* Supported syntax:
* * Filter expressions are made up of one or more restrictions.
* * Restrictions can be combined by `AND` or `OR` logical operators. A
* sequence of restrictions implicitly uses `AND`.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be `EQUALS (=)`.
* * Supported fields:
* - `entityStatus`
* Examples:
* * All `ENTITY_STATUS_ACTIVE` or `ENTITY_STATUS_PAUSED` campaigns under an
* advertiser:
* `(entityStatus="ENTITY_STATUS_ACTIVE" OR
* entityStatus="ENTITY_STATUS_PAUSED")`
* The length of this field should be no more than 500 characters.
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Field by which to sort the list.
* Acceptable values are:
* * `displayName` (default)
* * `entityStatus`
* The default sorting order is ascending. To specify descending order for
* a field, a suffix "desc" should be added to the field name. Example:
* `displayName desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size. Must be between `1` and `100`. If unspecified will
* default to `100`.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token returned from the
* previous call to `ListCampaigns` method. If not specified, the first page
* of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/**
* Fetches a @c GTLRDisplayVideo_ListCampaignsResponse.
*
* Lists campaigns in an advertiser.
* The order is defined by the order_by
* parameter.
* If a filter by
* entity_status is not specified, campaigns with
* `ENTITY_STATUS_ARCHIVED` will not be included in the results.
*
* @param advertiserId The ID of the advertiser to list campaigns for.
*
* @return GTLRDisplayVideoQuery_AdvertisersCampaignsList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId;
@end
/**
* Updates an existing campaign.
* Returns the updated campaign if successful.
*
* Method: displayvideo.advertisers.campaigns.patch
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersCampaignsPatch : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersCampaignsPatchWithObject:advertiserId:campaignId:]
/** Output only. The unique ID of the advertiser the campaign belongs to. */
@property(nonatomic, assign) long long advertiserId;
/** Output only. The unique ID of the campaign. Assigned by the system. */
@property(nonatomic, assign) long long campaignId;
/**
* Required. The mask to control which fields to update.
*
* String format is a comma-separated list of fields.
*/
@property(nonatomic, copy, nullable) NSString *updateMask;
/**
* Fetches a @c GTLRDisplayVideo_Campaign.
*
* Updates an existing campaign.
* Returns the updated campaign if successful.
*
* @param object The @c GTLRDisplayVideo_Campaign to include in the query.
* @param advertiserId Output only. The unique ID of the advertiser the
* campaign belongs to.
* @param campaignId Output only. The unique ID of the campaign. Assigned by
* the system.
*
* @return GTLRDisplayVideoQuery_AdvertisersCampaignsPatch
*/
+ (instancetype)queryWithObject:(GTLRDisplayVideo_Campaign *)object
advertiserId:(long long)advertiserId
campaignId:(long long)campaignId;
@end
/**
* Gets a channel for a partner or advertiser.
*
* Method: displayvideo.advertisers.channels.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersChannelsGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersChannelsGetWithadvertiserId:channelId:]
/** The ID of the advertiser that owns the fetched channel. */
@property(nonatomic, assign) long long advertiserId;
/** Required. The ID of the channel to fetch. */
@property(nonatomic, assign) long long channelId;
/** The ID of the partner that owns the fetched channel. */
@property(nonatomic, assign) long long partnerId;
/**
* Fetches a @c GTLRDisplayVideo_Channel.
*
* Gets a channel for a partner or advertiser.
*
* @param advertiserId The ID of the advertiser that owns the fetched channel.
* @param channelId Required. The ID of the channel to fetch.
*
* @return GTLRDisplayVideoQuery_AdvertisersChannelsGet
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId
channelId:(long long)channelId;
@end
/**
* Lists channels for a partner or advertiser.
*
* Method: displayvideo.advertisers.channels.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersChannelsList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersChannelsListWithadvertiserId:]
/** The ID of the advertiser that owns the channels. */
@property(nonatomic, assign) long long advertiserId;
/**
* Allows filtering by channel fields.
* Supported syntax:
* * Filter expressions for channel currently can only contain at most one
* * restriction.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be `CONTAINS (:)`.
* * Supported fields:
* - `displayName`
* Examples:
* * All channels for which the display name contains "google":
* `displayName : "google"`.
* The length of this field should be no more than 500 characters.
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Field by which to sort the list.
* Acceptable values are:
* * `displayName` (default)
* * `channelId`
* The default sorting order is ascending. To specify descending order for a
* field, a suffix " desc" should be added to the field name. Example:
* `displayName desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size. Must be between `1` and `100`. If unspecified will
* default to `100`. Returns error code `INVALID_ARGUMENT` if an invalid value
* is specified.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token returned from the
* previous call to `ListChannels` method. If not specified, the first page
* of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/** The ID of the partner that owns the channels. */
@property(nonatomic, assign) long long partnerId;
/**
* Fetches a @c GTLRDisplayVideo_ListChannelsResponse.
*
* Lists channels for a partner or advertiser.
*
* @param advertiserId The ID of the advertiser that owns the channels.
*
* @return GTLRDisplayVideoQuery_AdvertisersChannelsList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId;
@end
/**
* Creates a new advertiser.
* Returns the newly created advertiser if successful.
* This method can take up to 180 seconds to complete.
*
* Method: displayvideo.advertisers.create
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersCreate : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersCreateWithObject:]
/**
* Fetches a @c GTLRDisplayVideo_Advertiser.
*
* Creates a new advertiser.
* Returns the newly created advertiser if successful.
* This method can take up to 180 seconds to complete.
*
* @param object The @c GTLRDisplayVideo_Advertiser to include in the query.
*
* @return GTLRDisplayVideoQuery_AdvertisersCreate
*/
+ (instancetype)queryWithObject:(GTLRDisplayVideo_Advertiser *)object;
@end
/**
* Creates a new creative.
* Returns the newly created creative if successful.
*
* Method: displayvideo.advertisers.creatives.create
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersCreativesCreate : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersCreativesCreateWithObject:advertiserId:]
/** Output only. The unique ID of the advertiser the creative belongs to. */
@property(nonatomic, assign) long long advertiserId;
/**
* Fetches a @c GTLRDisplayVideo_Creative.
*
* Creates a new creative.
* Returns the newly created creative if successful.
*
* @param object The @c GTLRDisplayVideo_Creative to include in the query.
* @param advertiserId Output only. The unique ID of the advertiser the
* creative belongs to.
*
* @return GTLRDisplayVideoQuery_AdvertisersCreativesCreate
*/
+ (instancetype)queryWithObject:(GTLRDisplayVideo_Creative *)object
advertiserId:(long long)advertiserId;
@end
/**
* Deletes a creative.
* Returns error code `NOT_FOUND` if the creative does not exist.
* The creative should be archived first, i.e. set
* entity_status to `ENTITY_STATUS_ARCHIVED`, before
* it can be deleted.
*
* Method: displayvideo.advertisers.creatives.delete
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersCreativesDelete : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersCreativesDeleteWithadvertiserId:creativeId:]
/** The ID of the advertiser this creative belongs to. */
@property(nonatomic, assign) long long advertiserId;
/** The ID of the creative to be deleted. */
@property(nonatomic, assign) long long creativeId;
/**
* Fetches a @c GTLRDisplayVideo_Empty.
*
* Deletes a creative.
* Returns error code `NOT_FOUND` if the creative does not exist.
* The creative should be archived first, i.e. set
* entity_status to `ENTITY_STATUS_ARCHIVED`, before
* it can be deleted.
*
* @param advertiserId The ID of the advertiser this creative belongs to.
* @param creativeId The ID of the creative to be deleted.
*
* @return GTLRDisplayVideoQuery_AdvertisersCreativesDelete
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId
creativeId:(long long)creativeId;
@end
/**
* Gets a creative.
*
* Method: displayvideo.advertisers.creatives.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersCreativesGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersCreativesGetWithadvertiserId:creativeId:]
/** Required. The ID of the advertiser this creative belongs to. */
@property(nonatomic, assign) long long advertiserId;
/** Required. The ID of the creative to fetch. */
@property(nonatomic, assign) long long creativeId;
/**
* Fetches a @c GTLRDisplayVideo_Creative.
*
* Gets a creative.
*
* @param advertiserId Required. The ID of the advertiser this creative belongs
* to.
* @param creativeId Required. The ID of the creative to fetch.
*
* @return GTLRDisplayVideoQuery_AdvertisersCreativesGet
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId
creativeId:(long long)creativeId;
@end
/**
* Lists creatives in an advertiser.
* The order is defined by the order_by
* parameter.
* If a filter by
* entity_status is not specified, creatives with
* `ENTITY_STATUS_ARCHIVED` will not be included in the results.
*
* Method: displayvideo.advertisers.creatives.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersCreativesList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersCreativesListWithadvertiserId:]
/** Required. The ID of the advertiser to list creatives for. */
@property(nonatomic, assign) long long advertiserId;
/**
* Allows filtering by creative properties.
* Supported syntax:
* * Filter expressions are made up of one or more restrictions.
* * Restriction for the same field must be combined by `OR`.
* * Restriction for different fields must be combined by `AND`.
* * Between `(` and `)` there can only be restrictions combined by `OR`
* for the same field.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be `EQUALS (=)`.
* * Supported fields:
* - `entityStatus`
* - `creativeType`.
* - `dimensions`
* - `minDuration`
* - `maxDuration`
* - `approvalStatus`
* - `exchangeReviewStatus`
* - `dynamic`
* * For `entityStatus`, `minDuration`, `maxDuration`, and `dynamic` there may
* be at most one restriction.
* * For `dimensions`, the value is in the form of `"{width}x{height}"`.
* * For `exchangeReviewStatus`, the value is in the form of
* `{exchange}-{reviewStatus}`.
* * For `minDuration` and `maxDuration`, the value is in the form of
* `"{duration}s"`. Only seconds are supported with millisecond granularity.
* Examples:
* * All native creatives: `creativeType="CREATIVE_TYPE_NATIVE"`
* * All active creatives with 300x400 or 50x100 dimensions:
* `entityStatus="ENTITY_STATUS_ACTIVE" AND (dimensions="300x400"
* OR dimensions="50x100")`
* * All dynamic creatives that are approved by AdX or
* AppNexus, with a minimum duration of 5 seconds and 200ms.
* `dynamic="true" AND minDuration="5.2s" AND
* (exchangeReviewStatus="EXCHANGE_GOOGLE_AD_MANAGER-REVIEW_STATUS_APPROVED"
* OR exchangeReviewStatus="EXCHANGE_APPNEXUS-REVIEW_STATUS_APPROVED")`
* The length of this field should be no more than 500 characters.
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Field by which to sort the list.
* Acceptable values are:
* * `creativeId` (default)
* * `createTime`
* * `mediaDuration`
* * `dimensions` (sorts by width first, then by height)
* The default sorting order is ascending. To specify descending order for
* a field, a suffix "desc" should be added to the field name.
* Example: `createTime desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size. Must be between `1` and `100`. If unspecified will
* default to `100`. Returns error code `INVALID_ARGUMENT` if an invalid value
* is specified.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token
* returned from the previous call to `ListCreatives` method.
* If not specified, the first page of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/**
* Fetches a @c GTLRDisplayVideo_ListCreativesResponse.
*
* Lists creatives in an advertiser.
* The order is defined by the order_by
* parameter.
* If a filter by
* entity_status is not specified, creatives with
* `ENTITY_STATUS_ARCHIVED` will not be included in the results.
*
* @param advertiserId Required. The ID of the advertiser to list creatives
* for.
*
* @return GTLRDisplayVideoQuery_AdvertisersCreativesList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId;
@end
/**
* Updates an existing creative.
* Returns the updated creative if successful.
*
* Method: displayvideo.advertisers.creatives.patch
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersCreativesPatch : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersCreativesPatchWithObject:advertiserId:creativeId:]
/** Output only. The unique ID of the advertiser the creative belongs to. */
@property(nonatomic, assign) long long advertiserId;
/** Output only. The unique ID of the creative. Assigned by the system. */
@property(nonatomic, assign) long long creativeId;
/**
* Required. The mask to control which fields to update.
*
* String format is a comma-separated list of fields.
*/
@property(nonatomic, copy, nullable) NSString *updateMask;
/**
* Fetches a @c GTLRDisplayVideo_Creative.
*
* Updates an existing creative.
* Returns the updated creative if successful.
*
* @param object The @c GTLRDisplayVideo_Creative to include in the query.
* @param advertiserId Output only. The unique ID of the advertiser the
* creative belongs to.
* @param creativeId Output only. The unique ID of the creative. Assigned by
* the system.
*
* @return GTLRDisplayVideoQuery_AdvertisersCreativesPatch
*/
+ (instancetype)queryWithObject:(GTLRDisplayVideo_Creative *)object
advertiserId:(long long)advertiserId
creativeId:(long long)creativeId;
@end
/**
* Deletes an advertiser.
* Deleting an advertiser will delete all of its child resources, for example,
* campaigns, insertion orders and line items.
* A deleted advertiser cannot be recovered.
*
* Method: displayvideo.advertisers.delete
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersDelete : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersDeleteWithadvertiserId:]
/** The ID of the advertiser we need to delete. */
@property(nonatomic, assign) long long advertiserId;
/**
* Fetches a @c GTLRDisplayVideo_Empty.
*
* Deletes an advertiser.
* Deleting an advertiser will delete all of its child resources, for example,
* campaigns, insertion orders and line items.
* A deleted advertiser cannot be recovered.
*
* @param advertiserId The ID of the advertiser we need to delete.
*
* @return GTLRDisplayVideoQuery_AdvertisersDelete
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId;
@end
/**
* Gets an advertiser.
*
* Method: displayvideo.advertisers.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersGetWithadvertiserId:]
/** Required. The ID of the advertiser to fetch. */
@property(nonatomic, assign) long long advertiserId;
/**
* Fetches a @c GTLRDisplayVideo_Advertiser.
*
* Gets an advertiser.
*
* @param advertiserId Required. The ID of the advertiser to fetch.
*
* @return GTLRDisplayVideoQuery_AdvertisersGet
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId;
@end
/**
* Creates a new insertion order.
* Returns the newly created insertion order if successful.
*
* Method: displayvideo.advertisers.insertionOrders.create
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersInsertionOrdersCreate : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersInsertionOrdersCreateWithObject:advertiserId:]
/**
* Output only. The unique ID of the advertiser the insertion order belongs to.
*/
@property(nonatomic, assign) long long advertiserId;
/**
* Fetches a @c GTLRDisplayVideo_InsertionOrder.
*
* Creates a new insertion order.
* Returns the newly created insertion order if successful.
*
* @param object The @c GTLRDisplayVideo_InsertionOrder to include in the
* query.
* @param advertiserId Output only. The unique ID of the advertiser the
* insertion order belongs to.
*
* @return GTLRDisplayVideoQuery_AdvertisersInsertionOrdersCreate
*/
+ (instancetype)queryWithObject:(GTLRDisplayVideo_InsertionOrder *)object
advertiserId:(long long)advertiserId;
@end
/**
* Deletes an insertion order.
* Returns error code `NOT_FOUND` if the insertion order does not exist.
* The insertion order should be archived first, i.e. set
* entity_status to `ENTITY_STATUS_ARCHIVED`,
* to be able to delete it.
*
* Method: displayvideo.advertisers.insertionOrders.delete
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersInsertionOrdersDelete : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersInsertionOrdersDeleteWithadvertiserId:insertionOrderId:]
/** The ID of the advertiser this insertion order belongs to. */
@property(nonatomic, assign) long long advertiserId;
/** The ID of the insertion order we need to delete. */
@property(nonatomic, assign) long long insertionOrderId;
/**
* Fetches a @c GTLRDisplayVideo_Empty.
*
* Deletes an insertion order.
* Returns error code `NOT_FOUND` if the insertion order does not exist.
* The insertion order should be archived first, i.e. set
* entity_status to `ENTITY_STATUS_ARCHIVED`,
* to be able to delete it.
*
* @param advertiserId The ID of the advertiser this insertion order belongs
* to.
* @param insertionOrderId The ID of the insertion order we need to delete.
*
* @return GTLRDisplayVideoQuery_AdvertisersInsertionOrdersDelete
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId
insertionOrderId:(long long)insertionOrderId;
@end
/**
* Gets an insertion order.
* Returns error code `NOT_FOUND` if the insertion order does not exist.
*
* Method: displayvideo.advertisers.insertionOrders.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersInsertionOrdersGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersInsertionOrdersGetWithadvertiserId:insertionOrderId:]
/** Required. The ID of the advertiser this insertion order belongs to. */
@property(nonatomic, assign) long long advertiserId;
/** Required. The ID of the insertion order to fetch. */
@property(nonatomic, assign) long long insertionOrderId;
/**
* Fetches a @c GTLRDisplayVideo_InsertionOrder.
*
* Gets an insertion order.
* Returns error code `NOT_FOUND` if the insertion order does not exist.
*
* @param advertiserId Required. The ID of the advertiser this insertion order
* belongs to.
* @param insertionOrderId Required. The ID of the insertion order to fetch.
*
* @return GTLRDisplayVideoQuery_AdvertisersInsertionOrdersGet
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId
insertionOrderId:(long long)insertionOrderId;
@end
/**
* Lists insertion orders in an advertiser.
* The order is defined by the order_by
* parameter.
* If a filter by
* entity_status is not specified, insertion
* orders with `ENTITY_STATUS_ARCHIVED` will not be included in the results.
*
* Method: displayvideo.advertisers.insertionOrders.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersInsertionOrdersList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersInsertionOrdersListWithadvertiserId:]
/** Required. The ID of the advertiser to list insertion orders for. */
@property(nonatomic, assign) long long advertiserId;
/**
* Allows filtering by insertion order properties.
* Supported syntax:
* * Filter expressions are made up of one or more restrictions.
* * Restrictions can be combined by `AND` or `OR` logical operators. A
* sequence of restrictions implicitly uses `AND`.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be `EQUALS (=)`.
* * Supported fields:
* - `campaignId`
* - `entityStatus`
* Examples:
* * All insertion orders under a campaign: `campaignId="1234"`
* * All `ENTITY_STATUS_ACTIVE` or `ENTITY_STATUS_PAUSED` insertion orders
* under an advertiser:
* `(entityStatus="ENTITY_STATUS_ACTIVE" OR
* entityStatus="ENTITY_STATUS_PAUSED")`
* The length of this field should be no more than 500 characters.
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Field by which to sort the list.
* Acceptable values are:
* * "displayName" (default)
* * "entityStatus"
* The default sorting order is ascending. To specify descending order for
* a field, a suffix "desc" should be added to the field name. Example:
* `displayName desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size. Must be between `1` and `100`. If unspecified will
* default to `100`. Returns error code `INVALID_ARGUMENT` if an invalid value
* is specified.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token returned
* from the previous call to `ListInsertionOrders` method. If not specified,
* the first page of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/**
* Fetches a @c GTLRDisplayVideo_ListInsertionOrdersResponse.
*
* Lists insertion orders in an advertiser.
* The order is defined by the order_by
* parameter.
* If a filter by
* entity_status is not specified, insertion
* orders with `ENTITY_STATUS_ARCHIVED` will not be included in the results.
*
* @param advertiserId Required. The ID of the advertiser to list insertion
* orders for.
*
* @return GTLRDisplayVideoQuery_AdvertisersInsertionOrdersList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId;
@end
/**
* Updates an existing insertion order.
* Returns the updated insertion order if successful.
*
* Method: displayvideo.advertisers.insertionOrders.patch
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersInsertionOrdersPatch : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersInsertionOrdersPatchWithObject:advertiserId:insertionOrderId:]
/**
* Output only. The unique ID of the advertiser the insertion order belongs to.
*/
@property(nonatomic, assign) long long advertiserId;
/**
* Output only. The unique ID of the insertion order. Assigned by the system.
*/
@property(nonatomic, assign) long long insertionOrderId;
/**
* Required. The mask to control which fields to update.
*
* String format is a comma-separated list of fields.
*/
@property(nonatomic, copy, nullable) NSString *updateMask;
/**
* Fetches a @c GTLRDisplayVideo_InsertionOrder.
*
* Updates an existing insertion order.
* Returns the updated insertion order if successful.
*
* @param object The @c GTLRDisplayVideo_InsertionOrder to include in the
* query.
* @param advertiserId Output only. The unique ID of the advertiser the
* insertion order belongs to.
* @param insertionOrderId Output only. The unique ID of the insertion order.
* Assigned by the system.
*
* @return GTLRDisplayVideoQuery_AdvertisersInsertionOrdersPatch
*/
+ (instancetype)queryWithObject:(GTLRDisplayVideo_InsertionOrder *)object
advertiserId:(long long)advertiserId
insertionOrderId:(long long)insertionOrderId;
@end
/**
* Bulk edits targeting options under a single line item.
* The operation will delete the assigned targeting options provided in
* BulkEditLineItemAssignedTargetingOptionsRequest.delete_requests and
* then create the assigned targeting options provided in
* BulkEditLineItemAssignedTargetingOptionsRequest.create_requests .
*
* Method: displayvideo.advertisers.lineItems.bulkEditLineItemAssignedTargetingOptions
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersLineItemsBulkEditLineItemAssignedTargetingOptions : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersLineItemsBulkEditLineItemAssignedTargetingOptionsWithObject:advertiserId:lineItemId:]
/** Required. The ID of the advertiser the line item belongs to. */
@property(nonatomic, assign) long long advertiserId;
/**
* Required. The ID of the line item the assigned targeting option will belong
* to.
*/
@property(nonatomic, assign) long long lineItemId;
/**
* Fetches a @c
* GTLRDisplayVideo_BulkEditLineItemAssignedTargetingOptionsResponse.
*
* Bulk edits targeting options under a single line item.
* The operation will delete the assigned targeting options provided in
* BulkEditLineItemAssignedTargetingOptionsRequest.delete_requests and
* then create the assigned targeting options provided in
* BulkEditLineItemAssignedTargetingOptionsRequest.create_requests .
*
* @param object The @c
* GTLRDisplayVideo_BulkEditLineItemAssignedTargetingOptionsRequest to
* include in the query.
* @param advertiserId Required. The ID of the advertiser the line item belongs
* to.
* @param lineItemId Required. The ID of the line item the assigned targeting
* option will belong to.
*
* @return GTLRDisplayVideoQuery_AdvertisersLineItemsBulkEditLineItemAssignedTargetingOptions
*/
+ (instancetype)queryWithObject:(GTLRDisplayVideo_BulkEditLineItemAssignedTargetingOptionsRequest *)object
advertiserId:(long long)advertiserId
lineItemId:(long long)lineItemId;
@end
/**
* Lists assigned targeting options of a line item across targeting types.
*
* Method: displayvideo.advertisers.lineItems.bulkListLineItemAssignedTargetingOptions
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersLineItemsBulkListLineItemAssignedTargetingOptions : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersLineItemsBulkListLineItemAssignedTargetingOptionsWithadvertiserId:lineItemId:]
/** Required. The ID of the advertiser the line item belongs to. */
@property(nonatomic, assign) long long advertiserId;
/**
* Allows filtering by assigned targeting option properties.
* Supported syntax:
* * Filter expressions are made up of one or more restrictions.
* * Restrictions can be combined by the logical operator `OR` on the same
* field.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be `EQUALS (=)`.
* * Supported fields:
* - `targetingType`
* - `inheritance`
* Examples:
* * AssignedTargetingOptions of targeting type
* TARGETING_TYPE_PROXIMITY_LOCATION_LIST or TARGETING_TYPE_CHANNEL
* `targetingType="TARGETING_TYPE_PROXIMITY_LOCATION_LIST" OR
* targetingType="TARGETING_TYPE_CHANNEL"`
* * AssignedTargetingOptions with inheritance status of NOT_INHERITED or
* INHERITED_FROM_PARTNER
* `inheritance="NOT_INHERITED" OR inheritance="INHERITED_FROM_PARTNER"`
* The length of this field should be no more than 500 characters.
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Required. The ID of the line item to list assigned targeting options for.
*/
@property(nonatomic, assign) long long lineItemId;
/**
* Field by which to sort the list.
* Acceptable values are:
* * `targetingType` (default)
* The default sorting order is ascending. To specify descending order for
* a field, a suffix "desc" should be added to the field name. Example:
* `targetingType desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size.
* The size must be an integer between `1` and `5000`. If unspecified,
* the default is '5000'. Returns error code `INVALID_ARGUMENT` if an invalid
* value is specified.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token that lets the client fetch the next page of results.
* Typically, this is the value of
* next_page_token
* returned from the previous call to
* `BulkListLineItemAssignedTargetingOptions` method.
* If not specified, the first page of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/**
* Fetches a @c
* GTLRDisplayVideo_BulkListLineItemAssignedTargetingOptionsResponse.
*
* Lists assigned targeting options of a line item across targeting types.
*
* @param advertiserId Required. The ID of the advertiser the line item belongs
* to.
* @param lineItemId Required. The ID of the line item to list assigned
* targeting options for.
*
* @return GTLRDisplayVideoQuery_AdvertisersLineItemsBulkListLineItemAssignedTargetingOptions
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId
lineItemId:(long long)lineItemId;
@end
/**
* Creates a new line item.
* Returns the newly created line item if successful.
*
* Method: displayvideo.advertisers.lineItems.create
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersLineItemsCreate : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersLineItemsCreateWithObject:advertiserId:]
/** Output only. The unique ID of the advertiser the line item belongs to. */
@property(nonatomic, assign) long long advertiserId;
/**
* Fetches a @c GTLRDisplayVideo_LineItem.
*
* Creates a new line item.
* Returns the newly created line item if successful.
*
* @param object The @c GTLRDisplayVideo_LineItem to include in the query.
* @param advertiserId Output only. The unique ID of the advertiser the line
* item belongs to.
*
* @return GTLRDisplayVideoQuery_AdvertisersLineItemsCreate
*/
+ (instancetype)queryWithObject:(GTLRDisplayVideo_LineItem *)object
advertiserId:(long long)advertiserId;
@end
/**
* Deletes a line item.
* Returns error code `NOT_FOUND` if the line item does not exist.
* The line item should be archived first, i.e. set
* entity_status to `ENTITY_STATUS_ARCHIVED`, to be
* able to delete it.
*
* Method: displayvideo.advertisers.lineItems.delete
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersLineItemsDelete : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersLineItemsDeleteWithadvertiserId:lineItemId:]
/** The ID of the advertiser this line item belongs to. */
@property(nonatomic, assign) long long advertiserId;
/** The ID of the line item we need to fetch. */
@property(nonatomic, assign) long long lineItemId;
/**
* Fetches a @c GTLRDisplayVideo_Empty.
*
* Deletes a line item.
* Returns error code `NOT_FOUND` if the line item does not exist.
* The line item should be archived first, i.e. set
* entity_status to `ENTITY_STATUS_ARCHIVED`, to be
* able to delete it.
*
* @param advertiserId The ID of the advertiser this line item belongs to.
* @param lineItemId The ID of the line item we need to fetch.
*
* @return GTLRDisplayVideoQuery_AdvertisersLineItemsDelete
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId
lineItemId:(long long)lineItemId;
@end
/**
* Gets a line item.
*
* Method: displayvideo.advertisers.lineItems.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersLineItemsGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersLineItemsGetWithadvertiserId:lineItemId:]
/** Required. The ID of the advertiser this line item belongs to. */
@property(nonatomic, assign) long long advertiserId;
/** Required. The ID of the line item to fetch. */
@property(nonatomic, assign) long long lineItemId;
/**
* Fetches a @c GTLRDisplayVideo_LineItem.
*
* Gets a line item.
*
* @param advertiserId Required. The ID of the advertiser this line item
* belongs to.
* @param lineItemId Required. The ID of the line item to fetch.
*
* @return GTLRDisplayVideoQuery_AdvertisersLineItemsGet
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId
lineItemId:(long long)lineItemId;
@end
/**
* Lists line items in an advertiser.
* The order is defined by the order_by
* parameter.
* If a filter by
* entity_status is not specified, line items with
* `ENTITY_STATUS_ARCHIVED` will not be included in the results.
*
* Method: displayvideo.advertisers.lineItems.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersLineItemsList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersLineItemsListWithadvertiserId:]
/** Required. The ID of the advertiser to list line items for. */
@property(nonatomic, assign) long long advertiserId;
/**
* Allows filtering by line item properties.
* Supported syntax:
* * Filter expressions are made up of one or more restrictions.
* * Restrictions can be combined by `AND` or `OR` logical operators. A
* sequence of restrictions implicitly uses `AND`.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be `EQUALS (=)`.
* * Supported fields:
* - `campaignId`
* - `insertionOrderId`
* - `entityStatus`
* - `lineItemType`.
* Examples:
* * All line items under an insertion order: `insertionOrderId="1234"`
* * All `ENTITY_STATUS_ACTIVE` or `ENTITY_STATUS_PAUSED`
* and `LINE_ITEM_TYPE_DISPLAY_DEFAULT` line items under an advertiser:
* `(entityStatus="ENTITY_STATUS_ACTIVE" OR
* entityStatus="ENTITY_STATUS_PAUSED") AND
* lineItemType="LINE_ITEM_TYPE_DISPLAY_DEFAULT"`
* The length of this field should be no more than 500 characters.
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Field by which to sort the list.
* Acceptable values are:
* * "displayName" (default)
* * "entityStatus"
* The default sorting order is ascending. To specify descending order for
* a field, a suffix "desc" should be added to the field name. Example:
* `displayName desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size. Must be between `1` and `100`. If unspecified will
* default to `100`. Returns error code `INVALID_ARGUMENT` if an invalid value
* is specified.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token
* returned from the previous call to `ListLineItems` method.
* If not specified, the first page of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/**
* Fetches a @c GTLRDisplayVideo_ListLineItemsResponse.
*
* Lists line items in an advertiser.
* The order is defined by the order_by
* parameter.
* If a filter by
* entity_status is not specified, line items with
* `ENTITY_STATUS_ARCHIVED` will not be included in the results.
*
* @param advertiserId Required. The ID of the advertiser to list line items
* for.
*
* @return GTLRDisplayVideoQuery_AdvertisersLineItemsList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId;
@end
/**
* Updates an existing line item.
* Returns the updated line item if successful.
*
* Method: displayvideo.advertisers.lineItems.patch
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersLineItemsPatch : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersLineItemsPatchWithObject:advertiserId:lineItemId:]
/** Output only. The unique ID of the advertiser the line item belongs to. */
@property(nonatomic, assign) long long advertiserId;
/** Output only. The unique ID of the line item. Assigned by the system. */
@property(nonatomic, assign) long long lineItemId;
/**
* Required. The mask to control which fields to update.
*
* String format is a comma-separated list of fields.
*/
@property(nonatomic, copy, nullable) NSString *updateMask;
/**
* Fetches a @c GTLRDisplayVideo_LineItem.
*
* Updates an existing line item.
* Returns the updated line item if successful.
*
* @param object The @c GTLRDisplayVideo_LineItem to include in the query.
* @param advertiserId Output only. The unique ID of the advertiser the line
* item belongs to.
* @param lineItemId Output only. The unique ID of the line item. Assigned by
* the system.
*
* @return GTLRDisplayVideoQuery_AdvertisersLineItemsPatch
*/
+ (instancetype)queryWithObject:(GTLRDisplayVideo_LineItem *)object
advertiserId:(long long)advertiserId
lineItemId:(long long)lineItemId;
@end
/**
* Assigns a targeting option to a line item.
* Returns the assigned targeting option if successful.
*
* Method: displayvideo.advertisers.lineItems.targetingTypes.assignedTargetingOptions.create
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersLineItemsTargetingTypesAssignedTargetingOptionsCreate : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersLineItemsTargetingTypesAssignedTargetingOptionsCreateWithObject:advertiserId:lineItemId:targetingType:]
/** Required. The ID of the advertiser the line item belongs to. */
@property(nonatomic, assign) long long advertiserId;
/**
* Required. The ID of the line item the assigned targeting option will belong
* to.
*/
@property(nonatomic, assign) long long lineItemId;
/**
* Required. Identifies the type of this assigned targeting option.
*
* Likely values:
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUnspecified Value
* "TARGETING_TYPE_UNSPECIFIED"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeChannel Value
* "TARGETING_TYPE_CHANNEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAppCategory Value
* "TARGETING_TYPE_APP_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeApp Value
* "TARGETING_TYPE_APP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUrl Value
* "TARGETING_TYPE_URL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDayAndTime Value
* "TARGETING_TYPE_DAY_AND_TIME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAgeRange Value
* "TARGETING_TYPE_AGE_RANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeRegionalLocationList
* Value "TARGETING_TYPE_REGIONAL_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocationList
* Value "TARGETING_TYPE_PROXIMITY_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGender Value
* "TARGETING_TYPE_GENDER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeVideoPlayerSize Value
* "TARGETING_TYPE_VIDEO_PLAYER_SIZE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUserRewardedContent
* Value "TARGETING_TYPE_USER_REWARDED_CONTENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeParentalStatus Value
* "TARGETING_TYPE_PARENTAL_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentInstreamPosition
* Value "TARGETING_TYPE_CONTENT_INSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentOutstreamPosition
* Value "TARGETING_TYPE_CONTENT_OUTSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceType Value
* "TARGETING_TYPE_DEVICE_TYPE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAudienceGroup Value
* "TARGETING_TYPE_AUDIENCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeBrowser Value
* "TARGETING_TYPE_BROWSER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeHouseholdIncome Value
* "TARGETING_TYPE_HOUSEHOLD_INCOME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOnScreenPosition Value
* "TARGETING_TYPE_ON_SCREEN_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeThirdPartyVerifier
* Value "TARGETING_TYPE_THIRD_PARTY_VERIFIER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDigitalContentLabelExclusion
* Value "TARGETING_TYPE_DIGITAL_CONTENT_LABEL_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSensitiveCategoryExclusion
* Value "TARGETING_TYPE_SENSITIVE_CATEGORY_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeEnvironment Value
* "TARGETING_TYPE_ENVIRONMENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCarrierAndIsp Value
* "TARGETING_TYPE_CARRIER_AND_ISP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOperatingSystem Value
* "TARGETING_TYPE_OPERATING_SYSTEM"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceMakeModel Value
* "TARGETING_TYPE_DEVICE_MAKE_MODEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeKeyword Value
* "TARGETING_TYPE_KEYWORD"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeNegativeKeywordList
* Value "TARGETING_TYPE_NEGATIVE_KEYWORD_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeViewability Value
* "TARGETING_TYPE_VIEWABILITY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCategory Value
* "TARGETING_TYPE_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySource Value
* "TARGETING_TYPE_INVENTORY_SOURCE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeLanguage Value
* "TARGETING_TYPE_LANGUAGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAuthorizedSellerStatus
* Value "TARGETING_TYPE_AUTHORIZED_SELLER_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGeoRegion Value
* "TARGETING_TYPE_GEO_REGION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySourceGroup
* Value "TARGETING_TYPE_INVENTORY_SOURCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocation Value
* "TARGETING_TYPE_PROXIMITY_LOCATION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeExchange Value
* "TARGETING_TYPE_EXCHANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSubExchange Value
* "TARGETING_TYPE_SUB_EXCHANGE"
*/
@property(nonatomic, copy, nullable) NSString *targetingType;
/**
* Fetches a @c GTLRDisplayVideo_AssignedTargetingOption.
*
* Assigns a targeting option to a line item.
* Returns the assigned targeting option if successful.
*
* @param object The @c GTLRDisplayVideo_AssignedTargetingOption to include in
* the query.
* @param advertiserId Required. The ID of the advertiser the line item belongs
* to.
* @param lineItemId Required. The ID of the line item the assigned targeting
* option will belong to.
* @param targetingType Required. Identifies the type of this assigned
* targeting option.
*
* Likely values for @c targetingType:
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUnspecified Value
* "TARGETING_TYPE_UNSPECIFIED"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeChannel Value
* "TARGETING_TYPE_CHANNEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAppCategory Value
* "TARGETING_TYPE_APP_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeApp Value
* "TARGETING_TYPE_APP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUrl Value
* "TARGETING_TYPE_URL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDayAndTime Value
* "TARGETING_TYPE_DAY_AND_TIME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAgeRange Value
* "TARGETING_TYPE_AGE_RANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeRegionalLocationList
* Value "TARGETING_TYPE_REGIONAL_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocationList
* Value "TARGETING_TYPE_PROXIMITY_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGender Value
* "TARGETING_TYPE_GENDER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeVideoPlayerSize Value
* "TARGETING_TYPE_VIDEO_PLAYER_SIZE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUserRewardedContent
* Value "TARGETING_TYPE_USER_REWARDED_CONTENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeParentalStatus Value
* "TARGETING_TYPE_PARENTAL_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentInstreamPosition
* Value "TARGETING_TYPE_CONTENT_INSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentOutstreamPosition
* Value "TARGETING_TYPE_CONTENT_OUTSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceType Value
* "TARGETING_TYPE_DEVICE_TYPE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAudienceGroup Value
* "TARGETING_TYPE_AUDIENCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeBrowser Value
* "TARGETING_TYPE_BROWSER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeHouseholdIncome Value
* "TARGETING_TYPE_HOUSEHOLD_INCOME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOnScreenPosition Value
* "TARGETING_TYPE_ON_SCREEN_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeThirdPartyVerifier
* Value "TARGETING_TYPE_THIRD_PARTY_VERIFIER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDigitalContentLabelExclusion
* Value "TARGETING_TYPE_DIGITAL_CONTENT_LABEL_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSensitiveCategoryExclusion
* Value "TARGETING_TYPE_SENSITIVE_CATEGORY_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeEnvironment Value
* "TARGETING_TYPE_ENVIRONMENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCarrierAndIsp Value
* "TARGETING_TYPE_CARRIER_AND_ISP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOperatingSystem Value
* "TARGETING_TYPE_OPERATING_SYSTEM"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceMakeModel Value
* "TARGETING_TYPE_DEVICE_MAKE_MODEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeKeyword Value
* "TARGETING_TYPE_KEYWORD"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeNegativeKeywordList
* Value "TARGETING_TYPE_NEGATIVE_KEYWORD_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeViewability Value
* "TARGETING_TYPE_VIEWABILITY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCategory Value
* "TARGETING_TYPE_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySource Value
* "TARGETING_TYPE_INVENTORY_SOURCE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeLanguage Value
* "TARGETING_TYPE_LANGUAGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAuthorizedSellerStatus
* Value "TARGETING_TYPE_AUTHORIZED_SELLER_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGeoRegion Value
* "TARGETING_TYPE_GEO_REGION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySourceGroup
* Value "TARGETING_TYPE_INVENTORY_SOURCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocation Value
* "TARGETING_TYPE_PROXIMITY_LOCATION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeExchange Value
* "TARGETING_TYPE_EXCHANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSubExchange Value
* "TARGETING_TYPE_SUB_EXCHANGE"
*
* @return GTLRDisplayVideoQuery_AdvertisersLineItemsTargetingTypesAssignedTargetingOptionsCreate
*/
+ (instancetype)queryWithObject:(GTLRDisplayVideo_AssignedTargetingOption *)object
advertiserId:(long long)advertiserId
lineItemId:(long long)lineItemId
targetingType:(NSString *)targetingType;
@end
/**
* Deletes an assigned targeting option from a line item.
*
* Method: displayvideo.advertisers.lineItems.targetingTypes.assignedTargetingOptions.delete
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersLineItemsTargetingTypesAssignedTargetingOptionsDelete : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersLineItemsTargetingTypesAssignedTargetingOptionsDeleteWithadvertiserId:lineItemId:targetingType:assignedTargetingOptionId:]
/** Required. The ID of the advertiser the line item belongs to. */
@property(nonatomic, assign) long long advertiserId;
/** Required. The ID of the assigned targeting option to delete. */
@property(nonatomic, copy, nullable) NSString *assignedTargetingOptionId;
/**
* Required. The ID of the line item the assigned targeting option belongs to.
*/
@property(nonatomic, assign) long long lineItemId;
/**
* Required. Identifies the type of this assigned targeting option.
*
* Likely values:
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUnspecified Value
* "TARGETING_TYPE_UNSPECIFIED"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeChannel Value
* "TARGETING_TYPE_CHANNEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAppCategory Value
* "TARGETING_TYPE_APP_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeApp Value
* "TARGETING_TYPE_APP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUrl Value
* "TARGETING_TYPE_URL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDayAndTime Value
* "TARGETING_TYPE_DAY_AND_TIME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAgeRange Value
* "TARGETING_TYPE_AGE_RANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeRegionalLocationList
* Value "TARGETING_TYPE_REGIONAL_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocationList
* Value "TARGETING_TYPE_PROXIMITY_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGender Value
* "TARGETING_TYPE_GENDER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeVideoPlayerSize Value
* "TARGETING_TYPE_VIDEO_PLAYER_SIZE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUserRewardedContent
* Value "TARGETING_TYPE_USER_REWARDED_CONTENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeParentalStatus Value
* "TARGETING_TYPE_PARENTAL_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentInstreamPosition
* Value "TARGETING_TYPE_CONTENT_INSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentOutstreamPosition
* Value "TARGETING_TYPE_CONTENT_OUTSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceType Value
* "TARGETING_TYPE_DEVICE_TYPE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAudienceGroup Value
* "TARGETING_TYPE_AUDIENCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeBrowser Value
* "TARGETING_TYPE_BROWSER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeHouseholdIncome Value
* "TARGETING_TYPE_HOUSEHOLD_INCOME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOnScreenPosition Value
* "TARGETING_TYPE_ON_SCREEN_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeThirdPartyVerifier
* Value "TARGETING_TYPE_THIRD_PARTY_VERIFIER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDigitalContentLabelExclusion
* Value "TARGETING_TYPE_DIGITAL_CONTENT_LABEL_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSensitiveCategoryExclusion
* Value "TARGETING_TYPE_SENSITIVE_CATEGORY_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeEnvironment Value
* "TARGETING_TYPE_ENVIRONMENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCarrierAndIsp Value
* "TARGETING_TYPE_CARRIER_AND_ISP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOperatingSystem Value
* "TARGETING_TYPE_OPERATING_SYSTEM"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceMakeModel Value
* "TARGETING_TYPE_DEVICE_MAKE_MODEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeKeyword Value
* "TARGETING_TYPE_KEYWORD"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeNegativeKeywordList
* Value "TARGETING_TYPE_NEGATIVE_KEYWORD_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeViewability Value
* "TARGETING_TYPE_VIEWABILITY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCategory Value
* "TARGETING_TYPE_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySource Value
* "TARGETING_TYPE_INVENTORY_SOURCE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeLanguage Value
* "TARGETING_TYPE_LANGUAGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAuthorizedSellerStatus
* Value "TARGETING_TYPE_AUTHORIZED_SELLER_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGeoRegion Value
* "TARGETING_TYPE_GEO_REGION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySourceGroup
* Value "TARGETING_TYPE_INVENTORY_SOURCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocation Value
* "TARGETING_TYPE_PROXIMITY_LOCATION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeExchange Value
* "TARGETING_TYPE_EXCHANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSubExchange Value
* "TARGETING_TYPE_SUB_EXCHANGE"
*/
@property(nonatomic, copy, nullable) NSString *targetingType;
/**
* Fetches a @c GTLRDisplayVideo_Empty.
*
* Deletes an assigned targeting option from a line item.
*
* @param advertiserId Required. The ID of the advertiser the line item belongs
* to.
* @param lineItemId Required. The ID of the line item the assigned targeting
* option belongs to.
* @param targetingType Required. Identifies the type of this assigned
* targeting option.
* @param assignedTargetingOptionId Required. The ID of the assigned targeting
* option to delete.
*
* Likely values for @c targetingType:
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUnspecified Value
* "TARGETING_TYPE_UNSPECIFIED"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeChannel Value
* "TARGETING_TYPE_CHANNEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAppCategory Value
* "TARGETING_TYPE_APP_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeApp Value
* "TARGETING_TYPE_APP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUrl Value
* "TARGETING_TYPE_URL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDayAndTime Value
* "TARGETING_TYPE_DAY_AND_TIME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAgeRange Value
* "TARGETING_TYPE_AGE_RANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeRegionalLocationList
* Value "TARGETING_TYPE_REGIONAL_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocationList
* Value "TARGETING_TYPE_PROXIMITY_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGender Value
* "TARGETING_TYPE_GENDER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeVideoPlayerSize Value
* "TARGETING_TYPE_VIDEO_PLAYER_SIZE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUserRewardedContent
* Value "TARGETING_TYPE_USER_REWARDED_CONTENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeParentalStatus Value
* "TARGETING_TYPE_PARENTAL_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentInstreamPosition
* Value "TARGETING_TYPE_CONTENT_INSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentOutstreamPosition
* Value "TARGETING_TYPE_CONTENT_OUTSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceType Value
* "TARGETING_TYPE_DEVICE_TYPE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAudienceGroup Value
* "TARGETING_TYPE_AUDIENCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeBrowser Value
* "TARGETING_TYPE_BROWSER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeHouseholdIncome Value
* "TARGETING_TYPE_HOUSEHOLD_INCOME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOnScreenPosition Value
* "TARGETING_TYPE_ON_SCREEN_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeThirdPartyVerifier
* Value "TARGETING_TYPE_THIRD_PARTY_VERIFIER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDigitalContentLabelExclusion
* Value "TARGETING_TYPE_DIGITAL_CONTENT_LABEL_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSensitiveCategoryExclusion
* Value "TARGETING_TYPE_SENSITIVE_CATEGORY_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeEnvironment Value
* "TARGETING_TYPE_ENVIRONMENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCarrierAndIsp Value
* "TARGETING_TYPE_CARRIER_AND_ISP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOperatingSystem Value
* "TARGETING_TYPE_OPERATING_SYSTEM"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceMakeModel Value
* "TARGETING_TYPE_DEVICE_MAKE_MODEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeKeyword Value
* "TARGETING_TYPE_KEYWORD"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeNegativeKeywordList
* Value "TARGETING_TYPE_NEGATIVE_KEYWORD_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeViewability Value
* "TARGETING_TYPE_VIEWABILITY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCategory Value
* "TARGETING_TYPE_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySource Value
* "TARGETING_TYPE_INVENTORY_SOURCE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeLanguage Value
* "TARGETING_TYPE_LANGUAGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAuthorizedSellerStatus
* Value "TARGETING_TYPE_AUTHORIZED_SELLER_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGeoRegion Value
* "TARGETING_TYPE_GEO_REGION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySourceGroup
* Value "TARGETING_TYPE_INVENTORY_SOURCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocation Value
* "TARGETING_TYPE_PROXIMITY_LOCATION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeExchange Value
* "TARGETING_TYPE_EXCHANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSubExchange Value
* "TARGETING_TYPE_SUB_EXCHANGE"
*
* @return GTLRDisplayVideoQuery_AdvertisersLineItemsTargetingTypesAssignedTargetingOptionsDelete
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId
lineItemId:(long long)lineItemId
targetingType:(NSString *)targetingType
assignedTargetingOptionId:(NSString *)assignedTargetingOptionId;
@end
/**
* Gets a single targeting option assigned to a line item.
*
* Method: displayvideo.advertisers.lineItems.targetingTypes.assignedTargetingOptions.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersLineItemsTargetingTypesAssignedTargetingOptionsGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersLineItemsTargetingTypesAssignedTargetingOptionsGetWithadvertiserId:lineItemId:targetingType:assignedTargetingOptionId:]
/** Required. The ID of the advertiser the line item belongs to. */
@property(nonatomic, assign) long long advertiserId;
/**
* Required. An identifier unique to the targeting type in this line item that
* identifies the assigned targeting option being requested.
*/
@property(nonatomic, copy, nullable) NSString *assignedTargetingOptionId;
/**
* Required. The ID of the line item the assigned targeting option belongs to.
*/
@property(nonatomic, assign) long long lineItemId;
/**
* Required. Identifies the type of this assigned targeting option.
*
* Likely values:
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUnspecified Value
* "TARGETING_TYPE_UNSPECIFIED"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeChannel Value
* "TARGETING_TYPE_CHANNEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAppCategory Value
* "TARGETING_TYPE_APP_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeApp Value
* "TARGETING_TYPE_APP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUrl Value
* "TARGETING_TYPE_URL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDayAndTime Value
* "TARGETING_TYPE_DAY_AND_TIME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAgeRange Value
* "TARGETING_TYPE_AGE_RANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeRegionalLocationList
* Value "TARGETING_TYPE_REGIONAL_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocationList
* Value "TARGETING_TYPE_PROXIMITY_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGender Value
* "TARGETING_TYPE_GENDER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeVideoPlayerSize Value
* "TARGETING_TYPE_VIDEO_PLAYER_SIZE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUserRewardedContent
* Value "TARGETING_TYPE_USER_REWARDED_CONTENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeParentalStatus Value
* "TARGETING_TYPE_PARENTAL_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentInstreamPosition
* Value "TARGETING_TYPE_CONTENT_INSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentOutstreamPosition
* Value "TARGETING_TYPE_CONTENT_OUTSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceType Value
* "TARGETING_TYPE_DEVICE_TYPE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAudienceGroup Value
* "TARGETING_TYPE_AUDIENCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeBrowser Value
* "TARGETING_TYPE_BROWSER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeHouseholdIncome Value
* "TARGETING_TYPE_HOUSEHOLD_INCOME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOnScreenPosition Value
* "TARGETING_TYPE_ON_SCREEN_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeThirdPartyVerifier
* Value "TARGETING_TYPE_THIRD_PARTY_VERIFIER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDigitalContentLabelExclusion
* Value "TARGETING_TYPE_DIGITAL_CONTENT_LABEL_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSensitiveCategoryExclusion
* Value "TARGETING_TYPE_SENSITIVE_CATEGORY_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeEnvironment Value
* "TARGETING_TYPE_ENVIRONMENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCarrierAndIsp Value
* "TARGETING_TYPE_CARRIER_AND_ISP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOperatingSystem Value
* "TARGETING_TYPE_OPERATING_SYSTEM"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceMakeModel Value
* "TARGETING_TYPE_DEVICE_MAKE_MODEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeKeyword Value
* "TARGETING_TYPE_KEYWORD"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeNegativeKeywordList
* Value "TARGETING_TYPE_NEGATIVE_KEYWORD_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeViewability Value
* "TARGETING_TYPE_VIEWABILITY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCategory Value
* "TARGETING_TYPE_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySource Value
* "TARGETING_TYPE_INVENTORY_SOURCE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeLanguage Value
* "TARGETING_TYPE_LANGUAGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAuthorizedSellerStatus
* Value "TARGETING_TYPE_AUTHORIZED_SELLER_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGeoRegion Value
* "TARGETING_TYPE_GEO_REGION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySourceGroup
* Value "TARGETING_TYPE_INVENTORY_SOURCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocation Value
* "TARGETING_TYPE_PROXIMITY_LOCATION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeExchange Value
* "TARGETING_TYPE_EXCHANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSubExchange Value
* "TARGETING_TYPE_SUB_EXCHANGE"
*/
@property(nonatomic, copy, nullable) NSString *targetingType;
/**
* Fetches a @c GTLRDisplayVideo_AssignedTargetingOption.
*
* Gets a single targeting option assigned to a line item.
*
* @param advertiserId Required. The ID of the advertiser the line item belongs
* to.
* @param lineItemId Required. The ID of the line item the assigned targeting
* option belongs to.
* @param targetingType Required. Identifies the type of this assigned
* targeting option.
* @param assignedTargetingOptionId Required. An identifier unique to the
* targeting type in this line item that
* identifies the assigned targeting option being requested.
*
* Likely values for @c targetingType:
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUnspecified Value
* "TARGETING_TYPE_UNSPECIFIED"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeChannel Value
* "TARGETING_TYPE_CHANNEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAppCategory Value
* "TARGETING_TYPE_APP_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeApp Value
* "TARGETING_TYPE_APP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUrl Value
* "TARGETING_TYPE_URL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDayAndTime Value
* "TARGETING_TYPE_DAY_AND_TIME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAgeRange Value
* "TARGETING_TYPE_AGE_RANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeRegionalLocationList
* Value "TARGETING_TYPE_REGIONAL_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocationList
* Value "TARGETING_TYPE_PROXIMITY_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGender Value
* "TARGETING_TYPE_GENDER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeVideoPlayerSize Value
* "TARGETING_TYPE_VIDEO_PLAYER_SIZE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUserRewardedContent
* Value "TARGETING_TYPE_USER_REWARDED_CONTENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeParentalStatus Value
* "TARGETING_TYPE_PARENTAL_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentInstreamPosition
* Value "TARGETING_TYPE_CONTENT_INSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentOutstreamPosition
* Value "TARGETING_TYPE_CONTENT_OUTSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceType Value
* "TARGETING_TYPE_DEVICE_TYPE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAudienceGroup Value
* "TARGETING_TYPE_AUDIENCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeBrowser Value
* "TARGETING_TYPE_BROWSER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeHouseholdIncome Value
* "TARGETING_TYPE_HOUSEHOLD_INCOME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOnScreenPosition Value
* "TARGETING_TYPE_ON_SCREEN_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeThirdPartyVerifier
* Value "TARGETING_TYPE_THIRD_PARTY_VERIFIER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDigitalContentLabelExclusion
* Value "TARGETING_TYPE_DIGITAL_CONTENT_LABEL_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSensitiveCategoryExclusion
* Value "TARGETING_TYPE_SENSITIVE_CATEGORY_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeEnvironment Value
* "TARGETING_TYPE_ENVIRONMENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCarrierAndIsp Value
* "TARGETING_TYPE_CARRIER_AND_ISP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOperatingSystem Value
* "TARGETING_TYPE_OPERATING_SYSTEM"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceMakeModel Value
* "TARGETING_TYPE_DEVICE_MAKE_MODEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeKeyword Value
* "TARGETING_TYPE_KEYWORD"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeNegativeKeywordList
* Value "TARGETING_TYPE_NEGATIVE_KEYWORD_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeViewability Value
* "TARGETING_TYPE_VIEWABILITY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCategory Value
* "TARGETING_TYPE_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySource Value
* "TARGETING_TYPE_INVENTORY_SOURCE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeLanguage Value
* "TARGETING_TYPE_LANGUAGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAuthorizedSellerStatus
* Value "TARGETING_TYPE_AUTHORIZED_SELLER_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGeoRegion Value
* "TARGETING_TYPE_GEO_REGION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySourceGroup
* Value "TARGETING_TYPE_INVENTORY_SOURCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocation Value
* "TARGETING_TYPE_PROXIMITY_LOCATION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeExchange Value
* "TARGETING_TYPE_EXCHANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSubExchange Value
* "TARGETING_TYPE_SUB_EXCHANGE"
*
* @return GTLRDisplayVideoQuery_AdvertisersLineItemsTargetingTypesAssignedTargetingOptionsGet
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId
lineItemId:(long long)lineItemId
targetingType:(NSString *)targetingType
assignedTargetingOptionId:(NSString *)assignedTargetingOptionId;
@end
/**
* Lists the targeting options assigned to a line item.
*
* Method: displayvideo.advertisers.lineItems.targetingTypes.assignedTargetingOptions.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersLineItemsTargetingTypesAssignedTargetingOptionsList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersLineItemsTargetingTypesAssignedTargetingOptionsListWithadvertiserId:lineItemId:targetingType:]
/** Required. The ID of the advertiser the line item belongs to. */
@property(nonatomic, assign) long long advertiserId;
/**
* Allows filtering by assigned targeting option properties.
* Supported syntax:
* * Filter expressions are made up of one or more restrictions.
* * Restrictions can be combined by the logical operator `OR`.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be `EQUALS (=)`.
* * Supported fields:
* - `assignedTargetingOptionId`
* - `inheritance`
* Examples:
* * AssignedTargetingOptions with ID 1 or 2
* `assignedTargetingOptionId="1" OR assignedTargetingOptionId="2"`
* * AssignedTargetingOptions with inheritance status of NOT_INHERITED or
* INHERITED_FROM_PARTNER
* `inheritance="NOT_INHERITED" OR inheritance="INHERITED_FROM_PARTNER"`
* The length of this field should be no more than 500 characters.
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Required. The ID of the line item to list assigned targeting options for.
*/
@property(nonatomic, assign) long long lineItemId;
/**
* Field by which to sort the list.
* Acceptable values are:
* * `assignedTargetingOptionId` (default)
* The default sorting order is ascending. To specify descending order for
* a field, a suffix "desc" should be added to the field name. Example:
* `assignedTargetingOptionId desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size. Must be between `1` and `100`. If unspecified will
* default to `100`. Returns error code `INVALID_ARGUMENT` if an invalid value
* is specified.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token
* returned from the previous call to `ListLineItemAssignedTargetingOptions`
* method. If not specified, the first page of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/**
* Required. Identifies the type of assigned targeting options to list.
*
* Likely values:
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUnspecified Value
* "TARGETING_TYPE_UNSPECIFIED"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeChannel Value
* "TARGETING_TYPE_CHANNEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAppCategory Value
* "TARGETING_TYPE_APP_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeApp Value
* "TARGETING_TYPE_APP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUrl Value
* "TARGETING_TYPE_URL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDayAndTime Value
* "TARGETING_TYPE_DAY_AND_TIME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAgeRange Value
* "TARGETING_TYPE_AGE_RANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeRegionalLocationList
* Value "TARGETING_TYPE_REGIONAL_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocationList
* Value "TARGETING_TYPE_PROXIMITY_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGender Value
* "TARGETING_TYPE_GENDER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeVideoPlayerSize Value
* "TARGETING_TYPE_VIDEO_PLAYER_SIZE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUserRewardedContent
* Value "TARGETING_TYPE_USER_REWARDED_CONTENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeParentalStatus Value
* "TARGETING_TYPE_PARENTAL_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentInstreamPosition
* Value "TARGETING_TYPE_CONTENT_INSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentOutstreamPosition
* Value "TARGETING_TYPE_CONTENT_OUTSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceType Value
* "TARGETING_TYPE_DEVICE_TYPE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAudienceGroup Value
* "TARGETING_TYPE_AUDIENCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeBrowser Value
* "TARGETING_TYPE_BROWSER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeHouseholdIncome Value
* "TARGETING_TYPE_HOUSEHOLD_INCOME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOnScreenPosition Value
* "TARGETING_TYPE_ON_SCREEN_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeThirdPartyVerifier
* Value "TARGETING_TYPE_THIRD_PARTY_VERIFIER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDigitalContentLabelExclusion
* Value "TARGETING_TYPE_DIGITAL_CONTENT_LABEL_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSensitiveCategoryExclusion
* Value "TARGETING_TYPE_SENSITIVE_CATEGORY_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeEnvironment Value
* "TARGETING_TYPE_ENVIRONMENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCarrierAndIsp Value
* "TARGETING_TYPE_CARRIER_AND_ISP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOperatingSystem Value
* "TARGETING_TYPE_OPERATING_SYSTEM"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceMakeModel Value
* "TARGETING_TYPE_DEVICE_MAKE_MODEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeKeyword Value
* "TARGETING_TYPE_KEYWORD"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeNegativeKeywordList
* Value "TARGETING_TYPE_NEGATIVE_KEYWORD_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeViewability Value
* "TARGETING_TYPE_VIEWABILITY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCategory Value
* "TARGETING_TYPE_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySource Value
* "TARGETING_TYPE_INVENTORY_SOURCE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeLanguage Value
* "TARGETING_TYPE_LANGUAGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAuthorizedSellerStatus
* Value "TARGETING_TYPE_AUTHORIZED_SELLER_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGeoRegion Value
* "TARGETING_TYPE_GEO_REGION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySourceGroup
* Value "TARGETING_TYPE_INVENTORY_SOURCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocation Value
* "TARGETING_TYPE_PROXIMITY_LOCATION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeExchange Value
* "TARGETING_TYPE_EXCHANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSubExchange Value
* "TARGETING_TYPE_SUB_EXCHANGE"
*/
@property(nonatomic, copy, nullable) NSString *targetingType;
/**
* Fetches a @c GTLRDisplayVideo_ListLineItemAssignedTargetingOptionsResponse.
*
* Lists the targeting options assigned to a line item.
*
* @param advertiserId Required. The ID of the advertiser the line item belongs
* to.
* @param lineItemId Required. The ID of the line item to list assigned
* targeting options for.
* @param targetingType Required. Identifies the type of assigned targeting
* options to list.
*
* Likely values for @c targetingType:
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUnspecified Value
* "TARGETING_TYPE_UNSPECIFIED"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeChannel Value
* "TARGETING_TYPE_CHANNEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAppCategory Value
* "TARGETING_TYPE_APP_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeApp Value
* "TARGETING_TYPE_APP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUrl Value
* "TARGETING_TYPE_URL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDayAndTime Value
* "TARGETING_TYPE_DAY_AND_TIME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAgeRange Value
* "TARGETING_TYPE_AGE_RANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeRegionalLocationList
* Value "TARGETING_TYPE_REGIONAL_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocationList
* Value "TARGETING_TYPE_PROXIMITY_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGender Value
* "TARGETING_TYPE_GENDER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeVideoPlayerSize Value
* "TARGETING_TYPE_VIDEO_PLAYER_SIZE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUserRewardedContent
* Value "TARGETING_TYPE_USER_REWARDED_CONTENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeParentalStatus Value
* "TARGETING_TYPE_PARENTAL_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentInstreamPosition
* Value "TARGETING_TYPE_CONTENT_INSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentOutstreamPosition
* Value "TARGETING_TYPE_CONTENT_OUTSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceType Value
* "TARGETING_TYPE_DEVICE_TYPE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAudienceGroup Value
* "TARGETING_TYPE_AUDIENCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeBrowser Value
* "TARGETING_TYPE_BROWSER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeHouseholdIncome Value
* "TARGETING_TYPE_HOUSEHOLD_INCOME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOnScreenPosition Value
* "TARGETING_TYPE_ON_SCREEN_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeThirdPartyVerifier
* Value "TARGETING_TYPE_THIRD_PARTY_VERIFIER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDigitalContentLabelExclusion
* Value "TARGETING_TYPE_DIGITAL_CONTENT_LABEL_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSensitiveCategoryExclusion
* Value "TARGETING_TYPE_SENSITIVE_CATEGORY_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeEnvironment Value
* "TARGETING_TYPE_ENVIRONMENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCarrierAndIsp Value
* "TARGETING_TYPE_CARRIER_AND_ISP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOperatingSystem Value
* "TARGETING_TYPE_OPERATING_SYSTEM"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceMakeModel Value
* "TARGETING_TYPE_DEVICE_MAKE_MODEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeKeyword Value
* "TARGETING_TYPE_KEYWORD"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeNegativeKeywordList
* Value "TARGETING_TYPE_NEGATIVE_KEYWORD_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeViewability Value
* "TARGETING_TYPE_VIEWABILITY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCategory Value
* "TARGETING_TYPE_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySource Value
* "TARGETING_TYPE_INVENTORY_SOURCE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeLanguage Value
* "TARGETING_TYPE_LANGUAGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAuthorizedSellerStatus
* Value "TARGETING_TYPE_AUTHORIZED_SELLER_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGeoRegion Value
* "TARGETING_TYPE_GEO_REGION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySourceGroup
* Value "TARGETING_TYPE_INVENTORY_SOURCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocation Value
* "TARGETING_TYPE_PROXIMITY_LOCATION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeExchange Value
* "TARGETING_TYPE_EXCHANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSubExchange Value
* "TARGETING_TYPE_SUB_EXCHANGE"
*
* @return GTLRDisplayVideoQuery_AdvertisersLineItemsTargetingTypesAssignedTargetingOptionsList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId
lineItemId:(long long)lineItemId
targetingType:(NSString *)targetingType;
@end
/**
* Lists advertisers that are accessible to the current user.
* The order is defined by the order_by
* parameter.
* A single partner_id is required.
* Cross-partner listing is not supported.
*
* Method: displayvideo.advertisers.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersList]
/**
* Allows filtering by advertiser properties.
* Supported syntax:
* * Filter expressions are made up of one or more restrictions.
* * Restrictions can be combined by `AND` or `OR` logical operators. A
* sequence of restrictions implicitly uses `AND`.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be `EQUALS (=)`.
* * Supported fields:
* - `entityStatus`
* Examples:
* * All active advertisers under a partner:
* `entityStatus="ENTITY_STATUS_ACTIVE"`
* The length of this field should be no more than 500 characters.
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Field by which to sort the list.
* Acceptable values are:
* * `displayName` (default)
* * `entityStatus`
* The default sorting order is ascending. To specify descending order for
* a field, a suffix "desc" should be added to the field name. For example,
* `displayName desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size. Must be between `1` and `100`. If unspecified will
* default to `100`.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token
* returned from the previous call to `ListAdvertisers` method.
* If not specified, the first page of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/**
* Required. The ID of the partner that the fetched advertisers should all
* belong to.
* The system only supports listing advertisers for one partner at a time.
*/
@property(nonatomic, assign) long long partnerId;
/**
* Fetches a @c GTLRDisplayVideo_ListAdvertisersResponse.
*
* Lists advertisers that are accessible to the current user.
* The order is defined by the order_by
* parameter.
* A single partner_id is required.
* Cross-partner listing is not supported.
*
* @return GTLRDisplayVideoQuery_AdvertisersList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)query;
@end
/**
* Gets a location list.
*
* Method: displayvideo.advertisers.locationLists.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersLocationListsGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersLocationListsGetWithadvertiserId:locationListId:]
/**
* Required. The ID of the DV360 advertiser to which the fetched location list
* belongs.
*/
@property(nonatomic, assign) long long advertiserId;
/** Required. The ID of the location list to fetch. */
@property(nonatomic, assign) long long locationListId;
/**
* Fetches a @c GTLRDisplayVideo_LocationList.
*
* Gets a location list.
*
* @param advertiserId Required. The ID of the DV360 advertiser to which the
* fetched location list belongs.
* @param locationListId Required. The ID of the location list to fetch.
*
* @return GTLRDisplayVideoQuery_AdvertisersLocationListsGet
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId
locationListId:(long long)locationListId;
@end
/**
* Lists location lists based on a given advertiser id.
*
* Method: displayvideo.advertisers.locationLists.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersLocationListsList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersLocationListsListWithadvertiserId:]
/**
* Required. The ID of the DV360 advertiser to which the fetched location lists
* belong.
*/
@property(nonatomic, assign) long long advertiserId;
/**
* Allows filtering by location list fields.
* Supported syntax:
* * Filter expressions are made up of one or more restrictions.
* * Restrictions can be combined by `AND` or `OR` logical operators. A
* sequence of restrictions implicitly uses `AND`.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be `EQUALS (=)`.
* * Supported fields:
* - `locationType`
* Examples:
* * All regional location list:
* `locationType="TARGETING_LOCATION_TYPE_REGIONAL"`
* * All proximity location list:
* `locationType="TARGETING_LOCATION_TYPE_PROXIMITY"`
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Field by which to sort the list.
* Acceptable values are:
* * `locationListId` (default)
* * `displayName`
* The default sorting order is ascending. To specify descending order for
* a field, a suffix "desc" should be added to the field name. Example:
* `displayName desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size. Must be between `1` and `100`.
* Defaults to `100` if not set. Returns error code `INVALID_ARGUMENT` if an
* invalid value is specified.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token
* returned from the previous call to `ListLocationLists` method.
* If not specified, the first page of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/**
* Fetches a @c GTLRDisplayVideo_ListLocationListsResponse.
*
* Lists location lists based on a given advertiser id.
*
* @param advertiserId Required. The ID of the DV360 advertiser to which the
* fetched location lists belong.
*
* @return GTLRDisplayVideoQuery_AdvertisersLocationListsList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId;
@end
/**
* Gets a negative keyword list given an advertiser ID and a negative keyword
* list ID.
*
* Method: displayvideo.advertisers.negativeKeywordLists.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersNegativeKeywordListsGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersNegativeKeywordListsGetWithadvertiserId:negativeKeywordListId:]
/**
* Required. The ID of the DV360 advertiser to which the fetched negative
* keyword list
* belongs.
*/
@property(nonatomic, assign) long long advertiserId;
/** Required. The ID of the negative keyword list to fetch. */
@property(nonatomic, assign) long long negativeKeywordListId;
/**
* Fetches a @c GTLRDisplayVideo_NegativeKeywordList.
*
* Gets a negative keyword list given an advertiser ID and a negative keyword
* list ID.
*
* @param advertiserId Required. The ID of the DV360 advertiser to which the
* fetched negative keyword list
* belongs.
* @param negativeKeywordListId Required. The ID of the negative keyword list
* to fetch.
*
* @return GTLRDisplayVideoQuery_AdvertisersNegativeKeywordListsGet
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId
negativeKeywordListId:(long long)negativeKeywordListId;
@end
/**
* Lists negative keyword lists based on a given advertiser id.
*
* Method: displayvideo.advertisers.negativeKeywordLists.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersNegativeKeywordListsList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersNegativeKeywordListsListWithadvertiserId:]
/**
* Required. The ID of the DV360 advertiser to which the fetched negative
* keyword lists
* belong.
*/
@property(nonatomic, assign) long long advertiserId;
/**
* Requested page size. Must be between `1` and `100`.
* Defaults to `100` if not set. Returns error code `INVALID_ARGUMENT` if an
* invalid value is specified.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token
* returned from the previous call to `ListNegativeKeywordLists` method.
* If not specified, the first page of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/**
* Fetches a @c GTLRDisplayVideo_ListNegativeKeywordListsResponse.
*
* Lists negative keyword lists based on a given advertiser id.
*
* @param advertiserId Required. The ID of the DV360 advertiser to which the
* fetched negative keyword lists
* belong.
*
* @return GTLRDisplayVideoQuery_AdvertisersNegativeKeywordListsList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)queryWithAdvertiserId:(long long)advertiserId;
@end
/**
* Updates an existing advertiser.
* Returns the updated advertiser if successful.
*
* Method: displayvideo.advertisers.patch
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_AdvertisersPatch : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForAdvertisersPatchWithObject:advertiserId:]
/** Output only. The unique ID of the advertiser. Assigned by the system. */
@property(nonatomic, assign) long long advertiserId;
/**
* Required. The mask to control which fields to update.
*
* String format is a comma-separated list of fields.
*/
@property(nonatomic, copy, nullable) NSString *updateMask;
/**
* Fetches a @c GTLRDisplayVideo_Advertiser.
*
* Updates an existing advertiser.
* Returns the updated advertiser if successful.
*
* @param object The @c GTLRDisplayVideo_Advertiser to include in the query.
* @param advertiserId Output only. The unique ID of the advertiser. Assigned
* by the system.
*
* @return GTLRDisplayVideoQuery_AdvertisersPatch
*/
+ (instancetype)queryWithObject:(GTLRDisplayVideo_Advertiser *)object
advertiserId:(long long)advertiserId;
@end
/**
* Gets a combined audience.
*
* Method: displayvideo.combinedAudiences.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_CombinedAudiencesGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForCombinedAudiencesGetWithcombinedAudienceId:]
/**
* The ID of the advertiser that has access to the fetched combined
* audience.
*/
@property(nonatomic, assign) long long advertiserId;
/** Required. The ID of the combined audience to fetch. */
@property(nonatomic, assign) long long combinedAudienceId;
/** The ID of the partner that has access to the fetched combined audience. */
@property(nonatomic, assign) long long partnerId;
/**
* Fetches a @c GTLRDisplayVideo_CombinedAudience.
*
* Gets a combined audience.
*
* @param combinedAudienceId Required. The ID of the combined audience to
* fetch.
*
* @return GTLRDisplayVideoQuery_CombinedAudiencesGet
*/
+ (instancetype)queryWithCombinedAudienceId:(long long)combinedAudienceId;
@end
/**
* Lists combined audiences.
* The order is defined by the
* order_by parameter.
*
* Method: displayvideo.combinedAudiences.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_CombinedAudiencesList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForCombinedAudiencesList]
/**
* The ID of the advertiser that has access to the fetched combined
* audiences.
*/
@property(nonatomic, assign) long long advertiserId;
/**
* Allows filtering by combined audience fields.
* Supported syntax:
* * Filter expressions for combined audiences currently can only contain at
* most one restriction.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be `CONTAINS (:)`.
* * Supported fields:
* - `displayName`
* Examples:
* * All combined audiences for which the display name contains "Google":
* `displayName : "Google"`.
* The length of this field should be no more than 500 characters.
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Field by which to sort the list.
* Acceptable values are:
* * `combinedAudienceId` (default)
* * `displayName`
* The default sorting order is ascending. To specify descending order for
* a field, a suffix "desc" should be added to the field name. Example:
* `displayName desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size. Must be between `1` and `100`. If unspecified will
* default to `100`. Returns error code `INVALID_ARGUMENT` if an invalid value
* is specified.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token
* returned from the previous call to `ListCombinedAudiences` method.
* If not specified, the first page of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/**
* The ID of the partner that has access to the fetched combined audiences.
*/
@property(nonatomic, assign) long long partnerId;
/**
* Fetches a @c GTLRDisplayVideo_ListCombinedAudiencesResponse.
*
* Lists combined audiences.
* The order is defined by the
* order_by parameter.
*
* @return GTLRDisplayVideoQuery_CombinedAudiencesList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)query;
@end
/**
* Gets a custom list.
*
* Method: displayvideo.customLists.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_CustomListsGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForCustomListsGetWithcustomListId:]
/**
* The ID of the DV360 advertiser that has access to the fetched custom
* lists.
*/
@property(nonatomic, assign) long long advertiserId;
/** Required. The ID of the custom list to fetch. */
@property(nonatomic, assign) long long customListId;
/**
* Fetches a @c GTLRDisplayVideo_CustomList.
*
* Gets a custom list.
*
* @param customListId Required. The ID of the custom list to fetch.
*
* @return GTLRDisplayVideoQuery_CustomListsGet
*/
+ (instancetype)queryWithCustomListId:(long long)customListId;
@end
/**
* Lists custom lists.
* The order is defined by the order_by
* parameter.
*
* Method: displayvideo.customLists.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_CustomListsList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForCustomListsList]
/**
* The ID of the DV360 advertiser that has access to the fetched custom
* lists.
*/
@property(nonatomic, assign) long long advertiserId;
/**
* Allows filtering by custom list fields.
* Supported syntax:
* * Filter expressions for custom lists currently can only contain at
* most one restriction.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be `CONTAINS (:)`.
* * Supported fields:
* - `displayName`
* Examples:
* * All custom lists for which the display name contains "Google":
* `displayName : "Google"`.
* The length of this field should be no more than 500 characters.
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Field by which to sort the list.
* Acceptable values are:
* * `customListId` (default)
* * `displayName`
* The default sorting order is ascending. To specify descending order for
* a field, a suffix "desc" should be added to the field name. Example:
* `displayName desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size. Must be between `1` and `100`. If unspecified will
* default to `100`. Returns error code `INVALID_ARGUMENT` if an invalid value
* is specified.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token
* returned from the previous call to `ListCustomLists` method.
* If not specified, the first page of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/**
* Fetches a @c GTLRDisplayVideo_ListCustomListsResponse.
*
* Lists custom lists.
* The order is defined by the order_by
* parameter.
*
* @return GTLRDisplayVideoQuery_CustomListsList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)query;
@end
/**
* Gets a first and third party audience.
*
* Method: displayvideo.firstAndThirdPartyAudiences.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_FirstAndThirdPartyAudiencesGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForFirstAndThirdPartyAudiencesGetWithfirstAndThirdPartyAudienceId:]
/**
* The ID of the advertiser that has access to the fetched first and
* third party audience.
*/
@property(nonatomic, assign) long long advertiserId;
/** Required. The ID of the first and third party audience to fetch. */
@property(nonatomic, assign) long long firstAndThirdPartyAudienceId;
/**
* The ID of the partner that has access to the fetched first and
* third party audience.
*/
@property(nonatomic, assign) long long partnerId;
/**
* Fetches a @c GTLRDisplayVideo_FirstAndThirdPartyAudience.
*
* Gets a first and third party audience.
*
* @param firstAndThirdPartyAudienceId Required. The ID of the first and third
* party audience to fetch.
*
* @return GTLRDisplayVideoQuery_FirstAndThirdPartyAudiencesGet
*/
+ (instancetype)queryWithFirstAndThirdPartyAudienceId:(long long)firstAndThirdPartyAudienceId;
@end
/**
* Lists first and third party audiences.
* The order is defined by the
* order_by parameter.
*
* Method: displayvideo.firstAndThirdPartyAudiences.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_FirstAndThirdPartyAudiencesList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForFirstAndThirdPartyAudiencesList]
/**
* The ID of the advertiser that has access to the fetched first and
* third party audiences.
*/
@property(nonatomic, assign) long long advertiserId;
/**
* Allows filtering by first and third party audience fields.
* Supported syntax:
* * Filter expressions for first and third party audiences currently can
* only contain at most one restriction.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be `CONTAINS (:)`.
* * Supported fields:
* - `displayName`
* Examples:
* * All first and third party audiences for which the display name contains
* "Google": `displayName : "Google"`.
* The length of this field should be no more than 500 characters.
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Field by which to sort the list.
* Acceptable values are:
* * `firstAndThirdPartyAudienceId` (default)
* * `displayName`
* The default sorting order is ascending. To specify descending order for
* a field, a suffix "desc" should be added to the field name. Example:
* `displayName desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size. Must be between `1` and `100`. If unspecified will
* default to `100`. Returns error code `INVALID_ARGUMENT` if an invalid value
* is specified.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token
* returned from the previous call to `ListFirstAndThirdPartyAudiences`
* method. If not specified, the first page of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/**
* The ID of the partner that has access to the fetched first and
* third party audiences.
*/
@property(nonatomic, assign) long long partnerId;
/**
* Fetches a @c GTLRDisplayVideo_ListFirstAndThirdPartyAudiencesResponse.
*
* Lists first and third party audiences.
* The order is defined by the
* order_by parameter.
*
* @return GTLRDisplayVideoQuery_FirstAndThirdPartyAudiencesList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)query;
@end
/**
* Gets a Floodlight group.
*
* Method: displayvideo.floodlightGroups.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_FloodlightGroupsGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForFloodlightGroupsGetWithfloodlightGroupId:]
/** Required. The ID of the Floodlight group to fetch. */
@property(nonatomic, assign) long long floodlightGroupId;
/**
* Required. The partner context by which the Floodlight group is being
* accessed.
*/
@property(nonatomic, assign) long long partnerId;
/**
* Fetches a @c GTLRDisplayVideo_FloodlightGroup.
*
* Gets a Floodlight group.
*
* @param floodlightGroupId Required. The ID of the Floodlight group to fetch.
*
* @return GTLRDisplayVideoQuery_FloodlightGroupsGet
*/
+ (instancetype)queryWithFloodlightGroupId:(long long)floodlightGroupId;
@end
/**
* Updates an existing Floodlight group.
* Returns the updated Floodlight group if successful.
*
* Method: displayvideo.floodlightGroups.patch
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_FloodlightGroupsPatch : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForFloodlightGroupsPatchWithObject:floodlightGroupId:]
/**
* Output only. The unique ID of the Floodlight group. Assigned by the system.
*/
@property(nonatomic, assign) long long floodlightGroupId;
/**
* Required. The partner context by which the Floodlight group is being
* accessed.
*/
@property(nonatomic, assign) long long partnerId;
/**
* Required. The mask to control which fields to update.
*
* String format is a comma-separated list of fields.
*/
@property(nonatomic, copy, nullable) NSString *updateMask;
/**
* Fetches a @c GTLRDisplayVideo_FloodlightGroup.
*
* Updates an existing Floodlight group.
* Returns the updated Floodlight group if successful.
*
* @param object The @c GTLRDisplayVideo_FloodlightGroup to include in the
* query.
* @param floodlightGroupId Output only. The unique ID of the Floodlight group.
* Assigned by the system.
*
* @return GTLRDisplayVideoQuery_FloodlightGroupsPatch
*/
+ (instancetype)queryWithObject:(GTLRDisplayVideo_FloodlightGroup *)object
floodlightGroupId:(long long)floodlightGroupId;
@end
/**
* Gets a Google audience.
*
* Method: displayvideo.googleAudiences.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_GoogleAudiencesGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForGoogleAudiencesGetWithgoogleAudienceId:]
/**
* The ID of the advertiser that has access to the fetched Google audience.
*/
@property(nonatomic, assign) long long advertiserId;
/** Required. The ID of the Google audience to fetch. */
@property(nonatomic, assign) long long googleAudienceId;
/** The ID of the partner that has access to the fetched Google audience. */
@property(nonatomic, assign) long long partnerId;
/**
* Fetches a @c GTLRDisplayVideo_GoogleAudience.
*
* Gets a Google audience.
*
* @param googleAudienceId Required. The ID of the Google audience to fetch.
*
* @return GTLRDisplayVideoQuery_GoogleAudiencesGet
*/
+ (instancetype)queryWithGoogleAudienceId:(long long)googleAudienceId;
@end
/**
* Lists Google audiences.
* The order is defined by the order_by
* parameter.
*
* Method: displayvideo.googleAudiences.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_GoogleAudiencesList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForGoogleAudiencesList]
/**
* The ID of the advertiser that has access to the fetched Google audiences.
*/
@property(nonatomic, assign) long long advertiserId;
/**
* Allows filtering by Google audience fields.
* Supported syntax:
* * Filter expressions for Google audiences currently can only contain at
* most one restriction.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be `CONTAINS (:)`.
* * Supported fields:
* - `displayName`
* Examples:
* * All Google audiences for which the display name contains "Google":
* `displayName : "Google"`.
* The length of this field should be no more than 500 characters.
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Field by which to sort the list.
* Acceptable values are:
* * `googleAudienceId` (default)
* * `displayName`
* The default sorting order is ascending. To specify descending order for
* a field, a suffix "desc" should be added to the field name. Example:
* `displayName desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size. Must be between `1` and `100`. If unspecified will
* default to `100`. Returns error code `INVALID_ARGUMENT` if an invalid value
* is specified.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token
* returned from the previous call to `ListGoogleAudiences` method.
* If not specified, the first page of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/** The ID of the partner that has access to the fetched Google audiences. */
@property(nonatomic, assign) long long partnerId;
/**
* Fetches a @c GTLRDisplayVideo_ListGoogleAudiencesResponse.
*
* Lists Google audiences.
* The order is defined by the order_by
* parameter.
*
* @return GTLRDisplayVideoQuery_GoogleAudiencesList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)query;
@end
/**
* Gets an inventory source group.
*
* Method: displayvideo.inventorySourceGroups.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_InventorySourceGroupsGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForInventorySourceGroupsGetWithinventorySourceGroupId:]
/**
* The ID of the advertiser that has access to the inventory source group.
* If an inventory source group is partner-owned, only advertisers to which
* the group is explicitly shared can access the group.
*/
@property(nonatomic, assign) long long advertiserId;
/** Required. The ID of the inventory source group to fetch. */
@property(nonatomic, assign) long long inventorySourceGroupId;
/**
* The ID of the partner that has access to the inventory source group.
* A partner cannot access an advertiser-owned inventory source group.
*/
@property(nonatomic, assign) long long partnerId;
/**
* Fetches a @c GTLRDisplayVideo_InventorySourceGroup.
*
* Gets an inventory source group.
*
* @param inventorySourceGroupId Required. The ID of the inventory source group
* to fetch.
*
* @return GTLRDisplayVideoQuery_InventorySourceGroupsGet
*/
+ (instancetype)queryWithInventorySourceGroupId:(long long)inventorySourceGroupId;
@end
/**
* Lists inventory source groups that are accessible to the current user.
* The order is defined by the
* order_by parameter.
*
* Method: displayvideo.inventorySourceGroups.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_InventorySourceGroupsList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForInventorySourceGroupsList]
/**
* The ID of the advertiser that has access to the inventory source group.
* If an inventory source group is partner-owned, only advertisers to which
* the group is explicitly shared can access the group.
*/
@property(nonatomic, assign) long long advertiserId;
/**
* Allows filtering by inventory source group properties.
* Supported syntax:
* * Filter expressions are made up of one or more restrictions.
* * Restrictions can be combined by the logical operator `OR`.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be `EQUALS (=)`.
* * Supported fields:
* - `inventorySourceGroupId`
* The length of this field should be no more than 500 characters.
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Field by which to sort the list.
* Acceptable values are:
* * `displayName` (default)
* * `inventorySourceGroupId`
* The default sorting order is ascending. To specify descending order for
* a field, a suffix "desc" should be added to the field name. For example,
* `displayName desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size. Must be between `1` and `100`. If unspecified will
* default to `100`.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token
* returned from the previous call to `ListInventorySources` method.
* If not specified, the first page of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/**
* The ID of the partner that has access to the inventory source group.
* A partner cannot access advertiser-owned inventory source groups.
*/
@property(nonatomic, assign) long long partnerId;
/**
* Fetches a @c GTLRDisplayVideo_ListInventorySourceGroupsResponse.
*
* Lists inventory source groups that are accessible to the current user.
* The order is defined by the
* order_by parameter.
*
* @return GTLRDisplayVideoQuery_InventorySourceGroupsList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)query;
@end
/**
* Gets an inventory source.
*
* Method: displayvideo.inventorySources.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_InventorySourcesGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForInventorySourcesGetWithinventorySourceId:]
/** Required. The ID of the inventory source to fetch. */
@property(nonatomic, assign) long long inventorySourceId;
/**
* Required. The ID of the DV360 partner to which the fetched inventory source
* is permissioned.
*/
@property(nonatomic, assign) long long partnerId;
/**
* Fetches a @c GTLRDisplayVideo_InventorySource.
*
* Gets an inventory source.
*
* @param inventorySourceId Required. The ID of the inventory source to fetch.
*
* @return GTLRDisplayVideoQuery_InventorySourcesGet
*/
+ (instancetype)queryWithInventorySourceId:(long long)inventorySourceId;
@end
/**
* Lists inventory sources that are accessible to the current user.
* The order is defined by the
* order_by parameter.
* If a filter by
* entity_status is not
* specified, inventory sources with entity status `ENTITY_STATUS_ARCHIVED`
* will not be included in the results.
*
* Method: displayvideo.inventorySources.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_InventorySourcesList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForInventorySourcesList]
/** The ID of the advertiser that has access to the inventory source. */
@property(nonatomic, assign) long long advertiserId;
/**
* Allows filtering by inventory source properties.
* Supported syntax:
* * Filter expressions are made up of one or more restrictions.
* * Restrictions can be combined by `AND` or `OR` logical operators. A
* sequence of restrictions implicitly uses `AND`.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be `EQUALS (=)`.
* * Supported fields:
* - `status.entityStatus`
* - `commitment`
* - `deliveryMethod`
* - `rateDetails.rateType`
* - `exchange`
* Examples:
* * All active inventory sources:
* `status.entityStatus="ENTITY_STATUS_ACTIVE"`
* * Inventory sources belonging to Google Ad Manager or Rubicon exchanges:
* `exchange="EXCHANGE_GOOGLE_AD_MANAGER" OR exchange="EXCHANGE_RUBICON"`
* The length of this field should be no more than 500 characters.
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Field by which to sort the list.
* Acceptable values are:
* * `displayName` (default)
* The default sorting order is ascending. To specify descending order for
* a field, a suffix "desc" should be added to the field name. For example,
* `displayName desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size. Must be between `1` and `100`. If unspecified will
* default to `100`.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token
* returned from the previous call to `ListInventorySources` method.
* If not specified, the first page of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/** The ID of the partner that has access to the inventory source. */
@property(nonatomic, assign) long long partnerId;
/**
* Fetches a @c GTLRDisplayVideo_ListInventorySourcesResponse.
*
* Lists inventory sources that are accessible to the current user.
* The order is defined by the
* order_by parameter.
* If a filter by
* entity_status is not
* specified, inventory sources with entity status `ENTITY_STATUS_ARCHIVED`
* will not be included in the results.
*
* @return GTLRDisplayVideoQuery_InventorySourcesList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)query;
@end
/**
* Downloads media. Download is supported on the URI
* `/download/{resource_name=**}?alt=media.`
* **Note**: Download requests will not be successful without including
* `alt=media` query string.
*
* Method: displayvideo.media.download
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
* @c kGTLRAuthScopeDisplayVideoDoubleclickbidmanager
*/
@interface GTLRDisplayVideoQuery_MediaDownload : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForMediaDownloadWithresourceName:]
/**
* Name of the media that is being downloaded. See
* ReadRequest.resource_name.
*/
@property(nonatomic, copy, nullable) NSString *resourceName;
/**
* Fetches a @c GTLRDisplayVideo_GoogleBytestreamMedia.
*
* Downloads media. Download is supported on the URI
* `/download/{resource_name=**}?alt=media.`
* **Note**: Download requests will not be successful without including
* `alt=media` query string.
*
* @param resourceName Name of the media that is being downloaded. See
* ReadRequest.resource_name.
*
* @return GTLRDisplayVideoQuery_MediaDownload
*/
+ (instancetype)queryWithResourceName:(NSString *)resourceName;
/**
* Fetches the requested resource data as a @c GTLRDataObject.
*
* Downloads media. Download is supported on the URI
* `/download/{resource_name=**}?alt=media.`
* **Note**: Download requests will not be successful without including
* `alt=media` query string.
*
* @param resourceName Name of the media that is being downloaded. See
* ReadRequest.resource_name.
*
* @return GTLRDisplayVideoQuery_MediaDownload
*/
+ (instancetype)queryForMediaWithResourceName:(NSString *)resourceName;
@end
/**
* Gets a channel for a partner or advertiser.
*
* Method: displayvideo.partners.channels.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_PartnersChannelsGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForPartnersChannelsGetWithpartnerId:channelId:]
/** The ID of the advertiser that owns the fetched channel. */
@property(nonatomic, assign) long long advertiserId;
/** Required. The ID of the channel to fetch. */
@property(nonatomic, assign) long long channelId;
/** The ID of the partner that owns the fetched channel. */
@property(nonatomic, assign) long long partnerId;
/**
* Fetches a @c GTLRDisplayVideo_Channel.
*
* Gets a channel for a partner or advertiser.
*
* @param partnerId The ID of the partner that owns the fetched channel.
* @param channelId Required. The ID of the channel to fetch.
*
* @return GTLRDisplayVideoQuery_PartnersChannelsGet
*/
+ (instancetype)queryWithPartnerId:(long long)partnerId
channelId:(long long)channelId;
@end
/**
* Lists channels for a partner or advertiser.
*
* Method: displayvideo.partners.channels.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_PartnersChannelsList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForPartnersChannelsListWithpartnerId:]
/** The ID of the advertiser that owns the channels. */
@property(nonatomic, assign) long long advertiserId;
/**
* Allows filtering by channel fields.
* Supported syntax:
* * Filter expressions for channel currently can only contain at most one
* * restriction.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be `CONTAINS (:)`.
* * Supported fields:
* - `displayName`
* Examples:
* * All channels for which the display name contains "google":
* `displayName : "google"`.
* The length of this field should be no more than 500 characters.
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Field by which to sort the list.
* Acceptable values are:
* * `displayName` (default)
* * `channelId`
* The default sorting order is ascending. To specify descending order for a
* field, a suffix " desc" should be added to the field name. Example:
* `displayName desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size. Must be between `1` and `100`. If unspecified will
* default to `100`. Returns error code `INVALID_ARGUMENT` if an invalid value
* is specified.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token returned from the
* previous call to `ListChannels` method. If not specified, the first page
* of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/** The ID of the partner that owns the channels. */
@property(nonatomic, assign) long long partnerId;
/**
* Fetches a @c GTLRDisplayVideo_ListChannelsResponse.
*
* Lists channels for a partner or advertiser.
*
* @param partnerId The ID of the partner that owns the channels.
*
* @return GTLRDisplayVideoQuery_PartnersChannelsList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)queryWithPartnerId:(long long)partnerId;
@end
/**
* Creates an SDF Download Task. Returns an
* Operation.
* An SDF Download Task is a long-running, asynchronous operation. The
* metadata type of this operation is
* SdfDownloadTaskMetadata. If the request is successful, the
* response type of the operation is
* SdfDownloadTask. The response will not include the download files,
* which must be retrieved with
* media.download. The state of
* operation can be retrieved with
* sdfdownloadtask.operations.get.
* Any errors can be found in the
* error.message. Note
* that error.details is expected to be
* empty.
*
* Method: displayvideo.sdfdownloadtasks.create
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_SdfdownloadtasksCreate : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForSdfdownloadtasksCreateWithObject:]
/**
* Fetches a @c GTLRDisplayVideo_Operation.
*
* Creates an SDF Download Task. Returns an
* Operation.
* An SDF Download Task is a long-running, asynchronous operation. The
* metadata type of this operation is
* SdfDownloadTaskMetadata. If the request is successful, the
* response type of the operation is
* SdfDownloadTask. The response will not include the download files,
* which must be retrieved with
* media.download. The state of
* operation can be retrieved with
* sdfdownloadtask.operations.get.
* Any errors can be found in the
* error.message. Note
* that error.details is expected to be
* empty.
*
* @param object The @c GTLRDisplayVideo_CreateSdfDownloadTaskRequest to
* include in the query.
*
* @return GTLRDisplayVideoQuery_SdfdownloadtasksCreate
*/
+ (instancetype)queryWithObject:(GTLRDisplayVideo_CreateSdfDownloadTaskRequest *)object;
@end
/**
* Gets the latest state of an asynchronous SDF download task operation.
* Clients should poll this method at intervals of 30 seconds.
*
* Method: displayvideo.sdfdownloadtasks.operations.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
* @c kGTLRAuthScopeDisplayVideoDoubleclickbidmanager
*/
@interface GTLRDisplayVideoQuery_SdfdownloadtasksOperationsGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForSdfdownloadtasksOperationsGetWithname:]
/** The name of the operation resource. */
@property(nonatomic, copy, nullable) NSString *name;
/**
* Fetches a @c GTLRDisplayVideo_Operation.
*
* Gets the latest state of an asynchronous SDF download task operation.
* Clients should poll this method at intervals of 30 seconds.
*
* @param name The name of the operation resource.
*
* @return GTLRDisplayVideoQuery_SdfdownloadtasksOperationsGet
*/
+ (instancetype)queryWithName:(NSString *)name;
@end
/**
* Gets a single targeting option.
*
* Method: displayvideo.targetingTypes.targetingOptions.get
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_TargetingTypesTargetingOptionsGet : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForTargetingTypesTargetingOptionsGetWithtargetingType:targetingOptionId:]
/** Required. The Advertiser this request is being made in the context of. */
@property(nonatomic, assign) long long advertiserId;
/** Required. The ID of the of targeting option to retrieve. */
@property(nonatomic, copy, nullable) NSString *targetingOptionId;
/**
* Required. The type of targeting option to retrieve.
*
* Likely values:
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUnspecified Value
* "TARGETING_TYPE_UNSPECIFIED"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeChannel Value
* "TARGETING_TYPE_CHANNEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAppCategory Value
* "TARGETING_TYPE_APP_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeApp Value
* "TARGETING_TYPE_APP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUrl Value
* "TARGETING_TYPE_URL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDayAndTime Value
* "TARGETING_TYPE_DAY_AND_TIME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAgeRange Value
* "TARGETING_TYPE_AGE_RANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeRegionalLocationList
* Value "TARGETING_TYPE_REGIONAL_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocationList
* Value "TARGETING_TYPE_PROXIMITY_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGender Value
* "TARGETING_TYPE_GENDER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeVideoPlayerSize Value
* "TARGETING_TYPE_VIDEO_PLAYER_SIZE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUserRewardedContent
* Value "TARGETING_TYPE_USER_REWARDED_CONTENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeParentalStatus Value
* "TARGETING_TYPE_PARENTAL_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentInstreamPosition
* Value "TARGETING_TYPE_CONTENT_INSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentOutstreamPosition
* Value "TARGETING_TYPE_CONTENT_OUTSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceType Value
* "TARGETING_TYPE_DEVICE_TYPE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAudienceGroup Value
* "TARGETING_TYPE_AUDIENCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeBrowser Value
* "TARGETING_TYPE_BROWSER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeHouseholdIncome Value
* "TARGETING_TYPE_HOUSEHOLD_INCOME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOnScreenPosition Value
* "TARGETING_TYPE_ON_SCREEN_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeThirdPartyVerifier
* Value "TARGETING_TYPE_THIRD_PARTY_VERIFIER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDigitalContentLabelExclusion
* Value "TARGETING_TYPE_DIGITAL_CONTENT_LABEL_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSensitiveCategoryExclusion
* Value "TARGETING_TYPE_SENSITIVE_CATEGORY_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeEnvironment Value
* "TARGETING_TYPE_ENVIRONMENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCarrierAndIsp Value
* "TARGETING_TYPE_CARRIER_AND_ISP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOperatingSystem Value
* "TARGETING_TYPE_OPERATING_SYSTEM"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceMakeModel Value
* "TARGETING_TYPE_DEVICE_MAKE_MODEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeKeyword Value
* "TARGETING_TYPE_KEYWORD"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeNegativeKeywordList
* Value "TARGETING_TYPE_NEGATIVE_KEYWORD_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeViewability Value
* "TARGETING_TYPE_VIEWABILITY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCategory Value
* "TARGETING_TYPE_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySource Value
* "TARGETING_TYPE_INVENTORY_SOURCE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeLanguage Value
* "TARGETING_TYPE_LANGUAGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAuthorizedSellerStatus
* Value "TARGETING_TYPE_AUTHORIZED_SELLER_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGeoRegion Value
* "TARGETING_TYPE_GEO_REGION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySourceGroup
* Value "TARGETING_TYPE_INVENTORY_SOURCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocation Value
* "TARGETING_TYPE_PROXIMITY_LOCATION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeExchange Value
* "TARGETING_TYPE_EXCHANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSubExchange Value
* "TARGETING_TYPE_SUB_EXCHANGE"
*/
@property(nonatomic, copy, nullable) NSString *targetingType;
/**
* Fetches a @c GTLRDisplayVideo_TargetingOption.
*
* Gets a single targeting option.
*
* @param targetingType Required. The type of targeting option to retrieve.
* @param targetingOptionId Required. The ID of the of targeting option to
* retrieve.
*
* Likely values for @c targetingType:
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUnspecified Value
* "TARGETING_TYPE_UNSPECIFIED"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeChannel Value
* "TARGETING_TYPE_CHANNEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAppCategory Value
* "TARGETING_TYPE_APP_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeApp Value
* "TARGETING_TYPE_APP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUrl Value
* "TARGETING_TYPE_URL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDayAndTime Value
* "TARGETING_TYPE_DAY_AND_TIME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAgeRange Value
* "TARGETING_TYPE_AGE_RANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeRegionalLocationList
* Value "TARGETING_TYPE_REGIONAL_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocationList
* Value "TARGETING_TYPE_PROXIMITY_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGender Value
* "TARGETING_TYPE_GENDER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeVideoPlayerSize Value
* "TARGETING_TYPE_VIDEO_PLAYER_SIZE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUserRewardedContent
* Value "TARGETING_TYPE_USER_REWARDED_CONTENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeParentalStatus Value
* "TARGETING_TYPE_PARENTAL_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentInstreamPosition
* Value "TARGETING_TYPE_CONTENT_INSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentOutstreamPosition
* Value "TARGETING_TYPE_CONTENT_OUTSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceType Value
* "TARGETING_TYPE_DEVICE_TYPE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAudienceGroup Value
* "TARGETING_TYPE_AUDIENCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeBrowser Value
* "TARGETING_TYPE_BROWSER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeHouseholdIncome Value
* "TARGETING_TYPE_HOUSEHOLD_INCOME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOnScreenPosition Value
* "TARGETING_TYPE_ON_SCREEN_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeThirdPartyVerifier
* Value "TARGETING_TYPE_THIRD_PARTY_VERIFIER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDigitalContentLabelExclusion
* Value "TARGETING_TYPE_DIGITAL_CONTENT_LABEL_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSensitiveCategoryExclusion
* Value "TARGETING_TYPE_SENSITIVE_CATEGORY_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeEnvironment Value
* "TARGETING_TYPE_ENVIRONMENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCarrierAndIsp Value
* "TARGETING_TYPE_CARRIER_AND_ISP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOperatingSystem Value
* "TARGETING_TYPE_OPERATING_SYSTEM"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceMakeModel Value
* "TARGETING_TYPE_DEVICE_MAKE_MODEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeKeyword Value
* "TARGETING_TYPE_KEYWORD"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeNegativeKeywordList
* Value "TARGETING_TYPE_NEGATIVE_KEYWORD_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeViewability Value
* "TARGETING_TYPE_VIEWABILITY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCategory Value
* "TARGETING_TYPE_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySource Value
* "TARGETING_TYPE_INVENTORY_SOURCE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeLanguage Value
* "TARGETING_TYPE_LANGUAGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAuthorizedSellerStatus
* Value "TARGETING_TYPE_AUTHORIZED_SELLER_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGeoRegion Value
* "TARGETING_TYPE_GEO_REGION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySourceGroup
* Value "TARGETING_TYPE_INVENTORY_SOURCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocation Value
* "TARGETING_TYPE_PROXIMITY_LOCATION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeExchange Value
* "TARGETING_TYPE_EXCHANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSubExchange Value
* "TARGETING_TYPE_SUB_EXCHANGE"
*
* @return GTLRDisplayVideoQuery_TargetingTypesTargetingOptionsGet
*/
+ (instancetype)queryWithTargetingType:(NSString *)targetingType
targetingOptionId:(NSString *)targetingOptionId;
@end
/**
* Lists targeting options of a given type.
*
* Method: displayvideo.targetingTypes.targetingOptions.list
*
* Authorization scope(s):
* @c kGTLRAuthScopeDisplayVideoDisplayVideo
*/
@interface GTLRDisplayVideoQuery_TargetingTypesTargetingOptionsList : GTLRDisplayVideoQuery
// Previous library name was
// +[GTLQueryDisplayVideo queryForTargetingTypesTargetingOptionsListWithtargetingType:]
/** Required. The Advertiser this request is being made in the context of. */
@property(nonatomic, assign) long long advertiserId;
/**
* Allows filtering by targeting option properties.
* Supported syntax:
* * Filter expressions are made up of one or more restrictions.
* * Restrictions can be combined by `OR` logical operators.
* * A restriction has the form of `{field} {operator} {value}`.
* * The operator must be "=" (equal sign).
* * Supported fields:
* - `targetingOptionId`
* The length of this field should be no more than 500 characters.
*/
@property(nonatomic, copy, nullable) NSString *filter;
/**
* Field by which to sort the list.
* Acceptable values are:
* * `targetingOptionId` (default)
* The default sorting order is ascending. To specify descending order for
* a field, a suffix "desc" should be added to the field name.
* Example: `targetingOptionId desc`.
*/
@property(nonatomic, copy, nullable) NSString *orderBy;
/**
* Requested page size. Must be between `1` and `100`. If unspecified will
* default to `100`. Returns error code `INVALID_ARGUMENT` if an invalid value
* is specified.
*/
@property(nonatomic, assign) NSInteger pageSize;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* next_page_token
* returned from the previous call to `ListTargetingOptions` method.
* If not specified, the first page of results will be returned.
*/
@property(nonatomic, copy, nullable) NSString *pageToken;
/**
* Required. The type of targeting option to be listed.
*
* Likely values:
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUnspecified Value
* "TARGETING_TYPE_UNSPECIFIED"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeChannel Value
* "TARGETING_TYPE_CHANNEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAppCategory Value
* "TARGETING_TYPE_APP_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeApp Value
* "TARGETING_TYPE_APP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUrl Value
* "TARGETING_TYPE_URL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDayAndTime Value
* "TARGETING_TYPE_DAY_AND_TIME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAgeRange Value
* "TARGETING_TYPE_AGE_RANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeRegionalLocationList
* Value "TARGETING_TYPE_REGIONAL_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocationList
* Value "TARGETING_TYPE_PROXIMITY_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGender Value
* "TARGETING_TYPE_GENDER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeVideoPlayerSize Value
* "TARGETING_TYPE_VIDEO_PLAYER_SIZE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUserRewardedContent
* Value "TARGETING_TYPE_USER_REWARDED_CONTENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeParentalStatus Value
* "TARGETING_TYPE_PARENTAL_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentInstreamPosition
* Value "TARGETING_TYPE_CONTENT_INSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentOutstreamPosition
* Value "TARGETING_TYPE_CONTENT_OUTSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceType Value
* "TARGETING_TYPE_DEVICE_TYPE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAudienceGroup Value
* "TARGETING_TYPE_AUDIENCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeBrowser Value
* "TARGETING_TYPE_BROWSER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeHouseholdIncome Value
* "TARGETING_TYPE_HOUSEHOLD_INCOME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOnScreenPosition Value
* "TARGETING_TYPE_ON_SCREEN_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeThirdPartyVerifier
* Value "TARGETING_TYPE_THIRD_PARTY_VERIFIER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDigitalContentLabelExclusion
* Value "TARGETING_TYPE_DIGITAL_CONTENT_LABEL_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSensitiveCategoryExclusion
* Value "TARGETING_TYPE_SENSITIVE_CATEGORY_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeEnvironment Value
* "TARGETING_TYPE_ENVIRONMENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCarrierAndIsp Value
* "TARGETING_TYPE_CARRIER_AND_ISP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOperatingSystem Value
* "TARGETING_TYPE_OPERATING_SYSTEM"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceMakeModel Value
* "TARGETING_TYPE_DEVICE_MAKE_MODEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeKeyword Value
* "TARGETING_TYPE_KEYWORD"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeNegativeKeywordList
* Value "TARGETING_TYPE_NEGATIVE_KEYWORD_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeViewability Value
* "TARGETING_TYPE_VIEWABILITY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCategory Value
* "TARGETING_TYPE_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySource Value
* "TARGETING_TYPE_INVENTORY_SOURCE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeLanguage Value
* "TARGETING_TYPE_LANGUAGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAuthorizedSellerStatus
* Value "TARGETING_TYPE_AUTHORIZED_SELLER_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGeoRegion Value
* "TARGETING_TYPE_GEO_REGION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySourceGroup
* Value "TARGETING_TYPE_INVENTORY_SOURCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocation Value
* "TARGETING_TYPE_PROXIMITY_LOCATION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeExchange Value
* "TARGETING_TYPE_EXCHANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSubExchange Value
* "TARGETING_TYPE_SUB_EXCHANGE"
*/
@property(nonatomic, copy, nullable) NSString *targetingType;
/**
* Fetches a @c GTLRDisplayVideo_ListTargetingOptionsResponse.
*
* Lists targeting options of a given type.
*
* @param targetingType Required. The type of targeting option to be listed.
*
* Likely values for @c targetingType:
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUnspecified Value
* "TARGETING_TYPE_UNSPECIFIED"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeChannel Value
* "TARGETING_TYPE_CHANNEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAppCategory Value
* "TARGETING_TYPE_APP_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeApp Value
* "TARGETING_TYPE_APP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUrl Value
* "TARGETING_TYPE_URL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDayAndTime Value
* "TARGETING_TYPE_DAY_AND_TIME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAgeRange Value
* "TARGETING_TYPE_AGE_RANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeRegionalLocationList
* Value "TARGETING_TYPE_REGIONAL_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocationList
* Value "TARGETING_TYPE_PROXIMITY_LOCATION_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGender Value
* "TARGETING_TYPE_GENDER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeVideoPlayerSize Value
* "TARGETING_TYPE_VIDEO_PLAYER_SIZE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeUserRewardedContent
* Value "TARGETING_TYPE_USER_REWARDED_CONTENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeParentalStatus Value
* "TARGETING_TYPE_PARENTAL_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentInstreamPosition
* Value "TARGETING_TYPE_CONTENT_INSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeContentOutstreamPosition
* Value "TARGETING_TYPE_CONTENT_OUTSTREAM_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceType Value
* "TARGETING_TYPE_DEVICE_TYPE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAudienceGroup Value
* "TARGETING_TYPE_AUDIENCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeBrowser Value
* "TARGETING_TYPE_BROWSER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeHouseholdIncome Value
* "TARGETING_TYPE_HOUSEHOLD_INCOME"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOnScreenPosition Value
* "TARGETING_TYPE_ON_SCREEN_POSITION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeThirdPartyVerifier
* Value "TARGETING_TYPE_THIRD_PARTY_VERIFIER"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDigitalContentLabelExclusion
* Value "TARGETING_TYPE_DIGITAL_CONTENT_LABEL_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSensitiveCategoryExclusion
* Value "TARGETING_TYPE_SENSITIVE_CATEGORY_EXCLUSION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeEnvironment Value
* "TARGETING_TYPE_ENVIRONMENT"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCarrierAndIsp Value
* "TARGETING_TYPE_CARRIER_AND_ISP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeOperatingSystem Value
* "TARGETING_TYPE_OPERATING_SYSTEM"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeDeviceMakeModel Value
* "TARGETING_TYPE_DEVICE_MAKE_MODEL"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeKeyword Value
* "TARGETING_TYPE_KEYWORD"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeNegativeKeywordList
* Value "TARGETING_TYPE_NEGATIVE_KEYWORD_LIST"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeViewability Value
* "TARGETING_TYPE_VIEWABILITY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeCategory Value
* "TARGETING_TYPE_CATEGORY"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySource Value
* "TARGETING_TYPE_INVENTORY_SOURCE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeLanguage Value
* "TARGETING_TYPE_LANGUAGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeAuthorizedSellerStatus
* Value "TARGETING_TYPE_AUTHORIZED_SELLER_STATUS"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeGeoRegion Value
* "TARGETING_TYPE_GEO_REGION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeInventorySourceGroup
* Value "TARGETING_TYPE_INVENTORY_SOURCE_GROUP"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeProximityLocation Value
* "TARGETING_TYPE_PROXIMITY_LOCATION"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeExchange Value
* "TARGETING_TYPE_EXCHANGE"
* @arg @c kGTLRDisplayVideoTargetingTypeTargetingTypeSubExchange Value
* "TARGETING_TYPE_SUB_EXCHANGE"
*
* @return GTLRDisplayVideoQuery_TargetingTypesTargetingOptionsList
*
* @note Automatic pagination will be done when @c shouldFetchNextPages is
* enabled. See @c shouldFetchNextPages on @c GTLRService for more
* information.
*/
+ (instancetype)queryWithTargetingType:(NSString *)targetingType;
@end
NS_ASSUME_NONNULL_END
#pragma clang diagnostic pop
| 39.673135 | 169 | 0.761784 | [
"object"
] |
96b31b92ee52a11f28171f0b1af5e53b994dc1fc | 5,175 | h | C | src/baseScene.h | roymacdonald/ReCoded | 3bcb3d579cdd17381e54a508a1e4ef9e3d5bc4f1 | [
"MIT"
] | null | null | null | src/baseScene.h | roymacdonald/ReCoded | 3bcb3d579cdd17381e54a508a1e4ef9e3d5bc4f1 | [
"MIT"
] | null | null | null | src/baseScene.h | roymacdonald/ReCoded | 3bcb3d579cdd17381e54a508a1e4ef9e3d5bc4f1 | [
"MIT"
] | null | null | null |
#pragma once
#include "ofMain.h"
//#include "appConstants.h"
#include "ofxXmlSettings.h"
//#ifdef USE_MIDI_RECORDING
#include "ofxMidiRecorder.h"
//#endif
#include "appConstants.h"
void reportKnobs(string f);
class baseScene {
public:
virtual void setup(){}
virtual void update(){}
virtual void draw(){}
vector < float > origFloatValues;
vector < bool > origBoolValues;
vector < int > origIntValues;
void postSetup(){
for (auto & p : boolParams){
origBoolValues.push_back(p.get());
}
for (auto & p : floatParams){
origFloatValues.push_back(p.get());
}
for (auto & p : intParams){
origIntValues.push_back(p.get());
}
// vector<ofParameter<bool>> boolParams;
// vector<ofParameter<int>> intParams;
// vector<ofParameter<float>> floatParams;
}
// ofParameterGroup parametersCopy;
// virtual void postSetupSetup(){
// parametersCopy = parameters;
// }
void reset(){
resetTiming();
ofParameter<bool> boolParam;
ofParameter<int> intParam;
ofParameter<float> floatParam;
int boolCount = 0;
int intCount = 0;
int floatCount = 0;
for (auto param : parameters) {
if (param->type() == boolParam.type()) {
ofParameter<bool> &oldParam = param->cast<bool>();
oldParam.set(origBoolValues[boolCount]);
boolCount++;
} else if (param->type() == intParam.type()) {
ofParameter<int> &oldParam = param->cast<int>();
oldParam.set(origIntValues[intCount]);
intCount++;
} else if (param->type() == floatParam.type()) {
ofParameter<float> &oldParam = param->cast<float>();
oldParam.set(origFloatValues[floatCount]);
floatCount++;
}
}
// for (int i = 0; i < boolParams.size(); i++){
// boolParams[i].set(origBoolValues[i]);
// cout << "settings " << boolParams[i].getName() << " " << origBoolValues[i] << endl;
//
// //origBoolValues.push_back(p.get());
// }
//
// for (int i = 0; i < intParams.size(); i++){
// intParams[i].set(origIntValues[i]);
// cout << "settings " << intParams[i].getName() << " " << origIntValues[i] << endl;
// //origBoolValues.push_back(p.get());
// }
// for (int i = 0; i < floatParams.size(); i++){
// floatParams[i].set(origFloatValues[i]);
// cout << "settings " << floatParams[i].getName() << " " << origFloatValues[i] << endl;
// //origBoolValues.push_back(p.get());
// }
// for (int i = 0; i < parametersCopy.size(); i++){
// //parameters.set(parametersCopy.get(i).
//
// }
} // this is for scenes that change over time....
baseScene(){};
virtual ~baseScene(){}
void enableMidi();
void updateMidiParams();
vector<char> paramTypes;
void loadCode( string fileName, bool bShowAuthorAndArtistNames = true);
void setAuthor(string author);
void setOriginalArtist(string originalArtist);
int horribleKnobCounter = 0;
ofParameterGroup parameters; // this is the parameters of your sketch...
vector<ofParameter<bool>> boolParams;
vector<ofParameter<int>> intParams;
vector<ofParameter<float>> floatParams;
map<int,int> paramMap;
ofParameterGroup midiParameters;
string code; // this is the code we show
string author, originalArtist; // for scene transitions
ofRectangle dimensions; // this is the dimensions of
// the surface you are drawing into.
//#ifdef USE_MIDI_RECORDING
vector<ofxMidiRecordingEvent> recData;
string dataPath;
void setRecData(const vector<ofxMidiRecordingEvent>& data);
const vector<ofxMidiRecordingEvent>& getRecData();
bool hasRecData();
//#endif
//----------------------------------------
// scene timing and frames.
uint64_t startTime;
uint64_t startFrame;
float getElapsedTimef();
uint64_t getFrameNum();
void resetTiming();
//----------------------------------------
bool bIsSceneDone;
float sceneDuration = 25.0f;
static float smoothingSpeed;
bool isSceneDone();
void setSceneEnd();
void setSceneEnd(float time);
bool bHasEndSet;
bool isEndSet(){return bHasEndSet;}
bool bAnimateScene;
void reportKnobs(string f);
bool bUpdateParamFromRecording = true;
void updateInteractiveParams(float valChangeAsPct, int param, float abspct = 1.0);
vector < int > midiKnobs;
float defaultDuration = 45;
#ifdef TEST_SCENES
ofParameter<bool> bSceneTested = {"SceneTested", false};
ofParameter<bool> bBlacklist = {"Blacklist", false};
#endif
};
| 29.741379 | 99 | 0.55401 | [
"vector"
] |
96b9d1203582b265a9ae817cd462315063abc244 | 1,948 | h | C | libraries/include/hshare_wallet/hshare_addr_util.h | tiaotiao00/HSR00qianbao | a88afebeb98e786389f369447bcf9c3a2a352cfa | [
"MIT"
] | 66 | 2017-09-29T07:09:59.000Z | 2020-01-12T06:45:08.000Z | libraries/include/hshare_wallet/hshare_addr_util.h | tiaotiao00/HSR00qianbao | a88afebeb98e786389f369447bcf9c3a2a352cfa | [
"MIT"
] | 5 | 2017-12-13T13:12:05.000Z | 2018-01-18T10:34:02.000Z | libraries/include/hshare_wallet/hshare_addr_util.h | tiaotiao00/HSR00qianbao | a88afebeb98e786389f369447bcf9c3a2a352cfa | [
"MIT"
] | 11 | 2017-12-05T07:02:05.000Z | 2018-01-28T02:52:50.000Z | #pragma once
#ifndef HSHARE_ADDR_UTIL_H
#define HSHARE_ADDR_UTIL_H
#include "db.h"
#include "blockchain/Address.hpp"
#include "fc/crypto/elliptic.hpp"
#include "blockchain/PtsAddress.hpp"
#include <utilities/KeyConversion.hpp>
#include <openssl/ec.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <set>
#include "allocators.h"
#include <utilities/uint256.hpp>
//#include "key.hpp"
#include "privateConvert.hpp"
#include <fc/variant.hpp>
#include <openssl/sha.h>
namespace hshare
{
#define COMPRESSED 33
#define UNCOMPRESSED 65
typedef std::vector<unsigned char, secure_allocator<unsigned char> > CKeyingMaterial;
typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
const unsigned int WALLET_CRYPTO_KEY_SIZE = 32;
const unsigned int WALLET_CRYPTO_SALT_SIZE = 8;
class CMasterKey
{
public:
std::vector<unsigned char> vchCryptedKey;
std::vector<unsigned char> vchSalt;
// 0 = EVP_sha512()
// 1 = scrypt()
unsigned int nDerivationMethod;
unsigned int nDeriveIterations;
// Use this for more parameters to key derivation,
// such as the various parameters to scrypt
std::vector<unsigned char> vchOtherDerivationParameters;
IMPLEMENT_SERIALIZE
(
READWRITE(vchCryptedKey);
READWRITE(vchSalt);
READWRITE(nDerivationMethod);
READWRITE(nDeriveIterations);
READWRITE(vchOtherDerivationParameters);
)
CMasterKey()
{
// 25000 rounds is just under 0.1 seconds on a 1.86 GHz Pentium M
// ie slightly lower than the lowest hardware we need bother supporting
nDeriveIterations = 25000;
nDerivationMethod = 1;
vchOtherDerivationParameters = std::vector<unsigned char>(0);
}
};
DBErrors getUnencryptKeys(std::vector<std::string>& vwif, const std::string& infile = "wallet.dat");
DBErrors getEncryptKeys(std::vector<std::string>& vwif, const std::string& passwd, const std::string& infile = "wallet.dat");
}
#endif
| 24.658228 | 126 | 0.74538 | [
"vector"
] |
96ce25d725ca41765d63e0a6b3889a2f83e5abb9 | 4,969 | h | C | aws-cpp-sdk-macie2/include/aws/macie2/model/PutFindingsPublicationConfigurationRequest.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-macie2/include/aws/macie2/model/PutFindingsPublicationConfigurationRequest.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-macie2/include/aws/macie2/model/PutFindingsPublicationConfigurationRequest.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/macie2/Macie2_EXPORTS.h>
#include <aws/macie2/Macie2Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/macie2/model/SecurityHubConfiguration.h>
#include <utility>
#include <aws/core/utils/UUID.h>
namespace Aws
{
namespace Macie2
{
namespace Model
{
/**
*/
class AWS_MACIE2_API PutFindingsPublicationConfigurationRequest : public Macie2Request
{
public:
PutFindingsPublicationConfigurationRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "PutFindingsPublicationConfiguration"; }
Aws::String SerializePayload() const override;
/**
* <p>A unique, case-sensitive token that you provide to ensure the idempotency of
* the request.</p>
*/
inline const Aws::String& GetClientToken() const{ return m_clientToken; }
/**
* <p>A unique, case-sensitive token that you provide to ensure the idempotency of
* the request.</p>
*/
inline bool ClientTokenHasBeenSet() const { return m_clientTokenHasBeenSet; }
/**
* <p>A unique, case-sensitive token that you provide to ensure the idempotency of
* the request.</p>
*/
inline void SetClientToken(const Aws::String& value) { m_clientTokenHasBeenSet = true; m_clientToken = value; }
/**
* <p>A unique, case-sensitive token that you provide to ensure the idempotency of
* the request.</p>
*/
inline void SetClientToken(Aws::String&& value) { m_clientTokenHasBeenSet = true; m_clientToken = std::move(value); }
/**
* <p>A unique, case-sensitive token that you provide to ensure the idempotency of
* the request.</p>
*/
inline void SetClientToken(const char* value) { m_clientTokenHasBeenSet = true; m_clientToken.assign(value); }
/**
* <p>A unique, case-sensitive token that you provide to ensure the idempotency of
* the request.</p>
*/
inline PutFindingsPublicationConfigurationRequest& WithClientToken(const Aws::String& value) { SetClientToken(value); return *this;}
/**
* <p>A unique, case-sensitive token that you provide to ensure the idempotency of
* the request.</p>
*/
inline PutFindingsPublicationConfigurationRequest& WithClientToken(Aws::String&& value) { SetClientToken(std::move(value)); return *this;}
/**
* <p>A unique, case-sensitive token that you provide to ensure the idempotency of
* the request.</p>
*/
inline PutFindingsPublicationConfigurationRequest& WithClientToken(const char* value) { SetClientToken(value); return *this;}
/**
* <p>The configuration settings that determine which findings to publish to
* Security Hub.</p>
*/
inline const SecurityHubConfiguration& GetSecurityHubConfiguration() const{ return m_securityHubConfiguration; }
/**
* <p>The configuration settings that determine which findings to publish to
* Security Hub.</p>
*/
inline bool SecurityHubConfigurationHasBeenSet() const { return m_securityHubConfigurationHasBeenSet; }
/**
* <p>The configuration settings that determine which findings to publish to
* Security Hub.</p>
*/
inline void SetSecurityHubConfiguration(const SecurityHubConfiguration& value) { m_securityHubConfigurationHasBeenSet = true; m_securityHubConfiguration = value; }
/**
* <p>The configuration settings that determine which findings to publish to
* Security Hub.</p>
*/
inline void SetSecurityHubConfiguration(SecurityHubConfiguration&& value) { m_securityHubConfigurationHasBeenSet = true; m_securityHubConfiguration = std::move(value); }
/**
* <p>The configuration settings that determine which findings to publish to
* Security Hub.</p>
*/
inline PutFindingsPublicationConfigurationRequest& WithSecurityHubConfiguration(const SecurityHubConfiguration& value) { SetSecurityHubConfiguration(value); return *this;}
/**
* <p>The configuration settings that determine which findings to publish to
* Security Hub.</p>
*/
inline PutFindingsPublicationConfigurationRequest& WithSecurityHubConfiguration(SecurityHubConfiguration&& value) { SetSecurityHubConfiguration(std::move(value)); return *this;}
private:
Aws::String m_clientToken;
bool m_clientTokenHasBeenSet;
SecurityHubConfiguration m_securityHubConfiguration;
bool m_securityHubConfigurationHasBeenSet;
};
} // namespace Model
} // namespace Macie2
} // namespace Aws
| 37.08209 | 181 | 0.718052 | [
"model"
] |
96d4a14ffb97528384c68c5e99b8e8f970ec4050 | 4,737 | h | C | src/Structure/BoundaryElement.h | allen-cell-animated/medyan | 0b5ef64fb338c3961673361e5632980617937ee6 | [
"BSD-4-Clause-UC"
] | null | null | null | src/Structure/BoundaryElement.h | allen-cell-animated/medyan | 0b5ef64fb338c3961673361e5632980617937ee6 | [
"BSD-4-Clause-UC"
] | null | null | null | src/Structure/BoundaryElement.h | allen-cell-animated/medyan | 0b5ef64fb338c3961673361e5632980617937ee6 | [
"BSD-4-Clause-UC"
] | null | null | null |
//------------------------------------------------------------------
// **MEDYAN** - Simulation Package for the Mechanochemical
// Dynamics of Active Networks, v4.0
//
// Copyright (2015-2018) Papoian Lab, University of Maryland
//
// ALL RIGHTS RESERVED
//
// See the MEDYAN web page for more information:
// http://www.medyan.org
//------------------------------------------------------------------
#ifndef MEDYAN_BoundaryElement_h
#define MEDYAN_BoundaryElement_h
#include <iostream>
#include "common.h"
#include "Database.h"
#include "Trackable.h"
#include "Neighbor.h"
#include "Component.h"
#include "GController.h"
//FORWARD DECLARATIONS
class Bead;
/// Represents an element of a BoundarySurface.
/*!
* The BoundaryElement class is a representation of a BoundarySurface element, which can
* interact with other elements in the system, including other BoundaryElements as well
* as [Beads] (@ref Bead) in [Filaments](@ref Filament) and [Bubbles](@ref Bubble).
* Together, a collection of boundary elements make up a BoundarySurface.
*
* Extending the Neighbor class, all instances can be kept in
* [NeighborLists](@ref NeighborList).
*/
class BoundaryElement : public Component, public Trackable, public Neighbor,
public Database< BoundaryElement, false > {
friend class BoundaryCubic;
friend class BoundarySpherical;
friend class BoundaryCapsule;
friend class BoundaryCylinder;
protected:
vector<floatingpoint> _coords; ///< coordinates
floatingpoint _kRep; ///< Repulsion constant
floatingpoint _r0; ///< Screening length
public:
/// Default constructor
BoundaryElement(vector<floatingpoint> coords, floatingpoint kRepuls, floatingpoint screenLength)
: Trackable(false, false, false, true),
_coords(coords), _kRep(kRepuls), _r0(screenLength) {}
/// Destructor
/// @note noexcept is important here. Otherwise, gcc flags the constructor as
/// potentially throwing, which in turn disables move operations by the STL
/// containers. This behaviour is a gcc bug (as of gcc 4.703), and will presumbaly
/// be fixed in the future.
virtual ~BoundaryElement() noexcept {}
///return coordinates of boundary element
const vector<floatingpoint>& getCoords() {return _coords;}
///update the coordinates of the boundary element
virtual void updateCoords(const vector<floatingpoint> newCoords) = 0;
//@{
/// Implement for all boundary elements
/// Returns the distance from a given point to this boundary element
/// @return - 1) positive number if point is within boundary element
/// 2) Negative number if point is outside boundary element
/// 3) Infinity if point is not in domain of this boundary element
virtual floatingpoint distance(const vector<floatingpoint>& point) = 0;
virtual floatingpoint distance(floatingpoint const *point) = 0;
//@}
//@{
virtual floatingpoint lowerdistance(const vector<floatingpoint>& point) = 0;
virtual floatingpoint sidedistance(const vector<floatingpoint>& point) = 0;
/// Returns stretched distance, similar to distance above
virtual floatingpoint stretchedDistance(const vector<floatingpoint>& point,
const vector<floatingpoint>& force,
floatingpoint d) = 0;
virtual floatingpoint stretchedDistance(floatingpoint const *point,
floatingpoint const *force, floatingpoint d)
= 0;
//@}
//@{
/// Returns normal vector of point to plane
virtual const vector<floatingpoint> normal(const vector<floatingpoint> &point) = 0;
virtual const vector<floatingpoint> normal(const floatingpoint *point) = 0;
virtual const void elementeqn(floatingpoint* var) = 0;
//@}
//@{
/// Getter for mechanical parameters
virtual floatingpoint getRepulsionConst() {return _kRep;}
virtual floatingpoint getScreeningLength() {return _r0;}
//@}
//@{
/// SubSystem management, inherited from Trackable
// Does nothing
virtual void addToSubSystem() { }
virtual void removeFromSubSystem() {}
//@}
/// Get all instances of this class from the SubSystem
static const vector<BoundaryElement*>& getBoundaryElements() {
return getElements();
}
/// Get the number of boundary elements in this system
static int numBoundaryElements() {
return getElements().size();
}
virtual void printSelf()const;
//GetType implementation just returns zero (no boundary element types yet)
virtual int getType() {return 0;}
};
#endif
| 34.326087 | 100 | 0.663078 | [
"vector"
] |
96dcc32cf5813da8835f874d3d83559258b61d31 | 1,895 | h | C | projects/humans/skin_animated_humans/libraries/bvh_util/include/webots/bvh_util.h | HarpieRapace45/webots | ec3caee701c50b82925e76c638018d79de0067ea | [
"Apache-2.0"
] | 1,561 | 2019-09-04T11:32:32.000Z | 2022-03-31T18:00:09.000Z | projects/humans/skin_animated_humans/libraries/bvh_util/include/webots/bvh_util.h | HarpieRapace45/webots | ec3caee701c50b82925e76c638018d79de0067ea | [
"Apache-2.0"
] | 2,184 | 2019-09-03T11:35:02.000Z | 2022-03-31T10:01:44.000Z | projects/humans/skin_animated_humans/libraries/bvh_util/include/webots/bvh_util.h | HarpieRapace45/webots | ec3caee701c50b82925e76c638018d79de0067ea | [
"Apache-2.0"
] | 1,013 | 2019-09-07T05:09:32.000Z | 2022-03-31T13:01:28.000Z | /*
* Copyright 1996-2021 Cyberbotics Ltd.
*
* 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.
*/
/*
* Description: BVH file format utility class to be used with 'Skin' node to animate the mesh.
* It provides function to read the BVH file and adapt it to the 'Skin' model mesh.
*/
#ifndef WBU_BVH_UTIL_H
#define WBU_BVH_UTIL_H
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct WbuBvhMotionPrivate *WbuBvhMotion;
WbuBvhMotion wbu_bvh_read_file(const char *filename);
void wbu_bvh_cleanup(WbuBvhMotion motion);
const char *wbu_bvh_get_filename(WbuBvhMotion motion);
int wbu_bvh_get_joint_count(const WbuBvhMotion motion);
const char *wbu_bvh_get_joint_name(const WbuBvhMotion motion, int joint_id);
int wbu_bvh_get_frame_count(const WbuBvhMotion motion);
int wbu_bvh_get_frame_index(const WbuBvhMotion motion);
bool wbu_bvh_step(WbuBvhMotion motion);
bool wbu_bvh_goto_frame(WbuBvhMotion motion, int frame_number);
bool wbu_bvh_reset(WbuBvhMotion motion);
void wbu_bvh_set_scale(WbuBvhMotion motion, double scale);
const double *wbu_bvh_get_root_translation(const WbuBvhMotion motion);
const double *wbu_bvh_get_joint_rotation(const WbuBvhMotion motion, int joint_id);
void wbu_bvh_set_model_t_pose(const WbuBvhMotion motion, const double *axisAngle, int joint_id, bool global);
#ifdef __cplusplus
}
#endif
#endif // WBU_BVH_UTIL_H
| 33.245614 | 109 | 0.785752 | [
"mesh",
"model"
] |
96e5f383b392336eb5a5f1cb0e0835c9f609e072 | 2,279 | h | C | src/scene/particles.h | tmcarey/Scotty3D | 3d7fae7d9609bd425466db138e7bf9456090de73 | [
"MIT"
] | 191 | 2020-07-20T23:08:53.000Z | 2022-03-29T08:38:43.000Z | src/scene/particles.h | ruiwng/Scotty3D | 48e8191613c45368ef655239cc322a339726cc39 | [
"MIT"
] | 13 | 2020-12-15T01:23:22.000Z | 2021-04-24T03:16:52.000Z | src/scene/particles.h | ruiwng/Scotty3D | 48e8191613c45368ef655239cc322a339726cc39 | [
"MIT"
] | 120 | 2020-09-09T17:38:13.000Z | 2022-03-27T23:22:48.000Z |
#pragma once
#include <vector>
#include "../lib/mathlib.h"
#include "../platform/gl.h"
#include "object.h"
#include "pose.h"
namespace PT {
template<typename T> class BVH;
class Object;
} // namespace PT
class Scene_Particles {
public:
struct Particle {
Vec3 pos;
Vec3 velocity;
float age;
static const inline Vec3 acceleration = Vec3{0.0f, -9.8f, 0.0f};
bool update(const PT::Object& scene, float dt, float radius);
};
Scene_Particles(Scene_ID id);
Scene_Particles(Scene_ID id, Pose p, std::string name);
Scene_Particles(Scene_ID id, GL::Mesh&& mesh);
Scene_Particles(Scene_Particles&& src) = default;
Scene_Particles(const Scene_Particles& src) = delete;
~Scene_Particles() = default;
void operator=(const Scene_Particles& src) = delete;
Scene_Particles& operator=(Scene_Particles&& src) = default;
void clear();
void step(const PT::Object& scene, float dt);
void step2(const PT::Object& scene, float dt);
void gen_instances();
const std::vector<Particle>& get_particles() const;
BBox bbox() const;
void render(const Mat4& view, bool depth_only = false, bool posed = true,
bool particles_only = false);
Scene_ID id() const;
void set_time(float time);
const GL::Mesh& mesh() const;
void take_mesh(GL::Mesh&& mesh);
struct Options {
char name[MAX_NAME_LEN] = {};
Spectrum color = Spectrum(1.0f);
float velocity = 25.0f;
float angle = 0.0f;
float scale = 0.1f;
float lifetime = 15.0f;
float pps = 5.0f;
float dt = 0.01f;
bool enabled = false;
};
struct Anim_Particles {
void at(float t, Options& o) const;
void set(float t, Options o);
Splines<Spectrum, float, float, float, float, float, bool> splines;
};
Options opt;
Pose pose;
Anim_Pose anim;
Anim_Particles panim;
private:
void get_r();
Scene_ID _id;
std::vector<Particle> particles;
GL::Instances particle_instances;
GL::Mesh arrow;
float radius = 0.0f;
float last_update = 0.0f;
double particle_cooldown = 0.0f;
};
bool operator!=(const Scene_Particles::Options& l, const Scene_Particles::Options& r);
| 24.771739 | 86 | 0.63405 | [
"mesh",
"render",
"object",
"vector"
] |
96e80e376ad0212888410e81ebb611560e0fa921 | 3,239 | h | C | binpack/include/frida-1.0/gum/guminterceptor.h | hackerhouse-opensource/rebirth | 76cbdee74e985a2cf1185d7ca81045b1839cc229 | [
"CC0-1.0"
] | 16 | 2019-12-23T21:04:05.000Z | 2022-02-20T21:05:30.000Z | binpack/include/frida-1.0/gum/guminterceptor.h | hackerhouse-opensource/rebirth | 76cbdee74e985a2cf1185d7ca81045b1839cc229 | [
"CC0-1.0"
] | null | null | null | binpack/include/frida-1.0/gum/guminterceptor.h | hackerhouse-opensource/rebirth | 76cbdee74e985a2cf1185d7ca81045b1839cc229 | [
"CC0-1.0"
] | 4 | 2019-12-28T12:42:23.000Z | 2021-04-04T19:45:01.000Z | /*
* Copyright (C) 2008-2017 Ole André Vadla Ravnås <oleavr@nowsecure.com>
* Copyright (C) 2008 Christian Berentsen <jc.berentsen@gmail.com>
*
* Licence: wxWindows Library Licence, Version 3.1
*/
#ifndef __GUM_INTERCEPTOR_H__
#define __GUM_INTERCEPTOR_H__
#include <glib-object.h>
#include <gum/gumdefs.h>
#include <gum/guminvocationlistener.h>
#define GUM_TYPE_INTERCEPTOR (gum_interceptor_get_type ())
#define GUM_INTERCEPTOR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj),\
GUM_TYPE_INTERCEPTOR, GumInterceptor))
#define GUM_INTERCEPTOR_CAST(obj) ((GumInterceptor *) (obj))
#define GUM_INTERCEPTOR_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass),\
GUM_TYPE_INTERCEPTOR, GumInterceptorClass))
#define GUM_IS_INTERCEPTOR(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj),\
GUM_TYPE_INTERCEPTOR))
#define GUM_IS_INTERCEPTOR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE (\
(klass), GUM_TYPE_INTERCEPTOR))
#define GUM_INTERCEPTOR_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS (\
(obj), GUM_TYPE_INTERCEPTOR, GumInterceptorClass))
typedef struct _GumInterceptor GumInterceptor;
typedef struct _GumInterceptorClass GumInterceptorClass;
typedef GArray GumInvocationStack;
typedef struct _GumInterceptorPrivate GumInterceptorPrivate;
typedef enum
{
GUM_ATTACH_OK = 0,
GUM_ATTACH_WRONG_SIGNATURE = -1,
GUM_ATTACH_ALREADY_ATTACHED = -2,
GUM_ATTACH_POLICY_VIOLATION = -3
} GumAttachReturn;
typedef enum
{
GUM_REPLACE_OK = 0,
GUM_REPLACE_WRONG_SIGNATURE = -1,
GUM_REPLACE_ALREADY_REPLACED = -2,
GUM_REPLACE_POLICY_VIOLATION = -3
} GumReplaceReturn;
struct _GumInterceptor
{
GObject parent;
GumInterceptorPrivate * priv;
};
struct _GumInterceptorClass
{
GObjectClass parent_class;
};
G_BEGIN_DECLS
GUM_API GType gum_interceptor_get_type (void) G_GNUC_CONST;
GUM_API GumInterceptor * gum_interceptor_obtain (void);
GUM_API GumAttachReturn gum_interceptor_attach_listener (GumInterceptor * self,
gpointer function_address, GumInvocationListener * listener,
gpointer listener_function_data);
GUM_API void gum_interceptor_detach_listener (GumInterceptor * self,
GumInvocationListener * listener);
GUM_API GumReplaceReturn gum_interceptor_replace_function (
GumInterceptor * self, gpointer function_address,
gpointer replacement_function, gpointer replacement_function_data);
GUM_API void gum_interceptor_revert_function (GumInterceptor * self,
gpointer function_address);
GUM_API void gum_interceptor_begin_transaction (GumInterceptor * self);
GUM_API void gum_interceptor_end_transaction (GumInterceptor * self);
GUM_API gboolean gum_interceptor_flush (GumInterceptor * self);
GUM_API GumInvocationContext * gum_interceptor_get_current_invocation (void);
GUM_API GumInvocationStack * gum_interceptor_get_current_stack (void);
GUM_API void gum_interceptor_ignore_current_thread (GumInterceptor * self);
GUM_API void gum_interceptor_unignore_current_thread (GumInterceptor * self);
GUM_API void gum_interceptor_ignore_other_threads (GumInterceptor * self);
GUM_API void gum_interceptor_unignore_other_threads (GumInterceptor * self);
GUM_API gpointer gum_invocation_stack_translate (GumInvocationStack * self,
gpointer return_address);
G_END_DECLS
#endif
| 32.717172 | 79 | 0.810435 | [
"object"
] |
96ea33747b840d0946a7d79f66d6b4dfcc43e359 | 2,023 | h | C | subprojects/pdns-api-cpp/include/model/Metadata.h | pieterlexis/pdns-sysrepo | 56ca0ef7b249a169f4e33f12d81b825f25317052 | [
"Apache-2.0"
] | 2 | 2020-03-18T11:08:17.000Z | 2020-08-20T04:09:52.000Z | subprojects/pdns-api-cpp/include/model/Metadata.h | pieterlexis/pdns-sysrepo | 56ca0ef7b249a169f4e33f12d81b825f25317052 | [
"Apache-2.0"
] | 26 | 2020-01-15T16:41:00.000Z | 2020-04-30T12:09:11.000Z | subprojects/pdns-api-cpp/include/model/Metadata.h | pieterlexis/pdns-sysrepo | 56ca0ef7b249a169f4e33f12d81b825f25317052 | [
"Apache-2.0"
] | 3 | 2019-12-09T14:31:58.000Z | 2020-07-28T11:48:22.000Z | /**
* PowerDNS Authoritative HTTP API
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 0.0.13
*
* NOTE: This class is auto generated by OpenAPI-Generator 4.2.1.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/*
* Metadata.h
*
* Represents zone metadata
*/
#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_Metadata_H_
#define ORG_OPENAPITOOLS_CLIENT_MODEL_Metadata_H_
#include "../ModelBase.h"
#include <cpprest/details/basic_types.h>
#include <vector>
namespace org {
namespace openapitools {
namespace client {
namespace model {
/// <summary>
/// Represents zone metadata
/// </summary>
class Metadata
: public ModelBase
{
public:
Metadata();
virtual ~Metadata();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
web::json::value toJson() const override;
void fromJson(const web::json::value& json) override;
void toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) const override;
void fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) override;
/////////////////////////////////////////////
/// Metadata members
/// <summary>
/// Name of the metadata
/// </summary>
utility::string_t getKind() const;
bool kindIsSet() const;
void unsetKind();
void setKind(const utility::string_t& value);
/// <summary>
/// Array with all values for this metadata kind.
/// </summary>
std::vector<utility::string_t>& getMetadata();
bool metadataIsSet() const;
void unsetMetadata();
void setMetadata(const std::vector<utility::string_t>& value);
protected:
utility::string_t m_Kind;
bool m_KindIsSet;
std::vector<utility::string_t> m_Metadata;
bool m_MetadataIsSet;
};
}
}
}
}
#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_Metadata_H_ */
| 22.477778 | 119 | 0.668809 | [
"vector",
"model"
] |
96f7e4b0ee268db704e1b82154f278d33a38610c | 2,003 | h | C | libs/libupmq/cms/ObjectMessage.h | asvgit/broker | 766b66015b842be4d1106ff6c6145ad489c03c59 | [
"Apache-2.0"
] | 10 | 2019-10-31T14:36:01.000Z | 2022-02-25T13:47:23.000Z | libs/libupmq/cms/ObjectMessage.h | asvgit/broker | 766b66015b842be4d1106ff6c6145ad489c03c59 | [
"Apache-2.0"
] | 6 | 2019-11-07T14:55:50.000Z | 2021-03-03T09:31:35.000Z | libs/libupmq/cms/ObjectMessage.h | asvgit/broker | 766b66015b842be4d1106ff6c6145ad489c03c59 | [
"Apache-2.0"
] | 3 | 2019-11-07T14:23:33.000Z | 2020-11-05T18:35:16.000Z | /*
* Copyright 2014-present IVK JSC. 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.
*/
#ifndef _CMS_OBJECTMESSAGE_H_
#define _CMS_OBJECTMESSAGE_H_
#include <cms/Config.h>
#include <cms/Message.h>
namespace cms {
/**
* Place holder for interaction with JMS systems that support Java, the C++
* client is not responsible for deserializing the contained Object. The Object
* can be accessed in its serialized form as a vector of bytes which allows for
* bridging of message systems.
*
* serialized <code>ObjectMessage</code>s.
*
* @since 1.0
*/
class CMS_API ObjectMessage : public Message {
public:
virtual ~ObjectMessage(){};
/**
* Sets the payload bytes the represent the Object being transmitted.
*
* @param bytes
* The byte array that contains the serialized object.
*
* @throws CMSException - if the operation fails due to an internal error.
* @throws MessageNotWriteableException - if the Message is in Read-only Mode.
*/
virtual void setObjectBytes(const std::string &bytes) = 0;
/**
* Returns the byte array containing the serialized form of the transmitted Object.
*
* @return a byte vector containing the serialized Object.
*
* @throws CMSException - if the operation fails due to an internal error.
* @throws MessageNotReadableException - if the message is in write only mode.
*/
virtual std::string getObjectBytes() const = 0;
};
} // namespace cms
#endif /*_CMS_OBJECTMESSAGE_H_*/
| 31.793651 | 85 | 0.724913 | [
"object",
"vector"
] |
96fdb1499442436d8846cd244de57e6f67c0bb2a | 16,900 | c | C | codes/mudmuhan-ReCpp20/util/ed/editor3.c | jacking75/edu_com2us_cpp20_Training | 9d938a447ad52075033b65f7d881e2eb8007d09f | [
"MIT"
] | 13 | 2021-01-06T01:58:26.000Z | 2022-02-23T12:57:13.000Z | codes/mudmuhan-ReCpp20/util/ed/editor3.c | jacking75/edu_com2us_cpp20_Training | 9d938a447ad52075033b65f7d881e2eb8007d09f | [
"MIT"
] | null | null | null | codes/mudmuhan-ReCpp20/util/ed/editor3.c | jacking75/edu_com2us_cpp20_Training | 9d938a447ad52075033b65f7d881e2eb8007d09f | [
"MIT"
] | null | null | null | /*
* FILES1.C:
*
* File I/O Routines.
*
* Copyright (C) 1991 Brett J. Vickers
*
*/
#include "mstruct.h"
#include "mtype.h"
#include "mextern.h"
/**********************************************************************/
/* count_obj */
/**********************************************************************/
/* Return the total number of objects contained within an object. */
/* If perm_only != 0, then only the permanent objects are counted. */
int count_obj(obj_ptr, perm_only)
object *obj_ptr;
char perm_only;
{
otag *op;
int total=0;
op = obj_ptr->first_obj;
while(op) {
if(!perm_only || (perm_only && (F_ISSET(op->obj, OPERMT) ||
F_ISSET(op->obj, OPERM2))))
total++;
op = op->next_tag;
}
return(total);
}
/**********************************************************************/
/* write_obj */
/**********************************************************************/
/* Save an object to a file that has already been opened and positioned. */
/* This function recursively saves the items that are contained inside */
/* the object as well. If perm_only != 0 then only permanent objects */
/* within the object are saved with it. */
int write_obj(fd, obj_ptr, perm_only)
int fd;
object *obj_ptr;
char perm_only;
{
int n, cnt, cnt2=0, error=0;
otag *op;
n = write(fd, obj_ptr, sizeof(object));
if(n < sizeof(object))
merror("write_obj", FATAL);
cnt = count_obj(obj_ptr, perm_only);
n = write(fd, &cnt, sizeof(int));
if(n < sizeof(int))
merror("write_obj", FATAL);
if(cnt > 0) {
op = obj_ptr->first_obj;
while(op) {
if(!perm_only || (perm_only &&
(F_ISSET(op->obj, OPERMT) ||
F_ISSET(op->obj, OPERM2)))) {
if(write_obj(fd, op->obj, perm_only) < 0)
error = 1;
cnt2++;
}
op = op->next_tag;
}
}
if(cnt != cnt2 || error)
return(-1);
else
return(0);
}
/**********************************************************************/
/* count_inv */
/**********************************************************************/
/* Returns the number of objects a creature has in his inventory. */
/* If perm_only != 0 then only those objects which are permanent */
/* will be counted. */
int count_inv(crt_ptr, perm_only)
creature *crt_ptr;
char perm_only;
{
otag *op;
int total=0;
op = crt_ptr->first_obj;
while(op) {
if(!perm_only || (perm_only && (F_ISSET(op->obj, OPERMT) ||
F_ISSET(op->obj, OPERM2))))
total++;
op = op->next_tag;
}
return(total);
}
/**********************************************************************/
/* write_crt */
/**********************************************************************/
/* Save a creature to an already open and positioned file. This function */
/* also saves all the items the creature is holding. If perm_only != 0 */
/* then only those items which the creature is carrying that are */
/* permanent will be saved. */
int write_crt(fd, crt_ptr, perm_only)
int fd;
creature *crt_ptr;
char perm_only;
{
int n, cnt, cnt2=0, error=0;
otag *op;
n = write(fd, crt_ptr, sizeof(creature));
if(n < sizeof(creature))
merror("write_crt", FATAL);
cnt = count_inv(crt_ptr, perm_only);
n = write(fd, &cnt, sizeof(int));
if(n < sizeof(int))
merror("write_crt", FATAL);
if(cnt > 0) {
op = crt_ptr->first_obj;
while(op) {
if(!perm_only || (perm_only &&
(F_ISSET(op->obj, OPERMT) ||
F_ISSET(op->obj, OPERM2)))) {
if(write_obj(fd, op->obj, perm_only) < 0)
error = 1;
cnt2++;
}
op = op->next_tag;
}
}
if(cnt != cnt2 || error)
return(-1);
else
return(0);
}
/**********************************************************************/
/* count_mon */
/**********************************************************************/
/* Returns the number of monsters in a given room. If perm_only is */
/* nonzero, then only the number of permanent monsters in the room */
/* is returned. */
int count_mon(rom_ptr, perm_only)
room *rom_ptr;
char perm_only;
{
ctag *cp;
int total=0;
cp = rom_ptr->first_mon;
while(cp) {
if(!perm_only || (perm_only && F_ISSET(cp->crt, MPERMT)))
total++;
cp = cp->next_tag;
}
return(total);
}
/**********************************************************************/
/* count_ite */
/**********************************************************************/
/* Returns the number of items in the room. If perm_only is nonzero */
/* then only the number of permanent items in the room is returned. */
int count_ite(rom_ptr, perm_only)
room *rom_ptr;
char perm_only;
{
otag *op;
int total=0;
op = rom_ptr->first_obj;
while(op) {
if(!perm_only || (perm_only && (F_ISSET(op->obj, OPERMT) ||
F_ISSET(op->obj, OPERM2))))
total++;
op = op->next_tag;
}
return(total);
}
/**********************************************************************/
/* count_ext */
/**********************************************************************/
/* Returns the number of exits in the room */
int count_ext(rom_ptr)
room *rom_ptr;
{
xtag *xp;
int total = 0;
xp = rom_ptr->first_ext;
while(xp) {
total++;
xp = xp->next_tag;
}
return(total);
}
/**********************************************************************/
/* count_ply */
/**********************************************************************/
/* Returns the number of players in the room */
int count_ply(rom_ptr)
room *rom_ptr;
{
ctag *pp;
int total = 0;
pp = rom_ptr->first_ply;
while(pp) {
total++;
pp = pp->next_tag;
}
return(total);
}
/**********************************************************************/
/* write_rom */
/**********************************************************************/
/* Saves the room pointed to by rom_ptr with all its contents. Its */
/* contents include exits, descriptions, items and monsters. If */
/* perm_only is nonzero, then only items and monsters in the room */
/* which are permanent will be saved. */
int write_rom(fd, rom_ptr, perm_only)
int fd;
room *rom_ptr;
char perm_only;
{
int n, cnt, error=0;
xtag *xp;
ctag *cp;
otag *op;
n = write(fd, rom_ptr, sizeof(room));
if(n < sizeof(room))
merror("write_rom", FATAL);
cnt = count_ext(rom_ptr);
n = write(fd, &cnt, sizeof(int));
if(n < sizeof(int))
merror("write_rom", FATAL);
xp = rom_ptr->first_ext;
while(xp) {
n = write(fd, xp->ext, sizeof(exit_));
if(n < sizeof(exit_))
merror("write_rom", FATAL);
xp = xp->next_tag;
}
cnt = count_mon(rom_ptr, perm_only);
n = write(fd, &cnt, sizeof(int));
if(n < sizeof(int))
merror("write_rom", FATAL);
cp = rom_ptr->first_mon;
while(cp) {
if(!perm_only || (perm_only && F_ISSET(cp->crt, MPERMT)))
if(write_crt(fd, cp->crt, 0) < 0)
error = 1;
cp = cp->next_tag;
}
cnt = count_ite(rom_ptr, perm_only);
n = write(fd, &cnt, sizeof(int));
if(n < sizeof(int))
merror("write_rom", FATAL);
op = rom_ptr->first_obj;
while(op) {
if(!perm_only || (perm_only && (F_ISSET(op->obj, OPERMT) ||
F_ISSET(op->obj, OPERM2))))
if(write_obj(fd, op->obj, perm_only) < 0)
error = 1;
op = op->next_tag;
}
if(!rom_ptr->short_desc)
cnt = 0;
else
cnt = strlen(rom_ptr->short_desc) + 1;
n = write(fd, &cnt, sizeof(int));
if(n < sizeof(int))
merror("write_rom", FATAL);
if(cnt) {
n = write(fd, rom_ptr->short_desc, cnt);
if(n < cnt)
merror("write_rom", FATAL);
}
if(!rom_ptr->long_desc)
cnt = 0;
else
cnt = strlen(rom_ptr->long_desc) + 1;
n = write(fd, &cnt, sizeof(int));
if(n < sizeof(int))
merror("write_rom", FATAL);
if(cnt) {
n = write(fd, rom_ptr->long_desc, cnt);
if(n < cnt)
merror("write_rom", FATAL);
}
if(!rom_ptr->obj_desc)
cnt = 0;
else
cnt = strlen(rom_ptr->obj_desc) + 1;
n = write(fd, &cnt, sizeof(int));
if(n < sizeof(int))
merror("write_rom", FATAL);
if(cnt) {
n = write(fd, rom_ptr->obj_desc, cnt);
if(n < cnt)
merror("write_rom", FATAL);
}
if(error)
return(-1);
else
return(0);
}
/**********************************************************************/
/* read_obj */
/**********************************************************************/
/* Loads the object from the open and positioned file described by fd */
/* and also loads every object which it might contain. Returns -1 if */
/* there was an error. */
int read_obj(fd, obj_ptr)
int fd;
object *obj_ptr;
{
int n, cnt, error=0;
otag *op;
otag **prev;
object *obj;
n = read(fd, obj_ptr, sizeof(object));
if(n < sizeof(object))
error = 1;
obj_ptr->first_obj = 0;
obj_ptr->parent_obj = 0;
obj_ptr->parent_rom = 0;
obj_ptr->parent_crt = 0;
if(obj_ptr->shotscur > obj_ptr->shotsmax)
obj_ptr->shotscur = obj_ptr->shotsmax;
n = read(fd, &cnt, sizeof(int));
if(n < sizeof(int)) {
error = 1;
cnt = 0;
}
prev = &obj_ptr->first_obj;
while(cnt > 0) {
cnt--;
op = (otag *)malloc(sizeof(otag));
if(op) {
obj = (object *)malloc(sizeof(object));
if(obj) {
if(read_obj(fd, obj) < 0)
error = 1;
obj->parent_obj = obj_ptr;
op->obj = obj;
op->next_tag = 0;
*prev = op;
prev = &op->next_tag;
}
else
merror("read_obj", FATAL);
}
else
merror("read_obj", FATAL);
}
if(error)
return(-1);
else
return(0);
}
/**********************************************************************/
/* read_crt */
/**********************************************************************/
/* Loads a creature from an open and positioned file. The creature is */
/* loaded at the mem location specified by the second parameter. In */
/* addition, all the creature's objects have memory allocated for them */
/* and are loaded as well. Returns -1 on fail. */
int read_crt(fd, crt_ptr)
int fd;
creature *crt_ptr;
{
int n, cnt, error=0;
otag *op;
otag **prev;
object *obj;
n = read(fd, crt_ptr, sizeof(creature));
if(n < sizeof(creature))
error = 1;
crt_ptr->first_obj = 0;
crt_ptr->first_fol = 0;
crt_ptr->first_enm = 0;
crt_ptr->parent_rom = 0;
crt_ptr->following = 0;
for(n=0; n<20; n++)
crt_ptr->ready[n] = 0;
if(crt_ptr->mpcur > crt_ptr->mpmax)
crt_ptr->mpcur = crt_ptr->mpmax;
if(crt_ptr->hpcur > crt_ptr->hpmax)
crt_ptr->hpcur = crt_ptr->hpmax;
n = read(fd, &cnt, sizeof(int));
if(n < sizeof(int)) {
error = 1;
cnt = 0;
}
prev = &crt_ptr->first_obj;
while(cnt > 0) {
cnt--;
op = (otag *)malloc(sizeof(otag));
if(op) {
obj = (object *)malloc(sizeof(object));
if(obj) {
if(read_obj(fd, obj) < 0) {
printf("error 3\n");
error = 1;
}
obj->parent_crt = crt_ptr;
op->obj = obj;
op->next_tag = 0;
*prev = op;
prev = &op->next_tag;
}
else
merror("read_crt", FATAL);
}
else
merror("read_crt", FATAL);
}
if(error)
return(-1);
else
return(0);
}
/**********************************************************************/
/* read_rom */
/**********************************************************************/
/* Loads a room from an already open and positioned file into the memory */
/* pointed to by the second parameter. Also loaded are all creatures, */
/* exits, objects and descriptions for the room. -1 is returned upon */
/* failure. */
int read_rom(fd, rom_ptr)
int fd;
room *rom_ptr;
{
int n, cnt, error=0;
xtag *xp;
xtag **xprev;
exit_ *ext;
ctag *cp;
ctag **cprev;
creature *crt;
otag *op;
otag **oprev;
object *obj;
char *sh, *lo, *ob;
n = read(fd, rom_ptr, sizeof(room));
if(n < sizeof(room))
error = 1;
rom_ptr->short_desc = 0;
rom_ptr->long_desc = 0;
rom_ptr->obj_desc = 0;
rom_ptr->first_ext = 0;
rom_ptr->first_obj = 0;
rom_ptr->first_mon = 0;
rom_ptr->first_ply = 0;
n = read(fd, &cnt, sizeof(int));
if(n < sizeof(int)) {
error = 1;
cnt = 0;
}
/* Load the exits */
xprev = &rom_ptr->first_ext;
while(cnt > 0) {
cnt--;
xp = (xtag *)malloc(sizeof(xtag));
if(xp) {
ext = (exit_ *)malloc(sizeof(exit_));
if(ext) {
n = read(fd, ext, sizeof(exit_));
if(n < sizeof(exit_))
error = 1;
xp->ext = ext;
xp->next_tag = 0;
*xprev = xp;
xprev = &xp->next_tag;
}
else
merror("read_rom", FATAL);
}
else
merror("read_rom", FATAL);
}
/* Read the monsters */
n = read(fd, &cnt, sizeof(int));
if(n < sizeof(int)) {
error = 1;
cnt = 0;
}
cprev = &rom_ptr->first_mon;
while(cnt > 0) {
cnt--;
cp = (ctag *)malloc(sizeof(ctag));
if(cp) {
crt = (creature *)malloc(sizeof(creature));
if(crt) {
if(read_crt(fd, crt) < 0)
error = 1;
crt->parent_rom = rom_ptr;
cp->crt = crt;
cp->next_tag = 0;
*cprev = cp;
cprev = &cp->next_tag;
}
else
merror("read_rom", FATAL);
}
else
merror("read_rom", FATAL);
}
/* Read the items */
n = read(fd, &cnt, sizeof(int));
if(n < sizeof(int)) {
error = 1;
cnt = 0;
}
oprev = &rom_ptr->first_obj;
while(cnt > 0) {
cnt--;
op = (otag *)malloc(sizeof(otag));
if(op) {
obj = (object *)malloc(sizeof(object));
if(obj) {
if(read_obj(fd, obj) < 0)
error = 1;
obj->parent_rom = rom_ptr;
op->obj = obj;
op->next_tag = 0;
*oprev = op;
oprev = &op->next_tag;
}
else
merror("read_rom", FATAL);
}
else
merror("read_rom", FATAL);
}
/* Read the descriptions */
n = read(fd, &cnt, sizeof(int));
if(n < sizeof(int)) {
error = 1;
cnt = 0;
}
if(cnt) {
sh = (char *)malloc(cnt);
if(sh) {
n = read(fd, sh, cnt);
if(n < cnt)
error = 1;
rom_ptr->short_desc = sh;
}
else
merror("read_rom", FATAL);
}
n = read(fd, &cnt, sizeof(int));
if(n < sizeof(int)) {
error = 1;
cnt = 0;
}
if(cnt) {
lo = (char *)malloc(cnt);
if(lo) {
n = read(fd, lo, cnt);
if(n < cnt)
error = 1;
rom_ptr->long_desc = lo;
}
else
merror("read_rom", FATAL);
}
n = read(fd, &cnt, sizeof(int));
if(n < sizeof(int)) {
error = 1;
cnt = 0;
}
if(cnt) {
ob = (char *)malloc(cnt);
if(ob) {
n = read(fd, ob, cnt);
if(n < cnt)
error = 1;
rom_ptr->obj_desc = ob;
}
else
merror("read_rom", FATAL);
}
if(error)
return(-1);
else
return(0);
}
/**********************************************************************/
/* free_obj */
/**********************************************************************/
/* This function is called to release the object pointed to by the first */
/* parameter from memory. All objects contained within it are also */
/* released from memory. *ASSUMPTION*: This function will only be */
/* called from free_rom() or free_crt(). Otherwise there may be */
/* unresolved links in memory which would cause a game crash. */
void free_obj(obj_ptr)
object *obj_ptr;
{
otag *op, *temp;
op = obj_ptr->first_obj;
while(op) {
temp = op->next_tag;
free_obj(op->obj);
free(op);
op = temp;
}
free(obj_ptr);
}
/**********************************************************************/
/* free_crt */
/**********************************************************************/
/* This function releases the creature pointed to by the first parameter */
/* from memory. All items that creature has readied or carries will */
/* also be released. *ASSUMPTION*: This function will only be called */
/* from free_rom(). If it is called from somewhere else, unresolved */
/* links may remain and cause a game crash. *EXCEPTION*: This function */
/* can be called independently to free a player's information from */
/* memory (but not a monster). */
void free_crt(crt_ptr)
creature *crt_ptr;
{
otag *op, *temp;
int i;
for(i=0; i<20; i++)
if(crt_ptr->ready[i]) {
free_obj(crt_ptr->ready[i]);
crt_ptr->ready[i] = 0;
}
op = crt_ptr->first_obj;
while(op) {
temp = op->next_tag;
free_obj(op->obj);
free(op);
op = temp;
}
free(crt_ptr);
}
/**********************************************************************/
/* free_rom */
/**********************************************************************/
/* This function releases the a room and its contents from memory. The */
/* function is passed the room's pointer as its parameter. The exits, */
/* descriptions, objects and monsters are all released from memory. */
void free_rom(rom_ptr)
room *rom_ptr;
{
xtag *xp, *xtemp;
otag *op, *otemp;
ctag *cp, *ctemp;
free(rom_ptr->short_desc);
free(rom_ptr->long_desc);
free(rom_ptr->obj_desc);
xp = rom_ptr->first_ext;
while(xp) {
xtemp = xp->next_tag;
free(xp->ext);
free(xp);
xp = xtemp;
}
op = rom_ptr->first_obj;
while(op) {
otemp = op->next_tag;
free_obj(op->obj);
free(op);
op = otemp;
}
cp = rom_ptr->first_mon;
while(cp) {
ctemp = cp->next_tag;
free_crt(cp->crt);
free(cp);
cp = ctemp;
}
free(rom_ptr);
}
| 21.611253 | 76 | 0.518462 | [
"object"
] |
96fdd97a34c18c68a8387261baba63fd59336b9f | 1,476 | h | C | core/analysis/live_variables.h | nandor/genm-opt | b3347d508fff707837d1dc8232487ebfe157fe2a | [
"MIT"
] | 13 | 2020-06-25T18:26:54.000Z | 2021-02-16T03:14:38.000Z | core/analysis/live_variables.h | nandor/genm-opt | b3347d508fff707837d1dc8232487ebfe157fe2a | [
"MIT"
] | 3 | 2020-07-01T01:39:47.000Z | 2022-01-24T23:47:12.000Z | core/analysis/live_variables.h | nandor/genm-opt | b3347d508fff707837d1dc8232487ebfe157fe2a | [
"MIT"
] | 2 | 2021-03-11T05:08:09.000Z | 2021-07-17T23:36:17.000Z | // This file if part of the llir-opt project.
// Licensing information can be found in the LICENSE file.
// (C) 2018 Nandor Licker. All rights reserved.
#pragma once
#include <set>
#include <unordered_set>
#include <vector>
#include "core/inst.h"
#include "core/analysis/loop_nesting.h"
class Block;
class Func;
class Inst;
/**
* Helper class to compute live variable info for a function.
*/
class LiveVariables final {
public:
/**
* Computes live variable info for a function.
*/
LiveVariables(const Func *func);
/**
* Cleanup.
*/
~LiveVariables();
/**
* Returns the set of live-ins at a program point.
*/
std::vector<ConstRef<Inst>> LiveOut(const Inst *inst);
private:
using InstSet = std::unordered_set<ConstRef<Inst>>;
/// DFS over the DAG - CFG minus loop edges.
void TraverseDAG(const Block *block);
/// Propagate liveness in a node.
void TraverseNode(const Block *block);
/// DFS over the loop nesting forest.
void TraverseLoop(LoopNesting::Loop *loop);
/// Applies the transfer function of an instruction.
void KillDef(InstSet &live, const Inst *inst);
private:
/// Loop nesting forest.
LoopNesting loops_;
/// Map of visited nodes.
std::unordered_map
< const Block *
, std::pair<InstSet, InstSet>
> live_;
/// Cached live outs.
std::unordered_map
< const Inst *
, InstSet
> liveCache_;
/// Block for which LVA info was cached.
const Block *liveBlock_ = nullptr;
};
| 21.705882 | 61 | 0.678184 | [
"vector"
] |
8c023b1b868fe20f403e4bccf6d65928f04236e1 | 29,636 | c | C | src/fswAlgorithms/attDetermination/sunlineSuKF/sunlineSuKF.c | ian-cooke/basilisk_mag | a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14 | [
"0BSD"
] | null | null | null | src/fswAlgorithms/attDetermination/sunlineSuKF/sunlineSuKF.c | ian-cooke/basilisk_mag | a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14 | [
"0BSD"
] | 1 | 2019-03-13T20:52:22.000Z | 2019-03-13T20:52:22.000Z | src/fswAlgorithms/attDetermination/sunlineSuKF/sunlineSuKF.c | ian-cooke/basilisk_mag | a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14 | [
"0BSD"
] | null | null | null | /*
ISC License
Copyright (c) 2016-2018, Autonomous Vehicle Systems Lab, University of Colorado at Boulder
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "attDetermination/sunlineSuKF/sunlineSuKF.h"
#include "attDetermination/_GeneralModuleFiles/ukfUtilities.h"
#include "simulation/utilities/linearAlgebra.h"
#include "simulation/utilities/rigidBodyKinematics.h"
#include "simFswInterfaceMessages/macroDefinitions.h"
#include <string.h>
#include <math.h>
/*! This method initializes the ConfigData for theCSS WLS estimator.
It checks to ensure that the inputs are sane and then creates the
output message
@return void
@param ConfigData The configuration data associated with the CSS WLS estimator
*/
void SelfInit_sunlineSuKF(SunlineSuKFConfig *ConfigData, uint64_t moduleID)
{
mSetZero(ConfigData->cssNHat_B, MAX_NUM_CSS_SENSORS, 3);
/*! Begin method steps */
/*! - Create output message for module */
ConfigData->navStateOutMsgId = CreateNewMessage(ConfigData->navStateOutMsgName,
sizeof(NavAttIntMsg), "NavAttIntMsg", moduleID);
/*! - Create filter states output message which is mostly for debug*/
ConfigData->filtDataOutMsgId = CreateNewMessage(ConfigData->filtDataOutMsgName,
sizeof(SunlineFilterFswMsg), "SunlineFilterFswMsg", moduleID);
}
/*! This method performs the second stage of initialization for the CSS sensor
interface. It's primary function is to link the input messages that were
created elsewhere.
@return void
@param ConfigData The configuration data associated with the CSS interface
*/
void CrossInit_sunlineSuKF(SunlineSuKFConfig *ConfigData, uint64_t moduleID)
{
/*! Begin method steps */
/*! - Find the message ID for the coarse sun sensor data message */
ConfigData->cssDataInMsgId = subscribeToMessage(ConfigData->cssDataInMsgName,
sizeof(CSSArraySensorIntMsg), moduleID);
/*! - Find the message ID for the coarse sun sensor configuration message */
ConfigData->cssConfigInMsgId = subscribeToMessage(ConfigData->cssConfigInMsgName,
sizeof(CSSConfigFswMsg), moduleID);
}
/*! This method resets the sunline attitude filter to an initial state and
initializes the internal estimation matrices.
@return void
@param ConfigData The configuration data associated with the CSS estimator
@param callTime The clock time at which the function was called (nanoseconds)
*/
void Reset_sunlineSuKF(SunlineSuKFConfig *ConfigData, uint64_t callTime,
uint64_t moduleID)
{
int32_t i;
CSSConfigFswMsg cssConfigInBuffer;
uint64_t writeTime;
uint32_t writeSize;
double tempMatrix[SKF_N_STATES_SWITCH*SKF_N_STATES_SWITCH];
/*! Begin method steps*/
/*! - Zero the local configuration data structures and outputs */
memset(&cssConfigInBuffer, 0x0, sizeof(CSSConfigFswMsg));
memset(&(ConfigData->outputSunline), 0x0, sizeof(NavAttIntMsg));
/*! - Read in mass properties and coarse sun sensor configuration information.*/
ReadMessage(ConfigData->cssConfigInMsgId, &writeTime, &writeSize,
sizeof(CSSConfigFswMsg ), &cssConfigInBuffer, moduleID);
/*! - For each coarse sun sensor, convert the configuration data over from structure to body*/
for(i=0; i<cssConfigInBuffer.nCSS; i = i+1)
{
v3Copy(cssConfigInBuffer.cssVals[i].nHat_B, &(ConfigData->cssNHat_B[i*3]));
ConfigData->CBias[i] = cssConfigInBuffer.cssVals[i].CBias;
}
/*! - Save the count of sun sensors for later use */
ConfigData->numCSSTotal = cssConfigInBuffer.nCSS;
/*! - Initialize filter parameters to max values */
ConfigData->timeTag = callTime*NANO2SEC;
ConfigData->dt = 0.0;
ConfigData->numStates = SKF_N_STATES_SWITCH;
ConfigData->countHalfSPs = SKF_N_STATES_SWITCH;
ConfigData->numObs = MAX_N_CSS_MEAS;
/*! Initalize the filter to use b_1 of the body frame to make frame*/
v3Set(1, 0, 0, ConfigData->bVec_B);
ConfigData->switchTresh = 0.866;
/*! - Ensure that all internal filter matrices are zeroed*/
vSetZero(ConfigData->obs, ConfigData->numObs);
vSetZero(ConfigData->wM, ConfigData->countHalfSPs * 2 + 1);
vSetZero(ConfigData->wC, ConfigData->countHalfSPs * 2 + 1);
mSetZero(ConfigData->sBar, ConfigData->numStates, ConfigData->numStates);
mSetZero(ConfigData->SP, ConfigData->countHalfSPs * 2 + 1,
ConfigData->numStates);
mSetZero(ConfigData->sQnoise, ConfigData->numStates, ConfigData->numStates);
/*! - Set lambda/gamma to standard value for unscented kalman filters */
ConfigData->lambdaVal = ConfigData->alpha*ConfigData->alpha*
(ConfigData->numStates + ConfigData->kappa) - ConfigData->numStates;
ConfigData->gamma = sqrt(ConfigData->numStates + ConfigData->lambdaVal);
/*! - Set the wM/wC vectors to standard values for unscented kalman filters*/
ConfigData->wM[0] = ConfigData->lambdaVal / (ConfigData->numStates +
ConfigData->lambdaVal);
ConfigData->wC[0] = ConfigData->lambdaVal / (ConfigData->numStates +
ConfigData->lambdaVal) + (1 - ConfigData->alpha*ConfigData->alpha + ConfigData->beta);
for (i = 1; i<ConfigData->countHalfSPs * 2 + 1; i++)
{
ConfigData->wM[i] = 1.0 / 2.0*1.0 / (ConfigData->numStates +
ConfigData->lambdaVal);
ConfigData->wC[i] = ConfigData->wM[i];
}
/*! - User a cholesky decomposition to obtain the sBar and sQnoise matrices for use in
filter at runtime*/
mCopy(ConfigData->covar, ConfigData->numStates, ConfigData->numStates,
ConfigData->sBar);
ukfCholDecomp(ConfigData->sBar, ConfigData->numStates,
ConfigData->numStates, tempMatrix);
mCopy(tempMatrix, ConfigData->numStates, ConfigData->numStates,
ConfigData->sBar);
ukfCholDecomp(ConfigData->qNoise, ConfigData->numStates,
ConfigData->numStates, ConfigData->sQnoise);
mTranspose(ConfigData->sQnoise, ConfigData->numStates,
ConfigData->numStates, ConfigData->sQnoise);
return;
}
/*! This method takes the parsed CSS sensor data and outputs an estimate of the
sun vector in the ADCS body frame
@return void
@param ConfigData The configuration data associated with the CSS estimator
@param callTime The clock time at which the function was called (nanoseconds)
*/
void Update_sunlineSuKF(SunlineSuKFConfig *ConfigData, uint64_t callTime,
uint64_t moduleID)
{
double newTimeTag;
double yBar[MAX_N_CSS_MEAS];
double tempYVec[MAX_N_CSS_MEAS];
double sunheading_hat[3];
double states_BN[SKF_N_STATES_SWITCH];
int i;
uint64_t ClockTime;
uint32_t ReadSize;
SunlineFilterFswMsg sunlineDataOutBuffer;
/*! Begin method steps*/
/*! - Read the input parsed CSS sensor data message*/
ClockTime = 0;
ReadSize = 0;
memset(&(ConfigData->cssSensorInBuffer), 0x0, sizeof(CSSArraySensorIntMsg));
ReadMessage(ConfigData->cssDataInMsgId, &ClockTime, &ReadSize,
sizeof(CSSArraySensorIntMsg), (void*) (&(ConfigData->cssSensorInBuffer)), moduleID);
v3Normalize(&ConfigData->state[0], sunheading_hat);
/*! - Check for switching frames */
if (v3Dot(ConfigData->bVec_B, sunheading_hat) > ConfigData->switchTresh)
{
sunlineSuKFSwitch(ConfigData->bVec_B, ConfigData->state, ConfigData->covar);
}
/*! - If the time tag from the measured data is new compared to previous step,
propagate and update the filter*/
newTimeTag = ClockTime * NANO2SEC;
if(newTimeTag >= ConfigData->timeTag && ReadSize > 0)
{
sunlineSuKFTimeUpdate(ConfigData, newTimeTag);
sunlineSuKFMeasUpdate(ConfigData, newTimeTag);
}
/*! - If current clock time is further ahead than the measured time, then
propagate to this current time-step*/
newTimeTag = callTime*NANO2SEC;
if(newTimeTag > ConfigData->timeTag)
{
sunlineSuKFTimeUpdate(ConfigData, newTimeTag);
}
/*! - Compute Post Fit Residuals, first get Y (eq 22) using the states post fit*/
sunlineSuKFMeasModel(ConfigData);
/*! - Compute the value for the yBar parameter (equation 23)*/
vSetZero(yBar, ConfigData->numObs);
for(i=0; i<ConfigData->countHalfSPs*2+1; i++)
{
vCopy(&(ConfigData->yMeas[i*ConfigData->numObs]), ConfigData->numObs,
tempYVec);
vScale(ConfigData->wM[i], tempYVec, ConfigData->numObs, tempYVec);
vAdd(yBar, ConfigData->numObs, tempYVec, yBar);
}
/*! - The post fits are y- ybar*/
mSubtract(ConfigData->obs, MAX_N_CSS_MEAS, 1, yBar, ConfigData->postFits);
/*! - Write the sunline estimate into the copy of the navigation message structure*/
v3Copy(ConfigData->state, ConfigData->outputSunline.vehSunPntBdy);
v3Normalize(ConfigData->outputSunline.vehSunPntBdy,
ConfigData->outputSunline.vehSunPntBdy);
ConfigData->outputSunline.timeTag = ConfigData->timeTag;
WriteMessage(ConfigData->navStateOutMsgId, callTime, sizeof(NavAttIntMsg),
&(ConfigData->outputSunline), moduleID);
/* Switch the rates back to omega_BN instead of oemga_SB */
vCopy(ConfigData->state, SKF_N_STATES_SWITCH, states_BN);
vScale(-1, &(states_BN[3]), 2, &(states_BN[3]));
/*! - Populate the filter states output buffer and write the output message*/
sunlineDataOutBuffer.timeTag = ConfigData->timeTag;
sunlineDataOutBuffer.numObs = ConfigData->numObs;
memmove(sunlineDataOutBuffer.covar, ConfigData->covar,
SKF_N_STATES_SWITCH*SKF_N_STATES_SWITCH*sizeof(double));
memmove(sunlineDataOutBuffer.state, states_BN, SKF_N_STATES_SWITCH*sizeof(double));
memmove(sunlineDataOutBuffer.postFitRes, ConfigData->postFits, MAX_N_CSS_MEAS*sizeof(double));
WriteMessage(ConfigData->filtDataOutMsgId, callTime, sizeof(SunlineFilterFswMsg),
&sunlineDataOutBuffer, moduleID);
return;
}
/*! This method propagates a sunline state vector forward in time. Note
that the calling parameter is updated in place to save on data copies.
@return void
@param stateInOut The state that is propagated
*/
void sunlineStateProp(double *stateInOut, double *b_Vec, double dt)
{
double propagatedVel[SKF_N_STATES_HALF];
double omegaCrossd[SKF_N_STATES_HALF];
double omega_BN_S[SKF_N_STATES_HALF] = {0, -stateInOut[3], -stateInOut[4]};
double omega_BN_B[SKF_N_STATES_HALF];
double dcm_BS[SKF_N_STATES_HALF][SKF_N_STATES_HALF];
mSetZero(dcm_BS, SKF_N_STATES_HALF, SKF_N_STATES_HALF);
sunlineSuKFComputeDCM_BS(stateInOut, b_Vec, &dcm_BS[0][0]);
mMultV(dcm_BS, SKF_N_STATES_HALF, SKF_N_STATES_HALF, omega_BN_S, omega_BN_B);
/* Set local variables to zero*/
vSetZero(propagatedVel, SKF_N_STATES_HALF);
/*! Begin state update steps */
/*! Take omega cross d*/
v3Cross(omega_BN_B, stateInOut, omegaCrossd);
/*! - Multiply omega cross d by dt and add to state to propagate */
v3Scale(-dt, omegaCrossd, propagatedVel);
v3Add(stateInOut, propagatedVel, stateInOut);
return;
}
/*! This method performs the time update for the sunline kalman filter.
It propagates the sigma points forward in time and then gets the current
covariance and state estimates.
@return void
@param ConfigData The configuration data associated with the CSS estimator
@param updateTime The time that we need to fix the filter to (seconds)
*/
void sunlineSuKFTimeUpdate(SunlineSuKFConfig *ConfigData, double updateTime)
{
int i, Index;
double sBarT[SKF_N_STATES_SWITCH*SKF_N_STATES_SWITCH];
double xComp[SKF_N_STATES_SWITCH], AT[(2 * SKF_N_STATES_SWITCH + SKF_N_STATES_SWITCH)*SKF_N_STATES_SWITCH];
double aRow[SKF_N_STATES_SWITCH], rAT[SKF_N_STATES_SWITCH*SKF_N_STATES_SWITCH], xErr[SKF_N_STATES_SWITCH];
double sBarUp[SKF_N_STATES_SWITCH*SKF_N_STATES_SWITCH];
double *spPtr;
/*! Begin method steps*/
ConfigData->dt = updateTime - ConfigData->timeTag;
/*! - Copy over the current state estimate into the 0th Sigma point and propagate by dt*/
vCopy(ConfigData->state, ConfigData->numStates,
&(ConfigData->SP[0 * ConfigData->numStates + 0]));
sunlineStateProp(&(ConfigData->SP[0 * ConfigData->numStates + 0]), ConfigData->bVec_B, ConfigData->dt);
/*! - Scale that Sigma point by the appopriate scaling factor (Wm[0])*/
vScale(ConfigData->wM[0], &(ConfigData->SP[0 * ConfigData->numStates + 0]),
ConfigData->numStates, ConfigData->xBar);
/*! - Get the transpose of the sBar matrix because it is easier to extract Rows vs columns*/
mTranspose(ConfigData->sBar, ConfigData->numStates, ConfigData->numStates,
sBarT);
/*! - For each Sigma point, apply sBar-based error, propagate forward, and scale by Wm just like 0th.
Note that we perform +/- sigma points simultaneously in loop to save loop values.*/
for (i = 0; i<ConfigData->countHalfSPs; i++)
{
Index = i + 1;
spPtr = &(ConfigData->SP[Index*ConfigData->numStates]);
vCopy(&sBarT[i*ConfigData->numStates], ConfigData->numStates, spPtr);
vScale(ConfigData->gamma, spPtr, ConfigData->numStates, spPtr);
vAdd(spPtr, ConfigData->numStates, ConfigData->state, spPtr);
sunlineStateProp(spPtr, ConfigData->bVec_B, ConfigData->dt);
vScale(ConfigData->wM[Index], spPtr, ConfigData->numStates, xComp);
vAdd(xComp, ConfigData->numStates, ConfigData->xBar, ConfigData->xBar);
Index = i + 1 + ConfigData->countHalfSPs;
spPtr = &(ConfigData->SP[Index*ConfigData->numStates]);
vCopy(&sBarT[i*ConfigData->numStates], ConfigData->numStates, spPtr);
vScale(-ConfigData->gamma, spPtr, ConfigData->numStates, spPtr);
vAdd(spPtr, ConfigData->numStates, ConfigData->state, spPtr);
sunlineStateProp(spPtr, ConfigData->bVec_B, ConfigData->dt);
vScale(ConfigData->wM[Index], spPtr, ConfigData->numStates, xComp);
vAdd(xComp, ConfigData->numStates, ConfigData->xBar, ConfigData->xBar);
}
/*! - Zero the AT matrix prior to assembly*/
mSetZero(AT, (2 * ConfigData->countHalfSPs + ConfigData->numStates),
ConfigData->countHalfSPs);
/*! - Assemble the AT matrix. Note that this matrix is the internals of
the qr decomposition call in the source design documentation. It is
the inside of equation 20 in that document*/
for (i = 0; i<2 * ConfigData->countHalfSPs; i++)
{
vScale(-1.0, ConfigData->xBar, ConfigData->numStates, aRow);
vAdd(aRow, ConfigData->numStates,
&(ConfigData->SP[(i+1)*ConfigData->numStates]), aRow);
vScale(sqrt(ConfigData->wC[i+1]), aRow, ConfigData->numStates, aRow);
memcpy((void *)&AT[i*ConfigData->numStates], (void *)aRow,
ConfigData->numStates*sizeof(double));
}
/*! - Pop the sQNoise matrix on to the end of AT prior to getting QR decomposition*/
memcpy(&AT[2 * ConfigData->countHalfSPs*ConfigData->numStates],
ConfigData->sQnoise, ConfigData->numStates*ConfigData->numStates
*sizeof(double));
/*! - QR decomposition (only R computed!) of the AT matrix provides the new sBar matrix*/
ukfQRDJustR(AT, 2 * ConfigData->countHalfSPs + ConfigData->numStates,
ConfigData->countHalfSPs, rAT);
mCopy(rAT, ConfigData->numStates, ConfigData->numStates, sBarT);
mTranspose(sBarT, ConfigData->numStates, ConfigData->numStates,
ConfigData->sBar);
/*! - Shift the sBar matrix over by the xBar vector using the appropriate weight
like in equation 21 in design document.*/
vScale(-1.0, ConfigData->xBar, ConfigData->numStates, xErr);
vAdd(xErr, ConfigData->numStates, &ConfigData->SP[0], xErr);
ukfCholDownDate(ConfigData->sBar, xErr, ConfigData->wC[0],
ConfigData->numStates, sBarUp);
/*! - Save current sBar matrix, covariance, and state estimate off for further use*/
mCopy(sBarUp, ConfigData->numStates, ConfigData->numStates, ConfigData->sBar);
mTranspose(ConfigData->sBar, ConfigData->numStates, ConfigData->numStates,
ConfigData->covar);
mMultM(ConfigData->sBar, ConfigData->numStates, ConfigData->numStates,
ConfigData->covar, ConfigData->numStates, ConfigData->numStates,
ConfigData->covar);
vCopy(&(ConfigData->SP[0]), ConfigData->numStates, ConfigData->state );
ConfigData->timeTag = updateTime;
}
/*! This method computes what the expected measurement vector is for each CSS
that is present on the spacecraft. All data is transacted from the main
data structure for the model because there are many variables that would
have to be updated otherwise.
@return void
@param ConfigData The configuration data associated with the CSS estimator
*/
void sunlineSuKFMeasModel(SunlineSuKFConfig *ConfigData)
{
uint32_t i, j, obsCounter;
double sensorNormal[3];
/* Begin method steps */
obsCounter = 0;
/*! - Loop over all available coarse sun sensors and only use ones that meet validity threshold*/
for(i=0; i<ConfigData->numCSSTotal; i++)
{
if(ConfigData->cssSensorInBuffer.CosValue[i] > ConfigData->sensorUseThresh)
{
/*! - For each valid measurement, copy observation value and compute expected obs value
on a per sigma-point basis.*/
v3Scale(ConfigData->CBias[i], &(ConfigData->cssNHat_B[i*3]), sensorNormal);
ConfigData->obs[obsCounter] = ConfigData->cssSensorInBuffer.CosValue[i];
for(j=0; j<ConfigData->countHalfSPs*2+1; j++)
{
ConfigData->yMeas[obsCounter*(ConfigData->countHalfSPs*2+1) + j] =
v3Dot(&(ConfigData->SP[j*SKF_N_STATES_SWITCH]), sensorNormal);
}
obsCounter++;
}
}
/*! - yMeas matrix was set backwards deliberately so we need to transpose it through*/
mTranspose(ConfigData->yMeas, obsCounter, ConfigData->countHalfSPs*2+1,
ConfigData->yMeas);
ConfigData->numObs = obsCounter;
}
/*! This method performs the measurement update for the sunline kalman filter.
It applies the observations in the obs vectors to the current state estimate and
updates the state/covariance with that information.
@return void
@param ConfigData The configuration data associated with the CSS estimator
@param updateTime The time that we need to fix the filter to (seconds)
*/
void sunlineSuKFMeasUpdate(SunlineSuKFConfig *ConfigData, double updateTime)
{
uint32_t i;
double yBar[MAX_N_CSS_MEAS], syInv[MAX_N_CSS_MEAS*MAX_N_CSS_MEAS];
double kMat[SKF_N_STATES_SWITCH*MAX_N_CSS_MEAS];
double xHat[SKF_N_STATES_SWITCH], sBarT[SKF_N_STATES_SWITCH*SKF_N_STATES_SWITCH], tempYVec[MAX_N_CSS_MEAS];
double AT[(2 * SKF_N_STATES_SWITCH + MAX_N_CSS_MEAS)*MAX_N_CSS_MEAS], qChol[MAX_N_CSS_MEAS*MAX_N_CSS_MEAS];
double rAT[MAX_N_CSS_MEAS*MAX_N_CSS_MEAS], syT[MAX_N_CSS_MEAS*MAX_N_CSS_MEAS];
double sy[MAX_N_CSS_MEAS*MAX_N_CSS_MEAS];
double updMat[MAX_N_CSS_MEAS*MAX_N_CSS_MEAS], pXY[SKF_N_STATES_SWITCH*MAX_N_CSS_MEAS];
/*! Begin method steps*/
/*! - Compute the valid observations and the measurement model for all observations*/
sunlineSuKFMeasModel(ConfigData);
/*! - Compute the value for the yBar parameter (note that this is equation 23 in the
time update section of the reference document*/
vSetZero(yBar, ConfigData->numObs);
for(i=0; i<ConfigData->countHalfSPs*2+1; i++)
{
vCopy(&(ConfigData->yMeas[i*ConfigData->numObs]), ConfigData->numObs,
tempYVec);
vScale(ConfigData->wM[i], tempYVec, ConfigData->numObs, tempYVec);
vAdd(yBar, ConfigData->numObs, tempYVec, yBar);
}
/*! - Populate the matrix that we perform the QR decomposition on in the measurement
update section of the code. This is based on the differenence between the yBar
parameter and the calculated measurement models. Equation 24 in driving doc. */
mSetZero(AT, ConfigData->countHalfSPs*2+ConfigData->numObs,
ConfigData->numObs);
for(i=0; i<ConfigData->countHalfSPs*2; i++)
{
vScale(-1.0, yBar, ConfigData->numObs, tempYVec);
vAdd(tempYVec, ConfigData->numObs,
&(ConfigData->yMeas[(i+1)*ConfigData->numObs]), tempYVec);
vScale(sqrt(ConfigData->wC[i+1]), tempYVec, ConfigData->numObs, tempYVec);
memcpy(&(AT[i*ConfigData->numObs]), tempYVec,
ConfigData->numObs*sizeof(double));
}
/*! - This is the square-root of the Rk matrix which we treat as the Cholesky
decomposition of the observation variance matrix constructed for our number
of observations*/
mSetZero(ConfigData->qObs, ConfigData->numCSSTotal, ConfigData->numCSSTotal);
mSetIdentity(ConfigData->qObs, ConfigData->numObs, ConfigData->numObs);
mScale(ConfigData->qObsVal, ConfigData->qObs, ConfigData->numObs,
ConfigData->numObs, ConfigData->qObs);
ukfCholDecomp(ConfigData->qObs, ConfigData->numObs, ConfigData->numObs, qChol);
memcpy(&(AT[2*ConfigData->countHalfSPs*ConfigData->numObs]),
qChol, ConfigData->numObs*ConfigData->numObs*sizeof(double));
/*! - Perform QR decomposition (only R again) of the above matrix to obtain the
current Sy matrix*/
ukfQRDJustR(AT, 2*ConfigData->countHalfSPs+ConfigData->numObs,
ConfigData->numObs, rAT);
mCopy(rAT, ConfigData->numObs, ConfigData->numObs, syT);
mTranspose(syT, ConfigData->numObs, ConfigData->numObs, sy);
/*! - Shift the matrix over by the difference between the 0th SP-based measurement
model and the yBar matrix (cholesky down-date again)*/
vScale(-1.0, yBar, ConfigData->numObs, tempYVec);
vAdd(tempYVec, ConfigData->numObs, &(ConfigData->yMeas[0]), tempYVec);
ukfCholDownDate(sy, tempYVec, ConfigData->wC[0],
ConfigData->numObs, updMat);
/*! - Shifted matrix represents the Sy matrix */
mCopy(updMat, ConfigData->numObs, ConfigData->numObs, sy);
mTranspose(sy, ConfigData->numObs, ConfigData->numObs, syT);
/*! - Construct the Pxy matrix (equation 26) which multiplies the Sigma-point cloud
by the measurement model cloud (weighted) to get the total Pxy matrix*/
mSetZero(pXY, ConfigData->numStates, ConfigData->numObs);
for(i=0; i<2*ConfigData->countHalfSPs+1; i++)
{
vScale(-1.0, yBar, ConfigData->numObs, tempYVec);
vAdd(tempYVec, ConfigData->numObs,
&(ConfigData->yMeas[i*ConfigData->numObs]), tempYVec);
vSubtract(&(ConfigData->SP[i*ConfigData->numStates]), ConfigData->numStates,
ConfigData->xBar, xHat);
vScale(ConfigData->wC[i], xHat, ConfigData->numStates, xHat);
mMultM(xHat, ConfigData->numStates, 1, tempYVec, 1, ConfigData->numObs,
kMat);
mAdd(pXY, ConfigData->numStates, ConfigData->numObs, kMat, pXY);
}
/*! - Then we need to invert the SyT*Sy matrix to get the Kalman gain factor. Since
The Sy matrix is lower triangular, we can do a back-sub inversion instead of
a full matrix inversion. That is the ukfUInv and ukfLInv calls below. Once that
multiplication is done (equation 27), we have the Kalman Gain.*/
ukfUInv(syT, ConfigData->numObs, ConfigData->numObs, syInv);
mMultM(pXY, ConfigData->numStates, ConfigData->numObs, syInv,
ConfigData->numObs, ConfigData->numObs, kMat);
ukfLInv(sy, ConfigData->numObs, ConfigData->numObs, syInv);
mMultM(kMat, ConfigData->numStates, ConfigData->numObs, syInv,
ConfigData->numObs, ConfigData->numObs, kMat);
/*! - Difference the yBar and the observations to get the observed error and
multiply by the Kalman Gain to get the state update. Add the state update
to the state to get the updated state value (equation 27).*/
vSubtract(ConfigData->obs, ConfigData->numObs, yBar, tempYVec);
mMultM(kMat, ConfigData->numStates, ConfigData->numObs, tempYVec,
ConfigData->numObs, 1, xHat);
vAdd(ConfigData->state, ConfigData->numStates, xHat, ConfigData->state);
/*! - Compute the updated matrix U from equation 28. Note that I then transpose it
so that I can extract "columns" from adjacent memory*/
mMultM(kMat, ConfigData->numStates, ConfigData->numObs, sy,
ConfigData->numObs, ConfigData->numObs, pXY);
mTranspose(pXY, ConfigData->numStates, ConfigData->numObs, pXY);
/*! - For each column in the update matrix, perform a cholesky down-date on it to
get the total shifted S matrix (called sBar in internal parameters*/
for(i=0; i<ConfigData->numObs; i++)
{
vCopy(&(pXY[i*ConfigData->numStates]), ConfigData->numStates, tempYVec);
ukfCholDownDate(ConfigData->sBar, tempYVec, -1.0, ConfigData->numStates, sBarT);
mCopy(sBarT, ConfigData->numStates, ConfigData->numStates,
ConfigData->sBar);
}
/*! - Compute equivalent covariance based on updated sBar matrix*/
mTranspose(ConfigData->sBar, ConfigData->numStates, ConfigData->numStates,
ConfigData->covar);
mMultM(ConfigData->sBar, ConfigData->numStates, ConfigData->numStates,
ConfigData->covar, ConfigData->numStates, ConfigData->numStates,
ConfigData->covar);
}
/*! This method computes the dcms necessary for the switch between the two frames.
It the switches the states and the covariance, and sets s2 to be the new, different vector of the body frame.
@return void
@param covarBar The time updated covariance
@param hObs The H matrix filled with the observations
@param s2_B Pointer to the second frame vector
@param states Pointer to the states
@param covar Pointer to the covariance
*/
void sunlineSuKFSwitch(double *bVec_B, double *states, double *covar)
{
double dcm_BSold[SKF_N_STATES_HALF][SKF_N_STATES_HALF];
double dcm_BSnew_T[SKF_N_STATES_HALF][SKF_N_STATES_HALF];
double dcm_SnewSold[SKF_N_STATES_HALF][SKF_N_STATES_HALF];
double switchMatP[SKF_N_STATES_SWITCH][SKF_N_STATES_SWITCH];
double switchMat[SKF_N_STATES_SWITCH][SKF_N_STATES_SWITCH];
double sun_heading_norm[SKF_N_STATES_HALF];
double b1[SKF_N_STATES_HALF];
double b2[SKF_N_STATES_HALF];
/*! Set the body frame vectors*/
v3Set(1, 0, 0, b1);
v3Set(0, 1, 0, b2);
v3Normalize(&(states[0]), sun_heading_norm);
/*! Populate the dcm_BS with the "old" S-frame*/
sunlineSuKFComputeDCM_BS(sun_heading_norm, bVec_B, &dcm_BSold[0][0]);
if (v3IsEqual(bVec_B, b1, 1e-10))
{
sunlineSuKFComputeDCM_BS(sun_heading_norm, b2, &dcm_BSnew_T[0][0]);
v3Copy(b2, bVec_B);
}
else
{
sunlineSuKFComputeDCM_BS(sun_heading_norm, b1, &dcm_BSnew_T[0][0]);
v3Copy(b1, bVec_B);
}
mTranspose(dcm_BSnew_T, SKF_N_STATES_HALF, SKF_N_STATES_HALF, dcm_BSnew_T);
mMultM(dcm_BSnew_T, 3, 3, dcm_BSold, 3, 3, dcm_SnewSold);
mSetIdentity(switchMat, SKF_N_STATES_SWITCH, SKF_N_STATES_SWITCH);
mSetSubMatrix(&dcm_SnewSold[1][1], 1, 2, &switchMat, SKF_N_STATES_SWITCH, SKF_N_STATES_SWITCH, 3, 3);
mSetSubMatrix(&dcm_SnewSold[2][1], 1, 2, &switchMat, SKF_N_STATES_SWITCH, SKF_N_STATES_SWITCH, 4, 3);
mMultV(switchMat, SKF_N_STATES_SWITCH, SKF_N_STATES_SWITCH, states, states);
mMultM(switchMat, SKF_N_STATES_SWITCH, SKF_N_STATES_SWITCH, covar, SKF_N_STATES_SWITCH, SKF_N_STATES_SWITCH, switchMatP);
mTranspose(switchMat, SKF_N_STATES_SWITCH, SKF_N_STATES_SWITCH, switchMat);
mMultM(switchMatP, SKF_N_STATES_SWITCH, SKF_N_STATES_SWITCH, switchMat, SKF_N_STATES_SWITCH, SKF_N_STATES_SWITCH, covar);
return;
}
void sunlineSuKFComputeDCM_BS(double sunheading[SKF_N_STATES_HALF], double bVec[SKF_N_STATES_HALF], double *dcm){
double s1_B[SKF_N_STATES_HALF];
double s2_B[SKF_N_STATES_HALF];
double s3_B[SKF_N_STATES_HALF];
mSetZero(dcm, SKF_N_STATES_HALF, SKF_N_STATES_HALF);
v3SetZero(s2_B);
v3SetZero(s3_B);
v3Normalize(sunheading, s1_B);
v3Cross(sunheading, bVec, s2_B);
if (v3Norm(s2_B) < 1E-5){
mSetIdentity(dcm, SKF_N_STATES_HALF, SKF_N_STATES_HALF);
}
else{
v3Normalize(s2_B, s2_B);
/*! Populate the dcm_BS with the "new" S-frame*/
mSetSubMatrix(s1_B, 1, SKF_N_STATES_HALF, dcm, SKF_N_STATES_HALF, SKF_N_STATES_HALF, 0, 0);
mSetSubMatrix(&(s2_B), 1, SKF_N_STATES_HALF, dcm, SKF_N_STATES_HALF, SKF_N_STATES_HALF, 1, 0);
v3Cross(sunheading, s2_B, s3_B);
v3Normalize(s3_B, s3_B);
mSetSubMatrix(&(s3_B), 1, SKF_N_STATES_HALF, dcm, SKF_N_STATES_HALF, SKF_N_STATES_HALF, 2, 0);
mTranspose(dcm, SKF_N_STATES_HALF, SKF_N_STATES_HALF, dcm);
}
}
| 47.04127 | 135 | 0.702052 | [
"vector",
"model"
] |
8c05219a856a30c84eae46877d28f0524b659810 | 2,924 | h | C | accelerators/kdtreeaccel.h | cathook/rendering_final_proj | d0c147b563d6949839983bf38317c81367e2ed4c | [
"BSD-2-Clause"
] | 1 | 2020-01-13T11:45:30.000Z | 2020-01-13T11:45:30.000Z | accelerators/kdtreeaccel.h | piwell/CS348B-pbrt | 147a9a3ef55cfcb0a1ad0132c63d1ac2f928418f | [
"BSD-2-Clause"
] | null | null | null | accelerators/kdtreeaccel.h | piwell/CS348B-pbrt | 147a9a3ef55cfcb0a1ad0132c63d1ac2f928418f | [
"BSD-2-Clause"
] | null | null | null |
/*
pbrt source code Copyright(c) 1998-2012 Matt Pharr and Greg Humphreys.
This file is part of pbrt.
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.
*/
#if defined(_MSC_VER)
#pragma once
#endif
#ifndef PBRT_ACCELERATORS_KDTREEACCEL_H
#define PBRT_ACCELERATORS_KDTREEACCEL_H
// accelerators/kdtreeaccel.h*
#include "pbrt.h"
#include "primitive.h"
// KdTreeAccel Declarations
struct KdAccelNode;
struct BoundEdge;
class KdTreeAccel : public Aggregate {
public:
// KdTreeAccel Public Methods
KdTreeAccel(const vector<Reference<Primitive> > &p,
int icost = 80, int scost = 1, float ebonus = 0.5f, int maxp = 1,
int maxDepth = -1);
BBox WorldBound() const { return bounds; }
bool CanIntersect() const { return true; }
~KdTreeAccel();
bool Intersect(const Ray &ray, Intersection *isect) const;
bool IntersectP(const Ray &ray) const;
private:
// KdTreeAccel Private Methods
void buildTree(int nodeNum, const BBox &bounds,
const vector<BBox> &primBounds, uint32_t *primNums, int nprims, int depth,
BoundEdge *edges[3], uint32_t *prims0, uint32_t *prims1, int badRefines = 0);
// KdTreeAccel Private Data
int isectCost, traversalCost, maxPrims, maxDepth;
float emptyBonus;
vector<Reference<Primitive> > primitives;
KdAccelNode *nodes;
int nAllocedNodes, nextFreeNode;
BBox bounds;
MemoryArena arena;
};
struct KdToDo {
const KdAccelNode *node;
float tmin, tmax;
};
KdTreeAccel *CreateKdTreeAccelerator(const vector<Reference<Primitive> > &prims,
const ParamSet &ps);
#endif // PBRT_ACCELERATORS_KDTREEACCEL_H
| 34.809524 | 85 | 0.730506 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.