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
9ccf689caf8e68bc928a2faef7e10495aa8c8d54
3,001
h
C
src/animation/animation.h
nemerle/LumixEngine
6cfee07c4268c15994c7171cb5625179b1f369e2
[ "MIT" ]
null
null
null
src/animation/animation.h
nemerle/LumixEngine
6cfee07c4268c15994c7171cb5625179b1f369e2
[ "MIT" ]
null
null
null
src/animation/animation.h
nemerle/LumixEngine
6cfee07c4268c15994c7171cb5625179b1f369e2
[ "MIT" ]
null
null
null
#pragma once #include "engine/hash.h" #include "engine/hash_map.h" #include "engine/resource.h" #include "engine/string.h" namespace Lumix { struct Model; struct Pose; struct Quat; struct Vec3; struct Time { Time() {} explicit Time(u32 v) : value(v) {} static Time fromSeconds(float time) { ASSERT(time >= 0); return Time{u32(time * ONE_SECOND)}; } float seconds() const { return float(value / double(ONE_SECOND)); } Time operator*(float t) const { return Time{u32(value * t)}; } float operator/(const Time& rhs) const { return float(double(value) / double(rhs.value)); } Time operator+(const Time& rhs) const { return Time{value + rhs.value}; } Time operator-(const Time& rhs) const { return Time{value - rhs.value}; } void operator+=(const Time& rhs) { value += rhs.value; } bool operator<(const Time& rhs) const { return value < rhs.value; } bool operator<=(const Time& rhs) const { return value <= rhs.value; } bool operator>=(const Time& rhs) const { return value >= rhs.value; } Time operator%(const Time& rhs) const { return Time{value % rhs.value}; } u32 raw() const { return value; } private: u32 value; enum { ONE_SECOND = 1 << 15 }; }; struct BoneMask { BoneMask(IAllocator& allocator) : bones(allocator) {} BoneMask(BoneMask&& rhs) = default; StaticString<32> name; HashMap<BoneNameHash, u8> bones; }; struct Animation final : Resource { public: static const u32 HEADER_MAGIC = 0x5f4c4146; // '_LAF' static const ResourceType TYPE; public: enum class CurveType : u8 { KEYFRAMED, SAMPLED }; enum class Version : u32 { FIRST = 3, LAST }; struct Header { u32 magic; Version version; Time length; u32 frame_count; }; public: Animation(const Path& path, ResourceManager& resource_manager, IAllocator& allocator); ResourceType getType() const override { return TYPE; } Vec3 getTranslation(Time time, u32 curve_idx) const; Quat getRotation(Time time, u32 curve_idx) const; int getTranslationCurveIndex(BoneNameHash name_hash) const; int getRotationCurveIndex(BoneNameHash name_hash) const; void getRelativePose(Time time, Pose& pose, const Model& model, const BoneMask* mask) const; void getRelativePose(Time time, Pose& pose, const Model& model, float weight, const BoneMask* mask) const; Time getLength() const { return m_length; } private: void unload() override; bool load(u64 size, const u8* mem) override; private: Time m_length; struct TranslationCurve { BoneNameHash name; u32 count; const u16* times; const Vec3* pos; }; struct RotationCurve { BoneNameHash name; u32 count; const u16* times; const Quat* rot; }; Array<TranslationCurve> m_translations; Array<RotationCurve> m_rotations; Array<u8> m_mem; u32 m_frame_count = 0; friend struct AnimationSampler; }; inline Time lerp(Time op1, Time op2, float t) { const double d = double(op1.raw()) * (1 - t) + double(op2.raw()) * t; return Time(u32(d)); } } // namespace Lumix
24.398374
108
0.694768
[ "model" ]
9cd1e0caa24069d62bf3f23c366702148495760a
4,256
h
C
aws-cpp-sdk-dynamodbstreams/include/aws/dynamodbstreams/model/KeySchemaElement.h
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2020-07-16T19:03:13.000Z
2020-07-16T19:03:13.000Z
aws-cpp-sdk-dynamodbstreams/include/aws/dynamodbstreams/model/KeySchemaElement.h
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
18
2018-05-15T16:41:07.000Z
2018-05-21T00:46:30.000Z
aws-cpp-sdk-dynamodbstreams/include/aws/dynamodbstreams/model/KeySchemaElement.h
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2021-10-01T15:29:44.000Z
2021-10-01T15:29:44.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/dynamodbstreams/DynamoDBStreams_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/dynamodbstreams/model/KeyType.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace DynamoDBStreams { namespace Model { /** * <p>Represents <i>a single element</i> of a key schema. A key schema specifies * the attributes that make up the primary key of a table, or the key attributes of * an index.</p> <p>A <i>KeySchemaElement</i> represents exactly one attribute of * the primary key. For example, a hash type primary key would be represented by * one <i>KeySchemaElement</i>. A hash-and-range type primary key would require one * <i>KeySchemaElement</i> for the hash attribute, and another * <i>KeySchemaElement</i> for the range attribute.</p> */ class AWS_DYNAMODBSTREAMS_API KeySchemaElement { public: KeySchemaElement(); KeySchemaElement(const Aws::Utils::Json::JsonValue& jsonValue); KeySchemaElement& operator=(const Aws::Utils::Json::JsonValue& jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The name of a key attribute.</p> */ inline const Aws::String& GetAttributeName() const{ return m_attributeName; } /** * <p>The name of a key attribute.</p> */ inline void SetAttributeName(const Aws::String& value) { m_attributeNameHasBeenSet = true; m_attributeName = value; } /** * <p>The name of a key attribute.</p> */ inline void SetAttributeName(Aws::String&& value) { m_attributeNameHasBeenSet = true; m_attributeName = std::move(value); } /** * <p>The name of a key attribute.</p> */ inline void SetAttributeName(const char* value) { m_attributeNameHasBeenSet = true; m_attributeName.assign(value); } /** * <p>The name of a key attribute.</p> */ inline KeySchemaElement& WithAttributeName(const Aws::String& value) { SetAttributeName(value); return *this;} /** * <p>The name of a key attribute.</p> */ inline KeySchemaElement& WithAttributeName(Aws::String&& value) { SetAttributeName(std::move(value)); return *this;} /** * <p>The name of a key attribute.</p> */ inline KeySchemaElement& WithAttributeName(const char* value) { SetAttributeName(value); return *this;} /** * <p>The attribute data, consisting of the data type and the attribute value * itself.</p> */ inline const KeyType& GetKeyType() const{ return m_keyType; } /** * <p>The attribute data, consisting of the data type and the attribute value * itself.</p> */ inline void SetKeyType(const KeyType& value) { m_keyTypeHasBeenSet = true; m_keyType = value; } /** * <p>The attribute data, consisting of the data type and the attribute value * itself.</p> */ inline void SetKeyType(KeyType&& value) { m_keyTypeHasBeenSet = true; m_keyType = std::move(value); } /** * <p>The attribute data, consisting of the data type and the attribute value * itself.</p> */ inline KeySchemaElement& WithKeyType(const KeyType& value) { SetKeyType(value); return *this;} /** * <p>The attribute data, consisting of the data type and the attribute value * itself.</p> */ inline KeySchemaElement& WithKeyType(KeyType&& value) { SetKeyType(std::move(value)); return *this;} private: Aws::String m_attributeName; bool m_attributeNameHasBeenSet; KeyType m_keyType; bool m_keyTypeHasBeenSet; }; } // namespace Model } // namespace DynamoDBStreams } // namespace Aws
32.242424
127
0.683741
[ "model" ]
9cd650a883457560a4bc9b12eb6f574e5b0ddff7
7,473
h
C
include/brep/brnode.h
maths22/brlcad
44d270fca6e3336013322163ecae2920b30294ae
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
include/brep/brnode.h
maths22/brlcad
44d270fca6e3336013322163ecae2920b30294ae
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
include/brep/brnode.h
maths22/brlcad
44d270fca6e3336013322163ecae2920b30294ae
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
/* B R N O D E . H * BRL-CAD * * Copyright (c) 2004-2016 United States Government as represented by * the U.S. Army Research Laboratory. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this file; see the file named COPYING for more * information. */ /** @addtogroup brep_brnode * * @brief * Bounding Rectangle Hierarchy Node. * */ #ifndef BREP_BRNODE_H #define BREP_BRNODE_H #include "common.h" #ifdef __cplusplus extern "C++" { /* @cond */ #include <vector> #include <list> /* @endcond */ } #endif #include "brep/defines.h" /** @{ */ /** @file brep/brnode.h */ #ifdef __cplusplus __BEGIN_DECLS extern "C++" { namespace brlcad { /** * Bounding Rectangle Hierarchy */ class BREP_EXPORT BRNode { public: BRNode(); BRNode(const ON_BoundingBox &node); BRNode(const ON_Curve *curve, int m_adj_face_index, const ON_BoundingBox &node, const ON_BrepFace *face, const ON_Interval &t, bool innerTrim = false, bool checkTrim = true, bool trimmed = false); ~BRNode(); /** List of all children of a given node */ std::vector<BRNode *> *m_children; /** Bounding Box */ ON_BoundingBox m_node; /** Node management functions */ void addChild(const ON_BoundingBox &child); void addChild(BRNode *child); void removeChild(BRNode *child); /** Test if this node is a leaf node (i.e. m_children is empty) */ bool isLeaf(); /** Return a list of all nodes below this node that are leaf nodes */ void getLeaves(std::list<BRNode *> &out_leaves); /** Report the depth of this node in the hierarchy */ int depth(); /** * Get 2 points defining bounding box: * * @verbatim * *----------------max * | | * v | | * | | * min----------------* * u * @endverbatim */ void GetBBox(fastf_t *min, fastf_t *max) const; /** Surface Information */ const ON_BrepFace *m_face; ON_Interval m_u; ON_Interval m_v; /** Trim Curve Information */ const ON_Curve *m_trim; ON_Interval m_t; int m_adj_face_index; /** Trimming Flags */ bool m_checkTrim; bool m_trimmed; bool m_XIncreasing; bool m_Horizontal; bool m_Vertical; bool m_innerTrim; ON_3dPoint m_estimate; ON_2dPoint getClosestPointEstimate(const ON_3dPoint &pt); ON_2dPoint getClosestPointEstimate(const ON_3dPoint &pt, ON_Interval &u, ON_Interval &v); fastf_t getLinearEstimateOfV(fastf_t u); fastf_t getCurveEstimateOfV(fastf_t u, fastf_t tol) const; fastf_t getCurveEstimateOfU(fastf_t v, fastf_t tol) const; bool isTrimmed(const ON_2dPoint &uv, double &trimdist) const; bool doTrimming() const; private: BRNode *closer(const ON_3dPoint &pt, BRNode *left, BRNode *right); fastf_t m_slope; fastf_t m_vdot; fastf_t m_bb_diag; ON_3dPoint m_start; ON_3dPoint m_end; }; inline BRNode::BRNode() { m_start = ON_3dPoint::UnsetPoint; m_end = ON_3dPoint::UnsetPoint; m_children = new std::vector<BRNode *>(); } inline _BU_ATTR_ALWAYS_INLINE BRNode::BRNode( const ON_Curve *curve, int adj_face_index, const ON_BoundingBox &node, const ON_BrepFace *face, const ON_Interval &t, bool innerTrim /* = false */, bool checkTrim /* = true */, bool trimmed /* = false */) : m_node(node), m_face(face), m_trim(curve), m_t(t), m_adj_face_index(adj_face_index), m_checkTrim(checkTrim), m_trimmed(trimmed), m_innerTrim(innerTrim), m_slope(0.0), m_vdot(0.0) { m_start = curve->PointAt(m_t[0]); m_end = curve->PointAt(m_t[1]); /* check for vertical segments they can be removed from trims * above (can't tell direction and don't need */ m_Horizontal = false; m_Vertical = false; /* * should be okay since we split on Horz/Vert tangents */ if (m_end[X] < m_start[X]) { m_u[0] = m_end[X]; m_u[1] = m_start[X]; } else { m_u[0] = m_start[X]; m_u[1] = m_end[X]; } if (m_end[Y] < m_start[Y]) { m_v[0] = m_end[Y]; m_v[1] = m_start[Y]; } else { m_v[0] = m_start[Y]; m_v[1] = m_end[Y]; } if (NEAR_EQUAL(m_end[X], m_start[X], 0.000001)) { m_Vertical = true; if (m_innerTrim) { m_XIncreasing = false; } else { m_XIncreasing = true; } } else if (NEAR_EQUAL(m_end[Y], m_start[Y], 0.000001)) { m_Horizontal = true; if ((m_end[X] - m_start[X]) > 0.0) { m_XIncreasing = true; } else { m_XIncreasing = false; } m_slope = 0.0; } else { if ((m_end[X] - m_start[X]) > 0.0) { m_XIncreasing = true; } else { m_XIncreasing = false; } m_slope = (m_end[Y] - m_start[Y]) / (m_end[X] - m_start[X]); } m_bb_diag = DIST_PT_PT(m_start, m_end); m_children = new std::vector<BRNode *>(); } inline _BU_ATTR_ALWAYS_INLINE BRNode::BRNode(const ON_BoundingBox &node) : m_node(node) { m_adj_face_index = -99; m_checkTrim = true; m_trimmed = false; m_Horizontal = false; m_Vertical = false; m_XIncreasing = false; m_innerTrim = false; m_bb_diag = 0.0; m_slope = 0.0; m_vdot = 0.0; m_face = NULL; m_trim = NULL; m_start = ON_3dPoint::UnsetPoint; m_end = ON_3dPoint::UnsetPoint; for (int i = 0; i < 3; i++) { double d = m_node.m_max[i] - m_node.m_min[i]; if (NEAR_ZERO(d, ON_ZERO_TOLERANCE)) { m_node.m_min[i] -= 0.001; m_node.m_max[i] += 0.001; } } m_start = m_node.m_min; m_end = m_node.m_max; m_children = new std::vector<BRNode *>(); } inline void BRNode::addChild(const ON_BoundingBox &child) { m_children->push_back(new BRNode(child)); } inline void BRNode::addChild(BRNode *child) { if (LIKELY(child != NULL)) { m_children->push_back(child); } } inline void BRNode::removeChild(BRNode *child) { std::vector<BRNode *>::iterator i; for (i = m_children->begin(); i < m_children->end(); ++i) { if (*i == child) { delete *i; m_children->erase(i); } } } inline bool BRNode::isLeaf() { if (m_children->size() == 0) { return true; } return false; } inline void _BU_ATTR_ALWAYS_INLINE BRNode::GetBBox(fastf_t *min, fastf_t *max) const { VSETALL(min, INFINITY); VSETALL(max, -INFINITY); if (m_start != ON_3dPoint::UnsetPoint) { VMINMAX(min, max, m_start); } if (m_end != ON_3dPoint::UnsetPoint) { VMINMAX(min, max, m_end); } } inline bool BRNode::doTrimming() const { return m_checkTrim; } extern bool sortX(BRNode *first, BRNode *second); extern bool sortY(BRNode *first, BRNode *second); } /* namespace brlcad */ } /* extern C++ */ __END_DECLS #endif /** @} */ #endif /* BREP_BRNODE_H */ /* * Local Variables: * mode: C * tab-width: 8 * indent-tabs-mode: t * c-file-style: "stroustrup" * End: * ex: shiftwidth=4 tabstop=8 */
22.993846
91
0.62117
[ "cad", "vector" ]
9ce2362358448df7f1773b7ba2379ae896147cb2
4,359
h
C
include/cno_settings.h
Anadian/CNO
02d7d60f6dbc2451bc76134099dca42bc54e8cbb
[ "MIT" ]
null
null
null
include/cno_settings.h
Anadian/CNO
02d7d60f6dbc2451bc76134099dca42bc54e8cbb
[ "MIT" ]
null
null
null
include/cno_settings.h
Anadian/CNO
02d7d60f6dbc2451bc76134099dca42bc54e8cbb
[ "MIT" ]
null
null
null
//cno_settings.h #ifndef CNO_SETTINGS_H #define CNO_SETTINGS_H #ifdef __cplusplus extern "C"{ #endif //__cplusplus #if (CNO_SETTINGS_MATCH_ENGINE == CNO_SETTINGS_MATCH_ENGINE_REGEX) && (!defined(CNO_SETTINGS_MATCH_VALIDATION_REGEX) || !defined(CNO_SETTINGS_MATCH_REGEX_NMATCH)) #define CNO_SETTINGS_MATCH_VALIDATION_REGEX ":([-0-9A-Za-z_ ]*)?:([0-9A-Za-z_]+)?:(([-0-9A-Za-z]+)(=([0-9A-Za-z]))?)?:(0|(([NIRBWAUFDnirbwaufd])[^!?=;]*([!?])(=(((\|)|(([-0-9A-Za-z_.\/\\ ]+)([!?])?)))+)?));" #define CNO_SETTINGS_MATCH_REGEX_NMATCH 18 #endif //(CNO_SETTINGS_MATCH_ENGINE == CNO_SETTINGS_MATCH_ENGINE_REGEX) && (!defined(CNO_SETTING_VALIDATION_REGEX) || !defined(CNO_SETTING_REGEX_NMATCH)) // Conversion regex: /{":([^:]*):([^:]*):([^:=]*)(=([A-Za-z]))?:([0NIRBWAUFD][!?]?)(=([^;]*))?;","(.*)"},/{CNO_Setting_Type_,"\1","\2",'\5',"\3",'\6',NULL,"\9",NULL,0,0,0,"\8"},/ // /^{":([0-9A-Za-z ]*)?:([0-9a-z_]*)?:(([-a-z]+)(=([0-9A-Za-z]))?)?:(([0-9A-Z])(([!?])(=(([0-9A-Za-z._\/-]+[!?]?)|\|)*)?)?);", ?"((\w*):)?(.*)"},?/{"\1","\2",'\6',"\4",CNO_Value_\8...,"\15","\16",NULL,0,NULL,NULL,"\9"},/ typedef enum CNO_Value_Type_enum{ CNO_Value_Flag='0', CNO_Value_Natural='N', CNO_Value_Integer='I', CNO_Value_Real='R', CNO_Value_Boolean='B', CNO_Value_Word='W', //[A-Za-z0-9_] CNO_Value_ASCII='A', CNO_Value_UTF8='U', CNO_Value_File='F', //file/directory/url CNO_Value_Discrete='D' } CNO_Value_Type\ty; typedef struct CNO_Settings_struct{ } CNO_Settings_type; //system defaults => user config => options => -C if specified /* */ CS\Byte\ty dialogs; /* */ CS\Byte\ty environment; /* input */ CS\Word\ty keyboard_mode; //scancode, keycode, text /* input */ CS\Word\ty text_mode; //software, hardware /* input */ CS\Byte\ty mouse_relative_motion; /* input */ CS\Byte\ty mouse_buttons; /* input */ CS\Byte\ty mouse_wheel; /* input */ CS\Word\ty controller_engine; //none, sdl-joystick, sdl-controller, xinput, libusb, libgamepad /* input */ CS\Byte\ty joystick_buttons; /* input */ CS\Byte\ty joystick_axis; /* input */ CS\Byte\ty joystick_hat; /* input */ CS\Byte\ty joystick_ball; /* input */ CS\Byte\ty joystick_axis_deadzone; /* input */ CS\Byte\ty joystick_axis_peak; /* input */ CS\Word\ty touch_mode; //mouse, touch /* */ CS\Byte\ty net; /* sdl2 */ CS\Byte\ty sdl2_enabled; /* sdl2 */ CS\Byte\ty sdl2_ttf_enabled; /* sdl2 */ CS\Byte\ty sdl2_gfx_enabled; /* sdl2 */ CS\Byte\ty sdl2_net_enabled; /* sdl2 image */ CS\Byte\ty enabled; /* sdl2 image */ CS\Byte\ty jpg; /* sdl2 image */ CS\Byte\ty png; /* sdl2 image */ CS\Byte\ty tif; /* sdl2 mixer */ CS\Byte\ty enabled; /* sdl2 mixer */ CS\Byte\ty flac; /* sdl2 mixer */ CS\Byte\ty mod; /* sdl2 mixer */ CS\Byte\ty mp3; /* sdl2 mixer */ CS\Byte\ty ogg; /* threads */ CS\Byte\ty enabled; /* threads */ CS\Byte\ty max_threads; /* threads */ CS\Byte\ty logic; /* threads */ CS\Byte\ty fileio; /* threads */ CS\Byte\ty network; /* video */ CS\Byte\ty enabled; /* video */ CS\Byte\ty save_screenshot_bmp; /* video */ CS\Byte\ty save_screenshot_png; /* video */ CS\Byte\ty driver; /* video */ CS\Byte\ty display; /* video */ CS\Byte\ty displaymode; /* video */ CS\Integer\ty x_offset; /* video */ CS\Integer\ty y_offset; /* video */ CS\Byte\ty width; /* video */ CS\Byte\ty height; /* video */ CS\Byte\ty bits_per_pixel; /* video */ CS\Byte\ty exclusive_fullscreen; /* video */ CS\Byte\ty framerate; /* video */ CS\Byte\ty resizable; /* video */ CS\Byte\ty borderless; /* video */ CS\Byte\ty disable_screensaver; /* video */ CS\Byte\ty software_bitmaps; //{":video:software_effects::B!=true|false!;","Boolean: Render graphical effects on the CPU (software style) as opposed to the, default, GPU (hardware-accelerated rendering)."}, /* video */ CS\Byte\ty software_render; /* directories */ CS\Byte\ty portable; /* directories */ CS\String\ty engine_data; /* directories */ CS\String\ty user_data; */ cno_u8_type CNO_Settings_Init(CNO_Setting_type *settings); cno_u8_type CNO_Settings_Default(CNO_Settings_type *settings); cno_u8_type CNO_Settings_GetOpt(CNO_Settings_type *settings, int argc, char *argv[]); cno_u8_type CNO_Settings_Save(CNO_Settings_type *settings, cno_cstring_type filename); cno_u8_type CNO_Settings_Load(CNO_Settings_type *settings, cno_cstring_type filename); cno_u8_type CNO_Settings_Quit(CNO_Setting_type *settings); #ifdef __cplusplus } #endif //__cplusplus #endif //CNO_SETTINGS_H
41.913462
221
0.67722
[ "render" ]
9ce37ae8e5af9f7f56e966d36367c3aea0b5b2e6
105,419
c
C
codegen/mex/epu_n_unit_accumulator/epu_n_unit_accumulator.c
bramzandbelt/epu
1179d338f96ef286bb91550825a08afac28d44d1
[ "MIT" ]
null
null
null
codegen/mex/epu_n_unit_accumulator/epu_n_unit_accumulator.c
bramzandbelt/epu
1179d338f96ef286bb91550825a08afac28d44d1
[ "MIT" ]
null
null
null
codegen/mex/epu_n_unit_accumulator/epu_n_unit_accumulator.c
bramzandbelt/epu
1179d338f96ef286bb91550825a08afac28d44d1
[ "MIT" ]
null
null
null
/* * epu_n_unit_accumulator.c * * Code generation for function 'epu_n_unit_accumulator' * * C source code generated on: Fri Aug 31 09:23:48 2012 * */ /* Include files */ #include "rt_nonfinite.h" #include "epu_n_unit_accumulator.h" #include "randn.h" #include "epu_n_unit_accumulator_emxutil.h" #include "interp1.h" #include "colon.h" #include "rdivide.h" #include "interp1q.h" #include "all.h" #include "mrdivide.h" #include "sum.h" #include "sqrt.h" #include "mean.h" #include "epu_n_unit_accumulator_mexutil.h" /* Type Definitions */ /* Named Constants */ /* Variable Declarations */ /* Variable Definitions */ static emlrtRSInfo emlrtRSI = { 150, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo b_emlrtRSI = { 159, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo c_emlrtRSI = { 162, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo d_emlrtRSI = { 165, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo e_emlrtRSI = { 168, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo f_emlrtRSI = { 170, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo g_emlrtRSI = { 174, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo h_emlrtRSI = { 174, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo i_emlrtRSI = { 174, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo j_emlrtRSI = { 181, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo k_emlrtRSI = { 204, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo l_emlrtRSI = { 208, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo m_emlrtRSI = { 211, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo n_emlrtRSI = { 214, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo o_emlrtRSI = { 217, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo p_emlrtRSI = { 224, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo q_emlrtRSI = { 253, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo r_emlrtRSI = { 254, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRSInfo gb_emlrtRSI = { 55, "mtimes", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/mtimes.m" }; static emlrtRSInfo hb_emlrtRSI = { 21, "mtimes", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/mtimes.m" }; static emlrtRSInfo ib_emlrtRSI = { 84, "mtimes", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/mtimes.m" }; static emlrtRSInfo jb_emlrtRSI = { 89, "mtimes", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/mtimes.m" }; static emlrtRSInfo kb_emlrtRSI = { 54, "eml_xgemm", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/blas/eml_xgemm.m" }; static emlrtRSInfo mb_emlrtRSI = { 32, "eml_blas_xgemm", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/blas/external/eml_blas_xgemm.m" }; static emlrtRSInfo nb_emlrtRSI = { 103, "eml_blas_xgemm", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/blas/external/eml_blas_xgemm.m" }; static emlrtRSInfo qb_emlrtRSI = { 11, "eml_li_find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_li_find.m" }; static emlrtRSInfo rb_emlrtRSI = { 14, "eml_li_find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_li_find.m" }; static emlrtRSInfo vb_emlrtRSI = { 16, "min", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/datafun/min.m" }; static emlrtRSInfo wb_emlrtRSI = { 18, "eml_min_or_max", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_min_or_max.m" }; static emlrtRSInfo xb_emlrtRSI = { 38, "eml_min_or_max", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_min_or_max.m" }; static emlrtRSInfo yb_emlrtRSI = { 73, "eml_min_or_max", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_min_or_max.m" }; static emlrtRSInfo ac_emlrtRSI = { 88, "eml_min_or_max", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_min_or_max.m" }; static emlrtRSInfo bc_emlrtRSI = { 41, "find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/elmat/find.m" }; static emlrtRSInfo dc_emlrtRSI = { 239, "find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/elmat/find.m" }; static emlrtRSInfo nc_emlrtRSI = { 79, "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m" }; static emlrtRSInfo oc_emlrtRSI = { 117, "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m" }; static emlrtRSInfo pc_emlrtRSI = { 233, "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m" }; static emlrtRSInfo qc_emlrtRSI = { 21, "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m" }; static emlrtRSInfo rc_emlrtRSI = { 79, "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m" }; static emlrtRSInfo sc_emlrtRSI = { 117, "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m" }; static emlrtRSInfo tc_emlrtRSI = { 32, "interp1", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/polyfun/interp1.m" }; static emlrtMCInfo e_emlrtMCI = { 85, 13, "mtimes", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/mtimes.m" }; static emlrtMCInfo f_emlrtMCI = { 84, 23, "mtimes", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/mtimes.m" }; static emlrtMCInfo g_emlrtMCI = { 90, 13, "mtimes", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/mtimes.m" }; static emlrtMCInfo h_emlrtMCI = { 89, 23, "mtimes", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/mtimes.m" }; static emlrtMCInfo k_emlrtMCI = { 14, 5, "eml_li_find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_li_find.m" }; static emlrtMCInfo p_emlrtMCI = { 41, 9, "eml_min_or_max", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_min_or_max.m" }; static emlrtMCInfo q_emlrtMCI = { 38, 19, "eml_min_or_max", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_min_or_max.m" }; static emlrtMCInfo r_emlrtMCI = { 74, 9, "eml_min_or_max", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_min_or_max.m" }; static emlrtMCInfo s_emlrtMCI = { 73, 19, "eml_min_or_max", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_min_or_max.m" }; static emlrtMCInfo u_emlrtMCI = { 239, 9, "find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/elmat/find.m" }; static emlrtMCInfo ab_emlrtMCI = { 234, 5, "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m" }; static emlrtMCInfo bb_emlrtMCI = { 233, 15, "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m" }; static emlrtRTEInfo emlrtRTEI = { 1, 28, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRTEInfo b_emlrtRTEI = { 118, 1, "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m" }; static emlrtRTEInfo c_emlrtRTEI = { 46, 1, "mtimes", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/mtimes.m" }; static emlrtRTEInfo d_emlrtRTEI = { 118, 1, "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m" }; static emlrtRTEInfo e_emlrtRTEI = { 111, 5, "find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/elmat/find.m" }; static emlrtRTEInfo f_emlrtRTEI = { 173, 10, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRTEInfo g_emlrtRTEI = { 174, 10, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRTEInfo h_emlrtRTEI = { 203, 4, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtRTEInfo i_emlrtRTEI = { 33, 6, "find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/elmat/find.m" }; static emlrtRTEInfo k_emlrtRTEI = { 17, 9, "eml_li_find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_li_find.m" }; static emlrtDCInfo emlrtDCI = { 143, 21, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 4 }; static emlrtDCInfo b_emlrtDCI = { 143, 48, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 4 }; static emlrtECInfo emlrtECI = { 2, 143, 14, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtECInfo b_emlrtECI = { 2, 159, 12, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtBCInfo emlrtBCI = { -1, -1, 162, 38, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtBCInfo b_emlrtBCI = { -1, -1, 162, 75, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtECInfo c_emlrtECI = { 2, 162, 61, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtECInfo d_emlrtECI = { 2, 162, 59, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtECInfo e_emlrtECI = { 2, 162, 27, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtECInfo f_emlrtECI = { 2, 162, 27, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtBCInfo c_emlrtBCI = { -1, -1, 162, 18, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtECInfo g_emlrtECI = { -1, 162, 7, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtBCInfo d_emlrtBCI = { -1, -1, 165, 18, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtBCInfo e_emlrtBCI = { -1, -1, 165, 34, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtBCInfo f_emlrtBCI = { -1, -1, 168, 29, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtECInfo h_emlrtECI = { 2, 168, 18, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtBCInfo g_emlrtBCI = { -1, -1, 173, 32, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtECInfo i_emlrtECI = { 2, 173, 21, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtBCInfo h_emlrtBCI = { -1, -1, 174, 38, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtECInfo j_emlrtECI = { 2, 174, 27, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtBCInfo i_emlrtBCI = { -1, -1, 174, 71, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtECInfo k_emlrtECI = { 2, 174, 60, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtBCInfo j_emlrtBCI = { -1, -1, 175, 22, "iCritical", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtBCInfo k_emlrtBCI = { -1, -1, 177, 48, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtBCInfo l_emlrtBCI = { -1, -1, 179, 22, "theta", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtECInfo l_emlrtECI = { 2, 208, 12, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtBCInfo m_emlrtBCI = { -1, -1, 211, 38, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtBCInfo n_emlrtBCI = { -1, -1, 211, 75, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtECInfo m_emlrtECI = { 2, 211, 61, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtECInfo n_emlrtECI = { 2, 211, 59, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtECInfo o_emlrtECI = { 2, 211, 27, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtECInfo p_emlrtECI = { 2, 211, 27, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtBCInfo o_emlrtBCI = { -1, -1, 211, 18, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtECInfo q_emlrtECI = { -1, 211, 7, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtBCInfo p_emlrtBCI = { -1, -1, 214, 18, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtBCInfo q_emlrtBCI = { -1, -1, 214, 34, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtBCInfo r_emlrtBCI = { -1, -1, 217, 42, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtECInfo r_emlrtECI = { -1, 221, 27, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m" }; static emlrtBCInfo s_emlrtBCI = { -1, -1, 105, 24, "", "eml_blas_xgemm", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/blas/external/eml_blas_xgemm.m", 0 }; static emlrtBCInfo t_emlrtBCI = { -1, -1, 106, 5, "", "eml_blas_xgemm", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/blas/external/eml_blas_xgemm.m", 0 }; static emlrtBCInfo u_emlrtBCI = { -1, -1, 107, 23, "", "eml_blas_xgemm", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/blas/external/eml_blas_xgemm.m", 0 }; static emlrtBCInfo v_emlrtBCI = { -1, -1, 105, 24, "", "eml_blas_xgemm", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/blas/external/eml_blas_xgemm.m", 0 }; static emlrtBCInfo w_emlrtBCI = { -1, -1, 106, 5, "", "eml_blas_xgemm", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/blas/external/eml_blas_xgemm.m", 0 }; static emlrtBCInfo x_emlrtBCI = { -1, -1, 107, 23, "", "eml_blas_xgemm", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/blas/external/eml_blas_xgemm.m", 0 }; static emlrtBCInfo y_emlrtBCI = { -1, -1, 178, 12, "", "eml_min_or_max", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_min_or_max.m", 0 }; static emlrtBCInfo ab_emlrtBCI = { -1, -1, 198, 27, "", "eml_min_or_max", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_min_or_max.m", 0 }; static emlrtBCInfo bb_emlrtBCI = { -1, -1, 218, 32, "", "eml_min_or_max", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_min_or_max.m", 0 }; static emlrtBCInfo cb_emlrtBCI = { -1, -1, 249, 17, "", "find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/elmat/find.m", 0 }; static emlrtBCInfo db_emlrtBCI = { -1, -1, 249, 17, "", "find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/elmat/find.m", 0 }; static emlrtDCInfo c_emlrtDCI = { 118, 28, "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m", 4 }; static emlrtBCInfo eb_emlrtBCI = { -1, -1, 120, 5, "", "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m", 0 }; static emlrtDCInfo d_emlrtDCI = { 118, 28, "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m", 4 }; static emlrtBCInfo fb_emlrtBCI = { -1, -1, 120, 5, "", "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m", 0 }; static emlrtDCInfo e_emlrtDCI = { 203, 24, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 1 }; static emlrtDCInfo f_emlrtDCI = { 203, 24, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 4 }; static emlrtDCInfo g_emlrtDCI = { 203, 24, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 1 }; static emlrtDCInfo h_emlrtDCI = { 203, 24, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 4 }; static emlrtBCInfo gb_emlrtBCI = { -1, -1, 214, 23, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtBCInfo hb_emlrtBCI = { -1, -1, 217, 7, "mActivation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtBCInfo ib_emlrtBCI = { -1, -1, 219, 27, "mActivation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtBCInfo jb_emlrtBCI = { -1, -1, 221, 27, "mActivation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtBCInfo kb_emlrtBCI = { -1, -1, 240, 36, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtDCInfo i_emlrtDCI = { 240, 36, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 1 }; static emlrtBCInfo lb_emlrtBCI = { -1, -1, 230, 36, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtDCInfo j_emlrtDCI = { 230, 36, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 1 }; static emlrtBCInfo mb_emlrtBCI = { -1, -1, 165, 23, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtBCInfo nb_emlrtBCI = { -1, -1, 174, 75, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtBCInfo ob_emlrtBCI = { -1, -1, 174, 85, "theta", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtBCInfo pb_emlrtBCI = { -1, -1, 199, 32, "", "eml_min_or_max", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_min_or_max.m", 0 }; static emlrtBCInfo qb_emlrtBCI = { -1, -1, 231, 33, "", "find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/elmat/find.m", 0 }; static emlrtBCInfo rb_emlrtBCI = { -1, -1, 233, 17, "", "find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/elmat/find.m", 0 }; static emlrtBCInfo sb_emlrtBCI = { -1, -1, 177, 38, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtBCInfo tb_emlrtBCI = { -1, -1, 195, 36, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtDCInfo k_emlrtDCI = { 195, 36, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 1 }; static emlrtBCInfo ub_emlrtBCI = { -1, -1, 188, 39, "activation", "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 0 }; static emlrtDCInfo l_emlrtDCI = { 188, 39, "epu_n_unit_accumulator", "/Users/bram/Documents/EPU/Simulation_2012Aug28/m-files/epu_n_unit_accumulator.m", 1 }; static emlrtBCInfo vb_emlrtBCI = { -1, -1, 122, 9, "", "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m", 0 }; static emlrtBCInfo wb_emlrtBCI = { -1, -1, 134, 13, "", "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m", 0 }; static emlrtBCInfo xb_emlrtBCI = { -1, -1, 135, 13, "", "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m", 0 }; static emlrtBCInfo yb_emlrtBCI = { -1, -1, 131, 13, "", "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m", 0 }; static emlrtBCInfo ac_emlrtBCI = { -1, -1, 122, 9, "", "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m", 0 }; static emlrtBCInfo bc_emlrtBCI = { -1, -1, 134, 13, "", "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m", 0 }; static emlrtBCInfo cc_emlrtBCI = { -1, -1, 135, 13, "", "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m", 0 }; static emlrtBCInfo dc_emlrtBCI = { -1, -1, 131, 13, "", "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m", 0 }; static emlrtBCInfo ec_emlrtBCI = { -1, -1, 127, 13, "", "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m", 0 }; static emlrtBCInfo fc_emlrtBCI = { -1, -1, 128, 13, "", "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m", 0 }; static emlrtBCInfo gc_emlrtBCI = { -1, -1, 127, 13, "", "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m", 0 }; static emlrtBCInfo hc_emlrtBCI = { -1, -1, 128, 13, "", "colon", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/ops/colon.m", 0 }; static emlrtBCInfo ic_emlrtBCI = { -1, -1, 219, 28, "", "eml_min_or_max", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_min_or_max.m", 0 }; static emlrtDCInfo o_emlrtDCI = { 17, 37, "eml_li_find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_li_find.m", 4 }; static emlrtBCInfo mc_emlrtBCI = { -1, -1, 27, 12, "", "eml_li_find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_li_find.m", 0 }; static emlrtBCInfo nc_emlrtBCI = { -1, -1, 28, 13, "", "eml_li_find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_li_find.m", 0 }; static emlrtBCInfo oc_emlrtBCI = { -1, -1, 40, 12, "", "eml_li_find", "/Applications/MATLAB_R2011b.app/toolbox/eml/lib/matlab/eml/eml_li_find.m", 0 }; /* Function Declarations */ static void eml_li_find(const emxArray_boolean_T *x, emxArray_int32_T *y); /* Function Definitions */ /* * */ static void eml_li_find(const emxArray_boolean_T *x, emxArray_int32_T *y) { int32_T n; int32_T k; int32_T i; const mxArray *b_y; const mxArray *m3; int32_T j; n = x->size[1]; EMLRTPUSHRTSTACK(&qb_emlrtRSI); k = 0; for (i = 1; i <= n; i++) { if (x->data[emlrtDynamicBoundsCheck(i, 1, x->size[1], &oc_emlrtBCI) - 1]) { k++; } } EMLRTPOPRTSTACK(&qb_emlrtRSI); if (k <= n) { } else { EMLRTPUSHRTSTACK(&rb_emlrtRSI); b_y = NULL; m3 = mxCreateString("Assertion failed."); emlrtAssign(&b_y, m3); error(b_y, &k_emlrtMCI); EMLRTPOPRTSTACK(&rb_emlrtRSI); } emlrtNonNegativeCheckR2009b((real_T)k, &o_emlrtDCI); j = y->size[0] * y->size[1]; y->size[0] = 1; y->size[1] = k; emxEnsureCapacity((emxArray__common *)y, j, (int32_T)sizeof(int32_T), &k_emlrtRTEI); j = 1; for (i = 1; i <= n; i++) { if (x->data[emlrtDynamicBoundsCheck(i, 1, x->size[1], &mc_emlrtBCI) - 1]) { y->data[emlrtDynamicBoundsCheck(j, 1, y->size[1], &nc_emlrtBCI) - 1] = i; j++; } } } /* * function [rt,activation] = epu_n_unit_accumulator(nTP,v,dt,sigmaXi,SigmaXi,theta,k,affTime,effTime,pN,dMeth,iAT) */ void epu_n_unit_accumulator(epu_n_unit_accumulatorStackData *SD, real_T nTP, const emxArray_real_T *v, real_T dt, real_T sigmaXi, const emxArray_real_T *SigmaXi, const emxArray_real_T *theta, const emxArray_real_T *k, real_T affTime, real_T effTime, emxArray_real_T *pN, real_T dMeth, const emxArray_real_T *iAT, real_T *rt, emxArray_real_T *activation) { real_T prop; real_T x; int32_T nm1d2; int32_T ixstart; int32_T i0; int32_T loop_ub; int32_T idx; emxArray_boolean_T *b_pN; real_T iTP; boolean_T innerDimOk; emxArray_real_T *iCritical; emxArray_real_T *C; emxArray_real_T *r0; emxArray_int32_T *r1; emxArray_int32_T *ii; emxArray_boolean_T *iCrossed; emxArray_boolean_T *b_prop; emxArray_boolean_T *b_activation; emxArray_boolean_T *c_activation; emxArray_int32_T *r2; emxArray_real_T *r3; emxArray_real_T *r4; emxArray_int32_T *r5; emxArray_int32_T *r6; emxArray_real_T *d_activation; emxArray_real_T *e_activation; emxArray_real_T *f_activation; emxArray_real_T *g_activation; emxArray_real_T *h_activation; emxArray_real_T *i_activation; emxArray_real_T *j_activation; emxArray_real_T *k_activation; emxArray_int32_T *b_ii; emxArray_real_T *l_activation; emxArray_real_T *m_activation; boolean_T exitg2; const mxArray *y; static const int32_T iv0[2] = { 1, 45 }; const mxArray *m0; static const char_T cv0[45] = { 'C', 'o', 'd', 'e', 'r', ':', 't', 'o', 'o', 'l', 'b', 'o', 'x', ':', 'm', 't', 'i', 'm', 'e', 's', '_', 'n', 'o', 'D', 'y', 'n', 'a', 'm', 'i', 'c', 'S', 'c', 'a', 'l', 'a', 'r', 'E', 'x', 'p', 'a', 'n', 's', 'i', 'o', 'n' }; const mxArray *b_y; static const int32_T iv1[2] = { 1, 21 }; static const char_T cv1[21] = { 'C', 'o', 'd', 'e', 'r', ':', 'M', 'A', 'T', 'L', 'A', 'B', ':', 'i', 'n', 'n', 'e', 'r', 'd', 'i', 'm' }; int32_T b_k; uint32_T unnamed_idx_1; int32_T n; char_T TRANSA; char_T TRANSB; int32_T b_C[2]; int32_T iv2[2]; int32_T n_activation[2]; const mxArray *c_y; static const int32_T iv3[2] = { 1, 36 }; static const char_T cv2[36] = { 'C', 'o', 'd', 'e', 'r', ':', 't', 'o', 'o', 'l', 'b', 'o', 'x', ':', 'a', 'u', 't', 'o', 'D', 'i', 'm', 'I', 'n', 'c', 'o', 'm', 'p', 'a', 't', 'i', 'b', 'i', 'l', 'i', 't', 'y' }; const mxArray *d_y; static const int32_T iv4[2] = { 1, 39 }; static const char_T cv3[39] = { 'C', 'o', 'd', 'e', 'r', ':', 't', 'o', 'o', 'l', 'b', 'o', 'x', ':', 'e', 'm', 'l', '_', 'm', 'i', 'n', '_', 'o', 'r', '_', 'm', 'a', 'x', '_', 'v', 'a', 'r', 'D', 'i', 'm', 'Z', 'e', 'r', 'o' }; boolean_T exitg4; boolean_T exitg3; boolean_T guard1 = FALSE; const mxArray *e_y; int32_T iv5[2]; emxArray_int32_T r7; real_T mActivation[2]; real_T b_dt[2]; emxArray_real_T *b_mActivation; real_T mThreshold; emxArray_real_T *o_activation; emxArray_boolean_T *p_activation; emxArray_int32_T *r8; emxArray_real_T *r9; emxArray_real_T *r10; emxArray_real_T *q_activation; emxArray_real_T *r_activation; emxArray_real_T *s_activation; emxArray_real_T *t_activation; emxArray_real_T *u_activation; emxArray_real_T *v_activation; emxArray_real_T *w_activation; boolean_T exitg1; const mxArray *f_y; static const int32_T iv6[2] = { 1, 45 }; const mxArray *g_y; static const int32_T iv7[2] = { 1, 21 }; const mxArray *h_y; static const int32_T iv8[2] = { 1, 21 }; static const char_T cv4[21] = { 'C', 'o', 'd', 'e', 'r', ':', 'M', 'A', 'T', 'L', 'A', 'B', ':', 'p', 'm', 'a', 'x', 's', 'i', 'z', 'e' }; const mxArray *i_y; static const int32_T iv9[2] = { 1, 21 }; emxArray_real_T *x_activation; emlrtHeapReferenceStackEnterFcn(); /* % N-UNIT REDUNDANT ACCUMULATOR MODEL WITHOUT LATERAL INHIBITION */ /* INPUTS */ /* nTP - number of time points (TP) for which to log data (in ms from */ /* target onset) */ /* v - vector with accumulation rates across accumulators */ /* * units: spikes s-1 ms-1 */ /* * size & class: 1xnA double, where nA is number of */ /* accumulators */ /* * support: v ? ?: (0,+?) */ /* dt - time step size of stochastic differential equation */ /* * units: ms */ /* * size & class: 1x1 double */ /* * support: dt ? ?: [0,+?) */ /* sigmaXi - scale parameter of the Gaussian noise distribution */ /* * units: spikes s-1 */ /* * size & class: 1x1 double */ /* * support: sigmaXi ? ?: (0,+?) */ /* SigmaXi - Cholesky-like decomposed covariance matrix */ /* * units: ? */ /* * size & class: nAxnA double */ /* * support: SigmaXi */ /* theta - vector with thresholds across accumulators */ /* * units: spikes s-1 */ /* * size & class: 1xnA double, where nA is number of */ /* accumulators */ /* * support: theta ? ?: (0,+?) */ /* k - vector with leakage parameters */ /* * units: */ /* * size & class: 1xnA double, where nA is number of */ /* accumulators */ /* * support: k ? ?: (0,+?) */ /* affTime - afferent (encoding) time */ /* * units: ms */ /* * size & class: 1x1 double */ /* * support: affTime ? ?: [0,+?) */ /* effTime - efferent (response execution) time */ /* * units: ms */ /* * size & class: 1x1 double */ /* * support: effTime ? ?: [0,+?) */ /* pN - proportion of accumulators necessary to produce an RT ('RT */ /* rule'). */ /* * units: unitless */ /* * size & class: 1x1 double */ /* * support: pN ? ?: [0,1], where 0 means that the very */ /* first accumulator reaching threshold produces RT */ /* dMeth - decision method, polling or pooling */ /* * units: unitless */ /* * size & class: 1x1 double */ /* * support: * 1 polling */ /* * 2 pooling */ /* iAT - accumulators indices for which to provide accumulation */ /* trajectories */ /* * units: unitless */ /* * size & class: 1xN double, where N is the number of indices */ /* to get and N <= nA, where nA is number of accumulators */ /* * support: iAT ? ?: [1,nA] */ /* */ /* */ /* EXAMPLE USAGE: */ /* nTP = 1500; */ /* v = 1+randn(1,10); */ /* sigmaXi = .2; */ /* rXi = .5; */ /* theta = 100.*ones(1,10); */ /* k = zeros(1,10); */ /* affTime = 100; */ /* effTime = 10; */ /* pN = 0; */ /* dMeth = 1; */ /* iAT = [1,3,5]; */ /* */ /* [rt,activation] = ... */ /* epu_n_unit_accumulator(nTP,v,sigmaXi,SigmaXi,theta,k,affTime,effTime,pN,dMeth,iAT); */ /* */ /* */ /* */ /* THESE EXAMPLES NEED TO BE UPDATED AND ADJUSTED! */ /* */ /* */ /* % Example 1: Perfect integration of evidence, polling-based RT generation, very */ /* % first accumulator reaching threshold determines RT */ /* */ /* muRate = 1+randn(1,10); */ /* wnF = 0; */ /* nTP = 1500; */ /* k = zeros(1,10); */ /* theta = 100 .* ones(1,10); */ /* t0 = 100; */ /* dMeth = 1; */ /* q = 0; */ /* iAT = [1 3 4]; */ /* */ /* [rt,activation] = ... */ /* epu_n_unit_accumulator(muRate,wnF,nTP,k,theta,t0,dMeth,q,iAT); */ /* */ /* % Example 2: Leaky integration of evidence, polling-based RT generation, median */ /* % accumulator reaching threshold determines RT */ /* */ /* muRate = 1+randn(1,10); */ /* wnF = 1; */ /* nTP = 1500 */ /* theta = 100 .* ones(1,10); */ /* k = 0.5.*muRate./theta; */ /* t0 = 100; */ /* dMeth = 1; */ /* q = 0.5; */ /* iAT = [1 3 4]; */ /* */ /* [rt,activation] = ... */ /* epu_n_unit_accumulator(muRate,wnF,nTP,k,theta,t0,dMeth,q,iAT); */ /* */ /* % Example 3: Leaky integration of evidence, pooling-based RT generation */ /* */ /* muRate = 1+randn(1,10); */ /* wnF = 1; */ /* nTP = 1500; */ /* theta = 100 .* ones(1,10); */ /* k = 0.5.*muRate./theta; */ /* t0 = 100; */ /* dMeth = 2; */ /* q = 0.5; */ /* iAT = 10; */ /* */ /* [rt,activation] = ... */ /* epu_n_unit_accumulator(muRate,wnF,nTP,k,theta,t0,dMeth,q,iAT); */ /* */ /* Bram Zandbelt, April 2012 */ /* % */ /* % 1. Parameter settings & array pre-allocation */ /* warning off */ /* Constants */ /* 'epu_n_unit_accumulator:137' TAU = 1; */ /* Time scale (in ms), see Usher & McClelland 2001, p. 558 */ /* User-defined parameters */ /* 'epu_n_unit_accumulator:140' nA = size(v,2); */ /* Number of accumulator units */ /* Arrays for logging data */ /* 'epu_n_unit_accumulator:143' activation = [zeros(floor(affTime./dt),nA);nan(ceil((nTP-affTime)./dt),nA)]; */ prop = muDoubleScalarFloor(rdivide(affTime, dt)); emlrtNonNegativeCheckR2009b(prop, &emlrtDCI); x = muDoubleScalarCeil(rdivide(nTP - affTime, dt)); emlrtNonNegativeCheckR2009b(x, &b_emlrtDCI); nm1d2 = v->size[1]; ixstart = v->size[1]; emlrtDimSizeEqCheck(nm1d2, ixstart, &emlrtECI); nm1d2 = v->size[1]; ixstart = v->size[1]; i0 = activation->size[0] * activation->size[1]; activation->size[0] = (int32_T)prop + (int32_T)x; activation->size[1] = nm1d2; emxEnsureCapacity((emxArray__common *)activation, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = nm1d2 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { idx = (int32_T)prop - 1; for (nm1d2 = 0; nm1d2 <= idx; nm1d2++) { activation->data[nm1d2 + activation->size[0] * i0] = 0.0; } } loop_ub = ixstart - 1; for (i0 = 0; i0 <= loop_ub; i0++) { idx = (int32_T)x - 1; for (nm1d2 = 0; nm1d2 <= idx; nm1d2++) { activation->data[(nm1d2 + (int32_T)prop) + activation->size[0] * i0] = rtNaN; } } emxInit_boolean_T(&b_pN, 2, &emlrtRTEI, TRUE); /* Activation */ /* 'epu_n_unit_accumulator:144' rt = Inf; */ *rt = rtInf; /* % 2. Accumulator trajectories */ /* iTP = affTime+1; % Before affTime, activation is zero */ /* 'epu_n_unit_accumulator:148' iTP = floor(affTime./dt)+1; */ iTP = muDoubleScalarFloor(rdivide(affTime, dt)) + 1.0; /* Before affTime, activation is zero */ /* 'epu_n_unit_accumulator:150' if all(pN == 0) */ EMLRTPUSHRTSTACK(&emlrtRSI); i0 = b_pN->size[0] * b_pN->size[1]; b_pN->size[0] = 1; b_pN->size[1] = pN->size[1]; emxEnsureCapacity((emxArray__common *)b_pN, i0, (int32_T)sizeof(boolean_T), &emlrtRTEI); loop_ub = pN->size[0] * pN->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { b_pN->data[i0] = (pN->data[i0] == 0.0); } innerDimOk = all(b_pN); EMLRTPOPRTSTACK(&emlrtRSI); emxFree_boolean_T(&b_pN); if (innerDimOk) { /* 'epu_n_unit_accumulator:151' pN = realmin; */ i0 = pN->size[0] * pN->size[1]; pN->size[0] = 1; pN->size[1] = 1; emxEnsureCapacity((emxArray__common *)pN, i0, (int32_T)sizeof(real_T), &emlrtRTEI); pN->data[0] = 2.2250738585072014E-308; /* This ensures that very first accumulator determines RT */ } /* 'epu_n_unit_accumulator:154' if dMeth == 1 */ emxInit_real_T(&iCritical, 2, &g_emlrtRTEI, TRUE); emxInit_real_T(&C, 2, &emlrtRTEI, TRUE); emxInit_real_T(&r0, 2, &emlrtRTEI, TRUE); emxInit_int32_T(&r1, 1, &emlrtRTEI, TRUE); b_emxInit_int32_T(&ii, 2, &i_emlrtRTEI, TRUE); if (dMeth == 1.0) { /* Polling */ /* 'epu_n_unit_accumulator:156' while iTP < Inf */ emxInit_boolean_T(&iCrossed, 2, &f_emlrtRTEI, TRUE); emxInit_boolean_T(&b_prop, 2, &emlrtRTEI, TRUE); emxInit_boolean_T(&b_activation, 2, &emlrtRTEI, TRUE); emxInit_boolean_T(&c_activation, 2, &emlrtRTEI, TRUE); b_emxInit_int32_T(&r2, 2, &emlrtRTEI, TRUE); emxInit_real_T(&r3, 2, &emlrtRTEI, TRUE); emxInit_real_T(&r4, 2, &emlrtRTEI, TRUE); b_emxInit_int32_T(&r5, 2, &emlrtRTEI, TRUE); emxInit_int32_T(&r6, 1, &emlrtRTEI, TRUE); emxInit_real_T(&d_activation, 2, &emlrtRTEI, TRUE); emxInit_real_T(&e_activation, 2, &emlrtRTEI, TRUE); emxInit_real_T(&f_activation, 2, &emlrtRTEI, TRUE); emxInit_real_T(&g_activation, 2, &emlrtRTEI, TRUE); emxInit_real_T(&h_activation, 2, &emlrtRTEI, TRUE); emxInit_real_T(&i_activation, 2, &emlrtRTEI, TRUE); emxInit_real_T(&j_activation, 2, &emlrtRTEI, TRUE); emxInit_real_T(&k_activation, 2, &emlrtRTEI, TRUE); b_emxInit_int32_T(&b_ii, 2, &emlrtRTEI, TRUE); emxInit_real_T(&l_activation, 2, &emlrtRTEI, TRUE); emxInit_real_T(&m_activation, 2, &emlrtRTEI, TRUE); exitg2 = 0U; while ((exitg2 == 0U) && (iTP < rtInf)) { /* Generate correlated Gaussian noise */ /* 'epu_n_unit_accumulator:159' Xi = randn(1,size(SigmaXi,1)) * SigmaXi + zeros(1,nA); */ EMLRTPUSHRTSTACK(&b_emlrtRSI); randn(SD, (real_T)SigmaXi->size[0], iCritical); EMLRTPUSHRTSTACK(&hb_emlrtRSI); innerDimOk = (iCritical->size[1] == SigmaXi->size[0]); if (!innerDimOk) { if ((iCritical->size[1] == 1) || ((SigmaXi->size[0] == 1) && (SigmaXi->size[1] == 1))) { EMLRTPUSHRTSTACK(&ib_emlrtRSI); y = NULL; m0 = mxCreateCharArray(2, iv0); emlrtInitCharArray(45, m0, cv0); emlrtAssign(&y, m0); error(message(y, &e_emlrtMCI), &f_emlrtMCI); EMLRTPOPRTSTACK(&ib_emlrtRSI); } else { EMLRTPUSHRTSTACK(&jb_emlrtRSI); b_y = NULL; m0 = mxCreateCharArray(2, iv1); emlrtInitCharArray(21, m0, cv1); emlrtAssign(&b_y, m0); error(message(b_y, &g_emlrtMCI), &h_emlrtMCI); EMLRTPOPRTSTACK(&jb_emlrtRSI); } } EMLRTPOPRTSTACK(&hb_emlrtRSI); if ((iCritical->size[1] == 1) || (SigmaXi->size[0] == 1)) { i0 = C->size[0] * C->size[1]; C->size[0] = 1; C->size[1] = SigmaXi->size[1]; emxEnsureCapacity((emxArray__common *)C, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = SigmaXi->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { C->data[C->size[0] * i0] = 0.0; idx = iCritical->size[1] - 1; for (nm1d2 = 0; nm1d2 <= idx; nm1d2++) { C->data[C->size[0] * i0] += iCritical->data[iCritical->size[0] * nm1d2] * SigmaXi->data[nm1d2 + SigmaXi->size[0] * i0]; } } } else { b_k = iCritical->size[1]; unnamed_idx_1 = (uint32_T)SigmaXi->size[1]; i0 = C->size[0] * C->size[1]; C->size[0] = 1; C->size[1] = (int32_T)unnamed_idx_1; emxEnsureCapacity((emxArray__common *)C, i0, (int32_T)sizeof(real_T), &c_emlrtRTEI); n = SigmaXi->size[1]; i0 = C->size[0] * C->size[1]; C->size[0] = 1; emxEnsureCapacity((emxArray__common *)C, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = C->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { C->data[C->size[0] * i0] = 0.0; } EMLRTPUSHRTSTACK(&gb_emlrtRSI); EMLRTPUSHRTSTACK(&kb_emlrtRSI); if ((n < 1) || (b_k < 1)) { } else { EMLRTPUSHRTSTACK(&mb_emlrtRSI); ixstart = 1; x = 1.0; idx = 1; prop = 0.0; nm1d2 = 1; TRANSA = 'N'; TRANSB = 'N'; EMLRTPUSHRTSTACK(&nb_emlrtRSI); emlrtDynamicBoundsCheck(1, 1, iCritical->size[1], &v_emlrtBCI); emlrtDynamicBoundsCheck(1, 1, SigmaXi->size[0] * SigmaXi->size[1], &w_emlrtBCI); emlrtDynamicBoundsCheck(1, 1, C->size[1], &x_emlrtBCI); dgemm32(&TRANSA, &TRANSB, &ixstart, &n, &b_k, &x, &iCritical->data[0], &idx, &SigmaXi->data[0], &b_k, &prop, &C->data[0], &nm1d2); EMLRTPOPRTSTACK(&nb_emlrtRSI); EMLRTPOPRTSTACK(&mb_emlrtRSI); } EMLRTPOPRTSTACK(&kb_emlrtRSI); EMLRTPOPRTSTACK(&gb_emlrtRSI); } EMLRTPOPRTSTACK(&b_emlrtRSI); for (i0 = 0; i0 < 2; i0++) { b_C[i0] = C->size[i0]; } iv2[0] = 1; iv2[1] = v->size[1]; emlrtSizeEqCheckND(b_C, iv2, &b_emlrtECI); /* Compute activation level */ /* 'epu_n_unit_accumulator:162' activation(iTP,:) = activation(iTP-1,:) + dt./TAU.*(v-k.*activation(iTP-1,:)) + sqrt(dt./TAU).*Xi; */ emlrtDynamicBoundsCheck((int32_T)(iTP - 1.0), 1, activation->size[0], &b_emlrtBCI); for (i0 = 0; i0 < 2; i0++) { b_C[i0] = k->size[i0]; } i0 = activation->size[1]; nm1d2 = d_activation->size[0] * d_activation->size[1]; d_activation->size[0] = 1; d_activation->size[1] = i0; emxEnsureCapacity((emxArray__common *)d_activation, nm1d2, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { d_activation->data[d_activation->size[0] * i0] = activation->data[((int32_T)(iTP - 1.0) + activation->size[0] * i0) - 1]; } for (i0 = 0; i0 < 2; i0++) { n_activation[i0] = d_activation->size[i0]; } emlrtSizeEqCheckND(b_C, n_activation, &c_emlrtECI); i0 = r0->size[0] * r0->size[1]; r0->size[0] = 1; r0->size[1] = k->size[1]; emxEnsureCapacity((emxArray__common *)r0, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = k->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r0->data[r0->size[0] * i0] = k->data[k->size[0] * i0] * activation->data[((int32_T)(iTP - 1.0) + activation->size[0] * i0) - 1]; } for (i0 = 0; i0 < 2; i0++) { b_C[i0] = v->size[i0]; } for (i0 = 0; i0 < 2; i0++) { iv2[i0] = r0->size[i0]; } emlrtSizeEqCheckND(b_C, iv2, &d_emlrtECI); emlrtDynamicBoundsCheck((int32_T)(iTP - 1.0), 1, activation->size[0], &emlrtBCI); i0 = r0->size[0] * r0->size[1]; r0->size[0] = 1; r0->size[1] = v->size[1]; emxEnsureCapacity((emxArray__common *)r0, i0, (int32_T)sizeof(real_T), &emlrtRTEI); x = rdivide(dt, 1.0); loop_ub = v->size[0] * v->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r0->data[i0] = x * (v->data[i0] - r0->data[i0]); } i0 = activation->size[1]; nm1d2 = e_activation->size[0] * e_activation->size[1]; e_activation->size[0] = 1; e_activation->size[1] = i0; emxEnsureCapacity((emxArray__common *)e_activation, nm1d2, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { e_activation->data[e_activation->size[0] * i0] = activation->data[((int32_T)(iTP - 1.0) + activation->size[0] * i0) - 1]; } for (i0 = 0; i0 < 2; i0++) { n_activation[i0] = e_activation->size[i0]; } for (i0 = 0; i0 < 2; i0++) { iv2[i0] = r0->size[i0]; } emlrtSizeEqCheckND(n_activation, iv2, &e_emlrtECI); EMLRTPUSHRTSTACK(&c_emlrtRSI); x = rdivide(dt, 1.0); b_sqrt(&x); i0 = C->size[0] * C->size[1]; C->size[0] = 1; emxEnsureCapacity((emxArray__common *)C, i0, (int32_T)sizeof(real_T), &emlrtRTEI); nm1d2 = C->size[0]; ixstart = C->size[1]; loop_ub = nm1d2 * ixstart - 1; for (i0 = 0; i0 <= loop_ub; i0++) { C->data[i0] *= x; } EMLRTPOPRTSTACK(&c_emlrtRSI); i0 = activation->size[1]; nm1d2 = f_activation->size[0] * f_activation->size[1]; f_activation->size[0] = 1; f_activation->size[1] = i0; emxEnsureCapacity((emxArray__common *)f_activation, nm1d2, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { f_activation->data[f_activation->size[0] * i0] = activation->data[((int32_T)(iTP - 1.0) + activation->size[0] * i0) - 1]; } for (i0 = 0; i0 < 2; i0++) { n_activation[i0] = f_activation->size[i0]; } for (i0 = 0; i0 < 2; i0++) { b_C[i0] = C->size[i0]; } emlrtSizeEqCheckND(n_activation, b_C, &f_emlrtECI); emlrtDynamicBoundsCheck((int32_T)iTP, 1, activation->size[0], &c_emlrtBCI); i0 = activation->size[1]; nm1d2 = r1->size[0]; r1->size[0] = i0; emxEnsureCapacity((emxArray__common *)r1, nm1d2, (int32_T)sizeof(int32_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r1->data[i0] = i0; } iv2[0] = 1; iv2[1] = r1->size[0]; i0 = activation->size[1]; nm1d2 = g_activation->size[0] * g_activation->size[1]; g_activation->size[0] = 1; g_activation->size[1] = i0; emxEnsureCapacity((emxArray__common *)g_activation, nm1d2, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { g_activation->data[g_activation->size[0] * i0] = activation->data[((int32_T)iTP + activation->size[0] * i0) - 2]; } for (i0 = 0; i0 < 2; i0++) { n_activation[i0] = g_activation->size[i0]; } emlrtSubAssignSizeCheck(iv2, 2, n_activation, 2, &g_emlrtECI); ixstart = activation->size[1]; i0 = h_activation->size[0] * h_activation->size[1]; h_activation->size[0] = 1; h_activation->size[1] = ixstart; emxEnsureCapacity((emxArray__common *)h_activation, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = ixstart - 1; for (i0 = 0; i0 <= loop_ub; i0++) { h_activation->data[h_activation->size[0] * i0] = (activation->data[((int32_T)iTP + activation->size[0] * i0) - 2] + r0->data[r0->size[0] * i0]) + C->data[C->size[0] * i0]; } loop_ub = h_activation->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { activation->data[((int32_T)iTP + activation->size[0] * r1->data[i0]) - 1] = h_activation->data[h_activation->size[0] * i0]; } /* Reset activation level if it goes below zero */ /* 'epu_n_unit_accumulator:165' activation(iTP,(activation(iTP,:) < 0)) = 0; */ EMLRTPUSHRTSTACK(&d_emlrtRSI); i0 = activation->size[1]; ixstart = emlrtDynamicBoundsCheck((int32_T)iTP, 1, activation->size[0], &e_emlrtBCI); nm1d2 = c_activation->size[0] * c_activation->size[1]; c_activation->size[0] = 1; c_activation->size[1] = i0; emxEnsureCapacity((emxArray__common *)c_activation, nm1d2, (int32_T)sizeof(boolean_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { c_activation->data[c_activation->size[0] * i0] = (activation->data[(ixstart + activation->size[0] * i0) - 1] < 0.0); } eml_li_find(c_activation, ii); i0 = r2->size[0] * r2->size[1]; r2->size[0] = 1; r2->size[1] = ii->size[1]; emxEnsureCapacity((emxArray__common *)r2, i0, (int32_T)sizeof(int32_T), &emlrtRTEI); loop_ub = ii->size[0] * ii->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r2->data[i0] = emlrtDynamicBoundsCheck(ii->data[i0], 1, activation->size[1], &mb_emlrtBCI); } i0 = r1->size[0]; r1->size[0] = r2->size[1]; emxEnsureCapacity((emxArray__common *)r1, i0, (int32_T)sizeof(int32_T), &emlrtRTEI); loop_ub = r2->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r1->data[i0] = r2->data[i0]; } EMLRTPOPRTSTACK(&d_emlrtRSI); ixstart = activation->size[0]; emlrtDynamicBoundsCheck((int32_T)iTP, 1, ixstart, &d_emlrtBCI); nm1d2 = r1->size[0]; loop_ub = nm1d2 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { activation->data[((int32_T)iTP + activation->size[0] * (r1->data[i0] - 1)) - 1] = 0.0; } /* Proportion of accumulators above threshold */ /* 'epu_n_unit_accumulator:168' prop = sum(activation(iTP,:) > theta)/nA; */ emlrtDynamicBoundsCheck((int32_T)iTP, 1, activation->size[0], &f_emlrtBCI); i0 = activation->size[1]; nm1d2 = i_activation->size[0] * i_activation->size[1]; i_activation->size[0] = 1; i_activation->size[1] = i0; emxEnsureCapacity((emxArray__common *)i_activation, nm1d2, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { i_activation->data[i_activation->size[0] * i0] = activation->data[((int32_T)iTP + activation->size[0] * i0) - 1]; } for (i0 = 0; i0 < 2; i0++) { n_activation[i0] = i_activation->size[i0]; } for (i0 = 0; i0 < 2; i0++) { b_C[i0] = theta->size[i0]; } emlrtSizeEqCheckND(n_activation, b_C, &h_emlrtECI); EMLRTPUSHRTSTACK(&e_emlrtRSI); i0 = activation->size[1]; nm1d2 = b_activation->size[0] * b_activation->size[1]; b_activation->size[0] = 1; b_activation->size[1] = i0; emxEnsureCapacity((emxArray__common *)b_activation, nm1d2, (int32_T)sizeof(boolean_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { b_activation->data[b_activation->size[0] * i0] = (activation->data[((int32_T)iTP + activation->size[0] * i0) - 1] > theta->data[theta->size[0] * i0]); } prop = mrdivide(sum(b_activation), (real_T)v->size[1]); EMLRTPOPRTSTACK(&e_emlrtRSI); /* 'epu_n_unit_accumulator:170' if isinf(rt) && all(prop >= pN) */ if (muDoubleScalarIsInf(*rt)) { EMLRTPUSHRTSTACK(&f_emlrtRSI); i0 = b_prop->size[0] * b_prop->size[1]; b_prop->size[0] = 1; b_prop->size[1] = pN->size[1]; emxEnsureCapacity((emxArray__common *)b_prop, i0, (int32_T)sizeof(boolean_T), &emlrtRTEI); loop_ub = pN->size[0] * pN->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { b_prop->data[i0] = (prop >= pN->data[i0]); } innerDimOk = all(b_prop); EMLRTPOPRTSTACK(&f_emlrtRSI); if (innerDimOk) { /* Determine RT if sufficient number of accumulators have reached threshold */ /* Identify critical accumulator (i.e. crossed threshold most recently) and determine RT */ /* 'epu_n_unit_accumulator:173' iCrossed = activation(iTP,:) - theta > 0; */ emlrtDynamicBoundsCheck((int32_T)iTP, 1, activation->size[0], &g_emlrtBCI); i0 = activation->size[1]; nm1d2 = j_activation->size[0] * j_activation->size[1]; j_activation->size[0] = 1; j_activation->size[1] = i0; emxEnsureCapacity((emxArray__common *)j_activation, nm1d2, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { j_activation->data[j_activation->size[0] * i0] = activation->data[((int32_T)iTP + activation->size[0] * i0) - 1]; } for (i0 = 0; i0 < 2; i0++) { n_activation[i0] = j_activation->size[i0]; } for (i0 = 0; i0 < 2; i0++) { b_C[i0] = theta->size[i0]; } emlrtSizeEqCheckND(n_activation, b_C, &i_emlrtECI); i0 = activation->size[1]; nm1d2 = iCrossed->size[0] * iCrossed->size[1]; iCrossed->size[0] = 1; iCrossed->size[1] = i0; emxEnsureCapacity((emxArray__common *)iCrossed, nm1d2, (int32_T)sizeof(boolean_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { iCrossed->data[iCrossed->size[0] * i0] = (activation->data[((int32_T)iTP + activation->size[0] * i0) - 1] - theta->data[theta->size[0] * i0] > 0.0); } /* 'epu_n_unit_accumulator:174' iCritical = find(activation(iTP,:) - theta == min(activation(iTP,iCrossed)-theta(iCrossed))); */ emlrtDynamicBoundsCheck((int32_T)iTP, 1, activation->size[0], &h_emlrtBCI); i0 = activation->size[1]; nm1d2 = k_activation->size[0] * k_activation->size[1]; k_activation->size[0] = 1; k_activation->size[1] = i0; emxEnsureCapacity((emxArray__common *)k_activation, nm1d2, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { k_activation->data[k_activation->size[0] * i0] = activation->data[((int32_T)iTP + activation->size[0] * i0) - 1]; } for (i0 = 0; i0 < 2; i0++) { n_activation[i0] = k_activation->size[i0]; } for (i0 = 0; i0 < 2; i0++) { b_C[i0] = theta->size[i0]; } emlrtSizeEqCheckND(n_activation, b_C, &j_emlrtECI); EMLRTPUSHRTSTACK(&g_emlrtRSI); eml_li_find(iCrossed, ii); i0 = r5->size[0] * r5->size[1]; r5->size[0] = 1; r5->size[1] = ii->size[1]; emxEnsureCapacity((emxArray__common *)r5, i0, (int32_T)sizeof(int32_T), &emlrtRTEI); loop_ub = ii->size[0] * ii->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r5->data[i0] = emlrtDynamicBoundsCheck(ii->data[i0], 1, activation->size[1], &nb_emlrtBCI); } nm1d2 = r5->size[1]; ixstart = emlrtDynamicBoundsCheck((int32_T)iTP, 1, activation->size[0], &i_emlrtBCI); i0 = iCritical->size[0] * iCritical->size[1]; iCritical->size[0] = 1; iCritical->size[1] = nm1d2; emxEnsureCapacity((emxArray__common *)iCritical, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = nm1d2 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { iCritical->data[iCritical->size[0] * i0] = activation->data[(ixstart + activation->size[0] * (r5->data[i0] - 1)) - 1]; } EMLRTPOPRTSTACK(&g_emlrtRSI); EMLRTPUSHRTSTACK(&h_emlrtRSI); eml_li_find(iCrossed, ii); i0 = r0->size[0] * r0->size[1]; r0->size[0] = 1; r0->size[1] = ii->size[1]; emxEnsureCapacity((emxArray__common *)r0, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = ii->size[0] * ii->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r0->data[i0] = theta->data[emlrtDynamicBoundsCheck(ii->data[i0], 1, theta->size[1], &ob_emlrtBCI) - 1]; } EMLRTPOPRTSTACK(&h_emlrtRSI); for (i0 = 0; i0 < 2; i0++) { b_C[i0] = iCritical->size[i0]; } for (i0 = 0; i0 < 2; i0++) { iv2[i0] = r0->size[i0]; } emlrtSizeEqCheckND(b_C, iv2, &k_emlrtECI); EMLRTPUSHRTSTACK(&i_emlrtRSI); i0 = iCritical->size[0] * iCritical->size[1]; iCritical->size[0] = 1; emxEnsureCapacity((emxArray__common *)iCritical, i0, (int32_T)sizeof(real_T), &emlrtRTEI); ixstart = iCritical->size[0]; nm1d2 = iCritical->size[1]; loop_ub = ixstart * nm1d2 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { iCritical->data[i0] -= r0->data[i0]; } EMLRTPUSHRTSTACK(&vb_emlrtRSI); EMLRTPUSHRTSTACK(&wb_emlrtRSI); if ((iCritical->size[1] == 1) || (iCritical->size[1] != 1)) { innerDimOk = TRUE; } else { innerDimOk = FALSE; } if (innerDimOk) { } else { EMLRTPUSHRTSTACK(&xb_emlrtRSI); c_y = NULL; m0 = mxCreateCharArray(2, iv3); emlrtInitCharArray(36, m0, cv2); emlrtAssign(&c_y, m0); error(message(c_y, &p_emlrtMCI), &q_emlrtMCI); EMLRTPOPRTSTACK(&xb_emlrtRSI); } if (iCritical->size[1] > 0) { } else { EMLRTPUSHRTSTACK(&yb_emlrtRSI); d_y = NULL; m0 = mxCreateCharArray(2, iv4); emlrtInitCharArray(39, m0, cv3); emlrtAssign(&d_y, m0); error(message(d_y, &r_emlrtMCI), &s_emlrtMCI); EMLRTPOPRTSTACK(&yb_emlrtRSI); } EMLRTPUSHRTSTACK(&ac_emlrtRSI); ixstart = 1; n = iCritical->size[1]; emlrtDynamicBoundsCheck(1, 1, iCritical->size[1], &y_emlrtBCI); x = iCritical->data[0]; if (n > 1) { if (muDoubleScalarIsNaN(iCritical->data[0])) { nm1d2 = 2; exitg4 = 0U; while ((exitg4 == 0U) && (nm1d2 <= n)) { ixstart = nm1d2; emlrtDynamicBoundsCheck(nm1d2, 1, iCritical->size[1], &ab_emlrtBCI); if (!muDoubleScalarIsNaN(iCritical->data[nm1d2 - 1])) { x = iCritical->data[emlrtDynamicBoundsCheck(nm1d2, 1, iCritical->size[1], &pb_emlrtBCI) - 1]; exitg4 = 1U; } else { nm1d2++; } } } if (ixstart < n) { for (nm1d2 = ixstart + 1; nm1d2 <= n; nm1d2++) { emlrtDynamicBoundsCheck(nm1d2, 1, iCritical->size[1], &bb_emlrtBCI); if (iCritical->data[nm1d2 - 1] < x) { x = iCritical->data[emlrtDynamicBoundsCheck(nm1d2, 1, iCritical->size[1], &ic_emlrtBCI) - 1]; } } } } EMLRTPOPRTSTACK(&ac_emlrtRSI); EMLRTPOPRTSTACK(&wb_emlrtRSI); EMLRTPOPRTSTACK(&vb_emlrtRSI); i0 = activation->size[1]; nm1d2 = iCrossed->size[0] * iCrossed->size[1]; iCrossed->size[0] = 1; iCrossed->size[1] = i0; emxEnsureCapacity((emxArray__common *)iCrossed, nm1d2, (int32_T)sizeof(boolean_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { iCrossed->data[iCrossed->size[0] * i0] = (activation->data[((int32_T)iTP + activation->size[0] * i0) - 1] - theta->data[theta->size[0] * i0] == x); } EMLRTPUSHRTSTACK(&bc_emlrtRSI); ixstart = iCrossed->size[1]; idx = 0; i0 = ii->size[0] * ii->size[1]; ii->size[0] = 1; ii->size[1] = ixstart; emxEnsureCapacity((emxArray__common *)ii, i0, (int32_T)sizeof(int32_T), &e_emlrtRTEI); nm1d2 = 1; exitg3 = 0U; while ((exitg3 == 0U) && (nm1d2 <= ixstart)) { guard1 = FALSE; if (iCrossed->data[emlrtDynamicBoundsCheck(nm1d2, 1, iCrossed->size[1], &qb_emlrtBCI) - 1]) { idx++; ii->data[emlrtDynamicBoundsCheck(idx, 1, ii->size[1], &rb_emlrtBCI) - 1] = nm1d2; if (idx >= ixstart) { exitg3 = 1U; } else { guard1 = TRUE; } } else { guard1 = TRUE; } if (guard1 == TRUE) { nm1d2++; } } if (idx <= ixstart) { } else { EMLRTPUSHRTSTACK(&dc_emlrtRSI); e_y = NULL; m0 = mxCreateString("Assertion failed."); emlrtAssign(&e_y, m0); error(e_y, &u_emlrtMCI); EMLRTPOPRTSTACK(&dc_emlrtRSI); } if (ixstart == 1) { if (idx == 0) { i0 = ii->size[0] * ii->size[1]; ii->size[0] = 1; ii->size[1] = 0; emxEnsureCapacity((emxArray__common *)ii, i0, (int32_T)sizeof(int32_T), &emlrtRTEI); } } else { if (1 > idx) { i0 = 0; } else { emlrtDynamicBoundsCheck(1, 1, ii->size[1], &cb_emlrtBCI); i0 = emlrtDynamicBoundsCheck(idx, 1, ii->size[1], &db_emlrtBCI); } nm1d2 = r6->size[0]; r6->size[0] = i0; emxEnsureCapacity((emxArray__common *)r6, nm1d2, (int32_T)sizeof(int32_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r6->data[i0] = 1 + i0; } iv5[0] = 1; iv5[1] = r6->size[0]; i0 = b_ii->size[0] * b_ii->size[1]; b_ii->size[0] = iv5[0]; b_ii->size[1] = iv5[1]; emxEnsureCapacity((emxArray__common *)b_ii, i0, (int32_T)sizeof(int32_T), &emlrtRTEI); loop_ub = iv5[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { idx = iv5[0] - 1; for (nm1d2 = 0; nm1d2 <= idx; nm1d2++) { r7 = *r6; r7.size = (int32_T *)&iv5; r7.numDimensions = 1; b_ii->data[nm1d2 + b_ii->size[0] * i0] = ii->data[r7.data[nm1d2 + r7.size[0] * i0] - 1]; } } i0 = ii->size[0] * ii->size[1]; ii->size[0] = 1; ii->size[1] = b_ii->size[1]; emxEnsureCapacity((emxArray__common *)ii, i0, (int32_T)sizeof(int32_T), &emlrtRTEI); loop_ub = b_ii->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { ii->data[ii->size[0] * i0] = b_ii->data[b_ii->size[0] * i0]; } } EMLRTPOPRTSTACK(&bc_emlrtRSI); i0 = iCritical->size[0] * iCritical->size[1]; iCritical->size[0] = 1; iCritical->size[1] = ii->size[1]; emxEnsureCapacity((emxArray__common *)iCritical, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = ii->size[0] * ii->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { iCritical->data[i0] = (real_T)ii->data[i0]; } EMLRTPOPRTSTACK(&i_emlrtRSI); /* 'epu_n_unit_accumulator:175' iCritical = iCritical(1); */ emlrtDynamicBoundsCheck(1, 1, iCritical->size[1], &j_emlrtBCI); /* This is because when r equals 1, all accumulators cross at the same time */ /* 'epu_n_unit_accumulator:177' actAroundThres = activation(iTP-1:iTP,iCritical); */ emlrtDynamicBoundsCheck((int32_T)iCritical->data[0], 1, activation->size[1], &k_emlrtBCI); for (i0 = 0; i0 < 2; i0++) { emlrtDynamicBoundsCheck((int32_T)(iTP + (-1.0 + (real_T)i0)), 1, activation->size[0], &sb_emlrtBCI); } /* 'epu_n_unit_accumulator:178' tAroundThres = dt.*[iTP-1,iTP]'; */ /* 'epu_n_unit_accumulator:179' critThres = theta(iCritical); */ emlrtDynamicBoundsCheck((int32_T)iCritical->data[0], 1, theta->size[1], &l_emlrtBCI); /* 'epu_n_unit_accumulator:181' rt = interp1q(actAroundThres,tAroundThres,critThres) + effTime; */ EMLRTPUSHRTSTACK(&j_emlrtRSI); ixstart = (int32_T)iCritical->data[0]; for (i0 = 0; i0 < 2; i0++) { mActivation[i0] = activation->data[((int32_T)(iTP + (-1.0 + (real_T)i0)) + activation->size[0] * (ixstart - 1)) - 1]; } b_dt[0] = dt * (iTP - 1.0); b_dt[1] = dt * iTP; *rt = interp1q(mActivation, b_dt, theta->data[(int32_T)iCritical->data[0] - 1]) + effTime; EMLRTPOPRTSTACK(&j_emlrtRSI); /* 'epu_n_unit_accumulator:183' rt = rt(1); */ /* If interp1q returns vector rather than scalar */ } } /* 'epu_n_unit_accumulator:186' if iTP*dt > rt */ if (iTP * dt > *rt) { /* Keep data from selected accumulators */ /* 'epu_n_unit_accumulator:188' activation = activation(:,iAT); */ i0 = r3->size[0] * r3->size[1]; r3->size[0] = 1; r3->size[1] = iAT->size[1]; emxEnsureCapacity((emxArray__common *)r3, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = iAT->size[0] * iAT->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r3->data[i0] = (real_T)emlrtDynamicBoundsCheck((int32_T)emlrtIntegerCheckR2009b(iAT->data[i0], &l_emlrtDCI), 1, activation->size[1], &ub_emlrtBCI); } ixstart = activation->size[0]; nm1d2 = r3->size[1]; i0 = m_activation->size[0] * m_activation->size[1]; m_activation->size[0] = ixstart; m_activation->size[1] = nm1d2; emxEnsureCapacity((emxArray__common *)m_activation, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = nm1d2 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { idx = ixstart - 1; for (nm1d2 = 0; nm1d2 <= idx; nm1d2++) { m_activation->data[nm1d2 + m_activation->size[0] * i0] = activation->data[nm1d2 + activation->size[0] * ((int32_T)r3->data[i0] - 1)]; } } i0 = activation->size[0] * activation->size[1]; activation->size[0] = m_activation->size[0]; activation->size[1] = m_activation->size[1]; emxEnsureCapacity((emxArray__common *)activation, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = m_activation->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { idx = m_activation->size[0] - 1; for (nm1d2 = 0; nm1d2 <= idx; nm1d2++) { activation->data[nm1d2 + activation->size[0] * i0] = m_activation->data[nm1d2 + m_activation->size[0] * i0]; } } exitg2 = 1U; } else { /* 'epu_n_unit_accumulator:192' if iTP > floor(nTP./dt)-1 */ if (iTP > muDoubleScalarFloor(rdivide(nTP, dt)) - 1.0) { /* If trial end (i.e. maximum number of time points) has been reached */ /* Keep data from selected accumulators */ /* 'epu_n_unit_accumulator:194' rt = nan; */ *rt = rtNaN; /* 'epu_n_unit_accumulator:195' activation = activation(:,iAT); */ i0 = r4->size[0] * r4->size[1]; r4->size[0] = 1; r4->size[1] = iAT->size[1]; emxEnsureCapacity((emxArray__common *)r4, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = iAT->size[0] * iAT->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r4->data[i0] = (real_T)emlrtDynamicBoundsCheck((int32_T)emlrtIntegerCheckR2009b(iAT->data[i0], &k_emlrtDCI), 1, activation->size[1], &tb_emlrtBCI); } ixstart = activation->size[0]; nm1d2 = r4->size[1]; i0 = l_activation->size[0] * l_activation->size[1]; l_activation->size[0] = ixstart; l_activation->size[1] = nm1d2; emxEnsureCapacity((emxArray__common *)l_activation, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = nm1d2 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { idx = ixstart - 1; for (nm1d2 = 0; nm1d2 <= idx; nm1d2++) { l_activation->data[nm1d2 + l_activation->size[0] * i0] = activation->data[nm1d2 + activation->size[0] * ((int32_T)r4->data[i0] - 1)]; } } i0 = activation->size[0] * activation->size[1]; activation->size[0] = l_activation->size[0]; activation->size[1] = l_activation->size[1]; emxEnsureCapacity((emxArray__common *)activation, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = l_activation->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { idx = l_activation->size[0] - 1; for (nm1d2 = 0; nm1d2 <= idx; nm1d2++) { activation->data[nm1d2 + activation->size[0] * i0] = l_activation->data[nm1d2 + l_activation->size[0] * i0]; } } exitg2 = 1U; } else { /* 'epu_n_unit_accumulator:199' iTP = iTP + 1; */ iTP++; emlrtBreakCheck(); } } } emxFree_real_T(&m_activation); emxFree_real_T(&l_activation); emxFree_int32_T(&b_ii); emxFree_real_T(&k_activation); emxFree_real_T(&j_activation); emxFree_real_T(&i_activation); emxFree_real_T(&h_activation); emxFree_real_T(&g_activation); emxFree_real_T(&f_activation); emxFree_real_T(&e_activation); emxFree_real_T(&d_activation); emxFree_int32_T(&r6); emxFree_int32_T(&r5); emxFree_real_T(&r4); emxFree_real_T(&r3); emxFree_int32_T(&r2); emxFree_boolean_T(&c_activation); emxFree_boolean_T(&b_activation); emxFree_boolean_T(&b_prop); emxFree_boolean_T(&iCrossed); } else { if (dMeth == 2.0) { b_emxInit_real_T(&b_mActivation, 1, &h_emlrtRTEI, TRUE); /* 'epu_n_unit_accumulator:202' elseif dMeth == 2 */ /* Pooling */ /* 'epu_n_unit_accumulator:203' mActivation = zeros(nTP,1); */ i0 = b_mActivation->size[0]; b_mActivation->size[0] = (int32_T)emlrtIntegerCheckR2009b(emlrtNonNegativeCheckR2009b(nTP, &f_emlrtDCI), &e_emlrtDCI); emxEnsureCapacity((emxArray__common *)b_mActivation, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = (int32_T)emlrtIntegerCheckR2009b(emlrtNonNegativeCheckR2009b(nTP, &h_emlrtDCI), &g_emlrtDCI) - 1; for (i0 = 0; i0 <= loop_ub; i0++) { b_mActivation->data[i0] = 0.0; } /* 'epu_n_unit_accumulator:204' mThreshold = mean(theta); */ EMLRTPUSHRTSTACK(&k_emlrtRSI); mThreshold = mean(theta); EMLRTPOPRTSTACK(&k_emlrtRSI); /* 'epu_n_unit_accumulator:205' while iTP < Inf */ emxInit_real_T(&o_activation, 2, &emlrtRTEI, TRUE); emxInit_boolean_T(&p_activation, 2, &emlrtRTEI, TRUE); b_emxInit_int32_T(&r8, 2, &emlrtRTEI, TRUE); emxInit_real_T(&r9, 2, &emlrtRTEI, TRUE); emxInit_real_T(&r10, 2, &emlrtRTEI, TRUE); emxInit_real_T(&q_activation, 2, &emlrtRTEI, TRUE); emxInit_real_T(&r_activation, 2, &emlrtRTEI, TRUE); emxInit_real_T(&s_activation, 2, &emlrtRTEI, TRUE); emxInit_real_T(&t_activation, 2, &emlrtRTEI, TRUE); emxInit_real_T(&u_activation, 2, &emlrtRTEI, TRUE); emxInit_real_T(&v_activation, 2, &emlrtRTEI, TRUE); emxInit_real_T(&w_activation, 2, &emlrtRTEI, TRUE); exitg1 = 0U; while ((exitg1 == 0U) && (iTP < rtInf)) { /* Generate correlated Gaussian noise */ /* 'epu_n_unit_accumulator:208' Xi = randn(1,size(SigmaXi,1)) * SigmaXi + zeros(1,nA); */ EMLRTPUSHRTSTACK(&l_emlrtRSI); randn(SD, (real_T)SigmaXi->size[0], iCritical); EMLRTPUSHRTSTACK(&hb_emlrtRSI); innerDimOk = (iCritical->size[1] == SigmaXi->size[0]); if (!innerDimOk) { if ((iCritical->size[1] == 1) || ((SigmaXi->size[0] == 1) && (SigmaXi->size[1] == 1))) { EMLRTPUSHRTSTACK(&ib_emlrtRSI); f_y = NULL; m0 = mxCreateCharArray(2, iv6); emlrtInitCharArray(45, m0, cv0); emlrtAssign(&f_y, m0); error(message(f_y, &e_emlrtMCI), &f_emlrtMCI); EMLRTPOPRTSTACK(&ib_emlrtRSI); } else { EMLRTPUSHRTSTACK(&jb_emlrtRSI); g_y = NULL; m0 = mxCreateCharArray(2, iv7); emlrtInitCharArray(21, m0, cv1); emlrtAssign(&g_y, m0); error(message(g_y, &g_emlrtMCI), &h_emlrtMCI); EMLRTPOPRTSTACK(&jb_emlrtRSI); } } EMLRTPOPRTSTACK(&hb_emlrtRSI); if ((iCritical->size[1] == 1) || (SigmaXi->size[0] == 1)) { i0 = C->size[0] * C->size[1]; C->size[0] = 1; C->size[1] = SigmaXi->size[1]; emxEnsureCapacity((emxArray__common *)C, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = SigmaXi->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { C->data[C->size[0] * i0] = 0.0; idx = iCritical->size[1] - 1; for (nm1d2 = 0; nm1d2 <= idx; nm1d2++) { C->data[C->size[0] * i0] += iCritical->data[iCritical->size[0] * nm1d2] * SigmaXi->data[nm1d2 + SigmaXi->size[0] * i0]; } } } else { b_k = iCritical->size[1]; unnamed_idx_1 = (uint32_T)SigmaXi->size[1]; i0 = C->size[0] * C->size[1]; C->size[0] = 1; C->size[1] = (int32_T)unnamed_idx_1; emxEnsureCapacity((emxArray__common *)C, i0, (int32_T)sizeof(real_T), &c_emlrtRTEI); n = SigmaXi->size[1]; i0 = C->size[0] * C->size[1]; C->size[0] = 1; emxEnsureCapacity((emxArray__common *)C, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = C->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { C->data[C->size[0] * i0] = 0.0; } EMLRTPUSHRTSTACK(&gb_emlrtRSI); EMLRTPUSHRTSTACK(&kb_emlrtRSI); if ((n < 1) || (b_k < 1)) { } else { EMLRTPUSHRTSTACK(&mb_emlrtRSI); ixstart = 1; x = 1.0; idx = 1; prop = 0.0; nm1d2 = 1; TRANSA = 'N'; TRANSB = 'N'; EMLRTPUSHRTSTACK(&nb_emlrtRSI); emlrtDynamicBoundsCheck(1, 1, iCritical->size[1], &s_emlrtBCI); emlrtDynamicBoundsCheck(1, 1, SigmaXi->size[0] * SigmaXi->size[1], &t_emlrtBCI); emlrtDynamicBoundsCheck(1, 1, C->size[1], &u_emlrtBCI); dgemm32(&TRANSA, &TRANSB, &ixstart, &n, &b_k, &x, &iCritical->data[0], &idx, &SigmaXi->data[0], &b_k, &prop, &C->data[0], &nm1d2); EMLRTPOPRTSTACK(&nb_emlrtRSI); EMLRTPOPRTSTACK(&mb_emlrtRSI); } EMLRTPOPRTSTACK(&kb_emlrtRSI); EMLRTPOPRTSTACK(&gb_emlrtRSI); } EMLRTPOPRTSTACK(&l_emlrtRSI); for (i0 = 0; i0 < 2; i0++) { b_C[i0] = C->size[i0]; } iv2[0] = 1; iv2[1] = v->size[1]; emlrtSizeEqCheckND(b_C, iv2, &l_emlrtECI); /* Compute activation level */ /* 'epu_n_unit_accumulator:211' activation(iTP,:) = activation(iTP-1,:) + dt./TAU.*(v-k.*activation(iTP-1,:)) + sqrt(dt./TAU).*Xi; */ emlrtDynamicBoundsCheck((int32_T)(iTP - 1.0), 1, activation->size[0], &n_emlrtBCI); for (i0 = 0; i0 < 2; i0++) { b_C[i0] = k->size[i0]; } i0 = activation->size[1]; nm1d2 = q_activation->size[0] * q_activation->size[1]; q_activation->size[0] = 1; q_activation->size[1] = i0; emxEnsureCapacity((emxArray__common *)q_activation, nm1d2, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { q_activation->data[q_activation->size[0] * i0] = activation->data[((int32_T)(iTP - 1.0) + activation->size[0] * i0) - 1]; } for (i0 = 0; i0 < 2; i0++) { n_activation[i0] = q_activation->size[i0]; } emlrtSizeEqCheckND(b_C, n_activation, &m_emlrtECI); i0 = r0->size[0] * r0->size[1]; r0->size[0] = 1; r0->size[1] = k->size[1]; emxEnsureCapacity((emxArray__common *)r0, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = k->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r0->data[r0->size[0] * i0] = k->data[k->size[0] * i0] * activation->data[((int32_T)(iTP - 1.0) + activation->size[0] * i0) - 1]; } for (i0 = 0; i0 < 2; i0++) { b_C[i0] = v->size[i0]; } for (i0 = 0; i0 < 2; i0++) { iv2[i0] = r0->size[i0]; } emlrtSizeEqCheckND(b_C, iv2, &n_emlrtECI); emlrtDynamicBoundsCheck((int32_T)(iTP - 1.0), 1, activation->size[0], &m_emlrtBCI); i0 = r0->size[0] * r0->size[1]; r0->size[0] = 1; r0->size[1] = v->size[1]; emxEnsureCapacity((emxArray__common *)r0, i0, (int32_T)sizeof(real_T), &emlrtRTEI); x = rdivide(dt, 1.0); loop_ub = v->size[0] * v->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r0->data[i0] = x * (v->data[i0] - r0->data[i0]); } i0 = activation->size[1]; nm1d2 = r_activation->size[0] * r_activation->size[1]; r_activation->size[0] = 1; r_activation->size[1] = i0; emxEnsureCapacity((emxArray__common *)r_activation, nm1d2, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r_activation->data[r_activation->size[0] * i0] = activation->data[((int32_T)(iTP - 1.0) + activation->size[0] * i0) - 1]; } for (i0 = 0; i0 < 2; i0++) { n_activation[i0] = r_activation->size[i0]; } for (i0 = 0; i0 < 2; i0++) { iv2[i0] = r0->size[i0]; } emlrtSizeEqCheckND(n_activation, iv2, &o_emlrtECI); EMLRTPUSHRTSTACK(&m_emlrtRSI); x = dt; b_sqrt(&x); i0 = C->size[0] * C->size[1]; C->size[0] = 1; emxEnsureCapacity((emxArray__common *)C, i0, (int32_T)sizeof(real_T), &emlrtRTEI); nm1d2 = C->size[0]; ixstart = C->size[1]; loop_ub = nm1d2 * ixstart - 1; for (i0 = 0; i0 <= loop_ub; i0++) { C->data[i0] *= x; } EMLRTPOPRTSTACK(&m_emlrtRSI); i0 = activation->size[1]; nm1d2 = s_activation->size[0] * s_activation->size[1]; s_activation->size[0] = 1; s_activation->size[1] = i0; emxEnsureCapacity((emxArray__common *)s_activation, nm1d2, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { s_activation->data[s_activation->size[0] * i0] = activation->data[((int32_T)(iTP - 1.0) + activation->size[0] * i0) - 1]; } for (i0 = 0; i0 < 2; i0++) { n_activation[i0] = s_activation->size[i0]; } for (i0 = 0; i0 < 2; i0++) { b_C[i0] = C->size[i0]; } emlrtSizeEqCheckND(n_activation, b_C, &p_emlrtECI); emlrtDynamicBoundsCheck((int32_T)iTP, 1, activation->size[0], &o_emlrtBCI); i0 = activation->size[1]; nm1d2 = r1->size[0]; r1->size[0] = i0; emxEnsureCapacity((emxArray__common *)r1, nm1d2, (int32_T)sizeof(int32_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r1->data[i0] = i0; } iv2[0] = 1; iv2[1] = r1->size[0]; i0 = activation->size[1]; nm1d2 = t_activation->size[0] * t_activation->size[1]; t_activation->size[0] = 1; t_activation->size[1] = i0; emxEnsureCapacity((emxArray__common *)t_activation, nm1d2, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { t_activation->data[t_activation->size[0] * i0] = activation->data[((int32_T)iTP + activation->size[0] * i0) - 2]; } for (i0 = 0; i0 < 2; i0++) { n_activation[i0] = t_activation->size[i0]; } emlrtSubAssignSizeCheck(iv2, 2, n_activation, 2, &q_emlrtECI); ixstart = activation->size[1]; i0 = u_activation->size[0] * u_activation->size[1]; u_activation->size[0] = 1; u_activation->size[1] = ixstart; emxEnsureCapacity((emxArray__common *)u_activation, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = ixstart - 1; for (i0 = 0; i0 <= loop_ub; i0++) { u_activation->data[u_activation->size[0] * i0] = (activation->data[((int32_T)iTP + activation->size[0] * i0) - 2] + r0->data[r0->size[0] * i0]) + C->data[C->size[0] * i0]; } loop_ub = u_activation->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { activation->data[((int32_T)iTP + activation->size[0] * r1->data[i0]) - 1] = u_activation->data[u_activation->size[0] * i0]; } /* Reset activation level if it goes below zero */ /* 'epu_n_unit_accumulator:214' activation(iTP,(activation(iTP,:) < 0)) = 0; */ EMLRTPUSHRTSTACK(&n_emlrtRSI); i0 = activation->size[1]; ixstart = emlrtDynamicBoundsCheck((int32_T)iTP, 1, activation->size[0], &q_emlrtBCI); nm1d2 = p_activation->size[0] * p_activation->size[1]; p_activation->size[0] = 1; p_activation->size[1] = i0; emxEnsureCapacity((emxArray__common *)p_activation, nm1d2, (int32_T)sizeof(boolean_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { p_activation->data[p_activation->size[0] * i0] = (activation->data[(ixstart + activation->size[0] * i0) - 1] < 0.0); } eml_li_find(p_activation, ii); i0 = r8->size[0] * r8->size[1]; r8->size[0] = 1; r8->size[1] = ii->size[1]; emxEnsureCapacity((emxArray__common *)r8, i0, (int32_T)sizeof(int32_T), &emlrtRTEI); loop_ub = ii->size[0] * ii->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r8->data[i0] = emlrtDynamicBoundsCheck(ii->data[i0], 1, activation->size[1], &gb_emlrtBCI); } i0 = r1->size[0]; r1->size[0] = r8->size[1]; emxEnsureCapacity((emxArray__common *)r1, i0, (int32_T)sizeof(int32_T), &emlrtRTEI); loop_ub = r8->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r1->data[i0] = r8->data[i0]; } EMLRTPOPRTSTACK(&n_emlrtRSI); ixstart = activation->size[0]; emlrtDynamicBoundsCheck((int32_T)iTP, 1, ixstart, &p_emlrtBCI); nm1d2 = r1->size[0]; loop_ub = nm1d2 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { activation->data[((int32_T)iTP + activation->size[0] * (r1->data[i0] - 1)) - 1] = 0.0; } /* Compute mean activation level across all accumulators */ /* 'epu_n_unit_accumulator:217' mActivation(iTP) = mean(activation(iTP,:)); */ EMLRTPUSHRTSTACK(&o_emlrtRSI); i0 = activation->size[1]; ixstart = emlrtDynamicBoundsCheck((int32_T)iTP, 1, activation->size[0], &r_emlrtBCI); nm1d2 = o_activation->size[0] * o_activation->size[1]; o_activation->size[0] = 1; o_activation->size[1] = i0; emxEnsureCapacity((emxArray__common *)o_activation, nm1d2, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = i0 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { o_activation->data[o_activation->size[0] * i0] = activation->data[(ixstart + activation->size[0] * i0) - 1]; } b_mActivation->data[emlrtDynamicBoundsCheck((int32_T)iTP, 1, b_mActivation->size[0], &hb_emlrtBCI) - 1] = mean(o_activation); EMLRTPOPRTSTACK(&o_emlrtRSI); /* 'epu_n_unit_accumulator:219' if isinf(rt) && all(mActivation(iTP) > mThreshold) */ if (muDoubleScalarIsInf(*rt)) { innerDimOk = (b_mActivation->data[emlrtDynamicBoundsCheck((int32_T)iTP, 1, b_mActivation->size[0], &ib_emlrtBCI) - 1] > mThreshold); if (innerDimOk) { /* 'epu_n_unit_accumulator:221' actAroundThres = mActivation(iTP-1:iTP); */ emlrtVectorVectorIndexCheck(b_mActivation->size[0], 1, 1, 2, &r_emlrtECI); for (i0 = 0; i0 < 2; i0++) { emlrtDynamicBoundsCheck((int32_T)(iTP + (-1.0 + (real_T)i0)), 1, b_mActivation->size[0], &jb_emlrtBCI); } /* 'epu_n_unit_accumulator:222' tAroundThres = dt.*[iTP-1,iTP]'; */ /* 'epu_n_unit_accumulator:224' rt = interp1q(actAroundThres,tAroundThres,mThreshold) + effTime; */ EMLRTPUSHRTSTACK(&p_emlrtRSI); for (i0 = 0; i0 < 2; i0++) { mActivation[i0] = b_mActivation->data[(int32_T)(iTP + (-1.0 + (real_T)i0)) - 1]; } b_dt[0] = dt * (iTP - 1.0); b_dt[1] = dt * iTP; *rt = interp1q(mActivation, b_dt, mThreshold) + effTime; EMLRTPOPRTSTACK(&p_emlrtRSI); /* 'epu_n_unit_accumulator:226' rt = rt(1); */ /* In case inetrp1q returns vector rather than scalar */ } } /* 'epu_n_unit_accumulator:229' if iTP*dt > rt */ if (iTP * dt > *rt) { /* 'epu_n_unit_accumulator:230' activation = activation(:,iAT); */ i0 = r9->size[0] * r9->size[1]; r9->size[0] = 1; r9->size[1] = iAT->size[1]; emxEnsureCapacity((emxArray__common *)r9, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = iAT->size[0] * iAT->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r9->data[i0] = (real_T)emlrtDynamicBoundsCheck((int32_T)emlrtIntegerCheckR2009b(iAT->data[i0], &j_emlrtDCI), 1, activation->size[1], &lb_emlrtBCI); } ixstart = activation->size[0]; nm1d2 = r9->size[1]; i0 = w_activation->size[0] * w_activation->size[1]; w_activation->size[0] = ixstart; w_activation->size[1] = nm1d2; emxEnsureCapacity((emxArray__common *)w_activation, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = nm1d2 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { idx = ixstart - 1; for (nm1d2 = 0; nm1d2 <= idx; nm1d2++) { w_activation->data[nm1d2 + w_activation->size[0] * i0] = activation->data[nm1d2 + activation->size[0] * ((int32_T)r9->data[i0] - 1)]; } } i0 = activation->size[0] * activation->size[1]; activation->size[0] = w_activation->size[0]; activation->size[1] = w_activation->size[1]; emxEnsureCapacity((emxArray__common *)activation, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = w_activation->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { idx = w_activation->size[0] - 1; for (nm1d2 = 0; nm1d2 <= idx; nm1d2++) { activation->data[nm1d2 + activation->size[0] * i0] = w_activation->data[nm1d2 + w_activation->size[0] * i0]; } } exitg1 = 1U; } else { /* 'epu_n_unit_accumulator:237' if iTP > floor(nTP./dt)-1 */ if (iTP > muDoubleScalarFloor(nTP / dt) - 1.0) { /* Keep data from selected accumulators */ /* 'epu_n_unit_accumulator:239' rt = nan; */ *rt = rtNaN; /* 'epu_n_unit_accumulator:240' activation = activation(:,iAT); */ i0 = r10->size[0] * r10->size[1]; r10->size[0] = 1; r10->size[1] = iAT->size[1]; emxEnsureCapacity((emxArray__common *)r10, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = iAT->size[0] * iAT->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { r10->data[i0] = (real_T)emlrtDynamicBoundsCheck((int32_T)emlrtIntegerCheckR2009b(iAT->data[i0], &i_emlrtDCI), 1, activation->size[1], &kb_emlrtBCI); } ixstart = activation->size[0]; nm1d2 = r10->size[1]; i0 = v_activation->size[0] * v_activation->size[1]; v_activation->size[0] = ixstart; v_activation->size[1] = nm1d2; emxEnsureCapacity((emxArray__common *)v_activation, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = nm1d2 - 1; for (i0 = 0; i0 <= loop_ub; i0++) { idx = ixstart - 1; for (nm1d2 = 0; nm1d2 <= idx; nm1d2++) { v_activation->data[nm1d2 + v_activation->size[0] * i0] = activation->data[nm1d2 + activation->size[0] * ((int32_T)r10->data[i0] - 1)]; } } i0 = activation->size[0] * activation->size[1]; activation->size[0] = v_activation->size[0]; activation->size[1] = v_activation->size[1]; emxEnsureCapacity((emxArray__common *)activation, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = v_activation->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { idx = v_activation->size[0] - 1; for (nm1d2 = 0; nm1d2 <= idx; nm1d2++) { activation->data[nm1d2 + activation->size[0] * i0] = v_activation->data[nm1d2 + v_activation->size[0] * i0]; } } exitg1 = 1U; } else { /* 'epu_n_unit_accumulator:247' iTP = iTP + 1; */ iTP++; emlrtBreakCheck(); } } } emxFree_real_T(&w_activation); emxFree_real_T(&v_activation); emxFree_real_T(&u_activation); emxFree_real_T(&t_activation); emxFree_real_T(&s_activation); emxFree_real_T(&r_activation); emxFree_real_T(&q_activation); emxFree_real_T(&r10); emxFree_real_T(&r9); emxFree_int32_T(&r8); emxFree_boolean_T(&p_activation); emxFree_real_T(&o_activation); emxFree_real_T(&b_mActivation); } } emxFree_int32_T(&ii); emxFree_int32_T(&r1); emxFree_real_T(&r0); /* Transform to 1-ms steps */ /* 'epu_n_unit_accumulator:253' t = dt:dt:nTP; */ EMLRTPUSHRTSTACK(&q_emlrtRSI); EMLRTPUSHRTSTACK(&nc_emlrtRSI); float_colon_length(dt, dt, nTP, &n, &x, &prop, &innerDimOk); EMLRTPUSHRTSTACK(&oc_emlrtRSI); if (!innerDimOk) { } else { EMLRTPUSHRTSTACK(&pc_emlrtRSI); h_y = NULL; m0 = mxCreateCharArray(2, iv8); emlrtInitCharArray(21, m0, cv4); emlrtAssign(&h_y, m0); error(message(h_y, &ab_emlrtMCI), &bb_emlrtMCI); EMLRTPOPRTSTACK(&pc_emlrtRSI); } EMLRTPOPRTSTACK(&oc_emlrtRSI); emlrtNonNegativeCheckR2009b((real_T)n, &c_emlrtDCI); i0 = iCritical->size[0] * iCritical->size[1]; iCritical->size[0] = 1; iCritical->size[1] = n; emxEnsureCapacity((emxArray__common *)iCritical, i0, (int32_T)sizeof(real_T), &b_emlrtRTEI); if (n > 0) { emlrtDynamicBoundsCheck(1, 1, iCritical->size[1], &eb_emlrtBCI); iCritical->data[0] = x; if (n > 1) { iCritical->data[emlrtDynamicBoundsCheck(n, 1, iCritical->size[1], &vb_emlrtBCI) - 1] = prop; ixstart = n - 1; i0 = ixstart; nm1d2 = (int32_T)((uint32_T)i0 >> 1); for (b_k = 1; b_k <= nm1d2 - 1; b_k++) { mThreshold = (real_T)b_k * dt; iCritical->data[emlrtDynamicBoundsCheck(b_k + 1, 1, iCritical->size[1], &gc_emlrtBCI) - 1] = x + mThreshold; iCritical->data[emlrtDynamicBoundsCheck(n - b_k, 1, iCritical->size[1], &hc_emlrtBCI) - 1] = prop - mThreshold; } if (nm1d2 << 1 == ixstart) { iCritical->data[emlrtDynamicBoundsCheck(nm1d2 + 1, 1, iCritical->size[1], &yb_emlrtBCI) - 1] = (x + prop) / 2.0; } else { mThreshold = (real_T)nm1d2 * dt; iCritical->data[emlrtDynamicBoundsCheck(nm1d2 + 1, 1, iCritical->size[1], &wb_emlrtBCI) - 1] = x + mThreshold; iCritical->data[emlrtDynamicBoundsCheck(nm1d2 + 2, 1, iCritical->size[1], &xb_emlrtBCI) - 1] = prop - mThreshold; } } } EMLRTPOPRTSTACK(&nc_emlrtRSI); EMLRTPOPRTSTACK(&q_emlrtRSI); /* 'epu_n_unit_accumulator:254' activation = interp1(t,activation,colon(1,nTP)); */ EMLRTPUSHRTSTACK(&r_emlrtRSI); EMLRTPUSHRTSTACK(&qc_emlrtRSI); EMLRTPUSHRTSTACK(&rc_emlrtRSI); float_colon_length(1.0, 1.0, nTP, &n, &x, &prop, &innerDimOk); EMLRTPUSHRTSTACK(&sc_emlrtRSI); if (!innerDimOk) { } else { EMLRTPUSHRTSTACK(&pc_emlrtRSI); i_y = NULL; m0 = mxCreateCharArray(2, iv9); emlrtInitCharArray(21, m0, cv4); emlrtAssign(&i_y, m0); error(message(i_y, &ab_emlrtMCI), &bb_emlrtMCI); EMLRTPOPRTSTACK(&pc_emlrtRSI); } EMLRTPOPRTSTACK(&sc_emlrtRSI); emlrtNonNegativeCheckR2009b((real_T)n, &d_emlrtDCI); i0 = C->size[0] * C->size[1]; C->size[0] = 1; C->size[1] = n; emxEnsureCapacity((emxArray__common *)C, i0, (int32_T)sizeof(real_T), &d_emlrtRTEI); if (n > 0) { emlrtDynamicBoundsCheck(1, 1, C->size[1], &fb_emlrtBCI); C->data[0] = x; if (n > 1) { C->data[emlrtDynamicBoundsCheck(n, 1, C->size[1], &ac_emlrtBCI) - 1] = prop; ixstart = n - 1; i0 = ixstart; nm1d2 = (int32_T)((uint32_T)i0 >> 1); for (b_k = 1; b_k <= nm1d2 - 1; b_k++) { C->data[emlrtDynamicBoundsCheck(b_k + 1, 1, C->size[1], &ec_emlrtBCI) - 1] = x + (real_T)b_k; C->data[emlrtDynamicBoundsCheck(n - b_k, 1, C->size[1], &fc_emlrtBCI) - 1] = prop - (real_T)b_k; } if (nm1d2 << 1 == ixstart) { C->data[emlrtDynamicBoundsCheck(nm1d2 + 1, 1, C->size[1], &dc_emlrtBCI) - 1] = (x + prop) / 2.0; } else { C->data[emlrtDynamicBoundsCheck(nm1d2 + 1, 1, C->size[1], &bc_emlrtBCI) - 1] = x + (real_T)nm1d2; C->data[emlrtDynamicBoundsCheck(nm1d2 + 2, 1, C->size[1], &cc_emlrtBCI) - 1] = prop - (real_T)nm1d2; } } } emxInit_real_T(&x_activation, 2, &emlrtRTEI, TRUE); EMLRTPOPRTSTACK(&rc_emlrtRSI); EMLRTPOPRTSTACK(&qc_emlrtRSI); EMLRTPUSHRTSTACK(&tc_emlrtRSI); i0 = x_activation->size[0] * x_activation->size[1]; x_activation->size[0] = activation->size[0]; x_activation->size[1] = activation->size[1]; emxEnsureCapacity((emxArray__common *)x_activation, i0, (int32_T)sizeof(real_T), &emlrtRTEI); loop_ub = activation->size[0] * activation->size[1] - 1; for (i0 = 0; i0 <= loop_ub; i0++) { x_activation->data[i0] = activation->data[i0]; } interp1_work(x_activation, C, iCritical, activation); EMLRTPOPRTSTACK(&tc_emlrtRSI); EMLRTPOPRTSTACK(&r_emlrtRSI); emxFree_real_T(&x_activation); emxFree_real_T(&C); emxFree_real_T(&iCritical); emlrtHeapReferenceStackLeaveFcn(); } /* End of code generation (epu_n_unit_accumulator.c) */
59.727479
353
0.539912
[ "vector", "model", "transform" ]
9ceeb740d6aae3b72ea67d6333ae44473cafeff1
354
h
C
app/src/main/cpp/torch/csrc/jit/import_method.h
cedrickchee/pytorch-android
5568dcd5fdbbb4e1eac050b9a9c8080fc3696daa
[ "MIT" ]
109
2018-11-03T15:11:51.000Z
2022-01-06T05:34:35.000Z
app/src/main/cpp/torch/csrc/jit/import_method.h
Pandinosaurus/pytorch-android
5568dcd5fdbbb4e1eac050b9a9c8080fc3696daa
[ "MIT" ]
7
2019-01-04T01:49:09.000Z
2019-10-16T06:46:31.000Z
app/src/main/cpp/torch/csrc/jit/import_method.h
Pandinosaurus/pytorch-android
5568dcd5fdbbb4e1eac050b9a9c8080fc3696daa
[ "MIT" ]
23
2019-01-19T16:34:19.000Z
2021-07-08T01:16:17.000Z
#pragma once #include <torch/csrc/jit/ir.h> #include <torch/csrc/jit/script/module.h> #include <torch/csrc/jit/script/compiler.h> namespace torch { namespace jit { TORCH_API void import_methods(const std::shared_ptr<script::Module>& mod, const std::string& src, const std::vector<at::Tensor>& constant_table); } // namespace jit } // namespace torch
25.285714
145
0.742938
[ "vector" ]
9cf2b5f317bb5b27b647d7fe940d2ef639e8e845
2,729
h
C
win/devkit/plug-ins/MetadataSample/tweakMetadataNode.h
leegoonz/Maya-devkit
b81fe799b58e854e4ef16435426d60446e975871
[ "ADSL" ]
10
2018-03-30T16:09:02.000Z
2021-12-07T07:29:19.000Z
win/devkit/plug-ins/MetadataSample/tweakMetadataNode.h
leegoonz/Maya-devkit
b81fe799b58e854e4ef16435426d60446e975871
[ "ADSL" ]
null
null
null
win/devkit/plug-ins/MetadataSample/tweakMetadataNode.h
leegoonz/Maya-devkit
b81fe799b58e854e4ef16435426d60446e975871
[ "ADSL" ]
9
2018-06-02T09:18:49.000Z
2021-12-20T09:24:35.000Z
// // File: tweakMetadataNode.h // // Description: // Example implementation of a node which takes in a mesh geometry // and modifies the metadata inside it in a manner // described by the "operation" attribute. // // To test the node, use the following Python commands /* import maya.cmds as cmds cmds.loadPlugin( 'metadataPlugin' ) tweakStruct = cmds.dataStructure( format='raw', asString='name=TweakStructure:int32=value' ) tweak = cmds.createNode( 'tweakMetadata' ) (xform, creator) = cmds.polyPlane( name='testPlane' ) shape = cmds.listRelatives( xform, children=True )[0] cmds.connectAttr( '%s.outMesh' % creator, '%s.inMesh' % tweak ) cmds.disconnectAttr( '%s.outMesh' % creator, '%s.inMesh' % shape ) cmds.connectAttr( '%s.outMesh' % tweak, '%s.inMesh' % shape ) cmds.setAttr( '%s.operation' % tweak, 1 ) cmds.exportMetadata( shape ) // // Output should show a set of metadata channels with random numbers // // Play around with the subdivision on "polyPlane" to generate // different metadata as component counts change. // // Notice that every evaluation causes a different set of random // numbers to be generated. To keep consistency with your metadata // you have to follow the DG principle of "the same inputs will // produce the same outputs". Try adding a random seed to this // example node to make the random numbers reproducible. // */ #include <maya/MPxNode.h> class tweakMetadataNode : public MPxNode { public: tweakMetadataNode (); virtual ~tweakMetadataNode (); static void* creator (); static MStatus initialize (); static const char* nodeName (); // Tweak function // virtual MStatus compute ( const MPlug&, MDataBlock&); // Types of operations this node can perform // enum eOpTypes { kOpNone, kOpRandomize, kOpFill, kOpDouble }; public: // Node attributes static MObject aOperation; static MObject aInMesh; static MObject aOutMesh; // This has to be globally unique or it could cause problems with file I/O static MTypeId id; private: }; //- // ================================================================== // Copyright 2012 Autodesk, Inc. All rights reserved. // // This computer source code and related instructions and comments are // the unpublished confidential and proprietary information of Autodesk, // Inc. and are protected under applicable copyright and trade secret // law. They may not be disclosed to, copied or used by any third party // without the prior written consent of Autodesk, Inc. // ================================================================== //+
34.1125
76
0.648589
[ "mesh", "geometry", "shape" ]
9cf34ab84aa3042479e465a971a1c41e31877070
9,680
c
C
ext/splash2x/kernels/cholesky/src/amal.c
manggoguy/parsec-modified
d14edfb62795805c84a4280d67b50cca175b95af
[ "BSD-3-Clause" ]
null
null
null
ext/splash2x/kernels/cholesky/src/amal.c
manggoguy/parsec-modified
d14edfb62795805c84a4280d67b50cca175b95af
[ "BSD-3-Clause" ]
null
null
null
ext/splash2x/kernels/cholesky/src/amal.c
manggoguy/parsec-modified
d14edfb62795805c84a4280d67b50cca175b95af
[ "BSD-3-Clause" ]
null
null
null
#line 233 "./parmacs.pthreads.c.m4" #line 1 "amal.C" /*************************************************************************/ /* */ /* Copyright (c) 1994 Stanford University */ /* */ /* All rights reserved. */ /* */ /* Permission is given to use, copy, and modify this software for any */ /* non-commercial purpose as long as this copyright notice is not */ /* removed. All other uses, including redistribution in whole or in */ /* part, are forbidden without prior written permission. */ /* */ /* This software is provided with absolutely no warranty and no */ /* support. */ /* */ /*************************************************************************/ #line 17 #include <pthread.h> #line 17 #include <sys/time.h> #line 17 #include <unistd.h> #line 17 #include <stdlib.h> #line 17 extern pthread_t PThreadTable[]; #line 17 #include <stdio.h> #include "matrix.h" long *next_in_super, *member_of, *super_parent; long *tree_firstchild, *tree_sibling; long *tree_original_firstchild, *tree_original_sibling; long ops_added; double *crit; extern long *INVP; long OpsFromSuper(long size, long nz) { long ops = 0; ops += size*(size+1)*(2*size+1)/6; ops += size*size*(nz-size); ops += 2*size*(nz-size)*(nz-size+1)/2; return(ops); } long CountSupers(long cols, long *node) { long i, supers; supers = 0; for (i=0; i<cols; i+=node[i]) supers++; return(supers); } void Amalgamate2(long join, SMatrix M, long *T, long *nz, long *node, long *domain, long target_size) { long i, j; long counter, supers_before, supers_after; double g_ops_before; extern double *work_tree; extern long *PERM, *firstchild, *child; tree_firstchild = (long *) malloc((M.n+1)*sizeof(long)); tree_sibling = (long *) malloc((M.n+1)*sizeof(long)); tree_original_firstchild = (long *) malloc((M.n+1)*sizeof(long)); tree_original_sibling = (long *) malloc((M.n+1)*sizeof(long)); next_in_super = (long *) malloc((M.n+1)*sizeof(long)); member_of = (long *) malloc((M.n+1)*sizeof(long)); super_parent = (long *) malloc((M.n+1)*sizeof(long)); for (i=0; i<=M.n; i++) tree_firstchild[i] = -1; /* link supernodes in child, sibling tree */ for (i=0; i<M.n; i+=node[i]) { super_parent[i] = T[i+node[i]-1]; tree_sibling[i] = tree_firstchild[super_parent[i]]; tree_firstchild[super_parent[i]] = i; } super_parent[M.n] = M.n; for (i=0; i<=M.n; i++) { tree_original_firstchild[i] = tree_firstchild[i]; tree_original_sibling[i] = tree_sibling[i]; } /* link nodes within supernodes */ for (i=0; i<M.n; i+=node[i]) { for (j=i; j<i+node[i]; j++) { next_in_super[j] = j+1; member_of[j] = i; } next_in_super[i+node[i]-1] = -1; } member_of[M.n] = M.n; supers_before = CountSupers(M.n, node); ops_added = 0; g_ops_before = work_tree[M.n]; i = tree_original_firstchild[M.n]; while (i != -1) { ConsiderMerge(join, i, M, nz, node, domain, target_size, 1); i = tree_original_sibling[i]; } counter = M.n; ReorderMatrix(M, M.n, node, &counter, PERM); InvertPerm(M.n, PERM, INVP); FixNodeNZAndT(M, PERM, node, nz, T); free(tree_firstchild); free(tree_sibling); free(tree_original_firstchild); free(tree_original_sibling); free(next_in_super); free(member_of); free(super_parent); ParentToChild(T, M.n, firstchild, child); ComputeWorkTree(M, nz, work_tree); supers_after = CountSupers(M.n, node); printf("%ld/%ld supers before/after\n", supers_before, supers_after); printf("%.0f/%.0f (%.2f) ops before/after amalgamation\n", g_ops_before, work_tree[M.n], work_tree[M.n]/(double) g_ops_before); if (ops_added != work_tree[M.n]-g_ops_before) printf("Model says %ld ops added, really %.0f\n", ops_added, work_tree[M.n]-g_ops_before); } void ConsiderMerge(long join, long super, SMatrix M, long *nz, long *node, long *domain, long target_size, long traversal_order) { long i, parent; long ops_before, ops_after, do_merge, do_merge_simple, possible; long allow_critical_to_grow; double time_before, time_after, dummy, simple_diff; double path_grows; super = member_of[super]; /* merge until no longer profitable */ for (;;) { if (super_parent[super] == M.n) break; parent = super_parent[super]; ops_before = OpsFromSuper(node[super], nz[super]); ops_after = OpsFromSuper(node[super], nz[parent]+node[super]); time_before = 0; PDIV(node[super], nz[super], &dummy, &dummy, &time_before); PMOD(node[super], nz[super]-node[super], nz[super]-node[super], &dummy, &dummy, &time_before); PADD(nz[super]-node[super], nz[super]-node[super], &dummy, &time_before); PDIV(node[parent], nz[parent], &dummy, &dummy, &time_before); PMOD(node[parent], nz[parent]-node[parent], nz[parent]-node[parent], &dummy, &dummy, &time_before); PADD(nz[parent]-node[parent], nz[parent]-node[parent], &dummy, &time_before); time_after = 0; PDIV(node[super]+node[parent], node[super]+nz[parent], &dummy, &dummy, &time_after); PMOD(node[super]+node[parent], nz[parent]-node[parent], nz[parent]-node[parent], &dummy, &dummy, &time_after); PADD(nz[parent]-node[parent], nz[parent]-node[parent], &dummy, &time_after); simple_diff = (ops_after-ops_before) - 5.0*3*(nz[super]-node[super])*(nz[super]-node[super]+1)/2; possible = (!domain || domain[super] == 0 || domain[parent] != 0); allow_critical_to_grow = 1; if ((!domain || domain[super] == 0) && time_before > time_after) { if (allow_critical_to_grow) path_grows = 0; } else path_grows = 0.0; do_merge = (possible && time_before > time_after && path_grows == 0.0); do_merge_simple = (possible && simple_diff < 0); if (do_merge) { JoinTwoSupers2(nz, node, super, parent); ops_added += (ops_after-ops_before); } else break; } i = tree_original_firstchild[super]; while (i != -1) { ConsiderMerge(join, i, M, nz, node, domain, target_size, traversal_order); i = tree_original_sibling[i]; } } void JoinTwoSupers2(long *nz, long *node, long child, long parent) { long i, child_last, member, grandparent; /* record new memberships */ member = parent; while (member != -1) { member_of[member] = child; member = next_in_super[member]; } /* find last member of child */ child_last = child; while (next_in_super[child_last] != -1) child_last = next_in_super[child_last]; /* link in nodes in parent */ next_in_super[child_last] = parent; /* adjust sizes */ nz[child] = nz[parent]+node[child]; node[child] += node[parent]; /* adjust child parent */ super_parent[child] = super_parent[parent]; /* children of 'parent' become children of 'child' */ while (tree_firstchild[parent] != -1) { i = tree_firstchild[parent]; tree_firstchild[parent] = tree_sibling[i]; if (member_of[i] != child) { super_parent[member_of[i]] = child; tree_sibling[i] = tree_firstchild[child]; tree_firstchild[child] = i; } } /* siblings of 'parent' become siblings of 'child' */ grandparent = super_parent[parent]; tree_sibling[child] = tree_sibling[parent]; i = tree_firstchild[grandparent]; if (i == parent) tree_firstchild[grandparent] = child; else { while (tree_sibling[i] != parent) i = tree_sibling[i]; tree_sibling[i] = child; } } void ReorderMatrix(SMatrix M, long super, long *node, long *counter, long *PERM) { long child, member, which_member; if (super != M.n) { super = member_of[super]; member = super; which_member = 0; while (member != -1) { PERM[*counter-node[super]+which_member] = member; member = next_in_super[member]; which_member++; } *counter -= node[super]; } child = tree_firstchild[super]; while (child != -1) { ReorderMatrix(M, child, node, counter, PERM); child = tree_sibling[child]; } } void FixNodeNZAndT(SMatrix M, long *PERM, long *node, long *nz, long *T) { long super, j; long *tmp; tmp = (long *) malloc(M.n*sizeof(long)); for (j=0; j<M.n; j++) tmp[j] = node[j]; for (j=0; j<M.n; j++) node[j] = tmp[PERM[j]]; for (super=0; super<M.n; super+=node[super]) for (j=super+1; j<super+node[super]; j++) node[j] = super-j; for (j=0; j<M.n; j++) tmp[j] = nz[j]; for (super=0; super<M.n; super+=node[super]) { nz[super] = tmp[PERM[super]]; for (j=super+1; j<super+node[super]; j++) nz[j] = nz[super]+super-j; } for (super=0; super<M.n; super+=node[super]) { for (j=super; j<super+node[super]; j++) T[j] = j+1; T[super+node[super]-1] = INVP[super_parent[PERM[super]]]; } free(tmp); } void InvertPerm(long n, long *PERM, long *INVP) { long i; for (i=0; i<=n; i++) INVP[i] = -1; for (i=0; i<=n; i++) INVP[PERM[i]] = i; for (i=0; i<=n; i++) if (INVP[i] == -1) printf("Not a valid permutation\n"); } double PathLength(long cols, long rows, long target_panel_size) { double path_length; path_length = 3*(cols*rows-cols*(cols-1)/2); path_length *= target_panel_size; return(path_length); }
27.816092
128
0.592769
[ "model" ]
9cfd371ad13aa63800843afacef5d881a6a760c8
756
h
C
DXMUI/Parser/Markup/MarkupBuilder.h
Ulvmane/DXMUI
999d30c1d21777f382cbf37d7aa2c701d5951ac3
[ "MIT" ]
null
null
null
DXMUI/Parser/Markup/MarkupBuilder.h
Ulvmane/DXMUI
999d30c1d21777f382cbf37d7aa2c701d5951ac3
[ "MIT" ]
null
null
null
DXMUI/Parser/Markup/MarkupBuilder.h
Ulvmane/DXMUI
999d30c1d21777f382cbf37d7aa2c701d5951ac3
[ "MIT" ]
null
null
null
#pragma once #include "Canvas\Canvas.h" #include "Canvas\ICanvasElement.h" #include <vector> namespace DXMUI { class DXMBuilder { public: DXMBuilder(); Canvas Build(); void DivAppend(const int aDepth, std::string& aID, ICanvasElement* aElementToAppend); void AddNode(); void Clear(); private: struct NodeContent { std::string myID; ICanvasElement* myElement; std::vector<NodeContent> myChildren; }; struct DXMBuildNode { DXMBuildNode* myChild = nullptr; NodeContent myContent; } myRoot; private: void GenerateContent(NodeContent* aContent, std::vector<std::shared_ptr<DXMUI::ICanvasElement>>& aElems, std::vector<std::string>& aIDs); void Clear(DXMBuildNode* toClear); DXMBuildNode* myTail; }; }
19.894737
139
0.708995
[ "vector" ]
1403c44b88841b910a75d70bc93b69edbc1c4374
1,723
h
C
jage/Shader.h
Rexagon/jage
560457b382fb250f3c5c385f45590c0537e2e9b8
[ "Apache-2.0" ]
1
2019-12-23T09:27:16.000Z
2019-12-23T09:27:16.000Z
jage/Shader.h
Rexagon/jage
560457b382fb250f3c5c385f45590c0537e2e9b8
[ "Apache-2.0" ]
null
null
null
jage/Shader.h
Rexagon/jage
560457b382fb250f3c5c385f45590c0537e2e9b8
[ "Apache-2.0" ]
null
null
null
#pragma once #include <string> #include <vector> #include <map> #include <GL/glew.h> #include "Math.h" class Shader { public: Shader(); ~Shader(); void bind(); bool attachPart(const std::string& source, GLenum type, std::string& infoLog); bool link(std::string& infoLog); void setAttribute(unsigned int index, const std::string& name); void setUniform(const std::string& name, int data); void setUniform(const std::string& name, float data); void setUniform(const std::string& name, const vec2& data); void setUniform(const std::string& name, const ivec2& data); void setUniform(const std::string& name, const vec3& data); void setUniform(const std::string& name, const ivec3& data); void setUniform(const std::string& name, const vec4& data); void setUniform(const std::string& name, const ivec4& data); void setUniform(const std::string& name, const mat4& data); void setUniformArray(const std::string& name, int* data, int size); void setUniformArray(const std::string& name, float* data, int size); void setUniformArray(const std::string& name, vec2* data, int size); void setUniformArray(const std::string& name, ivec2* data, int size); void setUniformArray(const std::string& name, vec3* data, int size); void setUniformArray(const std::string& name, ivec3* data, int size); void setUniformArray(const std::string& name, vec4* data, int size); void setUniformArray(const std::string& name, ivec4* data, int size); void setUniformArray(const std::string& name, mat4* data, int size); unsigned int getUniformLocation(const std::string& name); GLuint getHandle() const; private: GLuint m_program; std::vector<GLint> m_shaders; std::map<std::string, GLint> m_uniformLocations; };
32.509434
79
0.732443
[ "vector" ]
140773fd158744712dbcc59ecaf33137919d9ce0
4,780
h
C
src/core/random.h
accosmin/zob
9e840894ffd6ab718fa800aca67e4a25e941e546
[ "MIT" ]
6
2015-04-14T19:42:38.000Z
2015-11-12T17:41:35.000Z
src/core/random.h
cyy1991/nano
9e840894ffd6ab718fa800aca67e4a25e941e546
[ "MIT" ]
93
2015-04-10T19:02:38.000Z
2016-03-09T17:56:16.000Z
src/core/random.h
accosmin/zob
9e840894ffd6ab718fa800aca67e4a25e941e546
[ "MIT" ]
2
2015-05-27T16:42:31.000Z
2015-08-21T14:39:55.000Z
#pragma once #include <random> #include <cassert> #include <numeric> #include <algorithm> #include <type_traits> namespace nano { using rng_t = std::minstd_rand; template <typename tscalar, typename = typename std::is_arithmetic<tscalar>::type> using udist_t = typename std::conditional< std::is_integral<tscalar>::value, std::uniform_int_distribution<tscalar>, std::uniform_real_distribution<tscalar>>::type; /// /// \brief create & initialize a random number generator. /// inline auto make_rng() { // todo: use seed_seq to initialize the RNG (see C++17) return rng_t{std::random_device{}()}; } /// /// \brief create an uniform distribution for the [min, max] range. /// template <typename tscalar, typename = typename std::is_arithmetic<tscalar>::type> inline auto make_udist(const tscalar min, const tscalar max) { assert(min <= max); return udist_t<tscalar>(min, max); } /// /// \brief generate a random value uniformaly distributed in the [min, max] range. /// template <typename tscalar, typename trng, typename = typename std::is_arithmetic<tscalar>::type> tscalar urand(const tscalar min, const tscalar max, trng&& rng) { auto udist = make_udist<tscalar>(min, max); return udist(rng); } /// /// \brief fill the [begin, range) range of elements with random values uniformaly distributed in the [min, max] range. /// template <typename tscalar, typename titerator, typename trng, typename = typename std::is_arithmetic<tscalar>::type> void urand(const tscalar min, const tscalar max, titerator begin, const titerator end, trng&& rng) { auto udist = make_udist<tscalar>(min, max); for ( ; begin != end; ++ begin) { *begin = udist(rng); } } /// /// \brief add to the [begin, range) range of elements random values uniformaly distributed in the [min, max] range. /// template <typename tscalar, typename titerator, typename trng, typename = typename std::is_arithmetic<tscalar>::type> void add_urand(const tscalar min, const tscalar max, titerator begin, const titerator end, trng&& rng) { auto udist = make_udist<tscalar>(min, max); for ( ; begin != end; ++ begin) { *begin += udist(rng); } } /// /// \brief randomly split count elements in percentage_value1% having value1 and the rest value2. /// template <typename tvalue> auto split2(const size_t count, const tvalue value1, const size_t percentage_value1, const tvalue value2) { assert(percentage_value1 <= 100); const auto begin0 = size_t(0); const auto begin1 = begin0 + count * percentage_value1 / 100; const auto begin2 = count; std::vector<tvalue> values(count); std::fill(values.begin() + begin0, values.begin() + begin1, value1); std::fill(values.begin() + begin1, values.begin() + begin2, value2); std::shuffle(values.begin(), values.end(), make_rng()); return values; } /// /// \brief randomly split count elements in percentage_value1% having value1, /// percentage_value2% having value2 and the rest value3. /// template <typename tvalue> auto split3(const size_t count, const tvalue value1, const size_t percentage_value1, const tvalue value2, const size_t percentage_value2, const tvalue value3) { assert(percentage_value1 + percentage_value2 <= 100); const auto begin0 = size_t(0); const auto begin1 = begin0 + count * percentage_value1 / 100; const auto begin2 = begin1 + count * percentage_value2 / 100; const auto begin3 = count; std::vector<tvalue> values(count); std::fill(values.begin() + begin0, values.begin() + begin1, value1); std::fill(values.begin() + begin1, values.begin() + begin2, value2); std::fill(values.begin() + begin2, values.begin() + begin3, value3); std::shuffle(values.begin(), values.end(), make_rng()); return values; } }
39.180328
127
0.556695
[ "vector" ]
140a460b2acb7865463ff8ffe39b3fbc4fbb58e3
114,028
c
C
drivers/video/msm/mdss/mdss_hdmi_tx.c
cesarmo759/android_kernel_samsung_msm8916
f19717ef6c984b64a75ea600a735dc937b127c25
[ "Apache-2.0" ]
1
2020-06-28T00:49:21.000Z
2020-06-28T00:49:21.000Z
drivers/video/msm/mdss/mdss_hdmi_tx.c
cesarmo759/android_kernel_samsung_msm8916
f19717ef6c984b64a75ea600a735dc937b127c25
[ "Apache-2.0" ]
null
null
null
drivers/video/msm/mdss/mdss_hdmi_tx.c
cesarmo759/android_kernel_samsung_msm8916
f19717ef6c984b64a75ea600a735dc937b127c25
[ "Apache-2.0" ]
1
2021-03-05T16:54:52.000Z
2021-03-05T16:54:52.000Z
/* Copyright (c) 2010-2014,2016 The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/bitops.h> #include <linux/delay.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/iopoll.h> #include <linux/of_address.h> #include <linux/of_gpio.h> #include <linux/of_platform.h> #include <linux/types.h> #include <linux/msm_hdmi.h> #define REG_DUMP 0 #include "mdss_debug.h" #include "mdss_fb.h" #include "mdss_hdmi_cec.h" #include "mdss_hdmi_edid.h" #include "mdss_hdmi_hdcp.h" #include "mdss_hdmi_tx.h" #include "mdss.h" #include "mdss_panel.h" #include "mdss_hdmi_mhl.h" #define DRV_NAME "hdmi-tx" #define COMPATIBLE_NAME "qcom,hdmi-tx" #define DEFAULT_VIDEO_RESOLUTION HDMI_VFRMT_640x480p60_4_3 #define DEFAULT_HDMI_PRIMARY_RESOLUTION HDMI_VFRMT_1280x720p60_16_9 /* HDMI PHY/PLL bit field macros */ #define SW_RESET BIT(2) #define SW_RESET_PLL BIT(0) #define HPD_DISCONNECT_POLARITY 0 #define HPD_CONNECT_POLARITY 1 /* * Audio engine may take 1 to 3 sec to shutdown * in normal cases. To handle worst cases, making * timeout for audio engine shutdown as 5 sec. */ #define AUDIO_POLL_SLEEP_US (5 * 1000) #define AUDIO_POLL_TIMEOUT_US (AUDIO_POLL_SLEEP_US * 1000) #define LPA_DMA_IDLE_MAX 200 #define IFRAME_CHECKSUM_32(d) \ ((d & 0xff) + ((d >> 8) & 0xff) + \ ((d >> 16) & 0xff) + ((d >> 24) & 0xff)) /* Enable HDCP by default */ static bool hdcp_feature_on = true; /* Supported HDMI Audio channels */ #define MSM_HDMI_AUDIO_CHANNEL_2 2 #define MSM_HDMI_AUDIO_CHANNEL_3 3 #define MSM_HDMI_AUDIO_CHANNEL_4 4 #define MSM_HDMI_AUDIO_CHANNEL_5 5 #define MSM_HDMI_AUDIO_CHANNEL_6 6 #define MSM_HDMI_AUDIO_CHANNEL_7 7 #define MSM_HDMI_AUDIO_CHANNEL_8 8 /* AVI INFOFRAME DATA */ #define NUM_MODES_AVI 20 #define AVI_MAX_DATA_BYTES 13 enum { DATA_BYTE_1, DATA_BYTE_2, DATA_BYTE_3, DATA_BYTE_4, DATA_BYTE_5, DATA_BYTE_6, DATA_BYTE_7, DATA_BYTE_8, DATA_BYTE_9, DATA_BYTE_10, DATA_BYTE_11, DATA_BYTE_12, DATA_BYTE_13, }; #define IFRAME_PACKET_OFFSET 0x80 /* * InfoFrame Type Code: * 0x0 - Reserved * 0x1 - Vendor Specific * 0x2 - Auxiliary Video Information * 0x3 - Source Product Description * 0x4 - AUDIO * 0x5 - MPEG Source * 0x6 - NTSC VBI * 0x7 - 0xFF - Reserved */ #define AVI_IFRAME_TYPE 0x2 #define AVI_IFRAME_VERSION 0x2 #define LEFT_SHIFT_BYTE(x) ((x) << 8) #define LEFT_SHIFT_WORD(x) ((x) << 16) #define LEFT_SHIFT_24BITS(x) ((x) << 24) /* AVI Infoframe data byte 3, bit 7 (msb) represents ITC bit */ #define SET_ITC_BIT(byte) (byte = (byte | BIT(7))) #define CLR_ITC_BIT(byte) (byte = (byte & ~BIT(7))) /* * CN represents IT content type, if ITC bit in infoframe data byte 3 * is set, CN bits will represent content type as below: * 0b00 Graphics * 0b01 Photo * 0b10 Cinema * 0b11 Game */ #define CONFIG_CN_BITS(bits, byte) \ (byte = (byte & ~(BIT(4) | BIT(5))) |\ ((bits & (BIT(0) | BIT(1))) << 4)) enum msm_hdmi_supported_audio_sample_rates { AUDIO_SAMPLE_RATE_32KHZ, AUDIO_SAMPLE_RATE_44_1KHZ, AUDIO_SAMPLE_RATE_48KHZ, AUDIO_SAMPLE_RATE_88_2KHZ, AUDIO_SAMPLE_RATE_96KHZ, AUDIO_SAMPLE_RATE_176_4KHZ, AUDIO_SAMPLE_RATE_192KHZ, AUDIO_SAMPLE_RATE_MAX }; enum hdmi_tx_hpd_states { HPD_OFF, HPD_ON, HPD_ON_CONDITIONAL_MTP, HPD_DISABLE, HPD_ENABLE }; enum hdmi_tx_res_states { RESOLUTION_UNCHANGED, RESOLUTION_CHANGED }; /* parameters for clock regeneration */ struct hdmi_tx_audio_acr { u32 n; u32 cts; }; struct hdmi_tx_audio_acr_arry { u32 pclk; struct hdmi_tx_audio_acr lut[AUDIO_SAMPLE_RATE_MAX]; }; static int hdmi_tx_set_mhl_hpd(struct platform_device *pdev, uint8_t on); static int hdmi_tx_sysfs_enable_hpd(struct hdmi_tx_ctrl *hdmi_ctrl, int on); static irqreturn_t hdmi_tx_isr(int irq, void *data); static void hdmi_tx_hpd_off(struct hdmi_tx_ctrl *hdmi_ctrl); static int hdmi_tx_enable_power(struct hdmi_tx_ctrl *hdmi_ctrl, enum hdmi_tx_power_module_type module, int enable); static int hdmi_tx_audio_setup(struct hdmi_tx_ctrl *hdmi_ctrl); static struct mdss_hw hdmi_tx_hw = { .hw_ndx = MDSS_HW_HDMI, .ptr = NULL, .irq_handler = hdmi_tx_isr, }; static struct dss_gpio hpd_gpio_config[] = { {0, 1, COMPATIBLE_NAME "-hpd"}, {0, 1, COMPATIBLE_NAME "-mux-en"}, {0, 0, COMPATIBLE_NAME "-mux-sel"}, {0, 1, COMPATIBLE_NAME "-mux-lpm"} }; static struct dss_gpio ddc_gpio_config[] = { {0, 1, COMPATIBLE_NAME "-ddc-mux-sel"}, {0, 1, COMPATIBLE_NAME "-ddc-clk"}, {0, 1, COMPATIBLE_NAME "-ddc-data"} }; static struct dss_gpio core_gpio_config[] = { }; static struct dss_gpio cec_gpio_config[] = { {0, 1, COMPATIBLE_NAME "-cec"} }; const char *hdmi_pm_name(enum hdmi_tx_power_module_type module) { switch (module) { case HDMI_TX_HPD_PM: return "HDMI_TX_HPD_PM"; case HDMI_TX_DDC_PM: return "HDMI_TX_DDC_PM"; case HDMI_TX_CORE_PM: return "HDMI_TX_CORE_PM"; case HDMI_TX_CEC_PM: return "HDMI_TX_CEC_PM"; default: return "???"; } } /* hdmi_pm_name */ /* * 13 Bytes of AVI infoframe data wrt each resolution * Data Byte 01: 0 Y1 Y0 A0 B1 B0 S1 S0 * Data Byte 02: C1 C0 M1 M0 R3 R2 R1 R0 * Data Byte 03: ITC EC2 EC1 EC0 Q1 Q0 SC1 SC0 * Data Byte 04: 0 VIC6 VIC5 VIC4 VIC3 VIC2 VIC1 VIC0 * Data Byte 05: 0 0 0 0 PR3 PR2 PR1 PR0 * Data Byte 06: LSB Line No of End of Top Bar * Data Byte 07: MSB Line No of End of Top Bar * Data Byte 08: LSB Line No of Start of Bottom Bar * Data Byte 09: MSB Line No of Start of Bottom Bar * Data Byte 10: LSB Pixel Number of End of Left Bar * Data Byte 11: MSB Pixel Number of End of Left Bar * Data Byte 12: LSB Pixel Number of Start of Right Bar * Data Byte 13: MSB Pixel Number of Start of Right Bar */ static u8 hdmi_tx_avi_iframe_lut[HDMI_EVFRMT_END + 1][AVI_MAX_DATA_BYTES] = { [HDMI_VFRMT_720x480p60_4_3] = { 0x10, 0x18, 0x00, 0x02, 0x00, 0x00, 0x00, 0xE1, 0x01, 0x00, 0x00, 0xD1, 0x02}, [HDMI_VFRMT_720x480i60_16_9] = { 0x10, 0x18, 0x00, 0x07, 0x01, 0x00, 0x00, 0xE1, 0x01, 0x00, 0x00, 0xD1, 0x02}, [HDMI_VFRMT_720x576p50_16_9] = { 0x10, 0x28, 0x00, 0x12, 0x00, 0x00, 0x00, 0x41, 0x02, 0x00, 0x00, 0xD1, 0x02}, [HDMI_VFRMT_720x576i50_16_9] = { 0x10, 0x28, 0x00, 0x16, 0x01, 0x00, 0x00, 0x41, 0x02, 0x00, 0x00, 0xD1, 0x02}, [HDMI_VFRMT_1280x720p60_16_9] = { 0x10, 0x28, 0x00, 0x04, 0x00, 0x00, 0x00, 0xD1, 0x02, 0x00, 0x00, 0x01, 0x05}, [HDMI_VFRMT_1280x720p50_16_9] = { 0x10, 0x28, 0x00, 0x13, 0x00, 0x00, 0x00, 0xD1, 0x02, 0x00, 0x00, 0x01, 0x05}, [HDMI_VFRMT_1920x1080p60_16_9] = { 0x10, 0x28, 0x00, 0x10, 0x00, 0x00, 0x00, 0x39, 0x04, 0x00, 0x00, 0x81, 0x07}, [HDMI_VFRMT_1920x1080i60_16_9] = { 0x10, 0x28, 0x00, 0x05, 0x00, 0x00, 0x00, 0x39, 0x04, 0x00, 0x00, 0x81, 0x07}, [HDMI_VFRMT_1920x1080p50_16_9] = { 0x10, 0x28, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x39, 0x04, 0x00, 0x00, 0x81, 0x07}, [HDMI_VFRMT_1920x1080i50_16_9] = { 0x10, 0x28, 0x00, 0x14, 0x00, 0x00, 0x00, 0x39, 0x04, 0x00, 0x00, 0x81, 0x07}, [HDMI_VFRMT_1920x1080p24_16_9] = { 0x10, 0x28, 0x00, 0x20, 0x00, 0x00, 0x00, 0x39, 0x04, 0x00, 0x00, 0x81, 0x07}, [HDMI_VFRMT_1920x1080p30_16_9] = { 0x10, 0x28, 0x00, 0x22, 0x00, 0x00, 0x00, 0x39, 0x04, 0x00, 0x00, 0x81, 0x07}, [HDMI_VFRMT_1920x1080p25_16_9] = { 0x10, 0x28, 0x00, 0x21, 0x00, 0x00, 0x00, 0x39, 0x04, 0x00, 0x00, 0x81, 0x07}, [HDMI_VFRMT_640x480p60_4_3] = { 0x10, 0x18, 0x00, 0x01, 0x00, 0x00, 0x00, 0xE1, 0x01, 0x00, 0x00, 0x81, 0x02}, [HDMI_VFRMT_720x480p60_16_9] = { 0x10, 0x28, 0x00, 0x03, 0x00, 0x00, 0x00, 0xE1, 0x01, 0x00, 0x00, 0xD1, 0x02}, [HDMI_VFRMT_720x576p50_4_3] = { 0x10, 0x18, 0x00, 0x11, 0x00, 0x00, 0x00, 0x41, 0x02, 0x00, 0x00, 0xD1, 0x02}, [HDMI_VFRMT_3840x2160p30_16_9] = { 0x10, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x71, 0x08, 0x00, 0x00, 0x01, 0x0F}, [HDMI_VFRMT_3840x2160p25_16_9] = { 0x10, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x71, 0x08, 0x00, 0x00, 0x01, 0x0F}, [HDMI_VFRMT_3840x2160p24_16_9] = { 0x10, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x71, 0x08, 0x00, 0x00, 0x01, 0x0F}, [HDMI_VFRMT_4096x2160p24_16_9] = { 0x10, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x71, 0x08, 0x00, 0x00, 0x01, 0x10} }; /* hdmi_tx_avi_iframe_lut */ /* Audio constants lookup table for hdmi_tx_audio_acr_setup */ /* Valid Pixel-Clock rates: 25.2MHz, 27MHz, 27.03MHz, 74.25MHz, 148.5MHz */ static const struct hdmi_tx_audio_acr_arry hdmi_tx_audio_acr_lut[] = { /* 25.200MHz */ {25200, {{4096, 25200}, {6272, 28000}, {6144, 25200}, {12544, 28000}, {12288, 25200}, {25088, 28000}, {24576, 25200} } }, /* 27.000MHz */ {27000, {{4096, 27000}, {6272, 30000}, {6144, 27000}, {12544, 30000}, {12288, 27000}, {25088, 30000}, {24576, 27000} } }, /* 27.027MHz */ {27027, {{4096, 27027}, {6272, 30030}, {6144, 27027}, {12544, 30030}, {12288, 27027}, {25088, 30030}, {24576, 27027} } }, /* 74.250MHz */ {74250, {{4096, 74250}, {6272, 82500}, {6144, 74250}, {12544, 82500}, {12288, 74250}, {25088, 82500}, {24576, 74250} } }, /* 148.500MHz */ {148500, {{4096, 148500}, {6272, 165000}, {6144, 148500}, {12544, 165000}, {12288, 148500}, {25088, 165000}, {24576, 148500} } }, /* 297.000MHz */ {297000, {{3072, 222750}, {4704, 247500}, {5120, 247500}, {9408, 247500}, {10240, 247500}, {18816, 247500}, {20480, 247500} } }, }; int register_hdmi_cable_notification(struct hdmi_cable_notify *handler) { struct hdmi_tx_ctrl *hdmi_ctrl = NULL; struct list_head *pos; if (!hdmi_tx_hw.ptr) { DEV_WARN("%s: HDMI Tx core not ready\n", __func__); return -EPROBE_DEFER; } if (!handler) { DEV_ERR("%s: Empty handler\n", __func__); return -ENODEV; } hdmi_ctrl = (struct hdmi_tx_ctrl *) hdmi_tx_hw.ptr; mutex_lock(&hdmi_ctrl->cable_notify_mutex); handler->status = hdmi_ctrl->hpd_state; list_for_each(pos, &hdmi_ctrl->cable_notify_handlers); list_add_tail(&handler->link, pos); mutex_unlock(&hdmi_ctrl->cable_notify_mutex); return handler->status; } /* register_hdmi_cable_notification */ int unregister_hdmi_cable_notification(struct hdmi_cable_notify *handler) { struct hdmi_tx_ctrl *hdmi_ctrl = NULL; if (!hdmi_tx_hw.ptr) { DEV_WARN("%s: HDMI Tx core not ready\n", __func__); return -ENODEV; } if (!handler) { DEV_ERR("%s: Empty handler\n", __func__); return -ENODEV; } hdmi_ctrl = (struct hdmi_tx_ctrl *) hdmi_tx_hw.ptr; mutex_lock(&hdmi_ctrl->cable_notify_mutex); list_del(&handler->link); mutex_unlock(&hdmi_ctrl->cable_notify_mutex); return 0; } /* unregister_hdmi_cable_notification */ static void hdmi_tx_cable_notify_work(struct work_struct *work) { struct hdmi_tx_ctrl *hdmi_ctrl = NULL; struct hdmi_cable_notify *pos; hdmi_ctrl = container_of(work, struct hdmi_tx_ctrl, cable_notify_work); if (!hdmi_ctrl) { DEV_ERR("%s: invalid hdmi data\n", __func__); return; } mutex_lock(&hdmi_ctrl->cable_notify_mutex); list_for_each_entry(pos, &hdmi_ctrl->cable_notify_handlers, link) { if (pos->status != hdmi_ctrl->hpd_state) { pos->status = hdmi_ctrl->hpd_state; pos->hpd_notify(pos); } } mutex_unlock(&hdmi_ctrl->cable_notify_mutex); } /* hdmi_tx_cable_notify_work */ static bool hdmi_tx_is_cea_format(int mode) { bool cea_fmt; if ((mode > 0) && (mode <= HDMI_EVFRMT_END)) cea_fmt = true; else cea_fmt = false; DEV_DBG("%s: %s\n", __func__, cea_fmt ? "Yes" : "No"); return cea_fmt; } static inline bool hdmi_tx_is_hdcp_enabled(struct hdmi_tx_ctrl *hdmi_ctrl) { if (hdmi_ctrl->hdcp_feature_on && hdmi_ctrl->present_hdcp) return true; return false; } static const char *hdmi_tx_pm_name(enum hdmi_tx_power_module_type module) { switch (module) { case HDMI_TX_HPD_PM: return "HDMI_TX_HPD_PM"; case HDMI_TX_DDC_PM: return "HDMI_TX_DDC_PM"; case HDMI_TX_CORE_PM: return "HDMI_TX_CORE_PM"; case HDMI_TX_CEC_PM: return "HDMI_TX_CEC_PM"; default: return "???"; } } /* hdmi_tx_pm_name */ static const char *hdmi_tx_io_name(u32 type) { switch (type) { case HDMI_TX_CORE_IO: return "core_physical"; case HDMI_TX_PHY_IO: return "phy_physical"; case HDMI_TX_QFPROM_IO: return "qfprom_physical"; default: return NULL; } } /* hdmi_tx_io_name */ static int hdmi_tx_get_vic_from_panel_info(struct hdmi_tx_ctrl *hdmi_ctrl, struct mdss_panel_info *pinfo) { int new_vic = -1; u32 h_total, v_total; struct msm_hdmi_mode_timing_info timing; if (!hdmi_ctrl || !pinfo) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } if (pinfo->vic) { if (hdmi_get_supported_mode(pinfo->vic)) { new_vic = pinfo->vic; DEV_DBG("%s: %s is supported\n", __func__, msm_hdmi_mode_2string(new_vic)); } else { DEV_ERR("%s: invalid or not supported vic %d\n", __func__, pinfo->vic); return -EPERM; } } else { timing.active_h = pinfo->xres; timing.back_porch_h = pinfo->lcdc.h_back_porch; timing.front_porch_h = pinfo->lcdc.h_front_porch; timing.pulse_width_h = pinfo->lcdc.h_pulse_width; h_total = timing.active_h + timing.back_porch_h + timing.front_porch_h + timing.pulse_width_h; DEV_DBG("%s: ah=%d bph=%d fph=%d pwh=%d ht=%d\n", __func__, timing.active_h, timing.back_porch_h, timing.front_porch_h, timing.pulse_width_h, h_total); timing.active_v = pinfo->yres; timing.back_porch_v = pinfo->lcdc.v_back_porch; timing.front_porch_v = pinfo->lcdc.v_front_porch; timing.pulse_width_v = pinfo->lcdc.v_pulse_width; v_total = timing.active_v + timing.back_porch_v + timing.front_porch_v + timing.pulse_width_v; DEV_DBG("%s: av=%d bpv=%d fpv=%d pwv=%d vt=%d\n", __func__, timing.active_v, timing.back_porch_v, timing.front_porch_v, timing.pulse_width_v, v_total); timing.pixel_freq = pinfo->clk_rate / 1000; if (h_total && v_total) { timing.refresh_rate = ((timing.pixel_freq * 1000) / (h_total * v_total)) * 1000; } else { DEV_ERR("%s: cannot cal refresh rate\n", __func__); return -EPERM; } DEV_DBG("%s: pixel_freq=%d refresh_rate=%d\n", __func__, timing.pixel_freq, timing.refresh_rate); new_vic = hdmi_get_video_id_code(&timing); } return new_vic; } /* hdmi_tx_get_vic_from_panel_info */ static inline u32 hdmi_tx_is_dvi_mode(struct hdmi_tx_ctrl *hdmi_ctrl) { return hdmi_edid_get_sink_mode( hdmi_ctrl->feature_data[HDMI_TX_FEAT_EDID]) ? 0 : 1; } /* hdmi_tx_is_dvi_mode */ static inline void hdmi_tx_send_cable_notification( struct hdmi_tx_ctrl *hdmi_ctrl, int val) { int state = 0; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } state = hdmi_ctrl->sdev.state; switch_set_state(&hdmi_ctrl->sdev, val); DEV_INFO("%s: cable state %s %d\n", __func__, hdmi_ctrl->sdev.state == state ? "is same" : "switched to", hdmi_ctrl->sdev.state); /* Notify all registered modules of cable connection status */ schedule_work(&hdmi_ctrl->cable_notify_work); } /* hdmi_tx_send_cable_notification */ static inline void hdmi_tx_set_audio_switch_node( struct hdmi_tx_ctrl *hdmi_ctrl, int val) { int state = 0; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } state = hdmi_ctrl->audio_sdev.state; if (!hdmi_tx_is_dvi_mode(hdmi_ctrl) && hdmi_tx_is_cea_format(hdmi_ctrl->video_resolution)) { switch_set_state(&hdmi_ctrl->audio_sdev, val); DEV_INFO("%s: audio state %s %d\n", __func__, hdmi_ctrl->audio_sdev.state == state ? "is same" : "switched to", hdmi_ctrl->audio_sdev.state); } } /* hdmi_tx_set_audio_switch_node */ static void hdmi_tx_wait_for_audio_engine(struct hdmi_tx_ctrl *hdmi_ctrl) { u64 status = 0; u32 wait_for_vote = 50; struct dss_io_data *io = NULL; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: core io not inititalized\n", __func__); return; } /* * wait for 5 sec max for audio engine to acknowledge if hdmi tx core * can be safely turned off. Sleep for a reasonable time to make sure * vote_hdmi_core_on variable is updated properly by audio. */ while (hdmi_ctrl->vote_hdmi_core_on && --wait_for_vote) msleep(100); if (!wait_for_vote) DEV_ERR("%s: HDMI core still voted for power on\n", __func__); if (readl_poll_timeout(io->base + HDMI_AUDIO_PKT_CTRL, status, (status & BIT(0)) == 0, AUDIO_POLL_SLEEP_US, AUDIO_POLL_TIMEOUT_US)) DEV_ERR("%s: Error turning off audio packet transmission.\n", __func__); if (readl_poll_timeout(io->base + HDMI_AUDIO_CFG, status, (status & BIT(0)) == 0, AUDIO_POLL_SLEEP_US, AUDIO_POLL_TIMEOUT_US)) DEV_ERR("%s: Error turning off audio engine.\n", __func__); } static struct hdmi_tx_ctrl *hdmi_tx_get_drvdata_from_panel_data( struct mdss_panel_data *mpd) { struct hdmi_tx_ctrl *hdmi_ctrl = NULL; if (mpd) { hdmi_ctrl = container_of(mpd, struct hdmi_tx_ctrl, panel_data); if (!hdmi_ctrl) DEV_ERR("%s: hdmi_ctrl = NULL\n", __func__); } else { DEV_ERR("%s: mdss_panel_data = NULL\n", __func__); } return hdmi_ctrl; } /* hdmi_tx_get_drvdata_from_panel_data */ static struct hdmi_tx_ctrl *hdmi_tx_get_drvdata_from_sysfs_dev( struct device *device) { struct msm_fb_data_type *mfd = NULL; struct mdss_panel_data *panel_data = NULL; struct fb_info *fbi = dev_get_drvdata(device); if (fbi) { mfd = (struct msm_fb_data_type *)fbi->par; panel_data = dev_get_platdata(&mfd->pdev->dev); return hdmi_tx_get_drvdata_from_panel_data(panel_data); } else { DEV_ERR("%s: fbi = NULL\n", __func__); return NULL; } } /* hdmi_tx_get_drvdata_from_sysfs_dev */ /* todo: Fix this. Right now this is declared in hdmi_util.h */ void *hdmi_get_featuredata_from_sysfs_dev(struct device *device, u32 feature_type) { struct hdmi_tx_ctrl *hdmi_ctrl = NULL; if (!device || feature_type >= HDMI_TX_FEAT_MAX) { DEV_ERR("%s: invalid input\n", __func__); return NULL; } hdmi_ctrl = hdmi_tx_get_drvdata_from_sysfs_dev(device); if (hdmi_ctrl) return hdmi_ctrl->feature_data[feature_type]; else return NULL; } /* hdmi_tx_get_featuredata_from_sysfs_dev */ EXPORT_SYMBOL(hdmi_get_featuredata_from_sysfs_dev); static ssize_t hdmi_tx_sysfs_rda_connected(struct device *dev, struct device_attribute *attr, char *buf) { ssize_t ret; struct hdmi_tx_ctrl *hdmi_ctrl = hdmi_tx_get_drvdata_from_sysfs_dev(dev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } mutex_lock(&hdmi_ctrl->mutex); ret = snprintf(buf, PAGE_SIZE, "%d\n", hdmi_ctrl->hpd_state); DEV_DBG("%s: '%d'\n", __func__, hdmi_ctrl->hpd_state); mutex_unlock(&hdmi_ctrl->mutex); return ret; } /* hdmi_tx_sysfs_rda_connected */ static ssize_t hdmi_tx_sysfs_rda_video_mode(struct device *dev, struct device_attribute *attr, char *buf) { ssize_t ret; struct hdmi_tx_ctrl *hdmi_ctrl = hdmi_tx_get_drvdata_from_sysfs_dev(dev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } mutex_lock(&hdmi_ctrl->mutex); ret = snprintf(buf, PAGE_SIZE, "%d\n", hdmi_ctrl->video_resolution); DEV_DBG("%s: '%d'\n", __func__, hdmi_ctrl->video_resolution); mutex_unlock(&hdmi_ctrl->mutex); return ret; } /* hdmi_tx_sysfs_rda_video_mode */ static ssize_t hdmi_tx_sysfs_rda_hpd(struct device *dev, struct device_attribute *attr, char *buf) { ssize_t ret; struct hdmi_tx_ctrl *hdmi_ctrl = hdmi_tx_get_drvdata_from_sysfs_dev(dev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } ret = snprintf(buf, PAGE_SIZE, "%d\n", hdmi_ctrl->hpd_feature_on); DEV_DBG("%s: '%d'\n", __func__, hdmi_ctrl->hpd_feature_on); return ret; } /* hdmi_tx_sysfs_rda_hpd */ static ssize_t hdmi_tx_sysfs_wta_hpd(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int hpd, rc = 0; ssize_t ret = strnlen(buf, PAGE_SIZE); struct hdmi_tx_ctrl *hdmi_ctrl = NULL; DEV_DBG("%s:\n", __func__); hdmi_ctrl = hdmi_tx_get_drvdata_from_sysfs_dev(dev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } rc = kstrtoint(buf, 10, &hpd); if (rc) { DEV_ERR("%s: kstrtoint failed. rc=%d\n", __func__, rc); return rc; } if (hdmi_ctrl->mhl_max_pclk && hpd && (!hdmi_ctrl->mhl_hpd_on || hdmi_ctrl->hpd_feature_on)) return 0; switch (hpd) { case HPD_OFF: case HPD_DISABLE: if (hpd == HPD_DISABLE) hdmi_ctrl->hpd_disabled = true; if (!hdmi_ctrl->hpd_feature_on) { DEV_DBG("%s: HPD is already off\n", __func__); return ret; } rc = hdmi_tx_sysfs_enable_hpd(hdmi_ctrl, false); if (hdmi_ctrl->panel_power_on && hdmi_ctrl->hpd_state) { hdmi_tx_set_audio_switch_node(hdmi_ctrl, 0); hdmi_tx_wait_for_audio_engine(hdmi_ctrl); } hdmi_tx_send_cable_notification(hdmi_ctrl, 0); break; case HPD_ON: if (hdmi_ctrl->hpd_disabled == true) { DEV_ERR("%s: hpd is disabled, state %d not allowed\n", __func__, hpd); return ret; } if (hdmi_ctrl->pdata.cond_power_on) { DEV_ERR("%s: hpd state %d not allowed w/ cond. hpd\n", __func__, hpd); return ret; } if (hdmi_ctrl->hpd_feature_on) { DEV_DBG("%s: HPD is already on\n", __func__); return ret; } rc = hdmi_tx_sysfs_enable_hpd(hdmi_ctrl, true); break; case HPD_ON_CONDITIONAL_MTP: if (hdmi_ctrl->hpd_disabled == true) { DEV_ERR("%s: hpd is disabled, state %d not allowed\n", __func__, hpd); return ret; } if (!hdmi_ctrl->pdata.cond_power_on) { DEV_ERR("%s: hpd state %d not allowed w/o cond. hpd\n", __func__, hpd); return ret; } if (hdmi_ctrl->hpd_feature_on) { DEV_DBG("%s: HPD is already on\n", __func__); return ret; } rc = hdmi_tx_sysfs_enable_hpd(hdmi_ctrl, true); break; case HPD_ENABLE: hdmi_ctrl->hpd_disabled = false; rc = hdmi_tx_sysfs_enable_hpd(hdmi_ctrl, true); break; default: DEV_ERR("%s: Invalid HPD state requested\n", __func__); return ret; } if (!rc) { hdmi_ctrl->hpd_feature_on = (~hdmi_ctrl->hpd_feature_on) & BIT(0); DEV_DBG("%s: '%d'\n", __func__, hdmi_ctrl->hpd_feature_on); } else { DEV_ERR("%s: failed to '%s' hpd. rc = %d\n", __func__, hpd ? "enable" : "disable", rc); ret = rc; } return ret; } /* hdmi_tx_sysfs_wta_hpd */ static ssize_t hdmi_tx_sysfs_wta_vendor_name(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { ssize_t ret, sz; u8 *s = (u8 *) buf; u8 *d = NULL; struct hdmi_tx_ctrl *hdmi_ctrl = hdmi_tx_get_drvdata_from_sysfs_dev(dev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } d = hdmi_ctrl->spd_vendor_name; ret = strnlen(buf, PAGE_SIZE); ret = (ret > 8) ? 8 : ret; sz = sizeof(hdmi_ctrl->spd_vendor_name); memset(hdmi_ctrl->spd_vendor_name, 0, sz); while (*s) { if (*s & 0x60 && *s ^ 0x7f) { *d = *s; } else { /* stop copying if control character found */ break; } if (++s > (u8 *) (buf + ret)) break; d++; } hdmi_ctrl->spd_vendor_name[sz - 1] = 0; DEV_DBG("%s: '%s'\n", __func__, hdmi_ctrl->spd_vendor_name); return ret; } /* hdmi_tx_sysfs_wta_vendor_name */ static ssize_t hdmi_tx_sysfs_rda_vendor_name(struct device *dev, struct device_attribute *attr, char *buf) { ssize_t ret; struct hdmi_tx_ctrl *hdmi_ctrl = hdmi_tx_get_drvdata_from_sysfs_dev(dev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } ret = snprintf(buf, PAGE_SIZE, "%s\n", hdmi_ctrl->spd_vendor_name); DEV_DBG("%s: '%s'\n", __func__, hdmi_ctrl->spd_vendor_name); return ret; } /* hdmi_tx_sysfs_rda_vendor_name */ static ssize_t hdmi_tx_sysfs_wta_product_description(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { ssize_t ret, sz; u8 *s = (u8 *) buf; u8 *d = NULL; struct hdmi_tx_ctrl *hdmi_ctrl = hdmi_tx_get_drvdata_from_sysfs_dev(dev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } d = hdmi_ctrl->spd_product_description; ret = strnlen(buf, PAGE_SIZE); ret = (ret > 16) ? 16 : ret; sz = sizeof(hdmi_ctrl->spd_product_description); memset(hdmi_ctrl->spd_product_description, 0, sz); while (*s) { if (*s & 0x60 && *s ^ 0x7f) { *d = *s; } else { /* stop copying if control character found */ break; } if (++s > (u8 *) (buf + ret)) break; d++; } hdmi_ctrl->spd_product_description[sz - 1] = 0; DEV_DBG("%s: '%s'\n", __func__, hdmi_ctrl->spd_product_description); return ret; } /* hdmi_tx_sysfs_wta_product_description */ static ssize_t hdmi_tx_sysfs_rda_product_description(struct device *dev, struct device_attribute *attr, char *buf) { ssize_t ret; struct hdmi_tx_ctrl *hdmi_ctrl = hdmi_tx_get_drvdata_from_sysfs_dev(dev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } ret = snprintf(buf, PAGE_SIZE, "%s\n", hdmi_ctrl->spd_product_description); DEV_DBG("%s: '%s'\n", __func__, hdmi_ctrl->spd_product_description); return ret; } /* hdmi_tx_sysfs_rda_product_description */ static ssize_t hdmi_tx_sysfs_wta_avi_itc(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { ssize_t ret = strnlen(buf, PAGE_SIZE); struct hdmi_tx_ctrl *hdmi_ctrl = NULL; int loop = 0, itc = 0, rc = 0; hdmi_ctrl = hdmi_tx_get_drvdata_from_sysfs_dev(dev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } rc = kstrtoint(buf, 10, &itc); if (rc) { DEV_ERR("%s: kstrtoint failed. rc =%d\n", __func__, rc); return rc; } if (itc < 0 || itc > 1) { DEV_ERR("%s: Invalid ITC %d\n", __func__, itc); return ret; } if (mutex_lock_interruptible(&hdmi_ctrl->lut_lock)) return -ERESTARTSYS; for (loop = 0; loop < NUM_MODES_AVI; loop++) { u8 *avi_infoframe = hdmi_tx_avi_iframe_lut[loop]; if (itc) SET_ITC_BIT(avi_infoframe[DATA_BYTE_3]); else CLR_ITC_BIT(avi_infoframe[DATA_BYTE_3]); } mutex_unlock(&hdmi_ctrl->lut_lock); return ret; } /* hdmi_tx_sysfs_wta_avi_itc */ static ssize_t hdmi_tx_sysfs_wta_avi_cn_bits(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { ssize_t ret = strnlen(buf, PAGE_SIZE); struct hdmi_tx_ctrl *hdmi_ctrl = NULL; int loop = 0, cn_bits = 0, rc = 0; hdmi_ctrl = hdmi_tx_get_drvdata_from_sysfs_dev(dev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } rc = kstrtoint(buf, 10, &cn_bits); if (rc) { DEV_ERR("%s: kstrtoint failed. rc=%d\n", __func__, rc); return rc; } /* As per CEA-861-E, CN is a positive number and can be max 3 */ if (cn_bits < 0 || cn_bits > 3) { DEV_ERR("%s: Invalid CN %d\n", __func__, cn_bits); return ret; } if (mutex_lock_interruptible(&hdmi_ctrl->lut_lock)) return -ERESTARTSYS; for (loop = 0; loop < NUM_MODES_AVI; loop++) { u8 *avi_infoframe = hdmi_tx_avi_iframe_lut[loop]; CONFIG_CN_BITS(cn_bits, avi_infoframe[DATA_BYTE_5]); } mutex_unlock(&hdmi_ctrl->lut_lock); return ret; } /* hdmi_tx_sysfs_wta_cn_bits */ static DEVICE_ATTR(connected, S_IRUGO, hdmi_tx_sysfs_rda_connected, NULL); static DEVICE_ATTR(video_mode, S_IRUGO, hdmi_tx_sysfs_rda_video_mode, NULL); static DEVICE_ATTR(hpd, S_IRUGO | S_IWUSR, hdmi_tx_sysfs_rda_hpd, hdmi_tx_sysfs_wta_hpd); static DEVICE_ATTR(vendor_name, S_IRUGO | S_IWUSR, hdmi_tx_sysfs_rda_vendor_name, hdmi_tx_sysfs_wta_vendor_name); static DEVICE_ATTR(product_description, S_IRUGO | S_IWUSR, hdmi_tx_sysfs_rda_product_description, hdmi_tx_sysfs_wta_product_description); static DEVICE_ATTR(avi_itc, S_IWUSR, NULL, hdmi_tx_sysfs_wta_avi_itc); static DEVICE_ATTR(avi_cn0_1, S_IWUSR, NULL, hdmi_tx_sysfs_wta_avi_cn_bits); static struct attribute *hdmi_tx_fs_attrs[] = { &dev_attr_connected.attr, &dev_attr_video_mode.attr, &dev_attr_hpd.attr, &dev_attr_vendor_name.attr, &dev_attr_product_description.attr, &dev_attr_avi_itc.attr, &dev_attr_avi_cn0_1.attr, NULL, }; static struct attribute_group hdmi_tx_fs_attrs_group = { .attrs = hdmi_tx_fs_attrs, }; static int hdmi_tx_sysfs_create(struct hdmi_tx_ctrl *hdmi_ctrl, struct fb_info *fbi) { int rc; if (!hdmi_ctrl || !fbi) { DEV_ERR("%s: invalid input\n", __func__); return -ENODEV; } rc = sysfs_create_group(&fbi->dev->kobj, &hdmi_tx_fs_attrs_group); if (rc) { DEV_ERR("%s: failed, rc=%d\n", __func__, rc); return rc; } hdmi_ctrl->kobj = &fbi->dev->kobj; DEV_DBG("%s: sysfs group %pK\n", __func__, hdmi_ctrl->kobj); return 0; } /* hdmi_tx_sysfs_create */ static void hdmi_tx_sysfs_remove(struct hdmi_tx_ctrl *hdmi_ctrl) { if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } if (hdmi_ctrl->kobj) sysfs_remove_group(hdmi_ctrl->kobj, &hdmi_tx_fs_attrs_group); hdmi_ctrl->kobj = NULL; } /* hdmi_tx_sysfs_remove */ static int hdmi_tx_config_avmute(struct hdmi_tx_ctrl *hdmi_ctrl, bool set) { struct dss_io_data *io; u32 av_mute_status; bool av_pkt_en = false; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: Core io is not initialized\n", __func__); return -EINVAL; } av_mute_status = DSS_REG_R(io, HDMI_GC); if (set) { if (!(av_mute_status & BIT(0))) { DSS_REG_W(io, HDMI_GC, av_mute_status | BIT(0)); av_pkt_en = true; } } else { if (av_mute_status & BIT(0)) { DSS_REG_W(io, HDMI_GC, av_mute_status & ~BIT(0)); av_pkt_en = true; } } /* Enable AV Mute tranmission here */ if (av_pkt_en) DSS_REG_W(io, HDMI_VBI_PKT_CTRL, DSS_REG_R(io, HDMI_VBI_PKT_CTRL) | (BIT(4) & BIT(5))); DEV_DBG("%s: AVMUTE %s\n", __func__, set ? "set" : "cleared"); return 0; } /* hdmi_tx_config_avmute */ static bool hdmi_tx_is_encryption_set(struct hdmi_tx_ctrl *hdmi_ctrl) { struct dss_io_data *io; bool enc_en = true; u32 reg_val; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); goto end; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: Core io is not initialized\n", __func__); goto end; } reg_val = DSS_REG_R_ND(io, HDMI_HDCP_CTRL2); if ((reg_val & BIT(0)) && (reg_val & BIT(1))) goto end; if (DSS_REG_R_ND(io, HDMI_CTRL) & BIT(2)) goto end; return false; end: return enc_en; } /* hdmi_tx_is_encryption_set */ static void hdmi_tx_hdcp_cb(void *ptr, enum hdmi_hdcp_state status) { int rc = 0; struct hdmi_tx_ctrl *hdmi_ctrl = (struct hdmi_tx_ctrl *)ptr; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } DEV_DBG("%s: HDCP status=%s hpd_state=%d\n", __func__, hdcp_state_name(status), hdmi_ctrl->hpd_state); switch (status) { case HDCP_STATE_AUTHENTICATED: if (hdmi_ctrl->hpd_state) { rc = hdmi_tx_config_avmute(hdmi_ctrl, false); hdmi_tx_set_audio_switch_node(hdmi_ctrl, 1); } break; case HDCP_STATE_AUTH_FAIL: if (hdmi_tx_is_encryption_set(hdmi_ctrl)) { hdmi_tx_set_audio_switch_node(hdmi_ctrl, 0); rc = hdmi_tx_config_avmute(hdmi_ctrl, true); } if (hdmi_ctrl->hpd_state) { DEV_DBG("%s: Reauthenticating\n", __func__); rc = hdmi_hdcp_reauthenticate( hdmi_ctrl->feature_data[HDMI_TX_FEAT_HDCP]); if (rc) DEV_ERR("%s: HDCP reauth failed. rc=%d\n", __func__, rc); } else { DEV_DBG("%s: Not reauthenticating. Cable not conn\n", __func__); } break; case HDCP_STATE_AUTHENTICATING: case HDCP_STATE_INACTIVE: default: break; /* do nothing */ } } /* Enable HDMI features */ static int hdmi_tx_init_features(struct hdmi_tx_ctrl *hdmi_ctrl) { struct hdmi_edid_init_data edid_init_data; struct hdmi_hdcp_init_data hdcp_init_data; struct hdmi_cec_init_data cec_init_data; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } /* Initialize EDID feature */ edid_init_data.io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; edid_init_data.mutex = &hdmi_ctrl->mutex; edid_init_data.sysfs_kobj = hdmi_ctrl->kobj; edid_init_data.ddc_ctrl = &hdmi_ctrl->ddc_ctrl; hdmi_ctrl->feature_data[HDMI_TX_FEAT_EDID] = hdmi_edid_init(&edid_init_data); if (!hdmi_ctrl->feature_data[HDMI_TX_FEAT_EDID]) { DEV_ERR("%s: hdmi_edid_init failed\n", __func__); return -EPERM; } hdmi_edid_set_video_resolution( hdmi_ctrl->feature_data[HDMI_TX_FEAT_EDID], hdmi_ctrl->video_resolution); /* Initialize HDCP feature */ if (hdmi_ctrl->present_hdcp) { struct resource *res = NULL; res = platform_get_resource_byname(hdmi_ctrl->pdev, IORESOURCE_MEM, hdmi_tx_io_name(HDMI_TX_CORE_IO)); if (!res) { DEV_ERR("%s: Error getting HDMI tx core resource\n", __func__); return -ENODEV; } hdcp_init_data.phy_addr = res->start; hdcp_init_data.core_io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; hdcp_init_data.qfprom_io = &hdmi_ctrl->pdata.io[HDMI_TX_QFPROM_IO]; hdcp_init_data.mutex = &hdmi_ctrl->mutex; hdcp_init_data.sysfs_kobj = hdmi_ctrl->kobj; hdcp_init_data.ddc_ctrl = &hdmi_ctrl->ddc_ctrl; hdcp_init_data.workq = hdmi_ctrl->workq; hdcp_init_data.notify_status = hdmi_tx_hdcp_cb; hdcp_init_data.cb_data = (void *)hdmi_ctrl; hdmi_ctrl->feature_data[HDMI_TX_FEAT_HDCP] = hdmi_hdcp_init(&hdcp_init_data); if (!hdmi_ctrl->feature_data[HDMI_TX_FEAT_HDCP]) { DEV_ERR("%s: hdmi_hdcp_init failed\n", __func__); hdmi_edid_deinit(hdmi_ctrl->feature_data[ HDMI_TX_FEAT_EDID]); hdmi_ctrl->feature_data[HDMI_TX_FEAT_EDID] = NULL; return -EPERM; } DEV_DBG("%s: HDCP feature initialized\n", __func__); } /* Initialize CEC feature */ cec_init_data.io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; cec_init_data.sysfs_kobj = hdmi_ctrl->kobj; cec_init_data.workq = hdmi_ctrl->workq; hdmi_ctrl->feature_data[HDMI_TX_FEAT_CEC] = hdmi_cec_init(&cec_init_data); if (!hdmi_ctrl->feature_data[HDMI_TX_FEAT_CEC]) DEV_WARN("%s: hdmi_cec_init failed\n", __func__); return 0; } /* hdmi_tx_init_features */ static inline u32 hdmi_tx_is_controller_on(struct hdmi_tx_ctrl *hdmi_ctrl) { struct dss_io_data *io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; return DSS_REG_R_ND(io, HDMI_CTRL) & BIT(0); } /* hdmi_tx_is_controller_on */ static int hdmi_tx_init_panel_info(struct hdmi_tx_ctrl *hdmi_ctrl) { struct mdss_panel_info *pinfo; const struct msm_hdmi_mode_timing_info *timing; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } timing = hdmi_get_supported_mode(hdmi_ctrl->video_resolution); pinfo = &hdmi_ctrl->panel_data.panel_info; if (!timing || !pinfo) { DEV_ERR("%s: invalid timing data\n", __func__); return -EINVAL; } pinfo->xres = timing->active_h; pinfo->yres = timing->active_v; pinfo->clk_rate = timing->pixel_freq*1000; pinfo->lcdc.h_back_porch = timing->back_porch_h; pinfo->lcdc.h_front_porch = timing->front_porch_h; pinfo->lcdc.h_pulse_width = timing->pulse_width_h; pinfo->lcdc.v_back_porch = timing->back_porch_v; pinfo->lcdc.v_front_porch = timing->front_porch_v; pinfo->lcdc.v_pulse_width = timing->pulse_width_v; pinfo->type = DTV_PANEL; pinfo->pdest = DISPLAY_2; pinfo->wait_cycle = 0; pinfo->bpp = 24; pinfo->fb_num = 1; pinfo->lcdc.border_clr = 0; /* blk */ pinfo->lcdc.underflow_clr = 0xff; /* blue */ pinfo->lcdc.hsync_skew = 0; pinfo->cont_splash_enabled = hdmi_ctrl->pdata.cont_splash_enabled; return 0; } /* hdmi_tx_init_panel_info */ /* Table tuned to indicate video formats supported by the MHL Tx */ /* Valid pclk rates (Mhz): 25.2, 27, 27.03, 74.25 */ static void hdmi_tx_setup_mhl_video_mode_lut(struct hdmi_tx_ctrl *hdmi_ctrl) { u32 i; struct msm_hdmi_mode_timing_info *temp_timing; if (!hdmi_ctrl->mhl_max_pclk) { DEV_WARN("%s: mhl max pclk not set!\n", __func__); return; } DEV_DBG("%s: max mode set to [%u]\n", __func__, hdmi_ctrl->mhl_max_pclk); for (i = 0; i < HDMI_VFRMT_MAX; i++) { temp_timing = (struct msm_hdmi_mode_timing_info *)hdmi_get_supported_mode(i); if (!temp_timing) continue; /* formats that exceed max mhl line clk bw */ if (temp_timing->pixel_freq > hdmi_ctrl->mhl_max_pclk) hdmi_del_supported_mode(i); } } /* hdmi_tx_setup_mhl_video_mode_lut */ static int hdmi_tx_read_sink_info(struct hdmi_tx_ctrl *hdmi_ctrl) { int status; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } if (!hdmi_tx_is_controller_on(hdmi_ctrl)) { DEV_ERR("%s: failed: HDMI controller is off", __func__); status = -ENXIO; goto error; } hdmi_ddc_config(&hdmi_ctrl->ddc_ctrl); status = hdmi_edid_read(hdmi_ctrl->feature_data[HDMI_TX_FEAT_EDID]); if (!status) DEV_DBG("%s: hdmi_edid_read success\n", __func__); else DEV_ERR("%s: hdmi_edid_read failed\n", __func__); error: return status; } /* hdmi_tx_read_sink_info */ static void hdmi_tx_hpd_int_work(struct work_struct *work) { struct hdmi_tx_ctrl *hdmi_ctrl = NULL; struct dss_io_data *io; hdmi_ctrl = container_of(work, struct hdmi_tx_ctrl, hpd_int_work); if (!hdmi_ctrl || !hdmi_ctrl->hpd_initialized) { DEV_DBG("%s: invalid input\n", __func__); return; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; DEV_DBG("%s: Got HPD %s interrupt\n", __func__, hdmi_ctrl->hpd_state ? "CONNECT" : "DISCONNECT"); if (hdmi_ctrl->hpd_state) { /* * If a down stream device or bridge chip is attached to hdmi * Tx core output, it is likely that it might be powering the * hpd module ON/OFF on cable connect/disconnect as it would * have its own mechanism of detecting cable. Flush power off * work is needed in case there is any race condidtion between * power off and on during fast cable plug in/out. */ if (hdmi_ctrl->ds_registered) flush_work(&hdmi_ctrl->power_off_work); if (hdmi_tx_enable_power(hdmi_ctrl, HDMI_TX_DDC_PM, true)) { DEV_ERR("%s: Failed to enable ddc power\n", __func__); return; } /* Enable SW DDC before EDID read */ DSS_REG_W_ND(io, HDMI_DDC_ARBITRATION , DSS_REG_R(io, HDMI_DDC_ARBITRATION) & ~(BIT(4))); hdmi_tx_read_sink_info(hdmi_ctrl); if (hdmi_tx_enable_power(hdmi_ctrl, HDMI_TX_DDC_PM, false)) DEV_ERR("%s: Failed to disable ddc power\n", __func__); hdmi_tx_send_cable_notification(hdmi_ctrl, true); } else { hdmi_tx_set_audio_switch_node(hdmi_ctrl, 0); hdmi_tx_wait_for_audio_engine(hdmi_ctrl); hdmi_tx_send_cable_notification(hdmi_ctrl, false); } if (!completion_done(&hdmi_ctrl->hpd_done)) complete_all(&hdmi_ctrl->hpd_done); } /* hdmi_tx_hpd_int_work */ static int hdmi_tx_check_capability(struct hdmi_tx_ctrl *hdmi_ctrl) { u32 hdmi_disabled, hdcp_disabled; struct dss_io_data *io = NULL; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } io = &hdmi_ctrl->pdata.io[HDMI_TX_QFPROM_IO]; if (!io->base) { DEV_ERR("%s: QFPROM io is not initialized\n", __func__); return -EINVAL; } hdcp_disabled = DSS_REG_R_ND(io, QFPROM_RAW_FEAT_CONFIG_ROW0_LSB) & BIT(31); hdmi_disabled = DSS_REG_R_ND(io, QFPROM_RAW_FEAT_CONFIG_ROW0_MSB) & BIT(0); DEV_DBG("%s: Features <HDMI:%s, HDCP:%s>\n", __func__, hdmi_disabled ? "OFF" : "ON", hdcp_disabled ? "OFF" : "ON"); if (hdmi_disabled) { DEV_ERR("%s: HDMI disabled\n", __func__); return -ENODEV; } if (hdcp_disabled) { hdmi_ctrl->present_hdcp = 0; DEV_WARN("%s: HDCP disabled\n", __func__); } else { hdmi_ctrl->present_hdcp = 1; DEV_DBG("%s: Device is HDCP enabled\n", __func__); } return 0; } /* hdmi_tx_check_capability */ static int hdmi_tx_set_video_fmt(struct hdmi_tx_ctrl *hdmi_ctrl, struct mdss_panel_info *pinfo) { int new_vic = -1; const struct msm_hdmi_mode_timing_info *timing = NULL; int res_changed = RESOLUTION_UNCHANGED; if (!hdmi_ctrl || !pinfo) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } new_vic = hdmi_tx_get_vic_from_panel_info(hdmi_ctrl, pinfo); if ((new_vic < 0) || (new_vic > HDMI_VFRMT_MAX)) { DEV_ERR("%s: invalid or not supported vic\n", __func__); return -EPERM; } if (hdmi_ctrl->video_resolution != new_vic) { res_changed = RESOLUTION_CHANGED; DEV_DBG("%s: switching from %s => %s", __func__, msm_hdmi_mode_2string(hdmi_ctrl->video_resolution), msm_hdmi_mode_2string(new_vic)); } hdmi_ctrl->video_resolution = (u32)new_vic; timing = hdmi_get_supported_mode(hdmi_ctrl->video_resolution); if (!timing) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } /* todo: find a better way */ hdmi_ctrl->pdata.power_data[HDMI_TX_CORE_PM].clk_config[0].rate = timing->pixel_freq * 1000; hdmi_edid_set_video_resolution( hdmi_ctrl->feature_data[HDMI_TX_FEAT_EDID], hdmi_ctrl->video_resolution); return res_changed; } /* hdmi_tx_set_video_fmt */ static int hdmi_tx_video_setup(struct hdmi_tx_ctrl *hdmi_ctrl, int video_format) { u32 total_v = 0; u32 total_h = 0; u32 start_h = 0; u32 end_h = 0; u32 start_v = 0; u32 end_v = 0; struct dss_io_data *io = NULL; const struct msm_hdmi_mode_timing_info *timing = hdmi_get_supported_mode(video_format); if (timing == NULL) { DEV_ERR("%s: video format not supported: %d\n", __func__, video_format); return -EPERM; } if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: Core io is not initialized\n", __func__); return -EPERM; } total_h = timing->active_h + timing->front_porch_h + timing->back_porch_h + timing->pulse_width_h - 1; total_v = timing->active_v + timing->front_porch_v + timing->back_porch_v + timing->pulse_width_v - 1; if (((total_v << 16) & 0xE0000000) || (total_h & 0xFFFFE000)) { DEV_ERR("%s: total v=%d or h=%d is larger than supported\n", __func__, total_v, total_h); return -EPERM; } DSS_REG_W(io, HDMI_TOTAL, (total_v << 16) | (total_h << 0)); start_h = timing->back_porch_h + timing->pulse_width_h; end_h = (total_h + 1) - timing->front_porch_h; if (((end_h << 16) & 0xE0000000) || (start_h & 0xFFFFE000)) { DEV_ERR("%s: end_h=%d or start_h=%d is larger than supported\n", __func__, end_h, start_h); return -EPERM; } DSS_REG_W(io, HDMI_ACTIVE_H, (end_h << 16) | (start_h << 0)); start_v = timing->back_porch_v + timing->pulse_width_v - 1; end_v = total_v - timing->front_porch_v; if (((end_v << 16) & 0xE0000000) || (start_v & 0xFFFFE000)) { DEV_ERR("%s: end_v=%d or start_v=%d is larger than supported\n", __func__, end_v, start_v); return -EPERM; } DSS_REG_W(io, HDMI_ACTIVE_V, (end_v << 16) | (start_v << 0)); if (timing->interlaced) { DSS_REG_W(io, HDMI_V_TOTAL_F2, (total_v + 1) << 0); DSS_REG_W(io, HDMI_ACTIVE_V_F2, ((end_v + 1) << 16) | ((start_v + 1) << 0)); } else { DSS_REG_W(io, HDMI_V_TOTAL_F2, 0); DSS_REG_W(io, HDMI_ACTIVE_V_F2, 0); } DSS_REG_W(io, HDMI_FRAME_CTRL, ((timing->interlaced << 31) & 0x80000000) | ((timing->active_low_h << 29) & 0x20000000) | ((timing->active_low_v << 28) & 0x10000000)); return 0; } /* hdmi_tx_video_setup */ static void hdmi_tx_set_avi_infoframe(struct hdmi_tx_ctrl *hdmi_ctrl) { int i; u8 *avi_iframe_data; u8 checksum; u8 scaninfo; u32 sum, reg_val; struct dss_io_data *io = NULL; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: Core io is not initialized\n", __func__); return; } avi_iframe_data = hdmi_tx_avi_iframe_lut[hdmi_ctrl->video_resolution]; scaninfo = hdmi_edid_get_sink_scaninfo( hdmi_ctrl->feature_data[HDMI_TX_FEAT_EDID], hdmi_ctrl->video_resolution); avi_iframe_data[DATA_BYTE_1] |= scaninfo & (BIT(1) | BIT(0)); sum = IFRAME_PACKET_OFFSET + AVI_IFRAME_TYPE + AVI_IFRAME_VERSION + AVI_MAX_DATA_BYTES; for (i = 0; i < AVI_MAX_DATA_BYTES; i++) sum += avi_iframe_data[i]; sum &= 0xFF; sum = 256 - sum; checksum = (u8) sum; reg_val = checksum | LEFT_SHIFT_BYTE(avi_iframe_data[DATA_BYTE_1]) | LEFT_SHIFT_WORD(avi_iframe_data[DATA_BYTE_2]) | LEFT_SHIFT_24BITS(avi_iframe_data[DATA_BYTE_3]); DSS_REG_W(io, HDMI_AVI_INFO0, reg_val); reg_val = avi_iframe_data[DATA_BYTE_4] | LEFT_SHIFT_BYTE(avi_iframe_data[DATA_BYTE_5]) | LEFT_SHIFT_WORD(avi_iframe_data[DATA_BYTE_6]) | LEFT_SHIFT_24BITS(avi_iframe_data[DATA_BYTE_7]); DSS_REG_W(io, HDMI_AVI_INFO1, reg_val); reg_val = avi_iframe_data[DATA_BYTE_8] | LEFT_SHIFT_BYTE(avi_iframe_data[DATA_BYTE_9]) | LEFT_SHIFT_WORD(avi_iframe_data[DATA_BYTE_10]) | LEFT_SHIFT_24BITS(avi_iframe_data[DATA_BYTE_11]); DSS_REG_W(io, HDMI_AVI_INFO2, reg_val); reg_val = avi_iframe_data[DATA_BYTE_12] | LEFT_SHIFT_BYTE(avi_iframe_data[DATA_BYTE_13]) | LEFT_SHIFT_24BITS(AVI_IFRAME_VERSION); DSS_REG_W(io, HDMI_AVI_INFO3, reg_val); /* AVI InfFrame enable (every frame) */ DSS_REG_W(io, HDMI_INFOFRAME_CTRL0, DSS_REG_R(io, HDMI_INFOFRAME_CTRL0) | BIT(1) | BIT(0)); } /* hdmi_tx_set_avi_infoframe */ /* todo: add 3D support */ static void hdmi_tx_set_vendor_specific_infoframe( struct hdmi_tx_ctrl *hdmi_ctrl) { int i; u8 vs_iframe[9]; /* two header + length + 6 data */ u32 sum, reg_val; u32 hdmi_vic, hdmi_video_format; struct dss_io_data *io = NULL; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: Core io is not initialized\n", __func__); return; } /* HDMI Spec 1.4a Table 8-10 */ vs_iframe[0] = 0x81; /* type */ vs_iframe[1] = 0x1; /* version */ vs_iframe[2] = 0x8; /* length */ vs_iframe[3] = 0x0; /* PB0: checksum */ /* PB1..PB3: 24 Bit IEEE Registration Code 00_0C_03 */ vs_iframe[4] = 0x03; vs_iframe[5] = 0x0C; vs_iframe[6] = 0x00; hdmi_video_format = 0x1; switch (hdmi_ctrl->video_resolution) { case HDMI_VFRMT_3840x2160p30_16_9: hdmi_vic = 0x1; break; case HDMI_VFRMT_3840x2160p25_16_9: hdmi_vic = 0x2; break; case HDMI_VFRMT_3840x2160p24_16_9: hdmi_vic = 0x3; break; case HDMI_VFRMT_4096x2160p24_16_9: hdmi_vic = 0x4; break; default: hdmi_video_format = 0x0; hdmi_vic = 0x0; } /* PB4: HDMI Video Format[7:5], Reserved[4:0] */ vs_iframe[7] = (hdmi_video_format << 5) & 0xE0; /* PB5: HDMI_VIC or 3D_Structure[7:4], Reserved[3:0] */ vs_iframe[8] = hdmi_vic; /* compute checksum */ sum = 0; for (i = 0; i < 9; i++) sum += vs_iframe[i]; sum &= 0xFF; sum = 256 - sum; vs_iframe[3] = (u8)sum; reg_val = (hdmi_vic << 16) | (vs_iframe[3] << 8) | (hdmi_video_format << 5) | vs_iframe[2]; DSS_REG_W(io, HDMI_VENSPEC_INFO0, reg_val); /* vendor specific info-frame enable (every frame) */ DSS_REG_W(io, HDMI_INFOFRAME_CTRL0, DSS_REG_R(io, HDMI_INFOFRAME_CTRL0) | BIT(13) | BIT(12)); } /* hdmi_tx_set_vendor_specific_infoframe */ static void hdmi_tx_set_spd_infoframe(struct hdmi_tx_ctrl *hdmi_ctrl) { u32 packet_header = 0; u32 check_sum = 0; u32 packet_payload = 0; u32 packet_control = 0; u8 *vendor_name = NULL; u8 *product_description = NULL; struct dss_io_data *io = NULL; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: Core io is not initialized\n", __func__); return; } vendor_name = hdmi_ctrl->spd_vendor_name; product_description = hdmi_ctrl->spd_product_description; /* Setup Packet header and payload */ /* * 0x83 InfoFrame Type Code * 0x01 InfoFrame Version Number * 0x19 Length of Source Product Description InfoFrame */ packet_header = 0x83 | (0x01 << 8) | (0x19 << 16); DSS_REG_W(io, HDMI_GENERIC1_HDR, packet_header); check_sum += IFRAME_CHECKSUM_32(packet_header); packet_payload = (vendor_name[3] & 0x7f) | ((vendor_name[4] & 0x7f) << 8) | ((vendor_name[5] & 0x7f) << 16) | ((vendor_name[6] & 0x7f) << 24); DSS_REG_W(io, HDMI_GENERIC1_1, packet_payload); check_sum += IFRAME_CHECKSUM_32(packet_payload); /* Product Description (7-bit ASCII code) */ packet_payload = (vendor_name[7] & 0x7f) | ((product_description[0] & 0x7f) << 8) | ((product_description[1] & 0x7f) << 16) | ((product_description[2] & 0x7f) << 24); DSS_REG_W(io, HDMI_GENERIC1_2, packet_payload); check_sum += IFRAME_CHECKSUM_32(packet_payload); packet_payload = (product_description[3] & 0x7f) | ((product_description[4] & 0x7f) << 8) | ((product_description[5] & 0x7f) << 16) | ((product_description[6] & 0x7f) << 24); DSS_REG_W(io, HDMI_GENERIC1_3, packet_payload); check_sum += IFRAME_CHECKSUM_32(packet_payload); packet_payload = (product_description[7] & 0x7f) | ((product_description[8] & 0x7f) << 8) | ((product_description[9] & 0x7f) << 16) | ((product_description[10] & 0x7f) << 24); DSS_REG_W(io, HDMI_GENERIC1_4, packet_payload); check_sum += IFRAME_CHECKSUM_32(packet_payload); packet_payload = (product_description[11] & 0x7f) | ((product_description[12] & 0x7f) << 8) | ((product_description[13] & 0x7f) << 16) | ((product_description[14] & 0x7f) << 24); DSS_REG_W(io, HDMI_GENERIC1_5, packet_payload); check_sum += IFRAME_CHECKSUM_32(packet_payload); /* * Source Device Information * 00h unknown * 01h Digital STB * 02h DVD * 03h D-VHS * 04h HDD Video * 05h DVC * 06h DSC * 07h Video CD * 08h Game * 09h PC general */ packet_payload = (product_description[15] & 0x7f) | 0x00 << 8; DSS_REG_W(io, HDMI_GENERIC1_6, packet_payload); check_sum += IFRAME_CHECKSUM_32(packet_payload); /* Vendor Name (7bit ASCII code) */ packet_payload = ((vendor_name[0] & 0x7f) << 8) | ((vendor_name[1] & 0x7f) << 16) | ((vendor_name[2] & 0x7f) << 24); check_sum += IFRAME_CHECKSUM_32(packet_payload); packet_payload |= ((0x100 - (0xff & check_sum)) & 0xff); DSS_REG_W(io, HDMI_GENERIC1_0, packet_payload); /* * GENERIC1_LINE | GENERIC1_CONT | GENERIC1_SEND * Setup HDMI TX generic packet control * Enable this packet to transmit every frame * Enable HDMI TX engine to transmit Generic packet 1 */ packet_control = DSS_REG_R_ND(io, HDMI_GEN_PKT_CTRL); packet_control |= ((0x1 << 24) | (1 << 5) | (1 << 4)); DSS_REG_W(io, HDMI_GEN_PKT_CTRL, packet_control); } /* hdmi_tx_set_spd_infoframe */ static void hdmi_tx_set_mode(struct hdmi_tx_ctrl *hdmi_ctrl, u32 power_on) { struct dss_io_data *io = NULL; /* Defaults: Disable block, HDMI mode */ u32 reg_val = BIT(1); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: Core io is not initialized\n", __func__); return; } mutex_lock(&hdmi_ctrl->mutex); if (power_on) { /* Enable the block */ reg_val |= BIT(0); /* HDMI Encryption, if HDCP is enabled */ if (hdmi_tx_is_hdcp_enabled(hdmi_ctrl) && !hdmi_ctrl->pdata.primary) reg_val |= BIT(2); /* Set transmission mode to DVI based in EDID info */ if (hdmi_edid_get_sink_mode( hdmi_ctrl->feature_data[HDMI_TX_FEAT_EDID]) == 0) reg_val &= ~BIT(1); /* DVI mode */ } DSS_REG_W(io, HDMI_CTRL, reg_val); mutex_unlock(&hdmi_ctrl->mutex); DEV_DBG("HDMI Core: %s, HDMI_CTRL=0x%08x\n", power_on ? "Enable" : "Disable", reg_val); } /* hdmi_tx_set_mode */ static int hdmi_tx_pinctrl_set_state(struct hdmi_tx_ctrl *hdmi_ctrl, enum hdmi_tx_power_module_type module, bool active) { struct pinctrl_state *pin_state; int rc = -EFAULT; struct dss_module_power *power_data = NULL; u64 cur_pin_states; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -ENODEV; } if (IS_ERR_OR_NULL(hdmi_ctrl->pin_res.pinctrl)) return 0; power_data = &hdmi_ctrl->pdata.power_data[module]; cur_pin_states = active ? (hdmi_ctrl->pdata.pin_states | BIT(module)) : (hdmi_ctrl->pdata.pin_states & ~BIT(module)); if (cur_pin_states & BIT(HDMI_TX_HPD_PM)) { if (cur_pin_states & BIT(HDMI_TX_DDC_PM)) { if (cur_pin_states & BIT(HDMI_TX_CEC_PM)) pin_state = hdmi_ctrl->pin_res.state_active; else pin_state = hdmi_ctrl->pin_res.state_ddc_active; } else if (cur_pin_states & BIT(HDMI_TX_CEC_PM)) { pin_state = hdmi_ctrl->pin_res.state_cec_active; } else { pin_state = hdmi_ctrl->pin_res.state_hpd_active; } } else { pin_state = hdmi_ctrl->pin_res.state_suspend; } if (!IS_ERR_OR_NULL(pin_state)) { rc = pinctrl_select_state(hdmi_ctrl->pin_res.pinctrl, pin_state); if (rc) pr_err("%s: cannot set pins\n", __func__); else hdmi_ctrl->pdata.pin_states = cur_pin_states; } else { pr_err("%s: pinstate not found\n", __func__); } return rc; } static int hdmi_tx_pinctrl_init(struct platform_device *pdev) { struct hdmi_tx_ctrl *hdmi_ctrl; hdmi_ctrl = platform_get_drvdata(pdev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -ENODEV; } hdmi_ctrl->pin_res.pinctrl = devm_pinctrl_get(&pdev->dev); if (IS_ERR_OR_NULL(hdmi_ctrl->pin_res.pinctrl)) { pr_err("%s: failed to get pinctrl\n", __func__); return PTR_ERR(hdmi_ctrl->pin_res.pinctrl); } hdmi_ctrl->pin_res.state_active = pinctrl_lookup_state(hdmi_ctrl->pin_res.pinctrl, "hdmi_active"); if (IS_ERR_OR_NULL(hdmi_ctrl->pin_res.state_active)) pr_debug("%s: cannot get active pinstate\n", __func__); hdmi_ctrl->pin_res.state_hpd_active = pinctrl_lookup_state(hdmi_ctrl->pin_res.pinctrl, "hdmi_hpd_active"); if (IS_ERR_OR_NULL(hdmi_ctrl->pin_res.state_hpd_active)) pr_debug("%s: cannot get hpd active pinstate\n", __func__); hdmi_ctrl->pin_res.state_cec_active = pinctrl_lookup_state(hdmi_ctrl->pin_res.pinctrl, "hdmi_cec_active"); if (IS_ERR_OR_NULL(hdmi_ctrl->pin_res.state_cec_active)) pr_debug("%s: cannot get cec active pinstate\n", __func__); hdmi_ctrl->pin_res.state_ddc_active = pinctrl_lookup_state(hdmi_ctrl->pin_res.pinctrl, "hdmi_ddc_active"); if (IS_ERR_OR_NULL(hdmi_ctrl->pin_res.state_ddc_active)) pr_debug("%s: cannot get ddc active pinstate\n", __func__); hdmi_ctrl->pin_res.state_suspend = pinctrl_lookup_state(hdmi_ctrl->pin_res.pinctrl, "hdmi_sleep"); if (IS_ERR_OR_NULL(hdmi_ctrl->pin_res.state_suspend)) pr_debug("%s: cannot get sleep pinstate\n", __func__); return 0; } static int hdmi_tx_config_power(struct hdmi_tx_ctrl *hdmi_ctrl, enum hdmi_tx_power_module_type module, int config) { int rc = 0; struct dss_module_power *power_data = NULL; if (!hdmi_ctrl || module >= HDMI_TX_MAX_PM) { DEV_ERR("%s: Error: invalid input\n", __func__); rc = -EINVAL; goto exit; } power_data = &hdmi_ctrl->pdata.power_data[module]; if (!power_data) { DEV_ERR("%s: Error: invalid power data\n", __func__); rc = -EINVAL; goto exit; } if (config) { rc = msm_dss_config_vreg(&hdmi_ctrl->pdev->dev, power_data->vreg_config, power_data->num_vreg, 1); if (rc) { DEV_ERR("%s: Failed to config %s vreg. Err=%d\n", __func__, hdmi_tx_pm_name(module), rc); goto exit; } rc = msm_dss_get_clk(&hdmi_ctrl->pdev->dev, power_data->clk_config, power_data->num_clk); if (rc) { DEV_ERR("%s: Failed to get %s clk. Err=%d\n", __func__, hdmi_tx_pm_name(module), rc); msm_dss_config_vreg(&hdmi_ctrl->pdev->dev, power_data->vreg_config, power_data->num_vreg, 0); } } else { msm_dss_put_clk(power_data->clk_config, power_data->num_clk); rc = msm_dss_config_vreg(&hdmi_ctrl->pdev->dev, power_data->vreg_config, power_data->num_vreg, 0); if (rc) DEV_ERR("%s: Fail to deconfig %s vreg. Err=%d\n", __func__, hdmi_tx_pm_name(module), rc); } exit: return rc; } /* hdmi_tx_config_power */ static int hdmi_tx_enable_power(struct hdmi_tx_ctrl *hdmi_ctrl, enum hdmi_tx_power_module_type module, int enable) { int rc = 0; struct dss_module_power *power_data = NULL; if (!hdmi_ctrl || module >= HDMI_TX_MAX_PM) { DEV_ERR("%s: Error: invalid input\n", __func__); rc = -EINVAL; goto error; } power_data = &hdmi_ctrl->pdata.power_data[module]; if (!power_data) { DEV_ERR("%s: Error: invalid power data\n", __func__); rc = -EINVAL; goto error; } if (enable) { if (hdmi_ctrl->panel_data.panel_info.cont_splash_enabled) { DEV_DBG("%s: %s already eanbled by splash\n", __func__, hdmi_pm_name(module)); return 0; } rc = msm_dss_enable_vreg(power_data->vreg_config, power_data->num_vreg, 1); if (rc) { DEV_ERR("%s: Failed to enable %s vreg. Error=%d\n", __func__, hdmi_tx_pm_name(module), rc); goto error; } rc = hdmi_tx_pinctrl_set_state(hdmi_ctrl, module, enable); if (rc) { DEV_ERR("%s: Failed to set %s pinctrl state\n", __func__, hdmi_tx_pm_name(module)); goto error; } rc = msm_dss_enable_gpio(power_data->gpio_config, power_data->num_gpio, 1); if (rc) { DEV_ERR("%s: Failed to enable %s gpio. Error=%d\n", __func__, hdmi_tx_pm_name(module), rc); goto disable_vreg; } rc = msm_dss_clk_set_rate(power_data->clk_config, power_data->num_clk); if (rc) { DEV_ERR("%s: failed to set clks rate for %s. err=%d\n", __func__, hdmi_tx_pm_name(module), rc); goto disable_gpio; } rc = msm_dss_enable_clk(power_data->clk_config, power_data->num_clk, 1); if (rc) { DEV_ERR("%s: Failed to enable clks for %s. Error=%d\n", __func__, hdmi_tx_pm_name(module), rc); goto disable_gpio; } } else { msm_dss_enable_clk(power_data->clk_config, power_data->num_clk, 0); msm_dss_enable_gpio(power_data->gpio_config, power_data->num_gpio, 0); hdmi_tx_pinctrl_set_state(hdmi_ctrl, module, 0); msm_dss_enable_vreg(power_data->vreg_config, power_data->num_vreg, 0); } return rc; disable_gpio: msm_dss_enable_gpio(power_data->gpio_config, power_data->num_gpio, 0); disable_vreg: msm_dss_enable_vreg(power_data->vreg_config, power_data->num_vreg, 0); error: return rc; } /* hdmi_tx_enable_power */ static void hdmi_tx_core_off(struct hdmi_tx_ctrl *hdmi_ctrl) { if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } hdmi_tx_enable_power(hdmi_ctrl, HDMI_TX_CEC_PM, 0); hdmi_tx_enable_power(hdmi_ctrl, HDMI_TX_CORE_PM, 0); } /* hdmi_tx_core_off */ static int hdmi_tx_core_on(struct hdmi_tx_ctrl *hdmi_ctrl) { int rc = 0; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } rc = hdmi_tx_enable_power(hdmi_ctrl, HDMI_TX_CORE_PM, 1); if (rc) { DEV_ERR("%s: core hdmi_msm_enable_power failed rc = %d\n", __func__, rc); return rc; } rc = hdmi_tx_enable_power(hdmi_ctrl, HDMI_TX_CEC_PM, 1); if (rc) { DEV_ERR("%s: cec hdmi_msm_enable_power failed rc = %d\n", __func__, rc); goto disable_core_power; } return rc; disable_core_power: hdmi_tx_enable_power(hdmi_ctrl, HDMI_TX_CORE_PM, 0); return rc; } /* hdmi_tx_core_on */ static void hdmi_tx_phy_reset(struct hdmi_tx_ctrl *hdmi_ctrl) { unsigned int phy_reset_polarity = 0x0; unsigned int pll_reset_polarity = 0x0; unsigned int val; struct dss_io_data *io = NULL; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: core io not inititalized\n", __func__); return; } val = DSS_REG_R_ND(io, HDMI_PHY_CTRL); phy_reset_polarity = val >> 3 & 0x1; pll_reset_polarity = val >> 1 & 0x1; if (phy_reset_polarity == 0) DSS_REG_W_ND(io, HDMI_PHY_CTRL, val | SW_RESET); else DSS_REG_W_ND(io, HDMI_PHY_CTRL, val & (~SW_RESET)); if (pll_reset_polarity == 0) DSS_REG_W_ND(io, HDMI_PHY_CTRL, val | SW_RESET_PLL); else DSS_REG_W_ND(io, HDMI_PHY_CTRL, val & (~SW_RESET_PLL)); if (phy_reset_polarity == 0) DSS_REG_W_ND(io, HDMI_PHY_CTRL, val & (~SW_RESET)); else DSS_REG_W_ND(io, HDMI_PHY_CTRL, val | SW_RESET); if (pll_reset_polarity == 0) DSS_REG_W_ND(io, HDMI_PHY_CTRL, val & (~SW_RESET_PLL)); else DSS_REG_W_ND(io, HDMI_PHY_CTRL, val | SW_RESET_PLL); } /* hdmi_tx_phy_reset */ static void hdmi_tx_init_phy(struct hdmi_tx_ctrl *hdmi_ctrl) { struct dss_io_data *io = NULL; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } io = &hdmi_ctrl->pdata.io[HDMI_TX_PHY_IO]; if (!io->base) { DEV_DBG("%s: phy not initialized or init not available\n", __func__); return; } DSS_REG_W_ND(io, HDMI_PHY_ANA_CFG0, 0x1B); DSS_REG_W_ND(io, HDMI_PHY_ANA_CFG1, 0xF2); DSS_REG_W_ND(io, HDMI_PHY_BIST_CFG0, 0x0); DSS_REG_W_ND(io, HDMI_PHY_BIST_PATN0, 0x0); DSS_REG_W_ND(io, HDMI_PHY_BIST_PATN1, 0x0); DSS_REG_W_ND(io, HDMI_PHY_BIST_PATN2, 0x0); DSS_REG_W_ND(io, HDMI_PHY_BIST_PATN3, 0x0); DSS_REG_W_ND(io, HDMI_PHY_PD_CTRL1, 0x20); } /* hdmi_tx_init_phy */ static void hdmi_tx_powerdown_phy(struct hdmi_tx_ctrl *hdmi_ctrl) { struct dss_io_data *io = NULL; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } io = &hdmi_ctrl->pdata.io[HDMI_TX_PHY_IO]; if (!io->base) { DEV_DBG("%s: phy not initialized or pd not available\n", __func__); return; } DSS_REG_W_ND(io, HDMI_PHY_PD_CTRL0, 0x7F); } /* hdmi_tx_powerdown_phy */ static int hdmi_tx_audio_acr_setup(struct hdmi_tx_ctrl *hdmi_ctrl, bool enabled) { /* Read first before writing */ u32 acr_pck_ctrl_reg; u32 sample_rate; struct dss_io_data *io = NULL; if (!hdmi_ctrl) { DEV_ERR("%s: Invalid input\n", __func__); return -EINVAL; } sample_rate = hdmi_ctrl->audio_data.sample_rate; io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: core io not inititalized\n", __func__); return -EINVAL; } acr_pck_ctrl_reg = DSS_REG_R(io, HDMI_ACR_PKT_CTRL); if (enabled) { const struct msm_hdmi_mode_timing_info *timing = hdmi_get_supported_mode(hdmi_ctrl->video_resolution); const struct hdmi_tx_audio_acr_arry *audio_acr = &hdmi_tx_audio_acr_lut[0]; const int lut_size = sizeof(hdmi_tx_audio_acr_lut) / sizeof(*hdmi_tx_audio_acr_lut); u32 i, n, cts, layout, multiplier, aud_pck_ctrl_2_reg; if (timing == NULL) { DEV_WARN("%s: video format %d not supported\n", __func__, hdmi_ctrl->video_resolution); return -EPERM; } for (i = 0; i < lut_size; audio_acr = &hdmi_tx_audio_acr_lut[++i]) { if (audio_acr->pclk == timing->pixel_freq) break; } if (i >= lut_size) { DEV_WARN("%s: pixel clk %d not supported\n", __func__, timing->pixel_freq); return -EPERM; } n = audio_acr->lut[sample_rate].n; cts = audio_acr->lut[sample_rate].cts; layout = (MSM_HDMI_AUDIO_CHANNEL_2 == hdmi_ctrl->audio_data.channel_num) ? 0 : 1; if ( (AUDIO_SAMPLE_RATE_192KHZ == sample_rate) || (AUDIO_SAMPLE_RATE_176_4KHZ == sample_rate)) { multiplier = 4; n >>= 2; /* divide N by 4 and use multiplier */ } else if ( (AUDIO_SAMPLE_RATE_96KHZ == sample_rate) || (AUDIO_SAMPLE_RATE_88_2KHZ == sample_rate)) { multiplier = 2; n >>= 1; /* divide N by 2 and use multiplier */ } else { multiplier = 1; } DEV_DBG("%s: n=%u, cts=%u, layout=%u\n", __func__, n, cts, layout); /* AUDIO_PRIORITY | SOURCE */ acr_pck_ctrl_reg |= 0x80000100; /* Reset multiplier bits */ acr_pck_ctrl_reg &= ~(7 << 16); /* N_MULTIPLE(multiplier) */ acr_pck_ctrl_reg |= (multiplier & 7) << 16; if ((AUDIO_SAMPLE_RATE_48KHZ == sample_rate) || (AUDIO_SAMPLE_RATE_96KHZ == sample_rate) || (AUDIO_SAMPLE_RATE_192KHZ == sample_rate)) { /* SELECT(3) */ acr_pck_ctrl_reg |= 3 << 4; /* CTS_48 */ cts <<= 12; /* CTS: need to determine how many fractional bits */ DSS_REG_W(io, HDMI_ACR_48_0, cts); /* N */ DSS_REG_W(io, HDMI_ACR_48_1, n); } else if ( (AUDIO_SAMPLE_RATE_44_1KHZ == sample_rate) || (AUDIO_SAMPLE_RATE_88_2KHZ == sample_rate) || (AUDIO_SAMPLE_RATE_176_4KHZ == sample_rate)) { /* SELECT(2) */ acr_pck_ctrl_reg |= 2 << 4; /* CTS_44 */ cts <<= 12; /* CTS: need to determine how many fractional bits */ DSS_REG_W(io, HDMI_ACR_44_0, cts); /* N */ DSS_REG_W(io, HDMI_ACR_44_1, n); } else { /* default to 32k */ /* SELECT(1) */ acr_pck_ctrl_reg |= 1 << 4; /* CTS_32 */ cts <<= 12; /* CTS: need to determine how many fractional bits */ DSS_REG_W(io, HDMI_ACR_32_0, cts); /* N */ DSS_REG_W(io, HDMI_ACR_32_1, n); } /* Payload layout depends on number of audio channels */ /* LAYOUT_SEL(layout) */ aud_pck_ctrl_2_reg = 1 | (layout << 1); /* override | layout */ DSS_REG_W(io, HDMI_AUDIO_PKT_CTRL2, aud_pck_ctrl_2_reg); /* SEND | CONT */ acr_pck_ctrl_reg |= 0x00000003; } else { /* ~(SEND | CONT) */ acr_pck_ctrl_reg &= ~0x00000003; } DSS_REG_W(io, HDMI_ACR_PKT_CTRL, acr_pck_ctrl_reg); return 0; } /* hdmi_tx_audio_acr_setup */ static int hdmi_tx_audio_iframe_setup(struct hdmi_tx_ctrl *hdmi_ctrl, bool enabled) { struct dss_io_data *io = NULL; u32 channel_count = 1; /* Def to 2 channels -> Table 17 in CEA-D */ u32 num_of_channels; u32 channel_allocation; u32 level_shift; u32 down_mix; u32 check_sum, audio_info_0_reg, audio_info_1_reg; u32 audio_info_ctrl_reg; u32 aud_pck_ctrl_2_reg; u32 layout; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } num_of_channels = hdmi_ctrl->audio_data.channel_num; channel_allocation = hdmi_ctrl->audio_data.spkr_alloc; level_shift = hdmi_ctrl->audio_data.level_shift; down_mix = hdmi_ctrl->audio_data.down_mix; io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: core io not inititalized\n", __func__); return -EINVAL; } layout = (MSM_HDMI_AUDIO_CHANNEL_2 == num_of_channels) ? 0 : 1; aud_pck_ctrl_2_reg = 1 | (layout << 1); DSS_REG_W(io, HDMI_AUDIO_PKT_CTRL2, aud_pck_ctrl_2_reg); /* * Please see table 20 Audio InfoFrame in HDMI spec * FL = front left * FC = front Center * FR = front right * FLC = front left center * FRC = front right center * RL = rear left * RC = rear center * RR = rear right * RLC = rear left center * RRC = rear right center * LFE = low frequency effect */ /* Read first then write because it is bundled with other controls */ audio_info_ctrl_reg = DSS_REG_R(io, HDMI_INFOFRAME_CTRL0); if (enabled) { switch (num_of_channels) { case MSM_HDMI_AUDIO_CHANNEL_2: break; case MSM_HDMI_AUDIO_CHANNEL_3: channel_count = 2; break; case MSM_HDMI_AUDIO_CHANNEL_4: channel_count = 3; break; case MSM_HDMI_AUDIO_CHANNEL_5: channel_count = 4; break; case MSM_HDMI_AUDIO_CHANNEL_6: channel_count = 5; break; case MSM_HDMI_AUDIO_CHANNEL_7: channel_count = 6; break; case MSM_HDMI_AUDIO_CHANNEL_8: channel_count = 7; break; default: DEV_ERR("%s: Unsupported num_of_channels = %u\n", __func__, num_of_channels); return -EINVAL; } /* Program the Channel-Speaker allocation */ audio_info_1_reg = 0; /* CA(channel_allocation) */ audio_info_1_reg |= channel_allocation & 0xff; /* Program the Level shifter */ audio_info_1_reg |= (level_shift << 11) & 0x00007800; /* Program the Down-mix Inhibit Flag */ audio_info_1_reg |= (down_mix << 15) & 0x00008000; DSS_REG_W(io, HDMI_AUDIO_INFO1, audio_info_1_reg); /* * Calculate CheckSum: Sum of all the bytes in the * Audio Info Packet (See table 8.4 in HDMI spec) */ check_sum = 0; /* HDMI_AUDIO_INFO_FRAME_PACKET_HEADER_TYPE[0x84] */ check_sum += 0x84; /* HDMI_AUDIO_INFO_FRAME_PACKET_HEADER_VERSION[0x01] */ check_sum += 1; /* HDMI_AUDIO_INFO_FRAME_PACKET_LENGTH[0x0A] */ check_sum += 0x0A; check_sum += channel_count; check_sum += channel_allocation; /* See Table 8.5 in HDMI spec */ check_sum += (level_shift & 0xF) << 3 | (down_mix & 0x1) << 7; check_sum &= 0xFF; check_sum = (u8) (256 - check_sum); audio_info_0_reg = 0; /* CHECKSUM(check_sum) */ audio_info_0_reg |= check_sum & 0xff; /* CC(channel_count) */ audio_info_0_reg |= (channel_count << 8) & 0x00000700; DSS_REG_W(io, HDMI_AUDIO_INFO0, audio_info_0_reg); /* * Set these flags * AUDIO_INFO_UPDATE | * AUDIO_INFO_SOURCE | * AUDIO_INFO_CONT | * AUDIO_INFO_SEND */ audio_info_ctrl_reg |= 0x000000F0; } else { /*Clear these flags * ~(AUDIO_INFO_UPDATE | * AUDIO_INFO_SOURCE | * AUDIO_INFO_CONT | * AUDIO_INFO_SEND) */ audio_info_ctrl_reg &= ~0x000000F0; } DSS_REG_W(io, HDMI_INFOFRAME_CTRL0, audio_info_ctrl_reg); dss_reg_dump(io->base, io->len, enabled ? "HDMI-AUDIO-ON: " : "HDMI-AUDIO-OFF: ", REG_DUMP); return 0; } /* hdmi_tx_audio_iframe_setup */ static int hdmi_tx_audio_info_setup(struct platform_device *pdev, u32 sample_rate, u32 num_of_channels, u32 channel_allocation, u32 level_shift, bool down_mix) { int rc = 0; struct hdmi_tx_ctrl *hdmi_ctrl = platform_get_drvdata(pdev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -ENODEV; } if (!hdmi_tx_is_dvi_mode(hdmi_ctrl) && hdmi_ctrl->panel_power_on) { /* Map given sample rate to Enum */ if (sample_rate == 32000) sample_rate = AUDIO_SAMPLE_RATE_32KHZ; else if (sample_rate == 44100) sample_rate = AUDIO_SAMPLE_RATE_44_1KHZ; else if (sample_rate == 48000) sample_rate = AUDIO_SAMPLE_RATE_48KHZ; else if (sample_rate == 88200) sample_rate = AUDIO_SAMPLE_RATE_88_2KHZ; else if (sample_rate == 96000) sample_rate = AUDIO_SAMPLE_RATE_96KHZ; else if (sample_rate == 176400) sample_rate = AUDIO_SAMPLE_RATE_176_4KHZ; else if (sample_rate == 192000) sample_rate = AUDIO_SAMPLE_RATE_192KHZ; hdmi_ctrl->audio_data.sample_rate = sample_rate; hdmi_ctrl->audio_data.channel_num = num_of_channels; hdmi_ctrl->audio_data.spkr_alloc = channel_allocation; hdmi_ctrl->audio_data.level_shift = level_shift; hdmi_ctrl->audio_data.down_mix = down_mix; rc = hdmi_tx_audio_setup(hdmi_ctrl); if (rc) DEV_ERR("%s: hdmi_tx_audio_iframe_setup failed.rc=%d\n", __func__, rc); } else { rc = -EPERM; } return rc; } /* hdmi_tx_audio_info_setup */ static int hdmi_tx_get_audio_edid_blk(struct platform_device *pdev, struct msm_hdmi_audio_edid_blk *blk) { struct hdmi_tx_ctrl *hdmi_ctrl = platform_get_drvdata(pdev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -ENODEV; } if (!hdmi_ctrl->audio_sdev.state) return -EPERM; return hdmi_edid_get_audio_blk( hdmi_ctrl->feature_data[HDMI_TX_FEAT_EDID], blk); } /* hdmi_tx_get_audio_edid_blk */ static u8 hdmi_tx_tmds_enabled(struct platform_device *pdev) { struct hdmi_tx_ctrl *hdmi_ctrl = platform_get_drvdata(pdev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -ENODEV; } /* status of tmds */ return (hdmi_ctrl->timing_gen_on == true); } static int hdmi_tx_set_mhl_max_pclk(struct platform_device *pdev, u32 max_val) { struct hdmi_tx_ctrl *hdmi_ctrl = NULL; hdmi_ctrl = platform_get_drvdata(pdev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -ENODEV; } if (max_val) { hdmi_ctrl->mhl_max_pclk = max_val; hdmi_tx_setup_mhl_video_mode_lut(hdmi_ctrl); } else { DEV_ERR("%s: invalid max pclk val\n", __func__); return -EINVAL; } return 0; } int msm_hdmi_register_mhl(struct platform_device *pdev, struct msm_hdmi_mhl_ops *ops, void *data) { struct hdmi_tx_ctrl *hdmi_ctrl = platform_get_drvdata(pdev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid pdev\n", __func__); return -ENODEV; } if (!ops) { DEV_ERR("%s: invalid ops\n", __func__); return -EINVAL; } ops->tmds_enabled = hdmi_tx_tmds_enabled; ops->set_mhl_max_pclk = hdmi_tx_set_mhl_max_pclk; ops->set_upstream_hpd = hdmi_tx_set_mhl_hpd; hdmi_ctrl->ds_registered = true; return 0; } static int hdmi_tx_get_cable_status(struct platform_device *pdev, u32 vote) { struct hdmi_tx_ctrl *hdmi_ctrl = platform_get_drvdata(pdev); unsigned long flags; u32 hpd; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -ENODEV; } spin_lock_irqsave(&hdmi_ctrl->hpd_state_lock, flags); hpd = hdmi_ctrl->hpd_state; spin_unlock_irqrestore(&hdmi_ctrl->hpd_state_lock, flags); hdmi_ctrl->vote_hdmi_core_on = false; if (vote && hpd) hdmi_ctrl->vote_hdmi_core_on = true; return hpd; } int msm_hdmi_register_audio_codec(struct platform_device *pdev, struct msm_hdmi_audio_codec_ops *ops) { struct hdmi_tx_ctrl *hdmi_ctrl = platform_get_drvdata(pdev); if (!hdmi_ctrl || !ops) { DEV_ERR("%s: invalid input\n", __func__); return -ENODEV; } ops->audio_info_setup = hdmi_tx_audio_info_setup; ops->get_audio_edid_blk = hdmi_tx_get_audio_edid_blk; ops->hdmi_cable_status = hdmi_tx_get_cable_status; return 0; } /* hdmi_tx_audio_register */ EXPORT_SYMBOL(msm_hdmi_register_audio_codec); static int hdmi_tx_audio_setup(struct hdmi_tx_ctrl *hdmi_ctrl) { int rc = 0; struct dss_io_data *io = NULL; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: core io not inititalized\n", __func__); return -EINVAL; } rc = hdmi_tx_audio_acr_setup(hdmi_ctrl, true); if (rc) { DEV_ERR("%s: hdmi_tx_audio_acr_setup failed. rc=%d\n", __func__, rc); return rc; } rc = hdmi_tx_audio_iframe_setup(hdmi_ctrl, true); if (rc) { DEV_ERR("%s: hdmi_tx_audio_iframe_setup failed. rc=%d\n", __func__, rc); return rc; } DEV_INFO("HDMI Audio: Enabled\n"); return 0; } /* hdmi_tx_audio_setup */ static void hdmi_tx_audio_off(struct hdmi_tx_ctrl *hdmi_ctrl) { struct dss_io_data *io = NULL; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: core io not inititalized\n", __func__); return; } if (hdmi_tx_audio_iframe_setup(hdmi_ctrl, false)) DEV_ERR("%s: hdmi_tx_audio_iframe_setup failed.\n", __func__); if (hdmi_tx_audio_acr_setup(hdmi_ctrl, false)) DEV_ERR("%s: hdmi_tx_audio_acr_setup failed.\n", __func__); hdmi_ctrl->audio_data.sample_rate = AUDIO_SAMPLE_RATE_48KHZ; hdmi_ctrl->audio_data.channel_num = MSM_HDMI_AUDIO_CHANNEL_2; DEV_INFO("HDMI Audio: Disabled\n"); } /* hdmi_tx_audio_off */ static int hdmi_tx_start(struct hdmi_tx_ctrl *hdmi_ctrl) { int rc = 0; struct dss_io_data *io = NULL; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: core io is not initialized\n", __func__); return -EINVAL; } hdmi_tx_set_mode(hdmi_ctrl, false); hdmi_tx_init_phy(hdmi_ctrl); DSS_REG_W(io, HDMI_USEC_REFTIMER, 0x0001001B); hdmi_tx_set_mode(hdmi_ctrl, true); rc = hdmi_tx_video_setup(hdmi_ctrl, hdmi_ctrl->video_resolution); if (rc) { DEV_ERR("%s: hdmi_tx_video_setup failed. rc=%d\n", __func__, rc); hdmi_tx_set_mode(hdmi_ctrl, false); return rc; } if (!hdmi_tx_is_dvi_mode(hdmi_ctrl) && hdmi_tx_is_cea_format(hdmi_ctrl->video_resolution)) { hdmi_tx_audio_setup(hdmi_ctrl); if (!hdmi_tx_is_hdcp_enabled(hdmi_ctrl) && !hdmi_tx_is_encryption_set(hdmi_ctrl)) hdmi_tx_set_audio_switch_node(hdmi_ctrl, 1); hdmi_tx_set_avi_infoframe(hdmi_ctrl); hdmi_tx_set_vendor_specific_infoframe(hdmi_ctrl); hdmi_tx_set_spd_infoframe(hdmi_ctrl); } /* todo: CEC */ DEV_INFO("%s: HDMI Core: Initialized\n", __func__); return rc; } /* hdmi_tx_start */ static void hdmi_tx_hpd_polarity_setup(struct hdmi_tx_ctrl *hdmi_ctrl, bool polarity) { struct dss_io_data *io = NULL; u32 cable_sense; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: core io is not initialized\n", __func__); return; } if (polarity) DSS_REG_W(io, HDMI_HPD_INT_CTRL, BIT(2) | BIT(1)); else DSS_REG_W(io, HDMI_HPD_INT_CTRL, BIT(2)); cable_sense = (DSS_REG_R(io, HDMI_HPD_INT_STATUS) & BIT(1)) >> 1; DEV_DBG("%s: listen = %s, sense = %s\n", __func__, polarity ? "connect" : "disconnect", cable_sense ? "connect" : "disconnect"); if (cable_sense == polarity) { u32 reg_val = DSS_REG_R(io, HDMI_HPD_CTRL); /* Toggle HPD circuit to trigger HPD sense */ DSS_REG_W(io, HDMI_HPD_CTRL, reg_val & ~BIT(28)); DSS_REG_W(io, HDMI_HPD_CTRL, reg_val | BIT(28)); } } /* hdmi_tx_hpd_polarity_setup */ static void hdmi_tx_power_off_work(struct work_struct *work) { struct hdmi_tx_ctrl *hdmi_ctrl = NULL; struct dss_io_data *io = NULL; hdmi_ctrl = container_of(work, struct hdmi_tx_ctrl, power_off_work); if (!hdmi_ctrl) { DEV_DBG("%s: invalid input\n", __func__); return; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: Core io is not initialized\n", __func__); return; } if (!hdmi_tx_is_dvi_mode(hdmi_ctrl)) hdmi_tx_audio_off(hdmi_ctrl); hdmi_tx_powerdown_phy(hdmi_ctrl); hdmi_cec_deconfig(hdmi_ctrl->feature_data[HDMI_TX_FEAT_CEC]); hdmi_tx_core_off(hdmi_ctrl); if (hdmi_ctrl->hpd_off_pending) { hdmi_tx_hpd_off(hdmi_ctrl); hdmi_ctrl->hpd_off_pending = false; } mutex_lock(&hdmi_ctrl->mutex); hdmi_ctrl->panel_power_on = false; mutex_unlock(&hdmi_ctrl->mutex); DEV_INFO("%s: HDMI Core: OFF\n", __func__); if (hdmi_ctrl->hdmi_tx_hpd_done) hdmi_ctrl->hdmi_tx_hpd_done( hdmi_ctrl->downstream_data); } /* hdmi_tx_power_off_work */ static int hdmi_tx_power_off(struct mdss_panel_data *panel_data) { struct hdmi_tx_ctrl *hdmi_ctrl = hdmi_tx_get_drvdata_from_panel_data(panel_data); if (!hdmi_ctrl || (!panel_data->panel_info.cont_splash_enabled && !hdmi_ctrl->panel_power_on)) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } /* * Queue work item to handle power down sequence. * This is needed since we need to wait for the audio engine * to shutdown first before we shutdown the HDMI core. */ DEV_DBG("%s: Queuing work to power off HDMI core\n", __func__); queue_work(hdmi_ctrl->workq, &hdmi_ctrl->power_off_work); return 0; } /* hdmi_tx_power_off */ static int hdmi_tx_power_on(struct mdss_panel_data *panel_data) { int rc = 0; int res_changed = RESOLUTION_UNCHANGED; struct dss_io_data *io = NULL; struct mdss_panel_info *panel_info = NULL; struct hdmi_tx_ctrl *hdmi_ctrl = hdmi_tx_get_drvdata_from_panel_data(panel_data); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: core io is not initialized\n", __func__); return -EINVAL; } if (!hdmi_ctrl->hpd_initialized) { DEV_ERR("%s: HDMI on is not possible w/o cable detection.\n", __func__); return -EPERM; } panel_info = &panel_data->panel_info; hdmi_ctrl->hdcp_feature_on = hdcp_feature_on; /* If a power down is already underway, wait for it to finish */ flush_work(&hdmi_ctrl->power_off_work); res_changed = hdmi_tx_set_video_fmt(hdmi_ctrl, panel_info); DEV_DBG("%s: %dx%d%s\n", __func__, panel_info->xres, panel_info->yres, panel_info->cont_splash_enabled ? " (handoff underway)" : ""); if (hdmi_ctrl->pdata.cont_splash_enabled) { hdmi_ctrl->pdata.cont_splash_enabled = false; panel_data->panel_info.cont_splash_enabled = false; if (res_changed == RESOLUTION_UNCHANGED) { hdmi_ctrl->panel_power_on = true; hdmi_cec_config( hdmi_ctrl->feature_data[HDMI_TX_FEAT_CEC]); if (!hdmi_tx_is_hdcp_enabled(hdmi_ctrl)) hdmi_tx_set_audio_switch_node(hdmi_ctrl, 1); goto end; } } rc = hdmi_tx_core_on(hdmi_ctrl); if (rc) { DEV_ERR("%s: hdmi_msm_core_on failed\n", __func__); return rc; } mutex_lock(&hdmi_ctrl->mutex); hdmi_ctrl->panel_power_on = true; mutex_unlock(&hdmi_ctrl->mutex); hdmi_cec_config(hdmi_ctrl->feature_data[HDMI_TX_FEAT_CEC]); if (hdmi_ctrl->hpd_state) { DEV_DBG("%s: Turning HDMI on\n", __func__); rc = hdmi_tx_start(hdmi_ctrl); if (rc) { DEV_ERR("%s: hdmi_tx_start failed. rc=%d\n", __func__, rc); hdmi_tx_power_off(panel_data); return rc; } } end: dss_reg_dump(io->base, io->len, "HDMI-ON: ", REG_DUMP); DEV_INFO("%s: HDMI=%s DVI= %s\n", __func__, hdmi_tx_is_controller_on(hdmi_ctrl) ? "ON" : "OFF" , hdmi_tx_is_dvi_mode(hdmi_ctrl) ? "ON" : "OFF"); hdmi_tx_hpd_polarity_setup(hdmi_ctrl, HPD_DISCONNECT_POLARITY); if (hdmi_ctrl->hdmi_tx_hpd_done) hdmi_ctrl->hdmi_tx_hpd_done(hdmi_ctrl->downstream_data); return 0; } /* hdmi_tx_power_on */ static void hdmi_tx_hpd_off(struct hdmi_tx_ctrl *hdmi_ctrl) { int rc = 0; struct dss_io_data *io = NULL; unsigned long flags; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } if (!hdmi_ctrl->hpd_initialized) { DEV_DBG("%s: HPD is already OFF, returning\n", __func__); return; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: core io not inititalized\n", __func__); return; } /* finish the ongoing hpd work if any */ flush_work(&hdmi_ctrl->hpd_int_work); /* Turn off HPD interrupts */ DSS_REG_W(io, HDMI_HPD_INT_CTRL, 0); hdmi_ctrl->mdss_util->disable_irq(&hdmi_tx_hw); hdmi_tx_set_mode(hdmi_ctrl, false); if (hdmi_ctrl->hpd_state) { rc = hdmi_tx_enable_power(hdmi_ctrl, HDMI_TX_DDC_PM, 0); if (rc) DEV_INFO("%s: Failed to disable ddc power. Error=%d\n", __func__, rc); } rc = hdmi_tx_enable_power(hdmi_ctrl, HDMI_TX_HPD_PM, 0); if (rc) DEV_INFO("%s: Failed to disable hpd power. Error=%d\n", __func__, rc); spin_lock_irqsave(&hdmi_ctrl->hpd_state_lock, flags); hdmi_ctrl->hpd_state = false; spin_unlock_irqrestore(&hdmi_ctrl->hpd_state_lock, flags); hdmi_ctrl->hpd_initialized = false; DEV_DBG("%s: HPD is now OFF\n", __func__); } /* hdmi_tx_hpd_off */ static int hdmi_tx_hpd_on(struct hdmi_tx_ctrl *hdmi_ctrl) { u32 reg_val; int rc = 0; struct dss_io_data *io = NULL; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: core io not inititalized\n", __func__); return -EINVAL; } if (hdmi_ctrl->hpd_initialized) { DEV_DBG("%s: HPD is already ON\n", __func__); } else { rc = hdmi_tx_enable_power(hdmi_ctrl, HDMI_TX_HPD_PM, true); if (rc) { DEV_ERR("%s: Failed to enable hpd power. rc=%d\n", __func__, rc); return rc; } dss_reg_dump(io->base, io->len, "HDMI-INIT: ", REG_DUMP); if (!hdmi_ctrl->panel_data.panel_info.cont_splash_enabled) { hdmi_tx_set_mode(hdmi_ctrl, false); hdmi_tx_phy_reset(hdmi_ctrl); hdmi_tx_set_mode(hdmi_ctrl, true); } DSS_REG_W(io, HDMI_USEC_REFTIMER, 0x0001001B); hdmi_ctrl->mdss_util->enable_irq(&hdmi_tx_hw); hdmi_ctrl->hpd_initialized = true; DEV_INFO("%s: HDMI HW version = 0x%x\n", __func__, DSS_REG_R_ND(&hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO], HDMI_VERSION)); /* set timeout to 4.1ms (max) for hardware debounce */ reg_val = DSS_REG_R(io, HDMI_HPD_CTRL) | 0x1FFF; /* Turn on HPD HW circuit */ DSS_REG_W(io, HDMI_HPD_CTRL, reg_val | BIT(28)); hdmi_tx_hpd_polarity_setup(hdmi_ctrl, HPD_CONNECT_POLARITY); DEV_DBG("%s: HPD is now ON\n", __func__); } return rc; } /* hdmi_tx_hpd_on */ static int hdmi_tx_sysfs_enable_hpd(struct hdmi_tx_ctrl *hdmi_ctrl, int on) { int rc = 0; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } DEV_INFO("%s: %d\n", __func__, on); if (on) { rc = hdmi_tx_hpd_on(hdmi_ctrl); } else { /* If power down is already underway, wait for it to finish */ flush_work(&hdmi_ctrl->power_off_work); if (!hdmi_ctrl->panel_power_on) hdmi_tx_hpd_off(hdmi_ctrl); else hdmi_ctrl->hpd_off_pending = true; } return rc; } /* hdmi_tx_sysfs_enable_hpd */ static int hdmi_tx_set_mhl_hpd(struct platform_device *pdev, uint8_t on) { int rc = 0; struct hdmi_tx_ctrl *hdmi_ctrl = NULL; hdmi_ctrl = platform_get_drvdata(pdev); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } /* mhl status should override */ hdmi_ctrl->mhl_hpd_on = on; if (!on && hdmi_ctrl->hpd_feature_on) { rc = hdmi_tx_sysfs_enable_hpd(hdmi_ctrl, false); } else if (on && !hdmi_ctrl->hpd_feature_on) { rc = hdmi_tx_sysfs_enable_hpd(hdmi_ctrl, true); } else { DEV_DBG("%s: hpd is already '%s'. return\n", __func__, hdmi_ctrl->hpd_feature_on ? "enabled" : "disabled"); return rc; } if (!rc) { hdmi_ctrl->hpd_feature_on = (~hdmi_ctrl->hpd_feature_on) & BIT(0); DEV_DBG("%s: '%d'\n", __func__, hdmi_ctrl->hpd_feature_on); } else { DEV_ERR("%s: failed to '%s' hpd. rc = %d\n", __func__, on ? "enable" : "disable", rc); } return rc; } static irqreturn_t hdmi_tx_isr(int irq, void *data) { struct dss_io_data *io = NULL; struct hdmi_tx_ctrl *hdmi_ctrl = (struct hdmi_tx_ctrl *)data; unsigned long flags; if (!hdmi_ctrl) { DEV_WARN("%s: invalid input data, ISR ignored\n", __func__); return IRQ_HANDLED; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_WARN("%s: core io not initialized, ISR ignored\n", __func__); return IRQ_HANDLED; } if (DSS_REG_R(io, HDMI_HPD_INT_STATUS) & BIT(0)) { spin_lock_irqsave(&hdmi_ctrl->hpd_state_lock, flags); hdmi_ctrl->hpd_state = (DSS_REG_R(io, HDMI_HPD_INT_STATUS) & BIT(1)) >> 1; spin_unlock_irqrestore(&hdmi_ctrl->hpd_state_lock, flags); /* * Ack the current hpd interrupt and stop listening to * new hpd interrupt. */ DSS_REG_W(io, HDMI_HPD_INT_CTRL, BIT(0)); queue_work(hdmi_ctrl->workq, &hdmi_ctrl->hpd_int_work); } if (hdmi_ddc_isr(&hdmi_ctrl->ddc_ctrl)) DEV_ERR("%s: hdmi_ddc_isr failed\n", __func__); if (hdmi_ctrl->feature_data[HDMI_TX_FEAT_CEC]) if (hdmi_cec_isr(hdmi_ctrl->feature_data[HDMI_TX_FEAT_CEC])) DEV_ERR("%s: hdmi_cec_isr failed\n", __func__); if (hdmi_ctrl->feature_data[HDMI_TX_FEAT_HDCP]) if (hdmi_hdcp_isr(hdmi_ctrl->feature_data[HDMI_TX_FEAT_HDCP])) DEV_ERR("%s: hdmi_hdcp_isr failed\n", __func__); return IRQ_HANDLED; } /* hdmi_tx_isr */ static void hdmi_tx_dev_deinit(struct hdmi_tx_ctrl *hdmi_ctrl) { if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } if (hdmi_ctrl->feature_data[HDMI_TX_FEAT_CEC]) { hdmi_cec_deinit(hdmi_ctrl->feature_data[HDMI_TX_FEAT_CEC]); hdmi_ctrl->feature_data[HDMI_TX_FEAT_CEC] = NULL; } if (hdmi_ctrl->feature_data[HDMI_TX_FEAT_HDCP]) { hdmi_hdcp_deinit(hdmi_ctrl->feature_data[HDMI_TX_FEAT_HDCP]); hdmi_ctrl->feature_data[HDMI_TX_FEAT_HDCP] = NULL; } if (hdmi_ctrl->feature_data[HDMI_TX_FEAT_EDID]) { hdmi_edid_deinit(hdmi_ctrl->feature_data[HDMI_TX_FEAT_EDID]); hdmi_ctrl->feature_data[HDMI_TX_FEAT_EDID] = NULL; } switch_dev_unregister(&hdmi_ctrl->audio_sdev); switch_dev_unregister(&hdmi_ctrl->sdev); if (hdmi_ctrl->workq) destroy_workqueue(hdmi_ctrl->workq); mutex_destroy(&hdmi_ctrl->lut_lock); mutex_destroy(&hdmi_ctrl->cable_notify_mutex); mutex_destroy(&hdmi_ctrl->mutex); hdmi_tx_hw.ptr = NULL; } /* hdmi_tx_dev_deinit */ static int hdmi_tx_dev_init(struct hdmi_tx_ctrl *hdmi_ctrl) { int rc = 0; struct hdmi_tx_platform_data *pdata = NULL; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } pdata = &hdmi_ctrl->pdata; rc = hdmi_tx_check_capability(hdmi_ctrl); if (rc) { DEV_ERR("%s: no HDMI device\n", __func__); goto fail_no_hdmi; } /* irq enable/disable will be handled in hpd on/off */ hdmi_tx_hw.ptr = (void *)hdmi_ctrl; hdmi_setup_video_mode_lut(); mutex_init(&hdmi_ctrl->mutex); mutex_init(&hdmi_ctrl->lut_lock); mutex_init(&hdmi_ctrl->cable_notify_mutex); INIT_LIST_HEAD(&hdmi_ctrl->cable_notify_handlers); hdmi_ctrl->workq = create_workqueue("hdmi_tx_workq"); if (!hdmi_ctrl->workq) { DEV_ERR("%s: hdmi_tx_workq creation failed.\n", __func__); rc = -EPERM; goto fail_create_workq; } hdmi_ctrl->ddc_ctrl.io = &pdata->io[HDMI_TX_CORE_IO]; init_completion(&hdmi_ctrl->ddc_ctrl.ddc_sw_done); hdmi_ctrl->panel_power_on = false; hdmi_ctrl->panel_suspend = false; hdmi_ctrl->hpd_state = false; hdmi_ctrl->hpd_initialized = false; hdmi_ctrl->hpd_off_pending = false; init_completion(&hdmi_ctrl->hpd_done); INIT_WORK(&hdmi_ctrl->hpd_int_work, hdmi_tx_hpd_int_work); INIT_WORK(&hdmi_ctrl->cable_notify_work, hdmi_tx_cable_notify_work); INIT_WORK(&hdmi_ctrl->power_off_work, hdmi_tx_power_off_work); spin_lock_init(&hdmi_ctrl->hpd_state_lock); hdmi_ctrl->audio_data.sample_rate = AUDIO_SAMPLE_RATE_48KHZ; hdmi_ctrl->audio_data.channel_num = MSM_HDMI_AUDIO_CHANNEL_2; hdmi_ctrl->sdev.name = "hdmi"; if (switch_dev_register(&hdmi_ctrl->sdev) < 0) { DEV_ERR("%s: Hdmi switch registration failed\n", __func__); rc = -ENODEV; goto fail_create_workq; } hdmi_ctrl->audio_sdev.name = "hdmi_audio"; if (switch_dev_register(&hdmi_ctrl->audio_sdev) < 0) { DEV_ERR("%s: hdmi_audio switch registration failed\n", __func__); rc = -ENODEV; goto fail_audio_switch_dev; } return 0; fail_audio_switch_dev: switch_dev_unregister(&hdmi_ctrl->sdev); fail_create_workq: if (hdmi_ctrl->workq) destroy_workqueue(hdmi_ctrl->workq); mutex_destroy(&hdmi_ctrl->lut_lock); mutex_destroy(&hdmi_ctrl->mutex); fail_no_hdmi: return rc; } /* hdmi_tx_dev_init */ static int hdmi_tx_start_hdcp(struct hdmi_tx_ctrl *hdmi_ctrl) { int rc; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } if (hdmi_ctrl->panel_data.panel_info.cont_splash_enabled || !hdmi_tx_is_hdcp_enabled(hdmi_ctrl)) return 0; if (hdmi_tx_is_encryption_set(hdmi_ctrl)) hdmi_tx_config_avmute(hdmi_ctrl, true); if (hdmi_tx_enable_power(hdmi_ctrl, HDMI_TX_DDC_PM, true)) { DEV_ERR("%s: Failed to enable ddc power\n", __func__); return -ENODEV; } rc = hdmi_hdcp_authenticate(hdmi_ctrl->feature_data[HDMI_TX_FEAT_HDCP]); if (rc) DEV_ERR("%s: hdcp auth failed. rc=%d\n", __func__, rc); return rc; } static int hdmi_tx_panel_event_handler(struct mdss_panel_data *panel_data, int event, void *arg) { int rc = 0, new_vic = -1; struct hdmi_tx_ctrl *hdmi_ctrl = hdmi_tx_get_drvdata_from_panel_data(panel_data); if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } DEV_DBG("%s: event = %d suspend=%d, hpd_feature=%d\n", __func__, event, hdmi_ctrl->panel_suspend, hdmi_ctrl->hpd_feature_on); switch (event) { case MDSS_EVENT_FB_REGISTERED: rc = hdmi_tx_sysfs_create(hdmi_ctrl, arg); if (rc) { DEV_ERR("%s: hdmi_tx_sysfs_create failed.rc=%d\n", __func__, rc); return rc; } rc = hdmi_tx_init_features(hdmi_ctrl); if (rc) { DEV_ERR("%s: init_features failed.rc=%d\n", __func__, rc); hdmi_tx_sysfs_remove(hdmi_ctrl); return rc; } if (hdmi_ctrl->pdata.primary) { INIT_COMPLETION(hdmi_ctrl->hpd_done); rc = hdmi_tx_sysfs_enable_hpd(hdmi_ctrl, true); if (rc) { DEV_ERR("%s: hpd_enable failed. rc=%d\n", __func__, rc); hdmi_tx_sysfs_remove(hdmi_ctrl); return rc; } else { hdmi_ctrl->hpd_feature_on = true; } } break; case MDSS_EVENT_CHECK_PARAMS: new_vic = hdmi_tx_get_vic_from_panel_info(hdmi_ctrl, (struct mdss_panel_info *)arg); if ((new_vic < 0) || (new_vic > HDMI_VFRMT_MAX)) { DEV_ERR("%s: invalid or not supported vic\n", __func__); return -EPERM; } /* * return value of 1 lets mdss know that panel * needs a reconfig due to new resolution and * it will issue close and open subsequently. */ if (new_vic != hdmi_ctrl->video_resolution) rc = 1; else DEV_DBG("%s: no res change.\n", __func__); break; case MDSS_EVENT_RESUME: /* If a suspend is already underway, wait for it to finish */ if (hdmi_ctrl->panel_suspend && hdmi_ctrl->panel_power_on) flush_work(&hdmi_ctrl->power_off_work); if (hdmi_ctrl->hpd_feature_on) { INIT_COMPLETION(hdmi_ctrl->hpd_done); rc = hdmi_tx_hpd_on(hdmi_ctrl); if (rc) DEV_ERR("%s: hdmi_tx_hpd_on failed. rc=%d\n", __func__, rc); } break; case MDSS_EVENT_RESET: if (hdmi_ctrl->panel_suspend) { u32 timeout; hdmi_ctrl->panel_suspend = false; timeout = wait_for_completion_timeout( &hdmi_ctrl->hpd_done, HZ/10); if (!timeout && !hdmi_ctrl->hpd_state) { DEV_INFO("%s: cable removed during suspend\n", __func__); hdmi_tx_send_cable_notification(hdmi_ctrl, false); rc = -EPERM; } else { DEV_DBG("%s: cable present after resume\n", __func__); } } break; case MDSS_EVENT_UNBLANK: rc = hdmi_tx_power_on(panel_data); if (rc) DEV_ERR("%s: hdmi_tx_power_on failed. rc=%d\n", __func__, rc); break; case MDSS_EVENT_PANEL_ON: rc = hdmi_tx_start_hdcp(hdmi_ctrl); if (rc) DEV_ERR("%s: hdcp start failed rc=%d\n", __func__, rc); hdmi_ctrl->timing_gen_on = true; break; case MDSS_EVENT_SUSPEND: if (!hdmi_ctrl->panel_power_on) { if (hdmi_ctrl->hpd_feature_on) hdmi_tx_hpd_off(hdmi_ctrl); hdmi_ctrl->panel_suspend = false; } else { hdmi_ctrl->hpd_off_pending = true; hdmi_ctrl->panel_suspend = true; } break; case MDSS_EVENT_BLANK: if (hdmi_tx_is_hdcp_enabled(hdmi_ctrl)) { DEV_DBG("%s: Turning off HDCP\n", __func__); hdmi_hdcp_off( hdmi_ctrl->feature_data[HDMI_TX_FEAT_HDCP]); rc = hdmi_tx_enable_power(hdmi_ctrl, HDMI_TX_DDC_PM, false); if (rc) DEV_ERR("%s: Failed to disable ddc power\n", __func__); } break; case MDSS_EVENT_PANEL_OFF: if (hdmi_ctrl->panel_power_on) { hdmi_tx_config_avmute(hdmi_ctrl, 1); rc = hdmi_tx_power_off(panel_data); if (rc) DEV_ERR("%s: hdmi_tx_power_off failed.rc=%d\n", __func__, rc); } else { DEV_DBG("%s: hdmi is already powered off\n", __func__); } hdmi_ctrl->timing_gen_on = false; break; case MDSS_EVENT_CLOSE: if (panel_data->panel_info.cont_splash_enabled) { hdmi_tx_power_off(panel_data); panel_data->panel_info.cont_splash_enabled = false; } else { if (hdmi_ctrl->hpd_feature_on) hdmi_tx_hpd_polarity_setup(hdmi_ctrl, HPD_CONNECT_POLARITY); } break; } return rc; } /* hdmi_tx_panel_event_handler */ static int hdmi_tx_register_panel(struct hdmi_tx_ctrl *hdmi_ctrl) { int rc = 0; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } hdmi_ctrl->panel_data.event_handler = hdmi_tx_panel_event_handler; if (!hdmi_ctrl->pdata.primary) hdmi_ctrl->video_resolution = DEFAULT_VIDEO_RESOLUTION; rc = hdmi_tx_init_panel_info(hdmi_ctrl); if (rc) { DEV_ERR("%s: hdmi_init_panel_info failed\n", __func__); return rc; } rc = mdss_register_panel(hdmi_ctrl->pdev, &hdmi_ctrl->panel_data); if (rc) { DEV_ERR("%s: FAILED: to register HDMI panel\n", __func__); return rc; } rc = hdmi_ctrl->mdss_util->register_irq(&hdmi_tx_hw); if (rc) DEV_ERR("%s: mdss_register_irq failed.\n", __func__); return rc; } /* hdmi_tx_register_panel */ static void hdmi_tx_deinit_resource(struct hdmi_tx_ctrl *hdmi_ctrl) { int i; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } /* VREG & CLK */ for (i = HDMI_TX_MAX_PM - 1; i >= 0; i--) { if (hdmi_tx_config_power(hdmi_ctrl, i, 0)) DEV_ERR("%s: '%s' power deconfig fail\n", __func__, hdmi_tx_pm_name(i)); } /* IO */ for (i = HDMI_TX_MAX_IO - 1; i >= 0; i--) { if (hdmi_ctrl->pdata.io[i].base) msm_dss_iounmap(&hdmi_ctrl->pdata.io[i]); } } /* hdmi_tx_deinit_resource */ static int hdmi_tx_init_resource(struct hdmi_tx_ctrl *hdmi_ctrl) { int i, rc = 0; struct hdmi_tx_platform_data *pdata = NULL; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } pdata = &hdmi_ctrl->pdata; hdmi_tx_pinctrl_init(hdmi_ctrl->pdev); /* IO */ for (i = 0; i < HDMI_TX_MAX_IO; i++) { rc = msm_dss_ioremap_byname(hdmi_ctrl->pdev, &pdata->io[i], hdmi_tx_io_name(i)); if (rc) { DEV_DBG("%s: '%s' remap failed or not available\n", __func__, hdmi_tx_io_name(i)); } DEV_INFO("%s: '%s': start = 0x%pK, len=0x%x\n", __func__, hdmi_tx_io_name(i), pdata->io[i].base, pdata->io[i].len); } /* VREG & CLK */ for (i = 0; i < HDMI_TX_MAX_PM; i++) { rc = hdmi_tx_config_power(hdmi_ctrl, i, 1); if (rc) { DEV_ERR("%s: '%s' power config failed.rc=%d\n", __func__, hdmi_tx_pm_name(i), rc); goto error; } } return rc; error: hdmi_tx_deinit_resource(hdmi_ctrl); return rc; } /* hdmi_tx_init_resource */ static void hdmi_tx_put_dt_clk_data(struct device *dev, struct dss_module_power *module_power) { if (!module_power) { DEV_ERR("%s: invalid input\n", __func__); return; } if (module_power->clk_config) { devm_kfree(dev, module_power->clk_config); module_power->clk_config = NULL; } module_power->num_clk = 0; } /* hdmi_tx_put_dt_clk_data */ /* todo: once clk are moved to device tree then change this implementation */ static int hdmi_tx_get_dt_clk_data(struct device *dev, struct dss_module_power *mp, u32 module_type) { int rc = 0; if (!dev || !mp) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } DEV_DBG("%s: module: '%s'\n", __func__, hdmi_tx_pm_name(module_type)); switch (module_type) { case HDMI_TX_HPD_PM: mp->num_clk = 4; mp->clk_config = devm_kzalloc(dev, sizeof(struct dss_clk) * mp->num_clk, GFP_KERNEL); if (!mp->clk_config) { DEV_ERR("%s: can't alloc '%s' clk mem\n", __func__, hdmi_tx_pm_name(module_type)); goto error; } snprintf(mp->clk_config[0].clk_name, 32, "%s", "iface_clk"); mp->clk_config[0].type = DSS_CLK_AHB; mp->clk_config[0].rate = 0; snprintf(mp->clk_config[1].clk_name, 32, "%s", "core_clk"); mp->clk_config[1].type = DSS_CLK_OTHER; mp->clk_config[1].rate = 19200000; /* * This clock is required to clock MDSS interrupt registers * when HDMI is the only block turned on within MDSS. Since * rate for this clock is controlled by MDP driver, treat this * similar to AHB clock and do not set rate for it. */ snprintf(mp->clk_config[2].clk_name, 32, "%s", "mdp_core_clk"); mp->clk_config[2].type = DSS_CLK_AHB; mp->clk_config[2].rate = 0; snprintf(mp->clk_config[3].clk_name, 32, "%s", "alt_iface_clk"); mp->clk_config[3].type = DSS_CLK_AHB; mp->clk_config[3].rate = 0; break; case HDMI_TX_CORE_PM: mp->num_clk = 1; mp->clk_config = devm_kzalloc(dev, sizeof(struct dss_clk) * mp->num_clk, GFP_KERNEL); if (!mp->clk_config) { DEV_ERR("%s: can't alloc '%s' clk mem\n", __func__, hdmi_tx_pm_name(module_type)); goto error; } snprintf(mp->clk_config[0].clk_name, 32, "%s", "extp_clk"); mp->clk_config[0].type = DSS_CLK_PCLK; /* This rate will be overwritten when core is powered on */ mp->clk_config[0].rate = 148500000; break; case HDMI_TX_DDC_PM: case HDMI_TX_CEC_PM: mp->num_clk = 0; DEV_DBG("%s: no clk\n", __func__); break; default: DEV_ERR("%s: invalid module type=%d\n", __func__, module_type); return -EINVAL; } return rc; error: if (mp->clk_config) { devm_kfree(dev, mp->clk_config); mp->clk_config = NULL; } mp->num_clk = 0; return rc; } /* hdmi_tx_get_dt_clk_data */ static void hdmi_tx_put_dt_vreg_data(struct device *dev, struct dss_module_power *module_power) { if (!module_power) { DEV_ERR("%s: invalid input\n", __func__); return; } if (module_power->vreg_config) { devm_kfree(dev, module_power->vreg_config); module_power->vreg_config = NULL; } module_power->num_vreg = 0; } /* hdmi_tx_put_dt_vreg_data */ static int hdmi_tx_get_dt_vreg_data(struct device *dev, struct dss_module_power *mp, u32 module_type) { int i, j, rc = 0; int dt_vreg_total = 0, mod_vreg_total = 0; u32 ndx_mask = 0; u32 *val_array = NULL; const char *mod_name = NULL; struct device_node *of_node = NULL; if (!dev || !mp) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } switch (module_type) { case HDMI_TX_HPD_PM: mod_name = "hpd"; break; case HDMI_TX_DDC_PM: mod_name = "ddc"; break; case HDMI_TX_CORE_PM: mod_name = "core"; break; case HDMI_TX_CEC_PM: mod_name = "cec"; break; default: DEV_ERR("%s: invalid module type=%d\n", __func__, module_type); return -EINVAL; } DEV_DBG("%s: module: '%s'\n", __func__, hdmi_tx_pm_name(module_type)); of_node = dev->of_node; dt_vreg_total = of_property_count_strings(of_node, "qcom,supply-names"); if (dt_vreg_total < 0) { DEV_ERR("%s: vreg not found. rc=%d\n", __func__, dt_vreg_total); rc = dt_vreg_total; goto error; } /* count how many vreg for particular hdmi module */ for (i = 0; i < dt_vreg_total; i++) { const char *st = NULL; rc = of_property_read_string_index(of_node, "qcom,supply-names", i, &st); if (rc) { DEV_ERR("%s: error reading name. i=%d, rc=%d\n", __func__, i, rc); goto error; } if (strnstr(st, mod_name, strlen(st))) { ndx_mask |= BIT(i); mod_vreg_total++; } } if (mod_vreg_total > 0) { mp->num_vreg = mod_vreg_total; mp->vreg_config = devm_kzalloc(dev, sizeof(struct dss_vreg) * mod_vreg_total, GFP_KERNEL); if (!mp->vreg_config) { DEV_ERR("%s: can't alloc '%s' vreg mem\n", __func__, hdmi_tx_pm_name(module_type)); goto error; } } else { DEV_DBG("%s: no vreg\n", __func__); return 0; } val_array = devm_kzalloc(dev, sizeof(u32) * dt_vreg_total, GFP_KERNEL); if (!val_array) { DEV_ERR("%s: can't allocate vreg scratch mem\n", __func__); rc = -ENOMEM; goto error; } for (i = 0, j = 0; (i < dt_vreg_total) && (j < mod_vreg_total); i++) { const char *st = NULL; if (!(ndx_mask & BIT(0))) { ndx_mask >>= 1; continue; } /* vreg-name */ rc = of_property_read_string_index(of_node, "qcom,supply-names", i, &st); if (rc) { DEV_ERR("%s: error reading name. i=%d, rc=%d\n", __func__, i, rc); goto error; } snprintf(mp->vreg_config[j].vreg_name, 32, "%s", st); /* vreg-min-voltage */ memset(val_array, 0, sizeof(u32) * dt_vreg_total); rc = of_property_read_u32_array(of_node, "qcom,min-voltage-level", val_array, dt_vreg_total); if (rc) { DEV_ERR("%s: error read '%s' min volt. rc=%d\n", __func__, hdmi_tx_pm_name(module_type), rc); goto error; } mp->vreg_config[j].min_voltage = val_array[i]; /* vreg-max-voltage */ memset(val_array, 0, sizeof(u32) * dt_vreg_total); rc = of_property_read_u32_array(of_node, "qcom,max-voltage-level", val_array, dt_vreg_total); if (rc) { DEV_ERR("%s: error read '%s' max volt. rc=%d\n", __func__, hdmi_tx_pm_name(module_type), rc); goto error; } mp->vreg_config[j].max_voltage = val_array[i]; /* vreg-op-mode */ memset(val_array, 0, sizeof(u32) * dt_vreg_total); rc = of_property_read_u32_array(of_node, "qcom,enable-load", val_array, dt_vreg_total); if (rc) { DEV_ERR("%s: error read '%s' enable load. rc=%d\n", __func__, hdmi_tx_pm_name(module_type), rc); goto error; } mp->vreg_config[j].enable_load = val_array[i]; memset(val_array, 0, sizeof(u32) * dt_vreg_total); rc = of_property_read_u32_array(of_node, "qcom,disable-load", val_array, dt_vreg_total); if (rc) { DEV_ERR("%s: error read '%s' disable load. rc=%d\n", __func__, hdmi_tx_pm_name(module_type), rc); goto error; } mp->vreg_config[j].disable_load = val_array[i]; DEV_DBG("%s: %s min=%d, max=%d, enable=%d disable=%d\n", __func__, mp->vreg_config[j].vreg_name, mp->vreg_config[j].min_voltage, mp->vreg_config[j].max_voltage, mp->vreg_config[j].enable_load, mp->vreg_config[j].disable_load); ndx_mask >>= 1; j++; } devm_kfree(dev, val_array); return rc; error: if (mp->vreg_config) { devm_kfree(dev, mp->vreg_config); mp->vreg_config = NULL; } mp->num_vreg = 0; if (val_array) devm_kfree(dev, val_array); return rc; } /* hdmi_tx_get_dt_vreg_data */ static void hdmi_tx_put_dt_gpio_data(struct device *dev, struct dss_module_power *module_power) { if (!module_power) { DEV_ERR("%s: invalid input\n", __func__); return; } if (module_power->gpio_config) { devm_kfree(dev, module_power->gpio_config); module_power->gpio_config = NULL; } module_power->num_gpio = 0; } /* hdmi_tx_put_dt_gpio_data */ static int hdmi_tx_get_dt_gpio_data(struct device *dev, struct dss_module_power *mp, u32 module_type) { int i, j; int mp_gpio_cnt = 0, gpio_list_size = 0; struct dss_gpio *gpio_list = NULL; struct device_node *of_node = NULL; DEV_DBG("%s: module: '%s'\n", __func__, hdmi_tx_pm_name(module_type)); if (!dev || !mp) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } of_node = dev->of_node; switch (module_type) { case HDMI_TX_HPD_PM: gpio_list_size = ARRAY_SIZE(hpd_gpio_config); gpio_list = hpd_gpio_config; break; case HDMI_TX_DDC_PM: gpio_list_size = ARRAY_SIZE(ddc_gpio_config); gpio_list = ddc_gpio_config; break; case HDMI_TX_CORE_PM: gpio_list_size = ARRAY_SIZE(core_gpio_config); gpio_list = core_gpio_config; break; case HDMI_TX_CEC_PM: gpio_list_size = ARRAY_SIZE(cec_gpio_config); gpio_list = cec_gpio_config; break; default: DEV_ERR("%s: invalid module type=%d\n", __func__, module_type); return -EINVAL; } for (i = 0; i < gpio_list_size; i++) if (of_find_property(of_node, gpio_list[i].gpio_name, NULL)) mp_gpio_cnt++; if (!mp_gpio_cnt) { DEV_DBG("%s: no gpio\n", __func__); return 0; } DEV_DBG("%s: mp_gpio_cnt = %d\n", __func__, mp_gpio_cnt); mp->num_gpio = mp_gpio_cnt; mp->gpio_config = devm_kzalloc(dev, sizeof(struct dss_gpio) * mp_gpio_cnt, GFP_KERNEL); if (!mp->gpio_config) { DEV_ERR("%s: can't alloc '%s' gpio mem\n", __func__, hdmi_tx_pm_name(module_type)); mp->num_gpio = 0; return -ENOMEM; } for (i = 0, j = 0; i < gpio_list_size; i++) { int gpio = of_get_named_gpio(of_node, gpio_list[i].gpio_name, 0); if (gpio < 0) { DEV_DBG("%s: no gpio named %s\n", __func__, gpio_list[i].gpio_name); continue; } memcpy(&mp->gpio_config[j], &gpio_list[i], sizeof(struct dss_gpio)); mp->gpio_config[j].gpio = (unsigned)gpio; DEV_DBG("%s: gpio num=%d, name=%s, value=%d\n", __func__, mp->gpio_config[j].gpio, mp->gpio_config[j].gpio_name, mp->gpio_config[j].value); j++; } return 0; } /* hdmi_tx_get_dt_gpio_data */ static void hdmi_tx_put_dt_data(struct device *dev, struct hdmi_tx_platform_data *pdata) { int i; if (!dev || !pdata) { DEV_ERR("%s: invalid input\n", __func__); return; } for (i = HDMI_TX_MAX_PM - 1; i >= 0; i--) hdmi_tx_put_dt_clk_data(dev, &pdata->power_data[i]); for (i = HDMI_TX_MAX_PM - 1; i >= 0; i--) hdmi_tx_put_dt_vreg_data(dev, &pdata->power_data[i]); for (i = HDMI_TX_MAX_PM - 1; i >= 0; i--) hdmi_tx_put_dt_gpio_data(dev, &pdata->power_data[i]); } /* hdmi_tx_put_dt_data */ static int hdmi_tx_get_dt_data(struct platform_device *pdev, struct hdmi_tx_platform_data *pdata) { int i, rc = 0; struct device_node *of_node = NULL; struct hdmi_tx_ctrl *hdmi_ctrl = platform_get_drvdata(pdev); bool splash_en; if (!pdev || !pdata) { DEV_ERR("%s: invalid input\n", __func__); return -EINVAL; } of_node = pdev->dev.of_node; rc = of_property_read_u32(of_node, "cell-index", &pdev->id); if (rc) { DEV_ERR("%s: dev id from dt not found.rc=%d\n", __func__, rc); goto error; } DEV_DBG("%s: id=%d\n", __func__, pdev->id); /* GPIO */ for (i = 0; i < HDMI_TX_MAX_PM; i++) { rc = hdmi_tx_get_dt_gpio_data(&pdev->dev, &pdata->power_data[i], i); if (rc) { DEV_ERR("%s: '%s' get_dt_gpio_data failed.rc=%d\n", __func__, hdmi_tx_pm_name(i), rc); goto error; } } /* VREG */ for (i = 0; i < HDMI_TX_MAX_PM; i++) { rc = hdmi_tx_get_dt_vreg_data(&pdev->dev, &pdata->power_data[i], i); if (rc) { DEV_ERR("%s: '%s' get_dt_vreg_data failed.rc=%d\n", __func__, hdmi_tx_pm_name(i), rc); goto error; } } /* CLK */ for (i = 0; i < HDMI_TX_MAX_PM; i++) { rc = hdmi_tx_get_dt_clk_data(&pdev->dev, &pdata->power_data[i], i); if (rc) { DEV_ERR("%s: '%s' get_dt_clk_data failed.rc=%d\n", __func__, hdmi_tx_pm_name(i), rc); goto error; } } if (!hdmi_ctrl->pdata.primary) hdmi_ctrl->pdata.primary = of_property_read_bool( pdev->dev.of_node, "qcom,primary_panel"); pdata->cond_power_on = of_property_read_bool(pdev->dev.of_node, "qcom,conditional-power-on"); splash_en = of_property_read_bool(pdev->dev.of_node, "qcom,cont-splash-enabled"); /* cont splash screen is supported only for hdmi primary */ pdata->cont_splash_enabled = hdmi_ctrl->pdata.primary ? splash_en : false; return rc; error: hdmi_tx_put_dt_data(&pdev->dev, pdata); return rc; } /* hdmi_tx_get_dt_data */ static void hdmi_tx_audio_tear_down(struct hdmi_tx_ctrl *hdmi_ctrl) { struct dss_io_data *io; u32 audio_pkt_ctrl; u32 audio_eng_cfg; if (!hdmi_ctrl) { DEV_ERR("%s: invalid input\n", __func__); return; } io = &hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO]; if (!io->base) { DEV_ERR("%s: Core io is not initialized\n", __func__); return; } audio_pkt_ctrl = DSS_REG_R(io, HDMI_AUDIO_PKT_CTRL); audio_eng_cfg = DSS_REG_R(io, HDMI_AUDIO_CFG); if ((audio_pkt_ctrl & BIT(0)) || (audio_eng_cfg & BIT(0))) { u32 lpa_dma, i = 0; void __iomem *lpa_base = ioremap(LPASS_LPAIF_RDDMA_CTL0, 0xFF); lpa_dma = readl_relaxed(lpa_base + LPASS_LPAIF_RDDMA_PER_CNT0); /* Disable audio packet transmission */ DSS_REG_W(io, HDMI_AUDIO_PKT_CTRL, DSS_REG_R(io, HDMI_AUDIO_PKT_CTRL) & ~BIT(0)); /* Wait for LPA DMA Engine to be idle */ while (i < LPA_DMA_IDLE_MAX) { u32 val; /* * sleep for minimum HW recommended time * for HW status to update. */ msleep(20); val = readl_relaxed(lpa_base + LPASS_LPAIF_RDDMA_PER_CNT0); if (val == lpa_dma) break; lpa_dma = val; i++; } DEV_DBG("%s: LPA DMA idle after %d ms\n", __func__, i * 20); /* Disable audio engine */ DSS_REG_W(io, HDMI_AUDIO_CFG, DSS_REG_R(io, HDMI_AUDIO_CFG) & ~BIT(0)); /* Disable LPA DMA Engine */ writel_relaxed(readl_relaxed(lpa_base) & ~BIT(0), lpa_base); iounmap(lpa_base); } } static int hdmi_tx_probe(struct platform_device *pdev) { int rc = 0, i; struct device_node *of_node = pdev->dev.of_node; struct hdmi_tx_ctrl *hdmi_ctrl = NULL; struct mdss_panel_cfg *pan_cfg = NULL; if (!of_node) { DEV_ERR("%s: FAILED: of_node not found\n", __func__); rc = -ENODEV; return rc; } hdmi_ctrl = devm_kzalloc(&pdev->dev, sizeof(*hdmi_ctrl), GFP_KERNEL); if (!hdmi_ctrl) { DEV_ERR("%s: FAILED: cannot alloc hdmi tx ctrl\n", __func__); rc = -ENOMEM; goto failed_no_mem; } platform_set_drvdata(pdev, hdmi_ctrl); hdmi_ctrl->pdev = pdev; pan_cfg = mdss_panel_intf_type(MDSS_PANEL_INTF_HDMI); if (IS_ERR(pan_cfg)) { return PTR_ERR(pan_cfg); } else if (pan_cfg) { int vic; if (kstrtoint(pan_cfg->arg_cfg, 10, &vic)) vic = DEFAULT_HDMI_PRIMARY_RESOLUTION; hdmi_ctrl->pdata.primary = true; hdmi_ctrl->panel_data.panel_info.is_prim_panel = true; hdmi_ctrl->video_resolution = vic; } hdmi_ctrl->mdss_util = mdss_get_util_intf(); if (hdmi_ctrl->mdss_util == NULL) { pr_err("Failed to get mdss utility functions\n"); rc = -ENODEV; goto failed_res_init; } hdmi_tx_hw.irq_info = mdss_intr_line(); if (hdmi_tx_hw.irq_info == NULL) { pr_err("Failed to get mdss irq information\n"); return -ENODEV; } rc = hdmi_tx_get_dt_data(pdev, &hdmi_ctrl->pdata); if (rc) { DEV_ERR("%s: FAILED: parsing device tree data. rc=%d\n", __func__, rc); goto failed_dt_data; } rc = hdmi_tx_init_resource(hdmi_ctrl); if (rc) { DEV_ERR("%s: FAILED: resource init. rc=%d\n", __func__, rc); goto failed_res_init; } rc = hdmi_tx_dev_init(hdmi_ctrl); if (rc) { DEV_ERR("%s: FAILED: hdmi_tx_dev_init. rc=%d\n", __func__, rc); goto failed_dev_init; } rc = hdmi_tx_register_panel(hdmi_ctrl); if (rc) { DEV_ERR("%s: FAILED: register_panel. rc=%d\n", __func__, rc); goto failed_reg_panel; } rc = of_platform_populate(of_node, NULL, NULL, &pdev->dev); if (rc) { DEV_ERR("%s: Failed to add child devices. rc=%d\n", __func__, rc); goto failed_reg_panel; } else { DEV_DBG("%s: Add child devices.\n", __func__); } if (mdss_debug_register_base("hdmi", hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO].base, hdmi_ctrl->pdata.io[HDMI_TX_CORE_IO].len)) DEV_WARN("%s: hdmi_tx debugfs register failed\n", __func__); if (hdmi_ctrl->panel_data.panel_info.cont_splash_enabled) { for (i = 0; i < HDMI_TX_MAX_PM; i++) { msm_dss_enable_vreg( hdmi_ctrl->pdata.power_data[i].vreg_config, hdmi_ctrl->pdata.power_data[i].num_vreg, 1); msm_dss_enable_gpio( hdmi_ctrl->pdata.power_data[i].gpio_config, hdmi_ctrl->pdata.power_data[i].num_gpio, 1); msm_dss_enable_clk( hdmi_ctrl->pdata.power_data[i].clk_config, hdmi_ctrl->pdata.power_data[i].num_clk, 1); } hdmi_tx_audio_tear_down(hdmi_ctrl); } return rc; failed_reg_panel: hdmi_tx_dev_deinit(hdmi_ctrl); failed_dev_init: hdmi_tx_deinit_resource(hdmi_ctrl); failed_res_init: hdmi_tx_put_dt_data(&pdev->dev, &hdmi_ctrl->pdata); failed_dt_data: devm_kfree(&pdev->dev, hdmi_ctrl); failed_no_mem: return rc; } /* hdmi_tx_probe */ static int hdmi_tx_remove(struct platform_device *pdev) { struct hdmi_tx_ctrl *hdmi_ctrl = platform_get_drvdata(pdev); if (!hdmi_ctrl) { DEV_ERR("%s: no driver data\n", __func__); return -ENODEV; } hdmi_tx_sysfs_remove(hdmi_ctrl); hdmi_tx_dev_deinit(hdmi_ctrl); hdmi_tx_deinit_resource(hdmi_ctrl); hdmi_tx_put_dt_data(&pdev->dev, &hdmi_ctrl->pdata); devm_kfree(&hdmi_ctrl->pdev->dev, hdmi_ctrl); return 0; } /* hdmi_tx_remove */ static const struct of_device_id hdmi_tx_dt_match[] = { {.compatible = COMPATIBLE_NAME,}, { /* Sentinel */ }, }; MODULE_DEVICE_TABLE(of, hdmi_tx_dt_match); static struct platform_driver this_driver = { .probe = hdmi_tx_probe, .remove = hdmi_tx_remove, .driver = { .name = DRV_NAME, .of_match_table = hdmi_tx_dt_match, }, }; static int __init hdmi_tx_drv_init(void) { int rc; rc = platform_driver_register(&this_driver); if (rc) DEV_ERR("%s: FAILED: rc=%d\n", __func__, rc); return rc; } /* hdmi_tx_drv_init */ static void __exit hdmi_tx_drv_exit(void) { platform_driver_unregister(&this_driver); } /* hdmi_tx_drv_exit */ static int set_hdcp_feature_on(const char *val, const struct kernel_param *kp) { int rc = 0; rc = param_set_bool(val, kp); if (!rc) pr_debug("%s: HDCP feature = %d\n", __func__, hdcp_feature_on); return rc; } static struct kernel_param_ops hdcp_feature_on_param_ops = { .set = set_hdcp_feature_on, .get = param_get_bool, }; module_param_cb(hdcp, &hdcp_feature_on_param_ops, &hdcp_feature_on, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(hdcp, "Enable or Disable HDCP"); module_init(hdmi_tx_drv_init); module_exit(hdmi_tx_drv_exit); MODULE_LICENSE("GPL v2"); MODULE_VERSION("0.3"); MODULE_DESCRIPTION("HDMI MSM TX driver");
26.334411
78
0.703889
[ "3d" ]
140cad7f813b2f90f358f5069c6bb6f368a50af9
1,343
h
C
EpgTimerSrv/EpgTimerSrv/NotifyManager.h
nexus7ici/tkntrec
7fbe93d1d87f693adb161984202c92b09b86716b
[ "MIT" ]
null
null
null
EpgTimerSrv/EpgTimerSrv/NotifyManager.h
nexus7ici/tkntrec
7fbe93d1d87f693adb161984202c92b09b86716b
[ "MIT" ]
null
null
null
EpgTimerSrv/EpgTimerSrv/NotifyManager.h
nexus7ici/tkntrec
7fbe93d1d87f693adb161984202c92b09b86716b
[ "MIT" ]
null
null
null
#pragma once #include "../../Common/ErrDef.h" #include "../../Common/CommonDef.h" #include "../../Common/ThreadUtil.h" class CNotifyManager { public: CNotifyManager(); ~CNotifyManager(); void RegistGUI(DWORD processID); void RegistTCP(const REGIST_TCP_INFO& info); void UnRegistGUI(DWORD processID); void UnRegistTCP(const REGIST_TCP_INFO& info); void SetNotifyWindow(HWND hwnd, UINT msgID); vector<NOTIFY_SRV_INFO> RemoveSentList(); bool GetNotify(NOTIFY_SRV_INFO* info, DWORD targetCount) const; vector<DWORD> GetRegistGUI() const; vector<REGIST_TCP_INFO> GetRegistTCP() const; void AddNotify(DWORD notifyID); void SetNotifySrvStatus(DWORD status); void AddNotifyMsg(DWORD notifyID, wstring msg); bool IsGUI() const { return guiFlag; } void SetGUI(bool f) { guiFlag = f; } protected: mutable recursive_mutex_ managerLock; CAutoResetEvent notifyEvent; thread_ notifyThread; bool notifyStopFlag; DWORD srvStatus; DWORD notifyCount; size_t notifyRemovePos; vector<pair<DWORD, HANDLE>> registGUIList; vector<REGIST_TCP_INFO> registTCPList; HWND hwndNotify; UINT msgIDNotify; bool guiFlag; vector<NOTIFY_SRV_INFO> notifyList; vector<NOTIFY_SRV_INFO> notifySentList; protected: void SendNotify(); static void SendNotifyThread(CNotifyManager* sys); };
24.87037
65
0.742368
[ "vector" ]
14149aec5af29909c9fdd514f1739e78808aea2b
881
h
C
Source/DOM classes/SVG-DOM/SVGViewSpec.h
flemingm/SVGKit
5245e58ccbf2be2a618da37d9157d17c392be27b
[ "MIT" ]
null
null
null
Source/DOM classes/SVG-DOM/SVGViewSpec.h
flemingm/SVGKit
5245e58ccbf2be2a618da37d9157d17c392be27b
[ "MIT" ]
null
null
null
Source/DOM classes/SVG-DOM/SVGViewSpec.h
flemingm/SVGKit
5245e58ccbf2be2a618da37d9157d17c392be27b
[ "MIT" ]
null
null
null
/*! SVGViewSpec interface SVGViewSpec : SVGZoomAndPan, SVGFitToViewBox { readonly attribute SVGTransformList transform; readonly attribute SVGElement viewTarget; readonly attribute DOMString viewBoxString; readonly attribute DOMString preserveAspectRatioString; readonly attribute DOMString transformString; readonly attribute DOMString viewTargetString; }; */ #import <Foundation/Foundation.h> #import <SVGKit/SVGElement.h> @interface SVGViewSpec : NSObject /* FIXME: SVGTransformList not implemented yet: @property(nonatomic,readonly) SVGTransformList transform; */ @property(nonatomic,readonly) SVGElement* viewTarget; @property(nonatomic,readonly) NSString* viewBoxString; @property(nonatomic,readonly) NSString* preserveAspectRatioString; @property(nonatomic,readonly) NSString* transformString; @property(nonatomic,readonly) NSString* viewTargetString; @end
31.464286
108
0.824064
[ "transform" ]
1416b8c7c2ec1e4c757a02b6b268bb9455a9272f
1,799
h
C
include/linalg/animated_transform.h
Twinklebear/tray
eeb6dc930a3f81bb2abd74a41a4fb409a0e0865b
[ "MIT" ]
61
2015-01-01T10:58:21.000Z
2022-01-05T14:22:15.000Z
include/linalg/animated_transform.h
Twinklebear/tray
eeb6dc930a3f81bb2abd74a41a4fb409a0e0865b
[ "MIT" ]
null
null
null
include/linalg/animated_transform.h
Twinklebear/tray
eeb6dc930a3f81bb2abd74a41a4fb409a0e0865b
[ "MIT" ]
3
2016-04-11T19:07:47.000Z
2018-05-31T12:40:50.000Z
#ifndef ANIMATED_TRANSFORM_H #define ANIMATED_TRANSFORM_H #include <array> #include "linalg/transform.h" #include "linalg/quaternion.h" /* * Animated transformation based on interpolating two transforms * between the given times, based on Shoemake and Duff (1992) and * PBR */ class AnimatedTransform { const float start_time, end_time; const bool animated; Transform start_transform, end_transform; //The decomposed start and end transformations std::array<Vector, 2> translation; std::array<Quaternion, 2> rotation; std::array<Matrix4, 2> scaling; public: /* * Create a transform that interpolates between the start and * end transformations over the start and end times */ AnimatedTransform(const Transform &start_transform, float start_time, const Transform &end_transform, float end_time); /* * Compute the interpolated transform at some point */ Transform interpolate(float t) const; void interpolate(float t, Transform &transform) const; /* * Compute the bounds the BBox covers when animated with this transformation */ BBox motion_bound(const BBox &b) const; Point operator()(float t, const Point &p) const; void operator()(float t, const Point &p, Point &out) const; Vector operator()(float t, const Vector &v) const; void operator()(float t, const Vector &v, Vector &out) const; Ray operator()(const Ray &r) const; void operator()(const Ray &r, Ray &out) const; RayDifferential operator()(const RayDifferential &r) const; void operator()(const RayDifferential &r, RayDifferential &out) const; private: /* * Decompose a transformation into its translation, rotation * and scaling components as descibed by Shoemake and Duff & PBR */ static void decompose(const Matrix4 &m, Vector &trans, Quaternion &rot, Matrix4 &scale); }; #endif
31.017241
77
0.748193
[ "vector", "transform" ]
141b9502d646ea91745fff5f87374297e321778a
7,755
h
C
Source/Plugins/bsfRenderBeast/Shading/BsTiledDeferred.h
webhaikal/bsf
a4df35e3dee098a32ad09ecdfbada8956764bb83
[ "MIT" ]
3
2020-04-14T06:23:18.000Z
2020-06-02T11:07:08.000Z
Source/Plugins/bsfRenderBeast/Shading/BsTiledDeferred.h
cwmagnus/bsf
c735aead580e86e69ef228f3b8d99b474b72f2c7
[ "MIT" ]
null
null
null
Source/Plugins/bsfRenderBeast/Shading/BsTiledDeferred.h
cwmagnus/bsf
c735aead580e86e69ef228f3b8d99b474b72f2c7
[ "MIT" ]
null
null
null
//************************************ bs::framework - Copyright 2018 Marko Pintera **************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// #pragma once #include "BsRenderBeastPrerequisites.h" #include "Renderer/BsRendererMaterial.h" #include "Renderer/BsParamBlocks.h" #include "RenderAPI/BsGpuPipelineParamInfo.h" #include "BsRendererLight.h" #include "BsRendererReflectionProbe.h" namespace bs { namespace ct { struct SkyInfo; struct SceneInfo; class RendererViewGroup; /** @addtogroup RenderBeast * @{ */ BS_PARAM_BLOCK_BEGIN(TiledLightingParamDef) BS_PARAM_BLOCK_ENTRY(Vector4I, gLightCounts) BS_PARAM_BLOCK_ENTRY(Vector2I, gLightStrides) BS_PARAM_BLOCK_ENTRY(Vector2I, gFramebufferSize) BS_PARAM_BLOCK_END extern TiledLightingParamDef gTiledLightingParamDef; /** Shader that performs a lighting pass over data stored in the Gbuffer. */ class TiledDeferredLightingMat : public RendererMaterial<TiledDeferredLightingMat> { RMAT_DEF_CUSTOMIZED("TiledDeferredLighting.bsl"); /** Helper method used for initializing variations of this material. */ template<UINT32 msaa> static const ShaderVariation& getVariation() { static ShaderVariation variation = ShaderVariation( { ShaderVariation::Param("MSAA_COUNT", msaa) }); return variation; } public: TiledDeferredLightingMat(); /** Binds the material for rendering, sets up parameters and executes it. */ void execute(const RendererView& view, const VisibleLightData& lightData, const GBufferTextures& gbuffer, const SPtr<Texture>& inputTexture, const SPtr<Texture>& lightAccumTex, const SPtr<Texture>& lightAccumTexArray, const SPtr<Texture>& msaaCoverage); /** Returns the material variation matching the provided parameters. */ static TiledDeferredLightingMat* getVariation(UINT32 msaaCount); private: UINT32 mSampleCount; GBufferParams mGBufferParams; GpuParamBuffer mLightBufferParam; GpuParamLoadStoreTexture mOutputTextureParam; GpuParamTexture mInColorTextureParam; GpuParamTexture mMSAACoverageTexParam; SPtr<GpuParamBlockBuffer> mParamBuffer; static const UINT32 TILE_SIZE; }; /** * Moves data from a texture array into a MSAA texture. Primarily useful when needing to do unordered writes to a * MSAA texture which isn't directly supported on some backends, so writes are done to a texture array instead. The * array is expected to have the same number of layers as the number of samples in the MSAA texture, each layer * containing a sample for that specific pixel. */ class TextureArrayToMSAATexture : public RendererMaterial<TextureArrayToMSAATexture> { RMAT_DEF("TextureArrayToMSAATexture.bsl"); public: TextureArrayToMSAATexture(); /** Binds the material for rendering, sets up parameters and executes it. */ void execute(const SPtr<Texture>& inputArray, const SPtr<Texture>& target); private: GpuParamTexture mInputParam; }; BS_PARAM_BLOCK_BEGIN(ClearLoadStoreParamDef) BS_PARAM_BLOCK_ENTRY(Vector2I, gSize) BS_PARAM_BLOCK_ENTRY(Vector4, gFloatClearVal) BS_PARAM_BLOCK_ENTRY(Vector4I, gIntClearVal) BS_PARAM_BLOCK_END extern ClearLoadStoreParamDef gClearLoadStoreParamDef; /** Possible object types used as clear destinations by ClearLoadStoreMat. */ enum class ClearLoadStoreType { Texture, TextureArray, Buffer }; /** Possible data types used in destination objects in ClearLoadStoreMat. */ enum class ClearLoadStoreDataType { Float, Int }; /** Clears the provided texture to zero, using a compute shader. */ class ClearLoadStoreMat : public RendererMaterial<ClearLoadStoreMat> { RMAT_DEF_CUSTOMIZED("ClearLoadStore.bsl"); /** Helper method used for initializing variations of this material. */ template<ClearLoadStoreType OBJ_TYPE, ClearLoadStoreDataType DATA_TYPE, UINT32 NUM_COMPONENTS> static const ShaderVariation& getVariation() { static ShaderVariation variation = ShaderVariation( { ShaderVariation::Param("OBJ_TYPE", (int)OBJ_TYPE), ShaderVariation::Param("DATA_TYPE", (int)DATA_TYPE), ShaderVariation::Param("NUM_COMPONENTS", NUM_COMPONENTS), }); return variation; } public: ClearLoadStoreMat(); /** * Binds the material for rendering, sets up parameters and executes it. Only works on variations of * this material intended for textures and texture arrays. */ void execute(const SPtr<Texture>& target, const Color& clearValue = Color::ZERO, const TextureSurface& surface = TextureSurface::COMPLETE); /** * Binds the material for rendering, sets up parameters and executes it. Only works on variations of * this material intended for buffers. */ void execute(const SPtr<GpuBuffer>& target, const Color& clearValue = Color::ZERO); /** * Returns the material variation matching the provided parameters. * * @param[in] objType Type of object used for clear source. * @param[in] dataType Base data type stored in the clear source object. * @param[in] numComponents Number of components in the source objects's data type (e.g. float2, float4). * In range [1, 4]. * @return Material variation matching the provided values. */ static ClearLoadStoreMat* getVariation(ClearLoadStoreType objType, ClearLoadStoreDataType dataType, UINT32 numComponents); private: /** TILE_SIZE * TILE_SIZE is the number of pixels to process per thread. */ static constexpr UINT32 TILE_SIZE = 4; /** Number of threads to launch per work group. */ static constexpr UINT32 NUM_THREADS = 128; GpuParamLoadStoreTexture mOutputTextureParam; GpuParamBuffer mOutputBufferParam; SPtr<GpuParamBlockBuffer> mParamBuffer; }; BS_PARAM_BLOCK_BEGIN(TiledImageBasedLightingParamDef) BS_PARAM_BLOCK_ENTRY(Vector2I, gFramebufferSize) BS_PARAM_BLOCK_END extern TiledImageBasedLightingParamDef gTiledImageBasedLightingParamDef; /** Shader that performs a lighting pass over data stored in the Gbuffer. */ class TiledDeferredImageBasedLightingMat : public RendererMaterial<TiledDeferredImageBasedLightingMat> { RMAT_DEF_CUSTOMIZED("TiledDeferredImageBasedLighting.bsl"); /** Helper method used for initializing variations of this material. */ template<UINT32 msaa> static const ShaderVariation& getVariation() { static ShaderVariation variation = ShaderVariation( { ShaderVariation::Param("MSAA_COUNT", msaa) }); return variation; } public: /** Container for parameters to be passed to the execute() method. */ struct Inputs { GBufferTextures gbuffer; SPtr<Texture> lightAccumulation; SPtr<Texture> sceneColorTex; SPtr<Texture> sceneColorTexArray; SPtr<Texture> preIntegratedGF; SPtr<Texture> ambientOcclusion; SPtr<Texture> ssr; SPtr<Texture> msaaCoverage; }; TiledDeferredImageBasedLightingMat(); /** Binds the material for rendering, sets up parameters and executes it. */ void execute(const RendererView& view, const SceneInfo& sceneInfo, const VisibleReflProbeData& probeData, const Inputs& inputs); /** Returns the material variation matching the provided parameters. */ static TiledDeferredImageBasedLightingMat* getVariation(UINT32 msaaCount); private: UINT32 mSampleCount; GpuParamTexture mGBufferA; GpuParamTexture mGBufferB; GpuParamTexture mGBufferC; GpuParamTexture mGBufferDepth; GpuParamTexture mInColorTextureParam; GpuParamTexture mMSAACoverageTexParam; ImageBasedLightingParams mImageBasedParams; GpuParamLoadStoreTexture mOutputTextureParam; SPtr<GpuParamBlockBuffer> mParamBuffer; ReflProbeParamBuffer mReflProbeParamBuffer; static const UINT32 TILE_SIZE; }; /** @} */ }}
33.426724
124
0.760155
[ "object" ]
141daf8d6db69baacb61d6d98905190e013ab149
1,040
c
C
nitan/kungfu/skill/mahayana.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
1
2019-03-27T07:25:16.000Z
2019-03-27T07:25:16.000Z
nitan/kungfu/skill/mahayana.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
nitan/kungfu/skill/mahayana.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
// mahayana.c 大乘涅磐功 //Last Modified by winder on Mar. 10 2000 #include <ansi.h>; inherit SKILL; string type() { return "knowledge"; } int learn_bonus() { return 30; } int practice_bonus() { return 30; } int success() { return 30; } int power_point(object me) { return 1; } int valid_learn(object me) { if( query("shen", me)<0 ) return notify_fail("你的邪氣太重,無法修煉大乘涅磐功。\n"); return 1; } void skill_improved(object me) { if ((int)me->query_skill("mahayana", 1) == 120 && !query("sl_gift/mhyn", me) && query("gender", me) != "男性" ) { addn("dex", 1, me); set("sl_gift/mhyn", 1, me); tell_object(me, HIM "\n你的大乘涅磐功學有所成,提高了你的身法。\n" NOR); } } int help(object me) { write(HIC"\n大乘涅磐功:"NOR"\n"); write(@HELP 峨嵋派素不喜與人爭鬥,弟子門人常常閉門修煉以增長人體潛 能,其有效程度乃取決於佛法修為(即大乘涅磐功的等級)。打坐 靜修可在峨嵋禪房使用命令jingzuo。請help jingzuo。 學習要求: 相應的臨濟十二莊 不能學禪宗心法外的其他宗教心法 HELP ); return 1; }
21.666667
71
0.558654
[ "object" ]
141f433cd1767ce39cbb3c0391ebdf919a9cd8d2
9,417
h
C
RecoVertex/VertexTools/interface/SequentialVertexFitter.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
RecoVertex/VertexTools/interface/SequentialVertexFitter.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
RecoVertex/VertexTools/interface/SequentialVertexFitter.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#ifndef SequentialVertexFitter_H #define SequentialVertexFitter_H #include "RecoVertex/VertexPrimitives/interface/VertexFitter.h" #include "RecoVertex/VertexTools/interface/LinearizationPointFinder.h" #include "RecoVertex/VertexPrimitives/interface/VertexUpdator.h" #include "RecoVertex/VertexPrimitives/interface/VertexSmoother.h" #include "RecoVertex/VertexTools/interface/LinearizedTrackStateFactory.h" #include "RecoVertex/VertexTools/interface/VertexTrackFactory.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/isFinite.h" #include <cmath> // #include "TrackingTools/TransientTrack/interface/TransientTrack.h" // #include "Vertex/VertexPrimitives/interface/VertexSeedFactory.h" /** * Sequential vertex fitter, where the vertex is updated one track * at the time. * The fitter will iterate over the set of tracks until the transverse * distance between vertices computed in the previous and the current * iterations is less than the specified convergence criteria, or until * the maximum number of iterations is reached. * The transverse distance determines the linearization error. * The default convergence criterion is 1 mm. The default maximum * number of steps is 10. * These parameters can be configured in .orcarc ( * SequentialVertexFitter:maximumDistance and * SequentialVertexFitter:maximumNumberOfIterations). * After the vertex fit, the tracks can be refit with the additional * constraint of the vertex position. */ template <unsigned int N> class SequentialVertexFitter : public VertexFitter<N> { public: typedef ReferenceCountingPointer<RefittedTrackState<N> > RefCountedRefittedTrackState; typedef ReferenceCountingPointer<VertexTrack<N> > RefCountedVertexTrack; typedef ReferenceCountingPointer<LinearizedTrackState<N> > RefCountedLinearizedTrackState; /** * Reimplemented constructors to use any kind of * linearisation point finder, vertex updator and smoother. * If no smoother is to be used, do not specify an instance for it. */ SequentialVertexFitter(const LinearizationPointFinder & linP, const VertexUpdator<N> & updator, const VertexSmoother<N> & smoother, const AbstractLTSFactory<N> & ltsf); /** * Same as above, using a ParameterSet to set the convergence criteria */ SequentialVertexFitter(const edm::ParameterSet& pSet, const LinearizationPointFinder & linP, const VertexUpdator<N> & updator, const VertexSmoother<N> & smoother, const AbstractLTSFactory<N> & ltsf); /** * Copy constructor */ SequentialVertexFitter(const SequentialVertexFitter & original); ~SequentialVertexFitter() override; /** * Method to set the convergence criterion * (the maximum distance between the vertex computed in the previous * and the current iterations to consider the fit to have converged) */ void setMaximumDistance(float maxShift) {theMaxShift = maxShift;} /** * Method to set the maximum number of iterations to perform */ void setMaximumNumberOfIterations(int maxIterations) {theMaxStep = maxIterations;} /** * Method returning the fitted vertex, from a container of reco::TransientTracks. * The linearization point will be searched with the given LP finder. * No prior vertex position will be used in the vertex fit. * \param tracks The container of RecTracks to fit. * \return The fitted vertex */ CachingVertex<N> vertex(const std::vector<reco::TransientTrack> & tracks) const override; /** * Method returning the fitted vertex, from a container of VertexTracks. * For the first loop, the LinearizedTrackState contained in the VertexTracks * will be used. If subsequent loops are needed, the new VertexTracks will * be created with the last estimate of the vertex as linearization point. * No prior vertex position will be used in the vertex fit. * \param tracks The container of VertexTracks to fit. * \return The fitted vertex */ CachingVertex<N> vertex(const std::vector<RefCountedVertexTrack> & tracks) const override; /** * Same as above, only now also with BeamSpot! */ CachingVertex<N> vertex(const std::vector<RefCountedVertexTrack> & tracks, const reco::BeamSpot & spot ) const override; /** Fit vertex out of a set of RecTracks. Uses the specified linearization point. */ CachingVertex<N> vertex(const std::vector<reco::TransientTrack> & tracks, const GlobalPoint& linPoint) const override; /** Fit vertex out of a set of TransientTracks. * The specified BeamSpot will be used as priot, but NOT for the linearization. * The specified LinearizationPointFinder will be used to find the linearization point. */ CachingVertex<N> vertex(const std::vector<reco::TransientTrack> & tracks, const reco::BeamSpot& beamSpot) const override; /** Fit vertex out of a set of RecTracks. * Uses the position as both the linearization point AND as prior * estimate of the vertex position. The error is used for the * weight of the prior estimate. */ CachingVertex<N> vertex(const std::vector<reco::TransientTrack> & tracks, const GlobalPoint& priorPos, const GlobalError& priorError) const override; /** Fit vertex out of a set of VertexTracks * Uses the position and error for the prior estimate of the vertex. * This position is not used to relinearize the tracks. */ CachingVertex<N> vertex(const std::vector<RefCountedVertexTrack> & tracks, const GlobalPoint& priorPos, const GlobalError& priorError) const override; /** * Method returning the fitted vertex, from a VertexSeed. * For the first loop, the position of the VertexSeed will be used as * linearization point. If subsequent loops are needed, the new VertexTracks * will be created with the last estimate of the vertex as linearization point. * In case a non-sero error is given, the position and error of the * VertexSeed will be used as prior estimate in the vertex fit. * \param seed The VertexSeed to fit. * \return The fitted vertex */ // virtual CachingVertex<N> vertex(const RefCountedVertexSeed seed) const; /** * Access methods */ const LinearizationPointFinder * linearizationPointFinder() const {return theLinP;} const VertexUpdator<N> * vertexUpdator() const {return theUpdator;} const VertexSmoother<N> * vertexSmoother() const {return theSmoother;} const float maxShift() const {return theMaxShift;} const int maxStep() const {return theMaxStep;} const edm::ParameterSet parameterSet() const {return thePSet;} SequentialVertexFitter * clone() const override { return new SequentialVertexFitter(* this); } const AbstractLTSFactory<N> * linearizedTrackStateFactory() const { return theLTrackFactory;} protected: /** * Default constructor. Is here, as we do not want anybody to use it. */ SequentialVertexFitter() {} private: /** * The methode where the vrte fit is actually done. The seed is used as the * prior estimate in the vertex fit (in case its error is large, it will have * little influence on the fit. * The tracks will be relinearized in case further loops are needed. * \parameter tracks The tracks to use in the fit. * \paraemter priorVertex The prior estimate of the vertex * \return The fitted vertex */ CachingVertex<N> fit(const std::vector<RefCountedVertexTrack> & tracks, const VertexState priorVertex, bool withPrior) const; /** * Construct a container of VertexTrack from a set of RecTracks. * \param tracks The container of RecTracks. * \param seed The seed to use for the VertexTracks. This position will * also be used as the new linearization point. * \return The container of VertexTracks which are to be used in the next fit. */ std::vector<RefCountedVertexTrack> linearizeTracks(const std::vector<reco::TransientTrack> & tracks, const VertexState state) const; /** * Construct new a container of VertexTrack with a new linearization point * and vertex seed, from an existing set of VertexTrack, from which only the * recTracks will be used. * \param tracks The original container of VertexTracks, from which the RecTracks * will be extracted. * \param seed The seed to use for the VertexTracks. This position will * also be used as the new linearization point. * \return The container of VertexTracks which are to be used in the next fit. */ std::vector<RefCountedVertexTrack> reLinearizeTracks( const std::vector<RefCountedVertexTrack> & tracks, const VertexState state) const; /** * Reads the configurable parameters. */ void readParameters(); void setDefaultParameters(); /** * Checks whether any of the three coordinates is a Nan */ inline bool hasNan(const GlobalPoint& point) const { using namespace std; return (edm::isNotFinite(point.x())|| edm::isNotFinite(point.y()) || edm::isNotFinite(point.z())); } float theMaxShift; int theMaxStep; edm::ParameterSet thePSet; LinearizationPointFinder* theLinP; VertexUpdator<N> * theUpdator; VertexSmoother<N> * theSmoother; const AbstractLTSFactory<N> * theLTrackFactory; // LinearizedTrackStateFactoryAbstractLTSFactory theLTrackFactory; VertexTrackFactory<N> theVTrackFactory; // VertexSeedFactory theVSeedFactory; }; #endif
35.535849
122
0.742062
[ "vector" ]
141fab73eb94b5d25dc9979a54a15960acd16d16
9,529
c
C
src/property_list_service.c
hposix/libimobiledevice-qt
de55bb7e8a201e37e0335a07c85e7ad156bb4307
[ "MIT" ]
4
2016-11-29T08:59:46.000Z
2021-01-21T18:06:43.000Z
src/property_list_service.c
hposix/libimobiledevice-qt
de55bb7e8a201e37e0335a07c85e7ad156bb4307
[ "MIT" ]
1
2016-11-29T10:06:58.000Z
2016-12-03T03:10:45.000Z
src/property_list_service.c
hposix/libimobiledevice-qt
de55bb7e8a201e37e0335a07c85e7ad156bb4307
[ "MIT" ]
2
2016-11-21T07:35:20.000Z
2019-12-01T09:29:33.000Z
/* * property_list_service.c * PropertyList service implementation. * * Copyright (c) 2010 Nikias Bassen. All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdlib.h> #include <string.h> #include "property_list_service.h" #include "common/debug.h" #include "endianness.h" /** * Convert a service_error_t value to a property_list_service_error_t value. * Used internally to get correct error codes. * * @param err A service_error_t error code * * @return A matching property_list_service_error_t error code, * PROPERTY_LIST_SERVICE_E_UNKNOWN_ERROR otherwise. */ static property_list_service_error_t service_to_property_list_service_error(service_error_t err) { switch (err) { case SERVICE_E_SUCCESS: return PROPERTY_LIST_SERVICE_E_SUCCESS; case SERVICE_E_INVALID_ARG: return PROPERTY_LIST_SERVICE_E_INVALID_ARG; case SERVICE_E_MUX_ERROR: return PROPERTY_LIST_SERVICE_E_MUX_ERROR; case SERVICE_E_SSL_ERROR: return PROPERTY_LIST_SERVICE_E_SSL_ERROR; default: break; } return PROPERTY_LIST_SERVICE_E_UNKNOWN_ERROR; } LIBIMOBILEDEVICE_API property_list_service_error_t property_list_service_client_new(idevice_t device, lockdownd_service_descriptor_t service, property_list_service_client_t *client) { if (!device || !service || service->port == 0 || !client || *client) return PROPERTY_LIST_SERVICE_E_INVALID_ARG; service_client_t parent = NULL; service_error_t rerr = service_client_new(device, service, &parent); if (rerr != SERVICE_E_SUCCESS) { return service_to_property_list_service_error(rerr); } /* create client object */ property_list_service_client_t client_loc = (property_list_service_client_t)malloc(sizeof(struct property_list_service_client_private)); client_loc->parent = parent; /* all done, return success */ *client = client_loc; return PROPERTY_LIST_SERVICE_E_SUCCESS; } LIBIMOBILEDEVICE_API property_list_service_error_t property_list_service_client_free(property_list_service_client_t client) { if (!client) return PROPERTY_LIST_SERVICE_E_INVALID_ARG; property_list_service_error_t err = service_to_property_list_service_error(service_client_free(client->parent)); free(client); client = NULL; return err; } /** * Sends a plist using the given property list service client. * Internally used generic plist send function. * * @param client The property list service client to use for sending. * @param plist plist to send * @param binary 1 = send binary plist, 0 = send xml plist * * @return PROPERTY_LIST_SERVICE_E_SUCCESS on success, * PROPERTY_LIST_SERVICE_E_INVALID_ARG when one or more parameters are * invalid, PROPERTY_LIST_SERVICE_E_PLIST_ERROR when dict is not a valid * plist, or PROPERTY_LIST_SERVICE_E_UNKNOWN_ERROR when an unspecified * error occurs. */ static property_list_service_error_t internal_plist_send(property_list_service_client_t client, plist_t plist, int binary) { property_list_service_error_t res = PROPERTY_LIST_SERVICE_E_UNKNOWN_ERROR; char *content = NULL; uint32_t length = 0; uint32_t nlen = 0; int bytes = 0; if (!client || (client && !client->parent) || !plist) { return PROPERTY_LIST_SERVICE_E_INVALID_ARG; } if (binary) { plist_to_bin(plist, &content, &length); } else { plist_to_xml(plist, &content, &length); } if (!content || length == 0) { return PROPERTY_LIST_SERVICE_E_PLIST_ERROR; } nlen = htobe32(length); debug_info("sending %d bytes", length); service_send(client->parent, (const char*)&nlen, sizeof(nlen), (uint32_t*)&bytes); if (bytes == sizeof(nlen)) { service_send(client->parent, content, length, (uint32_t*)&bytes); if (bytes > 0) { debug_info("sent %d bytes", bytes); debug_plist(plist); if ((uint32_t)bytes == length) { res = PROPERTY_LIST_SERVICE_E_SUCCESS; } else { debug_info("ERROR: Could not send all data (%d of %d)!", bytes, length); } } } if (bytes <= 0) { debug_info("ERROR: sending to device failed."); } free(content); return res; } LIBIMOBILEDEVICE_API property_list_service_error_t property_list_service_send_xml_plist(property_list_service_client_t client, plist_t plist) { return internal_plist_send(client, plist, 0); } LIBIMOBILEDEVICE_API property_list_service_error_t property_list_service_send_binary_plist(property_list_service_client_t client, plist_t plist) { return internal_plist_send(client, plist, 1); } /** * Receives a plist using the given property list service client. * Internally used generic plist receive function. * * @param client The property list service client to use for receiving * @param plist pointer to a plist_t that will point to the received plist * upon successful return * @param timeout Maximum time in milliseconds to wait for data. * * @return PROPERTY_LIST_SERVICE_E_SUCCESS on success, * PROPERTY_LIST_SERVICE_E_INVALID_ARG when client or *plist is NULL, * PROPERTY_LIST_SERVICE_E_PLIST_ERROR when the received data cannot be * converted to a plist, PROPERTY_LIST_SERVICE_E_MUX_ERROR when a * communication error occurs, or PROPERTY_LIST_SERVICE_E_UNKNOWN_ERROR * when an unspecified error occurs. */ static property_list_service_error_t internal_plist_receive_timeout(property_list_service_client_t client, plist_t *plist, unsigned int timeout) { property_list_service_error_t res = PROPERTY_LIST_SERVICE_E_UNKNOWN_ERROR; uint32_t pktlen = 0; uint32_t bytes = 0; if (!client || (client && !client->parent) || !plist) { return PROPERTY_LIST_SERVICE_E_INVALID_ARG; } *plist = NULL; service_error_t serr = service_receive_with_timeout(client->parent, (char*)&pktlen, sizeof(pktlen), &bytes, timeout); if ((serr == SERVICE_E_SUCCESS) && (bytes == 0)) { return PROPERTY_LIST_SERVICE_E_RECEIVE_TIMEOUT; } debug_info("initial read=%i", bytes); if (bytes < 4) { debug_info("initial read failed!"); return PROPERTY_LIST_SERVICE_E_MUX_ERROR; } else { pktlen = be32toh(pktlen); if (pktlen < (1 << 24)) { /* prevent huge buffers */ uint32_t curlen = 0; char *content = NULL; debug_info("%d bytes following", pktlen); content = (char*)malloc(pktlen); if (!content) { debug_info("out of memory when allocating %d bytes", pktlen); return PROPERTY_LIST_SERVICE_E_UNKNOWN_ERROR; } while (curlen < pktlen) { service_receive(client->parent, content+curlen, pktlen-curlen, &bytes); if (bytes <= 0) { res = PROPERTY_LIST_SERVICE_E_MUX_ERROR; break; } debug_info("received %d bytes", bytes); curlen += bytes; } if (curlen < pktlen) { debug_info("received incomplete packet (%d of %d bytes)", curlen, pktlen); if (curlen > 0) { debug_info("incomplete packet following:"); debug_buffer(content, curlen); } free(content); return res; } if ((pktlen > 8) && !memcmp(content, "bplist00", 8)) { plist_from_bin(content, pktlen, plist); } else if ((pktlen > 5) && !memcmp(content, "<?xml", 5)) { /* iOS 4.3+ hack: plist data might contain invalid characters, thus we convert those to spaces */ for (bytes = 0; bytes < pktlen-1; bytes++) { if ((content[bytes] >= 0) && (content[bytes] < 0x20) && (content[bytes] != 0x09) && (content[bytes] != 0x0a) && (content[bytes] != 0x0d)) content[bytes] = 0x20; } plist_from_xml(content, pktlen, plist); } else { debug_info("WARNING: received unexpected non-plist content"); debug_buffer(content, pktlen); } if (*plist) { debug_plist(*plist); res = PROPERTY_LIST_SERVICE_E_SUCCESS; } else { res = PROPERTY_LIST_SERVICE_E_PLIST_ERROR; } free(content); content = NULL; } else { res = PROPERTY_LIST_SERVICE_E_UNKNOWN_ERROR; } } return res; } LIBIMOBILEDEVICE_API property_list_service_error_t property_list_service_receive_plist_with_timeout(property_list_service_client_t client, plist_t *plist, unsigned int timeout) { return internal_plist_receive_timeout(client, plist, timeout); } LIBIMOBILEDEVICE_API property_list_service_error_t property_list_service_receive_plist(property_list_service_client_t client, plist_t *plist) { return internal_plist_receive_timeout(client, plist, 10000); } LIBIMOBILEDEVICE_API property_list_service_error_t property_list_service_enable_ssl(property_list_service_client_t client) { if (!client || !client->parent) return PROPERTY_LIST_SERVICE_E_INVALID_ARG; return service_to_property_list_service_error(service_enable_ssl(client->parent)); } LIBIMOBILEDEVICE_API property_list_service_error_t property_list_service_disable_ssl(property_list_service_client_t client) { if (!client || !client->parent) return PROPERTY_LIST_SERVICE_E_INVALID_ARG; return service_to_property_list_service_error(service_disable_ssl(client->parent)); }
34.400722
181
0.753175
[ "object" ]
14201cca7574f3fc436279bfbbb390c0d10cc3a7
5,232
h
C
baseVideo/avd_sdk.framework/Headers/AVDLivecast.h
ZhangQiJin/videoChat
a930f1ca7114b4c23c7359ea5e99732ad5113646
[ "MIT" ]
1
2020-12-25T03:30:47.000Z
2020-12-25T03:30:47.000Z
baseVideo/avd_sdk.framework/Headers/AVDLivecast.h
ZhangQiJin/videoChat
a930f1ca7114b4c23c7359ea5e99732ad5113646
[ "MIT" ]
1
2020-07-05T14:45:17.000Z
2021-01-24T04:39:06.000Z
baseVideo/avd_sdk.framework/Headers/AVDLivecast.h
ZhangQiJin/videoChat
a930f1ca7114b4c23c7359ea5e99732ad5113646
[ "MIT" ]
null
null
null
// // AVDLivecast.h // avd_sdk // // Created by skin on 15-7-21. // Copyright (c) 2015年 t3ee. All rights reserved. // #ifndef avd_sdk_AVDLivecast_h #define avd_sdk_AVDLivecast_h #import "AVDCommon.h" #import "AVDVideoView.h" #import "AVDEasyRoom.h" #import "AVDFakeVideoCapturer.h" #import "AVDFakeAudioCapturer.h" /** 客户端直播状态定义 * * @note 状态迁移图 * * [success] [success] * 1.init -----(init)--> 2.connecting --> 3.ready ------(publishRTMP)--> 4.livecast * A <--[failed] | <--[failed] | * | | | * | | [conn loss] [conn loss]| * | --------> 5.reconnecting <---- * | <--------- | ------> * | [reconnected] | [reconnected] * ---------------------------------------------------------- * [reconnect failed] */ enum AVDLivecastStatus { lc_init, /**< 初始状态 */ lc_connecting, /**< 正在连接服务器 */ lc_ready, /**< 视频可以预览,准备好可以直播 */ lc_livecast, /**< 正在直播 */ lc_reconnecting, /**< 正在与服务器重连接 */ }; /** * 直播回调接口类 * * 直播回调接口定义了直播对象操作的异步返回,直播状态通知等。 */ @protocol AVDLivecastDelegate<NSObject> /// 通知 /** 直播流状态更改通知 * * @param[in] status 当前直播状态。 * @note 开始推流时,会每间隔 3s 调用该回调方法来反馈该 3s 内的流状态,包括视频帧率、音频帧率、音视频总码率 */ - (void) onStatus:(enum AVDLivecastStatus)status; /** 直播网络状态通知 * * @param[in] status 当前网络状态。 */ - (void) onConnectionStatus:(enum AVDConnectionStatus)status; /** 直播错误通知 * * @param[in] error 错误码 * @param[in] message 错误消息 */ - (void) onError:(AVDResult)error message:(NSString*)message; @end @protocol AVDStreamStatsDelegate<NSObject> /// 通知 /** 间隔 3s 调用该回调方法来反馈该 3s 内的流状态,包括视频帧率、音视频总码率 * * @param[in] videofps 视频帧率。 * @param[in] avbps 音视频总码率: kbps。 */ - (void) onStreamlast3Stats:(NSUInteger)videofps avbps:(NSUInteger)avbps; @end /** * 直播接口类 * * 直播接口定义了直播对象创建和释放、直播功能操作。 */ @interface AVDLivecast : NSObject @property (nonatomic,weak) id <AVDLivecastDelegate> delegate; /**< 直播回调代理 */ @property (nonatomic,weak) id <AVDStreamStatsDelegate> streamStatsdelegate; /**< 直播推流状态回调代理 */ @property (nonatomic,retain) AVDVideoParams *videoParams; /**< 视频参数 */ @property (nonatomic,retain) AVDAudioParams *audioParams; /**< 音频参数 */ @property (nonatomic,assign,readonly) enum AVDLivecastStatus status; /**< 直播状态 */ @property (nonatomic,assign,readonly) BOOL isMicrophoneMute; /**< 麦克风是否mute状态 */ /** 设置直播Id * @return 返回错误代码。 * @note 直播Id唯一标识一个直播,设置后才能使用直播接口。 */ + (AVDResult)setLivecastId:(AVDRoomId)castId; /** 获取直播接口 * @return 返回直播接口指针。 * @note 当前需要先设置直播Id,后才能使用下面所有接口。 * @sa setLivecastId */ + (AVDLivecast*) instance; /** 释放直播接口 */ + (void) destory; /** 直播对象初始化 * * @return 返回错误代码。 */ - (AVDResult) initContext; /** 直播对象反初始化 * @return 返回错误代码。 */ - (AVDResult) uninit; /** 设置视频显示窗口 * @param[in] render 本地预览render接口。 * @return 返回错误代码。 * @sa IVideoRender */ - (AVDResult) setDisplayView:(id<AVDVideoRenderer>)render; /** 设置视频外部导入数据源 * * @param[in] vcapturer 视频外部导入数据源。 * @return 返回错误代码。 * @sa FakeVideoCapturer */ - (AVDResult) setVideoSource:(AVDFakeVideoCapturer*)vcapturer; /** 设置音频外部导入数据源 * * @param[in] acapturer 音频外部导入数据源。 * @return 返回错误代码。 * @sa FakeAudioCapturer */ - (AVDResult) setAudioSource:(AVDFakeAudioCapturer*)acapturer; /** 预览本地缺省摄像头视频 * @return 返回错误代码。 */ - (AVDResult) startPreview; /** 取消预览缺省摄像头视频 * @return 返回错误代码。 */ - (AVDResult) stopPreview; /** 视频切换摄像头 * @return 返回错误代码。 */ - (AVDResult) switchCamera; /** 本地麦克风静默 * @return 返回错误代码。 */ - (AVDResult) muteMicrophone; /** 本地麦克风静默取消 * @return 返回错误代码。 */ - (AVDResult) unmuteMicrophone; /** 抓取直播图像 * * @param[in] quality 图像质量:0-100, 0最差,100最好。 * @return 返回错误代码。 * @note 目前在直播状态下,播放端无法抓取视频(rtmp播放器播放的时候) */ - (AVDResult) captureImage:(NSInteger)quality; /** 开始直播 * * @param[in] pushUrl 直播rtmp推流地址。 * @return 返回错误代码。 */ - (AVDResult) publisRTMP:(NSString*)pushUrl; /** 停止直播 * * @return 返回错误代码。 */ - (AVDResult) unpublish; /** 判断是否正在连麦中 * @return 是否正在连麦。 */ - (BOOL) isInRoom; /** 直播开始连麦 * * @param[in] room 互动房间接口。 * @return 返回错误代码。 * @note 互动房间通过创建IEasyRoom操作,需要先创建IEasyRoom接口,然后与直播接口进行挂接 * 直播互动挂接,系统内部会实现以下缺省操作: * 1. 自动挂接直播的采集音视频流到房间的采集音视频流 * 2. 自动挂接房间的合屏视频流和混音音频流到直播推送音视频流 * @sa IEasyRoom */ - (AVDResult) attachRoom:(AVDEasyRoom*)room; /** 直播停止连麦 * @return 返回错误代码。 */ - (AVDResult) detachRoom; /** 设置房间选项 * * @param[in] type 房间选项类型。 * @param[in] svalue 选项内容,根据选项说明填入。 * @return 返回错误代码。 */ - (AVDResult) setOption:(enum AVDRoomOption)type value:(NSString*)svalue; /** 获取房间选项 * * @param[in] type 房间选项类型。 * @return 返回选项内容,根据选项说明解析。 */ - (NSString*) getOption:(enum AVDRoomOption)type; #ifndef DOXYGEN_SHOULD_SKIP_THIS // Disallow init and don't add to documentation - (id)init __attribute__(( unavailable("init is not a supported initializer for this class."))); #endif /* DOXYGEN_SHOULD_SKIP_THIS */ @end #endif
23.150442
94
0.599006
[ "render" ]
14224bdbe609ad54009a8a1b6e36088050791f31
409
h
C
engine/include/System.h
moreal/BS_Engine
92680a137d546895dfe280987aea7b3c02821bdd
[ "MIT" ]
null
null
null
engine/include/System.h
moreal/BS_Engine
92680a137d546895dfe280987aea7b3c02821bdd
[ "MIT" ]
null
null
null
engine/include/System.h
moreal/BS_Engine
92680a137d546895dfe280987aea7b3c02821bdd
[ "MIT" ]
null
null
null
#pragma once /** * @brief A system that is a singleton object in the system layer. * @see README */ class System { public: /// @brief Initializes everything necessary to run the game engine. bool Initialize() noexcept; /// @brief To constantly call to update the scene with the manager. void RunLoop() noexcept; /// @brief Clean up everything created by the game engine. void Release() noexcept; };
22.722222
68
0.718826
[ "object" ]
1423435dcb19dd1267bab07b615d8a808d5435c1
5,196
h
C
samples/sample_fei/include/fei_encode.h
strassek-snapshots/MediaSDK
1d419006b9bb10d93c1ade7bd6643c6d73e63efc
[ "MIT" ]
null
null
null
samples/sample_fei/include/fei_encode.h
strassek-snapshots/MediaSDK
1d419006b9bb10d93c1ade7bd6643c6d73e63efc
[ "MIT" ]
null
null
null
samples/sample_fei/include/fei_encode.h
strassek-snapshots/MediaSDK
1d419006b9bb10d93c1ade7bd6643c6d73e63efc
[ "MIT" ]
1
2018-01-04T06:53:11.000Z
2018-01-04T06:53:11.000Z
/******************************************************************************\ Copyright (c) 2005-2017, Intel Corporation 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 copyright holder 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. This sample was distributed or derived from the Intel's Media Samples package. The original version of this sample may be obtained from https://software.intel.com/en-us/intel-media-server-studio or https://software.intel.com/en-us/media-client-solutions-support. \**********************************************************************************/ #ifndef __SAMPLE_FEI_ENCODE_INTERFACE_H__ #define __SAMPLE_FEI_ENCODE_INTERFACE_H__ #include "encoding_task.h" #include "predictors_repacking.h" #ifndef MFX_VERSION #error MFX_VERSION not defined #endif class FEI_EncodeInterface { private: FEI_EncodeInterface(const FEI_EncodeInterface& other_encode); // forbidden FEI_EncodeInterface& operator= (const FEI_EncodeInterface& other_encode); // forbidden public: MFXVideoSession* m_pmfxSession; MFXVideoENCODE* m_pmfxENCODE; mfxEncodeCtrl m_encodeControl; mfxVideoParam m_videoParams; mfxU32 m_allocId; bufList* m_pExtBuffers; AppConfig* m_pAppConfig; mfxBitstream m_mfxBS; mfxSyncPoint m_SyncPoint; bool m_bSingleFieldMode; /* Bitstream writer */ CSmplBitstreamWriter m_FileWriter; /* For I/O operations with extension buffers */ FILE* m_pMvPred_in; FILE* m_pENC_MBCtrl_in; FILE* m_pMbQP_in; FILE* m_pRepackCtrl_in; FILE* m_pWeights_in; FILE* m_pMBstat_out; FILE* m_pMV_out; FILE* m_pMBcode_out; #if (MFX_VERSION >= 1025) FILE* m_pRepackStat_out; #endif std::vector<mfxExtBuffer*> m_InitExtParams; /* Temporary memory to speed up computations */ std::vector<mfxI16> m_tmpForMedian; std::vector<mfxExtFeiPreEncMV::mfxExtFeiPreEncMVMB> m_tmpForReading; mfxExtFeiEncMV::mfxExtFeiEncMVMB m_tmpMBencMV; FEI_EncodeInterface(MFXVideoSession* session, mfxU32 allocId, bufList* ext_bufs, AppConfig* config); ~FEI_EncodeInterface(); mfxStatus Init() { return m_pmfxENCODE->Init(&m_videoParams); } mfxStatus Close() { return m_pmfxENCODE->Close(); } mfxStatus Reset(mfxU16 width = 0, mfxU16 height = 0, mfxU16 crop_w = 0, mfxU16 crop_h = 0) { if (width && height && crop_w && crop_h) { m_videoParams.mfx.FrameInfo.Width = width; m_videoParams.mfx.FrameInfo.Height = height; m_videoParams.mfx.FrameInfo.CropW = crop_w; m_videoParams.mfx.FrameInfo.CropH = crop_h; } return m_pmfxENCODE->Reset(&m_videoParams); } mfxStatus QueryIOSurf(mfxFrameAllocRequest* request) { return m_pmfxENCODE->QueryIOSurf(&m_videoParams, request); } mfxVideoParam* GetCommonVideoParams() { return &m_videoParams; } mfxStatus UpdateVideoParam() { return m_pmfxENCODE->GetVideoParam(&m_videoParams); } void GetRefInfo(mfxU16 & picStruct, mfxU16 & refDist, mfxU16 & numRefFrame, mfxU16 & gopSize, mfxU16 & gopOptFlag, mfxU16 & idrInterval, mfxU16 & numRefActiveP, mfxU16 & numRefActiveBL0, mfxU16 & numRefActiveBL1, mfxU16 & bRefType, bool & bSigleFieldProcessing); mfxStatus FillParameters(); mfxStatus InitFrameParams(iTask* eTask); mfxStatus AllocateSufficientBuffer(); mfxStatus EncodeOneFrame(iTask* eTask); mfxStatus FlushOutput(iTask* eTask); mfxStatus ResetState(); }; #endif // __SAMPLE_FEI_ENCODE_INTERFACE_H__
39.067669
755
0.685527
[ "vector" ]
142bb8bfcdf4a416cefd8675637526938940ad1b
671
h
C
src/Texture.h
Cykobox/Adventure
418aa9798e8a25ff77974d8c52157a4235358098
[ "libtiff", "Libpng", "BSD-3-Clause" ]
1
2015-09-25T20:36:50.000Z
2015-09-25T20:36:50.000Z
src/Texture.h
Cykobox/Adventure
418aa9798e8a25ff77974d8c52157a4235358098
[ "libtiff", "Libpng", "BSD-3-Clause" ]
null
null
null
src/Texture.h
Cykobox/Adventure
418aa9798e8a25ff77974d8c52157a4235358098
[ "libtiff", "Libpng", "BSD-3-Clause" ]
null
null
null
// // Texture.h // (c) Christopher Bauer 2014 // // Responsibilities: Own a single texture and render it to the screen. // #include <string> #include <SDL.h> class Texture { public: Texture(); ~Texture(); bool Load(SDL_Renderer* Renderer, std::string Filename); void Render(int X, int Y) const; void Render(int X, int Y, int Width, int Height) const; void Render(int X, int Y, int Width, int Height, int SX, int SY, int SWidth, int SHeight) const; int GetWidth() { return mWidth; } int GetHeight() { return mHeight; } private: std::string mFilename; int mWidth = 0; int mHeight = 0; SDL_Renderer* mpRenderer = NULL; SDL_Texture* mpSDLTexture = NULL; };
20.96875
97
0.691505
[ "render" ]
142c323e875728549db6c8ef01b9630078cc338a
7,927
h
C
ProjectTemplate/ProjectTemplate/inlcude/libMTKBleManager/SOSCallOperator.h
ChangXingGroup/SZPjoject
807e602e88ca0005f205234137e81342c9005f04
[ "MIT" ]
null
null
null
ProjectTemplate/ProjectTemplate/inlcude/libMTKBleManager/SOSCallOperator.h
ChangXingGroup/SZPjoject
807e602e88ca0005f205234137e81342c9005f04
[ "MIT" ]
null
null
null
ProjectTemplate/ProjectTemplate/inlcude/libMTKBleManager/SOSCallOperator.h
ChangXingGroup/SZPjoject
807e602e88ca0005f205234137e81342c9005f04
[ "MIT" ]
null
null
null
// // SOSCallOperator.h // MtkBleManager // // Created by user on 15-1-22. // Copyright (c) 2015年 ___MTK___. All rights reserved. // #import <Foundation/Foundation.h> #import "SOSContact.h" static const int CMD_TYPE_RESPONSE_ERROR = 0x11; static const int CMD_TYPE_SUPPORT_INDICATION = 0x12; static const int CMD_TYPE_RESPONSE_READ_NUM_NAME = 0X13; static const int CMD_TYPE_RESPONSE_WRITE_NUM_NAME = 0x14; static const int CMD_TYPE_REQUEST_READ = 0x03; static const int CMD_TYPE_REQUEST_WRITE = 0x04; //error response code static const int ERR_UNKNOWN_CMD = 0x01; static const int ERR_INVALID_VALUE = 0X02; static const int ERR_INVALID_KEY = 0x03; static const int ERR_INVALID_VALUE_LENTH = 0x04; static const int ERR_SOSLIST_FULL = 0x05; static const int ERR_INVALID_PDU = 0x06; //read request/response value flag static const int READ_VALUE_FLAG_NUM = 0x01; static const int READ_VALUE_FLAG_NAME = 0x02; static const int READ_VALUE_FLAG_MODE = 0x03; static const int READ_VALUE_FLAG_REPTIMES = 0x04; //write type static const int WRITE_TYPE_ADD = 0x00; static const int WRITE_TYPE_MODIFY = 0x01; static const int WRITE_TYPE_DELETE = 0x02; //call mode static const int CALL_MODE_AUTO = 0; static const int CALL_MODE_MANUAL = 1; /*! The delegate of SOSCallOperator object should adopt the SOSCallDataDelegate protocol. The delegate uses this protocol's method to monitor the indication and response from remote BLE device. */ @protocol SOSCallDataDelegate <NSObject> /*! This method is invoked after GATT is connected and handshake for DOGP is done. Remote BLE device will report some information automatically through this method. @param keyCout The hardware key count for SOS call supported by remote BLE device. @param indexC the index count under every hardware key @param modeValue Call mode saved in remote BLE device @param repTimes Repeate times saved in remote BLE device */ - (void)onIndication: (int)keyCout indexCount: (int)indexC mode: (int)modeValue repeatTimes: (int)repTimes; /*! Invoked after you retrieve contact information from remote BLE device. NOTE: If some contacts already exist in remote BLE device, this method will also be invoke to report the contact information without calling <code>sendReadContact:index:</code> @param keyId Key ID @param index Index ID @param nameVal contact name saved in remote BLE device @param numberVal contact phone number saved in remote BLE device */ - (void)onReadNameNumber: (int)keyId indexId: (int)index name: (NSString *)nameVal number: (NSString *)numberVal; /*! Invoked after you retrieve call mode from remote BLE device @param keyId Key ID @param index Index ID @param modeVal call mode returned from remote BLE device */ - (void)onReadMode: (int)keyId indexId: (int)index mode: (int)modeVal; /*! Invoked after you retrieve repeate times from remote BLE device @param keyId Key ID @param index Key ID @param repTimesVal Repeate times return from remote BLE device */ - (void)onReadRepTimes: (int)keyId indexId: (int)index repTimes: (int)repTimesVal; /*! Invoked after connect state changes @param state current connect state after change. <code> 0: DISCONNECTED 2: CONNECTED </code> */ - (void)onConnectStateChange: (int)state; /*! Invoked after you write contact/mode/repeate time to remote BLE device successfully @param cmdLabel Reserved for future use @param type The write type parameter for the write command which triggers this callback. @param keyIdVal The Key ID parameter for the write command which triggers this callback. @param indexIdVal The Index ID parameter for the write command which triggers this callback. @param valueTagArray The tag array shows the value which is wrote/updated successfully to remote BLE device. tag: <code> 0x01: contact number 0x02: contact name 0x03: call mode 0x04: repeate times </code> */ - (void)onWriteCallBack: (int)cmdLabel writeType: (int)type keyId: (int)keyIdVal indexId: (int)indexIdVal valueTag: (NSArray *)valueTagArray; @end @interface SOSCallOperator : NSObject /*! If the default object does not exists yet, it is created. @return Returns the defaults object. */ + (id)getSosCallOperaterInstance; - (void)registerSOSCallDelegate: (id<SOSCallDataDelegate>)delegate; - (void)unRegisterSOSCallDelegate: (id<SOSCallDataDelegate>)delegate; /*! Set contact info including name and phone number to remote BLE device. When it sets contacts successfully to remote device, it calls <code>onWriteCallBack</code> method of its delegate. @param keyId the key ID which is to be set @param indexId the index ID belongs to the key which is to be set @param contactVal the contact value @param updateType should be <code>WRITE_TYPE_ADD</code>, <code>WRITE_TYPE_MODIFY</code> or <code>WRITE_TYPE_DELETE</code> */ - (void)setContact: (int)keyId index: (int)indexId contact: (SOSContact *)contactVal updateType: (int)updateType; /*! Set only contact name to remote BLE device. When it sets contact name successfully to remote device, it calls <code>onWriteCallBack</code> method of its delegate. @param keyId the key ID which is to be set @param indexId the index ID belongs to the key which is to be set @param nameVal contact name @param type should be <code>WRITE_TYPE_ADD</code>, <code>WRITE_TYPE_MODIFY</code> or <code>WRITE_TYPE_DELETE</code> */ -(void)sendWriteContactName: (int)keyId index: (int)indexId name: (NSString *)nameVal updateType: (int)type; /*! Set only contact phone number to remote BLE device. When it sets contact phone number successfully to remote device, it calls <code>onWriteCallBack</code> method of its delegate. @param keyId the key ID which is to be set @param indexId the index ID belongs to the key which is to be set @param numVal contact phone number @param type should be <code>WRITE_TYPE_ADD</code>, <code>WRITE_TYPE_MODIFY</code> or <code>WRITE_TYPE_DELETE</code> */ - (void)sendWriteContactNumber: (int)keyId index: (int)indexId number: (NSString *)numVal updateType: (int)type; /*! Retrieves contact info from remote BLE device. The delegate <code>onReadNameNumber</code> will be called if get contact successfully @param keyId Key ID @param indexId Index ID */ - (void)sendReadContact: (int)keyId index: (int)indexId; /*! Delete contact at remote BLE device. When it deletes contact successfully in remote device, it calls <code>onWriteCallBack</code> method of its delegate. @param keyId Key ID @param indexId Index ID */ - (void)sendDeleteContact: (int)keyId index: (int)indexId; /*! Set call mode to remote BLE device. When it writes call mode successfully to remote device, it calls <code>onWriteCallBack</code> method of its delegate. @param keyId Key ID @param indexId Index ID @param modeVal call mode value which is to be set */ - (void)sendWriteMode: (int)keyId index: (int)indexId mode: (int)modeVal; /*! Retrieves call mode from remote BLE device The delegate <code>onReadMode</code> will be called if get contact successfully @param keyId Key ID @param indexId Index ID */ - (void)sendReadMode: (int)keyId index: (int)indexId; /*! Set Repeat Times to remote BLE device. When it sets repeate times successfully to remote device, it calls <code>onWriteCallBack</code> method of its delegate. @param keyId Key ID @param indexId Index ID @param repTimesVal Repeat times which to be set */ - (void)sendWriteRepeatTime: (int)keyId index: (int)indexId repeat: (int)repTimesVal; /*! Retrieves Repeat times from remote BLE device. The delegate <code>onReadRepTimes</code> will be called if get contact successfully @param keyId Key ID @param indexId Index ID */ - (void)sendReadRepeatTime: (int)keyId index: (int)indexId; @end
35.547085
178
0.750473
[ "object" ]
14343f9226f8b3aace4eb4e1815c7883b1250aa5
900
h
C
include/ShadeRecord.h
encelo/pmTracer
aee6d2b2e0166b526459794cb7befb808921ee3d
[ "MIT" ]
2
2020-11-02T19:41:02.000Z
2021-12-10T00:03:17.000Z
include/ShadeRecord.h
encelo/pmTracer
aee6d2b2e0166b526459794cb7befb808921ee3d
[ "MIT" ]
null
null
null
include/ShadeRecord.h
encelo/pmTracer
aee6d2b2e0166b526459794cb7befb808921ee3d
[ "MIT" ]
null
null
null
#ifndef PMTRACER_SHADERECORD_H #define PMTRACER_SHADERECORD_H #include "Vector3.h" #include "Ray.h" #include "RGBColor.h" namespace pm { class Material; class World; class Tracer; class ShadeRecord { public: /// True if the ray hit an object bool hitAnObject; /// Material of the nearest object const Material *material; /// World coordinates of hit point Vector3 hitPoint; /// Hit point in local object coordinates Vector3 localHitPoint; /// Surface normal at hit point Vector3 normal; /// For specular highlights Ray ray; /// Recursion depth int depth; /// For area lights Vector3 dir; /// Ray parameter float t; /// Reference to the world const World &world; /// Reference to the tracer const Tracer &tracer; ShadeRecord(const World &wr, const Tracer &tr) : hitAnObject(false), material(nullptr), depth(0), t(0.0f), world(wr), tracer(tr) {} }; } #endif
18.75
50
0.707778
[ "object" ]
143ecbda06adfc6b5572849b5b5796dc29f83d09
3,103
h
C
projects/math_library/code/vec4.h
Surmage/test_math_library
aa7e56f7da44476826d354c3fcb9d1f6ac20f639
[ "MIT" ]
null
null
null
projects/math_library/code/vec4.h
Surmage/test_math_library
aa7e56f7da44476826d354c3fcb9d1f6ac20f639
[ "MIT" ]
null
null
null
projects/math_library/code/vec4.h
Surmage/test_math_library
aa7e56f7da44476826d354c3fcb9d1f6ac20f639
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <assert.h> namespace Math { class vec4 { public: float x; float y; float z; float w; vec4() { x = 0; y = 0; z = 0; w = 0; } vec4(float const nx, float const ny, float const nz, float const nw) { x = nx; y = ny; z = nz; w = nw; } vec4(vec4 const& v) { x = v.x; y = v.y; z = v.z; w = v.w; } void operator=(vec4 const& rhs) { this->x = rhs.x; this->y = rhs.y; this->z = rhs.z; this->w = rhs.w; } vec4 operator-() { vec4 newVec(-x, -y, -z, -w); return newVec; } vec4 operator+(vec4 const& v) { vec4 newVec(x + v.x, y + v.y, z + v.z, w + v.w); return newVec; } void operator+=(vec4 const& rhs) { this->x += rhs.x; this->y += rhs.y; this->z += rhs.z; this->w += rhs.w; } vec4 operator-(vec4 const& rhs) { vec4 newVec(x - rhs.x, y - rhs.y, z - rhs.z, w - rhs.w); return newVec; } void operator-=(vec4 const& rhs) { this->x -= rhs.x; this->y -= rhs.y; this->z -= rhs.z; this->w -= rhs.w; } void operator*=(float const scalar) { this->x *= scalar; this->y *= scalar; this->z *= scalar; this->w *= scalar; } vec4 operator*(float const scalar) { vec4 newVec(x * scalar, y * scalar, z * scalar, w * scalar); return newVec; } bool operator==(vec4 const& rhs) { return this->x == rhs.x && this->y == rhs.y && this->z == rhs.z && this->w == rhs.w; } bool operator!=(vec4 const& rhs) { if ((x != rhs.x) || (y != rhs.y) || (z != rhs.z) || (w != rhs.w)) return true; else return false; } float& operator[](unsigned int const i) { assert(i >= 0 && i <= 3); switch (i) { case 1: return y; case 2: return z; case 3: return w; case 0: default: return x; } } const float operator[](unsigned int const i) const { assert(i >= 0 && i <= 3); switch (i) { case 1: return y; case 2: return z; case 3: return w; case 0: default: return x; } } float setElement(unsigned int const i, float const value) { if (i > 3) { std::cerr << "Error\n"; return -1; } if (i == 0) this->x = value; else if (i == 1) this->y = value; else if (i == 2) this->z = value; else if (i == 3) this->w = value; return 0; } float getElement(unsigned int const i)const { if (i > 3) { std::cerr << "Error\n"; return -1; } if (i == 0) return x; else if (i == 1) return y; else if (i == 2) return z; else if (i == 3) return w; return 0; } void printVec4()const { std::cout << x << ", " << y << ", " << z << ", " << w << "\n"; } }; float dot(vec4 const& a, vec4 const& b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } float length(vec4 const& v) { return sqrt(powf(v.x, 2) + powf(v.y, 2) + powf(v.z, 2) + powf(v.w, 2)); } vec4 normalize(vec4 const& v) { //convert to unit vector float vecLen = length(v); vec4 newVec; newVec.x = v.x / vecLen; newVec.y = v.y / vecLen; newVec.z = v.z / vecLen; newVec.w = v.w; return newVec; } }
19.639241
87
0.508862
[ "vector" ]
afd87d398f8461abf5e22462d7dc3735f842a76a
8,453
h
C
fake/tennis/include/api/cpp/workbench.h
TenniS-Open/SeetaAIPLib
8676683d7a0e6b3b5c55ad573c8fa49be0c84041
[ "BSD-2-Clause" ]
null
null
null
fake/tennis/include/api/cpp/workbench.h
TenniS-Open/SeetaAIPLib
8676683d7a0e6b3b5c55ad573c8fa49be0c84041
[ "BSD-2-Clause" ]
null
null
null
fake/tennis/include/api/cpp/workbench.h
TenniS-Open/SeetaAIPLib
8676683d7a0e6b3b5c55ad573c8fa49be0c84041
[ "BSD-2-Clause" ]
null
null
null
// // Created by kier on 2019/3/16. // #ifndef TENNIS_API_CPP_WORKBENCH_H #define TENNIS_API_CPP_WORKBENCH_H #include "../workbench.h" #include "except.h" #include "device.h" #include "module.h" #include "tensor.h" #include "image_filter.h" #include "program.h" #include <string> namespace ts { namespace api { enum class CpuPowerMode : int32_t { BALANCE = TS_CPU_BALANCE, BIG_CORE = TS_CPU_BIG_CORE, LITTLE_CORE = TS_CPU_LITTLE_CORE, }; /** * @see ts_Workbench */ class Workbench { public: using self = Workbench; using raw = ts_Workbench; using shared = std::shared_ptr<self>; using shared_raw = std::shared_ptr<raw>; static self NewRef(raw *ptr) { return self(ptr); } Workbench(const self &) = default; Workbench &operator=(const self &) = default; raw *get_raw() const { return m_impl.get(); } bool operator==(std::nullptr_t) const { return get_raw() == nullptr; } bool operator!=(std::nullptr_t) const { return get_raw() != nullptr; } // Workbench() : self((ts_Device*)(nullptr)) {} Workbench(std::nullptr_t) {} Workbench() = default; explicit Workbench(const Device &device) : self(device.get_raw()) {} explicit Workbench(const ts_Device *device) : self(ts_new_Workbench(device)) { TS_API_AUTO_CHECK(m_impl != nullptr); } static Workbench Load(const Module &module, const Device &device) { return Load(module.get_raw(), device.get_raw()); } static Workbench Load(const ts_Module *module, const Device &device) { return Load(module, device.get_raw()); } static Workbench Load(const Module &module, const ts_Device *device) { return Load(module.get_raw(), device); } static Workbench Load(const ts_Module *module, const ts_Device *device) { Workbench loaded(ts_Workbench_Load(module, device)); TS_API_AUTO_CHECK(loaded.m_impl != nullptr); return std::move(loaded); } Workbench clone() const { Workbench dolly(ts_Workbench_clone(m_impl.get())); TS_API_AUTO_CHECK(dolly.m_impl != nullptr); return std::move(dolly); } void input(int slot, const ts_Tensor *tensor) { TS_API_AUTO_CHECK(ts_Workbench_input(m_impl.get(), slot, tensor)); } void input(int slot, const Tensor &tensor) { input(slot, tensor.get_raw()); } void input(const std::string &name, const ts_Tensor *tensor) { TS_API_AUTO_CHECK(ts_Workbench_input_by_name(m_impl.get(), name.c_str(), tensor)); } void input(const std::string &name, const Tensor &tensor) { input(name, tensor.get_raw()); } void run() { TS_API_AUTO_CHECK(ts_Workbench_run(m_impl.get())); } void output(int slot, ts_Tensor *tensor) { TS_API_AUTO_CHECK(ts_Workbench_output(m_impl.get(), slot, tensor)); } void output(int slot, const Tensor &tensor) { output(slot, tensor.get_raw()); } void output(const std::string &name, ts_Tensor *tensor) { TS_API_AUTO_CHECK(ts_Workbench_output_by_name(m_impl.get(), name.c_str(), tensor)); } void output(const std::string &name, Tensor &tensor) { output(name, tensor.get_raw()); } Tensor output(int slot) { Tensor tensor; output(slot, tensor); return std::move(tensor); } Tensor output(const std::string &name) { Tensor tensor; output(name, tensor); return std::move(tensor); } void set_computing_thread_number(int number) { TS_API_AUTO_CHECK(ts_Workbench_set_computing_thread_number(m_impl.get(), number)); } void bind_filter(int slot, const ts_ImageFilter *filter) { TS_API_AUTO_CHECK(ts_Workbench_bind_filter(m_impl.get(), slot, filter)); } void bind_filter(int slot, const ImageFilter &tensor) { bind_filter(slot, tensor.get_raw()); } void bind_filter(const std::string &name, const ts_ImageFilter *filter) { TS_API_AUTO_CHECK(ts_Workbench_bind_filter_by_name(m_impl.get(), name.c_str(), filter)); } void bind_filter(const std::string &name, const ImageFilter &tensor) { bind_filter(name, tensor.get_raw()); } void setup_context() const { TS_API_AUTO_CHECK(ts_Workbench_setup_context(m_impl.get())); } void setup(const ts_Program *program) { TS_API_AUTO_CHECK(ts_Workbench_setup(m_impl.get(), program)); } void setup(const Program &program) { TS_API_AUTO_CHECK(ts_Workbench_setup(m_impl.get(), program.get_raw())); } Program compile(const Module &module) { return compile(module.get_raw()); } Program compile(const ts_Module *module) { auto program = Program::NewRef(ts_Workbench_compile(m_impl.get(), module)); TS_API_AUTO_CHECK(program != nullptr); return std::move(program); } void setup_device() const { TS_API_AUTO_CHECK(ts_Workbench_setup_device(m_impl.get())); } void setup_runtime() const { TS_API_AUTO_CHECK(ts_Workbench_setup_runtime(m_impl.get())); } int input_count() const { return ts_Workbench_input_count(m_impl.get()); } int output_count() const { return ts_Workbench_output_count(m_impl.get()); } void run_hook(const std::vector<std::string> &node_names) { std::vector<const char *> c_node_names(node_names.size()); for (size_t i = 0; i < node_names.size(); ++i) { c_node_names[i] = node_names[i].c_str(); } TS_API_AUTO_CHECK( ts_Workbench_run_hook(m_impl.get(), c_node_names.data(), int32_t(c_node_names.size()))); } static Workbench Load(const Module &module, const Device &device, const std::string &options) { Workbench loaded(ts_Workbench_Load_v2(module.get_raw(), device.get_raw(), options.c_str())); TS_API_AUTO_CHECK(loaded.m_impl != nullptr); return std::move(loaded); } Program compile(const Module &module, const std::string &options) { auto program = Program::NewRef(ts_Workbench_compile_v2(m_impl.get(), module.get_raw(), options.c_str())); TS_API_AUTO_CHECK(program != nullptr); return std::move(program); } void set_operator_param(const std::string &node_name, const std::string &param, const Tensor &value) { TS_API_AUTO_CHECK(ts_Workbench_set_operator_param( m_impl.get(), node_name.c_str(), param.c_str(), value.get_raw())) } std::string summary() const { auto json = ts_Workbench_summary(m_impl.get()); TS_API_AUTO_CHECK(json != nullptr); return json; } bool set_cpu_mode(ts_CpuPowerMode mode) { return ts_Workbench_set_cpu_mode(m_impl.get(), mode); } bool set_cpu_mode(CpuPowerMode mode) { return ts_Workbench_set_cpu_mode(m_impl.get(), ts_CpuPowerMode(mode)); } private: Workbench(raw *ptr) : m_impl(pack(ptr)) {} static shared_raw pack(raw *ptr) { return shared_raw(ptr, ts_free_Workbench); } shared_raw m_impl; }; } } #endif //TENNIS_API_CPP_WORKBENCH_H
34.643443
121
0.552585
[ "vector" ]
afdbe769428571979373167b10e1ebb618ed0f5e
1,321
h
C
GameState.h
DimpyRed/pandemonium_c_code
38c1a2410b234e704ba036dea421cc619206665b
[ "MIT" ]
null
null
null
GameState.h
DimpyRed/pandemonium_c_code
38c1a2410b234e704ba036dea421cc619206665b
[ "MIT" ]
2
2020-04-14T01:25:38.000Z
2020-04-27T16:29:12.000Z
GameState.h
DimpyRed/pandemonium_c_code
38c1a2410b234e704ba036dea421cc619206665b
[ "MIT" ]
null
null
null
// // Created by david on 4/9/20. // #ifndef PANDEMONIUM_C_CODE_GAMESTATE_H #define PANDEMONIUM_C_CODE_GAMESTATE_H #include "Piece.h" #include <vector> #include "Position.h" #include <iostream> //organized in counter-clockwise direction for your convenience const int ADJACENT_VECTORS[6][2] = {{1,0}, {0,1}, {-1, 1}, {-1, 0}, {0, -1}, {1, -1}}; /* * 'pieces' should be the only permanent date structure used. * */ class GameState{ public: GameState(); GameState(const GameState& other); ~GameState(); void addPiece(int pos_x, int pos_y, int team, int type); void addPiece(int pos_x, int pos_y, int team); void removePiece(Piece *p); bool position_empty(int pos_x, int pos_y); void movePieceAbsolute(Piece *p, int pos_x, int pos_y); void movePieceRelative(Piece *p, int move_x, int move_y); std::vector<Position> getAdjacentSpaces(int pos_x, int pos_y); bool areAdjacent(Position pos_1, Position Pos_2); bool pieceExists(Piece *p); std::vector<Piece*> pieceList(); bool onBoard(int x, int y); Piece* atLocation(int x, int y); Piece* correspondingPiece(Piece *p, GameState other); std::string GameStateToStringConverter(); void printBoardInText(); private: std::vector<Piece *> pieces; }; #endif //PANDEMONIUM_C_CODE_GAMESTATE_H
24.018182
86
0.689629
[ "vector" ]
afdd9209ec615b2ec6b490620d51730a4777ef3d
1,131
h
C
Game/src/TextureData.h
rasmusrosengren/OpenGL3DGame
db6101d8aae97b8798a99ae458e62d2a8b407acb
[ "MIT" ]
null
null
null
Game/src/TextureData.h
rasmusrosengren/OpenGL3DGame
db6101d8aae97b8798a99ae458e62d2a8b407acb
[ "MIT" ]
null
null
null
Game/src/TextureData.h
rasmusrosengren/OpenGL3DGame
db6101d8aae97b8798a99ae458e62d2a8b407acb
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <vector> #include "dependencies\stb_image.h" class TextureData { private: int m_width; int m_height; int m_channels; unsigned char* m_data; public: TextureData(const std::string& path, int forcedChannels = 4); // Returns the rgb value of a pixel; const int getRGB(int x, int y) const; // Returns the red channel value of a pixel, returns 0 if invalid range const unsigned char getR(int x, int y) const; // Returns the green channel value of a pixel, returns 0 if invalid range const unsigned char getG(int x, int y) const; // Returns the blue channel value of a pixel, returns 0 if invalid range const unsigned char getB(int x, int y) const; // Returns the alpha channel value of a pixel, returns 0 if invalid range unsigned char getA(int x, int y) const; // Returns the width of the texture in pixels const int getWidth() const; // Returns the height of the texture in pixels const int getHeight() const; // Returns the number of channels of the texture const int getChannels() const; // Returns the texture data const unsigned char* getData() const; };
25.704545
74
0.733864
[ "vector" ]
afe309d9600eafb8a0b591e3317fb9961d4a182c
2,030
h
C
ThirdParty/fides/vtkfides/fides/CoordinateSystem.h
gabrielventosa/vtk
723711d79b0a23de6f07421a27e89539f9d500da
[ "BSD-3-Clause" ]
2
2021-07-07T22:53:19.000Z
2021-07-31T19:29:35.000Z
ThirdParty/fides/vtkfides/fides/CoordinateSystem.h
gabrielventosa/vtk
723711d79b0a23de6f07421a27e89539f9d500da
[ "BSD-3-Clause" ]
2
2020-11-18T16:50:34.000Z
2022-01-21T13:31:47.000Z
ThirdParty/fides/vtkfides/fides/CoordinateSystem.h
gabrielventosa/vtk
723711d79b0a23de6f07421a27e89539f9d500da
[ "BSD-3-Clause" ]
5
2020-10-02T10:14:35.000Z
2022-03-10T07:50:22.000Z
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. // //============================================================================ #ifndef fides_datamodel_CoordinateSystem_H_ #define fides_datamodel_CoordinateSystem_H_ #include <fides/Array.h> #include <fides/DataModel.h> #include <fides/MetaData.h> #include <vtkm/cont/CoordinateSystem.h> namespace fides { namespace datamodel { /// \brief Data model object for VTK-m coordinate systems. /// /// \c fides::datamodel::CoordinateSystem is responsible of creating /// VTK-m coordinate systems by loading data defined by the Fides /// data model. struct CoordinateSystem : public DataModelBase { /// Overridden to handle the undelying Array. The Array /// object determines the actual type of the coordinate system. void ProcessJSON(const rapidjson::Value& json, DataSourcesType& sources) override; /// Reads and returns coordinate systems. The heavy-lifting is /// handled by the underlying Array object. /// The paths are passed to the \c DataSources to create /// file paths. \c selections restrict the data that is loaded. std::vector<vtkm::cont::CoordinateSystem> Read( const std::unordered_map<std::string, std::string>& paths, DataSourcesType& sources, const fides::metadata::MetaData& selections); /// Returns the number of blocks in the underlying Array variable. /// Used by the reader to provide meta-data on blocks. size_t GetNumberOfBlocks( const std::unordered_map<std::string, std::string>& paths, DataSourcesType& sources); private: std::shared_ptr<fides::datamodel::Array> Array; bool NumberOfBlocksInitialized = false; size_t NumberOfBlocks = 0; }; } } #endif
32.741935
78
0.682266
[ "object", "vector", "model" ]
afe7bb54e245f5192b3f6a5a1e584c761889df77
949
h
C
gEarth.Pack/MeasureAreaHandler.h
songgod/gEarth
e4ea0fa15a40f08481c7ea7e42e6f4ace8659984
[ "MIT" ]
5
2021-06-16T06:24:29.000Z
2022-03-10T03:41:44.000Z
gEarth.Pack/MeasureAreaHandler.h
songgod/gEarth
e4ea0fa15a40f08481c7ea7e42e6f4ace8659984
[ "MIT" ]
1
2020-10-14T14:20:58.000Z
2020-10-14T14:20:58.000Z
gEarth.Pack/MeasureAreaHandler.h
songgod/gEarth
e4ea0fa15a40f08481c7ea7e42e6f4ace8659984
[ "MIT" ]
2
2021-06-16T06:24:32.000Z
2021-08-02T09:05:42.000Z
#pragma once #include "MeasureBaseHandler.h" namespace gEarthPack { class MeasureAreaHandler : public MeasureBaseHandler { public: MeasureAreaHandler(); ~MeasureAreaHandler(); public: class MeasureAreaResultHandler : public osg::Referenced { public: virtual void onAreaChanged(MeasureAreaHandler* sender, double area) = 0; }; public: typedef std::vector<osg::ref_ptr<MeasureAreaResultHandler>> ResultHandlers; ResultHandlers& getResHandlers() { return _reshandlers; } const ResultHandlers& getResHandlers() const { return _reshandlers; } void setSurface(bool b); bool getSurface() const { return _bsurface; } public: virtual bool handle(const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa); virtual osgEarth::Features::Feature* createFeature(); virtual void fireMeasureChanged(); virtual void clear(); private: bool _bsurface; bool _bnewmeasure; ResultHandlers _reshandlers; }; }
21.088889
85
0.74921
[ "vector" ]
aff423f16ee53882663b554fbd24db1d444e9cb0
742
c
C
lib/wizards/irmeli/area4/ruum24.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/irmeli/area4/ruum24.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/irmeli/area4/ruum24.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
inherit "room/room"; object monster; reset(arg) { if(!present("gremlin 2")) { move_object(clone_object("/wizards/irmeli/area4/gremlin3.c"), this_object()); move_object(clone_object("/wizards/irmeli/area4/gremlin3.c"), this_object()); } if(arg) return; add_exit("west","/wizards/irmeli/area4/ruum23.c"); set_not_out(1); short_desc = "Floor two inside the Orthanc, tower of death"; long_desc = "You are now at eastern-wing on floor two, but it ends right here. You have\n"+ "now only one exit from this room and unfortunately you need to go\n"+ "backwards, if you wan't see more big halls. This room doesn't\n"+ "look very domestic.\n"; }
16.488889
93
0.62938
[ "object" ]
aff6963247ef5cba0f6d267ea44c6f0044850c4c
1,419
h
C
sequential_line_search_2d_gui/core.h
takuma-ya/sequential_bayesian_optimization
cf0cc61adb4a66cbf3eb8e5f22e441d5af539f8f
[ "MIT" ]
null
null
null
sequential_line_search_2d_gui/core.h
takuma-ya/sequential_bayesian_optimization
cf0cc61adb4a66cbf3eb8e5f22e441d5af539f8f
[ "MIT" ]
null
null
null
sequential_line_search_2d_gui/core.h
takuma-ya/sequential_bayesian_optimization
cf0cc61adb4a66cbf3eb8e5f22e441d5af539f8f
[ "MIT" ]
null
null
null
#ifndef CORE_H #define CORE_H #include <vector> #include <memory> #include <Eigen/Core> #include "preference.h" #include "slider.h" class PreferenceRegressor; class MainWindow; class Core { public: Core(); static Core& getInstance() { static Core core; return core; } std::shared_ptr<PreferenceRegressor> regressor; MainWindow* mainWindow; bool use_MAP_hyperparameters; Eigen::MatrixXd X; std::vector<Preference> D; double evaluateObjectiveFunction(const Eigen::VectorXd &x) const; void clear() { X = Eigen::MatrixXd::Zero(0, 0); D.clear(); x_max = Eigen::VectorXd::Zero(0); regressor = nullptr; slider = nullptr; } // For optimization void proceedOptimization(); Eigen::VectorXd x_max; double y_max; // For regression void addData(const Eigen::VectorXd& x1, const Eigen::VectorXd &x2); void addData(const Eigen::VectorXd& x1, const Eigen::VectorXd &x2, const Eigen::VectorXd &x3); void addData(const std::vector<Eigen::VectorXd>& xs); void computeRegression(); // For slider management void updateSliderEnds(); std::shared_ptr<Slider> slider; Eigen::VectorXd computeParametersFromSlider(int sliderValue, int minValue, int maxValue) const; Eigen::VectorXd computeParametersFromSlider(double value) const; }; #endif // CORE_H
22.887097
99
0.662438
[ "vector" ]
afff2e1fff66299273f4471ba3abb5b49077b3e6
1,073
h
C
IfcPlusPlus/src/ifcpp/IFC4/include/IfcSurfaceSide.h
AlexVlk/ifcplusplus
2f8cd5457312282b8d90b261dbf8fb66e1c84057
[ "MIT" ]
426
2015-04-12T10:00:46.000Z
2022-03-29T11:03:02.000Z
IfcPlusPlus/src/ifcpp/IFC4/include/IfcSurfaceSide.h
AlexVlk/ifcplusplus
2f8cd5457312282b8d90b261dbf8fb66e1c84057
[ "MIT" ]
124
2015-05-15T05:51:00.000Z
2022-02-09T15:25:12.000Z
IfcPlusPlus/src/ifcpp/IFC4/include/IfcSurfaceSide.h
AlexVlk/ifcplusplus
2f8cd5457312282b8d90b261dbf8fb66e1c84057
[ "MIT" ]
214
2015-05-06T07:30:37.000Z
2022-03-26T16:14:04.000Z
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #pragma once #include <vector> #include <map> #include <sstream> #include <string> #include "ifcpp/model/GlobalDefines.h" #include "ifcpp/model/BasicTypes.h" #include "ifcpp/model/BuildingObject.h" // TYPE IfcSurfaceSide = ENUMERATION OF (POSITIVE ,NEGATIVE ,BOTH); class IFCQUERY_EXPORT IfcSurfaceSide : virtual public BuildingObject { public: enum IfcSurfaceSideEnum { ENUM_POSITIVE, ENUM_NEGATIVE, ENUM_BOTH }; IfcSurfaceSide() = default; IfcSurfaceSide( IfcSurfaceSideEnum e ) { m_enum = e; } virtual const char* className() const { return "IfcSurfaceSide"; } virtual shared_ptr<BuildingObject> getDeepCopy( BuildingCopyOptions& options ); virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const; virtual const std::wstring toString() const; static shared_ptr<IfcSurfaceSide> createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map ); IfcSurfaceSideEnum m_enum; };
32.515152
138
0.747437
[ "vector", "model" ]
b3012eb921b1e62a803b681f03954fbb17d14cea
2,431
h
C
base/version.h
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
321
2018-06-17T03:52:46.000Z
2022-03-18T02:34:52.000Z
base/version.h
j4ckfrost/android_external_chromium_org
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
19
2018-06-26T10:37:45.000Z
2020-12-09T03:16:45.000Z
base/version.h
j4ckfrost/android_external_chromium_org
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
268
2015-01-21T05:53:28.000Z
2022-03-25T22:09:01.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_VERSION_H_ #define BASE_VERSION_H_ #include <string> #include <vector> #include "base/base_export.h" #include "base/basictypes.h" namespace base { // Version represents a dotted version number, like "1.2.3.4", supporting // parsing and comparison. class BASE_EXPORT Version { public: // The only thing you can legally do to a default constructed // Version object is assign to it. Version(); ~Version(); // Initializes from a decimal dotted version number, like "0.1.1". // Each component is limited to a uint16. Call IsValid() to learn // the outcome. explicit Version(const std::string& version_str); // Returns true if the object contains a valid version number. bool IsValid() const; // Returns true if the version wildcard string is valid. The version wildcard // string may end with ".*" (e.g. 1.2.*, 1.*). Any other arrangement with "*" // is invalid (e.g. 1.*.3 or 1.2.3*). This functions defaults to standard // Version behavior (IsValid) if no wildcard is present. static bool IsValidWildcardString(const std::string& wildcard_string); // Commonly used pattern. Given a valid version object, compare if a // |version_str| results in a newer version. Returns true if the // string represents valid version and if the version is greater than // than the version of this object. bool IsOlderThan(const std::string& version_str) const; bool Equals(const Version& other) const; // Returns -1, 0, 1 for <, ==, >. int CompareTo(const Version& other) const; // Given a valid version object, compare if a |wildcard_string| results in a // newer version. This function will default to CompareTo if the string does // not end in wildcard sequence ".*". IsValidWildcard(wildcard_string) must be // true before using this function. int CompareToWildcardString(const std::string& wildcard_string) const; // Return the string representation of this version. const std::string GetString() const; const std::vector<uint16>& components() const { return components_; } private: std::vector<uint16> components_; }; } // namespace base // TODO(xhwang) remove this when all users are updated to explicitly use the // namespace using base::Version; #endif // BASE_VERSION_H_
33.30137
80
0.724805
[ "object", "vector" ]
b3037d33a172c870752ea43ea1604c297089930d
9,424
h
C
src/motioncore/protocols/yao/gate.h
Udbhavbisarya23/MOTION2NX
eb26f639d8c1729cebfa85dd3bf41b770cebe92b
[ "MIT" ]
6
2021-11-05T00:39:47.000Z
2022-02-26T16:42:55.000Z
src/motioncore/protocols/yao/gate.h
Udbhavbisarya23/MOTION2NX
eb26f639d8c1729cebfa85dd3bf41b770cebe92b
[ "MIT" ]
7
2021-11-07T06:53:00.000Z
2022-03-23T11:46:40.000Z
src/motioncore/protocols/yao/gate.h
Udbhavbisarya23/MOTION2NX
eb26f639d8c1729cebfa85dd3bf41b770cebe92b
[ "MIT" ]
7
2021-11-04T12:01:07.000Z
2022-03-29T12:15:23.000Z
// MIT License // // Copyright (c) 2020 Lennart Braun // // 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 <cstdint> #include <variant> #include "gate/new_gate.h" #include "utility/bit_vector.h" #include "utility/block.h" #include "utility/reusable_future.h" #include "wire.h" namespace ENCRYPTO::ObliviousTransfer { class FixedXCOT128Receiver; class FixedXCOT128Sender; class GOT128Receiver; class GOT128Sender; } // namespace ENCRYPTO::ObliviousTransfer namespace MOTION::proto::yao { class YaoProvider; class YaoWire; using YaoWireVector = std::vector<std::shared_ptr<YaoWire>>; enum class OutputRecipient : std::uint8_t; namespace detail { class BasicYaoInputGate : public NewGate { public: BasicYaoInputGate(std::size_t gate_id, YaoProvider&, std::size_t num_wires, std::size_t num_simd); BasicYaoInputGate(std::size_t gate_id, YaoProvider&, std::size_t num_wires, std::size_t num_simd, ENCRYPTO::ReusableFiberFuture<std::vector<ENCRYPTO::BitVector<>>>&&); YaoWireVector& get_output_wires() noexcept { return outputs_; }; protected: YaoProvider& yao_provider_; const std::size_t num_wires_; const std::size_t num_simd_; ENCRYPTO::ReusableFiberFuture<std::vector<ENCRYPTO::BitVector<>>> input_future_; YaoWireVector outputs_; }; class BasicYaoOutputGate : public NewGate { public: BasicYaoOutputGate(std::size_t gate_id, YaoProvider&, YaoWireVector&&, OutputRecipient); virtual ENCRYPTO::ReusableFiberFuture<std::vector<ENCRYPTO::BitVector<>>> get_output_future() = 0; protected: YaoProvider& yao_provider_; std::size_t num_wires_; ENCRYPTO::ReusableFiberPromise<std::vector<ENCRYPTO::BitVector<>>> output_promise_; ENCRYPTO::ReusableFiberFuture<ENCRYPTO::BitVector<>> bits_future_; ENCRYPTO::BitVector<> decoding_info_; const YaoWireVector inputs_; OutputRecipient output_recipient_; }; class BasicYaoUnaryGate : public NewGate { public: BasicYaoUnaryGate(std::size_t gate_id, YaoProvider&, YaoWireVector&&, bool forward); YaoWireVector& get_output_wires() noexcept { return outputs_; }; protected: YaoProvider& yao_provider_; std::size_t num_wires_; const YaoWireVector inputs_; YaoWireVector outputs_; }; class BasicYaoBinaryGate : public NewGate { public: BasicYaoBinaryGate(std::size_t gate_id, YaoProvider&, YaoWireVector&&, YaoWireVector&&); YaoWireVector& get_output_wires() noexcept { return outputs_; }; protected: YaoProvider& yao_provider_; std::size_t num_wires_; const YaoWireVector inputs_a_; const YaoWireVector inputs_b_; YaoWireVector outputs_; }; } // namespace detail class YaoInputGateGarbler : public detail::BasicYaoInputGate { public: YaoInputGateGarbler(std::size_t gate_id, YaoProvider&, std::size_t num_wires, std::size_t num_simd, bool in_setup); YaoInputGateGarbler(std::size_t gate_id, YaoProvider&, std::size_t num_wires, std::size_t num_simd, bool in_setup, ENCRYPTO::ReusableFiberFuture<std::vector<ENCRYPTO::BitVector<>>>&&); // create with in_setup = false YaoInputGateGarbler(std::size_t gate_id, YaoProvider&, std::size_t num_wires, std::size_t num_simd); YaoInputGateGarbler(std::size_t gate_id, YaoProvider&, std::size_t num_wires, std::size_t num_simd, ENCRYPTO::ReusableFiberFuture<std::vector<ENCRYPTO::BitVector<>>>&&); bool need_setup() const noexcept override { return true; } bool need_online() const noexcept override { return true; } void evaluate_setup() override; void evaluate_online() override; private: std::variant<bool, std::shared_ptr<ENCRYPTO::ObliviousTransfer::GOT128Sender>, std::shared_ptr<ENCRYPTO::ObliviousTransfer::FixedXCOT128Sender>> ot_sender_; }; class YaoInputGateEvaluator : public detail::BasicYaoInputGate { public: YaoInputGateEvaluator(std::size_t gate_id, YaoProvider&, std::size_t num_wires, std::size_t num_simd, bool in_setup); YaoInputGateEvaluator(std::size_t gate_id, YaoProvider&, std::size_t num_wires, std::size_t num_simd, bool in_setup, ENCRYPTO::ReusableFiberFuture<std::vector<ENCRYPTO::BitVector<>>>&&); // create with in_setup = false YaoInputGateEvaluator(std::size_t gate_id, YaoProvider&, std::size_t num_wires, std::size_t num_simd); YaoInputGateEvaluator(std::size_t gate_id, YaoProvider&, std::size_t num_wires, std::size_t num_simd, ENCRYPTO::ReusableFiberFuture<std::vector<ENCRYPTO::BitVector<>>>&&); bool need_setup() const noexcept override { return true; } bool need_online() const noexcept override { return true; } void evaluate_setup() override; void evaluate_online() override; private: std::variant<bool, std::shared_ptr<ENCRYPTO::ObliviousTransfer::GOT128Receiver>, std::shared_ptr<ENCRYPTO::ObliviousTransfer::FixedXCOT128Receiver>> ot_receiver_; ENCRYPTO::ReusableFiberFuture<ENCRYPTO::block128_vector> keys_future_; }; class YaoOutputGateGarbler : public detail::BasicYaoOutputGate { public: YaoOutputGateGarbler(std::size_t gate_id, YaoProvider& yao_provider, YaoWireVector&& in, OutputRecipient); ENCRYPTO::ReusableFiberFuture<std::vector<ENCRYPTO::BitVector<>>> get_output_future() override; bool need_setup() const noexcept override { return true; } bool need_online() const noexcept override { return true; } void evaluate_setup() override; void evaluate_online() override; }; class YaoOutputGateEvaluator : public detail::BasicYaoOutputGate { public: YaoOutputGateEvaluator(std::size_t gate_id, YaoProvider& yao_provider, YaoWireVector&& in, OutputRecipient); ENCRYPTO::ReusableFiberFuture<std::vector<ENCRYPTO::BitVector<>>> get_output_future() override; bool need_setup() const noexcept override { return true; } bool need_online() const noexcept override { return true; } void evaluate_setup() override; void evaluate_online() override; }; class YaoINVGateGarbler : public detail::BasicYaoUnaryGate { public: YaoINVGateGarbler(std::size_t gate_id, YaoProvider&, YaoWireVector&&); bool need_setup() const noexcept override { return true; } bool need_online() const noexcept override { return false; } void evaluate_setup() override; void evaluate_online() override {} }; class YaoINVGateEvaluator : public detail::BasicYaoUnaryGate { public: YaoINVGateEvaluator(std::size_t gate_id, YaoProvider&, YaoWireVector&&); bool need_setup() const noexcept override { return false; } bool need_online() const noexcept override { return false; } void evaluate_setup() override {} void evaluate_online() override {} }; class YaoXORGateGarbler : public detail::BasicYaoBinaryGate { public: YaoXORGateGarbler(std::size_t gate_id, YaoProvider&, YaoWireVector&&, YaoWireVector&&); bool need_setup() const noexcept override { return true; } bool need_online() const noexcept override { return false; } void evaluate_setup() override; void evaluate_online() override {} }; class YaoXORGateEvaluator : public detail::BasicYaoBinaryGate { public: YaoXORGateEvaluator(std::size_t gate_id, YaoProvider&, YaoWireVector&&, YaoWireVector&&); bool need_setup() const noexcept override { return false; } bool need_online() const noexcept override { return true; } void evaluate_setup() override {} void evaluate_online() override; }; class YaoANDGateGarbler : public detail::BasicYaoBinaryGate { public: YaoANDGateGarbler(std::size_t gate_id, YaoProvider&, YaoWireVector&&, YaoWireVector&&); bool need_setup() const noexcept override { return true; } bool need_online() const noexcept override { return false; } void evaluate_setup() override; void evaluate_online() override {} }; class YaoANDGateEvaluator : public detail::BasicYaoBinaryGate { public: YaoANDGateEvaluator(std::size_t gate_id, YaoProvider&, YaoWireVector&&, YaoWireVector&&); bool need_setup() const noexcept override { return true; } bool need_online() const noexcept override { return true; } void evaluate_setup() override; void evaluate_online() override; private: ENCRYPTO::ReusableFiberFuture<ENCRYPTO::block128_vector> garbled_tables_fut_; }; } // namespace MOTION::proto::yao
39.596639
100
0.740556
[ "vector" ]
b30dbaa8336876aac2dff28a8462dc8c557a5db2
814
h
C
Modules/@babylonjs/react-native/submodules/BabylonNative/Plugins/NativeEngine/Source/IndexBuffer.h
HarveyLijh/ReactNativeBabylon
d9ac79d1e1a00f03f9a4fcf5419e5b118e65e586
[ "MIT" ]
null
null
null
Modules/@babylonjs/react-native/submodules/BabylonNative/Plugins/NativeEngine/Source/IndexBuffer.h
HarveyLijh/ReactNativeBabylon
d9ac79d1e1a00f03f9a4fcf5419e5b118e65e586
[ "MIT" ]
null
null
null
Modules/@babylonjs/react-native/submodules/BabylonNative/Plugins/NativeEngine/Source/IndexBuffer.h
HarveyLijh/ReactNativeBabylon
d9ac79d1e1a00f03f9a4fcf5419e5b118e65e586
[ "MIT" ]
null
null
null
#pragma once #include <bgfx/bgfx.h> #include <napi/napi.h> #include <gsl/gsl> #include <optional> namespace Babylon { class IndexBuffer final { public: IndexBuffer(gsl::span<uint8_t> bytes, uint16_t flags, bool dynamic); ~IndexBuffer(); void Dispose(); void Update(Napi::Env env, gsl::span<uint8_t> bytes, uint32_t startIndex); bool CreateHandle(); void Set(bgfx::Encoder* encoder, uint32_t firstIndex, uint32_t numIndices); private: std::optional<std::vector<uint8_t>> m_bytes{}; uint16_t m_flags{}; bool m_dynamic{}; union { bgfx::IndexBufferHandle m_handle{bgfx::kInvalidHandle}; bgfx::DynamicIndexBufferHandle m_dynamicHandle; }; bool m_disposed{}; }; }
22
83
0.615479
[ "vector" ]
b31c550f8baa6e305a4f2678968ec792b23e7a62
5,480
c
C
cmds/spells/f/_fire_seeds.c
facadepapergirl/shadowgate
2b811671c5c85952ed93767753d72fc0d12819d8
[ "MIT" ]
null
null
null
cmds/spells/f/_fire_seeds.c
facadepapergirl/shadowgate
2b811671c5c85952ed93767753d72fc0d12819d8
[ "MIT" ]
null
null
null
cmds/spells/f/_fire_seeds.c
facadepapergirl/shadowgate
2b811671c5c85952ed93767753d72fc0d12819d8
[ "MIT" ]
null
null
null
//Fire Seeds for druids //Partially based on fireball //Coded by ~Circe~ 3/19/13 #include <spell.h> #include <magic.h> #include <rooms.h> #include <daemons.h> #define WILD_TERRAINS ({"heavy forest","light forest","jungle","dense jungle","scrub lands","grasslands","savannah","desert","desert rocks","rocky","hills","branches","old mounts","new mounts","swamp","marsh","snow","meadows","beach","shore","nat cave","built cave","built tunnel","nat tunnel","cemetery","garden"}) inherit SPELL; int effect,x,i,y; object victim,tempob,*foes,*oldfoes,*allies; void damage(); void create() { ::create(); set_spell_name("fire seeds"); set_spell_level(([ "druid" : 6 ])); set_spell_sphere("fire"); set_syntax("cast CLASS fire seeds on TARGET"); set_description("Upon casting this spell, a druid scoops up seeds from " "the surrounding wilderness and enchants them before hurling them " "at his foes. The seeds explode upon impact, burning his foes. The " "druid will make an attempt to damage only foes, but that is not always " "possible, and targets have a chance to avoid the brunt of the spell for " "half damage. This spell can be cast only in the wilderness.\n\n" "%^BOLD%^NOTE:%^RESET%^ If you receive a message that you cannot cast " "the spell in a certain room because of the terrain and you think you " "received the message in error, please <bug here> and let us know so we " "can see if the terrain needs to be adjusted."); set_verbal_comp(); set_somatic_comp(); set_target_required(1); set_immunities( ({"fire"}) ); set_save("reflex"); } /* int preSpell() { */ /* string myterrain = environment(caster)->query_terrain(); */ /* if(member_array(myterrain,WILD_TERRAINS) == -1){ */ /* tell_object(caster, "You cannot find any seeds to cast that spell in this terrain!"); */ /* tell_object(caster, "Terrain type = "+myterrain+""); */ /* return 0; */ /* } */ /* return 1; */ /* } */ string query_cast_string() { return "%^RESET%^%^RED%^"+caster->QCN+" kneels, scooping a handful of seeds " "from the ground as "+caster->QS+" chants, "+caster->QP+" eyes on "+target->QCN+".\%^RESET%^"; } void spell_effect(int prof) { if(!present(target,caster->is_room()?caster:environment(caster))){ tell_object(caster,"%^BOLD%^Your target is not in this area.\n"); dest_effect(); return; } spell_successful(); spell_kill(target,caster); if(!interactive(caster) && !caster->query_invis()) foes = ({}); if(!living(caster)) { foes = all_living(environment(target)); foes = filter_array(foes, "is_non_immortal",FILTERS_D); } else { if(sizeof(caster->query_attackers())){ foes = caster->query_attackers(); } } if(!objectp(target)) return; if(sizeof(foes) > 0){ if (member_array(target,foes) != -1){ foes -= ({ target}); } } foes = target_filter(foes); if (interactive(caster)) tell_object(target,"%^RESET%^%^ORANGE%^"+caster->QCN+" hurls the seeds directly at you!%^RESET%^"); if(living(caster)) { tell_object(caster,"%^RESET%^%^ORANGE%^You hurl the seeds at "+target->QCN+"!%^RESET%^"); } tell_room(place, "%^BOLD%^%^RED%^"+caster->QCN+" hurls the seeds " "at "+target->QCN+", and they explode in a riot of flames!%^RESET%^",({ caster, target}) ); tell_object(target,"%^BOLD%^%^RED%^The seeds explode, engulfing you in flames!%^RESET%^"); tell_object(caster,"%^BOLD%^%^RED%^The seeds explode, engulfing " ""+target->QCN+" in sizzling flames!%^RESET%^"); oldfoes=foes; foes = ({}); allies = ({}); y=2+to_int((clevel-5)/2); if (sizeof(oldfoes) < y) y = sizeof(oldfoes); for (x=0;x < y;x++) { tempob=oldfoes[random(sizeof(oldfoes))]; if(do_save(tempob)) allies += ({ tempob}); else foes += ({ tempob}); oldfoes -= ({ tempob}); } y=clevel; if(do_save(target)) damage_targ(target, "torso", to_int(sdamage / 2),"fire" ); else damage_targ(target, "torso", sdamage,"fire" ); for (x=0;x < sizeof(foes);x++) { if (!objectp(foes[x])) continue; tell_room(environment(foes[x]),"%^BOLD%^%^WHITE%^The fiery blast from the seeds slams into "+foes[x]->QCN+"!",foes[x]); tell_object(foes[x],"%^BOLD%^%^WHITE%^The fiery blast from the seeds slams into you!"); if(do_save(foes[x])) damage_targ(foes[x], "torso", to_int(sdamage / 2),"fire" ); else damage_targ(foes[x], "torso", sdamage,"fire" ); } for (x=0;x < sizeof(allies);x++) { if (!objectp(allies[x])) continue; tell_room(environment(allies[x]),"%^RESET%^%^ORANGE%^"+allies[x]->QCN+" is singed by the blast from the seeds!%^RESET%^",allies[x]); tell_object(allies[x],"%^RESET%^%^ORANGE%^You are singed by the blast from the seeds!%^RESET%^"); if(do_save(allies[x])) damage_targ(allies[x], "torso", to_int(sdamage / 4),"fire" ); else damage_targ(allies[x], "torso", sdamage/2,"fire" ); } dest_effect(); } void dest_effect() { ::dest_effect(); if(objectp(TO)) TO->remove(); }
39.42446
315
0.584489
[ "object" ]
b31cc22005e9035abd63b3895379353e7691c07e
778
h
C
src/wxTTM/Database/LtListStore.h
ttm-tt/wxTTM
f9c75f05a564a0d82034412c1eb4c94d943e267f
[ "MIT" ]
null
null
null
src/wxTTM/Database/LtListStore.h
ttm-tt/wxTTM
f9c75f05a564a0d82034412c1eb4c94d943e267f
[ "MIT" ]
null
null
null
src/wxTTM/Database/LtListStore.h
ttm-tt/wxTTM
f9c75f05a564a0d82034412c1eb4c94d943e267f
[ "MIT" ]
null
null
null
/* Copyright (C) 2020 Christoph Theis */ // View ueber die Meldungen #ifndef LTLISTSTORE_H #define LTLISTSTORE_H #include "StoreObj.h" #include "LtStore.h" // Tabellendaten in eigene Struktur // Viewdaten class LtListStore : public StoreObj, public LtRec { // Tabelle in Datenbank erzeugen public: static bool CreateView(); static bool RemoveView(); public: LtListStore(Connection *connPtr = 0); // Defaultkonstruktor ~LtListStore(); virtual void Init(); public: bool SelectById(long id); bool SelectByPl(long plID, const timestamp * = NULL); std::vector<std::pair<timestamp, long>> GetTimestamps(long plID); private: wxString SelectString(const timestamp * = NULL) const; bool BindRec(); }; #endif
19.45
69
0.681234
[ "vector" ]
b321b7b8f10316d63985a9f30ddd6367d47b3d25
6,746
h
C
cds/container/details/feldman_hashset_base.h
simple555a/libcds
d05a0909402369d4a79eb82aed1742a7b227548b
[ "BSD-2-Clause" ]
null
null
null
cds/container/details/feldman_hashset_base.h
simple555a/libcds
d05a0909402369d4a79eb82aed1742a7b227548b
[ "BSD-2-Clause" ]
null
null
null
cds/container/details/feldman_hashset_base.h
simple555a/libcds
d05a0909402369d4a79eb82aed1742a7b227548b
[ "BSD-2-Clause" ]
1
2020-02-01T15:18:59.000Z
2020-02-01T15:18:59.000Z
//$$CDS-header$$ #ifndef CDSLIB_CONTAINER_DETAILS_FELDMAN_HASHSET_BASE_H #define CDSLIB_CONTAINER_DETAILS_FELDMAN_HASHSET_BASE_H #include <cds/intrusive/details/feldman_hashset_base.h> #include <cds/container/details/base.h> namespace cds { namespace container { /// \p FeldmanHashSet related definitions /** @ingroup cds_nonintrusive_helper */ namespace feldman_hashset { /// Hash accessor option /** @copydetails cds::intrusive::feldman_hashset::traits::hash_accessor */ template <typename Accessor> using hash_accessor = cds::intrusive::feldman_hashset::hash_accessor< Accessor >; /// \p FeldmanHashSet internal statistics, see cds::intrusive::feldman_hashset::stat template <typename EventCounter = cds::atomicity::event_counter> using stat = cds::intrusive::feldman_hashset::stat< EventCounter >; /// \p FeldmanHashSet empty internal statistics typedef cds::intrusive::feldman_hashset::empty_stat empty_stat; /// Bit-wise memcmp-based comparator for hash value \p T template <typename T> using bitwise_compare = cds::intrusive::feldman_hashset::bitwise_compare< T >; /// \p FeldmanHashSet level statistics typedef cds::intrusive::feldman_hashset::level_statistics level_statistics; /// \p FeldmanHashSet traits struct traits { /// Mandatory functor to get hash value from data node /** @copydetails cds::intrusive::feldman_hashset::traits::hash_accessor */ typedef cds::opt::none hash_accessor; /// Hash comparing functor /** @copydetails cds::intrusive::feldman_hashset::traits::compare */ typedef cds::opt::none compare; /// Specifies binary predicate used for hash compare. /** @copydetails cds::intrusive::feldman_hashset::traits::less */ typedef cds::opt::none less; /// Item counter /** @copydetails cds::intrusive::feldman_hashset::traits::item_counter */ typedef cds::atomicity::item_counter item_counter; /// Item allocator /** Default is \ref CDS_DEFAULT_ALLOCATOR */ typedef CDS_DEFAULT_ALLOCATOR allocator; /// Array node allocator /** @copydetails cds::intrusive::feldman_hashset::traits::node_allocator */ typedef CDS_DEFAULT_ALLOCATOR node_allocator; /// C++ memory ordering model /** @copydetails cds::intrusive::feldman_hashset::traits::memory_model */ typedef cds::opt::v::relaxed_ordering memory_model; /// Back-off strategy typedef cds::backoff::Default back_off; /// Internal statistics /** @copydetails cds::intrusive::feldman_hashset::traits::stat */ typedef empty_stat stat; /// RCU deadlock checking policy (only for \ref cds_container_FeldmanHashSet_rcu "RCU-based FeldmanHashSet") /** @copydetails cds::intrusive::feldman_hashset::traits::rcu_check_deadlock */ typedef cds::opt::v::rcu_throw_deadlock rcu_check_deadlock; }; /// Metafunction converting option list to \p feldman_hashset::traits /** Supported \p Options are: - \p feldman_hashset::hash_accessor - mandatory option, hash accessor functor. @copydetails traits::hash_accessor - \p opt::allocator - item allocator @copydetails traits::allocator - \p opt::node_allocator - array node allocator. @copydetails traits::node_allocator - \p opt::compare - hash comparison functor. No default functor is provided. If the option is not specified, the \p opt::less is used. - \p opt::less - specifies binary predicate used for hash comparison. @copydetails cds::container::feldman_hashset::traits::less - \p opt::back_off - back-off strategy used. If the option is not specified, the \p cds::backoff::Default is used. - \p opt::item_counter - the type of item counting feature. @copydetails cds::intrusive::feldman_hashset::traits::item_counter - \p opt::memory_model - C++ memory ordering model. Can be \p opt::v::relaxed_ordering (relaxed memory model, the default) or \p opt::v::sequential_consistent (sequentially consisnent memory model). - \p opt::stat - internal statistics. By default, it is disabled (\p feldman_hashset::empty_stat). To enable it use \p feldman_hashset::stat - \p opt::rcu_check_deadlock - a deadlock checking policy for \ref cds_intrusive_FeldmanHashSet_rcu "RCU-based FeldmanHashSet" Default is \p opt::v::rcu_throw_deadlock */ template <typename... Options> struct make_traits { # ifdef CDS_DOXYGEN_INVOKED typedef implementation_defined type ; ///< Metafunction result # else typedef typename cds::opt::make_options< typename cds::opt::find_type_traits< traits, Options... >::type ,Options... >::type type; # endif }; } // namespace feldman_hashset //@cond // Forward declaration template < class GC, typename T, class Traits = cds::container::feldman_hashset::traits > class FeldmanHashSet; //@endcond //@cond namespace details { template <typename GC, typename T, typename Traits> struct make_feldman_hashset { typedef GC gc; typedef T value_type; typedef Traits original_traits; typedef cds::details::Allocator< value_type, typename original_traits::allocator > cxx_node_allocator; struct node_disposer { void operator()( value_type * p ) const { cxx_node_allocator().Delete( p ); } }; struct intrusive_traits: public original_traits { typedef node_disposer disposer; }; // Metafunction result typedef cds::intrusive::FeldmanHashSet< GC, T, intrusive_traits > type; }; } // namespace details //@endcond }} // namespace cds::container #endif // #ifndef CDSLIB_CONTAINER_DETAILS_FELDMAN_HASHSET_BASE_H
38.99422
138
0.602283
[ "model" ]
b323469f17854653a79ba1c91e51c6e6b61ad64f
19,309
h
C
src/mongo/s/catalog/sharding_catalog_manager.h
marcelodsx/mongo
324839c0c0c2b294a44d130105797ccdbb3b17a9
[ "Apache-2.0" ]
null
null
null
src/mongo/s/catalog/sharding_catalog_manager.h
marcelodsx/mongo
324839c0c0c2b294a44d130105797ccdbb3b17a9
[ "Apache-2.0" ]
null
null
null
src/mongo/s/catalog/sharding_catalog_manager.h
marcelodsx/mongo
324839c0c0c2b294a44d130105797ccdbb3b17a9
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2015 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #pragma once #include "mongo/base/disallow_copying.h" #include "mongo/base/status_with.h" #include "mongo/db/concurrency/d_concurrency.h" #include "mongo/executor/task_executor.h" #include "mongo/s/catalog/type_chunk.h" #include "mongo/s/catalog/type_database.h" #include "mongo/s/catalog/type_shard.h" #include "mongo/s/client/shard.h" #include "mongo/s/client/shard_registry.h" #include "mongo/s/shard_key_pattern.h" #include "mongo/stdx/mutex.h" namespace mongo { class OperationContext; class RemoteCommandTargeter; class ServiceContext; class UUID; /** * Implements modifications to the sharding catalog metadata. * * TODO: Currently the code responsible for writing the sharding catalog metadata is split between * this class and ShardingCatalogClient. Eventually all methods that write catalog data should be * moved out of ShardingCatalogClient and into this class. */ class ShardingCatalogManager { MONGO_DISALLOW_COPYING(ShardingCatalogManager); public: ShardingCatalogManager(ServiceContext* serviceContext, std::unique_ptr<executor::TaskExecutor> addShardExecutor); ~ShardingCatalogManager(); /** * Instantiates an instance of the sharding catalog manager and installs it on the specified * service context. This method is not thread-safe and must be called only once when the service * is starting. */ static void create(ServiceContext* serviceContext, std::unique_ptr<executor::TaskExecutor> addShardExecutor); /** * Retrieves the per-service instance of the ShardingCatalogManager. This instance is only * available if the node is running as a config server. */ static ShardingCatalogManager* get(ServiceContext* serviceContext); static ShardingCatalogManager* get(OperationContext* operationContext); /** * Safe to call multiple times as long as the calls are externally synchronized to be * non-overlapping. */ void startup(); /** * Performs necessary cleanup when shutting down cleanly. */ void shutDown(); /** * Checks if this is the first start of a newly instantiated config server and if so pre-creates * the catalog collections and their indexes. Also generates and persists the cluster's * identity. */ Status initializeConfigDatabaseIfNeeded(OperationContext* opCtx); /** * Invoked on cluster identity metadata rollback after replication step down. Throws out any * cached identity information and causes it to be reloaded/re-created on the next attempt. */ void discardCachedConfigDatabaseInitializationState(); // // Zone Operations // /** * Adds the given shardName to the zone. Returns ErrorCodes::ShardNotFound if a shard by that * name does not exist. */ Status addShardToZone(OperationContext* opCtx, const std::string& shardName, const std::string& zoneName); /** * Removes the given shardName from the zone. Returns ErrorCodes::ShardNotFound if a shard by * that name does not exist. */ Status removeShardFromZone(OperationContext* opCtx, const std::string& shardName, const std::string& zoneName); /** * Assigns a range of a sharded collection to a particular shard zone. If range is a prefix of * the shard key, the range will be converted into a new range with full shard key filled with * MinKey values. */ Status assignKeyRangeToZone(OperationContext* opCtx, const NamespaceString& ns, const ChunkRange& range, const std::string& zoneName); /** * Removes a range from a zone. * * NOTE: unlike assignKeyRangeToZone, the given range will never be converted to include the * full shard key. */ Status removeKeyRangeFromZone(OperationContext* opCtx, const NamespaceString& ns, const ChunkRange& range); // // Chunk Operations // /** * Updates metadata in the config.chunks collection to show the given chunk as split into * smaller chunks at the specified split points. */ Status commitChunkSplit(OperationContext* opCtx, const NamespaceString& ns, const OID& requestEpoch, const ChunkRange& range, const std::vector<BSONObj>& splitPoints, const std::string& shardName); /** * Updates metadata in the config.chunks collection so the chunks with given boundaries are seen * merged into a single larger chunk. */ Status commitChunkMerge(OperationContext* opCtx, const NamespaceString& ns, const OID& requestEpoch, const std::vector<BSONObj>& chunkBoundaries, const std::string& shardName); /** * Updates metadata in config.chunks collection to show the given chunk in its new shard. */ StatusWith<BSONObj> commitChunkMigration(OperationContext* opCtx, const NamespaceString& nss, const ChunkType& migratedChunk, const boost::optional<ChunkType>& controlChunk, const OID& collectionEpoch, const ShardId& fromShard, const ShardId& toShard); // // Database Operations // /** * Creates a new database entry for the specified database name in the configuration * metadata and sets the specified shard as primary. * * @param dbName name of the database (case sensitive) * * Returns Status::OK on success or any error code indicating the failure. These are some * of the known failures: * - NamespaceExists - database already exists * - DatabaseDifferCase - database already exists, but with a different case * - ShardNotFound - could not find a shard to place the DB on */ Status createDatabase(OperationContext* opCtx, const std::string& dbName); /** * Creates a new database or updates the sharding status for an existing one. Cannot be * used for the admin/config/local DBs, which should not be created or sharded manually * anyways. * * Returns Status::OK on success or any error code indicating the failure. These are some * of the known failures: * - DatabaseDifferCase - database already exists, but with a different case * - ShardNotFound - could not find a shard to place the DB on */ Status enableSharding(OperationContext* opCtx, const std::string& dbName); // // Collection Operations // /** * Shards a collection. Assumes that the database is enabled for sharding. * * @param ns: namespace of collection to shard * @param uuid: the collection's UUID. Optional because new in 3.6. * @param fieldsAndOrder: shardKey pattern * @param defaultCollation: the default collation for the collection, to be written to * config.collections. If empty, the collection default collation is simple binary * comparison. Note the the shard key collation will always be simple binary comparison, * even if the collection default collation is non-simple. * @param unique: if true, ensure underlying index enforces a unique constraint. * @param initPoints: create chunks based on a set of specified split points. * @param initShardIds: If non-empty, specifies the set of shards to assign chunks between. * Otherwise all chunks will be assigned to the primary shard for the database. */ void shardCollection(OperationContext* opCtx, const std::string& ns, const boost::optional<UUID> uuid, const ShardKeyPattern& fieldsAndOrder, const BSONObj& defaultCollation, bool unique, const std::vector<BSONObj>& initPoints, const bool distributeInitialChunks); // // Shard Operations // /** * * Adds a new shard. It expects a standalone mongod process or replica set to be running on the * provided address. * * 'shardProposedName' is an optional string with the proposed name of the shard. If it is * nullptr, a name will be automatically generated; if not nullptr, it cannot * contain the empty string. * 'shardConnectionString' is the complete connection string of the shard being added. * 'maxSize' is the optional space quota in bytes. Zero means there's no limitation to space * usage. * * On success returns the name of the newly added shard. */ StatusWith<std::string> addShard(OperationContext* opCtx, const std::string* shardProposedName, const ConnectionString& shardConnectionString, const long long maxSize); // // Cluster Upgrade Operations // /** * Returns a BSON representation of an update request that can be used to insert a shardIdentity * doc into the shard for the given shardType (or update the shard's existing shardIdentity * doc's configsvrConnString if the _id, shardName, and clusterId do not conflict). */ BSONObj createShardIdentityUpsertForAddShard(OperationContext* opCtx, const std::string& shardName); /** * Runs the setFeatureCompatibilityVersion command on all shards. */ Status setFeatureCompatibilityVersionOnShards(OperationContext* opCtx, const std::string& version); // // For Diagnostics // /** * Append information about the connection pools owned by the CatalogManager. */ void appendConnectionStats(executor::ConnectionPoolStats* stats); /** * Only used for unit-tests, clears a previously-created catalog manager from the specified * service context, so that 'create' can be called again. */ static void clearForTests(ServiceContext* serviceContext); private: /** * Performs the necessary checks for version compatibility and creates a new config.version * document if the current cluster config is empty. */ Status _initConfigVersion(OperationContext* opCtx); /** * Builds all the expected indexes on the config server. */ Status _initConfigIndexes(OperationContext* opCtx); /** * Used during addShard to determine if there is already an existing shard that matches the * shard that is currently being added. An OK return with boost::none indicates that there * is no conflicting shard, and we can proceed trying to add the new shard. An OK return * with a ShardType indicates that there is an existing shard that matches the shard being added * but since the options match, this addShard request can do nothing and return success. A * non-OK return either indicates a problem reading the existing shards from disk or more likely * indicates that an existing shard conflicts with the shard being added and they have different * options, so the addShard attempt must be aborted. */ StatusWith<boost::optional<ShardType>> _checkIfShardExists( OperationContext* opCtx, const ConnectionString& propsedShardConnectionString, const std::string* shardProposedName, long long maxSize); /** * Validates that the specified endpoint can serve as a shard server. In particular, this * this function checks that the shard can be contacted and that it is not already member of * another sharded cluster. * * @param targeter For sending requests to the shard-to-be. * @param shardProposedName Optional proposed name for the shard. Can be omitted in which case * a unique name for the shard will be generated from the shard's connection string. If it * is not omitted, the value cannot be the empty string. * * On success returns a partially initialized ShardType object corresponding to the requested * shard. It will have the hostName field set and optionally the name, if the name could be * generated from either the proposed name or the connection string set name. The returned * shard's name should be checked and if empty, one should be generated using some uniform * algorithm. */ StatusWith<ShardType> _validateHostAsShard(OperationContext* opCtx, std::shared_ptr<RemoteCommandTargeter> targeter, const std::string* shardProposedName, const ConnectionString& connectionString); /** * Runs the listDatabases command on the specified host and returns the names of all databases * it returns excluding those named local, config and admin, since they serve administrative * purposes. */ StatusWith<std::vector<std::string>> _getDBNamesListFromShard( OperationContext* opCtx, std::shared_ptr<RemoteCommandTargeter> targeter); /** * Runs a command against a "shard" that is not yet in the cluster and thus not present in the * ShardRegistry. */ StatusWith<Shard::CommandResponse> _runCommandForAddShard(OperationContext* opCtx, RemoteCommandTargeter* targeter, const std::string& dbName, const BSONObj& cmdObj); /** * Checks that the given database name doesn't already exist in the config.databases * collection, including under different casing. Optional db can be passed and will * be set with the database details if the given dbName exists. * * Returns OK status if the db does not exist. * Some known errors include: * NamespaceExists if it exists with the same casing * DatabaseDifferCase if it exists under different casing. */ Status _checkDbDoesNotExist(OperationContext* opCtx, const std::string& dbName, DatabaseType* db); /** * Selects an optimal shard on which to place a newly created database from the set of * available shards. Will return ShardNotFound if shard could not be found. */ static StatusWith<ShardId> _selectShardForNewDatabase(OperationContext* opCtx, ShardRegistry* shardRegistry); // The owning service context ServiceContext* const _serviceContext; // Executor specifically used for sending commands to servers that are in the process of being // added as shards. Does not have any connection hook set on it, thus it can be used to talk to // servers that are not yet in the ShardRegistry. const std::unique_ptr<executor::TaskExecutor> _executorForAddShard; // // All member variables are labeled with one of the following codes indicating the // synchronization rules for accessing them. // // (M) Must hold _mutex for access. // (R) Read only, can only be written during initialization. // (S) Self-synchronizing; access in any way from any context. // stdx::mutex _mutex; // True if shutDown() has been called. False, otherwise. bool _inShutdown{false}; // (M) // True if startup() has been called. bool _started{false}; // (M) // True if initializeConfigDatabaseIfNeeded() has been called and returned successfully. bool _configInitialized{false}; // (M) /** * Lock for shard zoning operations. This should be acquired when doing any operations that * can affect the config.tags collection or the tags field of the config.shards collection. * No other locks should be held when locking this. If an operation needs to take database * locks (for example to write to a local collection) those locks should be taken after * taking this. */ Lock::ResourceMutex _kZoneOpLock; /** * Lock for chunk split/merge/move operations. This should be acquired when doing split/merge/ * move operations that can affect the config.chunks collection. * No other locks should be held when locking this. If an operation needs to take database * locks (for example to write to a local collection) those locks should be taken after * taking this. */ Lock::ResourceMutex _kChunkOpLock; /** * Lock that guards changes to the set of shards in the cluster (ie addShard and removeShard * requests). * TODO: Currently only taken during addShard requests, this should also be taken in X mode * during removeShard, once removeShard is moved to run on the config server primary instead of * on mongos. At that point we should also change any operations that expect the shard not to * be removed while they are running (such as removeShardFromZone) to take this in shared mode. */ Lock::ResourceMutex _kShardMembershipLock; }; } // namespace mongo
43.884091
100
0.654565
[ "object", "vector" ]
b327ce0df6e76b9f8bfd3abab9bf5c780c3413ae
4,492
h
C
WaterFLayout.h
Mosoink/WaterFLayout
d223e49c6ca666c44ec8052d58f0fcacd53a7589
[ "MIT" ]
null
null
null
WaterFLayout.h
Mosoink/WaterFLayout
d223e49c6ca666c44ec8052d58f0fcacd53a7589
[ "MIT" ]
null
null
null
WaterFLayout.h
Mosoink/WaterFLayout
d223e49c6ca666c44ec8052d58f0fcacd53a7589
[ "MIT" ]
null
null
null
// // WaterFLayout.h // CollectionView // // Created by d2space on 14-2-24. // Copyright (c) 2014年 D2space. All rights reserved. // #import <UIKit/UIKit.h> /** * Constants that specify the types of supplementary views that can be presented using a waterfall layout. */ /// A supplementary view that identifies the header for a given section. extern NSString *const WaterFallSectionHeader; /// A supplementary view that identifies the footer for a given section. extern NSString *const WaterFallSectionFooter; #pragma mark WaterF @protocol WaterFLayoutDelegate <UICollectionViewDelegate> @required /** * Asks the delegate for the size of the specified item’s cell. * * @param collectionView * The collection view object displaying the waterfall layout. * @param collectionViewLayout * The layout object requesting the information. * @param indexPath * The index path of the item. * * @return * The original size of the specified item. Both width and height must be greater than 0. */ - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath; @optional /** * Asks the delegate for the height of the header view in the specified section. * * @param collectionView * The collection view object displaying the waterfall layout. * @param collectionViewLayout * The layout object requesting the information. * @param section * The index of the section whose header size is being requested. * * @return * The height of the header. If you return 0, no header is added. * * @discussion * If you do not implement this method, the waterfall layout uses the value in its headerHeight property to set the size of the header. * * @see * headerHeight */ - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout heightForHeaderInSection:(NSInteger)section; /** * Asks the delegate for the height of the footer view in the specified section. * * @param collectionView * The collection view object displaying the waterfall layout. * @param collectionViewLayout * The layout object requesting the information. * @param section * The index of the section whose header size is being requested. * * @return * The height of the footer. If you return 0, no footer is added. * * @discussion * If you do not implement this method, the waterfall layout uses the value in its footerHeight property to set the size of the footer. * * @see * footerHeight */ - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout heightForFooterInSection:(NSInteger)section; @end @interface WaterFLayout : UICollectionViewLayout /** * @brief How many columns for this layout. * @discussion Default: 2 */ @property (nonatomic, assign) NSInteger columnCount; /** * @brief The minimum spacing to use between successive columns. * @discussion Default: 10.0 */ @property (nonatomic, assign) CGFloat minimumColumnSpacing; /** * @brief The minimum spacing to use between items in the same column. * @discussion Default: 10.0 * @note This spacing is not applied to the space between header and columns or between columns and footer. */ @property (nonatomic, assign) CGFloat minimumInteritemSpacing; /** * @brief Height for section header * @discussion * If your collectionView's delegate doesn't implement `collectionView:layout:heightForHeaderInSection:`, * then this value will be used. * * Default: 0 */ @property (nonatomic, assign) CGFloat headerHeight; /** * @brief Height for section footer * @discussion * If your collectionView's delegate doesn't implement `collectionView:layout:heightForFooterInSection:`, * then this value will be used. * * Default: 0 */ @property (nonatomic, assign) CGFloat footerHeight; /** * @brief The margins that are used to lay out content in each section. * @discussion * Section insets are margins applied only to the items in the section. * They represent the distance between the header view and the columns and between the columns and the footer view. * They also indicate the spacing on either side of columns. They do not affect the size of the headers or footers themselves. * * Default: UIEdgeInsetsZero */ @property (nonatomic, assign) UIEdgeInsets sectionInset; @end
33.522388
162
0.74065
[ "object" ]
b3308696c4e5ae7459c8ccec8e352a3b9568dabb
1,295
h
C
Engine/Source/Runtime/Renderer/Private/CustomDepthRendering.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/Renderer/Private/CustomDepthRendering.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/Renderer/Private/CustomDepthRendering.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. /*============================================================================= CustomDepthRendering.h: CustomDepth rendering implementation. =============================================================================*/ #pragma once #include "CoreMinimal.h" #include "RendererInterface.h" #include "SceneView.h" #include "DrawingPolicy.h" class FPrimitiveSceneProxy; /** * Set of custom depth scene prims */ class FCustomDepthPrimSet { public: /** * Iterate over the prims and draw them * @param ViewInfo - current view used to draw items * @return true if anything was drawn */ bool DrawPrims(FRHICommandListImmediate& RHICmdList, const class FViewInfo& View, FDrawingPolicyRenderState& DrawRenderState, bool bWriteCustomStencilValues); /** * Adds a new primitives to the list of distortion prims * @param PrimitiveSceneProxies - primitive info to add. */ void Append(FPrimitiveSceneProxy** PrimitiveSceneProxies, int32 NumProxies) { Prims.Append(PrimitiveSceneProxies, NumProxies); } /** * @return number of prims to render */ int32 NumPrims() const { return Prims.Num(); } private: /** list of prims added from the scene */ TArray<FPrimitiveSceneProxy*, SceneRenderingAllocator> Prims; };
25.392157
159
0.659459
[ "render" ]
b337a865675f98a8d50890d5bc2fa69b92d99ef0
1,088
c
C
etl_e2e/census_etl/dfxml/src/cpu_info.c
thinkmoore/das
d9faabf3de987b890a5079b914f5aba597215b14
[ "CC0-1.0" ]
35
2019-04-16T19:37:01.000Z
2022-02-14T20:33:41.000Z
etl_e2e/census_etl/dfxml/src/cpu_info.c
thinkmoore/das
d9faabf3de987b890a5079b914f5aba597215b14
[ "CC0-1.0" ]
6
2019-06-05T19:41:15.000Z
2020-08-19T19:04:59.000Z
etl_e2e/census_etl/dfxml/src/cpu_info.c
thinkmoore/das
d9faabf3de987b890a5079b914f5aba597215b14
[ "CC0-1.0" ]
12
2019-05-02T19:38:06.000Z
2021-09-11T22:02:03.000Z
/* * Revision History: * 2012 - Simson L. Garfinkel - Created for bulk_extractor. * * Test program for cpuid program. */ #include <stdint.h> #include <stdio.h> #include <limits.h> #define cpuid(id) __asm__( "cpuid" : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) : "a"(id), "b"(0), "c"(0), "d"(0)) #define b(val, base, end) ((val << (__WORDSIZE-end-1)) >> (__WORDSIZE-end+base-1)) int main(int argc, char **argv) { unsigned long eax, ebx, ecx, edx; cpuid(0); printf("identification: \"%.4s%.4s%.4s\"\n", (char *)&ebx, (char *)&edx, (char *)&ecx); printf("cpu information:\n"); cpuid(1); printf(" family %ld model %ld stepping %ld efamily %ld emodel %ld\n", b(eax, 8, 11), b(eax, 4, 7), b(eax, 0, 3), b(eax, 20, 27), b(eax, 16, 19)); printf(" brand %ld cflush sz %ld*8 nproc %ld apicid %ld\n", b(ebx, 0, 7), b(ebx, 8, 15), b(ebx, 16, 23), b(ebx, 24, 31)); cpuid(0x80000006); printf("L1 cache size (per core): %ld KB\n", b(ecx, 16, 31)); return(0); }
30.222222
114
0.52114
[ "model" ]
6c31e163c3fc216007201508360447d5b40c191c
5,116
h
C
src/misc/ShellUtility.h
4paradigm/prpc
2d264b696dd08191346535b852bb2b5391506a20
[ "Apache-2.0" ]
2
2021-08-24T03:35:11.000Z
2021-09-08T15:17:07.000Z
src/misc/ShellUtility.h
4paradigm/prpc
2d264b696dd08191346535b852bb2b5391506a20
[ "Apache-2.0" ]
null
null
null
src/misc/ShellUtility.h
4paradigm/prpc
2d264b696dd08191346535b852bb2b5391506a20
[ "Apache-2.0" ]
null
null
null
#ifndef PARADIGM4_PICO_COMMON_SHELL_UTILITY_H #define PARADIGM4_PICO_COMMON_SHELL_UTILITY_H #include <stdio.h> #include <string> #include "error_code.h" #include "pico_log.h" #include "Archive.h" namespace paradigm4 { namespace pico { namespace core { enum class FileSystemType : int8_t { UNKNOWN, LOCAL, HDFS, KAFKA, MEM }; PICO_ENUM_SERIALIZATION(FileSystemType, int8_t); enum class FileExtType { PZ, GZ, SNAPPY, OTHER }; struct bipopen_result_t { FILE* fp_read = nullptr; FILE* fp_write = nullptr; int pid = -1; std::string shell_bin = ""; std::string shell_arg = ""; std::string command = ""; std::string gen_full_command() const { return "{" + shell_bin + (shell_arg == "" ? std::string("") : ("}{" + shell_arg)) + "} [" + command + "]"; } }; struct popen_result_t { FILE* file = nullptr; bipopen_result_t result; std::string mode = ""; }; class ShellUtility : public VirtualObject { public: ShellUtility() = delete; static void set_default_shell(const std::string& shell_bin, const std::string& shell_arg); /*! * \brief exec command cmd, return shell output file pointer */ static shared_ptr<FILE> execute(const std::string& cmd) { return open(cmd, "r", true); } /*! * \brief exec command cmd, return result in string */ static std::string execute_tostring(const std::string& cmd); static popen_result_t inner_popen(const std::string& cmd, const std::string& mode); static int inner_pclose(popen_result_t& r); static shared_ptr<FILE> open(const std::string& cmd, const std::string& mode, bool is_pipe = false); /*! * \brief check current file system, HDFS or local */ static FileSystemType fs_type(const std::string& path_str) { std::string prefix; std::string name; return fs_type(path_str, prefix, name); } /** * @brief get file type, extra protocol prefix, path name * * @param path_str path name with protocol * @param prefix extra protocol prefix, for fs type * @param name the name of the actual use * * @return file type */ static FileSystemType fs_type(const std::string& path_str, std::string& prefix, std::string& name); /** * @brief get file type protocol string * * @param type * * @return */ static std::string fs_type_desc(FileSystemType type); /** * @brief check file ext name * * @param path_str * * @return ext type */ static FileExtType ext_type(const std::string& path_str); /*! * \brief exec pipe_cmd and put result in path, return $path's file pointer, * just open $path file('w' mode) when pipe_cmd is empty * \param hdp 'hdfs dfs' */ static shared_ptr<FILE> open_write(const std::string& path, const std::string& pipe_cmd, const std::string& hdp = ""); /*! * \brief exec pipe_cmd with path as input, return output file pointer, * just return path file pointer when pipe_cmd is empty */ static shared_ptr<FILE> open_read(const std::string& path, const std::string& pipe_cmd, const std::string& hdp = ""); /*! * \brief return file list under $reg_path */ static std::vector<std::string> get_file_list(const std::string& reg_path); static std::vector<std::string> get_file_list(const std::vector<std::string>& reg_path); /*! * \brief return file list under hdfs path $reg_path */ static std::vector<std::string> get_hdfs_file_list(const std::string& hadoop_bin, const std::string& reg_path); static std::vector<std::string> get_hdfs_file_list(const std::string& hadoop_bin, const std::vector<std::string>& reg_path); /*! * \brief generate cmd to use origin_cmd's output as pipe_cmd's input */ static void add_pipecmd(std::string& origin_cmd, bool& is_pipe, const std::string& pipe_cmd); static std::string read_file_to_string(FILE* ptr); /*! * \brief run pipe_cmd with file as input, return result as string */ static std::string read_file_to_string(const std::string& file, const std::string& pipe_cmd = "", const std::string& hadoop = ""); static void write_string_to_file(FILE* ptr, const std::string& ); static void write_string_to_file(const std::string& file, const std::string& str, const std::string& pipe_cmd = "", const std::string& hadoop = ""); static bipopen_result_t bipopen(const std::string& command, std::string shell_bin = "", std::string shell_arg = ""); /*! * \brief get bipipe state until terminate */ static int bipclose(bipopen_result_t& r); private: static std::string default_shell_bin; static std::string default_shell_arg; }; } // namespace core } // namespace pico } // namespace paradigm4 #endif // PARADIGM4_PICO_COMMON_SHELL_UTILITY_H
27.654054
94
0.63018
[ "vector" ]
6c385b10831f8dc17818fcd5df8184d0d681c709
19,855
h
C
head/sys/netinet/ip_fw.h
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
null
null
null
head/sys/netinet/ip_fw.h
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
null
null
null
head/sys/netinet/ip_fw.h
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
null
null
null
/*- * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa * * 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 THE AUTHOR 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 AUTHOR 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. * * $FreeBSD: soc2013/dpl/head/sys/netinet/ip_fw.h 249753 2013-03-20 10:35:33Z melifaro $ */ #ifndef _IPFW2_H #define _IPFW2_H /* * The default rule number. By the design of ip_fw, the default rule * is the last one, so its number can also serve as the highest number * allowed for a rule. The ip_fw code relies on both meanings of this * constant. */ #define IPFW_DEFAULT_RULE 65535 /* * Default number of ipfw tables. */ #define IPFW_TABLES_MAX 65535 #define IPFW_TABLES_DEFAULT 128 /* * Most commands (queue, pipe, tag, untag, limit...) can have a 16-bit * argument between 1 and 65534. The value 0 is unused, the value * 65535 (IP_FW_TABLEARG) is used to represent 'tablearg', i.e. the * can be 1..65534, or 65535 to indicate the use of a 'tablearg' * result of the most recent table() lookup. * Note that 16bit is only a historical limit, resulting from * the use of a 16-bit fields for that value. In reality, we can have * 2^32 pipes, queues, tag values and so on, and use 0 as a tablearg. */ #define IPFW_ARG_MIN 1 #define IPFW_ARG_MAX 65534 #define IP_FW_TABLEARG 65535 /* XXX should use 0 */ /* * Number of entries in the call stack of the call/return commands. * Call stack currently is an uint16_t array with rule numbers. */ #define IPFW_CALLSTACK_SIZE 16 /* IP_FW3 header/opcodes */ typedef struct _ip_fw3_opheader { uint16_t opcode; /* Operation opcode */ uint16_t reserved[3]; /* Align to 64-bit boundary */ } ip_fw3_opheader; /* IPFW extented tables support */ #define IP_FW_TABLE_XADD 86 /* add entry */ #define IP_FW_TABLE_XDEL 87 /* delete entry */ #define IP_FW_TABLE_XGETSIZE 88 /* get table size */ #define IP_FW_TABLE_XLIST 89 /* list table contents */ /* * The kernel representation of ipfw rules is made of a list of * 'instructions' (for all practical purposes equivalent to BPF * instructions), which specify which fields of the packet * (or its metadata) should be analysed. * * Each instruction is stored in a structure which begins with * "ipfw_insn", and can contain extra fields depending on the * instruction type (listed below). * Note that the code is written so that individual instructions * have a size which is a multiple of 32 bits. This means that, if * such structures contain pointers or other 64-bit entities, * (there is just one instance now) they may end up unaligned on * 64-bit architectures, so the must be handled with care. * * "enum ipfw_opcodes" are the opcodes supported. We can have up * to 256 different opcodes. When adding new opcodes, they should * be appended to the end of the opcode list before O_LAST_OPCODE, * this will prevent the ABI from being broken, otherwise users * will have to recompile ipfw(8) when they update the kernel. */ enum ipfw_opcodes { /* arguments (4 byte each) */ O_NOP, O_IP_SRC, /* u32 = IP */ O_IP_SRC_MASK, /* ip = IP/mask */ O_IP_SRC_ME, /* none */ O_IP_SRC_SET, /* u32=base, arg1=len, bitmap */ O_IP_DST, /* u32 = IP */ O_IP_DST_MASK, /* ip = IP/mask */ O_IP_DST_ME, /* none */ O_IP_DST_SET, /* u32=base, arg1=len, bitmap */ O_IP_SRCPORT, /* (n)port list:mask 4 byte ea */ O_IP_DSTPORT, /* (n)port list:mask 4 byte ea */ O_PROTO, /* arg1=protocol */ O_MACADDR2, /* 2 mac addr:mask */ O_MAC_TYPE, /* same as srcport */ O_LAYER2, /* none */ O_IN, /* none */ O_FRAG, /* none */ O_RECV, /* none */ O_XMIT, /* none */ O_VIA, /* none */ O_IPOPT, /* arg1 = 2*u8 bitmap */ O_IPLEN, /* arg1 = len */ O_IPID, /* arg1 = id */ O_IPTOS, /* arg1 = id */ O_IPPRECEDENCE, /* arg1 = precedence << 5 */ O_IPTTL, /* arg1 = TTL */ O_IPVER, /* arg1 = version */ O_UID, /* u32 = id */ O_GID, /* u32 = id */ O_ESTAB, /* none (tcp established) */ O_TCPFLAGS, /* arg1 = 2*u8 bitmap */ O_TCPWIN, /* arg1 = desired win */ O_TCPSEQ, /* u32 = desired seq. */ O_TCPACK, /* u32 = desired seq. */ O_ICMPTYPE, /* u32 = icmp bitmap */ O_TCPOPTS, /* arg1 = 2*u8 bitmap */ O_VERREVPATH, /* none */ O_VERSRCREACH, /* none */ O_PROBE_STATE, /* none */ O_KEEP_STATE, /* none */ O_LIMIT, /* ipfw_insn_limit */ O_LIMIT_PARENT, /* dyn_type, not an opcode. */ /* * These are really 'actions'. */ O_LOG, /* ipfw_insn_log */ O_PROB, /* u32 = match probability */ O_CHECK_STATE, /* none */ O_ACCEPT, /* none */ O_DENY, /* none */ O_REJECT, /* arg1=icmp arg (same as deny) */ O_COUNT, /* none */ O_SKIPTO, /* arg1=next rule number */ O_PIPE, /* arg1=pipe number */ O_QUEUE, /* arg1=queue number */ O_DIVERT, /* arg1=port number */ O_TEE, /* arg1=port number */ O_FORWARD_IP, /* fwd sockaddr */ O_FORWARD_MAC, /* fwd mac */ O_NAT, /* nope */ O_REASS, /* none */ /* * More opcodes. */ O_IPSEC, /* has ipsec history */ O_IP_SRC_LOOKUP, /* arg1=table number, u32=value */ O_IP_DST_LOOKUP, /* arg1=table number, u32=value */ O_ANTISPOOF, /* none */ O_JAIL, /* u32 = id */ O_ALTQ, /* u32 = altq classif. qid */ O_DIVERTED, /* arg1=bitmap (1:loop, 2:out) */ O_TCPDATALEN, /* arg1 = tcp data len */ O_IP6_SRC, /* address without mask */ O_IP6_SRC_ME, /* my addresses */ O_IP6_SRC_MASK, /* address with the mask */ O_IP6_DST, O_IP6_DST_ME, O_IP6_DST_MASK, O_FLOW6ID, /* for flow id tag in the ipv6 pkt */ O_ICMP6TYPE, /* icmp6 packet type filtering */ O_EXT_HDR, /* filtering for ipv6 extension header */ O_IP6, /* * actions for ng_ipfw */ O_NETGRAPH, /* send to ng_ipfw */ O_NGTEE, /* copy to ng_ipfw */ O_IP4, O_UNREACH6, /* arg1=icmpv6 code arg (deny) */ O_TAG, /* arg1=tag number */ O_TAGGED, /* arg1=tag number */ O_SETFIB, /* arg1=FIB number */ O_FIB, /* arg1=FIB desired fib number */ O_SOCKARG, /* socket argument */ O_CALLRETURN, /* arg1=called rule number */ O_FORWARD_IP6, /* fwd sockaddr_in6 */ O_DSCP, /* 2 u32 = DSCP mask */ O_SETDSCP, /* arg1=DSCP value */ O_LAST_OPCODE /* not an opcode! */ }; /* * The extension header are filtered only for presence using a bit * vector with a flag for each header. */ #define EXT_FRAGMENT 0x1 #define EXT_HOPOPTS 0x2 #define EXT_ROUTING 0x4 #define EXT_AH 0x8 #define EXT_ESP 0x10 #define EXT_DSTOPTS 0x20 #define EXT_RTHDR0 0x40 #define EXT_RTHDR2 0x80 /* * Template for instructions. * * ipfw_insn is used for all instructions which require no operands, * a single 16-bit value (arg1), or a couple of 8-bit values. * * For other instructions which require different/larger arguments * we have derived structures, ipfw_insn_*. * * The size of the instruction (in 32-bit words) is in the low * 6 bits of "len". The 2 remaining bits are used to implement * NOT and OR on individual instructions. Given a type, you can * compute the length to be put in "len" using F_INSN_SIZE(t) * * F_NOT negates the match result of the instruction. * * F_OR is used to build or blocks. By default, instructions * are evaluated as part of a logical AND. An "or" block * { X or Y or Z } contains F_OR set in all but the last * instruction of the block. A match will cause the code * to skip past the last instruction of the block. * * NOTA BENE: in a couple of places we assume that * sizeof(ipfw_insn) == sizeof(u_int32_t) * this needs to be fixed. * */ typedef struct _ipfw_insn { /* template for instructions */ u_int8_t opcode; u_int8_t len; /* number of 32-bit words */ #define F_NOT 0x80 #define F_OR 0x40 #define F_LEN_MASK 0x3f #define F_LEN(cmd) ((cmd)->len & F_LEN_MASK) u_int16_t arg1; } ipfw_insn; /* * The F_INSN_SIZE(type) computes the size, in 4-byte words, of * a given type. */ #define F_INSN_SIZE(t) ((sizeof (t))/sizeof(u_int32_t)) /* * This is used to store an array of 16-bit entries (ports etc.) */ typedef struct _ipfw_insn_u16 { ipfw_insn o; u_int16_t ports[2]; /* there may be more */ } ipfw_insn_u16; /* * This is used to store an array of 32-bit entries * (uid, single IPv4 addresses etc.) */ typedef struct _ipfw_insn_u32 { ipfw_insn o; u_int32_t d[1]; /* one or more */ } ipfw_insn_u32; /* * This is used to store IP addr-mask pairs. */ typedef struct _ipfw_insn_ip { ipfw_insn o; struct in_addr addr; struct in_addr mask; } ipfw_insn_ip; /* * This is used to forward to a given address (ip). */ typedef struct _ipfw_insn_sa { ipfw_insn o; struct sockaddr_in sa; } ipfw_insn_sa; /* * This is used to forward to a given address (ipv6). */ typedef struct _ipfw_insn_sa6 { ipfw_insn o; struct sockaddr_in6 sa; } ipfw_insn_sa6; /* * This is used for MAC addr-mask pairs. */ typedef struct _ipfw_insn_mac { ipfw_insn o; u_char addr[12]; /* dst[6] + src[6] */ u_char mask[12]; /* dst[6] + src[6] */ } ipfw_insn_mac; /* * This is used for interface match rules (recv xx, xmit xx). */ typedef struct _ipfw_insn_if { ipfw_insn o; union { struct in_addr ip; int glob; } p; char name[IFNAMSIZ]; } ipfw_insn_if; /* * This is used for storing an altq queue id number. */ typedef struct _ipfw_insn_altq { ipfw_insn o; u_int32_t qid; } ipfw_insn_altq; /* * This is used for limit rules. */ typedef struct _ipfw_insn_limit { ipfw_insn o; u_int8_t _pad; u_int8_t limit_mask; /* combination of DYN_* below */ #define DYN_SRC_ADDR 0x1 #define DYN_SRC_PORT 0x2 #define DYN_DST_ADDR 0x4 #define DYN_DST_PORT 0x8 u_int16_t conn_limit; } ipfw_insn_limit; /* * This is used for log instructions. */ typedef struct _ipfw_insn_log { ipfw_insn o; u_int32_t max_log; /* how many do we log -- 0 = all */ u_int32_t log_left; /* how many left to log */ } ipfw_insn_log; /* * Data structures required by both ipfw(8) and ipfw(4) but not part of the * management API are protected by IPFW_INTERNAL. */ #ifdef IPFW_INTERNAL /* Server pool support (LSNAT). */ struct cfg_spool { LIST_ENTRY(cfg_spool) _next; /* chain of spool instances */ struct in_addr addr; u_short port; }; #endif /* Redirect modes id. */ #define REDIR_ADDR 0x01 #define REDIR_PORT 0x02 #define REDIR_PROTO 0x04 #ifdef IPFW_INTERNAL /* Nat redirect configuration. */ struct cfg_redir { LIST_ENTRY(cfg_redir) _next; /* chain of redir instances */ u_int16_t mode; /* type of redirect mode */ struct in_addr laddr; /* local ip address */ struct in_addr paddr; /* public ip address */ struct in_addr raddr; /* remote ip address */ u_short lport; /* local port */ u_short pport; /* public port */ u_short rport; /* remote port */ u_short pport_cnt; /* number of public ports */ u_short rport_cnt; /* number of remote ports */ int proto; /* protocol: tcp/udp */ struct alias_link **alink; /* num of entry in spool chain */ u_int16_t spool_cnt; /* chain of spool instances */ LIST_HEAD(spool_chain, cfg_spool) spool_chain; }; #endif #ifdef IPFW_INTERNAL /* Nat configuration data struct. */ struct cfg_nat { /* chain of nat instances */ LIST_ENTRY(cfg_nat) _next; int id; /* nat id */ struct in_addr ip; /* nat ip address */ char if_name[IF_NAMESIZE]; /* interface name */ int mode; /* aliasing mode */ struct libalias *lib; /* libalias instance */ /* number of entry in spool chain */ int redir_cnt; /* chain of redir instances */ LIST_HEAD(redir_chain, cfg_redir) redir_chain; }; #endif #define SOF_NAT sizeof(struct cfg_nat) #define SOF_REDIR sizeof(struct cfg_redir) #define SOF_SPOOL sizeof(struct cfg_spool) /* Nat command. */ typedef struct _ipfw_insn_nat { ipfw_insn o; struct cfg_nat *nat; } ipfw_insn_nat; /* Apply ipv6 mask on ipv6 addr */ #define APPLY_MASK(addr,mask) \ (addr)->__u6_addr.__u6_addr32[0] &= (mask)->__u6_addr.__u6_addr32[0]; \ (addr)->__u6_addr.__u6_addr32[1] &= (mask)->__u6_addr.__u6_addr32[1]; \ (addr)->__u6_addr.__u6_addr32[2] &= (mask)->__u6_addr.__u6_addr32[2]; \ (addr)->__u6_addr.__u6_addr32[3] &= (mask)->__u6_addr.__u6_addr32[3]; /* Structure for ipv6 */ typedef struct _ipfw_insn_ip6 { ipfw_insn o; struct in6_addr addr6; struct in6_addr mask6; } ipfw_insn_ip6; /* Used to support icmp6 types */ typedef struct _ipfw_insn_icmp6 { ipfw_insn o; uint32_t d[7]; /* XXX This number si related to the netinet/icmp6.h * define ICMP6_MAXTYPE * as follows: n = ICMP6_MAXTYPE/32 + 1 * Actually is 203 */ } ipfw_insn_icmp6; /* * Here we have the structure representing an ipfw rule. * * It starts with a general area (with link fields and counters) * followed by an array of one or more instructions, which the code * accesses as an array of 32-bit values. * * Given a rule pointer r: * * r->cmd is the start of the first instruction. * ACTION_PTR(r) is the start of the first action (things to do * once a rule matched). * * When assembling instruction, remember the following: * * + if a rule has a "keep-state" (or "limit") option, then the * first instruction (at r->cmd) MUST BE an O_PROBE_STATE * + if a rule has a "log" option, then the first action * (at ACTION_PTR(r)) MUST be O_LOG * + if a rule has an "altq" option, it comes after "log" * + if a rule has an O_TAG option, it comes after "log" and "altq" * * NOTE: we use a simple linked list of rules because we never need * to delete a rule without scanning the list. We do not use * queue(3) macros for portability and readability. */ struct ip_fw { struct ip_fw *x_next; /* linked list of rules */ struct ip_fw *next_rule; /* ptr to next [skipto] rule */ /* 'next_rule' is used to pass up 'set_disable' status */ uint16_t act_ofs; /* offset of action in 32-bit units */ uint16_t cmd_len; /* # of 32-bit words in cmd */ uint16_t rulenum; /* rule number */ uint8_t set; /* rule set (0..31) */ #define RESVD_SET 31 /* set for default and persistent rules */ uint8_t _pad; /* padding */ uint32_t id; /* rule id */ /* These fields are present in all rules. */ uint64_t pcnt; /* Packet counter */ uint64_t bcnt; /* Byte counter */ uint32_t timestamp; /* tv_sec of last match */ ipfw_insn cmd[1]; /* storage for commands */ }; #define ACTION_PTR(rule) \ (ipfw_insn *)( (u_int32_t *)((rule)->cmd) + ((rule)->act_ofs) ) #define RULESIZE(rule) (sizeof(struct ip_fw) + \ ((struct ip_fw *)(rule))->cmd_len * 4 - 4) #if 1 // should be moved to in.h /* * This structure is used as a flow mask and a flow id for various * parts of the code. * addr_type is used in userland and kernel to mark the address type. * fib is used in the kernel to record the fib in use. * _flags is used in the kernel to store tcp flags for dynamic rules. */ struct ipfw_flow_id { uint32_t dst_ip; uint32_t src_ip; uint16_t dst_port; uint16_t src_port; uint8_t fib; uint8_t proto; uint8_t _flags; /* protocol-specific flags */ uint8_t addr_type; /* 4=ip4, 6=ip6, 1=ether ? */ struct in6_addr dst_ip6; struct in6_addr src_ip6; uint32_t flow_id6; uint32_t extra; /* queue/pipe or frag_id */ }; #endif #define IS_IP6_FLOW_ID(id) ((id)->addr_type == 6) /* * Dynamic ipfw rule. */ typedef struct _ipfw_dyn_rule ipfw_dyn_rule; struct _ipfw_dyn_rule { ipfw_dyn_rule *next; /* linked list of rules. */ struct ip_fw *rule; /* pointer to rule */ /* 'rule' is used to pass up the rule number (from the parent) */ ipfw_dyn_rule *parent; /* pointer to parent rule */ u_int64_t pcnt; /* packet match counter */ u_int64_t bcnt; /* byte match counter */ struct ipfw_flow_id id; /* (masked) flow id */ u_int32_t expire; /* expire time */ u_int32_t bucket; /* which bucket in hash table */ u_int32_t state; /* state of this rule (typically a * combination of TCP flags) */ u_int32_t ack_fwd; /* most recent ACKs in forward */ u_int32_t ack_rev; /* and reverse directions (used */ /* to generate keepalives) */ u_int16_t dyn_type; /* rule type */ u_int16_t count; /* refcount */ }; /* * Definitions for IP option names. */ #define IP_FW_IPOPT_LSRR 0x01 #define IP_FW_IPOPT_SSRR 0x02 #define IP_FW_IPOPT_RR 0x04 #define IP_FW_IPOPT_TS 0x08 /* * Definitions for TCP option names. */ #define IP_FW_TCPOPT_MSS 0x01 #define IP_FW_TCPOPT_WINDOW 0x02 #define IP_FW_TCPOPT_SACK 0x04 #define IP_FW_TCPOPT_TS 0x08 #define IP_FW_TCPOPT_CC 0x10 #define ICMP_REJECT_RST 0x100 /* fake ICMP code (send a TCP RST) */ #define ICMP6_UNREACH_RST 0x100 /* fake ICMPv6 code (send a TCP RST) */ /* * These are used for lookup tables. */ #define IPFW_TABLE_CIDR 1 /* Table for holding IPv4/IPv6 prefixes */ #define IPFW_TABLE_INTERFACE 2 /* Table for holding interface names */ #define IPFW_TABLE_MAXTYPE 2 /* Maximum valid number */ typedef struct _ipfw_table_entry { in_addr_t addr; /* network address */ u_int32_t value; /* value */ u_int16_t tbl; /* table number */ u_int8_t masklen; /* mask length */ } ipfw_table_entry; typedef struct _ipfw_table_xentry { uint16_t len; /* Total entry length */ uint8_t type; /* entry type */ uint8_t masklen; /* mask length */ uint16_t tbl; /* table number */ uint32_t value; /* value */ union { /* Longest field needs to be aligned by 4-byte boundary */ struct in6_addr addr6; /* IPv6 address */ char iface[IF_NAMESIZE]; /* interface name */ } k; } ipfw_table_xentry; typedef struct _ipfw_table { u_int32_t size; /* size of entries in bytes */ u_int32_t cnt; /* # of entries */ u_int16_t tbl; /* table number */ ipfw_table_entry ent[0]; /* entries */ } ipfw_table; typedef struct _ipfw_xtable { ip_fw3_opheader opheader; /* eXtended tables are controlled via IP_FW3 */ uint32_t size; /* size of entries in bytes */ uint32_t cnt; /* # of entries */ uint16_t tbl; /* table number */ uint8_t type; /* table type */ ipfw_table_xentry xent[0]; /* entries */ } ipfw_xtable; #endif /* _IPFW2_H */
30.926791
88
0.660841
[ "vector" ]
6c390a1f981b1510125446f95c006cae0f243214
13,965
h
C
linux-2.6.16-unmod/drivers/usb/media/usbvideo.h
ut-osa/syncchar
eba20da163260b6ae1ef3e334ad2137873a8d625
[ "BSD-3-Clause" ]
1
2020-11-10T12:47:02.000Z
2020-11-10T12:47:02.000Z
linux-2.6.0/drivers/usb/media/usbvideo.h
dnhua/Linux_study
96863b599cbba9c925b3209bed07b1d7b60cb463
[ "MIT" ]
null
null
null
linux-2.6.0/drivers/usb/media/usbvideo.h
dnhua/Linux_study
96863b599cbba9c925b3209bed07b1d7b60cb463
[ "MIT" ]
1
2019-05-14T16:36:45.000Z
2019-05-14T16:36:45.000Z
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef usbvideo_h #define usbvideo_h #include <linux/config.h> #include <linux/videodev.h> #include <linux/usb.h> /* Most helpful debugging aid */ #define assert(expr) ((void) ((expr) ? 0 : (err("assert failed at line %d",__LINE__)))) #define USBVIDEO_REPORT_STATS 1 /* Set to 0 to block statistics on close */ /* Bit flags (options) */ #define FLAGS_RETRY_VIDIOCSYNC (1 << 0) #define FLAGS_MONOCHROME (1 << 1) #define FLAGS_DISPLAY_HINTS (1 << 2) #define FLAGS_OVERLAY_STATS (1 << 3) #define FLAGS_FORCE_TESTPATTERN (1 << 4) #define FLAGS_SEPARATE_FRAMES (1 << 5) #define FLAGS_CLEAN_FRAMES (1 << 6) #define FLAGS_NO_DECODING (1 << 7) /* Bit flags for frames (apply to the frame where they are specified) */ #define USBVIDEO_FRAME_FLAG_SOFTWARE_CONTRAST (1 << 0) /* Camera capabilities (maximum) */ #define CAMERA_URB_FRAMES 32 #define CAMERA_MAX_ISO_PACKET 1023 /* 1022 actually sent by camera */ #define FRAMES_PER_DESC (CAMERA_URB_FRAMES) #define FRAME_SIZE_PER_DESC (CAMERA_MAX_ISO_PACKET) /* This macro restricts an int variable to an inclusive range */ #define RESTRICT_TO_RANGE(v,mi,ma) { if ((v) < (mi)) (v) = (mi); else if ((v) > (ma)) (v) = (ma); } #define V4L_BYTES_PER_PIXEL 3 /* Because we produce RGB24 */ /* * Use this macro to construct constants for different video sizes. * We have to deal with different video sizes that have to be * configured in the device or compared against when we receive * a data. Normally one would define a bunch of VIDEOSIZE_x_by_y * #defines and that's the end of story. However this solution * does not allow to convert between real pixel sizes and the * constant (integer) value that may be used to tag a frame or * whatever. The set of macros below constructs videosize constants * from the pixel size and allows to reconstruct the pixel size * from the combined value later. */ #define VIDEOSIZE(x,y) (((x) & 0xFFFFL) | (((y) & 0xFFFFL) << 16)) #define VIDEOSIZE_X(vs) ((vs) & 0xFFFFL) #define VIDEOSIZE_Y(vs) (((vs) >> 16) & 0xFFFFL) typedef unsigned long videosize_t; /* * This macro checks if the camera is still operational. The 'uvd' * pointer must be valid, uvd->dev must be valid, we are not * removing the device and the device has not erred on us. */ #define CAMERA_IS_OPERATIONAL(uvd) (\ (uvd != NULL) && \ ((uvd)->dev != NULL) && \ ((uvd)->last_error == 0) && \ (!(uvd)->remove_pending)) /* * We use macros to do YUV -> RGB conversion because this is * very important for speed and totally unimportant for size. * * YUV -> RGB Conversion * --------------------- * * B = 1.164*(Y-16) + 2.018*(V-128) * G = 1.164*(Y-16) - 0.813*(U-128) - 0.391*(V-128) * R = 1.164*(Y-16) + 1.596*(U-128) * * If you fancy integer arithmetics (as you should), hear this: * * 65536*B = 76284*(Y-16) + 132252*(V-128) * 65536*G = 76284*(Y-16) - 53281*(U-128) - 25625*(V-128) * 65536*R = 76284*(Y-16) + 104595*(U-128) * * Make sure the output values are within [0..255] range. */ #define LIMIT_RGB(x) (((x) < 0) ? 0 : (((x) > 255) ? 255 : (x))) #define YUV_TO_RGB_BY_THE_BOOK(my,mu,mv,mr,mg,mb) { \ int mm_y, mm_yc, mm_u, mm_v, mm_r, mm_g, mm_b; \ mm_y = (my) - 16; \ mm_u = (mu) - 128; \ mm_v = (mv) - 128; \ mm_yc= mm_y * 76284; \ mm_b = (mm_yc + 132252*mm_v ) >> 16; \ mm_g = (mm_yc - 53281*mm_u - 25625*mm_v ) >> 16; \ mm_r = (mm_yc + 104595*mm_u ) >> 16; \ mb = LIMIT_RGB(mm_b); \ mg = LIMIT_RGB(mm_g); \ mr = LIMIT_RGB(mm_r); \ } #define RING_QUEUE_SIZE (128*1024) /* Must be a power of 2 */ #define RING_QUEUE_ADVANCE_INDEX(rq,ind,n) (rq)->ind = ((rq)->ind + (n)) & ((rq)->length-1) #define RING_QUEUE_DEQUEUE_BYTES(rq,n) RING_QUEUE_ADVANCE_INDEX(rq,ri,n) #define RING_QUEUE_PEEK(rq,ofs) ((rq)->queue[((ofs) + (rq)->ri) & ((rq)->length-1)]) struct RingQueue { unsigned char *queue; /* Data from the Isoc data pump */ int length; /* How many bytes allocated for the queue */ int wi; /* That's where we write */ int ri; /* Read from here until you hit write index */ wait_queue_head_t wqh; /* Processes waiting */ }; enum ScanState { ScanState_Scanning, /* Scanning for header */ ScanState_Lines /* Parsing lines */ }; /* Completion states of the data parser */ enum ParseState { scan_Continue, /* Just parse next item */ scan_NextFrame, /* Frame done, send it to V4L */ scan_Out, /* Not enough data for frame */ scan_EndParse /* End parsing */ }; enum FrameState { FrameState_Unused, /* Unused (no MCAPTURE) */ FrameState_Ready, /* Ready to start grabbing */ FrameState_Grabbing, /* In the process of being grabbed into */ FrameState_Done, /* Finished grabbing, but not been synced yet */ FrameState_Done_Hold, /* Are syncing or reading */ FrameState_Error, /* Something bad happened while processing */ }; /* * Some frames may contain only even or odd lines. This type * specifies what type of deinterlacing is required. */ enum Deinterlace { Deinterlace_None=0, Deinterlace_FillOddLines, Deinterlace_FillEvenLines }; #define USBVIDEO_NUMFRAMES 2 /* How many frames we work with */ #define USBVIDEO_NUMSBUF 2 /* How many URBs linked in a ring */ /* This structure represents one Isoc request - URB and buffer */ struct usbvideo_sbuf { char *data; struct urb *urb; }; struct usbvideo_frame { char *data; /* Frame buffer */ unsigned long header; /* Significant bits from the header */ videosize_t canvas; /* The canvas (max. image) allocated */ videosize_t request; /* That's what the application asked for */ unsigned short palette; /* The desired format */ enum FrameState frameState;/* State of grabbing */ enum ScanState scanstate; /* State of scanning */ enum Deinterlace deinterlace; int flags; /* USBVIDEO_FRAME_FLAG_xxx bit flags */ int curline; /* Line of frame we're working on */ long seqRead_Length; /* Raw data length of frame */ long seqRead_Index; /* Amount of data that has been already read */ void *user; /* Additional data that user may need */ }; /* Statistics that can be overlaid on screen */ struct usbvideo_statistics { unsigned long frame_num; /* Sequential number of the frame */ unsigned long urb_count; /* How many URBs we received so far */ unsigned long urb_length; /* Length of last URB */ unsigned long data_count; /* How many bytes we received */ unsigned long header_count; /* How many frame headers we found */ unsigned long iso_skip_count; /* How many empty ISO packets received */ unsigned long iso_err_count; /* How many bad ISO packets received */ }; struct usbvideo; struct uvd { struct video_device vdev; /* Must be the first field! */ struct usb_device *dev; struct usbvideo *handle; /* Points back to the struct usbvideo */ void *user_data; /* Camera-dependent data */ int user_size; /* Size of that camera-dependent data */ int debug; /* Debug level for usbvideo */ unsigned char iface; /* Video interface number */ unsigned char video_endp; unsigned char ifaceAltActive; unsigned char ifaceAltInactive; /* Alt settings */ unsigned long flags; /* FLAGS_USBVIDEO_xxx */ unsigned long paletteBits; /* Which palettes we accept? */ unsigned short defaultPalette; /* What palette to use for read() */ struct semaphore lock; int user; /* user count for exclusive use */ videosize_t videosize; /* Current setting */ videosize_t canvas; /* This is the width,height of the V4L canvas */ int max_frame_size; /* Bytes in one video frame */ int uvd_used; /* Is this structure in use? */ int streaming; /* Are we streaming Isochronous? */ int grabbing; /* Are we grabbing? */ int settingsAdjusted; /* Have we adjusted contrast etc.? */ int last_error; /* What calamity struck us? */ char *fbuf; /* Videodev buffer area */ int fbuf_size; /* Videodev buffer size */ int curframe; int iso_packet_len; /* Videomode-dependent, saves bus bandwidth */ struct RingQueue dp; /* Isoc data pump */ struct usbvideo_frame frame[USBVIDEO_NUMFRAMES]; struct usbvideo_sbuf sbuf[USBVIDEO_NUMSBUF]; volatile int remove_pending; /* If set then about to exit */ struct video_picture vpic, vpic_old; /* Picture settings */ struct video_capability vcap; /* Video capabilities */ struct video_channel vchan; /* May be used for tuner support */ struct usbvideo_statistics stats; char videoName[32]; /* Holds name like "video7" */ }; /* * usbvideo callbacks (virtual methods). They are set when usbvideo * services are registered. All of these default to NULL, except those * that default to usbvideo-provided methods. */ struct usbvideo_cb { int (*probe)(struct usb_interface *, const struct usb_device_id *); void (*userFree)(struct uvd *); void (*disconnect)(struct usb_interface *); int (*setupOnOpen)(struct uvd *); void (*videoStart)(struct uvd *); void (*videoStop)(struct uvd *); void (*processData)(struct uvd *, struct usbvideo_frame *); void (*postProcess)(struct uvd *, struct usbvideo_frame *); void (*adjustPicture)(struct uvd *); int (*getFPS)(struct uvd *); int (*overlayHook)(struct uvd *, struct usbvideo_frame *); int (*getFrame)(struct uvd *, int); int (*startDataPump)(struct uvd *uvd); void (*stopDataPump)(struct uvd *uvd); int (*setVideoMode)(struct uvd *uvd, struct video_window *vw); }; struct usbvideo { int num_cameras; /* As allocated */ struct usb_driver usbdrv; /* Interface to the USB stack */ char drvName[80]; /* Driver name */ struct semaphore lock; /* Mutex protecting camera structures */ struct usbvideo_cb cb; /* Table of callbacks (virtual methods) */ struct video_device vdt; /* Video device template */ struct uvd *cam; /* Array of camera structures */ struct module *md_module; /* Minidriver module */ }; /* * This macro retrieves callback address from the struct uvd object. * No validity checks are done here, so be sure to check the * callback beforehand with VALID_CALLBACK. */ #define GET_CALLBACK(uvd,cbName) ((uvd)->handle->cb.cbName) /* * This macro returns either callback pointer or NULL. This is safe * macro, meaning that most of components of data structures involved * may be NULL - this only results in NULL being returned. You may * wish to use this macro to make sure that the callback is callable. * However keep in mind that those checks take time. */ #define VALID_CALLBACK(uvd,cbName) ((((uvd) != NULL) && \ ((uvd)->handle != NULL)) ? GET_CALLBACK(uvd,cbName) : NULL) int RingQueue_Dequeue(struct RingQueue *rq, unsigned char *dst, int len); int RingQueue_Enqueue(struct RingQueue *rq, const unsigned char *cdata, int n); void RingQueue_WakeUpInterruptible(struct RingQueue *rq); void RingQueue_Flush(struct RingQueue *rq); static inline int RingQueue_GetLength(const struct RingQueue *rq) { return (rq->wi - rq->ri + rq->length) & (rq->length-1); } static inline int RingQueue_GetFreeSpace(const struct RingQueue *rq) { return rq->length - RingQueue_GetLength(rq); } void usbvideo_DrawLine( struct usbvideo_frame *frame, int x1, int y1, int x2, int y2, unsigned char cr, unsigned char cg, unsigned char cb); void usbvideo_HexDump(const unsigned char *data, int len); void usbvideo_SayAndWait(const char *what); void usbvideo_TestPattern(struct uvd *uvd, int fullframe, int pmode); /* Memory allocation routines */ unsigned long usbvideo_kvirt_to_pa(unsigned long adr); int usbvideo_register( struct usbvideo **pCams, const int num_cams, const int num_extra, const char *driverName, const struct usbvideo_cb *cbTable, struct module *md, const struct usb_device_id *id_table); struct uvd *usbvideo_AllocateDevice(struct usbvideo *cams); int usbvideo_RegisterVideoDevice(struct uvd *uvd); void usbvideo_Deregister(struct usbvideo **uvt); int usbvideo_v4l_initialize(struct video_device *dev); void usbvideo_DeinterlaceFrame(struct uvd *uvd, struct usbvideo_frame *frame); /* * This code performs bounds checking - use it when working with * new formats, or else you may get oopses all over the place. * If pixel falls out of bounds then it gets shoved back (as close * to place of offence as possible) and is painted bright red. * * There are two important concepts: frame width, height and * V4L canvas width, height. The former is the area requested by * the application -for this very frame-. The latter is the largest * possible frame that we can serve (we advertise that via V4L ioctl). * The frame data is expected to be formatted as lines of length * VIDEOSIZE_X(fr->request), total VIDEOSIZE_Y(frame->request) lines. */ static inline void RGB24_PUTPIXEL( struct usbvideo_frame *fr, int ix, int iy, unsigned char vr, unsigned char vg, unsigned char vb) { register unsigned char *pf; int limiter = 0, mx, my; mx = ix; my = iy; if (mx < 0) { mx=0; limiter++; } else if (mx >= VIDEOSIZE_X((fr)->request)) { mx= VIDEOSIZE_X((fr)->request) - 1; limiter++; } if (my < 0) { my = 0; limiter++; } else if (my >= VIDEOSIZE_Y((fr)->request)) { my = VIDEOSIZE_Y((fr)->request) - 1; limiter++; } pf = (fr)->data + V4L_BYTES_PER_PIXEL*((iy)*VIDEOSIZE_X((fr)->request) + (ix)); if (limiter) { *pf++ = 0; *pf++ = 0; *pf++ = 0xFF; } else { *pf++ = (vb); *pf++ = (vg); *pf++ = (vr); } } #endif /* usbvideo_h */
35.444162
99
0.697888
[ "object" ]
6c3f81277d337049de57877b6e78789d84bea69e
5,142
h
C
src/P1/dictionary.h
daviddias99/project-2-feup-prog
1033a3fead013d188b51334c8f1e96032d95d439
[ "MIT" ]
null
null
null
src/P1/dictionary.h
daviddias99/project-2-feup-prog
1033a3fead013d188b51334c8f1e96032d95d439
[ "MIT" ]
null
null
null
src/P1/dictionary.h
daviddias99/project-2-feup-prog
1033a3fead013d188b51334c8f1e96032d95d439
[ "MIT" ]
null
null
null
#ifndef dictionary_h #define dictionary_h #include <fstream> #include <string> #include <vector> #include <map> using namespace std; /** * The Dictionary class stores the contents of a synonyms dictionary text file, which consists of words and its synonyms. * The class is responsible from extracting only the simple words and its synonyms(that could be expressions) from a text file in the specified format. * Each object of the Dictionary class can only be associated with one dictionary text file. */ class Dictionary { public: //---------- CONSTRUCTOR ---------- /** * Creates an empty dictionary which is not associated to any dictionary text file. */ Dictionary(); //---------- PUBLIC MEMBER FUNCTIONS ---------- /** * Extracts words from a synonyms dictionary file, storing them in a map(key = word; value = string of synonyms). * * @param fileName name of the dictionary file * @return true if the extraction was successful, false otherwise */ bool extractWords(string fileName); /** * Gives the name of the file associated to the dictionary. * * @return name of the dictionary file */ string getDicName(); /** * Checks if a given word belongs on the dictionary(case insensitive). * * @param word word we want to check if it belongs on the dictionary * @return true if the word is on the dictionary */ bool wordExists(string word); /** * Returns a vector containing all the synonyms of a given word(case insensitive). * * @param word word whose synonyms we want to know * @return vector containing the synonyms from a given word */ vector<string> getSynonyms(string word); /** * Randomly chooses a word from the vector of synonyms of a given word(case insensitive). * * @param word word whose random synonym we want * @return string corresponding to a random synonym of the given word */ string getRndSyn(string word); /** * Receives a wildcard and returns a vector with all possible matches for each substring starting in the first letter of the wildcard. * * @param wildcard wildcard containing '?' * @return vector of strings containing all the matches for the given wildcard */ vector<string> suggestions(string wildcard); private: //---------- PRIVATE MEMBER FUNCTIONS ---------- /** * Modifies a word removing all the spaces from the beginning and end. * * @param word word to be normalized, passed by reference */ void removeSpaces(string& word); /** * Receives a word and returns it in all capital letters * * @param word word to make all caps * @return word in all caps */ string allCaps(string word); /** * Checks if a string is a simple word(only one word with all alphabetic chars). * * @param s string to be validated * @return true if the string is a valid simple word, false otherwise */ bool isValidWord(string s); /** * Checks if a string is a valid synonym(can be an expression, having ' ' or '-'). * * @param s string to be validated * @return true if the string is a valid synonym, false otherwise */ bool isValidSyn(string s); /** * Processes a line from the dictionary, adding the words and the synonyms to the map. * * @param line line from the dictionary */ void processLine(string line); /** * Gives a random integer between two given numbers(don't forget to seed the RNG in the main function). * * @param n1 bound * @param n2 other bound * @return random between n1 and n2 (n1 and n2 included) */ int randomBetween(int n1, int n2); /** * Gives all the words present in the dictionary that match the given wildcard. * * @param wilCard string corresponding to the wildcard(A ? sign matches any character, except an empty string) * @return vector containing all the matching words */ vector<string> getFittingWords(string wildCard); ////////////////////////////////////////////////////////////////////////// // WildcardMatch // str - Input string to match // strWild - Match mask that may contain wildcards like ? and * // // A ? sign matches any character, except an empty string. // A * sign matches any string inclusive an empty string. // Characters are compared caseless. // // ADAPTED FROM: // https://www.codeproject.com/Articles/188256/A-Simple-Wildcard-Matching-Function bool wildcardMatch(const char *str, const char *strWild); /** * Finds if a certain word exists in the given vector. * * @param vector vector of strings * @param word word to be seached in the vector * @return true if the word is present in the vector, false otherwise */ bool vectorFind(vector<string>& vector, string word); /** * Produces, from a given wildcard, a vector that contains the invalid wildcards. * * @param wildcard a wildcard * @result a vector containing the invalid wildcards */ vector<string> invalidWildcards(string wildcard); //---------- PRIVATE ATTRIBUTES ---------- map<string, vector<string>> wordMap; // map(key = word; value = string of synonyms) string fileName; // name of the dictionary file used to extract the words }; #endif
29.050847
151
0.686503
[ "object", "vector" ]
6c426528ee81c7a7000c328bebccd7aab241b8a9
45,093
h
C
include/cutlass/transform/threadblock/predicated_tile_access_iterator.h
MegEngine/cutlass
31798848e40c2752d4b3db193491a63b77455029
[ "BSD-3-Clause" ]
44
2020-09-15T05:31:25.000Z
2022-03-22T08:02:02.000Z
include/cutlass/transform/threadblock/predicated_tile_access_iterator.h
MegEngine/cutlass
31798848e40c2752d4b3db193491a63b77455029
[ "BSD-3-Clause" ]
null
null
null
include/cutlass/transform/threadblock/predicated_tile_access_iterator.h
MegEngine/cutlass
31798848e40c2752d4b3db193491a63b77455029
[ "BSD-3-Clause" ]
7
2020-09-16T15:18:21.000Z
2022-03-28T10:06:11.000Z
/*************************************************************************************************** * Copyright (c) 2017-2020, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 NVIDIA CORPORATION 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 TOR (INCLUDING *NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, *EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **************************************************************************************************/ /*! \file \brief Templates calculating the address and predicates to the load of tiles from pitch-linear rank=2 tensors. This iterator uses masks to guard out-of-bounds accesses and visits the last "residue" tile first, with the objective of minimizing predicate mask updates during steady-state operation. A precomputed "Params" object minimizes the amount of state that must be stored in registers, and integer addition is used to advance the pointer through memory. */ #pragma once #include "cutlass/array.h" #include "cutlass/coord.h" #include "cutlass/cutlass.h" #include "cutlass/layout/matrix.h" #include "cutlass/layout/pitch_linear.h" #include "cutlass/matrix_shape.h" #include "cutlass/predicate_vector.h" #include "cutlass/tensor_ref.h" #include "cutlass/tensor_view.h" //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// namespace cutlass { namespace transform { namespace threadblock { //////////////////////////////////////////////////////////////////////////////// /// PredicatedTileAccessIterator /// template <typename Shape, typename Element, typename Layout, int AdvanceRank, typename ThreadMap, typename AccessType> class PredicatedTileAccessIterator; //////////////////////////////////////////////////////////////////////////////// /// Specialization of PredicatedTileAccessIterator for pitch-linear data. /// template <typename Shape_, typename Element_, int AdvanceRank, typename ThreadMap_, typename AccessType_> class PredicatedTileAccessIterator<Shape_, Element_, layout::PitchLinear, AdvanceRank, ThreadMap_, AccessType_> { public: static_assert(AdvanceRank == 0 || AdvanceRank == 1, "Specialization for pitch-linear iterator may along advance " "along the " "contiguous(rank=0) or strided(rank=1) dimension."); using Shape = Shape_; using Element = Element_; using Layout = layout::PitchLinear; static int const kAdvanceRank = AdvanceRank; using ThreadMap = ThreadMap_; using AccessType = AccessType_; using Index = typename Layout::Index; using LongIndex = typename Layout::LongIndex; using TensorRef = TensorRef<Element, Layout>; using TensorView = TensorView<Element, Layout>; using TensorCoord = typename Layout::TensorCoord; using Pointer = Element*; using NonConstPointer = typename platform::remove_const<Element>::type*; static int const kAccessesPerVector = ThreadMap::kElementsPerAccess / AccessType::kElements; static_assert(!(ThreadMap::kElementsPerAccess % AccessType::kElements), "Vectors implied by the thread map must be divisible by the " "access type."); static int const kPredicatesPerByte = 4; static int const kPredicatesPerWord = 4 * kPredicatesPerByte; static int const kPredicateCount = ThreadMap::Iterations::kCount * kAccessesPerVector; /// Number of 32b words containing predicates static int const kPredicateByteCount = (kPredicateCount + kPredicatesPerByte - 1) / kPredicatesPerByte; static int const kPredicateWordCount = (kPredicateByteCount + 3) / 4; static unsigned const kPredicateMask = (1u << kPredicatesPerByte) - 1u; static_assert(kPredicateWordCount <= 4, "Too many predicates."); /// Predicate vector stores mask to guard accesses using Mask = Array<uint32_t, kPredicateWordCount>; /// Parameters object is precomputed state and is host-constructible class Params { public: friend PredicatedTileAccessIterator; private: /// stride of pitch-linear layout (units of Element) int stride_; /// amount (in byte) to increment pointer to move to next access along /// strided dimension LongIndex inc_strided_; /// amount (in byte) to increment pointer from last access to first /// access of next tile LongIndex inc_next_; /// amount (in byte) to increment pointer from first access of current /// tile to first access of next tile LongIndex inc_advance_; public: // Default ctor CUTLASS_HOST_DEVICE Params() : stride_(0), inc_strided_(0), inc_next_(0), inc_advance_(0) {} /// Construct the Params object given a pitch-linear tensor's layout CUTLASS_HOST_DEVICE Params(Layout const& layout) : stride_(layout.stride(0)) { inc_strided_ = (LongIndex(stride_) * ThreadMap::Delta::kStrided) * sizeof_bits<Element>::value / 8; if (kAdvanceRank) { // advance along strided dimension inc_advance_ = Shape::kStrided * LongIndex(stride_) * sizeof_bits<Element>::value / 8; } else { // advance along contiguous dimension inc_advance_ = Shape::kContiguous * sizeof_bits<Element>::value / 8; } inc_next_ = inc_advance_ - LongIndex(ThreadMap::Iterations::kStrided - 1) * ThreadMap::Delta::kStrided * LongIndex(stride_) * sizeof_bits<Element>::value / 8; }; }; private: /// Internal pointer type permits fast address arithmetic using BytePointer = char*; private: // // Data members // /// Parameters object with precomputed internal state Params const& params_; /// Internal pointer to first access of tile BytePointer pointer_; /// Guard predicates uint32_t predicates_[kPredicateWordCount]; /// Size of tensor TensorCoord extent_; /// Initial offset for each thread TensorCoord thread_offset_; /// Offset to the first steady-state tile TensorCoord residue_offset_; /// Used for out-of-order visitation bool is_residue_tile_; /// Iteration along vectors implied by the thread map int iteration_vector_; /// Iteration in the contiguous dimension int iteration_contiguous_; /// Iteration in the strided dimension int iteration_strided_; private: /// Computes predicates based on internally tracked per-thread offset. CUTLASS_DEVICE void compute_predicates_( /// Extent of the matrix window TensorCoord extent, /// optionally, simplify predicate calculation during 'steady state' /// phase bool is_steady_state = false) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < kPredicateWordCount; ++i) { predicates_[i] = 0u; } CUTLASS_PRAGMA_UNROLL for (int access_idx = 0; access_idx < ThreadMap::Iterations::kCount * kAccessesPerVector; ++access_idx) { int s = access_idx / (ThreadMap::Iterations::kContiguous * kAccessesPerVector); int access_residual = access_idx % (ThreadMap::Iterations::kContiguous * kAccessesPerVector); int c = access_residual / kAccessesPerVector; int v = access_residual % kAccessesPerVector; TensorCoord iteration_coord(c * ThreadMap::Delta::kContiguous + v * AccessType::kElements, s * ThreadMap::Delta::kStrided); TensorCoord coord = thread_offset_ + iteration_coord; bool guard; if (is_steady_state) { if (kAdvanceRank == 0) { guard = (coord.strided() < extent.strided()); } else { guard = (coord.contiguous() < extent.contiguous()); } } else { guard = (coord.strided() < extent.strided() && coord.contiguous() < extent.contiguous()); } int pred_idx = v + kAccessesPerVector * (c + ThreadMap::Iterations::kContiguous * s); int word_idx = pred_idx / kPredicatesPerWord; int residual = pred_idx % kPredicatesPerWord; int byte_idx = residual / kPredicatesPerByte; int bit_idx = residual % kPredicatesPerByte; predicates_[word_idx] |= (unsigned(guard) << (byte_idx * 8 + bit_idx)); } } public: /// Constructs a TileIterator from its precomputed state, threadblock /// offset, and thread ID CUTLASS_HOST_DEVICE PredicatedTileAccessIterator( /// Precomputed parameters object Params const& params, /// Pointer to start of tensor Pointer pointer, /// Extent of tensor TensorCoord extent, /// ID of each participating thread int thread_id, /// Initial offset of threadblock TensorCoord const& threadblock_offset) : params_(params), pointer_(reinterpret_cast<BytePointer>( const_cast<NonConstPointer>(pointer))), extent_(extent), is_residue_tile_(true) { TensorCoord residue_extent; if (kAdvanceRank) { Index residue_size = (extent_[kAdvanceRank] - threadblock_offset.strided()) % Shape::kStrided; if (!residue_size) { residue_size = Shape::kStrided; } residue_offset_ = make_Coord(0, residue_size); residue_extent = make_Coord(extent_.contiguous(), min(threadblock_offset.strided() + residue_size, extent_.strided())); } else { Index residue_size = (extent_[kAdvanceRank] - threadblock_offset.contiguous()) % Shape::kContiguous; if (!residue_size) { residue_size = Shape::kContiguous; } residue_offset_ = make_Coord(residue_size, 0); residue_extent = make_Coord( min(extent_.contiguous(), threadblock_offset.contiguous() + residue_size), extent_.strided()); } // Per-thread offset in logical coordinates of tensor thread_offset_ = threadblock_offset + ThreadMap::initial_offset(thread_id); // update internal pointers Layout layout(params_.stride_); add_pointer_offset(layout(thread_offset_)); compute_predicates_(residue_extent, false); set_iteration_index(0); } /// Construct a PredicatedTileAccessIterator with zero threadblock offset CUTLASS_HOST_DEVICE PredicatedTileAccessIterator( /// Precomputed parameters object Params const& params, /// Pointer to start of tensor Pointer pointer, /// Extent of tensor TensorCoord extent, ///< ID of each participating thread int thread_id) : PredicatedTileAccessIterator(params, pointer, extent, thread_id, make_Coord(0, 0)) {} /// Overrides the internal iteration index CUTLASS_HOST_DEVICE void set_iteration_index(int index) { iteration_vector_ = index % kAccessesPerVector; int residual_access = index / kAccessesPerVector; iteration_contiguous_ = residual_access % ThreadMap::Iterations::kContiguous; iteration_strided_ = residual_access / ThreadMap::Iterations::kContiguous; } /// Adds a pointer offset in units of Element CUTLASS_HOST_DEVICE void add_pointer_offset(LongIndex pointer_offset) { pointer_ += sizeof_bits<Element>::value * pointer_offset / 8; } /// Advances an iterator along logical dimensions of matrix in units of /// whole tiles CUTLASS_DEVICE void add_tile_offset(TensorCoord const& tile_offset) { if (is_residue_tile_) { thread_offset_ += residue_offset_; Layout layout(params_.stride_); add_pointer_offset(layout(residue_offset_)); compute_predicates_(extent_, true); if (kAdvanceRank) { pointer_ += params_.inc_advance_ * LongIndex(tile_offset.strided() - 1); pointer_ += Shape::kContiguous * tile_offset.contiguous(); } else { pointer_ += params_.inc_advance_ * LongIndex(tile_offset.contiguous() - 1); pointer_ += Shape::kStrided * tile_offset.strided(); } } else { if (kAdvanceRank) { pointer_ += params_.inc_advance_ * LongIndex(tile_offset.strided()); pointer_ += Shape::kContiguous * tile_offset.contiguous(); } else { pointer_ += params_.inc_advance_ * LongIndex(tile_offset.contiguous()); pointer_ += Shape::kStrided * tile_offset.strided(); } } is_residue_tile_ = false; } /// Returns a pointer CUTLASS_HOST_DEVICE AccessType* get() const { return reinterpret_cast<AccessType*>( pointer_ + iteration_contiguous_ * (ThreadMap::Delta::kContiguous * sizeof_bits<Element>::value) / 8) + iteration_vector_; } /// Increment and return an instance to self. CUTLASS_HOST_DEVICE PredicatedTileAccessIterator& operator++() { ++iteration_vector_; if (iteration_vector_ < kAccessesPerVector) { return *this; } iteration_vector_ = 0; ++iteration_contiguous_; if (iteration_contiguous_ < ThreadMap::Iterations::kContiguous) { return *this; } // Enter here only if (iteration_contiguous_ == // ThreadMap::Iteration::kContiguous) iteration_contiguous_ = 0; ++iteration_strided_; if (iteration_strided_ < ThreadMap::Iterations::kStrided) { pointer_ += params_.inc_strided_; return *this; } // Enter here only if (iteration_stride_ == // ThreadMap::Iteration::kStrided) which means we enter the next tile. iteration_strided_ = 0; // advance to next tile pointer_ += params_.inc_next_; // now return to start tile - if the iterator is subsequently advanced, // this subtraction as well as the subsequent integer addition are both // elided by the compiler. pointer_ -= params_.inc_advance_; return *this; } /// Increment and return an instance to self. CUTLASS_HOST_DEVICE PredicatedTileAccessIterator operator++(int) { PredicatedTileAccessIterator self(*this); operator++(); return self; } /// Clears the predicate set efficiently CUTLASS_HOST_DEVICE void clear_mask() { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < kPredicateWordCount; ++i) { predicates_[i] = 0u; } } /// Clears the predicate set efficiently CUTLASS_HOST_DEVICE void enable_mask() { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < kPredicateWordCount; ++i) { predicates_[i] = 0xffffffff; } } /// Sets the predicate mask, overriding value stored in predicate iterator CUTLASS_HOST_DEVICE void set_mask(Mask const& mask) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < kPredicateWordCount; ++i) { predicates_[i] = mask[i]; } } /// Gets the mask CUTLASS_HOST_DEVICE void get_mask(Mask& mask) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < kPredicateWordCount; ++i) { mask[i] = predicates_[i]; } } /// Returns whether access is valid or not CUTLASS_HOST_DEVICE bool valid() { int pred_idx = iteration_vector_ + kAccessesPerVector * (iteration_contiguous_ + iteration_strided_ * ThreadMap::Iterations::kContiguous); int word_idx = pred_idx / kPredicatesPerWord; int residual = pred_idx % kPredicatesPerWord; int byte_idx = residual / kPredicatesPerByte; int bit_idx = residual % kPredicatesPerByte; bool pred = (predicates_[word_idx] & (1u << (byte_idx * 8 + bit_idx))) != 0; return pred; // return true; } }; //////////////////////////////////////////////////////////////////////////////// /// Specialization of PredicatedTileAccessIterator for column-major data. /// /// Satisfies: ForwardTileIteratorConcept | /// ReadableContiguousTileIteratorConcept | /// WriteableContiguousTileIteratorConcept | /// MaskedTileIteratorConcept /// template <typename Shape_, typename Element_, int AdvanceRank, typename ThreadMap_, typename AccessType_> class PredicatedTileAccessIterator<Shape_, Element_, layout::ColumnMajor, AdvanceRank, ThreadMap_, AccessType_> { public: static_assert(AdvanceRank == 0 || AdvanceRank == 1, "Specialization for pitch-linear iterator may along advance " "along the " "contiguous(rank=0) or strided(rank=1) dimension."); using Shape = Shape_; using Element = Element_; using Layout = layout::ColumnMajor; static int const kAdvanceRank = AdvanceRank; using ThreadMap = ThreadMap_; using AccessType = AccessType_; using Index = typename Layout::Index; using LongIndex = typename Layout::LongIndex; using TensorRef = TensorRef<Element, Layout>; using TensorView = TensorView<Element, Layout>; using TensorCoord = typename Layout::TensorCoord; using Pointer = Element*; using NonConstPointer = typename platform::remove_const<Element>::type*; using UnderlyingIterator = PredicatedTileAccessIterator< layout::PitchLinearShape<Shape::kRow, Shape::kColumn>, Element, layout::PitchLinear, (kAdvanceRank == 0 ? 0 : 1), ThreadMap, AccessType>; /// Predicate vector stores mask to guard accesses using Mask = typename UnderlyingIterator::Mask; static int const kAccessesPerVector = UnderlyingIterator::kAccessesPerVector; /// Parameters object is precomputed state and is host-constructible class Params { private: friend PredicatedTileAccessIterator; /// Parameters object typename UnderlyingIterator::Params params_; public: /// Default ctor CUTLASS_HOST_DEVICE Params() {} /// Construct the Params object given a pitch-linear tensor's layout CUTLASS_HOST_DEVICE Params(Layout const& layout) : params_(layout::PitchLinear(layout.stride(0))){}; }; private: // // Data members // /// Underlying pitch-linear tile iterator UnderlyingIterator iterator_; public: /// Constructs a TileIterator from its precomputed state, threadblock /// offset, and thread ID CUTLASS_HOST_DEVICE PredicatedTileAccessIterator( ///< Precomputed parameters object Params const& params, ///< Pointer to start of tensor Pointer pointer, ///< Extent of tensor TensorCoord extent, ///< ID of each participating thread int thread_id, ///< Initial offset of threadblock TensorCoord const& threadblock_offset) : iterator_(params.params_, pointer, layout::PitchLinearCoord(extent.row(), extent.column()), thread_id, layout::PitchLinearCoord(threadblock_offset.row(), threadblock_offset.column())) { } /// Construct a PredicatedTileAccessIterator with zero threadblock offset CUTLASS_HOST_DEVICE PredicatedTileAccessIterator( Params const& params, ///< Precomputed parameters object Pointer pointer, ///< Pointer to start of tensor TensorCoord extent, ///< Extent of tensor int thread_id ///< ID of each participating thread ) : PredicatedTileAccessIterator(params, pointer, extent, thread_id, make_Coord(0, 0)) {} /// Overrides the internal iteration index CUTLASS_HOST_DEVICE void set_iteration_index(int index) { iterator_.set_iteration_index(index); } /// Adds a pointer offset in units of Element CUTLASS_HOST_DEVICE void add_pointer_offset(LongIndex pointer_offset) { iterator_.add_pointer_offset(pointer_offset); } /// Advances an iterator along logical dimensions of matrix in units of /// whole tiles CUTLASS_HOST_DEVICE void add_tile_offset(TensorCoord const& tile_offset) { iterator_.add_tile_offset({tile_offset.row(), tile_offset.column()}); } /// Returns a pointer CUTLASS_HOST_DEVICE AccessType* get() const { return reinterpret_cast<AccessType*>(iterator_.get()); } /// Advances to the next tile in memory. /// /// The first time this method is called, predicates are updated, and the /// iterator's internal pointer is reverted to the first "steady state" /// tile. Subsequent calls are lightweight and must only update the internal /// pointer. CUTLASS_HOST_DEVICE PredicatedTileAccessIterator& operator++() { ++iterator_; return *this; } /// Advances to the next tile in memory. /// /// The first time this method is called, predicates are updated, and the /// iterator's internal pointer is reverted to the first "steady state" /// tile. Subsequent calls are lightweight and must only update the internal /// pointer. CUTLASS_HOST_DEVICE PredicatedTileAccessIterator operator++(int) { PredicatedTileAccessIterator self(*this); operator++(); return self; } /// Clears the predicate set efficiently CUTLASS_HOST_DEVICE void clear_mask() { iterator_.clear_mask(); } /// Clears the predicate set efficiently CUTLASS_HOST_DEVICE void enable_mask() { iterator_.enable_mask(); } /// Sets the predicate mask, overriding value stored in predicate iterator CUTLASS_HOST_DEVICE void set_mask(Mask const& mask) { iterator_.set_mask(mask); } /// Gets the mask CUTLASS_HOST_DEVICE void get_mask(Mask& mask) { iterator_.get_mask(mask); } /// Returns whether access is valid or not CUTLASS_HOST_DEVICE bool valid() { return iterator_.valid(); } }; //////////////////////////////////////////////////////////////////////////////// /// Specialization of PredicatedTileAccessIterator for row-major data. /// /// Satisfies: ForwardTileIteratorConcept | /// ReadableContiguousTileIteratorConcept | /// WriteableContiguousTileIteratorConcept | /// MaskedTileIteratorConcept /// template <typename Shape_, typename Element_, int AdvanceRank, typename ThreadMap_, typename AccessType_> class PredicatedTileAccessIterator<Shape_, Element_, layout::RowMajor, AdvanceRank, ThreadMap_, AccessType_> { public: static_assert(AdvanceRank == 0 || AdvanceRank == 1, "Specialization for pitch-linear iterator may along advance " "along the " "contiguous(rank=0) or strided(rank=1) dimension."); using Shape = Shape_; using Element = Element_; using Layout = layout::RowMajor; static int const kAdvanceRank = AdvanceRank; using ThreadMap = ThreadMap_; using AccessType = AccessType_; using Index = typename Layout::Index; using LongIndex = typename Layout::LongIndex; using TensorRef = TensorRef<Element, Layout>; using TensorView = TensorView<Element, Layout>; using TensorCoord = typename Layout::TensorCoord; using Pointer = Element*; using NonConstPointer = typename platform::remove_const<Element>::type*; using UnderlyingIterator = PredicatedTileAccessIterator< layout::PitchLinearShape<Shape::kColumn, Shape::kRow>, Element, layout::PitchLinear, (kAdvanceRank == 0 ? 1 : 0), ThreadMap, AccessType>; static int const kAccessesPerVector = UnderlyingIterator::kAccessesPerVector; /// Predicate vector stores mask to guard accesses using Mask = typename UnderlyingIterator::Mask; /// Parameters object is precomputed state and is host-constructible class Params { private: friend PredicatedTileAccessIterator; /// Parameters object typename UnderlyingIterator::Params params_; public: /// Default ctor CUTLASS_HOST_DEVICE Params() {} /// Construct the Params object given a pitch-linear tensor's layout CUTLASS_HOST_DEVICE Params(Layout const& layout) : params_(layout::PitchLinear(layout.stride(0))){}; }; private: // // Data members // /// Underlying pitch-linear tile iterator UnderlyingIterator iterator_; public: /// Constructs a TileIterator from its precomputed state, threadblock /// offset, and thread ID CUTLASS_HOST_DEVICE PredicatedTileAccessIterator( ///< Precomputed parameters object Params const& params, ///< Pointer to start of tensor Pointer pointer, ///< Extent of tensor TensorCoord extent, ///< ID of each participating thread int thread_id, ///< Initial offset of threadblock TensorCoord const& threadblock_offset) : iterator_(params.params_, pointer, layout::PitchLinearCoord(extent.column(), extent.row()), thread_id, layout::PitchLinearCoord(threadblock_offset.column(), threadblock_offset.row())) {} /// Construct a PredicatedTileAccessIterator with zero threadblock offset CUTLASS_HOST_DEVICE PredicatedTileAccessIterator( Params const& params, ///< Precomputed parameters object Pointer pointer, ///< Pointer to start of tensor TensorCoord extent, ///< Extent of tensor int thread_id ///< ID of each participating thread ) : PredicatedTileAccessIterator(params, pointer, extent, thread_id, make_Coord(0, 0)) {} /// Overrides the internal iteration index CUTLASS_HOST_DEVICE void set_iteration_index(int index) { iterator_.set_iteration_index(index); } /// Adds a pointer offset in units of Element CUTLASS_HOST_DEVICE void add_pointer_offset(LongIndex pointer_offset) { iterator_.add_pointer_offset(pointer_offset); } /// Advances an iterator along logical dimensions of matrix in units of /// whole tiles CUTLASS_HOST_DEVICE void add_tile_offset(TensorCoord const& tile_offset) { iterator_.add_tile_offset({tile_offset.column(), tile_offset.row()}); } /// Returns a pointer CUTLASS_HOST_DEVICE AccessType* get() const { return reinterpret_cast<AccessType*>(iterator_.get()); } /// Advances to the next tile in memory. /// /// The first time this method is called, predicates are updated, and the /// iterator's internal pointer is reverted to the first "steady state" /// tile. Subsequent calls are lightweight and must only update the internal /// pointer. CUTLASS_HOST_DEVICE PredicatedTileAccessIterator& operator++() { ++iterator_; return *this; } /// Advances to the next tile in memory. /// /// The first time this method is called, predicates are updated, and the /// iterator's internal pointer is reverted to the first "steady state" /// tile. Subsequent calls are lightweight and must only update the internal /// pointer. CUTLASS_HOST_DEVICE PredicatedTileAccessIterator operator++(int) { PredicatedTileAccessIterator self(*this); operator++(); return self; } /// Clears the predicate set efficiently CUTLASS_HOST_DEVICE void clear_mask() { iterator_.clear_mask(); } /// Clears the predicate set efficiently CUTLASS_HOST_DEVICE void enable_mask() { iterator_.enable_mask(); } /// Sets the predicate mask, overriding value stored in predicate iterator CUTLASS_HOST_DEVICE void set_mask(Mask const& mask) { iterator_.set_mask(mask); } /// Gets the mask CUTLASS_HOST_DEVICE void get_mask(Mask& mask) { iterator_.get_mask(mask); } /// Returns whether access is valid or not CUTLASS_HOST_DEVICE bool valid() { return iterator_.valid(); } }; //////////////////////////////////////////////////////////////////////////////// /// Specialization of PredicatedTileAccessIterator for column-major interleaved /// data. It is mapped to the congruous layout. /// /// Satisfies: ForwardTileIteratorConcept | /// ReadableContiguousTileIteratorConcept | /// WriteableContiguousTileIteratorConcept | /// MaskedTileIteratorConcept /// template <typename Shape_, typename Element_, int AdvanceRank, typename ThreadMap_, typename AccessType_, int InterleavedK> class PredicatedTileAccessIterator<Shape_, Element_, layout::ColumnMajorInterleaved<InterleavedK>, AdvanceRank, ThreadMap_, AccessType_> { public: static_assert(AdvanceRank == 0 || AdvanceRank == 1, "Specialization for pitch-linear iterator may along advance " "along the " "contiguous(rank=0) or strided(rank=1) dimension."); using Shape = Shape_; using Element = Element_; static int const kInterleavedK = InterleavedK; using Layout = layout::ColumnMajorInterleaved<kInterleavedK>; static int const kAdvanceRank = AdvanceRank; using ThreadMap = ThreadMap_; using AccessType = AccessType_; using Index = typename Layout::Index; using LongIndex = typename Layout::LongIndex; using TensorRef = TensorRef<Element, Layout>; using TensorView = TensorView<Element, Layout>; using TensorCoord = typename Layout::TensorCoord; using Pointer = Element*; using NonConstPointer = typename platform::remove_const<Element>::type*; using UnderlyingIterator = PredicatedTileAccessIterator< layout::PitchLinearShape<Shape::kRow * kInterleavedK, Shape::kColumn / kInterleavedK>, Element, layout::PitchLinear, (kAdvanceRank == 0 ? 0 : 1), ThreadMap, AccessType>; static int const kAccessesPerVector = UnderlyingIterator::kAccessesPerVector; /// Predicate vector stores mask to guard accesses using Mask = typename UnderlyingIterator::Mask; /// Parameters object is precomputed state and is host-constructible class Params { private: friend PredicatedTileAccessIterator; /// Parameters object typename UnderlyingIterator::Params params_; public: CUTLASS_HOST_DEVICE Params() {} /// Construct the Params object given a pitch-linear tensor's layout CUTLASS_HOST_DEVICE Params(Layout const& layout) : params_(layout::PitchLinear(layout.stride(0))) {} }; private: // // Data members // /// Underlying pitch-linear tile iterator UnderlyingIterator iterator_; public: /// Constructs a TileIterator from its precomputed state, threadblock /// offset, and thread ID CUTLASS_HOST_DEVICE PredicatedTileAccessIterator( /// Precomputed parameters object Params const& params, /// Pointer to start of tensor Pointer pointer, /// Extent of tensor TensorCoord extent, /// ID of each participating thread int thread_id, /// Initial offset of threadblock TensorCoord const& threadblock_offset) : iterator_( params.params_, pointer, layout::PitchLinearCoord(extent.row() * kInterleavedK, extent.column() / kInterleavedK), thread_id, layout::PitchLinearCoord( threadblock_offset.row() * kInterleavedK, threadblock_offset.column() / kInterleavedK)) {} /// Construct a PredicatedTileAccessIterator with zero threadblock offset CUTLASS_HOST_DEVICE PredicatedTileAccessIterator( Params const& params, ///< Precomputed parameters object Pointer pointer, ///< Pointer to start of tensor TensorCoord extent, ///< Extent of tensor int thread_id ///< ID of each participating thread ) : PredicatedTileAccessIterator(params, pointer, extent, thread_id, make_Coord(0, 0)) {} /// Overrides the internal iteration index CUTLASS_HOST_DEVICE void set_iteration_index(int index) { iterator_.set_iteration_index(index); } /// Adds a pointer offset in units of Element CUTLASS_HOST_DEVICE void add_pointer_offset(LongIndex pointer_offset) { iterator_.add_pointer_offset(pointer_offset); } /// Advances an iterator along logical dimensions of matrix in units of /// whole tiles CUTLASS_HOST_DEVICE void add_tile_offset(TensorCoord const& tile_offset) { iterator_.add_tile_offset({tile_offset.row(), tile_offset.column()}); } /// Returns a pointer CUTLASS_HOST_DEVICE AccessType* get() const { return reinterpret_cast<AccessType*>(iterator_.get()); } /// Advances to the next tile in memory. /// /// The first time this method is called, predicates are updated, and the /// iterator's internal pointer is reverted to the first "steady state" /// tile. Subsequent calls are lightweight and must only update the internal /// pointer. CUTLASS_HOST_DEVICE PredicatedTileAccessIterator& operator++() { ++iterator_; return *this; } /// Advances to the next tile in memory. /// /// The first time this method is called, predicates are updated, and the /// iterator's internal pointer is reverted to the first "steady state" /// tile. Subsequent calls are lightweight and must only update the internal /// pointer. CUTLASS_HOST_DEVICE PredicatedTileAccessIterator operator++(int) { PredicatedTileAccessIterator self(*this); operator++(); return self; } /// Clears the predicate set efficiently CUTLASS_HOST_DEVICE void clear_mask() { iterator_.clear_mask(); } /// Clears the predicate set efficiently CUTLASS_HOST_DEVICE void enable_mask() { iterator_.enable_mask(); } /// Sets the predicate mask, overriding value stored in predicate iterator CUTLASS_HOST_DEVICE void set_mask(Mask const& mask) { iterator_.set_mask(mask); } /// Gets the mask CUTLASS_HOST_DEVICE void get_mask(Mask& mask) { iterator_.get_mask(mask); } /// Returns whether access is valid or not CUTLASS_HOST_DEVICE bool valid() { return iterator_.valid(); } }; //////////////////////////////////////////////////////////////////////////////// /// Specialization of PredicatedTileAccessIterator for row-major interleaved /// data. // It is mapped to the congruous layout. /// /// Satisfies: ForwardTileIteratorConcept | /// ReadableContiguousTileIteratorConcept | /// WriteableContiguousTileIteratorConcept | /// MaskedTileIteratorConcept /// template <typename Shape_, typename Element_, int AdvanceRank, typename ThreadMap_, typename AccessType_, int InterleavedK> class PredicatedTileAccessIterator<Shape_, Element_, layout::RowMajorInterleaved<InterleavedK>, AdvanceRank, ThreadMap_, AccessType_> { public: static_assert(AdvanceRank == 0 || AdvanceRank == 1, "Specialization for pitch-linear iterator may along advance " "along the " "contiguous(rank=0) or strided(rank=1) dimension."); using Shape = Shape_; using Element = Element_; static int const kInterleavedK = InterleavedK; using Layout = layout::RowMajorInterleaved<kInterleavedK>; static int const kAdvanceRank = AdvanceRank; using ThreadMap = ThreadMap_; using AccessType = AccessType_; using Index = typename Layout::Index; using LongIndex = typename Layout::LongIndex; using TensorRef = TensorRef<Element, Layout>; using TensorView = TensorView<Element, Layout>; using TensorCoord = typename Layout::TensorCoord; using Pointer = Element*; using NonConstPointer = typename platform::remove_const<Element>::type*; using UnderlyingIterator = PredicatedTileAccessIterator< layout::PitchLinearShape<Shape::kColumn * kInterleavedK, Shape::kRow / kInterleavedK>, Element, layout::PitchLinear, (kAdvanceRank == 0 ? 1 : 0), ThreadMap, AccessType>; static int const kAccessesPerVector = UnderlyingIterator::kAccessesPerVector; /// Predicate vector stores mask to guard accesses using Mask = typename UnderlyingIterator::Mask; /// Parameters object is precomputed state and is host-constructible class Params { private: friend PredicatedTileAccessIterator; /// Parameters object typename UnderlyingIterator::Params params_; public: CUTLASS_HOST_DEVICE Params() {} /// Construct the Params object given a pitch-linear tensor's layout CUTLASS_HOST_DEVICE Params(Layout const& layout) : params_(layout::PitchLinear(layout.stride(0))) {} }; private: // // Data members // /// Underlying pitch-linear tile iterator UnderlyingIterator iterator_; public: /// Constructs a TileIterator from its precomputed state, threadblock /// offset, and thread ID CUTLASS_HOST_DEVICE PredicatedTileAccessIterator( /// Precomputed parameters object Params const& params, /// Pointer to start of tensor Pointer pointer, /// Extent of tensor TensorCoord extent, /// ID of each participating thread int thread_id, /// Initial offset of threadblock TensorCoord const& threadblock_offset) : iterator_( params.params_, pointer, layout::PitchLinearCoord(extent.column() * kInterleavedK, extent.row() / kInterleavedK), thread_id, layout::PitchLinearCoord( threadblock_offset.column() * kInterleavedK, threadblock_offset.row() / kInterleavedK)) {} /// Construct a PredicatedTileAccessIterator with zero threadblock offset CUTLASS_HOST_DEVICE PredicatedTileAccessIterator( Params const& params, ///< Precomputed parameters object Pointer pointer, ///< Pointer to start of tensor TensorCoord extent, ///< Extent of tensor int thread_id ///< ID of each participating thread ) : PredicatedTileAccessIterator(params, pointer, extent, thread_id, make_Coord(0, 0)) {} /// Overrides the internal iteration index CUTLASS_HOST_DEVICE void set_iteration_index(int index) { iterator_.set_iteration_index(index); } /// Adds a pointer offset in units of Element CUTLASS_HOST_DEVICE void add_pointer_offset(LongIndex pointer_offset) { iterator_.add_pointer_offset(pointer_offset); } /// Advances an iterator along logical dimensions of matrix in units of /// whole tiles CUTLASS_HOST_DEVICE void add_tile_offset(TensorCoord const& tile_offset) { iterator_.add_tile_offset({tile_offset.column(), tile_offset.row()}); } /// Returns a pointer CUTLASS_HOST_DEVICE AccessType* get() const { return reinterpret_cast<AccessType*>(iterator_.get()); } /// Advances to the next tile in memory. /// /// The first time this method is called, predicates are updated, and the /// iterator's internal pointer is reverted to the first "steady state" /// tile. Subsequent calls are lightweight and must only update the internal /// pointer. CUTLASS_HOST_DEVICE PredicatedTileAccessIterator& operator++() { ++iterator_; return *this; } /// Advances to the next tile in memory. /// /// The first time this method is called, predicates are updated, and the /// iterator's internal pointer is reverted to the first "steady state" /// tile. Subsequent calls are lightweight and must only update the internal /// pointer. CUTLASS_HOST_DEVICE PredicatedTileAccessIterator operator++(int) { PredicatedTileAccessIterator self(*this); operator++(); return self; } /// Clears the predicate set efficiently CUTLASS_HOST_DEVICE void clear_mask() { iterator_.clear_mask(); } /// Clears the predicate set efficiently CUTLASS_HOST_DEVICE void enable_mask() { iterator_.enable_mask(); } /// Sets the predicate mask, overriding value stored in predicate iterator CUTLASS_HOST_DEVICE void set_mask(Mask const& mask) { iterator_.set_mask(mask); } /// Gets the mask CUTLASS_HOST_DEVICE void get_mask(Mask& mask) { iterator_.get_mask(mask); } /// Returns whether access is valid or not CUTLASS_HOST_DEVICE bool valid() { return iterator_.valid(); } }; //////////////////////////////////////////////////////////////////////////////// } // namespace threadblock } // namespace transform } // namespace cutlass ////////////////////////////////////////////////////////////////////////////////
36.132212
100
0.615927
[ "object", "shape", "vector", "transform" ]
6c4429b368b649229e91902a015c500cc7c4d111
2,947
h
C
chrome/browser/gtk/options/url_picker_dialog_gtk.h
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
2
2017-09-02T19:08:28.000Z
2021-11-15T15:15:14.000Z
chrome/browser/gtk/options/url_picker_dialog_gtk.h
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/gtk/options/url_picker_dialog_gtk.h
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
1
2020-04-13T05:45:10.000Z
2020-04-13T05:45:10.000Z
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_GTK_OPTIONS_URL_PICKER_DIALOG_GTK_H_ #define CHROME_BROWSER_GTK_OPTIONS_URL_PICKER_DIALOG_GTK_H_ #pragma once #include <string> #include "app/gtk_signal.h" #include "base/basictypes.h" #include "base/callback.h" #include "chrome/browser/gtk/gtk_tree.h" #include "chrome/browser/history/history.h" class AccessibleWidgetHelper; class GURL; class Profile; class PossibleURLModel; class UrlPickerDialogGtk : public gtk_tree::TableAdapter::Delegate { public: typedef Callback1<const GURL&>::Type UrlPickerCallback; UrlPickerDialogGtk(UrlPickerCallback* callback, Profile* profile, GtkWindow* parent); ~UrlPickerDialogGtk(); // gtk_tree::TableAdapter::Delegate implementation. virtual void SetColumnValues(int row, GtkTreeIter* iter); private: // Call the callback based on url entry. void AddURL(); // Set sensitivity of buttons based on url entry state. void EnableControls(); // Return the entry-formatted url for path in the sorted model. std::string GetURLForPath(GtkTreePath* path) const; // GTK sorting callbacks. static gint CompareTitle(GtkTreeModel* model, GtkTreeIter* a, GtkTreeIter* b, gpointer window); static gint CompareURL(GtkTreeModel* model, GtkTreeIter* a, GtkTreeIter* b, gpointer window); CHROMEGTK_CALLBACK_0(UrlPickerDialogGtk, void, OnUrlEntryChanged); CHROMEGTK_CALLBACK_2(UrlPickerDialogGtk, void, OnHistoryRowActivated, GtkTreePath*, GtkTreeViewColumn*); CHROMEGTK_CALLBACK_1(UrlPickerDialogGtk, void, OnResponse, int); CHROMEGTK_CALLBACK_0(UrlPickerDialogGtk, void, OnWindowDestroy); // Callback for user selecting rows in recent history list. CHROMEG_CALLBACK_0(UrlPickerDialogGtk, void, OnHistorySelectionChanged, GtkTreeSelection*) // The dialog window. GtkWidget* dialog_; // The text entry for manually adding an URL. GtkWidget* url_entry_; // The add button (we need a reference to it so we can de-activate it when the // |url_entry_| is empty.) GtkWidget* add_button_; // The recent history list. GtkWidget* history_tree_; GtkListStore* history_list_store_; GtkTreeModel* history_list_sort_; GtkTreeSelection* history_selection_; // Profile. Profile* profile_; // The table model. scoped_ptr<PossibleURLModel> url_table_model_; scoped_ptr<gtk_tree::TableAdapter> url_table_adapter_; // Called if the user selects an url. UrlPickerCallback* callback_; // Helper object to manage accessibility metadata. scoped_ptr<AccessibleWidgetHelper> accessible_widget_helper_; DISALLOW_COPY_AND_ASSIGN(UrlPickerDialogGtk); }; #endif // CHROME_BROWSER_GTK_OPTIONS_URL_PICKER_DIALOG_GTK_H_
31.351064
80
0.746522
[ "object", "model" ]
6c4871e43d018ca96f28ca645d0f61bb4b5542d8
6,923
h
C
2.4/include/org/apache/xpath/objects/XStringForChars.h
yaohb/J2ObjCAuto
8b5252896999f367066e3f68226620f78c020923
[ "MIT" ]
null
null
null
2.4/include/org/apache/xpath/objects/XStringForChars.h
yaohb/J2ObjCAuto
8b5252896999f367066e3f68226620f78c020923
[ "MIT" ]
null
null
null
2.4/include/org/apache/xpath/objects/XStringForChars.h
yaohb/J2ObjCAuto
8b5252896999f367066e3f68226620f78c020923
[ "MIT" ]
null
null
null
// // Generated by the J2ObjC translator. DO NOT EDIT! // source: /Users/antoniocortes/j2objcprj/relases/j2objc/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/objects/XStringForChars.java // #include "J2ObjC_header.h" #pragma push_macro("INCLUDE_ALL_OrgApacheXpathObjectsXStringForChars") #ifdef RESTRICT_OrgApacheXpathObjectsXStringForChars #define INCLUDE_ALL_OrgApacheXpathObjectsXStringForChars 0 #else #define INCLUDE_ALL_OrgApacheXpathObjectsXStringForChars 1 #endif #undef RESTRICT_OrgApacheXpathObjectsXStringForChars #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 (OrgApacheXpathObjectsXStringForChars_) && (INCLUDE_ALL_OrgApacheXpathObjectsXStringForChars || defined(INCLUDE_OrgApacheXpathObjectsXStringForChars)) #define OrgApacheXpathObjectsXStringForChars_ #define RESTRICT_OrgApacheXpathObjectsXString 1 #define INCLUDE_OrgApacheXpathObjectsXString 1 #include "org/apache/xpath/objects/XString.h" @class IOSCharArray; @class OrgApacheXmlUtilsFastStringBuffer; @protocol OrgXmlSaxContentHandler; @protocol OrgXmlSaxExtLexicalHandler; /*! @brief This class will wrap a FastStringBuffer and allow for */ @interface OrgApacheXpathObjectsXStringForChars : OrgApacheXpathObjectsXString { @public /*! @brief The start position in the fsb. */ jint m_start_; /*! @brief The length of the string. */ jint m_length_; NSString *m_strCache_; } @property (readonly, class) jlong serialVersionUID NS_SWIFT_NAME(serialVersionUID); + (jlong)serialVersionUID; #pragma mark Public /*! @brief Construct a XNodeSet object. @param val FastStringBuffer object this will wrap, must be non-null. @param start The start position in the array. @param length The number of characters to read from the array. */ - (instancetype __nonnull)initWithCharArray:(IOSCharArray *)val withInt:(jint)start withInt:(jint)length; /*! @brief Cast result object to a string. @return The string this wraps or the empty string if null */ - (void)appendToFsbWithOrgApacheXmlUtilsFastStringBuffer:(OrgApacheXmlUtilsFastStringBuffer *)fsb; /*! @brief Returns the character at the specified index.An index ranges from <code>0</code> to <code>length() - 1</code>. The first character of the sequence is at index <code>0</code>, the next at index <code>1</code>, and so on, as for array indexing. @param index the index of the character. @return the character at the specified index of this string. The first character is at index <code>0</code>. @throw IndexOutOfBoundsExceptionif the <code>index</code> argument is negative or not less than the length of this string. */ - (jchar)charAtWithInt:(jint)index; /*! @brief Directly call the comment method on the passed LexicalHandler for the string-value. @param lh A non-null reference to a LexicalHandler. @throw org.xml.sax.SAXException */ - (void)dispatchAsCommentWithOrgXmlSaxExtLexicalHandler:(id<OrgXmlSaxExtLexicalHandler>)lh; /*! @brief Directly call the characters method on the passed ContentHandler for the string-value.Multiple calls to the ContentHandler's characters methods may well occur for a single call to this method. @param ch A non-null reference to a ContentHandler. @throw org.xml.sax.SAXException */ - (void)dispatchCharactersEventsWithOrgXmlSaxContentHandler:(id<OrgXmlSaxContentHandler>)ch; /*! @brief Cast result object to a string. @return The string this wraps or the empty string if null */ - (OrgApacheXmlUtilsFastStringBuffer *)fsb; /*! @brief Copies characters from this string into the destination character array. @param srcBegin index of the first character in the string to copy. @param srcEnd index after the last character in the string to copy. @param dst the destination array. @param dstBegin the start offset in the destination array. @throw IndexOutOfBoundsExceptionIf any of the following is true: <ul><li><code>srcBegin</code> is negative. <li><code>srcBegin</code> is greater than <code>srcEnd</code> <li><code>srcEnd</code> is greater than the length of this string <li><code>dstBegin</code> is negative <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than <code>dst.length</code></ul> @throw NullPointerExceptionif <code>dst</code> is <code>null</code> */ - (void)getCharsWithInt:(jint)srcBegin withInt:(jint)srcEnd withCharArray:(IOSCharArray *)dst withInt:(jint)dstBegin; /*! @brief Tell if this object contains a java String object. @return true if this XMLString can return a string without creating one. */ - (jboolean)hasString; /*! @brief Returns the length of this string. @return the length of the sequence of characters represented by this object. */ - (jint)length; /*! @brief Since this object is incomplete without the length and the offset, we have to convert to a string when this function is called. @return The java String representation of this object. */ - (id)object; /*! @brief Cast result object to a string. @return The string this wraps or the empty string if null */ - (NSString *)str; // Disallowed inherited constructors, do not use. - (instancetype __nonnull)initWithId:(id)arg0 NS_UNAVAILABLE; @end J2OBJC_EMPTY_STATIC_INIT(OrgApacheXpathObjectsXStringForChars) J2OBJC_FIELD_SETTER(OrgApacheXpathObjectsXStringForChars, m_strCache_, NSString *) inline jlong OrgApacheXpathObjectsXStringForChars_get_serialVersionUID(void); #define OrgApacheXpathObjectsXStringForChars_serialVersionUID -2235248887220850467LL J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathObjectsXStringForChars, serialVersionUID, jlong) FOUNDATION_EXPORT void OrgApacheXpathObjectsXStringForChars_initWithCharArray_withInt_withInt_(OrgApacheXpathObjectsXStringForChars *self, IOSCharArray *val, jint start, jint length); FOUNDATION_EXPORT OrgApacheXpathObjectsXStringForChars *new_OrgApacheXpathObjectsXStringForChars_initWithCharArray_withInt_withInt_(IOSCharArray *val, jint start, jint length) NS_RETURNS_RETAINED; FOUNDATION_EXPORT OrgApacheXpathObjectsXStringForChars *create_OrgApacheXpathObjectsXStringForChars_initWithCharArray_withInt_withInt_(IOSCharArray *val, jint start, jint length); J2OBJC_TYPE_LITERAL_HEADER(OrgApacheXpathObjectsXStringForChars) #endif #if __has_feature(nullability) #pragma clang diagnostic pop #endif #pragma clang diagnostic pop #pragma pop_macro("INCLUDE_ALL_OrgApacheXpathObjectsXStringForChars")
35.502564
196
0.764986
[ "object" ]
6c4ac5e7a077468cdc2291da079baa605159b2a0
11,048
h
C
Engine/Source/Editor/Sequencer/Public/SequencerCommands.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Editor/Sequencer/Public/SequencerCommands.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Editor/Sequencer/Public/SequencerCommands.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Framework/Commands/Commands.h" #include "EditorStyleSet.h" class FSequencerCommands : public TCommands<FSequencerCommands> { public: FSequencerCommands() : TCommands<FSequencerCommands> ( "Sequencer", NSLOCTEXT("Contexts", "Sequencer", "Sequencer"), NAME_None, // "MainFrame" // @todo Fix this crash FEditorStyle::GetStyleSetName() // Icon Style Set ) {} /** Toggle play */ TSharedPtr< FUICommandInfo > TogglePlay; /** Play forward */ TSharedPtr< FUICommandInfo > PlayForward; /** Jump to start of playback */ TSharedPtr< FUICommandInfo > JumpToStart; /** Jump to end of playback */ TSharedPtr< FUICommandInfo > JumpToEnd; /** Shuttle forward */ TSharedPtr< FUICommandInfo > ShuttleForward; /** Shuttle backward */ TSharedPtr< FUICommandInfo > ShuttleBackward; /** Pause */ TSharedPtr< FUICommandInfo > Pause; /** Step forward */ TSharedPtr< FUICommandInfo > StepForward; /** Step backward */ TSharedPtr< FUICommandInfo > StepBackward; /** Step to next key */ TSharedPtr< FUICommandInfo > StepToNextKey; /** Step to previous key */ TSharedPtr< FUICommandInfo > StepToPreviousKey; /** Step to next camera key */ TSharedPtr< FUICommandInfo > StepToNextCameraKey; /** Step to previous camera key */ TSharedPtr< FUICommandInfo > StepToPreviousCameraKey; /** Step to next shot */ TSharedPtr< FUICommandInfo > StepToNextShot; /** Step to previous shot */ TSharedPtr< FUICommandInfo > StepToPreviousShot; /** Set start playback range */ TSharedPtr< FUICommandInfo > SetStartPlaybackRange; /** Set end playback range */ TSharedPtr< FUICommandInfo > SetEndPlaybackRange; /** Reset the view range to the playback range */ TSharedPtr< FUICommandInfo > ResetViewRange; /** Zoom into the view range */ TSharedPtr< FUICommandInfo > ZoomInViewRange; /** Zoom out of the view range */ TSharedPtr< FUICommandInfo > ZoomOutViewRange; /** Set the selection range to the next shot. */ TSharedPtr< FUICommandInfo > SetSelectionRangeToNextShot; /** Set the selection range to the previous shot. */ TSharedPtr< FUICommandInfo > SetSelectionRangeToPreviousShot; /** Set the playback range to all the shots. */ TSharedPtr< FUICommandInfo > SetPlaybackRangeToAllShots; /** Toggle locking the playback range. */ TSharedPtr< FUICommandInfo > TogglePlaybackRangeLocked; /** Forces playback both in editor and at runtime to be evaluated at fixed frame intervals. */ TSharedPtr< FUICommandInfo > ToggleForceFixedFrameIntervalPlayback; /** Reruns construction scripts on bound actors every frame. */ TSharedPtr< FUICommandInfo > ToggleRerunConstructionScripts; /** Toggle constraining the time cursor to the playback range while scrubbing */ TSharedPtr< FUICommandInfo > ToggleKeepCursorInPlaybackRangeWhileScrubbing; /** Toggle constraining the time cursor to the playback range during playback */ TSharedPtr< FUICommandInfo > ToggleKeepCursorInPlaybackRange; /** Toggle constraining the playback range to the section bounds */ TSharedPtr< FUICommandInfo > ToggleKeepPlaybackRangeInSectionBounds; /** Expand all nodes and descendants */ TSharedPtr< FUICommandInfo > ExpandAllNodesAndDescendants; /** Collapse all nodes and descendants */ TSharedPtr< FUICommandInfo > CollapseAllNodesAndDescendants; /** Expand/collapse nodes */ TSharedPtr< FUICommandInfo > ToggleExpandCollapseNodes; /** Expand/collapse nodes and descendants */ TSharedPtr< FUICommandInfo > ToggleExpandCollapseNodesAndDescendants; /** Sets the upper bound of the selection range */ TSharedPtr< FUICommandInfo > SetSelectionRangeEnd; /** Sets the lower bound of the selection range */ TSharedPtr< FUICommandInfo > SetSelectionRangeStart; /** Clear and reset the selection range */ TSharedPtr< FUICommandInfo > ResetSelectionRange; /** Select all keys that fall into the selection range*/ TSharedPtr< FUICommandInfo > SelectKeysInSelectionRange; /** Select all sections that fall into the selection range*/ TSharedPtr< FUICommandInfo > SelectSectionsInSelectionRange; /** Select all keys and sections that fall into the selection range*/ TSharedPtr< FUICommandInfo > SelectAllInSelectionRange; /** Sets a key at the current time for the selected actor */ TSharedPtr< FUICommandInfo > SetKey; /** Sets the interp tangent mode for the selected keys to auto */ TSharedPtr< FUICommandInfo > SetInterpolationCubicAuto; /** Sets the interp tangent mode for the selected keys to user */ TSharedPtr< FUICommandInfo > SetInterpolationCubicUser; /** Sets the interp tangent mode for the selected keys to break */ TSharedPtr< FUICommandInfo > SetInterpolationCubicBreak; /** Sets the interp tangent mode for the selected keys to linear */ TSharedPtr< FUICommandInfo > SetInterpolationLinear; /** Sets the interp tangent mode for the selected keys to constant */ TSharedPtr< FUICommandInfo > SetInterpolationConstant; /** Trim section to the left, keeping the right portion */ TSharedPtr< FUICommandInfo > TrimSectionLeft; /** Trim section to the right, keeping the left portion */ TSharedPtr< FUICommandInfo > TrimSectionRight; /** Translate the selected keys and section to the left */ TSharedPtr< FUICommandInfo > TranslateLeft; /** Translate the selected keys and section to the right */ TSharedPtr< FUICommandInfo > TranslateRight; /** Split section */ TSharedPtr< FUICommandInfo > SplitSection; /** Set the auto change mode to Key. */ TSharedPtr< FUICommandInfo > SetAutoKey; /** Set the auto change mode to Track. */ TSharedPtr< FUICommandInfo > SetAutoTrack; /** Set the auto change mode to None. */ TSharedPtr< FUICommandInfo > SetAutoChangeAll; /** Set the auto change mode to None. */ TSharedPtr< FUICommandInfo > SetAutoChangeNone; /** Set allow edits to all. */ TSharedPtr< FUICommandInfo > AllowAllEdits; /** Set allow edits to sequencer only. */ TSharedPtr< FUICommandInfo > AllowSequencerEditsOnly; /** Set allow edits to levels only. */ TSharedPtr< FUICommandInfo > AllowLevelEditsOnly; /** Turns autokey on and off. */ TSharedPtr< FUICommandInfo > ToggleAutoKeyEnabled; /** Turns key all on and off. */ TSharedPtr< FUICommandInfo > ToggleKeyAllEnabled; /** Turns show frame numbers on and off. */ TSharedPtr< FUICommandInfo > ToggleShowFrameNumbers; /** Toggle the visibility of the goto box. */ TSharedPtr< FUICommandInfo > ToggleShowGotoBox; /** Toggle the visibility of the transform box. */ TSharedPtr< FUICommandInfo > ToggleShowTransformBox; /** Turns the range slider on and off. */ TSharedPtr< FUICommandInfo > ToggleShowRangeSlider; /** Turns snapping on and off. */ TSharedPtr< FUICommandInfo > ToggleIsSnapEnabled; /** Toggles whether or not keys should snap to the selected interval. */ TSharedPtr< FUICommandInfo > ToggleSnapKeyTimesToInterval; /** Toggles whether or not keys should snap to other keys in the section. */ TSharedPtr< FUICommandInfo > ToggleSnapKeyTimesToKeys; /** Toggles whether or not sections should snap to the selected interval. */ TSharedPtr< FUICommandInfo > ToggleSnapSectionTimesToInterval; /** Toggles whether or not sections should snap to other sections. */ TSharedPtr< FUICommandInfo > ToggleSnapSectionTimesToSections; /** Toggles whether or not snap to key times while scrubbing. */ TSharedPtr< FUICommandInfo > ToggleSnapPlayTimeToKeys; /** Toggles whether or not the play time should snap to the selected interval. */ TSharedPtr< FUICommandInfo > ToggleSnapPlayTimeToInterval; /** Toggles whether or not the play time should snap to the pressed key. */ TSharedPtr< FUICommandInfo > ToggleSnapPlayTimeToPressedKey; /** Toggles whether or not the play time should snap to the dragged key. */ TSharedPtr< FUICommandInfo > ToggleSnapPlayTimeToDraggedKey; /** Toggles whether or not to snap curve values to the interval. */ TSharedPtr< FUICommandInfo > ToggleSnapCurveValueToInterval; /** Finds the viewed sequence asset in the content browser. */ TSharedPtr< FUICommandInfo > FindInContentBrowser; /** Toggles whether to show combined keys at the top node level. */ TSharedPtr< FUICommandInfo > ToggleCombinedKeyframes; /** Toggles whether to show channel colors in the track area. */ TSharedPtr< FUICommandInfo > ToggleChannelColors; /** Toggles whether the label browser is enabled in the level editor. */ TSharedPtr< FUICommandInfo > ToggleLabelBrowser; /** Turns auto scroll on and off. */ TSharedPtr< FUICommandInfo > ToggleAutoScroll; /** Toggles whether or not the curve editor should be shown. */ TSharedPtr< FUICommandInfo > ToggleShowCurveEditor; /** Toggles whether or not the curve editor time range should be linked to the sequencer. */ TSharedPtr< FUICommandInfo > ToggleLinkCurveEditorTimeRange; /** Toggles visualization of pre and post roll */ TSharedPtr< FUICommandInfo > ToggleShowPreAndPostRoll; /** Enable the move tool */ TSharedPtr< FUICommandInfo > MoveTool; /** Enable the marquee selection tool */ TSharedPtr< FUICommandInfo > MarqueeTool; /** Open a panel that enables exporting the sequence to a movie */ TSharedPtr< FUICommandInfo > RenderMovie; /** Create camera and set it as the current camera cut */ TSharedPtr< FUICommandInfo > CreateCamera; /** Paste from the sequencer clipboard history */ TSharedPtr< FUICommandInfo > PasteFromHistory; /** Convert the selected possessed objects to spawnables. These will be spawned and destroyed by sequencer as per object's the spawn track. */ TSharedPtr< FUICommandInfo > ConvertToSpawnable; /** Convert the selected spawnable objects to possessables. The newly created possessables will be created in the current level. */ TSharedPtr< FUICommandInfo > ConvertToPossessable; /** Saves the current state of this object as the default spawnable state. */ TSharedPtr< FUICommandInfo > SaveCurrentSpawnableState; /** Restores all animated state for the current sequence. */ TSharedPtr< FUICommandInfo > RestoreAnimatedState; /** Discard all changes to the current movie scene. */ TSharedPtr< FUICommandInfo > DiscardChanges; /** Attempts to fix broken actor references. */ TSharedPtr< FUICommandInfo > FixActorReferences; /** Rebinds all possessable references with their current bindings. */ TSharedPtr< FUICommandInfo > RebindPossessableReferences; /** Attempts to move all time data for this sequence on to a valid frame */ TSharedPtr< FUICommandInfo > FixFrameTiming; /** Record the selected actors into a sub sequence of the currently active sequence */ TSharedPtr< FUICommandInfo > RecordSelectedActors; /** Imports animation from fbx. */ TSharedPtr< FUICommandInfo > ImportFBX; /** Exports animation to fbx. */ TSharedPtr< FUICommandInfo > ExportFBX; /** Toggle whether we should evaluate sub sequences in isolation */ TSharedPtr< FUICommandInfo > ToggleEvaluateSubSequencesInIsolation; /** * Initialize commands */ virtual void RegisterCommands() override; };
34.417445
143
0.761586
[ "object", "transform" ]
6c4b185d7991d1eb2336b28618f4a0a025566b0f
798
h
C
include/BattleState.h
unbgames/Wenova
4860429d1bdc323b7ab8e7d53876e32de8941f46
[ "MIT" ]
null
null
null
include/BattleState.h
unbgames/Wenova
4860429d1bdc323b7ab8e7d53876e32de8941f46
[ "MIT" ]
3
2017-08-28T23:57:45.000Z
2017-10-08T19:36:41.000Z
include/BattleState.h
joaorobson/Wenova
4860429d1bdc323b7ab8e7d53876e32de8941f46
[ "MIT" ]
1
2019-04-07T20:19:20.000Z
2019-04-07T20:19:20.000Z
#ifndef BATTLESTATE_H #define BATTLESTATE_H #include "State.h" #include "Sprite.h" #include "Text.h" #include "Timer.h" #include "Music.h" #include "Sound.h" #include "Fighter.h" #include "Vector.h" #include "TimeCounter.h" #include "BattleEnd.h" #include <vector> #include <utility> #define N_PLAYERS 4 using std::vector; using std::pair; class BattleState : public State{ private: vector<pair<Sprite, Vector> > backgrounds; Fighter* players[N_PLAYERS]; Music music; Sound sound; void read_level_design(string stage); bool game_over; int alive[5]; TimeCounter *time_counter; BattleEnd *battleEnd; public: BattleState(string stage, vector< pair<string, string> > players_info); ~BattleState(); void update(float delta); void render(); void pause(); void resume(); }; #endif
16.978723
72
0.729323
[ "render", "vector" ]
6c4ef01da87b4563ce6cfbb24102ce5580ed9147
5,430
h
C
mindspore/ccsrc/device/ascend/ascend_stream_assign.h
TommyLike/mindspore
401dabb786a9097d6dd84f391657d266b04e9a37
[ "Apache-2.0" ]
1
2020-05-23T07:08:46.000Z
2020-05-23T07:08:46.000Z
mindspore/ccsrc/device/ascend/ascend_stream_assign.h
liyong126/mindspore
930a1fb0a8fa9432025442c4f4732058bb7af592
[ "Apache-2.0" ]
7
2020-03-30T08:31:56.000Z
2020-04-01T09:54:39.000Z
mindspore/ccsrc/device/ascend/ascend_stream_assign.h
liyong126/mindspore
930a1fb0a8fa9432025442c4f4732058bb7af592
[ "Apache-2.0" ]
1
2020-03-30T17:07:43.000Z
2020-03-30T17:07:43.000Z
/** * Copyright 2019 Huawei Technologies Co., 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. */ #ifndef MINDSPORE_CCSRC_DEVICE_ASCEND_ASCEND_STREAM_ASSIGN_H_ #define MINDSPORE_CCSRC_DEVICE_ASCEND_ASCEND_STREAM_ASSIGN_H_ #include <functional> #include <unordered_map> #include <string> #include <vector> #include <memory> #include <unordered_set> #include "runtime/base.h" #include "runtime/rt_model.h" #include "runtime/stream.h" #include "session/kernel_graph.h" namespace mindspore { namespace device { namespace ascend { using std::map; using std::shared_ptr; using std::unordered_map; using std::unordered_set; using std::vector; class AscendStreamAssign { public: static AscendStreamAssign& GetInstance() { static AscendStreamAssign instance; // Guaranteed to be destroyed. return instance; } AscendStreamAssign(const AscendStreamAssign&) = delete; AscendStreamAssign& operator=(const AscendStreamAssign&) = delete; uint32_t GetTotalStreamNum() const; // new stream policy uint32_t GetTotalCommonStreamNum() const { return total_common_stream_num_; } uint32_t GetTotalIndependStreamNum() const { return total_independ_stream_num_; } uint32_t GetTotalEventNum() const { return total_event_num_; } const uint32_t GetFisrtPhysicId() const { return first_physic_id_; } const uint32_t GetFirstLogicId() const { return first_logic_id_; } void InsertActiveNew(const std::shared_ptr<session::KernelGraph>& graph_ptr); void AssignAllNodesStream(const std::shared_ptr<session::KernelGraph>& graph_ptr); void ResetNew(); void AssignStreamNew(const std::shared_ptr<session::KernelGraph>& graph_ptr); bool IsIndependentNode(const CNodePtr& node_ptr); const std::unordered_map<uint32_t, uint32_t> GetIndependentMap() { return logic_to_independent_map_; } const std::unordered_map<uint32_t, uint32_t> GetPhysicMap() { return logic_to_physic_map_; } std::vector<uint32_t> GetWaitStreams(); std::vector<uint32_t> GetHcomStreams(); private: AscendStreamAssign() = default; ~AscendStreamAssign() = default; CNodePtr CreateSendApplyKernel(const std::shared_ptr<session::KernelGraph>& graph_ptr, uint32_t event_id, uint32_t stream_id); CNodePtr CreateRecvApplyKernel(const std::shared_ptr<session::KernelGraph>& graph_ptr, uint32_t event_id, uint32_t stream_id); vector<CNodePtr>::iterator FindTargetOp(vector<CNodePtr>::iterator begin, vector<CNodePtr>::iterator end, const CNodePtr& node); bool IsHcom(const CNodePtr& apply_kernel); bool IsProcessed(uint32_t logic_id); vector<uint32_t> TransLogicToPhysic(const vector<uint32_t>& logic_ids); void AssignCommonStreamId(const CNodePtr& cur_cnode_ptr, CNodePtr* pre_cnode_ptr, uint32_t* cur_index, uint32_t* cur_stream_id); void RecordIdMap(uint32_t logic_id, uint32_t physic_id); void UpdateStreamActive(const CNodePtr& active_ptr); void UpdateStreamSwitch(const CNodePtr& switch_ptr, const CNodePtr& active_ptr); bool IsTaskSink(); void AssignIndependentStreamId(const CNodePtr& cur_cnode_ptr, uint32_t deal_logic_id); void UpdateStreamId(const std::shared_ptr<session::KernelGraph>& graph_ptr); void PrintGraphExeOrders(const std::shared_ptr<session::KernelGraph>& graph_ptr); void RecordFirstCommonOp(const CNodePtr& cur_cnode_ptr, uint32_t cur_node_logic_id, uint32_t cur_stream_id); uint32_t GetLogicId(const CNodePtr& cur_cnode_ptr); void SetCommonStreamNum(uint32_t cur_stream_id); void FindAllReduceParallel(const std::shared_ptr<session::KernelGraph>& graph_ptr); bool IsProcessedParallelStream(uint32_t stream_id); vector<uint32_t> GetParallelStream(uint32_t cur_stream_id, uint32_t stream_acitve_id); void InsertSendRecvForIndependent(const std::shared_ptr<session::KernelGraph>& graph_ptr); void InsertSendRecvForHcomParallel(const std::shared_ptr<session::KernelGraph>& graph_ptr); uint32_t total_common_stream_num_{0}; uint32_t total_independ_stream_num_{0}; uint32_t total_event_num_{0}; uint32_t first_physic_id_{UINT32_MAX}; uint32_t first_logic_id_{UINT32_MAX}; uint32_t independent_id_{UINT32_MAX}; vector<uint32_t> processed_logic_id_{}; std::unordered_map<uint32_t, uint32_t> logic_to_physic_map_{}; // key:logic id, value: first physic id std::unordered_map<uint32_t, uint32_t> logic_to_independent_map_{}; // key:logic id, value: dependent id std::vector<uint32_t> independent_before_physic_id_{}; // record independent id before first physic id std::vector<std::vector<uint32_t>> inner_parallel_streams_{}; std::vector<uint32_t> processed_parallel_streams_{}; std::vector<uint32_t> hcom_stream_list_{}; // new policy end }; } // namespace ascend } // namespace device } // namespace mindspore #endif // MINDSPORE_CCSRC_DEVICE_ASCEND_ASCEND_STREAM_ASSIGN_H_
44.508197
118
0.769245
[ "vector" ]
6c604a3284970f6c979513b6accdd921685c7ea8
6,479
c
C
src/sundials/sundials_nonlinearsolver.c
xantares/sundials
38aa03b990e616db52acd053730c31fcc3eb91f9
[ "BSD-3-Clause" ]
null
null
null
src/sundials/sundials_nonlinearsolver.c
xantares/sundials
38aa03b990e616db52acd053730c31fcc3eb91f9
[ "BSD-3-Clause" ]
null
null
null
src/sundials/sundials_nonlinearsolver.c
xantares/sundials
38aa03b990e616db52acd053730c31fcc3eb91f9
[ "BSD-3-Clause" ]
null
null
null
/* ----------------------------------------------------------------------------- * Programmer(s): David J. Gardner @ LLNL * ----------------------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2019, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End * ----------------------------------------------------------------------------- * This is the implementation file for a generic SUNNonlinerSolver package. It * contains the implementation of the SUNNonlinearSolver operations listed in * the 'ops' structure in sundials_nonlinearsolver.h * ---------------------------------------------------------------------------*/ #include <stdlib.h> #include <sundials/sundials_nonlinearsolver.h> /* ----------------------------------------------------------------------------- * Create a new empty SUNLinearSolver object * ---------------------------------------------------------------------------*/ SUNNonlinearSolver SUNNonlinSolNewEmpty() { SUNNonlinearSolver NLS; SUNNonlinearSolver_Ops ops; /* create nonlinear solver object */ NLS = NULL; NLS = (SUNNonlinearSolver) malloc(sizeof *NLS); if (NLS == NULL) return(NULL); /* create nonlinear solver ops structure */ ops = NULL; ops = (SUNNonlinearSolver_Ops) malloc(sizeof *ops); if (ops == NULL) { free(NLS); return(NULL); } /* initialize operations to NULL */ ops->gettype = NULL; ops->initialize = NULL; ops->setup = NULL; ops->solve = NULL; ops->free = NULL; ops->setsysfn = NULL; ops->setlsetupfn = NULL; ops->setlsolvefn = NULL; ops->setctestfn = NULL; ops->setmaxiters = NULL; ops->getnumiters = NULL; ops->getcuriter = NULL; ops->getnumconvfails = NULL; /* attach ops and initialize content to NULL */ NLS->ops = ops; NLS->content = NULL; return(NLS); } /* ----------------------------------------------------------------------------- * Free a generic SUNNonlinearSolver (assumes content is already empty) * ---------------------------------------------------------------------------*/ void SUNNonlinSolFreeEmpty(SUNNonlinearSolver NLS) { if (NLS == NULL) return; /* free non-NULL ops structure */ if (NLS->ops) free(NLS->ops); NLS->ops = NULL; /* free overall N_Vector object and return */ free(NLS); return; } /* ----------------------------------------------------------------------------- * core functions * ---------------------------------------------------------------------------*/ SUNNonlinearSolver_Type SUNNonlinSolGetType(SUNNonlinearSolver NLS) { return(NLS->ops->gettype(NLS)); } int SUNNonlinSolInitialize(SUNNonlinearSolver NLS) { if (NLS->ops->initialize) return((int) NLS->ops->initialize(NLS)); else return(SUN_NLS_SUCCESS); } int SUNNonlinSolSetup(SUNNonlinearSolver NLS, N_Vector y, void* mem) { if (NLS->ops->setup) return((int) NLS->ops->setup(NLS, y, mem)); else return(SUN_NLS_SUCCESS); } int SUNNonlinSolSolve(SUNNonlinearSolver NLS, N_Vector y0, N_Vector y, N_Vector w, realtype tol, booleantype callLSetup, void* mem) { return((int) NLS->ops->solve(NLS, y0, y, w, tol, callLSetup, mem)); } int SUNNonlinSolFree(SUNNonlinearSolver NLS) { if (NLS == NULL) return(SUN_NLS_SUCCESS); /* if the free operation exists use it */ if (NLS->ops) if (NLS->ops->free) return(NLS->ops->free(NLS)); /* if we reach this point, either ops == NULL or free == NULL, try to cleanup by freeing the content, ops, and solver */ if (NLS->content) { free(NLS->content); NLS->content = NULL; } if (NLS->ops) { free(NLS->ops); NLS->ops = NULL; } free(NLS); NLS = NULL; return(SUN_NLS_SUCCESS); } /* ----------------------------------------------------------------------------- * set functions * ---------------------------------------------------------------------------*/ /* set the nonlinear system function (required) */ int SUNNonlinSolSetSysFn(SUNNonlinearSolver NLS, SUNNonlinSolSysFn SysFn) { return((int) NLS->ops->setsysfn(NLS, SysFn)); } /* set the linear solver setup function (optional) */ int SUNNonlinSolSetLSetupFn(SUNNonlinearSolver NLS, SUNNonlinSolLSetupFn LSetupFn) { if (NLS->ops->setlsetupfn) return((int) NLS->ops->setlsetupfn(NLS, LSetupFn)); else return(SUN_NLS_SUCCESS); } /* set the linear solver solve function (optional) */ int SUNNonlinSolSetLSolveFn(SUNNonlinearSolver NLS, SUNNonlinSolLSolveFn LSolveFn) { if (NLS->ops->setlsolvefn) return((int) NLS->ops->setlsolvefn(NLS, LSolveFn)); else return(SUN_NLS_SUCCESS); } /* set the convergence test function (optional) */ int SUNNonlinSolSetConvTestFn(SUNNonlinearSolver NLS, SUNNonlinSolConvTestFn CTestFn, void* ctest_data) { if (NLS->ops->setctestfn) return((int) NLS->ops->setctestfn(NLS, CTestFn, ctest_data)); else return(SUN_NLS_SUCCESS); } int SUNNonlinSolSetMaxIters(SUNNonlinearSolver NLS, int maxiters) { if (NLS->ops->setmaxiters) return((int) NLS->ops->setmaxiters(NLS, maxiters)); else return(SUN_NLS_SUCCESS); } /* ----------------------------------------------------------------------------- * get functions * ---------------------------------------------------------------------------*/ /* get the total number on nonlinear iterations (optional) */ int SUNNonlinSolGetNumIters(SUNNonlinearSolver NLS, long int *niters) { if (NLS->ops->getnumiters) { return((int) NLS->ops->getnumiters(NLS, niters)); } else { *niters = 0; return(SUN_NLS_SUCCESS); } } /* get the iteration count for the current nonlinear solve */ int SUNNonlinSolGetCurIter(SUNNonlinearSolver NLS, int *iter) { if (NLS->ops->getcuriter) { return((int) NLS->ops->getcuriter(NLS, iter)); } else { *iter = -1; return(SUN_NLS_SUCCESS); } } /* get the total number on nonlinear solve convergence failures (optional) */ int SUNNonlinSolGetNumConvFails(SUNNonlinearSolver NLS, long int *nconvfails) { if (NLS->ops->getnumconvfails) { return((int) NLS->ops->getnumconvfails(NLS, nconvfails)); } else { *nconvfails = 0; return(SUN_NLS_SUCCESS); } }
30.134884
82
0.559191
[ "object" ]
6c60bf509573b276fa565cf78db56bd4fa140654
7,311
c
C
nvxs/CLAPACK/TESTING/EIG/dlafts.c
makevoid/animeface-2009
d4824f49282547456bc71e4735f46c4eea1926f3
[ "MIT" ]
281
2017-02-18T04:28:11.000Z
2022-02-28T11:37:34.000Z
nvxs/CLAPACK/TESTING/EIG/dlafts.c
makevoid/animeface-2009
d4824f49282547456bc71e4735f46c4eea1926f3
[ "MIT" ]
8
2017-02-22T09:27:44.000Z
2021-10-03T07:52:10.000Z
nvxs/CLAPACK/TESTING/EIG/dlafts.c
makevoid/animeface-2009
d4824f49282547456bc71e4735f46c4eea1926f3
[ "MIT" ]
39
2017-03-11T17:42:54.000Z
2022-01-19T11:46:03.000Z
#include "f2c.h" #include "blaswrap.h" /* Table of constant values */ static integer c__1 = 1; static integer c__4 = 4; /* Subroutine */ int dlafts_(char *type__, integer *m, integer *n, integer * imat, integer *ntests, doublereal *result, integer *iseed, doublereal *thresh, integer *iounit, integer *ie) { /* Format strings */ static char fmt_9999[] = "(\002 Matrix order=\002,i5,\002, type=\002,i2" ",\002, seed=\002,4(i4,\002,\002),\002 result \002,i3,\002 is\002" ",0p,f8.2)"; static char fmt_9998[] = "(\002 Matrix order=\002,i5,\002, type=\002,i2" ",\002, seed=\002,4(i4,\002,\002),\002 result \002,i3,\002 is\002" ",1p,d10.3)"; static char fmt_9997[] = "(1x,i5,\002 x\002,i5,\002 matrix, type=\002," "i2,\002, s\002,\002eed=\002,3(i4,\002,\002),i4,\002: result \002" ",i3,\002 is\002,0p,f8.2)"; static char fmt_9996[] = "(1x,i5,\002 x\002,i5,\002 matrix, type=\002," "i2,\002, s\002,\002eed=\002,3(i4,\002,\002),i4,\002: result \002" ",i3,\002 is\002,1p,d10.3)"; /* System generated locals */ integer i__1; /* Builtin functions */ integer s_wsfe(cilist *), do_fio(integer *, char *, ftnlen), e_wsfe(void); /* Local variables */ integer k; extern /* Subroutine */ int dlahd2_(integer *, char *); /* Fortran I/O blocks */ static cilist io___2 = { 0, 0, 0, fmt_9999, 0 }; static cilist io___3 = { 0, 0, 0, fmt_9998, 0 }; static cilist io___4 = { 0, 0, 0, fmt_9997, 0 }; static cilist io___5 = { 0, 0, 0, fmt_9996, 0 }; /* -- LAPACK auxiliary test routine (version 3.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ /* November 2006 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLAFTS tests the result vector against the threshold value to */ /* see which tests for this matrix type failed to pass the threshold. */ /* Output is to the file given by unit IOUNIT. */ /* Arguments */ /* ========= */ /* TYPE - CHARACTER*3 */ /* On entry, TYPE specifies the matrix type to be used in the */ /* printed messages. */ /* Not modified. */ /* N - INTEGER */ /* On entry, N specifies the order of the test matrix. */ /* Not modified. */ /* IMAT - INTEGER */ /* On entry, IMAT specifies the type of the test matrix. */ /* A listing of the different types is printed by DLAHD2 */ /* to the output file if a test fails to pass the threshold. */ /* Not modified. */ /* NTESTS - INTEGER */ /* On entry, NTESTS is the number of tests performed on the */ /* subroutines in the path given by TYPE. */ /* Not modified. */ /* RESULT - DOUBLE PRECISION array of dimension( NTESTS ) */ /* On entry, RESULT contains the test ratios from the tests */ /* performed in the calling program. */ /* Not modified. */ /* ISEED - INTEGER array of dimension( 4 ) */ /* Contains the random seed that generated the matrix used */ /* for the tests whose ratios are in RESULT. */ /* Not modified. */ /* THRESH - DOUBLE PRECISION */ /* On entry, THRESH specifies the acceptable threshold of the */ /* test ratios. If RESULT( K ) > THRESH, then the K-th test */ /* did not pass the threshold and a message will be printed. */ /* Not modified. */ /* IOUNIT - INTEGER */ /* On entry, IOUNIT specifies the unit number of the file */ /* to which the messages are printed. */ /* Not modified. */ /* IE - INTEGER */ /* On entry, IE contains the number of tests which have */ /* failed to pass the threshold so far. */ /* Updated on exit if any of the ratios in RESULT also fail. */ /* ===================================================================== */ /* .. Local Scalars .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Executable Statements .. */ /* Parameter adjustments */ --iseed; --result; /* Function Body */ if (*m == *n) { /* Output for square matrices: */ i__1 = *ntests; for (k = 1; k <= i__1; ++k) { if (result[k] >= *thresh) { /* If this is the first test to fail, call DLAHD2 */ /* to print a header to the data file. */ if (*ie == 0) { dlahd2_(iounit, type__); } ++(*ie); /* ** WRITE( IOUNIT, 15 )' Matrix of order', N, */ /* ** $ ', type ', IMAT, */ /* ** $ ', test ', K, */ /* ** $ ', ratio = ', RESULT( K ) */ /* ** 15 FORMAT( A16, I5, 2( A8, I2 ), A11, G13.6 ) */ if (result[k] < 1e4) { io___2.ciunit = *iounit; s_wsfe(&io___2); do_fio(&c__1, (char *)&(*n), (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&(*imat), (ftnlen)sizeof(integer)); do_fio(&c__4, (char *)&iseed[1], (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&k, (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&result[k], (ftnlen)sizeof( doublereal)); e_wsfe(); } else { io___3.ciunit = *iounit; s_wsfe(&io___3); do_fio(&c__1, (char *)&(*n), (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&(*imat), (ftnlen)sizeof(integer)); do_fio(&c__4, (char *)&iseed[1], (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&k, (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&result[k], (ftnlen)sizeof( doublereal)); e_wsfe(); } } /* L10: */ } } else { /* Output for rectangular matrices */ i__1 = *ntests; for (k = 1; k <= i__1; ++k) { if (result[k] >= *thresh) { /* If this is the first test to fail, call DLAHD2 */ /* to print a header to the data file. */ if (*ie == 0) { dlahd2_(iounit, type__); } ++(*ie); /* ** WRITE( IOUNIT, FMT = 9997 )' Matrix of size', M, ' x', */ /* ** $ N, ', type ', IMAT, ', test ', K, ', ratio = ', */ /* ** $ RESULT( K ) */ /* ** 9997 FORMAT( A10, I5, A2, I5, A7, I2, A8, I2, A11, G13.6 ) */ if (result[k] < 1e4) { io___4.ciunit = *iounit; s_wsfe(&io___4); do_fio(&c__1, (char *)&(*m), (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&(*n), (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&(*imat), (ftnlen)sizeof(integer)); do_fio(&c__4, (char *)&iseed[1], (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&k, (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&result[k], (ftnlen)sizeof( doublereal)); e_wsfe(); } else { io___5.ciunit = *iounit; s_wsfe(&io___5); do_fio(&c__1, (char *)&(*m), (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&(*n), (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&(*imat), (ftnlen)sizeof(integer)); do_fio(&c__4, (char *)&iseed[1], (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&k, (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&result[k], (ftnlen)sizeof( doublereal)); e_wsfe(); } } /* L20: */ } } return 0; /* End of DLAFTS */ } /* dlafts_ */
33.383562
78
0.524278
[ "vector" ]
6c62654e7b854e37259dc0f4c7b3b27f9e775913
32,564
h
C
include/QtGIS/qtgis.h
Vladimir-Lin/QtGIS
995c414618745e0e1e6eead86463ecc820357585
[ "MIT" ]
null
null
null
include/QtGIS/qtgis.h
Vladimir-Lin/QtGIS
995c414618745e0e1e6eead86463ecc820357585
[ "MIT" ]
null
null
null
include/QtGIS/qtgis.h
Vladimir-Lin/QtGIS
995c414618745e0e1e6eead86463ecc820357585
[ "MIT" ]
null
null
null
/**************************************************************************** * * * Copyright (C) 2015 Neutrino International Inc. * * * * Author : Brian Lin <lin.foxman@gmail.com>, Skype: wolfram_lin * * * ****************************************************************************/ #ifndef QT_GIS_H #define QT_GIS_H #include <QtManagers> QT_BEGIN_NAMESPACE #ifndef QT_STATIC # if defined(QT_BUILD_QTGIS_LIB) # define Q_GIS_EXPORT Q_DECL_EXPORT # else # define Q_GIS_EXPORT Q_DECL_IMPORT # endif #else # define Q_GIS_EXPORT #endif namespace N { class Q_GIS_EXPORT ContinentLists ; class Q_GIS_EXPORT AreaLists ; namespace Map { class Q_GIS_EXPORT Adapter ; class Q_GIS_EXPORT Geometry ; class Q_GIS_EXPORT Point ; class Q_GIS_EXPORT CirclePoint ; class Q_GIS_EXPORT ImagePoint ; class Q_GIS_EXPORT FixedImageOverlay ; class Q_GIS_EXPORT Curve ; class Q_GIS_EXPORT LineString ; class Q_GIS_EXPORT Layer ; class Q_GIS_EXPORT GeometryLayer ; class Q_GIS_EXPORT MapLayer ; class Q_GIS_EXPORT LayerManager ; class Q_GIS_EXPORT ImageManager ; class Q_GIS_EXPORT MapNetwork ; class Q_GIS_EXPORT EmptyAdapter ; class Q_GIS_EXPORT TileAdapter ; class Q_GIS_EXPORT WmsAdapter ; class Q_GIS_EXPORT GoogleAdapter ; class Q_GIS_EXPORT GoogleSatelliteAdapter ; class Q_GIS_EXPORT OsmAdapter ; class Q_GIS_EXPORT YahooAdapter ; class Q_GIS_EXPORT OpenAerialAdapter ; class Q_GIS_EXPORT MapControl ; } /***************************************************************************** * * * Geographic widgets * * * *****************************************************************************/ class Q_GIS_EXPORT ContinentLists : public TreeDock { Q_OBJECT public: explicit ContinentLists (StandardConstructor) ; virtual ~ContinentLists (void) ; protected: QPoint dragPoint ; virtual void Configure (void) ; virtual bool FocusIn (void) ; private: public slots: virtual void List (void) ; virtual void Copy (void) ; protected slots: bool Menu (QPoint pos) ; private slots: signals: }; class Q_GIS_EXPORT AreaLists : public TreeDock { Q_OBJECT public: explicit AreaLists (StandardConstructor) ; virtual ~AreaLists (void); protected: virtual void Configure (void) ; virtual bool FocusIn (void) ; private: public slots: virtual bool startup (void) ; virtual void Insert (void) ; virtual void Delete (void) ; protected slots: virtual bool Menu (QPoint pos) ; virtual void doubleClicked (QTreeWidgetItem * item,int column) ; virtual void nameFinished (void) ; virtual void englishFinished (void) ; private slots: signals: }; namespace Map { class Q_GIS_EXPORT Adapter : public QObject { friend class Layer; Q_OBJECT public: Adapter (const QString & host , const QString & serverPath , int tilesize , int minZoom = 0 , int maxZoom = 0 ) ; virtual ~Adapter (void) ; QString host (void) const ; int tilesize (void) const ; int minZoom (void) const ; int maxZoom (void) const ; int currentZoom (void) const ; virtual int adaptedZoom (void)const ; virtual QPoint coordinateToDisplay (const QPointF & coordinate) const = 0 ; virtual QPointF displayToCoordinate (const QPoint & point ) const = 0 ; protected: virtual void zoom_in (void) = 0; virtual void zoom_out (void) = 0; virtual bool isValid (int x,int y,int z) const = 0 ; virtual QString query (int x,int y,int z) const = 0 ; QSize size ; QString myhost ; QString serverPath ; int mytilesize ; int min_zoom ; int max_zoom ; int current_zoom ; int param1 ; int param2 ; int param3 ; int param4 ; int param5 ; int param6 ; QString sub1 ; QString sub2 ; QString sub3 ; QString sub4 ; QString sub5 ; QString sub6 ; int order[3][2] ; int middle_x ; int middle_y ; qreal numberOfTiles ; QLocale loc ; }; class Q_GIS_EXPORT Layer : public QObject { Q_OBJECT public: friend class LayerManager; enum LayerType { MapLayer , /*!< uses the MapAdapter to display maps, only gets refreshed when a new offscreen image is needed */ GeometryLayer /*!< gets refreshed everytime when a geometry changes */ } ; Layer (QString layername , Adapter * mapadapter , enum LayerType layertype , bool takeevents = true ) ; Layer (const Layer & old) ; virtual ~Layer (void); QString layername (void) const ; const Adapter * mapadapter (void) const ; void addGeometry (Geometry * geometry) ; void removeGeometry (Geometry * geometry) ; void clearGeometries (void) ; bool isVisible (void) const ; Layer::LayerType layertype (void) const ; void setMapAdapter (Adapter * mapadapter) ; Layer & operator = (const Layer & rhs) ; protected: void moveWidgets (const QPoint mapmiddle_px) const ; void drawYourImage (QPainter* painter,const QPoint mapmiddle_px) const ; void drawYourGeometries (QPainter* painter,const QPoint mapmiddle_px,QRect viewport) const ; void setSize (QSize size) ; QRect offscreenViewport (void) const ; bool takesMouseEvents (void) const ; void mouseEvent (const QMouseEvent *,const QPoint mapmiddle_px) ; void zoomIn (void) const ; void zoomOut (void) const ; void _draw (QPainter * painter,const QPoint mapmiddle_px) const ; private: bool visible ; QString mylayername ; LayerType mylayertype ; QSize size ; QPoint screenmiddle ; QList<Geometry *> geometries ; Adapter * mapAdapter ; bool takeevents ; mutable QRect myoffscreenViewport ; public slots: void setVisible (bool visible) ; protected slots: private slots: signals: void geometryClicked (Geometry * geometry,QPoint point) ; void updateRequest (QRectF rect) ; void updateRequest (void) ; }; class Q_GIS_EXPORT GeometryLayer : public Layer { Q_OBJECT public: GeometryLayer (QString layername , Adapter * mapadapter , bool takeevents = true ) ; virtual ~GeometryLayer (void) ; protected: private: }; class Q_GIS_EXPORT MapLayer : public Layer { Q_OBJECT public: MapLayer (QString layername , Adapter * mapadapter , bool takeevents = true ) ; virtual ~MapLayer (void) ; protected: private: }; class Q_GIS_EXPORT Geometry : public QObject { Q_OBJECT public: friend class LineString ; explicit Geometry (QString name = QString()) ; virtual ~Geometry (void); QString GeometryType; bool Equals (Geometry * geom) ; QString toString (void) ; QString name (void) const ; Geometry * parentGeometry (void) const ; bool isVisible (void) const ; void setName (QString name) ; QPen * pen (void) const ; virtual QRectF boundingBox (void) = 0 ; virtual QList<Point *> points (void) = 0 ; virtual bool Touches (Point * geom , const Adapter * mapadapter ) = 0 ; virtual void draw (QPainter * painter , const Adapter * mapadapter , const QRect & viewport , const QPoint offset ) = 0 ; virtual bool hasPoints (void) const ; virtual bool hasClickedPoints (void) const ; virtual void setPen (QPen * pen) ; virtual QList<Geometry *> clickedPoints (void) ; protected: QPen * mypen ; bool visible ; QString myname ; void setParentGeometry (Geometry* geom) ; private: Geometry * myparentGeometry ; Geometry(const Geometry & old); Geometry & operator = (const Geometry & rhs) ; public slots: virtual void setVisible(bool visible); protected slots: private slots: signals: void updateRequest (Geometry * geom); void updateRequest (QRectF rect); void geometryClicked (Geometry * geometry,QPoint point) ; void positionChanged (Geometry * geom); }; class Q_GIS_EXPORT Point : public Geometry { Q_OBJECT public: friend class Layer ; friend class LineString ; //! sets where the point should be aligned enum Alignment { TopLeft , /*!< Align on TopLeft*/ TopRight , /*!< Align on TopRight*/ BottomLeft , /*!< Align on BottomLeft*/ BottomRight , /*!< Align on BottomRight*/ Middle /*!< Align on Middle*/ } ; Point (void) ; explicit Point (const Point & ) ; Point (qreal x,qreal y,QString name = QString(),enum Alignment alignment=Middle) ; Point (qreal x,qreal y,QWidget * widget,QString name = QString(),enum Alignment alignment = Middle) ; Point (qreal x,qreal y,QPixmap * pixmap,QString name = QString(),enum Alignment alignment = Middle) ; virtual ~Point (void) ; virtual QRectF boundingBox (void) ; qreal longitude (void) const ; qreal latitude (void) const ; QPointF coordinate (void) const ; virtual QList<Point *> points (void) ; QWidget * widget (void) ; QPixmap * pixmap (void) ; void setBaselevel (int zoomlevel) ; void setMinsize (QSize minsize) ; void setMaxsize (QSize maxsize) ; Point::Alignment alignment (void) const ; protected: qreal X ; qreal Y ; QSize size ; QWidget * mywidget ; QPixmap * mypixmap ; Alignment myalignment ; int homelevel ; QSize displaysize ; QSize minsize ; QSize maxsize ; void drawWidget (const Adapter * mapadapter , const QPoint offset ) ; virtual void draw (QPainter * painter , const Adapter * mapadapter , const QRect & viewport , const QPoint offset ) ; QPoint alignedPoint (const QPoint point ) const ; virtual bool Touches (Point * geom,const Adapter * mapadapter) ; public slots: void setCoordinate (QPointF point) ; virtual void setVisible (bool visible) ; protected slots: private slots: signals: }; class Q_GIS_EXPORT CirclePoint : public Point { Q_OBJECT public: CirclePoint (qreal x , qreal y , QString name = QString ( ) , Alignment alignment = Middle , QPen * pen = 0 ) ; CirclePoint (qreal x , qreal y , int radius = 10 , QString name = QString ( ) , Alignment alignment = Middle , QPen * pen = 0 ) ; virtual ~CirclePoint (void) ; virtual void setPen (QPen * pen) ; }; class Q_GIS_EXPORT ImagePoint : public Point { Q_OBJECT public: ImagePoint (qreal x , qreal y , QString filename , QString name = QString() , Alignment alignment = Middle ) ; ImagePoint (qreal x , qreal y , QPixmap * pixmap , QString name = QString() , Alignment alignment = Middle ) ; virtual ~ImagePoint(void) ; }; class Q_GIS_EXPORT FixedImageOverlay : public ImagePoint { Q_OBJECT public: FixedImageOverlay (qreal x_upperleft , qreal y_upperleft , qreal x_lowerright , qreal y_lowerright , QString filename , QString name = QString() ) ; FixedImageOverlay (qreal x_upperleft , qreal y_upperleft , qreal x_lowerright , qreal y_lowerright , QPixmap * pixmap , QString name = QString() ) ; virtual ~FixedImageOverlay (void) ; virtual void draw (QPainter * painter , const Adapter * mapadapter , const QRect & viewport , const QPoint offset ) ; protected: qreal x_lowerright ; qreal y_lowerright ; private: }; class Q_GIS_EXPORT Curve : public Geometry { Q_OBJECT public: double Length ; Curve (QString name = QString()) ; virtual ~Curve (void) ; protected: private: }; class Q_GIS_EXPORT LineString : public Curve { Q_OBJECT public: LineString (void) ; LineString (const QList<Point *> points , QString name = QString() , QPen * pen = 0 ) ; virtual ~LineString (void) ; QList<Point *> points (void) ; void addPoint (Point * point) ; void setPoints (QList<Point *> points) ; int numberOfPoints (void) const ; virtual QRectF boundingBox (void) ; virtual bool hasPoints (void) const ; virtual bool hasClickedPoints (void) const ; virtual QList<Geometry *> clickedPoints (void) ; protected: virtual bool Touches (Geometry * geom,const Adapter * mapadapter) ; virtual bool Touches (Point * geom,const Adapter * mapadapter) ; virtual void draw (QPainter * painter , const Adapter * mapadapter , const QRect & screensize , const QPoint offset ) ; private: QList < Point * > vertices ; QList < Geometry * > touchedPoints ; }; class Q_GIS_EXPORT ImageManager : public QObject { Q_OBJECT public: ImageManager (QObject * parent = 0) ; ImageManager (const ImageManager & im ) ; virtual ~ImageManager (void) ; static ImageManager * instance (void) ; ImageManager & operator = (const ImageManager & im) ; MapNetwork * Loader (void) ; QPixmap getImage (const QString & host ,const QString & path) ; QPixmap prefetchImage (const QString & host ,const QString & path) ; void receivedImage (const QPixmap pixmap,const QString & url ) ; void loadingQueueEmpty (void) ; void abortLoading (void) ; void setProxy (QString host, int port) ; void setCacheDir (const QDir & path) ; protected: QPixmap emptyPixmap ; MapNetwork * net ; QStringList prefetch ; QDir cacheDir ; bool doPersistentCaching ; static ImageManager * m_Instance ; QString absolutePath (QString tileName) ; bool saveTile (QString tileName,QPixmap tileData) ; bool loadTile (QString tileName,QPixmap & tileData) ; bool tileExist (QString tileName) ; private: signals: void imageReceived (void) ; void loadingFinished (void) ; }; class Q_GIS_EXPORT MapNetwork : public QObject , public Thread { Q_OBJECT public: MapNetwork (ImageManager * image) ; MapNetwork (const MapNetwork & old ) ; virtual ~MapNetwork (void) ; MapNetwork & operator = (const MapNetwork & rhs) ; void loadImage (const QString & host,const QString & url) ; bool imageIsLoading (QString url) ; bool isBusy (void) ; bool viaProxy (void) ; protected: ImageManager * image ; QMap<int,QUrl> loadingMap ; CUIDs loadingIDs ; QMutex vectorMutex ; bool hasProxy ; QString ProxyHost ; int ProxyPort ; int dlTime ; virtual void run (int Type,ThreadData * data) ; void pendingDownload (void) ; void Download (QUrl & url) ; private: public slots: virtual void abortLoading (void) ; virtual void setProxy (QString host, int port); virtual void disableProxy (void) ; protected slots: private slots: void relayStart (void) ; void relayStop (void) ; signals: void sendStart (void) ; void sendStop (void) ; void startLoading (void) ; void stopLoading (void) ; }; class Q_GIS_EXPORT EmptyAdapter : public Adapter { Q_OBJECT public: EmptyAdapter (int tileSize = 256 , int minZoom = 0 , int maxZoom = 17 ) ; virtual ~EmptyAdapter (void) ; virtual QPoint coordinateToDisplay (const QPointF &) const ; virtual QPointF displayToCoordinate (const QPoint &) const ; qreal PI; protected: qreal rad_deg (qreal x) const; qreal deg_rad (qreal x) const; virtual bool isValid (int x,int y,int z) const ; virtual void zoom_in (void) ; virtual void zoom_out (void) ; virtual QString query (int x,int y,int z) const ; virtual int tilesonzoomlevel (int zoomlevel) const ; virtual int xoffset (int x) const ; virtual int yoffset (int y) const ; private: }; class Q_GIS_EXPORT TileAdapter : public Adapter { Q_OBJECT public: TileAdapter (const QString & host , const QString & serverPath , int tilesize , int minZoom = 0 , int maxZoom = 17 ) ; virtual ~TileAdapter (void) ; virtual QPoint coordinateToDisplay (const QPointF &) const ; virtual QPointF displayToCoordinate (const QPoint &) const ; qreal PI; protected: qreal rad_deg (qreal x) const ; qreal deg_rad (qreal x) const ; virtual bool isValid (int x,int y,int z) const ; virtual void zoom_in (void) ; virtual void zoom_out (void) ; virtual QString query (int x,int y,int z) const ; virtual int tilesonzoomlevel (int zoomlevel) const ; virtual int xoffset (int x) const ; virtual int yoffset (int y) const ; }; class Q_GIS_EXPORT WmsAdapter : public Adapter { public: WmsAdapter (QString host , QString serverPath , int tilesize = 256 ) ; virtual ~WmsAdapter (void) ; virtual QPoint coordinateToDisplay (const QPointF &) const ; virtual QPointF displayToCoordinate (const QPoint &) const ; protected: virtual void zoom_in (void) ; virtual void zoom_out (void) ; virtual QString query (int x,int y,int z) const ; virtual bool isValid (int x,int y,int z) const ; private: virtual QString getQ (qreal ux,qreal uy,qreal ox,qreal oy) const ; qreal coord_per_x_tile ; qreal coord_per_y_tile ; }; class Q_GIS_EXPORT GoogleAdapter : public TileAdapter { Q_OBJECT public: GoogleAdapter(void) ; virtual ~GoogleAdapter(void) ; protected: private: }; class Q_GIS_EXPORT GoogleSatelliteAdapter : public TileAdapter { Q_OBJECT public: GoogleSatelliteAdapter (void) ; virtual ~GoogleSatelliteAdapter (void) ; virtual QPoint coordinateToDisplay (const QPointF &) const ; virtual QPointF displayToCoordinate (const QPoint &) const ; QString getHost (void) const ; protected: virtual void zoom_in (void) ; virtual void zoom_out (void) ; virtual QString query (int x,int y,int z) const ; virtual bool isValid (int x,int y,int z) const ; private: virtual QString getQ (qreal longitude, qreal latitude, int zoom) const ; qreal getMercatorLatitude (qreal YCoord) const ; qreal getMercatorYCoord (qreal lati ) const ; qreal coord_per_x_tile ; qreal coord_per_y_tile ; int srvNum ; }; class Q_GIS_EXPORT OsmAdapter : public TileAdapter { Q_OBJECT public: OsmAdapter (void) ; virtual ~OsmAdapter (void) ; }; class Q_GIS_EXPORT YahooAdapter : public TileAdapter { Q_OBJECT public: YahooAdapter (void) ; YahooAdapter (QString host,QString url) ; virtual ~YahooAdapter (void) ; bool isValid (int x,int y,int z) const ; protected: virtual int tilesonzoomlevel (int zoomlevel) const ; virtual int yoffset (int y) const ; }; class Q_GIS_EXPORT OpenAerialAdapter : public TileAdapter { Q_OBJECT public: OpenAerialAdapter (void) ; virtual ~OpenAerialAdapter (void) ; }; class Q_GIS_EXPORT LayerManager : public QObject { Q_OBJECT public: LayerManager (MapControl * control,QSize size) ; LayerManager (const LayerManager & old) ; virtual ~LayerManager (void) ; LayerManager & operator = (const LayerManager & rhs) ; QPointF currentCoordinate (void) const ; QPixmap getImage (void) const ; Layer * layer (void) const ; Layer * layer (const QString & ) const ; QStringList layers (void) const ; void addLayer (Layer * layer) ; void setView (const QPointF & coordinate) ; void setView (const QList<QPointF> coordinates) ; void setViewAndZoomIn (const QList<QPointF> coordinates) ; void zoomIn (void) ; void zoomOut (void) ; void setZoom (int zoomlevel) ; int currentZoom (void) const ; QRectF getViewport (void) const ; void scrollView (const QPoint & offset) ; void mouseEvent (const QMouseEvent * evnt) ; QPoint getMapmiddle_px (void) const ; void forceRedraw (void) ; void removeZoomImage (void) ; void drawGeoms (QPainter * painter); void drawImage (QPainter * painter); protected: void newOffscreenImage (bool clearImage = true,bool showZoomImage = true) ; inline bool checkOffscreen (void) const ; inline bool containsAll (QList<QPointF> coordinates) const ; inline void moveWidgets (void) ; inline void setMiddle (QList<QPointF> coordinates) ; MapControl * mapcontrol ; QPoint screenmiddle ; // middle of the screen QPoint scroll ; // scrollvalue of the offscreen image QPoint zoomImageScroll ; // scrollvalue of the zoom image QSize size ; // widget size QSize offSize ; // size of the offscreen image QPixmap composedOffscreenImage ; QPixmap composedOffscreenImage2 ; QPixmap zoomImage ; QList<Layer *> mylayers ; QPoint mapmiddle_px ; // projection-display coordinates QPointF mapmiddle ; // world coordinate QPoint whilenewscroll ; private: public slots: void updateRequest (QRectF rect) ; void updateRequest (void) ; void resize (QSize newSize) ; void takeLayer (QString layer) ; protected slots: private slots: signals: }; class Q_GIS_EXPORT MapControl : public Widget { Q_OBJECT public: enum MouseMode { Panning , /*!< The map is moved */ Dragging , /*!< A rectangular can be drawn */ None , /*!< Mouse move events have no efect to the map */ } ; explicit MapControl (StandardConstructor) ; MapControl (QSize size,MouseMode mousemode = Panning) ; MapControl (const MapControl & old) ; virtual ~MapControl (void) ; virtual QSize sizeHint (void) const ; void addSource (QString name) ; void addLayer (Layer * layer) ; Layer * layer (const QString & layername) const ; QStringList layers (void) const ; int numberOfLayers (void) const ; QPointF currentCoordinate (void) const ; int currentZoom (void) const ; void setView (const QPointF & coordinate ) const ; void setView (const QList<QPointF> coordinates ) const ; void setView (const Point * point ) const ; void setViewAndZoomIn (const QList<QPointF> coordinates ) const ; void followGeometry (const Geometry * geometry ) const ; void stopFollowing (Geometry * geometry ) ; void moveTo (QPointF coordinate ) ; void setMouseMode (MouseMode mousemode ) ; MapControl::MouseMode mouseMode (void) ; void enablePersistentCache (const QDir & path= QDir ( QDir::homePath() + QString("/QMapControl.cache") ) ) ; void setProxy (QString host,int port) ; void showScale (bool show) ; virtual bool isBusy (void) ; protected: virtual void Configure (void) ; virtual bool FocusIn (void) ; virtual void paintEvent (QPaintEvent * evnt) ; virtual void contextMenuEvent (QContextMenuEvent * evnt) ; virtual void resizeEvent (QResizeEvent * evnt) ; virtual void focusInEvent (QFocusEvent * evnt) ; virtual void focusOutEvent (QFocusEvent * evnt) ; virtual void mousePressEvent (QMouseEvent * evnt) ; virtual void mouseReleaseEvent (QMouseEvent * evnt) ; virtual void mouseMoveEvent (QMouseEvent * evnt) ; private: LayerManager * layermanager ; QPoint screen_middle ; // middle of the widget (half size) QPoint pre_click_px ; // used for scrolling (MouseMode Panning) QPoint current_mouse_pos ; // used for scrolling and dragging (MouseMode Panning/Dragging) QSize size ; // size of the widget bool mousepressed ; MouseMode mymousemode ; bool scaleVisible ; bool m_loadingFlag ; QMutex moveMutex ; // used for method moveTo() QPointF target ; // used for method moveTo() int steps ; // used for method moveTo() QDateTime lastResize ; bool resizeAction ; QString proxyHost ; int proxyPort ; QPointF clickToWorldCoordinate (QPoint click) ; MapControl & operator= (const MapControl & rhs) ; void drawMeasurement (QPainter & painter) ; QString TwoDigits (int v) ; QString DegreeToString (double v) ; QString PositionToString (QPointF p) ; public slots: virtual bool Relocation (void) ; virtual void Export (void) ; void zoomIn (void) ; void zoomOut (void) ; void setZoom (int zoomlevel) ; void scrollLeft (int pixel = 10) ; void scrollRight (int pixel = 10) ; void scrollUp (int pixel = 10) ; void scrollDown (int pixel = 10) ; void scroll (const QPoint scroll) ; void updateRequest (QRect rect) ; void updateRequestNew (void) ; void resize (const QSize newSize) ; protected slots: virtual bool Menu (QPoint pos) ; void tick (void) ; void loadingFinished (void) ; void positionChanged (Geometry * geom) ; void LoadingStart (void) ; void LoadingStop (void) ; private slots: signals: void mouseEventCoordinate (const QMouseEvent * evnt , const QPointF coordinate) ; void boxDragged (const QRectF) ; void geometryClicked (Geometry * geometry , QPoint coord_px) ; void viewChanged (const QPointF & coordinate , int zoom ) ; }; } } QT_END_NAMESPACE #endif
30.837121
123
0.50519
[ "geometry" ]
6c64734da22bc3257c286adc9cb30eaaccdecb6c
3,761
h
C
core/proteinstructure/multiclustering_options.h
tecdatalab/legacy
9b5286d3375fff691a80ceb44172549e9a6bdee5
[ "Apache-2.0" ]
null
null
null
core/proteinstructure/multiclustering_options.h
tecdatalab/legacy
9b5286d3375fff691a80ceb44172549e9a6bdee5
[ "Apache-2.0" ]
null
null
null
core/proteinstructure/multiclustering_options.h
tecdatalab/legacy
9b5286d3375fff691a80ceb44172549e9a6bdee5
[ "Apache-2.0" ]
null
null
null
#ifndef _MULTICLUSTERING_OPTIONS_H_ #define _MULTICLUSTERING_OPTIONS_H_ #include <getopt.h> #include <string> #include <cstdlib> #include <vector> #include <iostream> using namespace std; #define CUTOFF_OPTION "cutoff" #define CUTOFF_CHAR 'c' #define PRINT_SIZES_OPTION "printsizes" #define PRINT_SIZES_CHAR 'p' #define INPUT_OPTION "input" #define INPUT_CHAR 'i' #define DIRECTORY_CHAR 'd' #define DIRECTORY_DEFAULT "" #define OUTPUT_CHAR 'o' // d is the input directory, where the pdb and prediction files are located #define MULTICLUSTERING_SHORT_OPTIONS "d:o:" static struct option multiclustering_long_options[] = { {INPUT_OPTION, required_argument, 0, INPUT_CHAR}, {CUTOFF_OPTION, required_argument, 0, CUTOFF_CHAR}, {PRINT_SIZES_OPTION, required_argument, 0, PRINT_SIZES_CHAR}, {0,0,0,0} }; // This class parses the command line arguments supplied to the multiple docking clustering program class multiclustering_options { public: // Only constructor in this class. It uses the input arguments in order to call getopt_long // to help the parsing process. After the instance is created, the methods provided by this class // will tell the caller if the process was successful and what is the value of the different configuration // parameters used multiclustering_options(int argc, char** argv) { input = ""; // this is the only required argument directory = DIRECTORY_DEFAULT; sizes_file = ""; // default value that should be replaced later on cutoff = -1; // so far we haven't encountered errors parse_error = false; bool options_left = true; while(options_left) { int option_index, c; // c represents the character associated with an option c = getopt_long(argc, argv, MULTICLUSTERING_SHORT_OPTIONS, multiclustering_long_options, &option_index); if(c == -1) { options_left = false; } else { // determine what type of option we got switch(c) { case INPUT_CHAR: input = optarg; break; case DIRECTORY_CHAR: directory = optarg; break; case CUTOFF_CHAR: cutoff = atof(optarg); break; case PRINT_SIZES_CHAR: sizes_file = optarg; break; case OUTPUT_CHAR: output_file = optarg; break; case '?': //option not recognized (an error is automatically printed) default: options_left = false; parse_error = true; break; } } } } // the parse was successful if the errors flag is false and if all required arguments were supplied bool parse_successful() { return !parse_error && !input.empty() && !output_file.empty() && cutoff != -1; } // returns the input ga file provided string get_input_file() { return input; } // returns the name of the input directory provided or its default value, if it wasn't provided string get_input_directory() { return directory; } /* If specified, it returns the name of the file where the cluster sizes will be output */ string get_sizes_file() { return sizes_file; } /* * Retrieve the cutoff (in angstroms) that determines if two elements should be clustered * because of their proximity */ double get_cutoff() { return cutoff; } /* * Return the name of the output file that will be used */ string get_output_file() { return output_file; } private: // These variables hold the parameters that come directly from the command line further processing is done by the methods string directory; string input; string sizes_file; string output_file; double cutoff; // set to false in case that unrecognized options or errors are found by getopt_long bool parse_error; }; #endif
25.585034
123
0.698219
[ "vector" ]
6c6c9ed5eb57de0b18f2ad6fcca6aaa2ae595d2c
7,819
h
C
src/publishers/DreamHostPublisher.h
daq-tools/EnviroDIY-ModularSensors
64bdb75cdc2920880db6bcd452c61d0584ccde38
[ "BSD-3-Clause" ]
58
2017-06-22T18:28:16.000Z
2022-03-20T17:48:27.000Z
src/publishers/DreamHostPublisher.h
daq-tools/EnviroDIY-ModularSensors
64bdb75cdc2920880db6bcd452c61d0584ccde38
[ "BSD-3-Clause" ]
293
2017-02-24T16:49:35.000Z
2022-03-31T17:09:32.000Z
src/publishers/DreamHostPublisher.h
daq-tools/EnviroDIY-ModularSensors
64bdb75cdc2920880db6bcd452c61d0584ccde38
[ "BSD-3-Clause" ]
36
2017-06-22T18:28:17.000Z
2021-12-09T22:47:04.000Z
/** * @file DreamHostPublisher.h * @copyright 2020 Stroud Water Research Center * Part of the EnviroDIY ModularSensors library for Arduino * @author Sara Geleskie Damiano <sdamiano@stroudcenter.org> * * @brief Contains the DreamHostPublisher subclass of dataPublisher for * publishing data to the Stroud Center's now-deprecated DreamHost based live * sensor data system. */ // Header Guards #ifndef SRC_PUBLISHERS_DREAMHOSTPUBLISHER_H_ #define SRC_PUBLISHERS_DREAMHOSTPUBLISHER_H_ // Debugging Statement // #define MS_DREAMHOSTPUBLISHER_DEBUG #ifdef MS_DREAMHOSTPUBLISHER_DEBUG #define MS_DEBUGGING_STD "DreamHostPublisher" #endif // Included Dependencies #include "ModSensorDebugger.h" #undef MS_DEBUGGING_STD #include "dataPublisherBase.h" // ============================================================================ // Functions for the SWRC Sensors DreamHost data receivers. // ============================================================================ /** * @brief The DreamHostPublisher subclass of dataPublisher is for publishing * data to the Stroud Center's now-deprecated DreamHost based live sensor data * system. * * @ingroup the_publishers */ class DreamHostPublisher : public dataPublisher { public: // Constructors /** * @brief Construct a new DreamHost Publisher object with no members set. */ DreamHostPublisher(); /** * @brief Construct a new DreamHost Publisher object * * @note If a client is never specified, the publisher will attempt to * create and use a client on a LoggerModem instance tied to the attached * logger. * * @param baseLogger The logger supplying the data to be published * @param sendEveryX Currently unimplemented, intended for future use to * enable caching and bulk publishing * @param sendOffset Currently unimplemented, intended for future use to * enable publishing data at a time slightly delayed from when it is * collected * * @note It is possible (though very unlikey) that using this constructor * could cause errors if the compiler attempts to initialize the publisher * instance before the logger instance. If you suspect you are seeing that * issue, use the null constructor and a populated begin(...) within your * set-up function. */ explicit DreamHostPublisher(Logger& baseLogger, uint8_t sendEveryX = 1, uint8_t sendOffset = 0); /** * @brief Construct a new DreamHost Publisher object * * @param baseLogger The logger supplying the data to be published * @param inClient An Arduino client instance to use to print data to. * Allows the use of any type of client and multiple clients tied to a * single TinyGSM modem instance * @param sendEveryX Currently unimplemented, intended for future use to * enable caching and bulk publishing * @param sendOffset Currently unimplemented, intended for future use to * enable publishing data at a time slightly delayed from when it is * collected * * @note It is possible (though very unlikey) that using this constructor * could cause errors if the compiler attempts to initialize the publisher * instance before the logger instance. If you suspect you are seeing that * issue, use the null constructor and a populated begin(...) within your * set-up function. */ DreamHostPublisher(Logger& baseLogger, Client* inClient, uint8_t sendEveryX = 1, uint8_t sendOffset = 0); /** * @brief Construct a new DreamHost Publisher object * * @param baseLogger The logger supplying the data to be published * @param dhUrl The URL for sending data to DreamHost * @param sendEveryX Currently unimplemented, intended for future use to * enable caching and bulk publishing * @param sendOffset Currently unimplemented, intended for future use to * enable publishing data at a time slightly delayed from when it is * collected */ DreamHostPublisher(Logger& baseLogger, const char* dhUrl, uint8_t sendEveryX = 1, uint8_t sendOffset = 0); /** * @brief Construct a new DreamHost Publisher object * * @param baseLogger The logger supplying the data to be published * @param inClient An Arduino client instance to use to print data to. * Allows the use of any type of client and multiple clients tied to a * single TinyGSM modem instance * @param dhUrl The URL for sending data to DreamHost * @param sendEveryX Currently unimplemented, intended for future use to * enable caching and bulk publishing * @param sendOffset Currently unimplemented, intended for future use to * enable publishing data at a time slightly delayed from when it is * collected */ DreamHostPublisher(Logger& baseLogger, Client* inClient, const char* dhUrl, uint8_t sendEveryX = 1, uint8_t sendOffset = 0); /** * @brief Destroy the DreamHost Publisher object */ virtual ~DreamHostPublisher(); // Returns the data destination String getEndpoint(void) override { return String(dreamhostHost); } // Functions for private SWRC server /** * @brief Set the url of the DreamHost data receiver * * @param dhUrl The URL for sending data to DreamHost */ void setDreamHostPortalRX(const char* dhUrl); /** * @brief This creates all of the URL parameter tags and values and writes * the result to an Arduino stream. * * HTML headers are not included. * * @param stream The Arduino stream to write out the URL and parameters to. */ void printSensorDataDreamHost(Stream* stream); /** * @brief This prints a fully structured GET request for DreamHost to the * specified stream. * * This includes the HTML headers. * * @param stream The Arduino stream to write out the URL and parameters to. */ void printDreamHostRequest(Stream* stream); // A way to begin with everything already set /** * @copydoc dataPublisher::begin(Logger& baseLogger, Client* inClient) * @param dhUrl The URL for sending data to DreamHost */ void begin(Logger& baseLogger, Client* inClient, const char* dhUrl); /** * @copydoc dataPublisher::begin(Logger& baseLogger) * @param dhUrl The URL for sending data to DreamHost */ void begin(Logger& baseLogger, const char* dhUrl); // int16_t postDataDreamHost(void); /** * @brief Utilizes an attached modem to make a TCP connection to the * DreamHost URL and then stream out a get request over that connection. * * This depends on an internet connection already having been made and a * client being available. * * @param outClient An Arduino client instance to use to print data to. * Allows the use of any type of client and multiple clients tied to a * single TinyGSM modem instance * * @return **int16_t** The http status code of the response. */ int16_t publishData(Client* outClient) override; protected: // portions of the GET request /** * @anchor dreamhost_protected_vars * @name Portions of the GET request to DreamHost * * @{ */ static const char* dreamhostHost; ///< The host name static const int dreamhostPort; ///< The host port static const char* loggerTag; ///< The Stroud logger number static const char* timestampTagDH; ///< The timestamp /**@}*/ private: const char* _DreamHostPortalRX; bool _dualPost = true; }; #endif // SRC_PUBLISHERS_DREAMHOSTPUBLISHER_H_
38.141463
79
0.672848
[ "object" ]
6c78fd213ddb75f82c2e712a0370f9772108c7d3
1,181
h
C
framework/io_core/excludeFromBuild/tools/GLTFsaver.h
Hurleyworks/Ketone
97c0c730a6e3155154a0ccb87a535e109dfa3c7d
[ "Apache-2.0" ]
1
2021-04-01T01:16:33.000Z
2021-04-01T01:16:33.000Z
framework/io_core/excludeFromBuild/tools/GLTFsaver.h
Hurleyworks/Ketone
97c0c730a6e3155154a0ccb87a535e109dfa3c7d
[ "Apache-2.0" ]
null
null
null
framework/io_core/excludeFromBuild/tools/GLTFsaver.h
Hurleyworks/Ketone
97c0c730a6e3155154a0ccb87a535e109dfa3c7d
[ "Apache-2.0" ]
null
null
null
// This header file was auto-generated by ClassMate++ // Created: 3 May 2020 4:34:01 pm // Copyright (c) 2020, HurleyWorks #pragma once using sabi::MeshBuffersHandle; using sabi::VMapDB; using Accessors = std::pair<std::string, std::string>; using Microsoft::glTF::BufferBuilder; using Microsoft::glTF::Document; using Microsoft::glTF::ResourceWriter; using Microsoft::glTF::Asset; class GLTFsaver { public: GLTFsaver(); ~GLTFsaver(); void serializeMesh (const std::filesystem::path& outputFolder, MeshBuffersHandle& meshToSerialize, const std::string& outputName); private: MeshBuffersHandle mesh = nullptr; Document document; std::unique_ptr<ResourceWriter> resourceWriter; std::unique_ptr<BufferBuilder> bufferBuilder = nullptr; void createBuffer (const std::string& bufferID); std::string createMesh(); std::string createMaterial (sabi::Material& mat); std::string createIndices (const MatrixXu& F, MatrixXf& V, MatrixXf& N); std::string createVertices (const MatrixXf& V); std::string createVertexNormals (const MatrixXf& N); std::string createTextureCoords_0 (const VMapDB& vmaps); }; // end class GLTFsaver
29.525
134
0.731583
[ "mesh" ]
6c794519b16040018f2d5913d141339dde8a4ccb
5,985
h
C
src/ballistica/graphics/render_pass.h
Benefit-Zebra/ballistica
eb85df82cff22038e74a2d93abdcbe9cd755d782
[ "MIT" ]
317
2020-04-04T00:33:10.000Z
2022-03-28T01:07:09.000Z
src/ballistica/graphics/render_pass.h
Alshahriah/ballistica
326f6677a0118667e93ce9034849622ebef706fa
[ "MIT" ]
315
2020-04-04T22:33:10.000Z
2022-03-31T22:50:02.000Z
src/ballistica/graphics/render_pass.h
Alshahriah/ballistica
326f6677a0118667e93ce9034849622ebef706fa
[ "MIT" ]
97
2020-04-04T01:32:17.000Z
2022-03-16T19:02:59.000Z
// Released under the MIT License. See LICENSE for details. #ifndef BALLISTICA_GRAPHICS_RENDER_PASS_H_ #define BALLISTICA_GRAPHICS_RENDER_PASS_H_ #include <memory> #include <vector> #include "ballistica/math/matrix44f.h" namespace ballistica { // A drawing context for one pass. This can be a render to the screen, a shadow // pass, a window, etc. class RenderPass { public: enum class ReflectionSubPass { kRegular, kMirrored }; enum class Type { kLightShadowPass, kLightPass, kBeautyPass, kBeautyPassBG, kBlitPass, // Standard 2d overlay stuff. May be drawn in 2d or on a plane in 3d // space (in vr). In VR, each of these elements are drawn individually // and can thus have their own depth. also in VR this overlay repositions // itself per level; use kOverlayFixedPass for items that shouldn't. // this overlay may be obscured by UI. Use OVERLAY_FRONT_PASS if you need // things to show up in front of UI. kOverlayPass, // Just like kOverlayPass but guaranteed to draw in front of UI. kOverlayFrontPass, // Actually drawn in regular 3d space - for life bars, names, etc that // need to overlay regular 3d stuff but exist in the world. kOverlay3DPass, // Only used in VR - overlay stuff drawn into a flat 2d texture so that // scissoring/etc works (the UI uses this). kOverlayFlatPass, /// Only used in VR - stuff that needs to cover absolutely everything /// else (like the 3d wipe fade). kVRCoverPass, // Only used in VR - overlay elements that should always be fixed in space. kOverlayFixedPass }; RenderPass(Type type_in, FrameDef* frame_def); virtual ~RenderPass(); auto type() const -> Type { return type_; } // The physical size of the drawing surface. auto physical_width() const -> float { return physical_width_; } auto physical_height() const -> float { return physical_height_; } // The virtual size of the drawing surface. // This may or may not have anything to do with the physical size // (for instance the overlay pass in VR has its own bounds which // is completely independent of the physical surface it gets drawn into). auto virtual_width() const -> float { return virtual_width_; } auto virtual_height() const -> float { return virtual_height_; } // Should objects be rendered 'underground' in this pass? auto floor_reflection() const -> bool { return floor_reflection_; } void set_floor_reflection(bool val) { floor_reflection_ = val; } auto GetPhysicalAspectRatio() const -> float { return physical_width() / physical_height(); } void SetCamera(const Vector3f& pos, const Vector3f& target, const Vector3f& up, float near_clip, float far_clip, float fov_x, // Set to -1 for auto. float fov_y, bool use_fov_tangents, float fov_tan_l, float fov_tan_r, float fov_tan_b, float fov_tan_t, const std::vector<Vector3f>& area_of_interest_points); auto frame_def() const -> FrameDef* { return frame_def_; } void Render(RenderTarget* t, bool transparent); auto tex_project_matrix() const -> const Matrix44f& { return tex_project_matrix_; } auto projection_matrix() const -> const Matrix44f& { return projection_matrix_; } auto model_view_matrix() const -> const Matrix44f& { return model_view_matrix_; } auto model_view_projection_matrix() const -> const Matrix44f& { return model_view_projection_matrix_; } auto HasDrawCommands() const -> bool; void Finalize(); void Reset(); // Whether this pass draws stuff from the per-shader command lists auto UsesWorldLists() const -> bool { switch (type()) { case Type::kBeautyPass: case Type::kBeautyPassBG: return true; case Type::kOverlayPass: case Type::kOverlayFrontPass: case Type::kOverlay3DPass: case Type::kVRCoverPass: case Type::kOverlayFlatPass: case Type::kOverlayFixedPass: case Type::kBlitPass: case Type::kLightPass: case Type::kLightShadowPass: return false; default: throw Exception(); } } auto commands_flat() const -> RenderCommandBuffer* { return commands_flat_.get(); } auto commands_flat_transparent() const -> RenderCommandBuffer* { return commands_flat_transparent_.get(); } auto GetCommands(ShadingType type) const -> RenderCommandBuffer* { return commands_[static_cast<int>(type)].get(); } auto cam_area_of_interest_points() const -> const std::vector<Vector3f>& { return cam_area_of_interest_points_; } private: void SetFrustum(float near_val, float far_val); // Our pass holds sets of draw-commands bucketed by section and // component-type. std::unique_ptr<RenderCommandBuffer> commands_[static_cast<int>(ShadingType::kCount)]; std::unique_ptr<RenderCommandBuffer> commands_flat_; std::unique_ptr<RenderCommandBuffer> commands_flat_transparent_; Vector3f cam_pos_{0.0f, 0.0f, 0.0f}; Vector3f cam_target_{0.0f, 0.0f, 0.0f}; Vector3f cam_up_{0.0f, 0.0f, 0.0f}; float cam_near_clip_{}; float cam_far_clip_{}; float cam_fov_x_{}; float cam_fov_y_{}; // We can now alternately supply left, right, top, bottom frustum tangents. bool cam_use_fov_tangents_{}; float cam_fov_l_tan_{1.0f}; float cam_fov_r_tan_{1.0f}; float cam_fov_t_tan_{1.0f}; float cam_fov_b_tan_{1.0f}; std::vector<Vector3f> cam_area_of_interest_points_; Type type_{}; // For lights/shadows. Matrix44f tex_project_matrix_{kMatrix44fIdentity}; Matrix44f projection_matrix_{kMatrix44fIdentity}; Matrix44f model_view_matrix_{kMatrix44fIdentity}; Matrix44f model_view_projection_matrix_{kMatrix44fIdentity}; bool floor_reflection_{}; FrameDef* frame_def_{}; float physical_width_{}; float physical_height_{}; float virtual_width_{}; float virtual_height_{}; }; } // namespace ballistica #endif // BALLISTICA_GRAPHICS_RENDER_PASS_H_
35.625
79
0.713617
[ "render", "vector", "3d" ]
6c7f98d6b6836eed419e275c92d123e2a0b0453f
3,317
h
C
src/OrbitBase/include/OrbitBase/ThreadPool.h
trobol/orbit
62a206c34b1308e0d56b91f695f39ba8879b713c
[ "BSD-2-Clause" ]
1
2021-04-15T23:59:38.000Z
2021-04-15T23:59:38.000Z
src/OrbitBase/include/OrbitBase/ThreadPool.h
idfoxdale/orbit
c6525a14e65b1de57028eaca0ab633265aedf348
[ "BSD-2-Clause" ]
null
null
null
src/OrbitBase/include/OrbitBase/ThreadPool.h
idfoxdale/orbit
c6525a14e65b1de57028eaca0ab633265aedf348
[ "BSD-2-Clause" ]
1
2020-07-14T13:16:03.000Z
2020-07-14T13:16:03.000Z
// Copyright (c) 2020 The Orbit 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 ORBIT_BASE_THREAD_POOL_H_ #define ORBIT_BASE_THREAD_POOL_H_ #include <stddef.h> #include <memory> #include <utility> #include "OrbitBase/Action.h" #include "OrbitBase/Future.h" #include "OrbitBase/Promise.h" #include "absl/time/time.h" // This class implements a thread pool. ThreadPool allows to execute // actions in another thread without the need to manage creation and destruction // of that thread. // // Usage example: // // /* Schedule an action on the thread-pool */ // thread_poool->Schedule(CreateAction([data]{ // DoSomethingWith(data); // })); // // /* Shutdown thread-pool, blocks until all currently executed actions are // complete and stops all worker threads */ // // thread_pool->Shutdown(); // thread_pool->Wait(); // class ThreadPool { public: ThreadPool() = default; virtual ~ThreadPool() = default; virtual void Schedule(std::unique_ptr<Action> action) = 0; template <typename F> auto Schedule(F&& functor) -> orbit_base::Future<std::decay_t<decltype(functor())>> { using ReturnType = std::decay_t<decltype(functor())>; orbit_base::Promise<ReturnType> promise; orbit_base::Future<ReturnType> future = promise.GetFuture(); if constexpr (std::is_same_v<ReturnType, void>) { auto function_wrapper = [functor = std::forward<F>(functor), promise = std::move(promise)]() mutable { functor(); promise.MarkFinished(); }; Schedule(CreateAction(std::move(function_wrapper))); } else { auto function_wrapper = [functor = std::forward<F>(functor), promise = std::move(promise)]() mutable { promise.SetResult(functor()); }; Schedule(CreateAction(std::move(function_wrapper))); } return future; } // Initiates shutdown, any Schedule after this call will fail. virtual void Shutdown() = 0; // Wait until all tasks are complete. This should be called // before the object is destroyed, usually after calling // Shutdown(). virtual void Wait() = 0; virtual void EnableAutoProfiling(bool value) = 0; void ShutdownAndWait() { Shutdown(); Wait(); } virtual size_t GetPoolSize() = 0; virtual size_t GetNumberOfBusyThreads() = 0; // Create ThreadPool with specified minimum and maximum number of worker // threads. // // Whenever an action is Scheduled the thread pool puts it in an internal // queue. Worker threads pick actions from the queue and execute them. // If at the time of scheduling new action there are no idle worker threads, // the thread pool creates a new worker thread if current number of worker // threads is less than maximum pool size. // // If queue is empty thread_pool reduces number of worker threads // until they hit thread_pool_min_size. thread_ttl specifies the duration // for the such a thread to remain in idle state before it finishes the // execution. static std::unique_ptr<ThreadPool> Create(size_t thread_pool_min_size, size_t thread_pool_max_size, absl::Duration thread_ttl); }; #endif // ORBIT_BASE_THREAD_POOL_H_
32.203883
100
0.686464
[ "object" ]
6c83d896f2ad8f2f5c232c5fc876f39d7c63f587
4,709
h
C
aws-cpp-sdk-iot-data/include/aws/iot-data/model/ListNamedShadowsForThingRequest.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-iot-data/include/aws/iot-data/model/ListNamedShadowsForThingRequest.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-iot-data/include/aws/iot-data/model/ListNamedShadowsForThingRequest.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/iot-data/IoTDataPlane_EXPORTS.h> #include <aws/iot-data/IoTDataPlaneRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Http { class URI; } //namespace Http namespace IoTDataPlane { namespace Model { /** */ class AWS_IOTDATAPLANE_API ListNamedShadowsForThingRequest : public IoTDataPlaneRequest { public: ListNamedShadowsForThingRequest(); // 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 "ListNamedShadowsForThing"; } Aws::String SerializePayload() const override; void AddQueryStringParameters(Aws::Http::URI& uri) const override; /** * <p>The name of the thing.</p> */ inline const Aws::String& GetThingName() const{ return m_thingName; } /** * <p>The name of the thing.</p> */ inline bool ThingNameHasBeenSet() const { return m_thingNameHasBeenSet; } /** * <p>The name of the thing.</p> */ inline void SetThingName(const Aws::String& value) { m_thingNameHasBeenSet = true; m_thingName = value; } /** * <p>The name of the thing.</p> */ inline void SetThingName(Aws::String&& value) { m_thingNameHasBeenSet = true; m_thingName = std::move(value); } /** * <p>The name of the thing.</p> */ inline void SetThingName(const char* value) { m_thingNameHasBeenSet = true; m_thingName.assign(value); } /** * <p>The name of the thing.</p> */ inline ListNamedShadowsForThingRequest& WithThingName(const Aws::String& value) { SetThingName(value); return *this;} /** * <p>The name of the thing.</p> */ inline ListNamedShadowsForThingRequest& WithThingName(Aws::String&& value) { SetThingName(std::move(value)); return *this;} /** * <p>The name of the thing.</p> */ inline ListNamedShadowsForThingRequest& WithThingName(const char* value) { SetThingName(value); return *this;} /** * <p>The token to retrieve the next set of results.</p> */ inline const Aws::String& GetNextToken() const{ return m_nextToken; } /** * <p>The token to retrieve the next set of results.</p> */ inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; } /** * <p>The token to retrieve the next set of results.</p> */ inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; } /** * <p>The token to retrieve the next set of results.</p> */ inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); } /** * <p>The token to retrieve the next set of results.</p> */ inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); } /** * <p>The token to retrieve the next set of results.</p> */ inline ListNamedShadowsForThingRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;} /** * <p>The token to retrieve the next set of results.</p> */ inline ListNamedShadowsForThingRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;} /** * <p>The token to retrieve the next set of results.</p> */ inline ListNamedShadowsForThingRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;} /** * <p>The result page size.</p> */ inline int GetPageSize() const{ return m_pageSize; } /** * <p>The result page size.</p> */ inline bool PageSizeHasBeenSet() const { return m_pageSizeHasBeenSet; } /** * <p>The result page size.</p> */ inline void SetPageSize(int value) { m_pageSizeHasBeenSet = true; m_pageSize = value; } /** * <p>The result page size.</p> */ inline ListNamedShadowsForThingRequest& WithPageSize(int value) { SetPageSize(value); return *this;} private: Aws::String m_thingName; bool m_thingNameHasBeenSet; Aws::String m_nextToken; bool m_nextTokenHasBeenSet; int m_pageSize; bool m_pageSizeHasBeenSet; }; } // namespace Model } // namespace IoTDataPlane } // namespace Aws
29.803797
127
0.662986
[ "model" ]
6c83e8f2e2b0d02d4490b58c0a89d50161521a52
7,188
h
C
lib/Runtime/Language/JavascriptExceptionOperators.h
leeswimming/ChakraCore
026774f9bfc672194eafe6e27eece87c5cabe109
[ "MIT" ]
null
null
null
lib/Runtime/Language/JavascriptExceptionOperators.h
leeswimming/ChakraCore
026774f9bfc672194eafe6e27eece87c5cabe109
[ "MIT" ]
null
null
null
lib/Runtime/Language/JavascriptExceptionOperators.h
leeswimming/ChakraCore
026774f9bfc672194eafe6e27eece87c5cabe109
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once #ifdef _M_AMD64 extern "C" void *amd64_CallWithFakeFrame(void *target, void *frame, size_t spillSize, size_t argsSize, void *arg0 = nullptr) throw(...); #elif defined(_M_ARM) extern "C" void *arm_CallEhFrame(void *target, void *framePtr, void *localsPtr, size_t argsSize) throw(...); extern "C" void *arm_CallCatch(void *target, void *framePtr, void *localsPtr, size_t argsSize, void *catchObj) throw(...); #elif defined(_M_ARM64) extern "C" void *arm64_CallEhFrame(void *target, void *framePtr, void *localsPtr, size_t argsSize) throw(...); extern "C" void *arm64_CallCatch(void *target, void *framePtr, void *localsPtr, size_t argsSize, void *catchObj) throw(...); #endif namespace Js { class JavascriptExceptionContext; class JavascriptExceptionOperators /* All static */ { public: static const uint64 DefaultStackTraceLimit = 10; static const uint64 MaxStackTraceLimit = _UI64_MAX; // AutoCatchHandlerExists tracks where an exception will be caught and not propagated out. // It should be included wherever an exception is caught and swallowed. class AutoCatchHandlerExists { private: bool m_previousCatchHandlerExists; bool m_previousCatchHandlerToUserCodeStatus; ThreadContext* m_threadContext; void FetchNonUserCodeStatus(ScriptContext *scriptContext); public: AutoCatchHandlerExists(ScriptContext* scriptContext); ~AutoCatchHandlerExists(); }; static void __declspec(noreturn) OP_Throw(Var object, ScriptContext* scriptContext); static void __declspec(noreturn) Throw(Var object, ScriptContext* scriptContext); static void __declspec(noreturn) ThrowExceptionObject(Js::JavascriptExceptionObject* exceptionObject, ScriptContext* scriptContext, bool considerPassingToDebugger = false, PVOID returnAddress = NULL, bool resetStack = false); static void __declspec(noreturn) RethrowExceptionObject(Js::JavascriptExceptionObject* exceptionObject, ScriptContext* scriptContext, bool considerPassingToDebugger = false); static void __declspec(noreturn) DoThrow(JavascriptExceptionObject* exceptionObject, ScriptContext* scriptContext); static void __declspec(noreturn) DoThrowCheckClone(JavascriptExceptionObject* exceptionObject, ScriptContext* scriptContext); #ifdef _M_X64 static void *OP_TryCatch(void *try_, void *catch_, void *frame, size_t spillSize, size_t argsSize, int hasBailedOutOffset, ScriptContext *scriptContext); static void *OP_TryFinally(void *try_, void *finally_, void *frame, size_t spillSize, size_t argsSize, ScriptContext *scriptContext); #elif defined(_M_ARM32_OR_ARM64) static void* OP_TryCatch(void* continuationAddr, void* handlerAddr, void* framePtr, void *localsPtr, size_t argsSize, int hasBailedOutOffset, ScriptContext* scriptContext); static void* OP_TryFinally(void* continuationAddr, void* handlerAddr, void* framePtr, void *localsPtr, size_t argsSize, ScriptContext* scriptContext); #else static void* OP_TryCatch(void* continuationAddr, void* handlerAddr, void* framePtr, int hasBailedOutOffset, ScriptContext* scriptContext); static void* OP_TryFinally(void* continuationAddr, void* handlerAddr, void* framePtr, ScriptContext* scriptContext); #endif #if defined(DBG) && defined(_M_IX86) static void DbgCheckEHChain(); #endif static JavascriptExceptionObject* GetOutOfMemoryExceptionObject(ScriptContext* scriptContext); static Var OP_RuntimeTypeError(MessageId messageId, ScriptContext* scriptContext); static Var OP_RuntimeRangeError(MessageId messageId, ScriptContext* scriptContext); static Var OP_RuntimeReferenceError(MessageId messageId, ScriptContext* scriptContext); static Var OP_WebAssemblyRuntimeError(MessageId messageId, ScriptContext* scriptContext); static void __declspec(noreturn) ThrowOutOfMemory(ScriptContext* scriptContext); static void __declspec(noreturn) ThrowStackOverflow(ScriptContext* scriptContext, PVOID returnAddress); static uint64 GetStackTraceLimit(Var thrownObject, ScriptContext* scriptContext); static Var ThrowTypeErrorRestrictedPropertyAccessor(RecyclableObject* function, CallInfo callInfo, ...); static Var StackTraceAccessor(RecyclableObject* function, CallInfo callInfo, ...); static void WalkStackForExceptionContext(ScriptContext& scriptContext, JavascriptExceptionContext& exceptionContext, Var thrownObject, uint64 stackCrawlLimit, PVOID returnAddress, bool isThrownException = true, bool resetSatck = false); static void AddStackTraceToObject(Var obj, JavascriptExceptionContext::StackTrace* stackTrace, ScriptContext& scriptContext, bool isThrownException = true, bool resetSatck = false); static uint64 StackCrawlLimitOnThrow(Var thrownObject, ScriptContext& scriptContext); class EntryInfo { public: static FunctionInfo StackTraceAccessor; // For strict mode static FunctionInfo ThrowTypeErrorRestrictedPropertyAccessor; }; private: static JavascriptFunction * WalkStackForExceptionContextInternal(ScriptContext& scriptContext, JavascriptExceptionContext& exceptionContext, Var thrownObject, uint32& callerByteCodeOffset, uint64 stackCrawlLimit, PVOID returnAddress, bool isThrownException, bool resetStack = false); static void ThrowExceptionObjectInternal(Js::JavascriptExceptionObject * exceptionObject, ScriptContext* scriptContext, bool fillExceptionContext, bool considerPassingToDebugger, PVOID returnAddress, bool resetStack); static BOOL GetCaller(JavascriptStackWalker& walker, JavascriptFunction*& jsFunc); static void DumpStackTrace(JavascriptExceptionContext& exceptionContext, bool isThrownException = true); static JavascriptExceptionContext::StackTrace* TrimStackTraceForThrownObject(JavascriptExceptionContext::StackTrace* stackTraceOriginal, Var thrownObject, ScriptContext& scriptContext); static void AppendExternalFrameToStackTrace(CompoundString* bs, LPCWSTR functionName, LPCWSTR fileName, ULONG lineNumber, LONG characterPosition); static void AppendLibraryFrameToStackTrace(CompoundString* bs, LPCWSTR functionName); static bool IsErrorInstance(Var thrownObject); static bool CrawlStackForWER(Js::ScriptContext& scriptContext); static void DispatchExceptionToDebugger(Js::JavascriptExceptionObject * exceptionObject, ScriptContext* scriptContext); }; } // namespace Js
65.944954
244
0.726767
[ "object" ]
6c8713306a2641affa04d4fb06080e24a08d172b
82,181
c
C
keyhunt.c
Axeleron/keyhunt
a75a7bbe23e3dd281628508dc7710ad39fc72665
[ "MIT" ]
3
2021-09-22T16:22:52.000Z
2022-02-26T10:39:26.000Z
keyhunt.c
Axeleron/keyhunt
a75a7bbe23e3dd281628508dc7710ad39fc72665
[ "MIT" ]
null
null
null
keyhunt.c
Axeleron/keyhunt
a75a7bbe23e3dd281628508dc7710ad39fc72665
[ "MIT" ]
1
2021-09-06T14:16:00.000Z
2021-09-06T14:16:00.000Z
/* Develop by Luis Alberto email: alberto.bsd@gmail.com */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <math.h> #include <time.h> #include <vector> #include <inttypes.h> #include "base58/libbase58.h" #include "rmd160/rmd160.h" #include "sha256/sha256.h" #include "bloom/bloom.h" #include "sha3/sha3.h" #include "secp256k1/SECP256k1.h" #include "secp256k1/Point.h" #include "secp256k1/Int.h" #include "secp256k1/IntGroup.h" #include "secp256k1/Random.h" #include "util.h" #ifdef WIN32 #include <windows.h> #endif #define CRYPTO_NONE 0 #define CRYPTO_BTC 1 #define CRYPTO_ETH 2 #define CRYPTO_ALL 3 #define MODE_XPOINT 0 #define MODE_ADDRESS 1 #define MODE_BSGS 2 #define MODE_RMD160 3 #define MODE_PUB2RMD 4 #define SEARCH_UNCOMPRESS 0 #define SEARCH_COMPRESS 1 #define SEARCH_BOTH 2 struct bsgs_xvalue { uint8_t value[6]; uint64_t index; }; struct address_value { uint8_t value[20]; }; struct tothread { int nt; //Number thread char *rs; //range start char *rpt; //rng per thread }; struct bPload { uint32_t threadid; uint64_t from; uint64_t to; uint64_t counter; }; struct __attribute__((__packed__)) publickey { uint8_t parity; union { uint8_t data8[32]; uint32_t data32[8]; uint64_t data64[4]; } X; }; const char *version = "0.1.20210412 secp256k1"; const char *bloomnames[256] = {"bloom_0","bloom_1","bloom_2","bloom_3","bloom_4","bloom_5","bloom_6","bloom_7","bloom_8","bloom_9","bloom_10","bloom_11","bloom_12","bloom_13","bloom_14","bloom_15","bloom_16","bloom_17","bloom_18","bloom_19","bloom_20","bloom_21","bloom_22","bloom_23","bloom_24","bloom_25","bloom_26","bloom_27","bloom_28","bloom_29","bloom_30","bloom_31","bloom_32","bloom_33","bloom_34","bloom_35","bloom_36","bloom_37","bloom_38","bloom_39","bloom_40","bloom_41","bloom_42","bloom_43","bloom_44","bloom_45","bloom_46","bloom_47","bloom_48","bloom_49","bloom_50","bloom_51","bloom_52","bloom_53","bloom_54","bloom_55","bloom_56","bloom_57","bloom_58","bloom_59","bloom_60","bloom_61","bloom_62","bloom_63","bloom_64","bloom_65","bloom_66","bloom_67","bloom_68","bloom_69","bloom_70","bloom_71","bloom_72","bloom_73","bloom_74","bloom_75","bloom_76","bloom_77","bloom_78","bloom_79","bloom_80","bloom_81","bloom_82","bloom_83","bloom_84","bloom_85","bloom_86","bloom_87","bloom_88","bloom_89","bloom_90","bloom_91","bloom_92","bloom_93","bloom_94","bloom_95","bloom_96","bloom_97","bloom_98","bloom_99","bloom_100","bloom_101","bloom_102","bloom_103","bloom_104","bloom_105","bloom_106","bloom_107","bloom_108","bloom_109","bloom_110","bloom_111","bloom_112","bloom_113","bloom_114","bloom_115","bloom_116","bloom_117","bloom_118","bloom_119","bloom_120","bloom_121","bloom_122","bloom_123","bloom_124","bloom_125","bloom_126","bloom_127","bloom_128","bloom_129","bloom_130","bloom_131","bloom_132","bloom_133","bloom_134","bloom_135","bloom_136","bloom_137","bloom_138","bloom_139","bloom_140","bloom_141","bloom_142","bloom_143","bloom_144","bloom_145","bloom_146","bloom_147","bloom_148","bloom_149","bloom_150","bloom_151","bloom_152","bloom_153","bloom_154","bloom_155","bloom_156","bloom_157","bloom_158","bloom_159","bloom_160","bloom_161","bloom_162","bloom_163","bloom_164","bloom_165","bloom_166","bloom_167","bloom_168","bloom_169","bloom_170","bloom_171","bloom_172","bloom_173","bloom_174","bloom_175","bloom_176","bloom_177","bloom_178","bloom_179","bloom_180","bloom_181","bloom_182","bloom_183","bloom_184","bloom_185","bloom_186","bloom_187","bloom_188","bloom_189","bloom_190","bloom_191","bloom_192","bloom_193","bloom_194","bloom_195","bloom_196","bloom_197","bloom_198","bloom_199","bloom_200","bloom_201","bloom_202","bloom_203","bloom_204","bloom_205","bloom_206","bloom_207","bloom_208","bloom_209","bloom_210","bloom_211","bloom_212","bloom_213","bloom_214","bloom_215","bloom_216","bloom_217","bloom_218","bloom_219","bloom_220","bloom_221","bloom_222","bloom_223","bloom_224","bloom_225","bloom_226","bloom_227","bloom_228","bloom_229","bloom_230","bloom_231","bloom_232","bloom_233","bloom_234","bloom_235","bloom_236","bloom_237","bloom_238","bloom_239","bloom_240","bloom_241","bloom_242","bloom_243","bloom_244","bloom_245","bloom_246","bloom_247","bloom_248","bloom_249","bloom_250","bloom_251","bloom_252","bloom_253","bloom_254","bloom_255"}; std::vector<Point> Gn; Point _2Gn; std::vector<Point> GSn; Point _2GSn; std::vector<Point> GS2n; Point _2GS2n; int CPU_GRP_SIZE = 1024; void init_generator(); int searchbinary(struct address_value *buffer,char *data,int64_t _N); void sleep_ms(int milliseconds); void _sort(struct address_value *arr,int64_t N); void _insertionsort(struct address_value *arr, int64_t n); void _introsort(struct address_value *arr,uint32_t depthLimit, int64_t n); void _swap(struct address_value *a,struct address_value *b); int64_t _partition(struct address_value *arr, int64_t n); void _myheapsort(struct address_value *arr, int64_t n); void _heapify(struct address_value *arr, int64_t n, int64_t i); void bsgs_sort(struct bsgs_xvalue *arr,int64_t n); void bsgs_myheapsort(struct bsgs_xvalue *arr, int64_t n); void bsgs_insertionsort(struct bsgs_xvalue *arr, int64_t n); void bsgs_introsort(struct bsgs_xvalue *arr,uint32_t depthLimit, int64_t n); void bsgs_swap(struct bsgs_xvalue *a,struct bsgs_xvalue *b); void bsgs_heapify(struct bsgs_xvalue *arr, int64_t n, int64_t i); int64_t bsgs_partition(struct bsgs_xvalue *arr, int64_t n); int bsgs_searchbinary(struct bsgs_xvalue *arr,char *data,int64_t _N,uint64_t *r_value); int bsgs_secondcheck(Int *start_range,uint32_t a,uint32_t k_index,Int *privatekey); void *thread_process(void *vargp); void *thread_process_bsgs(void *vargp); void *thread_process_bsgs_random(void *vargp); void *thread_bPload(void *vargp); void *thread_bPloadFile(void *vargp); void *thread_pub2rmd(void *vargp); char *publickeytohashrmd160(char *pkey,int length); char *pubkeytopubaddress(char *pkey,int length); //char *pubkeytopubaddress_eth(char *pkey,int length); int THREADOUTPUT = 0; char *bit_range_str_min; char *bit_range_str_max; const char *modes[5] = {"xpoint","address","bsgs","rmd160","pub2rmd"}; const char *cryptos[3] = {"btc","eth","all"}; const char *publicsearch[3] = {"uncompress","compress","both"}; const char *default_filename = "addresses.txt"; pthread_t *tid = NULL; pthread_mutex_t write_keys; pthread_mutex_t write_random; pthread_mutex_t bsgs_thread; struct bloom dummybloom; struct bloom bloom; unsigned int *steps = NULL; unsigned int *ends = NULL; uint64_t N = 0; uint64_t N_SECUENTIAL_MAX = 0xffffffff; uint64_t DEBUGCOUNT = 0x100000; Int OUTPUTSECONDS; int FLAGDEBUG = 0; int FLAGQUIET = 0; int KFACTOR = 1; int MAXLENGTHADDRESS = -1; int NTHREADS = 1; int FLAGSEARCH = 2; int FLAGBITRANGE = 0; int FLAGRANGE = 0; int FLAGFILE = 0; int FLAGVANITY = 0; int FLAGMODE = MODE_ADDRESS; int FLAGCRYPTO = 0; int FLAGALREADYSORTED = 0; int FLAGRAWDATA = 0; int FLAGRANDOM = 0; int FLAG_N = 0; int FLAGPRECALCUTED_P_FILE = 0; int FLAGPRECALCUTED_MP_FILE = 0; int FLAGBLOOMFILTER = 0; int len_vanity; int bitrange; char *vanity; char *range_start; char *range_end; uint64_t BSGS_XVALUE_RAM = 6; uint64_t BSGS_BUFFERXPOINTLENGTH = 32; uint64_t BSGS_BUFFERREGISTERLENGTH = 36; /* BSGS Variables */ int *bsgs_found; std::vector<Point> OriginalPointsBSGS; bool *OriginalPointsBSGScompressed; struct bsgs_xvalue *bPtable; struct address_value *addressTable; struct bloom bloom_bP[256]; struct bloom bloom_bPx2nd; //Second Bloom filter check uint64_t bloom_bP_totalbytes = 0; char *precalculated_p_filename; uint64_t bsgs_m = 4194304; uint64_t bsgs_m2; unsigned long int bsgs_aux; uint32_t bsgs_point_number; Int BSGS_GROUP_SIZE; Int BSGS_CURRENT; Int BSGS_R; Int BSGS_AUX; Int BSGS_N; Int BSGS_M; //M is squareroot(N) Int BSGS_M2; Int ONE; Int ZERO; Int MPZAUX; Point BSGS_P; //Original P is actually G, but this P value change over time for calculations Point BSGS_MP; //MP values this is m * P Point BSGS_MP2; //MP values this is m2 * P std::vector<Point> BSGS_AMP,BSGS_AMP2; Point point_temp,point_temp2; //Temp value for some process Int n_range_start; Int n_range_end; Int n_range_diff; Int n_range_aux; Secp256K1 *secp; int main(int argc, char **argv) { char buffer[1024]; char temporal[65]; char rawvalue[32]; struct tothread *tt; //tothread Tokenizer t,tokenizerbsgs,tokenizer_xpoint; //tokenizer char *filename,*precalculated_mp_filename,*hextemp,*aux,*aux2,*pointx_str,*pointy_str,*str_seconds,*str_total,*str_pretotal; FILE *fd; uint64_t j,total_precalculated,i,PERTHREAD,BASE,PERTHREAD_R,itemsbloom,itemsbloom2; int readed,s,continue_flag,check_flag,r,lenaux,lendiff,c; Int total,pretotal,debugcount_mpz,seconds; struct bPload *temp; secp = new Secp256K1(); secp->Init(); OUTPUTSECONDS.SetInt32(30); ZERO.SetInt32(0); ONE.SetInt32(1); BSGS_GROUP_SIZE.SetInt32(CPU_GRP_SIZE); rseed(clock() + time(NULL)); printf("[+] Version %s\n",version); while ((c = getopt(argc, argv, "dehqRwzb:c:f:g:k:l:m:n:p:r:s:t:v:G:")) != -1) { switch(c) { case 'h': printf("\nUsage:\n-h\t\tshow this help\n"); printf("-a file\t\tfile is a binary raw file with the aMP points precalculated. Just work with -m bsgs\n"); printf("-b bits\t\tFor some puzzles you only need some numbers of bits in the test keys.\n"); printf("\t\tThis option only is valid with the Random option -R\n"); printf("-c crypto\tSearch for specific crypo. < btc, eth, all > valid only w/ -m address \n"); printf("-e\t\tThe file is already Sorted descendent. This skip the sorting process.\n"); printf("\t\tYour file MUST be sordted if no you are going to lose collisions\n"); printf("-f file\t\tSpecify filename with addresses or xpoints or uncompressed public keys\n"); printf("-g count\tJust for the stats, mark as counted every debugcount keys \n"); printf("-k value\tUse this only with bsgs mode, k value is factor for M, more speed but more RAM use wisely\n"); printf("-l look\tWhat type of address/hash160 are you looking for < compress , uncompress , both>\n"); printf("-m mode\t\tmode of search for cryptos. ( bsgs , xpoint , rmd160 , address ) default: address (more slow)\n"); printf("-n uptoN\tCheck for N secuential numbers before the random chossen this only work with -R option\n"); printf("\t\tUse -n to set the N for the BSGS process. Bigger N more RAM needed\n"); printf("-p file\t\tfile is a binary raw file with the bP points precalculated. Just work with -m bsgs\n"); printf("-q\t\tset quiet the thread output\n"); printf("-r SR:EN\tStarRange:EndRange, the end range can be omited for search from start range to N-1 ECC value\n"); printf("-R\t\tRandom this is the default behaivor\n"); printf("-s ns\t\tNumber of seconds for the stats output, 0 to omit output.\n"); printf("-t tn\t\tThreads number, must be positive integer\n"); printf("-v va\t\tSearch for vanity Address, only with -m address\n"); printf("-w\t\tMark the input file as RAW data xpoint fixed 32 byte each point. Valid only with -m xpoint\n"); //printf("-z\t\tSave and load bloom bloomfilter from File\n"); printf("\t\tUse the hexcharstoraw tool to create a raw file from your current hexadecimal file\n"); printf("\nExample\n\n"); printf("%s -t 16 -r 00000001:FFFFFFFF -s 0\n\n",argv[0]); printf("This line run the program with 16 threads from the range 00000001 to FFFFFFFF without stats output\n\n"); printf("Developed by AlbertoBSD\tTips BTC: 1ABSD1rMTmNZHJrJP8AJhDNG1XbQjWcRz7\n"); printf("Thanks to Iceland always helping and sharing his ideas, Tips to Iceland: bc1q39meky2mn5qjq704zz0nnkl0v7kj4uz6r529at\n\n"); exit(0); break; case 'a': FLAGPRECALCUTED_MP_FILE = 1; precalculated_mp_filename = optarg; break; case 'b': bitrange = strtol(optarg,NULL,10); if(bitrange > 0 && bitrange <=256 ) { MPZAUX.Set(&ONE); MPZAUX.ShiftL(bitrange-1); bit_range_str_min = MPZAUX.GetBase16(); MPZAUX.Set(&ONE); MPZAUX.ShiftL(bitrange); if(MPZAUX.IsGreater(&secp->order)) { MPZAUX.Set(&secp->order); } bit_range_str_max = MPZAUX.GetBase16(); if(bit_range_str_min == NULL||bit_range_str_max == NULL) { fprintf(stderr,"[E] error malloc()\n"); exit(0); } printf("[+] Min range: %s\n",bit_range_str_min); printf("[+] Max range: %s\n",bit_range_str_max); FLAGBITRANGE = 1; } else { fprintf(stderr,"[E] invalid bits param: %s.\n",optarg); } break; case 'c': switch(indexOf(optarg,cryptos,3)) { case 0: //btc FLAGCRYPTO = CRYPTO_BTC; printf("[+] Setting search for btc adddress.\n"); break; case 1: //eth FLAGCRYPTO = CRYPTO_ETH; printf("[+] Setting search for eth adddress.\n"); break; case 2: //all FLAGCRYPTO = CRYPTO_ALL; printf("[+] Setting search for all cryptocurrencies avaible [btc].\n"); break; default: FLAGCRYPTO = CRYPTO_NONE; fprintf(stderr,"[E] Unknow crypto value %s\n",optarg); break; } break; case 'd': FLAGDEBUG = 1; break; case 'e': FLAGALREADYSORTED = 1; break; case 'f': FLAGFILE = 1; filename = optarg; break; case 'g': DEBUGCOUNT = strtol(optarg,NULL,10); if(DEBUGCOUNT == 0) { DEBUGCOUNT = 0x100000; fprintf(stderr,"[E] invalid -g option value: %s.\n",optarg); } break; case 'k': KFACTOR = (int)strtol(optarg,NULL,10); if(KFACTOR <= 0) { KFACTOR = 1; } printf("[+] Setting k factor to %i\n",KFACTOR); break; case 'l': switch(indexOf(optarg,publicsearch,3)) { case SEARCH_UNCOMPRESS: FLAGSEARCH = SEARCH_UNCOMPRESS; printf("[+] Search uncompress only\n"); break; case SEARCH_COMPRESS: FLAGSEARCH = SEARCH_COMPRESS; printf("[+] Search compress only\n"); break; case SEARCH_BOTH: FLAGSEARCH = SEARCH_BOTH; printf("[+] Search both compress and uncompress\n"); break; } break; case 'm': switch(indexOf(optarg,modes,5)) { case MODE_XPOINT: //xpoint FLAGMODE = MODE_XPOINT; printf("[+] Setting mode xpoint\n"); break; case MODE_ADDRESS: //address FLAGMODE = MODE_ADDRESS; printf("[+] Setting mode address\n"); break; case MODE_BSGS: FLAGMODE = MODE_BSGS; printf("[+] Setting mode BSGS\n"); break; case MODE_RMD160: FLAGMODE = MODE_RMD160; printf("[+] Setting mode rmd160\n"); break; case MODE_PUB2RMD: FLAGMODE = MODE_PUB2RMD; printf("[+] Setting mode pub2rmd\n"); break; default: FLAGMODE = MODE_ADDRESS; fprintf(stderr,"[+] Unknow mode value %s.\n",optarg); break; } break; case 'n': FLAG_N = 1; N_SECUENTIAL_MAX = strtol(optarg,NULL,10); if(N_SECUENTIAL_MAX <= 0) { FLAG_N = 0; N_SECUENTIAL_MAX = 0xFFFFFFFF; } break; case 'q': FLAGQUIET = 1; printf("[+] Set quiet thread output\n"); break; case 'p': FLAGPRECALCUTED_P_FILE = 1; precalculated_p_filename = optarg; break; case 'R': FLAGRANDOM = 1; printf("[+] Setting random mode.\n"); break; case 'r': if(optarg != NULL) { stringtokenizer(optarg,&t); switch(t.n) { case 1: range_start = nextToken(&t); if(isValidHex(range_start)) { FLAGRANGE = 1; range_end = secp->order.GetBase16(); } else { fprintf(stderr,"[E] Invalid hexstring : %s.\n",range_start); } break; case 2: range_start = nextToken(&t); range_end = nextToken(&t); if(isValidHex(range_start) && isValidHex(range_end)) { FLAGRANGE = 1; } else { if(isValidHex(range_start)) { printf("[E] Invalid hexstring : %s\n",range_start); } else { printf("[E] Invalid hexstring : %s\n",range_end); } } break; default: printf("[E] Unknow number of Range Params: %i\n",t.n); break; } } break; case 's': OUTPUTSECONDS.SetBase10(optarg); if(OUTPUTSECONDS.IsLower(&ZERO)) { OUTPUTSECONDS.SetInt32(30); } if(OUTPUTSECONDS.IsZero()) { printf("[+] Turn off stats output\n"); } else { hextemp = OUTPUTSECONDS.GetBase10(); printf("[+] Stats output every %s seconds\n",hextemp); free(hextemp); } break; case 't': NTHREADS = strtol(optarg,NULL,10); if(NTHREADS <= 0) { NTHREADS = 1; } printf((NTHREADS > 1) ? "[+] Setting %u threads\n": "[+] Setting %u thread\n",NTHREADS); break; case 'v': FLAGVANITY = 1; vanity = optarg; len_vanity = strlen(optarg); printf("[+] Added Vanity search : %s\n",vanity); break; case 'w': printf("[+] Data marked as RAW\n"); FLAGRAWDATA = 1; break; case 'z': printf("[+] Bloom filter marked to be saved\n"); FLAGBLOOMFILTER = 1; break; default: printf("[E] Unknow opcion %c\n",c); break; } } init_generator(); if(DEBUGCOUNT > N_SECUENTIAL_MAX) { DEBUGCOUNT = N_SECUENTIAL_MAX - 1; } if(FLAGFILE == 0) { filename =(char*) default_filename; } printf("[+] Opening file %s\n",filename); fd = fopen(filename,"rb"); if(fd == NULL) { fprintf(stderr,"[E] Can't open file %s\n",filename); exit(0); } if(FLAGMODE == MODE_ADDRESS && FLAGCRYPTO == CRYPTO_NONE) { //When none crypto is defined the default search is for Bitcoin FLAGCRYPTO = CRYPTO_BTC; printf("[+] Setting search for btc adddress\n"); } if(FLAGRANGE) { n_range_start.SetBase16(range_start); if(n_range_start.IsZero()) { n_range_start.AddOne(); } n_range_end.SetBase16(range_end); if(n_range_start.IsEqual(&n_range_end) == false ) { if( n_range_start.IsLower(&secp->order) && n_range_end.IsLowerOrEqual(&secp->order) ) { if( n_range_start.IsGreater(&n_range_end)) { fprintf(stderr,"[W] Opps, start range can't be great than end range. Swapping them\n"); n_range_aux.Set(&n_range_start); n_range_start.Set(&n_range_end); n_range_end.Set(&n_range_aux); } n_range_diff.Set(&n_range_end); n_range_diff.Sub(&n_range_start); } else { fprintf(stderr,"[E] Start and End range can't be great than N\nFallback to random mode!\n"); FLAGRANGE = 0; } } else { fprintf(stderr,"[E] Start and End range can't be the same\nFallback to random mode!\n"); FLAGRANGE = 0; } } if(FLAGMODE != MODE_BSGS) { if(FLAGRANGE == 0 && FLAGBITRANGE == 0) { n_range_start.SetInt32(1); n_range_end.Set(&secp->order); n_range_diff.Set(&n_range_end); n_range_diff.Sub(&n_range_start); } else { if(FLAGBITRANGE) { n_range_start.SetBase16(bit_range_str_min); n_range_end.SetBase16(bit_range_str_max); n_range_diff.Set(&n_range_end); n_range_diff.Sub(&n_range_start); } else { if(FLAGRANGE == 0) { fprintf(stderr,"[W] WTF!\n"); } } } } N = 0; if(FLAGMODE != MODE_BSGS) { aux =(char*) malloc(1000); if(aux == NULL) { fprintf(stderr,"[E] error malloc()\n"); } switch(FLAGMODE) { case MODE_ADDRESS: while(!feof(fd)) { hextemp = fgets(aux,998,fd); if(hextemp == aux) { trim(aux," \t\n\r"); r = strlen(aux); if(r > 10) { //Any length for invalid Address? if(r > MAXLENGTHADDRESS) { MAXLENGTHADDRESS = r; } N++; } } } MAXLENGTHADDRESS = 32; break; case MODE_PUB2RMD: case MODE_RMD160: if(FLAGRAWDATA) { while(!feof(fd)) { if(fread(aux,1,20,fd) == 20) { N++; } } } else { while(!feof(fd)) { hextemp = fgets(aux,998,fd); if(hextemp == aux) { trim(aux," \t\n\r"); r = strlen(aux); if(r == 40) { //Any length for invalid Address? N++; } } } } MAXLENGTHADDRESS = 20; break; case MODE_XPOINT: if(FLAGRAWDATA) { while(!feof(fd)) { if(fread(aux,1,32,fd) == 32) { N++; } } } else { while(!feof(fd)) { hextemp = fgets(aux,998,fd); if(hextemp == aux) { trim(aux," \t\n\r"); r = strlen(aux); if(r >= 32) { //Any length for invalid Address? N++; } } } } MAXLENGTHADDRESS = 32; break; } free(aux); if(N == 0) { fprintf(stderr,"[E] There is no valid data in the file\n"); exit(0); } fseek(fd,0,SEEK_SET); printf("[+] Allocating memory for %" PRIu64 " elements: %.2f MB\n",N,(double)(((double) sizeof(struct address_value)*N)/(double)1048576)); i = 0; addressTable = (struct address_value*) malloc(sizeof(struct address_value)*N); if(addressTable == NULL) { fprintf(stderr,"[E] Can't alloc memory for %" PRIu64 " elements\n",N); exit(0); } printf("[+] Initializing bloom filter for %" PRIu64 " elements.\n",N); if(N <= 1000) { if(bloom_init2(&bloom,1000,0.00001) == 1){ fprintf(stderr,"[E] error bloom_init for 10000 elements.\n"); exit(0); } } else { if(bloom_init2(&bloom,N,0.00001) == 1){ fprintf(stderr,"[E] error bloom_init for %" PRIu64 " elements.\n",N); fprintf(stderr,"[+] man enough is enough stop it\n"); exit(0); } } printf("[+] Loading data to the bloomfilter total: %.2f MB\n",(double)(((double) bloom.bytes)/(double)1048576)); i = 0; switch (FLAGMODE) { case MODE_ADDRESS: aux =(char*) malloc(2*MAXLENGTHADDRESS); if(aux == NULL) { fprintf(stderr,"[E] error malloc()\n"); exit(0); } while(i < N) { memset(aux,0,2*MAXLENGTHADDRESS); memset((void *)&addressTable[i],0,sizeof(struct address_value)); hextemp = fgets(aux,2*MAXLENGTHADDRESS,fd); if(hextemp == aux) { trim(aux," \t\n\r"); bloom_add(&bloom, aux,MAXLENGTHADDRESS); memcpy(addressTable[i].value,aux,20); i++; } else { trim(aux," \t\n\r"); fprintf(stderr,"[E] Omiting line : %s\n",aux); } } break; case MODE_XPOINT: if(FLAGRAWDATA) { aux = (char*)malloc(MAXLENGTHADDRESS); if(aux == NULL) { fprintf(stderr,"[E] error malloc()\n"); exit(0); } while(i < N) { if(fread(aux,1,MAXLENGTHADDRESS,fd) == 32) { memcpy(addressTable[i].value,aux,20); bloom_add(&bloom, aux,MAXLENGTHADDRESS); } i++; } } else { aux = (char*) malloc(5*MAXLENGTHADDRESS); if(aux == NULL) { fprintf(stderr,"[E] error malloc()\n"); exit(0); } while(i < N) { memset(aux,0,5*MAXLENGTHADDRESS); hextemp = fgets(aux,(5*MAXLENGTHADDRESS) -2,fd); memset((void *)&addressTable[i],0,sizeof(struct address_value)); if(hextemp == aux) { trim(aux," \t\n\r"); stringtokenizer(aux,&tokenizer_xpoint); hextemp = nextToken(&tokenizer_xpoint); lenaux = strlen(hextemp); if(isValidHex(hextemp)) { switch(lenaux) { case 64: /*X value*/ r = hexs2bin(aux,(uint8_t*) rawvalue); if(r) { memcpy(addressTable[i].value,rawvalue,20); bloom_add(&bloom,rawvalue,MAXLENGTHADDRESS); } else { fprintf(stderr,"[E] error hexs2bin\n"); } break; case 66: /*Compress publickey*/ r = hexs2bin(aux+2, (uint8_t*)rawvalue); if(r) { memcpy(addressTable[i].value,rawvalue,20); bloom_add(&bloom,rawvalue,MAXLENGTHADDRESS); } else { fprintf(stderr,"[E] error hexs2bin\n"); } break; case 130: /* Uncompress publickey length*/ memset(temporal,0,65); memcpy(temporal,aux+2,64); r = hexs2bin(temporal, (uint8_t*) rawvalue); if(r) { memcpy(addressTable[i].value,rawvalue,20); bloom_add(&bloom,rawvalue,MAXLENGTHADDRESS); } else { fprintf(stderr,"[E] error hexs2bin\n"); } break; default: fprintf(stderr,"[E] Omiting line unknow length size %i: %s\n",lenaux,aux); break; } } else { fprintf(stderr,"[E] Ignoring invalid hexvalue %s\n",aux); } freetokenizer(&tokenizer_xpoint); } else { fprintf(stderr,"[E] Omiting line : %s\n",aux); N--; } i++; } } break; case MODE_PUB2RMD: case MODE_RMD160: if(FLAGRAWDATA) { aux = (char*) malloc(MAXLENGTHADDRESS); if(aux == NULL) { fprintf(stderr,"[E] error malloc()\n"); exit(0); } while(i < N) { if(fread(aux,1,MAXLENGTHADDRESS,fd) == 20) { memcpy(addressTable[i].value,aux,20); bloom_add(&bloom, aux,MAXLENGTHADDRESS); } i++; } } else { aux = (char*) malloc(3*MAXLENGTHADDRESS); if(aux == NULL) { fprintf(stderr,"[E] error malloc()\n"); exit(0); } while(i < N) { memset(aux,0,3*MAXLENGTHADDRESS); hextemp = fgets(aux,3*MAXLENGTHADDRESS,fd); memset(addressTable[i].value,0,20); if(hextemp == aux) { trim(aux," \t\n\r"); lenaux = strlen(aux); if(isValidHex(aux)) { if(lenaux == 40) { if(hexs2bin(aux,addressTable[i].value)) { bloom_add(&bloom,addressTable[i].value,MAXLENGTHADDRESS); } else { fprintf(stderr,"[E] error hexs2bin\n"); } } else { fprintf(stderr,"[E] Ignoring invalid length line %s\n",aux); } } else { fprintf(stderr,"[E] Ignoring invalid hexvalue %s\n",aux); } } else { fprintf(stderr,"[E] Omiting line : %s\n",aux); } i++; } } break; } free(aux); fclose(fd); printf("[+] Bloomfilter completed\n"); if(FLAGALREADYSORTED) { printf("[+] File mark already sorted, skipping sort proccess\n"); printf("[+] %" PRIu64 " values were loaded\n",N); _sort(addressTable,N); } else { printf("[+] Sorting data ..."); _sort(addressTable,N); printf(" done! %" PRIu64 " values were loaded and sorted\n",N); } } if(FLAGMODE == MODE_BSGS) { DEBUGCOUNT = N_SECUENTIAL_MAX ; aux = (char*) malloc(1024); if(aux == NULL) { fprintf(stderr,"[E] error malloc()\n"); exit(0); } while(!feof(fd)) { if(fgets(aux,1022,fd) == aux) { trim(aux," \t\n\r"); if(strlen(aux) >= 128) { //Length of a full address in hexadecimal without 04 N++; }else { if(strlen(aux) >= 66) { N++; } } } } if(N == 0) { fprintf(stderr,"[E] There is no valid data in the file\n"); exit(0); } bsgs_found = (int*) calloc(N,sizeof(int)); OriginalPointsBSGS.reserve(N); OriginalPointsBSGScompressed = (bool*) malloc(N*sizeof(bool)); pointx_str = (char*) malloc(65); pointy_str = (char*) malloc(65); if(pointy_str == NULL || pointx_str == NULL || bsgs_found == NULL) { fprintf(stderr,"[E] error malloc()\n"); exit(0); } fseek(fd,0,SEEK_SET); i = 0; while(!feof(fd)) { if(fgets(aux,1022,fd) == aux) { trim(aux," \t\n\r"); if(strlen(aux) >= 66) { stringtokenizer(aux,&tokenizerbsgs); aux2 = nextToken(&tokenizerbsgs); memset(pointx_str,0,65); memset(pointy_str,0,65); switch(strlen(aux2)) { case 66: //Compress if(secp->ParsePublicKeyHex(aux2,OriginalPointsBSGS[i],OriginalPointsBSGScompressed[i])) { i++; } else { N--; } break; /* Somebody use this? To be removed 5/Nov */ /* case 128: //Without the 04 memcpy(pointx_str,aux2,64); memcpy(pointy_str,aux2+64,64); if(isValidHex(pointx_str) && isValidHex(pointy_str)) { mpz_init_set_str(OriginalPointsBSGS[i].x,pointx_str,16); mpz_init_set_str(OriginalPointsBSGS[i].y,pointy_str,16); //printf("Adding point ( %s , %s )\n",pointx_str,pointy_str); i++; } else { fprintf(stderr,"[E] Some invalid hexdata in the file: %s\n",aux2); N--; } break; */ case 130: //With the 04 if(secp->ParsePublicKeyHex(aux2,OriginalPointsBSGS[i],OriginalPointsBSGScompressed[i])) { i++; } else { N--; } break; default: printf("Invalid length: %s\n",aux2); N--; break; } freetokenizer(&tokenizerbsgs); } } } fclose(fd); bsgs_point_number = N; if(bsgs_point_number > 0) { printf("[+] Added %u points from file\n",bsgs_point_number); } else { printf("[E] The file don't have any valid publickeys\n"); exit(0); } BSGS_N.SetInt32(0); BSGS_M.SetInt32(0); /* hextemp = BSGS_N.GetBase10(); printf("[+] BSGS_N: %s\n",hextemp); free(hextemp); hextemp = BSGS_M.GetBase10(); printf("[+] BSGS_M: %s\n",hextemp); free(hextemp); */ BSGS_M.SetInt64(bsgs_m); //printf("[+] bsgs_m: %"PRIu64"\n",bsgs_m); /* hextemp = BSGS_N.GetBase10(); printf("[+] BSGS_N: %s\n",hextemp); free(hextemp); hextemp = BSGS_M.GetBase10(); printf("[+] BSGS_M: %s\n",hextemp); free(hextemp); */ if(FLAG_N) { //Custom N by the -n param BSGS_N.SetInt64(N_SECUENTIAL_MAX); } else { //Default N BSGS_N.SetInt64((uint64_t)0x100000000000); } if(BSGS_N.HasSqrt()) { //If the root is exact BSGS_M.Set(&BSGS_N); BSGS_M.ModSqrt(); } else { fprintf(stderr,"[E] -n param doesn't have exact square root\n"); exit(0); } /* hextemp = BSGS_N.GetBase16(); printf("[+] BSGS_N: %s\n",hextemp); free(hextemp); hextemp = BSGS_M.GetBase16(); printf("[+] BSGS_M: %s\n",hextemp); free(hextemp); */ BSGS_AUX.Set(&BSGS_M); BSGS_AUX.Mod(&BSGS_GROUP_SIZE); if(!BSGS_AUX.IsZero()){ hextemp = BSGS_GROUP_SIZE.GetBase10(); fprintf(stderr,"[E] M value is not divisible by %s\n",hextemp); exit(0); } bsgs_m = BSGS_M.GetInt64(); BSGS_N.Set(&BSGS_M); BSGS_N.Mult(&BSGS_M); DEBUGCOUNT = bsgs_m * bsgs_m; if(FLAGRANGE || FLAGBITRANGE) { if(FLAGBITRANGE) { // Bit Range n_range_start.SetBase16(bit_range_str_min); n_range_end.SetBase16(bit_range_str_max); n_range_diff.Set(&n_range_end); n_range_diff.Sub(&n_range_start); printf("[+] Bit Range %i\n",bitrange); } } else { //Random start n_range_start.SetInt32(1); n_range_end.Set(&secp->order); n_range_diff.Rand(&n_range_start,&n_range_end); n_range_start.Set(&n_range_diff); } BSGS_CURRENT.Set(&n_range_start); /* hextemp = BSGS_N.GetBase16(); printf("[+] BSGS_N: %s\n",hextemp); free(hextemp); hextemp = BSGS_M.GetBase16(); printf("[+] BSGS_M: %s\n",hextemp); free(hextemp); */ if(n_range_diff.IsLower(&BSGS_N) ) { BSGS_N.Set(&n_range_diff); if(BSGS_N.HasSqrt()) { //If the root is exact BSGS_M.Set(&BSGS_N); BSGS_M.ModSqrt(); /* hextemp = BSGS_N.GetBase16(); printf("[+] BSGS_N: %s\n",hextemp); free(hextemp); hextemp = BSGS_M.GetBase16(); printf("[+] BSGS_M: %s\n",hextemp); free(hextemp); */ } else { fprintf(stderr,"[E] the range is small and doesn't have exact square root\n"); exit(0); } bsgs_m = BSGS_M.GetInt64(); BSGS_N.Set(&BSGS_M); BSGS_N.Mult(&BSGS_M); DEBUGCOUNT = bsgs_m * bsgs_m; bsgs_m = BSGS_M.GetInt64(); DEBUGCOUNT = (uint64_t)((uint64_t)bsgs_m * (uint64_t)bsgs_m); } BSGS_M.Mult((uint64_t)KFACTOR); BSGS_AUX.SetInt32(20); BSGS_R.Set(&BSGS_M); BSGS_R.Mod(&BSGS_AUX); BSGS_M2.Set(&BSGS_M); BSGS_M2.Div(&BSGS_AUX); if(!BSGS_R.IsZero()) { BSGS_M2.AddOne(); } bsgs_m2 = BSGS_M2.GetInt64(); BSGS_AUX.Set(&BSGS_N); BSGS_AUX.Div(&BSGS_M); BSGS_R.Set(&BSGS_N); BSGS_R.Mod(&BSGS_M); if(!BSGS_R.IsZero()) { BSGS_N.Set(&BSGS_M); BSGS_N.Mult(&BSGS_AUX); } bsgs_m = (uint64_t)((uint64_t) bsgs_m * (uint64_t)KFACTOR); bsgs_aux = BSGS_AUX.GetInt64(); DEBUGCOUNT = (uint64_t)((uint64_t)bsgs_m * (uint64_t)bsgs_aux); printf("[+] Setting N up to %" PRIu64 ".\n",DEBUGCOUNT); itemsbloom = ((uint64_t)(bsgs_m/256)) > 10000 ? (uint64_t)(bsgs_m/256) : 10000; itemsbloom2 = bsgs_m2 > 1000 ? bsgs_m : 10000; if( FLAGBLOOMFILTER == 1 ) { int continuebloom = 1; int numberbloom = 0; for(i=0; i< 256 && continuebloom; i++) { if(bloom_loadcustom(&bloom_bP[i],(char*)bloomnames[i]) == 1){ continuebloom = 0; } else { if(bloom_dummy(&dummybloom,itemsbloom,0.000001) == 0){ numberbloom++; if(dummybloom.bytes != bloom_bP[i].bytes) { continuebloom = 0; } } else { continuebloom = 0; } } } if(continuebloom == 1) { if(bloom_loadcustom(&bloom_bPx2nd,(char*)"bPx2nd") == 1) { continuebloom == 0; } else { if(bloom_dummy(&dummybloom,itemsbloom2,0.000001) == 0){ if(dummybloom.bytes != bloom_bPx2nd.bytes) { continuebloom = 0; } if(continuebloom == 0) { bloom_free(&bloom_bPx2nd); } } } } if(continuebloom == 0) { fprintf(stderr,"[E] Some bloom file fail or missmatch size\n"); FLAGBLOOMFILTER = 0; for(i=0; i < numberbloom ; i++) { bloom_free(&bloom_bP[i]); } } } /* if( FLAGBLOOMFILTER == 0) { */ for(i=0; i< 256; i++) { if(bloom_init2(&bloom_bP[i],itemsbloom,0.000001) == 1){ fprintf(stderr,"[E] error bloom_init [%" PRIu64 "]\n",i); exit(0); } bloom_bP_totalbytes += bloom_bP[i].bytes; if(FLAGDEBUG) bloom_print(&bloom_bP[i]); } printf("[+] Init 1st bloom filter for %lu elements : %.2f MB\n",bsgs_m,(float)((uint64_t)bloom_bP_totalbytes/(uint64_t)1048576)); if(bsgs_m2 > 1000) { if(bloom_init2(&bloom_bPx2nd,bsgs_m2,0.000001) == 1){ fprintf(stderr,"[E] error bloom_init for %lu elements\n",bsgs_m2); exit(0); } } else { if(bloom_init2(&bloom_bPx2nd,1000,0.000001) == 1){ fprintf(stderr,"[E] error bloom_init for 1000 elements\n"); exit(0); } } if(FLAGDEBUG) bloom_print(&bloom_bPx2nd); printf("[+] Init 2nd bloom filter for %lu elements : %.2f MB\n",bsgs_m2,(double)((double)bloom_bPx2nd.bytes/(double)1048576)); //bloom_print(&bloom_bPx2nd); /* hextemp = BSGS_M.GetBase16(); printf("[+] BSGS_M: %s\n",hextemp); free(hextemp); hextemp = BSGS_M2.GetBase16(); printf("[+] BSGS_M2: %s\n",hextemp); free(hextemp); */ BSGS_MP = secp->ComputePublicKey(&BSGS_M); BSGS_MP2 = secp->ComputePublicKey(&BSGS_M2); printf("[+] Allocating %.1f MB for %" PRIu64 " aMP Points\n",(double)(((double)(bsgs_aux*sizeof(Point)))/(double)1048576),bsgs_aux); i = 0; BSGS_AMP.reserve(bsgs_aux); //printf("[+] Allocating %.1f MB for aMP Points (2nd)\n",(float)(((uint64_t)(bsgs_m2*sizeof(struct strPoint)))/(uint64_t)1048576)); BSGS_AMP2.reserve(bsgs_m2); i= 0; if(FLAGPRECALCUTED_MP_FILE) { printf("[+] Reading aMP points from file %s\n",precalculated_mp_filename); fd = fopen(precalculated_mp_filename,"rb"); if(fd != NULL) { while(!feof(fd) && i < bsgs_aux ) { if(fread(temporal,1,64,fd) == 64) { BSGS_AMP[i].x.Set32Bytes((unsigned char*)temporal); BSGS_AMP[i].x.Set32Bytes((unsigned char*)(temporal+32)); i++; } } if(i < bsgs_aux) { //If the input file have less item than bsgs_m printf("[+] Fixme file contains less items than the amount of items needed\n"); exit(0); } } else { fprintf(stderr,"[E] Can't open file %s falling back to the calculation mode\n",filename); printf("[+] Precalculating %lu aMP points\n",bsgs_aux); point_temp.Set(BSGS_MP); for(i = 0; i < bsgs_aux; i++) { BSGS_AMP[i] = secp->Negation(point_temp); if(i == 0) { printf("\n[+] point_temp vs BSGS_MP %s\n",point_temp.equals(BSGS_MP) ? "Si iguales":"No, diferentes"); } if(point_temp.equals(BSGS_MP)) { point_temp2 = secp->DoubleDirect(BSGS_MP); } else { point_temp2 = secp->AddDirect(point_temp,BSGS_MP); } point_temp.Set(point_temp2); } } } else { printf("[+] Precalculating %" PRIu64 " aMP points\n",bsgs_aux); point_temp.Set(BSGS_MP); for(i = 0; i < bsgs_aux; i++) { BSGS_AMP[i] = secp->Negation(point_temp); if(i == 0) { point_temp2 = secp->DoubleDirect(BSGS_MP); } else { point_temp2 = secp->AddDirect(point_temp,BSGS_MP); } point_temp.Set(point_temp2); } } point_temp.Set(BSGS_MP2); for(i = 0; i < 20; i++) { BSGS_AMP2[i] = secp->Negation(point_temp); if(i == 0) { point_temp2 = secp->DoubleDirect(BSGS_MP2); } else { point_temp2 = secp->AddDirect(point_temp,BSGS_MP2); } point_temp.Set(point_temp2); } printf("[+] Allocating %.2f MB for %" PRIu64 " bP Points\n",(double)((double)((uint64_t)bsgs_m2*(uint64_t)sizeof(struct bsgs_xvalue))/(double)1048576),bsgs_m2); //printf("[+] Allocating %.2f MB for bP Points\n",(float)((uint64_t)((uint64_t)bsgs_m*(uint64_t)sizeof(struct bsgs_xvalue))/(uint64_t)1048576)); bPtable = (struct bsgs_xvalue*) calloc(bsgs_m2,sizeof(struct bsgs_xvalue)); if(bPtable == NULL) { printf("[E] error malloc()\n"); exit(0); } i = 0; j = 0; BASE = 0; PERTHREAD = bsgs_m /NTHREADS; PERTHREAD_R = bsgs_m % NTHREADS; temp = (struct bPload *) calloc(NTHREADS,sizeof(struct bPload)); tid = (pthread_t *) calloc(NTHREADS,sizeof(pthread_t)); if(FLAGPRECALCUTED_P_FILE) { printf("[+] Reading %lu bP points from file %s\n",bsgs_m,precalculated_p_filename); for(i = 0; i < NTHREADS; i++) { temp[i].threadid = i; temp[i].counter = 0; if(i < NTHREADS -1) { temp[i].from = BASE +1; temp[i].to = BASE + PERTHREAD; } else { temp[i].from = BASE + 1; temp[i].to = BASE + PERTHREAD + PERTHREAD_R; } if(FLAGDEBUG) printf("[I] %lu to %lu\n",temp[i].from,temp[i].to); s = pthread_create(&tid[i],NULL,thread_bPloadFile,(void *)&temp[i]); BASE+=PERTHREAD; } } else { for(i = 0; i < NTHREADS; i++) { temp[i].counter = 0; if(i < NTHREADS -1) { temp[i].from = BASE +1; temp[i].to = BASE + PERTHREAD; BASE+=PERTHREAD; } else { temp[i].from = BASE + 1; temp[i].to = BASE + PERTHREAD + PERTHREAD_R; BASE+=(PERTHREAD + PERTHREAD_R); } if(FLAGDEBUG) printf("[I] %lu to %lu\n",temp[i].from,temp[i].to); s = pthread_create(&tid[i],NULL,thread_bPload,(void *)&temp[i]); } } total_precalculated = 0; do { sleep(1); total_precalculated = 0; for(i = 0; i < NTHREADS; i++) { total_precalculated+=temp[i].counter; } printf("\r[+] processing %lu/%lu bP points : %i%%",total_precalculated,bsgs_m,(int) (((double)total_precalculated/(double)bsgs_m)*100)); fflush(stdout); } while(total_precalculated < bsgs_m); for(i = 0; i < NTHREADS; i++) { pthread_join(tid[i], NULL); } printf("\n"); free(temp); free(tid); printf("[+] Sorting %lu elements... ",bsgs_m2); bsgs_sort(bPtable,bsgs_m2); printf("Done!\n"); i = 0; steps = (unsigned int *) calloc(NTHREADS,sizeof(int)); ends = (unsigned int *) calloc(NTHREADS,sizeof(int)); tid = (pthread_t *) calloc(NTHREADS,sizeof(pthread_t)); DEBUGCOUNT = (uint64_t)((uint64_t)bsgs_m * (uint64_t)bsgs_aux); for(i= 0;i < NTHREADS; i++) { tt = (tothread*) malloc(sizeof(struct tothread)); tt->nt = i; if(FLAGRANDOM) { s = pthread_create(&tid[i],NULL,thread_process_bsgs_random,(void *)tt); } else { s = pthread_create(&tid[i],NULL,thread_process_bsgs,(void *)tt); } if(s != 0) { fprintf(stderr,"[E] pthread_create thread_process\n"); exit(0); } } free(aux); } if(FLAGMODE != MODE_BSGS) { steps = (unsigned int *) calloc(NTHREADS,sizeof(int)); ends = (unsigned int *) calloc(NTHREADS,sizeof(int)); tid = (pthread_t *) calloc(NTHREADS,sizeof(pthread_t)); for(i= 0;i < NTHREADS; i++) { tt = (tothread*) malloc(sizeof(struct tothread)); tt->nt = i; steps[i] = 0; switch(FLAGMODE) { case MODE_ADDRESS: case MODE_XPOINT: case MODE_RMD160: s = pthread_create(&tid[i],NULL,thread_process,(void *)tt); break; case MODE_PUB2RMD: s = pthread_create(&tid[i],NULL,thread_pub2rmd,(void *)tt); break; } if(s != 0) { fprintf(stderr,"[E] pthread_create thread_process\n"); exit(0); } } } continue_flag = 1; total.SetInt32(0); pretotal.SetInt32(0); debugcount_mpz.SetInt64(DEBUGCOUNT); seconds.SetInt32(0); do { sleep(1); seconds.AddOne(); check_flag = 1; for(i = 0; i <NTHREADS && check_flag; i++) { check_flag &= ends[i]; } if(check_flag) { continue_flag = 0; } if(OUTPUTSECONDS.IsGreater(&ZERO) ){ MPZAUX.Set(&seconds); MPZAUX.Mod(&OUTPUTSECONDS); if(MPZAUX.IsZero()) { total.SetInt32(0); i = 0; while(i < NTHREADS) { pretotal.Set(&debugcount_mpz); pretotal.Mult(steps[i]); total.Add(&pretotal); i++; } pretotal.Set(&total); pretotal.Div(&seconds); str_seconds = seconds.GetBase10(); str_pretotal = pretotal.GetBase10(); str_total = total.GetBase10(); pthread_mutex_lock(&bsgs_thread); if(THREADOUTPUT == 1) { sprintf(buffer,"\nTotal %s keys in %s seconds: %s keys/s\r",str_total,str_seconds,str_pretotal); } else { sprintf(buffer,"\rTotal %s keys in %s seconds: %s keys/s\r",str_total,str_seconds,str_pretotal); } printf("%s",buffer); fflush(stdout); THREADOUTPUT = 0; pthread_mutex_unlock(&bsgs_thread); free(str_seconds); free(str_pretotal); free(str_total); } } }while(continue_flag); } /* char *pubkeytopubaddress_eth(char *pkey,int length) { char *temp,*pubaddress = calloc(MAXLENGTHADDRESS,1); char *digest = malloc(32); if(digest == NULL || pubaddress == NULL) { fprintf(stderr,"error malloc()\n"); exit(0); } pubaddress[0] = '0'; pubaddress[1] = 'x'; shake256(digest, 256,(const uint8_t* ) pkey, length); temp = tohex(digest+12,20); strcpy(pubaddress+2,temp); free(temp); free(digest); return pubaddress; } */ char *pubkeytopubaddress(char *pkey,int length) { char *pubaddress = (char*) calloc(MAXLENGTHADDRESS+10,1); char *digest = (char*) calloc(60,1); size_t pubaddress_size = MAXLENGTHADDRESS+10; if(pubaddress == NULL || digest == NULL) { fprintf(stderr,"error malloc()\n"); exit(0); } //digest [000...0] sha256(pkey, length, digest); //digest [SHA256 32 bytes+000....0] RMD160Data((const unsigned char*)digest,32, digest+1); //digest [? +RMD160 20 bytes+????000....0] digest[0] = 0; //digest [0 +RMD160 20 bytes+????000....0] sha256(digest, 21, digest+21); //digest [0 +RMD160 20 bytes+SHA256 32 bytes+....0] sha256(digest+21, 32, digest+21); //digest [0 +RMD160 20 bytes+SHA256 32 bytes+....0] if(!b58enc(pubaddress,&pubaddress_size,digest,25)){ fprintf(stderr,"error b58enc\n"); } free(digest); return pubaddress; // pubaddress need to be free by te caller funtion } char *publickeytohashrmd160(char *pkey,int length) { char *hash160 = (char*) malloc(20); char *digest = (char*) malloc(32); if(hash160 == NULL || digest == NULL) { fprintf(stderr,"error malloc()\n"); exit(0); } //digest [000...0] sha256(pkey, length, digest); //digest [SHA256 32 bytes] RMD160Data((const unsigned char*)digest,32, hash160); //hash160 [RMD160 20 bytes] free(digest); return hash160; // hash160 need to be free by te caller funtion } int searchbinary(struct address_value *buffer,char *data,int64_t _N) { int64_t half,min,max,current; int r = 0,rcmp; min = 0; current = 0; max = _N; half = _N; while(!r && half >= 1) { half = (max - min)/2; rcmp = memcmp(data,buffer[current+half].value,20); if(rcmp == 0) { r = 1; //Found!! } else { if(rcmp < 0) { //data < temp_read max = (max-half); } else { // data > temp_read min = (min+half); } current = min; } } return r; } void *thread_process(void *vargp) { struct tothread *tt; Point pts[CPU_GRP_SIZE]; Int dx[CPU_GRP_SIZE / 2 + 1]; IntGroup *grp = new IntGroup(CPU_GRP_SIZE / 2 + 1); Point startP; Int dy; Int dyn; Int _s; Int _p; Point pp; Point pn; int hLength = (CPU_GRP_SIZE / 2 - 1); uint64_t i,j; Point R,temporal; uint64_t count = 0; int r,thread_number,found,continue_flag = 1; char *public_key_compressed,*public_key_uncompressed,hexstrpoint[65],rawvalue[32]; char *publickeyhashrmd160_compress,*publickeyhashrmd160_uncompress; char *hextemp,*public_key_compressed_hex,*public_key_uncompressed_hex; char *eth_address; char *public_address_compressed,*public_address_uncompressed; unsigned long longtemp; FILE *keys,*vanityKeys; Int key_mpz,mpz_bit_range_min,mpz_bit_range_max,mpz_bit_range_diff; tt = (struct tothread *)vargp; thread_number = tt->nt; free(tt); found = 0; grp->Set(dx); do { if(FLAGRANDOM){ key_mpz.Rand(&n_range_start,&n_range_end); } else { if(n_range_start.IsLower(&n_range_end)){ pthread_mutex_lock(&write_random); key_mpz.Set(&n_range_start); n_range_start.Add(N_SECUENTIAL_MAX); pthread_mutex_unlock(&write_random); } else { continue_flag = 0; } } if(continue_flag) { count = 0; do { if(FLAGQUIET == 0){ hextemp = key_mpz.GetBase16(); printf("\rBase key: %s ",hextemp); fflush(stdout); free(hextemp); THREADOUTPUT = 1; } key_mpz.Add((uint64_t)CPU_GRP_SIZE / 2); startP = secp->ComputePublicKey(&key_mpz); key_mpz.Sub((uint64_t)CPU_GRP_SIZE / 2); for(i = 0; i < hLength; i++) { dx[i].ModSub(&Gn[i].x,&startP.x); } dx[i].ModSub(&Gn[i].x,&startP.x); // For the first point dx[i + 1].ModSub(&_2Gn.x,&startP.x); // For the next center point grp->ModInv(); pts[CPU_GRP_SIZE / 2] = startP; for(i = 0; i<hLength; i++) { pp = startP; pn = startP; // P = startP + i*G dy.ModSub(&Gn[i].y,&pp.y); _s.ModMulK1(&dy,&dx[i]); // s = (p2.y-p1.y)*inverse(p2.x-p1.x); _p.ModSquareK1(&_s); // _p = pow2(s) pp.x.ModNeg(); pp.x.ModAdd(&_p); pp.x.ModSub(&Gn[i].x); // rx = pow2(s) - p1.x - p2.x; if(FLAGMODE != MODE_XPOINT ) { pp.y.ModSub(&Gn[i].x,&pp.x); pp.y.ModMulK1(&_s); pp.y.ModSub(&Gn[i].y); // ry = - p2.y - s*(ret.x-p2.x); } // P = startP - i*G , if (x,y) = i*G then (x,-y) = -i*G dyn.Set(&Gn[i].y); dyn.ModNeg(); dyn.ModSub(&pn.y); _s.ModMulK1(&dyn,&dx[i]); // s = (p2.y-p1.y)*inverse(p2.x-p1.x); _p.ModSquareK1(&_s); // _p = pow2(s) pn.x.ModNeg(); pn.x.ModAdd(&_p); pn.x.ModSub(&Gn[i].x); // rx = pow2(s) - p1.x - p2.x; if(FLAGMODE != MODE_XPOINT ) { pn.y.ModSub(&Gn[i].x,&pn.x); pn.y.ModMulK1(&_s); pn.y.ModAdd(&Gn[i].y); // ry = - p2.y - s*(ret.x-p2.x); } pts[CPU_GRP_SIZE / 2 + (i + 1)] = pp; pts[CPU_GRP_SIZE / 2 - (i + 1)] = pn; } // First point (startP - (GRP_SZIE/2)*G) pn = startP; dyn.Set(&Gn[i].y); dyn.ModNeg(); dyn.ModSub(&pn.y); _s.ModMulK1(&dyn,&dx[i]); _p.ModSquareK1(&_s); pn.x.ModNeg(); pn.x.ModAdd(&_p); pn.x.ModSub(&Gn[i].x); if(FLAGMODE != MODE_XPOINT ) { pn.y.ModSub(&Gn[i].x,&pn.x); pn.y.ModMulK1(&_s); pn.y.ModAdd(&Gn[i].y); } pts[0] = pn; for(j = 0; j < CPU_GRP_SIZE;j++){ //temporal.Set(R); switch(FLAGMODE) { case MODE_ADDRESS: case MODE_RMD160: switch(FLAGSEARCH) { case SEARCH_UNCOMPRESS: public_key_uncompressed = secp->GetPublicKeyRaw(false,pts[j]); break; case SEARCH_COMPRESS: public_key_compressed = secp->GetPublicKeyRaw(true,pts[j]); break; case SEARCH_BOTH: public_key_uncompressed = secp->GetPublicKeyRaw(false,pts[j]); public_key_compressed = secp->GetPublicKeyRaw(true,pts[j]); break; } break; } switch(FLAGMODE) { case MODE_ADDRESS: switch(FLAGSEARCH) { case SEARCH_UNCOMPRESS: public_address_uncompressed = pubkeytopubaddress(public_key_uncompressed,65); break; case SEARCH_COMPRESS: public_address_compressed = pubkeytopubaddress(public_key_compressed,33); break; case SEARCH_BOTH: public_address_compressed = pubkeytopubaddress(public_key_compressed,33); public_address_uncompressed = pubkeytopubaddress(public_key_uncompressed,65); break; } if(FLAGVANITY) { if(FLAGSEARCH == SEARCH_UNCOMPRESS || FLAGSEARCH == SEARCH_BOTH){ if(strncmp(public_address_uncompressed,vanity,len_vanity) == 0) { hextemp = key_mpz.GetBase16(); vanityKeys = fopen("vanitykeys.txt","a+"); if(vanityKeys != NULL) { fprintf(vanityKeys,"PrivKey: %s\nAddress uncompressed: %s\n",hextemp,public_address_uncompressed); fclose(vanityKeys); } printf("\nVanity privKey: %s\nAddress uncompressed: %s\n",hextemp,public_address_uncompressed); free(hextemp); } } if(FLAGSEARCH == SEARCH_COMPRESS || FLAGSEARCH == SEARCH_BOTH){ if(strncmp(public_address_compressed,vanity,len_vanity) == 0) { hextemp = key_mpz.GetBase16(); vanityKeys = fopen("vanitykeys.txt","a+"); if(vanityKeys != NULL) { fprintf(vanityKeys,"PrivKey: %s\nAddress compressed: %s\n",hextemp,public_address_compressed); fclose(vanityKeys); } printf("\nVanity privKey: %s\nAddress compressed: %s\n",hextemp,public_address_compressed); free(hextemp); } } } if(FLAGSEARCH == SEARCH_COMPRESS || FLAGSEARCH == SEARCH_BOTH){ r = bloom_check(&bloom,public_address_compressed,MAXLENGTHADDRESS); if(r) { r = searchbinary(addressTable,public_address_compressed,N); if(r) { found++; hextemp = key_mpz.GetBase16(); public_key_compressed_hex = tohex(public_key_compressed,33); pthread_mutex_lock(&write_keys); keys = fopen("KEYFOUNDKEYFOUND.txt","a+"); if(keys != NULL) { fprintf(keys,"PrivKey: %s\npubkey: %s\naddress: %s\n",hextemp,public_key_compressed_hex,public_address_compressed); fclose(keys); } printf("\nHIT!! PrivKey: %s\npubkey: %s\naddress: %s\n",hextemp,public_key_compressed_hex,public_address_compressed); pthread_mutex_unlock(&write_keys); free(public_key_compressed_hex); free(hextemp); } } free(public_address_compressed); } if(FLAGSEARCH == SEARCH_UNCOMPRESS || FLAGSEARCH == SEARCH_BOTH){ r = bloom_check(&bloom,public_address_uncompressed,MAXLENGTHADDRESS); if(r) { r = searchbinary(addressTable,public_address_uncompressed,N); if(r) { found++; hextemp = key_mpz.GetBase16(); public_key_uncompressed_hex = tohex(public_key_uncompressed,65); pthread_mutex_lock(&write_keys); keys = fopen("KEYFOUNDKEYFOUND.txt","a+"); if(keys != NULL) { fprintf(keys,"PrivKey: %s\npubkey: %s\naddress: %s\n",hextemp,public_key_uncompressed_hex,public_address_uncompressed); fclose(keys); } printf("\nHIT!! PrivKey: %s\npubkey: %s\naddress: %s\n",hextemp,public_key_uncompressed_hex,public_address_uncompressed); pthread_mutex_unlock(&write_keys); free(public_key_uncompressed_hex); free(hextemp); } } free(public_address_uncompressed); } if( (FLAGCRYPTO & CRYPTO_ETH) != 0) { /* mpz_export((public_key_uncompressed+1),&longtemp,1,8,1,0,R.x); mpz_export((public_key_uncompressed+33),&longtemp,1,8,1,0,R.y); public_address_uncompressed = pubkeytopubaddress_eth(public_key_uncompressed+1,64); //printf("Testing for %s\n",public_address_uncompressed); r = bloom_check(&bloom,public_address_uncompressed,MAXLENGTHADDRESS); if(r) { r = searchbinary(addressTable,public_address_uncompressed,N); if(r) { hextemp = (char*) malloc(65); mpz_get_str(hextemp,16,key_mpz); public_key_uncompressed_hex = tohex(public_key_uncompressed+1,64); pthread_mutex_lock(&write_keys); keys = fopen("keys.txt","a+"); if(keys != NULL) { fprintf(keys,"PrivKey: %s\npubkey: %s\naddress: %s\n",hextemp,public_key_uncompressed_hex,public_address_uncompressed); fclose(keys); } printf("HIT!! PrivKey: %s\npubkey: %s\naddress: %s\n",hextemp,public_key_uncompressed_hex,public_address_uncompressed); pthread_mutex_unlock(&write_keys); free(public_key_uncompressed_hex); free(hextemp); } free(public_address_uncompressed); } */ } break; case MODE_RMD160: switch(FLAGSEARCH) { case SEARCH_UNCOMPRESS: publickeyhashrmd160_uncompress = publickeytohashrmd160(public_key_uncompressed,65); break; case SEARCH_COMPRESS: publickeyhashrmd160_compress = publickeytohashrmd160(public_key_compressed,33); break; case SEARCH_BOTH: publickeyhashrmd160_compress = publickeytohashrmd160(public_key_compressed,33); publickeyhashrmd160_uncompress = publickeytohashrmd160(public_key_uncompressed,65); break; } if(FLAGSEARCH == SEARCH_COMPRESS || FLAGSEARCH == SEARCH_BOTH){ r = bloom_check(&bloom,publickeyhashrmd160_compress,MAXLENGTHADDRESS); if(r) { r = searchbinary(addressTable,publickeyhashrmd160_compress,N); if(r) { found++; hextemp = key_mpz.GetBase16(); public_key_compressed_hex = tohex(public_key_compressed,33); pthread_mutex_lock(&write_keys); keys = fopen("KEYFOUNDKEYFOUND.txt","a+"); if(keys != NULL) { fprintf(keys,"PrivKey: %s\npubkey: %s\n",hextemp,public_key_compressed_hex); fclose(keys); } printf("\nHIT!! PrivKey: %s\npubkey: %s\n",hextemp,public_key_compressed_hex); pthread_mutex_unlock(&write_keys); free(public_key_compressed_hex); free(hextemp); } } free(publickeyhashrmd160_compress); } if(FLAGSEARCH == SEARCH_UNCOMPRESS || FLAGSEARCH == SEARCH_BOTH){ r = bloom_check(&bloom,publickeyhashrmd160_uncompress,MAXLENGTHADDRESS); if(r) { r = searchbinary(addressTable,publickeyhashrmd160_uncompress,N); if(r) { found++; hextemp = key_mpz.GetBase16(); public_key_uncompressed_hex = tohex(public_key_uncompressed,65); pthread_mutex_lock(&write_keys); keys = fopen("KEYFOUNDKEYFOUND.txt","a+"); if(keys != NULL) { fprintf(keys,"PrivKey: %s\npubkey: %s\n",hextemp,public_key_uncompressed_hex); fclose(keys); } printf("\nHIT!! PrivKey: %s\npubkey: %s\n",hextemp,public_key_uncompressed_hex); pthread_mutex_unlock(&write_keys); free(public_key_uncompressed_hex); free(hextemp); } } free(publickeyhashrmd160_uncompress); } break; case MODE_XPOINT: pts[j].x.Get32Bytes((unsigned char *)rawvalue); r = bloom_check(&bloom,rawvalue,MAXLENGTHADDRESS); if(r) { r = searchbinary(addressTable,rawvalue,N); if(r) { found++; hextemp = key_mpz.GetBase16(); R = secp->ComputePublicKey(&key_mpz); public_key_compressed = secp->GetPublicKeyHex(true,R); printf("\nHIT!! PrivKey: %s\npubkey: %s\n",hextemp,public_key_compressed); pthread_mutex_lock(&write_keys); keys = fopen("KEYFOUNDKEYFOUND.txt","a+"); if(keys != NULL) { fprintf(keys,"PrivKey: %s\npubkey: %s\n",hextemp,public_key_compressed); fclose(keys); } pthread_mutex_unlock(&write_keys); free(public_key_compressed); free(hextemp); } } break; } if(FLAGMODE == MODE_ADDRESS || FLAGMODE == MODE_RMD160) { switch(FLAGSEARCH) { case SEARCH_UNCOMPRESS: free(public_key_uncompressed); break; case SEARCH_COMPRESS: free(public_key_compressed); break; case SEARCH_BOTH: free(public_key_compressed); free(public_key_uncompressed); break; } } count++; if(count % DEBUGCOUNT == 0) { steps[thread_number]++; } key_mpz.AddOne(); } // Next start point (startP + GRP_SIZE*G) pp = startP; dy.ModSub(&_2Gn.y,&pp.y); _s.ModMulK1(&dy,&dx[i + 1]); _p.ModSquareK1(&_s); pp.x.ModNeg(); pp.x.ModAdd(&_p); pp.x.ModSub(&_2Gn.x); pp.y.ModSub(&_2Gn.x,&pp.x); pp.y.ModMulK1(&_s); pp.y.ModSub(&_2Gn.y); startP = pp; }while(count <= N_SECUENTIAL_MAX && continue_flag); } } while(continue_flag); ends[thread_number] = 1; return NULL; } void _swap(struct address_value *a,struct address_value *b) { struct address_value t; t = *a; *a = *b; *b = t; } void _sort(struct address_value *arr,int64_t n) { uint32_t depthLimit = ((uint32_t) ceil(log(n))) * 2; _introsort(arr,depthLimit,n); } void _introsort(struct address_value *arr,uint32_t depthLimit, int64_t n) { int64_t p; if(n > 1) { if(n <= 16) { _insertionsort(arr,n); } else { if(depthLimit == 0) { _myheapsort(arr,n); } else { p = _partition(arr,n); if(p > 0) _introsort(arr , depthLimit-1 , p); if(p < n) _introsort(&arr[p+1],depthLimit-1,n-(p+1)); } } } } void _insertionsort(struct address_value *arr, int64_t n) { int64_t j; int64_t i; struct address_value key; for(i = 1; i < n ; i++ ) { key = arr[i]; j= i-1; while(j >= 0 && memcmp(arr[j].value,key.value,20) > 0) { arr[j+1] = arr[j]; j--; } arr[j+1] = key; } } int64_t _partition(struct address_value *arr, int64_t n) { struct address_value pivot; int64_t r,left,right; char *hextemp; r = n/2; pivot = arr[r]; left = 0; right = n-1; do { while(left < right && memcmp(arr[left].value,pivot.value,20) <= 0 ) { left++; } while(right >= left && memcmp(arr[right].value,pivot.value,20) > 0) { right--; } if(left < right) { if(left == r || right == r) { if(left == r) { r = right; } if(right == r) { r = left; } } _swap(&arr[right],&arr[left]); } }while(left < right); if(right != r) { _swap(&arr[right],&arr[r]); } return right; } void _heapify(struct address_value *arr, int64_t n, int64_t i) { int64_t largest = i; int64_t l = 2 * i + 1; int64_t r = 2 * i + 2; if (l < n && memcmp(arr[l].value,arr[largest].value,20) > 0) largest = l; if (r < n && memcmp(arr[r].value,arr[largest].value,20) > 0) largest = r; if (largest != i) { _swap(&arr[i],&arr[largest]); _heapify(arr, n, largest); } } void _myheapsort(struct address_value *arr, int64_t n) { int64_t i; for ( i = (n / 2) - 1; i >= 0; i--) { _heapify(arr, n, i); } for ( i = n - 1; i > 0; i--) { _swap(&arr[0] , &arr[i]); _heapify(arr, i, 0); } } /* OK */ void bsgs_swap(struct bsgs_xvalue *a,struct bsgs_xvalue *b) { struct bsgs_xvalue t; t = *a; *a = *b; *b = t; } /* OK */ void bsgs_sort(struct bsgs_xvalue *arr,int64_t n) { uint32_t depthLimit = ((uint32_t) ceil(log(n))) * 2; bsgs_introsort(arr,depthLimit,n); } /* OK */ void bsgs_introsort(struct bsgs_xvalue *arr,uint32_t depthLimit, int64_t n) { int64_t p; if(n > 1) { if(n <= 16) { bsgs_insertionsort(arr,n); } else { if(depthLimit == 0) { bsgs_myheapsort(arr,n); } else { p = bsgs_partition(arr,n); if(p > 0) bsgs_introsort(arr , depthLimit-1 , p); if(p < n) bsgs_introsort(&arr[p+1],depthLimit-1,n-(p+1)); } } } } /* OK */ void bsgs_insertionsort(struct bsgs_xvalue *arr, int64_t n) { int64_t j; int64_t i; struct bsgs_xvalue key; for(i = 1; i < n ; i++ ) { key = arr[i]; j= i-1; while(j >= 0 && memcmp(arr[j].value,key.value,BSGS_XVALUE_RAM) > 0) { arr[j+1] = arr[j]; j--; } arr[j+1] = key; } } int64_t bsgs_partition(struct bsgs_xvalue *arr, int64_t n) { struct bsgs_xvalue pivot; int64_t r,left,right; char *hextemp; r = n/2; pivot = arr[r]; left = 0; right = n-1; do { while(left < right && memcmp(arr[left].value,pivot.value,BSGS_XVALUE_RAM) <= 0 ) { left++; } while(right >= left && memcmp(arr[right].value,pivot.value,BSGS_XVALUE_RAM) > 0) { right--; } if(left < right) { if(left == r || right == r) { if(left == r) { r = right; } if(right == r) { r = left; } } bsgs_swap(&arr[right],&arr[left]); } }while(left < right); if(right != r) { bsgs_swap(&arr[right],&arr[r]); } return right; } void bsgs_heapify(struct bsgs_xvalue *arr, int64_t n, int64_t i) { int64_t largest = i; int64_t l = 2 * i + 1; int64_t r = 2 * i + 2; if (l < n && memcmp(arr[l].value,arr[largest].value,BSGS_XVALUE_RAM) > 0) largest = l; if (r < n && memcmp(arr[r].value,arr[largest].value,BSGS_XVALUE_RAM) > 0) largest = r; if (largest != i) { bsgs_swap(&arr[i],&arr[largest]); bsgs_heapify(arr, n, largest); } } void bsgs_myheapsort(struct bsgs_xvalue *arr, int64_t n) { int64_t i; for ( i = (n / 2) - 1; i >= 0; i--) { bsgs_heapify(arr, n, i); } for ( i = n - 1; i > 0; i--) { bsgs_swap(&arr[0] , &arr[i]); bsgs_heapify(arr, i, 0); } } int bsgs_searchbinary(struct bsgs_xvalue *buffer,char *data,int64_t _N,uint64_t *r_value) { char *temp_read; int64_t min,max,half,current; int r = 0,rcmp; min = 0; current = 0; max = _N; half = _N; while(!r && half >= 1) { half = (max - min)/2; rcmp = memcmp(data+16,buffer[current+half].value,BSGS_XVALUE_RAM); if(rcmp == 0) { *r_value = buffer[current+half].index; r = 1; } else { if(rcmp < 0) { max = (max-half); } else { min = (min+half); } current = min; } } return r; } void *thread_process_bsgs(void *vargp) { FILE *filekey; struct tothread *tt; char xpoint_raw[32],*aux_c,*hextemp; Int base_key,keyfound; Point base_point,point_aux,point_aux2,point_found,BSGS_S,BSGS_Q,BSGS_Q_AMP; uint32_t i,j,k,r,salir,thread_number,bloom_counter =0; tt = (struct tothread *)vargp; thread_number = tt->nt; free(tt); pthread_mutex_lock(&bsgs_thread); /* we need to set our base_key to the current BSGS_CURRENT value*/ base_key.Set(&BSGS_CURRENT); BSGS_CURRENT.Add(&BSGS_N); /*Then add BSGS_N to BSGS_CURRENT*/ /* We do this in an atomic pthread_mutex operation to not affect others threads so BSGS_CURRENT is never the same between threads */ pthread_mutex_unlock(&bsgs_thread); /* while base_key is less than n_range_end then: */ while(base_key.IsLower(&n_range_end) ) { //gmp_printf("While cycle: base_key : %Zd < n_range_end: %Zd\n",base_key,n_range_end); if(FLAGQUIET == 0){ aux_c = base_key.GetBase16(); printf("\r[+] Thread %s ",aux_c); fflush(stdout); free(aux_c); THREADOUTPUT = 1; } /* Set base_point in to base_key * G base_point = base_key * G */ // printf("[D] bsgs_point_number %u\n",bsgs_point_number); base_point = secp->ComputePublicKey(&base_key); /* We are going to need -( base_point * G) point_aux = -( base_point * G) */ point_aux = secp->Negation(base_point); /* hextemp = secp->GetPublicKeyHex(false,point_aux); printf("point_aux %s\n",hextemp); free(hextemp); hextemp = secp->GetPublicKeyHex(false,base_point); printf("base_point %s\n",hextemp); free(hextemp); */ for(k = 0; k < bsgs_point_number ; k++) { if(bsgs_found[k] == 0) { /*reset main variabler before the do-while cicle*/ /* Main cycle for every a in 0 to bsgs_m */ salir = 0; i = 0; BSGS_Q = secp->AddDirect(OriginalPointsBSGS[k],point_aux); BSGS_S.Set(BSGS_Q); do { /* if(i == 52428 || i == 0 || i == 1) { aux_c = secp->GetPublicKeyHex(false,BSGS_S); hextemp = secp->GetPublicKeyHex(false,BSGS_AMP[i]); printf("\r[d] Debug: %s : %u\n",aux_c,i); printf("[d] Debug: BSGS_AMP %s : %u\n",hextemp,i); free(aux_c); free(hextemp); } */ /* We need to test individually every point in BSGS_Q */ /*Extract BSGS_S.x into xpoint_raw*/ BSGS_S.x.Get32Bytes((unsigned char*)xpoint_raw); /* Lookup for the xpoint_raw into the bloom filter*/ r = bloom_check(&bloom_bP[((unsigned char)xpoint_raw[0])],xpoint_raw,32); if(r) { bloom_counter++; /* Lookup for the xpoint_raw into the full sorted list*/ //r = bsgs_searchbinary(bPtable,xpoint_raw,bsgs_m,&j); r = bsgs_secondcheck(&base_key,i,k,&keyfound); if(r) { hextemp = keyfound.GetBase16(); printf("\n[+] Thread Key found privkey %s\n",hextemp); point_aux2 = secp->ComputePublicKey(&keyfound); aux_c = secp->GetPublicKeyHex(OriginalPointsBSGScompressed[k],point_aux2); printf("[+] Publickey %s\n",aux_c); pthread_mutex_lock(&write_keys); filekey = fopen("KEYFOUNDKEYFOUND.txt","a"); if(filekey != NULL) { fprintf(filekey,"Key found privkey %s\nPublickey %s\n",hextemp,aux_c); fclose(filekey); } pthread_mutex_unlock(&write_keys); free(hextemp); free(aux_c); bsgs_found[k] = 1; salir = 1; for(j = 0; j < bsgs_point_number && salir; j++) { salir &= bsgs_found[j]; } if(salir) { printf("All points were found\n"); exit(0); } } } BSGS_Q_AMP = secp->AddDirect(BSGS_Q,BSGS_AMP[i]); BSGS_S.Set(BSGS_Q_AMP); i++; }while( i < bsgs_aux && !bsgs_found[k]); } //end if }// End for steps[thread_number]++; pthread_mutex_lock(&bsgs_thread); base_key.Set(&BSGS_CURRENT); BSGS_CURRENT.Add(&BSGS_N); pthread_mutex_unlock(&bsgs_thread); if(FLAGDEBUG ) printf("%u of %" PRIu64 "\n",bloom_counter,(uint64_t)(bsgs_aux*bsgs_point_number)); bloom_counter = 0; } ends[thread_number] = 1; return NULL; } void *thread_process_bsgs_random(void *vargp) { FILE *filekey; struct tothread *tt; char xpoint_raw[32],*aux_c,*hextemp; Int base_key,keyfound,n_range_random; Point base_point,point_aux,point_aux2,point_found,BSGS_S,BSGS_Q,BSGS_Q_AMP; uint32_t i,j,k,r,salir,thread_number,bloom_counter = 0; tt = (struct tothread *)vargp; thread_number = tt->nt; free(tt); pthread_mutex_lock(&bsgs_thread); /* | Start Range | End Range | None | 1 | EC.N | -b bit | Min bit value |Max bit value | -r A:B | A | B | */ // set base_key = random(end_range - start range) base_key.Rand(&n_range_start,&n_range_end); pthread_mutex_unlock(&bsgs_thread); /* while base_key is less than n_range_end then: */ while(base_key.IsLower(&n_range_end)) { //gmp_printf("While cycle: base_key : %Zd < n_range_end: %Zd\n",base_key,n_range_end); if(FLAGQUIET == 0){ aux_c = base_key.GetBase16(); printf("\r[+] Thread %s",aux_c); fflush(stdout); free(aux_c); THREADOUTPUT = 1; } /* Set base_point in to base_key * G base_point = base_key * G */ base_point = secp->ComputePublicKey(&base_key); /* We are going to need -( base_point * G) point_aux = -( base_point * G) */ point_aux = secp->Negation(base_point); /* We need to test individually every point in BSGS_Q */ for(k = 0; k < bsgs_point_number ; k++) { if(bsgs_found[k] == 0) { /*reset main variables before the do-while cicle*/ salir = 0; i = 0; /* Main cycle for every a in 0 to bsgs_aux */ BSGS_Q = secp->AddDirect(OriginalPointsBSGS[k],point_aux); BSGS_S.Set(BSGS_Q); do { BSGS_S.x.Get32Bytes((unsigned char*)xpoint_raw); r = bloom_check(&bloom_bP[((unsigned char)xpoint_raw[0])],xpoint_raw,32); if(r) { bloom_counter++; /* Lookup for the xpoint_raw into the full sorted list*/ r = bsgs_secondcheck(&base_key,i,k,&keyfound); if(r) { hextemp = keyfound.GetBase16(); printf("\n[+] Thread Key found privkey %s\n",hextemp); point_aux2 = secp->ComputePublicKey(&keyfound); aux_c = secp->GetPublicKeyHex(OriginalPointsBSGScompressed[k],point_aux2); printf("[+] Publickey %s\n",aux_c); pthread_mutex_lock(&write_keys); filekey = fopen("KEYFOUNDKEYFOUND.txt","a"); if(filekey != NULL) { fprintf(filekey,"Key found privkey %s\nPublickey %s\n",hextemp,aux_c); fclose(filekey); } free(hextemp); free(aux_c); pthread_mutex_unlock(&write_keys); bsgs_found[k] = 1; salir = 1; for(j = 0; j < bsgs_point_number && salir; j++) { salir &= bsgs_found[j]; } if(salir) { printf("All points were found\n"); exit(0); } } } BSGS_Q_AMP = secp->AddDirect(BSGS_AMP[i],BSGS_Q); BSGS_S.Set(BSGS_Q_AMP); i++; } while( i < bsgs_aux && !bsgs_found[k]); } //End if } // End for with k bsgs_point_number steps[thread_number]++; pthread_mutex_lock(&bsgs_thread); base_key.Rand(&n_range_start,&n_range_end); pthread_mutex_unlock(&bsgs_thread); if(FLAGDEBUG ) printf("%u of %" PRIu64 "\n",bloom_counter,(uint64_t)(bsgs_aux*bsgs_point_number)); bloom_counter = 0; } ends[thread_number] = 1; return NULL; } /* The bsgs_secondcheck function is made to perform a second BSGS search in a Range of less size. This funtion is made with the especific purpouse to USE a smaller bPTable in RAM. This new and small bPtable is around ~ squareroot( K *squareroot(N)) */ int bsgs_secondcheck(Int *start_range,uint32_t a,uint32_t k_index,Int *privatekey) { uint64_t j = 0; int i = 0,found = 0,r = 0; Int base_key; Point base_point,point_aux; Point BSGS_Q, BSGS_S,BSGS_Q_AMP; char pubkey[131],xpoint_str[65],xpoint_raw[32],*hexvalue; base_key.Set(&BSGS_M); base_key.Mult((uint64_t) a); base_key.Add(start_range); base_point = secp->ComputePublicKey(&base_key); point_aux = secp->Negation(base_point); BSGS_S = secp->AddDirect(OriginalPointsBSGS[k_index],point_aux); BSGS_Q.Set(BSGS_S); do { BSGS_S.x.Get32Bytes((unsigned char *)xpoint_raw); r = bloom_check(&bloom_bPx2nd,xpoint_raw,32); if(r) { r = bsgs_searchbinary(bPtable,xpoint_raw,bsgs_m2,&j); if(r) { privatekey->Set(&BSGS_M2); privatekey->Mult((uint64_t)i); privatekey->Add((uint64_t)(j+1)); privatekey->Add(&base_key); point_aux = secp->ComputePublicKey(privatekey); if(point_aux.x.IsEqual(&OriginalPointsBSGS[k_index].x)) { found = 1; } else { privatekey->Set(&BSGS_M2); privatekey->Mult((uint64_t)i); privatekey->Sub((uint64_t)(j+1)); privatekey->Add(&base_key); point_aux = secp->ComputePublicKey(privatekey); if(point_aux.x.IsEqual(&OriginalPointsBSGS[k_index].x)) { found = 1; } } } } BSGS_Q_AMP = secp->AddDirect(BSGS_Q,BSGS_AMP2[i]); BSGS_S.Set(BSGS_Q_AMP); i++; }while(i < 20 && !found); return found; } void *thread_bPloadFile(void *vargp) { FILE *fd; char rawvalue[32],*hextemp; struct bPload *tt; uint32_t j; uint64_t i; tt = (struct bPload *)vargp; fd = fopen(precalculated_p_filename,"rb"); if(fd == NULL) { fprintf(stderr,"Can't open file\n"); exit(0); } i = tt->from -1; j = tt->from -1; if(fseek(fd,(uint64_t)(i*32),SEEK_SET) != 0) { fprintf(stderr,"Can't seek the file at index %" PRIu64 ", offset %" PRIu64 "\n",i,(uint64_t)(i*32)); exit(0); } do { if(fread(rawvalue,1,32,fd) == 32) { if(i < bsgs_m2) { memcpy(bPtable[j].value,rawvalue+16,BSGS_XVALUE_RAM); bPtable[j].index = j; bloom_add(&bloom_bPx2nd, rawvalue, BSGS_BUFFERXPOINTLENGTH); j++; } bloom_add(&bloom_bP[((uint8_t)rawvalue[0])], rawvalue ,BSGS_BUFFERXPOINTLENGTH); i++; tt->counter++; } else { fprintf(stderr,"Can't read the file seen you have less items that the amount needed\n"); exit(0); } } while( i < tt->to ); pthread_exit(NULL); } void sleep_ms(int milliseconds) { // cross-platform sleep function #ifdef WIN32 Sleep(milliseconds); #elif _POSIX_C_SOURCE >= 199309L struct timespec ts; ts.tv_sec = milliseconds / 1000; ts.tv_nsec = (milliseconds % 1000) * 1000000; nanosleep(&ts, NULL); #else if (milliseconds >= 1000) sleep(milliseconds / 1000); usleep((milliseconds % 1000) * 1000); #endif } void *thread_pub2rmd(void *vargp) { FILE *fd; Int key_mpz; struct tothread *tt; uint64_t i,limit,j; char digest160[20]; char digest256[32]; char *temphex; int thread_number,r; int pub2rmd_continue = 1; struct publickey pub; limit = 0xFFFFFFFF; tt = (struct tothread *)vargp; thread_number = tt->nt; do { if(FLAGRANDOM){ key_mpz.Rand(&n_range_start,&n_range_diff); } else { if(n_range_start.IsLower(&n_range_end)) { pthread_mutex_lock(&write_random); key_mpz.Set(&n_range_start); n_range_start.Add(N_SECUENTIAL_MAX); pthread_mutex_unlock(&write_random); } else { pub2rmd_continue = 0; } } if(pub2rmd_continue) { key_mpz.Get32Bytes(pub.X.data8); pub.parity = 0x02; pub.X.data32[7] = 0; if(FLAGQUIET == 0) { temphex = tohex((char*)&pub,33); printf("\r[+] Thread %s",temphex); fflush(stdout); THREADOUTPUT = 1; } for(i = 0 ; i < limit ; i++) { pub.parity = 0x02; sha256((char*)&pub, 33, digest256); RMD160Data((const unsigned char*)digest256,32, digest160); r = bloom_check(&bloom,digest160,MAXLENGTHADDRESS); if(r) { r = searchbinary(addressTable,digest160,N); if(r) { temphex = tohex((char*)&pub,33); printf("\nHit: Publickey found %s\n",temphex); fd = fopen("KEYFOUNDKEYFOUND.txt","a+"); if(fd != NULL) { pthread_mutex_lock(&write_keys); fprintf(fd,"Publickey found %s\n",temphex); fclose(fd); pthread_mutex_unlock(&write_keys); } else { fprintf(stderr,"\nPublickey found %s\nbut the file can't be open\n",temphex); exit(0); } free(temphex); } } pub.parity = 0x03; sha256((char*)&pub, 33, digest256); RMD160Data((const unsigned char*)digest256,32, digest160); r = bloom_check(&bloom,digest160,MAXLENGTHADDRESS); if(r) { r = searchbinary(addressTable,digest160,N); if(r) { temphex = tohex((char*)&pub,33); printf("\nHit: Publickey found %s\n",temphex); fd = fopen("KEYFOUNDKEYFOUND.txt","a+"); if(fd != NULL) { pthread_mutex_lock(&write_keys); fprintf(fd,"Publickey found %s\n",temphex); fclose(fd); pthread_mutex_unlock(&write_keys); } else { fprintf(stderr,"\nPublickey found %s\nbut the file can't be open\n",temphex); exit(0); } free(temphex); } } pub.X.data32[7]++; if(pub.X.data32[7] % DEBUGCOUNT == 0) { steps[thread_number]++; } } /* End for */ } /* End if */ } while(pub2rmd_continue); ends[thread_number] = 1; return NULL; } void init_generator() { Point g = secp->G; Gn.reserve(CPU_GRP_SIZE / 2); Gn[0] = g; g = secp->DoubleDirect(g); Gn[1] = g; for(int i = 2; i < CPU_GRP_SIZE / 2; i++) { g = secp->AddDirect(g,secp->G); Gn[i] = g; } _2Gn = secp->DoubleDirect(Gn[CPU_GRP_SIZE / 2 - 1]); } void *thread_bPload(void *vargp) { char *hextemp,rawvalue[32]; struct bPload *tt; uint64_t j_counter,i_counter; uint64_t i,j,nbStep; IntGroup *grp = new IntGroup(CPU_GRP_SIZE / 2 + 1); Point startP; Int dx[CPU_GRP_SIZE / 2 + 1]; Point pts[CPU_GRP_SIZE]; Int dy; Int dyn; Int _s; Int _p; Point pp; Point pn; int hLength = (CPU_GRP_SIZE / 2 - 1); tt = (struct bPload *)vargp; Int km(tt->from); if(FLAGDEBUG) printf("[D] thread %i from %" PRIu64 " to %" PRIu64 "\n",tt->threadid,tt->from,tt->to); i_counter = tt->from -1; j_counter = tt->from -1; nbStep = (tt->to - (tt->from-1)) / CPU_GRP_SIZE; if( ((tt->to - (tt->from-1)) % CPU_GRP_SIZE ) != 0) { nbStep++; } km.Add((uint64_t)(CPU_GRP_SIZE / 2)); startP = secp->ComputePublicKey(&km); grp->Set(dx); for(uint64_t s=0;s<nbStep;s++) { for(i = 0; i < hLength; i++) { dx[i].ModSub(&Gn[i].x,&startP.x); } dx[i].ModSub(&Gn[i].x,&startP.x); // For the first point dx[i + 1].ModSub(&_2Gn.x,&startP.x);// For the next center point // Grouped ModInv grp->ModInv(); // We use the fact that P + i*G and P - i*G has the same deltax, so the same inverse // We compute key in the positive and negative way from the center of the group // center point pts[CPU_GRP_SIZE / 2] = startP; //Center point for(i = 0; i<hLength; i++) { pp = startP; pn = startP; // P = startP + i*G dy.ModSub(&Gn[i].y,&pp.y); _s.ModMulK1(&dy,&dx[i]); // s = (p2.y-p1.y)*inverse(p2.x-p1.x); _p.ModSquareK1(&_s); // _p = pow2(s) pp.x.ModNeg(); pp.x.ModAdd(&_p); pp.x.ModSub(&Gn[i].x); // rx = pow2(s) - p1.x - p2.x; #if 0 pp.y.ModSub(&Gn[i].x,&pp.x); pp.y.ModMulK1(&_s); pp.y.ModSub(&Gn[i].y); // ry = - p2.y - s*(ret.x-p2.x); #endif // P = startP - i*G , if (x,y) = i*G then (x,-y) = -i*G dyn.Set(&Gn[i].y); dyn.ModNeg(); dyn.ModSub(&pn.y); _s.ModMulK1(&dyn,&dx[i]); // s = (p2.y-p1.y)*inverse(p2.x-p1.x); _p.ModSquareK1(&_s); // _p = pow2(s) pn.x.ModNeg(); pn.x.ModAdd(&_p); pn.x.ModSub(&Gn[i].x); // rx = pow2(s) - p1.x - p2.x; #if 0 pn.y.ModSub(&Gn[i].x,&pn.x); pn.y.ModMulK1(&_s); pn.y.ModAdd(&Gn[i].y); // ry = - p2.y - s*(ret.x-p2.x); #endif pts[CPU_GRP_SIZE / 2 + (i + 1)] = pp; pts[CPU_GRP_SIZE / 2 - (i + 1)] = pn; } // First point (startP - (GRP_SZIE/2)*G) pn = startP; dyn.Set(&Gn[i].y); dyn.ModNeg(); dyn.ModSub(&pn.y); _s.ModMulK1(&dyn,&dx[i]); _p.ModSquareK1(&_s); pn.x.ModNeg(); pn.x.ModAdd(&_p); pn.x.ModSub(&Gn[i].x); #if 0 pn.y.ModSub(&Gn[i].x,&pn.x); pn.y.ModMulK1(&_s); pn.y.ModAdd(&Gn[i].y); #endif pts[0] = pn; for(j=0;j<CPU_GRP_SIZE;j++) { pts[j].x.Get32Bytes((unsigned char*)rawvalue); if(i_counter < bsgs_m2) { memcpy(bPtable[j_counter].value,rawvalue+16,BSGS_XVALUE_RAM); bPtable[j_counter].index = j_counter; bloom_add(&bloom_bPx2nd, rawvalue, BSGS_BUFFERXPOINTLENGTH); j_counter++; } if(i_counter < tt->to) { bloom_add(&bloom_bP[((uint8_t)rawvalue[0])], rawvalue ,BSGS_BUFFERXPOINTLENGTH); tt->counter++; i_counter++; } } // Next start point (startP + GRP_SIZE*G) pp = startP; dy.ModSub(&_2Gn.y,&pp.y); _s.ModMulK1(&dy,&dx[i + 1]); _p.ModSquareK1(&_s); pp.x.ModNeg(); pp.x.ModAdd(&_p); pp.x.ModSub(&_2Gn.x); pp.y.ModSub(&_2Gn.x,&pp.x); pp.y.ModMulK1(&_s); pp.y.ModSub(&_2Gn.y); startP = pp; } delete grp; pthread_exit(NULL); }
29.894871
2,995
0.597316
[ "vector" ]
6c898357ff812c95b39828f131d749e7ebd62785
1,552
h
C
llvm/passes/include/cfi/cfi.h
vusec/probeguard
37d2a554e7a757cbb6f6f87ebd27744765b32f3a
[ "BSD-2-Clause" ]
7
2019-04-17T03:29:21.000Z
2020-05-25T10:24:10.000Z
llvm/passes/include/cfi/cfi.h
vusec/probeguard
37d2a554e7a757cbb6f6f87ebd27744765b32f3a
[ "BSD-2-Clause" ]
null
null
null
llvm/passes/include/cfi/cfi.h
vusec/probeguard
37d2a554e7a757cbb6f6f87ebd27744765b32f3a
[ "BSD-2-Clause" ]
2
2019-04-27T12:17:33.000Z
2021-11-19T23:15:43.000Z
#ifndef CFI_H #define CFI_H #include <pass.h> #if LLVM_VERSION >= 37 #include <llvm/IR/Verifier.h> #include <llvm/IR/InstIterator.h> #define DEBUG_TYPE "cfi" #else #include <llvm/Analysis/Verifier.h> #include <llvm/Support/InstIterator.h> #endif #define CFI_INIT_FUNC "cfi_shadow_init" #define CFI_FWD_EDGE_CHECK_FUNC "cfi_fwd_edge_check" #define CFI_BK_EDGE_FUNC_ENTRY "cfi_bk_shadow_func_entry" #define CFI_BK_EDGE_FUNC_EXIT "cfi_bk_shadow_func_exit" using namespace llvm; namespace llvm { class CFIPass : public ModulePass { public: static char ID; CFIPass(); virtual bool runOnModule(Module &M); private: Module *M; std::vector<CallInst*> insertedFwdChecks; std::vector<CallInst*> insertedBkCheckFuncEntries; std::vector<CallInst*> insertedBkCheckFuncExits; std::set<Function*> indirectlyCalledFuncs; std::set<CallInst*> indirectCallInsts; Function *cfiFwdEdgeCheckHook; Function *cfiBkEdgeFuncEntryHook; Function *cfiBkEdgeFuncExitHook; Function *cfiInitHook; void getHooks(); bool insertCFIInitHook(Function *mainFunc); CallInst* insertFwdCFI(CallInst *CI, Instruction *nextInst); CallInst* insertBkFuncEntryHook(Instruction *nextInst); CallInst* insertBkFuncExitHook(ReturnInst *returnInst); // inline bool is_indirect_call(CallSite &CS); inline bool is_indirect_call(CallInst *CI); bool addFwdEdgeChecks(); bool addBkEdgeChecks(); void inlineTheChecks(std::vector<CallInst*> &insertedInsts); }; } #endif
25.866667
66
0.736469
[ "vector" ]
6c8b588ae356bffd0e94c98628874d413e9b61f9
6,426
c
C
openmp/mdpic3/extrasmd3/mdfield3_f.c
gcasabona/cuda
064cfa02398e2402c113d45153d7ba36ae930f7e
[ "W3C" ]
51
2017-03-22T04:06:03.000Z
2022-01-18T22:48:51.000Z
openmp/mdpic3/extrasmd3/mdfield3_f.c
gcasabona/cuda
064cfa02398e2402c113d45153d7ba36ae930f7e
[ "W3C" ]
null
null
null
openmp/mdpic3/extrasmd3/mdfield3_f.c
gcasabona/cuda
064cfa02398e2402c113d45153d7ba36ae930f7e
[ "W3C" ]
25
2017-02-22T05:21:32.000Z
2022-01-02T14:53:19.000Z
/* C Library for Skeleton 3D Darwin PIC Code field diagnostics */ /* Wrappers for calling the Fortran routines from a C main program */ #include <complex.h> void mpotp3_(float complex *q, float complex *pot, float complex *ffc, float *we, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv, int *nxhd, int *nyhd, int *nzhd); void mdivf3_(float complex *f, float complex *df, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv); void mgradf3_(float complex *df, float complex *f, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv); void mcurlf3_(float complex *f, float complex *g, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv); void mapotp33_(float complex *cu, float complex *axyz, float complex *ffc, float *ci, float *wm, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv, int *nxhd, int *nyhd, int *nzhd); void msmooth3_(float complex *q, float complex *qs, float complex *ffc, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv, int *nxhd, int *nyhd, int *nzhd); void msmooth33_(float complex *cu, float complex *cus, float complex *ffc, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv, int *nxhd, int *nyhd, int *nzhd); void rdmodes3_(float complex *pot, float complex *pott, int *nx, int *ny, int *nz, int *modesx, int *modesy, int *modesz, int *nxvh, int *nyv, int *nzv, int *modesxd, int *modesyd, int *modeszd); void wrmodes3_(float complex *pot, float complex *pott, int *nx, int *ny, int *nz, int *modesx, int *modesy, int *modesz, int *nxvh, int *nyv, int *nzv, int *modesxd, int *modesyd, int *modeszd); void rdvmodes3_(float complex *vpot, float complex *vpott, int *nx, int *ny, int *nz, int *modesx, int *modesy, int *modesz, int *ndim, int *nxvh, int *nyv, int *nzv, int *modesxd, int *modesyd, int *modeszd); void wrvmodes3_(float complex *vpot, float complex *vpott, int *nx, int *ny, int *nz, int *modesx, int *modesy, int *modesz, int *ndim, int *nxvh, int *nyv, int *nzv, int *modesxd, int *modesyd, int *modeszd); /* Interfaces to C */ /*--------------------------------------------------------------------*/ void cmpotp3(float complex q[], float complex pot[], float complex ffc[], float *we, int nx, int ny, int nz, int nxvh, int nyv, int nzv, int nxhd, int nyhd, int nzhd) { mpotp3_(q,pot,ffc,we,&nx,&ny,&nz,&nxvh,&nyv,&nzv,&nxhd,&nyhd,&nzhd); return; } /*--------------------------------------------------------------------*/ void cmdivf3(float complex f[], float complex df[], int nx, int ny, int nz, int nxvh, int nyv, int nzv) { mdivf3_(f,df,&nx,&ny,&nz,&nxvh,&nyv,&nzv); return; } /*--------------------------------------------------------------------*/ void cgmradf3(float complex df[], float complex f[], int nx, int ny, int nz, int nxvh, int nyv, int nzv) { mgradf3_(df,f,&nx,&ny,&nz,&nxvh,&nyv,&nzv); return; } /*--------------------------------------------------------------------*/ void cmcurlf3(float complex f[], float complex g[], int nx, int ny, int nz, int nxvh, int nyv, int nzv) { mcurlf3_(f,g,&nx,&ny,&nz,&nxvh,&nyv,&nzv); return; } /*--------------------------------------------------------------------*/ void cmapotp33(float complex cu[], float complex axyz[], float complex ffc[], float ci, float *wm, int nx, int ny, int nz, int nxvh, int nyv, int nzv, int nxhd, int nyhd, int nzhd) { mapotp33_(cu,axyz,ffc,&ci,wm,&nx,&ny,&nz,&nxvh,&nyv,&nzv,&nxhd,&nyhd, &nzhd); return; } /*--------------------------------------------------------------------*/ void cmsmooth3(float complex q[], float complex qs[], float complex ffc[], int nx, int ny, int nz, int nxvh, int nyv, int nzv, int nxhd, int nyhd, int nzhd) { msmooth3_(q,qs,ffc,&nx,&ny,&nz,&nxvh,&nyv,&nzv,&nxhd,&nyhd,&nzhd); return; } /*--------------------------------------------------------------------*/ void cmsmooth33(float complex cu[], float complex cus[], float complex ffc[], int nx, int ny, int nz, int nxvh, int nyv, int nzv, int nxhd, int nyhd, int nzhd) { msmooth33_(cu,cus,ffc,&nx,&ny,&nz,&nxvh,&nyv,&nzv,&nxhd,&nyhd,&nzhd); return; } /*--------------------------------------------------------------------*/ void crdmodes3(float complex pot[], float complex pott[], int nx, int ny, int nz, int modesx, int modesy, int modesz, int nxvh, int nyv, int nzv, int modesxd, int modesyd, int modeszd) { rdmodes3_(pot,pott,&nx,&ny,&nz,&modesx,&modesy,&modesz,&nxvh,&nyv, &nzv,&modesxd,&modesyd,&modeszd); return; } /*--------------------------------------------------------------------*/ void cwrmodes3(float complex pot[], float complex pott[], int nx, int ny, int nz, int modesx, int modesy, int modesz, int nxvh, int nyv, int nzv, int modesxd, int modesyd, int modeszd) { wrmodes3_(pot,pott,&nx,&ny,&nz,&modesx,&modesy,&modesz,&nxvh,&nyv, &nzv,&modesxd,&modesyd,&modeszd); return; } /*--------------------------------------------------------------------*/ void crdvmodes3(float complex vpot[], float complex vpott[], int nx, int ny, int nz, int modesx, int modesy, int modesz, int ndim, int nxvh, int nyv, int nzv, int modesxd, int modesyd, int modeszd) { rdvmodes3_(vpot,vpott,&nx,&ny,&nz,&modesx,&modesy,&modesz,&ndim, &nxvh,&nyv,&nzv,&modesxd,&modesyd,&modeszd); return; } /*--------------------------------------------------------------------*/ void cwrvmodes3(float complex vpot[], float complex vpott[], int nx, int ny, int nz, int modesx, int modesy, int modesz, int ndim, int nxvh, int nyv, int nzv, int modesxd, int modesyd, int modeszd) { wrvmodes3_(vpot,vpott,&nx,&ny,&nz,&modesx,&modesy,&modesz,&ndim, &nxvh,&nyv,&nzv,&modesxd,&modesyd,&modeszd); return; }
42.84
72
0.504669
[ "3d" ]
6c8ffc48e7380b684c03a244a860756b8cb69f80
1,127
h
C
config.h
UuqV/HomeworkServerHack
ceaababd8f098c7c0d2144d90ae99a4fc9817a19
[ "BSD-3-Clause" ]
null
null
null
config.h
UuqV/HomeworkServerHack
ceaababd8f098c7c0d2144d90ae99a4fc9817a19
[ "BSD-3-Clause" ]
null
null
null
config.h
UuqV/HomeworkServerHack
ceaababd8f098c7c0d2144d90ae99a4fc9817a19
[ "BSD-3-Clause" ]
null
null
null
#ifndef __CONFIG_H__ #define __CONFIG_H__ #include "grading/TestCase.h" const std::string assignment_message = ""; // Submission parameters const int max_submissions = 200; const int submission_penalty = 0; // Compile-time parameters const int max_cputime = 2; // in seconds, per test case const int max_submission_size = 10000; // in KB, entire submission (could be zip file) const int max_output_size = 1000; // in KB, per created output file // Grading parameters const int total_pts = 3; const int auto_pts = 3; const int ta_pts = 0; const int extra_credit_pts = 0; std::vector<TestCase> testcases { TestCase::MakeTest( "MyAnacondaDontWantNone", "python answer > output.txt", "python student > output.txt", TestCasePoints(3) new TestCaseComparison(&myersDiffbyLinebyChar, "output.txt", "output.txt", 1 ), new TestCaseComparison(&warnIfNotEmpty,"STDOUT.txt","STDOUT","", 0), new TestCaseComparison(&warnIfNotEmpty,"STDERR.txt","STDERR","", 0) ) };
26.833333
86
0.637977
[ "vector" ]
6c9b9ed496949c15a976d6e436a2ec7504da5622
4,958
h
C
DSPFilters4JUCEDemo/JuceLibraryCode/modules/juce_core/threads/juce_WaitableEvent.h
rc-h/dspfilters4juce
60b32a3af7eb89289f89e01db1239e312544ec2c
[ "MIT" ]
10
2017-07-16T04:50:47.000Z
2022-02-14T06:10:45.000Z
DSPFilters4JUCEDemo/JuceLibraryCode/modules/juce_core/threads/juce_WaitableEvent.h
rc-h/dspfilters4juce
60b32a3af7eb89289f89e01db1239e312544ec2c
[ "MIT" ]
199
2016-07-28T07:30:48.000Z
2017-10-14T06:15:40.000Z
UI/JuceLibraryCode/modules/juce_core/threads/juce_WaitableEvent.h
subutai-io/launcher
d8397995e18200b12d60781ed485af04f70bff03
[ "Apache-2.0" ]
3
2017-11-07T14:44:14.000Z
2021-03-16T02:45:57.000Z
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2016 - ROLI Ltd. Permission is granted to use this software under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license/ 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 ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC 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. ----------------------------------------------------------------------------- To release a closed-source product which uses other parts of JUCE not licensed under the ISC terms, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ #ifndef JUCE_WAITABLEEVENT_H_INCLUDED #define JUCE_WAITABLEEVENT_H_INCLUDED //============================================================================== /** Allows threads to wait for events triggered by other threads. A thread can call wait() on a WaitableObject, and this will suspend the calling thread until another thread wakes it up by calling the signal() method. */ class JUCE_API WaitableEvent { public: //============================================================================== /** Creates a WaitableEvent object. The object is initially in an unsignalled state. @param manualReset If this is false, the event will be reset automatically when the wait() method is called. If manualReset is true, then once the event is signalled, the only way to reset it will be by calling the reset() method. */ explicit WaitableEvent (bool manualReset = false) noexcept; /** Destructor. If other threads are waiting on this object when it gets deleted, this can cause nasty errors, so be careful! */ ~WaitableEvent() noexcept; //============================================================================== /** Suspends the calling thread until the event has been signalled. This will wait until the object's signal() method is called by another thread, or until the timeout expires. After the event has been signalled, this method will return true and if manualReset was set to false in the WaitableEvent's constructor, then the event will be reset. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative value will cause it to wait forever. @returns true if the object has been signalled, false if the timeout expires first. @see signal, reset */ bool wait (int timeOutMilliseconds = -1) const noexcept; //============================================================================== /** Wakes up any threads that are currently waiting on this object. If signal() is called when nothing is waiting, the next thread to call wait() will return immediately and reset the signal. If the WaitableEvent is manual reset, all current and future threads that wait upon this object will be woken, until reset() is explicitly called. If the WaitableEvent is automatic reset, and one or more threads is waiting upon the object, then one of them will be woken up. If no threads are currently waiting, then the next thread to call wait() will be woken up. As soon as a thread is woken, the signal is automatically reset. @see wait, reset */ void signal() const noexcept; //============================================================================== /** Resets the event to an unsignalled state. If it's not already signalled, this does nothing. */ void reset() const noexcept; private: //============================================================================== #if JUCE_WINDOWS void* handle; #else mutable pthread_cond_t condition; mutable pthread_mutex_t mutex; mutable bool triggered, manualReset; #endif JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WaitableEvent) }; #endif // JUCE_WAITABLEEVENT_H_INCLUDED
40.975207
104
0.582493
[ "object" ]
6cab57cde15eab90527f57a330125e850b485880
10,486
c
C
workfiles/Codes/checkImplementation.c
asifajrof/CSE316_Term_Project_Tetris
a7a42c195fbbf7d2aac05cdee066180e5a412308
[ "MIT" ]
null
null
null
workfiles/Codes/checkImplementation.c
asifajrof/CSE316_Term_Project_Tetris
a7a42c195fbbf7d2aac05cdee066180e5a412308
[ "MIT" ]
null
null
null
workfiles/Codes/checkImplementation.c
asifajrof/CSE316_Term_Project_Tetris
a7a42c195fbbf7d2aac05cdee066180e5a412308
[ "MIT" ]
null
null
null
#include <stdlib.h> #include<time.h> typedef int bool; #define FALSE 0x00 #define TRUE 0xFF #define UP -1 #define DOWN 1 #define LEFT -1 #define RIGHT 1 typedef enum { O, I, L, J, S, Z, T } shape_type; char row[] = {1, 2, 4, 8, 16, 32, 64, 128}; int rand_val[100] = {6 ,1 ,3 ,4 ,0 ,4 ,6 ,6 ,4 ,1 , 5 ,3 ,2 ,6 ,4 ,0 ,4 ,5 ,2 ,1 , 5 ,4 ,4 ,4 ,6 ,0 ,3 ,0 ,6 ,3 , 4 ,3 ,6 ,0 ,1 ,2 ,4 ,2 ,2 ,3 ,5 , 4 ,3 ,2 ,2 ,3 ,6 ,0 ,6 ,5 ,1 ,6 , 1 ,1 ,2 ,5 ,2 ,3 ,0 ,1 ,1 ,5 ,4 ,1, 5 ,6 ,3 ,5 ,5 ,3 ,3 ,2 ,5 ,1 ,6 ,6 ,1 , 5 ,3 ,1 ,2 ,5 ,4 ,4 ,3 ,1 ,4 ,0 ,3 ,3 , 4 ,0 ,2 ,0 ,0 ,3 ,2 ,2 ,1 ,1 }; bool shape_O_array[4][4]={{FALSE, TRUE, TRUE, FALSE}, {FALSE, TRUE, TRUE, FALSE}, {FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE}}; bool shape_I_array[4][4]={{FALSE, TRUE, FALSE, FALSE}, {FALSE, TRUE, FALSE, FALSE}, {FALSE, TRUE, FALSE, FALSE}, {FALSE, TRUE, FALSE, FALSE}}; bool shape_L_array[4][4]={{FALSE, TRUE, FALSE, FALSE}, {FALSE, TRUE, FALSE, FALSE}, {FALSE, TRUE, TRUE, FALSE}, {FALSE, FALSE, FALSE, FALSE}}; bool shape_J_array[4][4]={{FALSE, FALSE, TRUE, FALSE}, {FALSE, FALSE, TRUE, FALSE}, {FALSE, TRUE, TRUE, FALSE}, {FALSE, FALSE, FALSE, FALSE}}; bool shape_S_array[4][4]={{FALSE, TRUE, TRUE, FALSE}, { TRUE, TRUE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE}}; bool shape_Z_array[4][4]={{ TRUE, TRUE, FALSE, FALSE}, {FALSE, TRUE, TRUE, FALSE}, {FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE}}; bool shape_T_array[4][4]={{ TRUE, TRUE, TRUE, FALSE}, {FALSE, TRUE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE}}; bool current_display[16][8]={{FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}}; bool temp_shape_array[4][4]; bool current_shape_array[4][4]; int current_R = 0; int current_C = 2; int current_shape = -1; void row_shift(int length, bool shape_array[][4], int direction, int shift_count) //no wrap around { for(int counter=0; counter<shift_count; counter++){ int index = 0; if (direction>0){ index = length-1; } for (int i=0; i<length-1; i++){ for (int j=0; j<length; j++){ shape_array[index][j] = shape_array[index-direction][j]; } index = index - direction; } for (int j=0; j<length; j++){ shape_array[index][j] = FALSE; } } } void col_shift(int length, bool shape_array[][4], int direction, int shift_count) //no wrap around { for(int counter=0; counter<shift_count; counter++){ int index = 0; if (direction>0){ index = length-1; } for (int j=0; j<length-1; j++){ for (int i=0; i<length; i++){ shape_array[i][index] = shape_array[i][index-direction]; } index = index - direction; } for (int i=0; i<length; i++){ shape_array[i][index] = FALSE; } } } void align_top_left_justify(bool shape_array[][4]) { //top left justify shape after rotation //top int shift_count = -1; int shift_direction = UP; for (int i=0; i<4; i++){ for (int j=0; j<4; j++){ if(shape_array[i][j] == TRUE){ shift_count = i; break; } } if (shift_count != -1){ break; } } row_shift(4, shape_array,shift_direction,shift_count); //left justify int width = 0; int w1 = -1, w2 = -1; for (int j=0; j<4; j++){ for (int i=0; i<4; i++){ if(shape_array[i][j] == TRUE){ if(w1 == -1){ w1 = j; } w2 = j; break; } } if((w1 != -1) && (w2<j)){ break; } } width = w2 - w1 + 1; if(width == 1 || width == 2){ shift_count = w1 - 1; } else if(width == 3 || width == 4){ shift_count = w1 - 0; } if(shift_count<0){ shift_count = -shift_count; shift_direction = RIGHT; } else{ shift_direction = LEFT; } col_shift(4,shape_array,shift_direction,shift_count); } void rotate_shape(bool shape_array[][4]) { //rotate clockwise. //transpose, mirror. bool temp[4][4]; for (int i=0; i<4; i++){ for (int j=0; j<4; j++){ temp[i][j] = shape_array[i][j]; //copy } } for (int i=0; i<4; i++){ for (int j=0; j<4; j++){ temp_shape_array[i][j] = temp[j][i]; //transpose } } for (int i=0; i<4; i++){ for (int j=0; j<4; j++){ temp[i][j] = temp_shape_array[i][j]; } } for (int i=0; i<4; i++){ for (int j=0; j<4; j++){ temp_shape_array[i][j] = temp[i][3-j]; //mirror } } align_top_left_justify(temp_shape_array); } bool check_valid(int row, int col, bool shape_array[][4]) { for(int i=0; i<4; i++){ for (int j=0; j<4; j++){ if(shape_array[i][j] == TRUE){ if((row+i) > 15){ //bottom row reached //invalid return FALSE; } if((col+j) < 0 || (col+j) > 7){ //left/right col reached //invalid return FALSE; } if(current_display[row+i][col+j] == TRUE){ //position filled //invalid return FALSE; } } } } return TRUE; } void set_shape(bool shape_array[][4]) { for(int i=0; i<4; i++){ for (int j=0; j<4; j++){ if(shape_array[i][j] == TRUE){ current_display[current_R+i][current_C+j] = shape_array[i][j]; } } } //_delay_ms(50); } void remove_shape(bool shape_array[][4]) { for(int i=0; i<4; i++){ for (int j=0; j<4; j++){ if(shape_array[i][j] == TRUE){ current_display[current_R+i][current_C+j] = FALSE; } } } //_delay_ms(100); } int get_col(int row) { int col_value = 0x00; for (int j=0; j<8; j++){ if(current_display[row][j] == TRUE){ col_value |= 1<<(j); } } return col_value; } void remove_row(int row){ //shift rows downwards from row to 1 for(int i = row ; i > 0 ; i--){ for(int j = 0 ; j< 8; j++){ current_display[row][j] = current_display[row-1][j]; } } //put false in row 0 for(int i = 0 ; i < 8; i++){ current_display[0][i] = FALSE; } } void update_score1x(){ int temp ; for(int i = 0 ; i < 16 ; i++){ temp = TRUE; for(int j = 0 ; j < 8; j++){ temp &= current_display[i][j]; } if(temp == TRUE){ remove_row(i); } } } void update_score2x(){ int temp ; for(int i = 0 ; i < 12 ; i++){ temp = TRUE; int ii = i; for(int t = 0; t < 4; t++){ for(int j = 0 ; j < 8; j++){ temp &= current_display[ii][j]; } ii++; } if(temp == TRUE){ for(int t = 0; t < 4; t++){ remove_row(i); } } } } void go_left(){ remove_shape(current_shape_array); if(current_shape == -1){ return; } else if(check_valid(current_R, current_C-1 , current_shape_array) == TRUE){ current_C--; } set_shape(current_shape_array); } void go_right(){ remove_shape(current_shape_array); if(current_shape == -1){ return; } else if(check_valid(current_R, current_C+1 , current_shape_array) == TRUE){ current_C++; } set_shape(current_shape_array); } void go_down(){ //printf("%d %d \n", current_R ,current_C); remove_shape(current_shape_array); if(current_shape == -1){ return; } else if(check_valid(current_R+1, current_C , current_shape_array) == TRUE){ current_R++; } else{ set_shape(current_shape_array); current_C = 2; current_R = 0; for(int i = 0 ; i < 4; i++){ for(int j = 0; j < 4; j++){ current_shape_array[i][j] = FALSE; } } current_shape = -1; } set_shape(current_shape_array); } void generate_shape(){ //int shape = 0; int shape = rand()%7; current_shape = shape; //printf("Shape : %d\n", shape); if( shape == 0){ for(int i = 0 ; i < 4; i++){ for(int j = 0; j < 4; j++){ current_shape_array[i][j] = shape_O_array[i][j]; } } } else if(shape == 1){ for(int i = 0 ; i < 4; i++){ for(int j = 0; j < 4; j++){ current_shape_array[i][j] = shape_I_array[i][j]; } } } else if(shape == 2){ for(int i = 0 ; i < 4; i++){ for(int j = 0; j < 4; j++){ current_shape_array[i][j] = shape_L_array[i][j]; } } } else if(shape == 3){ for(int i = 0 ; i < 4; i++){ for(int j = 0; j < 4; j++){ current_shape_array[i][j] = shape_J_array[i][j]; } } } else if(shape == 4){ for(int i = 0 ; i < 4; i++){ for(int j = 0; j < 4; j++){ current_shape_array[i][j] = shape_S_array[i][j]; } } } else if(shape == 5){ for(int i = 0 ; i < 4; i++){ for(int j = 0; j < 4; j++){ current_shape_array[i][j] = shape_Z_array[i][j]; } } } else if(shape == 6){ for(int i = 0 ; i < 4; i++){ for(int j = 0; j < 4; j++){ current_shape_array[i][j] = shape_T_array[i][j]; } } } } void printMatrix(){ for(int i = 0 ; i < 16; i++){ for(int j = 0; j < 8; j++){ if(current_display[i][j]== TRUE){ printf("1 "); } else printf("0 "); } printf("\n"); } } void check_over(){ for(int i = 0; i < 8; i++){ if(current_display[0][i] == TRUE){ return 1; } } return 0; } int main(void) { srand(time(0)); int i = 0; while (1){ if(current_R == 0 && current_C == 2){ generate_shape(); if(check_valid(0 , 2 , current_shape_array) == TRUE) set_shape(current_shape_array); else{ printf("Game Over!"); return 0; } } if(i == 1){ go_left(); //_delay_ms(200); } if(i == 2){ go_right(); //_delay_ms(200); } if(i == 3){ go_down(); //_delay_ms(200); } if(i == 4){ rotate_shape(current_shape_array); remove_shape(current_shape_array); if(check_valid(current_R, current_C, temp_shape_array) == TRUE){ for(int i = 0 ; i < 4; i++){ for(int j = 0; j < 4; j++){ current_shape_array[i][j] = temp_shape_array[i][j]; } } } set_shape(current_shape_array); } update_score2x(); update_score1x(); printMatrix(); go_down(); scanf("%d", &i); } }
22.216102
98
0.561892
[ "shape" ]
6cae19c020249b3c99483f5da9dce9dc40086f76
47,398
c
C
sm64ex-nightly/src/game/paintings.c
alex-free/sm64ex-creator
e7089df69fb43f266b2165078d94245b33b8e72a
[ "Intel", "X11", "Unlicense" ]
2
2022-03-12T08:27:53.000Z
2022-03-12T18:26:06.000Z
sm64ex-nightly/src/game/paintings.c
alex-free/sm64ex-creator
e7089df69fb43f266b2165078d94245b33b8e72a
[ "Intel", "X11", "Unlicense" ]
null
null
null
sm64ex-nightly/src/game/paintings.c
alex-free/sm64ex-creator
e7089df69fb43f266b2165078d94245b33b8e72a
[ "Intel", "X11", "Unlicense" ]
null
null
null
#include <PR/ultratypes.h> #include "sm64.h" #include "area.h" #include "engine/graph_node.h" #include "engine/surface_collision.h" #include "game_init.h" #include "geo_misc.h" #include "levels/castle_inside/header.h" #include "levels/hmc/header.h" #include "levels/ttm/header.h" #include "mario.h" #include "memory.h" #include "moving_texture.h" #include "object_list_processor.h" #include "paintings.h" #include "save_file.h" #include "segment2.h" /** * @file paintings.c * * Implements the rippling painting effect. Paintings are GraphNodes that exist without being connected * to any particular object. * * Paintings are defined in level data. Look at levels/castle_inside/painting.inc.c for examples. * * The ripple effect uses data that is split into several parts: * The mesh positions are generated from a base mesh. See seg2_painting_triangle_mesh near the * bottom of bin/segment2.c * * The lighting for the ripple is also generated from a base table, seg2_painting_mesh_neighbor_tris * in bin/segment2.c * * Each painting's texture uses yet another table to map its texture to the mesh. * These maps are in level data, see levels/castle_inside/painting.inc.c for example. * * Finally, each painting has two display lists, normal and rippling, which are defined in the same * level data file as the Painting itself. See levels/castle_inside/painting.inc.c. * * * Painting state machine: * Paintings spawn in the PAINTING_IDLE state * From IDLE, paintings can change to PAINTING_RIPPLE or PAINTING_ENTERED * - This state checks for ENTERED because if Mario waits long enough, a PROXIMITY painting could * reset to IDLE * * Paintings in the PAINTING_RIPPLE state are passively rippling. * For RIPPLE_TRIGGER_PROXIMITY paintings, this means Mario bumped the wall in front of the * painting. * * Paintings that use RIPPLE_TRIGGER_CONTINUOUS try to transition to this state as soon as possible, * usually when Mario enters the room. * * A PROXIMITY painting will automatically reset to IDLE if its ripple magnitude becomes small * enough. * * Paintings in the PAINTING_ENTERED state have been entered by Mario. * A CONTINUOUS painting will automatically reset to RIPPLE if its ripple magnitude becomes small * enough. */ /** * Triggers a passive ripple on the left side of the painting. */ #define RIPPLE_LEFT 0x20 /** * Triggers a passive ripple in the middle the painting. */ #define RIPPLE_MIDDLE 0x10 /** * Triggers a passive ripple on the right side of the painting. */ #define RIPPLE_RIGHT 0x8 /** * Triggers an entry ripple on the left side of the painting. */ #define ENTER_LEFT 0x4 /** * Triggers an entry ripple in the middle of the painting. */ #define ENTER_MIDDLE 0x2 /** * Triggers an entry ripple on the right side of the painting. */ #define ENTER_RIGHT 0x1 /** * Use the 1/4th part of the painting that is nearest to Mario's current floor. */ #define NEAREST_4TH 30 /** * Use Mario's relative x position. * @see painting_mario_x */ #define MARIO_X 40 /** * Use the x center of the painting. */ #define MIDDLE_X 50 /** * Use Mario's relative y position. * @see painting_mario_y */ #define MARIO_Y 60 /** * Use Mario's relative z position. * @see painting_mario_z */ #define MARIO_Z 70 /** * Use the y center of the painting. */ #define MIDDLE_Y 80 /** * Does nothing to the timer. * Why -56 instead of false? Who knows. */ #define DONT_RESET -56 /** * Reset the timer to 0. */ #define RESET_TIMER 100 /// A copy of the type of floor Mario is standing on. s16 gPaintingMarioFloorType; // A copy of Mario's position f32 gPaintingMarioXPos; f32 gPaintingMarioYPos; f32 gPaintingMarioZPos; /** * When a painting is rippling, this mesh is generated each frame using the Painting's parameters. * * This mesh only contains the vertex positions and normals. * Paintings use an additional array to map textures to the mesh. */ struct PaintingMeshVertex *gPaintingMesh; /** * The painting's surface normals, used to approximate each of the vertex normals (for gouraud shading). */ Vec3f *gPaintingTriNorms; /** * The painting that is currently rippling. Only one painting can be rippling at once. */ struct Painting *gRipplingPainting; /** * Whether the DDD painting is moved forward, should being moving backwards, or has already moved backwards. */ s8 gDddPaintingStatus; struct Painting *sHmcPaintings[] = { &cotmc_painting, NULL, }; struct Painting *sInsideCastlePaintings[] = { &bob_painting, &ccm_painting, &wf_painting, &jrb_painting, &lll_painting, &ssl_painting, &hmc_painting, &ddd_painting, &wdw_painting, &thi_tiny_painting, &ttm_painting, &ttc_painting, &sl_painting, &thi_huge_painting, NULL, }; struct Painting *sTtmPaintings[] = { &ttm_slide_painting, NULL, }; struct Painting **sPaintingGroups[] = { sHmcPaintings, sInsideCastlePaintings, sTtmPaintings, }; s16 gPaintingUpdateCounter = 1; s16 gLastPaintingUpdateCounter = 0; /** * Stop paintings in paintingGroup from rippling if their id is different from *idptr. */ void stop_other_paintings(s16 *idptr, struct Painting *paintingGroup[]) { s16 index; s16 id = *idptr; index = 0; while (paintingGroup[index] != NULL) { struct Painting *painting = segmented_to_virtual(paintingGroup[index]); // stop all rippling except for the selected painting if (painting->id != id) { painting->state = 0; } index++; } } /** * @return Mario's y position inside the painting (bounded). */ f32 painting_mario_y(struct Painting *painting) { //! Unnecessary use of double constants // Add 50 to make the ripple closer to Mario's center of mass. f32 relY = gPaintingMarioYPos - painting->posY + 50.0; if (relY < 0.0) { relY = 0.0; } else if (relY > painting->size) { relY = painting->size; } return relY; } /** * @return Mario's z position inside the painting (bounded). */ f32 painting_mario_z(struct Painting *painting) { f32 relZ = painting->posZ - gPaintingMarioZPos; if (relZ < 0.0) { relZ = 0.0; } else if (relZ > painting->size) { relZ = painting->size; } return relZ; } /** * @return The y origin for the ripple, based on ySource. * For floor paintings, the z-axis is treated as y. */ f32 painting_ripple_y(struct Painting *painting, s8 ySource) { switch (ySource) { case MARIO_Y: return painting_mario_y(painting); // normal wall paintings break; case MARIO_Z: return painting_mario_z(painting); // floor paintings use X and Z break; case MIDDLE_Y: return painting->size / 2.0; // some concentric ripples don't care about Mario break; } } /** * Return the quarter of the painting that is closest to the floor Mario entered. */ f32 painting_nearest_4th(struct Painting *painting) { f32 firstQuarter = painting->size / 4.0; // 1/4 of the way across the painting f32 secondQuarter = painting->size / 2.0; // 1/2 of the way across the painting f32 thirdQuarter = painting->size * 3.0 / 4.0; // 3/4 of the way across the painting if (painting->floorEntered & RIPPLE_LEFT) { return firstQuarter; } else if (painting->floorEntered & RIPPLE_MIDDLE) { return secondQuarter; } else if (painting->floorEntered & RIPPLE_RIGHT) { return thirdQuarter; // Same as ripple floors. } else if (painting->floorEntered & ENTER_LEFT) { return firstQuarter; } else if (painting->floorEntered & ENTER_MIDDLE) { return secondQuarter; } else if (painting->floorEntered & ENTER_RIGHT) { return thirdQuarter; } } /** * @return Mario's x position inside the painting (bounded). */ f32 painting_mario_x(struct Painting *painting) { f32 relX = gPaintingMarioXPos - painting->posX; if (relX < 0.0) { relX = 0.0; } else if (relX > painting->size) { relX = painting->size; } return relX; } /** * @return The x origin for the ripple, based on xSource. */ f32 painting_ripple_x(struct Painting *painting, s8 xSource) { switch (xSource) { case NEAREST_4TH: // normal wall paintings return painting_nearest_4th(painting); break; case MARIO_X: // horizontally placed paintings use X and Z return painting_mario_x(painting); break; case MIDDLE_X: // concentric rippling may not care about Mario return painting->size / 2.0; break; } } /** * Set the painting's state, causing it to start a passive ripple or a ripple from Mario entering. * * @param state The state to enter * @param painting,paintingGroup identifies the painting that is changing state * @param xSource,ySource what to use for the x and y origin of the ripple * @param resetTimer if 100, set the timer to 0 */ void painting_state(s8 state, struct Painting *painting, struct Painting *paintingGroup[], s8 xSource, s8 ySource, s8 resetTimer) { // make sure no other paintings are rippling stop_other_paintings(&painting->id, paintingGroup); // use a different set of variables depending on the state switch (state) { case PAINTING_RIPPLE: painting->currRippleMag = painting->passiveRippleMag; painting->rippleDecay = painting->passiveRippleDecay; painting->currRippleRate = painting->passiveRippleRate; painting->dispersionFactor = painting->passiveDispersionFactor; break; case PAINTING_ENTERED: painting->currRippleMag = painting->entryRippleMag; painting->rippleDecay = painting->entryRippleDecay; painting->currRippleRate = painting->entryRippleRate; painting->dispersionFactor = painting->entryDispersionFactor; break; } painting->state = state; painting->rippleX = painting_ripple_x(painting, xSource); painting->rippleY = painting_ripple_y(painting, ySource); gPaintingMarioYEntry = gPaintingMarioYPos; // Because true or false would be too simple... if (resetTimer == RESET_TIMER) { painting->rippleTimer = 0.0f; } gRipplingPainting = painting; } /** * Idle update function for wall paintings that use RIPPLE_TRIGGER_PROXIMITY. */ void wall_painting_proximity_idle(struct Painting *painting, struct Painting *paintingGroup[]) { // Check for Mario triggering a ripple if (painting->floorEntered & RIPPLE_LEFT) { painting_state(PAINTING_RIPPLE, painting, paintingGroup, NEAREST_4TH, MARIO_Y, RESET_TIMER); } else if (painting->floorEntered & RIPPLE_MIDDLE) { painting_state(PAINTING_RIPPLE, painting, paintingGroup, NEAREST_4TH, MARIO_Y, RESET_TIMER); } else if (painting->floorEntered & RIPPLE_RIGHT) { painting_state(PAINTING_RIPPLE, painting, paintingGroup, NEAREST_4TH, MARIO_Y, RESET_TIMER); // Check for Mario entering } else if (painting->floorEntered & ENTER_LEFT) { painting_state(PAINTING_ENTERED, painting, paintingGroup, NEAREST_4TH, MARIO_Y, RESET_TIMER); } else if (painting->floorEntered & ENTER_MIDDLE) { painting_state(PAINTING_ENTERED, painting, paintingGroup, NEAREST_4TH, MARIO_Y, RESET_TIMER); } else if (painting->floorEntered & ENTER_RIGHT) { painting_state(PAINTING_ENTERED, painting, paintingGroup, NEAREST_4TH, MARIO_Y, RESET_TIMER); } } /** * Rippling update function for wall paintings that use RIPPLE_TRIGGER_PROXIMITY. */ void wall_painting_proximity_rippling(struct Painting *painting, struct Painting *paintingGroup[]) { if (painting->floorEntered & ENTER_LEFT) { painting_state(PAINTING_ENTERED, painting, paintingGroup, NEAREST_4TH, MARIO_Y, RESET_TIMER); } else if (painting->floorEntered & ENTER_MIDDLE) { painting_state(PAINTING_ENTERED, painting, paintingGroup, NEAREST_4TH, MARIO_Y, RESET_TIMER); } else if (painting->floorEntered & ENTER_RIGHT) { painting_state(PAINTING_ENTERED, painting, paintingGroup, NEAREST_4TH, MARIO_Y, RESET_TIMER); } } /** * Idle update function for wall paintings that use RIPPLE_TRIGGER_CONTINUOUS. */ void wall_painting_continuous_idle(struct Painting *painting, struct Painting *paintingGroup[]) { // Check for Mario triggering a ripple if (painting->floorEntered & RIPPLE_LEFT) { painting_state(PAINTING_RIPPLE, painting, paintingGroup, MIDDLE_X, MIDDLE_Y, RESET_TIMER); } else if (painting->floorEntered & RIPPLE_MIDDLE) { painting_state(PAINTING_RIPPLE, painting, paintingGroup, MIDDLE_X, MIDDLE_Y, RESET_TIMER); } else if (painting->floorEntered & RIPPLE_RIGHT) { painting_state(PAINTING_RIPPLE, painting, paintingGroup, MIDDLE_X, MIDDLE_Y, RESET_TIMER); // Check for Mario entering } else if (painting->floorEntered & ENTER_LEFT) { painting_state(PAINTING_ENTERED, painting, paintingGroup, NEAREST_4TH, MARIO_Y, RESET_TIMER); } else if (painting->floorEntered & ENTER_MIDDLE) { painting_state(PAINTING_ENTERED, painting, paintingGroup, NEAREST_4TH, MARIO_Y, RESET_TIMER); } else if (painting->floorEntered & ENTER_RIGHT) { painting_state(PAINTING_ENTERED, painting, paintingGroup, NEAREST_4TH, MARIO_Y, RESET_TIMER); } } /** * Rippling update function for wall paintings that use RIPPLE_TRIGGER_CONTINUOUS. */ void wall_painting_continuous_rippling(struct Painting *painting, struct Painting *paintingGroup[]) { if (painting->floorEntered & ENTER_LEFT) { painting_state(PAINTING_ENTERED, painting, paintingGroup, NEAREST_4TH, MARIO_Y, DONT_RESET); } else if (painting->floorEntered & ENTER_MIDDLE) { painting_state(PAINTING_ENTERED, painting, paintingGroup, NEAREST_4TH, MARIO_Y, DONT_RESET); } else if (painting->floorEntered & ENTER_RIGHT) { painting_state(PAINTING_ENTERED, painting, paintingGroup, NEAREST_4TH, MARIO_Y, DONT_RESET); } } /** * Idle update function for floor paintings that use RIPPLE_TRIGGER_PROXIMITY. * * No floor paintings use RIPPLE_TRIGGER_PROXIMITY in the game. */ void floor_painting_proximity_idle(struct Painting *painting, struct Painting *paintingGroup[]) { // Check for Mario triggering a ripple if (painting->floorEntered & RIPPLE_LEFT) { painting_state(PAINTING_RIPPLE, painting, paintingGroup, MARIO_X, MARIO_Z, RESET_TIMER); } else if (painting->floorEntered & RIPPLE_MIDDLE) { painting_state(PAINTING_RIPPLE, painting, paintingGroup, MARIO_X, MARIO_Z, RESET_TIMER); } else if (painting->floorEntered & RIPPLE_RIGHT) { painting_state(PAINTING_RIPPLE, painting, paintingGroup, MARIO_X, MARIO_Z, RESET_TIMER); // Only check for Mario entering if he jumped below the surface } else if (painting->marioWentUnder) { if (painting->currFloor & ENTER_LEFT) { painting_state(PAINTING_ENTERED, painting, paintingGroup, MARIO_X, MARIO_Z, RESET_TIMER); } else if (painting->currFloor & ENTER_MIDDLE) { painting_state(PAINTING_ENTERED, painting, paintingGroup, MARIO_X, MARIO_Z, RESET_TIMER); } else if (painting->currFloor & ENTER_RIGHT) { painting_state(PAINTING_ENTERED, painting, paintingGroup, MARIO_X, MARIO_Z, RESET_TIMER); } } } /** * Rippling update function for floor paintings that use RIPPLE_TRIGGER_PROXIMITY. * * No floor paintings use RIPPLE_TRIGGER_PROXIMITY in the game. */ void floor_painting_proximity_rippling(struct Painting *painting, struct Painting *paintingGroup[]) { if (painting->marioWentUnder) { if (painting->currFloor & ENTER_LEFT) { painting_state(PAINTING_ENTERED, painting, paintingGroup, MARIO_X, MARIO_Z, RESET_TIMER); } else if (painting->currFloor & ENTER_MIDDLE) { painting_state(PAINTING_ENTERED, painting, paintingGroup, MARIO_X, MARIO_Z, RESET_TIMER); } else if (painting->currFloor & ENTER_RIGHT) { painting_state(PAINTING_ENTERED, painting, paintingGroup, MARIO_X, MARIO_Z, RESET_TIMER); } } } /** * Idle update function for floor paintings that use RIPPLE_TRIGGER_CONTINUOUS. * * Both floor paintings (HMC and CotMC) are hidden behind a door, which hides the ripple's start up. * The floor just inside the doorway is RIPPLE_LEFT, so the painting starts rippling as soon as Mario * enters the room. */ void floor_painting_continuous_idle(struct Painting *painting, struct Painting *paintingGroup[]) { // Check for Mario triggering a ripple if (painting->floorEntered & RIPPLE_LEFT) { painting_state(PAINTING_RIPPLE, painting, paintingGroup, MIDDLE_X, MIDDLE_Y, RESET_TIMER); } else if (painting->floorEntered & RIPPLE_MIDDLE) { painting_state(PAINTING_RIPPLE, painting, paintingGroup, MIDDLE_X, MIDDLE_Y, RESET_TIMER); } else if (painting->floorEntered & RIPPLE_RIGHT) { painting_state(PAINTING_RIPPLE, painting, paintingGroup, MIDDLE_X, MIDDLE_Y, RESET_TIMER); // Check for Mario entering } else if (painting->currFloor & ENTER_LEFT) { painting_state(PAINTING_ENTERED, painting, paintingGroup, MARIO_X, MARIO_Z, RESET_TIMER); } else if (painting->currFloor & ENTER_MIDDLE) { painting_state(PAINTING_ENTERED, painting, paintingGroup, MARIO_X, MARIO_Z, RESET_TIMER); } else if (painting->currFloor & ENTER_RIGHT) { painting_state(PAINTING_ENTERED, painting, paintingGroup, MARIO_X, MARIO_Z, RESET_TIMER); } } /** * Rippling update function for floor paintings that use RIPPLE_TRIGGER_CONTINUOUS. */ void floor_painting_continuous_rippling(struct Painting *painting, struct Painting *paintingGroup[]) { if (painting->marioWentUnder) { if (painting->currFloor & ENTER_LEFT) { painting_state(PAINTING_ENTERED, painting, paintingGroup, MARIO_X, MARIO_Z, DONT_RESET); } else if (painting->currFloor & ENTER_MIDDLE) { painting_state(PAINTING_ENTERED, painting, paintingGroup, MARIO_X, MARIO_Z, DONT_RESET); } else if (painting->currFloor & ENTER_RIGHT) { painting_state(PAINTING_ENTERED, painting, paintingGroup, MARIO_X, MARIO_Z, DONT_RESET); } } } /** * Check for Mario entering one of the special floors associated with the painting. */ void painting_update_floors(struct Painting *painting) { s16 paintingId = painting->id; s8 rippleLeft = 0; s8 rippleMiddle = 0; s8 rippleRight = 0; s8 enterLeft = 0; s8 enterMiddle = 0; s8 enterRight = 0; /* The area in front of every painting in the game (except HMC and CotMC, which *\ |* act a little differently) is made up of 3 special floor triangles with special *| |* (unique) surface types. This code checks which surface Mario is currently on *| \* and sets a bitfield accordingly. */ // check if Mario's current floor is one of the special floors if (gPaintingMarioFloorType == paintingId * 3 + SURFACE_PAINTING_WOBBLE_A6) { rippleLeft = RIPPLE_LEFT; } if (gPaintingMarioFloorType == paintingId * 3 + SURFACE_PAINTING_WOBBLE_A7) { rippleMiddle = RIPPLE_MIDDLE; } if (gPaintingMarioFloorType == paintingId * 3 + SURFACE_PAINTING_WOBBLE_A8) { rippleRight = RIPPLE_RIGHT; } if (gPaintingMarioFloorType == paintingId * 3 + SURFACE_PAINTING_WARP_D3) { enterLeft = ENTER_LEFT; } if (gPaintingMarioFloorType == paintingId * 3 + SURFACE_PAINTING_WARP_D4) { enterMiddle = ENTER_MIDDLE; } if (gPaintingMarioFloorType == paintingId * 3 + SURFACE_PAINTING_WARP_D5) { enterRight = ENTER_RIGHT; } painting->lastFloor = painting->currFloor; // at most 1 of these will be nonzero; painting->currFloor = rippleLeft + rippleMiddle + rippleRight + enterLeft + enterMiddle + enterRight; // floorEntered is true iff currFloor is true and lastFloor is false // (Mario just entered the floor on this frame) painting->floorEntered = (painting->lastFloor ^ painting->currFloor) & painting->currFloor; painting->marioWasUnder = painting->marioIsUnder; // Check if Mario has fallen below the painting (used for floor paintings) if (gPaintingMarioYPos < painting->posY) { painting->marioIsUnder = TRUE; } else { painting->marioIsUnder = FALSE; } // Mario "went under" if he was not under last frame, but is under now painting->marioWentUnder = (painting->marioWasUnder ^ painting->marioIsUnder) & painting->marioIsUnder; } /** * Update the ripple's timer and magnitude, making it propagate outwards. * * Automatically changes the painting back to IDLE state (or RIPPLE for continuous paintings) if the * ripple's magnitude becomes small enough. */ void painting_update_ripple_state(struct Painting *painting) { if (gPaintingUpdateCounter != gLastPaintingUpdateCounter) { painting->currRippleMag *= painting->rippleDecay; //! After ~6.47 days, paintings with RIPPLE_TRIGGER_CONTINUOUS will increment this to //! 16777216 (1 << 24), at which point it will freeze (due to floating-point //! imprecision?) and the painting will stop rippling. This happens to HMC, DDD, and //! CotMC. This happens on Wii VC. Untested on N64 and Wii U VC. painting->rippleTimer += 1.0; } if (painting->rippleTrigger == RIPPLE_TRIGGER_PROXIMITY) { // if the painting is barely rippling, make it stop rippling if (painting->currRippleMag <= 1.0) { painting->state = PAINTING_IDLE; gRipplingPainting = NULL; } } else if (painting->rippleTrigger == RIPPLE_TRIGGER_CONTINUOUS) { // if the painting is doing the entry ripple but the ripples are as small as those from the // passive ripple, make it do a passive ripple // If Mario goes below the surface but doesn't warp, the painting will eventually reset. if (painting->state == PAINTING_ENTERED && painting->currRippleMag <= painting->passiveRippleMag) { painting->state = PAINTING_RIPPLE; painting->currRippleMag = painting->passiveRippleMag; painting->rippleDecay = painting->passiveRippleDecay; painting->currRippleRate = painting->passiveRippleRate; painting->dispersionFactor = painting->passiveDispersionFactor; } } } /** * @return the ripple function at posX, posY * note that posX and posY correspond to a point on the face of the painting, not actual axes */ s16 calculate_ripple_at_point(struct Painting *painting, f32 posX, f32 posY) { /// Controls the peaks of the ripple. f32 rippleMag = painting->currRippleMag; /// Controls the ripple's frequency f32 rippleRate = painting->currRippleRate; /// Controls how fast the ripple spreads f32 dispersionFactor = painting->dispersionFactor; /// How far the ripple has spread f32 rippleTimer = painting->rippleTimer; /// x and y ripple origin f32 rippleX = painting->rippleX; f32 rippleY = painting->rippleY; f32 distanceToOrigin; f32 rippleDistance; posX *= painting->size / PAINTING_SIZE; posY *= painting->size / PAINTING_SIZE; distanceToOrigin = sqrtf((posX - rippleX) * (posX - rippleX) + (posY - rippleY) * (posY - rippleY)); // A larger dispersionFactor makes the ripple spread slower rippleDistance = distanceToOrigin / dispersionFactor; if (rippleTimer < rippleDistance) { // if the ripple hasn't reached the point yet, make the point magnitude 0 return 0; } else { // use a cosine wave to make the ripple go up and down, // scaled by the painting's ripple magnitude f32 rippleZ = rippleMag * cosf(rippleRate * (2 * M_PI) * (rippleTimer - rippleDistance)); // round it to an int and return it return round_float(rippleZ); } } /** * If movable, return the ripple function at (posX, posY) * else return 0 */ s16 ripple_if_movable(struct Painting *painting, s16 movable, s16 posX, s16 posY) { s16 rippleZ = 0; if (movable) { rippleZ = calculate_ripple_at_point(painting, posX, posY); } return rippleZ; } /** * Allocates and generates a mesh for the rippling painting effect by modifying the passed in `mesh` * based on the painting's current ripple state. * * The `mesh` table describes the location of mesh vertices, whether they move when rippling, and what * triangles they belong to. * * The static mesh passed in is organized into two lists. This function only uses the first list, * painting_calculate_triangle_normals below uses the second one. * * The first list describes the vertices in this format: * numVertices * v0 x, v0 y, movable * ... * vN x, vN y, movable * Where x and y are from 0 to PAINTING_SIZE, movable is 0 or 1. * * The mesh used in game, seg2_painting_triangle_mesh, is in bin/segment2.c. */ void painting_generate_mesh(struct Painting *painting, s16 *mesh, s16 numTris) { s16 i; gPaintingMesh = mem_pool_alloc(gEffectsMemoryPool, numTris * sizeof(struct PaintingMeshVertex)); if (gPaintingMesh == NULL) { } // accesses are off by 1 since the first entry is the number of vertices for (i = 0; i < numTris; i++) { gPaintingMesh[i].pos[0] = mesh[i * 3 + 1]; gPaintingMesh[i].pos[1] = mesh[i * 3 + 2]; // The "z coordinate" of each vertex in the mesh is either 1 or 0. Instead of being an // actual coordinate, it just determines whether the vertex moves gPaintingMesh[i].pos[2] = ripple_if_movable(painting, mesh[i * 3 + 3], gPaintingMesh[i].pos[0], gPaintingMesh[i].pos[1]); } } /** * Calculate the surface normals of each triangle in the generated ripple mesh. * * The static mesh passed in is organized into two lists. This function uses the second list, * painting_generate_mesh above uses the first one. * * The second list in `mesh` describes the mesh's triangles in this format: * numTris * tri0 v0, tri0 v1, tri0 v2 * ... * triN v0, triN v1, triN v2 * Where each v0, v1, v2 is an index into the first list in `mesh`. * * The mesh used in game, seg2_painting_triangle_mesh, is in bin/segment2.c. */ void painting_calculate_triangle_normals(s16 *mesh, s16 numVtx, s16 numTris) { s16 i; gPaintingTriNorms = mem_pool_alloc(gEffectsMemoryPool, numTris * sizeof(Vec3f)); if (gPaintingTriNorms == NULL) { } for (i = 0; i < numTris; i++) { s16 tri = numVtx * 3 + i * 3 + 2; // Add 2 because of the 2 length entries preceding the list s16 v0 = mesh[tri]; s16 v1 = mesh[tri + 1]; s16 v2 = mesh[tri + 2]; f32 x0 = gPaintingMesh[v0].pos[0]; f32 y0 = gPaintingMesh[v0].pos[1]; f32 z0 = gPaintingMesh[v0].pos[2]; f32 x1 = gPaintingMesh[v1].pos[0]; f32 y1 = gPaintingMesh[v1].pos[1]; f32 z1 = gPaintingMesh[v1].pos[2]; f32 x2 = gPaintingMesh[v2].pos[0]; f32 y2 = gPaintingMesh[v2].pos[1]; f32 z2 = gPaintingMesh[v2].pos[2]; // Cross product to find each triangle's normal vector gPaintingTriNorms[i][0] = (y1 - y0) * (z2 - z1) - (z1 - z0) * (y2 - y1); gPaintingTriNorms[i][1] = (z1 - z0) * (x2 - x1) - (x1 - x0) * (z2 - z1); gPaintingTriNorms[i][2] = (x1 - x0) * (y2 - y1) - (y1 - y0) * (x2 - x1); } } /** * Rounds a floating-point component of a normal vector to an s8 by multiplying it by 127 or 128 and * rounding away from 0. */ s8 normalize_component(f32 comp) { s8 rounded; if (comp > 0.0) { rounded = comp * 127.0 + 0.5; // round up } else if (comp < 0.0) { rounded = comp * 128.0 - 0.5; // round down } else { rounded = 0; // don't round 0 } return rounded; } /** * Approximates the painting mesh's vertex normals by averaging the normals of all triangles sharing a * vertex. Used for Gouraud lighting. * * After each triangle's surface normal is calculated, the `neighborTris` table describes which triangles * each vertex should use when calculating the average normal vector. * * The table is a list of entries in this format: * numNeighbors, tri0, tri1, ..., triN * * Where each 'tri' is an index into gPaintingTriNorms. * Entry i in `neighborTris` corresponds to the vertex at gPaintingMesh[i] * * The table used in game, seg2_painting_mesh_neighbor_tris, is in bin/segment2.c. */ void painting_average_vertex_normals(s16 *neighborTris, s16 numVtx) { UNUSED s16 unused; s16 tri; s16 i; s16 j; s16 neighbors; s16 entry = 0; for (i = 0; i < numVtx; i++) { f32 nx = 0.0f; f32 ny = 0.0f; f32 nz = 0.0f; f32 nlen; // The first number of each entry is the number of adjacent tris neighbors = neighborTris[entry]; for (j = 0; j < neighbors; j++) { tri = neighborTris[entry + j + 1]; nx += gPaintingTriNorms[tri][0]; ny += gPaintingTriNorms[tri][1]; nz += gPaintingTriNorms[tri][2]; } // Move to the next vertex's entry entry += neighbors + 1; // average the surface normals from each neighboring tri nx /= neighbors; ny /= neighbors; nz /= neighbors; nlen = sqrtf(nx * nx + ny * ny + nz * nz); if (nlen == 0.0) { gPaintingMesh[i].norm[0] = 0; gPaintingMesh[i].norm[1] = 0; gPaintingMesh[i].norm[2] = 0; } else { gPaintingMesh[i].norm[0] = normalize_component(nx / nlen); gPaintingMesh[i].norm[1] = normalize_component(ny / nlen); gPaintingMesh[i].norm[2] = normalize_component(nz / nlen); } } } /** * Creates a display list that draws the rippling painting, with 'img' mapped to the painting's mesh, * using 'textureMap'. * * If the textureMap doesn't describe the whole mesh, then multiple calls are needed to draw the whole * painting. */ Gfx *render_painting(u8 *img, s16 tWidth, s16 tHeight, s16 *textureMap, s16 mapVerts, s16 mapTris, u8 alpha) { s16 group; s16 map; s16 triGroup; s16 mapping; s16 meshVtx; s16 tx; s16 ty; // We can fit 15 (16 / 3) vertices in the RSP's vertex buffer. // Group triangles by 5, with one remainder group. s16 triGroups = mapTris / 5; s16 remGroupTris = mapTris % 5; s16 numVtx = mapTris * 3; s16 commands = triGroups * 2 + remGroupTris + 7; Vtx *verts = alloc_display_list(numVtx * sizeof(Vtx)); Gfx *dlist = alloc_display_list(commands * sizeof(Gfx)); Gfx *gfx = dlist; if (verts == NULL || dlist == NULL) { } gLoadBlockTexture(gfx++, tWidth, tHeight, G_IM_FMT_RGBA, img); // Draw the groups of 5 first for (group = 0; group < triGroups; group++) { // The triangle groups are the second part of the texture map. // Each group is a list of 15 mappings triGroup = mapVerts * 3 + group * 15 + 2; for (map = 0; map < 15; map++) { // The mapping is just an index into the earlier part of the textureMap // Some mappings are repeated, for example, when multiple triangles share a vertex mapping = textureMap[triGroup + map]; // The first entry is the ID of the vertex in the mesh meshVtx = textureMap[mapping * 3 + 1]; // The next two are the texture coordinates for that vertex tx = textureMap[mapping * 3 + 2]; ty = textureMap[mapping * 3 + 3]; // Map the texture and place it in the verts array make_vertex(verts, group * 15 + map, gPaintingMesh[meshVtx].pos[0], gPaintingMesh[meshVtx].pos[1], gPaintingMesh[meshVtx].pos[2], tx, ty, gPaintingMesh[meshVtx].norm[0], gPaintingMesh[meshVtx].norm[1], gPaintingMesh[meshVtx].norm[2], alpha); } // Load the vertices and draw the 5 triangles gSPVertex(gfx++, VIRTUAL_TO_PHYSICAL(verts + group * 15), 15, 0); gSPDisplayList(gfx++, dl_paintings_draw_ripples); } // One group left with < 5 triangles triGroup = mapVerts * 3 + triGroups * 15 + 2; // Map the texture to the triangles for (map = 0; map < remGroupTris * 3; map++) { mapping = textureMap[triGroup + map]; meshVtx = textureMap[mapping * 3 + 1]; tx = textureMap[mapping * 3 + 2]; ty = textureMap[mapping * 3 + 3]; make_vertex(verts, triGroups * 15 + map, gPaintingMesh[meshVtx].pos[0], gPaintingMesh[meshVtx].pos[1], gPaintingMesh[meshVtx].pos[2], tx, ty, gPaintingMesh[meshVtx].norm[0], gPaintingMesh[meshVtx].norm[1], gPaintingMesh[meshVtx].norm[2], alpha); } // Draw the triangles individually gSPVertex(gfx++, VIRTUAL_TO_PHYSICAL(verts + triGroups * 15), remGroupTris * 3, 0); for (group = 0; group < remGroupTris; group++) { gSP1Triangle(gfx++, group * 3, group * 3 + 1, group * 3 + 2, 0); } gSPEndDisplayList(gfx); return dlist; } /** * Orient the painting mesh for rendering. */ Gfx *painting_model_view_transform(struct Painting *painting) { f32 sizeRatio = painting->size / PAINTING_SIZE; Mtx *rotX = alloc_display_list(sizeof(Mtx)); Mtx *rotY = alloc_display_list(sizeof(Mtx)); Mtx *translate = alloc_display_list(sizeof(Mtx)); Mtx *scale = alloc_display_list(sizeof(Mtx)); Gfx *dlist = alloc_display_list(5 * sizeof(Gfx)); Gfx *gfx = dlist; if (rotX == NULL || rotY == NULL || translate == NULL || dlist == NULL) { } guTranslate(translate, painting->posX, painting->posY, painting->posZ); guRotate(rotX, painting->pitch, 1.0f, 0.0f, 0.0f); guRotate(rotY, painting->yaw, 0.0f, 1.0f, 0.0f); guScale(scale, sizeRatio, sizeRatio, sizeRatio); gSPMatrix(gfx++, translate, G_MTX_MODELVIEW | G_MTX_MUL | G_MTX_PUSH); gSPMatrix(gfx++, rotX, G_MTX_MODELVIEW | G_MTX_MUL | G_MTX_NOPUSH); gSPMatrix(gfx++, rotY, G_MTX_MODELVIEW | G_MTX_MUL | G_MTX_NOPUSH); gSPMatrix(gfx++, scale, G_MTX_MODELVIEW | G_MTX_MUL | G_MTX_NOPUSH); gSPEndDisplayList(gfx); return dlist; } /** * Ripple a painting that has 1 or more images that need to be mapped */ Gfx *painting_ripple_image(struct Painting *painting) { s16 meshVerts; s16 meshTris; s16 i; s16 *textureMap; s16 imageCount = painting->imageCount; s16 tWidth = painting->textureWidth; s16 tHeight = painting->textureHeight; s16 **textureMaps = segmented_to_virtual(painting->textureMaps); u8 **textures = segmented_to_virtual(painting->textureArray); Gfx *dlist = alloc_display_list((imageCount + 6) * sizeof(Gfx)); Gfx *gfx = dlist; if (dlist == NULL) { return dlist; } gSPDisplayList(gfx++, painting_model_view_transform(painting)); gSPDisplayList(gfx++, dl_paintings_rippling_begin); gSPDisplayList(gfx++, painting->rippleDisplayList); // Map each image to the mesh's vertices for (i = 0; i < imageCount; i++) { textureMap = segmented_to_virtual(textureMaps[i]); meshVerts = textureMap[0]; meshTris = textureMap[meshVerts * 3 + 1]; gSPDisplayList(gfx++, render_painting(textures[i], tWidth, tHeight, textureMap, meshVerts, meshTris, painting->alpha)); } // Update the ripple, may automatically reset the painting's state. painting_update_ripple_state(painting); gSPPopMatrix(gfx++, G_MTX_MODELVIEW); gSPDisplayList(gfx++, dl_paintings_rippling_end); gSPEndDisplayList(gfx); return dlist; } /** * Ripple a painting that has 1 "environment map" texture. */ Gfx *painting_ripple_env_mapped(struct Painting *painting) { s16 meshVerts; s16 meshTris; s16 *textureMap; s16 tWidth = painting->textureWidth; s16 tHeight = painting->textureHeight; s16 **textureMaps = segmented_to_virtual(painting->textureMaps); u8 **tArray = segmented_to_virtual(painting->textureArray); Gfx *dlist = alloc_display_list(7 * sizeof(Gfx)); Gfx *gfx = dlist; if (dlist == NULL) { return dlist; } gSPDisplayList(gfx++, painting_model_view_transform(painting)); gSPDisplayList(gfx++, dl_paintings_env_mapped_begin); gSPDisplayList(gfx++, painting->rippleDisplayList); // Map the image to the mesh's vertices textureMap = segmented_to_virtual(textureMaps[0]); meshVerts = textureMap[0]; meshTris = textureMap[meshVerts * 3 + 1]; gSPDisplayList(gfx++, render_painting(tArray[0], tWidth, tHeight, textureMap, meshVerts, meshTris, painting->alpha)); // Update the ripple, may automatically reset the painting's state. painting_update_ripple_state(painting); gSPPopMatrix(gfx++, G_MTX_MODELVIEW); gSPDisplayList(gfx++, dl_paintings_env_mapped_end); gSPEndDisplayList(gfx); return dlist; } /** * Generates a mesh, calculates vertex normals for lighting, and renders a rippling painting. * The mesh and vertex normals are regenerated and freed every frame. */ Gfx *display_painting_rippling(struct Painting *painting) { s16 *mesh = segmented_to_virtual(seg2_painting_triangle_mesh); s16 *neighborTris = segmented_to_virtual(seg2_painting_mesh_neighbor_tris); s16 numVtx = mesh[0]; s16 numTris = mesh[numVtx * 3 + 1]; Gfx *dlist; // Generate the mesh and its lighting data painting_generate_mesh(painting, mesh, numVtx); painting_calculate_triangle_normals(mesh, numVtx, numTris); painting_average_vertex_normals(neighborTris, numVtx); // Map the painting's texture depending on the painting's texture type. switch (painting->textureType) { case PAINTING_IMAGE: dlist = painting_ripple_image(painting); break; case PAINTING_ENV_MAP: dlist = painting_ripple_env_mapped(painting); break; } // The mesh data is freed every frame. mem_pool_free(gEffectsMemoryPool, gPaintingMesh); mem_pool_free(gEffectsMemoryPool, gPaintingTriNorms); return dlist; } /** * Render a normal painting. */ Gfx *display_painting_not_rippling(struct Painting *painting) { Gfx *dlist = alloc_display_list(4 * sizeof(Gfx)); Gfx *gfx = dlist; if (dlist == NULL) { return dlist; } gSPDisplayList(gfx++, painting_model_view_transform(painting)); gSPDisplayList(gfx++, painting->normalDisplayList); gSPPopMatrix(gfx++, G_MTX_MODELVIEW); gSPEndDisplayList(gfx); return dlist; } /** * Clear Mario-related state and clear gRipplingPainting. */ void reset_painting(struct Painting *painting) { painting->lastFloor = 0; painting->currFloor = 0; painting->floorEntered = 0; painting->marioWasUnder = 0; painting->marioIsUnder = 0; painting->marioWentUnder = 0; gRipplingPainting = NULL; // Make sure all variables are reset correctly. // With segmented memory the segments that contain the relevant // Painting structs are reloaded from ROM upon level load. painting->state = PAINTING_IDLE; painting->currRippleMag = 0.0f; painting->rippleDecay = 1.0f; painting->currRippleRate = 0.0f; painting->dispersionFactor = 0.0f; painting->rippleTimer = 0.0f; painting->rippleX = 0.0f; painting->rippleY = 0.0f; if (painting == &ddd_painting) { // Move DDD painting to initial position, in case the animation // that moves the painting stops during level unload. painting->posX = 3456.0f; } } /** * Controls the x coordinate of the DDD painting. * * Before Mario gets the "Board Bowser's Sub" star in DDD, the painting spawns at frontPos. * * If Mario just got the star, the painting's x coordinate moves to backPos at a rate of `speed` units. * * When the painting reaches backPos, a save flag is set so that the painting will spawn at backPos * whenever it loads. * * This function also sets gDddPaintingStatus, which controls the warp: * 0 (0b00): set x coordinate to frontPos * 2 (0b10): set x coordinate to backPos * 3 (0b11): same as 2. Bit 0 is ignored */ void move_ddd_painting(struct Painting *painting, f32 frontPos, f32 backPos, f32 speed) { // Obtain the DDD star flags u32 dddFlags = save_file_get_star_flags(gCurrSaveFileNum - 1, COURSE_DDD - 1); // Get the other save file flags u32 saveFileFlags = save_file_get_flags(); // Find out whether Board Bowser's Sub was collected u32 bowsersSubBeaten = dddFlags & BOARD_BOWSERS_SUB; // Check whether DDD has already moved back u32 dddBack = saveFileFlags & SAVE_FLAG_DDD_MOVED_BACK; if (!bowsersSubBeaten && !dddBack) { // If we haven't collected the star or moved the painting, put the painting at the front painting->posX = frontPos; gDddPaintingStatus = 0; } else if (bowsersSubBeaten && !dddBack) { // If we've collected the star but not moved the painting back, // Each frame, move the painting by a certain speed towards the back area. painting->posX += speed; gDddPaintingStatus = BOWSERS_SUB_BEATEN; if (painting->posX >= backPos) { painting->posX = backPos; // Tell the save file that we've moved DDD back. save_file_set_flags(SAVE_FLAG_DDD_MOVED_BACK); } } else if (bowsersSubBeaten && dddBack) { // If the painting has already moved back, place it in the back position. painting->posX = backPos; gDddPaintingStatus = BOWSERS_SUB_BEATEN | DDD_BACK; } } /** * Set the painting's node's layer based on its alpha */ void set_painting_layer(struct GraphNodeGenerated *gen, struct Painting *painting) { switch (painting->alpha) { case 0xFF: // Opaque gen->fnNode.node.flags = (gen->fnNode.node.flags & 0xFF) | (LAYER_OPAQUE << 8); break; default: gen->fnNode.node.flags = (gen->fnNode.node.flags & 0xFF) | (LAYER_TRANSPARENT << 8); break; } } /** * Display either a normal painting or a rippling one depending on the painting's ripple status */ Gfx *display_painting(struct Painting *painting) { switch (painting->state) { case PAINTING_IDLE: return display_painting_not_rippling(painting); break; default: return display_painting_rippling(painting); break; } } /** * Update function for wall paintings. * Calls a different update function depending on the painting's ripple trigger and current state. */ void wall_painting_update(struct Painting *painting, struct Painting *paintingGroup[]) { if (painting->rippleTrigger == RIPPLE_TRIGGER_PROXIMITY) { switch (painting->state) { case PAINTING_IDLE: wall_painting_proximity_idle(painting, paintingGroup); break; case PAINTING_RIPPLE: wall_painting_proximity_rippling(painting, paintingGroup); break; } } else if (painting->rippleTrigger == RIPPLE_TRIGGER_CONTINUOUS) { switch (painting->state) { case PAINTING_IDLE: wall_painting_continuous_idle(painting, paintingGroup); break; case PAINTING_RIPPLE: wall_painting_continuous_rippling(painting, paintingGroup); break; } } } /** * Update function for floor paintings (HMC and CotMC) * Calls a different update function depending on the painting's ripple trigger and current state. * * No floor paintings use RIPPLE_TRIGGER_PROXIMITY in the game. */ void floor_painting_update(struct Painting *painting, struct Painting *paintingGroup[]) { if (painting->rippleTrigger == RIPPLE_TRIGGER_PROXIMITY) { switch (painting->state) { case PAINTING_IDLE: floor_painting_proximity_idle(painting, paintingGroup); break; case PAINTING_RIPPLE: floor_painting_proximity_rippling(painting, paintingGroup); break; } } else if (painting->rippleTrigger == RIPPLE_TRIGGER_CONTINUOUS) { switch (painting->state) { case PAINTING_IDLE: floor_painting_continuous_idle(painting, paintingGroup); break; case PAINTING_RIPPLE: floor_painting_continuous_rippling(painting, paintingGroup); break; } } } /** * Render and update the painting whose id and group matches the values in the GraphNode's parameter. * Use PAINTING_ID(id, group) to set the right parameter in a level's geo layout. */ Gfx *geo_painting_draw(s32 callContext, struct GraphNode *node, UNUSED void *context) { struct GraphNodeGenerated *gen = (struct GraphNodeGenerated *) node; s32 group = (gen->parameter >> 8) & 0xFF; s32 id = gen->parameter & 0xFF; Gfx *paintingDlist = NULL; struct Painting **paintingGroup = sPaintingGroups[group]; struct Painting *painting = segmented_to_virtual(paintingGroup[id]); if (callContext != GEO_CONTEXT_RENDER) { reset_painting(painting); } else if (callContext == GEO_CONTEXT_RENDER) { // Update the ddd painting before drawing if (group == 1 && id == PAINTING_ID_DDD) { move_ddd_painting(painting, 3456.0f, 5529.6f, 20.0f); } // Determine if the painting is transparent set_painting_layer(gen, painting); // Draw before updating paintingDlist = display_painting(painting); // Update the painting painting_update_floors(painting); switch ((s16) painting->pitch) { // only paintings with 0 pitch are treated as walls case 0: wall_painting_update(painting, paintingGroup); break; default: floor_painting_update(painting, paintingGroup); break; } } return paintingDlist; } /** * Update the painting system's local copy of Mario's current floor and position. */ Gfx *geo_painting_update(s32 callContext, UNUSED struct GraphNode *node, UNUSED Mat4 c) { struct Surface *surface; // Reset the update counter if (callContext != GEO_CONTEXT_RENDER) { gLastPaintingUpdateCounter = gAreaUpdateCounter - 1; gPaintingUpdateCounter = gAreaUpdateCounter; } else { gLastPaintingUpdateCounter = gPaintingUpdateCounter; gPaintingUpdateCounter = gAreaUpdateCounter; // Store Mario's floor and position find_floor(gMarioObject->oPosX, gMarioObject->oPosY, gMarioObject->oPosZ, &surface); gPaintingMarioFloorType = surface->type; gPaintingMarioXPos = gMarioObject->oPosX; gPaintingMarioYPos = gMarioObject->oPosY; gPaintingMarioZPos = gMarioObject->oPosZ; } return NULL; }
37.145768
127
0.67256
[ "mesh", "render", "object", "vector" ]
6cb6d69cb5f9a7c9e48b40f1089717b5cd709891
5,155
h
C
OsiriXAPI.framework/Versions/A/Headers/octree.h
nevitdilmen/Osirix-ColorMRI
47549f97dd09b414742e773f365a4e7143bf2067
[ "MIT" ]
20
2016-02-02T10:31:41.000Z
2021-11-08T08:35:25.000Z
OsiriXAPI.framework/Versions/A/Headers/octree.h
nevitdilmen/Osirix-ColorMRI
47549f97dd09b414742e773f365a4e7143bf2067
[ "MIT" ]
14
2018-01-03T16:49:04.000Z
2018-06-01T15:19:06.000Z
OsiriXAPI.framework/Versions/A/Headers/octree.h
nevitdilmen/Osirix-ColorMRI
47549f97dd09b414742e773f365a4e7143bf2067
[ "MIT" ]
9
2018-01-24T21:46:10.000Z
2022-03-08T09:42:42.000Z
#ifndef __octree_h #define __octree_h #include <iostream> /**\brief An n-dimensional octree. Perhaps it should be named a tttntree (two-to-the n tree)? * * This templated class provides an n-dimensional binary tree, storing an * object whose type is specified by the first template parameter at each * node (whether or not that node is a leaf). * The second template parameter is an integer constant specifying the * dimension of the tree. * The final template parameter takes an allocator object just as the STL does. * * The tree itself stores the center and overall bounds of the root node; * the nodes themselves do not contain any information on the geometry. * If needed, it can be derived from an octree_path object referring to * the node or stored in the template class at each node for fast access. * This makes the class useful for storing abstract trees with minimal overhead * as well as trees embedded in a metric space. * * Access to entries in the tree is provided by octree_cursor and octree_iterator * objects, both of which inherit octree_path. * An octree_path stores a vector of integers describing a descent from the root * node to a particular child node of the octree. * Since each node of a \f$d\f$-dimensional tree has \f$2^d\f$ children, * the integers in the vector will all be in \f$\{0,\ldots,2^d-1\}\f$. * * The octree_cursor class provides a free-form way to visit nodes in the octree; * it does not behave like an interator that guarantees each node will be visited once. * Instead, it provides a way to move up, down, and across the tree from any location. * This makes it useful for local queries that do not need to traverse the entire tree. * * The octree_iterator class simply traverses the tree in depth-first order * and can be configured to visit only leaf nodes or to include all nodes. */ template< typename T_, int d_ = 3, typename A_ = std::allocator<T_> > class octree { public: typedef T_ value_type; typedef T_* pointer; typedef T_& reference; typedef const T_* const_pointer; typedef const T_& const_reference; typedef octree<T_,d_,A_> _self_type; typedef _self_type* _self_pointer; typedef octree_node<T_,d_,A_>* octree_node_pointer; typedef octree_node<T_,d_,A_>& octree_node_reference; typedef const octree_node<T_,d_,A_>* const_octree_node_pointer; typedef const octree_node<T_,d_,A_>& const_octree_node_reference; typedef typename std::vector<octree_node_pointer>::size_type size_type; typedef A_ allocator_type; // Ugly. But neccessary according to young me. Old me says so. typedef octree_iterator< T_, T_&, T_*, _self_type, _self_pointer, d_ > iterator; typedef octree_iterator< T_, const T_&, const T_*, _self_type, _self_pointer, d_ > const_iterator; typedef octree_cursor< T_, T_&, T_*, _self_type, _self_pointer, d_ > cursor; typedef octree_cursor< T_, const T_&, const T_*, _self_type, _self_pointer, d_ > const_cursor; octree( const double* center, double size ); octree( const double* center, double size, const value_type& root_node_value ); virtual ~octree(); /** \brief Iterator based access. * * Iterators come in const and non-const versions as well as versions * that visit all nodes or just leaf nodes. By default, only leaf nodes * are visited. * * You may add or remove children while iterating with some caveats. * When adding children, any iterator currently referencing the node * to which children were added will reference the first child node * when incremented. Iterators confined to leaf nodes may reference * non-leaf nodes when refinement occurs between increments/decrements. * When removing children from node \a A, any iterators pointing to * grandchildren of \a A will become invalid. Iterators pointing to * children of \a A may not be dereferenced but may be incremented or * decremented safely. */ //@{ iterator begin( bool only_leaves = true ) { return iterator( _M_root, _M_root, only_leaves ); } iterator end( bool only_leaves = true ) { return iterator( _M_root, 0, only_leaves ); } const_iterator begin( bool only_leaves = true ) const { return const_iterator( _M_root, _M_root, only_leaves ); } const_iterator end( bool only_leaves = true ) const { return const_iterator( _M_root, 0, only_leaves ); } //@} octree_node_pointer root() { return this->_M_root; } size_t size( bool only_leaves = false ); /** \brief Geometric information * Binary trees of dimension 2 or higher are often used to partition geometric objects into subsets. * In order to do this, the tree must have some geometric center and size. * These are set by the constructor but may be queried at any time. * They may not be modified as that would require a re-partitioning of the objects (typically stored * at nodes or leaf-nodes). */ //@{ const double* center() const { return this->_M_center; } double size() const { return this->_M_size; } //@} protected: octree_node_pointer _M_root; double _M_center[d_]; double _M_size; }; #endif // __octree_h
43.319328
115
0.733657
[ "geometry", "object", "vector" ]
6cc0517016e505ac5e24c99326a7499c20adb96e
3,918
h
C
fxjs/xfa/cfxjse_value.h
softwarecapital/google.pdfium
d6c0f7d6aeaac79ca1eb7fb065d80dbd3504c92e
[ "Apache-2.0" ]
25
2019-05-07T16:16:40.000Z
2022-03-30T09:04:00.000Z
fxjs/xfa/cfxjse_value.h
softwarecapital/google.pdfium
d6c0f7d6aeaac79ca1eb7fb065d80dbd3504c92e
[ "Apache-2.0" ]
4
2020-10-20T13:09:56.000Z
2021-04-10T00:23:35.000Z
fxjs/xfa/cfxjse_value.h
softwarecapital/google.pdfium
d6c0f7d6aeaac79ca1eb7fb065d80dbd3504c92e
[ "Apache-2.0" ]
11
2019-09-11T20:43:10.000Z
2022-03-30T09:04:01.000Z
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #ifndef FXJS_XFA_CFXJSE_VALUE_H_ #define FXJS_XFA_CFXJSE_VALUE_H_ #include <memory> #include <vector> #include "core/fxcrt/fx_string.h" #include "core/fxcrt/fx_system.h" #include "core/fxcrt/unowned_ptr.h" #include "third_party/base/check.h" #include "v8/include/v8.h" class CFXJSE_Class; class CFXJSE_HostObject; class CFXJSE_Value { public: CFXJSE_Value(); CFXJSE_Value(v8::Isolate* pIsolate, v8::Local<v8::Value> value); ~CFXJSE_Value(); bool IsEmpty() const; bool IsUndefined(v8::Isolate* pIsolate) const; bool IsNull(v8::Isolate* pIsolate) const; bool IsBoolean(v8::Isolate* pIsolate) const; bool IsString(v8::Isolate* pIsolate) const; bool IsNumber(v8::Isolate* pIsolate) const; bool IsInteger(v8::Isolate* pIsolate) const; bool IsObject(v8::Isolate* pIsolate) const; bool IsArray(v8::Isolate* pIsolate) const; bool IsFunction(v8::Isolate* pIsolate) const; bool ToBoolean(v8::Isolate* pIsolate) const; float ToFloat(v8::Isolate* pIsolate) const; double ToDouble(v8::Isolate* pIsolate) const; int32_t ToInteger(v8::Isolate* pIsolate) const; ByteString ToString(v8::Isolate* pIsolate) const; WideString ToWideString(v8::Isolate* pIsolate) const { return WideString::FromUTF8(ToString(pIsolate).AsStringView()); } CFXJSE_HostObject* ToHostObject(v8::Isolate* pIsolate) const; void SetUndefined(v8::Isolate* pIsolate); void SetNull(v8::Isolate* pIsolate); void SetBoolean(v8::Isolate* pIsolate, bool bBoolean); void SetInteger(v8::Isolate* pIsolate, int32_t nInteger); void SetDouble(v8::Isolate* pIsolate, double dDouble); void SetString(v8::Isolate* pIsolate, ByteStringView szString); void SetFloat(v8::Isolate* pIsolate, float fFloat); void SetHostObject(v8::Isolate* pIsolate, CFXJSE_HostObject* lpObject, CFXJSE_Class* pClass); void SetArray(v8::Isolate* pIsolate, const std::vector<std::unique_ptr<CFXJSE_Value>>& values); bool GetObjectProperty(v8::Isolate* pIsolate, ByteStringView szPropName, CFXJSE_Value* lpPropValue); bool SetObjectProperty(v8::Isolate* pIsolate, ByteStringView szPropName, CFXJSE_Value* lpPropValue); bool GetObjectPropertyByIdx(v8::Isolate* pIsolate, uint32_t uPropIdx, CFXJSE_Value* lpPropValue); void DeleteObjectProperty(v8::Isolate* pIsolate, ByteStringView szPropName); bool HasObjectOwnProperty(v8::Isolate* pIsolate, ByteStringView szPropName, bool bUseTypeGetter); bool SetObjectOwnProperty(v8::Isolate* pIsolate, ByteStringView szPropName, CFXJSE_Value* lpPropValue); // Return empty local on error. static v8::Local<v8::Function> NewBoundFunction( v8::Isolate* pIsolate, v8::Local<v8::Function> hOldFunction, v8::Local<v8::Object> lpNewThis); v8::Local<v8::Value> GetValue(v8::Isolate* pIsolate) const; const v8::Global<v8::Value>& DirectGetValue() const { return m_hValue; } void ForceSetValue(v8::Isolate* pIsolate, v8::Local<v8::Value> hValue) { m_hValue.Reset(pIsolate, hValue); } void Assign(v8::Isolate* pIsolate, const CFXJSE_Value* lpValue) { DCHECK(lpValue); if (lpValue) { m_hValue.Reset(pIsolate, lpValue->m_hValue); } else { m_hValue.Reset(); } } private: CFXJSE_Value(const CFXJSE_Value&) = delete; CFXJSE_Value& operator=(const CFXJSE_Value&) = delete; v8::Global<v8::Value> m_hValue; }; #endif // FXJS_XFA_CFXJSE_VALUE_H_
36.277778
80
0.685043
[ "object", "vector" ]
8c2145e3a52ab44dc9f90cc502bd1c713fc8b0e2
24,876
h
C
IfcPlusPlus/src/ifcpp/geometry/GeometryConverter.h
linsipese/ifcppstudy
e09f05d276b5e129fcb6be65800472979cd4c800
[ "MIT" ]
1
2018-10-23T09:43:07.000Z
2018-10-23T09:43:07.000Z
IfcPlusPlus/src/ifcpp/geometry/GeometryConverter.h
linsipese/ifcppstudy
e09f05d276b5e129fcb6be65800472979cd4c800
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/geometry/GeometryConverter.h
linsipese/ifcppstudy
e09f05d276b5e129fcb6be65800472979cd4c800
[ "MIT" ]
null
null
null
/* -*-c++-*- IfcPlusPlus - www.ifcplusplus.com - Copyright (C) 2011 Fabian Gerold * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #pragma once #include <set> #include <sstream> #include <osg/Switch> #include <ifcpp/model/shared_ptr.h> #include <ifcpp/model/IfcPPObject.h> #include <ifcpp/model/IfcPPModel.h> #include <ifcpp/model/StatusCallback.h> #include <ifcpp/IFC4/include/IfcComplexProperty.h> #include <ifcpp/IFC4/include/IfcIdentifier.h> #include <ifcpp/IFC4/include/IfcProject.h> #include <ifcpp/IFC4/include/IfcProduct.h> #include <ifcpp/IFC4/include/IfcPropertySet.h> #include <ifcpp/IFC4/include/IfcPropertySetDefinitionSet.h> #include <ifcpp/IFC4/include/IfcPropertySingleValue.h> #include <ifcpp/IFC4/include/IfcRelAggregates.h> #include <ifcpp/IFC4/include/IfcRelContainedInSpatialStructure.h> #include <ifcpp/IFC4/include/IfcRelDefinesByProperties.h> #include <ifcpp/IFC4/include/IfcSimpleProperty.h> #include "RepresentationConverter.h" #include "ConverterOSG.h" #include "GeometrySettings.h" #include "GeometryInputData.h" class GeometryConverter : public StatusCallback { protected: shared_ptr<IfcPPModel> m_ifc_model; shared_ptr<GeometrySettings> m_geom_settings; shared_ptr<RepresentationConverter> m_representation_converter; shared_ptr<ConverterOSG> m_converter_osg; std::map<int, shared_ptr<ProductShapeInputData> > m_shape_input_data; boost::unordered_map<int, shared_ptr<IfcPPObject> > m_map_outside_spatial_structure; double m_recent_progress; std::map<int, std::vector<shared_ptr<StatusCallback::Message> > > m_messages; #ifdef IFCPP_OPENMP Mutex m_writelock_messages; #endif public: // getters and setters shared_ptr<IfcPPModel>& getIfcPPModel() { return m_ifc_model; } shared_ptr<RepresentationConverter>& getRepresentationConverter() { return m_representation_converter; } shared_ptr<ConverterOSG>& getConverterOSG() { return m_converter_osg; } shared_ptr<GeometrySettings>& getGeomSettings() { return m_geom_settings; } std::map<int, shared_ptr<ProductShapeInputData> >& getShapeInputData() { return m_shape_input_data; } boost::unordered_map<int, shared_ptr<IfcPPObject> >& getObjectsOutsideSpatialStructure() { return m_map_outside_spatial_structure; } virtual void slotMessageWrapper( void* ptr, shared_ptr<StatusCallback::Message> m ) { GeometryConverter* myself = (GeometryConverter*)ptr; if( myself ) { if( m->m_entity ) { #ifdef IFCPP_OPENMP ScopedLock lock( myself->m_writelock_messages ); #endif // make sure that the same message for one entity does not appear several times const int entity_id = m->m_entity->m_id; std::map<int, std::vector<shared_ptr<StatusCallback::Message> > >::iterator it = myself->m_messages.find( entity_id ); if( it != myself->m_messages.end() ) { std::vector<shared_ptr<StatusCallback::Message> >& vec_message_for_entity = it->second; for( size_t i = 0; i < vec_message_for_entity.size(); ++i ) { shared_ptr<StatusCallback::Message>& existing_message = vec_message_for_entity[i]; if( existing_message->m_message_text.compare( m->m_message_text ) == 0 ) { // same message for same entity is already there, so ignore message return; } } vec_message_for_entity.push_back( m ); } else { std::vector<shared_ptr<StatusCallback::Message> >& vec = myself->m_messages.insert( std::make_pair( entity_id, std::vector<shared_ptr<StatusCallback::Message> >() ) ).first->second; vec.push_back( m ); } } myself->messageCallback( m ); } } GeometryConverter( shared_ptr<IfcPPModel>& ifc_model ) { m_ifc_model = ifc_model; m_geom_settings = shared_ptr<GeometrySettings>( new GeometrySettings() ); resetNumVerticesPerCircle(); shared_ptr<UnitConverter>& unit_converter = m_ifc_model->getUnitConverter(); m_representation_converter = shared_ptr<RepresentationConverter>( new RepresentationConverter( m_geom_settings, unit_converter ) ); m_converter_osg = shared_ptr<ConverterOSG>( new ConverterOSG( m_geom_settings ) ); // redirect all messages to slotMessageWrapper addCallbackChild( m_ifc_model.get() ); addCallbackChild( m_representation_converter.get() ); addCallbackChild( m_converter_osg.get() ); } virtual ~GeometryConverter() { } void resetModel() { progressTextCallback( L"Unloading model, cleaning up memory..." ); clearInputCache(); m_recent_progress = 0.0; m_ifc_model->clearCache(); m_ifc_model->clearIfcModel(); progressTextCallback( L"Unloading model done" ); progressValueCallback( 0.0, "parse" ); #ifdef _DEBUG GeomDebugUtils::clearMeshsetDump(); #endif } void clearInputCache() { m_shape_input_data.clear(); m_map_outside_spatial_structure.clear(); m_converter_osg->clearAppearanceCache(); m_representation_converter->clearCache(); m_messages.clear(); } void resetNumVerticesPerCircle() { m_geom_settings->resetNumVerticesPerCircle(); } void setModel( shared_ptr<IfcPPModel> model ) { clearInputCache(); m_ifc_model = model; m_representation_converter->clearCache(); m_representation_converter->setUnitConverter( m_ifc_model->getUnitConverter() ); //m_ifc_model->setMessageCallBack( this, &slotMessageWrapper ); addCallbackChild( m_ifc_model.get() ); } /*\brief method createGeometryOSG: Creates geometry for OpenSceneGraph from previously loaded model. \param[out] parent_group Group to append the resulting geometry. **/ void createGeometryOSG( osg::ref_ptr<osg::Switch> parent_group ) { progressTextCallback( L"Creating geometry..." ); progressValueCallback( 0, "geometry" ); m_shape_input_data.clear(); m_map_outside_spatial_structure.clear(); m_representation_converter->clearCache(); std::vector<shared_ptr<IfcProduct> > vec_products; const double length_to_meter_factor = m_ifc_model->getUnitConverter()->getLengthInMeterFactor(); carve::setEpsilon( 1.4901161193847656e-05*length_to_meter_factor ); const boost::unordered_map<int, shared_ptr<IfcPPEntity> >& map_entities = m_ifc_model->getMapIfcEntities(); for( auto it = map_entities.begin(); it != map_entities.end(); ++it ) { shared_ptr<IfcPPEntity> obj = it->second; shared_ptr<IfcProduct> product = dynamic_pointer_cast<IfcProduct>( obj ); if( product ) { vec_products.push_back( product ); } // TODO: sort vec_products such, that products with complex geometry are at the beginning (better scheduling for omp). Rate complexity by number of CSG ops, and number of vertices. Check if sorting pays off. } // create geometry for for each IfcProduct independently, spatial structure will be resolved later std::map<int, shared_ptr<ProductShapeInputData> >* map_products_ptr = &m_shape_input_data; const int num_products = (int)vec_products.size(); #ifdef IFCPP_OPENMP Mutex writelock_map; #pragma omp parallel firstprivate(num_products) shared(map_products_ptr) { // time for one product may vary significantly, so schedule not so many #pragma omp for schedule(dynamic,10) #endif for( int i = 0; i < num_products; ++i ) { shared_ptr<IfcProduct> product = vec_products[i]; std::stringstream thread_err; if( dynamic_pointer_cast<IfcFeatureElementSubtraction>( product ) ) { // geometry will be created in method subtractOpenings continue; } if( !product->m_Representation ) { continue; } const int product_id = product->m_id; shared_ptr<ProductShapeInputData> product_geom_input_data( new ProductShapeInputData() ); product_geom_input_data->m_ifc_product = product; try { convertIfcProduct( product_geom_input_data ); m_converter_osg->convertToOSG( product_geom_input_data, length_to_meter_factor ); } #ifdef _DEBUG catch( DebugBreakException& dbge ) { throw dbge; } #endif catch( IfcPPOutOfMemoryException& e ) { throw e; } catch( IfcPPException& e ) { thread_err << e.what(); } catch( carve::exception& e ) { thread_err << e.str(); } catch( std::exception& e ) { thread_err << e.what(); } catch( ... ) { thread_err << "undefined error, product id " << product_id; } { #ifdef IFCPP_OPENMP ScopedLock scoped_lock( writelock_map ); #endif map_products_ptr->insert( std::make_pair( product_id, product_geom_input_data ) ); if( thread_err.tellp() > 0 ) { messageCallback( thread_err.str().c_str(), StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ ); } } // progress callback double progress = (double)i / (double)num_products; if( progress - m_recent_progress > 0.02 ) { #ifdef IFCPP_OPENMP if( omp_get_thread_num() == 0 ) #endif { // leave 10% of progress to openscenegraph internals progressValueCallback( progress*0.9, "geometry" ); m_recent_progress = progress; } } } #ifdef IFCPP_OPENMP } // implicit barrier #endif try { // now resolve spatial structure shared_ptr<IfcProject> ifc_project = m_ifc_model->getIfcProject(); if( ifc_project ) { resolveProjectStructure( ifc_project, parent_group ); } // check if there are entities that are not in spatial structure osg::ref_ptr<osg::Group> group_outside_spatial_structure = new osg::Group(); group_outside_spatial_structure->setName( "Entities not in spatial structure" ); for( auto it_product_shapes = m_shape_input_data.begin(); it_product_shapes != m_shape_input_data.end(); ++it_product_shapes ) { shared_ptr<ProductShapeInputData> product_shape = it_product_shapes->second; shared_ptr<IfcProduct> ifc_product( product_shape->m_ifc_product ); if( !product_shape ) { continue; } if( !product_shape->m_added_to_node ) { shared_ptr<IfcFeatureElementSubtraction> opening = dynamic_pointer_cast<IfcFeatureElementSubtraction>( ifc_product ); if( opening ) { continue; } if( product_shape->m_product_switch.valid() ) { #ifdef _DEBUG if( product_shape->m_product_switch->getNumParents() > 0 ) { std::cout << __FUNC__ << ": product_shape->m_product_switch->getNumParents() > 0" << std::endl; } #endif group_outside_spatial_structure->addChild( product_shape->m_product_switch ); } product_shape->m_added_to_node = true; } m_map_outside_spatial_structure[ifc_product->m_id] = ifc_product; } if( group_outside_spatial_structure->getNumChildren() > 0 ) { #ifdef _DEBUG if( group_outside_spatial_structure->getNumParents() > 0 ) { std::cout << __FUNC__ << ": group_outside_spatial_structure->getNumParents() > 0" << std::endl; } #endif parent_group->addChild( group_outside_spatial_structure ); } } catch( IfcPPOutOfMemoryException& e ) { throw e; } catch( IfcPPException& e ) { messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" ); } catch( std::exception& e ) { messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" ); } catch( ... ) { messageCallback( "undefined error", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ ); } m_representation_converter->getProfileCache()->clearProfileCache(); progressTextCallback( L"Loading file done" ); progressValueCallback( 1.0, "geometry" ); } bool inParentList( const int entity_id, osg::Group* group ) { if( !group ) { return false; } const osg::Group::ParentList& vec_parents = group->getParents(); for( size_t ii = 0; ii < vec_parents.size(); ++ii ) { osg::Group* parent = vec_parents[ii]; if( parent ) { const std::string parent_name = parent->getName(); if( parent_name.length() > 0 ) { if( parent_name.at( 0 ) == '#' ) { // extract entity id std::string parent_name_id = parent_name.substr( 1 ); size_t last_index = parent_name_id.find_first_not_of( "0123456789" ); std::string id_str = parent_name_id.substr( 0, last_index ); const int id = std::stoi( id_str.c_str() ); if( id == entity_id ) { return true; } bool in_parent_list = inParentList( entity_id, parent ); if( in_parent_list ) { return true; } } } } } return false; } void resolveProjectStructure( const shared_ptr<IfcObjectDefinition>& obj_def, osg::ref_ptr<osg::Switch> group ) { const int entity_id = obj_def->m_id; if( inParentList( entity_id, group ) ) { messageCallback( "Cycle in project structure detected", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__, obj_def.get() ); return; } shared_ptr<IfcProduct> ifc_product = dynamic_pointer_cast<IfcProduct>( obj_def ); if( ifc_product ) { std::map<int, shared_ptr<ProductShapeInputData> >::iterator it_product_map = m_shape_input_data.find( entity_id ); if( it_product_map != m_shape_input_data.end() ) { shared_ptr<ProductShapeInputData>& product_shape = it_product_map->second; if( product_shape ) { if( product_shape->m_product_switch ) { if( product_shape->m_added_to_node ) { // IfcRelContained/RelAggregates relationship is required to be hierarchical (an element can only be contained in exactly one spatial structure element) std::cout << "already product_shape->added_to_node" << std::endl; } #ifdef _DEBUG for( size_t ii_parent = 0; ii_parent < product_shape->m_product_switch->getNumParents(); ++ii_parent ) { osg::Node* parent_node = product_shape->m_product_switch->getParent( ii_parent ); const std::string parent_name = parent_node->getName(); std::cout << __FUNC__ << ": product_shape->m_product_switch->getNumParents() > 0" << std::endl; } #endif group->addChild( product_shape->m_product_switch ); product_shape->m_added_to_node = true; } } } } if( group->getName().size() < 1 ) { std::stringstream switch_name; switch_name << "#" << entity_id << "=" << obj_def->className() << " parent group"; group->setName( switch_name.str().c_str() ); } const std::vector<weak_ptr<IfcRelAggregates> >& vec_IsDecomposedBy = obj_def->m_IsDecomposedBy_inverse; for( size_t ii = 0; ii < vec_IsDecomposedBy.size(); ++ii ) { const weak_ptr<IfcRelAggregates>& rel_aggregates_weak_ptr = vec_IsDecomposedBy[ii]; if( rel_aggregates_weak_ptr.expired() ) { continue; } shared_ptr<IfcRelAggregates> rel_aggregates( rel_aggregates_weak_ptr ); if( rel_aggregates ) { const std::vector<shared_ptr<IfcObjectDefinition> >& vec_related_objects = rel_aggregates->m_RelatedObjects; for( size_t jj = 0; jj < vec_related_objects.size(); ++jj ) { const shared_ptr<IfcObjectDefinition>& child_obj_def = vec_related_objects[jj]; if( child_obj_def ) { osg::ref_ptr<osg::Switch> group_subparts = new osg::Switch(); std::stringstream group_subparts_name; group_subparts_name << "#" << child_obj_def->m_id << "=" << child_obj_def->className(); #ifdef _DEBUG group_subparts_name << ", RelatedObjects[" << jj << "]"; #endif group_subparts->setName( group_subparts_name.str().c_str() ); group->addChild( group_subparts ); resolveProjectStructure( child_obj_def, group_subparts ); } } } } shared_ptr<IfcSpatialStructureElement> spatial_ele = dynamic_pointer_cast<IfcSpatialStructureElement>( obj_def ); if( spatial_ele ) { const std::vector<weak_ptr<IfcRelContainedInSpatialStructure> >& vec_contains = spatial_ele->m_ContainsElements_inverse; for( size_t ii = 0; ii < vec_contains.size(); ++ii ) { const weak_ptr<IfcRelContainedInSpatialStructure>& rel_contained_weak_ptr = vec_contains[ii]; if( rel_contained_weak_ptr.expired() ) { continue; } shared_ptr<IfcRelContainedInSpatialStructure> rel_contained( rel_contained_weak_ptr ); if( rel_contained ) { const std::vector<shared_ptr<IfcProduct> >& vec_related_elements = rel_contained->m_RelatedElements; for( size_t jj = 0; jj < vec_related_elements.size(); ++jj ) { const shared_ptr<IfcProduct>& related_product = vec_related_elements[jj]; if( related_product ) { osg::ref_ptr<osg::Switch> group_subparts = new osg::Switch(); std::stringstream group_subparts_name; group_subparts_name << "#" << related_product->m_id << "=" << related_product->className(); #ifdef _DEBUG group_subparts_name << ", RelatedElements[" << jj << "]"; #endif group_subparts->setName( group_subparts_name.str().c_str() ); group->addChild( group_subparts ); resolveProjectStructure( related_product, group_subparts ); } } } } } // TODO: handle IfcRelAssignsToProduct } void readAppearanceFromPropertySet( const shared_ptr<IfcPropertySet>& prop_set, shared_ptr<ProductShapeInputData>& product_shape ) { if( !prop_set ) { return; } for( auto& ifc_property : prop_set->m_HasProperties ) { if( !ifc_property ) { continue; } shared_ptr<IfcSimpleProperty> simple_property = dynamic_pointer_cast<IfcSimpleProperty>( ifc_property ); if( simple_property ) { // ENTITY IfcSimpleProperty ABSTRACT SUPERTYPE OF(ONEOF( IfcPropertyBoundedValue, IfcPropertyEnumeratedValue, IfcPropertyListValue, // IfcPropertyReferenceValue, IfcPropertySingleValue, IfcPropertyTableValue)) shared_ptr<IfcIdentifier> property_name = simple_property->m_Name; std::wstring name_str = property_name->m_value; if( name_str.compare( L"LayerName" ) == 0 ) { // TODO: implement layers } shared_ptr<IfcText> description = simple_property->m_Description; shared_ptr<IfcPropertySingleValue> property_single_value = dynamic_pointer_cast<IfcPropertySingleValue>( simple_property ); if( property_single_value ) { //shared_ptr<IfcValue>& nominal_value = property_single_value->m_NominalValue; //optional //shared_ptr<IfcUnit>& unit = property_single_value->m_Unit; //optional } continue; } shared_ptr<IfcComplexProperty> complex_property = dynamic_pointer_cast<IfcComplexProperty>( ifc_property ); if( complex_property ) { if( !complex_property->m_UsageName ) continue; if( complex_property->m_UsageName->m_value.compare( L"Color" ) == 0 ) { carve::geom::vector<4> vec_color; m_representation_converter->getStylesConverter()->convertIfcComplexPropertyColor( complex_property, vec_color ); shared_ptr<AppearanceData> appearance_data( new AppearanceData( -1 ) ); if( !appearance_data ) { throw IfcPPOutOfMemoryException( __FUNC__ ); } appearance_data->m_apply_to_geometry_type = AppearanceData::ANY; appearance_data->m_color_ambient = vec_color; appearance_data->m_color_diffuse = vec_color; appearance_data->m_color_specular = vec_color; appearance_data->m_shininess = 35.f; product_shape->addAppearance( appearance_data ); } } } } //\brief method convertIfcProduct: Creates geometry objects (meshset with connected vertex-edge-face graph) from an IfcProduct object // caution: when using OpenMP, this method runs in parallel threads, so every write access to member variables needs a write lock void convertIfcProduct( shared_ptr<ProductShapeInputData>& product_shape ) { shared_ptr<IfcProduct> ifc_product( product_shape->m_ifc_product ); if( !ifc_product ) { return; } if( !ifc_product->m_Representation ) { return; } //const int product_id = ifc_product->m_id; const double length_factor = m_ifc_model->getUnitConverter()->getLengthInMeterFactor(); product_shape->m_ifc_product = ifc_product; // evaluate IFC geometry shared_ptr<IfcProductRepresentation>& product_representation = ifc_product->m_Representation; std::vector<shared_ptr<IfcRepresentation> >& vec_representations = product_representation->m_Representations; for( size_t i_representations = 0; i_representations < vec_representations.size(); ++i_representations ) { const shared_ptr<IfcRepresentation>& representation = vec_representations[i_representations]; try { shared_ptr<ProductRepresentationData> representation_data( new ProductRepresentationData() ); m_representation_converter->convertIfcRepresentation( representation, representation_data ); product_shape->m_vec_representations.push_back( representation_data ); } catch( IfcPPOutOfMemoryException& e ) { throw e; } catch( IfcPPException& e ) { messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" ); } catch( std::exception& e ) { messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" ); } } // IfcProduct has an ObjectPlacement that can be local or global carve::math::Matrix product_placement_matrix( carve::math::Matrix::IDENT() ); if( ifc_product->m_ObjectPlacement ) { // IfcPlacement2Matrix follows related placements in case of local coordinate systems std::unordered_set<IfcObjectPlacement*> placement_already_applied; PlacementConverter::convertIfcObjectPlacement( ifc_product->m_ObjectPlacement, length_factor, product_placement_matrix, this, placement_already_applied ); product_shape->applyPosition( product_placement_matrix ); } // handle openings std::vector<shared_ptr<ProductShapeInputData> > vec_opening_data; const shared_ptr<IfcElement> ifc_element = dynamic_pointer_cast<IfcElement>( ifc_product ); if( ifc_element ) { m_representation_converter->subtractOpenings( ifc_element, product_shape ); } // Fetch the IFCProduct relationships if( ifc_product->m_IsDefinedBy_inverse.size() > 0 ) { std::vector<weak_ptr<IfcRelDefinesByProperties> >& vec_IsDefinedBy_inverse = ifc_product->m_IsDefinedBy_inverse; for( size_t i = 0; i < vec_IsDefinedBy_inverse.size(); ++i ) { shared_ptr<IfcRelDefinesByProperties> rel_def( vec_IsDefinedBy_inverse[i] ); shared_ptr<IfcPropertySetDefinitionSelect> relating_property_definition_select = rel_def->m_RelatingPropertyDefinition; if( relating_property_definition_select ) { // TYPE IfcPropertySetDefinitionSelect = SELECT (IfcPropertySetDefinition ,IfcPropertySetDefinitionSet); shared_ptr<IfcPropertySetDefinition> property_set_def = dynamic_pointer_cast<IfcPropertySetDefinition>( relating_property_definition_select ); if( property_set_def ) { shared_ptr<IfcPropertySet> property_set = dynamic_pointer_cast<IfcPropertySet>( property_set_def ); if( property_set ) { readAppearanceFromPropertySet( property_set, product_shape ); } continue; } shared_ptr<IfcPropertySetDefinitionSet> property_set_def_set = dynamic_pointer_cast<IfcPropertySetDefinitionSet>( relating_property_definition_select ); if( property_set_def_set ) { std::vector<shared_ptr<IfcPropertySetDefinition> >& vec_propterty_set_def = property_set_def_set->m_vec; std::vector<shared_ptr<IfcPropertySetDefinition> >::iterator it_property_set_def; for( it_property_set_def = vec_propterty_set_def.begin(); it_property_set_def != vec_propterty_set_def.end(); ++it_property_set_def ) { shared_ptr<IfcPropertySetDefinition> property_set_def2 = ( *it_property_set_def ); if( property_set_def2 ) { shared_ptr<IfcPropertySet> property_set = dynamic_pointer_cast<IfcPropertySet>( property_set_def2 ); if( property_set ) { readAppearanceFromPropertySet( property_set, product_shape ); } } } continue; } } } } } };
35.792806
211
0.698062
[ "geometry", "object", "vector", "model" ]
8c228b8caa432f79f73093206d45f13dbfb55503
5,819
h
C
src/ripple/app/ledger/impl/LedgerDeltaAcquire.h
BRTNetwork/brtd
5bda54d04a669bfbe4cfd4bb5399d56caeaf5a1a
[ "BSL-1.0" ]
null
null
null
src/ripple/app/ledger/impl/LedgerDeltaAcquire.h
BRTNetwork/brtd
5bda54d04a669bfbe4cfd4bb5399d56caeaf5a1a
[ "BSL-1.0" ]
null
null
null
src/ripple/app/ledger/impl/LedgerDeltaAcquire.h
BRTNetwork/brtd
5bda54d04a669bfbe4cfd4bb5399d56caeaf5a1a
[ "BSL-1.0" ]
null
null
null
//------------------------------------------------------------------------------ /* This file is part of brtd: https://github.com/BRTNetwork/brtd Copyright (c) 2012, 2020 Ripple Labs Inc. 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. */ //============================================================================== #ifndef RIPPLE_APP_LEDGER_LEDGERDELTAACQUIRE_H_INCLUDED #define RIPPLE_APP_LEDGER_LEDGERDELTAACQUIRE_H_INCLUDED #include <ripple/app/ledger/InboundLedger.h> #include <ripple/app/ledger/Ledger.h> #include <ripple/app/ledger/impl/TimeoutCounter.h> #include <ripple/basics/CountedObject.h> #include <ripple/basics/base_uint.h> #include <list> #include <map> namespace ripple { class InboundLedgers; class PeerSet; namespace test { class LedgerReplayClient; } // namespace test /** * Manage the retrieval of a ledger delta (header and transactions) * from the network. Before asking peers, always check if the local * node has the ledger. */ class LedgerDeltaAcquire final : public TimeoutCounter, public std::enable_shared_from_this<LedgerDeltaAcquire>, public CountedObject<LedgerDeltaAcquire> { public: /** * A callback used to notify that the delta's data is ready or failed. * @param successful if the ledger delta data was acquired successfully * @param hash hash of the ledger to build */ using OnDeltaDataCB = std::function<void(bool successful, uint256 const& hash)>; /** * Constructor * @param app Application reference * @param inboundLedgers InboundLedgers reference * @param ledgerHash hash of the ledger * @param ledgerSeq sequence number of the ledger * @param peerSet manage a set of peers that we will ask for the ledger */ LedgerDeltaAcquire( Application& app, InboundLedgers& inboundLedgers, uint256 const& ledgerHash, std::uint32_t ledgerSeq, std::unique_ptr<PeerSet> peerSet); ~LedgerDeltaAcquire() override; /** * Start the LedgerDeltaAcquire task * @param numPeers number of peers to try initially */ void init(int numPeers); /** * Process the data extracted from a peer's reply * @param info info (header) of the ledger * @param orderedTxns set of Txns of the ledger * * @note info and Txns must have been verified against the ledger hash */ void processData( LedgerInfo const& info, std::map<std::uint32_t, std::shared_ptr<STTx const>>&& orderedTxns); /** * Try to build the ledger if not already * @param parent parent ledger * @return the ledger if built, nullptr otherwise (e.g. waiting for peers' * replies of the ledger info (header) and Txns.) * @note may throw runtime_error if the replay failed due to data error */ std::shared_ptr<Ledger const> tryBuild(std::shared_ptr<Ledger const> const& parent); /** * Add a reason and a callback to the LedgerDeltaAcquire subtask. * The reason is used to process the ledger once it is replayed. * The callback is called when the delta's data is ready or failed * @note the callback will be called once and only once unless this object * is destructed before the call. */ void addDataCallback(InboundLedger::Reason reason, OnDeltaDataCB&& cb); static char const* getCountedObjectName() { return "LedgerDeltaAcquire"; } private: void onTimer(bool progress, ScopedLockType& peerSetLock) override; std::weak_ptr<TimeoutCounter> pmDowncast() override; /** * Trigger another round * @param limit number of new peers to send the request * @param sl lock. this function must be called with the lock */ void trigger(std::size_t limit, ScopedLockType& sl); /** * Process a newly built ledger, such as store it. * @param sl lock. this function must be called with the lock * @param reason specific new reason if any * @note this function should be called (1) when the ledger is built the * first time, and (2) when a LedgerReplayTask with a new reason * is added. */ void onLedgerBuilt( ScopedLockType& sl, std::optional<InboundLedger::Reason> reason = {}); /** * Call the OnDeltaDataCB callbacks * @param sl lock. this function must be called with the lock */ void notify(ScopedLockType& sl); InboundLedgers& inboundLedgers_; std::uint32_t const ledgerSeq_; std::unique_ptr<PeerSet> peerSet_; std::shared_ptr<Ledger const> replayTemp_ = {}; std::shared_ptr<Ledger const> fullLedger_ = {}; std::map<std::uint32_t, std::shared_ptr<STTx const>> orderedTxns_; std::vector<OnDeltaDataCB> dataReadyCallbacks_; std::set<InboundLedger::Reason> reasons_; std::uint32_t noFeaturePeerCount = 0; bool fallBack_ = false; friend class LedgerReplayTask; // for asserts only friend class test::LedgerReplayClient; }; } // namespace ripple #endif
33.635838
80
0.667469
[ "object", "vector" ]
8c307a6a737499ce71a7ed6a6f26809ce0e79ddc
5,740
c
C
orte/mca/grpcomm/pmi/pmi2_pmap_parser.c
urids/XSCALAMPI
38624f682211d55c047183637fed8dbcc09f6d74
[ "BSD-3-Clause-Open-MPI" ]
1
2019-02-25T19:56:36.000Z
2019-02-25T19:56:36.000Z
orte/mca/grpcomm/pmi/pmi2_pmap_parser.c
urids/XSCALAMPI
38624f682211d55c047183637fed8dbcc09f6d74
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
orte/mca/grpcomm/pmi/pmi2_pmap_parser.c
urids/XSCALAMPI
38624f682211d55c047183637fed8dbcc09f6d74
[ "BSD-3-Clause-Open-MPI" ]
3
2015-11-29T06:00:56.000Z
2021-03-29T07:03:29.000Z
/* -*- Mode: C; c-basic-offset:4 ; -*- */ /* * * Copyright (c) 2013 Mellanox Technologies, Inc. * All rights reserved. * Copyright (c) 2014 Intel, Inc. All rights reserved. * $COPYRIGHT$ * Additional copyrights may follow * * $HEADER$ * */ #ifdef STANDALONE_TEST #define WANT_PMI2_SUPPORT 1 #else #include "orte_config.h" #include "orte/constants.h" #include "orte/types.h" #include "grpcomm_pmi.h" #endif /** pmi2 process mapping is returned as a comma separated list of tuples: ex: (vector,(0,4,4),(0,4,1)) slurm cyclic distro of 4 ranks over 2 nodes: (vector,(0,2,1),(0,2,1)) slurm block distro of 4 ranks over 2 nodes: (vector,(0,2,2)) Format of each tuple is (base, H, L), where H is number of nodes spawned by tuple, L is number of ranks per node, base is offset from node 0. Tuple can be visualized as a rectangle on two dimensional (Hosts, Local Ranks) plane: ------------------------------------ Hosts -> | H | +--------+ |<- base -->| | | | | L | +--------+ Local Ranks V Note that ranks increase by column. Tuple (0,2,3) looks like: 0 3 1 4 2 5 */ #include <stdio.h> #include <stdlib.h> #include <string.h> static int find_my_node(char *map, int me) { int abs_rank; int base, H, L; char *p; p = map; abs_rank = 0; while (NULL != (p = strstr(p+1, ",("))) { if (3 != sscanf(p, ",(%d,%d,%d)", &base, &H, &L)) { return -1; } if (me >= abs_rank && me < abs_rank + H*L) { /* found my rectangle, compute node */ return base + (me - abs_rank)/L; } abs_rank += H*L; } return -1; } static int *find_lrs(char *map, int my_node, int *nlrs) { int abs_rank; int base, H, L; char *p; int *lrs; int max_lr; int i; p = map; abs_rank = 0; *nlrs = 0; max_lr = 16; lrs = malloc(max_lr * sizeof(int)); while (NULL != (p = strstr(p+1, ",("))) { if (3 != sscanf(p, ",(%d,%d,%d)", &base, &H, &L)) { free(lrs); return NULL; } if (base <= my_node && my_node < base + H) { if (*nlrs + L >= max_lr) { lrs = realloc(lrs, (max_lr + L) * sizeof(int)); if (NULL == lrs) { *nlrs = 0; free(lrs); return NULL; } max_lr += L; } /* skip (my_node - base) columns of L elems, * numbers in my column are local to me */ for (i = 0; i < L; i++) { lrs[*nlrs] = (my_node - base) * L + i + abs_rank; (*nlrs) ++; } } abs_rank += H*L; } if (0 == *nlrs) { free(lrs); lrs = 0; } return lrs; } /** * @param pmap process map as returned by PMI_process_mapping * attribute * @param my_rank * @param node set to my node id * @param nlrs set to the number of local ranks returned * * @return array that contains ranks local to my_rank or NULL * on failure. Array must be freed by the caller. */ int *orte_grpcomm_pmi2_parse_pmap(char *pmap, int my_rank, int *node, int *nlrs) { char *p; p = strstr(pmap, "(vector"); if (NULL == p) { return NULL; } *node = find_my_node(p, my_rank); if (0 > *node) { return NULL; } return find_lrs(p, *node, nlrs); } #ifdef STANDALONE_TEST #include <assert.h> static void dump_lrs(int *lrs, int me, int node, int n) { int i; printf("Total %d ranks/node, node %d me %d\n", n, node, me); for (i = 0; i < n; i++) { printf("%d ", lrs[i]); } printf("\n"); free(lrs); } int main(int argc, char **argv) { int me, n, node; int *lrs; char *pmap; int a1[] = {0, 1}; int a2[] = {2, 3}; int a3[] = {0, 2}; int a4[] = {1, 3}; int a5[] = {0,1,3,2,16,17}; int a6[] = {8,9,10,11,19}; if (argc == 3) { me = atoi(argv[1]); lrs = orte_grpcomm_pmi2_parse_pmap(argv[2], me, &node, &n); if (NULL == lrs) { printf("can not parse pmap\n"); exit(1); } dump_lrs(lrs, me, node, n); exit(0); } /* built in cases */ pmap = "(vector,(0,2,2))"; me = 1; lrs = orte_grpcomm_pmi2_parse_pmap(pmap, me, &node, &n); assert(lrs); assert(n == 2); assert(memcmp(lrs, a1, 2) == 0); free(lrs); pmap = "(vector,(0,2,2))"; me = 2; lrs = orte_grpcomm_pmi2_parse_pmap(pmap, me, &node, &n); assert(lrs); assert(n == 2); assert(memcmp(lrs, a2, 2) == 0); free(lrs); /* cyclic distro which skips node 0 */ pmap = "(vector,(1,2,1),(1,2,1))"; me = 0; lrs = orte_grpcomm_pmi2_parse_pmap(pmap, me, &node, &n); assert(lrs); assert(n == 2); assert(memcmp(lrs, a3, n) == 0); free(lrs); pmap = "(vector,(1,2,1),(1,2,1))"; me = 3; lrs = orte_grpcomm_pmi2_parse_pmap(pmap, me, &node, &n); assert(lrs); assert(n == 2); assert(memcmp(lrs, a4, n) == 0); free(lrs); pmap = "(vector,(0,4,4),(0,1,2),(1,3,1))"; me = 3; lrs = orte_grpcomm_pmi2_parse_pmap(pmap, me, &node, &n); assert(lrs); assert(n == 6); assert(memcmp(lrs, a5, n) == 0); free(lrs); pmap = "(vector,(0,4,4),(0,1,2),(1,3,1))"; me = 10; lrs = orte_grpcomm_pmi2_parse_pmap(pmap, me, &node, &n); assert(lrs); assert(n == 5); assert(memcmp(lrs, a6, n) == 0); free(lrs); return 0; } #endif
23.145161
67
0.487108
[ "vector" ]
8c3c39367673d7ccd2e67914f147e37371566545
1,956
h
C
include/maxsdk/Util/IDlgShowingStatusForPolyObj.h
bear1704/DX11_Portfolio
8ab70c793cf7f10eceaea34afb786264828c09a0
[ "Apache-2.0" ]
null
null
null
include/maxsdk/Util/IDlgShowingStatusForPolyObj.h
bear1704/DX11_Portfolio
8ab70c793cf7f10eceaea34afb786264828c09a0
[ "Apache-2.0" ]
null
null
null
include/maxsdk/Util/IDlgShowingStatusForPolyObj.h
bear1704/DX11_Portfolio
8ab70c793cf7f10eceaea34afb786264828c09a0
[ "Apache-2.0" ]
null
null
null
// // Copyright 2012 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // // #pragma once #include "../Noncopyable.h" namespace MaxSDK { namespace Util { //! \brief A pure virtual interface for Poly Object's UI as dialog Showing Status. /*! class IDlgShowingStatusForPolyObj If the Poly Objects' UI setting is used as dialog, dialog will replace caddy to show the parameters of the Poly Objects. If the dialog is showing right now, users change the Poly Objects' UI setting as caddy, a tip dialog at the bottom-center of the View panel in Max will pop up and remind users that the caddy controls will now be used. */ class IDlgShowingStatusForPolyObj : public MaxSDK::Util::Noncopyable { public: //! Destructor virtual ~IDlgShowingStatusForPolyObj(){} /*! To get whether the Poly Object's UI as dialog is currently showing or not. \return true if the dialog is currently showing, false otherwise. */ virtual bool IsDlgShowingForPolyObj() const = 0; /*! To set the showing status of Poly Object's UI as dialog. \param[in] bShowing if bShowing is true, the showing status of Poly Object's UI as dialog is on. false otherwise. */ virtual void SetDlgShowingForPolyObj(bool bShowing) = 0; /*! To get whether the Poly Object's UI as dialog is set as on or off. \return true if the dialog is set as on, false otherwise. */ virtual bool GetDlgShowSettingForPolyObj() const = 0; /*! To set the showing setting of Poly Object's UI as dialog. \param[in] bDlgShow if bDlgShow is true, the showing setting of Poly Object's UI as dialog is on. false otherwise. */ virtual void SetDlgShowSettingForPolyObj(bool bDlgShow) = 0; }; UtilExport IDlgShowingStatusForPolyObj* GetDlgShowingStatusForPolyObj(); } }
33.724138
93
0.748978
[ "object" ]
8c3f7fff4022f96de1a2fc4f0272e0be378637b9
15,679
c
C
c2000/C2000Ware_1_00_06_00/driverlib/f2807x/examples/cpu1/mcbsp/mcbsp_ex5_ext_loopback.c
ramok/Themis_ForHPSDR
d0f323a843ac0a488ef816ccb7c828032855a40a
[ "Unlicense" ]
null
null
null
c2000/C2000Ware_1_00_06_00/driverlib/f2807x/examples/cpu1/mcbsp/mcbsp_ex5_ext_loopback.c
ramok/Themis_ForHPSDR
d0f323a843ac0a488ef816ccb7c828032855a40a
[ "Unlicense" ]
null
null
null
c2000/C2000Ware_1_00_06_00/driverlib/f2807x/examples/cpu1/mcbsp/mcbsp_ex5_ext_loopback.c
ramok/Themis_ForHPSDR
d0f323a843ac0a488ef816ccb7c828032855a40a
[ "Unlicense" ]
1
2021-07-21T08:10:37.000Z
2021-07-21T08:10:37.000Z
//############################################################################# // // FILE: mcbsp_ex5_ext_loopback.c // // TITLE: McBSP external loopback example. // //! \addtogroup driver_example_list //! <h1> McBSP external loopback example </h1> //! //! This example demonstrates the McBSP operation using external loopback. //! This example does not use interrupts. Instead, a polling method is used //! to check the receive data. The incoming data is checked for accuracy. //! //! Three different serial word sizes can be tested. Before compiling //! this project, select the serial word size of 8, 16 or 32 by using //! the \#define statements at the beginning of the code. //! //! This program will execute until terminated by the user. //! //! \b 8-bit \b word \b example: \n //! The sent data looks like this:\n //! 00 01 02 03 04 05 06 07 .... FE FF\n //! //! \b 16-bit \b word \b example: \n //! The sent data looks like this:\n //! 0000 0001 0002 0003 0004 0005 0006 0007 .... FFFE FFFF\n //! //! \b 32-bit \b word \b example: \n //! The sent data looks like this: \n //! FFFF0000 FFFE0001 FFFD0002 .... 0000FFFF \n //! //! \b External \b Connections \n //! \b McBSPA \b Signals - \b McBSPB \b signals //! - MCLKXA - MCLKRB //! - MFSXA - MFSRB //! - MDXA - MDRB //! - MCLKRA - MCLKXB //! - MFSRA - MFSXB //! - MDRA - MDXB //! //! \b Watch \b Variables: \n //! - \b txData1A - Sent data word by McBSPA Transmitter:8 or 16-bit or low //! half of 32-bit //! - \b txData2A - Sent data word by McBSPA Transmitter:upper half of 32-bit //! - \b rxData1A - Received data word by MCBSPA Receiver:8 or 16-bit or lower //! half of 32-bit //! - \b rxData2A - Received data word by McBSPA Receiver:upper half of 32-bit //! - \b txData1B - Sent data word by McBSPB Transmitter:8 or 16-bit or low //! half of 32-bit //! - \b txData2B - Sent data word by McBSPB Transmitter:upper half of 32-bit //! - \b rxData1B - Received data word by McBSPB Receiver:8 or 16-bit or lower //! half of 32-bit //! - \b rxData2B - Received data word by McBSPB Receiver:upper half of 32-bit //! - \b errCountGlobal - Error counter //! //! \note txData2A, rxData2A, txData2B and rxData2B are not used for 8-bit or //! 16-bit word size. // //############################################################################# // $TI Release: F2807x Support Library v3.05.00.00 $ // $Release Date: Thu Oct 18 15:52:12 CDT 2018 $ // $Copyright: // Copyright (C) 2014-2018 Texas Instruments Incorporated - http://www.ti.com/ // // 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 Texas Instruments Incorporated 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. // $ //############################################################################# // // Included Files // #include "device.h" #include "driverlib.h" // // Define to select wait delay. // #define MCBSP_CYCLE_NOP0(n) __asm(" RPT #(" #n ") || NOP") #define MCBSP_CYCLE_NOP(n) MCBSP_CYCLE_NOP0(n) // // Define to select the word-size for McBSP operation to 8, 16 or 32 bit. // //#define WORD_SIZE 8U //#define WORD_SIZE 16U #define WORD_SIZE 32U // // Globals // uint32_t errCountGlobal = 0; // // Variables for transmitting, receiving and testing the data. // uint16_t txData1A = 0x0000; uint16_t txData2A = 0x0000; uint16_t rxData1A = 0x0000; uint16_t rxData2A = 0x0000; uint16_t txData1B = 0x0000; uint16_t txData2B = 0x0000; uint16_t rxData1B = 0x0000; uint16_t rxData2B = 0x0000; uint16_t dataSize; // // Function Prototypes // extern void setupMcBSPAPinmux(void); extern void setupMcBSPBPinmux(void); void initMcBSPLoopback(void); void initTransmitter(uint32_t base); void initReceiver(uint32_t base); void enableModule(uint32_t base); void resetModule(uint32_t base); // // Main // void main(void) { uint32_t tempData; errCountGlobal = 0x0; // // Initialize device clock and peripherals. // Device_init(); // // Disable all the interrupts. // DINT; // // Setup GPIO by disabling pin locks and enabling pullups. // Device_initGPIO(); // // Initialize GPIOs for McBSPA and McBSPB. // setupMcBSPAPinmux(); setupMcBSPBPinmux(); // // Initialize PIE and clear PIE registers. Disables CPU interrupts. // Interrupt_initModule(); // // Initialize the PIE vector table with pointers to the shell Interrupt // Service Routines (ISR). // Interrupt_initVectorTable(); dataSize = WORD_SIZE; // // Reset McBSPA & McBSPB modules. // resetModule(MCBSPA_BASE); resetModule(MCBSPB_BASE); // // Initialize the transmitter & receiver modules in McBSPA & McBSPB. // initTransmitter(MCBSPA_BASE); initReceiver(MCBSPA_BASE); initTransmitter(MCBSPB_BASE); initReceiver(MCBSPB_BASE); // // Enable McBSPA & McBSP modules. // enableModule(MCBSPA_BASE); enableModule(MCBSPB_BASE); // // Run a loopback test in 8-bit mode. // if(dataSize == 8) { txData1A = 0x0000; while(1) { // // Transmit 8-bit data from McBSPSA Tx. // while(!McBSP_isTxReady(MCBSPA_BASE)); McBSP_write16bitData(MCBSPA_BASE, txData1A); // // Checks if data is received at McBSPB Rx. // while(!McBSP_isRxReady(MCBSPB_BASE)); rxData1B = McBSP_read16bitData(MCBSPB_BASE); txData1B = rxData1B; // // Retransmit the received data from McBSPB Tx to McBSPA Rx. // while(!McBSP_isTxReady(MCBSPB_BASE)); McBSP_write16bitData(MCBSPB_BASE, txData1B); // // Receive data at McBSPA Rx. // while(!McBSP_isRxReady(MCBSPA_BASE)); rxData1A = McBSP_read16bitData(MCBSPA_BASE); // // Check if correct data is received. // if(rxData1A != txData1A) { errCountGlobal++; ESTOP0; } txData1A++; txData1A = txData1A & 0x00FF; NOP; } } else if(dataSize == 16) { txData1A = 0x0000; while(1) { // // Transmit 16-bit data from McBSPSA Tx. // while(!McBSP_isTxReady(MCBSPA_BASE)); McBSP_write16bitData(MCBSPA_BASE, txData1A); // // Checks if data is received at McBSPB Rx. // while(!McBSP_isRxReady(MCBSPB_BASE)); rxData1B = McBSP_read16bitData(MCBSPB_BASE); txData1B = rxData1B; // // Retransmit the received data from McBSPB Tx to McBSPA Rx. // while(!McBSP_isTxReady(MCBSPB_BASE)); McBSP_write16bitData(MCBSPB_BASE, txData1B); // // Receive data at McBSPA Rx. // while(!McBSP_isRxReady(MCBSPA_BASE)); rxData1A = McBSP_read16bitData(MCBSPA_BASE); // // Check if correct data is received. // if(rxData1A != txData1A) { errCountGlobal++; ESTOP0; } txData1A++; NOP; } } else if(dataSize == 32) { txData2A = 0xFFFF; txData1A = 0x0000; while(1) { // // Transmit 32-bit data from McBSPSA Tx. // tempData = (txData1A|(((uint32_t)txData2A) << 16U)); while(!McBSP_isTxReady(MCBSPA_BASE)); McBSP_write32bitData(MCBSPA_BASE, tempData); // // Check if data is received at McBSPB Rx. // while(!McBSP_isRxReady(MCBSPB_BASE)); tempData = McBSP_read32bitData(MCBSPB_BASE); rxData1B = tempData & 0xFFFF; rxData2B = tempData >> 16U; // // Retransmit the received data from McBSPB Tx to McBSPA Rx. // txData1B = rxData1B; txData2B = rxData2B; tempData = (txData1B|(((uint32_t)txData2B) << 16U)); while(!McBSP_isTxReady(MCBSPB_BASE)); McBSP_write32bitData(MCBSPB_BASE, tempData); // // Receive data at McBSPA Rx. // while(!McBSP_isRxReady(MCBSPA_BASE)); tempData = McBSP_read32bitData(MCBSPA_BASE); rxData1A = tempData & 0xFFFF; rxData2A = tempData >> 16U; // // Check if correct data is received. // if(rxData1A != txData1A || rxData2A != txData2A) { errCountGlobal++; ESTOP0; } txData1A++; txData2A--; NOP; } } } // // Enable Module - This function enables the modules in McBSP. // void enableModule(uint32_t base) { // // Enable Sample rate generator and frame-sync logic and wait for atleast // 2 CLKG clock cycles. // McBSP_enableSampleRateGenerator(base); McBSP_enableFrameSyncLogic(base); // // Wait for CPU cycles equivalent to 2 CLKG cycles-init delay. // Total cycles required = 2*(SYSCLK/(LSPCLK/(1+CLKGDV_VAL))). In this // example LSPCLK = SYSCLK/4 and CLKGDV_VAL = 1. // MCBSP_CYCLE_NOP(16); // // Release Tx from reset. // McBSP_enableTransmitter(base); McBSP_enableReceiver(base); } // // Reset Module - This function disables the modules in McBSP. // void resetModule(uint32_t base) { // // Reset FS generator, sample rate generator, transmitter & receiver. // McBSP_resetFrameSyncLogic(base); McBSP_resetSampleRateGenerator(base); McBSP_resetTransmitter(base); McBSP_resetReceiver(base); } // // Init Transmitter - This function initialises McBSP transmitter module. // void initTransmitter(uint32_t base) { // // Right justify word. // McBSP_setRxSignExtension(base, MCBSP_RIGHT_JUSTIFY_FILL_ZERO); // // Set Rx & Tx delay to 1 cycle. // McBSP_setTxDataDelayBits(base, MCBSP_DATA_DELAY_BIT_1); // // Configure McBSP data behaviour: phase = 1; frame length = 1 word and // word length = dataSize. // if(dataSize == 8) { McBSP_setTxDataSize(base, MCBSP_PHASE_ONE_FRAME, MCBSP_BITS_PER_WORD_8, 0); } else if(dataSize == 16) { McBSP_setTxDataSize(base, MCBSP_PHASE_ONE_FRAME, MCBSP_BITS_PER_WORD_16, 0); } else if(dataSize == 32) { McBSP_setTxDataSize(base, MCBSP_PHASE_ONE_FRAME, MCBSP_BITS_PER_WORD_32, 0); } // // Configure Frame synchronization behaviour. // // // Enable transmit frame-sync ignore function. // McBSP_disableTxFrameSyncErrorDetection(base); // // Set Tx frame-sync source as internal. // McBSP_setTxFrameSyncSource(base, MCBSP_TX_INTERNAL_FRAME_SYNC_SOURCE); // // Set the trigger source for internally generated frame-sync pulse. // McBSP_setTxInternalFrameSyncSource(base, MCBSP_TX_INTERNAL_FRAME_SYNC_DATA); // // Set no external clock sync for CLKG. // McBSP_disableSRGSyncFSR(base); // // Set frame-sync pulse period. // McBSP_setFrameSyncPulsePeriod(base, 320); // // Set frame-sync pulse width. // McBSP_setFrameSyncPulseWidthDivider(base, 1); // // Configure Tx Clock behaviour. // // // Set LSPCLK as input source for sample rate generator. // McBSP_setTxSRGClockSource(base, MCBSP_SRG_TX_CLOCK_SOURCE_LSPCLK); // // Set CLKX source as sample rate generator. // McBSP_setTxClockSource(base, MCBSP_INTERNAL_TX_CLOCK_SOURCE); // // Set Divide down value for CLKG. // McBSP_setSRGDataClockDivider(base, 1); // // Wait for CPU cycles equivalent to 2 SRG cycles-init delay. // Total cycles required = 2*(SYSCLK/LSPCLK). In this example // LSPCLK = SYSCLK/4. // MCBSP_CYCLE_NOP(8); } // // Init Receiver - This function initialises the McBSP Receiver module. // void initReceiver(uint32_t base) { // // Configure McBSP data behaviour. // if(dataSize == 8) { McBSP_setRxDataSize(base, MCBSP_PHASE_ONE_FRAME, MCBSP_BITS_PER_WORD_8, 0); } else if(dataSize == 16) { McBSP_setRxDataSize(base, MCBSP_PHASE_ONE_FRAME, MCBSP_BITS_PER_WORD_16, 0); } else if(dataSize == 32) { McBSP_setRxDataSize(base, MCBSP_PHASE_ONE_FRAME, MCBSP_BITS_PER_WORD_32, 0); } // // Set Rx data delay to 1 cycle. // McBSP_setRxDataDelayBits(base, MCBSP_DATA_DELAY_BIT_1); // // Set receive sign-extension and justification mode. // McBSP_setRxSignExtension(base, MCBSP_RIGHT_JUSTIFY_FILL_ZERO); // // Configure Rx frame-sync behaviour. // // // Set Rx frame sync source as external. // McBSP_setRxFrameSyncSource(base, MCBSP_RX_EXTERNAL_FRAME_SYNC_SOURCE); // // Disable DLB mode. // McBSP_disableLoopback(base); // // Set no external clock sync for CLKG i.e. GSYNC = 0. // McBSP_disableSRGSyncFSR(base); // // Configure Rx clock behaviour. // // // Set MCLKR pin as source for CLKR. // McBSP_setRxClockSource(base, MCBSP_EXTERNAL_RX_CLOCK_SOURCE); // // Set LSPCLK as input source for sample rate generator. // McBSP_setRxSRGClockSource(base, MCBSP_SRG_RX_CLOCK_SOURCE_LSPCLK); // // Set Divide down value for CLKG. // McBSP_setSRGDataClockDivider(base, 1); // // Wait for CPU cycles equivalent to 2 SRG cycles-init delay. // Total cycles required = 2*(SYSCLK/LSPCLK). In this example // LSPCLK = SYSCLK/4. // MCBSP_CYCLE_NOP(8); } // // End of File //
27.410839
80
0.597104
[ "vector" ]
8c3fe25b7a973988036d080aae89d7215edcec8a
9,372
h
C
iphone-private-frameworks-master/UIKit/UIWindow2.h
tt295362026/demo
7d6e9e75f29c992ea9c5693d38f76e0012bbbf15
[ "BSD-4-Clause" ]
2
2016-04-19T14:27:00.000Z
2017-03-17T17:49:20.000Z
iphone-private-frameworks-master/UIKit/UIWindow2.h
tt295362026/demo
7d6e9e75f29c992ea9c5693d38f76e0012bbbf15
[ "BSD-4-Clause" ]
null
null
null
iphone-private-frameworks-master/UIKit/UIWindow2.h
tt295362026/demo
7d6e9e75f29c992ea9c5693d38f76e0012bbbf15
[ "BSD-4-Clause" ]
null
null
null
/** * This header is generated by class-dump-z 0.1-11o. * class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3. */ #import "UIKit-Structs.h" #import <UIKit/UIWindow.h> #import <UIKit/UIView.h> #import <Availability2.h> #import <IOSurface/IOSurface.h> @class NSUndoManager; @interface UIWindow () +(CGRect)constrainFrameToScreen:(CGRect)screen; +(id)keyWindow; +(void)_noteStatusBarHeightChanged:(float)changed oldHeight:(float)height fence:(int)fence; +(CFDictionaryRef)_ioSurfacePropertyDictionaryForRect:(CGRect)rect; +(IOSurfaceRef)createIOSurfaceWithContextId:(unsigned)contextId frame:(CGRect)frame; +(IOSurfaceRef)createIOSurfaceWithContextIds:(const unsigned*)contextIds count:(size_t)count frame:(CGRect)frame; +(IOSurfaceRef)createScreenIOSurface; -(id)initWithFrame:(CGRect)frame; -(id)initWithFrame:(CGRect)frame output:(int)anOutput; -(id)initWithFrame:(CGRect)frame output:(int)anOutput bitsPerComponent:(int)component; -(id)initWithContentRect:(CGRect)contentRect; -(id)initWithCoder:(id)coder; -(void)dealloc; -(void)setContentView:(id)view; -(id)representation; -(BOOL)_ignoresHitTest; -(BOOL)_disableGroupOpacity; -(BOOL)_disableEdgeAntialiasing; -(unsigned)_contextId; -(void)makeKeyAndOrderFront:(id)front; -(void)orderFront:(id)front; -(void)_orderFrontWithoutMakingKey; -(void)orderOut:(id)anOut; -(void)setHidden:(BOOL)hidden; -(void)makeKey:(id)key; -(CGPoint)warpPoint:(CGPoint)point; -(BOOL)_pointInStatusBar:(CGPoint)statusBar; -(void)_handleMouseDown:(GSEventRef)down; -(void)_handleMouseDragged:(GSEventRef)dragged; -(void)_handleMouseUp:(GSEventRef)up; -(void)_handleMouseEntered:(GSEventRef)entered; -(void)_handleMouseMoved:(GSEventRef)moved; -(void)_handleMouseExited:(GSEventRef)exited; -(BOOL)_isScrollingEnabledForView:(id)view; -(void)_statusBarMouseDown:(GSEventRef)down; -(void)_statusBarMouseDragged:(GSEventRef)dragged; -(void)_statusBarMouseUp:(GSEventRef)up; -(void)_sendGesturesForEvent:(id)event; -(void)_sendTouchesForEvent:(id)event; -(void)_setExclusiveTouchView:(id)view; -(id)_exclusiveTouchView; -(void)_beginModalSession; -(void)_endModalSession; -(id)nextResponder; -(BOOL)_containedInAbsoluteResponderChain; -(CGPoint)convertWindowToDevice:(CGPoint)device; -(CGPoint)convertDeviceToWindow:(CGPoint)window; -(void)setLevel:(float)level; -(float)level; -(void)setBecomeKeyOnOrderFront:(BOOL)front; -(void)_clearPendingKeyboardChanges; -(BOOL)_shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation; -(void)_handleStatusBarOrientationChange:(id)change; -(void)_handleDeviceOrientationChange:(id)change; -(void)_updateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation animated:(BOOL)animated; -(void)_updateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration force:(BOOL)force; -(void)_updateInterfaceOrientationFromDeviceOrientation; -(void)beginDisablingInterfaceAutorotation; -(BOOL)isInterfaceAutorotationDisabled; -(void)endDisablingInterfaceAutorotation; -(void)setAutorotates:(BOOL)autorotates; -(void)setAutorotates:(BOOL)autorotates forceUpdateInterfaceOrientation:(BOOL)orientation; -(void)_setRotatableViewOrientation:(int)orientation duration:(double)duration; -(int)_degreesToRotateFromInterfaceOrientation:(int)interfaceOrientation toInterfaceOrientation:(int)interfaceOrientation2; -(void)_forceTwoPartRotationAnimation:(BOOL)animation; -(void)_updateStatusBarToInterfaceOrientation:(int)interfaceOrientation duration:(double)duration fenceID:(int)id animation:(int)animation; -(void)_updateStatusBarToInterfaceOrientation:(int)interfaceOrientation duration:(double)duration; -(void)_setRotatableViewOrientation:(int)orientation duration:(double)duration force:(BOOL)force; -(BOOL)autorotates; -(BOOL)isRotating; -(BOOL)isUsingOnePartRotationAnimation; -(int)interfaceOrientation; -(void)synchronizeDrawingWithID:(int)id; -(void)synchronizeDrawingWithID:(int)id count:(unsigned)count; -(void)handleStatusBarChangeFromHeight:(float)height toHeight:(float)height2; -(int)windowOutput; -(int)bitsPerComponent; -(void)setDelegate:(id)delegate; -(id)delegate; -(void)makeKeyWindow; -(void)becomeKeyWindow; -(void)resignKeyWindow; -(void)makeKeyAndVisible; -(id)contentView; -(void)_registerChargedView:(id)view; -(void)_unregisterChargedView:(id)view; -(void)_registerSwipeView:(id)view; -(void)_unregisterSwipeView:(id)view; -(void)_registerScrollToTopView:(id)topView; -(void)_unregisterScrollToTopView:(id)topView; -(void)_setFirstResponder:(id)responder; -(UIResponder*)firstResponder; -(UIResponder*)_firstResponder; -(BOOL)_becomeFirstResponderWhenPossible; -(id)undoManager; -(void)undo:(id)undo; -(void)redo:(id)redo; -(BOOL)canPerformAction:(SEL)action withSender:(id)sender; -(void)_setMouseDownView:(id)view withEvent:(GSEventRef)event; -(void)_setMouseEnteredView:(id)view; -(BOOL)_clearMouseView; -(IOSurfaceRef)createIOSurfaceWithFrame:(CGRect)frame; -(IOSurfaceRef)createIOSurface; -(void)_setCancelScroller:(BOOL)scroller; -(BOOL)_isLayerHidden; -(void)_setLayerHidden:(BOOL)hidden; -(id)_touchData; #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2 // inherited: -(void)encodeWithCoder:(id)coder; -(void)awakeFromNib; +(void*)createRotatedCGImageFromIOSurface:(void*)iosurface; +(void*)createIOSurfaceWithContextIds:(const unsigned*)contextIds count:(unsigned)count frame:(CGRect)frame outTransform:(CGAffineTransform*)transform; +(id)_hitTestToPoint:(CGPoint)point pathIndex:(int)index forEvent:(id)event; +(id)_findWithDisplayPoint:(CGPoint)displayPoint; -(BOOL)_isClassicControllerWindow; -(void)_updateTransformLayer; -(void)_createContext; -(void)_destroyContext; -(void)_createContextIfNecessary; -(float)_contentsScale; -(void)_setContentsScale:(float)scale; -(void)_updateInterfaceOrientationFromDeviceOrientation:(BOOL)deviceOrientation; -(void)_setRotatableClient:(id)client toOrientation:(int)orientation duration:(double)duration force:(BOOL)force; -(void)_finishedFirstHalfRotation:(id)rotation finished:(id)finished context:(id)context; -(void)_finishedFullRotation:(id)rotation finished:(id)finished context:(id)context; -(int)_windowOutput; -(CGPoint)_transformDisplayToWindowCoordinates:(CGPoint)windowCoordinates; -(CGPoint)_convertOffset:(CGPoint)offset toWindow:(id)window; -(CGPoint)_convertOffset:(CGPoint)offset fromWindow:(id)window; -(id)_rootViewControllers; -(id)_clientsForRotation; -(void)_addRootViewController:(id)controller; -(void)_removeRootViewController:(id)controller; -(BOOL)resizesToFullScreen; -(void)setResizesToFullScreen:(BOOL)fullScreen; #else -(void)_commonInit; -(void)_createWindow; -(void)_slideHeaderView:(id)view andFooterView:(id)view2 offScreen:(BOOL)screen forInterfaceOrientation:(int)interfaceOrientation; -(void)_positionHeaderView:(id)view andFooterView:(id)view2 outsideContentViewForInterfaceOrientation:(int)interfaceOrientation; -(void)_applicationDidBeginIgnoringInteractionEvents:(id)_application; -(void)_applicationDidEndIgnoringInteractionEvents:(id)_application; -(void)_finishedFirstHalfRotation:(id)rotation finished:(id)finished context:(void*)context; -(void)_finishedFullRotation:(id)rotation finished:(id)finished context:(void*)context; -(BOOL)isHandlingContentRotation; -(BOOL)acceptsGlobalPoint:(CGPoint)point; #endif @end @interface UIWindow (UITextEffectsWindow) -(void)updateForOrientation:(int)orientation; -(void)matchDeviceOrientation; @end @interface UIWindow (UIKitAccessibilityInterfaceBuilderSupport) -(BOOL)isElementAccessibilityExposedToInterfaceBuilder; @end @protocol UIWindowDelegate @optional -(BOOL)window:(UIWindow*)window shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation; -(void)window:(UIWindow*)window willRotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration; -(void)window:(UIWindow*)window willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration; -(void)window:(UIWindow*)window willAnimateFromContentFrame:(CGRect)fromFrame toContentFrame:(CGRect)toFrame; -(void)window:(UIWindow*)window willAnimateFirstHalfOfRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration; -(void)window:(UIWindow*)window didAnimateFirstHalfOfRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation; -(void)window:(UIWindow*)window willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration; -(void)window:(UIWindow*)window didRotateFromInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation; -(BOOL)shouldWindowUseOnePartInterfaceRotationAnimation:(UIWindow*)window; -(UIView*)rotatingContentViewForWindow:(UIWindow*)window; -(UIView*)rotatingHeaderViewForWindow:(UIWindow*)window; -(UIView*)rotatingFooterViewForWindow:(UIWindow*)window; #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2 -(id)clientsForRotationForWindow:(UIWindow*)window; -(void)getRotationContentSettings:(XXStruct_t5OlHA*)settings forWindow:(UIWindow*)window; #else -(void)getRotationContentSettings:(XXStruct_TF$i3B*)settings forWindow:(UIWindow*)window; #endif @end @interface UIWindow (UITextEffectsWindowAdditions) -(BOOL)_isTextEffectsWindow __OSX_AVAILABLE_STARTING(__MAC_NA, __IPHONE_3_1); @end
47.095477
167
0.831946
[ "transform" ]
8c411202668eedd8f7a398048ce75432309d86d6
2,505
h
C
firestore/src/ios/document_reference_ios.h
NetsoftHoldings/firebase-cpp-sdk
356c63bddde5ed76483cbfc5f3ff5b228c5cbe1f
[ "Apache-2.0" ]
null
null
null
firestore/src/ios/document_reference_ios.h
NetsoftHoldings/firebase-cpp-sdk
356c63bddde5ed76483cbfc5f3ff5b228c5cbe1f
[ "Apache-2.0" ]
null
null
null
firestore/src/ios/document_reference_ios.h
NetsoftHoldings/firebase-cpp-sdk
356c63bddde5ed76483cbfc5f3ff5b228c5cbe1f
[ "Apache-2.0" ]
null
null
null
#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_DOCUMENT_REFERENCE_IOS_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_DOCUMENT_REFERENCE_IOS_H_ #include <functional> #include <memory> #include <string> #include "firestore/src/include/firebase/firestore/collection_reference.h" #include "firestore/src/include/firebase/firestore/document_reference.h" #include "firestore/src/include/firebase/firestore/map_field_value.h" #include "firestore/src/ios/firestore_ios.h" #include "firestore/src/ios/promise_factory_ios.h" #include "firestore/src/ios/user_data_converter_ios.h" #include "Firestore/core/src/firebase/firestore/api/document_reference.h" namespace firebase { namespace firestore { namespace core { class ParsedSetData; class ParsedUpdateData; } // namespace core class Firestore; class FirestoreInternal; class DocumentReferenceInternal { public: explicit DocumentReferenceInternal(api::DocumentReference&& reference); Firestore* firestore(); FirestoreInternal* firestore_internal(); const std::string& id() const { return reference_.document_id(); } std::string path() const { return reference_.Path(); } const model::DocumentKey& key() const { return reference_.key(); } CollectionReference Parent(); CollectionReference Collection(const std::string& collection_path); Future<DocumentSnapshot> Get(Source source); Future<DocumentSnapshot> GetLastResult(); Future<void> Set(const MapFieldValue& data, const SetOptions& options); Future<void> SetLastResult(); Future<void> Update(const MapFieldValue& data); Future<void> Update(const MapFieldPathValue& data); Future<void> UpdateLastResult(); Future<void> Delete(); Future<void> DeleteLastResult(); ListenerRegistration AddSnapshotListener( MetadataChanges metadata_changes, EventListener<DocumentSnapshot>* listener); ListenerRegistration AddSnapshotListener( MetadataChanges metadata_changes, std::function<void(const DocumentSnapshot&, Error)> callback); const api::DocumentReference& document_reference_core() const { return reference_; } private: enum class AsyncApis { kGet, kSet, kUpdate, kDelete, kCount, }; Future<void> UpdateImpl(core::ParsedUpdateData&& parsed); api::DocumentReference reference_; PromiseFactory<AsyncApis> promise_factory_; UserDataConverter user_data_converter_; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_DOCUMENT_REFERENCE_IOS_H_
29.127907
74
0.782036
[ "model" ]
8c5aba3dd06dbe122d7dfe93bab9a6962b321ea4
2,017
h
C
arc/arcauth.h
siilky/catomania
cb3a05cbef523d16b8929b390e190e0cd5924ee9
[ "MIT" ]
1
2021-02-05T23:20:07.000Z
2021-02-05T23:20:07.000Z
arc/arcauth.h
siilky/catomania
cb3a05cbef523d16b8929b390e190e0cd5924ee9
[ "MIT" ]
null
null
null
arc/arcauth.h
siilky/catomania
cb3a05cbef523d16b8929b390e190e0cd5924ee9
[ "MIT" ]
null
null
null
#pragma once #include <QObject> #include <QNetworkAccessManager> #include "connection.h" #include "error.h" #include "fragments.h" class NetChannelTcp; struct rsa_st; typedef struct rsa_st RSA; namespace ARC { class ArcAuth : public QObject { Q_OBJECT public: enum StatusCode { None = 0, IncorrectPassword = 3, AccountBlocked = 10, PinRequired = 15, IncorrectPin = 20, }; ArcAuth(QString hwId, QString pcName, QString userAgent, QObject *parent = 0); virtual ~ArcAuth(); void setProxy(const QNetworkProxy & proxy); void setPin(QString pin); QString token() const { return token_; } ErrorState getError() const { return error_; } unsigned statusCode() const { return statusCode_; } QString pcName() const { return pcName_; } public Q_SLOTS: virtual void start(const QString & email, const QString & password); Q_SIGNALS: void progress(int value, int maxValue); void finished(bool success); void needPin(); void error(const QString & message); // indicates error message only private Q_SLOTS: void onConnected(); void onDisconnected(); private: void onRsaPublicKey(const FragmentRsaPublicKey *f); void onHandshakeOk(const FragmentHandshakeOk *f); void onLoginRe(const FragmentLoginRe *f); void onGetTokenRe(const FragmentGetTokenRe *f); void sendGetToken(); void abort(); void finish(); static const int MaxProgress = 3; QString email_; QString password_; QString useragent_; QString hwId_; QString pcName_; int progress_; int progressMax_; ErrorState error_; unsigned statusCode_; unsigned tokenReq_; QString token_; QNetworkProxy proxy_; QTimer keepaliveTimer_; ARC::Connection connection_; std::vector<Connection::Cookie> cookies_; RSA *rsa_ = nullptr; std::array<unsigned, 4> teaKey_; }; }
18.675926
82
0.651958
[ "vector" ]
8c5b41aebb53ec33571724f0832037c768b784e2
1,205
h
C
zebROS_ws/src/base_trajectory/include/base_trajectory/sample_trajectory.h
FRC900/2020Offseason
36ccd74667d379b07d9b7a1e937307c6d8119229
[ "BSD-3-Clause" ]
2
2021-09-23T22:34:11.000Z
2022-01-13T00:20:12.000Z
zebROS_ws/src/base_trajectory/include/base_trajectory/sample_trajectory.h
FRC900/2020Offseason
36ccd74667d379b07d9b7a1e937307c6d8119229
[ "BSD-3-Clause" ]
19
2021-03-20T01:10:04.000Z
2022-01-17T22:51:05.000Z
zebROS_ws/src/base_trajectory/include/base_trajectory/sample_trajectory.h
FRC900/2020Offseason
36ccd74667d379b07d9b7a1e937307c6d8119229
[ "BSD-3-Clause" ]
null
null
null
#ifndef INC_SAMPLE_TRAJECTORY_ #define INC_SAMPLE_TRAJECTORY_ #include "spline_util/spline_util.h" enum class SampleTrajectoryType { CPU, THREADED, CUDA, HYBRID }; template <class T> class SampleTrajectoryImpl; template <class T> class SampleTrajectory { public: SampleTrajectory(double distBetweenArcLength, double distBetweenArcLengthEpsilon, double midTimeInflation, SampleTrajectoryType type = SampleTrajectoryType::CPU); ~SampleTrajectory(); bool sample(std::vector<T> &equalArcLengthTimes, std::vector<T> &equalArcLengthPositions, std::vector<SegmentState<T>> &xStates, std::vector<SegmentState<T>> &yStates, std::vector<SegmentState<T>> &thetaStates, const XYTTrajectory<T> &trajectory, const ArcLengthTrajectory<T> &arcLengthTrajectory); void setDistBetweenArcLengths(double distBetweenArcLength); void setDistBetweenArcLengthEpsilon(double distBetweenArcLengthEpsilon); void setMidTimeInflation(double midTimeInflation); double getDistBetweenArcLengths() const; double getDistBetweenArcLengthEpsilon() const; double getMidTimeInflation() const; private: std::unique_ptr<SampleTrajectoryImpl<T>> impl_; }; #endif
26.195652
74
0.775934
[ "vector" ]
8c63083d57076d7e734ba82a7153cd2acf956ed7
2,644
h
C
MoravaEngine/src/Scene/SceneVoxelTerrainSL.h
dtrajko/MoravaEngine
dab8a9e84bde6bdb5e979596c29cabccb566b9d4
[ "Apache-2.0" ]
168
2020-07-18T04:20:27.000Z
2022-03-31T23:39:38.000Z
MoravaEngine/src/Scene/SceneVoxelTerrainSL.h
dtrajko/MoravaEngine
dab8a9e84bde6bdb5e979596c29cabccb566b9d4
[ "Apache-2.0" ]
5
2020-11-23T12:33:06.000Z
2022-01-05T15:15:30.000Z
MoravaEngine/src/Scene/SceneVoxelTerrainSL.h
dtrajko/MoravaEngine
dab8a9e84bde6bdb5e979596c29cabccb566b9d4
[ "Apache-2.0" ]
8
2020-09-07T03:04:18.000Z
2022-03-25T13:47:16.000Z
#pragma once #include "Scene/Scene.h" #include "Core/Raycast.h" #include "Instancing/RenderInstanced.h" #include "Player/Player.h" #include "Player/PlayerController.h" #include "Terrain/MapGenerator.h" #include "Terrain/TerrainSL.h" #include "Terrain/TerrainVoxel.h" class SceneVoxelTerrainSL : public Scene { public: SceneVoxelTerrainSL(); virtual ~SceneVoxelTerrainSL() override; virtual void Update(float timestep, Window* mainWindow) override; virtual void UpdateImGui(float timestep, Window* mainWindow) override; virtual void Render(Window* mainWindow, glm::mat4 projectionMatrix, std::string passType, std::map<std::string, Hazel::Ref<MoravaShader>> shaders, std::map<std::string, int> uniforms) override; void UpdateCooldown(float timestep, Window* mainWindow); void Release(); inline Raycast* GetRaycast() const { return m_Raycast; }; std::vector<glm::vec3> GetRayIntersectPositions(float timestep, Camera* camera); void Dig(bool* keys, float timestep); void CastRay(bool* keys, bool* buttons, float timestep); bool IsRayIntersectPosition(glm::vec3 position); void OnClick(bool* keys, bool* buttons, float timestep); bool IsPositionVacant(glm::ivec3 queryPosition); void AddVoxel(); void DeleteVoxel(); private: virtual void SetCamera() override; virtual void SetupTextures() override; virtual void SetupTextureSlots() override; virtual void SetupMeshes() override; bool IsTerrainConfigChanged(); void CheckMapRebuildRequirements(); RenderInstanced* m_RenderInstanced; glm::ivec3 m_TerrainScale; glm::ivec3 m_TerrainScalePrev; float m_TerrainNoiseFactor; float m_TerrainNoiseFactorPrev; EventCooldown m_UpdateCooldown; EventCooldown m_DigCooldown; EventCooldown m_RayIntersectCooldown; EventCooldown m_RayCastCooldown; EventCooldown m_OnClickCooldown; Player* m_Player; PlayerController* m_PlayerController; bool m_TerrainSettingsChanged; Pivot* m_PivotScene; float m_DigDistance; Raycast* m_Raycast; // Scene settings bool m_DrawGizmos; bool m_RenderPlayer; bool m_UnlockRotation; bool m_UnlockRotationPrev; // mouse cursor intersection std::vector<glm::vec3> m_IntersectPositionVector; bool m_DeleteMode; // add or delete glm::ivec3 m_IntersectPosition; glm::vec4 m_CubeColor; unsigned int m_DeleteVoxelCodeGLFW; TerrainSL* m_TerrainSL; MapGenerator::MapGenConf m_MapGenConf; MapGenerator::MapGenConf m_MapGenConfPrev; int m_HeightMapMultiplier; int m_HeightMapMultiplierPrev; float m_SeaLevel; float m_SeaLevelPrev; int m_LevelOfDetail; int m_LevelOfDetailPrev; bool m_IsRequiredMapUpdate; bool m_IsRequiredMapRebuild; bool m_TerrainEditMode; };
26.44
105
0.795386
[ "render", "vector" ]
8c65a04e1104ca3705eebc0268612558136cc76a
7,972
h
C
Engine/Common/Utility/Math/SimpleGeometry.h
LineGames/Leggiero
8fe13d86454a08ba8a3a8cebe1ce92343090c1be
[ "MIT" ]
22
2021-04-19T03:01:44.000Z
2021-12-03T11:14:10.000Z
Engine/Common/Utility/Math/SimpleGeometry.h
LineGames/Leggiero
8fe13d86454a08ba8a3a8cebe1ce92343090c1be
[ "MIT" ]
null
null
null
Engine/Common/Utility/Math/SimpleGeometry.h
LineGames/Leggiero
8fe13d86454a08ba8a3a8cebe1ce92343090c1be
[ "MIT" ]
3
2021-04-20T05:06:40.000Z
2021-07-31T01:25:53.000Z
//////////////////////////////////////////////////////////////////////////////// // Math/SimpleGeometry.h (Leggiero - Utility) // // Simple Mathmatical Geometry Utilites //////////////////////////////////////////////////////////////////////////////// #ifndef __UTILITY__MATH__SIMPLE_GEOMETRY_H #define __UTILITY__MATH__SIMPLE_GEOMETRY_H // Standard Library #include <cmath> // Leggiero.Utility #include "SimpleMath.h" namespace Leggiero { namespace Utility { namespace Math { namespace FloatingPointLongConstants { constexpr long double kPi = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148L; constexpr long double kInversePi = 1.0L / kPi; constexpr long double kPiOver2 = kPi / 2.0L; constexpr long double kPiOver3 = kPi / 3.0L; constexpr long double kPiOver4 = kPi / 4.0L; constexpr long double kPiOver6 = kPi / 6.0L; constexpr long double kPiMul2 = kPi * 2.0L; constexpr long double kPiMul3 = kPi * 3.0L; constexpr long double kPiMul4 = kPi * 4.0L; constexpr long double kRad2Deg = 180.0L / kPi; constexpr long double kDeg2Rad = kPi / 180.0L; } template <typename T> class FloatingPointSimpleGeometry { public: using ValueType = T; public: // Constants static constexpr T kPi = static_cast<T>(FloatingPointLongConstants::kPi); static constexpr T kInversePi = static_cast<T>(FloatingPointLongConstants::kInversePi); static constexpr T kPiOver2 = static_cast<T>(FloatingPointLongConstants::kPiOver2); static constexpr T kPiOver3 = static_cast<T>(FloatingPointLongConstants::kPiOver3); static constexpr T kPiOver4 = static_cast<T>(FloatingPointLongConstants::kPiOver4); static constexpr T kPiOver6 = static_cast<T>(FloatingPointLongConstants::kPiOver6); static constexpr T kPiMul2 = static_cast<T>(FloatingPointLongConstants::kPiMul2); static constexpr T kPiMul3 = static_cast<T>(FloatingPointLongConstants::kPiMul3); static constexpr T kPiMul4 = static_cast<T>(FloatingPointLongConstants::kPiMul4); static constexpr T kRad2Deg = static_cast<T>(FloatingPointLongConstants::kRad2Deg); static constexpr T kDeg2Rad = static_cast<T>(FloatingPointLongConstants::kDeg2Rad); public: static constexpr T Rad2Deg(T radian) { return radian * kRad2Deg; } static constexpr T Deg2Rad(T degree) { return degree * kDeg2Rad; } static T WrapAnglePi(T angle) { return Math::WrapMinMax<T>(angle, -kPi, kPi); } static T WrapAngle2Pi(T angle) { return Math::WrapMinMax<T>(angle, 0, kPiMul2); } static T OppositeAngle(T angle) { return WrapAnglePi(angle + kPi); } static T DeltaAngle(T angleTo, T angleFrom) { if (angleFrom > angleTo) { T delta = angleFrom - angleTo; if (delta > kPi) { return angleTo + kPiMul2 - angleFrom; } return -delta; } else { T delta = angleTo - angleFrom; if (delta > kPi) { return -(angleFrom + kPiMul2 - angleTo); } return delta; } } inline T AzimuthPi(T x, T y) { constexpr T kAxisEpsilon = static_cast<T>(0.00000000000001L); if (x > -kAxisEpsilon && x < kAxisEpsilon) { if (y >= static_cast<T>(0.0)) { return kPiOver2; } return -kPiOver2; } return static_cast<T>(std::atan2l(y, x)); } }; } namespace Mathd { constexpr double kPi = Math::FloatingPointSimpleGeometry<double>::kPi; constexpr double kInversePi = static_cast<double>(Math::FloatingPointLongConstants::kInversePi); constexpr double kPiOver2 = static_cast<double>(Math::FloatingPointLongConstants::kPiOver2); constexpr double kPiOver3 = static_cast<double>(Math::FloatingPointLongConstants::kPiOver3); constexpr double kPiOver4 = static_cast<double>(Math::FloatingPointLongConstants::kPiOver4); constexpr double kPiOver6 = static_cast<double>(Math::FloatingPointLongConstants::kPiOver6); constexpr double kPiMul2 = static_cast<double>(Math::FloatingPointLongConstants::kPiMul2); constexpr double kPiMul3 = static_cast<double>(Math::FloatingPointLongConstants::kPiMul3); constexpr double kPiMul4 = static_cast<double>(Math::FloatingPointLongConstants::kPiMul4); constexpr double kRad2Deg = static_cast<double>(Math::FloatingPointLongConstants::kRad2Deg); constexpr double kDeg2Rad = static_cast<double>(Math::FloatingPointLongConstants::kDeg2Rad); constexpr double Rad2Deg(double radian) { return radian * kRad2Deg; } constexpr double Deg2Rad(double degree) { return degree * kDeg2Rad; } inline double WrapAnglePi(double angle) { return Math::WrapMinMax<double>(angle, -kPi, kPi); } inline double WrapAngle2Pi(double angle) { return Math::WrapMinMax<double>(angle, 0, kPiMul2); } inline double OppositeAngle(double angle) { return WrapAnglePi(angle + kPi); } inline double DeltaAngle(double angleTo, double angleFrom) { if (angleFrom > angleTo) { double delta = angleFrom - angleTo; if (delta > kPi) { return angleTo + kPiMul2 - angleFrom; } return -delta; } else { double delta = angleTo - angleFrom; if (delta > kPi) { return -(angleFrom + kPiMul2 - angleTo); } return delta; } } inline double AzimuthPi(double x, double y) { constexpr double kAxisEpsilon = 0.000000000001; if (x > -kAxisEpsilon && x < kAxisEpsilon) { if (y >= 0.0) { return kPiOver2; } return -kPiOver2; } return std::atan2(y, x); } } namespace Mathf { constexpr float kPi = static_cast<float>(Math::FloatingPointLongConstants::kPi); constexpr float kInversePi = static_cast<float>(Math::FloatingPointLongConstants::kInversePi); constexpr float kPiOver2 = static_cast<float>(Math::FloatingPointLongConstants::kPiOver2); constexpr float kPiOver3 = static_cast<float>(Math::FloatingPointLongConstants::kPiOver3); constexpr float kPiOver4 = static_cast<float>(Math::FloatingPointLongConstants::kPiOver4); constexpr float kPiOver6 = static_cast<float>(Math::FloatingPointLongConstants::kPiOver6); constexpr float kPiMul2 = static_cast<float>(Math::FloatingPointLongConstants::kPiMul2); constexpr float kPiMul3 = static_cast<float>(Math::FloatingPointLongConstants::kPiMul3); constexpr float kPiMul4 = static_cast<float>(Math::FloatingPointLongConstants::kPiMul4); constexpr float kRad2Deg = static_cast<float>(Math::FloatingPointLongConstants::kRad2Deg); constexpr float kDeg2Rad = static_cast<float>(Math::FloatingPointLongConstants::kDeg2Rad); constexpr float Rad2Deg(float radian) { return radian * kRad2Deg; } constexpr float Deg2Rad(float degree) { return degree * kDeg2Rad; } inline float WrapAnglePi(float angle) { return Math::WrapMinMax<float>(angle, -kPi, kPi); } inline float WrapAngle2Pi(float angle) { return Math::WrapMinMax<float>(angle, 0, kPiMul2); } inline float OppositeAngle(float angle) { return WrapAnglePi(angle + kPi); } inline float DeltaAngle(float angleTo, float angleFrom) { if (angleFrom > angleTo) { float delta = angleFrom - angleTo; if (delta > kPi) { return angleTo + kPiMul2 - angleFrom; } return -delta; } else { float delta = angleTo - angleFrom; if (delta > kPi) { return -(angleFrom + kPiMul2 - angleTo); } return delta; } } inline float AzimuthPi(float x, float y) { constexpr float kAxisEpsilon = 0.0000001f; if (x > -kAxisEpsilon && x < kAxisEpsilon) { if (y >= 0.0f) { return kPiOver2; } return -kPiOver2; } return std::atan2f(y, x); } } namespace Math { } } } #endif
26.573333
141
0.665454
[ "geometry" ]
8c66458c7f39339f99776753e1fb5764891e808d
24,654
h
C
code/Syntax_Tree.h
qkmics/Pascal-S_Complier
e2fd6962c7900b549cd6617a8e1fa04afc44b83d
[ "MIT" ]
null
null
null
code/Syntax_Tree.h
qkmics/Pascal-S_Complier
e2fd6962c7900b549cd6617a8e1fa04afc44b83d
[ "MIT" ]
null
null
null
code/Syntax_Tree.h
qkmics/Pascal-S_Complier
e2fd6962c7900b549cd6617a8e1fa04afc44b83d
[ "MIT" ]
null
null
null
// File Name : Syntax_Tree.h // Notes : Define the Syntax Tree DataStructure // Version : 0.6 // Author : Yun Zhang // : Boxi Cao #pragma once #include <vector> #include <string> #include <iostream> #include "Public_define.h" using namespace std; // class declare class Programstruct; class Program_Body; class Const_Declarations; class Var_Declarations; class SubProgram_Declarations; class Statement_List; class Common; class Procedure; class Function; class Statement; class Parameter_List; class Variable; class Procedure_Call; class Function_Call; class Expression; class Simple_Expression; class Term; class Factor; class Not; class Uminus; class Type; class Const_Value; class Assignop; class If_Then_Else; class For; class Parameter; class Relop; class Addop; class Mulop; class Id; class Id_List; class Period; class Expression_List; // 以下类都是在抽象语法树中没有的类,为实现翻译方案而创建 class Program_Head; class Compound_Statement; class Const_Declaration; class Var_Declaration; class SubProgram_Declaration; class Subprogram; class Subprogram_Head; class Subprogram_Body; class Formal_Parameter; class Var_Parameter; class Value_Parameter; class Id_Varpart; // class define // 以下类都是在抽象语法树中没有的类 class Program_Head { public: Program_Head(Id * M_Id,Id_List *M_Id_List){ m_Id=M_Id; m_Id_List=M_Id_List; } ~Program_Head(); Id * m_Id; Id_List *m_Id_List; }; class Compound_Statement{ public: Compound_Statement(Statement_List * M_Statement_List){ m_Statement_List=M_Statement_List; } ~Compound_Statement(); Statement_List * m_Statement_List; }; class Const_Declaration { public: Const_Declaration(){}; Const_Declaration(vector<pair<Id*, Const_Value*> > Mv_Const){ mv_Const=Mv_Const; } ~Const_Declaration(); vector<pair<Id*, Const_Value*> > mv_Const; }; class Var_Declaration { public: Var_Declaration(){}; Var_Declaration(vector<pair<Id_List*, Type*> > Mv_Var){ mv_Var=Mv_Var; } ~Var_Declaration(); vector<pair<Id_List*, Type*> > mv_Var; }; class SubProgram_Declaration { public: SubProgram_Declaration(); ~SubProgram_Declaration(); vector<Subprogram*> mv_Subprogram; }; class Subprogram { public: Subprogram(); ~Subprogram(); Subprogram_Head * m_Subprogram_Head; Subprogram_Body *m_Subprogram_Body; }; class Subprogram_Head { public: Subprogram_Head(Id * M_ID,Formal_Parameter *M_Formal_Parameter,int SType){ m_ID=M_ID; m_Formal_Parameter=M_Formal_Parameter; Simple_Type=SType; } ~Subprogram_Head(); Id * m_ID; Formal_Parameter *m_Formal_Parameter; int Simple_Type; }; class Subprogram_Body { public: Subprogram_Body(Const_Declarations * M_Const_Declarations,Var_Declarations *M_Var_Declarations,Compound_Statement *M_Compound_Statement){ m_Const_Declarations=M_Const_Declarations; m_Var_Declarations=M_Var_Declarations; m_Compound_Statement=M_Compound_Statement; } ~Subprogram_Body(); Const_Declarations * m_Const_Declarations; Var_Declarations *m_Var_Declarations; Compound_Statement *m_Compound_Statement; }; class Formal_Parameter { public: Formal_Parameter(Parameter_List * M_Parameter_List){ m_Parameter_List=M_Parameter_List; } ~Formal_Parameter(); Parameter_List * m_Parameter_List; }; class Var_Parameter { public: Var_Parameter(Value_Parameter * M_Value_Parameter){ m_Value_Parameter=M_Value_Parameter; } ~Var_Parameter(); Value_Parameter * m_Value_Parameter; }; class Value_Parameter { public: Value_Parameter(Id_List *M_Id_List,int SType){ m_Id_List=M_Id_List; Simple_Type=SType; } ~Value_Parameter(); int Simple_Type; Id_List * m_Id_List; }; class Id_Varpart{ public: Id_Varpart(); Id_Varpart(Expression_List *M_Expression_List){ m_Expression_List=M_Expression_List; } ~Id_Varpart(); Expression_List *m_Expression_List; //这个指针可以为NULL }; // Program Total node // The Root of Syntax Tree class Programstruct { public: Programstruct(Id * Mp_Id,Id_List *Mp_Id_List,Program_Body *Mp_Program_Body){ mp_Id=Mp_Id; mp_Id_List=Mp_Id_List; mp_Program_Body=Mp_Program_Body; } ~Programstruct(); string func_codeGeneration(); bool error_detect(); Id * mp_Id; Id_List *mp_Id_List; Program_Body *mp_Program_Body; void outputTree(); }; // Define the Main Program body // include four parts class Program_Body { public: Program_Body(Const_Declarations *Mp_Const_Declarations,Var_Declarations *Mp_Var_Declarations,SubProgram_Declarations *Mp_SubProgram_Declarations,Compound_Statement *Mp_Compound_Statements){ mp_Const_Declarations=Mp_Const_Declarations; mp_Var_Declarations=Mp_Var_Declarations; mp_SubProgram_Declarations=Mp_SubProgram_Declarations; mp_Statement_List=Mp_Compound_Statements -> m_Statement_List; } ~Program_Body(); string func_codeGeneration(); pair<bool, string> create_symbolsheet(); bool error_detect(); Const_Declarations *mp_Const_Declarations; Var_Declarations *mp_Var_Declarations; SubProgram_Declarations *mp_SubProgram_Declarations; Statement_List *mp_Statement_List; void outputTree(); }; // Const Block class Const_Declarations { public: Const_Declarations(){}; Const_Declarations(vector<pair<Id*, Const_Value*> > Mv_Const){ mv_Const=Mv_Const; } ~Const_Declarations(); bool error_detect(string symbolSheet_name); string func_codeGeneration(); vector<pair<Id*, Const_Value*> > mv_Const; void outputTree(); }; // Var Block class Var_Declarations { public: Var_Declarations() {}; Var_Declarations(vector<pair<Id_List*, Type*> > Mv_Var){ mv_Var=Mv_Var; } ~Var_Declarations(); bool error_detect(string symbolSheet_name); string func_codeGeneration(); vector<pair<Id_List*, Type*> >mv_Var; void outputTree(); }; // SubProgram Block // Define the functions and procedures class SubProgram_Declarations { public: SubProgram_Declarations(){}; SubProgram_Declarations(vector<Common*> Mv_Common){ mv_Common=Mv_Common; } ~SubProgram_Declarations(); bool error_detect(string symbolSheet_name); bool definition_error_detect(); string func_codeGeneration(); void func_checkType(); vector<Common*>mv_Common; void outputTree(); }; // contain many statements class Statement_List { public: Statement_List(){}; Statement_List(vector<Statement*>Mv_Statement){ mv_Statement=Mv_Statement; } ~Statement_List(); string func_codeGeneration(); bool error_detect(string); vector<Statement*>mv_Statement; void outputTree(); }; class Common { public: virtual string func_codeGeneration() = 0; virtual int func_checkReturnType() = 0; virtual int func_get_Common_Type() { return -1; } virtual pair<bool, string> create_symbolsheet() = 0; virtual bool error_detect() = 0; virtual Id * get_func_id() = 0; virtual Parameter_List * get_param_list() = 0; virtual Const_Declarations * get_const_dec() = 0; virtual Var_Declarations * get_var_dec() = 0; virtual int get_lineno() = 0; virtual void outputTree() = 0; }; // the Precodure block class Procedure : public Common { public: Procedure(int M_lineno,Id *Mp_Id,Parameter_List *Mp_Parameter_List,Const_Declarations *Mp_Const_Declarations,Var_Declarations *Mp_Var_Declarations,Statement_List *Mp_Statement_List); string func_codeGeneration() override; int func_checkReturnType() override { return -1; // return VOID } int func_get_Common_Type() override { return COMMON_PROCEDURE; } pair<bool, string> create_symbolsheet() override; bool error_detect() override; Id * get_func_id() override { return mp_Id; } Parameter_List * get_param_list() override { return mp_Parameter_List; } Const_Declarations * get_const_dec() override { return mp_Const_Declarations; } Var_Declarations * get_var_dec() override { return mp_Var_Declarations; } int get_lineno() override { return m_lineno; } int m_lineno; Id *mp_Id; Parameter_List *mp_Parameter_List; Const_Declarations *mp_Const_Declarations; Var_Declarations *mp_Var_Declarations; Statement_List *mp_Statement_List; void outputTree(); }; // the Function block class Function : public Common { public: Function(int M_returnType,int M_lineno,Id *Mp_Id,Parameter_List *Mp_Parameter_List,Const_Declarations *Mp_Const_Declarations,Var_Declarations *Mp_Var_Declarations,Statement_List *Mp_Statement_List); string func_codeGeneration() override; int func_checkReturnType() override { return m_returnType; } int func_get_Common_Type() override{ return COMMON_FUNCTION; } pair<bool, string> create_symbolsheet() override; bool error_detect() override; Id * get_func_id() override { return mp_Id; } Parameter_List * get_param_list() override { return mp_Parameter_List; } Const_Declarations * get_const_dec() override { return mp_Const_Declarations; } Var_Declarations * get_var_dec() override { return mp_Var_Declarations; } int get_lineno() override { return m_lineno; } int m_returnType; int m_lineno; Id *mp_Id; Parameter_List *mp_Parameter_List; Const_Declarations *mp_Const_Declarations; Var_Declarations *mp_Var_Declarations; Statement_List *mp_Statement_List; void outputTree(); }; // the statements are partitioned by ';' class Statement { public: Statement(){}; ~Statement(); string func_codeGeneration(); void func_checkType(); bool error_detect(string symbol_sheet_name); int m_stateType; int m_lineno; // the below pointers // only one can be assigned to non-NULL // the others must be null Assignop *mp_Assignop; Procedure_Call *mp_Procedure_call; // which include the read and write call Statement_List *mp_Statement_List; // which refered to begin-block-end If_Then_Else *mp_If_Then_Else; For *mp_For; void outputTree(); }; // only used for function or procedure define class Parameter_List { public: Parameter_List(){}; Parameter_List(int M_lineno,vector<Parameter*> Mv_Patameter){ m_lineno=M_lineno; mv_Patameter=Mv_Patameter; } ~Parameter_List(); bool error_detect(string symbolSheet_name); string func_codeGeneration(); int m_lineno; vector<Parameter*> mv_Patameter; void outputTree(); }; // define the variable type class Variable { public: Variable(){}; ~Variable(); string func_codeGeneration(); bool error_detect(string symbol_sheet_name); int getType() { return type; } bool m_isArray; int m_lineno; Id *mp_Id; int type; // default to be null // // if m_isArray == true // this pointer point to the index of array(multi-dimension) // partition by ',' in pascal Expression_List *mp_Expression_List; void outputTree(); }; // belong to statement class Procedure_Call { public: Procedure_Call(){}; ~Procedure_Call(); string func_codeGeneration(); bool error_detect(string symbol_sheet_name); int m_proCall_Tpye; int m_expNum; int m_lineno; Id *mp_Id; Expression_List *mp_Expression_List; void outputTree(); }; class Function_Call { public: Function_Call(); Function_Call(int M_expNum,int M_lineno,Id *Mp_Id,Expression_List *Mp_Expression_List){ m_expNum=M_expNum; m_lineno=M_lineno; mp_Id=Mp_Id; mp_Expression_List=Mp_Expression_List; } ~Function_Call(); string func_codeGeneration(); bool error_detect(string symbol_sheet_name); int m_expNum; int m_lineno; Id *mp_Id; Expression_List *mp_Expression_List; void outputTree(); }; // the expression can be calculate to a value class Expression { public: Expression(){}; ~Expression(); string func_codeGeneration(); bool error_detect(string symbol_sheet_name); void setType(int _type) { type = _type; }; int getType() { return type; } int getRangeVal() { return rangeVal; }; bool getRangeValid() { return rangeValid; } int m_lineno; int rangeVal; bool rangeValid; // the below two pointers // only one can be assign to non-NULL // the other must be NULL Relop *mp_Relop; Simple_Expression *mp_Simple_Expression; int type; void outputTree(); }; // belong to expression class Simple_Expression { public: Simple_Expression(int M_lineno,Addop *Mp_Addop,Term *Mp_Term){ m_lineno=M_lineno; mp_Addop=Mp_Addop; mp_Term=Mp_Term; } ~Simple_Expression(); string func_codeGeneration(); bool error_detect(string symbol_sheet_name); void setType(int _type) { type = _type; }; int getType() { return type; }; int getRangeVal() { return rangeVal; } bool getRangeValid() { return rangeValid; } int m_lineno; int type; int rangeVal; bool rangeValid; // the below two pointers // only one can be assign to non-NULL // the other must be NULL Addop *mp_Addop; Term *mp_Term; void outputTree(); }; class Term { public: Term(int M_lineno,Mulop *Mp_Mulop,Factor *Mp_Factor){ m_lineno=M_lineno; mp_Mulop=Mp_Mulop; mp_Factor=Mp_Factor; } ~Term(); string func_codeGeneration(); bool error_detect(string symbol_sheet_name); void setType(int _type) { type = _type; } int getType() { return type; }; int getRangeVal() { return rangeVal; } bool getRangeValid() { return rangeValid; } int m_lineno; int type; int rangeVal; bool rangeValid; // the below two pointers // only one can be assign to non-NULL // the other must be NULL Mulop *mp_Mulop; Factor *mp_Factor; void outputTree(); }; // the smallest value unit class Factor { public: Factor(){}; ~Factor(); string func_codeGeneration(); bool error_detect(string symbol_sheet_name); int getType() { return type; }//返回数据类型,integer,char等等 void setType(int _type) { type = _type; } int func_checkFactorType() { return m_factorType; } int getRangeVal() { return rangeVal; } bool getRangeValid() { return rangeValid; } int rangeVal; bool rangeValid; int m_int; float m_real; char m_char; bool m_bool; int m_factorType; int m_lineno; int type; // the below pointers // only one can be assigned to non-NULL // the others must be null Variable *mp_Variable; Function_Call *mp_Function_Call; Expression *mp_Expression; Not *mp_Not; Uminus *mp_Uminus; void outputTree(); }; // the operator 'not' class Not { public: Not(); ~Not(); string func_codeGeneration(); bool error_detect(string symbol_sheet_name); int m_lineno; Factor *mp_Factor; void outputTree(); }; // the operator + - // as for: // -1 +2 -i +j class Uminus { public: Uminus(); ~Uminus(); string func_codeGeneration(); bool error_detect(string symbol_sheet_name); int getType() { return type; }; void setType(int _type) {type = _type; } int getRangeVal() { return rangeVal; } bool getRangeValid() { return rangeValid; } int rangeVal; bool rangeValid; int m_lineno; int m_unimusType; int type; Factor *mp_Factor; void outputTree(); }; // only used for var block class Type { public: Type(){}; ~Type(); string func_codeGeneration(); string func_code_getperiod(); int func_checkSimpleType() { return m_simpleType; } bool func_check_isArray() { return m_isArray; } int get_lineno() { return m_lineno; } vector<pair<int, int> > func_get_Period(); int m_simpleType; bool m_isArray; int m_lineno; // if m_isArray == true // this pointer will point to the period(multi-dimension) Period *mp_Period; void outputTree(); }; // used for const block class Const_Value { public: Const_Value(){}; ~Const_Value(); string func_codeGeneration(); int func_checkValueType() { return m_valueType; } int m_postNeg; int m_valueType; // the below value are all unsigned int m_int; float m_real; char m_char; bool m_bool; int m_lineno; bool m_isId; // if m_isId == true // this pointer point to the refered ID Id *mp_Id; void outputTree(); }; class Assignop { public: Assignop(); Assignop(Variable *Mp_Variable,Expression* Mp_Expression){ mp_Variable = Mp_Variable; mp_Expression = Mp_Expression; } ~Assignop(); string func_codeGeneration(); bool error_detect(string symbol_sheet_name); int m_lineno; Variable *mp_Variable; Expression *mp_Expression; void outputTree(); }; class If_Then_Else { public: If_Then_Else(); If_Then_Else(Expression *_mp_Expression, Statement *_mp_Statement_1, Statement *_mp_Statement_2) { mp_Expression = _mp_Expression; mp_Statement_1 = _mp_Statement_1; mp_Statement_2 = _mp_Statement_2; } ~If_Then_Else(); string func_codeGeneration(); bool error_detect(string symbol_sheet_name); int m_lineno; Expression *mp_Expression; Statement *mp_Statement_1; Statement *mp_Statement_2; void outputTree(); }; class For { public: For(); For(Id *_mp_Id, Expression *_mp_Expression_1, Expression *_mp_Expression_2, Statement *_mp_Statment) { mp_Id = _mp_Id; mp_Expression_1 = _mp_Expression_1; mp_Expression_2 = _mp_Expression_2; mp_Statment = _mp_Statment; } ~For(); string func_codeGeneration(); bool error_detect(string symbol_sheet_name); int m_lineno; Id *mp_Id; Expression *mp_Expression_1; Expression *mp_Expression_2; Statement *mp_Statment; void outputTree(); }; class Parameter { public: Parameter(bool M_isVal,int M_lineno,Id_List *Mp_Id_List){ m_isVal=M_isVal; m_lineno=M_lineno; mp_Id_List=Mp_Id_List; } ~Parameter(); string func_codeGeneration(); bool func_isVal() { return m_isVal; } vector<Id*> func_get_mv_id(); int get_lineno() { return m_lineno; } int func_get_m_type() { return m_Type; } Id_List* get_idlist() { return mp_Id_List; } // define whether the parameter is variable element bool m_isVal; int m_lineno; int m_Type; Id_List *mp_Id_List; void outputTree(); }; class Relop { public: Relop(); Relop(int M_relopType,int M_lineno,Simple_Expression *Mp_Simple_Expression_1,Simple_Expression *Mp_Simple_Expression_2){ m_relopType=M_relopType; m_lineno=M_lineno; mp_Simple_Expression_1=Mp_Simple_Expression_1; mp_Simple_Expression_2=Mp_Simple_Expression_1; } ~Relop(); string func_codeGeneration(); bool error_detect(string symbol_sheet_name); int func_checkRelopType() { return m_relopType; } void func_setRelopType(int _type) { m_relopType = _type; } void setType(int _type) { type = _type; } //设置或返回该表达式是什么类型; int getType() { return type; } int m_relopType; int m_lineno; int type; Simple_Expression *mp_Simple_Expression_1; Simple_Expression *mp_Simple_Expression_2; void outputTree(); }; class Addop { public: Addop(); Addop(int M_addopType,int M_lineno,Simple_Expression *Mp_Simple_Expression,Term *Mp_Term){ m_addopType=M_addopType; m_lineno=M_lineno; mp_Simple_Expression=Mp_Simple_Expression; mp_Term=Mp_Term; } ~Addop(); string func_codeGeneration(); bool error_detect(string symbol_sheet_name); int getType() { return type; } void setType(int _type) { type = _type; } //设置type的值 int func_checkAddopType() { return m_addopType; } void func_checkAddopType(int _type) { m_addopType = _type; } int m_addopType; int m_lineno; int type; Simple_Expression *mp_Simple_Expression; Term *mp_Term; void outputTree(); }; class Mulop { public: Mulop(); Mulop(int M_mulopType,int M_lineno,Term *Mp_Term,Factor *Mp_Factor){ m_mulopType=M_mulopType; m_lineno=M_lineno; mp_Term=Mp_Term; mp_Factor=Mp_Factor; } ~Mulop(); string func_codeGeneration(); bool error_detect(string symbol_sheet_name); int func_checkMulopType() { return m_mulopType; } void setType(int _type) { type = _type; } int getType() { return type; } int m_mulopType; int m_lineno; int type; Term *mp_Term; Factor *mp_Factor; void outputTree(); }; class Id{ public: Id(){}; ~Id(); string func_codeGeneration(); int func_checkType() { return m_idType; }; string func_getName() { return m_name; } bool func_isVal() { return m_isVal; } string m_name; int m_idType; int m_lineno; // This note only used in function and procedure // to identify whether the id // is a variable element // // no matter in parameter declaration // or in the func/proc body // // default to be false // bool m_isVal; void outputTree(); }; class Id_List { public: Id_List(){}; ~Id_List(); string func_codeGeneration(); vector<Id*> func_get_mv_Id() { return mv_Id; } int get_id_num() { return (int)mv_Id.size(); } // vector<int> get_id_types() { // vector<int> id_types; // for (auto id: mv_Id) { // id_types.push_back(id->m_idType); // } // return id_types; // } bool isVal() { return mv_Id.front()->m_isVal; // the vector should be the same kind } int m_lineno; vector<Id*>mv_Id; void outputTree(); }; class Period { public: Period(){}; Period(vector<pair<int, int> > Mv_dims){ mv_dims=Mv_dims; } ~Period(); string func_codeGeneration(); vector<pair<int, int> > func_get_Range() { return mv_dims; } // record the multi-dimension ranges vector<pair<int, int> >mv_dims; void outputTree(); }; class Expression_List { public: Expression_List(){}; Expression_List(vector<Expression*>Mv_Expression,vector<int> MType){ mv_Expression=Mv_Expression; mv_Type=MType; } ~Expression_List(); string func_codeGeneration(); bool error_detect(string symbol_sheet_name); vector<Expression*> func_get_mv_exp() { return mv_Expression; } vector<int> func_get_mv_type() { return mv_Type; } vector<int> rangeVal; vector<bool> rangeValid; vector<Expression*>mv_Expression; // store the Type of each expression // allowed type: // TYPE_INTERGER // TYPE_REAL // TYPE_CHAR vector<int>mv_Type; // this vector default to be false // // if the expression list used in // function call or procedure call // // we should know whether the parameter is // a variable element // // if this parameter is a variable element // it must be an id vector<bool>mv_VarDefine; void outputTree(); };
22.291139
202
0.648455
[ "vector" ]
8c680a28c70ee86959f504eba8af15752747800a
3,259
h
C
src/tpp_solution.h
RSkinderowicz/MMAS-for-UTPP
423a5b87c8240cb16cbe5a5adc7f3295f5d93705
[ "MIT" ]
null
null
null
src/tpp_solution.h
RSkinderowicz/MMAS-for-UTPP
423a5b87c8240cb16cbe5a5adc7f3295f5d93705
[ "MIT" ]
null
null
null
src/tpp_solution.h
RSkinderowicz/MMAS-for-UTPP
423a5b87c8240cb16cbe5a5adc7f3295f5d93705
[ "MIT" ]
null
null
null
#ifndef TPP_SOLUTION_H #define TPP_SOLUTION_H #include "tpp.h" namespace TPP { struct Solution { struct MarketAddVerdict { int cost_change_{ 0 }; uint32_t index_{ 0 }; bool demand_satisfied_{ false }; // True if after market is added // all demands are satisfied }; const Instance &instance_; vector<uint32_t> route_{ 0u }; // A depot int cost_{ 0 }; int travel_cost_{ 0 }; vector<uint8_t> market_selected_; // [i] = true if market i is a part of solution vector<vector<ProductOffer>> product_offers_; // [i] - list of offers for product i // in the solution vector<int> purchase_costs_; // [i] = total purchase cost for product i vector<int> demand_remaining_; // [i] = a total unsatisfied demand for the product i vector<uint32_t> remaining_products_; // a list of ids of still needed // products, i.e. with demand > 0 vector<uint32_t> markets_per_product_; // [i] = how many markets were // necessary to satisfy demand vector<uint32_t> unselected_markets_; int total_unsatisfied_demand_{ 0 }; Solution(const Instance &instance) noexcept; void push_back_market(uint32_t market_id) noexcept; void insert_market_at_pos(uint32_t market_id, uint32_t index) noexcept; void remove_market_at_pos(uint32_t pos) noexcept; /** * Calculates how the solution cost changes if a product offer is added. * Returns change of a total product purchase cost and a boolean equal to true * if demand is satisfied after adding the offer. * * This has complexity of O(log(K)) for U-TPP * and O(M log(K)) for capacitated version */ pair<int, int> calc_product_offer_add_cost(ProductOffer offer) const noexcept; int add_product_offer(const ProductOffer &offer) noexcept; int remove_product_offer(const ProductOffer &offer) noexcept; pair<int, bool> calc_product_offer_removal_cost(const ProductOffer &offer) const noexcept; MarketAddVerdict calc_market_removal_cost(uint32_t market_id, bool validity_required=false) const noexcept; MarketAddVerdict calc_market_add_cost(uint32_t market_id) const noexcept; /* * Returns true if adding market to a solution will result in a * feasible solution, i.e. with all demands satisfied. */ bool check_market_satisfies_demand(uint32_t market_id) const noexcept; bool is_market_used(uint32_t market_id) const noexcept; bool is_valid() const noexcept; vector<uint32_t> get_unselected_markets() const noexcept; uint32_t get_market_pos_in_route(uint32_t market_id) const noexcept; /** * Returns an error of the solution relative to the best known result * or std::numeric_limits<double>::max() if best known is not * available. */ double get_relative_error() const noexcept; }; } #endif
37.034091
98
0.6278
[ "vector" ]
8c6fb42b34d2364e55390f360ce5c4d02061c443
13,674
h
C
include/abb_librws/v2_0/rws_interface.h
herrvonregen/abb_librws
a34f824b76b7a63b41f53054f1d0588535aa6b39
[ "BSD-3-Clause" ]
null
null
null
include/abb_librws/v2_0/rws_interface.h
herrvonregen/abb_librws
a34f824b76b7a63b41f53054f1d0588535aa6b39
[ "BSD-3-Clause" ]
5
2021-11-25T09:24:05.000Z
2022-02-21T13:41:14.000Z
include/abb_librws/v2_0/rws_interface.h
NoMagicAi/abb_librws
a34f824b76b7a63b41f53054f1d0588535aa6b39
[ "BSD-3-Clause" ]
2
2021-03-20T09:30:53.000Z
2022-01-02T13:13:30.000Z
/*********************************************************************************************************************** * * Copyright (c) 2015, ABB Schweiz AG * 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 ABB 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. * *********************************************************************************************************************** */ #pragma once #include <abb_librws/rws_cfg.h> #include <abb_librws/v2_0/rws_client.h> #include <abb_librws/v2_0/rws.h> #include <abb_librws/common/rw/io.h> #include <abb_librws/rws_subscription.h> #include <abb_librws/rws_info.h> #include <abb_librws/xml_attribute.h> #include <chrono> #include <cstdint> namespace abb :: rws :: v2_0 { /** * \brief User-friendly interface to Robot Web Services (RWS) 2.0. * * Only a subset of the features available in RWS are implemented here. * See https://developercenter.robotstudio.com/api/RWS for details about RWS 2.0 */ class RWSInterface { public: /** * \brief A constructor. * * \param client RWS client */ explicit RWSInterface(RWSClient& client); /** * \brief Retrieves the configuration instances for the arms defined in the system. * * \return std::vector<cfg::moc::Arm> containing a list of the arms defined in the system. * * \throw std::runtime_error if failed to get or parse the configuration instances. */ std::vector<cfg::moc::Arm> getCFGArms(); /** * \brief Retrieves the configuration instances for the joints defined in the system. * * \return std::vector<cfg::moc::Joint> containing a list of the joints defined in the system. * * \throw std::runtime_error if failed to get or parse the configuration instances. */ std::vector<cfg::moc::Joint> getCFGJoints(); /** * \brief Retrieves the configuration instances for the mechanical units defined in the system. * * \return std::vector<cfg::moc::MechanicalUnit> containing a list of the mechanical units defined in the system. * * \throw std::runtime_error if failed to get or parse the configuration instances. */ std::vector<cfg::moc::MechanicalUnit> getCFGMechanicalUnits(); /** * \brief Retrieves the configuration instances for the mechanical unit groups defined in the system. * * \return std::vector<cfg::sys::MechanicalUnitGroup> containing a list of the mechanical unit groups in the system. * * \throw std::runtime_error if failed to get or parse the configuration instances. */ std::vector<cfg::sys::MechanicalUnitGroup> getCFGMechanicalUnitGroups(); /** * \brief Retrieves the configuration instances for the present (RobotWare) options. * * \return std::vector<cfg::sys::PresentOption> containing a list of the present (RobotWare) options. * * \throw std::runtime_error if failed to get or parse the configuration instances. */ std::vector<cfg::sys::PresentOption> getCFGPresentOptions(); /** * \brief Retrieves the configuration instances for the robots defined in the system. * * \return std::vector<cfg::moc::Robot> containing a list of robots defined in the system. * * \throw std::runtime_error if failed to get or parse the configuration instances. */ std::vector<cfg::moc::Robot> getCFGRobots(); /** * \brief Retrieves the configuration instances for the singles defined in the system. * * \return std::vector<cfg::moc::Single> containing a list of the singles defined in the system. * * \throw std::runtime_error if failed to get or parse the configuration instances. */ std::vector<cfg::moc::Single> getCFGSingles(); /** * \brief Retrieves the configuration instances for the transmissions defined in the system. * * \return std::vector<cfg::moc::Transmission> containing a list of the transmissions defined in the system. * * \throw std::runtime_error if failed to get or parse the configuration instances. */ std::vector<cfg::moc::Transmission> getCFGTransmission(); /** * \brief A method for retrieving the RobotWare options present on the active robot controller system. * * This method has been deprecated, please use 'getCFGPresentOptions()' instead. * * \return std::vector<RobotWareOptionInfo> containing a list of the present RobotWare options. */ ABB_LIBRWS_DEPRECATED std::vector<RobotWareOptionInfo> getPresentRobotWareOptions(); /// @brief Get value of a digital signal /// /// @param signal_name Name of the signal /// @return Value of the requested digital signal /// bool getDigitalSignal(std::string const& signal_name); /// @brief Get value of an analog signal /// /// @param signal_name Name of the signal /// @return Value of the requested analog signal /// float getAnalogSignal(std::string const& signal_name); /// @brief Get value of a group signal /// /// @param signal_name Name of the signal /// @return Value of the requested group signal /// std::uint32_t getGroupSignal(std::string const& signal_name); /** * \brief Get values of all IO signals. * * \return Mapping from IO signal names to values. */ rw::io::IOSignalInfo getIOSignals(); /** * \brief A method for retrieving static information about a mechanical unit. * * \param mechunit for the mechanical unit's name. * * \return static information about a mechanical unit. * * \throw \a std::runtime_error if something goes wrong. */ MechanicalUnitStaticInfo getMechanicalUnitStaticInfo(const std::string& mechunit); /** * \brief A method for retrieving dynamic information about a mechanical unit. * * \param mechunit for the mechanical unit's name. * * \return dynamic information about a mechanical unit. * * \throw \a std::runtime_error if something goes wrong. */ MechanicalUnitDynamicInfo getMechanicalUnitDynamicInfo(const std::string& mechunit); /** * \brief A method for retrieving the current jointtarget values of a mechanical unit. * * \param mechunit for the mechanical unit's name. * * \return jointtarget data. * * \throw \a std::runtime_error if something goes wrong. */ JointTarget getMechanicalUnitJointTarget(const std::string& mechunit); /** * \brief A method for retrieving the current robtarget values of a mechanical unit. * * \param mechunit for the mechanical unit's name. * \param coordinate for the coordinate mode (base, world, tool, or wobj) in which the robtarget will be reported. * \param tool for the tool frame relative to which the robtarget will be reported. * \param wobj for the work object (wobj) relative to which the robtarget will be reported. * * \throw \a std::runtime_error if something goes wrong. * * \return robtarget data. */ RobTarget getMechanicalUnitRobTarget(const std::string& mechunit, Coordinate coordinate = Coordinate::ACTIVE, const std::string& tool = "", const std::string& wobj = ""); /** * \brief A method for retrieving some system information from the robot controller. * * \return SystemInfo containing the system information (info will be empty if e.g. a timeout occurred). * * \throw \a std::runtime_error if something goes wrong. */ SystemInfo getSystemInfo(); /// @brief Set value of a digital signal /// /// @param signal_name Name of the signal /// @param value New value of the signal /// void setDigitalSignal(std::string const& signal_name, bool value); /// @brief Set value of an analog signal /// /// @param signal_name Name of the signal /// @param value New value of the signal /// void setAnalogSignal(std::string const& signal_name, float value); /// @brief Set value of a group signal /// /// @param signal_name Name of the signal /// @param value New value of the signal /// void setGroupSignal(std::string const& signal_name, std::uint32_t value); /** * \brief A method for retrieving a file from the robot controller. * * Note: Depending on the file, then the content can be in text or binary format. * * \param resource specifying the file's directory and name. * * \return file content. * * \throw \a std::exception if something goes wrong. */ std::string getFile(const FileResource& resource); /** * \brief A method for uploading a file to the robot controller. * * \param resource specifying the file's directory and name. * \param file_content for the file's content. * * \throw \a std::exception if something goes wrong. */ void uploadFile(const FileResource& resource, const std::string& file_content); /** * \brief A method for deleting a file from the robot controller. * * \param resource specifying the file's directory and name. * * \throw \a std::exception if something goes wrong. */ void deleteFile(const FileResource& resource); /** * \brief Creates a subscription group. * * \param resources specifying the resources to subscribe to. * * \return Newly created \a SubscriptionGroup for specified subscription resources. * * \throw \a std::exception if something goes wrong */ SubscriptionGroup openSubscription(const SubscriptionResources& resources); /** * \brief A method for registering a user as local. * * \param username specifying the user name. * \param application specifying the external application. * \param location specifying the location. * * \throw \a std::exception if something goes wrong. */ void registerLocalUser(const std::string& username = SystemConstants::General::DEFAULT_USERNAME, const std::string& application = SystemConstants::General::EXTERNAL_APPLICATION, const std::string& location = SystemConstants::General::EXTERNAL_LOCATION); /** * \brief A method for registering a user as remote. * * \param username specifying the user name. * \param application specifying the external application. * \param location specifying the location. * * \throw \a std::exception if something goes wrong. */ void registerRemoteUser(const std::string& username = SystemConstants::General::DEFAULT_USERNAME, const std::string& application = SystemConstants::General::EXTERNAL_APPLICATION, const std::string& location = SystemConstants::General::EXTERNAL_LOCATION); /** * \brief Request RWS mastership * * \param domain requested mastership domain */ void requestMastership(MastershipDomain domain); /** * \brief Release RWS mastership * * \param domain mastership domain to be released */ void releaseMastership(MastershipDomain domain); private: using RWSResult = RWSClient::RWSResult; /** * \brief A method for comparing a single text content (from a XML document node) with a specific string value. * * \param rws_result for containing a RWS communication result. * \param attribute for specifying the XML node's required attribute. * \param compare_string for specifying the comparison string. * * \return The result of the comparison. */ static bool compareSingleContent(const RWSResult& rws_result, const XMLAttribute& attribute, const std::string& compare_string); /** * \brief A method for retrieving the value if an IO signal. * * \param iosignal for the name of the IO signal. * * \return std::string containing the IO signal's value (empty if not found). */ std::string getIOSignal(const std::string& iosignal); /** * \brief A method for setting the value of an IO signal. * * \param iosignal for the name of the IO signal. * \param value for the IO signal's new value. * * \throw \a std::runtime_error if something goes wrong. */ void setIOSignal(const std::string& iosignal, const std::string& value); /** * \brief The RWS client used to communicate with the robot controller. */ RWSClient& rws_client_; }; } // end namespace rws
34.793893
120
0.682682
[ "object", "vector" ]
8c70878c772f6fa28483073117268c38c914dd05
7,978
c
C
src/test/graphics/clear-grab.c
PSP-Archive/System-Interface-Library
42bfd5b1f0e767215010365894cfa9598915ea55
[ "X11" ]
null
null
null
src/test/graphics/clear-grab.c
PSP-Archive/System-Interface-Library
42bfd5b1f0e767215010365894cfa9598915ea55
[ "X11" ]
null
null
null
src/test/graphics/clear-grab.c
PSP-Archive/System-Interface-Library
42bfd5b1f0e767215010365894cfa9598915ea55
[ "X11" ]
null
null
null
/* * System Interface Library for games * Copyright (c) 2007-2020 Andrew Church <achurch@achurch.org> * Released under the GNU GPL version 3 or later; NO WARRANTY is provided. * See the file COPYING.txt for details. * * src/test/graphics/clear-grab.c: Tests for graphics_clear() and * graphics_read_pixels(). These are split out from base.c so they can be * run in a single window instead of having to open and close the window * for each test (which can be slow). */ #include "src/base.h" #include "src/graphics.h" #include "src/memory.h" #include "src/test/base.h" #include "src/test/graphics/internal.h" /*************************************************************************/ /***************************** Test routines *****************************/ /*************************************************************************/ static int do_test_graphics_clear_grab(void); int test_graphics_clear_grab(void) { return run_tests_in_window(do_test_graphics_clear_grab); } DEFINE_GENERIC_TEST_RUNNER(do_test_graphics_clear_grab) TEST_INIT(init) { graphics_start_frame(); return 1; } TEST_CLEANUP(cleanup) { graphics_finish_frame(); graphics_flush_resources(); return 1; } /*-----------------------------------------------------------------------*/ TEST(test_clear_sync_grab) { const int width = graphics_display_width(); const int height = graphics_display_height(); uint8_t *pixels; ASSERT(pixels = mem_alloc(width * height * 4, 0, MEM_ALLOC_TEMP)); graphics_clear(0, 0, 0, 0, 1, 0); graphics_sync(); // Call it once just to verify that it doesn't break. CHECK_TRUE(graphics_read_pixels(0, 0, width, height, pixels)); for (int i = 0; i < width*height*4; i += 4) { CHECK_PIXEL(&pixels[i], 0,0,0,255, (i/4) % width, (i/4) / width); } mem_free(pixels); return 1; } /*-----------------------------------------------------------------------*/ TEST(test_clear_with_color) { #define TESTCASE(r,g,b,pr,pg,pb) {__LINE__, r, g, b, {pr, pg, pb, 255}} static const struct {int line; float r, g, b; uint8_t pixel[4];} tests[] ={ TESTCASE( 1.0, 0.0, 0.0, 255, 0, 0), TESTCASE( 0.0, 1.0, 0.0, 0,255, 0), TESTCASE( 0.0, 0.0, 1.0, 0, 0,255), TESTCASE( 1.0, 1.0, 1.0, 255,255,255), TESTCASE( 0.2, 0.4, 0.6, 51,102,153), TESTCASE(-1.0,-1.0,-1.0, 0, 0, 0), TESTCASE( 2.0, 2.0, 2.0, 255,255,255), }; #undef TESTCASE const int width = graphics_display_width(); const int height = graphics_display_height(); uint8_t *pixels; ASSERT(pixels = mem_alloc(width * height * 4, 0, MEM_ALLOC_TEMP)); for (int test = 0; test < lenof(tests); test++) { if (test > 0) { /* Don't leave a red screen displayed for a long time if these * tests are slow. */ graphics_finish_frame(); graphics_start_frame(); } graphics_clear(tests[test].r, tests[test].g, tests[test].b, 0, 1, 0); CHECK_TRUE(graphics_read_pixels(0, 0, width, height, pixels)); for (int i = 0; i < width*height*4; i += 4) { CHECK_PIXEL(&pixels[i], tests[test].pixel[0], tests[test].pixel[1], tests[test].pixel[2], tests[test].pixel[3], (i/4) % width, (i/4) / height); } } mem_free(pixels); return 1; } /*-----------------------------------------------------------------------*/ TEST(test_grab_bounds_negative) { graphics_clear(0.2, 0.4, 0.6, 0, 1, 0); uint8_t pixels[8*8*4]; /* graphics_read_pixels() says that areas outside the window are * undefined, but we rely on current behavior that pixels with X or Y * coordinate less than zero are unchanged. */ memset(pixels, 1, sizeof(pixels)); CHECK_TRUE(graphics_read_pixels(-2, -6, 8, 8, pixels)); for (int i = 0; i < 8*8*4; i += 4) { const int x = (i/4) % 8; const int y = (i/4) / 8; const int r = (x >= 2 && y >= 6 ? 51 : 1); const int g = (x >= 2 && y >= 6 ? 102 : 1); const int b = (x >= 2 && y >= 6 ? 153 : 1); const int a = (x >= 2 && y >= 6 ? 255 : 1); CHECK_PIXEL(&pixels[i], r,g,b,a, x, y); } return 1; } /*-----------------------------------------------------------------------*/ TEST(test_grab_bounds_negative_2) { graphics_clear(0.2, 0.4, 0.6, 0, 1, 0); uint8_t pixels[8*8*4]; memset(pixels, 1, sizeof(pixels)); CHECK_TRUE(graphics_read_pixels(-8, -6, 8, 8, pixels)); CHECK_TRUE(graphics_read_pixels(-6, -8, 8, 8, pixels)); for (int i = 0; i < 8*8*4; i += 4) { const int x = (i/4) % 8; const int y = (i/4) / 8; CHECK_PIXEL(&pixels[i], 1,1,1,1, x, y); } return 1; } /*-----------------------------------------------------------------------*/ TEST(test_grab_bounds_positive) { const int width = graphics_display_width(); const int height = graphics_display_height(); graphics_clear(0.2, 0.4, 0.6, 0, 1, 0); uint8_t pixels[8*8*4]; memset(pixels, 1, sizeof(pixels)); CHECK_TRUE(graphics_read_pixels(width-2, height-6, 8, 8, pixels)); for (int i = 0; i < 8*8*4; i += 4) { const int x = (i/4) % 8; const int y = (i/4) / 8; if (x < 2 && y < 6) { CHECK_PIXEL(&pixels[i], 51,102,153,255, x, y); } } return 1; } /*-----------------------------------------------------------------------*/ TEST(test_grab_bounds_positive_2) { const int width = graphics_display_width(); const int height = graphics_display_height(); graphics_clear(0.2, 0.4, 0.6, 0, 1, 0); uint8_t pixels[8*8*4]; /* Just check that the calls succeed, since the data is undefined. */ CHECK_TRUE(graphics_read_pixels(width, 0, 8, 8, pixels)); CHECK_TRUE(graphics_read_pixels(0, height+4, 8, 8, pixels)); CHECK_TRUE(graphics_read_pixels(width, height+4, 8, 8, pixels)); return 1; } /*-----------------------------------------------------------------------*/ TEST(test_grab_invalid) { CHECK_FALSE(graphics_read_pixels(0, 0, 8, 8, NULL)); return 1; } /*-----------------------------------------------------------------------*/ /* This test is here rather than with the other attribute tests since we * render a couple of frames to ensure that toggling V-sync doesn't cause * graphics driver problems. */ TEST(test_set_vsync_while_open) { const int width = graphics_display_width(); const int height = graphics_display_height(); uint8_t *pixels; ASSERT(pixels = mem_alloc(width * height * 4, 0, MEM_ALLOC_TEMP)); graphics_clear(0, 1, 1, 0, 1, 0); CHECK_TRUE(graphics_read_pixels(0, 0, width, height, pixels)); for (int i = 0; i < width*height*4; i += 4) { CHECK_PIXEL(&pixels[i], 0,255,255,255, (i/4) % width, (i/4) / width); } if (!graphics_set_display_attr("vsync", 0)) { mem_free(pixels); SKIP("System does not support toggling V-sync."); } graphics_finish_frame(); graphics_start_frame(); graphics_clear(0, 1, 0, 0, 1, 0); CHECK_TRUE(graphics_read_pixels(0, 0, width, height, pixels)); for (int i = 0; i < width*height*4; i += 4) { CHECK_PIXEL(&pixels[i], 0,255,0,255, (i/4) % width, (i/4) / width); } if (!graphics_set_display_attr("vsync", 1)) { mem_free(pixels); SKIP("System does not support toggling V-sync."); } graphics_finish_frame(); graphics_start_frame(); graphics_clear(0, 0, 1, 0, 1, 0); CHECK_TRUE(graphics_read_pixels(0, 0, width, height, pixels)); for (int i = 0; i < width*height*4; i += 4) { CHECK_PIXEL(&pixels[i], 0,0,255,255, (i/4) % width, (i/4) / width); } mem_free(pixels); return 1; } /*************************************************************************/ /*************************************************************************/
32.563265
79
0.527701
[ "render" ]
967986f983082f4b17454191b87c443a3362bf4d
3,038
h
C
contrib/mmtf-c/mmtf_parser_private.h
gmrandazzo/Pymol
7f081625686bdc0a74c879f998f067c254af5ec8
[ "CNRI-Python" ]
null
null
null
contrib/mmtf-c/mmtf_parser_private.h
gmrandazzo/Pymol
7f081625686bdc0a74c879f998f067c254af5ec8
[ "CNRI-Python" ]
null
null
null
contrib/mmtf-c/mmtf_parser_private.h
gmrandazzo/Pymol
7f081625686bdc0a74c879f998f067c254af5ec8
[ "CNRI-Python" ]
null
null
null
// ************************************************************************* // Copyright [2016] [RCSB] // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // // This is a private header file for mmtf_parser.c and must not be included // by other files. // // The authors of this code are: Julien Ferte (http://www.julienferte.com/), // Anthony Bradley, Thomas Holder. // // // Other contributors: Yana Valasatava, Alexander Rose. // // ************************************************************************* #ifndef MMTF_PRIVATE_H #define MMTF_PRIVATE_H #include "mmtf_parser.h" //*** Standard libs #include <stdbool.h> //*** MsgPack lib #ifdef MMTF_MSGPACK_USE_CPP11 #include <msgpack.hpp> #define msgpack_object msgpack::object #define msgpack_object_kv msgpack::object_kv #define msgpack_object_str msgpack::object_str #define MMTF_MSGPACK_TYPE(T) msgpack::type::T #else #include <msgpack.h> #define MMTF_MSGPACK_TYPE(T) MSGPACK_OBJECT_##T #endif #ifdef __cplusplus extern "C" { #endif //*** Array converters float* MMTF_parser_float_from_bytes(const char*, uint32_t, uint32_t*); int8_t* MMTF_parser_int8_from_bytes(const char*, uint32_t, uint32_t*); int16_t* MMTF_parser_int16_from_bytes(const char*, uint32_t, uint32_t*); int32_t* MMTF_parser_int32_from_bytes(const char*, const uint32_t, uint32_t*); char** MMTF_parser_strings_from_bytes(const char*, uint32_t, uint32_t, uint32_t*); //*** Array decoders int32_t* MMTF_parser_run_length_decode(const int32_t*, uint32_t, uint32_t*); int32_t* MMTF_parser_delta_decode(const int32_t*, uint32_t, uint32_t*); int32_t* MMTF_parser_recursive_indexing_decode_from_16(const int16_t*, uint32_t, uint32_t*); int32_t* MMTF_parser_recursive_indexing_decode_from_8(const int8_t*, uint32_t, uint32_t*); float* MMTF_parser_integer_decode_from_16(const int16_t*, uint32_t, int32_t, uint32_t*); float* MMTF_parser_integer_decode_from_32(const int32_t*, uint32_t, int32_t, uint32_t*); //*** Unpacking from MsgPack and applying strategy char* MMTF_parser_fetch_string(const msgpack_object*); int64_t MMTF_parser_fetch_int(const msgpack_object*); float MMTF_parser_fetch_float(const msgpack_object*); MMTF_Entity* MMTF_parser_fetch_entityList(const msgpack_object*, size_t*); MMTF_GroupType* MMTF_parser_fetch_groupTypeList(const msgpack_object*, size_t*); MMTF_BioAssembly* MMTF_parser_fetch_bioAssemblyList(const msgpack_object*, size_t*); MMTF_Transform* MMTF_parser_fetch_transformList(const msgpack_object*, size_t*); #ifdef __cplusplus } #endif #endif // vi:sw=4:expandtab
35.741176
92
0.74819
[ "object" ]
967a59b4298e988bbe245b951627cb4ddbff2dbc
19,545
h
C
third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.h
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.h
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.h
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
/* * Copyright (c) 2010, Google 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 Google 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 DrawingBuffer_h #define DrawingBuffer_h #include "cc/layers/texture_layer_client.h" #include "gpu/command_buffer/common/mailbox.h" #include "gpu/command_buffer/common/sync_token.h" #include "platform/PlatformExport.h" #include "platform/geometry/IntSize.h" #include "platform/graphics/GraphicsTypes3D.h" #include "platform/graphics/gpu/WebGLImageConversion.h" #include "third_party/khronos/GLES2/gl2.h" #include "third_party/skia/include/core/SkBitmap.h" #include "wtf/Deque.h" #include "wtf/Noncopyable.h" #include "wtf/RefCounted.h" #include "wtf/Vector.h" #include <memory> namespace cc { class SharedBitmap; } namespace gpu { namespace gles2 { class GLES2Interface; } } namespace WTF { class ArrayBufferContents; } namespace blink { class Extensions3DUtil; class StaticBitmapImage; class WebExternalTextureLayer; class WebGraphicsContext3DProvider; class WebGraphicsContext3DProviderWrapper; class WebLayer; // Manages a rendering target (framebuffer + attachment) for a canvas. Can // publish its rendering results to a WebLayer for compositing. class PLATFORM_EXPORT DrawingBuffer : public NON_EXPORTED_BASE(cc::TextureLayerClient), public RefCounted<DrawingBuffer> { WTF_MAKE_NONCOPYABLE(DrawingBuffer); public: class Client { public: // Returns true if the DrawingBuffer is currently bound for draw. virtual bool DrawingBufferClientIsBoundForDraw() = 0; virtual void DrawingBufferClientRestoreScissorTest() = 0; // Restores the mask and clear value for color, depth, and stencil buffers. virtual void DrawingBufferClientRestoreMaskAndClearValues() = 0; virtual void DrawingBufferClientRestorePixelPackAlignment() = 0; // Restores the GL_TEXTURE_2D binding for the active texture unit only. virtual void DrawingBufferClientRestoreTexture2DBinding() = 0; virtual void DrawingBufferClientRestoreRenderbufferBinding() = 0; virtual void DrawingBufferClientRestoreFramebufferBinding() = 0; virtual void DrawingBufferClientRestorePixelUnpackBufferBinding() = 0; }; enum PreserveDrawingBuffer { Preserve, Discard, }; enum WebGLVersion { WebGL1, WebGL2, }; enum ChromiumImageUsage { AllowChromiumImage, DisallowChromiumImage, }; static PassRefPtr<DrawingBuffer> create( std::unique_ptr<WebGraphicsContext3DProvider>, Client*, const IntSize&, bool premultipliedAlpha, bool wantAlphaChannel, bool wantDepthBuffer, bool wantStencilBuffer, bool wantAntialiasing, PreserveDrawingBuffer, WebGLVersion, ChromiumImageUsage); static void forceNextDrawingBufferCreationToFail(); ~DrawingBuffer() override; // Destruction will be completed after all mailboxes are released. void beginDestruction(); // Issues a glClear() on all framebuffers associated with this DrawingBuffer. void clearFramebuffers(GLbitfield clearMask); // Indicates whether the DrawingBuffer internally allocated a packed // depth-stencil renderbuffer in the situation where the end user only asked // for a depth buffer. In this case, we need to upgrade clears of the depth // buffer to clears of the depth and stencil buffers in order to avoid // performance problems on some GPUs. bool hasImplicitStencilBuffer() const { return m_hasImplicitStencilBuffer; } bool hasDepthBuffer() const { return !!m_depthStencilBuffer; } bool hasStencilBuffer() const { return !!m_depthStencilBuffer; } // Given the desired buffer size, provides the largest dimensions that will // fit in the pixel budget. static IntSize adjustSize(const IntSize& desiredSize, const IntSize& curSize, int maxTextureSize); // Resizes (or allocates if necessary) all buffers attached to the default // framebuffer. Returns whether the operation was successful. bool resize(const IntSize&); // Bind the default framebuffer to |target|. |target| must be // GL_FRAMEBUFFER, GL_READ_FRAMEBUFFER, or GL_DRAW_FRAMEBUFFER. void bind(GLenum target); IntSize size() const { return m_size; } // Resolves the multisample color buffer to the normal color buffer and leaves // the resolved color buffer bound to GL_READ_FRAMEBUFFER and // GL_DRAW_FRAMEBUFFER. void resolveAndBindForReadAndDraw(); bool multisample() const; bool discardFramebufferSupported() const { return m_discardFramebufferSupported; } // Returns false if the contents had previously been marked as changed and // have not yet been committed. bool markContentsChanged(); void setBufferClearNeeded(bool); bool bufferClearNeeded() const; void setIsHidden(bool); void setFilterQuality(SkFilterQuality); // Whether the target for draw operations has format GL_RGBA, but is // emulating format GL_RGB. When the target's storage is first // allocated, its alpha channel must be cleared to 1. All future drawing // operations must use a color mask with alpha=GL_FALSE. bool requiresAlphaChannelToBePreserved(); // Similar to requiresAlphaChannelToBePreserved(), but always targets the // default framebuffer. bool defaultBufferRequiresAlphaChannelToBePreserved(); WebLayer* platformLayer(); gpu::gles2::GLES2Interface* contextGL(); WebGraphicsContext3DProvider* contextProvider(); // cc::TextureLayerClient implementation. bool PrepareTextureMailbox( cc::TextureMailbox* outMailbox, std::unique_ptr<cc::SingleReleaseCallback>* outReleaseCallback) override; // Returns a StaticBitmapImage backed by a texture containing the current // contents of the front buffer. This is done without any pixel copies. The // texture in the ImageBitmap is from the active ContextProvider on the // DrawingBuffer. PassRefPtr<StaticBitmapImage> transferToStaticBitmapImage(); bool copyToPlatformTexture(gpu::gles2::GLES2Interface*, GLuint texture, GLenum internalFormat, GLenum destType, GLint level, bool premultiplyAlpha, bool flipY, const IntPoint& destTextureOffset, const IntRect& sourceSubRectangle, SourceDrawingBuffer); bool paintRenderingResultsToImageData(int&, int&, SourceDrawingBuffer, WTF::ArrayBufferContents&); int sampleCount() const { return m_sampleCount; } bool explicitResolveOfMultisampleData() const { return m_antiAliasingMode == MSAAExplicitResolve; } // Rebind the read and draw framebuffers that WebGL is expecting. void restoreFramebufferBindings(); // Restore all state that may have been dirtied by any call. void restoreAllState(); void addNewMailboxCallback(std::unique_ptr<WTF::Closure> closure) { m_newMailboxCallback = std::move(closure); } protected: // For unittests DrawingBuffer(std::unique_ptr<WebGraphicsContext3DProvider>, std::unique_ptr<Extensions3DUtil>, Client*, bool discardFramebufferSupported, bool wantAlphaChannel, bool premultipliedAlpha, PreserveDrawingBuffer, WebGLVersion, bool wantsDepth, bool wantsStencil, ChromiumImageUsage); bool initialize(const IntSize&, bool useMultisampling); // Shared memory bitmaps that were released by the compositor and can be used // again by this DrawingBuffer. struct RecycledBitmap { std::unique_ptr<cc::SharedBitmap> bitmap; IntSize size; }; Vector<RecycledBitmap> m_recycledBitmaps; private: friend class ScopedStateRestorer; friend class ColorBuffer; // This structure should wrap all public entrypoints that may modify GL state. // It will restore all state when it drops out of scope. class ScopedStateRestorer { public: ScopedStateRestorer(DrawingBuffer*); ~ScopedStateRestorer(); // Mark parts of the state that are dirty and need to be restored. void setClearStateDirty() { m_clearStateDirty = true; } void setPixelPackAlignmentDirty() { m_pixelPackAlignmentDirty = true; } void setTextureBindingDirty() { m_textureBindingDirty = true; } void setRenderbufferBindingDirty() { m_renderbufferBindingDirty = true; } void setFramebufferBindingDirty() { m_framebufferBindingDirty = true; } void setPixelUnpackBufferBindingDirty() { m_pixelUnpackBufferBindingDirty = true; } private: RefPtr<DrawingBuffer> m_drawingBuffer; // The previous state restorer, in case restorers are nested. ScopedStateRestorer* m_previousStateRestorer = nullptr; bool m_clearStateDirty = false; bool m_pixelPackAlignmentDirty = false; bool m_textureBindingDirty = false; bool m_renderbufferBindingDirty = false; bool m_framebufferBindingDirty = false; bool m_pixelUnpackBufferBindingDirty = false; }; // All parameters necessary to generate the texture for the ColorBuffer. struct ColorBufferParameters { DISALLOW_NEW(); GLenum target = 0; GLenum internalColorFormat = 0; // The internal color format used when allocating storage for the // texture. This may be different from internalColorFormat if RGB // emulation is required. GLenum creationInternalColorFormat = 0; GLenum colorFormat = 0; }; struct ColorBuffer : public RefCounted<ColorBuffer> { ColorBuffer(DrawingBuffer*, const ColorBufferParameters&, const IntSize&, GLuint textureId, GLuint imageId); ~ColorBuffer(); // The owning DrawingBuffer. Note that DrawingBuffer is explicitly destroyed // by the beginDestruction method, which will eventually drain all of its // ColorBuffers. RefPtr<DrawingBuffer> drawingBuffer; const ColorBufferParameters parameters; const IntSize size; const GLuint textureId = 0; const GLuint imageId = 0; // The mailbox used to send this buffer to the compositor. gpu::Mailbox mailbox; // The sync token for when this buffer was sent to the compositor. gpu::SyncToken produceSyncToken; // The sync token for when this buffer was received back from the // compositor. gpu::SyncToken receiveSyncToken; private: WTF_MAKE_NONCOPYABLE(ColorBuffer); }; // The same as clearFramebuffers(), but leaves GL state dirty. void clearFramebuffersInternal(GLbitfield clearMask); // The same as reset(), but leaves GL state dirty. bool resizeFramebufferInternal(const IntSize&); // The same as commit(), but leaves GL state dirty. void resolveMultisampleFramebufferInternal(); bool prepareTextureMailboxInternal( cc::TextureMailbox* outMailbox, std::unique_ptr<cc::SingleReleaseCallback>* outReleaseCallback, bool forceGpuResult); // Helper functions to be called only by prepareTextureMailboxInternal. bool finishPrepareTextureMailboxGpu( cc::TextureMailbox* outMailbox, std::unique_ptr<cc::SingleReleaseCallback>* outReleaseCallback); bool finishPrepareTextureMailboxSoftware( cc::TextureMailbox* outMailbox, std::unique_ptr<cc::SingleReleaseCallback>* outReleaseCallback); // Callbacks for mailboxes given to the compositor from // finishPrepareTextureMailboxGpu and finishPrepareTextureMailboxSoftware. void mailboxReleasedGpu(RefPtr<ColorBuffer>, const gpu::SyncToken&, bool lostResource); void mailboxReleasedSoftware(std::unique_ptr<cc::SharedBitmap>, const IntSize&, const gpu::SyncToken&, bool lostResource); // The texture parameters to use for a texture that will be backed by a // CHROMIUM_image, backed by a GpuMemoryBuffer. ColorBufferParameters gpuMemoryBufferColorBufferParameters(); // The texture parameters to use for an ordinary GL texture. ColorBufferParameters textureColorBufferParameters(); // Attempts to allocator storage for, or resize all buffers. Returns whether // the operation was successful. bool resizeDefaultFramebuffer(const IntSize&); void clearPlatformLayer(); std::unique_ptr<cc::SharedBitmap> createOrRecycleBitmap(); // Updates the current size of the buffer, ensuring that // s_currentResourceUsePixels is updated. void setSize(const IntSize& size); // This is the order of bytes to use when doing a readback. enum ReadbackOrder { ReadbackRGBA, ReadbackSkia }; // Helper function which does a readback from the currently-bound // framebuffer into a buffer of a certain size with 4-byte pixels. void readBackFramebuffer(unsigned char* pixels, int width, int height, ReadbackOrder, WebGLImageConversion::AlphaOp); // Helper function to flip a bitmap vertically. void flipVertically(uint8_t* data, int width, int height); // If RGB emulation is required, then the CHROMIUM image's alpha channel // must be immediately cleared after it is bound to a texture. Nothing // should be allowed to change the alpha channel after this. void clearChromiumImageAlpha(const ColorBuffer&); // Tries to create a CHROMIUM_image backed texture if // RuntimeEnabledFeatures::webGLImageChromiumEnabled() is true. On failure, // or if the flag is false, creates a default texture. Always returns a valid // ColorBuffer. RefPtr<ColorBuffer> createColorBuffer(const IntSize&); // Creates or recycles a ColorBuffer of size |m_size|. PassRefPtr<ColorBuffer> createOrRecycleColorBuffer(); // Attaches |m_backColorBuffer| to |m_fbo|, which is always the source for // read operations. void attachColorBufferToReadFramebuffer(); // Whether the WebGL client desires an explicit resolve. This is // implemented by forwarding all draw operations to a multisample // renderbuffer, which is resolved before any read operations or swaps. bool wantExplicitResolve(); // Whether the WebGL client wants a depth or stencil buffer. bool wantDepthOrStencil(); // The format to use when creating a multisampled renderbuffer. GLenum getMultisampledRenderbufferFormat(); // Weak, reset by beginDestruction. Client* m_client = nullptr; const PreserveDrawingBuffer m_preserveDrawingBuffer; const WebGLVersion m_webGLVersion; std::unique_ptr<WebGraphicsContext3DProviderWrapper> m_contextProvider; // Lifetime is tied to the m_contextProvider. gpu::gles2::GLES2Interface* m_gl; std::unique_ptr<Extensions3DUtil> m_extensionsUtil; IntSize m_size = {-1, -1}; const bool m_discardFramebufferSupported; const bool m_wantAlphaChannel; const bool m_premultipliedAlpha; const bool m_softwareRendering; bool m_hasImplicitStencilBuffer = false; bool m_storageTextureSupported = false; std::unique_ptr<WTF::Closure> m_newMailboxCallback; // The current state restorer, which is used to track state dirtying. It is in // error to dirty state shared with WebGL while there is no existing state // restorer. It is also in error to instantiate two state restorers at once. ScopedStateRestorer* m_stateRestorer = nullptr; // This is used when the user requests either a depth or stencil buffer. GLuint m_depthStencilBuffer = 0; // When wantExplicitResolve() returns true, the target of all draw // operations. GLuint m_multisampleFBO = 0; // The id of the renderbuffer storage for |m_multisampleFBO|. GLuint m_multisampleRenderbuffer = 0; // When wantExplicitResolve() returns false, the target of all draw and // read operations. When wantExplicitResolve() returns true, the target of // all read operations. GLuint m_fbo = 0; // The ColorBuffer that backs |m_fbo|. RefPtr<ColorBuffer> m_backColorBuffer; // The ColorBuffer that was most recently presented to the compositor by // prepareTextureMailboxInternal. RefPtr<ColorBuffer> m_frontColorBuffer; // True if our contents have been modified since the last presentation of this // buffer. bool m_contentsChanged = true; // True if commit() has been called since the last time markContentsChanged() // had been called. bool m_contentsChangeCommitted = false; bool m_bufferClearNeeded = false; // Whether the client wants a depth or stencil buffer. const bool m_wantDepth; const bool m_wantStencil; enum AntialiasingMode { None, MSAAImplicitResolve, MSAAExplicitResolve, ScreenSpaceAntialiasing, }; AntialiasingMode m_antiAliasingMode = None; int m_maxTextureSize = 0; int m_sampleCount = 0; bool m_destructionInProgress = false; bool m_isHidden = false; SkFilterQuality m_filterQuality = kLow_SkFilterQuality; std::unique_ptr<WebExternalTextureLayer> m_layer; // Mailboxes that were released by the compositor can be used again by this // DrawingBuffer. Deque<RefPtr<ColorBuffer>> m_recycledColorBufferQueue; // If the width and height of the Canvas's backing store don't // match those that we were given in the most recent call to // reshape(), then we need an intermediate bitmap to read back the // frame buffer into. This seems to happen when CSS styles are // used to resize the Canvas. SkBitmap m_resizingBitmap; // In the case of OffscreenCanvas, we do not want to enable the // WebGLImageChromium flag, so we replace all the // RuntimeEnabledFeatures::webGLImageChromiumEnabled() call with // shouldUseChromiumImage() calls, and set m_chromiumImageUsage to // DisallowChromiumImage in the case of OffscreenCanvas. ChromiumImageUsage m_chromiumImageUsage; bool shouldUseChromiumImage(); }; } // namespace blink #endif // DrawingBuffer_h
37.157795
80
0.728524
[ "geometry", "vector" ]
9688b3ef1d332f79d3097deb7e4839c9dd4e11d8
5,055
h
C
source/common/stats/raw_stat_data.h
maximebedard/envoy
f0aedf04536f7e19a7053da2ebba4a25f642db2d
[ "Apache-2.0" ]
2
2019-04-30T02:10:12.000Z
2019-05-18T03:38:08.000Z
source/common/stats/raw_stat_data.h
dcj227/envoy
56f2f0d0161051a0b0eea1e1bad355a4668f1930
[ "Apache-2.0" ]
null
null
null
source/common/stats/raw_stat_data.h
dcj227/envoy
56f2f0d0161051a0b0eea1e1bad355a4668f1930
[ "Apache-2.0" ]
null
null
null
#pragma once #include <algorithm> #include <atomic> #include <chrono> #include <cstdint> #include <functional> #include <list> #include <memory> #include <regex> #include <string> #include <unordered_map> #include "envoy/stats/stat_data_allocator.h" #include "envoy/stats/stats_options.h" #include "envoy/stats/symbol_table.h" #include "common/common/assert.h" #include "common/common/block_memory_hash_set.h" #include "common/common/hash.h" #include "common/common/thread.h" #include "common/stats/stat_data_allocator_impl.h" #include "absl/strings/string_view.h" namespace Envoy { namespace Stats { /** * This structure is the backing memory for both CounterImpl and GaugeImpl. It is designed so that * it can be allocated from shared memory if needed. * * @note Due to name_ being variable size, sizeof(RawStatData) probably isn't useful. Use * RawStatData::structSize() or RawStatData::structSizeWithOptions() instead. */ struct RawStatData { /** * Due to the flexible-array-length of name_, c-style allocation * and initialization are necessary. */ RawStatData() = delete; ~RawStatData() = delete; /** * @return uint64_t the size of this struct, accounting for the length of * name_ and padding for alignment. */ static uint64_t structSize(uint64_t name_size); /** * Wrapper for structSize, taking a StatsOptions struct. Required by * BlockMemoryHashSet, which has the context to supply StatsOptions. */ static uint64_t structSizeWithOptions(const StatsOptions& stats_options); /** * Initializes this object to have the specified key, a refcount of 1, and all * other values zero. Required for the HeapRawStatDataAllocator, which does * not expect stat name truncation. We pass in the number of bytes allocated * in order to assert the copy is safe inline. * * @param key the key * @param stats_options the stats options */ void initialize(absl::string_view key, const StatsOptions& stats_options); /** * @return uint64_t a hash of the key. This is required by BlockMemoryHashSet. */ static uint64_t hash(absl::string_view key) { return HashUtil::xxHash64(key); } /** * @return true if object is in use. */ bool initialized() { return name_[0] != '\0'; } /** * @return absl::string_view the name as a string_view. */ absl::string_view key() const { return absl::string_view(name_); } /** * @return const char* the name. */ const char* name() const { return name_; } std::atomic<uint64_t> value_; std::atomic<uint64_t> pending_increment_; std::atomic<uint16_t> flags_; std::atomic<uint16_t> ref_count_; std::atomic<uint32_t> unused_; char name_[]; }; using RawStatDataSet = BlockMemoryHashSet<Stats::RawStatData>; template <class Stat> class RawStat : public Stat { public: RawStat(StatName stat_name, RawStatData& data, StatDataAllocatorImpl<RawStatData>& alloc, absl::string_view tag_extracted_name, const std::vector<Tag>& tags) : Stat(data, alloc, tag_extracted_name, tags), stat_name_storage_(stat_name, alloc.symbolTable()) {} ~RawStat() { stat_name_storage_.free(this->symbolTable()); } StatName statName() const override { return stat_name_storage_.statName(); } private: StatNameStorage stat_name_storage_; }; class RawStatDataAllocator : public StatDataAllocatorImpl<RawStatData> { public: RawStatDataAllocator(Thread::BasicLockable& mutex, RawStatDataSet& stats_set, const StatsOptions& options, SymbolTable& symbol_table) : StatDataAllocatorImpl(symbol_table), mutex_(mutex), stats_set_(stats_set), options_(options) {} ~RawStatDataAllocator(); virtual RawStatData* alloc(absl::string_view name); // Virtual only for mocking. void free(Stats::RawStatData& data) override; RawStatData* allocStatName(StatName stat_name) { return alloc(symbolTable().toString(stat_name)); } // StatDataAllocator bool requiresBoundedStatNameSize() const override { return true; } template <class Stat> std::shared_ptr<Stat> makeStat(StatName name, absl::string_view tag_extracted_name, const std::vector<Tag>& tags) { RawStatData* raw_stat_data = allocStatName(name); if (raw_stat_data == nullptr) { return nullptr; } return std::make_shared<RawStat<Stat>>(name, *raw_stat_data, *this, tag_extracted_name, tags); } CounterSharedPtr makeCounter(StatName name, absl::string_view tag_extracted_name, const std::vector<Tag>& tags) override { return makeStat<CounterImpl<RawStatData>>(name, tag_extracted_name, tags); } GaugeSharedPtr makeGauge(StatName name, absl::string_view tag_extracted_name, const std::vector<Tag>& tags) override { return makeStat<GaugeImpl<RawStatData>>(name, tag_extracted_name, tags); } private: Thread::BasicLockable& mutex_; RawStatDataSet& stats_set_ GUARDED_BY(mutex_); const StatsOptions& options_; }; } // namespace Stats } // namespace Envoy
32.197452
98
0.715529
[ "object", "vector" ]
96891313a1b07fa1ae85b0ce71188cce5cc3faae
3,179
c
C
app/src/main/c/bluez-5.60/mesh/mesh-io.c
IllusionMan1212/ShockPair
0ad1fbd7edfcbf51e4b677d10ab3e137efec0b88
[ "MIT" ]
1
2021-07-12T00:34:11.000Z
2021-07-12T00:34:11.000Z
app/src/main/c/bluez-5.60/mesh/mesh-io.c
IllusionMan1212/ShockPair
0ad1fbd7edfcbf51e4b677d10ab3e137efec0b88
[ "MIT" ]
null
null
null
app/src/main/c/bluez-5.60/mesh/mesh-io.c
IllusionMan1212/ShockPair
0ad1fbd7edfcbf51e4b677d10ab3e137efec0b88
[ "MIT" ]
null
null
null
// SPDX-License-Identifier: LGPL-2.1-or-later /* * * BlueZ - Bluetooth protocol stack for Linux * * Copyright (C) 2018 Intel Corporation. All rights reserved. * * */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <ell/ell.h> #include "lib/bluetooth.h" #include "mesh/mesh-defs.h" #include "mesh/mesh-io.h" #include "mesh/mesh-io-api.h" /* List of Mesh-IO Type headers */ #include "mesh/mesh-io-generic.h" #include "mesh/mesh-io-unit.h" /* List of Supported Mesh-IO Types */ static const struct mesh_io_table table[] = { {MESH_IO_TYPE_GENERIC, &mesh_io_generic}, {MESH_IO_TYPE_UNIT_TEST, &mesh_io_unit}, }; static struct l_queue *io_list; static bool match_by_io(const void *a, const void *b) { return a == b; } static bool match_by_type(const void *a, const void *b) { const struct mesh_io *io = a; const enum mesh_io_type type = L_PTR_TO_UINT(b); return io->type == type; } struct mesh_io *mesh_io_new(enum mesh_io_type type, void *opts, mesh_io_ready_func_t cb, void *user_data) { const struct mesh_io_api *api = NULL; struct mesh_io *io; uint16_t i; for (i = 0; i < L_ARRAY_SIZE(table); i++) { if (table[i].type == type) { api = table[i].api; break; } } io = l_queue_find(io_list, match_by_type, L_UINT_TO_PTR(type)); if (!api || !api->init || io) return NULL; io = l_new(struct mesh_io, 1); io->type = type; io->api = api; if (!api->init(io, opts, cb, user_data)) goto fail; if (!io_list) io_list = l_queue_new(); if (l_queue_push_head(io_list, io)) return io; fail: if (api->destroy) api->destroy(io); l_free(io); return NULL; } void mesh_io_destroy(struct mesh_io *io) { io = l_queue_remove_if(io_list, match_by_io, io); if (io && io->api && io->api->destroy) io->api->destroy(io); l_free(io); if (l_queue_isempty(io_list)) { l_queue_destroy(io_list, NULL); io_list = NULL; } } bool mesh_io_get_caps(struct mesh_io *io, struct mesh_io_caps *caps) { io = l_queue_find(io_list, match_by_io, io); if (io && io->api && io->api->caps) return io->api->caps(io, caps); return false; } bool mesh_io_register_recv_cb(struct mesh_io *io, const uint8_t *filter, uint8_t len, mesh_io_recv_func_t cb, void *user_data) { io = l_queue_find(io_list, match_by_io, io); if (io && io->api && io->api->reg) return io->api->reg(io, filter, len, cb, user_data); return false; } bool mesh_io_deregister_recv_cb(struct mesh_io *io, const uint8_t *filter, uint8_t len) { io = l_queue_find(io_list, match_by_io, io); if (io && io->api && io->api->dereg) return io->api->dereg(io, filter, len); return false; } bool mesh_io_send(struct mesh_io *io, struct mesh_io_send_info *info, const uint8_t *data, uint16_t len) { io = l_queue_find(io_list, match_by_io, io); if (!io) io = l_queue_peek_head(io_list); if (io && io->api && io->api->send) return io->api->send(io, info, data, len); return false; } bool mesh_io_send_cancel(struct mesh_io *io, const uint8_t *pattern, uint8_t len) { io = l_queue_find(io_list, match_by_io, io); if (io && io->api && io->api->cancel) return io->api->cancel(io, pattern, len); return false; }
19.745342
74
0.675055
[ "mesh" ]
968a0aba1c4e056db9b7ab85f317269e75566043
786
h
C
02_CoreRPG/Source/walkingcharacter.h
bugsbycarlin/SecretSalsa
b4b15e7ba14cdc2be9aad4d111e710ed0ec507ee
[ "MIT" ]
null
null
null
02_CoreRPG/Source/walkingcharacter.h
bugsbycarlin/SecretSalsa
b4b15e7ba14cdc2be9aad4d111e710ed0ec507ee
[ "MIT" ]
null
null
null
02_CoreRPG/Source/walkingcharacter.h
bugsbycarlin/SecretSalsa
b4b15e7ba14cdc2be9aad4d111e710ed0ec507ee
[ "MIT" ]
null
null
null
/* Secret Salsa Matthew Carlin Copyright 2019 */ #pragma once #include <deque> #include <map> #include <string> #include <vector> #include "honey.h" #include "character.h" using namespace Honey; using namespace std; class WalkingCharacter : public Character { public: WalkingCharacter(State* state); ~WalkingCharacter(); void walkBehavior(float ax, float ay); void followBehavior(int x, int y); void seekBehavior(int x, int y); void koBehavior(); void draw(); float vx; float vy; deque<position> position_history; const int history_size = 80; const float velocity_tolerance = 45; const float restitution = 0.85; // No longer const, set in constructor for now float max_velocity; float max_ax; float max_ay; float velocity_decay; };
16.723404
48
0.711196
[ "vector" ]
968af203cfcc36e2c2ff44c485c84b16e60900a3
5,870
h
C
onnxruntime/core/providers/mkldnn/mkldnn_common.h
hqucms/onnxruntime
6e4e76414639f50836a64546603c8957227857b0
[ "MIT" ]
2
2019-07-30T10:37:33.000Z
2021-01-05T21:12:29.000Z
onnxruntime/core/providers/mkldnn/mkldnn_common.h
hqucms/onnxruntime
6e4e76414639f50836a64546603c8957227857b0
[ "MIT" ]
8
2019-10-08T14:20:49.000Z
2021-04-19T16:56:52.000Z
onnxruntime/core/providers/mkldnn/mkldnn_common.h
hqucms/onnxruntime
6e4e76414639f50836a64546603c8957227857b0
[ "MIT" ]
4
2021-06-05T19:52:22.000Z
2021-11-30T13:58:13.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include "core/common/common.h" #include "mkldnn.hpp" #include <unordered_map> namespace onnxruntime { namespace mkl_dnn { template <typename T> static mkldnn::memory::data_type MklDnnType(); // Add more types here as needed. template <> mkldnn::memory::data_type MklDnnType<float>() { return mkldnn::memory::data_type::f32; } static mkldnn::engine& GetEngine() { static mkldnn::engine cpu_engine = mkldnn::engine(mkldnn::engine::cpu, 0); return cpu_engine; } static void AddDimsToKey(std::string& key, const mkldnn::memory::dims& dims) { key.append(1, '#'); for (size_t i = 0; i < dims.size(); i++) { key.append(std::to_string(dims[i])); key.append(1, '_'); } key.append(1, '#'); } class PrimitiveBase { public: virtual ~PrimitiveBase() = default; }; template <typename T> class PrimitivePool { public: PrimitivePool() = default; ~PrimitivePool() = default; void SetPrimitive(const std::string& key, std::unique_ptr<PrimitiveBase> primitive) { auto& map = PrimitivePool<T>::GetMap(); auto iter = map.find(key); // We should not find a primitive already using this key. ORT_ENFORCE(iter == map.end(), "duplicate key: " + key); map.insert(std::make_pair(key, std::move(primitive))); } PrimitiveBase* GetPrimitive(const std::string& key) { const auto& map = PrimitivePool<T>::GetMap(); auto iter = map.find(key); if (iter != map.end()) { return iter->second.get(); } else { return nullptr; } } private: // For thread safety, the map needs to be kept in thread local storage. static inline std::unordered_map<std::string, std::unique_ptr<PrimitiveBase>>& GetMap() { static thread_local std::unordered_map<std::string, std::unique_ptr<PrimitiveBase>> map; return map; } }; // Struct which encapsulates parameters for MKLDNN memory reorder primitive. struct MemoryReorderParams { const mkldnn::memory& src; const mkldnn::memory& dst; MemoryReorderParams(const mkldnn::memory& src, const mkldnn::memory& dst) : src(src), dst(dst) {} // Used as the key for MemoryReorder primitive reuse pool. std::string ToString() const { std::string key; key.reserve(64); key.append("reorder_"); const auto& src_desc = src.get_primitive_desc().desc().data; const auto& dst_desc = dst.get_primitive_desc().desc().data; mkldnn::memory::dims src_dims(src_desc.dims, &src_desc.dims[src_desc.ndims]); mkldnn::memory::dims dst_dims(dst_desc.dims, &dst_desc.dims[dst_desc.ndims]); key.append(std::to_string(src_desc.format)); key.append(1, '_'); key.append(std::to_string(dst_desc.data_type)); AddDimsToKey(key, src_dims); key.append(std::to_string(dst_desc.format)); key.append(1, '_'); key.append(std::to_string(dst_desc.data_type)); AddDimsToKey(key, dst_dims); return key; } }; // Encapsulates an MKLDNN memory reorder primitive. // these are needed to convert the source/weight/destination memory layout // to one that is identified by MKLDNN to be optimal for performance. class MemoryReorderPrimitive : public PrimitiveBase { public: explicit MemoryReorderPrimitive(const MemoryReorderParams& params) : cpu_engine_(GetEngine()) { Initialize(params); } ~MemoryReorderPrimitive() = default; std::shared_ptr<mkldnn::primitive> GetPrimitive() { return context_.primitive; } void SetMemory(const MemoryReorderParams& params) { context_.src_mem->set_data_handle(params.src.get_data_handle()); context_.dst_mem->set_data_handle(params.dst.get_data_handle()); } private: struct MemoryReorderContext { std::shared_ptr<mkldnn::memory> src_mem; std::shared_ptr<mkldnn::memory> dst_mem; std::shared_ptr<mkldnn::primitive> primitive; MemoryReorderContext() : src_mem(nullptr), dst_mem(nullptr), primitive(nullptr) { } } context_; mkldnn::engine& cpu_engine_; void Initialize(const MemoryReorderParams& params) { context_.src_mem = std::make_shared<mkldnn::memory>( mkldnn::memory({params.src.get_primitive_desc().desc(), cpu_engine_}, nullptr)); context_.dst_mem = std::make_shared<mkldnn::memory>( mkldnn::memory({params.dst.get_primitive_desc().desc(), cpu_engine_}, nullptr)); context_.primitive = std::make_shared<mkldnn::reorder>( mkldnn::reorder(*context_.src_mem, *context_.dst_mem)); } }; // Pool which allows for reuse of MKLDNN memory reorder primitives which are expensive to instantiate. // To address thread safety, the primitives are stored in a map on thread local storage. template <typename T> class MemoryReorderPrimitivePool : public PrimitivePool<T> { public: static MemoryReorderPrimitivePool& GetInstance() { static MemoryReorderPrimitivePool pool; return pool; } static MemoryReorderPrimitive* Get(const MemoryReorderParams& params) { MemoryReorderPrimitive* primitive = static_cast<MemoryReorderPrimitive*>( MemoryReorderPrimitivePool<T>::GetInstance().GetPrimitive(params.ToString())); if (primitive == nullptr) { auto reorder_primitive = std::make_unique<MemoryReorderPrimitive>(params); primitive = reorder_primitive.get(); MemoryReorderPrimitivePool<T>::GetInstance().SetPrimitive(params.ToString(), std::move(reorder_primitive)); } primitive->SetMemory(params); return primitive; } private: MemoryReorderPrimitivePool() = default; ~MemoryReorderPrimitivePool() = default; }; template <typename T> static void DoReorder(const MemoryReorderParams& params) { std::vector<mkldnn::primitive> net; net.push_back(*(MemoryReorderPrimitivePool<T>::Get(params)->GetPrimitive())); mkldnn::stream(mkldnn::stream::kind::eager).submit(net).wait(); } } // namespace mkl_dnn } // namespace onnxruntime
33.352273
113
0.713969
[ "vector" ]
96922fe5b04ca0e516e41e88066be502591f8fd2
622
h
C
3rdparty/meshlab-master/src/external/structuresynth-1.5/ssynth/StructureSynth/Model/RuleRef.h
HoEmpire/slambook2
96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4
[ "MIT" ]
4
2016-03-30T14:31:52.000Z
2019-02-02T05:01:32.000Z
graphics/meshlab/src/external/structuresynth-1.5/ssynth/StructureSynth/Model/RuleRef.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
graphics/meshlab/src/external/structuresynth-1.5/ssynth/StructureSynth/Model/RuleRef.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "Rule.h" namespace StructureSynth { namespace Model { /// A RuleRef holds a pointer to a rule. /// Its is a placeholder, since rule are parsed as symbolic references, /// and need to be resolved into actual pointers after the complete parsing of the script. class RuleRef { public: RuleRef(QString namedReference) : reference(namedReference) { rulePtr = 0; }; ~RuleRef() {}; Rule* rule() { return rulePtr; } QString getReference() const { return reference; } void setRef(Rule* rule) { rulePtr = rule; } private: Rule* rulePtr; QString reference; }; } }
20.733333
92
0.675241
[ "model" ]
969cd1b41a2a3b0da22c1c176976db21f0809d3e
1,405
h
C
include/math/mat4.h
ten3roberts/cuttle
b4b828c2fdace5e54c8f4806b32cc78b8d40cc85
[ "BSD-3-Clause" ]
2
2020-12-14T15:58:13.000Z
2021-12-29T13:20:47.000Z
include/math/mat4.h
ten3roberts/cuttle
b4b828c2fdace5e54c8f4806b32cc78b8d40cc85
[ "BSD-3-Clause" ]
1
2020-06-13T09:14:43.000Z
2020-06-13T09:14:43.000Z
include/math/mat4.h
ten3roberts/cuttle
b4b828c2fdace5e54c8f4806b32cc78b8d40cc85
[ "BSD-3-Clause" ]
null
null
null
#ifndef MAT4_H #define MAT4_H #include "vec.h" #include <stdint.h> // [row][col] typedef struct { float raw[4][4]; } mat4; // Returns a 4x4 matrix initialized with zero extern const mat4 mat4_zero; // Returns a 4x4 identity matrix extern const mat4 mat4_identity; // Returns a translation matrix mat4 mat4_translate(vec3 v); //Returns a scaling matrix mat4 mat4_scale(vec3 v); // Generates a perspective projection matrix mat4 mat4_perspective(float aspect, float fov, float near, float far); // Generates a orthographic projection matrix // Such that if width is window aspect and height is 1, a 2 units wide quad will cover the screen // Maps the coordinates to x : {-width, width} and y = {-height, height} mat4 mat4_ortho(float width, float height, float near, float far); mat4 mat4_mul(const mat4* a, const mat4* b); // Multiplies a scalar pairwise on the matrix mat4 mat4_scalar_mul(const mat4* a, float scalar); mat4 mat4_add(const mat4* a, const mat4* b); mat4 mat4_transpose(const mat4* a); float mat4_determinant(const mat4* a); mat4 mat4_inverse(const mat4* a); // Performs a matrix vector column multiplication vec4 mat4_transform_vec4(const mat4* m, vec4 v); // Performs a matrix vector column multiplication vec3 mat4_transform_vec3(const mat4* m, vec3 v); // Converts a matrix to a comma line separated float grid void mat4_string(mat4* a, char* buf, int precision); #endif
26.509434
97
0.753737
[ "vector" ]
969dc54ab7df310a06fd15787cb194de3ea536e4
13,090
c
C
source/blender/draw/modes/paint_texture_mode.c
sambler/myblender
241cc5e8469efc67320f0be942115dacca281096
[ "Naumen", "Condor-1.1", "MS-PL" ]
3
2016-10-01T22:48:11.000Z
2018-08-14T17:29:04.000Z
source/blender/draw/modes/paint_texture_mode.c
segfault87/blender
77c7440540626828b080444165a28887c255594e
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
source/blender/draw/modes/paint_texture_mode.c
segfault87/blender
77c7440540626828b080444165a28887c255594e
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright 2016, Blender Foundation. */ /** \file * \ingroup draw */ #include "DRW_engine.h" #include "DRW_render.h" #include "BKE_node.h" #include "BLI_string_utils.h" /* If builtin shaders are needed */ #include "GPU_shader.h" #include "GPU_texture.h" #include "draw_common.h" #include "draw_mode_engines.h" #include "DNA_mesh_types.h" #include "DEG_depsgraph_query.h" extern char datatoc_common_colormanagement_lib_glsl[]; extern char datatoc_common_globals_lib_glsl[]; extern char datatoc_common_view_lib_glsl[]; extern char datatoc_paint_texture_vert_glsl[]; extern char datatoc_paint_texture_frag_glsl[]; extern char datatoc_paint_wire_vert_glsl[]; extern char datatoc_paint_wire_frag_glsl[]; extern char datatoc_paint_face_vert_glsl[]; extern char datatoc_paint_face_selection_vert_glsl[]; extern char datatoc_gpu_shader_uniform_color_frag_glsl[]; /* *********** LISTS *********** */ /* All lists are per viewport specific datas. * They are all free when viewport changes engines * or is free itself. Use PAINT_TEXTURE_engine_init() to * initialize most of them and PAINT_TEXTURE_cache_init() * for PAINT_TEXTURE_PassList */ typedef struct PAINT_TEXTURE_PassList { /* Declare all passes here and init them in * PAINT_TEXTURE_cache_init(). * Only contains (DRWPass *) */ struct DRWPass *stencil_mask_overlay; struct DRWPass *wire_select_overlay; struct DRWPass *face_select_overlay; } PAINT_TEXTURE_PassList; typedef struct PAINT_TEXTURE_FramebufferList { /* Contains all framebuffer objects needed by this engine. * Only contains (GPUFrameBuffer *) */ struct GPUFrameBuffer *fb; } PAINT_TEXTURE_FramebufferList; typedef struct PAINT_TEXTURE_TextureList { /* Contains all framebuffer textures / utility textures * needed by this engine. Only viewport specific textures * (not per object). Only contains (GPUTexture *) */ struct GPUTexture *texture; } PAINT_TEXTURE_TextureList; typedef struct PAINT_TEXTURE_StorageList { /* Contains any other memory block that the engine needs. * Only directly MEM_(m/c)allocN'ed blocks because they are * free with MEM_freeN() when viewport is freed. * (not per object) */ struct CustomStruct *block; struct PAINT_TEXTURE_PrivateData *g_data; } PAINT_TEXTURE_StorageList; typedef struct PAINT_TEXTURE_Data { /* Struct returned by DRW_viewport_engine_data_ensure. * If you don't use one of these, just make it a (void *) */ // void *fbl; void *engine_type; /* Required */ PAINT_TEXTURE_FramebufferList *fbl; PAINT_TEXTURE_TextureList *txl; PAINT_TEXTURE_PassList *psl; PAINT_TEXTURE_StorageList *stl; } PAINT_TEXTURE_Data; typedef struct PAINT_TEXTURE_Shaders { /* Custom shaders : * Add sources to source/blender/draw/modes/shaders * init in PAINT_TEXTURE_engine_init(); * free in PAINT_TEXTURE_engine_free(); */ struct GPUShader *stencil_mask_overlay; struct GPUShader *wire_select_overlay; struct GPUShader *face_select_overlay; } PAINT_TEXTURE_Shaders; /* *********** STATIC *********** */ static struct { PAINT_TEXTURE_Shaders sh_data[GPU_SHADER_CFG_LEN]; } e_data = {{{NULL}}}; /* Engine data */ typedef struct PAINT_TEXTURE_PrivateData { /* This keeps the references of the shading groups for * easy access in PAINT_TEXTURE_cache_populate() */ DRWShadingGroup *shgroup_stencil_mask; /* face-mask */ DRWShadingGroup *lwire_select_shgrp; DRWShadingGroup *face_select_shgrp; DRWView *view_wires; } PAINT_TEXTURE_PrivateData; /* Transient data */ /* *********** FUNCTIONS *********** */ /* Init Textures, Framebuffers, Storage and Shaders. * It is called for every frames. */ static void PAINT_TEXTURE_engine_init(void *vedata) { PAINT_TEXTURE_StorageList *stl = ((PAINT_TEXTURE_Data *)vedata)->stl; const DRWContextState *draw_ctx = DRW_context_state_get(); PAINT_TEXTURE_Shaders *sh_data = &e_data.sh_data[draw_ctx->sh_cfg]; if (!sh_data->stencil_mask_overlay) { const GPUShaderConfigData *sh_cfg_data = &GPU_shader_cfg_data[draw_ctx->sh_cfg]; sh_data->stencil_mask_overlay = GPU_shader_create_from_arrays({ .vert = (const char *[]){sh_cfg_data->lib, datatoc_common_globals_lib_glsl, datatoc_common_view_lib_glsl, datatoc_paint_texture_vert_glsl, NULL}, .frag = (const char *[]){datatoc_common_colormanagement_lib_glsl, datatoc_paint_texture_frag_glsl, NULL}, .defs = (const char *[]){sh_cfg_data->def, NULL}, }); sh_data->wire_select_overlay = GPU_shader_create_from_arrays({ .vert = (const char *[]){sh_cfg_data->lib, datatoc_common_globals_lib_glsl, datatoc_common_view_lib_glsl, datatoc_paint_wire_vert_glsl, NULL}, .frag = (const char *[]){datatoc_paint_wire_frag_glsl, NULL}, .defs = (const char *[]){sh_cfg_data->def, "#define USE_SELECT\n", NULL}, }); sh_data->face_select_overlay = GPU_shader_create_from_arrays({ .vert = (const char *[]){sh_cfg_data->lib, datatoc_common_view_lib_glsl, datatoc_paint_face_selection_vert_glsl, NULL}, .frag = (const char *[]){datatoc_common_view_lib_glsl, datatoc_gpu_shader_uniform_color_frag_glsl, NULL}, .defs = (const char *[]){sh_cfg_data->def, NULL}, }); } if (!stl->g_data) { /* Alloc transient pointers */ stl->g_data = MEM_mallocN(sizeof(*stl->g_data), __func__); stl->g_data->shgroup_stencil_mask = NULL; } stl->g_data->view_wires = DRW_view_create_with_zoffset(draw_ctx->rv3d, 1.0f); } static DRWShadingGroup *create_texture_paint_stencil_mask_shading_group( PAINT_TEXTURE_PassList *psl, const DRWContextState *draw_ctx) { PAINT_TEXTURE_Shaders *sh_data = &e_data.sh_data[draw_ctx->sh_cfg]; Scene *scene = draw_ctx->scene; const ImagePaintSettings *imapaint = &scene->toolsettings->imapaint; DRWShadingGroup *grp = DRW_shgroup_create(sh_data->stencil_mask_overlay, psl->stencil_mask_overlay); DRW_shgroup_uniform_float(grp, "alpha", &draw_ctx->v3d->overlay.texture_paint_mode_opacity, 1); DRW_shgroup_uniform_block(grp, "globalsBlock", G_draw.block_ubo); const bool masking_inverted = (imapaint->flag & IMAGEPAINT_PROJECT_LAYER_STENCIL_INV) > 0; GPUTexture *stencil = GPU_texture_from_blender(imapaint->stencil, NULL, GL_TEXTURE_2D); DRW_shgroup_uniform_texture(grp, "maskingImage", stencil); DRW_shgroup_uniform_bool_copy( grp, "maskingImagePremultiplied", (imapaint->stencil->alpha_mode == IMA_ALPHA_PREMUL)); DRW_shgroup_uniform_vec3(grp, "maskingColor", imapaint->stencil_col, 1); DRW_shgroup_uniform_bool_copy(grp, "maskingInvertStencil", masking_inverted); return grp; } static bool PAINT_TEXTURE_stencil_mask_enabled(const ImagePaintSettings *imapaint) { return imapaint->flag & IMAGEPAINT_PROJECT_LAYER_STENCIL && imapaint->stencil != NULL; } /* Here init all passes and shading groups * Assume that all Passes are NULL */ static void PAINT_TEXTURE_cache_init(void *vedata) { PAINT_TEXTURE_PassList *psl = ((PAINT_TEXTURE_Data *)vedata)->psl; PAINT_TEXTURE_StorageList *stl = ((PAINT_TEXTURE_Data *)vedata)->stl; const DRWContextState *draw_ctx = DRW_context_state_get(); Scene *scene = draw_ctx->scene; const ImagePaintSettings *imapaint = &scene->toolsettings->imapaint; PAINT_TEXTURE_Shaders *sh_data = &e_data.sh_data[draw_ctx->sh_cfg]; /* Stencil Mask */ if (PAINT_TEXTURE_stencil_mask_enabled(imapaint)) { DRWState state = DRW_STATE_WRITE_COLOR | DRW_STATE_DEPTH_EQUAL | DRW_STATE_BLEND_ALPHA; psl->stencil_mask_overlay = DRW_pass_create("Stencil Mask Pass", state); stl->g_data->shgroup_stencil_mask = create_texture_paint_stencil_mask_shading_group(psl, draw_ctx); } /* Face Mask */ { DRWState state = DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL; DRWPass *pass = DRW_pass_create("Wire Mask Pass", state); DRWShadingGroup *shgrp = DRW_shgroup_create(sh_data->wire_select_overlay, pass); DRW_shgroup_uniform_block(shgrp, "globalsBlock", G_draw.block_ubo); if (draw_ctx->sh_cfg == GPU_SHADER_CFG_CLIPPED) { DRW_shgroup_state_enable(shgrp, DRW_STATE_CLIP_PLANES); } psl->wire_select_overlay = pass; stl->g_data->lwire_select_shgrp = shgrp; } { DRWState state = DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_BLEND_ALPHA; DRWPass *pass = DRW_pass_create("Face Mask Pass", state); DRWShadingGroup *shgrp = DRW_shgroup_create(sh_data->face_select_overlay, pass); static const float col[4] = {1.0f, 1.0f, 1.0f, 0.2f}; DRW_shgroup_uniform_vec4(shgrp, "color", col, 1); if (draw_ctx->sh_cfg == GPU_SHADER_CFG_CLIPPED) { DRW_shgroup_state_enable(shgrp, DRW_STATE_CLIP_PLANES); } psl->face_select_overlay = pass; stl->g_data->face_select_shgrp = shgrp; } } /* Add geometry to shadingGroups. Execute for each objects */ static void PAINT_TEXTURE_cache_populate(void *vedata, Object *ob) { PAINT_TEXTURE_PassList *psl = ((PAINT_TEXTURE_Data *)vedata)->psl; PAINT_TEXTURE_StorageList *stl = ((PAINT_TEXTURE_Data *)vedata)->stl; const DRWContextState *draw_ctx = DRW_context_state_get(); UNUSED_VARS(psl, stl); if ((ob->type == OB_MESH) && (draw_ctx->obact == ob)) { /* Get geometry cache */ const Mesh *me_orig = DEG_get_original_object(ob)->data; Scene *scene = draw_ctx->scene; const ImagePaintSettings *imapaint = &scene->toolsettings->imapaint; const bool use_face_sel = (me_orig->editflag & ME_EDIT_PAINT_FACE_SEL) != 0; const bool masking_enabled = imapaint->flag & IMAGEPAINT_PROJECT_LAYER_STENCIL && imapaint->stencil != NULL; if (masking_enabled) { if (stl->g_data->shgroup_stencil_mask) { struct GPUBatch *geom = DRW_cache_mesh_surface_texpaint_single_get(ob); DRW_shgroup_call(stl->g_data->shgroup_stencil_mask, geom, ob); } } /* Face Mask */ if (use_face_sel) { struct GPUBatch *geom; geom = DRW_cache_mesh_surface_edges_get(ob); DRW_shgroup_call(stl->g_data->lwire_select_shgrp, geom, ob); geom = DRW_cache_mesh_surface_get(ob); DRW_shgroup_call(stl->g_data->face_select_shgrp, geom, ob); } } } /* Draw time ! Control rendering pipeline from here */ static void PAINT_TEXTURE_draw_scene(void *vedata) { PAINT_TEXTURE_PassList *psl = ((PAINT_TEXTURE_Data *)vedata)->psl; PAINT_TEXTURE_StorageList *stl = ((PAINT_TEXTURE_Data *)vedata)->stl; if (psl->stencil_mask_overlay) { DRW_draw_pass(psl->stencil_mask_overlay); } DRW_draw_pass(psl->face_select_overlay); DRW_view_set_active(stl->g_data->view_wires); DRW_draw_pass(psl->wire_select_overlay); DRW_view_set_active(NULL); } /* Cleanup when destroying the engine. * This is not per viewport ! only when quitting blender. * Mostly used for freeing shaders */ static void PAINT_TEXTURE_engine_free(void) { for (int sh_data_index = 0; sh_data_index < ARRAY_SIZE(e_data.sh_data); sh_data_index++) { PAINT_TEXTURE_Shaders *sh_data = &e_data.sh_data[sh_data_index]; GPUShader **sh_data_as_array = (GPUShader **)sh_data; for (int i = 0; i < (sizeof(PAINT_TEXTURE_Shaders) / sizeof(GPUShader *)); i++) { DRW_SHADER_FREE_SAFE(sh_data_as_array[i]); } } } static const DrawEngineDataSize PAINT_TEXTURE_data_size = DRW_VIEWPORT_DATA_SIZE( PAINT_TEXTURE_Data); DrawEngineType draw_engine_paint_texture_type = { NULL, NULL, N_("PaintTextureMode"), &PAINT_TEXTURE_data_size, &PAINT_TEXTURE_engine_init, &PAINT_TEXTURE_engine_free, &PAINT_TEXTURE_cache_init, &PAINT_TEXTURE_cache_populate, NULL, NULL, /* draw_background but not needed by mode engines */ &PAINT_TEXTURE_draw_scene, NULL, NULL, };
36.977401
98
0.706875
[ "mesh", "geometry", "object" ]
969e5db5acdfccb2f38aed22a8f7c09b5fa726f1
6,128
h
C
graphics/qt3d/qt3d_v1/view.h
mission-systems-pty-ltd/snark
2bc8a20292ee3684d3a9897ba6fee43fed8d89ae
[ "BSD-3-Clause" ]
63
2015-01-14T14:38:02.000Z
2022-02-01T09:56:03.000Z
graphics/qt3d/qt3d_v1/view.h
NEU-LC/snark
db890f73f4c4bbe679405f3a607fd9ea373deb2c
[ "BSD-3-Clause" ]
39
2015-01-21T00:57:38.000Z
2020-04-22T04:22:35.000Z
graphics/qt3d/qt3d_v1/view.h
NEU-LC/snark
db890f73f4c4bbe679405f3a607fd9ea373deb2c
[ "BSD-3-Clause" ]
36
2015-01-15T04:17:14.000Z
2022-02-17T17:13:35.000Z
// This file is part of snark, a generic and flexible library for robotics research // Copyright (c) 2011 The University of Sydney // 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 Sydney nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE // GRANTED BY THIS LICENSE. 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. /// @author Cedric Wohlleber #ifndef SNARK_GRAPHICS_GL_VIEW_H_ #define SNARK_GRAPHICS_GL_VIEW_H_ #ifndef Q_MOC_RUN #include <boost/optional.hpp> #include <boost/thread.hpp> #endif #include <Eigen/Core> #include <Qt3D/qglview.h> #include <QMouseEvent> #ifndef Q_MOC_RUN #include <comma/visiting/traits.h> // quick and dirty #include "coordinates.h" #endif #include "../../traits.h" namespace snark { namespace graphics { namespace qt3d { class camera_options; /// base class for 3d viewers with mouse navigation class view : public QGLView { Q_OBJECT public: view( const QColor4ub& background_color , const camera_options& camera_options , boost::optional< QVector3D > scene_center = boost::optional< QVector3D >() , boost::optional< double > scene_radius = boost::optional< double >() ); virtual ~view() {} double scene_radius() const; private slots: void hide_coordinates() { m_show_coordinates = false; update(); } protected: void updateZFar(); void updateView( const QVector3D& min, const QVector3D& max ); void lookAtCenter(); void draw_coordinates( QGLPainter* painter ); void mousePressEvent( QMouseEvent *e ); void mouseReleaseEvent( QMouseEvent *e ); void mouseMoveEvent( QMouseEvent *e ); void wheelEvent( QWheelEvent *e ); QVector3D unproject( float x, float y, float depth ); boost::optional< QVector3D > getPoint( const QPoint& point2d ); void mouseDoubleClickEvent( QMouseEvent *e ); virtual void mouse_double_right_click_event( QMouseEvent *e ) {} const QColor4ub m_background_color; QVector3D m_sceneCenter; bool scene_center_fixed_; bool m_z_up; boost::optional< Eigen::Vector3d > m_offset; bool scale_near_plane; private: boost::optional< QPoint > m_startPan; boost::optional< QPoint > m_startRotate; double scene_radius_; bool scene_radius_fixed_; QVector3D m_revolve; boost::optional< coordinates > m_coordinates; bool m_show_coordinates; }; } } } // namespace snark { namespace graphics { namespace gt3d { namespace comma { namespace visiting { template <> struct traits< QGLCamera > { template < typename Key, class Visitor > static void visit( Key, QGLCamera& p, Visitor& v ) { bool b = p.adjustForAspectRatio(); v.apply( "adjust_for_aspect_ratio", b ); p.setAdjustForAspectRatio( b ); QVector3D w; w = p.center(); v.apply( "center", w ); p.setCenter( w ); w = p.eye(); v.apply( "eye", w ); p.setEye( w ); double d; d = p.eyeSeparation(); v.apply( "eye-separation", d ); p.setEyeSeparation( d ); d = p.farPlane(); v.apply( "far-plane", d ); p.setFarPlane( d ); d = p.fieldOfView(); v.apply( "field-of-view", d ); p.setFieldOfView( d ); QSizeF s; s = p.minViewSize(); v.apply( "min-view-size", s ); p.setMinViewSize( s ); w = p.motionAdjustment(); v.apply( "motion-adjustment", w ); p.setMotionAdjustment( w ); d = p.nearPlane(); v.apply( "near-plane", d ); p.setNearPlane( d ); int i; i = p.projectionType(); v.apply( "projection-type", i ); p.setProjectionType( static_cast< QGLCamera::ProjectionType >( i ) ); i = p.screenRotation(); v.apply( "screen-rotation", i ); p.setScreenRotation( i ); w = p.upVector(); v.apply( "up-vector", w ); p.setUpVector( w ); s = p.viewSize(); v.apply( "view-size", s ); p.setViewSize( s ); } template < typename Key, class Visitor > static void visit( Key, const QGLCamera& p, Visitor& v ) { v.apply( "adjust_for_aspect_ratio", p.adjustForAspectRatio() ); v.apply( "center", p.center() ); v.apply( "eye", p.eye() ); v.apply( "eye-separation", p.eyeSeparation() ); v.apply( "far-plane", p.farPlane() ); v.apply( "field-of-view", p.fieldOfView() ); v.apply( "min-view-size", p.minViewSize() ); v.apply( "motion-adjustment", p.motionAdjustment() ); v.apply( "near-plane", p.nearPlane() ); v.apply( "projection-type", static_cast< int >( p.projectionType() ) ); v.apply( "screen-rotation", p.screenRotation() ); v.apply( "up-vector", p.upVector() ); v.apply( "view-size", p.viewSize() ); } }; } } // namespace comma { namespace visiting { #endif /*SNARK_GRAPHICS_GL_VIEW_H_*/
40.582781
134
0.682115
[ "vector", "3d" ]
969eb5cd9c342af630b6a6d8c8887caeca111673
3,015
h
C
heekscad/src/OrientationModifier.h
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
heekscad/src/OrientationModifier.h
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
heekscad/src/OrientationModifier.h
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
#pragma once #include "stdafx.h" #include "../interface/ObjList.h" class COrientationModifier; class COrientationModifierParams { public: typedef enum { eNormalSpacing = 0 } eSpacing_t; eSpacing_t m_spacing; int m_number_of_rotations; // Number of quarter circle rotations. bool m_sketch_rotates_text; typedef enum { eLeftJustified = 0, // Valid for both open and closed sketches eCentreJustified, // Valid for open sketches only eRightJustified, // Valid for both open and closed sketches eTopJustified, // Valid only for closed sketches eBottomJustified // Valid only for closed sketches } eJustification_t; eJustification_t m_justification; void set_initial_values(); void write_values_to_config(); void GetProperties(COrientationModifier * parent, std::list<Property *> *list); void WriteXMLAttributes(TiXmlNode* pElem); void ReadParametersFromXMLElement(TiXmlElement* pElem); const wxString ConfigScope(void)const{return _T("OrientationModifier");} }; /** This class may be used to generate a transformation matrix at some point along the child elements. The first example of its use is to orient individual letters in a HText object along a line. This class does not re-orient anything itself. If is simply a container used to hold child path (graphics objects such as sketches). When asked to do so, it can return a transformation matrix (rotation and/or translation) for some point along the child curves. */ class COrientationModifier : public ObjList { public: COrientationModifierParams m_params; COrientationModifier() { m_params.set_initial_values(); } ~COrientationModifier() { } COrientationModifier & operator= ( const COrientationModifier & rhs ); COrientationModifier(const COrientationModifier & rhs ); // HeeksObj's virtual functions int GetType()const{return OrientationModifierType;} const wxChar* GetTypeString(void)const{return _T("OrientationModifier");} void glCommands(bool select, bool marked, bool no_color); bool OneOfAKind(){return false;} const wxBitmap &GetIcon(); void GetProperties(std::list<Property *> *list); HeeksObj *MakeACopy(void)const; void CopyFrom(const HeeksObj* object); void WriteXML(TiXmlNode *root); bool CanAddTo(HeeksObj* owner); bool CanAdd(HeeksObj* object); void GetTools(std::list<Tool*>* t_list, const wxPoint* p); void ReloadPointers(); static HeeksObj* ReadFromXMLElement(TiXmlElement* pElem); gp_Pnt & Transform(gp_Trsf existing_transformation, const double _distance, gp_Pnt & point, const float width ); bool SketchIsClosed(); void InitializeFromSketch(); private: typedef std::list<std::pair<TopoDS_Edge, double> > Edges_t; // NOTE: These three variables are relatively transient. They are only held here to reduce re-work // during a single rendering session. HeeksObj *m_last_child; Edges_t m_edges; double m_total_edge_length; }; // End COrientationModifier class definition.
30.765306
113
0.752902
[ "object", "transform" ]
96a078b2817f532b5e787e2f1f6267c6c44dd136
38,172
c
C
source/blender/editors/space_graph/graph_draw.c
1-MillionParanoidTterabytes/Blender-2.79b-blackened
e8d767324e69015aa66850d13bee7db1dc7d084b
[ "Unlicense" ]
2
2018-06-18T01:50:25.000Z
2018-06-18T01:50:32.000Z
source/blender/editors/space_graph/graph_draw.c
1-MillionParanoidTterabytes/Blender-2.79b-blackened
e8d767324e69015aa66850d13bee7db1dc7d084b
[ "Unlicense" ]
null
null
null
source/blender/editors/space_graph/graph_draw.c
1-MillionParanoidTterabytes/Blender-2.79b-blackened
e8d767324e69015aa66850d13bee7db1dc7d084b
[ "Unlicense" ]
null
null
null
/* * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) Blender Foundation * * Contributor(s): Joshua Leung (2009 Recode) * * ***** END GPL LICENSE BLOCK ***** */ /** \file blender/editors/space_graph/graph_draw.c * \ingroup spgraph */ #include <stdio.h> #include <math.h> #include <string.h> #include <float.h> #include "BLI_blenlib.h" #include "BLI_math.h" #include "BLI_utildefines.h" #include "DNA_anim_types.h" #include "DNA_screen_types.h" #include "DNA_space_types.h" #include "DNA_windowmanager_types.h" #include "DNA_userdef_types.h" #include "BKE_context.h" #include "BKE_curve.h" #include "BKE_fcurve.h" #include "BIF_gl.h" #include "BIF_glutil.h" #include "ED_anim_api.h" #include "graph_intern.h" #include "UI_interface.h" #include "UI_resources.h" #include "UI_view2d.h" /* *************************** */ /* Utility Drawing Defines */ /* determine the alpha value that should be used when * drawing components for some F-Curve (fcu) * - selected F-Curves should be more visible than partially visible ones */ static float fcurve_display_alpha(FCurve *fcu) { return (fcu->flag & FCURVE_SELECTED) ? 1.0f : U.fcu_inactive_alpha; } /* *************************** */ /* F-Curve Modifier Drawing */ /* Envelope -------------- */ /* TODO: draw a shaded poly showing the region of influence too!!! */ static void draw_fcurve_modifier_controls_envelope(FModifier *fcm, View2D *v2d) { FMod_Envelope *env = (FMod_Envelope *)fcm->data; FCM_EnvelopeData *fed; const float fac = 0.05f * BLI_rctf_size_x(&v2d->cur); int i; /* draw two black lines showing the standard reference levels */ glColor3f(0.0f, 0.0f, 0.0f); glLineWidth(1); setlinestyle(5); glBegin(GL_LINES); glVertex2f(v2d->cur.xmin, env->midval + env->min); glVertex2f(v2d->cur.xmax, env->midval + env->min); glVertex2f(v2d->cur.xmin, env->midval + env->max); glVertex2f(v2d->cur.xmax, env->midval + env->max); glEnd(); setlinestyle(0); /* set size of vertices (non-adjustable for now) */ glPointSize(2.0f); /* for now, point color is fixed, and is white */ glColor3f(1.0f, 1.0f, 1.0f); glBegin(GL_POINTS); for (i = 0, fed = env->data; i < env->totvert; i++, fed++) { /* only draw if visible * - min/max here are fixed, not relative */ if (IN_RANGE(fed->time, (v2d->cur.xmin - fac), (v2d->cur.xmax + fac))) { glVertex2f(fed->time, fed->min); glVertex2f(fed->time, fed->max); } } glEnd(); } /* *************************** */ /* F-Curve Drawing */ /* Points ---------------- */ /* helper func - draw keyframe vertices only for an F-Curve */ static void draw_fcurve_vertices_keyframes(FCurve *fcu, SpaceIpo *UNUSED(sipo), View2D *v2d, short edit, short sel) { BezTriple *bezt = fcu->bezt; const float fac = 0.05f * BLI_rctf_size_x(&v2d->cur); int i; glBegin(GL_POINTS); for (i = 0; i < fcu->totvert; i++, bezt++) { /* as an optimization step, only draw those in view * - we apply a correction factor to ensure that points don't pop in/out due to slight twitches of view size */ if (IN_RANGE(bezt->vec[1][0], (v2d->cur.xmin - fac), (v2d->cur.xmax + fac))) { if (edit) { /* 'Keyframe' vertex only, as handle lines and handles have already been drawn * - only draw those with correct selection state for the current drawing color * - */ if ((bezt->f2 & SELECT) == sel) glVertex3fv(bezt->vec[1]); } else { /* no check for selection here, as curve is not editable... */ /* XXX perhaps we don't want to even draw points? maybe add an option for that later */ glVertex3fv(bezt->vec[1]); } } } glEnd(); } /* helper func - draw handle vertex for an F-Curve as a round unfilled circle * NOTE: the caller MUST HAVE GL_LINE_SMOOTH & GL_BLEND ENABLED, otherwise, the controls don't * have a consistent appearance (due to off-pixel alignments)... */ static void draw_fcurve_handle_control(float x, float y, float xscale, float yscale, float hsize) { static GLuint displist = 0; /* initialize round circle shape */ if (displist == 0) { GLUquadricObj *qobj; displist = glGenLists(1); glNewList(displist, GL_COMPILE); qobj = gluNewQuadric(); gluQuadricDrawStyle(qobj, GLU_SILHOUETTE); gluDisk(qobj, 0, 0.7, 8, 1); gluDeleteQuadric(qobj); glEndList(); } /* adjust view transform before starting */ glTranslatef(x, y, 0.0f); glScalef(1.0f / xscale * hsize, 1.0f / yscale * hsize, 1.0f); /* draw! */ glCallList(displist); /* restore view transform */ glScalef(xscale / hsize, yscale / hsize, 1.0); glTranslatef(-x, -y, 0.0f); } /* helper func - draw handle vertices only for an F-Curve (if it is not protected) */ static void draw_fcurve_vertices_handles(FCurve *fcu, SpaceIpo *sipo, View2D *v2d, short sel, short sel_handle_only, float units_scale) { BezTriple *bezt = fcu->bezt; BezTriple *prevbezt = NULL; float hsize, xscale, yscale; int i; /* get view settings */ hsize = UI_GetThemeValuef(TH_HANDLE_VERTEX_SIZE) * U.pixelsize; UI_view2d_scale_get(v2d, &xscale, &yscale); /* Compensate OGL scale sued for unit mapping, so circle will be circle, not ellipse */ yscale *= units_scale; /* set handle color */ if (sel) UI_ThemeColor(TH_HANDLE_VERTEX_SELECT); else UI_ThemeColor(TH_HANDLE_VERTEX); /* anti-aliased lines for more consistent appearance */ if ((sipo->flag & SIPO_BEAUTYDRAW_OFF) == 0) glEnable(GL_LINE_SMOOTH); glEnable(GL_BLEND); for (i = 0; i < fcu->totvert; i++, prevbezt = bezt, bezt++) { /* Draw the editmode handles for a bezier curve (others don't have handles) * if their selection status matches the selection status we're drawing for * - first handle only if previous beztriple was bezier-mode * - second handle only if current beztriple is bezier-mode * * Also, need to take into account whether the keyframe was selected * if a Graph Editor option to only show handles of selected keys is on. */ if (!sel_handle_only || BEZT_ISSEL_ANY(bezt)) { if ((!prevbezt && (bezt->ipo == BEZT_IPO_BEZ)) || (prevbezt && (prevbezt->ipo == BEZT_IPO_BEZ))) { if ((bezt->f1 & SELECT) == sel) /* && v2d->cur.xmin < bezt->vec[0][0] < v2d->cur.xmax)*/ draw_fcurve_handle_control(bezt->vec[0][0], bezt->vec[0][1], xscale, yscale, hsize); } if (bezt->ipo == BEZT_IPO_BEZ) { if ((bezt->f3 & SELECT) == sel) /* && v2d->cur.xmin < bezt->vec[2][0] < v2d->cur.xmax)*/ draw_fcurve_handle_control(bezt->vec[2][0], bezt->vec[2][1], xscale, yscale, hsize); } } } if ((sipo->flag & SIPO_BEAUTYDRAW_OFF) == 0) glDisable(GL_LINE_SMOOTH); glDisable(GL_BLEND); } /* helper func - set color to draw F-Curve data with */ static void set_fcurve_vertex_color(FCurve *fcu, short sel) { /* Fade the 'intensity' of the vertices based on the selection of the curves too */ int alphaOffset = (int)((fcurve_display_alpha(fcu) - 1.0f) * 255); /* Set color of curve vertex based on state of curve (i.e. 'Edit' Mode) */ if ((fcu->flag & FCURVE_PROTECTED) == 0) { /* Curve's points ARE BEING edited */ if (sel) UI_ThemeColorShadeAlpha(TH_VERTEX_SELECT, 0, alphaOffset); else UI_ThemeColorShadeAlpha(TH_VERTEX, 0, alphaOffset); } else { /* Curve's points CANNOT BE edited */ if (sel) UI_ThemeColorShadeAlpha(TH_TEXT_HI, 0, alphaOffset); else UI_ThemeColorShadeAlpha(TH_TEXT, 0, alphaOffset); } } static void draw_fcurve_vertices(SpaceIpo *sipo, ARegion *ar, FCurve *fcu, short do_handles, short sel_handle_only, float units_scale) { View2D *v2d = &ar->v2d; /* only draw points if curve is visible * - draw unselected points before selected points as separate passes to minimize color-changing overhead * (XXX dunno if this is faster than drawing all in one pass though) * and also to make sure in the case of overlapping points that the selected is always visible * - draw handles before keyframes, so that keyframes will overlap handles (keyframes are more important for users) */ glPointSize(UI_GetThemeValuef(TH_VERTEX_SIZE)); /* draw the two handles first (if they're shown, the curve doesn't have just a single keyframe, and the curve is being edited) */ if (do_handles) { set_fcurve_vertex_color(fcu, 0); draw_fcurve_vertices_handles(fcu, sipo, v2d, 0, sel_handle_only, units_scale); set_fcurve_vertex_color(fcu, 1); draw_fcurve_vertices_handles(fcu, sipo, v2d, 1, sel_handle_only, units_scale); } /* draw keyframes over the handles */ set_fcurve_vertex_color(fcu, 0); draw_fcurve_vertices_keyframes(fcu, sipo, v2d, !(fcu->flag & FCURVE_PROTECTED), 0); set_fcurve_vertex_color(fcu, 1); draw_fcurve_vertices_keyframes(fcu, sipo, v2d, !(fcu->flag & FCURVE_PROTECTED), 1); } /* Handles ---------------- */ static bool draw_fcurve_handles_check(SpaceIpo *sipo, FCurve *fcu) { /* don't draw handle lines if handles are not to be shown */ if ( (sipo->flag & SIPO_NOHANDLES) || /* handles shouldn't be shown anywhere */ (fcu->flag & FCURVE_PROTECTED) || /* keyframes aren't editable */ #if 0 /* handles can still be selected and handle types set, better draw - campbell */ (fcu->flag & FCURVE_INT_VALUES) || /* editing the handles here will cause weird/incorrect interpolation issues */ #endif ((fcu->grp) && (fcu->grp->flag & AGRP_PROTECTED)) || /* group that curve belongs to is not editable */ (fcu->totvert <= 1) /* do not show handles if there is only 1 keyframe, otherwise they all clump together in an ugly ball */ ) { return 0; } else { return 1; } } /* draw lines for F-Curve handles only (this is only done in EditMode) * note: draw_fcurve_handles_check must be checked before running this. */ static void draw_fcurve_handles(SpaceIpo *sipo, FCurve *fcu) { int sel, b; /* a single call to GL_LINES here around these calls should be sufficient to still * get separate line segments, but which aren't wrapped with GL_LINE_STRIP every time we * want a single line */ glBegin(GL_LINES); /* slightly hacky, but we want to draw unselected points before selected ones * so that selected points are clearly visible */ for (sel = 0; sel < 2; sel++) { BezTriple *bezt = fcu->bezt, *prevbezt = NULL; int basecol = (sel) ? TH_HANDLE_SEL_FREE : TH_HANDLE_FREE; const float *fp; unsigned char col[4]; for (b = 0; b < fcu->totvert; b++, prevbezt = bezt, bezt++) { /* if only selected keyframes can get their handles shown, * check that keyframe is selected */ if (sipo->flag & SIPO_SELVHANDLESONLY) { if (BEZT_ISSEL_ANY(bezt) == 0) continue; } /* draw handle with appropriate set of colors if selection is ok */ if ((bezt->f2 & SELECT) == sel) { fp = bezt->vec[0]; /* only draw first handle if previous segment had handles */ if ((!prevbezt && (bezt->ipo == BEZT_IPO_BEZ)) || (prevbezt && (prevbezt->ipo == BEZT_IPO_BEZ))) { UI_GetThemeColor3ubv(basecol + bezt->h1, col); col[3] = fcurve_display_alpha(fcu) * 255; glColor4ubv((GLubyte *)col); glVertex2fv(fp); glVertex2fv(fp + 3); } /* only draw second handle if this segment is bezier */ if (bezt->ipo == BEZT_IPO_BEZ) { UI_GetThemeColor3ubv(basecol + bezt->h2, col); col[3] = fcurve_display_alpha(fcu) * 255; glColor4ubv((GLubyte *)col); glVertex2fv(fp + 3); glVertex2fv(fp + 6); } } else { /* only draw first handle if previous segment was had handles, and selection is ok */ if (((bezt->f1 & SELECT) == sel) && ((!prevbezt && (bezt->ipo == BEZT_IPO_BEZ)) || (prevbezt && (prevbezt->ipo == BEZT_IPO_BEZ)))) { fp = bezt->vec[0]; UI_GetThemeColor3ubv(basecol + bezt->h1, col); col[3] = fcurve_display_alpha(fcu) * 255; glColor4ubv((GLubyte *)col); glVertex2fv(fp); glVertex2fv(fp + 3); } /* only draw second handle if this segment is bezier, and selection is ok */ if (((bezt->f3 & SELECT) == sel) && (bezt->ipo == BEZT_IPO_BEZ)) { fp = bezt->vec[1]; UI_GetThemeColor3ubv(basecol + bezt->h2, col); col[3] = fcurve_display_alpha(fcu) * 255; glColor4ubv((GLubyte *)col); glVertex2fv(fp); glVertex2fv(fp + 3); } } } } glEnd(); /* GL_LINES */ } /* Samples ---------------- */ /* helper func - draw sample-range marker for an F-Curve as a cross * NOTE: the caller MUST HAVE GL_LINE_SMOOTH & GL_BLEND ENABLED, otherwise, the controls don't * have a consistent appearance (due to off-pixel alignments)... */ static void draw_fcurve_sample_control(float x, float y, float xscale, float yscale, float hsize) { static GLuint displist = 0; /* initialize X shape */ if (displist == 0) { displist = glGenLists(1); glNewList(displist, GL_COMPILE); glBegin(GL_LINES); glVertex2f(-0.7f, -0.7f); glVertex2f(+0.7f, +0.7f); glVertex2f(-0.7f, +0.7f); glVertex2f(+0.7f, -0.7f); glEnd(); /* GL_LINES */ glEndList(); } /* adjust view transform before starting */ glTranslatef(x, y, 0.0f); glScalef(1.0f / xscale * hsize, 1.0f / yscale * hsize, 1.0f); /* draw! */ glCallList(displist); /* restore view transform */ glScalef(xscale / hsize, yscale / hsize, 1.0); glTranslatef(-x, -y, 0.0f); } /* helper func - draw keyframe vertices only for an F-Curve */ static void draw_fcurve_samples(SpaceIpo *sipo, ARegion *ar, FCurve *fcu) { FPoint *first, *last; float hsize, xscale, yscale; /* get view settings */ hsize = UI_GetThemeValuef(TH_VERTEX_SIZE); UI_view2d_scale_get(&ar->v2d, &xscale, &yscale); /* set vertex color */ if (fcu->flag & (FCURVE_ACTIVE | FCURVE_SELECTED)) UI_ThemeColor(TH_TEXT_HI); else UI_ThemeColor(TH_TEXT); /* get verts */ first = fcu->fpt; last = (first) ? (first + (fcu->totvert - 1)) : (NULL); /* draw */ if (first && last) { /* anti-aliased lines for more consistent appearance */ if ((sipo->flag & SIPO_BEAUTYDRAW_OFF) == 0) glEnable(GL_LINE_SMOOTH); glEnable(GL_BLEND); draw_fcurve_sample_control(first->vec[0], first->vec[1], xscale, yscale, hsize); draw_fcurve_sample_control(last->vec[0], last->vec[1], xscale, yscale, hsize); glDisable(GL_BLEND); if ((sipo->flag & SIPO_BEAUTYDRAW_OFF) == 0) glDisable(GL_LINE_SMOOTH); } } /* Curve ---------------- */ /* helper func - just draw the F-Curve by sampling the visible region (for drawing curves with modifiers) */ static void draw_fcurve_curve(bAnimContext *ac, ID *id, FCurve *fcu, View2D *v2d, View2DGrid *grid) { SpaceIpo *sipo = (SpaceIpo *)ac->sl; ChannelDriver *driver; float samplefreq; float stime, etime; float unitFac, offset; float dx, dy; short mapping_flag = ANIM_get_normalization_flags(ac); int i, n; /* when opening a blend file on a different sized screen or while dragging the toolbar this can happen * best just bail out in this case */ UI_view2d_grid_size(grid, &dx, &dy); if (dx <= 0.0f) return; /* disable any drivers temporarily */ driver = fcu->driver; fcu->driver = NULL; /* compute unit correction factor */ unitFac = ANIM_unit_mapping_get_factor(ac->scene, id, fcu, mapping_flag, &offset); /* Note about sampling frequency: * Ideally, this is chosen such that we have 1-2 pixels = 1 segment * which means that our curves can be as smooth as possible. However, * this does mean that curves may not be fully accurate (i.e. if they have * sudden spikes which happen at the sampling point, we may have problems). * Also, this may introduce lower performance on less densely detailed curves, * though it is impossible to predict this from the modifiers! * * If the automatically determined sampling frequency is likely to cause an infinite * loop (i.e. too close to 0), then clamp it to a determined "safe" value. The value * chosen here is just the coarsest value which still looks reasonable... */ /* grid->dx represents the number of 'frames' between gridlines, but we divide by U.v2d_min_gridsize to get pixels-steps */ /* TODO: perhaps we should have 1.0 frames as upper limit so that curves don't get too distorted? */ samplefreq = dx / (U.v2d_min_gridsize * U.pixelsize); if (sipo->flag & SIPO_BEAUTYDRAW_OFF) { /* Low Precision = coarse lower-bound clamping * * Although the "Beauty Draw" flag was originally for AA'd * line drawing, the sampling rate here has a much greater * impact on performance (e.g. for T40372)! * * This one still amounts to 10 sample-frames for each 1-frame interval * which should be quite a decent approximation in many situations. */ if (samplefreq < 0.1f) samplefreq = 0.1f; } else { /* "Higher Precision" but slower - especially on larger windows (e.g. T40372) */ if (samplefreq < 0.00001f) samplefreq = 0.00001f; } /* the start/end times are simply the horizontal extents of the 'cur' rect */ stime = v2d->cur.xmin; etime = v2d->cur.xmax + samplefreq; /* + samplefreq here so that last item gets included... */ /* at each sampling interval, add a new vertex * - apply the unit correction factor to the calculated values so that * the displayed values appear correctly in the viewport */ glBegin(GL_LINE_STRIP); n = (etime - stime) / samplefreq + 0.5f; for (i = 0; i <= n; i++) { float ctime = stime + i * samplefreq; glVertex2f(ctime, (evaluate_fcurve(fcu, ctime) + offset) * unitFac); } glEnd(); /* restore driver */ fcu->driver = driver; } /* helper func - draw a samples-based F-Curve */ static void draw_fcurve_curve_samples(bAnimContext *ac, ID *id, FCurve *fcu, View2D *v2d) { FPoint *prevfpt = fcu->fpt; FPoint *fpt = prevfpt + 1; float fac, v[2]; int b = fcu->totvert - 1; float unit_scale, offset; short mapping_flag = ANIM_get_normalization_flags(ac); /* apply unit mapping */ glPushMatrix(); unit_scale = ANIM_unit_mapping_get_factor(ac->scene, id, fcu, mapping_flag, &offset); glScalef(1.0f, unit_scale, 1.0f); glTranslatef(0.0f, offset, 0.0f); glBegin(GL_LINE_STRIP); /* extrapolate to left? - left-side of view comes before first keyframe? */ if (prevfpt->vec[0] > v2d->cur.xmin) { v[0] = v2d->cur.xmin; /* y-value depends on the interpolation */ if ((fcu->extend == FCURVE_EXTRAPOLATE_CONSTANT) || (fcu->flag & FCURVE_INT_VALUES) || (fcu->totvert == 1)) { /* just extend across the first keyframe's value */ v[1] = prevfpt->vec[1]; } else { /* extrapolate linear doesn't use the handle, use the next points center instead */ fac = (prevfpt->vec[0] - fpt->vec[0]) / (prevfpt->vec[0] - v[0]); if (fac) fac = 1.0f / fac; v[1] = prevfpt->vec[1] - fac * (prevfpt->vec[1] - fpt->vec[1]); } glVertex2fv(v); } /* if only one sample, add it now */ if (fcu->totvert == 1) glVertex2fv(prevfpt->vec); /* loop over samples, drawing segments */ /* draw curve between first and last keyframe (if there are enough to do so) */ while (b--) { /* Linear interpolation: just add one point (which should add a new line segment) */ glVertex2fv(prevfpt->vec); /* get next pointers */ prevfpt = fpt; fpt++; /* last point? */ if (b == 0) glVertex2fv(prevfpt->vec); } /* extrapolate to right? (see code for left-extrapolation above too) */ if (prevfpt->vec[0] < v2d->cur.xmax) { v[0] = v2d->cur.xmax; /* y-value depends on the interpolation */ if ((fcu->extend == FCURVE_EXTRAPOLATE_CONSTANT) || (fcu->flag & FCURVE_INT_VALUES) || (fcu->totvert == 1)) { /* based on last keyframe's value */ v[1] = prevfpt->vec[1]; } else { /* extrapolate linear doesn't use the handle, use the previous points center instead */ fpt = prevfpt - 1; fac = (prevfpt->vec[0] - fpt->vec[0]) / (prevfpt->vec[0] - v[0]); if (fac) fac = 1.0f / fac; v[1] = prevfpt->vec[1] - fac * (prevfpt->vec[1] - fpt->vec[1]); } glVertex2fv(v); } glEnd(); glPopMatrix(); } /* helper func - check if the F-Curve only contains easily drawable segments * (i.e. no easing equation interpolations) */ static bool fcurve_can_use_simple_bezt_drawing(FCurve *fcu) { BezTriple *bezt; int i; for (i = 0, bezt = fcu->bezt; i < fcu->totvert; i++, bezt++) { if (ELEM(bezt->ipo, BEZT_IPO_CONST, BEZT_IPO_LIN, BEZT_IPO_BEZ) == false) { return false; } } return true; } /* helper func - draw one repeat of an F-Curve (using Bezier curve approximations) */ static void draw_fcurve_curve_bezts(bAnimContext *ac, ID *id, FCurve *fcu, View2D *v2d) { BezTriple *prevbezt = fcu->bezt; BezTriple *bezt = prevbezt + 1; float v1[2], v2[2], v3[2], v4[2]; float *fp, data[120]; float fac = 0.0f; int b = fcu->totvert - 1; int resol; float unit_scale, offset; short mapping_flag = ANIM_get_normalization_flags(ac); /* apply unit mapping */ glPushMatrix(); unit_scale = ANIM_unit_mapping_get_factor(ac->scene, id, fcu, mapping_flag, &offset); glScalef(1.0f, unit_scale, 1.0f); glTranslatef(0.0f, offset, 0.0f); glBegin(GL_LINE_STRIP); /* extrapolate to left? */ if (prevbezt->vec[1][0] > v2d->cur.xmin) { /* left-side of view comes before first keyframe, so need to extend as not cyclic */ v1[0] = v2d->cur.xmin; /* y-value depends on the interpolation */ if ((fcu->extend == FCURVE_EXTRAPOLATE_CONSTANT) || (prevbezt->ipo == BEZT_IPO_CONST) || (fcu->totvert == 1)) { /* just extend across the first keyframe's value */ v1[1] = prevbezt->vec[1][1]; } else if (prevbezt->ipo == BEZT_IPO_LIN) { /* extrapolate linear dosnt use the handle, use the next points center instead */ fac = (prevbezt->vec[1][0] - bezt->vec[1][0]) / (prevbezt->vec[1][0] - v1[0]); if (fac) fac = 1.0f / fac; v1[1] = prevbezt->vec[1][1] - fac * (prevbezt->vec[1][1] - bezt->vec[1][1]); } else { /* based on angle of handle 1 (relative to keyframe) */ fac = (prevbezt->vec[0][0] - prevbezt->vec[1][0]) / (prevbezt->vec[1][0] - v1[0]); if (fac) fac = 1.0f / fac; v1[1] = prevbezt->vec[1][1] - fac * (prevbezt->vec[0][1] - prevbezt->vec[1][1]); } glVertex2fv(v1); } /* if only one keyframe, add it now */ if (fcu->totvert == 1) { v1[0] = prevbezt->vec[1][0]; v1[1] = prevbezt->vec[1][1]; glVertex2fv(v1); } /* draw curve between first and last keyframe (if there are enough to do so) */ /* TODO: optimize this to not have to calc stuff out of view too? */ while (b--) { if (prevbezt->ipo == BEZT_IPO_CONST) { /* Constant-Interpolation: draw segment between previous keyframe and next, but holding same value */ v1[0] = prevbezt->vec[1][0]; v1[1] = prevbezt->vec[1][1]; glVertex2fv(v1); v1[0] = bezt->vec[1][0]; v1[1] = prevbezt->vec[1][1]; glVertex2fv(v1); } else if (prevbezt->ipo == BEZT_IPO_LIN) { /* Linear interpolation: just add one point (which should add a new line segment) */ v1[0] = prevbezt->vec[1][0]; v1[1] = prevbezt->vec[1][1]; glVertex2fv(v1); } else if (prevbezt->ipo == BEZT_IPO_BEZ) { /* Bezier-Interpolation: draw curve as series of segments between keyframes * - resol determines number of points to sample in between keyframes */ /* resol depends on distance between points (not just horizontal) OR is a fixed high res */ /* TODO: view scale should factor into this someday too... */ if (fcu->driver) { resol = 32; } else { resol = (int)(5.0f * len_v2v2(bezt->vec[1], prevbezt->vec[1])); } if (resol < 2) { /* only draw one */ v1[0] = prevbezt->vec[1][0]; v1[1] = prevbezt->vec[1][1]; glVertex2fv(v1); } else { /* clamp resolution to max of 32 */ /* NOTE: higher values will crash */ if (resol > 32) resol = 32; v1[0] = prevbezt->vec[1][0]; v1[1] = prevbezt->vec[1][1]; v2[0] = prevbezt->vec[2][0]; v2[1] = prevbezt->vec[2][1]; v3[0] = bezt->vec[0][0]; v3[1] = bezt->vec[0][1]; v4[0] = bezt->vec[1][0]; v4[1] = bezt->vec[1][1]; correct_bezpart(v1, v2, v3, v4); BKE_curve_forward_diff_bezier(v1[0], v2[0], v3[0], v4[0], data, resol, sizeof(float) * 3); BKE_curve_forward_diff_bezier(v1[1], v2[1], v3[1], v4[1], data + 1, resol, sizeof(float) * 3); for (fp = data; resol; resol--, fp += 3) glVertex2fv(fp); } } /* get next pointers */ prevbezt = bezt; bezt++; /* last point? */ if (b == 0) { v1[0] = prevbezt->vec[1][0]; v1[1] = prevbezt->vec[1][1]; glVertex2fv(v1); } } /* extrapolate to right? (see code for left-extrapolation above too) */ if (prevbezt->vec[1][0] < v2d->cur.xmax) { v1[0] = v2d->cur.xmax; /* y-value depends on the interpolation */ if ((fcu->extend == FCURVE_EXTRAPOLATE_CONSTANT) || (fcu->flag & FCURVE_INT_VALUES) || (prevbezt->ipo == BEZT_IPO_CONST) || (fcu->totvert == 1)) { /* based on last keyframe's value */ v1[1] = prevbezt->vec[1][1]; } else if (prevbezt->ipo == BEZT_IPO_LIN) { /* extrapolate linear dosnt use the handle, use the previous points center instead */ bezt = prevbezt - 1; fac = (prevbezt->vec[1][0] - bezt->vec[1][0]) / (prevbezt->vec[1][0] - v1[0]); if (fac) fac = 1.0f / fac; v1[1] = prevbezt->vec[1][1] - fac * (prevbezt->vec[1][1] - bezt->vec[1][1]); } else { /* based on angle of handle 1 (relative to keyframe) */ fac = (prevbezt->vec[2][0] - prevbezt->vec[1][0]) / (prevbezt->vec[1][0] - v1[0]); if (fac) fac = 1.0f / fac; v1[1] = prevbezt->vec[1][1] - fac * (prevbezt->vec[2][1] - prevbezt->vec[1][1]); } glVertex2fv(v1); } glEnd(); glPopMatrix(); } /* Debugging -------------------------------- */ /* Draw indicators which show the value calculated from the driver, * and how this is mapped to the value that comes out of it. This * is handy for helping users better understand how to interpret * the graphs, and also facilitates debugging. */ static void graph_draw_driver_debug(bAnimContext *ac, ID *id, FCurve *fcu) { ChannelDriver *driver = fcu->driver; View2D *v2d = &ac->ar->v2d; short mapping_flag = ANIM_get_normalization_flags(ac); float offset; float unitfac = ANIM_unit_mapping_get_factor(ac->scene, id, fcu, mapping_flag, &offset); /* for now, only show when debugging driver... */ //if ((driver->flag & DRIVER_FLAG_SHOWDEBUG) == 0) // return; /* No curve to modify/visualize the result? * => We still want to show the 1-1 default... */ if ((fcu->totvert == 0) && BLI_listbase_is_empty(&fcu->modifiers)) { float t; /* draw with thin dotted lines in style of what curve would have been */ glColor3fv(fcu->color); setlinestyle(20); glLineWidth(2.0f); /* draw 1-1 line, stretching just past the screen limits * NOTE: we need to scale the y-values to be valid for the units */ glBegin(GL_LINES); { t = v2d->cur.xmin; glVertex2f(t, (t + offset) * unitfac); t = v2d->cur.xmax; glVertex2f(t, (t + offset) * unitfac); } glEnd(); /* cleanup line drawing */ setlinestyle(0); } /* draw driver only if actually functional */ if ((driver->flag & DRIVER_FLAG_INVALID) == 0) { /* grab "coordinates" for driver outputs */ float x = driver->curval; float y = fcu->curval * unitfac; /* only draw indicators if the point is in range*/ if (x >= v2d->cur.xmin) { float co[2]; /* draw dotted lines leading towards this point from both axes ....... */ glColor3f(0.9f, 0.9f, 0.9f); setlinestyle(5); glBegin(GL_LINES); { /* x-axis lookup */ co[0] = x; if (y >= v2d->cur.ymin) { co[1] = v2d->cur.ymin - 1.0f; glVertex2fv(co); co[1] = y; glVertex2fv(co); } /* y-axis lookup */ co[1] = y; co[0] = v2d->cur.xmin - 1.0f; glVertex2fv(co); co[0] = x; glVertex2fv(co); } glEnd(); setlinestyle(0); /* x marks the spot .................................................... */ /* -> outer frame */ glColor3f(0.9f, 0.9f, 0.9f); glPointSize(7.0); glBegin(GL_POINTS); glVertex2f(x, y); glEnd(); /* inner frame */ glColor3f(0.9f, 0.0f, 0.0f); glPointSize(3.0); glBegin(GL_POINTS); glVertex2f(x, y); glEnd(); } } } /* Public Curve-Drawing API ---------------- */ /* Draw the 'ghost' F-Curves (i.e. snapshots of the curve) * NOTE: unit mapping has already been applied to the values, so do not try and apply again */ void graph_draw_ghost_curves(bAnimContext *ac, SpaceIpo *sipo, ARegion *ar) { FCurve *fcu; /* draw with thick dotted lines */ setlinestyle(10); glLineWidth(3.0f); /* anti-aliased lines for less jagged appearance */ if ((sipo->flag & SIPO_BEAUTYDRAW_OFF) == 0) glEnable(GL_LINE_SMOOTH); glEnable(GL_BLEND); /* the ghost curves are simply sampled F-Curves stored in sipo->ghostCurves */ for (fcu = sipo->ghostCurves.first; fcu; fcu = fcu->next) { /* set whatever color the curve has set * - this is set by the function which creates these * - draw with a fixed opacity of 2 */ glColor4f(fcu->color[0], fcu->color[1], fcu->color[2], 0.5f); /* simply draw the stored samples */ draw_fcurve_curve_samples(ac, NULL, fcu, &ar->v2d); } /* restore settings */ setlinestyle(0); if ((sipo->flag & SIPO_BEAUTYDRAW_OFF) == 0) glDisable(GL_LINE_SMOOTH); glDisable(GL_BLEND); } /* This is called twice from space_graph.c -> graph_main_region_draw() * Unselected then selected F-Curves are drawn so that they do not occlude each other. */ void graph_draw_curves(bAnimContext *ac, SpaceIpo *sipo, ARegion *ar, View2DGrid *grid, short sel) { ListBase anim_data = {NULL, NULL}; bAnimListElem *ale; int filter; /* build list of curves to draw */ filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_CURVE_VISIBLE); filter |= ((sel) ? (ANIMFILTER_SEL) : (ANIMFILTER_UNSEL)); ANIM_animdata_filter(ac, &anim_data, filter, ac->data, ac->datatype); /* for each curve: * draw curve, then handle-lines, and finally vertices in this order so that * the data will be layered correctly */ for (ale = anim_data.first; ale; ale = ale->next) { FCurve *fcu = (FCurve *)ale->key_data; FModifier *fcm = find_active_fmodifier(&fcu->modifiers); AnimData *adt = ANIM_nla_mapping_get(ac, ale); /* map keyframes for drawing if scaled F-Curve */ if (adt) ANIM_nla_mapping_apply_fcurve(adt, ale->key_data, 0, 0); /* draw curve: * - curve line may be result of one or more destructive modifiers or just the raw data, * so we need to check which method should be used * - controls from active modifier take precedence over keyframes * (XXX! editing tools need to take this into account!) */ /* 1) draw curve line */ { /* set color/drawing style for curve itself */ if (BKE_fcurve_is_protected(fcu)) { /* protected curves (non editable) are drawn with dotted lines */ setlinestyle(2); } if (((fcu->grp) && (fcu->grp->flag & AGRP_MUTED)) || (fcu->flag & FCURVE_MUTED)) { /* muted curves are drawn in a grayish hue */ /* XXX should we have some variations? */ UI_ThemeColorShade(TH_HEADER, 50); } else { /* set whatever color the curve has set * - unselected curves draw less opaque to help distinguish the selected ones */ glColor4f(fcu->color[0], fcu->color[1], fcu->color[2], fcurve_display_alpha(fcu)); } /* draw active F-Curve thicker than the rest to make it stand out */ if (fcu->flag & FCURVE_ACTIVE) { glLineWidth(2.0); } else { glLineWidth(1.0); } /* anti-aliased lines for less jagged appearance */ if ((sipo->flag & SIPO_BEAUTYDRAW_OFF) == 0) glEnable(GL_LINE_SMOOTH); glEnable(GL_BLEND); /* draw F-Curve */ if ((fcu->modifiers.first) || (fcu->flag & FCURVE_INT_VALUES)) { /* draw a curve affected by modifiers or only allowed to have integer values * by sampling it at various small-intervals over the visible region */ draw_fcurve_curve(ac, ale->id, fcu, &ar->v2d, grid); } else if (((fcu->bezt) || (fcu->fpt)) && (fcu->totvert)) { /* just draw curve based on defined data (i.e. no modifiers) */ if (fcu->bezt) { if (fcurve_can_use_simple_bezt_drawing(fcu)) draw_fcurve_curve_bezts(ac, ale->id, fcu, &ar->v2d); else draw_fcurve_curve(ac, ale->id, fcu, &ar->v2d, grid); } else if (fcu->fpt) { draw_fcurve_curve_samples(ac, ale->id, fcu, &ar->v2d); } } /* restore settings */ setlinestyle(0); if ((sipo->flag & SIPO_BEAUTYDRAW_OFF) == 0) glDisable(GL_LINE_SMOOTH); glDisable(GL_BLEND); } /* 2) draw handles and vertices as appropriate based on active * - if the option to only show controls if the F-Curve is selected is enabled, we must obey this */ if (!(sipo->flag & SIPO_SELCUVERTSONLY) || (fcu->flag & FCURVE_SELECTED)) { if (fcurve_are_keyframes_usable(fcu) == 0) { /* only draw controls if this is the active modifier */ if ((fcu->flag & FCURVE_ACTIVE) && (fcm)) { switch (fcm->type) { case FMODIFIER_TYPE_ENVELOPE: /* envelope */ draw_fcurve_modifier_controls_envelope(fcm, &ar->v2d); break; } } } else if (((fcu->bezt) || (fcu->fpt)) && (fcu->totvert)) { short mapping_flag = ANIM_get_normalization_flags(ac); float offset; float unit_scale = ANIM_unit_mapping_get_factor(ac->scene, ale->id, fcu, mapping_flag, &offset); /* apply unit-scaling to all values via OpenGL */ glPushMatrix(); glScalef(1.0f, unit_scale, 1.0f); glTranslatef(0.0f, offset, 0.0f); /* set this once and for all - all handles and handle-verts should use the same thickness */ glLineWidth(1.0); if (fcu->bezt) { bool do_handles = draw_fcurve_handles_check(sipo, fcu); if (do_handles) { /* only draw handles/vertices on keyframes */ glEnable(GL_BLEND); draw_fcurve_handles(sipo, fcu); glDisable(GL_BLEND); } draw_fcurve_vertices(sipo, ar, fcu, do_handles, (sipo->flag & SIPO_SELVHANDLESONLY), unit_scale); } else { /* samples: only draw two indicators at either end as indicators */ draw_fcurve_samples(sipo, ar, fcu); } glPopMatrix(); } } /* 3) draw driver debugging stuff */ if ((ac->datatype == ANIMCONT_DRIVERS) && (fcu->flag & FCURVE_ACTIVE)) { graph_draw_driver_debug(ac, ale->id, fcu); } /* undo mapping of keyframes for drawing if scaled F-Curve */ if (adt) ANIM_nla_mapping_apply_fcurve(adt, ale->key_data, 1, 0); } /* free list of curves */ ANIM_animdata_freelist(&anim_data); } /* ************************************************************************* */ /* Channel List */ /* left hand part */ void graph_draw_channel_names(bContext *C, bAnimContext *ac, ARegion *ar) { ListBase anim_data = {NULL, NULL}; bAnimListElem *ale; int filter; View2D *v2d = &ar->v2d; float y = 0.0f, height; size_t items; int i = 0; /* build list of channels to draw */ filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_LIST_VISIBLE | ANIMFILTER_LIST_CHANNELS); items = ANIM_animdata_filter(ac, &anim_data, filter, ac->data, ac->datatype); /* Update max-extent of channels here (taking into account scrollers): * - this is done to allow the channel list to be scrollable, but must be done here * to avoid regenerating the list again and/or also because channels list is drawn first * - offset of ACHANNEL_HEIGHT*2 is added to the height of the channels, as first is for * start of list offset, and the second is as a correction for the scrollers. */ height = (float)((items * ACHANNEL_STEP(ac)) + (ACHANNEL_HEIGHT(ac) * 2)); UI_view2d_totRect_set(v2d, BLI_rcti_size_x(&ar->v2d.mask), height); /* loop through channels, and set up drawing depending on their type */ { /* first pass: just the standard GL-drawing for backdrop + text */ size_t channel_index = 0; y = (float)ACHANNEL_FIRST(ac); for (ale = anim_data.first, i = 0; ale; ale = ale->next, i++) { const float yminc = (float)(y - ACHANNEL_HEIGHT_HALF(ac)); const float ymaxc = (float)(y + ACHANNEL_HEIGHT_HALF(ac)); /* check if visible */ if (IN_RANGE(yminc, v2d->cur.ymin, v2d->cur.ymax) || IN_RANGE(ymaxc, v2d->cur.ymin, v2d->cur.ymax) ) { /* draw all channels using standard channel-drawing API */ ANIM_channel_draw(ac, ale, yminc, ymaxc, channel_index); } /* adjust y-position for next one */ y -= ACHANNEL_STEP(ac); channel_index++; } } { /* second pass: widgets */ uiBlock *block = UI_block_begin(C, ar, __func__, UI_EMBOSS); size_t channel_index = 0; y = (float)ACHANNEL_FIRST(ac); /* set blending again, as may not be set in previous step */ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); for (ale = anim_data.first, i = 0; ale; ale = ale->next, i++) { const float yminc = (float)(y - ACHANNEL_HEIGHT_HALF(ac)); const float ymaxc = (float)(y + ACHANNEL_HEIGHT_HALF(ac)); /* check if visible */ if (IN_RANGE(yminc, v2d->cur.ymin, v2d->cur.ymax) || IN_RANGE(ymaxc, v2d->cur.ymin, v2d->cur.ymax) ) { /* draw all channels using standard channel-drawing API */ ANIM_channel_draw_widgets(C, ac, ale, block, yminc, ymaxc, channel_index); } /* adjust y-position for next one */ y -= ACHANNEL_STEP(ac); channel_index++; } UI_block_end(C, block); UI_block_draw(C, block); glDisable(GL_BLEND); } /* free tempolary channels */ ANIM_animdata_freelist(&anim_data); }
31.943096
148
0.649036
[ "shape", "transform" ]