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
45654b1c28882c8355a2333dce2274bf032b82be
3,646
h
C
ThirdParty/maslib/src/common/mas/core/queue.h
siavashk/GMM-FEM
045d5d9c19ef152c5268c04c111bbb9252a8b809
[ "BSD-2-Clause" ]
37
2015-06-22T07:53:38.000Z
2022-03-08T07:23:48.000Z
ThirdParty/maslib/src/common/mas/core/queue.h
jtpils/GMM-FEM
045d5d9c19ef152c5268c04c111bbb9252a8b809
[ "BSD-2-Clause" ]
null
null
null
ThirdParty/maslib/src/common/mas/core/queue.h
jtpils/GMM-FEM
045d5d9c19ef152c5268c04c111bbb9252a8b809
[ "BSD-2-Clause" ]
13
2015-06-17T06:17:01.000Z
2020-10-09T00:38:58.000Z
#ifndef MAS_CORE_QUEUE_H_ #define MAS_CORE_QUEUE_H_ #include <vector> #include <stack> namespace mas { namespace queue { // Null callback template<typename ReferenceType, typename SizeType> struct null_callback { void operator()(ReferenceType v, const SizeType a, const SizeType b) {} }; /** * @brief A modified version of the priority queue, using mas::heap * to control heap operations. Allows specification of a "moved callback" * that is useful to track positions of elements in the queue. * * The move callback function must define the operation:<br> * <code> * move(Sequence::value_type& val, const Sequence::size_type a, const Sequence::size_type b); * </code> * which will be called after <code>val</code> is moved from location <code>a</code> to <code>b</code> * in the queue. The callback can either be an operator on a struct, or a general function handler (e.g. lambda in c++11). * */ template<typename ValueType, typename Sequence = std::vector<ValueType>, typename Compare = std::less<typename Sequence::value_type>, typename MoveCallback = mas::queue::null_callback<typename Sequence::reference, typename Sequence::size_type> > class priority_queue { public: typedef typename Sequence::value_type value_type; typedef typename Sequence::reference reference; typedef typename Sequence::const_reference const_reference; typedef typename Sequence::size_type size_type; typedef Sequence container_type; protected: // See queue::c for notes on these names. Sequence c; Compare comp; MoveCallback mov; public: bool empty() const; size_type size() const; const_reference top() const; void push(const value_type& x); void pop(); #if __cplusplus < 201103L explicit priority_queue(const Compare& x = Compare(), const Sequence& s = Sequence(), const MoveCallback& m = MoveCallback()); template<typename InputIterator> priority_queue(InputIterator first, InputIterator last, const Compare& x = Compare(), const Sequence& s = Sequence(), const MoveCallback& m = MoveCallback()); #else // duplicated due to possible ambiguity for default constructors explicit priority_queue(const Compare& x = Compare(), Sequence&& s = Sequence(), const MoveCallback& m = MoveCallback()); template<typename InputIterator> priority_queue(InputIterator first, InputIterator last, const Compare& x = Compare(), Sequence&& s = Sequence(), const MoveCallback& m = MoveCallback()); explicit priority_queue(const Compare& x, const Sequence& s, const MoveCallback& m = MoveCallback()); template<typename InputIterator> priority_queue(InputIterator first, InputIterator last, const Compare& x, const Sequence& s, const MoveCallback& m = MoveCallback()); void push(value_type&& x); template<typename ... _Args> void emplace(_Args&&... __args); void swap( priority_queue& __pq) noexcept(noexcept(swap(c, __pq.c)) && noexcept(swap(comp, __pq.comp)) && noexcept(swap(mov, __pq.mov))); #endif // __cplusplus // NON-STANDARD pop and retrieve top element in queue value_type pop_top(); void pop_top(reference top); value_type pop(size_type loc); const_reference peek() const; const_reference peek(size_type loc) const; reference get(); reference get(size_type loc); void update(); void update(size_type loc); bool is_valid() const; template<typename IterateCallback> void iterate(const IterateCallback& cb); }; }// mas } // queue #include "mas/core/queue.hpp" #endif /* MAS_CORE_QUEUE_HPP_ */
29.642276
123
0.708173
[ "vector" ]
4565d3407aa7a0634370985e21b6a64e07717898
8,490
h
C
include/atbus_endpoint.h
sidyhe/libatbus
cc3f5371375c0a24405d11795105c502a3bdfd3f
[ "BSL-1.0", "Apache-2.0", "MIT" ]
179
2016-06-22T06:30:43.000Z
2022-03-27T16:02:26.000Z
include/atbus_endpoint.h
sidyhe/libatbus
cc3f5371375c0a24405d11795105c502a3bdfd3f
[ "BSL-1.0", "Apache-2.0", "MIT" ]
11
2019-01-12T05:03:20.000Z
2022-03-21T04:09:46.000Z
include/atbus_endpoint.h
sidyhe/libatbus
cc3f5371375c0a24405d11795105c502a3bdfd3f
[ "BSL-1.0", "Apache-2.0", "MIT" ]
55
2016-06-06T07:27:26.000Z
2021-11-22T12:22:07.000Z
/** * atbus_endpoint.h * * Created on: 2015年11月20日 * Author: owent */ #pragma once #ifndef LIBATBUS_ENDPOINT_H # define LIBATBUS_ENDPOINT_H # pragma once # include <list> # include <memory> # include <vector> # ifdef __cpp_impl_three_way_comparison # include <compare> # endif # ifdef _MSC_VER # include <WinSock2.h> # endif # include <design_pattern/nomovable.h> # include <design_pattern/noncopyable.h> # include "detail/libatbus_channel_export.h" # include "detail/libatbus_config.h" # include "detail/libatbus_error.h" # include "atbus_connection.h" namespace atbus { namespace detail { template <typename TKey, typename TVal> struct auto_select_map { using type = ATBUS_ADVANCE_TYPE_MAP(TKey, TVal); }; template <typename TVal> struct auto_select_set { using type = ATBUS_ADVANCE_TYPE_SET(TVal); }; } // namespace detail class node; struct ATBUS_MACRO_API endpoint_subnet_conf { ATBUS_MACRO_BUSID_TYPE id_prefix; // subnet prefix uint32_t mask_bits; // suffix bits endpoint_subnet_conf(); endpoint_subnet_conf(ATBUS_MACRO_BUSID_TYPE prefix, uint32_t mask); }; class ATBUS_MACRO_API endpoint_subnet_range { public: endpoint_subnet_range(); endpoint_subnet_range(ATBUS_MACRO_BUSID_TYPE a, uint32_t b); bool operator==(const endpoint_subnet_range &other) const; # ifdef __cpp_impl_three_way_comparison std::strong_ordering operator<=>(const endpoint_subnet_range &other) const; # else bool operator<(const endpoint_subnet_range &other) const; bool operator<=(const endpoint_subnet_range &other) const; bool operator>(const endpoint_subnet_range &other) const; bool operator>=(const endpoint_subnet_range &other) const; bool operator!=(const endpoint_subnet_range &other) const; # endif inline ATBUS_MACRO_BUSID_TYPE get_id_prefix() const { return id_prefix_; } inline uint32_t get_mask_bits() const { return mask_bits_; } inline ATBUS_MACRO_BUSID_TYPE get_id_min() const { return min_id_; } inline ATBUS_MACRO_BUSID_TYPE get_id_max() const { return max_id_; } bool contain(const endpoint_subnet_range &other) const; bool contain(ATBUS_MACRO_BUSID_TYPE id) const; static bool contain(ATBUS_MACRO_BUSID_TYPE id_prefix, uint32_t mask_bits, ATBUS_MACRO_BUSID_TYPE id); static bool contain(const endpoint_subnet_conf &conf, ATBUS_MACRO_BUSID_TYPE id); static bool lower_bound_by_max_id(const endpoint_subnet_range &l, ATBUS_MACRO_BUSID_TYPE r); private: ATBUS_MACRO_BUSID_TYPE id_prefix_; // subnet prefix uint32_t mask_bits_; // suffix bits ATBUS_MACRO_BUSID_TYPE min_id_; ATBUS_MACRO_BUSID_TYPE max_id_; }; class endpoint final : public util::design_pattern::noncopyable { public: using bus_id_t = ATBUS_MACRO_BUSID_TYPE; using ptr_t = std::shared_ptr<endpoint>; struct flag_t { enum type { RESETTING, /** 正在执行重置(防止递归死循环) **/ CONNECTION_SORTED, DESTRUCTING, /** 正在执行析构 **/ HAS_LISTEN_PORC, /** 是否有proc类的listen地址 **/ HAS_LISTEN_FD, /** 是否有fd类的listen地址 **/ MUTABLE_FLAGS, /** 可动态变化的属性其实边界 **/ HAS_PING_TIMER, /** 是否设置了ping定时器 **/ MAX }; }; using get_connection_fn_t = connection *(endpoint::*)(endpoint *ep) const; UTIL_DESIGN_PATTERN_NOCOPYABLE(endpoint) UTIL_DESIGN_PATTERN_NOMOVABLE(endpoint) private: endpoint(); public: /** * @brief 创建端点 */ static ATBUS_MACRO_API ptr_t create(node *owner, bus_id_t id, const std::vector<endpoint_subnet_conf> &subnets, int32_t pid, const std::string &hn); ATBUS_MACRO_API ~endpoint(); ATBUS_MACRO_API void reset(); ATBUS_MACRO_API bus_id_t get_id() const; ATBUS_MACRO_API const std::vector<endpoint_subnet_range> &get_subnets() const; ATBUS_MACRO_API int32_t get_pid() const; ATBUS_MACRO_API const std::string &get_hostname() const; ATBUS_MACRO_API const std::string &get_hash_code() const; ATBUS_MACRO_API void update_hash_code(const std::string &); ATBUS_MACRO_API bool is_child_node(bus_id_t id) const; static ATBUS_MACRO_API bus_id_t get_children_min_id(bus_id_t children_prefix, uint32_t mask); static ATBUS_MACRO_API bus_id_t get_children_max_id(bus_id_t children_prefix, uint32_t mask); static ATBUS_MACRO_API bool is_child_node(bus_id_t parent_id, bus_id_t parent_children_prefix, uint32_t parent_mask, bus_id_t checked_id); ATBUS_MACRO_API bool add_connection(connection *conn, bool force_data); ATBUS_MACRO_API bool remove_connection(connection *conn); /** * @brief 是否处于可用状态 * @note 可用状态是指同时存在正在运行的命令通道和数据通道 */ ATBUS_MACRO_API bool is_available() const; /** * @brief 获取flag * @param f flag的key * @return 返回f的值,如果f无效,返回false */ ATBUS_MACRO_API bool get_flag(flag_t::type f) const; /** * @brief 设置可变flag的值 * @param f flag的key,这个值必须大于等于flat_t::MUTABLE_FLAGS * @param v 值 * @return 0或错误码 * @see flat_t */ ATBUS_MACRO_API int set_flag(flag_t::type f, bool v); /** * @brief 获取所有flag * @return 整数表示的flags * @see flat_t */ ATBUS_MACRO_API uint32_t get_flags() const; /** * @breif 获取自身的资源holder */ ATBUS_MACRO_API ptr_t watch() const; ATBUS_MACRO_API const std::list<std::string> &get_listen() const; ATBUS_MACRO_API void add_listen(const std::string &addr); ATBUS_MACRO_API void add_ping_timer(); ATBUS_MACRO_API void clear_ping_timer(); private: static bool sort_connection_cmp_fn(const connection::ptr_t &left, const connection::ptr_t &right); public: ATBUS_MACRO_API connection *get_ctrl_connection(endpoint *ep) const; ATBUS_MACRO_API connection *get_data_connection(endpoint *ep) const; ATBUS_MACRO_API connection *get_data_connection(endpoint *ep, bool enable_fallback_ctrl) const; /** 增加错误计数 **/ ATBUS_MACRO_API size_t add_stat_fault(); /** 清空错误计数 **/ ATBUS_MACRO_API void clear_stat_fault(); ATBUS_MACRO_API void set_stat_ping(uint64_t p); ATBUS_MACRO_API uint64_t get_stat_ping() const; ATBUS_MACRO_API void set_stat_ping_delay(time_t pd, time_t pong_tm); ATBUS_MACRO_API time_t get_stat_ping_delay() const; ATBUS_MACRO_API time_t get_stat_last_pong() const; ATBUS_MACRO_API size_t get_stat_push_start_times() const; ATBUS_MACRO_API size_t get_stat_push_start_size() const; ATBUS_MACRO_API size_t get_stat_push_success_times() const; ATBUS_MACRO_API size_t get_stat_push_success_size() const; ATBUS_MACRO_API size_t get_stat_push_failed_times() const; ATBUS_MACRO_API size_t get_stat_push_failed_size() const; ATBUS_MACRO_API size_t get_stat_pull_times() const; ATBUS_MACRO_API size_t get_stat_pull_size() const; ATBUS_MACRO_API time_t get_stat_created_time_sec(); ATBUS_MACRO_API time_t get_stat_created_time_usec(); ATBUS_MACRO_API const node *get_owner() const; static ATBUS_MACRO_API void merge_subnets(std::vector<endpoint_subnet_range> &subnets); static ATBUS_MACRO_API std::vector<endpoint_subnet_range>::const_iterator search_subnet_for_id( const std::vector<endpoint_subnet_range> &subnets, bus_id_t id); static ATBUS_MACRO_API bool contain(const std::vector<endpoint_subnet_range> &parent_subnets, const std::vector<endpoint_subnet_range> &child_subnets); static ATBUS_MACRO_API bool contain(const std::vector<endpoint_subnet_range> &parent_subnets, const std::vector<endpoint_subnet_conf> &child_subnets); static ATBUS_MACRO_API bool contain(const std::vector<endpoint_subnet_range> &parent_subnets, bus_id_t id); static ATBUS_MACRO_API bool contain(const std::vector<endpoint_subnet_conf> &parent_subnets, bus_id_t id); private: bus_id_t id_; std::string hash_code_; std::vector<endpoint_subnet_range> subnets_; std::bitset<flag_t::MAX> flags_; std::string hostname_; int32_t pid_; // 这里不用智能指针是为了该值在上层对象(node)析构时仍然可用 node *owner_; timer_desc_ls<std::weak_ptr<endpoint> >::type::iterator ping_timer_; std::weak_ptr<endpoint> watcher_; std::list<std::string> listen_address_; connection::ptr_t ctrl_conn_; std::list<connection::ptr_t> data_conn_; // 统计数据 struct stat_t { size_t fault_count; // 错误容忍计数 uint64_t unfinished_ping; // 上一次未完成的ping的序号 time_t ping_delay; time_t last_pong_time; // 上一次接到PONG包时间 time_t created_time_sec; time_t created_time_usec; stat_t(); }; stat_t stat_; }; } // namespace atbus #endif /* LIBATBUS_ENDPOINT_H_ */
30.872727
118
0.745936
[ "vector" ]
4567a57674655e077071be3bd294eda090c0f179
52,635
h
C
src/VitaSound.h
MyLegGuy/libGeneralGood
09e7c8d35c11406e24519ee0eeaa59315544f1a6
[ "Zlib" ]
4
2017-10-27T16:25:12.000Z
2018-08-25T15:53:04.000Z
src/VitaSound.h
MyLegGuy/libGeneralGood
09e7c8d35c11406e24519ee0eeaa59315544f1a6
[ "Zlib" ]
null
null
null
src/VitaSound.h
MyLegGuy/libGeneralGood
09e7c8d35c11406e24519ee0eeaa59315544f1a6
[ "Zlib" ]
null
null
null
//zlib license (c) mylegguy // oldest to newest //https://pastebin.com/4R59NH12 //https://pastebin.com/raw/m9k41uD7 //https://pastebin.com/raw/SP4tpNga #if HEADER_MLGVITASOUND #warning reincluded #else #define HEADER_MLGVITASOUND #endif // If this is libGeneralGood #if PLATFORM #define INCLUDETESTCODE 0 #else #define INCLUDETESTCODE 1 #endif #define SNDPLAT_VITA 1 #define SNDPLAT_LINUX 2 #if __gnu_linux__ #define SNDPLATFORM SNDPLAT_LINUX #else #define SNDPLATFORM SNDPLAT_VITA #endif #include <stdint.h> #include <math.h> #include <stdlib.h> // memset and memcpy #include <string.h> #if SNDPLATFORM == SNDPLAT_VITA #include <psp2/ctrl.h> #include <psp2/audioout.h> #include <psp2/kernel/processmgr.h> #include <psp2/kernel/threadmgr.h> #include <vitasdk.h> #endif #include <ogg/ogg.h> #include <vorbis/codec.h> #include <vorbis/vorbisfile.h> #include <mpg123.h> #include <samplerate.h> #include "legarchive.h" #if INCLUDETESTCODE && SNDPLATFORM == SNDPLAT_VITA #include "debugScreen.h" #define printf psvDebugScreenPrintf #endif // Works best with small buffers // 65472 is SCE_AUDIO_MAX_LEN // 32000 is good // 19200 is probably good // 9600 // 4800 is godo for fadeout #define AUDIO_BUFFER_LENGTH 4800 // Best be even to avoid OV_EINVAL #define BIGBUFFERSCALE 1.30 // SRC_SINC_MEDIUM_QUALITY // SRC_SINC_FASTEST #define SAMPLERATECONVERSIONQUALITY SRC_SINC_FASTEST /* Format specific functions: _mlgsnd_getLengthInSamples mlgsnd_restartAudio mlgsnd_getNumChannels mlgsnd_getSampleRate _mlgsnd_disposeMusicMainStruct */ #define FILE_FORMAT_NONE 0 #define FILE_FORMAT_OGG 1 #define FILE_FORMAT_MP3 2 // Planned #define FILE_FORMAT_WAV 3 #define SHORT_SYNC_DELAY_MICRO 10000 #define STREAMING_BUFFERS 3 #define NAUDIO_QUITSTATUS_PLAYING 1 #define NAUDIO_QUITSTATUS_SHOULDQUIT 2 #define NAUDIO_QUITSTATUS_PAUSED 3 #define NAUDIO_QUITSTATUS_QUITTED 5 // I know "quitted" is wierd, but I don't want to make this constant sound like a command. #define NAUDIO_QUITSTATUS_PREPARING 6 // Getting audio ports and such ready #define NAUDIO_QUITSTATUS_FREED 7 // if value is >= STREAMSTATUS_DONTSTREAM the do not stream #define STREAMSTATUS_STREAMING 1 #define STREAMSTATUS_DONTSTREAM 2 #define STREAMSTATUS_MINISTREAM 3 // Streams until it reaches the end of the allocated buffers //#define STREAMSTATUS_DONESTREAMING 4 // Done with ministream #if SNDPLATFORM == SNDPLAT_LINUX #include <pthread.h> //#include <clock.h> // usleep #include <unistd.h> #define sceKernelDelayThread usleep #define SceCtrlData void* #define SCE_CTRL_SQUARE 1 #define SceUID pthread_t* #define SceSize int #define SceUInt unsigned int #define SceAudioOutMode signed int #define SCE_AUDIO_OUT_MODE_MONO 0 #define SCE_AUDIO_OUT_MODE_STEREO 0 #define SCE_AUDIO_OUT_PORT_TYPE_MAIN 0 #define SCE_AUDIO_VOLUME_FLAG_L_CH 0 #define SCE_AUDIO_VOLUME_FLAG_R_CH 0 #define SCE_AUDIO_OUT_MAX_VOL 500 int sceAudioOutOpenPort(int _a, int _b, int _c, int _d){ return 0; } int sceAudioOutSetConfig(int _a, int _b, int _c, int _d){ return 0; } void sceAudioOutReleasePort(int _a){} void sceAudioOutSetVolume(int _a, int _b, int _c[2]){} void sceKernelExitDeleteThread(int _a){pthread_exit(NULL);} char wasJustPressed(void* bla,int _passedValue){ return 0; } void sceKernelWaitThreadEnd(pthread_t* happy, int* _a, int* _b){ pthread_join(*happy,NULL); } void psvDebugScreenInit() {} void sceCtrlPeekBufferPositive() {}; int getTicks(){ struct timespec _myTime; clock_gettime(CLOCK_MONOTONIC, &_myTime); return _myTime.tv_nsec/1000000; } int _lastOutputTicks=0; int sceAudioOutOutput(int _a, void* _b){ int _newOutputTicks = getTicks(); if (_lastOutputTicks!=0){ //100 if (_newOutputTicks<_lastOutputTicks+100){ usleep(((_lastOutputTicks+100)-_newOutputTicks)*1000); } } return 0; } int mlgsnd_soundPlayingThread(SceSize args, void *argp); void* _soundThreadPthreadWrapper(void* _argument){ printf("before %p\n",_argument); mlgsnd_soundPlayingThread(1,_argument); return NULL; } //SceUID mySoundPlayingThreadID = sceKernelCreateThread("SOUNDPLAY", mlgsnd_soundPlayingThread, 0, 0x10000, 0, 0, NULL); //pthread_t* sceKernelCreateThread(){ // pthread_t* _returnThread = malloc(sizeof(pthread_t)); // pthread_create(_returnThread,NULL,_soundThreadPthreadWrapper,NULL); // return _returnThread; //} #endif typedef struct{ void* mainAudioStruct; // malloc'd and needs a free function void** audioBuffers; // malloc'd float* tempFloatSource; // Temp buffer to hold converted audio data float* tempFloatConverted; // malloc'd. This is the destination buffer for the converted audio data before it's copied back to the main buffer. SRC_DATA usualConverterData; SRC_STATE* personalConverter; // Needs a free function signed int nextBufferLoadOffset; unsigned int unscaledSamples; // Number of samples to load from the file and convert unsigned int scaledSamples; // Number of samples to play and size of destination buffer unsigned int numBuffers; // Number of audio buffers we can swap between. signed char fileFormat; // Tells you what the file format is, OGG, WAV, etc. SceUID playerThreadId; // Thread ID for the thread that's playing this sound. signed int audioPort; signed char shouldLoop; // bool signed int volume; // Current volume signed char myStreamStatus; // If we should stream or not signed char totalPlaying; // Non-streamed data can be played from multiple threads. signed char isFirstTime; signed char quitStatus; // 0 if should not quit, 1 if should quit, -1 if already quit signed char isFadingOut; unsigned int fadeoutPerSwap; // In Vita volume units signed int lastVolume; // Used to detect volume changes FILE* _internalFilePointer; // Do not mess with normally please }NathanAudio; int lastConverterError=0; signed char haveInitMpg123=0; //signed char nextLoadableSoundBuffer=1; //signed char lastLoadedSoundBuffer=1; //int _debugFilterPort=0; // TODO - Try downscaling high sample rate // Pretty sure my 125% buffer system will break it. void fixLegArchiveFile(legArchiveFile* _passedFile){ fclose(_passedFile->fp); _passedFile->fp = fopen(_passedFile->filename,"r"); fseek(_passedFile->fp,_passedFile->startPosition+_passedFile->internalPosition,SEEK_SET); } size_t oggReadCallback(void* ptr, size_t size, size_t nmemb, void* datasource){ //printf("read. %d;%d\n",size,nmemb); legArchiveFile* _passedFile = (legArchiveFile*)datasource; if (_passedFile->inArchive==1){ if (_passedFile->internalPosition+(size*nmemb)>=_passedFile->totalLength){ nmemb = (_passedFile->totalLength-_passedFile->internalPosition)/size; } } size_t _readElements = fread(ptr,size,nmemb,((legArchiveFile*)datasource)->fp); if (_readElements==0 && nmemb!=0 && feof(_passedFile->fp)==0){ printf("necesito fix.\n"); fixLegArchiveFile(_passedFile); return oggReadCallback(ptr,size,nmemb,datasource); } _passedFile->internalPosition += size*_readElements; return _readElements; } int oggCloseCallback(void *datasource){ fclose(((legArchiveFile*)datasource)->fp); if (((legArchiveFile*)datasource)->filename!=NULL){ free(((legArchiveFile*)datasource)->filename); } free(datasource); return 0; } long oggTellCallback(void *datasource){ if (((legArchiveFile*)datasource)->inArchive){ return ((legArchiveFile*)datasource)->internalPosition; }else{ return ftell(((legArchiveFile*)datasource)->fp); } } int oggSeekCallback(void *datasource, ogg_int64_t offset, int whence){ //printf("seek\n"); legArchiveFile* _passedFile = (legArchiveFile*)datasource; int _seekReturnValue; if (_passedFile->inArchive){ if (whence==SEEK_SET){ //printf("set %d;%d\n",offset,_passedFile->totalLength); _seekReturnValue = fseek(_passedFile->fp,_passedFile->internalPosition*-1+offset,SEEK_CUR); if (_seekReturnValue==0){ _passedFile->internalPosition=offset; } }else if (whence==SEEK_CUR){ //printf("cur %d\n",offset); if (_passedFile->internalPosition+offset>_passedFile->totalLength){ printf("too long."); } _seekReturnValue = fseek(_passedFile->fp,offset,SEEK_CUR); if (_seekReturnValue==0){ _passedFile->internalPosition+=offset; } }else if (whence==SEEK_END){ //printf("end %d\n",offset); _seekReturnValue = fseek(_passedFile->fp,_passedFile->totalLength-_passedFile->internalPosition+offset,SEEK_CUR); if (_seekReturnValue==0){ _passedFile->internalPosition=_passedFile->totalLength+offset; } }else{ printf("Unknown seek request %d\n",whence); _seekReturnValue=0; } }else{ _seekReturnValue = fseek(_passedFile->fp,offset,whence); } if (_seekReturnValue!=0 && feof(_passedFile->fp)==0){ fixLegArchiveFile(_passedFile); return oggSeekCallback(datasource,offset,whence); } return 0; } long mpgReadCallback(void* _passedData, void* _passedBuffer, size_t _passedBytes){ return oggReadCallback(_passedBuffer,1,_passedBytes,_passedData); } void mpgCloseCallback(void* _passedData){ oggCloseCallback(_passedData); } off_t mpgSeekCallback(void* _passedData, off_t offset, int whence){ oggSeekCallback(_passedData,offset,whence); return oggTellCallback(_passedData); } char mlgsndIsPlaying(NathanAudio* _passedAudio){ return !(_passedAudio->totalPlaying==0); } signed char mlgsnd_getNextBufferIndex(NathanAudio* _passedAudio, signed char _audioBufferSlot){ _audioBufferSlot++; if (_audioBufferSlot==_passedAudio->numBuffers){ return 0; } return _audioBufferSlot; } int64_t _mlgsnd_getLengthInSamples(NathanAudio* _passedAudio){ if (_passedAudio->fileFormat == FILE_FORMAT_OGG){ return ov_pcm_total(_passedAudio->mainAudioStruct,-1); }else if (_passedAudio->fileFormat == FILE_FORMAT_MP3){ int64_t _foundLength = mpg123_length(*((mpg123_handle**)_passedAudio->mainAudioStruct)); if (_foundLength==MPG123_ERR){ _foundLength=-1; } return _foundLength; }else{ return 0; } } signed int _mlgsnd_vitaSoundValueToGeneralGood(signed int _volumeValue){ return (int)((_volumeValue/(double)SCE_AUDIO_OUT_MAX_VOL)*128); } void _mlgsnd_waitWhilePreparing(NathanAudio* _passedAudio){ while (_passedAudio->quitStatus == NAUDIO_QUITSTATUS_PREPARING){ sceKernelDelayThread(SHORT_SYNC_DELAY_MICRO); } } void mlgsnd_setVolume(NathanAudio* _passedAudio, signed int _newVolume){ //_mlgsnd_waitWhilePreparing(_passedAudio); //if (_passedAudio->audioPort!=-1 && _passedAudio->playerThreadId!=0 && _passedAudio->quitStatus!=NAUDIO_QUITSTATUS_FREED){ // If is alive audio _passedAudio->volume = (int)((_newVolume/(double)128)*SCE_AUDIO_OUT_MAX_VOL); // sceAudioOutSetVolume(_passedAudio->audioPort, SCE_AUDIO_VOLUME_FLAG_L_CH |SCE_AUDIO_VOLUME_FLAG_R_CH, (int[]){_passedAudio->volume,_passedAudio->volume}); //} } /* From the currnet spot, seek a certian number of samples. Negative numbers supported. void mlgsnd_seekSamplesRelative(NathanAudio* _passedAudio, signed int _relativeSampleSeek){ if (_passedAudio->fileFormat==FILE_FORMAT_OGG){ ogg_int64_t _currentPosition = ov_pcm_tell(_passedAudio->mainAudioStruct); if (ov_pcm_seek(_passedAudio->mainAudioStruct,_currentPosition+_relativeSampleSeek)!=0){ printf("error.\n"); } } }*/ void mlgsnd_restartAudio(NathanAudio* _passedAudio){ if (_passedAudio->fileFormat==FILE_FORMAT_OGG){ if (ov_raw_seek(_passedAudio->mainAudioStruct,0)!=0){ printf("error.\n"); } }else if (_passedAudio->fileFormat==FILE_FORMAT_MP3){ mpg123_seek(*((mpg123_handle**)_passedAudio->mainAudioStruct),0,SEEK_SET); } } // _fadeoutTime is in milliseconds unsigned int mlgsnd_getFadeoutPerSwap(unsigned int _fadeoutTime, unsigned int _startVolume){ // (AUDIO_BUFFER_LENGTH/48000) - Time between swaps in seconds // _fadeoutTime * (AUDIO_BUFFER_LENGTH/48000) - Correct time between swaps return (unsigned int)(_startVolume/(_fadeoutTime / ((AUDIO_BUFFER_LENGTH/(double)48000)*1000))); } int mlgsnd_getNumChannels(NathanAudio* _passedMusic){ if (_passedMusic->fileFormat==FILE_FORMAT_OGG){ vorbis_info* vi=ov_info((_passedMusic->mainAudioStruct),-1); return vi->channels; }else if (_passedMusic->fileFormat==FILE_FORMAT_MP3){ long _rateResult; int _channelsResult, _encResult; mpg123_getformat(*((mpg123_handle**)_passedMusic->mainAudioStruct), &_rateResult, &_channelsResult, &_encResult); return _channelsResult; }else{ return 0; } } long mlgsnd_getSampleRate(NathanAudio* _passedMusic){ if (_passedMusic->fileFormat==FILE_FORMAT_OGG){ vorbis_info* vi=ov_info(_passedMusic->mainAudioStruct,-1); return vi->rate; }else if (_passedMusic->fileFormat==FILE_FORMAT_MP3){ long _rateResult; int _channelsResult, _encResult; mpg123_getformat(*((mpg123_handle**)_passedMusic->mainAudioStruct), &_rateResult, &_channelsResult, &_encResult); return _rateResult; }else{ return 0; } } long mlgsnd_getBufferSize(NathanAudio* _passedAudio, unsigned int _numberOfSamples, char _sizeOfUint){ return _numberOfSamples*_sizeOfUint*mlgsnd_getNumChannels(_passedAudio); } // Raw audio data stored as short long mlgsnd_getShortSourceSize(NathanAudio* _passedAudio){ return mlgsnd_getBufferSize(_passedAudio,_passedAudio->unscaledSamples,sizeof(short)); } // Raw audio data stored as float long mlgsnd_getFloatSourceSize(NathanAudio* _passedAudio){ return mlgsnd_getBufferSize(_passedAudio,_passedAudio->unscaledSamples,sizeof(float)); } // Converted audio data stored as float long mlgsnd_getFloatDestSize(NathanAudio* _passedAudio){ return mlgsnd_getBufferSize(_passedAudio,_passedAudio->scaledSamples,sizeof(float)); } // Do not use directly, use mlgsnd_getShortSrcDestSize // Converted audio data stored as short long __mlgsnd_getShortDestSize(NathanAudio* _passedAudio){ return mlgsnd_getBufferSize(_passedAudio,_passedAudio->scaledSamples,sizeof(short)); } // Get a buffer size that can hold short data before or after it's converted long mlgsnd_getShortSrcDestSize(NathanAudio* _passedAudio){ if (_passedAudio->scaledSamples>_passedAudio->unscaledSamples){ // If we upscale //printf("") return __mlgsnd_getShortDestSize(_passedAudio); }else{ // We downscale return mlgsnd_getShortSourceSize(_passedAudio); } } // Should be the size of the first buffer. This will get 125% of a short source buffer if it's bigger than the short dest buffer long mlgsnd_getBigShortSrcDestSize(NathanAudio* _passedAudio){ long _possibleBufferSizeOne = mlgsnd_getShortSourceSize(_passedAudio)*BIGBUFFERSCALE; long _possibleBufferSizeTwo = __mlgsnd_getShortDestSize(_passedAudio); return (_possibleBufferSizeOne > _possibleBufferSizeTwo ? _possibleBufferSizeOne : _possibleBufferSizeTwo); } long mlgsnd_getBigFloatSrcSize(NathanAudio* _passedAudio){ return mlgsnd_getFloatSourceSize(_passedAudio)*BIGBUFFERSCALE; } #if !defined(PLATFORM) && SNDPLATFORM != SNDPLAT_LINUX int getTicks(){ return (sceKernelGetProcessTimeWide()/1000); } #endif char* getErrorName(int _errorCode){ switch (_errorCode){ case OV_EREAD: return "OV_EREAD"; case OV_ENOTVORBIS: return "OV_ENOTVORBIS"; case OV_EVERSION: return "OV_EVERSION"; case OV_EBADHEADER: return "OV_EBADHEADER"; case OV_EFAULT: return "OV_EFAULT"; case OV_HOLE: return "OV_HOLE"; case OV_EBADLINK: return "OV_EBADLINK"; case OV_EINVAL: return "OV_EINVAL"; case 0: return "ok"; default: return "???"; } return "why is this here?"; } // Returns 1 for end of file or error // Return values // 0 - OK // 1 - End of file // 2 - Error signed char mlgsnd_readOGGData(OggVorbis_File* _fileToReadFrom, char* _destinationBuffer, int _totalBufferSize, char _passedShouldLoop, FILE* _internalFilePointer){ int _soundBufferWriteOffset=0; int _currentSection; int _bytesLeftInBuffer = _totalBufferSize; while(1){ // Read from my OGG file, at the correct offset in my buffer, I can read 4096 bytes at most, big endian, 16-bit samples, and signed samples long ret=ov_read(_fileToReadFrom,&(_destinationBuffer[_soundBufferWriteOffset]),_bytesLeftInBuffer,0,2,1,&_currentSection); if (ret == 0) { // EOF if (_passedShouldLoop==0){ if (_soundBufferWriteOffset==0){ return 1; }else{ // Just return what we have memset(&(_destinationBuffer[_soundBufferWriteOffset]),0,_bytesLeftInBuffer); return 0; } }else{ // Alright, we're going to loop. // When the user exits to LiveArea and goes back in, this code will thinks it hit EOF. That is because the file pointer won't work anymore. // Calling ov_raw_seek with a broken file pointer crashes. Standard functions won't crash when interacting with the file, though. // So, because we think we're at the end of the file, we can probably go back one byte. // If it doesn't work, we know the file pointer is broken and we should cancel loading. // If it does work, we can continue with the loading after fixing our seeking. if (fseek(_internalFilePointer,-1,SEEK_CUR)!=0){ // File has been broken, quit. return 2; }else{ fseek(_internalFilePointer,1,SEEK_CUR); } if (ov_raw_seek(_fileToReadFrom,0)!=0){ return 1; } } } else if (ret < 0) { printf("Error: %ld\n",ret); if (ret==OV_HOLE){ printf("OV_HOLE\n"); }else if(ret==OV_EBADLINK){ printf("OV_EBADLINK\n"); }else if (ret==OV_EINVAL){ printf("OV_EINVAL with %d bytes left\n",_bytesLeftInBuffer); } return 2; } else { _bytesLeftInBuffer-=ret; // Move pointer in buffer _soundBufferWriteOffset+=ret; if (_bytesLeftInBuffer<=0){ break; } } } return 0; } // Returns 1 for end of file or error // Return values // 0 - OK // 1 - End of file // 2 - Error signed char _mlgsnd_readMp3Data(mpg123_handle* _fileToReadFrom, char* _destinationBuffer, int _totalBufferSize, char _passedShouldLoop){ int _soundBufferWriteOffset=0; int _bytesLeftInBuffer = _totalBufferSize; while(1){ size_t _bytesDecoded; int _possibleErrorCode = mpg123_read(_fileToReadFrom,(unsigned char*)&(_destinationBuffer[_soundBufferWriteOffset]),_bytesLeftInBuffer,&_bytesDecoded); if (_possibleErrorCode==MPG123_DONE){ if (_passedShouldLoop==0){ if (_soundBufferWriteOffset==0){ return 1; }else{ // Just return what we have memset(&(_destinationBuffer[_soundBufferWriteOffset]),0,_bytesLeftInBuffer); return 0; } }else{ mpg123_seek(_fileToReadFrom,0,SEEK_SET); } }else if (_possibleErrorCode!=MPG123_OK){ printf("error, %s\n",mpg123_plain_strerror(_possibleErrorCode)); //return 2; } // Update position in buffer based on how much read _bytesLeftInBuffer-=_bytesDecoded; _soundBufferWriteOffset+=_bytesDecoded; if (_bytesLeftInBuffer<=0){ break; } } return 0; } void mlgsnd_fadeoutMusic(NathanAudio* _passedAudio, unsigned int _fadeoutTime){ _passedAudio->fadeoutPerSwap = mlgsnd_getFadeoutPerSwap(_fadeoutTime, _passedAudio->volume); _passedAudio->isFadingOut=1; } void mlgsnd_stopMusic(NathanAudio* _passedAudio){ if (_passedAudio->totalPlaying == 0){ // If there are none to stop then don't stop. return; } _passedAudio->quitStatus = NAUDIO_QUITSTATUS_SHOULDQUIT; _passedAudio->volume = 0; if (_passedAudio->audioPort!=-1){ sceAudioOutSetVolume(_passedAudio->audioPort, SCE_AUDIO_VOLUME_FLAG_L_CH |SCE_AUDIO_VOLUME_FLAG_R_CH, (int[]){0,0}); // Make it seem like the audio is stopped while it actually stops } if (_passedAudio->totalPlaying==1){ // Only wait for thread exit if we have only one thread. SceUInt _tempStoreTimeout = 50000000; int _storeExitStatus = 0; sceKernelWaitThreadEnd(_passedAudio->playerThreadId,&_storeExitStatus,&_tempStoreTimeout); // Timeout is 5 seconds }else{ // If multiple then wait for all of them to stop. while (_passedAudio->totalPlaying!=0){ sceKernelDelayThread(SHORT_SYNC_DELAY_MICRO); } } _passedAudio->playerThreadId=-1; _passedAudio->volume = SCE_AUDIO_OUT_MAX_VOL; // If we replay this sound _passedAudio->lastVolume = _passedAudio->volume; } void _mlgsnd_disposeMusicMainStruct(NathanAudio* _passedAudio){ if (_passedAudio->fileFormat==FILE_FORMAT_OGG){ ov_clear(_passedAudio->mainAudioStruct); }else if (_passedAudio->fileFormat==FILE_FORMAT_MP3){ mpg123_delete(*((mpg123_handle**)_passedAudio->mainAudioStruct)); fclose(_passedAudio->_internalFilePointer); } } void mlgsnd_freeMusic(NathanAudio* _passedAudio){ if (_passedAudio->quitStatus == NAUDIO_QUITSTATUS_FREED){ // Avoid audio double free. Actually, this line is useless and will still crash on double free. return; } // Don't free playing music mlgsnd_stopMusic(_passedAudio); // Different for each file format _mlgsnd_disposeMusicMainStruct(_passedAudio); // Free converter src_delete(_passedAudio->personalConverter); // Free main audio buffers int i; for (i=0;i<_passedAudio->numBuffers;i++){ free(_passedAudio->audioBuffers[i]); } free(_passedAudio->audioBuffers); // Free temp conversion buffers free(_passedAudio->tempFloatConverted); free(_passedAudio->tempFloatSource); // Phew, almost forgot these free(_passedAudio->mainAudioStruct); free(_passedAudio); } // Returns NOT 0 if audio is done playing or error, 0 otherwise signed char _mlgsnd_loadUnprocessedData(signed char _passedFormat, void* mainAudioStruct, char* _destinationBuffer, int _totalBufferSize, char _passedShouldLoop, NathanAudio* _passedAudio){ signed char _possibleReturnValue=-1; if (_passedFormat==FILE_FORMAT_OGG){ _possibleReturnValue = mlgsnd_readOGGData(mainAudioStruct,_destinationBuffer,_totalBufferSize,_passedShouldLoop,_passedAudio->_internalFilePointer); }else if (_passedFormat==FILE_FORMAT_MP3){ _possibleReturnValue = _mlgsnd_readMp3Data(*((mpg123_handle**)mainAudioStruct),_destinationBuffer,_totalBufferSize,_passedShouldLoop); } return _possibleReturnValue; } /*void _mlgsnd_processData(SRC_STATE* _passedConverter, SRC_DATA* _passedConverterData, short* _shortBuffer, float* _floatBufferTempSource, float* _floatBufferTempDest, unsigned int _smallBufferSamples, unsigned int _longBufferSamples, signed char _numChannels){ // Update data object _passedConverterData->data_in = _floatBufferTempSource; _passedConverterData->data_out = _floatBufferTempDest; // Keep these as is, secret rabbit code already accounts for channels. Stolen code: data->data_in + data->input_frames * psrc->channels _passedConverterData->input_frames = _smallBufferSamples; _passedConverterData->output_frames = _longBufferSamples; // Change our loaded short data into loaded float data src_short_to_float_array(_shortBuffer,_floatBufferTempSource,_smallBufferSamples*_numChannels); // Convert loaded float data into converted float data with proper sample rate in temp buffer int _possibleErrorCode = src_process(_passedConverter,_passedConverterData); if (_possibleErrorCode!=0){ printf("%s\n",src_strerror(_possibleErrorCode)); // SRC_STATE pointer is NULL } // Change converted float data in temp buffer to short data with proper sample rate in proper buffer src_float_to_short_array(_floatBufferTempDest,_shortBuffer,_longBufferSamples*_numChannels); }*/ // samples is _passedAudio->unscaledSamples // bytes is mlgsnd_getShortSourceSize(_passedAudio) signed int mlgsnd_loadMoreData(NathanAudio* _passedAudio, unsigned char _audioBufferSlot, unsigned int _passedSamples, unsigned int _passedSourceBufferSize){ signed char _possibleReturnValue = _mlgsnd_loadUnprocessedData(_passedAudio->fileFormat,_passedAudio->mainAudioStruct, &(((char**)_passedAudio->audioBuffers)[_audioBufferSlot][_passedAudio->nextBufferLoadOffset]),_passedSourceBufferSize-_passedAudio->nextBufferLoadOffset,_passedAudio->shouldLoop,_passedAudio); _passedAudio->nextBufferLoadOffset=0; if (_possibleReturnValue!=0){ return -1; } if (_passedAudio->usualConverterData.src_ratio!=1){ // Update data object _passedAudio->usualConverterData.data_in = _passedAudio->tempFloatSource; _passedAudio->usualConverterData.data_out = _passedAudio->tempFloatConverted; // Keep these as is, secret rabbit code already accounts for channels. Stolen code: data->data_in + data->input_frames * psrc->channels _passedAudio->usualConverterData.input_frames = _passedSamples; _passedAudio->usualConverterData.output_frames = _passedAudio->scaledSamples; // Change our loaded short data into loaded float data src_short_to_float_array(_passedAudio->audioBuffers[_audioBufferSlot],_passedAudio->tempFloatSource,_passedSamples*mlgsnd_getNumChannels(_passedAudio)); // Convert loaded float data into converted float data with proper sample rate in temp buffer int _possibleErrorCode = src_process(_passedAudio->personalConverter,&(_passedAudio->usualConverterData)); if (_possibleErrorCode!=0){ printf("%s\n",src_strerror(_possibleErrorCode)); // SRC_STATE pointer is NULL } //printf("%d;%d\n",_passedAudio->usualConverterData.input_frames_used,_passedAudio->usualConverterData.output_frames_gen); // Save unused samples if (_passedSamples>_passedAudio->usualConverterData.input_frames_used && _passedAudio->numBuffers!=1 ){ signed char _nextBuffer = mlgsnd_getNextBufferIndex(_passedAudio,_audioBufferSlot); signed int _possibleNextLoadOffset = (_passedSamples-_passedAudio->usualConverterData.input_frames_used)*sizeof(short)*mlgsnd_getNumChannels(_passedAudio); if (_possibleNextLoadOffset>_passedSourceBufferSize){ printf("too much data unused, so the only logical thing to do is discard it all\n"); }else{ _passedAudio->nextBufferLoadOffset = _possibleNextLoadOffset; memcpy( _passedAudio->audioBuffers[_nextBuffer], &(((char**)_passedAudio->audioBuffers)[_audioBufferSlot][_passedSourceBufferSize-_passedAudio->nextBufferLoadOffset]), _passedAudio->nextBufferLoadOffset ); } } // Change converted float data in temp buffer to short data with proper sample rate in proper buffer src_float_to_short_array(_passedAudio->tempFloatConverted,_passedAudio->audioBuffers[_audioBufferSlot],_passedAudio->usualConverterData.output_frames_gen*mlgsnd_getNumChannels(_passedAudio)); } /*_mlgsnd_processData(_passedAudio->personalConverter,&(_passedAudio->usualConverterData),_passedAudio->audioBuffers[_audioBufferSlot],_passedAudio->tempFloatSource,_passedAudio->tempFloatConverted,_passedAudio->unscaledSamples,_passedAudio->scaledSamples, mlgsnd_getNumChannels(_passedAudio) ); if (_passedAudio->usualConverterData.input_frames_used!=_passedAudio->unscaledSamples){ printf("failed.\n"); }*/ return 0; } // Process pause trigger void _mlgsnd_waitWhilePaused(NathanAudio* _passedAudio){ while (_passedAudio->quitStatus == NAUDIO_QUITSTATUS_PAUSED){ sceKernelDelayThread(SHORT_SYNC_DELAY_MICRO); } } int mlgsnd_soundPlayingThread(SceSize args, void *argp){ #if SNDPLATFORM == SNDPLAT_VITA argp = *((void***)argp); #endif NathanAudio* _passedAudio=(((void**)argp)[0]); int _currentPort = (int)(((void**)argp)[1]); free(argp); signed short i; for (i=0;_passedAudio->quitStatus != NAUDIO_QUITSTATUS_SHOULDQUIT;){ // Detect volume changes if (_passedAudio->lastVolume!=_passedAudio->volume){ sceAudioOutSetVolume(_currentPort, SCE_AUDIO_VOLUME_FLAG_L_CH |SCE_AUDIO_VOLUME_FLAG_R_CH, (int[]){_passedAudio->volume,_passedAudio->volume}); _passedAudio->lastVolume=_passedAudio->volume; } // Fadeout if needed if (_passedAudio->isFadingOut){ _passedAudio->volume-=_passedAudio->fadeoutPerSwap; // If fadeout is over if (_passedAudio->volume<0){ break; } sceAudioOutSetVolume(_currentPort, SCE_AUDIO_VOLUME_FLAG_L_CH |SCE_AUDIO_VOLUME_FLAG_R_CH, (int[]){_passedAudio->volume,_passedAudio->volume}); } //if (_currentPort!=_debugFilterPort){ // printf("%d;%d\n",_currentPort,sceAudioOutGetRestSample(_currentPort)); //} //if (<=0){ // printf("Bad.\n"); //} //if (sceAudioOutGetRestSample(_currentPort)<=64){ // printf("bad.\n"); //} //SceUInt64 _startTicks = sceKernelGetProcessTimeWide(); // Start playing audio if (sceAudioOutOutput(_currentPort, _passedAudio->audioBuffers[i])<0){ printf("Output error.\n"); } // Change buffer variable ++i; // If the next buffer is out of bounds if (i==_passedAudio->numBuffers){ if (_passedAudio->myStreamStatus>=STREAMSTATUS_DONTSTREAM){ // If we don't stream then we need to quit as we have no buffers left _passedAudio->quitStatus = NAUDIO_QUITSTATUS_SHOULDQUIT; --i; // Buffer variable is now the last known working buffer. If the quit status is changed between now and the end of the loop then the last working buffer will replay. }else{ // If we do stream i=0; } } // Stream audio data if we need to. if (_passedAudio->myStreamStatus == STREAMSTATUS_STREAMING || _passedAudio->myStreamStatus == STREAMSTATUS_MINISTREAM){ // Start loading next audio into the other buffer while the current audio buffer is playing. signed char _loadMoreResult = mlgsnd_loadMoreData(_passedAudio,i,_passedAudio->unscaledSamples,mlgsnd_getShortSourceSize(_passedAudio)); if (_passedAudio->myStreamStatus == STREAMSTATUS_MINISTREAM && i==_passedAudio->numBuffers-1){ // If we just loaded the last buffer. _passedAudio->myStreamStatus = STREAMSTATUS_DONTSTREAM; } if (_loadMoreResult==-1){ // If error or end of file without looping break; // Break out } } // Wait for audio to finish playing in the remaining time //sceAudioOutOutput(_currentPort, NULL); //printf("%ld\n",(long)(sceKernelGetProcessTimeWide()-_startTicks)); // Check low priority triggers _mlgsnd_waitWhilePaused(_passedAudio); } sceAudioOutOutput(_currentPort, NULL); // Wait for audio to finish playing sceAudioOutReleasePort(_currentPort); // Release the port now that there's no audio if (_passedAudio->audioPort==_currentPort){ _passedAudio->audioPort=-1; // Reset port variable } //_passedAudio->quitStatus = NAUDIO_QUITSTATUS_QUITTED; // Set quit before exiting _passedAudio->playerThreadId=-1; --_passedAudio->totalPlaying; sceKernelExitDeleteThread(0); return 0; } NathanAudio* _mlgsnd_loadAudioFILE(legArchiveFile _passedFile, char _passedFileFormat, char _passedShouldLoop, char _passedShouldStream){ NathanAudio* _returnAudio = malloc(sizeof(NathanAudio)); if (_passedFileFormat==FILE_FORMAT_MP3){ _returnAudio->fileFormat = FILE_FORMAT_MP3; int _lastMpg123Error; // https://www.mpg123.de/api/mpglib_8c_source.shtml if (!haveInitMpg123){ printf("Init mp3\n"); mpg123_init(); haveInitMpg123=1; } mpg123_handle* _newHandle = mpg123_new(NULL, &_lastMpg123Error); if(_newHandle == NULL){ printf("Unable to create mpg123 handle: %s\n", mpg123_plain_strerror(_lastMpg123Error)); return NULL; } _returnAudio->mainAudioStruct = malloc(sizeof(mpg123_handle*)); *((mpg123_handle**)_returnAudio->mainAudioStruct)=_newHandle; if (_passedFile.fp==NULL){ printf("bad.\n"); } //if (_passedFile.totalLength!=0){ legArchiveFile* _toPass = malloc(sizeof(legArchiveFile)); *_toPass = _passedFile; _lastMpg123Error = mpg123_replace_reader_handle(_newHandle,mpgReadCallback,mpgSeekCallback,mpgCloseCallback); _lastMpg123Error = mpg123_open_handle(_newHandle,_toPass); //}else{ // if (mpg123_open_fd(*((mpg123_handle**)_returnAudio->mainAudioStruct),fileno(_passedFile.fp))!=MPG123_OK){ // printf("open error for mpg123.\n"); // return NULL; // } //} // https://www.mpg123.de/api/group__mpg123__output.shtml _lastMpg123Error = mpg123_format_none(*((mpg123_handle**)_returnAudio->mainAudioStruct)); //44100 _lastMpg123Error = mpg123_format(*((mpg123_handle**)_returnAudio->mainAudioStruct),48000,MPG123_STEREO,MPG123_ENC_SIGNED_16); if (_lastMpg123Error!=MPG123_OK){ printf("error, %d;%s\n",_lastMpg123Error,mpg123_plain_strerror(_lastMpg123Error)); } }else if (_passedFileFormat == FILE_FORMAT_OGG){ OggVorbis_File myVorbisFile; int _possibleErrorCode; //if (_passedFile.totalLength!=0){ ov_callbacks myCallbacks; myCallbacks.read_func = oggReadCallback; myCallbacks.seek_func = oggSeekCallback; myCallbacks.close_func = oggCloseCallback; myCallbacks.tell_func = oggTellCallback; legArchiveFile* _toPass = malloc(sizeof(legArchiveFile)); *_toPass = _passedFile; //int _possibleErrorCode = ov_open(_passedFile.fp, &myVorbisFile, NULL, 0); _possibleErrorCode = ov_open_callbacks(_toPass, &myVorbisFile, NULL, 0,myCallbacks); //}else{ // _possibleErrorCode = ov_open(_passedFile.fp, &myVorbisFile, NULL, 0); //} if(_possibleErrorCode != 0){ fclose(_passedFile.fp); printf("open not worked!\n"); printf("Error: %d;%s",_possibleErrorCode,getErrorName(_possibleErrorCode)); return NULL; } _returnAudio->mainAudioStruct = malloc(sizeof(OggVorbis_File)); *((OggVorbis_File*)(_returnAudio->mainAudioStruct)) = myVorbisFile; _returnAudio->fileFormat = FILE_FORMAT_OGG; }else{ printf("Bad file format %d\n",_passedFileFormat); return NULL; } _returnAudio->_internalFilePointer = _passedFile.fp; _returnAudio->quitStatus=NAUDIO_QUITSTATUS_PREPARING; _returnAudio->isFadingOut=0; _returnAudio->volume = SCE_AUDIO_OUT_MAX_VOL; // SCE_AUDIO_OUT_MAX_VOL is actually max volume, not 0 decibels. _returnAudio->lastVolume = _returnAudio->volume; _returnAudio->shouldLoop = _passedShouldLoop; _returnAudio->playerThreadId=-1; _returnAudio->audioPort=-1; _returnAudio->isFirstTime=1; _returnAudio->totalPlaying=0; _returnAudio->nextBufferLoadOffset=0; // Setup sample rate ratios double _oldRateToNewRateRatio = (double)mlgsnd_getSampleRate(_returnAudio)/48000; _returnAudio->unscaledSamples = AUDIO_BUFFER_LENGTH*_oldRateToNewRateRatio; _returnAudio->scaledSamples = AUDIO_BUFFER_LENGTH; // Malloc temp buffers _returnAudio->tempFloatSource = malloc(mlgsnd_getBigFloatSrcSize(_returnAudio)); // Also needs to be able to hold big first buffer as float data _returnAudio->tempFloatConverted = malloc(mlgsnd_getFloatDestSize(_returnAudio)); // Init converter object data argument now that temp buffer exists _returnAudio->usualConverterData.data_in = _returnAudio->tempFloatSource; _returnAudio->usualConverterData.data_out = _returnAudio->tempFloatConverted; _returnAudio->usualConverterData.input_frames = _returnAudio->unscaledSamples; _returnAudio->usualConverterData.output_frames= _returnAudio->scaledSamples; _returnAudio->usualConverterData.src_ratio = 48000/(double)mlgsnd_getSampleRate(_returnAudio); _returnAudio->usualConverterData.end_of_input=0; // Init converter object _returnAudio->personalConverter = src_new(SAMPLERATECONVERSIONQUALITY,mlgsnd_getNumChannels(_returnAudio),&lastConverterError); if (lastConverterError!=0){ printf("%s\n",src_strerror(lastConverterError)); // Bad converter number } // Init data for audio _returnAudio->myStreamStatus = (_passedShouldStream ? STREAMSTATUS_STREAMING : STREAMSTATUS_DONTSTREAM); // How many buffers we would need if we were streaming _returnAudio->numBuffers = ceil((_mlgsnd_getLengthInSamples(_returnAudio)*_returnAudio->usualConverterData.src_ratio)/(double)AUDIO_BUFFER_LENGTH); if (_returnAudio->numBuffers<=0){ printf("ohnozies\n"); _returnAudio->numBuffers = STREAMING_BUFFERS+1; } // If we could fit our streaming sound in just our swap buffers then don't stream if (_returnAudio->numBuffers<=STREAMING_BUFFERS){ _returnAudio->myStreamStatus=STREAMSTATUS_MINISTREAM; }else if (_returnAudio->numBuffers==1){ _returnAudio->myStreamStatus=STREAMSTATUS_DONTSTREAM; } // Change the numBuffers variable if we're streaming if (_returnAudio->myStreamStatus==STREAMSTATUS_STREAMING){ // We are actually streaming _returnAudio->numBuffers=STREAMING_BUFFERS; }else{ // We're not streaming, don't change the numBuffers variable } // Malloc audio buffers depending on if we want streaming or not _returnAudio->audioBuffers = malloc(sizeof(void*)*_returnAudio->numBuffers); // Array // First buffer exception _returnAudio->audioBuffers[0] = malloc(mlgsnd_getBigShortSrcDestSize(_returnAudio)); // Needs to be able to hold the 125% unscaled and 100% scaled. TODO - We can't know which one is bigger. // Normal buffers int i; for (i=1;i<_returnAudio->numBuffers;i++){ _returnAudio->audioBuffers[i] = malloc(mlgsnd_getShortSrcDestSize(_returnAudio)); // The array elements, the audio buffers } ////mlgsnd_loadMoreData(_returnAudio,0); //// No matter what, we'll need the first buffer. //// Special code to load the first buffer //_mlgsnd_loadUnprocessedData(_returnAudio->fileFormat,_returnAudio->mainAudioStruct,_returnAudio->audioBuffers[0],mlgsnd_getInitBufferSize(_returnAudio,_returnAudio->unscaledSamples,sizeof(short)),1); // Always loop for now. ////void _mlgsnd_processData(SRC_STATE* _passedConverter, SRC_DATA* _passedConverterData, short* _shortBuffer, float* _floatBufferTempSource, float* _floatBufferTempDest, unsigned int _smallBufferSamples, unsigned int _longBufferSamples){ //_mlgsnd_processData(_returnAudio->personalConverter,&(_returnAudio->usualConverterData),_returnAudio->audioBuffers[0],_returnAudio->tempFloatSource,_returnAudio->tempFloatConverted,_mlgsnd_getInitSamples(_returnAudio->unscaledSamples),_returnAudio->scaledSamples,mlgsnd_getNumChannels(_returnAudio)); //if (_returnAudio->usualConverterData.output_frames_gen!=AUDIO_BUFFER_LENGTH){ // printf("will pop.\n"); //} //// No idea why this is never called. I guess everything just turns out okay? //if (_returnAudio->usualConverterData.input_frames_used!=_mlgsnd_getInitSamples(_returnAudio->unscaledSamples)){ // If we loaded too much // printf("seek %d\n",-1*(_mlgsnd_getInitSamples(_returnAudio->unscaledSamples)-_returnAudio->usualConverterData.input_frames_used)); // mlgsnd_seekSamplesRelative(_returnAudio,-1*(_mlgsnd_getInitSamples(_returnAudio->unscaledSamples)-_returnAudio->usualConverterData.input_frames_used)); //} mlgsnd_loadMoreData(_returnAudio,0,_returnAudio->unscaledSamples*BIGBUFFERSCALE,mlgsnd_getBigShortSrcDestSize(_returnAudio)); // Fill more buffers depending on if we want streaming or not if (_returnAudio->myStreamStatus==STREAMSTATUS_DONTSTREAM){ // Fill all buffers short i; for (i=1;i<_returnAudio->numBuffers;i++){ mlgsnd_loadMoreData(_returnAudio,i,_returnAudio->unscaledSamples,mlgsnd_getShortSourceSize(_returnAudio)); } } return _returnAudio; } NathanAudio* _mlgsnd_loadAudioFilename(char* _passedFilename, char _passedShouldLoop, char _passedShouldStream){ char _foundFileFormat = FILE_FORMAT_NONE; if (strlen(_passedFilename)>=4){ char _copiedExtension[5]; strcpy(_copiedExtension,&(_passedFilename[strlen(_passedFilename)-4])); // Convert the extension to lower case char i; for (i=0;i<4;++i){ if (_copiedExtension[i]<='Z' && _copiedExtension[i]>='A'){ _copiedExtension[i]+=32; } } if (strcmp(_copiedExtension,".mp3")==0){ _foundFileFormat = FILE_FORMAT_MP3; }else if (strcmp(_copiedExtension,".wav")==0){ // Not yet supported //_foundFileFormat = FILE_FORMAT_WAV; }else if (strcmp(_copiedExtension,".ogg")==0){ _foundFileFormat = FILE_FORMAT_OGG; } } if (_foundFileFormat!=FILE_FORMAT_NONE){ legArchiveFile _passFile; _passFile.fp = fopen(_passedFilename,"r"); _passFile.totalLength=0; _passFile.internalPosition=0; _passFile.inArchive=0; _passFile.filename = malloc(strlen(_passedFilename)+1); strcpy(_passFile.filename,_passedFilename); return _mlgsnd_loadAudioFILE(_passFile, _foundFileFormat, _passedShouldLoop, _passedShouldStream); }else{ return NULL; } } NathanAudio* mlgsnd_loadMusicFilename(char* filename){ return _mlgsnd_loadAudioFilename(filename,1,1); } NathanAudio* mlgsnd_loadSoundFilename(char* filename){ return _mlgsnd_loadAudioFilename(filename,0,0); } NathanAudio* mlgsnd_loadMusicFILE(legArchiveFile _passedFile, char _passedFileFormat){ return _mlgsnd_loadAudioFILE(_passedFile,_passedFileFormat,1,1); } NathanAudio* mlgsnd_loadSoundFILE(legArchiveFile _passedFile, char _passedFileFormat){ return _mlgsnd_loadAudioFILE(_passedFile,_passedFileFormat,0,0); } char _mlgsnd_initPort(NathanAudio* _passedAudio){ // SCE_AUDIO_MAX_LEN is 65472. 65472/44100 = 1.485. That feels like around how much I've loaded. // The port returned from this must be kept safe for future use _passedAudio->audioPort = sceAudioOutOpenPort(SCE_AUDIO_OUT_PORT_TYPE_MAIN, AUDIO_BUFFER_LENGTH, 48000, mlgsnd_getNumChannels(_passedAudio) == 1 ? SCE_AUDIO_OUT_MODE_MONO : SCE_AUDIO_OUT_MODE_STEREO); if (_passedAudio->audioPort<0){ // Probably no ports avalible return 0; } // More audio init sceAudioOutSetVolume(_passedAudio->audioPort, SCE_AUDIO_VOLUME_FLAG_L_CH |SCE_AUDIO_VOLUME_FLAG_R_CH, (int[]){_passedAudio->volume,_passedAudio->volume}); sceAudioOutSetConfig(_passedAudio->audioPort, -1, -1, (SceAudioOutMode)-1); // This line is probablly useless. A -1 argument means that the specific property isn't changed. But I saw my god, Rinnegatamante, do it, so I'll do it too. return 1; } void mlgsnd_play(NathanAudio* _passedAudio){ // We may need to rewind if we're streaming and this isn't our first time because buffers and file positions change. if ((_passedAudio->myStreamStatus == STREAMSTATUS_STREAMING) && !_passedAudio->isFirstTime){ if (_passedAudio->totalPlaying!=0){ // If we stream then we write to buffers then we can't have two threads reading from the same buffer, wait for stop. mlgsnd_stopMusic(_passedAudio); } // If this is our second time playing this audio mlgsnd_restartAudio(_passedAudio); // Reload first buffer mlgsnd_loadMoreData(_passedAudio,0,_passedAudio->unscaledSamples,mlgsnd_getShortSourceSize(_passedAudio)); } if (_passedAudio->isFirstTime){ _passedAudio->isFirstTime=0; } // Initialize audio ports and such if (_mlgsnd_initPort(_passedAudio)==0){ return; } // We just used the volume variable _passedAudio->lastVolume = _passedAudio->volume; // Set this flag as late as possible _passedAudio->quitStatus = NAUDIO_QUITSTATUS_PLAYING; // Do it before we start playing ++_passedAudio->totalPlaying; // Arguments for our new thread void** _newArgs = malloc(sizeof(void*)*2); _newArgs[0]=_passedAudio; _newArgs[1]=(void*)(_passedAudio->audioPort); #if SNDPLATFORM == SNDPLAT_VITA // Initialize sound playing thread, but don't start it. SceUID mySoundPlayingThreadID = sceKernelCreateThread("SOUNDPLAY", mlgsnd_soundPlayingThread, 0, 0x10000, 0, 0, NULL); _passedAudio->playerThreadId = mySoundPlayingThreadID; // Start sound thread sceKernelStartThread(_passedAudio->playerThreadId,sizeof(void**),&_newArgs); #elif SNDPLATFORM == SNDPLAT_LINUX _passedAudio->playerThreadId = malloc(sizeof(pthread_t)); pthread_create(_passedAudio->playerThreadId,NULL,_soundThreadPthreadWrapper,_newArgs); #endif } #if INCLUDETESTCODE==1 SceCtrlData lastCtrl; void printAudioDataStart(NathanAudio* _passedAudio, signed char _whichBuffer){ return; printf("Values in buffer %d.\n",_whichBuffer); int j; for (j=0;j<10;j++){ printf("%d,",(((short**)_passedAudio->audioBuffers[_whichBuffer]))[j]); } printf("\n"); } #if SNDPLATFORM == SNDPLAT_VITA char wasJustPressed(SceCtrlData ctrl, int _possibleControl){ if ((ctrl.buttons & _possibleControl) && !(lastCtrl.buttons & _possibleControl)){ return 1; } return 0; } #endif void printGuide(){ printf("Right - Swap sound filename\nLeft - Rewind\nDown - Toggle first time flag\nTriangle - Load\nSquare - Free\nCircle - Stop\nX - Play\n\n"); } #if SNDPLATFORM == SNDPLAT_VITA signed char checkFileExist(const char* location){ SceUID fileHandle = sceIoOpen(location, SCE_O_RDONLY, 0777); if (fileHandle < 0){ return 0; }else{ sceIoClose(fileHandle); return 1; } } void directoryTest(char* _path){ int j; int _start = getTicks(); for (j=0;j<100;++j){ checkFileExist(_path); } int _total = (getTicks()-_start); printf("Total:%d\n",_total); printf("Avg: %d\n",_total/100); } #endif int main(void) { psvDebugScreenInit(); // TODO - To fix load dictionary loading, just put the dictionary in a seperate file. if (sizeof(float)!=4 || sizeof(short)!=2 || (sizeof(int)>sizeof(void*) || (sizeof(short)>sizeof(float)))){ printf("Type sizes wrong, f;d, %d;%d\n",sizeof(float),sizeof(short)); if (!('Z'==90 && 'z'==122)){ printf("ASCII values are wrong.\n"); } } //NathanAudio* _theGoodBGM = mlgsnd_loadMusic("ux0:data/SOUNDTEST/dppbattlemono.ogg"); //mlgsnd_setVolume(_theGoodBGM,50); //mlgsnd_play(_theGoodBGM); // ////_debugFilterPort=_theGoodBGM->audioPort; //int j; ////for (j=0;j<2;++j){ //int _start = getTicks(); ////for (j=0;j<20;++j){ // //checkFileExist("ux0:data/SOUNDTEST/438224"); // printf("%d\n",checkFileExist("ux0:data/OneThousand/438224")); ////} //printf("Total:%d\n",(getTicks()-_start)); ////} ////aadbs.ogg //_start = getTicks(); ////for (j=0;j<20;++j){ // //checkFileExist("ux0:data/SOUNDTEST/438224"); // printf("%d\n",checkFileExist("ux0:data/OneThousand/aadbs.ogg")); ////} //printf("Total:%d\n",(getTicks()-_start)); //int j; ////for (j=0;j<2;++j){ //int _start = getTicks(); ////for (j=0;j<20;++j){ // //checkFileExist("ux0:data/SOUNDTEST/438224"); // printf("%d\n",checkFileExist("ux0:data/OneThousand/438224")); ////} //printf("Total:%d\n",(getTicks()-_start)); ////} ////aadbs.ogg //_start = getTicks(); ////for (j=0;j<20;++j){ // //checkFileExist("ux0:data/SOUNDTEST/438224"); // printf("%d\n",checkFileExist("ux0:data/OneThousand/aadbs.ogg")); ////} //printf("Total:%d\n",(getTicks()-_start)); #if SNDPLATFORM == SNDPLAT_VITA //legArchive soundarch = loadLegArchive("ux0:data/SOUNDTEST/oggarchive"); //legArchive soundarch = loadLegArchive("ux0:data/HIGURASHI/Games/base_install-converted/SEArchive.legArchive"); //legArchive soundarch = loadLegArchive("uma0:data/HIGURASHI/games/SayaNoUta-converted/SEArchive.legArchive"); #elif SNDPLATFORM == SNDPLAT_LINUX //legArchive soundarch = loadLegArchive("./uta"); #endif // ////https://www.mpg123.de/api/group__mpg123__lowio.shtml // ////NathanAudio* _theGoodBGM2 = _mlgsnd_loadAudio("ux0:data/HIGURASHI/Games/umineko 4-converted/SE/11900015.ogg",0,1); #if SNDPLATFORM == SNDPLAT_VITA //NathanAudio* _theGoodBGM2 = _mlgsnd_loadAudioFilename("ux0:data/SOUNDTEST/battlerika.ogg",1,1); //NathanAudio* _theGoodBGM2 = _mlgsnd_loadAudioFILE(getAdvancedFile(soundarch,"music/s02.mp3"),FILE_FORMAT_MP3,1,1); NathanAudio* _theGoodBGM2 = _mlgsnd_loadAudioFilename("ux0:data/s02.mp3",1,1); //if (checkFileExist("ux0:data/HIGURASHI/Games/base_install-converted/SE/special/title.mp3")==0){ // printf("grueiwre\n"); //} //NathanAudio* _theGoodBGM2 = _mlgsnd_loadAudioFilename("ux0:data/SOUNDTEST/BGM1.mp3",1,1); #elif SNDPLATFORM == SNDPLAT_LINUX //NathanAudio* _theGoodBGM2 = _mlgsnd_loadAudioFilename("./BGM1.mp3",1,1); //NathanAudio* _theGoodBGM2 = _mlgsnd_loadAudioFILE(getAdvancedFile(soundarch,"music/s02.mp3"),FILE_FORMAT_MP3,1,1); NathanAudio* _theGoodBGM2 = _mlgsnd_loadAudioFilename("./s02.mp3",1,1); //NathanAudio* _theGoodBGM2 = _mlgsnd_loadAudioFilename("./wa_038.ogg",0,1); #endif mlgsnd_setVolume(_theGoodBGM2,50); mlgsnd_play(_theGoodBGM2); //mlgsnd_freeMusic(_theGoodBGM2); //printf("a\n"); //sceKernelDelayThread(1000); //printf("b\n"); //_theGoodBGM2 = _mlgsnd_loadAudio("ux0:data/SOUNDTEST/smart.ogg",0,1); //mlgsnd_setVolume(_theGoodBGM2,50); //mlgsnd_play(_theGoodBGM2); //NathanAudio* _theGoodBGM3 = _mlgsnd_loadAudio("ux0:data/SOUNDTEST/rikatest.ogg",0,1); //mlgsnd_setVolume(_theGoodBGM3,50); //mlgsnd_play(_theGoodBGM3); //NathanAudio* _theGoodBGM3 = mlgsnd_loadMusic("ux0:data/SOUNDTEST/as.ogg"); //mlgsnd_setVolume(_theGoodBGM3,50); //mlgsnd_play(_theGoodBGM3); //NathanAudio* _theGoodBGM3 = mlgsnd_loadMusic("ux0:data/SOUNDTEST/as.ogg"); //mlgsnd_setVolume(_theGoodBGM3,50); //mlgsnd_play(_theGoodBGM3); /* NathanAudio* _lastSoundEffect=NULL; char* _firstPossibleSound="ux0:data/SOUNDTEST/yuna0023.ogg"; char* _secondPossibleSound="ux0:data/SOUNDTEST/mion.ogg"; //s20/01/440100006 //s20/01/440100008 char* _newSoundToPlay=_firstPossibleSound; //printf("X-Stop\nO-Free\nSquare-Pause\nTrinalge-Fadeout\nUp - play"); printGuide(); */ //SceUID _testfile = sceIoOpen("ux0:data/SOUNDTEST/a.txt",SCE_O_RDONLY,0777); //char readdata[5]; //readdata[4]='\0'; //sceIoRead(_testfile,readdata,4); while (1){ SceCtrlData ctrl; sceCtrlPeekBufferPositive(0, &ctrl, 1); //printf("a\n"); #if SNDPLATFORM == SNDPLAT_LINUX char _command[5]; fgets(_command,5,stdin); _command[strlen(_command)-1]='\0'; printf("%s\n",_command); if (_command[0]=='s'){ printf("attmeptfree.\n"); printf("Stop sound effect.\n"); mlgsnd_stopMusic(_theGoodBGM2); printf("Free sound effect.\n"); mlgsnd_freeMusic(_theGoodBGM2); } if (_command[0]=='p'){ printf("fqwdw\n"); mlgsnd_play(_theGoodBGM2); } #endif #if SNDPLATFORM == SNDPLAT_VITA if (wasJustPressed(ctrl,SCE_CTRL_SQUARE)){ if (_theGoodBGM2!=NULL){ printf("Stop sound effect.\n"); mlgsnd_stopMusic(_theGoodBGM2); printf("Free sound effect.\n"); mlgsnd_freeMusic(_theGoodBGM2); } } if (wasJustPressed(ctrl,SCE_CTRL_CROSS)){ printf("pla\n"); //NathanAudio* _theGoodBGM2 = _mlgsnd_loadAudioFILE(getAdvancedFile(soundarch,"msys20.ogg"),FILE_FORMAT_OGG,1,1); //mlgsnd_setVolume(_theGoodBGM2,50); mlgsnd_play(_theGoodBGM2); } if (wasJustPressed(ctrl,SCE_CTRL_TRIANGLE)){ //sceIoRead(_testfile,readdata,4); //printf("Read: %s\n",readdata); } #endif /* if (wasJustPressed(ctrl,SCE_CTRL_RIGHT)){ if (_newSoundToPlay==_firstPossibleSound){ _newSoundToPlay = _secondPossibleSound; }else{ _newSoundToPlay = _firstPossibleSound; } printf("Will play %s\n",_newSoundToPlay); } if (wasJustPressed(ctrl,SCE_CTRL_LEFT)){ printf("Rewind audio\n"); mlgsnd_restartAudio(_lastSoundEffect); } if (wasJustPressed(ctrl,SCE_CTRL_DOWN)){ _lastSoundEffect->isFirstTime = !_lastSoundEffect->isFirstTime; printf("First time flag is %d\n",_lastSoundEffect->isFirstTime); } if (wasJustPressed(ctrl,SCE_CTRL_TRIANGLE)){ printf("Load sound effect.\n"); _lastSoundEffect = _mlgsnd_loadAudio(_newSoundToPlay,0,1); } if (wasJustPressed(ctrl,SCE_CTRL_SQUARE)){ if (_lastSoundEffect!=NULL){ printf("Free sound effect.\n"); mlgsnd_freeMusic(_lastSoundEffect); } } if (wasJustPressed(ctrl,SCE_CTRL_CIRCLE)){ printf("Stopping...\n"); mlgsnd_stopMusic(_lastSoundEffect); //printf("Done.\n"); } if (wasJustPressed(ctrl,SCE_CTRL_CROSS)){ printf("Starting to play...\n"); mlgsnd_play(_lastSoundEffect); //printf("Done.\n"); } if (wasJustPressed(ctrl,SCE_CTRL_SELECT)){ mlgsnd_restartAudio(_lastSoundEffect); printf("%d\n",mlgsnd_loadMoreData(_lastSoundEffect,0,_lastSoundEffect->unscaledSamples,mlgsnd_getShortSourceSize(_lastSoundEffect))); printAudioDataStart(_lastSoundEffect,0); } if (wasJustPressed(ctrl,SCE_CTRL_START)){ printGuide(); } */ /* if (wasJustPressed(ctrl,SCE_CTRL_UP)){ printf("play sound %p\n",_newSoundToPlay); if (_lastSoundEffect!=NULL){ mlgsnd_freeMusic(_lastSoundEffect); } _lastSoundEffect = _mlgsnd_loadAudio(_newSoundToPlay,0,1); mlgsnd_setVolume(_lastSoundEffect,100); _lastSoundEffect->isFirstTime=0; mlgsnd_play(_lastSoundEffect); if (_newSoundToPlay==_firstPossibleSound){ _newSoundToPlay = _secondPossibleSound; }else{ _newSoundToPlay = _firstPossibleSound; } } if (wasJustPressed(ctrl,SCE_CTRL_SQUARE)){ if (_mlgsnd_initPort(_lastSoundEffect)==0){ return 0; } SceUID mySoundPlayingThreadID = sceKernelCreateThread("SOUNDPLAY", mlgsnd_soundPlayingThread, 0, 0x10000, 0, 0, NULL); _lastSoundEffect->playerThreadId = mySoundPlayingThreadID; void** _newArgs = malloc(sizeof(void*)*2); _newArgs[0]=_lastSoundEffect; _newArgs[1]=(void*)(_lastSoundEffect->audioPort); _lastSoundEffect->quitStatus = NAUDIO_QUITSTATUS_PLAYING; sceKernelStartThread(_lastSoundEffect->playerThreadId,sizeof(void**),&_newArgs); } if (wasJustPressed(ctrl,SCE_CTRL_TRIANGLE)){ mlgsnd_play(_lastSoundEffect); } if (wasJustPressed(ctrl,SCE_CTRL_RIGHT)){ mlgsnd_loadMoreData(_lastSoundEffect,0); } if (wasJustPressed(ctrl,SCE_CTRL_LEFT)){ mlgsnd_restartAudio(_lastSoundEffect); } if (wasJustPressed(ctrl,SCE_CTRL_DOWN)){ _lastSoundEffect->numBuffers=1; _lastSoundEffect->myStreamStatus=STREAMSTATUS_DONTSTREAM; mlgsnd_loadMoreData(_lastSoundEffect,0); mlgsnd_play(_lastSoundEffect); }*/ lastCtrl = ctrl; sceKernelDelayThread(10000); } #if SNDPLATFORM == SNDPLAT_VITA sceKernelExitProcess(0); #endif return 0; } #endif
37.623302
312
0.761736
[ "object" ]
45720d140fcabc3fd330d527f58710f7eb44b7cd
4,146
c
C
contrib/8086/a86/rel.c
doolinius/unix-v7-galileo
403dfb4fbb875095e84763553a952cfbc8d558fd
[ "MIT" ]
null
null
null
contrib/8086/a86/rel.c
doolinius/unix-v7-galileo
403dfb4fbb875095e84763553a952cfbc8d558fd
[ "MIT" ]
null
null
null
contrib/8086/a86/rel.c
doolinius/unix-v7-galileo
403dfb4fbb875095e84763553a952cfbc8d558fd
[ "MIT" ]
null
null
null
#include "mical.h" #include <a.out.h> /* Handle output file processing for a.out files */ FILE *tout; /* text portion of output file */ FILE *dout; /* data portion of output file */ FILE *rtout; /* text relocation commands */ FILE *rdout; /* data relocation commands */ long rtsize; /* size of text relocation area */ long rdsize; /* size of data relocation area */ long Sym_Write(); struct exec filhdr; /* header for a.out files, contains sizes */ /* Initialize files for output and write out the header */ Rel_Header() { char rname[STR_MAX]; /* name of file for relocation commands */ if ((tout = fopen(Rel_name, "w")) == NULL || (dout = fopen(Rel_name, "a")) == NULL) Sys_Error("open on output file %s failed", Rel_name); Concat(rname, Source_name, ".textr"); rtout = fopen(rname, "w"); Concat(rname, Source_name, ".datar"); rdout = fopen(rname, "w"); if (rtout == NULL || rdout == NULL) Sys_Error("open on output file %s failed", rname); fseek(tout, (long)N_TXTOFF(filhdr), 0); /* seek to start of text */ fseek(dout, (long)N_TXTOFF(filhdr)+tsize, 0); rtsize = 0; rdsize = 0; } /* Fix_Rel - Fix up the object file */ Fix_Rel() { register FILE *fin, *fout; register int i; char rname[STR_MAX]; /* name of file for relocation commands */ fclose(rtout); fclose(rdout); fclose(tout); filhdr.a_magic = OMAGIC; filhdr.a_text = tsize; filhdr.a_data = dsize; filhdr.a_bss = bsize; filhdr.a_trsize = rtsize; filhdr.a_drsize = rdsize; filhdr.a_entry = 0; fseek(dout, (long)(N_TXTOFF(filhdr)+tsize+dsize), 0); Concat(rname, Source_name, ".textr"); if ((fin = fopen(rname, "r")) == NULL) Sys_Error("cannot reopen relocation file %s", rname); while ((i = getc(fin)) != EOF) putc(i,dout); fclose(fin); unlink(rname); Concat(rname, Source_name, ".datar"); if ((fin = fopen(rname, "r")) == NULL) Sys_Error("cannot reopen relocation file %s", rname); while ((i = getc(fin)) != EOF) putc(i,dout); fclose(fin); unlink(rname); filhdr.a_syms = Sym_Write(dout); fseek(dout, 0L, 0); fwrite(&filhdr, sizeof(filhdr), 1, dout); } /* Put_Text - Write out text to proper portion of file */ Put_Text(code,length) register char *code; { if (Pass != 2) return; if (Cur_csect == Text_csect) fwrite(code, length, 1, tout); else if (Cur_csect == Data_csect) fwrite(code, length, 1, dout); else return; /* ignore if bss segment */ } /* Pad_Text - Write zero bytes to pad out proper portion of file */ Pad_Text(length) register length; { register FILE *f; if (Pass != 2) return; if (Cur_csect == Text_csect) f = tout; else if (Cur_csect == Data_csect) f = dout; else return; /* ignore if bss segment */ while (length-- > 0) putc(0, f); } /* set up relocation word for operand: * opnd pointer to operand structure * size 0 = byte, 1 = word, 2 = long/address * offset offset into current segment */ Put_Rel(opnd,size,offset,pcrel) struct oper *opnd; int size; long offset; { struct relocation_info r; if (opnd->sym_o == 0) return; /* no relocation */ if (Cur_csect == Text_csect) rtsize += rel_cmd(&r, opnd, size, offset, pcrel, rtout); else if (Cur_csect == Data_csect) rdsize += rel_cmd(&r, opnd, size, offset - tsize, pcrel, rdout); else return; /* just ignore if bss segment */ } /* rel_cmd - Generate a relocation command and output */ rel_cmd(rp, opnd, size, offset, pcrel, file) register struct relocation_info *rp; struct oper *opnd; int size; long offset; FILE *file; { int csid; /* reloc csect identifier */ register struct csect *csp; /* pointer to csect of sym */ register struct sym_bkt *sp; /* pointer to symbol */ sp = opnd->sym_o; csp = sp->csect_s; if (Pass == 2) { rp->r_address = offset; rp->r_pcrel = pcrel; rp->r_length = size; rp->r_extern = 0; if (!(sp->attr_s & S_DEF) && (sp->attr_s & S_EXT)) { rp->r_extern = 1; rp->r_symbolnum = sp->id_s; } else if (csp == Text_csect) rp->r_symbolnum = N_TEXT; else if (csp == Data_csect) rp->r_symbolnum = N_DATA; else if (csp == Bss_csect) rp->r_symbolnum = N_BSS; else Prog_Error(E_RELOCATE); fwrite(rp, sizeof *rp, 1, file); } return(sizeof *rp); }
27.276316
68
0.657984
[ "object" ]
457274d9bdea9852db469c52c2151c248a22a150
70,575
h
C
src/utilities/_hypre_utilities.h
CZHU20/hypre
ff45ecef32c9c92760d3e3e5777bdb1a3f41ea19
[ "ECL-2.0", "Apache-2.0", "MIT" ]
null
null
null
src/utilities/_hypre_utilities.h
CZHU20/hypre
ff45ecef32c9c92760d3e3e5777bdb1a3f41ea19
[ "ECL-2.0", "Apache-2.0", "MIT" ]
null
null
null
src/utilities/_hypre_utilities.h
CZHU20/hypre
ff45ecef32c9c92760d3e3e5777bdb1a3f41ea19
[ "ECL-2.0", "Apache-2.0", "MIT" ]
null
null
null
/*** DO NOT EDIT THIS FILE DIRECTLY (use 'headers' to generate) ***/ #ifndef hypre_UTILITIES_HEADER #define hypre_UTILITIES_HEADER #include "HYPRE_utilities.h" #ifdef HYPRE_USING_OPENMP #include <omp.h> #endif #ifdef __cplusplus extern "C" { #endif /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * General structures and values * *****************************************************************************/ #ifndef hypre_GENERAL_HEADER #define hypre_GENERAL_HEADER /* This allows us to consistently avoid 'int' throughout hypre */ typedef int hypre_int; typedef long int hypre_longint; typedef unsigned int hypre_uint; typedef unsigned long int hypre_ulongint; typedef unsigned long long int hypre_ulonglongint; /* This allows us to consistently avoid 'double' throughout hypre */ typedef double hypre_double; /*-------------------------------------------------------------------------- * Define various functions *--------------------------------------------------------------------------*/ #ifndef hypre_max #define hypre_max(a,b) (((a)<(b)) ? (b) : (a)) #endif #ifndef hypre_min #define hypre_min(a,b) (((a)<(b)) ? (a) : (b)) #endif #ifndef hypre_abs #define hypre_abs(a) (((a)>0) ? (a) : -(a)) #endif #ifndef hypre_round #define hypre_round(x) ( ((x) < 0.0) ? ((HYPRE_Int)(x - 0.5)) : ((HYPRE_Int)(x + 0.5)) ) #endif #ifndef hypre_pow2 #define hypre_pow2(i) ( 1 << (i) ) #endif #endif /* hypre_GENERAL_HEADER */ /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #ifndef hypre_PRINTF_HEADER #define hypre_PRINTF_HEADER #include <stdio.h> /* hypre_printf.c */ // #ifdef HYPRE_BIGINT HYPRE_Int hypre_ndigits( HYPRE_BigInt number ); HYPRE_Int hypre_printf( const char *format , ... ); HYPRE_Int hypre_fprintf( FILE *stream , const char *format, ... ); HYPRE_Int hypre_sprintf( char *s , const char *format, ... ); HYPRE_Int hypre_scanf( const char *format , ... ); HYPRE_Int hypre_fscanf( FILE *stream , const char *format, ... ); HYPRE_Int hypre_sscanf( char *s , const char *format, ... ); // #else // #define hypre_printf printf // #define hypre_fprintf fprintf // #define hypre_sprintf sprintf // #define hypre_scanf scanf // #define hypre_fscanf fscanf // #define hypre_sscanf sscanf // #endif #endif /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #ifndef hypre_ERROR_HEADER #define hypre_ERROR_HEADER #include <assert.h> /*-------------------------------------------------------------------------- * Global variable used in hypre error checking *--------------------------------------------------------------------------*/ extern HYPRE_Int hypre__global_error; #define hypre_error_flag hypre__global_error /*-------------------------------------------------------------------------- * HYPRE error macros *--------------------------------------------------------------------------*/ void hypre_error_handler(const char *filename, HYPRE_Int line, HYPRE_Int ierr, const char *msg); #define hypre_error(IERR) hypre_error_handler(__FILE__, __LINE__, IERR, NULL) #define hypre_error_w_msg(IERR, msg) hypre_error_handler(__FILE__, __LINE__, IERR, msg) #define hypre_error_in_arg(IARG) hypre_error(HYPRE_ERROR_ARG | IARG<<3) #ifdef HYPRE_DEBUG #define hypre_assert(EX) do { if (!(EX)) { hypre_fprintf(stderr, "[%s, %d] hypre_assert failed: %s\n", __FILE__, __LINE__, #EX); hypre_error(1); assert(EX); } } while (0) #else #ifdef __cplusplus /*extern "C++" { template<class T> static inline void hypre_assert( const T& ) { } }*/ #define hypre_assert(EX) do { static_cast<void> (EX); } while (0) #else #define hypre_assert(EX) do { (void) (EX); } while (0) #endif #endif #endif /* hypre_ERROR_HEADER */ /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Fake mpi stubs to generate serial codes without mpi * *****************************************************************************/ #ifndef hypre_MPISTUBS #define hypre_MPISTUBS #ifdef __cplusplus extern "C" { #endif #ifdef HYPRE_SEQUENTIAL /****************************************************************************** * MPI stubs to generate serial codes without mpi *****************************************************************************/ /*-------------------------------------------------------------------------- * Change all MPI names to hypre_MPI names to avoid link conflicts. * * NOTE: MPI_Comm is the only MPI symbol in the HYPRE user interface, * and is defined in `HYPRE_utilities.h'. *--------------------------------------------------------------------------*/ #define MPI_Comm hypre_MPI_Comm #define MPI_Group hypre_MPI_Group #define MPI_Request hypre_MPI_Request #define MPI_Datatype hypre_MPI_Datatype #define MPI_Status hypre_MPI_Status #define MPI_Op hypre_MPI_Op #define MPI_Aint hypre_MPI_Aint #define MPI_Info hypre_MPI_Info #define MPI_COMM_WORLD hypre_MPI_COMM_WORLD #define MPI_COMM_NULL hypre_MPI_COMM_NULL #define MPI_COMM_SELF hypre_MPI_COMM_SELF #define MPI_COMM_TYPE_SHARED hypre_MPI_COMM_TYPE_SHARED #define MPI_BOTTOM hypre_MPI_BOTTOM #define MPI_FLOAT hypre_MPI_FLOAT #define MPI_DOUBLE hypre_MPI_DOUBLE #define MPI_LONG_DOUBLE hypre_MPI_LONG_DOUBLE #define MPI_INT hypre_MPI_INT #define MPI_LONG_LONG_INT hypre_MPI_INT #define MPI_CHAR hypre_MPI_CHAR #define MPI_LONG hypre_MPI_LONG #define MPI_BYTE hypre_MPI_BYTE #define MPI_C_DOUBLE_COMPLEX hypre_MPI_COMPLEX #define MPI_SUM hypre_MPI_SUM #define MPI_MIN hypre_MPI_MIN #define MPI_MAX hypre_MPI_MAX #define MPI_LOR hypre_MPI_LOR #define MPI_LAND hypre_MPI_LAND #define MPI_SUCCESS hypre_MPI_SUCCESS #define MPI_STATUSES_IGNORE hypre_MPI_STATUSES_IGNORE #define MPI_UNDEFINED hypre_MPI_UNDEFINED #define MPI_REQUEST_NULL hypre_MPI_REQUEST_NULL #define MPI_INFO_NULL hypre_MPI_INFO_NULL #define MPI_ANY_SOURCE hypre_MPI_ANY_SOURCE #define MPI_ANY_TAG hypre_MPI_ANY_TAG #define MPI_SOURCE hypre_MPI_SOURCE #define MPI_TAG hypre_MPI_TAG #define MPI_Init hypre_MPI_Init #define MPI_Finalize hypre_MPI_Finalize #define MPI_Abort hypre_MPI_Abort #define MPI_Wtime hypre_MPI_Wtime #define MPI_Wtick hypre_MPI_Wtick #define MPI_Barrier hypre_MPI_Barrier #define MPI_Comm_create hypre_MPI_Comm_create #define MPI_Comm_dup hypre_MPI_Comm_dup #define MPI_Comm_f2c hypre_MPI_Comm_f2c #define MPI_Comm_group hypre_MPI_Comm_group #define MPI_Comm_size hypre_MPI_Comm_size #define MPI_Comm_rank hypre_MPI_Comm_rank #define MPI_Comm_free hypre_MPI_Comm_free #define MPI_Comm_split hypre_MPI_Comm_split #define MPI_Comm_split_type hypre_MPI_Comm_split_type #define MPI_Group_incl hypre_MPI_Group_incl #define MPI_Group_free hypre_MPI_Group_free #define MPI_Address hypre_MPI_Address #define MPI_Get_count hypre_MPI_Get_count #define MPI_Alltoall hypre_MPI_Alltoall #define MPI_Allgather hypre_MPI_Allgather #define MPI_Allgatherv hypre_MPI_Allgatherv #define MPI_Gather hypre_MPI_Gather #define MPI_Gatherv hypre_MPI_Gatherv #define MPI_Scatter hypre_MPI_Scatter #define MPI_Scatterv hypre_MPI_Scatterv #define MPI_Bcast hypre_MPI_Bcast #define MPI_Send hypre_MPI_Send #define MPI_Recv hypre_MPI_Recv #define MPI_Isend hypre_MPI_Isend #define MPI_Irecv hypre_MPI_Irecv #define MPI_Send_init hypre_MPI_Send_init #define MPI_Recv_init hypre_MPI_Recv_init #define MPI_Irsend hypre_MPI_Irsend #define MPI_Startall hypre_MPI_Startall #define MPI_Probe hypre_MPI_Probe #define MPI_Iprobe hypre_MPI_Iprobe #define MPI_Test hypre_MPI_Test #define MPI_Testall hypre_MPI_Testall #define MPI_Wait hypre_MPI_Wait #define MPI_Waitall hypre_MPI_Waitall #define MPI_Waitany hypre_MPI_Waitany #define MPI_Allreduce hypre_MPI_Allreduce #define MPI_Reduce hypre_MPI_Reduce #define MPI_Scan hypre_MPI_Scan #define MPI_Request_free hypre_MPI_Request_free #define MPI_Type_contiguous hypre_MPI_Type_contiguous #define MPI_Type_vector hypre_MPI_Type_vector #define MPI_Type_hvector hypre_MPI_Type_hvector #define MPI_Type_struct hypre_MPI_Type_struct #define MPI_Type_commit hypre_MPI_Type_commit #define MPI_Type_free hypre_MPI_Type_free #define MPI_Op_free hypre_MPI_Op_free #define MPI_Op_create hypre_MPI_Op_create #define MPI_User_function hypre_MPI_User_function #define MPI_Info_create hypre_MPI_Info_create /*-------------------------------------------------------------------------- * Types, etc. *--------------------------------------------------------------------------*/ /* These types have associated creation and destruction routines */ typedef HYPRE_Int hypre_MPI_Comm; typedef HYPRE_Int hypre_MPI_Group; typedef HYPRE_Int hypre_MPI_Request; typedef HYPRE_Int hypre_MPI_Datatype; typedef void (hypre_MPI_User_function) (); typedef struct { HYPRE_Int hypre_MPI_SOURCE; HYPRE_Int hypre_MPI_TAG; } hypre_MPI_Status; typedef HYPRE_Int hypre_MPI_Op; typedef HYPRE_Int hypre_MPI_Aint; typedef HYPRE_Int hypre_MPI_Info; #define hypre_MPI_COMM_SELF 1 #define hypre_MPI_COMM_WORLD 0 #define hypre_MPI_COMM_NULL -1 #define hypre_MPI_COMM_TYPE_SHARED 0 #define hypre_MPI_BOTTOM 0x0 #define hypre_MPI_FLOAT 0 #define hypre_MPI_DOUBLE 1 #define hypre_MPI_LONG_DOUBLE 2 #define hypre_MPI_INT 3 #define hypre_MPI_CHAR 4 #define hypre_MPI_LONG 5 #define hypre_MPI_BYTE 6 #define hypre_MPI_REAL 7 #define hypre_MPI_COMPLEX 8 #define hypre_MPI_SUM 0 #define hypre_MPI_MIN 1 #define hypre_MPI_MAX 2 #define hypre_MPI_LOR 3 #define hypre_MPI_LAND 4 #define hypre_MPI_SUCCESS 0 #define hypre_MPI_STATUSES_IGNORE 0 #define hypre_MPI_UNDEFINED -9999 #define hypre_MPI_REQUEST_NULL 0 #define hypre_MPI_INFO_NULL 0 #define hypre_MPI_ANY_SOURCE 1 #define hypre_MPI_ANY_TAG 1 #else /****************************************************************************** * MPI stubs to do casting of HYPRE_Int and hypre_int correctly *****************************************************************************/ typedef MPI_Comm hypre_MPI_Comm; typedef MPI_Group hypre_MPI_Group; typedef MPI_Request hypre_MPI_Request; typedef MPI_Datatype hypre_MPI_Datatype; typedef MPI_Status hypre_MPI_Status; typedef MPI_Op hypre_MPI_Op; typedef MPI_Aint hypre_MPI_Aint; typedef MPI_Info hypre_MPI_Info; typedef MPI_User_function hypre_MPI_User_function; #define hypre_MPI_COMM_WORLD MPI_COMM_WORLD #define hypre_MPI_COMM_NULL MPI_COMM_NULL #define hypre_MPI_BOTTOM MPI_BOTTOM #define hypre_MPI_COMM_SELF MPI_COMM_SELF #define hypre_MPI_COMM_TYPE_SHARED MPI_COMM_TYPE_SHARED #define hypre_MPI_FLOAT MPI_FLOAT #define hypre_MPI_DOUBLE MPI_DOUBLE #define hypre_MPI_LONG_DOUBLE MPI_LONG_DOUBLE /* HYPRE_MPI_INT is defined in HYPRE_utilities.h */ #define hypre_MPI_INT HYPRE_MPI_INT #define hypre_MPI_CHAR MPI_CHAR #define hypre_MPI_LONG MPI_LONG #define hypre_MPI_BYTE MPI_BYTE /* HYPRE_MPI_REAL is defined in HYPRE_utilities.h */ #define hypre_MPI_REAL HYPRE_MPI_REAL /* HYPRE_MPI_COMPLEX is defined in HYPRE_utilities.h */ #define hypre_MPI_COMPLEX HYPRE_MPI_COMPLEX #define hypre_MPI_SUM MPI_SUM #define hypre_MPI_MIN MPI_MIN #define hypre_MPI_MAX MPI_MAX #define hypre_MPI_LOR MPI_LOR #define hypre_MPI_SUCCESS MPI_SUCCESS #define hypre_MPI_STATUSES_IGNORE MPI_STATUSES_IGNORE #define hypre_MPI_UNDEFINED MPI_UNDEFINED #define hypre_MPI_REQUEST_NULL MPI_REQUEST_NULL #define hypre_MPI_INFO_NULL MPI_INFO_NULL #define hypre_MPI_ANY_SOURCE MPI_ANY_SOURCE #define hypre_MPI_ANY_TAG MPI_ANY_TAG #define hypre_MPI_SOURCE MPI_SOURCE #define hypre_MPI_TAG MPI_TAG #define hypre_MPI_LAND MPI_LAND #endif /****************************************************************************** * Everything below this applies to both ifdef cases above *****************************************************************************/ /*-------------------------------------------------------------------------- * Prototypes *--------------------------------------------------------------------------*/ /* mpistubs.c */ HYPRE_Int hypre_MPI_Init( hypre_int *argc , char ***argv ); HYPRE_Int hypre_MPI_Finalize( void ); HYPRE_Int hypre_MPI_Abort( hypre_MPI_Comm comm , HYPRE_Int errorcode ); HYPRE_Real hypre_MPI_Wtime( void ); HYPRE_Real hypre_MPI_Wtick( void ); HYPRE_Int hypre_MPI_Barrier( hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Comm_create( hypre_MPI_Comm comm , hypre_MPI_Group group , hypre_MPI_Comm *newcomm ); HYPRE_Int hypre_MPI_Comm_dup( hypre_MPI_Comm comm , hypre_MPI_Comm *newcomm ); hypre_MPI_Comm hypre_MPI_Comm_f2c( hypre_int comm ); HYPRE_Int hypre_MPI_Comm_size( hypre_MPI_Comm comm , HYPRE_Int *size ); HYPRE_Int hypre_MPI_Comm_rank( hypre_MPI_Comm comm , HYPRE_Int *rank ); HYPRE_Int hypre_MPI_Comm_free( hypre_MPI_Comm *comm ); HYPRE_Int hypre_MPI_Comm_group( hypre_MPI_Comm comm , hypre_MPI_Group *group ); HYPRE_Int hypre_MPI_Comm_split( hypre_MPI_Comm comm, HYPRE_Int n, HYPRE_Int m, hypre_MPI_Comm * comms ); HYPRE_Int hypre_MPI_Group_incl( hypre_MPI_Group group , HYPRE_Int n , HYPRE_Int *ranks , hypre_MPI_Group *newgroup ); HYPRE_Int hypre_MPI_Group_free( hypre_MPI_Group *group ); HYPRE_Int hypre_MPI_Address( void *location , hypre_MPI_Aint *address ); HYPRE_Int hypre_MPI_Get_count( hypre_MPI_Status *status , hypre_MPI_Datatype datatype , HYPRE_Int *count ); HYPRE_Int hypre_MPI_Alltoall( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Allgather( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Allgatherv( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int *recvcounts , HYPRE_Int *displs , hypre_MPI_Datatype recvtype , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Gather( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Gatherv( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int *recvcounts , HYPRE_Int *displs , hypre_MPI_Datatype recvtype , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Scatter( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Scatterv( void *sendbuf , HYPRE_Int *sendcounts , HYPRE_Int *displs, hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Bcast( void *buffer , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Send( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Recv( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int source , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Isend( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Irecv( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int source , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Send_init( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Recv_init( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Irsend( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Startall( HYPRE_Int count , hypre_MPI_Request *array_of_requests ); HYPRE_Int hypre_MPI_Probe( HYPRE_Int source , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Iprobe( HYPRE_Int source , HYPRE_Int tag , hypre_MPI_Comm comm , HYPRE_Int *flag , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Test( hypre_MPI_Request *request , HYPRE_Int *flag , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Testall( HYPRE_Int count , hypre_MPI_Request *array_of_requests , HYPRE_Int *flag , hypre_MPI_Status *array_of_statuses ); HYPRE_Int hypre_MPI_Wait( hypre_MPI_Request *request , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Waitall( HYPRE_Int count , hypre_MPI_Request *array_of_requests , hypre_MPI_Status *array_of_statuses ); HYPRE_Int hypre_MPI_Waitany( HYPRE_Int count , hypre_MPI_Request *array_of_requests , HYPRE_Int *index , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Allreduce( void *sendbuf , void *recvbuf , HYPRE_Int count , hypre_MPI_Datatype datatype , hypre_MPI_Op op , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Reduce( void *sendbuf , void *recvbuf , HYPRE_Int count , hypre_MPI_Datatype datatype , hypre_MPI_Op op , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Scan( void *sendbuf , void *recvbuf , HYPRE_Int count , hypre_MPI_Datatype datatype , hypre_MPI_Op op , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Request_free( hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Type_contiguous( HYPRE_Int count , hypre_MPI_Datatype oldtype , hypre_MPI_Datatype *newtype ); HYPRE_Int hypre_MPI_Type_vector( HYPRE_Int count , HYPRE_Int blocklength , HYPRE_Int stride , hypre_MPI_Datatype oldtype , hypre_MPI_Datatype *newtype ); HYPRE_Int hypre_MPI_Type_hvector( HYPRE_Int count , HYPRE_Int blocklength , hypre_MPI_Aint stride , hypre_MPI_Datatype oldtype , hypre_MPI_Datatype *newtype ); HYPRE_Int hypre_MPI_Type_struct( HYPRE_Int count , HYPRE_Int *array_of_blocklengths , hypre_MPI_Aint *array_of_displacements , hypre_MPI_Datatype *array_of_types , hypre_MPI_Datatype *newtype ); HYPRE_Int hypre_MPI_Type_commit( hypre_MPI_Datatype *datatype ); HYPRE_Int hypre_MPI_Type_free( hypre_MPI_Datatype *datatype ); HYPRE_Int hypre_MPI_Op_free( hypre_MPI_Op *op ); HYPRE_Int hypre_MPI_Op_create( hypre_MPI_User_function *function , hypre_int commute , hypre_MPI_Op *op ); #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_DEVICE_OPENMP) HYPRE_Int hypre_MPI_Comm_split_type(hypre_MPI_Comm comm, HYPRE_Int split_type, HYPRE_Int key, hypre_MPI_Info info, hypre_MPI_Comm *newcomm); HYPRE_Int hypre_MPI_Info_create(hypre_MPI_Info *info); HYPRE_Int hypre_MPI_Info_free( hypre_MPI_Info *info ); #endif #ifdef __cplusplus } #endif #endif /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #ifndef HYPRE_SMP_HEADER #define HYPRE_SMP_HEADER #endif #define HYPRE_SMP_SCHEDULE schedule(static) /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header file for memory management utilities * * The abstract memory model has a Host (think CPU) and a Device (think GPU) and * three basic types of memory management utilities: * * 1. Malloc(..., location) * location=LOCATION_DEVICE - malloc memory on the device * location=LOCATION_HOST - malloc memory on the host * 2. MemCopy(..., method) * method=HOST_TO_DEVICE - copy from host to device * method=DEVICE_TO_HOST - copy from device to host * method=DEVICE_TO_DEVICE - copy from device to device * 3. SetExecutionMode * location=LOCATION_DEVICE - execute on the device * location=LOCATION_HOST - execute on the host * * Although the abstract model does not explicitly reflect a managed memory * model (i.e., unified memory), it can support it. Here is a summary of how * the abstract model would be mapped to specific hardware scenarios: * * Not using a device, not using managed memory * Malloc(..., location) * location=LOCATION_DEVICE - host malloc e.g., malloc * location=LOCATION_HOST - host malloc e.g., malloc * MemoryCopy(..., locTo,locFrom) * locTo=LOCATION_HOST, locFrom=LOCATION_DEVICE - copy from host to host e.g., memcpy * locTo=LOCATION_DEVICE, locFrom=LOCATION_HOST - copy from host to host e.g., memcpy * locTo=LOCATION_DEVICE, locFrom=LOCATION_DEVICE - copy from host to host e.g., memcpy * SetExecutionMode * location=LOCATION_DEVICE - execute on the host * location=LOCATION_HOST - execute on the host * * Using a device, not using managed memory * Malloc(..., location) * location=LOCATION_DEVICE - device malloc e.g., cudaMalloc * location=LOCATION_HOST - host malloc e.g., malloc * MemoryCopy(..., locTo,locFrom) * locTo=LOCATION_HOST, locFrom=LOCATION_DEVICE - copy from device to host e.g., cudaMemcpy * locTo=LOCATION_DEVICE, locFrom=LOCATION_HOST - copy from host to device e.g., cudaMemcpy * locTo=LOCATION_DEVICE, locFrom=LOCATION_DEVICE - copy from device to device e.g., cudaMemcpy * SetExecutionMode * location=LOCATION_DEVICE - execute on the device * location=LOCATION_HOST - execute on the host * * Using a device, using managed memory * Malloc(..., location) * location=LOCATION_DEVICE - managed malloc e.g., cudaMallocManaged * location=LOCATION_HOST - host malloc e.g., malloc * MemoryCopy(..., locTo,locFrom) * locTo=LOCATION_HOST, locFrom=LOCATION_DEVICE - copy from device to host e.g., cudaMallocManaged * locTo=LOCATION_DEVICE, locFrom=LOCATION_HOST - copy from host to device e.g., cudaMallocManaged * locTo=LOCATION_DEVICE, locFrom=LOCATION_DEVICE - copy from device to device e.g., cudaMallocManaged * SetExecutionMode * location=LOCATION_DEVICE - execute on the device * location=LOCATION_HOST - execute on the host * *****************************************************************************/ #ifndef hypre_MEMORY_HEADER #define hypre_MEMORY_HEADER #include <stdio.h> #include <stdlib.h> /* stringification: * _Pragma(string-literal), so we need to cast argument to a string * The three dots as last argument of the macro tells compiler that this is a variadic macro. * I.e. this is a macro that receives variable number of arguments. */ #define HYPRE_STR(...) #__VA_ARGS__ #define HYPRE_XSTR(...) HYPRE_STR(__VA_ARGS__) //#define HYPRE_USING_MEMORY_TRACKER #ifdef __cplusplus extern "C" { #endif typedef enum _hypre_MemoryLocation { hypre_MEMORY_UNDEFINED = -1, hypre_MEMORY_HOST , hypre_MEMORY_HOST_PINNED , hypre_MEMORY_DEVICE , hypre_MEMORY_UNIFIED } hypre_MemoryLocation; /*------------------------------------------------------- * hypre_GetActualMemLocation * return actual location based on the selected memory model *-------------------------------------------------------*/ static inline hypre_MemoryLocation hypre_GetActualMemLocation(HYPRE_MemoryLocation location) { if (location == HYPRE_MEMORY_HOST) { return hypre_MEMORY_HOST; } if (location == HYPRE_MEMORY_DEVICE) { #if defined(HYPRE_USING_HOST_MEMORY) return hypre_MEMORY_HOST; #elif defined(HYPRE_USING_DEVICE_MEMORY) return hypre_MEMORY_DEVICE; #elif defined(HYPRE_USING_UNIFIED_MEMORY) return hypre_MEMORY_UNIFIED; #else #error Wrong HYPRE memory setting. #endif } return hypre_MEMORY_UNDEFINED; } #ifdef HYPRE_USING_MEMORY_TRACKER #ifdef __cplusplus extern "C++" { #endif #include <vector> struct hypre_memory_tracker_t { char _action[16]; void *_ptr; size_t _nbytes; hypre_MemoryLocation _memory_location; char _filename[256]; char _function[256]; HYPRE_Int _line; hypre_memory_tracker_t(const char *action, void *ptr, size_t nbytes, hypre_MemoryLocation memory_location, const char *filename, const char *function, HYPRE_Int line) { sprintf(_action, "%s", action); _ptr = ptr; _nbytes = nbytes; _memory_location = memory_location; sprintf(_filename, "%s", filename); sprintf(_function, "%s", function); _line = line; } void print() { printf("%8s %16p %10ld %d %32s %64s %d\n", _action, _ptr, _nbytes, _memory_location, _filename, _function, _line); } }; extern std::vector<hypre_memory_tracker_t> hypre_memory_tracker; static inline void hypre_MemoryTrackerInsert(struct hypre_memory_tracker_t const &memory) { if (memory._memory_location != hypre_MEMORY_HOST) /* if we only want to track GPU memory */ { hypre_memory_tracker.push_back(memory); } } #ifdef __cplusplus } #endif /* These Allocs are with memory tracker, for debug */ #define hypre_TAlloc(type, count, location) \ ( \ { \ void *ptr = hypre_MAlloc((size_t)(sizeof(type) * (count)), location); \ hypre_MemoryTrackerInsert( hypre_memory_tracker_t("malloc", ptr, sizeof(type)*(count), hypre_GetActualMemLocation(location), \ __FILE__, __func__, __LINE__) ); \ (type *) ptr; \ } \ ) #define _hypre_TAlloc(type, count, location) \ ( \ { \ void *ptr = _hypre_MAlloc((size_t)(sizeof(type) * (count)), location); \ hypre_MemoryTrackerInsert( hypre_memory_tracker_t("malloc", ptr, sizeof(type)*(count), location, __FILE__, __func__, __LINE__) ); \ (type *) ptr; \ } \ ) #define hypre_CTAlloc(type, count, location) \ ( \ { \ void *ptr = hypre_CAlloc((size_t)(count), (size_t)sizeof(type), location); \ hypre_MemoryTrackerInsert( hypre_memory_tracker_t("calloc", ptr, sizeof(type)*(count), hypre_GetActualMemLocation(location), \ __FILE__, __func__, __LINE__) ); \ (type *) ptr; \ } \ ) #define hypre_TReAlloc(ptr, type, count, location) \ ( \ { \ (type *) hypre_ReAlloc((char *)ptr, (size_t)(sizeof(type) * (count)), location); \ } \ ) #define hypre_TReAlloc_v2(ptr, old_type, old_count, new_type, new_count, location) \ ( \ { \ hypre_MemoryTrackerInsert( hypre_memory_tracker_t("rfree", ptr, sizeof(old_type)*(old_count), hypre_GetActualMemLocation(location), \ __FILE__, __func__, __LINE__) ); \ void *new_ptr = hypre_ReAlloc_v2((char *)ptr, (size_t)(sizeof(old_type)*(old_count)), (size_t)(sizeof(new_type)*(new_count)), location); \ hypre_MemoryTrackerInsert( hypre_memory_tracker_t("rmalloc", new_ptr, sizeof(new_type)*(new_count), hypre_GetActualMemLocation(location), \ __FILE__, __func__, __LINE__) ); \ (new_type *) new_ptr; \ } \ ) #define hypre_TMemcpy(dst, src, type, count, locdst, locsrc) \ ( \ { \ hypre_Memcpy((void *)(dst), (void *)(src), (size_t)(sizeof(type) * (count)), locdst, locsrc); \ } \ ) #define hypre_TFree(ptr, location) \ ( \ { \ hypre_MemoryTrackerInsert( hypre_memory_tracker_t("free", ptr, 0, hypre_GetActualMemLocation(location), \ __FILE__, __func__, __LINE__) ); \ hypre_Free((void *)ptr, location); \ ptr = NULL; \ } \ ) #define _hypre_TFree(ptr, location) \ ( \ { \ hypre_MemoryTrackerInsert( hypre_memory_tracker_t("free", ptr, 0, location, __FILE__, __func__, __LINE__) ); \ _hypre_Free((void *)ptr, location); \ ptr = NULL; \ } \ ) #else /* #ifdef HYPRE_USING_MEMORY_TRACKER */ #define hypre_TAlloc(type, count, location) \ ( (type *) hypre_MAlloc((size_t)(sizeof(type) * (count)), location) ) #define _hypre_TAlloc(type, count, location) \ ( (type *) _hypre_MAlloc((size_t)(sizeof(type) * (count)), location) ) #define hypre_CTAlloc(type, count, location) \ ( (type *) hypre_CAlloc((size_t)(count), (size_t)sizeof(type), location) ) #define hypre_TReAlloc(ptr, type, count, location) \ ( (type *) hypre_ReAlloc((char *)ptr, (size_t)(sizeof(type) * (count)), location) ) #define hypre_TReAlloc_v2(ptr, old_type, old_count, new_type, new_count, location) \ ( (new_type *) hypre_ReAlloc_v2((char *)ptr, (size_t)(sizeof(old_type)*(old_count)), (size_t)(sizeof(new_type)*(new_count)), location) ) #define hypre_TMemcpy(dst, src, type, count, locdst, locsrc) \ (hypre_Memcpy((void *)(dst), (void *)(src), (size_t)(sizeof(type) * (count)), locdst, locsrc)) #define hypre_TFree(ptr, location) \ ( hypre_Free((void *)ptr, location), ptr = NULL ) #define _hypre_TFree(ptr, location) \ ( _hypre_Free((void *)ptr, location), ptr = NULL ) #endif /* #ifdef HYPRE_USING_MEMORY_TRACKER */ /*-------------------------------------------------------------------------- * Prototypes *--------------------------------------------------------------------------*/ /* hypre_memory.c */ void * hypre_Memset(void *ptr, HYPRE_Int value, size_t num, HYPRE_MemoryLocation location); void hypre_MemPrefetch(void *ptr, size_t size, HYPRE_MemoryLocation location); void * hypre_MAlloc(size_t size, HYPRE_MemoryLocation location); void * hypre_CAlloc( size_t count, size_t elt_size, HYPRE_MemoryLocation location); void hypre_Free(void *ptr, HYPRE_MemoryLocation location); void hypre_Memcpy(void *dst, void *src, size_t size, HYPRE_MemoryLocation loc_dst, HYPRE_MemoryLocation loc_src); void * hypre_ReAlloc(void *ptr, size_t size, HYPRE_MemoryLocation location); void * hypre_ReAlloc_v2(void *ptr, size_t old_size, size_t new_size, HYPRE_MemoryLocation location); void * _hypre_MAlloc(size_t size, hypre_MemoryLocation location); void _hypre_Free(void *ptr, hypre_MemoryLocation location); HYPRE_ExecutionPolicy hypre_GetExecPolicy1(HYPRE_MemoryLocation location); HYPRE_ExecutionPolicy hypre_GetExecPolicy2(HYPRE_MemoryLocation location1, HYPRE_MemoryLocation location2); HYPRE_Int hypre_GetPointerLocation(const void *ptr, hypre_MemoryLocation *memory_location); HYPRE_Int hypre_PrintMemoryTracker(); HYPRE_Int hypre_SetCubMemPoolSize( hypre_uint bin_growth, hypre_uint min_bin, hypre_uint max_bin, size_t max_cached_bytes ); /* memory_dmalloc.c */ HYPRE_Int hypre_InitMemoryDebugDML( HYPRE_Int id ); HYPRE_Int hypre_FinalizeMemoryDebugDML( void ); char *hypre_MAllocDML( HYPRE_Int size , char *file , HYPRE_Int line ); char *hypre_CAllocDML( HYPRE_Int count , HYPRE_Int elt_size , char *file , HYPRE_Int line ); char *hypre_ReAllocDML( char *ptr , HYPRE_Int size , char *file , HYPRE_Int line ); void hypre_FreeDML( char *ptr , char *file , HYPRE_Int line ); #ifdef __cplusplus } #endif #endif /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #ifndef HYPRE_OMP_DEVICE_H #define HYPRE_OMP_DEVICE_H #if defined(HYPRE_USING_DEVICE_OPENMP) #include "omp.h" /* OpenMP 4.5 device memory management */ extern HYPRE_Int hypre__global_offload; extern HYPRE_Int hypre__offload_device_num; extern HYPRE_Int hypre__offload_host_num; /* stats */ extern size_t hypre__target_allc_count; extern size_t hypre__target_free_count; extern size_t hypre__target_allc_bytes; extern size_t hypre__target_free_bytes; extern size_t hypre__target_htod_count; extern size_t hypre__target_dtoh_count; extern size_t hypre__target_htod_bytes; extern size_t hypre__target_dtoh_bytes; /* CHECK MODE: check if offloading has effect (turned on when configured with --enable-debug) * if we ``enter'' an address, it should not exist in device [o.w NO EFFECT] * if we ``exit'' or ''update'' an address, it should exist in device [o.w ERROR] * hypre__offload_flag: 0 == OK; 1 == WRONG */ #ifdef HYPRE_DEVICE_OPENMP_CHECK #define HYPRE_OFFLOAD_FLAG(devnum, hptr, type) HYPRE_Int hypre__offload_flag = (type[1] == 'n') == omp_target_is_present(hptr, devnum); #else #define HYPRE_OFFLOAD_FLAG(...) HYPRE_Int hypre__offload_flag = 0; /* non-debug mode, always OK */ #endif /* OMP 4.5 offloading macro */ #define hypre_omp_device_offload(devnum, hptr, datatype, offset, count, type1, type2) \ {\ /* devnum: device number \ * hptr: host poiter \ * datatype \ * type1: ``e(n)ter'', ''e(x)it'', or ``u(p)date'' \ * type2: ``(a)lloc'', ``(t)o'', ``(d)elete'', ''(f)rom'' \ */ \ datatype *hypre__offload_hptr = (datatype *) hptr; \ /* if hypre__global_offload == 0, or * hptr (host pointer) == NULL, * this offload will be IGNORED */ \ if (hypre__global_offload && hypre__offload_hptr != NULL) { \ /* offloading offset and size (in datatype) */ \ size_t hypre__offload_offset = offset, hypre__offload_size = count; \ /* in the CHECK mode, we test if this offload has effect */ \ HYPRE_OFFLOAD_FLAG(devnum, hypre__offload_hptr, type1) \ if (hypre__offload_flag) { \ printf("[!NO Effect! %s %d] device %d target: %6s %6s, data %p, [%ld:%ld]\n", __FILE__, __LINE__, devnum, type1, type2, (void *)hypre__offload_hptr, hypre__offload_offset, hypre__offload_size); exit(0); \ } else { \ size_t offload_bytes = count * sizeof(datatype); \ /* printf("[ %s %d] device %d target: %6s %6s, data %p, [%d:%d]\n", __FILE__, __LINE__, devnum, type1, type2, (void *)hypre__offload_hptr, hypre__offload_offset, hypre__offload_size); */ \ if (type1[1] == 'n' && type2[0] == 't') { \ /* enter to */\ hypre__target_allc_count ++; \ hypre__target_allc_bytes += offload_bytes; \ hypre__target_htod_count ++; \ hypre__target_htod_bytes += offload_bytes; \ _Pragma (HYPRE_XSTR(omp target enter data map(to:hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \ } else if (type1[1] == 'n' && type2[0] == 'a') { \ /* enter alloc */ \ hypre__target_allc_count ++; \ hypre__target_allc_bytes += offload_bytes; \ _Pragma (HYPRE_XSTR(omp target enter data map(alloc:hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \ } else if (type1[1] == 'x' && type2[0] == 'd') { \ /* exit delete */\ hypre__target_free_count ++; \ hypre__target_free_bytes += offload_bytes; \ _Pragma (HYPRE_XSTR(omp target exit data map(delete:hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \ } else if (type1[1] == 'x' && type2[0] == 'f') {\ /* exit from */ \ hypre__target_free_count ++; \ hypre__target_free_bytes += offload_bytes; \ hypre__target_dtoh_count ++; \ hypre__target_dtoh_bytes += offload_bytes; \ _Pragma (HYPRE_XSTR(omp target exit data map(from:hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \ } else if (type1[1] == 'p' && type2[0] == 't') { \ /* update to */ \ hypre__target_htod_count ++; \ hypre__target_htod_bytes += offload_bytes; \ _Pragma (HYPRE_XSTR(omp target update to(hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \ } else if (type1[1] == 'p' && type2[0] == 'f') {\ /* update from */ \ hypre__target_dtoh_count ++; \ hypre__target_dtoh_bytes += offload_bytes; \ _Pragma (HYPRE_XSTR(omp target update from(hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \ } else {\ printf("error: unrecognized offloading type combination!\n"); exit(-1); \ } \ } \ } \ } HYPRE_Int HYPRE_OMPOffload(HYPRE_Int device, void *ptr, size_t num, const char *type1, const char *type2); HYPRE_Int HYPRE_OMPPtrIsMapped(void *p, HYPRE_Int device_num); HYPRE_Int HYPRE_OMPOffloadOn(); HYPRE_Int HYPRE_OMPOffloadOff(); HYPRE_Int HYPRE_OMPOffloadStatPrint(); #endif /* HYPRE_USING_DEVICE_OPENMP */ #endif /* HYPRE_OMP_DEVICE_H */ /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #ifndef hypre_THREADING_HEADER #define hypre_THREADING_HEADER #ifdef HYPRE_USING_OPENMP HYPRE_Int hypre_NumThreads( void ); HYPRE_Int hypre_NumActiveThreads( void ); HYPRE_Int hypre_GetThreadNum( void ); void hypre_SetNumThreads(HYPRE_Int nt); #else #define hypre_NumThreads() 1 #define hypre_NumActiveThreads() 1 #define hypre_GetThreadNum() 0 #define hypre_SetNumThreads(x) #endif void hypre_GetSimpleThreadPartition( HYPRE_Int *begin, HYPRE_Int *end, HYPRE_Int n ); #endif /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header file for doing timing * *****************************************************************************/ #ifndef HYPRE_TIMING_HEADER #define HYPRE_TIMING_HEADER #include <stdlib.h> #include <stdio.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif /*-------------------------------------------------------------------------- * Prototypes for low-level timing routines *--------------------------------------------------------------------------*/ /* timer.c */ HYPRE_Real time_getWallclockSeconds( void ); HYPRE_Real time_getCPUSeconds( void ); HYPRE_Real time_get_wallclock_seconds_( void ); HYPRE_Real time_get_cpu_seconds_( void ); /*-------------------------------------------------------------------------- * With timing off *--------------------------------------------------------------------------*/ #ifndef HYPRE_TIMING #define hypre_InitializeTiming(name) 0 #define hypre_FinalizeTiming(index) #define hypre_IncFLOPCount(inc) #define hypre_BeginTiming(i) #define hypre_EndTiming(i) #define hypre_PrintTiming(heading, comm) #define hypre_ClearTiming() /*-------------------------------------------------------------------------- * With timing on *--------------------------------------------------------------------------*/ #else /*------------------------------------------------------- * Global timing structure *-------------------------------------------------------*/ typedef struct { HYPRE_Real *wall_time; HYPRE_Real *cpu_time; HYPRE_Real *flops; char **name; HYPRE_Int *state; /* boolean flag to allow for recursive timing */ HYPRE_Int *num_regs; /* count of how many times a name is registered */ HYPRE_Int num_names; HYPRE_Int size; HYPRE_Real wall_count; HYPRE_Real CPU_count; HYPRE_Real FLOP_count; } hypre_TimingType; #ifdef HYPRE_TIMING_GLOBALS hypre_TimingType *hypre_global_timing = NULL; #else extern hypre_TimingType *hypre_global_timing; #endif /*------------------------------------------------------- * Accessor functions *-------------------------------------------------------*/ #define hypre_TimingWallTime(i) (hypre_global_timing -> wall_time[(i)]) #define hypre_TimingCPUTime(i) (hypre_global_timing -> cpu_time[(i)]) #define hypre_TimingFLOPS(i) (hypre_global_timing -> flops[(i)]) #define hypre_TimingName(i) (hypre_global_timing -> name[(i)]) #define hypre_TimingState(i) (hypre_global_timing -> state[(i)]) #define hypre_TimingNumRegs(i) (hypre_global_timing -> num_regs[(i)]) #define hypre_TimingWallCount (hypre_global_timing -> wall_count) #define hypre_TimingCPUCount (hypre_global_timing -> CPU_count) #define hypre_TimingFLOPCount (hypre_global_timing -> FLOP_count) /*------------------------------------------------------- * Prototypes *-------------------------------------------------------*/ /* timing.c */ HYPRE_Int hypre_InitializeTiming( const char *name ); HYPRE_Int hypre_FinalizeTiming( HYPRE_Int time_index ); HYPRE_Int hypre_IncFLOPCount( HYPRE_BigInt inc ); HYPRE_Int hypre_BeginTiming( HYPRE_Int time_index ); HYPRE_Int hypre_EndTiming( HYPRE_Int time_index ); HYPRE_Int hypre_ClearTiming( void ); HYPRE_Int hypre_PrintTiming( const char *heading , MPI_Comm comm ); #endif #ifdef __cplusplus } #endif #endif /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header file link lists * *****************************************************************************/ #ifndef HYPRE_LINKLIST_HEADER #define HYPRE_LINKLIST_HEADER #include <stdlib.h> #include <stdio.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif struct double_linked_list { HYPRE_Int data; struct double_linked_list *next_elt; struct double_linked_list *prev_elt; HYPRE_Int head; HYPRE_Int tail; }; typedef struct double_linked_list hypre_ListElement; typedef hypre_ListElement *hypre_LinkList; #ifdef __cplusplus } #endif #endif /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #ifndef hypre_EXCHANGE_DATA_HEADER #define hypre_EXCHANGE_DATA_HEADER #define hypre_BinaryTreeParentId(tree) (tree->parent_id) #define hypre_BinaryTreeNumChild(tree) (tree->num_child) #define hypre_BinaryTreeChildIds(tree) (tree->child_id) #define hypre_BinaryTreeChildId(tree, i) (tree->child_id[i]) typedef struct { HYPRE_Int parent_id; HYPRE_Int num_child; HYPRE_Int *child_id; } hypre_BinaryTree; /* In the fill_response() function the user needs to set the recv__buf and the response_message_size. Memory of size send_response_storage has been alllocated for the send_buf (in exchange_data) - if more is needed, then realloc and adjust the send_response_storage. The realloc amount should be storage+overhead. If the response is an empty "confirmation" message, then set response_message_size =0 (and do not modify the send_buf) */ typedef struct { HYPRE_Int (*fill_response)(void* recv_buf, HYPRE_Int contact_size, HYPRE_Int contact_proc, void* response_obj, MPI_Comm comm, void** response_buf, HYPRE_Int* response_message_size); HYPRE_Int send_response_overhead; /*set by exchange data */ HYPRE_Int send_response_storage; /*storage allocated for send_response_buf*/ void *data1; /*data fields user may want to access in fill_response */ void *data2; } hypre_DataExchangeResponse; HYPRE_Int hypre_CreateBinaryTree(HYPRE_Int, HYPRE_Int, hypre_BinaryTree*); HYPRE_Int hypre_DestroyBinaryTree(hypre_BinaryTree*); HYPRE_Int hypre_DataExchangeList(HYPRE_Int num_contacts, HYPRE_Int *contact_proc_list, void *contact_send_buf, HYPRE_Int *contact_send_buf_starts, HYPRE_Int contact_obj_size, HYPRE_Int response_obj_size, hypre_DataExchangeResponse *response_obj, HYPRE_Int max_response_size, HYPRE_Int rnum, MPI_Comm comm, void **p_response_recv_buf, HYPRE_Int **p_response_recv_buf_starts); #endif /* end of header */ /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header file for Caliper instrumentation macros * *****************************************************************************/ #ifndef CALIPER_INSTRUMENTATION_HEADER #define CALIPER_INSTRUMENTATION_HEADER #include "HYPRE_config.h" #ifdef HYPRE_USING_CALIPER #include <caliper/cali.h> char hypre__levelname[16]; #define HYPRE_ANNOTATE_FUNC_BEGIN CALI_MARK_FUNCTION_BEGIN #define HYPRE_ANNOTATE_FUNC_END CALI_MARK_FUNCTION_END #define HYPRE_ANNOTATE_LOOP_BEGIN(id, str) CALI_MARK_LOOP_BEGIN(id, str) #define HYPRE_ANNOTATE_LOOP_END(id) CALI_MARK_LOOP_END(id) #define HYPRE_ANNOTATE_ITER_BEGIN(id, it) CALI_MARK_ITERATION_BEGIN(id, it) #define HYPRE_ANNOTATE_ITER_END(id) CALI_MARK_ITERATION_END(id) #define HYPRE_ANNOTATE_MGLEVEL_BEGIN(lvl)\ {\ hypre_sprintf(hypre__levelname, "MG level %d", lvl);\ CALI_MARK_BEGIN(hypre__levelname);\ } #define HYPRE_ANNOTATE_MGLEVEL_END(lvl)\ {\ hypre_sprintf(hypre__levelname, "MG level %d", lvl);\ CALI_MARK_END(hypre__levelname);\ } #else #define HYPRE_ANNOTATE_FUNC_BEGIN #define HYPRE_ANNOTATE_FUNC_END #define HYPRE_ANNOTATE_LOOP_BEGIN(id, str) #define HYPRE_ANNOTATE_LOOP_END(id) #define HYPRE_ANNOTATE_ITER_BEGIN(id, it) #define HYPRE_ANNOTATE_ITER_END(id) #define HYPRE_ANNOTATE_MGLEVEL_BEGIN(lvl) #define HYPRE_ANNOTATE_MGLEVEL_END(lvl) #endif #endif /* CALIPER_INSTRUMENTATION_HEADER */ /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * General structures and values * *****************************************************************************/ #ifndef HYPRE_HANDLE_H #define HYPRE_HANDLE_H //#ifdef __cplusplus //extern "C++" { //#endif struct hypre_CudaData; typedef struct hypre_CudaData hypre_CudaData; typedef struct { HYPRE_Int hypre_error; HYPRE_MemoryLocation memory_location; HYPRE_ExecutionPolicy default_exec_policy; HYPRE_ExecutionPolicy struct_exec_policy; #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_DEVICE_OPENMP) hypre_CudaData *cuda_data; #endif } hypre_Handle; /* accessor macros to hypre_Handle */ #define hypre_HandleMemoryLocation(hypre_handle) ((hypre_handle) -> memory_location) #define hypre_HandleDefaultExecPolicy(hypre_handle) ((hypre_handle) -> default_exec_policy) #define hypre_HandleStructExecPolicy(hypre_handle) ((hypre_handle) -> struct_exec_policy) #define hypre_HandleCudaData(hypre_handle) ((hypre_handle) -> cuda_data) #define hypre_HandleCurandGenerator(hypre_handle) hypre_CudaDataCurandGenerator(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleCublasHandle(hypre_handle) hypre_CudaDataCublasHandle(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleCusparseHandle(hypre_handle) hypre_CudaDataCusparseHandle(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleCusparseMatDescr(hypre_handle) hypre_CudaDataCusparseMatDescr(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleCudaComputeStream(hypre_handle) hypre_CudaDataCudaComputeStream(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleCubBinGrowth(hypre_handle) hypre_CudaDataCubBinGrowth(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleCubMinBin(hypre_handle) hypre_CudaDataCubMinBin(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleCubMaxBin(hypre_handle) hypre_CudaDataCubMaxBin(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleCubMaxCachedBytes(hypre_handle) hypre_CudaDataCubMaxCachedBytes(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleCubDevAllocator(hypre_handle) hypre_CudaDataCubDevAllocator(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleCubUvmAllocator(hypre_handle) hypre_CudaDataCubUvmAllocator(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleCudaDevice(hypre_handle) hypre_CudaDataCudaDevice(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleCudaComputeStreamNum(hypre_handle) hypre_CudaDataCudaComputeStreamNum(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleCudaComputeStreamSync(hypre_handle) hypre_CudaDataCudaComputeStreamSync(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleCudaReduceBuffer(hypre_handle) hypre_CudaDataCudaReduceBuffer(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleStructCommRecvBuffer(hypre_handle) hypre_CudaDataStructCommRecvBuffer(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleStructCommSendBuffer(hypre_handle) hypre_CudaDataStructCommSendBuffer(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleStructCommRecvBufferSize(hypre_handle) hypre_CudaDataStructCommRecvBufferSize(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleStructCommSendBufferSize(hypre_handle) hypre_CudaDataStructCommSendBufferSize(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleSpgemmUseCusparse(hypre_handle) hypre_CudaDataSpgemmUseCusparse(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleSpgemmNumPasses(hypre_handle) hypre_CudaDataSpgemmNumPasses(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleSpgemmRownnzEstimateMethod(hypre_handle) hypre_CudaDataSpgemmRownnzEstimateMethod(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleSpgemmRownnzEstimateNsamples(hypre_handle) hypre_CudaDataSpgemmRownnzEstimateNsamples(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleSpgemmRownnzEstimateMultFactor(hypre_handle) hypre_CudaDataSpgemmRownnzEstimateMultFactor(hypre_HandleCudaData(hypre_handle)) #define hypre_HandleSpgemmHashType(hypre_handle) hypre_CudaDataSpgemmHashType(hypre_HandleCudaData(hypre_handle)) //#ifdef __cplusplus //} //#endif #endif /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /* amg_linklist.c */ void hypre_dispose_elt ( hypre_LinkList element_ptr ); void hypre_remove_point ( hypre_LinkList *LoL_head_ptr , hypre_LinkList *LoL_tail_ptr , HYPRE_Int measure , HYPRE_Int index , HYPRE_Int *lists , HYPRE_Int *where ); hypre_LinkList hypre_create_elt ( HYPRE_Int Item ); void hypre_enter_on_lists ( hypre_LinkList *LoL_head_ptr , hypre_LinkList *LoL_tail_ptr , HYPRE_Int measure , HYPRE_Int index , HYPRE_Int *lists , HYPRE_Int *where ); /* binsearch.c */ HYPRE_Int hypre_BinarySearch ( HYPRE_Int *list , HYPRE_Int value , HYPRE_Int list_length ); HYPRE_Int hypre_BigBinarySearch ( HYPRE_BigInt *list , HYPRE_BigInt value , HYPRE_Int list_length ); HYPRE_Int hypre_BinarySearch2 ( HYPRE_Int *list , HYPRE_Int value , HYPRE_Int low , HYPRE_Int high , HYPRE_Int *spot ); HYPRE_Int *hypre_LowerBound( HYPRE_Int *first, HYPRE_Int *last, HYPRE_Int value ); HYPRE_BigInt *hypre_BigLowerBound( HYPRE_BigInt *first, HYPRE_BigInt *last, HYPRE_BigInt value ); /* hypre_complex.c */ #ifdef HYPRE_COMPLEX HYPRE_Complex hypre_conj( HYPRE_Complex value ); HYPRE_Real hypre_cabs( HYPRE_Complex value ); HYPRE_Real hypre_creal( HYPRE_Complex value ); HYPRE_Real hypre_cimag( HYPRE_Complex value ); #else #define hypre_conj(value) value #define hypre_cabs(value) fabs(value) #define hypre_creal(value) value #define hypre_cimag(value) 0.0 #endif /* hypre_general.c */ hypre_Handle* hypre_handle(); hypre_Handle* hypre_HandleCreate(); HYPRE_Int hypre_HandleDestroy(hypre_Handle *hypre_handle_); HYPRE_Int HYPRE_Init(); HYPRE_Int HYPRE_Finalize(); HYPRE_Int hypre_SetDevice(HYPRE_Int use_device, hypre_Handle *hypre_handle_); /* hypre_qsort.c */ void hypre_swap ( HYPRE_Int *v , HYPRE_Int i , HYPRE_Int j ); void hypre_swap2 ( HYPRE_Int *v , HYPRE_Real *w , HYPRE_Int i , HYPRE_Int j ); void hypre_BigSwap2 ( HYPRE_BigInt *v , HYPRE_Real *w , HYPRE_Int i , HYPRE_Int j ); void hypre_swap2i ( HYPRE_Int *v , HYPRE_Int *w , HYPRE_Int i , HYPRE_Int j ); void hypre_BigSwap2i ( HYPRE_BigInt *v , HYPRE_Int *w , HYPRE_Int i , HYPRE_Int j ); void hypre_swap3i ( HYPRE_Int *v , HYPRE_Int *w , HYPRE_Int *z , HYPRE_Int i , HYPRE_Int j ); void hypre_swap3_d ( HYPRE_Real *v , HYPRE_Int *w , HYPRE_Int *z , HYPRE_Int i , HYPRE_Int j ); void hypre_swap3_d_perm(HYPRE_Int *v, HYPRE_Real *w, HYPRE_Int *z, HYPRE_Int i, HYPRE_Int j ); void hypre_BigSwap4_d ( HYPRE_Real *v , HYPRE_BigInt *w , HYPRE_Int *z , HYPRE_Int *y , HYPRE_Int i , HYPRE_Int j ); void hypre_swap_d ( HYPRE_Real *v , HYPRE_Int i , HYPRE_Int j ); void hypre_qsort0 ( HYPRE_Int *v , HYPRE_Int left , HYPRE_Int right ); void hypre_qsort1 ( HYPRE_Int *v , HYPRE_Real *w , HYPRE_Int left , HYPRE_Int right ); void hypre_BigQsort1 ( HYPRE_BigInt *v , HYPRE_Real *w , HYPRE_Int left , HYPRE_Int right ); void hypre_qsort2i ( HYPRE_Int *v , HYPRE_Int *w , HYPRE_Int left , HYPRE_Int right ); void hypre_BigQsort2i( HYPRE_BigInt *v, HYPRE_Int *w, HYPRE_Int left, HYPRE_Int right ); void hypre_qsort2 ( HYPRE_Int *v , HYPRE_Real *w , HYPRE_Int left , HYPRE_Int right ); void hypre_qsort2_abs ( HYPRE_Int *v , HYPRE_Real *w , HYPRE_Int left , HYPRE_Int right ); void hypre_qsort3i ( HYPRE_Int *v , HYPRE_Int *w , HYPRE_Int *z , HYPRE_Int left , HYPRE_Int right ); void hypre_qsort3ir ( HYPRE_Int *v , HYPRE_Real *w , HYPRE_Int *z , HYPRE_Int left , HYPRE_Int right ); void hypre_qsort3( HYPRE_Real *v, HYPRE_Int *w, HYPRE_Int *z, HYPRE_Int left, HYPRE_Int right ); void hypre_qsort3_abs ( HYPRE_Real *v , HYPRE_Int *w , HYPRE_Int *z , HYPRE_Int left , HYPRE_Int right ); void hypre_BigQsort4_abs ( HYPRE_Real *v , HYPRE_BigInt *w , HYPRE_Int *z , HYPRE_Int *y , HYPRE_Int left , HYPRE_Int right ); void hypre_qsort_abs ( HYPRE_Real *w , HYPRE_Int left , HYPRE_Int right ); void hypre_BigSwapbi(HYPRE_BigInt *v, HYPRE_Int *w, HYPRE_Int i, HYPRE_Int j ); void hypre_BigQsortbi( HYPRE_BigInt *v, HYPRE_Int *w, HYPRE_Int left, HYPRE_Int right ); void hypre_BigSwapLoc(HYPRE_BigInt *v, HYPRE_Int *w, HYPRE_Int i, HYPRE_Int j ); void hypre_BigQsortbLoc( HYPRE_BigInt *v, HYPRE_Int *w, HYPRE_Int left, HYPRE_Int right ); void hypre_BigSwapb2i(HYPRE_BigInt *v, HYPRE_Int *w, HYPRE_Int *z, HYPRE_Int i, HYPRE_Int j ); void hypre_BigQsortb2i( HYPRE_BigInt *v, HYPRE_Int *w, HYPRE_Int *z, HYPRE_Int left, HYPRE_Int right ); void hypre_BigSwap( HYPRE_BigInt *v, HYPRE_Int i, HYPRE_Int j ); void hypre_BigQsort0( HYPRE_BigInt *v, HYPRE_Int left, HYPRE_Int right ); void hypre_topo_sort(const HYPRE_Int *row_ptr, const HYPRE_Int *col_inds, const HYPRE_Complex *data, HYPRE_Int *ordering, HYPRE_Int n); void hypre_dense_topo_sort(const HYPRE_Complex *L, HYPRE_Int *ordering, HYPRE_Int n, HYPRE_Int is_col_major); /* qsplit.c */ HYPRE_Int hypre_DoubleQuickSplit ( HYPRE_Real *values , HYPRE_Int *indices , HYPRE_Int list_length , HYPRE_Int NumberKept ); /* random.c */ /* HYPRE_CUDA_GLOBAL */ void hypre_SeedRand ( HYPRE_Int seed ); /* HYPRE_CUDA_GLOBAL */ HYPRE_Int hypre_RandI ( void ); /* HYPRE_CUDA_GLOBAL */ HYPRE_Real hypre_Rand ( void ); /* hypre_prefix_sum.c */ /** * Assumed to be called within an omp region. * Let x_i be the input of ith thread. * The output of ith thread y_i = x_0 + x_1 + ... + x_{i-1} * Additionally, sum = x_0 + x_1 + ... + x_{nthreads - 1} * Note that always y_0 = 0 * * @param workspace at least with length (nthreads+1) * workspace[tid] will contain result for tid * workspace[nthreads] will contain sum */ void hypre_prefix_sum(HYPRE_Int *in_out, HYPRE_Int *sum, HYPRE_Int *workspace); /** * This version does prefix sum in pair. * Useful when we prefix sum of diag and offd in tandem. * * @param worksapce at least with length 2*(nthreads+1) * workspace[2*tid] and workspace[2*tid+1] will contain results for tid * workspace[3*nthreads] and workspace[3*nthreads + 1] will contain sums */ void hypre_prefix_sum_pair(HYPRE_Int *in_out1, HYPRE_Int *sum1, HYPRE_Int *in_out2, HYPRE_Int *sum2, HYPRE_Int *workspace); /** * @param workspace at least with length 3*(nthreads+1) * workspace[3*tid:3*tid+3) will contain results for tid */ void hypre_prefix_sum_triple(HYPRE_Int *in_out1, HYPRE_Int *sum1, HYPRE_Int *in_out2, HYPRE_Int *sum2, HYPRE_Int *in_out3, HYPRE_Int *sum3, HYPRE_Int *workspace); /** * n prefix-sums together. * workspace[n*tid:n*(tid+1)) will contain results for tid * workspace[nthreads*tid:nthreads*(tid+1)) will contain sums * * @param workspace at least with length n*(nthreads+1) */ void hypre_prefix_sum_multiple(HYPRE_Int *in_out, HYPRE_Int *sum, HYPRE_Int n, HYPRE_Int *workspace); /* hypre_hopscotch_hash.c */ #ifdef HYPRE_USING_OPENMP /* Check if atomic operations are available to use concurrent hopscotch hash table */ #if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) && (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) > 40100 #define HYPRE_USING_ATOMIC //#elif defined _MSC_VER // JSP: haven't tested, so comment out for now //#define HYPRE_USING_ATOMIC //#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_ATOMICS__) // JSP: not many compilers have implemented this, so comment out for now //#define HYPRE_USING_ATOMIC //#include <stdatomic.h> #endif #endif // HYPRE_USING_OPENMP #ifdef HYPRE_HOPSCOTCH #ifdef HYPRE_USING_ATOMIC // concurrent hopscotch hashing is possible only with atomic supports #define HYPRE_CONCURRENT_HOPSCOTCH #endif #endif #ifdef HYPRE_CONCURRENT_HOPSCOTCH typedef struct { HYPRE_Int volatile timestamp; omp_lock_t lock; } hypre_HopscotchSegment; #endif /** * The current typical use case of unordered set is putting input sequence * with lots of duplication (putting all colidx received from other ranks), * followed by one sweep of enumeration. * Since the capacity is set to the number of inputs, which is much larger * than the number of unique elements, we optimize for initialization and * enumeration whose time is proportional to the capacity. * For initialization and enumeration, structure of array (SoA) is better * for vectorization, cache line utilization, and so on. */ typedef struct { HYPRE_Int volatile segmentMask; HYPRE_Int volatile bucketMask; #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_HopscotchSegment* volatile segments; #endif HYPRE_Int *volatile key; hypre_uint *volatile hopInfo; HYPRE_Int *volatile hash; } hypre_UnorderedIntSet; typedef struct { HYPRE_Int volatile segmentMask; HYPRE_Int volatile bucketMask; #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_HopscotchSegment* volatile segments; #endif HYPRE_BigInt *volatile key; hypre_uint *volatile hopInfo; HYPRE_BigInt *volatile hash; } hypre_UnorderedBigIntSet; typedef struct { hypre_uint volatile hopInfo; HYPRE_Int volatile hash; HYPRE_Int volatile key; HYPRE_Int volatile data; } hypre_HopscotchBucket; typedef struct { hypre_uint volatile hopInfo; HYPRE_BigInt volatile hash; HYPRE_BigInt volatile key; HYPRE_Int volatile data; } hypre_BigHopscotchBucket; /** * The current typical use case of unoredered map is putting input sequence * with no duplication (inverse map of a bijective mapping) followed by * lots of lookups. * For lookup, array of structure (AoS) gives better cache line utilization. */ typedef struct { HYPRE_Int volatile segmentMask; HYPRE_Int volatile bucketMask; #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_HopscotchSegment* volatile segments; #endif hypre_HopscotchBucket* volatile table; } hypre_UnorderedIntMap; typedef struct { HYPRE_Int volatile segmentMask; HYPRE_Int volatile bucketMask; #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_HopscotchSegment* volatile segments; #endif hypre_BigHopscotchBucket* volatile table; } hypre_UnorderedBigIntMap; /* hypre_merge_sort.c */ /** * Why merge sort? * 1) Merge sort can take advantage of eliminating duplicates. * 2) Merge sort is more efficiently parallelizable than qsort */ void hypre_union2(HYPRE_Int n1, HYPRE_BigInt *arr1, HYPRE_Int n2, HYPRE_BigInt *arr2, HYPRE_Int *n3, HYPRE_BigInt *arr3, HYPRE_Int *map1, HYPRE_Int *map2); void hypre_merge_sort(HYPRE_Int *in, HYPRE_Int *temp, HYPRE_Int len, HYPRE_Int **sorted); void hypre_big_merge_sort(HYPRE_BigInt *in, HYPRE_BigInt *temp, HYPRE_Int len, HYPRE_BigInt **sorted); void hypre_sort_and_create_inverse_map(HYPRE_Int *in, HYPRE_Int len, HYPRE_Int **out, hypre_UnorderedIntMap *inverse_map); void hypre_big_sort_and_create_inverse_map(HYPRE_BigInt *in, HYPRE_Int len, HYPRE_BigInt **out, hypre_UnorderedBigIntMap *inverse_map); #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_DEVICE_OPENMP) HYPRE_Int hypre_SyncCudaComputeStream(hypre_Handle *hypre_handle); HYPRE_Int hypre_SyncCudaDevice(hypre_Handle *hypre_handle); HYPRE_Int hypreDevice_DiagScaleVector(HYPRE_Int n, HYPRE_Int *A_i, HYPRE_Complex *A_data, HYPRE_Complex *x, HYPRE_Complex *y); HYPRE_Int hypreDevice_IVAXPY(HYPRE_Int n, HYPRE_Complex *a, HYPRE_Complex *x, HYPRE_Complex *y); HYPRE_Int hypreDevice_MaskedIVAXPY(HYPRE_Int n, HYPRE_Complex *a, HYPRE_Complex *x, HYPRE_Complex *y, HYPRE_Int *mask); HYPRE_Int hypreDevice_BigIntFilln(HYPRE_BigInt *d_x, size_t n, HYPRE_BigInt v); #endif /* hypre_nvtx.c */ void hypre_NvtxPushRangeColor(const char *name, HYPRE_Int cid); void hypre_NvtxPushRange(const char *name); void hypre_NvtxPopRange(); #ifdef __cplusplus } #endif #endif
46.278689
374
0.631796
[ "vector", "model" ]
457357091a54b065765734ab5b9bae020759667b
11,670
h
C
ADSL/include/ADSL/DirectiveProcessor.h
jh14778/avs-device-sdk
4def446a92cc43d1fce37be3cfb30a6f85cf2d66
[ "Apache-2.0" ]
null
null
null
ADSL/include/ADSL/DirectiveProcessor.h
jh14778/avs-device-sdk
4def446a92cc43d1fce37be3cfb30a6f85cf2d66
[ "Apache-2.0" ]
null
null
null
ADSL/include/ADSL/DirectiveProcessor.h
jh14778/avs-device-sdk
4def446a92cc43d1fce37be3cfb30a6f85cf2d66
[ "Apache-2.0" ]
1
2019-02-08T19:49:13.000Z
2019-02-08T19:49:13.000Z
/* * DirectiveProcessor.h * * Copyright 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. */ #ifndef ALEXA_CLIENT_SDK_ADSL_INCLUDE_ADSL_DIRECTIVE_PROCESSOR_H_ #define ALEXA_CLIENT_SDK_ADSL_INCLUDE_ADSL_DIRECTIVE_PROCESSOR_H_ #include <condition_variable> #include <deque> #include <memory> #include <mutex> #include <string> #include <thread> #include <unordered_map> #include <AVSCommon/AVS/AVSDirective.h> #include <AVSCommon/SDKInterfaces/DirectiveHandlerInterface.h> #include "ADSL/DirectiveRouter.h" namespace alexaClientSDK { namespace adsl { /** * Object to process @c AVSDirectives that have a non-empty @c dialogRequestId. * @par * @c DirectiveProcessor receives directives via its @c onDirective() method. The @c dialogRequestId property of * incoming directives is checked against the current @c dialogRequestId (which is set by @c setDialogRequestId()). * If the @c AVSDirective's value is not empty and does not match, the @c AVSDirective is dropped, and * @c onDirective() returns @c true to indicate that the @c AVSDirective has been consumed (in this case, because * it is not longer relevant). * @par * After passing this hurdle, the @c AVSDirective is forwarded to the @c preHandleDirective() method of whichever * @c DirectiveHandler is registered to handle the @c AVSDirective. If no @c DirectiveHandler is registered, the * incoming directive is rejected and any directives with the same dialogRequestId that are already queued for * handling by the @c DirectiveProcessor are canceled (because an entire dialog is canceled when the handling of * any of its directives fails), and @c onDirective() returns @c false to indicate that the unhandled @c AVDirective * was rejected. * @par * Once an @c AVSDirective has been successfully forwarded for preHandling, it is enqueued awaiting its turn to be * handled. Handling is accomplished by forwarding the @c AVSDirective to the @c handleDirective() method of * whichever @c DirectiveHandler is registered to handle the @c AVSDirective. The handling of an @c AVSDirective can * be configured as @c BLOCKING or @c NON_BLOCKING. If the directive at the head of the handling queue is configured * for @c BLOCKING, the handling of subsequent @c AVSDirectives is held up until the @c DirectiveHandler for the * @c BLOCKING @c AVSDirective indicates that handling has completed or failed. Otherwise handleDirective() is * invoked, the @c AVSDirective is popped from the front of the queue, and processing of queued @c AVSDirective's * continues. */ class DirectiveProcessor { public: /** * Constructor. * * @param directiveRouter An object used to route directives to their registered handler. */ DirectiveProcessor(DirectiveRouter* directiveRouter); /** * Destructor. */ ~DirectiveProcessor(); /** * Set the current @c dialogRequestId. If a new value is specified any @c AVSDirective's whose pre-handling * or handling is already in progress the directive will be cancelled. * * @param dialogRequestId The new value for the current @c dialogRequestId. */ void setDialogRequestId(const std::string& dialogRequestId); /** * Queue an @c AVSDirective for handling by whatever @c DirectiveHandler was registered to handle it. * * @param directive The @c AVADirective to process. * @return Whether the directive was consumed. */ bool onDirective(std::shared_ptr<avsCommon::avs::AVSDirective> directive); /** * Shut down the DirectiveProcessor. This queues all outstanding @c AVSDirectives for cancellation and * blocks until the processing of all @c AVSDirectives has completed. */ void shutdown(); private: /** * Handle used to identify @c DirectiveProcessor instances referenced by @c DirectiveHandlerResult. * * Handles are used instead of a pointers to decouple the lifecycle of @c DirectiveProcessors from the lifecycle * of @c DirectiveHandlerInterface instances. In the case that a DirectiveHandler outlives the * @c DirectiveProcessor it may complete (or fail) the handling of a directive after (or during) the destruction * of the @c DirectiveProcessor. Using a handle instead of a pointer allows delivery of the completion / failure * notification to be dropped gracefully if the @c DirectiveProcessor is no longer there to receive it. * * @c ProcessorHandle values are mapped to @c DirectiveProcessor instances by the static @c m_handleMap. * The delivery of completion notifications by @c DirectiveHandlerResult and changes to @c m_handleMap * are serialized with the static @c m_handleMapMutex. */ using ProcessorHandle = unsigned int; /** * Implementation of @c DirectiveHandlerResultInterface that forwards the completion / failure status * to the @c DirectiveProcessor from which it originated. */ class DirectiveHandlerResult : public avsCommon::sdkInterfaces::DirectiveHandlerResultInterface { public: /** * Constructor. * * @param processorHandle handle of the @c DirectiveProcessor to forward to the result to. * @param directive The @c AVSDirective whose handling result will be specified by this instance. */ DirectiveHandlerResult(ProcessorHandle processorHandle, std::shared_ptr<avsCommon::avs::AVSDirective> directive); void setCompleted() override; void setFailed(const std::string& description) override; private: /// Handle of the @c DirectiveProcessor to forward notifications to. ProcessorHandle m_processorHandle; /// The @c AVSDirective whose handling result will be specified by this instance. std::shared_ptr<avsCommon::avs::AVSDirective> m_directive; }; /** * Receive notification that the handling of an @c AVSDirective has completed. * * @param directive The @c AVSDirective whose handling has completed. */ void onHandlingCompleted(std::shared_ptr<avsCommon::avs::AVSDirective> directive); /** * Receive notification that the handling of an @c AVSDirective has failed. * * @param directive The @c AVSDirective whose handling has failed. * @param description A description (suitable for logging diagnostics) that indicates the nature of the failure. */ void onHandlingFailed(std::shared_ptr<avsCommon::avs::AVSDirective> directive, const std::string& description); /** * Remove an @c AVSDirective from processing. * @note This method must only be called by threads that have acquired @c m_mutex. * * @param directive The @c AVSDirective to remove from processing. */ void removeDirectiveLocked(std::shared_ptr<avsCommon::avs::AVSDirective> directive); /** * Thread method for m_processingThread. */ void processingLoop(); /** * Process (cancel) all the items in @c m_cancelingQueue. * @note This method must only be called by threads that have acquired @c m_mutex. * * @param lock A @c unique_lock on m_mutex from the callers context, allowing this method to release * (and re-acquire) the lock around callbacks that need to be invoked. * @return Whether the @c AVSDirectives in @c m_cancelingQueue were processed. */ bool processCancelingQueueLocked(std::unique_lock<std::mutex>& lock); /** * Process (handle) the next @c AVSDirective in @c m_handlingQueue. * @note This method must only be called by threads that have acquired @c m_mutex. * * @param lock A @c unique_lock on m_mutex from the callers context, allowing this method to release * (and re-acquire) the lock around callbacks that need to be invoked. * @return Whether an @c AVSDirective from m_handlingQueue was processed. */ bool handleDirectiveLocked(std::unique_lock<std::mutex>& lock); /** * Set the current @c dialogRequestId. This cancels the processing of any @c AVSDirectives with a non-empty * dialogRequestId. * @note This method must only be called by threads that have acquired @c m_mutex. * * @param dialogRequestId The new value for the current @c dialogRequestId. */ void setDialogRequestIdLocked(const std::string& dialogRequestId); /** * Cancel the processing any @c AVSDirective with the specified dialogRequestId, and clear the m_dialogRequestID * if it matches the specified dialogRequestId. * @note This method must only be called by threads that have acquired @c m_mutex. * * @param dialogRequestId The dialogRequestId to scrub from processing. */ void scrubDialogRequestIdLocked(const std::string& dialogRequestId); /** * Move all the directives being handled or queued for handling to @c m_cancelingQueue. Also reset the * current @c dialogRequestId. * @note This method must only be called by threads that have acquired @c m_mutex. */ void queueAllDirectivesForCancellationLocked(); /// Handle value identifying this instance. int m_handle; /// A mutex used to serialize @c DirectiveProcessor operations with operations that occur in the creating context. std::mutex m_mutex; /// Object used to route directives to their assigned handler. DirectiveRouter* m_directiveRouter; /// Whether or not the @c DirectiveProcessor is shutting down. bool m_isShuttingDown; /// The current @c dialogRequestId std::string m_dialogRequestId; /// Queue of @c AVSDirectives waiting to be canceled. std::deque<std::shared_ptr<avsCommon::avs::AVSDirective>> m_cancelingQueue; /// The directive (if any) for which a preHandleDirective() call is in progress. std::shared_ptr<avsCommon::avs::AVSDirective> m_directiveBeingPreHandled; /// Queue of @c AVSDirectives waiting to be handled. std::deque<std::shared_ptr<avsCommon::avs::AVSDirective>> m_handlingQueue; /// Whether @c handleDirective() has been called for the directive at the @c front() of @c m_handlingQueue. bool m_isHandlingDirective; /// Condition variable used to wake @c processingLoop() when it is waiting. std::condition_variable m_wakeProcessingLoop; /// Thread processing elements on @c m_handlingQueue and @c m_cancelingQueue. std::thread m_processingThread; /// Mutex serializing the body of @ onDirective() to make the method thread-safe. std::mutex m_onDirectiveMutex; /// Mutex to serialize access to @c m_handleMap; static std::mutex m_handleMapMutex; /** * Map from @c ProcessorHandle value to @c DirectiveProcessor instance to allow for gracefully dropping a * completion (or failure) notification forwarded to the @c DirectiveProcessor during or after its destruction. */ static std::unordered_map<ProcessorHandle, DirectiveProcessor*> m_handleMap; /// Next available @c ProcessorHandle value. static ProcessorHandle m_nextProcessorHandle; }; } // namespace adsl } // namespace alexaClientSDK #endif // ALEXA_CLIENT_SDK_ADSL_INCLUDE_ADSL_DIRECTIVE_PROCESSOR_H_
43.87218
121
0.728363
[ "object" ]
45769cce1969f210463425e951c057e9f88e667e
1,959
h
C
CalibMuon/DTCalibration/test/stubs/DTMeanTimerPlotter.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
CalibMuon/DTCalibration/test/stubs/DTMeanTimerPlotter.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
CalibMuon/DTCalibration/test/stubs/DTMeanTimerPlotter.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#ifndef DTMeanTimerPlotter_H #define DTMeanTimerPlotter_H /** \class DTMeanTimerPlotter * Utility class to plot MeanTimer produced with DTVDriftCalibration. * The tmax histograms can be fitted using exactly the same code that is * used by the calibration application. * * \author S. Bolognesi - INFN Torino */ #include "TString.h" #include <vector> class TFile; class TCanvas; class TH1D; class TF1; class DTMeanTimerPlotter { public: /// Constructor DTMeanTimerPlotter(TFile* file); /// Destructor virtual ~DTMeanTimerPlotter(); // Operations /// Plot the time box of a given superlayer. /// Options: <br> /// "same" -> histo drawn in the active canvas, <br> /// "SingleDeltaT0" or "SingleFormula" -> fit and draw each TMax histo separately (in the same canvas) <br> /// "fit" -> draw and fit the histos <br> void plotMeanTimer(int wheel, int station, int sector, int sl, const TString& drawOptions = ""); /// Set the verbosity of the output: 0 = silent, 1 = info, 2 = debug void setVerbosity(unsigned int lvl); /// Set rebin number void setRebinning(unsigned int rebin); /// Reset the counter for histos color void resetColor(); protected: private: //Plot the TMax histogram for each deltaT0: THESE ARE NOT USED TO COMPUTE VDRIFT std::vector<TH1D*> plotSingleTMaxDeltaT0(TString& name); //Plot the TMax histogram for each formula std::vector<TH1D*> plotSingleTMaxFormula(TString& name); //Plot the total TMax histograms: THIS IS NOT USED TO COMPUTE VDRIFT std::vector<TH1D*> plotTotalTMax(TString& name); void plotHistos(std::vector<TH1D*> hTMaxes, TString& name, const TString& drawOptions); TString getHistoNameSuffix(int wheel, int station, int sector, int sl); std::vector<TF1*> fitTMaxes(std::vector<TH1D*> histo); double getMaximum(std::vector<TH1D*> hTMaxes); TFile* theFile; unsigned int theVerbosityLevel; unsigned int theRebinning; unsigned int color; }; #endif
29.681818
109
0.722818
[ "vector" ]
457786b0a541cc9cf467b87619e1cef70e34298d
3,623
h
C
dev/Code/Framework/AzCore/AzCore/Math/Crc.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
null
null
null
dev/Code/Framework/AzCore/AzCore/Math/Crc.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
null
null
null
dev/Code/Framework/AzCore/AzCore/Math/Crc.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
null
null
null
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #ifndef AZCORE_CRC_H #define AZCORE_CRC_H 1 #include <AzCore/base.h> #include <AzCore/std/string/string_view.h> ////////////////////////////////////////////////////////////////////////// // Macros for pre-processor Crc32 conversion // // When you user AZ_CRC("My string") by default it will map to AZ::Crc32("My string"). // We do have a pro-processor program which will precompute the crc for you and // transform that macro to AZ_CRC("My string",0xabcdef00) this will expand to just 0xabcdef00. // This will remove completely the "My string" from your executable, it will add it to a database and so on. // WHen you want to update the string, just change the string. // If you don't run the precomile step the code should still run fine, except it will be slower, // the strings will be in the exe and converted on the fly and you can't use the result where you need // a constant expression. // For example // switch(id) { // case AZ_CRC("My string",0xabcdef00): {} break; // this will compile fine // case AZ_CRC("My string"): {} break; // this will cause "error C2051: case expression not constant" // } // So it's you choice what you do, depending on your needs. // /// Implementation when we have only 1 param (by default it should be string. #define AZ_CRC_1(_1) AZ::Crc32(_1) /// Implementation when we have 2 params (we use the 2 only) #define AZ_CRC_2(_1, _2) AZ::Crc32(AZ::u32(_2)) #define AZ_CRC(...) AZ_MACRO_SPECIALIZE(AZ_CRC_, AZ_VA_NUM_ARGS(__VA_ARGS__), (__VA_ARGS__)) ////////////////////////////////////////////////////////////////////////// namespace AZ { class SerializeContext; /** * Class for all of our crc32 types, better than just using ints everywhere. */ class Crc32 { public: /** * Initializes to 0. */ AZ_MATH_FORCE_INLINE Crc32() : m_value(0) { } /** * Initializes from an int. */ AZ_MATH_FORCE_INLINE Crc32(AZ::u32 value) { m_value = value; } /** * Calculates the value from a string. */ explicit Crc32(const char* str); explicit Crc32(AZStd::string_view view); /** * Calculates the value from a block of raw data. */ Crc32(const void* data, size_t size, bool forceLowerCase = false); void Add(const char* str); void Add(const void* data, size_t size, bool forceLowerCase = false); AZ_MATH_FORCE_INLINE operator u32() const { return m_value; } AZ_MATH_FORCE_INLINE bool operator==(Crc32 rhs) const { return (m_value == rhs.m_value); } AZ_MATH_FORCE_INLINE bool operator!=(Crc32 rhs) const { return (m_value != rhs.m_value); } AZ_MATH_FORCE_INLINE bool operator!() const { return (m_value == 0); } static void Reflect(AZ::SerializeContext& context); protected: void Set(const void* data, size_t size, bool forceLowerCase = false); void Combine(u32 crc, size_t len); u32 m_value; }; }; #endif // AZCORE_CRC32_H #pragma once
36.59596
108
0.637317
[ "transform" ]
457851ed2a2fc1e066ac3dc12ea9377f31c760fe
5,211
h
C
src/asp/Sessions/RPC/RPCModel.h
fenglang12345/StereoPipeline-2.4.0
a9cb9129013f278e9f65e435193b735a6b051eb9
[ "Apache-2.0" ]
null
null
null
src/asp/Sessions/RPC/RPCModel.h
fenglang12345/StereoPipeline-2.4.0
a9cb9129013f278e9f65e435193b735a6b051eb9
[ "Apache-2.0" ]
null
null
null
src/asp/Sessions/RPC/RPCModel.h
fenglang12345/StereoPipeline-2.4.0
a9cb9129013f278e9f65e435193b735a6b051eb9
[ "Apache-2.0" ]
null
null
null
// __BEGIN_LICENSE__ // Copyright (c) 2009-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is licensed under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance with the // License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ // RPC model and triangulation. Following the paper: // Jacek Grodecki, Gene Dial and James Lutes, "Mathematical Model for // 3D Feature Extraction from Multiple Satellite Images Described by // RPCs." Proceedings of ASPRS 2004 Conference, Denver, Colorado, May, // 2004. #ifndef __STEREO_SESSION_RPC_MODEL_H__ #define __STEREO_SESSION_RPC_MODEL_H__ #include <vw/Math/Matrix.h> #include <vw/Math/Vector.h> #include <vw/Camera/CameraModel.h> #include <vw/Cartography/Datum.h> #include <string> #include <ostream> namespace vw { class DiskImageResourceGDAL; } namespace asp { class RPCModel : public vw::camera::CameraModel { public: typedef vw::Vector<double,20> CoeffVec; RPCModel( std::string const& filename ); RPCModel( vw::DiskImageResourceGDAL* resource ); RPCModel( vw::cartography::Datum const& datum, CoeffVec const& line_num_coeff, CoeffVec const& line_den_coeff, CoeffVec const& samp_num_coeff, CoeffVec const& samp_den_coeff, vw::Vector2 const& xy_offset, vw::Vector2 const& xy_scale, vw::Vector3 const& lonlatheight_offset, vw::Vector3 const& lonlatheight_scale ); virtual std::string type() const { return "RPC"; } virtual ~RPCModel() {} // Standard Access Methods. The concept of camera_center does not // apply well to RPC, we just return an arbitrary point on the // ray. virtual vw::Vector2 point_to_pixel( vw::Vector3 const& point ) const; virtual vw::Vector3 pixel_to_vector( vw::Vector2 const& pix ) const; virtual vw::Vector3 camera_center( vw::Vector2 const& pix ) const; static vw::Vector2 normalized_geodetic_to_normalized_pixel (vw::Vector3 const& normalized_geodetic, CoeffVec const& line_num_coeff, CoeffVec const& line_den_coeff, CoeffVec const& sample_num_coeff, CoeffVec const& sample_den_coeff ); vw::Vector2 normalized_geodetic_to_normalized_pixel ( vw::Vector3 const& normalized_geodetic ) const; vw::Vector2 geodetic_to_pixel( vw::Vector3 const& geodetic ) const; // Access to constants vw::cartography::Datum const& datum() const { return m_datum; } CoeffVec const& line_num_coeff() const { return m_line_num_coeff; } CoeffVec const& line_den_coeff() const { return m_line_den_coeff; } CoeffVec const& sample_num_coeff() const { return m_sample_num_coeff; } CoeffVec const& sample_den_coeff() const { return m_sample_den_coeff; } vw::Vector2 const& xy_offset() const { return m_xy_offset; } vw::Vector2 const& xy_scale() const { return m_xy_scale; } vw::Vector3 const& lonlatheight_offset() const { return m_lonlatheight_offset; } vw::Vector3 const& lonlatheight_scale() const { return m_lonlatheight_scale; } // Helper methods used for triangulation and projection static CoeffVec calculate_terms( vw::Vector3 const& normalized_geodetic ); static vw::Matrix<double, 20, 2> terms_Jacobian2( vw::Vector3 const& normalized_geodetic ); static vw::Matrix<double, 20, 3> terms_Jacobian3( vw::Vector3 const& normalized_geodetic ); static CoeffVec quotient_Jacobian( CoeffVec const& c, CoeffVec const& d, CoeffVec const& u ); static vw::Matrix3x3 normalization_Jacobian(vw::Vector3 const& q); vw::Matrix<double, 2, 3> geodetic_to_pixel_Jacobian (vw::Vector3 const& geodetic ) const; vw::Matrix<double, 2, 3> geodetic_to_pixel_numerical_Jacobian(vw::Vector3 const& geodetic, double tol) const; vw::Matrix<double, 2, 2> normalized_geodetic_to_pixel_Jacobian(vw::Vector3 const& normalized_geodetic ) const; vw::Vector2 image_to_ground(vw::Vector2 const& pixel, double height, vw::Vector2 lonlat_guess = vw::Vector2(0.0, 0.0)) const; void point_and_dir(vw::Vector2 const& pix, vw::Vector3 & P, vw::Vector3 & dir ) const; private: vw::cartography::Datum m_datum; // Scaling parameters CoeffVec m_line_num_coeff, m_line_den_coeff, m_sample_num_coeff, m_sample_den_coeff; vw::Vector2 m_xy_offset; vw::Vector2 m_xy_scale; vw::Vector3 m_lonlatheight_offset; vw::Vector3 m_lonlatheight_scale; void initialize( vw::DiskImageResourceGDAL* resource ); }; std::ostream& operator<<(std::ostream& os, const RPCModel& rpc); } #endif //__STEREO_SESSION_RPC_MODEL_H__
40.710938
114
0.715026
[ "vector", "model", "3d" ]
4581a7a4e41e35c1dc904a8464c13f91f40ce068
15,527
h
C
src/glsl/ralloc.h
cwabbott0/lima_compiler
51f162b1e25efddc5084782c530f503cdc843b08
[ "MIT" ]
9
2015-12-20T05:31:29.000Z
2022-01-04T11:18:36.000Z
src/glsl/ralloc.h
cwabbott0/lima_compiler
51f162b1e25efddc5084782c530f503cdc843b08
[ "MIT" ]
1
2017-04-19T15:45:54.000Z
2017-04-19T15:45:54.000Z
src/glsl/ralloc.h
cwabbott0/lima_compiler
51f162b1e25efddc5084782c530f503cdc843b08
[ "MIT" ]
2
2019-01-12T04:07:29.000Z
2020-10-27T12:31:05.000Z
/* * Copyright © 2010 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /** * \file ralloc.h * * ralloc: a recursive memory allocator * * The ralloc memory allocator creates a hierarchy of allocated * objects. Every allocation is in reference to some parent, and * every allocated object can in turn be used as the parent of a * subsequent allocation. This allows for extremely convenient * discarding of an entire tree/sub-tree of allocations by calling * ralloc_free on any particular object to free it and all of its * children. * * The conceptual working of ralloc was directly inspired by Andrew * Tridgell's talloc, but ralloc is an independent implementation * released under the MIT license and tuned for Mesa. * * The talloc implementation is available under the GNU Lesser * General Public License (GNU LGPL), version 3 or later. It is * more sophisticated than ralloc in that it includes reference * counting and debugging features. See: http://talloc.samba.org/ */ #ifndef RALLOC_H #define RALLOC_H #ifdef __cplusplus extern "C" { #endif #include <stddef.h> #include <stdarg.h> #include <stdbool.h> #include "main/compiler.h" /** * \def ralloc(ctx, type) * Allocate a new object chained off of the given context. * * This is equivalent to: * \code * ((type *) ralloc_size(ctx, sizeof(type)) * \endcode */ #define ralloc(ctx, type) ((type *) ralloc_size(ctx, sizeof(type))) /** * \def rzalloc(ctx, type) * Allocate a new object out of the given context and initialize it to zero. * * This is equivalent to: * \code * ((type *) rzalloc_size(ctx, sizeof(type)) * \endcode */ #define rzalloc(ctx, type) ((type *) rzalloc_size(ctx, sizeof(type))) /** * Allocate a new ralloc context. * * While any ralloc'd pointer can be used as a context, sometimes it is useful * to simply allocate a context with no associated memory. * * It is equivalent to: * \code * ((type *) ralloc_size(ctx, 0) * \endcode */ void *ralloc_context(const void *ctx); /** * Allocate memory chained off of the given context. * * This is the core allocation routine which is used by all others. It * simply allocates storage for \p size bytes and returns the pointer, * similar to \c malloc. */ void *ralloc_size(const void *ctx, size_t size); /** * Allocate zero-initialized memory chained off of the given context. * * This is similar to \c calloc with a size of 1. */ void *rzalloc_size(const void *ctx, size_t size); /** * Resize a piece of ralloc-managed memory, preserving data. * * Similar to \c realloc. Unlike C89, passing 0 for \p size does not free the * memory. Instead, it resizes it to a 0-byte ralloc context, just like * calling ralloc_size(ctx, 0). This is different from talloc. * * \param ctx The context to use for new allocation. If \p ptr != NULL, * it must be the same as ralloc_parent(\p ptr). * \param ptr Pointer to the memory to be resized. May be NULL. * \param size The amount of memory to allocate, in bytes. */ void *reralloc_size(const void *ctx, void *ptr, size_t size); /// \defgroup array Array Allocators @{ /** * \def ralloc_array(ctx, type, count) * Allocate an array of objects chained off the given context. * * Similar to \c calloc, but does not initialize the memory to zero. * * More than a convenience function, this also checks for integer overflow when * multiplying \c sizeof(type) and \p count. This is necessary for security. * * This is equivalent to: * \code * ((type *) ralloc_array_size(ctx, sizeof(type), count) * \endcode */ #define ralloc_array(ctx, type, count) \ ((type *) ralloc_array_size(ctx, sizeof(type), count)) /** * \def rzalloc_array(ctx, type, count) * Allocate a zero-initialized array chained off the given context. * * Similar to \c calloc. * * More than a convenience function, this also checks for integer overflow when * multiplying \c sizeof(type) and \p count. This is necessary for security. * * This is equivalent to: * \code * ((type *) rzalloc_array_size(ctx, sizeof(type), count) * \endcode */ #define rzalloc_array(ctx, type, count) \ ((type *) rzalloc_array_size(ctx, sizeof(type), count)) /** * \def reralloc(ctx, ptr, type, count) * Resize a ralloc-managed array, preserving data. * * Similar to \c realloc. Unlike C89, passing 0 for \p size does not free the * memory. Instead, it resizes it to a 0-byte ralloc context, just like * calling ralloc_size(ctx, 0). This is different from talloc. * * More than a convenience function, this also checks for integer overflow when * multiplying \c sizeof(type) and \p count. This is necessary for security. * * \param ctx The context to use for new allocation. If \p ptr != NULL, * it must be the same as ralloc_parent(\p ptr). * \param ptr Pointer to the array to be resized. May be NULL. * \param type The element type. * \param count The number of elements to allocate. */ #define reralloc(ctx, ptr, type, count) \ ((type *) reralloc_array_size(ctx, ptr, sizeof(type), count)) /** * Allocate memory for an array chained off the given context. * * Similar to \c calloc, but does not initialize the memory to zero. * * More than a convenience function, this also checks for integer overflow when * multiplying \p size and \p count. This is necessary for security. */ void *ralloc_array_size(const void *ctx, size_t size, unsigned count); /** * Allocate a zero-initialized array chained off the given context. * * Similar to \c calloc. * * More than a convenience function, this also checks for integer overflow when * multiplying \p size and \p count. This is necessary for security. */ void *rzalloc_array_size(const void *ctx, size_t size, unsigned count); /** * Resize a ralloc-managed array, preserving data. * * Similar to \c realloc. Unlike C89, passing 0 for \p size does not free the * memory. Instead, it resizes it to a 0-byte ralloc context, just like * calling ralloc_size(ctx, 0). This is different from talloc. * * More than a convenience function, this also checks for integer overflow when * multiplying \c sizeof(type) and \p count. This is necessary for security. * * \param ctx The context to use for new allocation. If \p ptr != NULL, * it must be the same as ralloc_parent(\p ptr). * \param ptr Pointer to the array to be resized. May be NULL. * \param size The size of an individual element. * \param count The number of elements to allocate. * * \return True unless allocation failed. */ void *reralloc_array_size(const void *ctx, void *ptr, size_t size, unsigned count); /// @} /** * Free a piece of ralloc-managed memory. * * This will also free the memory of any children allocated this context. */ void ralloc_free(void *ptr); /** * "Steal" memory from one context, changing it to another. * * This changes \p ptr's context to \p new_ctx. This is quite useful if * memory is allocated out of a temporary context. */ void ralloc_steal(const void *new_ctx, void *ptr); /** * Return the given pointer's ralloc context. */ void *ralloc_parent(const void *ptr); /** * Return a context whose memory will be automatically freed at program exit. * * The first call to this function creates a context and registers a handler * to free it using \c atexit. This may cause trouble if used in a library * loaded with \c dlopen. */ void *ralloc_autofree_context(void); /** * Set a callback to occur just before an object is freed. */ void ralloc_set_destructor(const void *ptr, void(*destructor)(void *)); /// \defgroup array String Functions @{ /** * Duplicate a string, allocating the memory from the given context. */ char *ralloc_strdup(const void *ctx, const char *str); /** * Duplicate a string, allocating the memory from the given context. * * Like \c strndup, at most \p n characters are copied. If \p str is longer * than \p n characters, \p n are copied, and a termining \c '\0' byte is added. */ char *ralloc_strndup(const void *ctx, const char *str, size_t n); /** * Concatenate two strings, allocating the necessary space. * * This appends \p str to \p *dest, similar to \c strcat, using ralloc_resize * to expand \p *dest to the appropriate size. \p dest will be updated to the * new pointer unless allocation fails. * * The result will always be null-terminated. * * \return True unless allocation failed. */ bool ralloc_strcat(char **dest, const char *str); /** * Concatenate two strings, allocating the necessary space. * * This appends at most \p n bytes of \p str to \p *dest, using ralloc_resize * to expand \p *dest to the appropriate size. \p dest will be updated to the * new pointer unless allocation fails. * * The result will always be null-terminated; \p str does not need to be null * terminated if it is longer than \p n. * * \return True unless allocation failed. */ bool ralloc_strncat(char **dest, const char *str, size_t n); /** * Print to a string. * * This is analogous to \c sprintf, but allocates enough space (using \p ctx * as the context) for the resulting string. * * \return The newly allocated string. */ char *ralloc_asprintf (const void *ctx, const char *fmt, ...) PRINTFLIKE(2, 3); /** * Print to a string, given a va_list. * * This is analogous to \c vsprintf, but allocates enough space (using \p ctx * as the context) for the resulting string. * * \return The newly allocated string. */ char *ralloc_vasprintf(const void *ctx, const char *fmt, va_list args); /** * Rewrite the tail of an existing string, starting at a given index. * * Overwrites the contents of *str starting at \p start with newly formatted * text, including a new null-terminator. Allocates more memory as necessary. * * This can be used to append formatted text when the length of the existing * string is already known, saving a strlen() call. * * \sa ralloc_asprintf_append * * \param str The string to be updated. * \param start The index to start appending new data at. * \param fmt A printf-style formatting string * * \p str will be updated to the new pointer unless allocation fails. * \p start will be increased by the length of the newly formatted text. * * \return True unless allocation failed. */ bool ralloc_asprintf_rewrite_tail(char **str, size_t *start, const char *fmt, ...) PRINTFLIKE(3, 4); /** * Rewrite the tail of an existing string, starting at a given index. * * Overwrites the contents of *str starting at \p start with newly formatted * text, including a new null-terminator. Allocates more memory as necessary. * * This can be used to append formatted text when the length of the existing * string is already known, saving a strlen() call. * * \sa ralloc_vasprintf_append * * \param str The string to be updated. * \param start The index to start appending new data at. * \param fmt A printf-style formatting string * \param args A va_list containing the data to be formatted * * \p str will be updated to the new pointer unless allocation fails. * \p start will be increased by the length of the newly formatted text. * * \return True unless allocation failed. */ bool ralloc_vasprintf_rewrite_tail(char **str, size_t *start, const char *fmt, va_list args); /** * Append formatted text to the supplied string. * * This is equivalent to * \code * ralloc_asprintf_rewrite_tail(str, strlen(*str), fmt, ...) * \endcode * * \sa ralloc_asprintf * \sa ralloc_asprintf_rewrite_tail * \sa ralloc_strcat * * \p str will be updated to the new pointer unless allocation fails. * * \return True unless allocation failed. */ bool ralloc_asprintf_append (char **str, const char *fmt, ...) PRINTFLIKE(2, 3); /** * Append formatted text to the supplied string, given a va_list. * * This is equivalent to * \code * ralloc_vasprintf_rewrite_tail(str, strlen(*str), fmt, args) * \endcode * * \sa ralloc_vasprintf * \sa ralloc_vasprintf_rewrite_tail * \sa ralloc_strcat * * \p str will be updated to the new pointer unless allocation fails. * * \return True unless allocation failed. */ bool ralloc_vasprintf_append(char **str, const char *fmt, va_list args); /// @} #ifdef __cplusplus } /* end of extern "C" */ #endif /** * Declare C++ new and delete operators which use ralloc. * * Placing this macro in the body of a class makes it possible to do: * * TYPE *var = new(mem_ctx) TYPE(...); * delete var; * * which is more idiomatic in C++ than calling ralloc. */ #define DECLARE_RALLOC_CXX_OPERATORS(TYPE) \ private: \ static void _ralloc_destructor(void *p) \ { \ reinterpret_cast<TYPE *>(p)->~TYPE(); \ } \ public: \ static void* operator new(size_t size, void *mem_ctx) \ { \ void *p = ralloc_size(mem_ctx, size); \ assert(p != NULL); \ if (!HAS_TRIVIAL_DESTRUCTOR(TYPE)) \ ralloc_set_destructor(p, _ralloc_destructor); \ return p; \ } \ \ static void operator delete(void *p) \ { \ /* The object's destructor is guaranteed to have already been \ * called by the delete operator at this point -- Make sure it's \ * not called again. \ */ \ if (!HAS_TRIVIAL_DESTRUCTOR(TYPE)) \ ralloc_set_destructor(p, NULL); \ ralloc_free(p); \ } #endif
34.813901
80
0.654408
[ "object" ]
45821db1ee8378d84a5a8aa40abf2195fa78e1b0
3,727
h
C
tensorflow/core/grappler/clusters/cluster.h
AlexChrisF/udacity
b7f85a74058fc63ccb7601c418450ab934ef5953
[ "Apache-2.0" ]
28
2017-04-08T09:47:57.000Z
2020-07-12T03:10:46.000Z
tensorflow/core/grappler/clusters/cluster.h
AlexChrisF/udacity
b7f85a74058fc63ccb7601c418450ab934ef5953
[ "Apache-2.0" ]
7
2017-07-13T09:40:59.000Z
2019-04-08T22:46:51.000Z
tensorflow/core/grappler/clusters/cluster.h
AlexChrisF/udacity
b7f85a74058fc63ccb7601c418450ab934ef5953
[ "Apache-2.0" ]
38
2017-04-28T04:15:48.000Z
2019-09-28T05:11:46.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_GRAPPLER_CLUSTERS_CLUSTER_H_ #define TENSORFLOW_GRAPPLER_CLUSTERS_CLUSTER_H_ #include <string> #include <utility> #include <vector> #include "tensorflow/core/framework/device_attributes.pb.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/grappler/grappler_item.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/public/session_options.h" namespace tensorflow { namespace grappler { // A cluster represents of collection of hardware resources available to run // the TensorFlow model. // A process can only create a single cluster at a time. class Cluster { public: explicit Cluster(int timeout_s); virtual ~Cluster(); // Provision the hardware resources needed to run TensorFlow and start a // TensorFlow session that can take advantage of these resources. // The actual resources that are leveraged depend on the type of cluster // instantiated. // Returns OK iff all the requested resources could be reserved and a // TensorFlow session successfully created. Returns an error otherwise. // There is no graceful degradation to handle the case where only a subset // of the requested resources are available. virtual Status Provision() = 0; // Whether soft placement is allowed. If allow_soft_placement is true, // an op will be placed on CPU if there's no GPU implementation for the OP // or if no GPU devices are known or registered or if we need to co-locate // with reftype input(s) which are from CPU. void AllowSoftPlacement(bool soft_placement_state); // Set the number of steps required to warmup TensorFlow. Must be called // before Provision(). void SetNumWarmupSteps(int num_steps); // Disable the collection of detailed statistics. void DisableDetailedStats(bool disable); // Return the list of TensorFlow devices that are available to execute a // graph. This is empty until provision() is called. const std::vector<DeviceAttributes>& GetDevices() const { return devices_; } // Convenience method that returns the set of device names. const std::vector<string> GetDeviceNames() const { std::vector<string> device_names; device_names.reserve(devices_.size()); for (const auto& device : devices_) { device_names.push_back(device.name()); } return device_names; } // Prepare the session to run the specified grappler item. This include // initializing all the model variables. virtual Status Initialize(const GrapplerItem& item) = 0; // Run the specified graph_def and return the corresponding metadata. virtual Status Run(const GraphDef& graph_def, const std::vector<std::pair<string, Tensor>>& feed, const std::vector<string>& fetch, RunMetadata* metadata) = 0; protected: std::vector<DeviceAttributes> devices_; const int timeout_s_; SessionOptions options_; RunOptions run_options_; }; } // end namespace grappler } // end namespace tensorflow #endif // TENSORFLOW_GRAPPLER_CLUSTERS_CLUSTER_H_
38.030612
80
0.734371
[ "vector", "model" ]
4586224ed8d6f6c5372ca0ee963de31d367d70bb
17,009
h
C
service/simulator/inc/simulator_resource_model_schema.h
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
301
2015-01-20T16:11:32.000Z
2021-11-25T04:29:36.000Z
service/simulator/inc/simulator_resource_model_schema.h
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
13
2015-06-04T09:55:15.000Z
2020-09-23T00:38:07.000Z
service/simulator/inc/simulator_resource_model_schema.h
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
233
2015-01-26T03:41:59.000Z
2022-03-18T23:54:04.000Z
/****************************************************************** * * Copyright 2016 Samsung Electronics All Rights Reserved. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************/ #ifndef SIMULATOR_RESOURCE_MODEL_SCHEMA_H_ #define SIMULATOR_RESOURCE_MODEL_SCHEMA_H_ #include <unordered_map> #include <memory> #include "simulator_resource_model.h" class IntegerProperty; class DoubleProperty; class BooleanProperty; class StringProperty; class ArrayProperty; class ModelProperty; class AttributeProperty { public: enum class Type { INTEGER, /**< Integer type */ DOUBLE, /**< Double type */ BOOLEAN, /**< Boolean type */ STRING, /**< String type */ MODEL, /**< Model type */ ARRAY /**< Array type */ }; explicit AttributeProperty(Type type); virtual ~AttributeProperty() {} /** * get the attribute type * @return attribute type */ Type getType() const; /** * Check the integer value * @return boolean value */ virtual bool isInteger() const { return false; } /** * Check the double value * @return boolean value */ virtual bool isDouble() const { return false; } /** * Check the boolean value * @return boolean value */ virtual bool isBoolean() const { return false; } /** * Check the string value * @return boolean value */ virtual bool isString() const { return false; } /** * Check array * @return boolean value */ virtual bool isArray() const { return false; } /** * Check model * @return boolean value */ virtual bool isModel() const { return false; } /** * Integer property * @return integer property object */ virtual std::shared_ptr<IntegerProperty> asInteger() { return nullptr; } /** * double property * @return double property object */ virtual std::shared_ptr<DoubleProperty> asDouble() { return nullptr; } /** * boolean property * @return boolean property object */ virtual std::shared_ptr<BooleanProperty> asBoolean() { return nullptr; } /** * string property * @return string property object */ virtual std::shared_ptr<StringProperty> asString() { return nullptr; } /** * array property * @return array property object */ virtual std::shared_ptr<ArrayProperty> asArray() { return nullptr; } /** * model property * @return model property object */ virtual std::shared_ptr<ModelProperty> asModel() { return nullptr; } /** * validate the attribute value * @param[in] value value to validate * @return boolean value */ virtual bool validate(const AttributeValueVariant &value) = 0; /** * This method is to get the attribute default value * @return class object */ virtual AttributeValueVariant buildValue() = 0; private: Type m_type; }; /** * IntegerProperty class */ class IntegerProperty : public AttributeProperty, public std::enable_shared_from_this<IntegerProperty> { public: static std::shared_ptr<IntegerProperty> build(int defaultValue = 0); /** * check value is integer or not * @return boolean value */ bool isInteger() const; std::shared_ptr<IntegerProperty> asInteger(); /** * set the given default vlaue * @param value value to set */ void setDefaultValue(int value); /** * set the range * @param min minimum range value * @param max maximum range value */ void setRange(int min, int max); /** * set the property values * @param values value to set */ void setValues(const std::vector<int> &values); /** * check range and return the true or false value * @return boolean value */ bool hasRange() const; /** * check value and return the true or false value * @return boolean value */ bool hasValues() const; /** * get the default property value * @return default value */ int getDefaultValue() const; /** * get the minimum and maximum range value * @param[out] min minimum range * @param[out] max maximum range * @return boolean value */ bool getRange(int &min, int &max) const; /** * get the property values * @param[out] values property value * @return boolean value */ bool getValues(std::vector<int> &values) const; /** * validate the attribute value * @param[in] value attribute value * @return boolean value */ bool validate(const AttributeValueVariant &value); /** * validate the value * @param[in] value attribute value * @return boolean value */ bool validate(const int &value); AttributeValueVariant buildValue(); private: explicit IntegerProperty(int defaultValue); int m_defaultValue; int m_min; int m_max; std::vector<int> m_values; bool m_hasRange; }; /* * DoubleProperty class */ class DoubleProperty : public AttributeProperty, public std::enable_shared_from_this<DoubleProperty> { public: static std::shared_ptr<DoubleProperty> build(double defaultValue = 0.0); /** * check value is double or not * @return boolean value */ bool isDouble() const; std::shared_ptr<DoubleProperty> asDouble(); /** * set the given default vlaue * @param value value to set */ void setDefaultValue(double value); /** * set the range * @param min minimum range value * @param max maximum range value */ void setRange(double min, double max); /** * set the property values * @param values value to set */ void setValues(const std::vector<double> &values); /** * check range and return the true or false value * @return boolean value */ bool hasRange() const; /** * check value and return the true or false value * @return boolean value */ bool hasValues() const; /** * get the default property value * @return default vlaue */ double getDefaultValue() const; /** * get the minimum and maximum range value * @param[out] min minimum range * @param[out] max maximum range * @return boolean value */ bool getRange(double &min, double &max) const; /** * get the property values * @param[out] values property value * @return boolean value */ bool getValues(std::vector<double> &values) const; /** * validate the attribute value * @param[in] value attribute value * @return boolean value */ bool validate(const AttributeValueVariant &value); /** * validate the value * @param[in] value attribute value * @return boolean value */ bool validate(const double &value); AttributeValueVariant buildValue(); private: explicit DoubleProperty(double defaultValue); double m_defaultValue; double m_min; double m_max; std::vector<double> m_values; bool m_hasRange; }; /** * BooleanProperty class */ class BooleanProperty : public AttributeProperty, public std::enable_shared_from_this<BooleanProperty> { public: static std::shared_ptr<BooleanProperty> build(bool defaultValue = true); /** * check value is boolean or not * @return boolean value */ bool isBoolean() const; std::shared_ptr<BooleanProperty> asBoolean(); /** * set default value * @param value attribute default value */ void setDefaultValue(bool value); /** * get default value * @return boolean value */ bool getDefaultValue() const; /** * validate attribute value * @param[in] value attribute value * @return boolean value */ bool validate(const AttributeValueVariant &value); AttributeValueVariant buildValue(); private: explicit BooleanProperty(bool defaultValue); bool m_defaultValue; }; /** * StringProperty class */ class StringProperty : public AttributeProperty, public std::enable_shared_from_this<StringProperty> { public: static std::shared_ptr<StringProperty> build(const std::string &defaultValue = ""); /** * check the string value * @return boolean value */ bool isString() const; std::shared_ptr<StringProperty> asString(); /** * set the given default vlaue * @param value value to set */ void setDefaultValue(const std::string &value); /** * set the range * @param min minimum range value * @param max maximum range value */ void setRange(size_t min, size_t max); /** * set the property values * @param values value to set */ void setValues(const std::vector<std::string> &values); /** * check range and return the true or false value * @return boolean value */ bool hasRange() const; /** * check value and return the true or false value * @return boolean value */ bool hasValues() const; std::string getDefaultValue() const; /** * get the minimum and maximum range value * @param min minimum range value * @param max maximum range value * @return boolean value */ bool getRange(size_t &min, size_t &max) const; /** * get the property values * @param[in] values attribute value * @return boolean value */ bool getValues(std::vector<std::string> &values) const; /** * validate attribute value * @param[in] values attribute value * @return boolean value */ bool validate(const AttributeValueVariant &value); /** * validate value * @param[in] values attribute value * @return boolean value */ bool validate(const std::string &value); AttributeValueVariant buildValue(); private: StringProperty(const std::string &defaultValue); std::string m_defaultValue; size_t m_min; size_t m_max; std::vector<std::string> m_values; bool m_hasRange; }; /** * ArrayProperty class */ class ArrayProperty : public AttributeProperty, public std::enable_shared_from_this<ArrayProperty> { public: static std::shared_ptr<ArrayProperty> build(); /** * check array * @return boolean value */ bool isArray() const; std::shared_ptr<ArrayProperty> asArray(); /** * set the range * @param minItems minimum range value * @param maxItems maximum range value */ void setRange(size_t minItems, size_t maxItems); /** * set variable state * @param[in] state value to set */ void setVariable(bool state); /** * set the state value * @param[in] state value to set */ void setUnique(bool state); /** * set element property * @param[in] property attribute property * @return boolean value */ bool setElementProperty(const std::shared_ptr<AttributeProperty> &property); /** * check range and return the true or false value * @return boolean value */ bool hasRange() const; /** * check the variable value * @return boolean value */ bool isVariable() const; /** * check the unique value * @return boolean value */ bool isUnique() const; /** * get the minimum items value * @return minimum item value */ size_t getMinItems() const; /** * get the maximum items value * @return miximum item value */ size_t getMaxItems() const; /** * get the element property * @return element property */ std::shared_ptr<AttributeProperty> getElementProperty(); /** * validate attribute value * @param[in] value attribute value * @return boolean value */ bool validate(const AttributeValueVariant &value); AttributeValueVariant buildValue(); private: ArrayProperty(); int findDepth(std::shared_ptr<AttributeProperty> &elementProperty); size_t m_min; size_t m_max; bool m_isVariableSize; bool m_isUnique; std::shared_ptr<AttributeProperty> m_elementProperty; bool m_hasRange; }; /** * ModelProperty class */ class ModelProperty : public AttributeProperty, public std::enable_shared_from_this<ModelProperty> { public: static std::shared_ptr<ModelProperty> build(); /** * check model * @return boolean value */ bool isModel() const; std::shared_ptr<ModelProperty> asModel(); bool add(const std::string &name, const std::shared_ptr<AttributeProperty> &property, bool required = false); std::shared_ptr<AttributeProperty> get(const std::string &name); std::unordered_map<std::string, std::shared_ptr<AttributeProperty>> getChildProperties(); /** * check name value and return true or false value * @param[in] name string value * @return boolean value */ bool isRequired(const std::string &name); /** * remove the given name * @param[in] name string value */ void remove(const std::string &name); /** * set the given value * @param[in] name set the value */ void setRequired(const std::string &name); /** * unset the given value * @param[in] name unset the value */ void unsetRequired(const std::string &name); SimulatorResourceModel buildResourceModel(); /** * validate attribute value * @param[in] value attribute value * @return boolean value */ bool validate(const AttributeValueVariant &value); /** * validate the model value * @param[in] model model to validate * @return boolean value */ bool validate(const SimulatorResourceModel &model); AttributeValueVariant buildValue(); private: ModelProperty(); std::unordered_map<std::string, bool> m_requiredAttributes; std::unordered_map<std::string, std::shared_ptr<AttributeProperty>> m_childProperties; }; typedef ModelProperty SimulatorResourceModelSchema; #endif
27.389694
97
0.545417
[ "object", "vector", "model" ]
4587befb6e60d89c984dae3760ae67e883377fe1
70,062
c
C
audio/windows/openal-soft-1.18.2/Alc/ALu.c
HecateTech/engine
30f5a7a4fe70925fd41fb2408c359d550cb8eab4
[ "BSD-2-Clause" ]
null
null
null
audio/windows/openal-soft-1.18.2/Alc/ALu.c
HecateTech/engine
30f5a7a4fe70925fd41fb2408c359d550cb8eab4
[ "BSD-2-Clause" ]
null
null
null
audio/windows/openal-soft-1.18.2/Alc/ALu.c
HecateTech/engine
30f5a7a4fe70925fd41fb2408c359d550cb8eab4
[ "BSD-2-Clause" ]
1
2020-02-07T02:37:09.000Z
2020-02-07T02:37:09.000Z
/** * OpenAL cross platform audio library * Copyright (C) 1999-2007 by authors. * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * Or go to http://www.gnu.org/copyleft/lgpl.html */ #include "config.h" #include <math.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <assert.h> #include "alMain.h" #include "alSource.h" #include "alBuffer.h" #include "alListener.h" #include "alAuxEffectSlot.h" #include "alu.h" #include "bs2b.h" #include "hrtf.h" #include "uhjfilter.h" #include "bformatdec.h" #include "static_assert.h" #include "mixer_defs.h" #include "backends/base.h" struct ChanMap { enum Channel channel; ALfloat angle; ALfloat elevation; }; /* Cone scalar */ ALfloat ConeScale = 1.0f; /* Localized Z scalar for mono sources */ ALfloat ZScale = 1.0f; extern inline ALfloat minf(ALfloat a, ALfloat b); extern inline ALfloat maxf(ALfloat a, ALfloat b); extern inline ALfloat clampf(ALfloat val, ALfloat min, ALfloat max); extern inline ALdouble mind(ALdouble a, ALdouble b); extern inline ALdouble maxd(ALdouble a, ALdouble b); extern inline ALdouble clampd(ALdouble val, ALdouble min, ALdouble max); extern inline ALuint minu(ALuint a, ALuint b); extern inline ALuint maxu(ALuint a, ALuint b); extern inline ALuint clampu(ALuint val, ALuint min, ALuint max); extern inline ALint mini(ALint a, ALint b); extern inline ALint maxi(ALint a, ALint b); extern inline ALint clampi(ALint val, ALint min, ALint max); extern inline ALint64 mini64(ALint64 a, ALint64 b); extern inline ALint64 maxi64(ALint64 a, ALint64 b); extern inline ALint64 clampi64(ALint64 val, ALint64 min, ALint64 max); extern inline ALuint64 minu64(ALuint64 a, ALuint64 b); extern inline ALuint64 maxu64(ALuint64 a, ALuint64 b); extern inline ALuint64 clampu64(ALuint64 val, ALuint64 min, ALuint64 max); extern inline ALfloat lerp(ALfloat val1, ALfloat val2, ALfloat mu); extern inline ALfloat resample_fir4(ALfloat val0, ALfloat val1, ALfloat val2, ALfloat val3, ALsizei frac); extern inline void aluVectorSet(aluVector *restrict vector, ALfloat x, ALfloat y, ALfloat z, ALfloat w); extern inline void aluMatrixfSetRow(aluMatrixf *matrix, ALuint row, ALfloat m0, ALfloat m1, ALfloat m2, ALfloat m3); extern inline void aluMatrixfSet(aluMatrixf *matrix, ALfloat m00, ALfloat m01, ALfloat m02, ALfloat m03, ALfloat m10, ALfloat m11, ALfloat m12, ALfloat m13, ALfloat m20, ALfloat m21, ALfloat m22, ALfloat m23, ALfloat m30, ALfloat m31, ALfloat m32, ALfloat m33); const aluMatrixf IdentityMatrixf = {{ { 1.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f }, }}; void DeinitVoice(ALvoice *voice) { struct ALvoiceProps *props; size_t count = 0; props = ATOMIC_EXCHANGE_PTR_SEQ(&voice->Update, NULL); if(props) al_free(props); props = ATOMIC_EXCHANGE_PTR(&voice->FreeList, NULL, almemory_order_relaxed); while(props) { struct ALvoiceProps *next; next = ATOMIC_LOAD(&props->next, almemory_order_relaxed); al_free(props); props = next; ++count; } /* This is excessively spammy if it traces every voice destruction, so just * warn if it was unexpectedly large. */ if(count > 3) WARN("Freed "SZFMT" voice property objects\n", count); } static inline HrtfDirectMixerFunc SelectHrtfMixer(void) { #ifdef HAVE_NEON if((CPUCapFlags&CPU_CAP_NEON)) return MixDirectHrtf_Neon; #endif #ifdef HAVE_SSE if((CPUCapFlags&CPU_CAP_SSE)) return MixDirectHrtf_SSE; #endif return MixDirectHrtf_C; } /* Prior to VS2013, MSVC lacks the round() family of functions. */ #if defined(_MSC_VER) && _MSC_VER < 1800 static float roundf(float val) { if(val < 0.0f) return ceilf(val-0.5f); return floorf(val+0.5f); } #endif /* This RNG method was created based on the math found in opusdec. It's quick, * and starting with a seed value of 22222, is suitable for generating * whitenoise. */ static inline ALuint dither_rng(ALuint *seed) { *seed = (*seed * 96314165) + 907633515; return *seed; } static inline void aluCrossproduct(const ALfloat *inVector1, const ALfloat *inVector2, ALfloat *outVector) { outVector[0] = inVector1[1]*inVector2[2] - inVector1[2]*inVector2[1]; outVector[1] = inVector1[2]*inVector2[0] - inVector1[0]*inVector2[2]; outVector[2] = inVector1[0]*inVector2[1] - inVector1[1]*inVector2[0]; } static inline ALfloat aluDotproduct(const aluVector *vec1, const aluVector *vec2) { return vec1->v[0]*vec2->v[0] + vec1->v[1]*vec2->v[1] + vec1->v[2]*vec2->v[2]; } static ALfloat aluNormalize(ALfloat *vec) { ALfloat length = sqrtf(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]); if(length > 0.0f) { ALfloat inv_length = 1.0f/length; vec[0] *= inv_length; vec[1] *= inv_length; vec[2] *= inv_length; } return length; } static void aluMatrixfFloat3(ALfloat *vec, ALfloat w, const aluMatrixf *mtx) { ALfloat v[4] = { vec[0], vec[1], vec[2], w }; vec[0] = v[0]*mtx->m[0][0] + v[1]*mtx->m[1][0] + v[2]*mtx->m[2][0] + v[3]*mtx->m[3][0]; vec[1] = v[0]*mtx->m[0][1] + v[1]*mtx->m[1][1] + v[2]*mtx->m[2][1] + v[3]*mtx->m[3][1]; vec[2] = v[0]*mtx->m[0][2] + v[1]*mtx->m[1][2] + v[2]*mtx->m[2][2] + v[3]*mtx->m[3][2]; } static aluVector aluMatrixfVector(const aluMatrixf *mtx, const aluVector *vec) { aluVector v; v.v[0] = vec->v[0]*mtx->m[0][0] + vec->v[1]*mtx->m[1][0] + vec->v[2]*mtx->m[2][0] + vec->v[3]*mtx->m[3][0]; v.v[1] = vec->v[0]*mtx->m[0][1] + vec->v[1]*mtx->m[1][1] + vec->v[2]*mtx->m[2][1] + vec->v[3]*mtx->m[3][1]; v.v[2] = vec->v[0]*mtx->m[0][2] + vec->v[1]*mtx->m[1][2] + vec->v[2]*mtx->m[2][2] + vec->v[3]*mtx->m[3][2]; v.v[3] = vec->v[0]*mtx->m[0][3] + vec->v[1]*mtx->m[1][3] + vec->v[2]*mtx->m[2][3] + vec->v[3]*mtx->m[3][3]; return v; } /* Prepares the interpolator for a given rate (determined by increment). A * result of AL_FALSE indicates that the filter output will completely cut * the input signal. * * With a bit of work, and a trade of memory for CPU cost, this could be * modified for use with an interpolated increment for buttery-smooth pitch * changes. */ ALboolean BsincPrepare(const ALuint increment, BsincState *state) { static const ALfloat scaleBase = 1.510578918e-01f, scaleRange = 1.177936623e+00f; static const ALuint m[BSINC_SCALE_COUNT] = { 24, 24, 24, 24, 24, 24, 24, 20, 20, 20, 16, 16, 16, 12, 12, 12 }; static const ALuint to[4][BSINC_SCALE_COUNT] = { { 0, 24, 408, 792, 1176, 1560, 1944, 2328, 2648, 2968, 3288, 3544, 3800, 4056, 4248, 4440 }, { 4632, 5016, 5400, 5784, 6168, 6552, 6936, 7320, 7640, 7960, 8280, 8536, 8792, 9048, 9240, 0 }, { 0, 9432, 9816, 10200, 10584, 10968, 11352, 11736, 12056, 12376, 12696, 12952, 13208, 13464, 13656, 13848 }, { 14040, 14424, 14808, 15192, 15576, 15960, 16344, 16728, 17048, 17368, 17688, 17944, 18200, 18456, 18648, 0 } }; static const ALuint tm[2][BSINC_SCALE_COUNT] = { { 0, 24, 24, 24, 24, 24, 24, 20, 20, 20, 16, 16, 16, 12, 12, 12 }, { 24, 24, 24, 24, 24, 24, 24, 20, 20, 20, 16, 16, 16, 12, 12, 0 } }; ALfloat sf; ALsizei si, pi; ALboolean uncut = AL_TRUE; if(increment > FRACTIONONE) { sf = (ALfloat)FRACTIONONE / increment; if(sf < scaleBase) { /* Signal has been completely cut. The return result can be used * to skip the filter (and output zeros) as an optimization. */ sf = 0.0f; si = 0; uncut = AL_FALSE; } else { sf = (BSINC_SCALE_COUNT - 1) * (sf - scaleBase) * scaleRange; si = fastf2i(sf); /* The interpolation factor is fit to this diagonally-symmetric * curve to reduce the transition ripple caused by interpolating * different scales of the sinc function. */ sf = 1.0f - cosf(asinf(sf - si)); } } else { sf = 0.0f; si = BSINC_SCALE_COUNT - 1; } state->sf = sf; state->m = m[si]; state->l = -(ALint)((m[si] / 2) - 1); /* The CPU cost of this table re-mapping could be traded for the memory * cost of a complete table map (1024 elements large). */ for(pi = 0;pi < BSINC_PHASE_COUNT;pi++) { state->coeffs[pi].filter = &bsincTab[to[0][si] + tm[0][si]*pi]; state->coeffs[pi].scDelta = &bsincTab[to[1][si] + tm[1][si]*pi]; state->coeffs[pi].phDelta = &bsincTab[to[2][si] + tm[0][si]*pi]; state->coeffs[pi].spDelta = &bsincTab[to[3][si] + tm[1][si]*pi]; } return uncut; } static ALboolean CalcListenerParams(ALCcontext *Context) { ALlistener *Listener = Context->Listener; ALfloat N[3], V[3], U[3], P[3]; struct ALlistenerProps *props; aluVector vel; props = ATOMIC_EXCHANGE_PTR(&Listener->Update, NULL, almemory_order_acq_rel); if(!props) return AL_FALSE; /* AT then UP */ N[0] = props->Forward[0]; N[1] = props->Forward[1]; N[2] = props->Forward[2]; aluNormalize(N); V[0] = props->Up[0]; V[1] = props->Up[1]; V[2] = props->Up[2]; aluNormalize(V); /* Build and normalize right-vector */ aluCrossproduct(N, V, U); aluNormalize(U); aluMatrixfSet(&Listener->Params.Matrix, U[0], V[0], -N[0], 0.0, U[1], V[1], -N[1], 0.0, U[2], V[2], -N[2], 0.0, 0.0, 0.0, 0.0, 1.0 ); P[0] = props->Position[0]; P[1] = props->Position[1]; P[2] = props->Position[2]; aluMatrixfFloat3(P, 1.0, &Listener->Params.Matrix); aluMatrixfSetRow(&Listener->Params.Matrix, 3, -P[0], -P[1], -P[2], 1.0f); aluVectorSet(&vel, props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f); Listener->Params.Velocity = aluMatrixfVector(&Listener->Params.Matrix, &vel); Listener->Params.Gain = props->Gain * Context->GainBoost; Listener->Params.MetersPerUnit = props->MetersPerUnit; Listener->Params.DopplerFactor = props->DopplerFactor; Listener->Params.SpeedOfSound = props->SpeedOfSound * props->DopplerVelocity; Listener->Params.SourceDistanceModel = props->SourceDistanceModel; Listener->Params.DistanceModel = props->DistanceModel; ATOMIC_REPLACE_HEAD(struct ALlistenerProps*, &Listener->FreeList, props); return AL_TRUE; } static ALboolean CalcEffectSlotParams(ALeffectslot *slot, ALCdevice *device) { struct ALeffectslotProps *props; ALeffectState *state; props = ATOMIC_EXCHANGE_PTR(&slot->Update, NULL, almemory_order_acq_rel); if(!props) return AL_FALSE; slot->Params.Gain = props->Gain; slot->Params.AuxSendAuto = props->AuxSendAuto; slot->Params.EffectType = props->Type; if(IsReverbEffect(slot->Params.EffectType)) { slot->Params.RoomRolloff = props->Props.Reverb.RoomRolloffFactor; slot->Params.DecayTime = props->Props.Reverb.DecayTime; slot->Params.DecayHFRatio = props->Props.Reverb.DecayHFRatio; slot->Params.DecayHFLimit = props->Props.Reverb.DecayHFLimit; slot->Params.AirAbsorptionGainHF = props->Props.Reverb.AirAbsorptionGainHF; } else { slot->Params.RoomRolloff = 0.0f; slot->Params.DecayTime = 0.0f; slot->Params.DecayHFRatio = 0.0f; slot->Params.DecayHFLimit = AL_FALSE; slot->Params.AirAbsorptionGainHF = 1.0f; } /* Swap effect states. No need to play with the ref counts since they keep * the same number of refs. */ state = props->State; props->State = slot->Params.EffectState; slot->Params.EffectState = state; V(state,update)(device, slot, &props->Props); ATOMIC_REPLACE_HEAD(struct ALeffectslotProps*, &slot->FreeList, props); return AL_TRUE; } static const struct ChanMap MonoMap[1] = { { FrontCenter, 0.0f, 0.0f } }, RearMap[2] = { { BackLeft, DEG2RAD(-150.0f), DEG2RAD(0.0f) }, { BackRight, DEG2RAD( 150.0f), DEG2RAD(0.0f) } }, QuadMap[4] = { { FrontLeft, DEG2RAD( -45.0f), DEG2RAD(0.0f) }, { FrontRight, DEG2RAD( 45.0f), DEG2RAD(0.0f) }, { BackLeft, DEG2RAD(-135.0f), DEG2RAD(0.0f) }, { BackRight, DEG2RAD( 135.0f), DEG2RAD(0.0f) } }, X51Map[6] = { { FrontLeft, DEG2RAD( -30.0f), DEG2RAD(0.0f) }, { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) }, { FrontCenter, DEG2RAD( 0.0f), DEG2RAD(0.0f) }, { LFE, 0.0f, 0.0f }, { SideLeft, DEG2RAD(-110.0f), DEG2RAD(0.0f) }, { SideRight, DEG2RAD( 110.0f), DEG2RAD(0.0f) } }, X61Map[7] = { { FrontLeft, DEG2RAD(-30.0f), DEG2RAD(0.0f) }, { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) }, { FrontCenter, DEG2RAD( 0.0f), DEG2RAD(0.0f) }, { LFE, 0.0f, 0.0f }, { BackCenter, DEG2RAD(180.0f), DEG2RAD(0.0f) }, { SideLeft, DEG2RAD(-90.0f), DEG2RAD(0.0f) }, { SideRight, DEG2RAD( 90.0f), DEG2RAD(0.0f) } }, X71Map[8] = { { FrontLeft, DEG2RAD( -30.0f), DEG2RAD(0.0f) }, { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) }, { FrontCenter, DEG2RAD( 0.0f), DEG2RAD(0.0f) }, { LFE, 0.0f, 0.0f }, { BackLeft, DEG2RAD(-150.0f), DEG2RAD(0.0f) }, { BackRight, DEG2RAD( 150.0f), DEG2RAD(0.0f) }, { SideLeft, DEG2RAD( -90.0f), DEG2RAD(0.0f) }, { SideRight, DEG2RAD( 90.0f), DEG2RAD(0.0f) } }; static void CalcPanningAndFilters(ALvoice *voice, const ALfloat Distance, const ALfloat *Dir, const ALfloat Spread, const ALfloat DryGain, const ALfloat DryGainHF, const ALfloat DryGainLF, const ALfloat *WetGain, const ALfloat *WetGainLF, const ALfloat *WetGainHF, ALeffectslot **SendSlots, const ALbuffer *Buffer, const struct ALvoiceProps *props, const ALlistener *Listener, const ALCdevice *Device) { struct ChanMap StereoMap[2] = { { FrontLeft, DEG2RAD(-30.0f), DEG2RAD(0.0f) }, { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) } }; bool DirectChannels = props->DirectChannels; const ALsizei NumSends = Device->NumAuxSends; const ALuint Frequency = Device->Frequency; const struct ChanMap *chans = NULL; ALsizei num_channels = 0; bool isbformat = false; ALfloat downmix_gain = 1.0f; ALsizei c, i, j; switch(Buffer->FmtChannels) { case FmtMono: chans = MonoMap; num_channels = 1; /* Mono buffers are never played direct. */ DirectChannels = false; break; case FmtStereo: /* Convert counter-clockwise to clockwise. */ StereoMap[0].angle = -props->StereoPan[0]; StereoMap[1].angle = -props->StereoPan[1]; chans = StereoMap; num_channels = 2; downmix_gain = 1.0f / 2.0f; break; case FmtRear: chans = RearMap; num_channels = 2; downmix_gain = 1.0f / 2.0f; break; case FmtQuad: chans = QuadMap; num_channels = 4; downmix_gain = 1.0f / 4.0f; break; case FmtX51: chans = X51Map; num_channels = 6; /* NOTE: Excludes LFE. */ downmix_gain = 1.0f / 5.0f; break; case FmtX61: chans = X61Map; num_channels = 7; /* NOTE: Excludes LFE. */ downmix_gain = 1.0f / 6.0f; break; case FmtX71: chans = X71Map; num_channels = 8; /* NOTE: Excludes LFE. */ downmix_gain = 1.0f / 7.0f; break; case FmtBFormat2D: num_channels = 3; isbformat = true; DirectChannels = false; break; case FmtBFormat3D: num_channels = 4; isbformat = true; DirectChannels = false; break; } voice->Flags &= ~(VOICE_HAS_HRTF | VOICE_HAS_NFC); if(isbformat) { /* Special handling for B-Format sources. */ if(Distance > FLT_EPSILON) { /* Panning a B-Format sound toward some direction is easy. Just pan * the first (W) channel as a normal mono sound and silence the * others. */ ALfloat coeffs[MAX_AMBI_COEFFS]; if(Device->AvgSpeakerDist > 0.0f && Listener->Params.MetersPerUnit > 0.0f) { ALfloat mdist = Distance * Listener->Params.MetersPerUnit; ALfloat w0 = SPEEDOFSOUNDMETRESPERSEC / (mdist * (ALfloat)Device->Frequency); ALfloat w1 = SPEEDOFSOUNDMETRESPERSEC / (Device->AvgSpeakerDist * (ALfloat)Device->Frequency); /* Clamp w0 for really close distances, to prevent excessive * bass. */ w0 = minf(w0, w1*4.0f); /* Only need to adjust the first channel of a B-Format source. */ NfcFilterAdjust1(&voice->Direct.Params[0].NFCtrlFilter[0], w0); NfcFilterAdjust2(&voice->Direct.Params[0].NFCtrlFilter[1], w0); NfcFilterAdjust3(&voice->Direct.Params[0].NFCtrlFilter[2], w0); for(i = 0;i < MAX_AMBI_ORDER+1;i++) voice->Direct.ChannelsPerOrder[i] = Device->Dry.NumChannelsPerOrder[i]; voice->Flags |= VOICE_HAS_NFC; } if(Device->Render_Mode == StereoPair) { ALfloat ev = asinf(Dir[1]); ALfloat az = atan2f(Dir[0], -Dir[2]); CalcAnglePairwiseCoeffs(az, ev, Spread, coeffs); } else CalcDirectionCoeffs(Dir, Spread, coeffs); /* NOTE: W needs to be scaled by sqrt(2) due to FuMa normalization. */ ComputePanningGains(Device->Dry, coeffs, DryGain*1.414213562f, voice->Direct.Params[0].Gains.Target); for(c = 1;c < num_channels;c++) { for(j = 0;j < MAX_OUTPUT_CHANNELS;j++) voice->Direct.Params[c].Gains.Target[j] = 0.0f; } for(i = 0;i < NumSends;i++) { const ALeffectslot *Slot = SendSlots[i]; if(Slot) ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels, coeffs, WetGain[i]*1.414213562f, voice->Send[i].Params[0].Gains.Target ); else for(j = 0;j < MAX_EFFECT_CHANNELS;j++) voice->Send[i].Params[0].Gains.Target[j] = 0.0f; for(c = 1;c < num_channels;c++) { for(j = 0;j < MAX_EFFECT_CHANNELS;j++) voice->Send[i].Params[c].Gains.Target[j] = 0.0f; } } } else { /* Local B-Format sources have their XYZ channels rotated according * to the orientation. */ ALfloat N[3], V[3], U[3]; aluMatrixf matrix; ALfloat scale; if(Device->AvgSpeakerDist > 0.0f) { /* NOTE: The NFCtrlFilters were created with a w0 of 0, which * is what we want for FOA input. The first channel may have * been previously re-adjusted if panned, so reset it. */ NfcFilterAdjust1(&voice->Direct.Params[0].NFCtrlFilter[0], 0.0f); NfcFilterAdjust2(&voice->Direct.Params[0].NFCtrlFilter[1], 0.0f); NfcFilterAdjust3(&voice->Direct.Params[0].NFCtrlFilter[2], 0.0f); voice->Direct.ChannelsPerOrder[0] = 1; voice->Direct.ChannelsPerOrder[1] = mini(voice->Direct.Channels-1, 3); for(i = 2;i < MAX_AMBI_ORDER+1;i++) voice->Direct.ChannelsPerOrder[2] = 0; voice->Flags |= VOICE_HAS_NFC; } /* AT then UP */ N[0] = props->Orientation[0][0]; N[1] = props->Orientation[0][1]; N[2] = props->Orientation[0][2]; aluNormalize(N); V[0] = props->Orientation[1][0]; V[1] = props->Orientation[1][1]; V[2] = props->Orientation[1][2]; aluNormalize(V); if(!props->HeadRelative) { const aluMatrixf *lmatrix = &Listener->Params.Matrix; aluMatrixfFloat3(N, 0.0f, lmatrix); aluMatrixfFloat3(V, 0.0f, lmatrix); } /* Build and normalize right-vector */ aluCrossproduct(N, V, U); aluNormalize(U); /* Build a rotate + conversion matrix (FuMa -> ACN+N3D). */ scale = 1.732050808f; aluMatrixfSet(&matrix, 1.414213562f, 0.0f, 0.0f, 0.0f, 0.0f, -N[0]*scale, N[1]*scale, -N[2]*scale, 0.0f, U[0]*scale, -U[1]*scale, U[2]*scale, 0.0f, -V[0]*scale, V[1]*scale, -V[2]*scale ); voice->Direct.Buffer = Device->FOAOut.Buffer; voice->Direct.Channels = Device->FOAOut.NumChannels; for(c = 0;c < num_channels;c++) ComputeFirstOrderGains(Device->FOAOut, matrix.m[c], DryGain, voice->Direct.Params[c].Gains.Target); for(i = 0;i < NumSends;i++) { const ALeffectslot *Slot = SendSlots[i]; if(Slot) { for(c = 0;c < num_channels;c++) ComputeFirstOrderGainsBF(Slot->ChanMap, Slot->NumChannels, matrix.m[c], WetGain[i], voice->Send[i].Params[c].Gains.Target ); } else { for(c = 0;c < num_channels;c++) for(j = 0;j < MAX_EFFECT_CHANNELS;j++) voice->Send[i].Params[c].Gains.Target[j] = 0.0f; } } } } else if(DirectChannels) { /* Direct source channels always play local. Skip the virtual channels * and write inputs to the matching real outputs. */ voice->Direct.Buffer = Device->RealOut.Buffer; voice->Direct.Channels = Device->RealOut.NumChannels; for(c = 0;c < num_channels;c++) { int idx; for(j = 0;j < MAX_OUTPUT_CHANNELS;j++) voice->Direct.Params[c].Gains.Target[j] = 0.0f; if((idx=GetChannelIdxByName(Device->RealOut, chans[c].channel)) != -1) voice->Direct.Params[c].Gains.Target[idx] = DryGain; } /* Auxiliary sends still use normal channel panning since they mix to * B-Format, which can't channel-match. */ for(c = 0;c < num_channels;c++) { ALfloat coeffs[MAX_AMBI_COEFFS]; CalcAngleCoeffs(chans[c].angle, chans[c].elevation, 0.0f, coeffs); for(i = 0;i < NumSends;i++) { const ALeffectslot *Slot = SendSlots[i]; if(Slot) ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels, coeffs, WetGain[i], voice->Send[i].Params[c].Gains.Target ); else for(j = 0;j < MAX_EFFECT_CHANNELS;j++) voice->Send[i].Params[c].Gains.Target[j] = 0.0f; } } } else if(Device->Render_Mode == HrtfRender) { /* Full HRTF rendering. Skip the virtual channels and render to the * real outputs. */ voice->Direct.Buffer = Device->RealOut.Buffer; voice->Direct.Channels = Device->RealOut.NumChannels; if(Distance > FLT_EPSILON) { ALfloat coeffs[MAX_AMBI_COEFFS]; ALfloat ev, az; ev = asinf(Dir[1]); az = atan2f(Dir[0], -Dir[2]); /* Get the HRIR coefficients and delays just once, for the given * source direction. */ GetHrtfCoeffs(Device->HrtfHandle, ev, az, Spread, voice->Direct.Params[0].Hrtf.Target.Coeffs, voice->Direct.Params[0].Hrtf.Target.Delay); voice->Direct.Params[0].Hrtf.Target.Gain = DryGain * downmix_gain; /* Remaining channels use the same results as the first. */ for(c = 1;c < num_channels;c++) { /* Skip LFE */ if(chans[c].channel == LFE) memset(&voice->Direct.Params[c].Hrtf.Target, 0, sizeof(voice->Direct.Params[c].Hrtf.Target)); else voice->Direct.Params[c].Hrtf.Target = voice->Direct.Params[0].Hrtf.Target; } /* Calculate the directional coefficients once, which apply to all * input channels of the source sends. */ CalcDirectionCoeffs(Dir, Spread, coeffs); for(i = 0;i < NumSends;i++) { const ALeffectslot *Slot = SendSlots[i]; if(Slot) for(c = 0;c < num_channels;c++) { /* Skip LFE */ if(chans[c].channel == LFE) for(j = 0;j < MAX_EFFECT_CHANNELS;j++) voice->Send[i].Params[c].Gains.Target[j] = 0.0f; else ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels, coeffs, WetGain[i] * downmix_gain, voice->Send[i].Params[c].Gains.Target ); } else for(j = 0;j < MAX_EFFECT_CHANNELS;j++) voice->Send[i].Params[c].Gains.Target[j] = 0.0f; } } else { /* Local sources on HRTF play with each channel panned to its * relative location around the listener, providing "virtual * speaker" responses. */ for(c = 0;c < num_channels;c++) { ALfloat coeffs[MAX_AMBI_COEFFS]; if(chans[c].channel == LFE) { /* Skip LFE */ memset(&voice->Direct.Params[c].Hrtf.Target, 0, sizeof(voice->Direct.Params[c].Hrtf.Target)); for(i = 0;i < NumSends;i++) { for(j = 0;j < MAX_EFFECT_CHANNELS;j++) voice->Send[i].Params[c].Gains.Target[j] = 0.0f; } continue; } /* Get the HRIR coefficients and delays for this channel * position. */ GetHrtfCoeffs(Device->HrtfHandle, chans[c].elevation, chans[c].angle, Spread, voice->Direct.Params[c].Hrtf.Target.Coeffs, voice->Direct.Params[c].Hrtf.Target.Delay ); voice->Direct.Params[c].Hrtf.Target.Gain = DryGain; /* Normal panning for auxiliary sends. */ CalcAngleCoeffs(chans[c].angle, chans[c].elevation, Spread, coeffs); for(i = 0;i < NumSends;i++) { const ALeffectslot *Slot = SendSlots[i]; if(Slot) ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels, coeffs, WetGain[i], voice->Send[i].Params[c].Gains.Target ); else for(j = 0;j < MAX_EFFECT_CHANNELS;j++) voice->Send[i].Params[c].Gains.Target[j] = 0.0f; } } } voice->Flags |= VOICE_HAS_HRTF; } else { /* Non-HRTF rendering. Use normal panning to the output. */ if(Distance > FLT_EPSILON) { ALfloat coeffs[MAX_AMBI_COEFFS]; ALfloat w0 = 0.0f; /* Calculate NFC filter coefficient if needed. */ if(Device->AvgSpeakerDist > 0.0f && Listener->Params.MetersPerUnit > 0.0f) { ALfloat mdist = Distance * Listener->Params.MetersPerUnit; ALfloat w1 = SPEEDOFSOUNDMETRESPERSEC / (Device->AvgSpeakerDist * (ALfloat)Device->Frequency); w0 = SPEEDOFSOUNDMETRESPERSEC / (mdist * (ALfloat)Device->Frequency); /* Clamp w0 for really close distances, to prevent excessive * bass. */ w0 = minf(w0, w1*4.0f); for(i = 0;i < MAX_AMBI_ORDER+1;i++) voice->Direct.ChannelsPerOrder[i] = Device->Dry.NumChannelsPerOrder[i]; voice->Flags |= VOICE_HAS_NFC; } /* Calculate the directional coefficients once, which apply to all * input channels. */ if(Device->Render_Mode == StereoPair) { ALfloat ev = asinf(Dir[1]); ALfloat az = atan2f(Dir[0], -Dir[2]); CalcAnglePairwiseCoeffs(az, ev, Spread, coeffs); } else CalcDirectionCoeffs(Dir, Spread, coeffs); for(c = 0;c < num_channels;c++) { /* Adjust NFC filters if needed. */ if((voice->Flags&VOICE_HAS_NFC)) { NfcFilterAdjust1(&voice->Direct.Params[c].NFCtrlFilter[0], w0); NfcFilterAdjust2(&voice->Direct.Params[c].NFCtrlFilter[1], w0); NfcFilterAdjust3(&voice->Direct.Params[c].NFCtrlFilter[2], w0); } /* Special-case LFE */ if(chans[c].channel == LFE) { for(j = 0;j < MAX_OUTPUT_CHANNELS;j++) voice->Direct.Params[c].Gains.Target[j] = 0.0f; if(Device->Dry.Buffer == Device->RealOut.Buffer) { int idx = GetChannelIdxByName(Device->RealOut, chans[c].channel); if(idx != -1) voice->Direct.Params[c].Gains.Target[idx] = DryGain; } continue; } ComputePanningGains(Device->Dry, coeffs, DryGain * downmix_gain, voice->Direct.Params[c].Gains.Target ); } for(i = 0;i < NumSends;i++) { const ALeffectslot *Slot = SendSlots[i]; if(Slot) for(c = 0;c < num_channels;c++) { /* Skip LFE */ if(chans[c].channel == LFE) for(j = 0;j < MAX_EFFECT_CHANNELS;j++) voice->Send[i].Params[c].Gains.Target[j] = 0.0f; else ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels, coeffs, WetGain[i] * downmix_gain, voice->Send[i].Params[c].Gains.Target ); } else for(c = 0;c < num_channels;c++) { for(j = 0;j < MAX_EFFECT_CHANNELS;j++) voice->Send[i].Params[c].Gains.Target[j] = 0.0f; } } } else { ALfloat w0 = 0.0f; if(Device->AvgSpeakerDist > 0.0f) { /* If the source distance is 0, set w0 to w1 to act as a pass- * through. We still want to pass the signal through the * filters so they keep an appropriate history, in case the * source moves away from the listener. */ w0 = SPEEDOFSOUNDMETRESPERSEC / (Device->AvgSpeakerDist * (ALfloat)Device->Frequency); for(i = 0;i < MAX_AMBI_ORDER+1;i++) voice->Direct.ChannelsPerOrder[i] = Device->Dry.NumChannelsPerOrder[i]; voice->Flags |= VOICE_HAS_NFC; } for(c = 0;c < num_channels;c++) { ALfloat coeffs[MAX_AMBI_COEFFS]; if((voice->Flags&VOICE_HAS_NFC)) { NfcFilterAdjust1(&voice->Direct.Params[c].NFCtrlFilter[0], w0); NfcFilterAdjust2(&voice->Direct.Params[c].NFCtrlFilter[1], w0); NfcFilterAdjust3(&voice->Direct.Params[c].NFCtrlFilter[2], w0); } /* Special-case LFE */ if(chans[c].channel == LFE) { for(j = 0;j < MAX_OUTPUT_CHANNELS;j++) voice->Direct.Params[c].Gains.Target[j] = 0.0f; if(Device->Dry.Buffer == Device->RealOut.Buffer) { int idx = GetChannelIdxByName(Device->RealOut, chans[c].channel); if(idx != -1) voice->Direct.Params[c].Gains.Target[idx] = DryGain; } for(i = 0;i < NumSends;i++) { for(j = 0;j < MAX_EFFECT_CHANNELS;j++) voice->Send[i].Params[c].Gains.Target[j] = 0.0f; } continue; } if(Device->Render_Mode == StereoPair) CalcAnglePairwiseCoeffs(chans[c].angle, chans[c].elevation, Spread, coeffs); else CalcAngleCoeffs(chans[c].angle, chans[c].elevation, Spread, coeffs); ComputePanningGains(Device->Dry, coeffs, DryGain, voice->Direct.Params[c].Gains.Target ); for(i = 0;i < NumSends;i++) { const ALeffectslot *Slot = SendSlots[i]; if(Slot) ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels, coeffs, WetGain[i], voice->Send[i].Params[c].Gains.Target ); else for(j = 0;j < MAX_EFFECT_CHANNELS;j++) voice->Send[i].Params[c].Gains.Target[j] = 0.0f; } } } } { ALfloat hfScale = props->Direct.HFReference / Frequency; ALfloat lfScale = props->Direct.LFReference / Frequency; ALfloat gainHF = maxf(DryGainHF, 0.001f); /* Limit -60dB */ ALfloat gainLF = maxf(DryGainLF, 0.001f); voice->Direct.FilterType = AF_None; if(gainHF != 1.0f) voice->Direct.FilterType |= AF_LowPass; if(gainLF != 1.0f) voice->Direct.FilterType |= AF_HighPass; ALfilterState_setParams( &voice->Direct.Params[0].LowPass, ALfilterType_HighShelf, gainHF, hfScale, calc_rcpQ_from_slope(gainHF, 1.0f) ); ALfilterState_setParams( &voice->Direct.Params[0].HighPass, ALfilterType_LowShelf, gainLF, lfScale, calc_rcpQ_from_slope(gainLF, 1.0f) ); for(c = 1;c < num_channels;c++) { ALfilterState_copyParams(&voice->Direct.Params[c].LowPass, &voice->Direct.Params[0].LowPass); ALfilterState_copyParams(&voice->Direct.Params[c].HighPass, &voice->Direct.Params[0].HighPass); } } for(i = 0;i < NumSends;i++) { ALfloat hfScale = props->Send[i].HFReference / Frequency; ALfloat lfScale = props->Send[i].LFReference / Frequency; ALfloat gainHF = maxf(WetGainHF[i], 0.001f); ALfloat gainLF = maxf(WetGainLF[i], 0.001f); voice->Send[i].FilterType = AF_None; if(gainHF != 1.0f) voice->Send[i].FilterType |= AF_LowPass; if(gainLF != 1.0f) voice->Send[i].FilterType |= AF_HighPass; ALfilterState_setParams( &voice->Send[i].Params[0].LowPass, ALfilterType_HighShelf, gainHF, hfScale, calc_rcpQ_from_slope(gainHF, 1.0f) ); ALfilterState_setParams( &voice->Send[i].Params[0].HighPass, ALfilterType_LowShelf, gainLF, lfScale, calc_rcpQ_from_slope(gainLF, 1.0f) ); for(c = 1;c < num_channels;c++) { ALfilterState_copyParams(&voice->Send[i].Params[c].LowPass, &voice->Send[i].Params[0].LowPass); ALfilterState_copyParams(&voice->Send[i].Params[c].HighPass, &voice->Send[i].Params[0].HighPass); } } } static void CalcNonAttnSourceParams(ALvoice *voice, const struct ALvoiceProps *props, const ALbuffer *ALBuffer, const ALCcontext *ALContext) { static const ALfloat dir[3] = { 0.0f, 0.0f, -1.0f }; const ALCdevice *Device = ALContext->Device; const ALlistener *Listener = ALContext->Listener; ALfloat DryGain, DryGainHF, DryGainLF; ALfloat WetGain[MAX_SENDS]; ALfloat WetGainHF[MAX_SENDS]; ALfloat WetGainLF[MAX_SENDS]; ALeffectslot *SendSlots[MAX_SENDS]; ALfloat Pitch; ALsizei i; voice->Direct.Buffer = Device->Dry.Buffer; voice->Direct.Channels = Device->Dry.NumChannels; for(i = 0;i < Device->NumAuxSends;i++) { SendSlots[i] = props->Send[i].Slot; if(!SendSlots[i] && i == 0) SendSlots[i] = ALContext->DefaultSlot; if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL) { SendSlots[i] = NULL; voice->Send[i].Buffer = NULL; voice->Send[i].Channels = 0; } else { voice->Send[i].Buffer = SendSlots[i]->WetBuffer; voice->Send[i].Channels = SendSlots[i]->NumChannels; } } /* Calculate the stepping value */ Pitch = (ALfloat)ALBuffer->Frequency/(ALfloat)Device->Frequency * props->Pitch; if(Pitch > (ALfloat)MAX_PITCH) voice->Step = MAX_PITCH<<FRACTIONBITS; else voice->Step = maxi(fastf2i(Pitch*FRACTIONONE + 0.5f), 1); BsincPrepare(voice->Step, &voice->ResampleState.bsinc); voice->Resampler = SelectResampler(props->Resampler); /* Calculate gains */ DryGain = clampf(props->Gain, props->MinGain, props->MaxGain); DryGain *= props->Direct.Gain * Listener->Params.Gain; DryGain = minf(DryGain, GAIN_MIX_MAX); DryGainHF = props->Direct.GainHF; DryGainLF = props->Direct.GainLF; for(i = 0;i < Device->NumAuxSends;i++) { WetGain[i] = clampf(props->Gain, props->MinGain, props->MaxGain); WetGain[i] *= props->Send[i].Gain * Listener->Params.Gain; WetGain[i] = minf(WetGain[i], GAIN_MIX_MAX); WetGainHF[i] = props->Send[i].GainHF; WetGainLF[i] = props->Send[i].GainLF; } CalcPanningAndFilters(voice, 0.0f, dir, 0.0f, DryGain, DryGainHF, DryGainLF, WetGain, WetGainLF, WetGainHF, SendSlots, ALBuffer, props, Listener, Device); } static void CalcAttnSourceParams(ALvoice *voice, const struct ALvoiceProps *props, const ALbuffer *ALBuffer, const ALCcontext *ALContext) { const ALCdevice *Device = ALContext->Device; const ALlistener *Listener = ALContext->Listener; const ALsizei NumSends = Device->NumAuxSends; aluVector Position, Velocity, Direction, SourceToListener; ALfloat Distance, ClampedDist, DopplerFactor; ALeffectslot *SendSlots[MAX_SENDS]; ALfloat RoomRolloff[MAX_SENDS]; ALfloat DecayDistance[MAX_SENDS]; ALfloat DecayHFDistance[MAX_SENDS]; ALfloat DryGain, DryGainHF, DryGainLF; ALfloat WetGain[MAX_SENDS]; ALfloat WetGainHF[MAX_SENDS]; ALfloat WetGainLF[MAX_SENDS]; bool directional; ALfloat dir[3]; ALfloat spread; ALfloat Pitch; ALint i; /* Set mixing buffers and get send parameters. */ voice->Direct.Buffer = Device->Dry.Buffer; voice->Direct.Channels = Device->Dry.NumChannels; for(i = 0;i < NumSends;i++) { SendSlots[i] = props->Send[i].Slot; if(!SendSlots[i] && i == 0) SendSlots[i] = ALContext->DefaultSlot; if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL) { SendSlots[i] = NULL; RoomRolloff[i] = 0.0f; DecayDistance[i] = 0.0f; DecayHFDistance[i] = 0.0f; } else if(SendSlots[i]->Params.AuxSendAuto) { RoomRolloff[i] = SendSlots[i]->Params.RoomRolloff + props->RoomRolloffFactor; DecayDistance[i] = SendSlots[i]->Params.DecayTime * SPEEDOFSOUNDMETRESPERSEC; DecayHFDistance[i] = DecayDistance[i] * SendSlots[i]->Params.DecayHFRatio; if(SendSlots[i]->Params.DecayHFLimit) { ALfloat airAbsorption = SendSlots[i]->Params.AirAbsorptionGainHF; if(airAbsorption < 1.0f) { ALfloat limitRatio = log10f(REVERB_DECAY_GAIN) / log10f(airAbsorption); DecayHFDistance[i] = minf(limitRatio, DecayHFDistance[i]); } } } else { /* If the slot's auxiliary send auto is off, the data sent to the * effect slot is the same as the dry path, sans filter effects */ RoomRolloff[i] = props->RolloffFactor; DecayDistance[i] = 0.0f; DecayHFDistance[i] = 0.0f; } if(!SendSlots[i]) { voice->Send[i].Buffer = NULL; voice->Send[i].Channels = 0; } else { voice->Send[i].Buffer = SendSlots[i]->WetBuffer; voice->Send[i].Channels = SendSlots[i]->NumChannels; } } /* Transform source to listener space (convert to head relative) */ aluVectorSet(&Position, props->Position[0], props->Position[1], props->Position[2], 1.0f); aluVectorSet(&Direction, props->Direction[0], props->Direction[1], props->Direction[2], 0.0f); aluVectorSet(&Velocity, props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f); if(props->HeadRelative == AL_FALSE) { const aluMatrixf *Matrix = &Listener->Params.Matrix; /* Transform source vectors */ Position = aluMatrixfVector(Matrix, &Position); Velocity = aluMatrixfVector(Matrix, &Velocity); Direction = aluMatrixfVector(Matrix, &Direction); } else { const aluVector *lvelocity = &Listener->Params.Velocity; /* Offset the source velocity to be relative of the listener velocity */ Velocity.v[0] += lvelocity->v[0]; Velocity.v[1] += lvelocity->v[1]; Velocity.v[2] += lvelocity->v[2]; } directional = aluNormalize(Direction.v) > FLT_EPSILON; SourceToListener.v[0] = -Position.v[0]; SourceToListener.v[1] = -Position.v[1]; SourceToListener.v[2] = -Position.v[2]; SourceToListener.v[3] = 0.0f; Distance = aluNormalize(SourceToListener.v); /* Initial source gain */ DryGain = props->Gain; DryGainHF = 1.0f; DryGainLF = 1.0f; for(i = 0;i < NumSends;i++) { WetGain[i] = props->Gain; WetGainHF[i] = 1.0f; WetGainLF[i] = 1.0f; } /* Calculate distance attenuation */ ClampedDist = Distance; switch(Listener->Params.SourceDistanceModel ? props->DistanceModel : Listener->Params.DistanceModel) { case InverseDistanceClamped: ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance); if(props->MaxDistance < props->RefDistance) break; /*fall-through*/ case InverseDistance: if(!(props->RefDistance > 0.0f)) ClampedDist = props->RefDistance; else { ALfloat dist = lerp(props->RefDistance, ClampedDist, props->RolloffFactor); if(dist > 0.0f) DryGain *= props->RefDistance / dist; for(i = 0;i < NumSends;i++) { dist = lerp(props->RefDistance, ClampedDist, RoomRolloff[i]); if(dist > 0.0f) WetGain[i] *= props->RefDistance / dist; } } break; case LinearDistanceClamped: ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance); if(props->MaxDistance < props->RefDistance) break; /*fall-through*/ case LinearDistance: if(!(props->MaxDistance != props->RefDistance)) ClampedDist = props->RefDistance; else { ALfloat attn = props->RolloffFactor * (ClampedDist-props->RefDistance) / (props->MaxDistance-props->RefDistance); DryGain *= maxf(1.0f - attn, 0.0f); for(i = 0;i < NumSends;i++) { attn = RoomRolloff[i] * (ClampedDist-props->RefDistance) / (props->MaxDistance-props->RefDistance); WetGain[i] *= maxf(1.0f - attn, 0.0f); } } break; case ExponentDistanceClamped: ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance); if(props->MaxDistance < props->RefDistance) break; /*fall-through*/ case ExponentDistance: if(!(ClampedDist > 0.0f && props->RefDistance > 0.0f)) ClampedDist = props->RefDistance; else { DryGain *= powf(ClampedDist/props->RefDistance, -props->RolloffFactor); for(i = 0;i < NumSends;i++) WetGain[i] *= powf(ClampedDist/props->RefDistance, -RoomRolloff[i]); } break; case DisableDistance: ClampedDist = props->RefDistance; break; } /* Distance-based air absorption */ if(ClampedDist > props->RefDistance && props->RolloffFactor > 0.0f) { ALfloat meters_base = (ClampedDist-props->RefDistance) * props->RolloffFactor * Listener->Params.MetersPerUnit; if(props->AirAbsorptionFactor > 0.0f) { ALfloat hfattn = powf(AIRABSORBGAINHF, meters_base * props->AirAbsorptionFactor); DryGainHF *= hfattn; for(i = 0;i < NumSends;i++) WetGainHF[i] *= hfattn; } if(props->WetGainAuto) { /* Apply a decay-time transformation to the wet path, based on the * source distance in meters. The initial decay of the reverb * effect is calculated and applied to the wet path. */ for(i = 0;i < NumSends;i++) { ALfloat gain; if(!(DecayDistance[i] > 0.0f)) continue; gain = powf(REVERB_DECAY_GAIN, meters_base/DecayDistance[i]); WetGain[i] *= gain; /* Yes, the wet path's air absorption is applied with * WetGainAuto on, rather than WetGainHFAuto. */ if(gain > 0.0f) { ALfloat gainhf = powf(REVERB_DECAY_GAIN, meters_base/DecayHFDistance[i]); WetGainHF[i] *= minf(gainhf / gain, 1.0f); } } } } /* Calculate directional soundcones */ if(directional && props->InnerAngle < 360.0f) { ALfloat ConeVolume; ALfloat ConeHF; ALfloat Angle; Angle = acosf(aluDotproduct(&Direction, &SourceToListener)); Angle = RAD2DEG(Angle * ConeScale * 2.0f); if(!(Angle > props->InnerAngle)) { ConeVolume = 1.0f; ConeHF = 1.0f; } else if(Angle < props->OuterAngle) { ALfloat scale = ( Angle-props->InnerAngle) / (props->OuterAngle-props->InnerAngle); ConeVolume = lerp(1.0f, props->OuterGain, scale); ConeHF = lerp(1.0f, props->OuterGainHF, scale); } else { ConeVolume = props->OuterGain; ConeHF = props->OuterGainHF; } DryGain *= ConeVolume; if(props->DryGainHFAuto) DryGainHF *= ConeHF; if(props->WetGainAuto) { for(i = 0;i < NumSends;i++) WetGain[i] *= ConeVolume; } if(props->WetGainHFAuto) { for(i = 0;i < NumSends;i++) WetGainHF[i] *= ConeHF; } } /* Apply gain and frequency filters */ DryGain = clampf(DryGain, props->MinGain, props->MaxGain); DryGain = minf(DryGain*props->Direct.Gain*Listener->Params.Gain, GAIN_MIX_MAX); DryGainHF *= props->Direct.GainHF; DryGainLF *= props->Direct.GainLF; for(i = 0;i < NumSends;i++) { WetGain[i] = clampf(WetGain[i], props->MinGain, props->MaxGain); WetGain[i] = minf(WetGain[i]*props->Send[i].Gain*Listener->Params.Gain, GAIN_MIX_MAX); WetGainHF[i] *= props->Send[i].GainHF; WetGainLF[i] *= props->Send[i].GainLF; } /* Initial source pitch */ Pitch = props->Pitch; /* Calculate velocity-based doppler effect */ DopplerFactor = props->DopplerFactor * Listener->Params.DopplerFactor; if(DopplerFactor > 0.0f) { const aluVector *lvelocity = &Listener->Params.Velocity; const ALfloat SpeedOfSound = Listener->Params.SpeedOfSound; ALfloat vss, vls; vss = aluDotproduct(&Velocity, &SourceToListener) * DopplerFactor; vls = aluDotproduct(lvelocity, &SourceToListener) * DopplerFactor; if(!(vls < SpeedOfSound)) { /* Listener moving away from the source at the speed of sound. * Sound waves can't catch it. */ Pitch = 0.0f; } else if(!(vss < SpeedOfSound)) { /* Source moving toward the listener at the speed of sound. Sound * waves bunch up to extreme frequencies. */ Pitch = HUGE_VALF; } else { /* Source and listener movement is nominal. Calculate the proper * doppler shift. */ Pitch *= (SpeedOfSound-vls) / (SpeedOfSound-vss); } } /* Adjust pitch based on the buffer and output frequencies, and calculate * fixed-point stepping value. */ Pitch *= (ALfloat)ALBuffer->Frequency/(ALfloat)Device->Frequency; if(Pitch > (ALfloat)MAX_PITCH) voice->Step = MAX_PITCH<<FRACTIONBITS; else voice->Step = maxi(fastf2i(Pitch*FRACTIONONE + 0.5f), 1); BsincPrepare(voice->Step, &voice->ResampleState.bsinc); voice->Resampler = SelectResampler(props->Resampler); if(Distance > FLT_EPSILON) { dir[0] = -SourceToListener.v[0]; /* Clamp Y, in case rounding errors caused it to end up outside of * -1...+1. */ dir[1] = clampf(-SourceToListener.v[1], -1.0f, 1.0f); dir[2] = -SourceToListener.v[2] * ZScale; } else { dir[0] = 0.0f; dir[1] = 0.0f; dir[2] = -1.0f; } if(props->Radius > Distance) spread = F_TAU - Distance/props->Radius*F_PI; else if(Distance > FLT_EPSILON) spread = asinf(props->Radius / Distance) * 2.0f; else spread = 0.0f; CalcPanningAndFilters(voice, Distance, dir, spread, DryGain, DryGainHF, DryGainLF, WetGain, WetGainLF, WetGainHF, SendSlots, ALBuffer, props, Listener, Device); } static void CalcSourceParams(ALvoice *voice, ALCcontext *context, ALboolean force) { ALbufferlistitem *BufferListItem; struct ALvoiceProps *props; props = ATOMIC_EXCHANGE_PTR(&voice->Update, NULL, almemory_order_acq_rel); if(!props && !force) return; if(props) { memcpy(voice->Props, props, FAM_SIZE(struct ALvoiceProps, Send, context->Device->NumAuxSends) ); ATOMIC_REPLACE_HEAD(struct ALvoiceProps*, &voice->FreeList, props); } props = voice->Props; BufferListItem = ATOMIC_LOAD(&voice->current_buffer, almemory_order_relaxed); while(BufferListItem != NULL) { const ALbuffer *buffer; if((buffer=BufferListItem->buffer) != NULL) { if(props->SpatializeMode == SpatializeOn || (props->SpatializeMode == SpatializeAuto && buffer->FmtChannels == FmtMono)) CalcAttnSourceParams(voice, props, buffer, context); else CalcNonAttnSourceParams(voice, props, buffer, context); break; } BufferListItem = ATOMIC_LOAD(&BufferListItem->next, almemory_order_acquire); } } static void UpdateContextSources(ALCcontext *ctx, const struct ALeffectslotArray *slots) { ALvoice **voice, **voice_end; ALsource *source; ALsizei i; IncrementRef(&ctx->UpdateCount); if(!ATOMIC_LOAD(&ctx->HoldUpdates, almemory_order_acquire)) { ALboolean force = CalcListenerParams(ctx); for(i = 0;i < slots->count;i++) force |= CalcEffectSlotParams(slots->slot[i], ctx->Device); voice = ctx->Voices; voice_end = voice + ctx->VoiceCount; for(;voice != voice_end;++voice) { source = ATOMIC_LOAD(&(*voice)->Source, almemory_order_acquire); if(source) CalcSourceParams(*voice, ctx, force); } } IncrementRef(&ctx->UpdateCount); } static void ApplyDistanceComp(ALfloatBUFFERSIZE *restrict Samples, DistanceComp *distcomp, ALfloat *restrict Values, ALsizei SamplesToDo, ALsizei numchans) { ALsizei i, c; Values = ASSUME_ALIGNED(Values, 16); for(c = 0;c < numchans;c++) { ALfloat *restrict inout = ASSUME_ALIGNED(Samples[c], 16); const ALfloat gain = distcomp[c].Gain; const ALsizei base = distcomp[c].Length; ALfloat *restrict distbuf = ASSUME_ALIGNED(distcomp[c].Buffer, 16); if(base == 0) { if(gain < 1.0f) { for(i = 0;i < SamplesToDo;i++) inout[i] *= gain; } continue; } if(SamplesToDo >= base) { for(i = 0;i < base;i++) Values[i] = distbuf[i]; for(;i < SamplesToDo;i++) Values[i] = inout[i-base]; memcpy(distbuf, &inout[SamplesToDo-base], base*sizeof(ALfloat)); } else { for(i = 0;i < SamplesToDo;i++) Values[i] = distbuf[i]; memmove(distbuf, distbuf+SamplesToDo, (base-SamplesToDo)*sizeof(ALfloat)); memcpy(distbuf+base-SamplesToDo, inout, SamplesToDo*sizeof(ALfloat)); } for(i = 0;i < SamplesToDo;i++) inout[i] = Values[i]*gain; } } static void ApplyDither(ALfloatBUFFERSIZE *restrict Samples, ALuint *dither_seed, const ALfloat quant_scale, const ALsizei SamplesToDo, const ALsizei numchans) { const ALfloat invscale = 1.0f / quant_scale; ALuint seed = *dither_seed; ALsizei c, i; /* Dithering. Step 1, generate whitenoise (uniform distribution of random * values between -1 and +1). Step 2 is to add the noise to the samples, * before rounding and after scaling up to the desired quantization depth. */ for(c = 0;c < numchans;c++) { ALfloat *restrict samples = Samples[c]; for(i = 0;i < SamplesToDo;i++) { ALfloat val = samples[i] * quant_scale; ALuint rng0 = dither_rng(&seed); ALuint rng1 = dither_rng(&seed); val += (ALfloat)(rng0*(1.0/UINT_MAX) - rng1*(1.0/UINT_MAX)); samples[i] = roundf(val) * invscale; } } *dither_seed = seed; } static inline ALfloat Conv_ALfloat(ALfloat val) { return val; } static inline ALint Conv_ALint(ALfloat val) { /* Floats only have a 24-bit mantissa, so [-16777216, +16777216] is the max * integer range normalized floats can be safely converted to (a bit of the * exponent helps out, effectively giving 25 bits). */ return fastf2i(clampf(val*16777216.0f, -16777216.0f, 16777215.0f))<<7; } static inline ALshort Conv_ALshort(ALfloat val) { return fastf2i(clampf(val*32768.0f, -32768.0f, 32767.0f)); } static inline ALbyte Conv_ALbyte(ALfloat val) { return fastf2i(clampf(val*128.0f, -128.0f, 127.0f)); } /* Define unsigned output variations. */ #define DECL_TEMPLATE(T, func, O) \ static inline T Conv_##T(ALfloat val) { return func(val)+O; } DECL_TEMPLATE(ALubyte, Conv_ALbyte, 128) DECL_TEMPLATE(ALushort, Conv_ALshort, 32768) DECL_TEMPLATE(ALuint, Conv_ALint, 2147483648u) #undef DECL_TEMPLATE #define DECL_TEMPLATE(T, A) \ static void Write##A(const ALfloatBUFFERSIZE *InBuffer, ALvoid *OutBuffer, \ ALsizei Offset, ALsizei SamplesToDo, ALsizei numchans) \ { \ ALsizei i, j; \ for(j = 0;j < numchans;j++) \ { \ const ALfloat *restrict in = ASSUME_ALIGNED(InBuffer[j], 16); \ T *restrict out = (T*)OutBuffer + Offset*numchans + j; \ \ for(i = 0;i < SamplesToDo;i++) \ out[i*numchans] = Conv_##T(in[i]); \ } \ } DECL_TEMPLATE(ALfloat, F32) DECL_TEMPLATE(ALuint, UI32) DECL_TEMPLATE(ALint, I32) DECL_TEMPLATE(ALushort, UI16) DECL_TEMPLATE(ALshort, I16) DECL_TEMPLATE(ALubyte, UI8) DECL_TEMPLATE(ALbyte, I8) #undef DECL_TEMPLATE void aluMixData(ALCdevice *device, ALvoid *OutBuffer, ALsizei NumSamples) { ALsizei SamplesToDo; ALsizei SamplesDone; ALCcontext *ctx; ALsizei i, c; START_MIXER_MODE(); for(SamplesDone = 0;SamplesDone < NumSamples;) { SamplesToDo = mini(NumSamples-SamplesDone, BUFFERSIZE); for(c = 0;c < device->Dry.NumChannels;c++) memset(device->Dry.Buffer[c], 0, SamplesToDo*sizeof(ALfloat)); if(device->Dry.Buffer != device->FOAOut.Buffer) for(c = 0;c < device->FOAOut.NumChannels;c++) memset(device->FOAOut.Buffer[c], 0, SamplesToDo*sizeof(ALfloat)); if(device->Dry.Buffer != device->RealOut.Buffer) for(c = 0;c < device->RealOut.NumChannels;c++) memset(device->RealOut.Buffer[c], 0, SamplesToDo*sizeof(ALfloat)); IncrementRef(&device->MixCount); ctx = ATOMIC_LOAD(&device->ContextList, almemory_order_acquire); while(ctx) { const struct ALeffectslotArray *auxslots; auxslots = ATOMIC_LOAD(&ctx->ActiveAuxSlots, almemory_order_acquire); UpdateContextSources(ctx, auxslots); for(i = 0;i < auxslots->count;i++) { ALeffectslot *slot = auxslots->slot[i]; for(c = 0;c < slot->NumChannels;c++) memset(slot->WetBuffer[c], 0, SamplesToDo*sizeof(ALfloat)); } /* source processing */ for(i = 0;i < ctx->VoiceCount;i++) { ALvoice *voice = ctx->Voices[i]; ALsource *source = ATOMIC_LOAD(&voice->Source, almemory_order_acquire); if(source && ATOMIC_LOAD(&voice->Playing, almemory_order_relaxed) && voice->Step > 0) { if(!MixSource(voice, source, device, SamplesToDo)) { ATOMIC_STORE(&voice->Source, NULL, almemory_order_relaxed); ATOMIC_STORE(&voice->Playing, false, almemory_order_release); } } } /* effect slot processing */ for(i = 0;i < auxslots->count;i++) { const ALeffectslot *slot = auxslots->slot[i]; ALeffectState *state = slot->Params.EffectState; V(state,process)(SamplesToDo, slot->WetBuffer, state->OutBuffer, state->OutChannels); } ctx = ctx->next; } /* Increment the clock time. Every second's worth of samples is * converted and added to clock base so that large sample counts don't * overflow during conversion. This also guarantees an exact, stable * conversion. */ device->SamplesDone += SamplesToDo; device->ClockBase += (device->SamplesDone/device->Frequency) * DEVICE_CLOCK_RES; device->SamplesDone %= device->Frequency; IncrementRef(&device->MixCount); if(device->HrtfHandle) { HrtfDirectMixerFunc HrtfMix; DirectHrtfState *state; int lidx, ridx; if(device->AmbiUp) ambiup_process(device->AmbiUp, device->Dry.Buffer, device->Dry.NumChannels, SAFE_CONST(ALfloatBUFFERSIZE*,device->FOAOut.Buffer), SamplesToDo ); lidx = GetChannelIdxByName(device->RealOut, FrontLeft); ridx = GetChannelIdxByName(device->RealOut, FrontRight); assert(lidx != -1 && ridx != -1); HrtfMix = SelectHrtfMixer(); state = device->Hrtf; for(c = 0;c < device->Dry.NumChannels;c++) { HrtfMix(device->RealOut.Buffer[lidx], device->RealOut.Buffer[ridx], device->Dry.Buffer[c], state->Offset, state->IrSize, SAFE_CONST(ALfloat2*,state->Chan[c].Coeffs), state->Chan[c].Values, SamplesToDo ); } state->Offset += SamplesToDo; } else if(device->AmbiDecoder) { if(device->Dry.Buffer != device->FOAOut.Buffer) bformatdec_upSample(device->AmbiDecoder, device->Dry.Buffer, SAFE_CONST(ALfloatBUFFERSIZE*,device->FOAOut.Buffer), device->FOAOut.NumChannels, SamplesToDo ); bformatdec_process(device->AmbiDecoder, device->RealOut.Buffer, device->RealOut.NumChannels, SAFE_CONST(ALfloatBUFFERSIZE*,device->Dry.Buffer), SamplesToDo ); } else if(device->AmbiUp) { ambiup_process(device->AmbiUp, device->RealOut.Buffer, device->RealOut.NumChannels, SAFE_CONST(ALfloatBUFFERSIZE*,device->FOAOut.Buffer), SamplesToDo ); } else if(device->Uhj_Encoder) { int lidx = GetChannelIdxByName(device->RealOut, FrontLeft); int ridx = GetChannelIdxByName(device->RealOut, FrontRight); if(lidx != -1 && ridx != -1) { /* Encode to stereo-compatible 2-channel UHJ output. */ EncodeUhj2(device->Uhj_Encoder, device->RealOut.Buffer[lidx], device->RealOut.Buffer[ridx], device->Dry.Buffer, SamplesToDo ); } } else if(device->Bs2b) { int lidx = GetChannelIdxByName(device->RealOut, FrontLeft); int ridx = GetChannelIdxByName(device->RealOut, FrontRight); if(lidx != -1 && ridx != -1) { /* Apply binaural/crossfeed filter */ bs2b_cross_feed(device->Bs2b, device->RealOut.Buffer[lidx], device->RealOut.Buffer[ridx], SamplesToDo); } } if(OutBuffer) { ALfloat (*Buffer)[BUFFERSIZE] = device->RealOut.Buffer; ALsizei Channels = device->RealOut.NumChannels; /* Use NFCtrlData for temp value storage. */ ApplyDistanceComp(Buffer, device->ChannelDelay, device->NFCtrlData, SamplesToDo, Channels); if(device->Limiter) ApplyCompression(device->Limiter, Channels, SamplesToDo, Buffer); if(device->DitherDepth > 0.0f) ApplyDither(Buffer, &device->DitherSeed, device->DitherDepth, SamplesToDo, Channels); switch(device->FmtType) { case DevFmtByte: WriteI8(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels); break; case DevFmtUByte: WriteUI8(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels); break; case DevFmtShort: WriteI16(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels); break; case DevFmtUShort: WriteUI16(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels); break; case DevFmtInt: WriteI32(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels); break; case DevFmtUInt: WriteUI32(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels); break; case DevFmtFloat: WriteF32(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels); break; } } SamplesDone += SamplesToDo; } END_MIXER_MODE(); } void aluHandleDisconnect(ALCdevice *device) { ALCcontext *ctx; device->Connected = ALC_FALSE; ctx = ATOMIC_LOAD_SEQ(&device->ContextList); while(ctx) { ALsizei i; for(i = 0;i < ctx->VoiceCount;i++) { ALvoice *voice = ctx->Voices[i]; ALsource *source; source = ATOMIC_EXCHANGE_PTR(&voice->Source, NULL, almemory_order_acq_rel); ATOMIC_STORE(&voice->Playing, false, almemory_order_release); if(source) { ALenum playing = AL_PLAYING; (void)(ATOMIC_COMPARE_EXCHANGE_STRONG_SEQ(&source->state, &playing, AL_STOPPED)); } } ctx->VoiceCount = 0; ctx = ctx->next; } }
38.264336
141
0.528974
[ "render", "vector", "transform" ]
458b338c9f1c923e4bffdbd5965aca1c3e01b284
2,210
h
C
ui/ozone/platform/drm/host/host_cursor_proxy.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
ui/ozone/platform/drm/host/host_cursor_proxy.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
ui/ozone/platform/drm/host/host_cursor_proxy.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_OZONE_PLATFORM_DRM_HOST_HOST_CURSOR_PROXY_H_ #define UI_OZONE_PLATFORM_DRM_HOST_HOST_CURSOR_PROXY_H_ #include "base/task/single_thread_task_runner.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_associated_remote.h" #include "ui/gfx/native_widget_types.h" #include "ui/ozone/platform/drm/host/drm_cursor.h" #include "ui/ozone/platform/drm/mojom/device_cursor.mojom.h" namespace ui { // Ozone requires a IPC from the browser (or mus-ws) process to the gpu (or // mus-gpu) process to control the mouse pointer. This class provides mouse // pointer control via Mojo-style IPC. This code runs only in the mus-ws (i.e. // it's the client) and sends mouse pointer control messages to a less // priviledged process. class HostCursorProxy : public DrmCursorProxy { public: HostCursorProxy( mojo::PendingAssociatedRemote<ui::ozone::mojom::DeviceCursor> main_cursor, mojo::PendingAssociatedRemote<ui::ozone::mojom::DeviceCursor> evdev_cursor); HostCursorProxy(const HostCursorProxy&) = delete; HostCursorProxy& operator=(const HostCursorProxy&) = delete; ~HostCursorProxy() override; private: // DrmCursorProxy. void CursorSet(gfx::AcceleratedWidget window, const std::vector<SkBitmap>& bitmaps, const gfx::Point& point, base::TimeDelta frame_delay) override; void Move(gfx::AcceleratedWidget window, const gfx::Point& point) override; void InitializeOnEvdevIfNecessary() override; // Accessed from UI thread only. mojo::AssociatedRemote<ui::ozone::mojom::DeviceCursor> main_cursor_; // Accessed from evdev thread only. mojo::AssociatedRemote<ui::ozone::mojom::DeviceCursor> evdev_cursor_; mojo::PendingAssociatedRemote<ui::ozone::mojom::DeviceCursor> evdev_cursor_pending_remote_; base::PlatformThreadRef ui_thread_ref_; scoped_refptr<base::SingleThreadTaskRunner> evdev_task_runner_; }; } // namespace ui #endif // UI_OZONE_PLATFORM_DRM_HOST_HOST_CURSOR_PROXY_H_
38.103448
80
0.761538
[ "vector" ]
4590dcce52375161cd5cc65c5bb5b8b56e0902be
3,532
h
C
src/HapticDirectoryTools.h
HardlightVR/HL-haptictools
c177a92ce3adab80416f0e85c1ad89083d9da6b6
[ "MIT" ]
null
null
null
src/HapticDirectoryTools.h
HardlightVR/HL-haptictools
c177a92ce3adab80416f0e85c1ad89083d9da6b6
[ "MIT" ]
null
null
null
src/HapticDirectoryTools.h
HardlightVR/HL-haptictools
c177a92ce3adab80416f0e85c1ad89083d9da6b6
[ "MIT" ]
1
2020-06-29T14:42:24.000Z
2020-06-29T14:42:24.000Z
#pragma once #include <string> #include <vector> #include <unordered_map> #include <boost\filesystem.hpp> #include "IJsonSerializable.h" #include "rapidjson\document.h" #include <unordered_map> #include <boost\functional\hash\hash.hpp> #include "HapticsLoadingException.h" class JsonValueInvalidException : public std::runtime_error { public: JsonValueInvalidException(const std::string& key) : std::runtime_error(std::string("Key '" + key + "' has an invalid value or is not present").c_str()) {} }; class HapticsRootDirectoryNotFound : public HapticsLoadingException { public: HapticsRootDirectoryNotFound(std::string err) : HapticsLoadingException(err) {} }; template<class T> T parseKeyOrThrow(const rapidjson::Value& root, const char* key) { rapidjson::Value::ConstMemberIterator itr = root.FindMember(key); if (itr != root.MemberEnd()) { return itr->value.Get<T>(); } else { throw JsonValueInvalidException(key); } } void findKeyOrThrow(const rapidjson::Value& root, const char* key); template<class T> T parseKeyOrDefault(const rapidjson::Value& root, const char* key, T defaultVal) { rapidjson::Value::ConstMemberIterator itr = root.FindMember(key); if (itr != root.MemberEnd()) { return itr->value.Get<T>(); } else { return defaultVal; } } namespace std { template<> struct hash<boost::filesystem::path> { size_t operator()(const boost::filesystem::path& p) const { return boost::filesystem::hash_value(p); } }; } namespace HapticDirectoryTools { class HapticFileNameList { public: std::vector<std::string> Patterns; std::vector<std::string> Sequences; std::vector<std::string> Experiences; std::string Namespace; std::string Studio; boost::filesystem::path Directory; std::string Description; }; class PackageNode { public: PackageNode() = default; PackageNode(HapticFileNameList data); std::string Namespace; HapticFileNameList Data; std::unordered_map<std::string, PackageNode> Children; }; class HapticConfig : public IJsonSerializable{ public: std::string Version; std::string Studio; std::string Package; std::string Description; virtual void Serialize(const rapidjson::Value& root) override; virtual void Deserialize(const rapidjson::Value& root) override; }; class HapticEnumerator { public: static const char* DirectoryNotFoundString; using package = std::tuple<boost::filesystem::path, HapticConfig>; HapticEnumerator(const std::string& path); PackageNode GeneratePackageTree(const std::vector<HapticFileNameList>& enumLists) const; std::vector<package> EnumeratePackages() const; std::vector<HapticFileNameList> GetAllFiles(const std::vector<package>& configs) const; std::vector<std::string> GetFileNames(boost::filesystem::path path) const; HapticFileNameList GetFilesInPackage(package config) const; static std::vector<boost::filesystem::path> GetDirectories(const std::string& path); private: std::vector<std::string> _validExtensions; std::string _basePath; void insert(PackageNode& node, HapticFileNameList& list) const; bool isValidFileExtension(const std::string& fileExtension) const; static const std::string PATTERN_DIR; static const std::string SEQUENCE_DIR; static const std::string EXPERIENCE_DIR; static const std::string MISSING_OR_INVALID_KEY; }; std::unordered_map<boost::filesystem::path, HapticConfig> GetPackageMap(const std::vector<HapticEnumerator::package>& packages); PackageNode GetAllPackages(const HapticEnumerator& enumerator); }
26.556391
129
0.749151
[ "vector" ]
45952bb8aea1df771a863de7452a49e6f59898da
5,454
c
C
word2vectocluto/word2vectocluto.c
LexicalCategoryInduction/NeuralNetworkLexicalCategoryInduction
d1f230af76dbdba370a2c0dc917f8beb44f5b2f6
[ "Apache-2.0" ]
1
2016-05-02T15:53:07.000Z
2016-05-02T15:53:07.000Z
word2vectocluto/word2vectocluto.c
LexicalCategoryInduction/NeuralNetworkLexicalCategoryInduction
d1f230af76dbdba370a2c0dc917f8beb44f5b2f6
[ "Apache-2.0" ]
null
null
null
word2vectocluto/word2vectocluto.c
LexicalCategoryInduction/NeuralNetworkLexicalCategoryInduction
d1f230af76dbdba370a2c0dc917f8beb44f5b2f6
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2016 Marianna D'Errico, Simone Bna' * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_STRING 500 #define MAX_WORDS 2000 int ArgPos(char *str, int argc, char **argv) { int a; for (a = 1; a < argc; a++) if (!strcmp(str, argv[a])) { if (a == argc - 1) { printf("Argument missing for %s\n", str); exit(1); } return a; } return -1; } int main(int argc, char **argv) { char input_file[MAX_STRING], input_words_file[MAX_STRING], omatrix_file[MAX_STRING],\ olabel_file[MAX_STRING], oclass_file[MAX_STRING], buf[MAX_STRING], str1[MAX_STRING], word_list[MAX_WORDS][MAX_STRING], class_list[MAX_WORDS][MAX_STRING]; int i, j, k, skip, nrow, mcol, nwords, nwords_found, word_exist[MAX_WORDS]; float number; if (argc == 1) { printf("Word2Vec to cluto matrix converter\n\n"); printf("Options:\n"); printf("Parameters:\n"); printf("\t-input_vector <file>\n"); printf("\t\tOutput vector file generated by word2vec\n"); printf("\t-input_word_list <file>\n"); printf("\t\tList of words to be found in the word vector generated by word2vec\n"); printf("\t-output_matrix <file>\n"); printf("\t-output_label <file>\n"); printf("\nExamples:\n"); printf("./word2vectocluto -input_vector vectors.txt -input_word_list word_list.txt -output_matrix vectors.mat -output_label vectors_label.mat\n\n"); return 0; } if ((i = ArgPos((char *)"-input_vector", argc, argv)) > 0) strcpy(input_file, argv[i + 1]); if ((i = ArgPos((char *)"-input_word_list", argc, argv)) > 0) strcpy(input_words_file, argv[i + 1]); if ((i = ArgPos((char *)"-output_matrix", argc, argv)) > 0) strcpy(omatrix_file, argv[i + 1]); if ((i = ArgPos((char *)"-output_label", argc, argv)) > 0) strcpy(olabel_file, argv[i + 1]); if ((i = ArgPos((char *)"-output_class_label", argc, argv)) > 0) strcpy(oclass_file, argv[i + 1]); FILE *fi; fi = fopen(input_file, "r"); if( fi == NULL ) { printf("A.\n"); printf("Error while opening the %s file.\n", input_file); exit(EXIT_FAILURE); } FILE *fi_words; fi_words = fopen(input_words_file, "r"); if( fi_words == NULL ) { printf("B.\n"); printf("Error while opening the %s file.\n", input_words_file); exit(EXIT_FAILURE); } FILE *fo_matrix; fo_matrix = fopen(omatrix_file, "w"); if( fo_matrix == NULL ) { printf("C.\n"); printf("Error while opening the %s file.\n", omatrix_file); exit(EXIT_FAILURE); } FILE *fo_label; fo_label = fopen(olabel_file, "w"); if( fo_label == NULL ) { printf("D.\n"); printf("Error while opening the %s file.\n", olabel_file); exit(EXIT_FAILURE); } FILE *fo_class; fo_class = fopen(oclass_file, "w"); if( fo_class == NULL ) { printf("D.\n"); printf("Error while opening the %s file.\n", oclass_file); exit(EXIT_FAILURE); } /* init word_exist to false */ for (i=0; i<MAX_WORDS; i++) { word_exist[i] = 0; } /* read the word list */ i = 0; while (fscanf(fi_words, "%s", buf) != EOF) { if(i%2 == 0) { strcpy(word_list[i/2], buf); } else { strcpy(class_list[i/2], buf); } /*printf("I read %s from file %s\n", word_list[i], input_words_file);*/ if(i%2 == 0) { for (j=0; j<(i/2); ++j) { if (!strcmp(word_list[i/2], word_list[j])) { printf("duplicate word : < %s >\n", word_list[j]); fscanf(fi_words, "%s", buf); --i; } } } ++i; } nwords = i/2; nwords_found = 0; printf("I read %d words\n", nwords); printf("Reading from file %s ...\n", input_file); fscanf(fi, "%d", &nrow); fscanf(fi, "%d", &mcol); fprintf(fo_matrix, "%-8d %-8d\n", nwords, mcol); i = 0; j = 0; k = 0; skip = 1; for (i = 0; i < nrow; i++) { skip = 1; fscanf(fi, "%s", str1); /** find the word in the list*/ for (k = 0; k < nwords; k++) { if (!strcmp(str1, word_list[k])) { /*printf("I found the word %s in the word list\n", str1);*/ word_exist[k] = 1; skip = 0; fprintf(fo_class, "%s\n", class_list[k]); } } if(!skip) { fprintf(fo_label, "%s\n", str1); } for (j = 0; j < mcol; j++) { fscanf(fi, "%f", &number); if(!skip) { fprintf(fo_matrix, "%f ", number); } } if(!skip) { fprintf(fo_matrix, "\n"); } } for(i=0; i<nwords; i++) { if(word_exist[i] == 0) { printf("The word < %s > from the list does not exist in the corpus.\n", word_list[i]); } else { nwords_found ++; } } printf("%d %d\n", nwords_found, mcol); rewind(fo_matrix); fprintf(fo_matrix, "%-8d %-8d\n", nwords_found, mcol); printf("...Done.\n"); fclose(fi_words); fclose(fo_matrix); fclose(fo_label); fclose(fo_class); fclose(fi); return 0; }
26.475728
157
0.589292
[ "vector" ]
459f5c2858efa1c7e99f8f8b44ba4abe6c8e9eb0
25,028
c
C
src/dR_nodes_math.c
mrjel/deepracin
42fc93a915b69d49d2f6d9b8603276bd23fd370e
[ "Apache-2.0" ]
8
2018-07-10T17:39:16.000Z
2018-10-22T18:13:30.000Z
src/dR_nodes_math.c
mrjel/deepracin
42fc93a915b69d49d2f6d9b8603276bd23fd370e
[ "Apache-2.0" ]
null
null
null
src/dR_nodes_math.c
mrjel/deepracin
42fc93a915b69d49d2f6d9b8603276bd23fd370e
[ "Apache-2.0" ]
1
2018-07-11T02:20:29.000Z
2018-07-11T02:20:29.000Z
#include "dR_nodes_math.h" #include "dR_core.h" // /////////////////////////// // Element-wise 2-operation // // /////////////////////////// dR_Node* dR_ElemWise2Operation(dR_Graph* net, dR_Node* inputLayer1, dR_Node* inputLayer2, dR_ElemWise2OperationType op){ dR_ElemWise2Op_Data* elemwise2op = g_malloc(sizeof(dR_ElemWise2Op_Data)); dR_Node* l = g_malloc(sizeof(dR_Node)); elemwise2op->op = op; l->layer = elemwise2op; l->type = tElemWise2Op; l->compute = dR_elemwise2op_compute; l->schedule = dR_elemwise2op_schedule; l->propagateShape = dR_elemwise2op_propagateShape; l->getRequiredOutputBufferSize = dR_elemwise2op_getRequiredOutputBufferSize; l->createKernel = dR_elemwise2op_createKernel; l->allocateBuffers = dR_elemwise2op_allocateBuffers; l->fillBuffers = dR_elemwise2op_fillBuffers; l->cleanupBuffers = dR_elemwise2op_cleanupBuffers; l->cleanupLayer = dR_elemwise2op_cleanupLayer; l->serializeNode = dR_elemwise2op_serializeNode; l->parseAppendNode = dR_elemwise2op_parseAppendNode; l->generateKernel = NULL; l->setVariables = NULL; l->createKernelName = NULL; l->printLayer = dR_elemwise2op_printLayer; if(inputLayer1&&inputLayer2) { l->previous_layers = dR_list_createEmptyList(); dR_list_append(l->previous_layers,inputLayer1); dR_list_append(l->previous_layers,inputLayer2); l->next_layers = dR_list_createEmptyList(); dR_list_append(inputLayer1->next_layers,l); dR_list_append(inputLayer2->next_layers,l); } else { g_print("Error: ElemWise2Operation node needs 2 appropriate Inputnodes"); } dR_appendLayer(net, l); return l; } gchar* dR_elemwise2op_serializeNode(dR_Node* layer, gchar* params[], gint* numParams, gfloat* variables[], gint variableSizes[], gint* numVariables) { dR_ElemWise2Op_Data* elemwise2op = (dR_ElemWise2Op_Data*)(layer->layer); gchar* desc = "ElemWise2Op"; gint numNodeParams = 1; gint numNodeVariables = 0; if(*numParams<numNodeParams||*numVariables<numNodeVariables) { g_print("SerializeNode needs space for %d parameters and %d variables!\n",numNodeParams,numNodeVariables); return NULL; } *numParams = numNodeParams; params[0] = g_strdup_printf("%d",elemwise2op->op); *numVariables = numNodeVariables; return desc; } dR_Node* dR_elemwise2op_parseAppendNode(dR_Graph* net, dR_Node** iNodes, gint numINodes, gchar** params, gint numParams, gfloat** variables, gint numVariables) { gint numNodeInputs = 2; gint numNodeParams = 1; gint numNodeVariables = 0; dR_Node* out; if(numINodes!=1) { g_print("Parsing Error: ElemWise2Op Node needs %d InputNodes but got %d!\n",numNodeInputs,numNodeVariables); return NULL; } if(numParams!=numNodeParams||numVariables!=numNodeVariables) { g_print("Parsing Error: ElemWise2Op Node needs %d Parameters and %d Variables!\n",numNodeParams,numNodeVariables); return NULL; } out = dR_ElemWise2Operation(net, iNodes[0], iNodes[1], atoi(params[0])); return out; } gboolean dR_elemwise2op_schedule(dR_Graph* net, dR_Node* layer){ // Nothing to do // Warnings shut up, please (void)net; (void)layer; return TRUE; } gboolean dR_elemwise2op_compute(dR_Graph* net, dR_Node* layer){ size_t globalWorkSize[3]; int paramid = 0; cl_mem* input1, *input2; dR_list_resetIt(layer->previous_layers); input1 = ((dR_Node*)dR_list_next(layer->previous_layers))->outputBuf->bufptr; input2 = ((dR_Node*)dR_list_next(layer->previous_layers))->outputBuf->bufptr; globalWorkSize[0] = layer->oshape.s0; globalWorkSize[1] = layer->oshape.s1; globalWorkSize[2] = layer->oshape.s2; net->clConfig->clError = clSetKernelArg(layer->clKernel, paramid, sizeof(cl_mem), (void *)input1); paramid++; net->clConfig->clError = clSetKernelArg(layer->clKernel, paramid, sizeof(cl_mem), (void *)input2); paramid++; net->clConfig->clError |= clSetKernelArg(layer->clKernel, paramid, sizeof(cl_mem), (void *)layer->outputBuf->bufptr); paramid++; if (dR_openCLError(net, "Setting kernel args failed.", "Element-wise 2-operation Kernel")) return FALSE; // execute kernel net->clConfig->clError = clEnqueueNDRangeKernel(net->clConfig->clCommandQueue, layer->clKernel, 3, NULL, globalWorkSize, NULL, 0, NULL, net->clConfig->clEvent); return dR_finishCLKernel(net, "deepRACIN:elemWise2Op"); } gboolean dR_elemwise2op_propagateShape(dR_Graph* net, dR_Node* layer) { dR_ElemWise2Op_Data* elemwise2op = (dR_ElemWise2Op_Data*)(layer->layer); dR_Node* lastlayer; if(layer->previous_layers->length!=2) { if(!net->config->silent) g_print("Elem-wise 2-operation Node with id %d has %d inputs but needs 2!\n",layer->layerID,layer->previous_layers->length); return FALSE; } dR_list_resetIt(layer->previous_layers); lastlayer = dR_list_next(layer->previous_layers); elemwise2op->ishape.s0 = lastlayer->oshape.s0; elemwise2op->ishape.s1 = lastlayer->oshape.s1; elemwise2op->ishape.s2 = lastlayer->oshape.s2; lastlayer = dR_list_next(layer->previous_layers); if(elemwise2op->ishape.s0!=lastlayer->oshape.s0||elemwise2op->ishape.s1!=lastlayer->oshape.s1||elemwise2op->ishape.s2!=lastlayer->oshape.s2) { if(!net->config->silent) { g_print("Elem-wise 2-operation Node needs 2 input nodes with the same shape!\n"); g_print("[%d, %d, %d] and [%d, %d, %d] not matching!\n", elemwise2op->ishape.s0,elemwise2op->ishape.s1,elemwise2op->ishape.s2,lastlayer->oshape.s0,lastlayer->oshape.s1,lastlayer->oshape.s2); } return FALSE; } layer->oshape.s0 = elemwise2op->ishape.s0; layer->oshape.s1 = elemwise2op->ishape.s1; layer->oshape.s2 = elemwise2op->ishape.s2; return TRUE; } gint32 dR_elemwise2op_getRequiredOutputBufferSize(dR_Node* layer) { return layer->oshape.s0*layer->oshape.s1*layer->oshape.s2; } gboolean dR_elemwise2op_createKernel(dR_Graph* net, dR_Node* layer) { dR_ElemWise2Op_Data* elemwise2op = (dR_ElemWise2Op_Data*)(layer->layer); gboolean ret=FALSE; switch(elemwise2op->op){ case tAdd: ret = dR_createKernel(net,"elemWiseAdd",&(layer->clKernel)); break; case tSub: ret = dR_createKernel(net,"elemWiseSub",&(layer->clKernel)); break; case tMul: ret = dR_createKernel(net,"elemWiseMul",&(layer->clKernel)); break; case tDiv: ret = dR_createKernel(net,"elemWiseDiv",&(layer->clKernel)); break; case tPow: ret = dR_createKernel(net,"elemWisePow",&(layer->clKernel)); break; } return ret; } gboolean dR_elemwise2op_allocateBuffers(dR_Graph* net, dR_Node* layer) { // Nothing to do // Warnings shut up, please (void)net; (void)layer; return TRUE; } gboolean dR_elemwise2op_fillBuffers(dR_Graph* net, dR_Node* layer) { // Nothing to do // Warnings shut up, please (void)net; (void)layer; return TRUE; } gboolean dR_elemwise2op_cleanupBuffers(dR_Graph* net, dR_Node* layer) { gboolean ret = TRUE; if(net->prepared) ret &= dR_cleanupKernel((layer->clKernel)); return ret; } gboolean dR_elemwise2op_cleanupLayer(dR_Graph* net, dR_Node* layer) { if(net->prepared) g_free((dR_ElemWise2Op_Data*)(layer->layer)); return TRUE; } gchar* dR_elemwise2op_printLayer(dR_Node* layer) { dR_ElemWise2Op_Data* elemwise2op = (dR_ElemWise2Op_Data*)(layer->layer); gchar* out; gchar* op; switch(elemwise2op->op){ case tAdd: op = "Add"; break; case tSub: op = "Sub"; break; case tMul: op = "Mul"; break; case tDiv: op = "Div"; break; case tPow: op = "Pow"; break; default: op = "Error"; } out = g_strdup_printf("%s%d%s%s%s", "Element-wise 2 input operation node: ",layer->layerID, "\n Operation: ", op,"\n"); return out; } // /////////////////////////// // Element-wise 1-operation // // /////////////////////////// dR_Node* dR_ElemWise1Operation(dR_Graph* net, dR_Node* inputLayer, dR_ElemWise1OperationType op, gfloat scalar){ dR_ElemWise1Op_Data* elemwise1op = g_malloc(sizeof(dR_ElemWise1Op_Data)); dR_Node* l = g_malloc(sizeof(dR_Node)); elemwise1op->op = op; elemwise1op->scalar = scalar; l->layer = elemwise1op; l->type = tElemWise1Op; l->compute = dR_elemwise1op_compute; l->schedule = dR_elemwise1op_schedule; l->propagateShape = dR_elemwise1op_propagateShape; l->getRequiredOutputBufferSize = dR_elemwise1op_getRequiredOutputBufferSize; l->createKernel = dR_elemwise1op_createKernel; l->allocateBuffers = dR_elemwise1op_allocateBuffers; l->fillBuffers = dR_elemwise1op_fillBuffers; l->cleanupBuffers = dR_elemwise1op_cleanupBuffers; l->cleanupLayer = dR_elemwise1op_cleanupLayer; l->serializeNode = dR_elemwise1op_serializeNode; l->parseAppendNode = dR_elemwise1op_parseAppendNode; l->generateKernel = NULL; l->setVariables = NULL; l->createKernelName = NULL; l->printLayer = dR_elemwise1op_printLayer; if(inputLayer) { l->previous_layers = dR_list_createEmptyList(); dR_list_append(l->previous_layers,inputLayer); l->next_layers = dR_list_createEmptyList(); dR_list_append(inputLayer->next_layers,l); } else { g_print("Error: ElemWise2Operation node needs an appropriate Inputnode"); } dR_appendLayer(net, l); return l; } gchar* dR_elemwise1op_serializeNode(dR_Node* layer, gchar* params[], gint* numParams, gfloat* variables[], gint variableSizes[], gint* numVariables) { dR_ElemWise1Op_Data* elemwise1op = (dR_ElemWise1Op_Data*)(layer->layer); gchar* desc = "ElemWise1Op"; gint numNodeParams = 2; gint numNodeVariables = 0; if(*numParams<numNodeParams||*numVariables<numNodeVariables) { g_print("SerializeNode needs space for %d parameters and %d variables!\n",numNodeParams,numNodeVariables); return NULL; } *numParams = numNodeParams; params[0] = g_strdup_printf("%d",elemwise1op->op); params[1] = g_strdup_printf("%f",elemwise1op->scalar); *numVariables = numNodeVariables; return desc; } dR_Node* dR_elemwise1op_parseAppendNode(dR_Graph* net, dR_Node** iNodes, gint numINodes, gchar** params, gint numParams, gfloat** variables, gint numVariables) { gint numNodeInputs = 1; gint numNodeParams = 2; gint numNodeVariables = 0; dR_Node* out; if(numINodes!=1) { g_print("Parsing Error: ElemWise1Op Node needs %d InputNodes but got %d!\n",numNodeInputs,numNodeVariables); return NULL; } if(numParams!=numNodeParams||numVariables!=numNodeVariables) { g_print("Parsing Error: ElemWise1Op Node needs %d Parameters and %d Variables!\n",numNodeParams,numNodeVariables); return NULL; } out = dR_ElemWise1Operation(net, iNodes[0], atoi(params[0]), (gfloat)atof(params[1])); return out; } gboolean dR_elemwise1op_schedule(dR_Graph* net, dR_Node* layer){ // Nothing to do // Warnings shut up, please (void)net; (void)layer; return TRUE; } gboolean dR_elemwise1op_compute(dR_Graph* net, dR_Node* layer){ dR_ElemWise1Op_Data* elemwise1op = (dR_ElemWise1Op_Data*)(layer->layer); size_t globalWorkSize[3]; int paramid = 0; cl_mem* input; dR_list_resetIt(layer->previous_layers); input = ((dR_Node*)dR_list_next(layer->previous_layers))->outputBuf->bufptr; globalWorkSize[0] = layer->oshape.s0; globalWorkSize[1] = layer->oshape.s1; globalWorkSize[2] = layer->oshape.s2; net->clConfig->clError = clSetKernelArg(layer->clKernel, paramid, sizeof(cl_mem), (void *)input); paramid++; net->clConfig->clError |= clSetKernelArg(layer->clKernel, paramid, sizeof(cl_mem), (void *)layer->outputBuf->bufptr); paramid++; if(elemwise1op->op==tAddS||elemwise1op->op==tSubS||elemwise1op->op==tMulS||elemwise1op->op==tDivS||elemwise1op->op==tFill||elemwise1op->op==tPowS) { net->clConfig->clError |= clSetKernelArg(layer->clKernel, paramid, sizeof(cl_float), (void *)&elemwise1op->scalar); paramid++; } if (dR_openCLError(net, "Setting kernel args failed.", "Element-wise 1-operation Kernel")) return FALSE; // execute kernel net->clConfig->clError = clEnqueueNDRangeKernel(net->clConfig->clCommandQueue, layer->clKernel, 3, NULL, globalWorkSize, NULL, 0, NULL, net->clConfig->clEvent); return dR_finishCLKernel(net, "deepRACIN:elemWise1Op"); } gboolean dR_elemwise1op_propagateShape(dR_Graph* net, dR_Node* layer) { dR_ElemWise1Op_Data* elemwise1op = (dR_ElemWise1Op_Data*)(layer->layer); dR_Node* lastlayer; if(layer->previous_layers->length!=1) { if(!net->config->silent) g_print("Elem-wise 1-operation node with id %d has %d inputs but needs 1!\n",layer->layerID,layer->previous_layers->length); return FALSE; } dR_list_resetIt(layer->previous_layers); lastlayer = dR_list_next(layer->previous_layers); elemwise1op->ishape.s0 = lastlayer->oshape.s0; elemwise1op->ishape.s1 = lastlayer->oshape.s1; elemwise1op->ishape.s2 = lastlayer->oshape.s2; layer->oshape.s0 = elemwise1op->ishape.s0; layer->oshape.s1 = elemwise1op->ishape.s1; layer->oshape.s2 = elemwise1op->ishape.s2; return TRUE; } gint32 dR_elemwise1op_getRequiredOutputBufferSize(dR_Node* layer) { return layer->oshape.s0*layer->oshape.s1*layer->oshape.s2; } gboolean dR_elemwise1op_createKernel(dR_Graph* net, dR_Node* layer) { dR_ElemWise1Op_Data* elemwise1op = (dR_ElemWise1Op_Data*)(layer->layer); gboolean ret=FALSE; switch(elemwise1op->op){ case tAddS: ret = dR_createKernel(net,"addScalar",&(layer->clKernel)); break; case tSubS: ret = dR_createKernel(net,"subScalar",&(layer->clKernel)); break; case tMulS: ret = dR_createKernel(net,"mulScalar",&(layer->clKernel)); break; case tDivS: ret = dR_createKernel(net,"divScalar",&(layer->clKernel)); break; case tLog: ret = dR_createKernel(net,"computeLog",&(layer->clKernel)); break; case tExp: ret = dR_createKernel(net,"computeExp",&(layer->clKernel)); break; case tSqrt: ret = dR_createKernel(net,"computeSqrt",&(layer->clKernel)); break; case tFill: ret = dR_createKernel(net,"fill",&(layer->clKernel)); break; case tPowS: ret = dR_createKernel(net,"powScalar",&(layer->clKernel)); break; } return ret; } gboolean dR_elemwise1op_allocateBuffers(dR_Graph* net, dR_Node* layer) { // Nothing to do // Warnings shut up, please (void)net; (void)layer; return TRUE; } gboolean dR_elemwise1op_fillBuffers(dR_Graph* net, dR_Node* layer) { // Nothing to do // Warnings shut up, please (void)net; (void)layer; return TRUE; } gboolean dR_elemwise1op_cleanupBuffers(dR_Graph* net, dR_Node* layer) { gboolean ret = TRUE; if(net->prepared) ret &= dR_cleanupKernel((layer->clKernel)); return ret; } gboolean dR_elemwise1op_cleanupLayer(dR_Graph* net, dR_Node* layer) { if(net->prepared) g_free((dR_ElemWise1Op_Data*)(layer->layer)); return TRUE; } gchar* dR_elemwise1op_printLayer(dR_Node* layer) { dR_ElemWise1Op_Data* elemwise1op = (dR_ElemWise1Op_Data*)(layer->layer); gchar* out; gchar* op; switch(elemwise1op->op){ case tAddS: op = "Add Scalar"; break; case tSubS: op = "Sub Scalar"; break; case tMulS: op = "Mul Scalar"; break; case tDivS: op = "Div Scalar"; break; case tLog: op = "Log"; break; case tExp: op = "Exp"; break; case tSqrt: op = "Sqrt"; break; case tFill: op = "Fill"; break; case tPowS: op = "Pow Scalar"; break; default: op = "Error"; } if(elemwise1op->op==tAddS||elemwise1op->op==tSubS||elemwise1op->op==tMulS||elemwise1op->op==tDivS||elemwise1op->op==tFill||elemwise1op->op==tPowS) { out = g_strdup_printf("%s%d%s%s%s%f%s", "Element-wise 1 input operation node: ",layer->layerID, "\n Operation: ", op,"\n Scalar: ",elemwise1op->scalar,"\n"); } else { out = g_strdup_printf("%s%d%s%s%s", "Element-wise 1 input operation node: ",layer->layerID, "\n Operation: ", op,"\n"); } return out; } // /////////// // Softmax // // /////////// dR_Node* dR_Softmax(dR_Graph* net, dR_Node* inputLayer){ dR_Softmax_Data* softmax = g_malloc(sizeof(dR_Softmax_Data)); dR_Node* l = g_malloc(sizeof(dR_Node)); l->layer = softmax; l->type = tSoftmax; // Mandatory l->compute = dR_softmax_compute; l->schedule = dR_softmax_schedule; l->propagateShape = dR_softmax_propagateShape; l->getRequiredOutputBufferSize = dR_softmax_getRequiredOutputBufferSize; l->createKernel = dR_softmax_createKernel; l->allocateBuffers = dR_softmax_allocateBuffers; l->fillBuffers = dR_softmax_fillBuffers; l->cleanupBuffers = dR_softmax_cleanupBuffers; l->cleanupLayer = dR_softmax_cleanupLayer; l->serializeNode = dR_softmax_serializeNode; l->parseAppendNode = dR_softmax_parseAppendNode; // Optional l->generateKernel = NULL; l->setVariables = NULL; l->createKernelName = NULL; l->printLayer = dR_softmax_printLayer; if(inputLayer!=NULL) { l->previous_layers = dR_list_createEmptyList(); dR_list_append(l->previous_layers,inputLayer); l->next_layers = dR_list_createEmptyList(); dR_list_append(inputLayer->next_layers,l); } else { g_print("Error: Softmax Layer needs an appropriate Inputnode\n"); } dR_appendLayer(net, l); return l; } gchar* dR_softmax_serializeNode(dR_Node* layer, gchar* params[], gint* numParams, gfloat* variables[], gint variableSizes[], gint* numVariables) { gchar* desc = "Softmax"; gint numNodeParams = 0; gint numNodeVariables = 0; if(*numParams<numNodeParams||*numVariables<numNodeVariables) { g_print("SerializeNode needs space for %d parameters and %d variables!\n",numNodeParams,numNodeVariables); return NULL; } *numParams = numNodeParams; *numVariables = numNodeVariables; return desc; } dR_Node* dR_softmax_parseAppendNode(dR_Graph* net, dR_Node** iNodes, gint numINodes, gchar** params, gint numParams, gfloat** variables, gint numVariables) { gint numNodeInputs = 1; gint numNodeParams = 0; gint numNodeVariables = 0; dR_Node* out; if(numINodes!=1) { g_print("Parsing Error: Softmax Node needs %d InputNodes but got %d!\n",numNodeInputs,numNodeVariables); return NULL; } if(numParams!=numNodeParams||numVariables!=numNodeVariables) { g_print("Parsing Error: Softmax Node needs %d Parameters and %d Variables!\n",numNodeParams,numNodeVariables); return NULL; } out = dR_Softmax(net, iNodes[0]); return out; } gboolean dR_softmax_schedule(dR_Graph* net, dR_Node* layer){ // Nothing to do // Warnings shut up, please (void)net; (void)layer; return TRUE; } gboolean dR_softmax_compute(dR_Graph* net, dR_Node* layer){ dR_Softmax_Data* softmaxlayer = (dR_Softmax_Data*)(layer->layer); cl_float sumExp = 0.0f; size_t globalWorkSize[3]; gint paramid = 0; gint i; gint inputsize = softmaxlayer->ishape.s0*softmaxlayer->ishape.s1*softmaxlayer->ishape.s2; cl_mem* input; dR_list_resetIt(layer->previous_layers); input = ((dR_Node*)dR_list_next(layer->previous_layers))->outputBuf->bufptr; //Compute Exp(x) globalWorkSize[0] = softmaxlayer->ishape.s0; globalWorkSize[1] = softmaxlayer->ishape.s1; globalWorkSize[2] = softmaxlayer->ishape.s2; paramid=0; net->clConfig->clError = clSetKernelArg(softmaxlayer->clKernelComputeExp, paramid, sizeof(cl_mem), (void *)input); paramid++; net->clConfig->clError |= clSetKernelArg(softmaxlayer->clKernelComputeExp, paramid, sizeof(cl_mem), (void *)layer->outputBuf->bufptr); paramid++; if (dR_openCLError(net, "Setting kernel args failed.", "Compute Exp(x) Kernel")) return FALSE; // execute kernel net->clConfig->clError = clEnqueueNDRangeKernel(net->clConfig->clCommandQueue, softmaxlayer->clKernelComputeExp, 3, NULL, globalWorkSize, NULL, 0, NULL, net->clConfig->clEvent); dR_finishCLKernel(net, "deepRACIN:softmaxExp"); // CPU implementation of the expsum-reduction (inefficient for large input matrices) dR_downloadArray(net, "reduceExps", layer->outputBuf->bufptr, 0 /*offset*/, inputsize * sizeof(cl_float), softmaxlayer->expsHost); for(i = 0; i<inputsize;i++) { sumExp += softmaxlayer->expsHost[i]; } // Multiply with 1/sum with mulScalar kernel sumExp = 1/sumExp; globalWorkSize[0] = layer->oshape.s0; globalWorkSize[1] = layer->oshape.s1; globalWorkSize[2] = layer->oshape.s2; paramid = 0; net->clConfig->clError = clSetKernelArg(layer->clKernel, paramid, sizeof(cl_mem), (void *)layer->outputBuf->bufptr); paramid++; net->clConfig->clError |= clSetKernelArg(layer->clKernel, paramid, sizeof(cl_mem), (void *)layer->outputBuf->bufptr); paramid++; net->clConfig->clError |= clSetKernelArg(layer->clKernel, paramid, sizeof(cl_float), (void *)&sumExp); paramid++; if (dR_openCLError(net, "Setting kernel args failed.", "Mul Scalar for softmax Kernel")) return FALSE; // execute kernel net->clConfig->clError = clEnqueueNDRangeKernel(net->clConfig->clCommandQueue, layer->clKernel, 3, NULL, globalWorkSize, NULL, 0, NULL, net->clConfig->clEvent); return dR_finishCLKernel(net, "deepRACIN:softmaxNorm"); } gboolean dR_softmax_propagateShape(dR_Graph* net, dR_Node* layer) { dR_Softmax_Data* softmaxlayer = ((dR_Softmax_Data*)(layer->layer)); dR_Node* lastlayer; if(layer->previous_layers->length!=1) { if(!net->config->silent) g_print("Softmax Layer with id %d has %d inputs but needs 1!\n",layer->layerID,layer->previous_layers->length); } dR_list_resetIt(layer->previous_layers); lastlayer = dR_list_next(layer->previous_layers); softmaxlayer->ishape.s0 = lastlayer->oshape.s0; softmaxlayer->ishape.s1 = lastlayer->oshape.s1; softmaxlayer->ishape.s2 = lastlayer->oshape.s2; layer->oshape.s0 = softmaxlayer->ishape.s0; layer->oshape.s1 = softmaxlayer->ishape.s1; layer->oshape.s2 = softmaxlayer->ishape.s2; return TRUE; } gint32 dR_softmax_getRequiredOutputBufferSize(dR_Node* layer) { return layer->oshape.s0*layer->oshape.s1*layer->oshape.s2; } gboolean dR_softmax_createKernel(dR_Graph* net, dR_Node* layer) { dR_Softmax_Data* softmax = (dR_Softmax_Data*)(layer->layer); gchar* kernelname; kernelname = "mulScalar"; dR_createKernel(net,"computeExp",&(softmax->clKernelComputeExp)); return dR_createKernel(net,kernelname,&(layer->clKernel)); } gboolean dR_softmax_allocateBuffers(dR_Graph* net, dR_Node* layer) { gboolean ret = TRUE; if(!net->prepared) { dR_Softmax_Data* softmax = ((dR_Softmax_Data*)(layer->layer)); softmax->expsHost = g_malloc(softmax->ishape.s0*softmax->ishape.s1*softmax->ishape.s2*sizeof(gfloat)); } return ret; } gboolean dR_softmax_fillBuffers(dR_Graph* net, dR_Node* layer) { // Nothing to do // Warnings shut up, please (void)net; (void)layer; return TRUE; } gboolean dR_softmax_cleanupBuffers(dR_Graph* net, dR_Node* layer) { gboolean ret = TRUE; if(net->prepared) { dR_Softmax_Data* softmax = ((dR_Softmax_Data*)(layer->layer)); ret &= dR_cleanupKernel((softmax->clKernelComputeExp)); ret &= dR_cleanupKernel((layer->clKernel)); } return ret; } gboolean dR_softmax_cleanupLayer(dR_Graph* net, dR_Node* layer) { dR_Softmax_Data* softmax = ((dR_Softmax_Data*)(layer->layer)); if(net->prepared) { g_free(softmax->expsHost); g_free((dR_Softmax_Data*)(layer->layer)); } return TRUE; } gchar* dR_softmax_printLayer(dR_Node* layer) { //dR_Softmax_Data* softmax = (dR_Softmax_Data*)(layer->layer); gchar* out; out = g_strdup_printf("%s%d%s", "Softmax Layer: ",layer->layerID,"\n"); return out; }
32.588542
159
0.666773
[ "shape" ]
45a2884b4c24bb777ba3aed10b2d8b04baa46770
106,337
h
C
includes/rtm/vector4d.h
sufalroy/rtm
f7f08c749cad90096626941351546bb1cdbb5ced
[ "MIT" ]
null
null
null
includes/rtm/vector4d.h
sufalroy/rtm
f7f08c749cad90096626941351546bb1cdbb5ced
[ "MIT" ]
null
null
null
includes/rtm/vector4d.h
sufalroy/rtm
f7f08c749cad90096626941351546bb1cdbb5ced
[ "MIT" ]
null
null
null
#pragma once //////////////////////////////////////////////////////////////////////////////// // The MIT License (MIT) // // Copyright (c) 2017 Nicholas Frechette & Animation Compression Library contributors // Copyright (c) 2018 Nicholas Frechette & Realtime Math contributors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //////////////////////////////////////////////////////////////////////////////// #include "rtm/math.h" #include "rtm/scalard.h" #include "rtm/version.h" #include "rtm/impl/compiler_utils.h" #include "rtm/impl/memory_utils.h" #include "rtm/impl/vector_common.h" RTM_IMPL_FILE_PRAGMA_PUSH namespace rtm { RTM_IMPL_VERSION_NAMESPACE_BEGIN ////////////////////////////////////////////////////////////////////////// // Setters, getters, and casts ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Loads an unaligned vector4 from memory. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_load(const double* input) RTM_NO_EXCEPT { return vector_set(input[0], input[1], input[2], input[3]); } ////////////////////////////////////////////////////////////////////////// // Loads an input scalar from memory into the [x] component and sets the [yzw] components to zero. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_load1(const double* input) RTM_NO_EXCEPT { return vector_set(input[0], 0.0, 0.0, 0.0); } ////////////////////////////////////////////////////////////////////////// // Loads an unaligned vector2 from memory and sets the [zw] components to zero. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_load2(const double* input) RTM_NO_EXCEPT { return vector_set(input[0], input[1], 0.0, 0.0); } ////////////////////////////////////////////////////////////////////////// // Loads an unaligned vector3 from memory and sets the [w] component to zero. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_load3(const double* input) RTM_NO_EXCEPT { return vector_set(input[0], input[1], input[2], 0.0); } ////////////////////////////////////////////////////////////////////////// // Loads an unaligned vector4 from memory. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_load(const float4d* input) RTM_NO_EXCEPT { return vector_set(input->x, input->y, input->z, input->w); } ////////////////////////////////////////////////////////////////////////// // Loads an unaligned vector2 from memory and sets the [zw] components to zero. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_load2(const float2d* input) RTM_NO_EXCEPT { return vector_set(input->x, input->y, 0.0, 0.0); } ////////////////////////////////////////////////////////////////////////// // Loads an unaligned vector3 from memory and sets the [w] component to zero. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_load3(const float3d* input) RTM_NO_EXCEPT { return vector_set(input->x, input->y, input->z, 0.0); } ////////////////////////////////////////////////////////////////////////// // Loads an input scalar from memory into the [xyzw] components. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_broadcast(const double* input) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) const __m128d value = _mm_load1_pd(input); return vector4d{ value, value }; #else return vector_set(*input); #endif } ////////////////////////////////////////////////////////////////////////// // Casts a quaternion to a vector4. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d quat_to_vector(const quatd& input) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return vector4d{ input.xy, input.zw }; #else return vector4d{ input.x, input.y, input.z, input.w }; #endif } ////////////////////////////////////////////////////////////////////////// // Casts a vector4 float32 variant to a float64 variant. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_cast(const vector4f& input) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return vector4d{ _mm_cvtps_pd(input), _mm_cvtps_pd(_mm_shuffle_ps(input, input, _MM_SHUFFLE(3, 2, 3, 2))) }; #elif defined(RTM_NEON_INTRINSICS) return vector4d{ double(vgetq_lane_f32(input, 0)), double(vgetq_lane_f32(input, 1)), double(vgetq_lane_f32(input, 2)), double(vgetq_lane_f32(input, 3)) }; #else return vector4d{ double(input.x), double(input.y), double(input.z), double(input.w) }; #endif } namespace rtm_impl { ////////////////////////////////////////////////////////////////////////// // This is a helper struct to allow a single consistent API between // various vector types when the semantics are identical but the return // type differs. Implicit coercion is used to return the desired value // at the call site. ////////////////////////////////////////////////////////////////////////// struct vector4d_vector_get_x { RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator double() const RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return _mm_cvtsd_f64(input.xy); #else return input.x; #endif } #if defined(RTM_SSE2_INTRINSICS) RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator scalard() const RTM_NO_EXCEPT { return scalard{ input.xy }; } #endif vector4d input; }; } ////////////////////////////////////////////////////////////////////////// // Returns the vector4 [x] component. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE constexpr rtm_impl::vector4d_vector_get_x vector_get_x(const vector4d& input) RTM_NO_EXCEPT { return rtm_impl::vector4d_vector_get_x{ input }; } namespace rtm_impl { ////////////////////////////////////////////////////////////////////////// // This is a helper struct to allow a single consistent API between // various vector types when the semantics are identical but the return // type differs. Implicit coercion is used to return the desired value // at the call site. ////////////////////////////////////////////////////////////////////////// struct vector4d_vector_get_y { RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator double() const RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return _mm_cvtsd_f64(_mm_shuffle_pd(input.xy, input.xy, 1)); #else return input.y; #endif } #if defined(RTM_SSE2_INTRINSICS) RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator scalard() const RTM_NO_EXCEPT { return scalard{ _mm_shuffle_pd(input.xy, input.xy, 1) }; } #endif vector4d input; }; } ////////////////////////////////////////////////////////////////////////// // Returns the vector4 [y] component. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE constexpr rtm_impl::vector4d_vector_get_y vector_get_y(const vector4d& input) RTM_NO_EXCEPT { return rtm_impl::vector4d_vector_get_y{ input }; } namespace rtm_impl { ////////////////////////////////////////////////////////////////////////// // This is a helper struct to allow a single consistent API between // various vector types when the semantics are identical but the return // type differs. Implicit coercion is used to return the desired value // at the call site. ////////////////////////////////////////////////////////////////////////// struct vector4d_vector_get_z { RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator double() const RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return _mm_cvtsd_f64(input.zw); #else return input.z; #endif } #if defined(RTM_SSE2_INTRINSICS) RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator scalard() const RTM_NO_EXCEPT { return scalard{ input.zw }; } #endif vector4d input; }; } ////////////////////////////////////////////////////////////////////////// // Returns the vector4 [z] component. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE constexpr rtm_impl::vector4d_vector_get_z vector_get_z(const vector4d& input) RTM_NO_EXCEPT { return rtm_impl::vector4d_vector_get_z{ input }; } namespace rtm_impl { ////////////////////////////////////////////////////////////////////////// // This is a helper struct to allow a single consistent API between // various vector types when the semantics are identical but the return // type differs. Implicit coercion is used to return the desired value // at the call site. ////////////////////////////////////////////////////////////////////////// struct vector4d_vector_get_w { RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator double() const RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return _mm_cvtsd_f64(_mm_shuffle_pd(input.zw, input.zw, 1)); #else return input.w; #endif } #if defined(RTM_SSE2_INTRINSICS) RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator scalard() const RTM_NO_EXCEPT { return scalard{ _mm_shuffle_pd(input.zw, input.zw, 1) }; } #endif vector4d input; }; } ////////////////////////////////////////////////////////////////////////// // Returns the vector4 [w] component. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE constexpr rtm_impl::vector4d_vector_get_w vector_get_w(const vector4d& input) RTM_NO_EXCEPT { return rtm_impl::vector4d_vector_get_w{ input }; } namespace rtm_impl { ////////////////////////////////////////////////////////////////////////// // This is a helper struct to allow a single consistent API between // various vector types when the semantics are identical but the return // type differs. Implicit coercion is used to return the desired value // at the call site. ////////////////////////////////////////////////////////////////////////// template<mix4 component> struct vector4d_vector_get_component_static { RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator double() const RTM_NO_EXCEPT { const mix4 xyzw = mix4(int(component) % 4); if (rtm_impl::static_condition<xyzw == mix4::x>::test()) return vector_get_x(input); else if (rtm_impl::static_condition<xyzw == mix4::y>::test()) return vector_get_y(input); else if (rtm_impl::static_condition<xyzw == mix4::z>::test()) return vector_get_z(input); else return vector_get_w(input); } #if defined(RTM_SSE2_INTRINSICS) RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator scalard() const RTM_NO_EXCEPT { const mix4 xyzw = mix4(int(component) % 4); if (rtm_impl::static_condition<xyzw == mix4::x>::test()) return vector_get_x(input); else if (rtm_impl::static_condition<xyzw == mix4::y>::test()) return vector_get_y(input); else if (rtm_impl::static_condition<xyzw == mix4::z>::test()) return vector_get_z(input); else return vector_get_w(input); } #endif vector4d input; }; } ////////////////////////////////////////////////////////////////////////// // Returns the vector4 desired component. ////////////////////////////////////////////////////////////////////////// template<mix4 component> RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE constexpr rtm_impl::vector4d_vector_get_component_static<component> vector_get_component(const vector4d& input) RTM_NO_EXCEPT { return rtm_impl::vector4d_vector_get_component_static<component>{ input }; } namespace rtm_impl { ////////////////////////////////////////////////////////////////////////// // This is a helper struct to allow a single consistent API between // various vector types when the semantics are identical but the return // type differs. Implicit coercion is used to return the desired value // at the call site. ////////////////////////////////////////////////////////////////////////// struct vector4d_vector_get_component { RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator double() const RTM_NO_EXCEPT { const mix4 xyzw = mix4(int(component) % 4); if (xyzw == mix4::x) return vector_get_x(input); else if (xyzw == mix4::y) return vector_get_y(input); else if (xyzw == mix4::z) return vector_get_z(input); else return vector_get_w(input); } #if defined(RTM_SSE2_INTRINSICS) RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator scalard() const RTM_NO_EXCEPT { const mix4 xyzw = mix4(int(component) % 4); if (xyzw == mix4::x) return vector_get_x(input); else if (xyzw == mix4::y) return vector_get_y(input); else if (xyzw == mix4::z) return vector_get_z(input); else return vector_get_w(input); } #endif vector4d input; mix4 component; int padding[3]; }; } ////////////////////////////////////////////////////////////////////////// // Returns the vector4 desired component. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE constexpr rtm_impl::vector4d_vector_get_component vector_get_component(const vector4d& input, mix4 component) RTM_NO_EXCEPT { return rtm_impl::vector4d_vector_get_component{ input, component, { 0 } }; } ////////////////////////////////////////////////////////////////////////// // Returns the smallest component in the input vector as a scalar. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE constexpr rtm_impl::vector4d_get_min_component vector_get_min_component(const vector4d& input) RTM_NO_EXCEPT { return rtm_impl::vector4d_get_min_component{ input }; } ////////////////////////////////////////////////////////////////////////// // Returns the largest component in the input vector as a scalar. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE constexpr rtm_impl::vector4d_get_max_component vector_get_max_component(const vector4d& input) RTM_NO_EXCEPT { return rtm_impl::vector4d_get_max_component{ input }; } ////////////////////////////////////////////////////////////////////////// // Sets the vector4 [x] component and returns the new value. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_set_x(const vector4d& input, double lane_value) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return vector4d{ _mm_move_sd(input.xy, _mm_set_sd(lane_value)), input.zw }; #else return vector4d{ lane_value, input.y, input.z, input.w }; #endif } #if defined(RTM_SSE2_INTRINSICS) ////////////////////////////////////////////////////////////////////////// // Sets the vector4 [x] component and returns the new value. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_set_x(const vector4d& input, const scalard& lane_value) RTM_NO_EXCEPT { return vector4d{ _mm_move_sd(input.xy, lane_value.value), input.zw }; } #endif ////////////////////////////////////////////////////////////////////////// // Sets the vector4 [y] component and returns the new value. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_set_y(const vector4d& input, double lane_value) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return vector4d{ _mm_shuffle_pd(input.xy, _mm_set_sd(lane_value), 0), input.zw }; #else return vector4d{ input.x, lane_value, input.z, input.w }; #endif } #if defined(RTM_SSE2_INTRINSICS) ////////////////////////////////////////////////////////////////////////// // Sets the vector4 [y] component and returns the new value. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_set_y(const vector4d& input, const scalard& lane_value) RTM_NO_EXCEPT { return vector4d{ _mm_shuffle_pd(input.xy, lane_value.value, 0), input.zw }; } #endif ////////////////////////////////////////////////////////////////////////// // Sets the vector4 [z] component and returns the new value. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_set_z(const vector4d& input, double lane_value) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return vector4d{ input.xy, _mm_move_sd(input.zw, _mm_set_sd(lane_value)) }; #else return vector4d{ input.x, input.y, lane_value, input.w }; #endif } #if defined(RTM_SSE2_INTRINSICS) ////////////////////////////////////////////////////////////////////////// // Sets the vector4 [z] component and returns the new value. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_set_z(const vector4d& input, const scalard& lane_value) RTM_NO_EXCEPT { return vector4d{ input.xy, _mm_move_sd(input.zw, lane_value.value) }; } #endif ////////////////////////////////////////////////////////////////////////// // Sets the vector4 [w] component and returns the new value. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_set_w(const vector4d& input, double lane_value) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return vector4d{ input.xy, _mm_shuffle_pd(input.zw, _mm_set_sd(lane_value), 0) }; #else return vector4d{ input.x, input.y, input.z, lane_value }; #endif } #if defined(RTM_SSE2_INTRINSICS) ////////////////////////////////////////////////////////////////////////// // Sets the vector4 [w] component and returns the new value. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_set_w(const vector4d& input, const scalard& lane_value) RTM_NO_EXCEPT { return vector4d{ input.xy, _mm_shuffle_pd(input.zw, lane_value.value, 0) }; } #endif ////////////////////////////////////////////////////////////////////////// // Returns a floating point pointer to the vector4 data. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE const double* vector_to_pointer(const vector4d& input) RTM_NO_EXCEPT { return reinterpret_cast<const double*>(&input); } ////////////////////////////////////////////////////////////////////////// // Writes a vector4 to unaligned memory. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE void vector_store(const vector4d& input, double* output) RTM_NO_EXCEPT { output[0] = vector_get_x(input); output[1] = vector_get_y(input); output[2] = vector_get_z(input); output[3] = vector_get_w(input); } ////////////////////////////////////////////////////////////////////////// // Writes a vector1 to unaligned memory. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE void vector_store1(const vector4d& input, double* output) RTM_NO_EXCEPT { output[0] = vector_get_x(input); } ////////////////////////////////////////////////////////////////////////// // Writes a vector2 to unaligned memory. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE void vector_store2(const vector4d& input, double* output) RTM_NO_EXCEPT { output[0] = vector_get_x(input); output[1] = vector_get_y(input); } ////////////////////////////////////////////////////////////////////////// // Writes a vector3 to unaligned memory. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE void vector_store3(const vector4d& input, double* output) RTM_NO_EXCEPT { output[0] = vector_get_x(input); output[1] = vector_get_y(input); output[2] = vector_get_z(input); } ////////////////////////////////////////////////////////////////////////// // Writes a vector4 to unaligned memory. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE void vector_store(const vector4d& input, uint8_t* output) RTM_NO_EXCEPT { std::memcpy(output, &input, sizeof(vector4d)); } ////////////////////////////////////////////////////////////////////////// // Writes a vector1 to unaligned memory. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE void vector_store1(const vector4d& input, uint8_t* output) { std::memcpy(output, &input, sizeof(double) * 1); } ////////////////////////////////////////////////////////////////////////// // Writes a vector2 to unaligned memory. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE void vector_store2(const vector4d& input, uint8_t* output) { std::memcpy(output, &input, sizeof(double) * 2); } ////////////////////////////////////////////////////////////////////////// // Writes a vector3 to unaligned memory. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE void vector_store3(const vector4d& input, uint8_t* output) { std::memcpy(output, &input, sizeof(double) * 3); } ////////////////////////////////////////////////////////////////////////// // Writes a vector4 to unaligned memory. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE void vector_store(const vector4d& input, float4d* output) RTM_NO_EXCEPT { output->x = vector_get_x(input); output->y = vector_get_y(input); output->z = vector_get_z(input); output->w = vector_get_w(input); } ////////////////////////////////////////////////////////////////////////// // Writes a vector2 to unaligned memory. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE void vector_store2(const vector4d& input, float2d* output) RTM_NO_EXCEPT { output->x = vector_get_x(input); output->y = vector_get_y(input); } ////////////////////////////////////////////////////////////////////////// // Writes a vector3 to unaligned memory. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE void vector_store3(const vector4d& input, float3d* output) RTM_NO_EXCEPT { output->x = vector_get_x(input); output->y = vector_get_y(input); output->z = vector_get_z(input); } ////////////////////////////////////////////////////////////////////////// // Arithmetic ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Per component addition of the two inputs: lhs + rhs ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_add(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return vector4d{ _mm_add_pd(lhs.xy, rhs.xy), _mm_add_pd(lhs.zw, rhs.zw) }; #else return vector_set(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); #endif } ////////////////////////////////////////////////////////////////////////// // Per component subtraction of the two inputs: lhs - rhs ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_sub(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return vector4d{ _mm_sub_pd(lhs.xy, rhs.xy), _mm_sub_pd(lhs.zw, rhs.zw) }; #else return vector_set(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); #endif } ////////////////////////////////////////////////////////////////////////// // Per component multiplication of the two inputs: lhs * rhs ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_mul(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return vector4d{ _mm_mul_pd(lhs.xy, rhs.xy), _mm_mul_pd(lhs.zw, rhs.zw) }; #else return vector_set(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); #endif } ////////////////////////////////////////////////////////////////////////// // Per component multiplication of the vector by a scalar: lhs * rhs ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_mul(const vector4d& lhs, double rhs) RTM_NO_EXCEPT { return vector_mul(lhs, vector_set(rhs)); } #if defined(RTM_SSE2_INTRINSICS) ////////////////////////////////////////////////////////////////////////// // Per component multiplication of the vector by a scalar: lhs * rhs ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_mul(const vector4d& lhs, const scalard& rhs) RTM_NO_EXCEPT { const __m128d rhs_xx = _mm_shuffle_pd(rhs.value, rhs.value, 0); return vector4d{ _mm_mul_pd(lhs.xy, rhs_xx), _mm_mul_pd(lhs.zw, rhs_xx) }; } #endif ////////////////////////////////////////////////////////////////////////// // Per component division of the two inputs: lhs / rhs ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_div(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return vector4d{ _mm_div_pd(lhs.xy, rhs.xy), _mm_div_pd(lhs.zw, rhs.zw) }; #else return vector_set(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w); #endif } ////////////////////////////////////////////////////////////////////////// // Per component maximum of the two inputs: max(lhs, rhs) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_max(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return vector4d{ _mm_max_pd(lhs.xy, rhs.xy), _mm_max_pd(lhs.zw, rhs.zw) }; #else return vector_set(scalar_max(lhs.x, rhs.x), scalar_max(lhs.y, rhs.y), scalar_max(lhs.z, rhs.z), scalar_max(lhs.w, rhs.w)); #endif } ////////////////////////////////////////////////////////////////////////// // Per component minimum of the two inputs: min(lhs, rhs) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_min(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return vector4d{ _mm_min_pd(lhs.xy, rhs.xy), _mm_min_pd(lhs.zw, rhs.zw) }; #else return vector_set(scalar_min(lhs.x, rhs.x), scalar_min(lhs.y, rhs.y), scalar_min(lhs.z, rhs.z), scalar_min(lhs.w, rhs.w)); #endif } ////////////////////////////////////////////////////////////////////////// // Per component clamping of an input between a minimum and a maximum value: min(max_value, max(min_value, input)) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_clamp(const vector4d& input, const vector4d& min_value, const vector4d& max_value) RTM_NO_EXCEPT { return vector_min(max_value, vector_max(min_value, input)); } ////////////////////////////////////////////////////////////////////////// // Per component absolute of the input: abs(input) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_abs(const vector4d& input) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) vector4d zero{ _mm_setzero_pd(), _mm_setzero_pd() }; return vector_max(vector_sub(zero, input), input); #else return vector_set(scalar_abs(input.x), scalar_abs(input.y), scalar_abs(input.z), scalar_abs(input.w)); #endif } ////////////////////////////////////////////////////////////////////////// // Per component negation of the input: -input ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_neg(const vector4d& input) RTM_NO_EXCEPT { return vector_mul(input, -1.0); } ////////////////////////////////////////////////////////////////////////// // Per component reciprocal of the input: 1.0 / input ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_reciprocal(const vector4d& input) RTM_NO_EXCEPT { return vector_div(vector_set(1.0), input); } ////////////////////////////////////////////////////////////////////////// // Per component square root of the input: sqrt(input) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_sqrt(const vector4d& input) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) return vector4d{ _mm_sqrt_pd(input.xy), _mm_sqrt_pd(input.zw) }; #else scalard x = vector_get_x(input); scalard y = vector_get_y(input); scalard z = vector_get_z(input); scalard w = vector_get_w(input); return vector_set(scalar_sqrt(x), scalar_sqrt(y), scalar_sqrt(z), scalar_sqrt(w)); #endif } ////////////////////////////////////////////////////////////////////////// // Per component returns the smallest integer value not less than the input (round towards positive infinity). // vector_ceil([1.8, 1.0, -1.8, -1.0]) = [2.0, 1.0, -1.0, -1.0] ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK inline vector4d vector_ceil(const vector4d& input) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) // NaN, +- Infinity, and numbers larger or equal to 2^23 remain unchanged // since they have no fractional part. const __m128i abs_mask = _mm_set_epi64x(0x7FFFFFFFFFFFFFFFULL, 0x7FFFFFFFFFFFFFFFULL); const __m128d fractional_limit = _mm_set1_pd(4503599627370496.0); // 2^52 // Build our mask, larger values that have no fractional part, and infinities will be true // Smaller values and NaN will be false __m128d abs_input_xy = _mm_and_pd(input.xy, _mm_castsi128_pd(abs_mask)); __m128d abs_input_zw = _mm_and_pd(input.zw, _mm_castsi128_pd(abs_mask)); __m128d is_input_large_xy = _mm_cmpge_pd(abs_input_xy, fractional_limit); __m128d is_input_large_zw = _mm_cmpge_pd(abs_input_zw, fractional_limit); // Test if our input is NaN with (value != value), it is only true for NaN __m128d is_nan_xy = _mm_cmpneq_pd(input.xy, input.xy); __m128d is_nan_zw = _mm_cmpneq_pd(input.zw, input.zw); // Combine our masks to determine if we should return the original value __m128d use_original_input_xy = _mm_or_pd(is_input_large_xy, is_nan_xy); __m128d use_original_input_zw = _mm_or_pd(is_input_large_zw, is_nan_zw); // Convert to an integer and back __m128d integer_part_xy = _mm_cvtepi32_pd(_mm_cvtpd_epi32(input.xy)); __m128d integer_part_zw = _mm_cvtepi32_pd(_mm_cvtpd_epi32(input.zw)); // Test if the returned value is smaller than the original. // A positive input will round towards zero and be lower when we need it to be greater. __m128d is_positive_xy = _mm_cmplt_pd(integer_part_xy, input.xy); __m128d is_positive_zw = _mm_cmplt_pd(integer_part_zw, input.zw); // Our mask output is 64 bit wide but to convert to a bias, we need 32 bit integers is_positive_xy = _mm_castps_pd(_mm_shuffle_ps(_mm_castpd_ps(is_positive_xy), _mm_castpd_ps(is_positive_xy), _MM_SHUFFLE(2, 0, 2, 0))); is_positive_zw = _mm_castps_pd(_mm_shuffle_ps(_mm_castpd_ps(is_positive_zw), _mm_castpd_ps(is_positive_zw), _MM_SHUFFLE(2, 0, 2, 0))); // Convert our mask to a float, ~0 yields -1.0 since it is a valid signed integer // Negative values will yield a 0.0 bias __m128d bias_xy = _mm_cvtepi32_pd(_mm_castpd_si128(is_positive_xy)); __m128d bias_zw = _mm_cvtepi32_pd(_mm_castpd_si128(is_positive_zw)); // Subtract our bias to properly handle positive values integer_part_xy = _mm_sub_pd(integer_part_xy, bias_xy); integer_part_zw = _mm_sub_pd(integer_part_zw, bias_zw); __m128d result_xy = _mm_or_pd(_mm_and_pd(use_original_input_xy, input.xy), _mm_andnot_pd(use_original_input_xy, integer_part_xy)); __m128d result_zw = _mm_or_pd(_mm_and_pd(use_original_input_zw, input.zw), _mm_andnot_pd(use_original_input_zw, integer_part_zw)); return vector4d{ result_xy, result_zw }; #else return vector_set(scalar_ceil(vector_get_x(input)), scalar_ceil(vector_get_y(input)), scalar_ceil(vector_get_z(input)), scalar_ceil(vector_get_w(input))); #endif } ////////////////////////////////////////////////////////////////////////// // Per component returns the largest integer value not greater than the input (round towards negative infinity). // vector_floor([1.8, 1.0, -1.8, -1.0]) = [1.0, 1.0, -2.0, -1.0] ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK inline vector4d vector_floor(const vector4d& input) RTM_NO_EXCEPT { #if defined(RTM_SSE4_INTRINSICS) return vector4d{ _mm_floor_pd(input.xy), _mm_floor_pd(input.zw) }; #elif defined(RTM_SSE2_INTRINSICS) // NaN, +- Infinity, and numbers larger or equal to 2^23 remain unchanged // since they have no fractional part. const __m128i abs_mask = _mm_set_epi64x(0x7FFFFFFFFFFFFFFFULL, 0x7FFFFFFFFFFFFFFFULL); const __m128d fractional_limit = _mm_set1_pd(4503599627370496.0); // 2^52 // Build our mask, larger values that have no fractional part, and infinities will be true // Smaller values and NaN will be false __m128d abs_input_xy = _mm_and_pd(input.xy, _mm_castsi128_pd(abs_mask)); __m128d abs_input_zw = _mm_and_pd(input.zw, _mm_castsi128_pd(abs_mask)); __m128d is_input_large_xy = _mm_cmpge_pd(abs_input_xy, fractional_limit); __m128d is_input_large_zw = _mm_cmpge_pd(abs_input_zw, fractional_limit); // Test if our input is NaN with (value != value), it is only true for NaN __m128d is_nan_xy = _mm_cmpneq_pd(input.xy, input.xy); __m128d is_nan_zw = _mm_cmpneq_pd(input.zw, input.zw); // Combine our masks to determine if we should return the original value __m128d use_original_input_xy = _mm_or_pd(is_input_large_xy, is_nan_xy); __m128d use_original_input_zw = _mm_or_pd(is_input_large_zw, is_nan_zw); // Convert to an integer and back __m128d integer_part_xy = _mm_cvtepi32_pd(_mm_cvtpd_epi32(input.xy)); __m128d integer_part_zw = _mm_cvtepi32_pd(_mm_cvtpd_epi32(input.zw)); // Test if the returned value is greater than the original. // A negative input will round towards zero and be greater when we need it to be smaller. __m128d is_negative_xy = _mm_cmpgt_pd(integer_part_xy, input.xy); __m128d is_negative_zw = _mm_cmpgt_pd(integer_part_zw, input.zw); // Our mask output is 64 bit wide but to convert to a bias, we need 32 bit integers is_negative_xy = _mm_castps_pd(_mm_shuffle_ps(_mm_castpd_ps(is_negative_xy), _mm_castpd_ps(is_negative_xy), _MM_SHUFFLE(2, 0, 2, 0))); is_negative_zw = _mm_castps_pd(_mm_shuffle_ps(_mm_castpd_ps(is_negative_zw), _mm_castpd_ps(is_negative_zw), _MM_SHUFFLE(2, 0, 2, 0))); // Convert our mask to a float, ~0 yields -1.0 since it is a valid signed integer // Positive values will yield a 0.0 bias __m128d bias_xy = _mm_cvtepi32_pd(_mm_castpd_si128(is_negative_xy)); __m128d bias_zw = _mm_cvtepi32_pd(_mm_castpd_si128(is_negative_zw)); // Add our bias to properly handle negative values integer_part_xy = _mm_add_pd(integer_part_xy, bias_xy); integer_part_zw = _mm_add_pd(integer_part_zw, bias_zw); __m128d result_xy = _mm_or_pd(_mm_and_pd(use_original_input_xy, input.xy), _mm_andnot_pd(use_original_input_xy, integer_part_xy)); __m128d result_zw = _mm_or_pd(_mm_and_pd(use_original_input_zw, input.zw), _mm_andnot_pd(use_original_input_zw, integer_part_zw)); return vector4d{ result_xy, result_zw }; #else return vector_set(scalar_floor(vector_get_x(input)), scalar_floor(vector_get_y(input)), scalar_floor(vector_get_z(input)), scalar_floor(vector_get_w(input))); #endif } ////////////////////////////////////////////////////////////////////////// // 3D cross product: lhs x rhs ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_cross3(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { // cross(a, b) = (a.yzx * b.zxy) - (a.zxy * b.yzx) const double lhs_x = vector_get_x(lhs); const double lhs_y = vector_get_y(lhs); const double lhs_z = vector_get_z(lhs); const double rhs_x = vector_get_x(rhs); const double rhs_y = vector_get_y(rhs); const double rhs_z = vector_get_z(rhs); return vector_set((lhs_y * rhs_z) - (lhs_z * rhs_y), (lhs_z * rhs_x) - (lhs_x * rhs_z), (lhs_x * rhs_y) - (lhs_y * rhs_x)); } namespace rtm_impl { ////////////////////////////////////////////////////////////////////////// // This is a helper struct to allow a single consistent API between // various vector types when the semantics are identical but the return // type differs. Implicit coercion is used to return the desired value // at the call site. ////////////////////////////////////////////////////////////////////////// struct vector4d_vector_dot { RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator double() const RTM_NO_EXCEPT { const scalard lhs_x = vector_get_x(lhs); const scalard lhs_y = vector_get_y(lhs); const scalard lhs_z = vector_get_z(lhs); const scalard lhs_w = vector_get_w(lhs); const scalard rhs_x = vector_get_x(rhs); const scalard rhs_y = vector_get_y(rhs); const scalard rhs_z = vector_get_z(rhs); const scalard rhs_w = vector_get_w(rhs); const scalard xx = scalar_mul(lhs_x, rhs_x); const scalard yy = scalar_mul(lhs_y, rhs_y); const scalard zz = scalar_mul(lhs_z, rhs_z); const scalard ww = scalar_mul(lhs_w, rhs_w); return scalar_cast(scalar_add(scalar_add(xx, yy), scalar_add(zz, ww))); } #if defined(RTM_SSE2_INTRINSICS) RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator scalard() const RTM_NO_EXCEPT { const scalard lhs_x = vector_get_x(lhs); const scalard lhs_y = vector_get_y(lhs); const scalard lhs_z = vector_get_z(lhs); const scalard lhs_w = vector_get_w(lhs); const scalard rhs_x = vector_get_x(rhs); const scalard rhs_y = vector_get_y(rhs); const scalard rhs_z = vector_get_z(rhs); const scalard rhs_w = vector_get_w(rhs); const scalard xx = scalar_mul(lhs_x, rhs_x); const scalard yy = scalar_mul(lhs_y, rhs_y); const scalard zz = scalar_mul(lhs_z, rhs_z); const scalard ww = scalar_mul(lhs_w, rhs_w); return scalar_add(scalar_add(xx, yy), scalar_add(zz, ww)); } #endif RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator vector4d() const RTM_NO_EXCEPT { const scalard dot = *this; return vector_set(dot); } vector4d lhs; vector4d rhs; }; } ////////////////////////////////////////////////////////////////////////// // 4D dot product: lhs . rhs ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE constexpr rtm_impl::vector4d_vector_dot vector_dot(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { return rtm_impl::vector4d_vector_dot{ lhs, rhs }; } namespace rtm_impl { ////////////////////////////////////////////////////////////////////////// // This is a helper struct to allow a single consistent API between // various vector types when the semantics are identical but the return // type differs. Implicit coercion is used to return the desired value // at the call site. ////////////////////////////////////////////////////////////////////////// struct vector4d_vector_dot3 { RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator double() const RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d x2_y2 = _mm_mul_pd(lhs.xy, rhs.xy); __m128d z2_w2 = _mm_mul_pd(lhs.zw, rhs.zw); __m128d y2 = _mm_shuffle_pd(x2_y2, x2_y2, 1); __m128d x2y2 = _mm_add_sd(x2_y2, y2); return _mm_cvtsd_f64(_mm_add_sd(x2y2, z2_w2)); #else return (vector_get_x(lhs) * vector_get_x(rhs)) + (vector_get_y(lhs) * vector_get_y(rhs)) + (vector_get_z(lhs) * vector_get_z(rhs)); #endif } #if defined(RTM_SSE2_INTRINSICS) RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator scalard() const RTM_NO_EXCEPT { __m128d x2_y2 = _mm_mul_pd(lhs.xy, rhs.xy); __m128d z2_w2 = _mm_mul_pd(lhs.zw, rhs.zw); __m128d y2 = _mm_shuffle_pd(x2_y2, x2_y2, 1); __m128d x2y2 = _mm_add_sd(x2_y2, y2); return scalard{ _mm_add_sd(x2y2, z2_w2) }; } #endif RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator vector4d() const RTM_NO_EXCEPT { const scalard dot = *this; return vector_set(dot); } vector4d lhs; vector4d rhs; }; } ////////////////////////////////////////////////////////////////////////// // 3D dot product: lhs . rhs ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE constexpr rtm_impl::vector4d_vector_dot3 vector_dot3(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { return rtm_impl::vector4d_vector_dot3{ lhs, rhs }; } ////////////////////////////////////////////////////////////////////////// // Returns the squared length/norm of the vector4. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE constexpr rtm_impl::vector4d_vector_dot vector_length_squared(const vector4d& input) RTM_NO_EXCEPT { return rtm_impl::vector4d_vector_dot{ input, input }; } ////////////////////////////////////////////////////////////////////////// // Returns the squared length/norm of the vector3. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE constexpr rtm_impl::vector4d_vector_dot3 vector_length_squared3(const vector4d& input) RTM_NO_EXCEPT { return rtm_impl::vector4d_vector_dot3{ input, input }; } namespace rtm_impl { ////////////////////////////////////////////////////////////////////////// // This is a helper struct to allow a single consistent API between // various vector types when the semantics are identical but the return // type differs. Implicit coercion is used to return the desired value // at the call site. ////////////////////////////////////////////////////////////////////////// struct vector4d_vector_length { RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator double() const RTM_NO_EXCEPT { const scalard len_sq = vector_length_squared(input); return scalar_cast(scalar_sqrt(len_sq)); } #if defined(RTM_SSE2_INTRINSICS) RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator scalard() const RTM_NO_EXCEPT { const scalard len_sq = vector_length_squared(input); return scalar_sqrt(len_sq); } #endif vector4d input; }; } ////////////////////////////////////////////////////////////////////////// // Returns the length/norm of the vector4. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE constexpr rtm_impl::vector4d_vector_length vector_length(const vector4d& input) RTM_NO_EXCEPT { return rtm_impl::vector4d_vector_length{ input }; } namespace rtm_impl { ////////////////////////////////////////////////////////////////////////// // This is a helper struct to allow a single consistent API between // various vector types when the semantics are identical but the return // type differs. Implicit coercion is used to return the desired value // at the call site. ////////////////////////////////////////////////////////////////////////// struct vector4d_vector_length3 { RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator double() const RTM_NO_EXCEPT { const scalard len_sq = vector_length_squared3(input); return scalar_cast(scalar_sqrt(len_sq)); } #if defined(RTM_SSE2_INTRINSICS) RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator scalard() const RTM_NO_EXCEPT { const scalard len_sq = vector_length_squared3(input); return scalar_sqrt(len_sq); } #endif vector4d input; }; } ////////////////////////////////////////////////////////////////////////// // Returns the length/norm of the vector3. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE constexpr rtm_impl::vector4d_vector_length3 vector_length3(const vector4d& input) RTM_NO_EXCEPT { return rtm_impl::vector4d_vector_length3{ input }; } namespace rtm_impl { ////////////////////////////////////////////////////////////////////////// // This is a helper struct to allow a single consistent API between // various vector types when the semantics are identical but the return // type differs. Implicit coercion is used to return the desired value // at the call site. ////////////////////////////////////////////////////////////////////////// struct vector4d_vector_length_reciprocal { RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator double() const RTM_NO_EXCEPT { const scalard len_sq = vector_length_squared(input); return scalar_cast(scalar_sqrt_reciprocal(len_sq)); } #if defined(RTM_SSE2_INTRINSICS) RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator scalard() const RTM_NO_EXCEPT { const scalard len_sq = vector_length_squared(input); return scalar_sqrt_reciprocal(len_sq); } #endif vector4d input; }; } ////////////////////////////////////////////////////////////////////////// // Returns the reciprocal length/norm of the vector4. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE constexpr rtm_impl::vector4d_vector_length_reciprocal vector_length_reciprocal(const vector4d& input) RTM_NO_EXCEPT { return rtm_impl::vector4d_vector_length_reciprocal{ input }; } namespace rtm_impl { ////////////////////////////////////////////////////////////////////////// // This is a helper struct to allow a single consistent API between // various vector types when the semantics are identical but the return // type differs. Implicit coercion is used to return the desired value // at the call site. ////////////////////////////////////////////////////////////////////////// struct vector4d_vector_length_reciprocal3 { RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator double() const RTM_NO_EXCEPT { const scalard len_sq = vector_length_squared3(input); return scalar_cast(scalar_sqrt_reciprocal(len_sq)); } #if defined(RTM_SSE2_INTRINSICS) RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE RTM_SIMD_CALL operator scalard() const RTM_NO_EXCEPT { const scalard len_sq = vector_length_squared3(input); return scalar_sqrt_reciprocal(len_sq); } #endif vector4d input; }; } ////////////////////////////////////////////////////////////////////////// // Returns the reciprocal length/norm of the vector3. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE constexpr rtm_impl::vector4d_vector_length_reciprocal3 vector_length_reciprocal3(const vector4d& input) RTM_NO_EXCEPT { return rtm_impl::vector4d_vector_length_reciprocal3{ input }; } ////////////////////////////////////////////////////////////////////////// // Returns the distance between two 3D points. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE rtm_impl::vector4d_vector_length3 vector_distance3(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { const vector4d difference = vector_sub(lhs, rhs); return rtm_impl::vector4d_vector_length3{ difference }; } ////////////////////////////////////////////////////////////////////////// // Returns a normalized vector3. // If the length of the input is not finite or zero, the result is undefined. // For a safe alternative, supply a fallback value and a threshold. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_normalize3(const vector4d& input) RTM_NO_EXCEPT { // Reciprocal is more accurate to normalize with const scalard len_sq = vector_length_squared3(input); return vector_mul(input, scalar_sqrt_reciprocal(len_sq)); } ////////////////////////////////////////////////////////////////////////// // Returns a normalized vector3. // If the length of the input is below the supplied threshold, the // fall back value is returned instead. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_normalize3(const vector4d& input, const vector4d& fallback, double threshold = 1.0E-8) RTM_NO_EXCEPT { // Reciprocal is more accurate to normalize with const scalard len_sq = vector_length_squared3(input); if (scalar_cast(len_sq) >= threshold) return vector_mul(input, scalar_sqrt_reciprocal(len_sq)); else return fallback; } ////////////////////////////////////////////////////////////////////////// // Returns per component the fractional part of the input. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK inline vector4d vector_fraction(const vector4d& input) RTM_NO_EXCEPT { return vector_set(scalar_fraction(vector_get_x(input)), scalar_fraction(vector_get_y(input)), scalar_fraction(vector_get_z(input)), scalar_fraction(vector_get_w(input))); } ////////////////////////////////////////////////////////////////////////// // Per component multiplication/addition of the three inputs: v2 + (v0 * v1) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_mul_add(const vector4d& v0, const vector4d& v1, const vector4d& v2) RTM_NO_EXCEPT { return vector_add(vector_mul(v0, v1), v2); } ////////////////////////////////////////////////////////////////////////// // Per component multiplication/addition of the three inputs: v2 + (v0 * s1) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_mul_add(const vector4d& v0, double s1, const vector4d& v2) RTM_NO_EXCEPT { return vector_add(vector_mul(v0, s1), v2); } #if defined(RTM_SSE2_INTRINSICS) ////////////////////////////////////////////////////////////////////////// // Per component multiplication/addition of the three inputs: v2 + (v0 * s1) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_mul_add(const vector4d& v0, const scalard& s1, const vector4d& v2) RTM_NO_EXCEPT { return vector_add(vector_mul(v0, s1), v2); } #endif ////////////////////////////////////////////////////////////////////////// // Per component negative multiplication/subtraction of the three inputs: -((v0 * v1) - v2) // This is mathematically equivalent to: v2 - (v0 * v1) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_neg_mul_sub(const vector4d& v0, const vector4d& v1, const vector4d& v2) RTM_NO_EXCEPT { return vector_sub(v2, vector_mul(v0, v1)); } ////////////////////////////////////////////////////////////////////////// // Per component negative multiplication/subtraction of the three inputs: -((v0 * s1) - v2) // This is mathematically equivalent to: v2 - (v0 * s1) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_neg_mul_sub(const vector4d& v0, double s1, const vector4d& v2) RTM_NO_EXCEPT { return vector_sub(v2, vector_mul(v0, s1)); } #if defined(RTM_SSE2_INTRINSICS) ////////////////////////////////////////////////////////////////////////// // Per component negative multiplication/subtraction of the three inputs: -((v0 * s1) - v2) // This is mathematically equivalent to: v2 - (v0 * s1) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_neg_mul_sub(const vector4d& v0, const scalard& s1, const vector4d& v2) RTM_NO_EXCEPT { return vector_sub(v2, vector_mul(v0, s1)); } #endif ////////////////////////////////////////////////////////////////////////// // Per component linear interpolation of the two inputs at the specified alpha. // The formula used is: ((1.0 - alpha) * start) + (alpha * end). // Interpolation is stable and will return 'start' when alpha is 0.0 and 'end' when it is 1.0. // This is the same instruction count when FMA is present but it might be slightly slower // due to the extra multiplication compared to: start + (alpha * (end - start)). ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_lerp(const vector4d& start, const vector4d& end, double alpha) RTM_NO_EXCEPT { // ((1.0 - alpha) * start) + (alpha * end) == (start - alpha * start) + (alpha * end) return vector_mul_add(end, alpha, vector_neg_mul_sub(start, alpha, start)); } #if defined(RTM_SSE2_INTRINSICS) ////////////////////////////////////////////////////////////////////////// // Per component linear interpolation of the two inputs at the specified alpha. // The formula used is: ((1.0 - alpha) * start) + (alpha * end). // Interpolation is stable and will return 'start' when alpha is 0.0 and 'end' when it is 1.0. // This is the same instruction count when FMA is present but it might be slightly slower // due to the extra multiplication compared to: start + (alpha * (end - start)). ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_lerp(const vector4d& start, const vector4d& end, const scalard& alpha) RTM_NO_EXCEPT { // ((1.0 - alpha) * start) + (alpha * end) == (start - alpha * start) + (alpha * end) const vector4d alpha_v = vector_set(alpha); return vector_mul_add(end, alpha_v, vector_neg_mul_sub(start, alpha_v, start)); } #endif ////////////////////////////////////////////////////////////////////////// // Per component linear interpolation of the two inputs at the specified alpha. // The formula used is: ((1.0 - alpha) * start) + (alpha * end). // Interpolation is stable and will return 'start' when alpha is 0.0 and 'end' when it is 1.0. // This is the same instruction count when FMA is present but it might be slightly slower // due to the extra multiplication compared to: start + (alpha * (end - start)). ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_lerp(const vector4d& start, const vector4d& end, const vector4d& alpha) RTM_NO_EXCEPT { // ((1.0 - alpha) * start) + (alpha * end) == (start - alpha * start) + (alpha * end) return vector_mul_add(end, alpha, vector_neg_mul_sub(start, alpha, start)); } ////////////////////////////////////////////////////////////////////////// // Comparisons and masking ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Returns per component ~0 if equal, otherwise 0: lhs == rhs ? ~0 : 0 ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE mask4d vector_equal(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_lt_pd = _mm_cmpeq_pd(lhs.xy, rhs.xy); __m128d zw_lt_pd = _mm_cmpeq_pd(lhs.zw, rhs.zw); return mask4d{ xy_lt_pd, zw_lt_pd }; #else return mask4d{ rtm_impl::get_mask_value(lhs.x == rhs.x), rtm_impl::get_mask_value(lhs.y == rhs.y), rtm_impl::get_mask_value(lhs.z == rhs.z), rtm_impl::get_mask_value(lhs.w == rhs.w) }; #endif } ////////////////////////////////////////////////////////////////////////// // Returns per component ~0 if less than, otherwise 0: lhs < rhs ? ~0 : 0 ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE mask4d vector_less_than(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_lt_pd = _mm_cmplt_pd(lhs.xy, rhs.xy); __m128d zw_lt_pd = _mm_cmplt_pd(lhs.zw, rhs.zw); return mask4d{xy_lt_pd, zw_lt_pd}; #else return mask4d{rtm_impl::get_mask_value(lhs.x < rhs.x), rtm_impl::get_mask_value(lhs.y < rhs.y), rtm_impl::get_mask_value(lhs.z < rhs.z), rtm_impl::get_mask_value(lhs.w < rhs.w)}; #endif } ////////////////////////////////////////////////////////////////////////// // Returns per component ~0 if less equal, otherwise 0: lhs <= rhs ? ~0 : 0 ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE mask4d vector_less_equal(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_lt_pd = _mm_cmple_pd(lhs.xy, rhs.xy); __m128d zw_lt_pd = _mm_cmple_pd(lhs.zw, rhs.zw); return mask4d{ xy_lt_pd, zw_lt_pd }; #else return mask4d{ rtm_impl::get_mask_value(lhs.x <= rhs.x), rtm_impl::get_mask_value(lhs.y <= rhs.y), rtm_impl::get_mask_value(lhs.z <= rhs.z), rtm_impl::get_mask_value(lhs.w <= rhs.w) }; #endif } ////////////////////////////////////////////////////////////////////////// // Returns per component ~0 if greater than, otherwise 0: lhs > rhs ? ~0 : 0 ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE mask4d vector_greater_than(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_ge_pd = _mm_cmpgt_pd(lhs.xy, rhs.xy); __m128d zw_ge_pd = _mm_cmpgt_pd(lhs.zw, rhs.zw); return mask4d{ xy_ge_pd, zw_ge_pd }; #else return mask4d{ rtm_impl::get_mask_value(lhs.x > rhs.x), rtm_impl::get_mask_value(lhs.y > rhs.y), rtm_impl::get_mask_value(lhs.z > rhs.z), rtm_impl::get_mask_value(lhs.w > rhs.w) }; #endif } ////////////////////////////////////////////////////////////////////////// // Returns per component ~0 if greater equal, otherwise 0: lhs >= rhs ? ~0 : 0 ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE mask4d vector_greater_equal(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_ge_pd = _mm_cmpge_pd(lhs.xy, rhs.xy); __m128d zw_ge_pd = _mm_cmpge_pd(lhs.zw, rhs.zw); return mask4d{ xy_ge_pd, zw_ge_pd }; #else return mask4d{ rtm_impl::get_mask_value(lhs.x >= rhs.x), rtm_impl::get_mask_value(lhs.y >= rhs.y), rtm_impl::get_mask_value(lhs.z >= rhs.z), rtm_impl::get_mask_value(lhs.w >= rhs.w) }; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if all 4 components are less than, otherwise false: all(lhs.xyzw < rhs.xyzw) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_all_less_than(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_lt_pd = _mm_cmplt_pd(lhs.xy, rhs.xy); __m128d zw_lt_pd = _mm_cmplt_pd(lhs.zw, rhs.zw); return (_mm_movemask_pd(xy_lt_pd) & _mm_movemask_pd(zw_lt_pd)) == 3; #else return lhs.x < rhs.x && lhs.y < rhs.y && lhs.z < rhs.z && lhs.w < rhs.w; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if all [xy] components are less than, otherwise false: all(lhs.xy < rhs.xy) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_all_less_than2(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_lt_pd = _mm_cmplt_pd(lhs.xy, rhs.xy); return _mm_movemask_pd(xy_lt_pd) == 3; #else return lhs.x < rhs.x && lhs.y < rhs.y; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if all [xyz] components are less than, otherwise false: all(lhs.xyz < rhs.xyz) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_all_less_than3(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_lt_pd = _mm_cmplt_pd(lhs.xy, rhs.xy); __m128d zw_lt_pd = _mm_cmplt_pd(lhs.zw, rhs.zw); return _mm_movemask_pd(xy_lt_pd) == 3 && (_mm_movemask_pd(zw_lt_pd) & 1) == 1; #else return lhs.x < rhs.x && lhs.y < rhs.y && lhs.z < rhs.z; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if any 4 components are less than, otherwise false: any(lhs.xyzw < rhs.xyzw) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_any_less_than(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_lt_pd = _mm_cmplt_pd(lhs.xy, rhs.xy); __m128d zw_lt_pd = _mm_cmplt_pd(lhs.zw, rhs.zw); return (_mm_movemask_pd(xy_lt_pd) | _mm_movemask_pd(zw_lt_pd)) != 0; #else return lhs.x < rhs.x || lhs.y < rhs.y || lhs.z < rhs.z || lhs.w < rhs.w; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if any [xy] components are less than, otherwise false: any(lhs.xy < rhs.xy) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_any_less_than2(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_lt_pd = _mm_cmplt_pd(lhs.xy, rhs.xy); return _mm_movemask_pd(xy_lt_pd) != 0; #else return lhs.x < rhs.x || lhs.y < rhs.y; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if any [xyz] components are less than, otherwise false: any(lhs.xyz < rhs.xyz) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_any_less_than3(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_lt_pd = _mm_cmplt_pd(lhs.xy, rhs.xy); __m128d zw_lt_pd = _mm_cmplt_pd(lhs.zw, rhs.zw); return _mm_movemask_pd(xy_lt_pd) != 0 || (_mm_movemask_pd(zw_lt_pd) & 0x1) != 0; #else return lhs.x < rhs.x || lhs.y < rhs.y || lhs.z < rhs.z; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if all 4 components are less equal, otherwise false: all(lhs.xyzw <= rhs.xyzw) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_all_less_equal(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_le_pd = _mm_cmple_pd(lhs.xy, rhs.xy); __m128d zw_le_pd = _mm_cmple_pd(lhs.zw, rhs.zw); return (_mm_movemask_pd(xy_le_pd) & _mm_movemask_pd(zw_le_pd)) == 3; #else return lhs.x <= rhs.x && lhs.y <= rhs.y && lhs.z <= rhs.z && lhs.w <= rhs.w; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if all [xy] components are less equal, otherwise false: all(lhs.xy <= rhs.xy) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_all_less_equal2(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_le_pd = _mm_cmple_pd(lhs.xy, rhs.xy); return _mm_movemask_pd(xy_le_pd) == 3; #else return lhs.x <= rhs.x && lhs.y <= rhs.y; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if all [xyz] components are less equal, otherwise false: all(lhs.xyz <= rhs.xyz) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_all_less_equal3(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_le_pd = _mm_cmple_pd(lhs.xy, rhs.xy); __m128d zw_le_pd = _mm_cmple_pd(lhs.zw, rhs.zw); return _mm_movemask_pd(xy_le_pd) == 3 && (_mm_movemask_pd(zw_le_pd) & 1) != 0; #else return lhs.x <= rhs.x && lhs.y <= rhs.y && lhs.z <= rhs.z; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if any 4 components are less equal, otherwise false: any(lhs.xyzw <= rhs.xyzw) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_any_less_equal(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_le_pd = _mm_cmple_pd(lhs.xy, rhs.xy); __m128d zw_le_pd = _mm_cmple_pd(lhs.zw, rhs.zw); return (_mm_movemask_pd(xy_le_pd) | _mm_movemask_pd(zw_le_pd)) != 0; #else return lhs.x <= rhs.x || lhs.y <= rhs.y || lhs.z <= rhs.z || lhs.w <= rhs.w; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if any [xy] components are less equal, otherwise false: any(lhs.xy <= rhs.xy) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_any_less_equal2(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_le_pd = _mm_cmple_pd(lhs.xy, rhs.xy); return _mm_movemask_pd(xy_le_pd) != 0; #else return lhs.x <= rhs.x || lhs.y <= rhs.y; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if any [xyz] components are less equal, otherwise false: any(lhs.xyz <= rhs.xyz) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_any_less_equal3(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_le_pd = _mm_cmple_pd(lhs.xy, rhs.xy); __m128d zw_le_pd = _mm_cmple_pd(lhs.zw, rhs.zw); return _mm_movemask_pd(xy_le_pd) != 0 || (_mm_movemask_pd(zw_le_pd) & 1) != 0; #else return lhs.x <= rhs.x || lhs.y <= rhs.y || lhs.z <= rhs.z; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if all 4 components are greater than, otherwise false: all(lhs.xyzw > rhs.xyzw) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_all_greater_than(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_ge_pd = _mm_cmpgt_pd(lhs.xy, rhs.xy); __m128d zw_ge_pd = _mm_cmpgt_pd(lhs.zw, rhs.zw); return (_mm_movemask_pd(xy_ge_pd) & _mm_movemask_pd(zw_ge_pd)) == 3; #else return lhs.x > rhs.x && lhs.y > rhs.y && lhs.z > rhs.z && lhs.w > rhs.w; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if all [xy] components are greater than, otherwise false: all(lhs.xy > rhs.xy) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_all_greater_than2(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_ge_pd = _mm_cmpgt_pd(lhs.xy, rhs.xy); return _mm_movemask_pd(xy_ge_pd) == 3; #else return lhs.x > rhs.x && lhs.y > rhs.y; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if all [xyz] components are greater than, otherwise false: all(lhs.xyz > rhs.xyz) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_all_greater_than3(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_ge_pd = _mm_cmpgt_pd(lhs.xy, rhs.xy); __m128d zw_ge_pd = _mm_cmpgt_pd(lhs.zw, rhs.zw); return _mm_movemask_pd(xy_ge_pd) == 3 && (_mm_movemask_pd(zw_ge_pd) & 1) != 0; #else return lhs.x > rhs.x && lhs.y > rhs.y && lhs.z > rhs.z; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if any 4 components are greater than, otherwise false: any(lhs.xyzw > rhs.xyzw) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_any_greater_than(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_ge_pd = _mm_cmpgt_pd(lhs.xy, rhs.xy); __m128d zw_ge_pd = _mm_cmpgt_pd(lhs.zw, rhs.zw); return (_mm_movemask_pd(xy_ge_pd) | _mm_movemask_pd(zw_ge_pd)) != 0; #else return lhs.x > rhs.x || lhs.y > rhs.y || lhs.z > rhs.z || lhs.w > rhs.w; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if any [xy] components are greater than, otherwise false: any(lhs.xy > rhs.xy) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_any_greater_than2(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_ge_pd = _mm_cmpgt_pd(lhs.xy, rhs.xy); return _mm_movemask_pd(xy_ge_pd) != 0; #else return lhs.x > rhs.x || lhs.y > rhs.y; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if any [xyz] components are greater than, otherwise false: any(lhs.xyz > rhs.xyz) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_any_greater_than3(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_ge_pd = _mm_cmpgt_pd(lhs.xy, rhs.xy); __m128d zw_ge_pd = _mm_cmpgt_pd(lhs.zw, rhs.zw); return _mm_movemask_pd(xy_ge_pd) != 0 || (_mm_movemask_pd(zw_ge_pd) & 1) != 0; #else return lhs.x > rhs.x || lhs.y > rhs.y || lhs.z > rhs.z; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if all 4 components are greater equal, otherwise false: all(lhs.xyzw >= rhs.xyzw) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_all_greater_equal(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_ge_pd = _mm_cmpge_pd(lhs.xy, rhs.xy); __m128d zw_ge_pd = _mm_cmpge_pd(lhs.zw, rhs.zw); return (_mm_movemask_pd(xy_ge_pd) & _mm_movemask_pd(zw_ge_pd)) == 3; #else return lhs.x >= rhs.x && lhs.y >= rhs.y && lhs.z >= rhs.z && lhs.w >= rhs.w; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if all [xy] components are greater equal, otherwise false: all(lhs.xy >= rhs.xy) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_all_greater_equal2(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_ge_pd = _mm_cmpge_pd(lhs.xy, rhs.xy); return _mm_movemask_pd(xy_ge_pd) == 3; #else return lhs.x >= rhs.x && lhs.y >= rhs.y; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if all [xyz] components are greater equal, otherwise false: all(lhs.xyz >= rhs.xyz) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_all_greater_equal3(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_ge_pd = _mm_cmpge_pd(lhs.xy, rhs.xy); __m128d zw_ge_pd = _mm_cmpge_pd(lhs.zw, rhs.zw); return _mm_movemask_pd(xy_ge_pd) == 3 && (_mm_movemask_pd(zw_ge_pd) & 1) != 0; #else return lhs.x >= rhs.x && lhs.y >= rhs.y && lhs.z >= rhs.z; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if any 4 components are greater equal, otherwise false: any(lhs.xyzw >= rhs.xyzw) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_any_greater_equal(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_ge_pd = _mm_cmpge_pd(lhs.xy, rhs.xy); __m128d zw_ge_pd = _mm_cmpge_pd(lhs.zw, rhs.zw); return (_mm_movemask_pd(xy_ge_pd) | _mm_movemask_pd(zw_ge_pd)) != 0; #else return lhs.x >= rhs.x || lhs.y >= rhs.y || lhs.z >= rhs.z || lhs.w >= rhs.w; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if any [xy] components are greater equal, otherwise false: any(lhs.xy >= rhs.xy) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_any_greater_equal2(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_ge_pd = _mm_cmpge_pd(lhs.xy, rhs.xy); return _mm_movemask_pd(xy_ge_pd) != 0; #else return lhs.x >= rhs.x || lhs.y >= rhs.y; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if any [xyz] components are greater equal, otherwise false: any(lhs.xyz >= rhs.xyz) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_any_greater_equal3(const vector4d& lhs, const vector4d& rhs) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy_ge_pd = _mm_cmpge_pd(lhs.xy, rhs.xy); __m128d zw_ge_pd = _mm_cmpge_pd(lhs.zw, rhs.zw); return _mm_movemask_pd(xy_ge_pd) != 0 || (_mm_movemask_pd(zw_ge_pd) & 1) != 0; #else return lhs.x >= rhs.x || lhs.y >= rhs.y || lhs.z >= rhs.z; #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if all 4 components are near equal, otherwise false: all(abs(lhs - rhs).xyzw <= threshold) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_all_near_equal(const vector4d& lhs, const vector4d& rhs, double threshold = 0.00001) RTM_NO_EXCEPT { return vector_all_less_equal(vector_abs(vector_sub(lhs, rhs)), vector_set(threshold)); } ////////////////////////////////////////////////////////////////////////// // Returns true if all [xy] components are near equal, otherwise false: all(abs(lhs - rhs).xy <= threshold) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_all_near_equal2(const vector4d& lhs, const vector4d& rhs, double threshold = 0.00001) RTM_NO_EXCEPT { return vector_all_less_equal2(vector_abs(vector_sub(lhs, rhs)), vector_set(threshold)); } ////////////////////////////////////////////////////////////////////////// // Returns true if all [xyz] components are near equal, otherwise false: all(abs(lhs - rhs).xyz <= threshold) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_all_near_equal3(const vector4d& lhs, const vector4d& rhs, double threshold = 0.00001) RTM_NO_EXCEPT { return vector_all_less_equal3(vector_abs(vector_sub(lhs, rhs)), vector_set(threshold)); } ////////////////////////////////////////////////////////////////////////// // Returns true if any 4 components are near equal, otherwise false: any(abs(lhs - rhs).xyzw <= threshold) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_any_near_equal(const vector4d& lhs, const vector4d& rhs, double threshold = 0.00001) RTM_NO_EXCEPT { return vector_any_less_equal(vector_abs(vector_sub(lhs, rhs)), vector_set(threshold)); } ////////////////////////////////////////////////////////////////////////// // Returns true if any [xy] components are near equal, otherwise false: any(abs(lhs - rhs).xy <= threshold) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_any_near_equal2(const vector4d& lhs, const vector4d& rhs, double threshold = 0.00001) RTM_NO_EXCEPT { return vector_any_less_equal2(vector_abs(vector_sub(lhs, rhs)), vector_set(threshold)); } ////////////////////////////////////////////////////////////////////////// // Returns true if any [xyz] components are near equal, otherwise false: any(abs(lhs - rhs).xyz <= threshold) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_any_near_equal3(const vector4d& lhs, const vector4d& rhs, double threshold = 0.00001) RTM_NO_EXCEPT { return vector_any_less_equal3(vector_abs(vector_sub(lhs, rhs)), vector_set(threshold)); } ////////////////////////////////////////////////////////////////////////// // Returns true if all 4 components are finite (not NaN/Inf), otherwise false: all(finite(input)) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_is_finite(const vector4d& input) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) const __m128i abs_mask = _mm_set_epi64x(0x7FFFFFFFFFFFFFFFULL, 0x7FFFFFFFFFFFFFFFULL); __m128d abs_input_xy = _mm_and_pd(input.xy, _mm_castsi128_pd(abs_mask)); __m128d abs_input_zw = _mm_and_pd(input.zw, _mm_castsi128_pd(abs_mask)); const __m128d infinity = _mm_set1_pd(std::numeric_limits<double>::infinity()); __m128d is_infinity_xy = _mm_cmpeq_pd(abs_input_xy, infinity); __m128d is_infinity_zw = _mm_cmpeq_pd(abs_input_zw, infinity); __m128d is_nan_xy = _mm_cmpneq_pd(input.xy, input.xy); __m128d is_nan_zw = _mm_cmpneq_pd(input.zw, input.zw); __m128d is_not_finite_xy = _mm_or_pd(is_infinity_xy, is_nan_xy); __m128d is_not_finite_zw = _mm_or_pd(is_infinity_zw, is_nan_zw); __m128d is_not_finite = _mm_or_pd(is_not_finite_xy, is_not_finite_zw); return _mm_movemask_pd(is_not_finite) == 0x0; #else return scalar_is_finite(vector_get_x(input)) && scalar_is_finite(vector_get_y(input)) && scalar_is_finite(vector_get_z(input)) && scalar_is_finite(vector_get_w(input)); #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if all [xy] components are finite (not NaN/Inf), otherwise false: all(finite(input)) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_is_finite2(const vector4d& input) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) const __m128i abs_mask = _mm_set_epi64x(0x7FFFFFFFFFFFFFFFULL, 0x7FFFFFFFFFFFFFFFULL); __m128d abs_input_xy = _mm_and_pd(input.xy, _mm_castsi128_pd(abs_mask)); const __m128d infinity = _mm_set1_pd(std::numeric_limits<double>::infinity()); __m128d is_infinity_xy = _mm_cmpeq_pd(abs_input_xy, infinity); __m128d is_nan_xy = _mm_cmpneq_pd(input.xy, input.xy); __m128d is_not_finite_xy = _mm_or_pd(is_infinity_xy, is_nan_xy); return _mm_movemask_pd(is_not_finite_xy) == 0x0; #else return scalar_is_finite(vector_get_x(input)) && scalar_is_finite(vector_get_y(input)); #endif } ////////////////////////////////////////////////////////////////////////// // Returns true if all [xyz] components are finite (not NaN/Inf), otherwise false: all(finite(input)) ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE bool vector_is_finite3(const vector4d& input) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) const __m128i abs_mask = _mm_set_epi64x(0x7FFFFFFFFFFFFFFFULL, 0x7FFFFFFFFFFFFFFFULL); __m128d abs_input_xy = _mm_and_pd(input.xy, _mm_castsi128_pd(abs_mask)); __m128d abs_input_zw = _mm_and_pd(input.zw, _mm_castsi128_pd(abs_mask)); const __m128d infinity = _mm_set1_pd(std::numeric_limits<double>::infinity()); __m128d is_infinity_xy = _mm_cmpeq_pd(abs_input_xy, infinity); __m128d is_infinity_zw = _mm_cmpeq_pd(abs_input_zw, infinity); __m128d is_nan_xy = _mm_cmpneq_pd(input.xy, input.xy); __m128d is_nan_zw = _mm_cmpneq_pd(input.zw, input.zw); __m128d is_not_finite_xy = _mm_or_pd(is_infinity_xy, is_nan_xy); __m128d is_not_finite_zw = _mm_or_pd(is_infinity_zw, is_nan_zw); return _mm_movemask_pd(is_not_finite_xy) == 0 && (_mm_movemask_pd(is_not_finite_zw) & 0x1) == 0; #else return scalar_is_finite(vector_get_x(input)) && scalar_is_finite(vector_get_y(input)) && scalar_is_finite(vector_get_z(input)); #endif } ////////////////////////////////////////////////////////////////////////// // Swizzling, permutations, and mixing ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Per component selection depending on the mask: mask != 0 ? if_true : if_false ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_select(const mask4d& mask, const vector4d& if_true, const vector4d& if_false) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy = RTM_VECTOR2D_SELECT(mask.xy, if_true.xy, if_false.xy); __m128d zw = RTM_VECTOR2D_SELECT(mask.zw, if_true.zw, if_false.zw); return vector4d{ xy, zw }; #else return vector4d{ rtm_impl::select(mask.x, if_true.x, if_false.x), rtm_impl::select(mask.y, if_true.y, if_false.y), rtm_impl::select(mask.z, if_true.z, if_false.z), rtm_impl::select(mask.w, if_true.w, if_false.w) }; #endif } ////////////////////////////////////////////////////////////////////////// // Mixes two inputs and returns the desired components. // [xyzw] indexes into the first input while [abcd] indexes in the second. ////////////////////////////////////////////////////////////////////////// template<mix4 comp0, mix4 comp1, mix4 comp2, mix4 comp3> RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_mix(const vector4d& input0, const vector4d& input1) RTM_NO_EXCEPT { // Slow code path, not yet optimized or not using intrinsics const double x = rtm_impl::is_mix_xyzw(comp0) ? vector_get_component<comp0>(input0) : vector_get_component<comp0>(input1); const double y = rtm_impl::is_mix_xyzw(comp1) ? vector_get_component<comp1>(input0) : vector_get_component<comp1>(input1); const double z = rtm_impl::is_mix_xyzw(comp2) ? vector_get_component<comp2>(input0) : vector_get_component<comp2>(input1); const double w = rtm_impl::is_mix_xyzw(comp3) ? vector_get_component<comp3>(input0) : vector_get_component<comp3>(input1); return vector_set(x, y, z, w); } ////////////////////////////////////////////////////////////////////////// // Replicates the [x] component in all components. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_dup_x(const vector4d& input) RTM_NO_EXCEPT { return vector_mix<mix4::x, mix4::x, mix4::x, mix4::x>(input, input); } ////////////////////////////////////////////////////////////////////////// // Replicates the [y] component in all components. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_dup_y(const vector4d& input) RTM_NO_EXCEPT { return vector_mix<mix4::y, mix4::y, mix4::y, mix4::y>(input, input); } ////////////////////////////////////////////////////////////////////////// // Replicates the [z] component in all components. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_dup_z(const vector4d& input) RTM_NO_EXCEPT { return vector_mix<mix4::z, mix4::z, mix4::z, mix4::z>(input, input); } ////////////////////////////////////////////////////////////////////////// // Replicates the [w] component in all components. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_dup_w(const vector4d& input) RTM_NO_EXCEPT { return vector_mix<mix4::w, mix4::w, mix4::w, mix4::w>(input, input); } ////////////////////////////////////////////////////////////////////////// // Logical ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Per component logical AND between the inputs: input0 & input1 ////////////////////////////////////////////////////////////////////////// inline vector4d vector_and(const vector4d& input0, const vector4d& input1) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy = _mm_and_pd(input0.xy, input1.xy); __m128d zw = _mm_and_pd(input0.zw, input1.zw); return vector4d{ xy, zw }; #else const uint64_t* input0_ = reinterpret_cast<const uint64_t*>(&input0); const uint64_t* input1_ = reinterpret_cast<const uint64_t*>(&input1); vector4d result; uint64_t* result_ = reinterpret_cast<uint64_t*>(&result); result_[0] = input0_[0] & input1_[0]; result_[1] = input0_[1] & input1_[1]; result_[2] = input0_[2] & input1_[2]; result_[3] = input0_[3] & input1_[3]; return result; #endif } ////////////////////////////////////////////////////////////////////////// // Per component logical OR between the inputs: input0 | input1 ////////////////////////////////////////////////////////////////////////// inline vector4d vector_or(const vector4d& input0, const vector4d& input1) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy = _mm_or_pd(input0.xy, input1.xy); __m128d zw = _mm_or_pd(input0.zw, input1.zw); return vector4d{ xy, zw }; #else const uint64_t* input0_ = reinterpret_cast<const uint64_t*>(&input0); const uint64_t* input1_ = reinterpret_cast<const uint64_t*>(&input1); vector4d result; uint64_t* result_ = reinterpret_cast<uint64_t*>(&result); result_[0] = input0_[0] | input1_[0]; result_[1] = input0_[1] | input1_[1]; result_[2] = input0_[2] | input1_[2]; result_[3] = input0_[3] | input1_[3]; return result; #endif } ////////////////////////////////////////////////////////////////////////// // Per component logical XOR between the inputs: input0 ^ input1 ////////////////////////////////////////////////////////////////////////// inline vector4d vector_xor(const vector4d& input0, const vector4d& input1) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) __m128d xy = _mm_xor_pd(input0.xy, input1.xy); __m128d zw = _mm_xor_pd(input0.zw, input1.zw); return vector4d{ xy, zw }; #else const uint64_t* input0_ = reinterpret_cast<const uint64_t*>(&input0); const uint64_t* input1_ = reinterpret_cast<const uint64_t*>(&input1); vector4d result; uint64_t* result_ = reinterpret_cast<uint64_t*>(&result); result_[0] = input0_[0] ^ input1_[0]; result_[1] = input0_[1] ^ input1_[1]; result_[2] = input0_[2] ^ input1_[2]; result_[3] = input0_[3] ^ input1_[3]; return result; #endif } ////////////////////////////////////////////////////////////////////////// // Miscellaneous ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Returns per component the sign of the input vector: input >= 0.0 ? 1.0 : -1.0 ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_sign(const vector4d& input) RTM_NO_EXCEPT { const mask4d mask = vector_greater_equal(input, vector_zero()); return vector_select(mask, vector_set(1.0), vector_set(-1.0)); } ////////////////////////////////////////////////////////////////////////// // Returns per component the input with the sign of the control value. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_copy_sign(const vector4d& input, const vector4d& control_sign) RTM_NO_EXCEPT { #if defined(RTM_SSE2_INTRINSICS) const __m128d sign_bit = _mm_set1_pd(-0.0); __m128d signs_xy = _mm_and_pd(sign_bit, control_sign.xy); __m128d signs_zw = _mm_and_pd(sign_bit, control_sign.zw); __m128d abs_input_xy = _mm_andnot_pd(sign_bit, input.xy); __m128d abs_input_zw = _mm_andnot_pd(sign_bit, input.zw); __m128d xy = _mm_or_pd(abs_input_xy, signs_xy); __m128d zw = _mm_or_pd(abs_input_zw, signs_zw); return vector4d{ xy, zw }; #else double x = vector_get_x(input); double y = vector_get_y(input); double z = vector_get_z(input); double w = vector_get_w(input); double x_sign = vector_get_x(control_sign); double y_sign = vector_get_y(control_sign); double z_sign = vector_get_z(control_sign); double w_sign = vector_get_w(control_sign); return vector_set(rtm_impl::copysign(x, x_sign), rtm_impl::copysign(y, y_sign), rtm_impl::copysign(z, z_sign), rtm_impl::copysign(w, w_sign)); #endif } ////////////////////////////////////////////////////////////////////////// // Returns per component the rounded input using a symmetric algorithm. // vector_round_symmetric(1.5) = 2.0 // vector_round_symmetric(1.2) = 1.0 // vector_round_symmetric(-1.5) = -2.0 // vector_round_symmetric(-1.2) = -1.0 ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK inline vector4d vector_round_symmetric(const vector4d& input) RTM_NO_EXCEPT { // NaN, +- Infinity, and numbers larger or equal to 2^23 remain unchanged // since they have no fractional part. #if defined(RTM_SSE4_INTRINSICS) __m128d zero = _mm_setzero_pd(); __m128d is_positive_xy = _mm_cmpge_pd(input.xy, zero); __m128d is_positive_zw = _mm_cmpge_pd(input.zw, zero); const __m128d sign_mask = _mm_set_pd(-0.0, -0.0); __m128d sign_xy = _mm_andnot_pd(is_positive_xy, sign_mask); __m128d sign_zw = _mm_andnot_pd(is_positive_zw, sign_mask); // For positive values, we add a bias of 0.5. // For negative values, we add a bias of -0.5. __m128d half = _mm_set1_pd(0.5); __m128d bias_xy = _mm_or_pd(sign_xy, half); __m128d bias_zw = _mm_or_pd(sign_zw, half); __m128d biased_input_xy = _mm_add_pd(input.xy, bias_xy); __m128d biased_input_zw = _mm_add_pd(input.zw, bias_zw); __m128d floored_xy = _mm_floor_pd(biased_input_xy); __m128d floored_zw = _mm_floor_pd(biased_input_zw); __m128d ceiled_xy = _mm_ceil_pd(biased_input_xy); __m128d ceiled_zw = _mm_ceil_pd(biased_input_zw); __m128d result_xy = RTM_VECTOR2D_SELECT(is_positive_xy, floored_xy, ceiled_xy); __m128d result_zw = RTM_VECTOR2D_SELECT(is_positive_zw, floored_zw, ceiled_zw); return vector4d{ result_xy, result_zw }; #elif defined(RTM_SSE2_INTRINSICS) const __m128i abs_mask = _mm_set_epi64x(0x7FFFFFFFFFFFFFFFULL, 0x7FFFFFFFFFFFFFFFULL); const __m128d fractional_limit = _mm_set1_pd(4503599627370496.0); // 2^52 // Build our mask, larger values that have no fractional part, and infinities will be true // Smaller values and NaN will be false __m128d abs_input_xy = _mm_and_pd(input.xy, _mm_castsi128_pd(abs_mask)); __m128d abs_input_zw = _mm_and_pd(input.zw, _mm_castsi128_pd(abs_mask)); __m128d is_input_large_xy = _mm_cmpge_pd(abs_input_xy, fractional_limit); __m128d is_input_large_zw = _mm_cmpge_pd(abs_input_zw, fractional_limit); // Test if our input is NaN with (value != value), it is only true for NaN __m128d is_nan_xy = _mm_cmpneq_pd(input.xy, input.xy); __m128d is_nan_zw = _mm_cmpneq_pd(input.zw, input.zw); // Combine our masks to determine if we should return the original value __m128d use_original_input_xy = _mm_or_pd(is_input_large_xy, is_nan_xy); __m128d use_original_input_zw = _mm_or_pd(is_input_large_zw, is_nan_zw); const __m128d sign_mask = _mm_set_pd(-0.0, -0.0); __m128d sign_xy = _mm_and_pd(input.xy, sign_mask); __m128d sign_zw = _mm_and_pd(input.zw, sign_mask); // For positive values, we add a bias of 0.5. // For negative values, we add a bias of -0.5. __m128d half = _mm_set1_pd(0.5); __m128d bias_xy = _mm_or_pd(sign_xy, half); __m128d bias_zw = _mm_or_pd(sign_zw, half); __m128d biased_input_xy = _mm_add_pd(input.xy, bias_xy); __m128d biased_input_zw = _mm_add_pd(input.zw, bias_zw); // Convert to an integer with truncation and back, this rounds towards zero. __m128d integer_part_xy = _mm_cvtepi32_pd(_mm_cvttpd_epi32(biased_input_xy)); __m128d integer_part_zw = _mm_cvtepi32_pd(_mm_cvttpd_epi32(biased_input_zw)); __m128d result_xy = _mm_or_pd(_mm_and_pd(use_original_input_xy, input.xy), _mm_andnot_pd(use_original_input_xy, integer_part_xy)); __m128d result_zw = _mm_or_pd(_mm_and_pd(use_original_input_zw, input.zw), _mm_andnot_pd(use_original_input_zw, integer_part_zw)); return vector4d{ result_xy, result_zw }; #else const vector4d half = vector_set(0.5); const vector4d floored = vector_floor(vector_add(input, half)); const vector4d ceiled = vector_ceil(vector_sub(input, half)); const mask4d is_greater_equal = vector_greater_equal(input, vector_zero()); return vector_select(is_greater_equal, floored, ceiled); #endif } ////////////////////////////////////////////////////////////////////////// // Returns per component the rounded input using banker's rounding (half to even). // vector_round_bankers(2.5) = 2.0 // vector_round_bankers(1.5) = 2.0 // vector_round_bankers(1.2) = 1.0 // vector_round_bankers(-2.5) = -2.0 // vector_round_bankers(-1.5) = -2.0 // vector_round_bankers(-1.2) = -1.0 ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK RTM_FORCE_INLINE vector4d vector_round_bankers(const vector4d& input) RTM_NO_EXCEPT { #if defined(RTM_SSE4_INTRINSICS) return vector4d{ _mm_round_pd(input.xy, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC), _mm_round_pd(input.zw, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) }; #elif defined(RTM_SSE2_INTRINSICS) const __m128i abs_mask = _mm_set_epi64x(0x7FFFFFFFFFFFFFFFULL, 0x7FFFFFFFFFFFFFFFULL); const __m128d sign_mask = _mm_set_pd(-0.0, -0.0); __m128d sign_xy = _mm_and_pd(input.xy, sign_mask); __m128d sign_zw = _mm_and_pd(input.zw, sign_mask); // We add the largest integer that a 64 bit floating point number can represent and subtract it afterwards. // This relies on the fact that if we had a fractional part, the new value cannot be represented accurately // and IEEE 754 will perform rounding for us. The default rounding mode is Banker's rounding. // This has the effect of removing the fractional part while simultaneously rounding. // Use the same sign as the input value to make sure we handle positive and negative values. const __m128d fractional_limit = _mm_set1_pd(4503599627370496.0); // 2^52 __m128d truncating_offset_xy = _mm_or_pd(sign_xy, fractional_limit); __m128d truncating_offset_zw = _mm_or_pd(sign_zw, fractional_limit); __m128d integer_part_xy = _mm_sub_pd(_mm_add_pd(input.xy, truncating_offset_xy), truncating_offset_xy); __m128d integer_part_zw = _mm_sub_pd(_mm_add_pd(input.zw, truncating_offset_zw), truncating_offset_zw); __m128d abs_input_xy = _mm_and_pd(input.xy, _mm_castsi128_pd(abs_mask)); __m128d abs_input_zw = _mm_and_pd(input.zw, _mm_castsi128_pd(abs_mask)); __m128d is_input_large_xy = _mm_cmpge_pd(abs_input_xy, fractional_limit); __m128d is_input_large_zw = _mm_cmpge_pd(abs_input_zw, fractional_limit); __m128d result_xy = _mm_or_pd(_mm_and_pd(is_input_large_xy, input.xy), _mm_andnot_pd(is_input_large_xy, integer_part_xy)); __m128d result_zw = _mm_or_pd(_mm_and_pd(is_input_large_zw, input.zw), _mm_andnot_pd(is_input_large_zw, integer_part_zw)); return vector4d{ result_xy, result_zw }; #else scalard x = scalar_round_bankers(scalard(vector_get_x(input))); scalard y = scalar_round_bankers(scalard(vector_get_y(input))); scalard z = scalar_round_bankers(scalard(vector_get_z(input))); scalard w = scalar_round_bankers(scalard(vector_get_w(input))); return vector_set(x, y, z, w); #endif } ////////////////////////////////////////////////////////////////////////// // Returns per component the sine of the input angle. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK inline vector4d vector_sin(const vector4d& input) RTM_NO_EXCEPT { scalard x = scalar_sin(scalard(vector_get_x(input))); scalard y = scalar_sin(scalard(vector_get_y(input))); scalard z = scalar_sin(scalard(vector_get_z(input))); scalard w = scalar_sin(scalard(vector_get_w(input))); return vector_set(x, y, z, w); } ////////////////////////////////////////////////////////////////////////// // Returns per component the arc-sine of the input. // Input value must be in the range [-1.0, 1.0]. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK inline vector4d vector_asin(const vector4d& input) RTM_NO_EXCEPT { scalard x = scalar_asin(scalard(vector_get_x(input))); scalard y = scalar_asin(scalard(vector_get_y(input))); scalard z = scalar_asin(scalard(vector_get_z(input))); scalard w = scalar_asin(scalard(vector_get_w(input))); return vector_set(x, y, z, w); } ////////////////////////////////////////////////////////////////////////// // Returns per component the cosine of the input angle. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK inline vector4d vector_cos(const vector4d& input) RTM_NO_EXCEPT { scalard x = scalar_cos(scalard(vector_get_x(input))); scalard y = scalar_cos(scalard(vector_get_y(input))); scalard z = scalar_cos(scalard(vector_get_z(input))); scalard w = scalar_cos(scalard(vector_get_w(input))); return vector_set(x, y, z, w); } ////////////////////////////////////////////////////////////////////////// // Returns per component the arc-cosine of the input. // Input value must be in the range [-1.0, 1.0]. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK inline vector4d vector_acos(const vector4d& input) RTM_NO_EXCEPT { scalard x = scalar_acos(scalard(vector_get_x(input))); scalard y = scalar_acos(scalard(vector_get_y(input))); scalard z = scalar_acos(scalard(vector_get_z(input))); scalard w = scalar_acos(scalard(vector_get_w(input))); return vector_set(x, y, z, w); } ////////////////////////////////////////////////////////////////////////// // Returns per component the sine and cosine of the input angle. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK inline void vector_sincos(const vector4d& input, vector4d& out_sine, vector4d& out_cosine) RTM_NO_EXCEPT { const vector4d x = scalar_sincos(scalard(vector_get_x(input))); const vector4d y = scalar_sincos(scalard(vector_get_y(input))); const vector4d z = scalar_sincos(scalard(vector_get_z(input))); const vector4d w = scalar_sincos(scalard(vector_get_w(input))); const vector4d cos_xy = vector_mix<mix4::y, mix4::b, mix4::y, mix4::b>(x, y); const vector4d cos_zw = vector_mix<mix4::y, mix4::b, mix4::y, mix4::b>(z, w); out_cosine = vector_mix<mix4::x, mix4::y, mix4::a, mix4::b>(cos_xy, cos_zw); const vector4d sin_xy = vector_mix<mix4::x, mix4::a, mix4::x, mix4::a>(x, y); const vector4d sin_zw = vector_mix<mix4::x, mix4::a, mix4::x, mix4::a>(z, w); out_sine = vector_mix<mix4::x, mix4::y, mix4::a, mix4::b>(sin_xy, sin_zw); } ////////////////////////////////////////////////////////////////////////// // Returns per component the tangent of the input angle. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK inline vector4d vector_tan(const vector4d& angle) RTM_NO_EXCEPT { // Use the identity: tan(angle) = sin(angle) / cos(angle) vector4d sin_; vector4d cos_; vector_sincos(angle, sin_, cos_); const mask4d is_cos_zero = vector_equal(cos_, vector_zero()); const vector4d signed_infinity = vector_copy_sign(vector_set(std::numeric_limits<double>::infinity()), angle); const vector4d result = vector_div(sin_, cos_); return vector_select(is_cos_zero, signed_infinity, result); } ////////////////////////////////////////////////////////////////////////// // Returns per component the arc-tangent of the input. // Note that due to the sign ambiguity, atan cannot determine which quadrant // the value resides in. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK inline vector4d vector_atan(const vector4d& input) RTM_NO_EXCEPT { scalard x = scalar_atan(scalard(vector_get_x(input))); scalard y = scalar_atan(scalard(vector_get_y(input))); scalard z = scalar_atan(scalard(vector_get_z(input))); scalard w = scalar_atan(scalard(vector_get_w(input))); return vector_set(x, y, z, w); } ////////////////////////////////////////////////////////////////////////// // Returns per component the arc-tangent of [y/x] using the sign of the arguments to // determine the correct quadrant. // Y represents the proportion of the y-coordinate. // X represents the proportion of the x-coordinate. ////////////////////////////////////////////////////////////////////////// RTM_DISABLE_SECURITY_COOKIE_CHECK inline vector4d vector_atan2(const vector4d& y, const vector4d& x) RTM_NO_EXCEPT { scalard x_ = scalar_atan2(scalard(vector_get_x(y)), scalard(vector_get_x(x))); scalard y_ = scalar_atan2(scalard(vector_get_y(y)), scalard(vector_get_y(x))); scalard z_ = scalar_atan2(scalard(vector_get_z(y)), scalard(vector_get_z(x))); scalard w_ = scalar_atan2(scalard(vector_get_w(y)), scalard(vector_get_w(x))); return vector_set(x_, y_, z_, w_); } RTM_IMPL_VERSION_NAMESPACE_END } RTM_IMPL_FILE_PRAGMA_POP
46.906484
216
0.594732
[ "vector", "3d" ]
45abbcf4337a604cbffa489a03e2e19ba0c85ed5
9,101
h
C
libs/SalesforceSDKCore/SalesforceSDKCore/Classes/Network/Network/Queue/CSFNetwork.h
appstronomy/SalesforceMobileSDK-iOS
f7aa1224c1cfc82614155145779c695d7595cb94
[ "Apache-2.0" ]
null
null
null
libs/SalesforceSDKCore/SalesforceSDKCore/Classes/Network/Network/Queue/CSFNetwork.h
appstronomy/SalesforceMobileSDK-iOS
f7aa1224c1cfc82614155145779c695d7595cb94
[ "Apache-2.0" ]
null
null
null
libs/SalesforceSDKCore/SalesforceSDKCore/Classes/Network/Network/Queue/CSFNetwork.h
appstronomy/SalesforceMobileSDK-iOS
f7aa1224c1cfc82614155145779c695d7595cb94
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved. Redistribution and use of this software 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 salesforce.com, inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of salesforce.com, inc. 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. */ #import <Foundation/Foundation.h> #import "SalesforceSDKConstants.h" @class CSFAction; @class SFUserAccount; @protocol CSFNetworkOutputCache; @protocol CSFNetworkDelegate; /** This is the scheduler and network dispatch class for managing a series of network operations on behalf of an application. Each instance is bound to an individual user account, and manages the OAuth2 token refresh, queueing and scheduling of network operations, handling the parsing of responses, and aggregation of common actions into batches. */ SFSDK_DEPRECATED(5.2, 6.0, "Use our SFRestAPI library instead to make REST API requests.") @interface CSFNetwork : NSObject @property (nonatomic, readonly, strong) NSURLSession *ephemeralSession; /** Indicates whether the network operation queue is suspended or not. @discussion This value will be automatically updated as network availability or OAuth2 access refreshes occur. It can be manually set to temporarily suspend the queue. */ @property (nonatomic, assign, getter = isNetworkSuspended) BOOL networkSuspended; @property (nonatomic, readonly, getter = isOnline) BOOL online; /** The count of network requests currently queued for processing. */ @property (nonatomic, assign, readonly) NSUInteger actionCount; /** The user account instance this CSFNetwork represents. */ @property (nonatomic, strong, readonly) SFUserAccount *account; /** * Indicates if the access token for this user account is being refreshed. * * During a token refresh, all active operations in the queue are suspended while the * token is updated. When the token is refreshed, the queue will resume. * * @see networkSuspended */ @property (atomic, readonly, getter=isRefreshingAccessToken) BOOL refreshingAccessToken; /** Reports aggregated progress information for all actions currently enqueued in this network instance. */ @property (nonatomic, strong, readonly) NSProgress *progress; /** Returns the network instance for the currently active user account. @see networkForUserAccount: */ + (instancetype)currentNetwork; /** Returns a shared global shared network instance. @see networkForUserAccount: */ + (instancetype)globalNetwork; /** Returns a reference to the shared instance of this class for the supplied user. If an instance doesn't yet exist for this user, one will be created. if nil will return a shared global network instance. @see currentNetwork */ + (instancetype)networkForUserAccount:(SFUserAccount*)account; /** Schedules and executes the supplied action on this network stack. */ - (void)executeAction:(CSFAction *)action; /** Executes each action in the array of actions, used for batch mode. */ - (void)executeActions:(NSArray *)actions completionBlock:(void(^)(NSArray *actions, NSArray *errors))completionBlock; /** Cancel all operations. */ - (void)cancelAllActions; /** * Cancel all operations matching the given context instance. * * @see [CSFAction context] */ - (void)cancelAllActionsWithContext:(id)context; /** * Returns a set of enqueued operations that have the given context. * * @see [CSFAction context] */ - (NSArray*)actionsWithContext:(id)context; /** * Sets a session configuration to be used for network requests in the Network SDK. * * @param sessionConfig Session configuration to be used. * @param isBackgroundSession YES - if it is a background session configuration, NO - otherwise. */ - (void)setSessionConfiguration:(NSURLSessionConfiguration *)sessionConfig isBackgroundSession:(BOOL)isBackgroundSession; /** Cross-site Request Forgery (CSRF) token provided in each server response and required for all Push API requests that change state (i.e. POST). */ @property (nonatomic, copy) NSString *securityToken; - (void)addDelegate:(id<CSFNetworkDelegate>)delegate; - (void)removeDelegate:(id<CSFNetworkDelegate>)delegate; @end @interface CSFNetwork (Salesforce) /** The ID for the Chatter Community that all Connect actions should use. Not all actions are Chatter Connect requests, nor do all Connect requests need to be made against a Chatter Community. But if a CHConnectAction request is enqueued that has a nil [CHConnectAction communityId] value, then this property will be used to set the default value that should be used. If this value is `nil` then all CHConnectAction requests whose communityId value is `nil` will not be altered. @see [CSFChatterAction communityId] */ @property (nonatomic, copy) NSString *defaultConnectCommunityId; @end @interface CSFNetwork (Caching) /** Indicates if caching the results of network requests through a local cache is enabled. @discussion This utilizes the instance supplied to the outputCache property to create a local persistent store to serialize the contents of network responses for use in accessing data offline. @see CSFNetworkOutputCache @see [CSFAction cacheResponse] */ @property (nonatomic, assign, getter = isOfflineCacheEnabled) BOOL offlineCacheEnabled; /** List of output cache handlers that will be used for storing results retrieved from this network instance. @discussion This array will contain a list of all the cache handlers that should be consulted when results are retrieved. Each object should conform to the CSFNetworkOutputCache protocol, and will each be interrogated in turn to determine whether or not they are capable of processing the results of each action. @see addOutputCache: @see removeOutputCache: */ @property (nonatomic, copy, readonly) NSArray *outputCaches; /** Explicitly adds an output cache handler to this network instance. @discussion Output caches support a plugin architechture where classes that implement the CSFNetworkOutputCache method cacheInstanceForNetwork: are automatically asked whether or not they should be supported within the supplied network instance. If you don't utilize this mechanism, explicit cache instances can be added using this method here. @param outputCache Output cache instance to add. */ - (void)addOutputCache:(NSObject<CSFNetworkOutputCache> *)outputCache; /** Explicitly removes the indicated output cache handler from this network instance. @param outputCache Output cache instance to remove. */ - (void)removeOutputCache:(NSObject<CSFNetworkOutputCache> *)outputCache; @end SFSDK_DEPRECATED(5.2, 6.0, "Use our SFRestAPI library instead to make REST API requests.") @protocol CSFNetworkDelegate <NSObject> @optional /** Called when an action is about to get enqueued. @discussion This method is called synchronously, giving the delegates a chance to inspect the action before CSFNetwork acts on it. Perform as little work as possible on this callback to avoid performance degradation. */ - (void)network:(CSFNetwork*)network willEnqueueAction:(CSFAction*)action; /** These methods inform delegates asynchronously about state of actions. */ - (void)network:(CSFNetwork*)network didStartAction:(CSFAction*)action; - (void)network:(CSFNetwork*)network didCancelAction:(CSFAction*)action; - (void)network:(CSFNetwork*)network didCompleteAction:(CSFAction*)action withError:(NSError*)error; /** Inform delegates asynchronously about states of tasks for an action @discussion This method enables monitoring states of particular tasks that an action might trigger. @see NSURLSessionTaskState */ - (void)network:(CSFNetwork*)network sessionTask:(NSURLSessionTask*)task changedState:(NSURLSessionTaskState)oldState toState:(NSURLSessionTaskState)newState forAction:(CSFAction*)action; @end
37.920833
334
0.78343
[ "object" ]
45b5c575f6a54eb09c2f65fc8ff556ec0a36af38
31,438
c
C
DualAxisGantryStab.X/SALTStabilizationInnerOuterLoop.c
FrauBluher/SALT
0a329fbbc574dae6cf6b99ac6683441f2e7f41eb
[ "MIT" ]
1
2015-01-31T07:30:41.000Z
2015-01-31T07:30:41.000Z
SALTStabilizationInnerOuterLoop_ert_rtw/SALTStabilizationInnerOuterLoop.c
FrauBluher/SALT
0a329fbbc574dae6cf6b99ac6683441f2e7f41eb
[ "MIT" ]
null
null
null
SALTStabilizationInnerOuterLoop_ert_rtw/SALTStabilizationInnerOuterLoop.c
FrauBluher/SALT
0a329fbbc574dae6cf6b99ac6683441f2e7f41eb
[ "MIT" ]
null
null
null
/* * File: SALTStabilizationInnerOuterLoop.c * * Code generated for Simulink model 'SALTStabilizationInnerOuterLoop'. * * Model version : 1.16 * Simulink Coder version : 8.1 (R2011b) 08-Jul-2011 * TLC version : 8.1 (Jul 9 2011) * C/C++ source code generated on : Fri Aug 16 18:44:18 2013 * * Target selection: ert.tlc * Embedded hardware selection: Microchip->dsPIC * Code generation objectives: Unspecified * Validation result: Not run */ #include "SALTStabilizationInnerOuterLoop.h" #include "SALTStabilizationInnerOuterLoop_private.h" /* Exported block states */ real32_T commandedAngle; /* '<Root>/Data Store Memory' */ real32_T torqueInputX; /* '<Root>/Data Store Memory11' */ real32_T AccelX; /* '<Root>/Data Store Memory12' */ real32_T GyroX; /* '<Root>/Data Store Memory13' */ real32_T AccelZ; /* '<Root>/Data Store Memory14' */ real32_T GyroZ; /* '<Root>/Data Store Memory15' */ real32_T CommandedY; /* '<Root>/Data Store Memory16' */ real32_T AccelY; /* '<Root>/Data Store Memory17' */ real32_T CommandedX; /* '<Root>/Data Store Memory18' */ real32_T torqueInputY; /* '<Root>/Data Store Memory19' */ real32_T GyroY; /* '<Root>/Data Store Memory6' */ real32_T fieldWeakening; /* '<Root>/Data Store Memory9' */ /* Block signals (auto storage) */ BlockIO_SALTStabilizationInnerO SALTStabilizationInnerOuterLo_B; /* Block states (auto storage) */ D_Work_SALTStabilizationInnerOu SALTStabilizationInnerOut_DWork; /* Real-time model */ RT_MODEL_SALTStabilizationInner SALTStabilizationInnerOuterL_M_; RT_MODEL_SALTStabilizationInner *const SALTStabilizationInnerOuterL_M = &SALTStabilizationInnerOuterL_M_; /* * Output and update for atomic system: * '<Root>/Duty Cycles' * '<Root>/Duty Cycles1' */ void SALTStabilizationInn_DutyCycles(real32_T rtu_Va, real32_T rtu_Vb, real32_T rtu_Vc, rtB_DutyCycles_SALTStabilizatio *localB) { real32_T T; /* MATLAB Function 'Duty Cycles': '<S3>:1' */ /* '<S3>:1:5' */ if (rtu_Va >= 0.0F) { /* '<S3>:1:7' */ if (rtu_Vb >= 0.0F) { /* '<S3>:1:8' */ /* Sector 3, 0 - 60 Degrees */ /* '<S3>:1:13' */ T = rtu_Vb * 100.0F; /* '<S3>:1:14' */ /* '<S3>:1:16' */ /* '<S3>:1:17' */ /* '<S3>:1:19' */ localB->PWM1 = 0.0F; /* '<S3>:1:20' */ localB->PWM2 = T; /* '<S3>:1:21' */ localB->PWM3 = rtu_Va * 100.0F + T; /* '<S3>:1:22' */ localB->sector = 3.0F; } else if (rtu_Vc >= 0.0F) { /* '<S3>:1:24' */ /* Sector 5, 120 - 180 Degrees */ /* '<S3>:1:29' */ T = rtu_Va * 100.0F; /* '<S3>:1:30' */ /* '<S3>:1:32' */ /* '<S3>:1:33' */ /* '<S3>:1:35' */ localB->PWM1 = rtu_Vc * 100.0F + T; /* '<S3>:1:36' */ localB->PWM2 = 0.0F; /* '<S3>:1:37' */ localB->PWM3 = T; /* '<S3>:1:38' */ localB->sector = 5.0F; } else { /* Sector 1, 60 - 120 Degrees */ /* '<S3>:1:41' */ /* '<S3>:1:42' */ /* '<S3>:1:44' */ T = -rtu_Vb * 100.0F; /* '<S3>:1:45' */ /* '<S3>:1:47' */ /* '<S3>:1:48' */ /* '<S3>:1:50' */ localB->PWM1 = T; /* '<S3>:1:51' */ localB->PWM2 = 0.0F; /* '<S3>:1:52' */ localB->PWM3 = -rtu_Vc * 100.0F + T; /* '<S3>:1:53' */ localB->sector = 1.0F; } } else if (rtu_Vb >= 0.0F) { /* '<S3>:1:57' */ if (rtu_Vc >= 0.0F) { /* '<S3>:1:58' */ /* Sector 6, 240 - 300 Degrees */ /* '<S3>:1:63' */ T = rtu_Vc * 100.0F; /* '<S3>:1:64' */ /* '<S3>:1:66' */ /* '<S3>:1:67' */ /* '<S3>:1:69' */ localB->PWM1 = T; /* '<S3>:1:70' */ localB->PWM2 = rtu_Vb * 100.0F + T; /* '<S3>:1:71' */ localB->PWM3 = 0.0F; /* '<S3>:1:72' */ localB->sector = 6.0F; } else { /* Sector 2, 300 - 0 Degrees */ /* '<S3>:1:75' */ /* '<S3>:1:76' */ /* '<S3>:1:78' */ T = -rtu_Vc * 100.0F; /* '<S3>:1:79' */ /* '<S3>:1:81' */ /* '<S3>:1:82' */ /* '<S3>:1:84' */ localB->PWM1 = 0.0F; /* '<S3>:1:85' */ localB->PWM2 = -rtu_Va * 100.0F + T; /* '<S3>:1:86' */ localB->PWM3 = T; /* '<S3>:1:87' */ localB->sector = 2.0F; } } else { /* Sector 4, 180 - 240 Degrees */ /* '<S3>:1:91' */ /* '<S3>:1:92' */ /* '<S3>:1:94' */ T = -rtu_Va * 100.0F; /* '<S3>:1:95' */ /* '<S3>:1:97' */ /* '<S3>:1:98' */ /* '<S3>:1:100' */ localB->PWM1 = -rtu_Vb * 100.0F + T; /* '<S3>:1:101' */ localB->PWM2 = T; /* '<S3>:1:102' */ localB->PWM3 = 0.0F; /* '<S3>:1:103' */ localB->sector = 4.0F; } } /* * Output and update for atomic system: * '<S5>/MATLAB Function' * '<S6>/MATLAB Function' */ void SALTStabilizatio_MATLABFunction(real32_T rtu_u, rtB_MATLABFunction_SALTStabiliz *localB) { /* MATLAB Function 'Y Axis Inner Outer Loop1/MATLAB Function': '<S13>:1' */ /* '<S13>:1:4' */ localB->y = rtu_u / 131.0F * 0.0174532924F * 5.0F; } /* * Output and update for atomic system: * '<S5>/MATLAB Function1' * '<S5>/MATLAB Function2' * '<S6>/MATLAB Function1' * '<S6>/MATLAB Function2' */ void SALTStabilizati_MATLABFunction1(real32_T rtu_u, rtB_MATLABFunction1_SALTStabili *localB) { /* MATLAB Function 'Y Axis Inner Outer Loop1/MATLAB Function1': '<S14>:1' */ /* '<S14>:1:4' */ localB->y = rtu_u / 32.8F; } /* * Initial conditions for atomic system: * '<S16>/Embedded MATLAB Function' * '<S17>/Embedded MATLAB Function' * '<S23>/Embedded MATLAB Function' * '<S24>/Embedded MATLAB Function' */ void SAL_EmbeddedMATLABFunction_Init(rtDW_EmbeddedMATLABFunction_SAL *localDW) { localDW->a_not_empty = FALSE; } /* * Output and update for atomic system: * '<S16>/Embedded MATLAB Function' * '<S17>/Embedded MATLAB Function' * '<S23>/Embedded MATLAB Function' * '<S24>/Embedded MATLAB Function' */ void SALTStab_EmbeddedMATLABFunction(real32_T rtu_u, real_T rtu_T, real_T rtu_f, rtB_EmbeddedMATLABFunction_SALT *localB, rtDW_EmbeddedMATLABFunction_SAL *localDW) { real_T omega; /* MATLAB Function 'Y Axis Inner Outer Loop1/Tustin Lowpass, Auto Initial Condition/Embedded MATLAB Function': '<S18>:1' */ /* This block supports an embeddable subset of the MATLAB language. */ /* See the help menu for details. */ if (!localDW->a_not_empty) { /* '<S18>:1:9' */ /* tf = [T*omega/(2+T*omega) T*omega/(2+T*omega)],[1 (T*omega-2)/(T*omega+2)] */ /* tf = [a a],[1 -b] */ /* '<S18>:1:12' */ omega = 6.2831853071795862 * rtu_f; /* '<S18>:1:13' */ localDW->a = rtu_T * omega / (rtu_T * omega + 2.0); localDW->a_not_empty = TRUE; /* '<S18>:1:14' */ localDW->b = -(rtu_T * omega - 2.0) / (rtu_T * omega + 2.0); /* '<S18>:1:15' */ localDW->y_km1 = rtu_u; /* '<S18>:1:16' */ localDW->u_km1 = rtu_u; } /* '<S18>:1:19' */ localB->y = (rtu_u + localDW->u_km1) * (real32_T)localDW->a + (real32_T) localDW->b * localDW->y_km1; /* '<S18>:1:20' */ localDW->y_km1 = localB->y; /* '<S18>:1:21' */ localDW->u_km1 = rtu_u; } real32_T rt_atan2f_snf(real32_T u0, real32_T u1) { real32_T y; if (rtIsNaNF(u0) || rtIsNaNF(u1)) { y = (rtNaNF); } else if (rtIsInfF(u0) && rtIsInfF(u1)) { y = (real32_T)atan2(u0 > 0.0F ? 1.0F : -1.0F, u1 > 0.0F ? 1.0F : -1.0F); } else if (u1 == 0.0F) { if (u0 > 0.0F) { y = RT_PIF / 2.0F; } else if (u0 < 0.0F) { y = -(RT_PIF / 2.0F); } else { y = 0.0F; } } else { y = (real32_T)atan2(u0, u1); } return y; } /* Model step function */ void SALTStabilizationInnerOuterLoop_step(void) { /* local block i/o variables */ real_T rtb_AntiWindup; real_T rtb_AntiWindup_b; real32_T rtb_DataStoreRead7; real32_T rtb_Gain1_f; real32_T rtb_DataStoreRead8; real32_T rtb_DataStoreRead9; real32_T rtb_TrigonometricFunction; real32_T rtb_Gain[3]; real32_T rtb_DataStoreRead3; real32_T rtb_Gain1_j; real32_T rtb_DataStoreRead4; real32_T rtb_DataStoreRead5; real32_T rtb_TrigonometricFunction_c; real32_T rtb_Gain_m[3]; real_T sinOut; real32_T rtb_DataStoreRead1; real32_T rtb_Cy; real32_T rtb_Gain4_a; real_T rtb_Product3; real_T rtb_TrigonometricFunction_o1; real_T rtb_Add; real32_T DiscreteTimeIntegrator; real_T DiscreteTimeIntegrator_0; real32_T DiscreteTimeIntegrator_e; real_T DiscreteTimeIntegrator1_b; int16_T i; /* DataStoreRead: '<Root>/Data Store Read1' */ rtb_DataStoreRead1 = fieldWeakening; /* DataStoreRead: '<Root>/Data Store Read10' */ rtb_Cy = CommandedX; /* DataStoreRead: '<Root>/Data Store Read7' */ rtb_DataStoreRead7 = GyroX; /* MATLAB Function: '<S6>/MATLAB Function' */ SALTStabilizatio_MATLABFunction(rtb_DataStoreRead7, &SALTStabilizationInnerOuterLo_B.sf_MATLABFunction); /* Gain: '<S6>/Gain1' */ rtb_Gain1_f = SALTStabilizationInnerOuterLo_P.Gain1_Gain_b * SALTStabilizationInnerOuterLo_B.sf_MATLABFunction.y; /* MATLAB Function: '<S23>/Embedded MATLAB Function' */ SALTStab_EmbeddedMATLABFunction(rtb_Gain1_f, SALTStabilizationInnerOuterLo_P.Constant_Value, SALTStabilizationInnerOuterLo_P.Constant1_Value, &SALTStabilizationInnerOuterLo_B.sf_EmbeddedMATLABFunction, &SALTStabilizationInnerOut_DWork.sf_EmbeddedMATLABFunction); /* DiscreteIntegrator: '<S6>/Discrete-Time Integrator' */ if (SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator_SYSTEM_E != 0) { DiscreteTimeIntegrator = SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator_DSTATE; } else { DiscreteTimeIntegrator = SALTStabilizationInnerOuterLo_P.DiscreteTimeIntegrator_gainval * SALTStabilizationInnerOuterLo_B.sf_EmbeddedMATLABFunction.y + SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator_DSTATE; } /* End of DiscreteIntegrator: '<S6>/Discrete-Time Integrator' */ /* DataStoreRead: '<Root>/Data Store Read8' */ rtb_DataStoreRead8 = AccelY; /* MATLAB Function: '<S6>/MATLAB Function1' */ SALTStabilizati_MATLABFunction1(rtb_DataStoreRead8, &SALTStabilizationInnerOuterLo_B.sf_MATLABFunction1); /* Gain: '<S6>/Gain4' */ rtb_Gain4_a = SALTStabilizationInnerOuterLo_P.Gain4_Gain_b * SALTStabilizationInnerOuterLo_B.sf_MATLABFunction1.y; /* DataStoreRead: '<Root>/Data Store Read9' */ rtb_DataStoreRead9 = AccelZ; /* MATLAB Function: '<S6>/MATLAB Function2' */ SALTStabilizati_MATLABFunction1(rtb_DataStoreRead9, &SALTStabilizationInnerOuterLo_B.sf_MATLABFunction2); /* Trigonometry: '<S6>/Trigonometric Function' */ rtb_TrigonometricFunction = rt_atan2f_snf(rtb_Gain4_a, SALTStabilizationInnerOuterLo_B.sf_MATLABFunction2.y); /* MATLAB Function: '<S24>/Embedded MATLAB Function' */ SALTStab_EmbeddedMATLABFunction(rtb_TrigonometricFunction, SALTStabilizationInnerOuterLo_P.Constant_Value_p, SALTStabilizationInnerOuterLo_P.Constant1_Value_p, &SALTStabilizationInnerOuterLo_B.sf_EmbeddedMATLABFunction_k, &SALTStabilizationInnerOut_DWork.sf_EmbeddedMATLABFunction_k); /* Sum: '<S2>/Add4' incorporates: * Sum: '<S6>/Add' */ rtb_Gain4_a = (DiscreteTimeIntegrator + SALTStabilizationInnerOuterLo_B.sf_EmbeddedMATLABFunction_k.y) + rtb_Cy; /* Product: '<S12>/Product1' incorporates: * Constant: '<S2>/Kp 2' */ rtb_Product3 = (real_T)rtb_Gain4_a * SALTStabilizationInnerOuterLo_P.Kp2_Value; /* Product: '<S12>/Product3' incorporates: * Constant: '<S2>/Kp 1' */ rtb_TrigonometricFunction_o1 = (real_T) SALTStabilizationInnerOuterLo_B.sf_EmbeddedMATLABFunction.y * SALTStabilizationInnerOuterLo_P.Kp1_Value; /* Switch: '<S12>/AntiWindup' incorporates: * Abs: '<S12>/Abs' * Constant: '<S12>/Constant5' * Constant: '<S12>/SaturationLimit1' * Constant: '<S2>/Ki 2' * Gain: '<S12>/Gain' * Memory: '<S12>/Memory1' * Product: '<S12>/Product4' * RelationalOperator: '<S12>/Relational Operator' * Sum: '<S12>/Sum1' * Sum: '<S12>/Sum2' */ if (fabs(((real_T)(SALTStabilizationInnerOuterLo_P.Gain_Gain * rtb_Gain4_a) * SALTStabilizationInnerOuterLo_P.Ki2_Value + SALTStabilizationInnerOut_DWork.Memory1_PreviousInput) + (rtb_Product3 + rtb_TrigonometricFunction_o1)) < SALTStabilizationInnerOuterLo_P.SaturationLimit1_Value) { rtb_AntiWindup = rtb_Gain4_a; } else { rtb_AntiWindup = SALTStabilizationInnerOuterLo_P.Constant5_Value_j; } /* End of Switch: '<S12>/AntiWindup' */ /* DiscreteIntegrator: '<S12>/Discrete-Time Integrator1' */ if (SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator1_SYSTEM_ != 0) { DiscreteTimeIntegrator_0 = SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator1_DSTATE; } else { DiscreteTimeIntegrator_0 = SALTStabilizationInnerOuterLo_P.DiscreteTimeIntegrator1_gainval * rtb_AntiWindup + SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator1_DSTATE; } /* End of DiscreteIntegrator: '<S12>/Discrete-Time Integrator1' */ /* Sum: '<S12>/Add' incorporates: * Constant: '<S2>/Ki 2' * Product: '<S12>/Product' */ rtb_Add = (DiscreteTimeIntegrator_0 * SALTStabilizationInnerOuterLo_P.Ki2_Value + rtb_Product3) + rtb_TrigonometricFunction_o1; /* Gain: '<Root>/Gain1' incorporates: * Saturate: '<S12>/Saturation1' * Sum: '<S2>/Add8' */ rtb_Product3 = ((rtb_Add >= SALTStabilizationInnerOuterLo_P.Saturation1_UpperSat ? SALTStabilizationInnerOuterLo_P.Saturation1_UpperSat : rtb_Add <= SALTStabilizationInnerOuterLo_P.Saturation1_LowerSat ? SALTStabilizationInnerOuterLo_P.Saturation1_LowerSat : rtb_Add) + (real_T)rtb_Cy) * SALTStabilizationInnerOuterLo_P.Gain1_Gain; /* Trigonometry: '<Root>/Trigonometric Function1' */ sinOut = sin(rtb_Product3); rtb_Product3 = cos(rtb_Product3); /* SignalConversion: '<S8>/TmpSignal ConversionAtGainInport1' incorporates: * DataStoreRead: '<Root>/Data Store Read11' * Product: '<S28>/AxBx' * Product: '<S28>/AxBy' * Product: '<S28>/AyBx' * Product: '<S28>/AyBy' * Sum: '<S28>/sumx' * Sum: '<S28>/sumy' * Trigonometry: '<Root>/Trigonometric Function1' */ rtb_Cy = (real32_T)((real_T)rtb_DataStoreRead1 * rtb_Product3) - (real32_T) ((real_T)torqueInputX * sinOut); rtb_Gain4_a = (real32_T)((real_T)torqueInputX * rtb_Product3) + (real32_T) ((real_T)rtb_DataStoreRead1 * sinOut); /* Gain: '<S8>/Gain' */ for (i = 0; i < 3; i++) { rtb_Gain[i] = 0.0F; rtb_Gain[i] += SALTStabilizationInnerOuterLo_P.Gain_Gain_a[i] * rtb_Cy; rtb_Gain[i] += SALTStabilizationInnerOuterLo_P.Gain_Gain_a[i + 3] * rtb_Gain4_a; } /* End of Gain: '<S8>/Gain' */ /* MATLAB Function: '<Root>/Duty Cycles1' */ SALTStabilizationInn_DutyCycles(rtb_Gain[0], rtb_Gain[1], rtb_Gain[2], &SALTStabilizationInnerOuterLo_B.sf_DutyCycles1); /* DataStoreWrite: '<Root>/Data Store Write1' */ SALTStabilizationInnerOut_DWork.T4 = SALTStabilizationInnerOuterLo_B.sf_DutyCycles1.PWM3; /* DataStoreWrite: '<Root>/Data Store Write2' */ SALTStabilizationInnerOut_DWork.T6 = SALTStabilizationInnerOuterLo_B.sf_DutyCycles1.PWM2; /* DataStoreRead: '<Root>/Data Store Read6' */ rtb_Cy = CommandedY; /* DataStoreRead: '<Root>/Data Store Read3' */ rtb_DataStoreRead3 = GyroY; /* MATLAB Function: '<S5>/MATLAB Function' */ SALTStabilizatio_MATLABFunction(rtb_DataStoreRead3, &SALTStabilizationInnerOuterLo_B.sf_MATLABFunction_c); /* Gain: '<S5>/Gain1' */ rtb_Gain1_j = SALTStabilizationInnerOuterLo_P.Gain1_Gain_k * SALTStabilizationInnerOuterLo_B.sf_MATLABFunction_c.y; /* MATLAB Function: '<S16>/Embedded MATLAB Function' */ SALTStab_EmbeddedMATLABFunction(rtb_Gain1_j, SALTStabilizationInnerOuterLo_P.Constant_Value_f, SALTStabilizationInnerOuterLo_P.Constant1_Value_f, &SALTStabilizationInnerOuterLo_B.sf_EmbeddedMATLABFunction_e, &SALTStabilizationInnerOut_DWork.sf_EmbeddedMATLABFunction_e); /* DiscreteIntegrator: '<S5>/Discrete-Time Integrator' */ if (SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator_SYSTEM_c != 0) { DiscreteTimeIntegrator_e = SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator_DSTATE_f; } else { DiscreteTimeIntegrator_e = SALTStabilizationInnerOuterLo_P.DiscreteTimeIntegrator_gainva_e * SALTStabilizationInnerOuterLo_B.sf_EmbeddedMATLABFunction_e.y + SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator_DSTATE_f; } /* End of DiscreteIntegrator: '<S5>/Discrete-Time Integrator' */ /* DataStoreRead: '<Root>/Data Store Read4' */ rtb_DataStoreRead4 = AccelX; /* MATLAB Function: '<S5>/MATLAB Function1' */ SALTStabilizati_MATLABFunction1(rtb_DataStoreRead4, &SALTStabilizationInnerOuterLo_B.sf_MATLABFunction1_i); /* Gain: '<S5>/Gain4' */ rtb_Gain4_a = SALTStabilizationInnerOuterLo_P.Gain4_Gain_j * SALTStabilizationInnerOuterLo_B.sf_MATLABFunction1_i.y; /* DataStoreRead: '<Root>/Data Store Read5' */ rtb_DataStoreRead5 = AccelZ; /* MATLAB Function: '<S5>/MATLAB Function2' */ SALTStabilizati_MATLABFunction1(rtb_DataStoreRead5, &SALTStabilizationInnerOuterLo_B.sf_MATLABFunction2_j); /* Trigonometry: '<S5>/Trigonometric Function' */ rtb_TrigonometricFunction_c = rt_atan2f_snf(rtb_Gain4_a, SALTStabilizationInnerOuterLo_B.sf_MATLABFunction2_j.y); /* MATLAB Function: '<S17>/Embedded MATLAB Function' */ SALTStab_EmbeddedMATLABFunction(rtb_TrigonometricFunction_c, SALTStabilizationInnerOuterLo_P.Constant_Value_m, SALTStabilizationInnerOuterLo_P.Constant1_Value_k, &SALTStabilizationInnerOuterLo_B.sf_EmbeddedMATLABFunction_a, &SALTStabilizationInnerOut_DWork.sf_EmbeddedMATLABFunction_a); /* Sum: '<S1>/Add4' incorporates: * Sum: '<S5>/Add' */ rtb_Gain4_a = (DiscreteTimeIntegrator_e + SALTStabilizationInnerOuterLo_B.sf_EmbeddedMATLABFunction_a.y) + rtb_Cy; /* Product: '<S11>/Product1' incorporates: * Constant: '<S1>/Kp 2' */ rtb_TrigonometricFunction_o1 = (real_T)rtb_Gain4_a * SALTStabilizationInnerOuterLo_P.Kp2_Value_f; /* Product: '<S11>/Product3' incorporates: * Constant: '<S1>/Kp 1' */ rtb_Product3 = (real_T) SALTStabilizationInnerOuterLo_B.sf_EmbeddedMATLABFunction_e.y * SALTStabilizationInnerOuterLo_P.Kp1_Value_e; /* Switch: '<S11>/AntiWindup' incorporates: * Abs: '<S11>/Abs' * Constant: '<S11>/Constant5' * Constant: '<S11>/SaturationLimit1' * Constant: '<S1>/Ki 2' * Gain: '<S11>/Gain' * Memory: '<S11>/Memory1' * Product: '<S11>/Product4' * RelationalOperator: '<S11>/Relational Operator' * Sum: '<S11>/Sum1' * Sum: '<S11>/Sum2' */ if (fabs(((real_T)(SALTStabilizationInnerOuterLo_P.Gain_Gain_c * rtb_Gain4_a) * SALTStabilizationInnerOuterLo_P.Ki2_Value_b + SALTStabilizationInnerOut_DWork.Memory1_PreviousInput_g) + (rtb_TrigonometricFunction_o1 + rtb_Product3)) < SALTStabilizationInnerOuterLo_P.SaturationLimit1_Value_o) { rtb_AntiWindup_b = rtb_Gain4_a; } else { rtb_AntiWindup_b = SALTStabilizationInnerOuterLo_P.Constant5_Value; } /* End of Switch: '<S11>/AntiWindup' */ /* DiscreteIntegrator: '<S11>/Discrete-Time Integrator1' */ if (SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator1_SYSTE_o != 0) { DiscreteTimeIntegrator1_b = SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator1_DSTAT_o; } else { DiscreteTimeIntegrator1_b = SALTStabilizationInnerOuterLo_P.DiscreteTimeIntegrator1_gainv_g * rtb_AntiWindup_b + SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator1_DSTAT_o; } /* End of DiscreteIntegrator: '<S11>/Discrete-Time Integrator1' */ /* Sum: '<S11>/Add' incorporates: * Constant: '<S1>/Ki 2' * Product: '<S11>/Product' */ rtb_TrigonometricFunction_o1 = (DiscreteTimeIntegrator1_b * SALTStabilizationInnerOuterLo_P.Ki2_Value_b + rtb_TrigonometricFunction_o1) + rtb_Product3; /* Gain: '<Root>/Gain4' incorporates: * Saturate: '<S11>/Saturation1' * Sum: '<S1>/Add8' */ rtb_Product3 = ((rtb_TrigonometricFunction_o1 >= SALTStabilizationInnerOuterLo_P.Saturation1_UpperSat_j ? SALTStabilizationInnerOuterLo_P.Saturation1_UpperSat_j : rtb_TrigonometricFunction_o1 <= SALTStabilizationInnerOuterLo_P.Saturation1_LowerSat_c ? SALTStabilizationInnerOuterLo_P.Saturation1_LowerSat_c : rtb_TrigonometricFunction_o1) + (real_T)rtb_Cy) * SALTStabilizationInnerOuterLo_P.Gain4_Gain; /* Trigonometry: '<Root>/Trigonometric Function' */ sinOut = sin(rtb_Product3); rtb_Product3 = cos(rtb_Product3); /* SignalConversion: '<S7>/TmpSignal ConversionAtGainInport1' incorporates: * DataStoreRead: '<Root>/Data Store Read2' * Product: '<S27>/AxBx' * Product: '<S27>/AxBy' * Product: '<S27>/AyBx' * Product: '<S27>/AyBy' * Sum: '<S27>/sumx' * Sum: '<S27>/sumy' * Trigonometry: '<Root>/Trigonometric Function' */ rtb_Cy = (real32_T)((real_T)rtb_DataStoreRead1 * rtb_Product3) - (real32_T) ((real_T)torqueInputY * sinOut); rtb_Gain4_a = (real32_T)((real_T)torqueInputY * rtb_Product3) + (real32_T) ((real_T)rtb_DataStoreRead1 * sinOut); /* Gain: '<S7>/Gain' */ for (i = 0; i < 3; i++) { rtb_Gain_m[i] = 0.0F; rtb_Gain_m[i] += SALTStabilizationInnerOuterLo_P.Gain_Gain_cl[i] * rtb_Cy; rtb_Gain_m[i] += SALTStabilizationInnerOuterLo_P.Gain_Gain_cl[i + 3] * rtb_Gain4_a; } /* End of Gain: '<S7>/Gain' */ /* MATLAB Function: '<Root>/Duty Cycles' */ SALTStabilizationInn_DutyCycles(rtb_Gain_m[0], rtb_Gain_m[1], rtb_Gain_m[2], &SALTStabilizationInnerOuterLo_B.sf_DutyCycles); /* DataStoreWrite: '<Root>/Data Store Write3' */ SALTStabilizationInnerOut_DWork.T1 = SALTStabilizationInnerOuterLo_B.sf_DutyCycles.PWM3; /* DataStoreWrite: '<Root>/Data Store Write4' */ SALTStabilizationInnerOut_DWork.T5 = SALTStabilizationInnerOuterLo_B.sf_DutyCycles1.PWM1; /* DataStoreWrite: '<Root>/Data Store Write5' */ SALTStabilizationInnerOut_DWork.Sector2 = SALTStabilizationInnerOuterLo_B.sf_DutyCycles1.sector; /* DataStoreWrite: '<Root>/Data Store Write6' */ SALTStabilizationInnerOut_DWork.T3 = SALTStabilizationInnerOuterLo_B.sf_DutyCycles.PWM2; /* DataStoreWrite: '<Root>/Data Store Write7' */ SALTStabilizationInnerOut_DWork.T2 = SALTStabilizationInnerOuterLo_B.sf_DutyCycles.PWM1; /* DataStoreWrite: '<Root>/Data Store Write8' */ SALTStabilizationInnerOut_DWork.Sector = SALTStabilizationInnerOuterLo_B.sf_DutyCycles.sector; /* Update for DiscreteIntegrator: '<S6>/Discrete-Time Integrator' */ SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator_SYSTEM_E = 0U; SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator_DSTATE = SALTStabilizationInnerOuterLo_P.DiscreteTimeIntegrator_gainval * SALTStabilizationInnerOuterLo_B.sf_EmbeddedMATLABFunction.y + DiscreteTimeIntegrator; /* Update for Memory: '<S12>/Memory1' */ SALTStabilizationInnerOut_DWork.Memory1_PreviousInput = rtb_Add; /* Update for DiscreteIntegrator: '<S12>/Discrete-Time Integrator1' */ SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator1_SYSTEM_ = 0U; SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator1_DSTATE = SALTStabilizationInnerOuterLo_P.DiscreteTimeIntegrator1_gainval * rtb_AntiWindup + DiscreteTimeIntegrator_0; /* Update for DiscreteIntegrator: '<S5>/Discrete-Time Integrator' */ SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator_SYSTEM_c = 0U; SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator_DSTATE_f = SALTStabilizationInnerOuterLo_P.DiscreteTimeIntegrator_gainva_e * SALTStabilizationInnerOuterLo_B.sf_EmbeddedMATLABFunction_e.y + DiscreteTimeIntegrator_e; /* Update for Memory: '<S11>/Memory1' */ SALTStabilizationInnerOut_DWork.Memory1_PreviousInput_g = rtb_TrigonometricFunction_o1; /* Update for DiscreteIntegrator: '<S11>/Discrete-Time Integrator1' */ SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator1_SYSTE_o = 0U; SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator1_DSTAT_o = SALTStabilizationInnerOuterLo_P.DiscreteTimeIntegrator1_gainv_g * rtb_AntiWindup_b + DiscreteTimeIntegrator1_b; } /* Model initialize function */ void SALTStabilizationInnerOuterLoop_initialize(void) { /* Registration code */ /* initialize non-finites */ rt_InitInfAndNaN(sizeof(real_T)); /* initialize error status */ rtmSetErrorStatus(SALTStabilizationInnerOuterL_M, (NULL)); /* block I/O */ (void) memset(((void *) &SALTStabilizationInnerOuterLo_B), 0, sizeof(BlockIO_SALTStabilizationInnerO)); /* states (dwork) */ (void) memset((void *)&SALTStabilizationInnerOut_DWork, 0, sizeof(D_Work_SALTStabilizationInnerOu)); /* exported global states */ commandedAngle = 0.0F; torqueInputX = 0.0F; AccelX = 0.0F; GyroX = 0.0F; AccelZ = 0.0F; GyroZ = 0.0F; CommandedY = 0.0F; AccelY = 0.0F; CommandedX = 0.0F; torqueInputY = 0.0F; GyroY = 0.0F; fieldWeakening = 0.0F; /* Start for DataStoreMemory: '<Root>/Data Store Memory' */ commandedAngle = SALTStabilizationInnerOuterLo_P.DataStoreMemory_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory1' */ SALTStabilizationInnerOut_DWork.T3 = SALTStabilizationInnerOuterLo_P.DataStoreMemory1_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory10' */ SALTStabilizationInnerOut_DWork.Sector = SALTStabilizationInnerOuterLo_P.DataStoreMemory10_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory11' */ torqueInputX = SALTStabilizationInnerOuterLo_P.DataStoreMemory11_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory12' */ AccelX = SALTStabilizationInnerOuterLo_P.DataStoreMemory12_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory13' */ GyroX = SALTStabilizationInnerOuterLo_P.DataStoreMemory13_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory14' */ AccelZ = SALTStabilizationInnerOuterLo_P.DataStoreMemory14_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory15' */ GyroZ = SALTStabilizationInnerOuterLo_P.DataStoreMemory15_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory16' */ CommandedY = SALTStabilizationInnerOuterLo_P.DataStoreMemory16_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory17' */ AccelY = SALTStabilizationInnerOuterLo_P.DataStoreMemory17_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory18' */ CommandedX = SALTStabilizationInnerOuterLo_P.DataStoreMemory18_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory19' */ torqueInputY = SALTStabilizationInnerOuterLo_P.DataStoreMemory19_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory2' */ SALTStabilizationInnerOut_DWork.T6 = SALTStabilizationInnerOuterLo_P.DataStoreMemory2_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory3' */ SALTStabilizationInnerOut_DWork.Sector2 = SALTStabilizationInnerOuterLo_P.DataStoreMemory3_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory4' */ SALTStabilizationInnerOut_DWork.T4 = SALTStabilizationInnerOuterLo_P.DataStoreMemory4_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory5' */ SALTStabilizationInnerOut_DWork.T5 = SALTStabilizationInnerOuterLo_P.DataStoreMemory5_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory6' */ GyroY = SALTStabilizationInnerOuterLo_P.DataStoreMemory6_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory7' */ SALTStabilizationInnerOut_DWork.T1 = SALTStabilizationInnerOuterLo_P.DataStoreMemory7_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory8' */ SALTStabilizationInnerOut_DWork.T2 = SALTStabilizationInnerOuterLo_P.DataStoreMemory8_InitialValue; /* Start for DataStoreMemory: '<Root>/Data Store Memory9' */ fieldWeakening = SALTStabilizationInnerOuterLo_P.DataStoreMemory9_InitialValue; /* InitializeConditions for MATLAB Function: '<S23>/Embedded MATLAB Function' */ SAL_EmbeddedMATLABFunction_Init (&SALTStabilizationInnerOut_DWork.sf_EmbeddedMATLABFunction); /* InitializeConditions for DiscreteIntegrator: '<S6>/Discrete-Time Integrator' */ SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator_DSTATE = SALTStabilizationInnerOuterLo_P.DiscreteTimeIntegrator_IC; /* InitializeConditions for MATLAB Function: '<S24>/Embedded MATLAB Function' */ SAL_EmbeddedMATLABFunction_Init (&SALTStabilizationInnerOut_DWork.sf_EmbeddedMATLABFunction_k); /* InitializeConditions for Memory: '<S12>/Memory1' */ SALTStabilizationInnerOut_DWork.Memory1_PreviousInput = SALTStabilizationInnerOuterLo_P.Memory1_X0; /* InitializeConditions for DiscreteIntegrator: '<S12>/Discrete-Time Integrator1' */ SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator1_DSTATE = SALTStabilizationInnerOuterLo_P.DiscreteTimeIntegrator1_IC; /* InitializeConditions for MATLAB Function: '<S16>/Embedded MATLAB Function' */ SAL_EmbeddedMATLABFunction_Init (&SALTStabilizationInnerOut_DWork.sf_EmbeddedMATLABFunction_e); /* InitializeConditions for DiscreteIntegrator: '<S5>/Discrete-Time Integrator' */ SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator_DSTATE_f = SALTStabilizationInnerOuterLo_P.DiscreteTimeIntegrator_IC_a; /* InitializeConditions for MATLAB Function: '<S17>/Embedded MATLAB Function' */ SAL_EmbeddedMATLABFunction_Init (&SALTStabilizationInnerOut_DWork.sf_EmbeddedMATLABFunction_a); /* InitializeConditions for Memory: '<S11>/Memory1' */ SALTStabilizationInnerOut_DWork.Memory1_PreviousInput_g = SALTStabilizationInnerOuterLo_P.Memory1_X0_k; /* InitializeConditions for DiscreteIntegrator: '<S11>/Discrete-Time Integrator1' */ SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator1_DSTAT_o = SALTStabilizationInnerOuterLo_P.DiscreteTimeIntegrator1_IC_g; /* Enable for DiscreteIntegrator: '<S6>/Discrete-Time Integrator' */ SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator_SYSTEM_E = 1U; /* Enable for DiscreteIntegrator: '<S12>/Discrete-Time Integrator1' */ SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator1_SYSTEM_ = 1U; /* Enable for DiscreteIntegrator: '<S5>/Discrete-Time Integrator' */ SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator_SYSTEM_c = 1U; /* Enable for DiscreteIntegrator: '<S11>/Discrete-Time Integrator1' */ SALTStabilizationInnerOut_DWork.DiscreteTimeIntegrator1_SYSTE_o = 1U; } /* Model terminate function */ void SALTStabilizationInnerOuterLoop_terminate(void) { /* (no terminate code required) */ } /* * File trailer for generated code. * * [EOF] */
34.50933
125
0.695591
[ "model" ]
45b817b01eea57ff18e12aa0525db72edb7e4d13
23,783
h
C
aws-cpp-sdk-gamelift/include/aws/gamelift/model/ScalingPolicy.h
ambasta/aws-sdk-cpp
c81192e00b572b76d175d84dff77185bd17ae1ac
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-gamelift/include/aws/gamelift/model/ScalingPolicy.h
ambasta/aws-sdk-cpp
c81192e00b572b76d175d84dff77185bd17ae1ac
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-gamelift/include/aws/gamelift/model/ScalingPolicy.h
ambasta/aws-sdk-cpp
c81192e00b572b76d175d84dff77185bd17ae1ac
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2016 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/gamelift/GameLift_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/gamelift/model/ScalingStatusType.h> #include <aws/gamelift/model/ScalingAdjustmentType.h> #include <aws/gamelift/model/ComparisonOperatorType.h> #include <aws/gamelift/model/MetricName.h> namespace Aws { namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace GameLift { namespace Model { /** * <p>Rule that controls how a fleet is scaled. Scaling policies are uniquely * identified by the combination of name and fleet ID.</p> */ class AWS_GAMELIFT_API ScalingPolicy { public: ScalingPolicy(); ScalingPolicy(const Aws::Utils::Json::JsonValue& jsonValue); ScalingPolicy& operator=(const Aws::Utils::Json::JsonValue& jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>Unique identity for the fleet associated with this scaling policy.</p> */ inline const Aws::String& GetFleetId() const{ return m_fleetId; } /** * <p>Unique identity for the fleet associated with this scaling policy.</p> */ inline void SetFleetId(const Aws::String& value) { m_fleetIdHasBeenSet = true; m_fleetId = value; } /** * <p>Unique identity for the fleet associated with this scaling policy.</p> */ inline void SetFleetId(Aws::String&& value) { m_fleetIdHasBeenSet = true; m_fleetId = value; } /** * <p>Unique identity for the fleet associated with this scaling policy.</p> */ inline void SetFleetId(const char* value) { m_fleetIdHasBeenSet = true; m_fleetId.assign(value); } /** * <p>Unique identity for the fleet associated with this scaling policy.</p> */ inline ScalingPolicy& WithFleetId(const Aws::String& value) { SetFleetId(value); return *this;} /** * <p>Unique identity for the fleet associated with this scaling policy.</p> */ inline ScalingPolicy& WithFleetId(Aws::String&& value) { SetFleetId(value); return *this;} /** * <p>Unique identity for the fleet associated with this scaling policy.</p> */ inline ScalingPolicy& WithFleetId(const char* value) { SetFleetId(value); return *this;} /** * <p>Descriptive label associated with a scaling policy. Policy names do not need * to be unique.</p> */ inline const Aws::String& GetName() const{ return m_name; } /** * <p>Descriptive label associated with a scaling policy. Policy names do not need * to be unique.</p> */ inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p>Descriptive label associated with a scaling policy. Policy names do not need * to be unique.</p> */ inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p>Descriptive label associated with a scaling policy. Policy names do not need * to be unique.</p> */ inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); } /** * <p>Descriptive label associated with a scaling policy. Policy names do not need * to be unique.</p> */ inline ScalingPolicy& WithName(const Aws::String& value) { SetName(value); return *this;} /** * <p>Descriptive label associated with a scaling policy. Policy names do not need * to be unique.</p> */ inline ScalingPolicy& WithName(Aws::String&& value) { SetName(value); return *this;} /** * <p>Descriptive label associated with a scaling policy. Policy names do not need * to be unique.</p> */ inline ScalingPolicy& WithName(const char* value) { SetName(value); return *this;} /** * <p>Current status of the scaling policy. The scaling policy is only in force * when in an <code>ACTIVE</code> status.</p> <ul> <li> <p> <b>ACTIVE</b> – The * scaling policy is currently in force.</p> </li> <li> <p> <b>UPDATE_REQUESTED</b> * – A request to update the scaling policy has been received.</p> </li> <li> <p> * <b>UPDATING</b> – A change is being made to the scaling policy.</p> </li> <li> * <p> <b>DELETE_REQUESTED</b> – A request to delete the scaling policy has been * received.</p> </li> <li> <p> <b>DELETING</b> – The scaling policy is being * deleted.</p> </li> <li> <p> <b>DELETED</b> – The scaling policy has been * deleted.</p> </li> <li> <p> <b>ERROR</b> – An error occurred in creating the * policy. It should be removed and recreated.</p> </li> </ul> */ inline const ScalingStatusType& GetStatus() const{ return m_status; } /** * <p>Current status of the scaling policy. The scaling policy is only in force * when in an <code>ACTIVE</code> status.</p> <ul> <li> <p> <b>ACTIVE</b> – The * scaling policy is currently in force.</p> </li> <li> <p> <b>UPDATE_REQUESTED</b> * – A request to update the scaling policy has been received.</p> </li> <li> <p> * <b>UPDATING</b> – A change is being made to the scaling policy.</p> </li> <li> * <p> <b>DELETE_REQUESTED</b> – A request to delete the scaling policy has been * received.</p> </li> <li> <p> <b>DELETING</b> – The scaling policy is being * deleted.</p> </li> <li> <p> <b>DELETED</b> – The scaling policy has been * deleted.</p> </li> <li> <p> <b>ERROR</b> – An error occurred in creating the * policy. It should be removed and recreated.</p> </li> </ul> */ inline void SetStatus(const ScalingStatusType& value) { m_statusHasBeenSet = true; m_status = value; } /** * <p>Current status of the scaling policy. The scaling policy is only in force * when in an <code>ACTIVE</code> status.</p> <ul> <li> <p> <b>ACTIVE</b> – The * scaling policy is currently in force.</p> </li> <li> <p> <b>UPDATE_REQUESTED</b> * – A request to update the scaling policy has been received.</p> </li> <li> <p> * <b>UPDATING</b> – A change is being made to the scaling policy.</p> </li> <li> * <p> <b>DELETE_REQUESTED</b> – A request to delete the scaling policy has been * received.</p> </li> <li> <p> <b>DELETING</b> – The scaling policy is being * deleted.</p> </li> <li> <p> <b>DELETED</b> – The scaling policy has been * deleted.</p> </li> <li> <p> <b>ERROR</b> – An error occurred in creating the * policy. It should be removed and recreated.</p> </li> </ul> */ inline void SetStatus(ScalingStatusType&& value) { m_statusHasBeenSet = true; m_status = value; } /** * <p>Current status of the scaling policy. The scaling policy is only in force * when in an <code>ACTIVE</code> status.</p> <ul> <li> <p> <b>ACTIVE</b> – The * scaling policy is currently in force.</p> </li> <li> <p> <b>UPDATE_REQUESTED</b> * – A request to update the scaling policy has been received.</p> </li> <li> <p> * <b>UPDATING</b> – A change is being made to the scaling policy.</p> </li> <li> * <p> <b>DELETE_REQUESTED</b> – A request to delete the scaling policy has been * received.</p> </li> <li> <p> <b>DELETING</b> – The scaling policy is being * deleted.</p> </li> <li> <p> <b>DELETED</b> – The scaling policy has been * deleted.</p> </li> <li> <p> <b>ERROR</b> – An error occurred in creating the * policy. It should be removed and recreated.</p> </li> </ul> */ inline ScalingPolicy& WithStatus(const ScalingStatusType& value) { SetStatus(value); return *this;} /** * <p>Current status of the scaling policy. The scaling policy is only in force * when in an <code>ACTIVE</code> status.</p> <ul> <li> <p> <b>ACTIVE</b> – The * scaling policy is currently in force.</p> </li> <li> <p> <b>UPDATE_REQUESTED</b> * – A request to update the scaling policy has been received.</p> </li> <li> <p> * <b>UPDATING</b> – A change is being made to the scaling policy.</p> </li> <li> * <p> <b>DELETE_REQUESTED</b> – A request to delete the scaling policy has been * received.</p> </li> <li> <p> <b>DELETING</b> – The scaling policy is being * deleted.</p> </li> <li> <p> <b>DELETED</b> – The scaling policy has been * deleted.</p> </li> <li> <p> <b>ERROR</b> – An error occurred in creating the * policy. It should be removed and recreated.</p> </li> </ul> */ inline ScalingPolicy& WithStatus(ScalingStatusType&& value) { SetStatus(value); return *this;} /** * <p>Amount of adjustment to make, based on the scaling adjustment type.</p> */ inline int GetScalingAdjustment() const{ return m_scalingAdjustment; } /** * <p>Amount of adjustment to make, based on the scaling adjustment type.</p> */ inline void SetScalingAdjustment(int value) { m_scalingAdjustmentHasBeenSet = true; m_scalingAdjustment = value; } /** * <p>Amount of adjustment to make, based on the scaling adjustment type.</p> */ inline ScalingPolicy& WithScalingAdjustment(int value) { SetScalingAdjustment(value); return *this;} /** * <p>Type of adjustment to make to a fleet's instance count (see * <a>FleetCapacity</a>):</p> <ul> <li> <p> <b>ChangeInCapacity</b> – add (or * subtract) the scaling adjustment value from the current instance count. Positive * values scale up while negative values scale down.</p> </li> <li> <p> * <b>ExactCapacity</b> – set the instance count to the scaling adjustment * value.</p> </li> <li> <p> <b>PercentChangeInCapacity</b> – increase or reduce * the current instance count by the scaling adjustment, read as a percentage. * Positive values scale up while negative values scale down.</p> </li> </ul> */ inline const ScalingAdjustmentType& GetScalingAdjustmentType() const{ return m_scalingAdjustmentType; } /** * <p>Type of adjustment to make to a fleet's instance count (see * <a>FleetCapacity</a>):</p> <ul> <li> <p> <b>ChangeInCapacity</b> – add (or * subtract) the scaling adjustment value from the current instance count. Positive * values scale up while negative values scale down.</p> </li> <li> <p> * <b>ExactCapacity</b> – set the instance count to the scaling adjustment * value.</p> </li> <li> <p> <b>PercentChangeInCapacity</b> – increase or reduce * the current instance count by the scaling adjustment, read as a percentage. * Positive values scale up while negative values scale down.</p> </li> </ul> */ inline void SetScalingAdjustmentType(const ScalingAdjustmentType& value) { m_scalingAdjustmentTypeHasBeenSet = true; m_scalingAdjustmentType = value; } /** * <p>Type of adjustment to make to a fleet's instance count (see * <a>FleetCapacity</a>):</p> <ul> <li> <p> <b>ChangeInCapacity</b> – add (or * subtract) the scaling adjustment value from the current instance count. Positive * values scale up while negative values scale down.</p> </li> <li> <p> * <b>ExactCapacity</b> – set the instance count to the scaling adjustment * value.</p> </li> <li> <p> <b>PercentChangeInCapacity</b> – increase or reduce * the current instance count by the scaling adjustment, read as a percentage. * Positive values scale up while negative values scale down.</p> </li> </ul> */ inline void SetScalingAdjustmentType(ScalingAdjustmentType&& value) { m_scalingAdjustmentTypeHasBeenSet = true; m_scalingAdjustmentType = value; } /** * <p>Type of adjustment to make to a fleet's instance count (see * <a>FleetCapacity</a>):</p> <ul> <li> <p> <b>ChangeInCapacity</b> – add (or * subtract) the scaling adjustment value from the current instance count. Positive * values scale up while negative values scale down.</p> </li> <li> <p> * <b>ExactCapacity</b> – set the instance count to the scaling adjustment * value.</p> </li> <li> <p> <b>PercentChangeInCapacity</b> – increase or reduce * the current instance count by the scaling adjustment, read as a percentage. * Positive values scale up while negative values scale down.</p> </li> </ul> */ inline ScalingPolicy& WithScalingAdjustmentType(const ScalingAdjustmentType& value) { SetScalingAdjustmentType(value); return *this;} /** * <p>Type of adjustment to make to a fleet's instance count (see * <a>FleetCapacity</a>):</p> <ul> <li> <p> <b>ChangeInCapacity</b> – add (or * subtract) the scaling adjustment value from the current instance count. Positive * values scale up while negative values scale down.</p> </li> <li> <p> * <b>ExactCapacity</b> – set the instance count to the scaling adjustment * value.</p> </li> <li> <p> <b>PercentChangeInCapacity</b> – increase or reduce * the current instance count by the scaling adjustment, read as a percentage. * Positive values scale up while negative values scale down.</p> </li> </ul> */ inline ScalingPolicy& WithScalingAdjustmentType(ScalingAdjustmentType&& value) { SetScalingAdjustmentType(value); return *this;} /** * <p>Comparison operator to use when measuring a metric against the threshold * value.</p> */ inline const ComparisonOperatorType& GetComparisonOperator() const{ return m_comparisonOperator; } /** * <p>Comparison operator to use when measuring a metric against the threshold * value.</p> */ inline void SetComparisonOperator(const ComparisonOperatorType& value) { m_comparisonOperatorHasBeenSet = true; m_comparisonOperator = value; } /** * <p>Comparison operator to use when measuring a metric against the threshold * value.</p> */ inline void SetComparisonOperator(ComparisonOperatorType&& value) { m_comparisonOperatorHasBeenSet = true; m_comparisonOperator = value; } /** * <p>Comparison operator to use when measuring a metric against the threshold * value.</p> */ inline ScalingPolicy& WithComparisonOperator(const ComparisonOperatorType& value) { SetComparisonOperator(value); return *this;} /** * <p>Comparison operator to use when measuring a metric against the threshold * value.</p> */ inline ScalingPolicy& WithComparisonOperator(ComparisonOperatorType&& value) { SetComparisonOperator(value); return *this;} /** * <p>Metric value used to trigger a scaling event.</p> */ inline double GetThreshold() const{ return m_threshold; } /** * <p>Metric value used to trigger a scaling event.</p> */ inline void SetThreshold(double value) { m_thresholdHasBeenSet = true; m_threshold = value; } /** * <p>Metric value used to trigger a scaling event.</p> */ inline ScalingPolicy& WithThreshold(double value) { SetThreshold(value); return *this;} /** * <p>Length of time (in minutes) the metric must be at or beyond the threshold * before a scaling event is triggered.</p> */ inline int GetEvaluationPeriods() const{ return m_evaluationPeriods; } /** * <p>Length of time (in minutes) the metric must be at or beyond the threshold * before a scaling event is triggered.</p> */ inline void SetEvaluationPeriods(int value) { m_evaluationPeriodsHasBeenSet = true; m_evaluationPeriods = value; } /** * <p>Length of time (in minutes) the metric must be at or beyond the threshold * before a scaling event is triggered.</p> */ inline ScalingPolicy& WithEvaluationPeriods(int value) { SetEvaluationPeriods(value); return *this;} /** * <p>Name of the GameLift-defined metric that is used to trigger an * adjustment.</p> <ul> <li> <p> <b>ActivatingGameSessions</b> – number of game * sessions in the process of being created (game session status = * <code>ACTIVATING</code>).</p> </li> <li> <p> <b>ActiveGameSessions</b> – number * of game sessions currently running (game session status = * <code>ACTIVE</code>).</p> </li> <li> <p> <b>CurrentPlayerSessions</b> – number * of active or reserved player sessions (player session status = * <code>ACTIVE</code> or <code>RESERVED</code>). </p> </li> <li> <p> * <b>AvailablePlayerSessions</b> – number of player session slots currently * available in active game sessions across the fleet, calculated by subtracting a * game session's current player session count from its maximum player session * count. This number does include game sessions that are not currently accepting * players (game session <code>PlayerSessionCreationPolicy</code> = * <code>DENY_ALL</code>).</p> </li> <li> <p> <b>ActiveInstances</b> – number of * instances currently running a game session.</p> </li> <li> <p> * <b>IdleInstances</b> – number of instances not currently running a game * session.</p> </li> </ul> */ inline const MetricName& GetMetricName() const{ return m_metricName; } /** * <p>Name of the GameLift-defined metric that is used to trigger an * adjustment.</p> <ul> <li> <p> <b>ActivatingGameSessions</b> – number of game * sessions in the process of being created (game session status = * <code>ACTIVATING</code>).</p> </li> <li> <p> <b>ActiveGameSessions</b> – number * of game sessions currently running (game session status = * <code>ACTIVE</code>).</p> </li> <li> <p> <b>CurrentPlayerSessions</b> – number * of active or reserved player sessions (player session status = * <code>ACTIVE</code> or <code>RESERVED</code>). </p> </li> <li> <p> * <b>AvailablePlayerSessions</b> – number of player session slots currently * available in active game sessions across the fleet, calculated by subtracting a * game session's current player session count from its maximum player session * count. This number does include game sessions that are not currently accepting * players (game session <code>PlayerSessionCreationPolicy</code> = * <code>DENY_ALL</code>).</p> </li> <li> <p> <b>ActiveInstances</b> – number of * instances currently running a game session.</p> </li> <li> <p> * <b>IdleInstances</b> – number of instances not currently running a game * session.</p> </li> </ul> */ inline void SetMetricName(const MetricName& value) { m_metricNameHasBeenSet = true; m_metricName = value; } /** * <p>Name of the GameLift-defined metric that is used to trigger an * adjustment.</p> <ul> <li> <p> <b>ActivatingGameSessions</b> – number of game * sessions in the process of being created (game session status = * <code>ACTIVATING</code>).</p> </li> <li> <p> <b>ActiveGameSessions</b> – number * of game sessions currently running (game session status = * <code>ACTIVE</code>).</p> </li> <li> <p> <b>CurrentPlayerSessions</b> – number * of active or reserved player sessions (player session status = * <code>ACTIVE</code> or <code>RESERVED</code>). </p> </li> <li> <p> * <b>AvailablePlayerSessions</b> – number of player session slots currently * available in active game sessions across the fleet, calculated by subtracting a * game session's current player session count from its maximum player session * count. This number does include game sessions that are not currently accepting * players (game session <code>PlayerSessionCreationPolicy</code> = * <code>DENY_ALL</code>).</p> </li> <li> <p> <b>ActiveInstances</b> – number of * instances currently running a game session.</p> </li> <li> <p> * <b>IdleInstances</b> – number of instances not currently running a game * session.</p> </li> </ul> */ inline void SetMetricName(MetricName&& value) { m_metricNameHasBeenSet = true; m_metricName = value; } /** * <p>Name of the GameLift-defined metric that is used to trigger an * adjustment.</p> <ul> <li> <p> <b>ActivatingGameSessions</b> – number of game * sessions in the process of being created (game session status = * <code>ACTIVATING</code>).</p> </li> <li> <p> <b>ActiveGameSessions</b> – number * of game sessions currently running (game session status = * <code>ACTIVE</code>).</p> </li> <li> <p> <b>CurrentPlayerSessions</b> – number * of active or reserved player sessions (player session status = * <code>ACTIVE</code> or <code>RESERVED</code>). </p> </li> <li> <p> * <b>AvailablePlayerSessions</b> – number of player session slots currently * available in active game sessions across the fleet, calculated by subtracting a * game session's current player session count from its maximum player session * count. This number does include game sessions that are not currently accepting * players (game session <code>PlayerSessionCreationPolicy</code> = * <code>DENY_ALL</code>).</p> </li> <li> <p> <b>ActiveInstances</b> – number of * instances currently running a game session.</p> </li> <li> <p> * <b>IdleInstances</b> – number of instances not currently running a game * session.</p> </li> </ul> */ inline ScalingPolicy& WithMetricName(const MetricName& value) { SetMetricName(value); return *this;} /** * <p>Name of the GameLift-defined metric that is used to trigger an * adjustment.</p> <ul> <li> <p> <b>ActivatingGameSessions</b> – number of game * sessions in the process of being created (game session status = * <code>ACTIVATING</code>).</p> </li> <li> <p> <b>ActiveGameSessions</b> – number * of game sessions currently running (game session status = * <code>ACTIVE</code>).</p> </li> <li> <p> <b>CurrentPlayerSessions</b> – number * of active or reserved player sessions (player session status = * <code>ACTIVE</code> or <code>RESERVED</code>). </p> </li> <li> <p> * <b>AvailablePlayerSessions</b> – number of player session slots currently * available in active game sessions across the fleet, calculated by subtracting a * game session's current player session count from its maximum player session * count. This number does include game sessions that are not currently accepting * players (game session <code>PlayerSessionCreationPolicy</code> = * <code>DENY_ALL</code>).</p> </li> <li> <p> <b>ActiveInstances</b> – number of * instances currently running a game session.</p> </li> <li> <p> * <b>IdleInstances</b> – number of instances not currently running a game * session.</p> </li> </ul> */ inline ScalingPolicy& WithMetricName(MetricName&& value) { SetMetricName(value); return *this;} private: Aws::String m_fleetId; bool m_fleetIdHasBeenSet; Aws::String m_name; bool m_nameHasBeenSet; ScalingStatusType m_status; bool m_statusHasBeenSet; int m_scalingAdjustment; bool m_scalingAdjustmentHasBeenSet; ScalingAdjustmentType m_scalingAdjustmentType; bool m_scalingAdjustmentTypeHasBeenSet; ComparisonOperatorType m_comparisonOperator; bool m_comparisonOperatorHasBeenSet; double m_threshold; bool m_thresholdHasBeenSet; int m_evaluationPeriods; bool m_evaluationPeriodsHasBeenSet; MetricName m_metricName; bool m_metricNameHasBeenSet; }; } // namespace Model } // namespace GameLift } // namespace Aws
51.367171
155
0.666527
[ "model" ]
45bc02043766410823ce1c77486b93f63a82db6d
2,150
h
C
inc/BootPIC18NonJ.h
bitgamma/palitra-bootloader
4203e48e6e13132c12c8202d6cf7d90a523c4676
[ "Apache-2.0" ]
null
null
null
inc/BootPIC18NonJ.h
bitgamma/palitra-bootloader
4203e48e6e13132c12c8202d6cf7d90a523c4676
[ "Apache-2.0" ]
null
null
null
inc/BootPIC18NonJ.h
bitgamma/palitra-bootloader
4203e48e6e13132c12c8202d6cf7d90a523c4676
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* Copyright 2016 Microchip Technology Inc. (www.microchip.com) 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. To request to license the code under the MLA license (www.microchip.com/mla_license), please contact mla_licensing@microchip.com *******************************************************************************/ #ifndef BOOTPIC18NONJ_H #define BOOTPIC18NONJ_H /** P U B L I C P R O T O T Y P E S *****************************************/ void UserInit(void); void ProcessIO(void); void ClearWatchdog(void); void DisableUSBandExecuteLongDelay(void); //Vector remapping/absolute address constants #define REMAPPED_APPLICATION_RESET_VECTOR 0x1000 //#define REMAPPED_APPLICATION_HIGH_ISR_VECTOR 0x1008 //See VectorRemap.asm //#define REMAPPED_APPLICATION_LOW_ISR_VECTOR 0x1018 //See VectorRemap.asm #define BOOTLOADER_ABSOLUTE_ENTRY_ADDRESS 0x001C //Execute a "goto 0x001C" inline assembly instruction, if you want to enter the bootloader mode from the application via software #define APP_SIGNATURE_ADDRESS 0x1006 //0x1006 and 0x1007 contains the "signature" WORD, indicating successful erase/program/verify operation #define APP_SIGNATURE_VALUE 0x600D //leet "GOOD", implying that the erase/program was a success and the bootloader intentionally programmed the APP_SIGNATURE_ADDRESS with this value #define APP_VERSION_ADDRESS 0x1016 //0x1016 and 0x1017 should contain the application image firmware version number #endif //BOOTPIC18NONJ_H
51.190476
203
0.686512
[ "vector" ]
45c06f02dd1dc3f05c96172ddf493416152d8525
2,220
h
C
src/game/etj_custom_map_votes.h
Aciz/etjump
6215e86cf9aeef504dc4eb24a57ecdc797cb7a2e
[ "BSL-1.0", "MIT" ]
16
2019-09-07T18:08:08.000Z
2022-03-04T21:37:06.000Z
src/game/etj_custom_map_votes.h
Aciz/etjump
6215e86cf9aeef504dc4eb24a57ecdc797cb7a2e
[ "BSL-1.0", "MIT" ]
121
2019-09-07T19:30:39.000Z
2022-01-31T20:59:48.000Z
src/game/etj_custom_map_votes.h
etjump/etjump
8dcc3ca939e95063e630367d98cac7ffeec6d88c
[ "BSL-1.0", "MIT" ]
14
2019-09-07T17:20:40.000Z
2022-01-30T06:47:15.000Z
/* * MIT License * * Copyright (c) 2021 ETJump team <zero@etjump.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef CUSTOM_MAP_VOTES_HH #define CUSTOM_MAP_VOTES_HH #include <vector> #include <string> class MapStatistics; class CustomMapVotes { public: struct MapType { std::string type; std::string callvoteText; std::vector<std::string> mapsOnServer; std::vector<std::string> otherMaps; }; struct TypeInfo { TypeInfo(bool typeExists, const std::string& callvoteText) : typeExists(typeExists), callvoteText(callvoteText) { } TypeInfo() : typeExists(false) { } bool typeExists; std::string callvoteText; }; CustomMapVotes(MapStatistics *mapStats); ~CustomMapVotes(); bool Load(); TypeInfo GetTypeInfo(const std::string& type) const; const std::string RandomMap(const std::string& type); bool isValidMap(const std::string &mapName); std::string ListTypes() const; const std::vector<std::string> *ListInfo(const std::string& name); void GenerateVotesFile(); private: std::vector<MapType> customMapVotes_; const std::vector<std::string> *_currentMapsOnServer; MapStatistics *_mapStats; }; #endif
30
81
0.736937
[ "vector" ]
45c1fa0484617d74a1e25c9d38abe4092ef4183e
1,605
h
C
igl/readWRL.h
aviadtzemah/animation2
9a3f980fbe27672fe71f8f61f73b5713f2af5089
[ "Apache-2.0" ]
2,392
2016-12-17T14:14:12.000Z
2022-03-30T19:40:40.000Z
igl/readWRL.h
aviadtzemah/animation2
9a3f980fbe27672fe71f8f61f73b5713f2af5089
[ "Apache-2.0" ]
106
2018-04-19T17:47:31.000Z
2022-03-01T19:44:11.000Z
igl/readWRL.h
aviadtzemah/animation2
9a3f980fbe27672fe71f8f61f73b5713f2af5089
[ "Apache-2.0" ]
184
2017-11-15T09:55:37.000Z
2022-02-21T16:30:46.000Z
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #ifndef IGL_READWRL_H #define IGL_READWRL_H #include "igl_inline.h" #include <string> #include <vector> #include <cstdio> namespace igl { // Read a mesh from an ascii wrl file, filling in vertex positions and face // indices of the first model. Mesh may have faces of any number of degree // // Templates: // Scalar type for positions and vectors (will be read as double and cast // to Scalar) // Index type for indices (will be read as int and cast to Index) // Inputs: // str path to .wrl file // Outputs: // V double matrix of vertex positions #V by 3 // F #F list of face indices into vertex positions // Returns true on success, false on errors template <typename Scalar, typename Index> IGL_INLINE bool readWRL( const std::string wrl_file_name, std::vector<std::vector<Scalar > > & V, std::vector<std::vector<Index > > & F); // Inputs: // wrl_file pointer to already opened .wrl file // Outputs: // wrl_file closed file template <typename Scalar, typename Index> IGL_INLINE bool readWRL( FILE * wrl_file, std::vector<std::vector<Scalar > > & V, std::vector<std::vector<Index > > & F); } #ifndef IGL_STATIC_LIBRARY # include "readWRL.cpp" #endif #endif
29.722222
79
0.680374
[ "mesh", "geometry", "vector", "model" ]
45c351dcfdbea120aecc54f3a703ab6007322656
4,511
h
C
chrome/browser/vr/ui_input_manager.h
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chrome/browser/vr/ui_input_manager.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/browser/vr/ui_input_manager.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2017 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_VR_UI_INPUT_MANAGER_H_ #define CHROME_BROWSER_VR_UI_INPUT_MANAGER_H_ #include <memory> #include <vector> #include "base/time/time.h" #include "ui/gfx/geometry/point3_f.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/vector3d_f.h" #include "ui/gfx/transform.h" namespace blink { class WebGestureEvent; } namespace vr { class UiScene; class UiElement; struct ControllerModel; struct RenderInfo; struct ReticleModel; struct EditedText; using GestureList = std::vector<std::unique_ptr<blink::WebGestureEvent>>; // Based on controller input finds the hit UI element and determines the // interaction with UI elements and the web contents. class UiInputManager { public: enum ButtonState { UP, // The button is released. DOWN, // The button is pressed. }; // When testing, it can be useful to hit test directly along the laser. // Updating the strategy permits this behavior, but it should not be used in // production. In production, we hit test along a ray that extends from the // world origin to a point far along the laser. enum HitTestStrategy { PROJECT_TO_WORLD_ORIGIN, PROJECT_TO_LASER_ORIGIN_FOR_TEST, }; explicit UiInputManager(UiScene* scene); ~UiInputManager(); // TODO(tiborg): Use generic gesture type instead of blink::WebGestureEvent. void HandleInput(base::TimeTicks current_time, const RenderInfo& render_info, const ControllerModel& controller_model, ReticleModel* reticle_model, GestureList* gesture_list); // Text input related. void RequestFocus(int element_id); void RequestUnfocus(int element_id); void OnInputEdited(const EditedText& info); void OnInputCommitted(const EditedText& info); void OnKeyboardHidden(); bool controller_quiescent() const { return controller_quiescent_; } bool controller_resting_in_viewport() const { return controller_resting_in_viewport_; } void set_hit_test_strategy(HitTestStrategy strategy) { hit_test_strategy_ = strategy; } private: void SendFlingCancel(GestureList* gesture_list, const gfx::PointF& target_point); void SendScrollEnd(GestureList* gesture_list, const gfx::PointF& target_point, ButtonState button_state); bool SendScrollBegin(UiElement* target, GestureList* gesture_list, const gfx::PointF& target_point); void SendScrollUpdate(GestureList* gesture_list, const gfx::PointF& target_point); void SendHoverEvents(UiElement* target, const gfx::PointF& target_point); void SendMove(UiElement* element, const gfx::PointF& target_point); void SendButtonDown(UiElement* target, const gfx::PointF& target_point, ButtonState button_state); bool SendButtonUp(const gfx::PointF& target_point, ButtonState button_state); void GetVisualTargetElement(const ControllerModel& controller_model, ReticleModel* reticle_model) const; void UpdateQuiescenceState(base::TimeTicks current_time, const ControllerModel& controller_model); void UpdateControllerFocusState(base::TimeTicks current_time, const RenderInfo& render_info, const ControllerModel& controller_model); void UnfocusFocusedElement(); UiScene* scene_; int hover_target_id_ = 0; // TODO(mthiesse): We shouldn't have a fling target. Elements should fling // independently and we should only cancel flings on the relevant element // when we do cancel flings. int fling_target_id_ = 0; int input_capture_element_id_ = 0; int focused_element_id_ = 0; bool in_click_ = false; bool in_scroll_ = false; HitTestStrategy hit_test_strategy_ = HitTestStrategy::PROJECT_TO_WORLD_ORIGIN; ButtonState previous_button_state_ = ButtonState::UP; base::TimeTicks last_significant_controller_update_time_; gfx::Transform last_significant_controller_transform_; bool controller_quiescent_ = false; base::TimeTicks last_controller_outside_viewport_time_; bool controller_resting_in_viewport_ = false; }; } // namespace vr #endif // CHROME_BROWSER_VR_UI_INPUT_MANAGER_H_
34.968992
80
0.717358
[ "geometry", "vector", "transform" ]
45c4dfa1ff8a6042fe9b8c645a889f8dc0918270
2,998
h
C
projects/vectorization/src/vectorization.h
goliat90/edg4x-rose
75984d718a5235fb1433e7cab1991ade8d44f9ac
[ "BSD-3-Clause" ]
4
2017-12-19T17:15:00.000Z
2021-02-05T12:25:50.000Z
projects/vectorization/src/vectorization.h
goliat90/edg4x-rose
75984d718a5235fb1433e7cab1991ade8d44f9ac
[ "BSD-3-Clause" ]
null
null
null
projects/vectorization/src/vectorization.h
goliat90/edg4x-rose
75984d718a5235fb1433e7cab1991ade8d44f9ac
[ "BSD-3-Clause" ]
2
2019-02-19T01:27:51.000Z
2019-02-19T12:29:49.000Z
#ifndef _VECTORIZATION_H #define _VECTORIZATION_H #include "rose.h" #include "sageBuilder.h" #include <vector> #include <iostream> #include <fstream> namespace SIMDVectorization { class conditionalStmts { SgExpression* lhsExpr; SgExpression* trueExpr; SgExpression* falseExpr; /* We use map as container to store the conditionalStmt data. This index is used to keep its insertion order. */ int index; public: conditionalStmts(SgExpression*,SgExpression*,SgExpression*,int); conditionalStmts(); ~conditionalStmts(); void updateFalseStmt(SgExpression*); SgExpression* getLhsExpr(); SgExpression* getTrueExpr(); SgExpression* getFalseExpr(); int getIndex(); }; // Add the SIMD header files, rose_simd.h, to the output file. void addHeaderFile(SgProject*); // Perform strip-mining on a loop. The integer argument is the vector factor. void stripmineLoop(SgForStatement*, int); // Perform strip-mining transformation on a vectorizable loop, update its loop stride. void updateLoopIteration(SgForStatement*, int); // vectorize unary operations insize vectorizable loop void vectorizeUnaryOp(SgUnaryOp*); // vectorize binary operations insize vectorizable loop void vectorizeBinaryOp(SgBinaryOp*); // vectorize ifStmt inside vectorizable loop void vectorizeConditionalStmt(SgIfStmt*); // vectorize function call inside vectorizable loop void vectorizeFunctionCall(SgFunctionCallExp*); // translate ifStmt inside vectorizable loop void translateIfStmt(SgIfStmt*, std::map<SgName,conditionalStmts*>&); // translate the binary operator to SIMD intrisic functions void translateBinaryOp(SgBinaryOp*, SgScopeStatement*, SgName); // translate the operands to use SIMD data types void translateOperand(SgExpression*); // identify all the multiply-accumulate operations and perform the translation on them. void translateMultiplyAccumulateOperation(SgStatement*); // repalce the multiply-accumulate operations to the function call. The second argument is the name of function. void generateMultiplyAccumulateFunctionCall(SgBinaryOp*,SgName); // Insert SIMD data types, __SIMD, __SIMDi and __SIMDd, into AST. void insertSIMDDataType(SgGlobal*); // get the mapped SIMD data type from the scalar data type SgType* getSIMDType(SgType*, SgScopeStatement*); // Decide the suffix name of SIMD functions based on the operand's type std::string getSIMDOpSuffix(SgType*); // Promote scalar variable to SIMD varialbe before the loop, or extract scalar from SIMD variable after loop void scalarVariableConversion(SgForStatement*, std::set<SgInitializedName*>, std::set<SgInitializedName*>); // Add expression for true statement into ConditionalStmtTable void insertConditionalStmtTable(SgStatement*, std::map<SgName,conditionalStmts*>&, int); void updateConditionalStmtTable(SgStatement*, std::map<SgName,conditionalStmts*>&); } #endif //_VECTORIZATION_H
33.685393
114
0.762175
[ "vector" ]
45c75b284a1e19bb4d2b3d14a8cf9b0b306de76b
1,832
h
C
tests/ut/common/graph/testcase/ge_graph/graph_builder_utils.h
Ascend/graphengine
45d6a09b12a07eb3c854452f83dab993eba79716
[ "Apache-2.0" ]
207
2020-03-28T02:12:50.000Z
2021-11-23T18:27:45.000Z
tests/ut/common/graph/testcase/ge_graph/graph_builder_utils.h
zengchen1024/graphengine
0c33e9d12562953ca4bd6c03cb77da2c2da74acd
[ "Apache-2.0" ]
4
2020-04-17T07:32:44.000Z
2021-06-26T04:55:03.000Z
tests/ut/common/graph/testcase/ge_graph/graph_builder_utils.h
zengchen1024/graphengine
0c33e9d12562953ca4bd6c03cb77da2c2da74acd
[ "Apache-2.0" ]
13
2020-03-28T02:52:26.000Z
2021-07-03T23:12:54.000Z
/** * Copyright 2019-2020 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 UT_COMMON_GRAPH_TESTCASE_GE_GRAPH_GRAPH_BUILDER_UTILS_H_ #define UT_COMMON_GRAPH_TESTCASE_GE_GRAPH_GRAPH_BUILDER_UTILS_H_ #include <string> #include <vector> #include "graph/compute_graph.h" #include "graph/graph.h" #include "graph/node.h" namespace ge { namespace ut { class GraphBuilder { public: explicit GraphBuilder(const std::string &name) { graph_ = std::make_shared<ComputeGraph>(name); } NodePtr AddNode(const std::string &name, const std::string &type, int in_cnt, int out_cnt, Format format = FORMAT_NCHW, DataType data_type = DT_FLOAT, std::vector<int64_t> shape = {1, 1, 224, 224}); NodePtr AddNDNode(const std::string &name, const std::string &type, int in_cnt, int out_cnt) { return AddNode(name, type, in_cnt, out_cnt, FORMAT_ND, DT_FLOAT, {1, 1, 224, 224}); } void AddDataEdge(NodePtr &src_node, int src_idx, NodePtr &dst_node, int dst_idx); void AddControlEdge(NodePtr &src_node, NodePtr &dst_node); ComputeGraphPtr GetGraph() { graph_->TopologicalSorting(); return graph_; } private: ComputeGraphPtr graph_; }; } // namespace ut } // namespace ge #endif // UT_COMMON_GRAPH_TESTCASE_GE_GRAPH_GRAPH_BUILDER_UTILS_H_
35.230769
99
0.73417
[ "shape", "vector" ]
45c9e1654443390b7a3ead6b4b5cd178c708d5a4
1,968
h
C
graphics/cgal/HalfedgeDS/doc/HalfedgeDS/CGAL/HalfedgeDS_halfedge_base.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
4
2016-03-30T14:31:52.000Z
2019-02-02T05:01:32.000Z
graphics/cgal/HalfedgeDS/doc/HalfedgeDS/CGAL/HalfedgeDS_halfedge_base.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
graphics/cgal/HalfedgeDS/doc/HalfedgeDS/CGAL/HalfedgeDS_halfedge_base.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
namespace CGAL { /*! \ingroup PkgHDS_VHF The class `HalfedgeDS_halfedge_base` is a model of the `HalfedgeDSHalfedge` concept. `Refs` is an instantiation of a `HalfedgeDS`. The full declaration states four template parameters: <TABLE border="0"><TR><TD ALIGN=LEFT VALIGN=TOP NOWRAP> <span class="mbox"></span> <TD ALIGN=LEFT VALIGN=TOP NOWRAP> `template <` <TD ALIGN=LEFT VALIGN=TOP NOWRAP> `class Refs,` <TR><TD ALIGN=LEFT VALIGN=TOP NOWRAP> <TD ALIGN=LEFT VALIGN=TOP NOWRAP> <TD ALIGN=LEFT VALIGN=TOP NOWRAP> `class Tag_prev ` <TD ALIGN=LEFT VALIGN=TOP NOWRAP> `= CGAL::Tag_true,` <TR><TD ALIGN=LEFT VALIGN=TOP NOWRAP> <TD ALIGN=LEFT VALIGN=TOP NOWRAP> <TD ALIGN=LEFT VALIGN=TOP NOWRAP> `class Tag_vertex ` <TD ALIGN=LEFT VALIGN=TOP NOWRAP> `= CGAL::Tag_true,` <TR><TD ALIGN=LEFT VALIGN=TOP NOWRAP> <TD ALIGN=LEFT VALIGN=TOP NOWRAP> <TD ALIGN=LEFT VALIGN=TOP NOWRAP> `class Tag_face ` <TD ALIGN=LEFT VALIGN=TOP NOWRAP> `= CGAL::Tag_true>` <TR><TD ALIGN=LEFT VALIGN=TOP NOWRAP> <TD ALIGN=LEFT VALIGN=TOP NOWRAP> `class HalfedgeDS_halfedge_base;` </TABLE> If `Tag_prev` \f$ \equiv\f$ `CGAL::Tag_true` a reference to the previous halfedge is supported. If `Tag_vertex` \f$ \equiv\f$ `CGAL::Tag_true` an incident vertex is supported. If `Tag_face` \f$ \equiv\f$ `CGAL::Tag_true` an incident face is supported. In all cases, a reference to the next halfedge and to the opposite halfedge is supported. \cgalModels `HalfedgeDSHalfedge` \sa `HalfedgeDS<Traits,Items,Alloc>` \sa `HalfedgeDSItems` \sa `PolyhedronItems_3` \sa `CGAL::HalfedgeDS_items_2` \sa `CGAL::HalfedgeDS_vertex_base<Refs>` \sa `CGAL::HalfedgeDS_face_base<Refs>` \sa `CGAL::HalfedgeDS_halfedge_min_base<Refs>` */ template< typename Refs > class HalfedgeDS_halfedge_base { public: /// \name Creation /// @{ /*! default constructor. */ HalfedgeDS_halfedge_base(); /// @} }; /* end HalfedgeDS_halfedge_base */ } /* end namespace CGAL */
22.62069
76
0.71748
[ "model" ]
45cd65db2df7c9f237db580aa69c18bccc80219e
2,597
h
C
torch/csrc/jit/codegen/cuda/index_reference_replay.h
sanchitintel/pytorch
416f59308023b5d98f6ea4ecdd0bcd3829edb7a7
[ "Intel" ]
60,067
2017-01-18T17:21:31.000Z
2022-03-31T21:37:45.000Z
torch/csrc/jit/codegen/cuda/index_reference_replay.h
sanchitintel/pytorch
416f59308023b5d98f6ea4ecdd0bcd3829edb7a7
[ "Intel" ]
66,955
2017-01-18T17:21:38.000Z
2022-03-31T23:56:11.000Z
torch/csrc/jit/codegen/cuda/index_reference_replay.h
sanchitintel/pytorch
416f59308023b5d98f6ea4ecdd0bcd3829edb7a7
[ "Intel" ]
19,210
2017-01-18T17:45:04.000Z
2022-03-31T23:51:56.000Z
#pragma once #include <torch/csrc/WindowsTorchApiMacro.h> #include <torch/csrc/jit/codegen/cuda/index_compute.h> #include <torch/csrc/jit/codegen/cuda/kernel_ir.h> #include <vector> namespace torch { namespace jit { namespace fuser { namespace cuda { struct ReferenceTensor { TensorDomain* domain = nullptr; // Map from concrete iteration domains in ComputeAtMaps to iter domains // including those used to construct domain. std::unordered_map<IterDomain*, IterDomain*> concrete_to_id; }; class IndexReferenceReplay : public OptInDispatch { private: IndexReferenceReplay(const std::vector<kir::ForLoop*>& loop_structure) : loop_structure_(loop_structure) {} // We're going to replay this split operation on the corresponding ID void handle(Split* s) override; // We're going to replay this merge operation on the corresponding IDs void handle(Merge* m) override; TensorDomain* computeReplay(); using OptInDispatch::handle; private: const std::vector<kir::ForLoop*>& loop_structure_; // Replay map std::unordered_map<IterDomain*, IterDomain*> concrete_to_id_; // Replay map std::unordered_set<IterDomain*> leaf_ids_; public: static ReferenceTensor getReference( const std::vector<kir::ForLoop*>& loop_structure) { auto replay = IndexReferenceReplay(loop_structure); ReferenceTensor ref; ref.domain = replay.computeReplay(); ref.concrete_to_id = replay.concrete_to_id_; return ref; } }; // Index into the reference based on the provided index map. IndexCompute getReferenceIndexing( const std::vector<kir::ForLoop*>& loop_structure, TensorDomain* reference_domain, std::unordered_map<kir::IterDomain*, kir::Val*> index_map, std::unordered_set<IterDomain*> preferred_path, std::unordered_map<kir::IterDomain*, kir::Val*> halo_extent_map = {}); // Short cut for global TVs. Index into the reference based on all loop indicies // in the loop structure. IndexCompute getReferenceIndexing( const std::vector<kir::ForLoop*>& loop_structure, TensorDomain* reference_domain); // When indexing there are sometimes an option to propagate an index down // multiple paths. This will return the IterDomains in the history of the // reference domain and mark which paths should be taken (if there's a // preference) to reach the roots provided in preferred_roots. std::unordered_set<IterDomain*> buildPreferredPaths( TensorDomain* reference_domain, const std::unordered_set<IterDomain*>& preferred_roots); } // namespace cuda } // namespace fuser } // namespace jit } // namespace torch
30.916667
80
0.750096
[ "vector" ]
45dc805de742bc090c4fd9259c1b5ef30cee1844
3,192
h
C
chrome/browser/devtools/protocol/devtools_protocol_test_support.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/devtools/protocol/devtools_protocol_test_support.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/devtools/protocol/devtools_protocol_test_support.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 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_DEVTOOLS_PROTOCOL_DEVTOOLS_PROTOCOL_TEST_SUPPORT_H_ #define CHROME_BROWSER_DEVTOOLS_PROTOCOL_DEVTOOLS_PROTOCOL_TEST_SUPPORT_H_ #include <string> #include <utility> #include <vector> #include "base/callback.h" #include "base/memory/scoped_refptr.h" #include "base/values.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/devtools_agent_host_client.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "url/origin.h" class DevToolsProtocolTestBase : public InProcessBrowserTest, public content::DevToolsAgentHostClient { public: DevToolsProtocolTestBase(); ~DevToolsProtocolTestBase() override; void SetAllowUnsafeOperations(bool allow) { allow_unsafe_operations_ = allow; } absl::optional<url::Origin> GetNavigationInitiatorOrigin() override; protected: using NotificationMatcher = base::RepeatingCallback<bool(const base::Value&)>; // InProcessBrowserTest interface void TearDownOnMainThread() override; // DevToolsAgentHostClient interface void DispatchProtocolMessage(content::DevToolsAgentHost* agent_host, base::span<const uint8_t> message) override; void SendCommand(const std::string& method) { SendCommand(method, base::Value(), false); } void SendCommandSync(const std::string& method) { SendCommandSync(method, base::Value()); } void SendCommandSync(const std::string& method, base::Value params) { SendCommand(method, std::move(params), true); } void SendCommand(const std::string& method, base::Value params, bool synchronous); void WaitForResponse(); void RunLoopUpdatingQuitClosure(); void AttachToBrowser(); void Attach(); void Detach(); virtual content::WebContents* web_contents(); base::Value WaitForNotification(const std::string& notification); base::Value WaitForMatchingNotification(const std::string& notification, const NotificationMatcher& matcher); // DevToolsAgentHostClient interface void AgentHostClosed(content::DevToolsAgentHost* agent_host) override; bool AllowUnsafeOperations() override; bool MaySendInputEventsToBrowser() override; scoped_refptr<content::DevToolsAgentHost> agent_host_; int last_sent_id_ = 0; base::OnceClosure run_loop_quit_closure_; bool in_dispatch_ = false; int waiting_for_command_result_id_ = 0; base::Value result_; std::vector<std::string> notifications_; std::vector<base::Value> notification_params_; std::string waiting_for_notification_; NotificationMatcher waiting_for_notification_matcher_; base::Value waiting_for_notification_params_; bool allow_unsafe_operations_ = true; bool may_send_input_event_to_browser_ = true; absl::optional<url::Origin> navigation_initiator_origin_; }; #endif // CHROME_BROWSER_DEVTOOLS_PROTOCOL_DEVTOOLS_PROTOCOL_TEST_SUPPORT_H_
34.322581
80
0.755013
[ "vector" ]
45dfbbd5077a35cc428f40017ff26e28aeb95201
4,450
h
C
server/include/chilkat/CkEmailBundleW.h
SKKU-Tizen-SecBTKey/FrameworkVirtualKeyboard
6962d4ef499e333f53bb25bed5ef0fe9c48be717
[ "Apache-2.0" ]
null
null
null
server/include/chilkat/CkEmailBundleW.h
SKKU-Tizen-SecBTKey/FrameworkVirtualKeyboard
6962d4ef499e333f53bb25bed5ef0fe9c48be717
[ "Apache-2.0" ]
null
null
null
server/include/chilkat/CkEmailBundleW.h
SKKU-Tizen-SecBTKey/FrameworkVirtualKeyboard
6962d4ef499e333f53bb25bed5ef0fe9c48be717
[ "Apache-2.0" ]
null
null
null
// CkEmailBundleW.h: interface for the CkEmailBundleW class. // ////////////////////////////////////////////////////////////////////// // This header is generated for Chilkat v9.5.0 #ifndef _CkEmailBundleW_H #define _CkEmailBundleW_H #include "chilkatDefs.h" #include "CkString.h" #include "CkWideCharBase.h" class CkEmailW; class CkStringArrayW; #ifndef __sun__ #pragma pack (push, 8) #endif // CLASS: CkEmailBundleW class CK_VISIBLE_PUBLIC CkEmailBundleW : public CkWideCharBase { private: // Don't allow assignment or copying these objects. CkEmailBundleW(const CkEmailBundleW &); CkEmailBundleW &operator=(const CkEmailBundleW &); public: CkEmailBundleW(void); virtual ~CkEmailBundleW(void); static CkEmailBundleW *createNew(void); void CK_VISIBLE_PRIVATE inject(void *impl); // May be called when finished with the object to free/dispose of any // internal resources held by the object. void dispose(void); // BEGIN PUBLIC INTERFACE // ---------------------- // Properties // ---------------------- // The number of emails in this bundle. int get_MessageCount(void); // ---------------------- // Methods // ---------------------- // Adds an email object to the bundle. bool AddEmail(const CkEmailW &email); // Returns the first email having a header field matching the headerFieldName and headerFieldValue exactly // (case sensitive). If no matching email is found, returns _NULL_. // The caller is responsible for deleting the object returned by this method. CkEmailW *FindByHeader(const wchar_t *name, const wchar_t *value); // Returns the Nth Email in the bundle. The email returned is a copy of the email // in the bundle. Updating the email object returned by GetEmail has no effect on // the email within the bundle. To update/replace the email in the bundle, your // program should call GetEmail to get a copy, make modifications, call // RemoveEmailByIndex to remove the email (passing the same index used in the call // to GetEmail), and then call AddEmail to insert the new/modified email into the // bundle. // // IMPORTANT: This method does NOT communicate with any mail server to download the // email. It simply returns the Nth email object that exists within it's in-memory // collection of email objects. // // The caller is responsible for deleting the object returned by this method. CkEmailW *GetEmail(int index); // Returns a StringArray object containing UIDLs for all Email objects in the // bundle. UIDLs are only valid for emails retrieved from POP3 servers. An email on // a POP3 server has a "UIDL", an email on IMAP servers has a "UID". If the email // was retrieved from an IMAP server, the UID will be accessible via the // "ckx-imap-uid" header field. // The caller is responsible for deleting the object returned by this method. CkStringArrayW *GetUidls(void); // Converts the email bundle to an XML document in memory. Returns the XML document // as a string. bool GetXml(CkString &outXml); // Converts the email bundle to an XML document in memory. Returns the XML document // as a string. const wchar_t *getXml(void); // Converts the email bundle to an XML document in memory. Returns the XML document // as a string. const wchar_t *xml(void); // Loads an email bundle from an XML file. bool LoadXml(const wchar_t *filename); // Loads an email bundle from an XML string. bool LoadXmlString(const wchar_t *xmlStr); // Removes an email from the bundle. This does not remove the email from the mail // server. bool RemoveEmail(const CkEmailW &email); // Removes the Nth email in a bundle. (Indexing begins at 0.) bool RemoveEmailByIndex(int index); // Converts each email to XML and persists the bundle to an XML file. The email // bundle can later be re-instantiated by calling MailMan.LoadXmlFile bool SaveXml(const wchar_t *filename); // Sorts emails in the bundle by date. void SortByDate(bool ascending); // Sorts emails in the bundle by recipient. void SortByRecipient(bool ascending); // Sorts emails in the bundle by sender. void SortBySender(bool ascending); // Sorts emails in the bundle by subject. void SortBySubject(bool ascending); // END PUBLIC INTERFACE }; #ifndef __sun__ #pragma pack (pop) #endif #endif
29.865772
109
0.691236
[ "object" ]
45e0874694b4c591d595a0a98c0a70077f4fa077
4,552
h
C
third_party/blink/renderer/modules/vibration/vibration_controller.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
110
2020-10-27T02:15:35.000Z
2022-03-30T10:24:52.000Z
third_party/blink/renderer/modules/vibration/vibration_controller.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
third_party/blink/renderer/modules/vibration/vibration_controller.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
37
2020-11-13T15:44:23.000Z
2022-03-25T09:08:22.000Z
/* * Copyright (C) 2012 Samsung Electronics * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_VIBRATION_VIBRATION_CONTROLLER_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_VIBRATION_VIBRATION_CONTROLLER_H_ #include "base/macros.h" #include "services/device/public/mojom/vibration_manager.mojom-blink.h" #include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_observer.h" #include "third_party/blink/renderer/core/page/page_visibility_observer.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/mojo/heap_mojo_remote.h" #include "third_party/blink/renderer/platform/supplementable.h" #include "third_party/blink/renderer/platform/timer.h" #include "third_party/blink/renderer/platform/wtf/vector.h" namespace blink { class Navigator; class V8UnionUnsignedLongOrUnsignedLongSequence; class MODULES_EXPORT VibrationController final : public GarbageCollected<VibrationController>, public Supplement<Navigator>, public ExecutionContextLifecycleObserver, public PageVisibilityObserver { public: using VibrationPattern = Vector<unsigned>; static const char kSupplementName[]; static VibrationController& From(Navigator&); static bool vibrate(Navigator&, unsigned time); static bool vibrate(Navigator&, const VibrationPattern&); explicit VibrationController(Navigator&); VibrationController(const VibrationController&) = delete; VibrationController& operator=(const VibrationController&) = delete; ~VibrationController() override; static VibrationPattern SanitizeVibrationPattern( const V8UnionUnsignedLongOrUnsignedLongSequence* input); void DoVibrate(TimerBase*); void DidVibrate(); // Cancels the ongoing vibration if there is one. void Cancel(); void DidCancel(); // Whether a pattern is being processed. If this is true, the vibration // hardware may currently be active, but during a pause it may be inactive. bool IsRunning() const { return is_running_; } VibrationPattern Pattern() const { return pattern_; } void Trace(Visitor*) const override; private: // Inherited from ExecutionContextLifecycleObserver. void ContextDestroyed() override; // Inherited from PageVisibilityObserver. void PageVisibilityChanged() override; bool Vibrate(const VibrationPattern&); // Remote to VibrationManager mojo interface. This is reset in // |contextDestroyed| and must not be called or recreated after it is reset. // // TODO(crbug.com/1116948): Remove kForceWithoutContextObserver parameter // after hooking disconnect handler in js is implemented in // MojoInterfaceInterceptor. // See: third_party/blink/web_tests/vibration/vibration-iframe.html HeapMojoRemote<device::mojom::blink::VibrationManager, HeapMojoWrapperMode::kForceWithoutContextObserver> vibration_manager_; // Timer for calling |doVibrate| after a delay. It is safe to call // |startOneshot| when the timer is already running: it may affect the time // at which it fires, but |doVibrate| will still be called only once. HeapTaskRunnerTimer<VibrationController> timer_do_vibrate_; // Whether a pattern is being processed. The vibration hardware may // currently be active, or during a pause it may be inactive. bool is_running_; // Whether an async mojo call to cancel is pending. bool is_calling_cancel_; // Whether an async mojo call to vibrate is pending. bool is_calling_vibrate_; VibrationPattern pattern_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_VIBRATION_VIBRATION_CONTROLLER_H_
37.933333
99
0.779218
[ "vector" ]
45e0eb084f4feee11861173f7f82f9f56125fd04
33,117
h
C
third_party/fwkacllib/inc/ops/nn_norm_ops.h
laekov/akg
5316b8cb2340bbf71bdc724dc9d81513a67b3104
[ "Apache-2.0" ]
1
2020-08-31T02:43:43.000Z
2020-08-31T02:43:43.000Z
third_party/fwkacllib/inc/ops/nn_norm_ops.h
laekov/akg
5316b8cb2340bbf71bdc724dc9d81513a67b3104
[ "Apache-2.0" ]
null
null
null
third_party/fwkacllib/inc/ops/nn_norm_ops.h
laekov/akg
5316b8cb2340bbf71bdc724dc9d81513a67b3104
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2019-2020 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 GE_OP_NN_NORM_OPS_H #define GE_OP_NN_NORM_OPS_H #include "graph/operator_reg.h" namespace ge { /** *@brief Computes the gradient for log softmax activations. *@par Inputs: *@li grad: A Tensor. Must be one of the following types: float16, float32. *@li x: A Tensor. Must be one of the following types: float16, float32. *@par Attributes: * axis: An optional list of ints. Defaults to "{-1}". *@par Outputs: * y: A Tensor. Has the same type as "grad". */ REG_OP(LogSoftmaxGrad) .INPUT(grad, TensorType({DT_FLOAT16, DT_FLOAT})) .INPUT(x, TensorType({DT_FLOAT16, DT_FLOAT})) .OUTPUT(y, TensorType({DT_FLOAT16, DT_FLOAT})) .ATTR(axis, ListInt, {-1}) .OP_END_FACTORY_REG(LogSoftmaxGrad) REG_OP(SparseSoftmaxCrossEntropyWithLogitsCCE) .INPUT(features, TensorType{DT_FLOAT}) .INPUT(labels, TensorType{DT_FLOAT}) .OUTPUT(out, TensorType{DT_FLOAT}) .OUTPUT(non, TensorType{DT_FLOAT}) .ATTR(cross_entropy_is_grad, Bool, 0) .ATTR(cross_entropy_mode, Int, 1) .ATTR(softmax_cross_entropy_lossscale_div_batch, Float, 1.0) .OP_END_FACTORY_REG(SparseSoftmaxCrossEntropyWithLogitsCCE) /** *@brief Computes sparse softmax cross entropy cost and gradients to backpropagate. *@par Inputs: *Two inputs, including: * @li features: A Tensor. Must be one of the following types: half, float32, double. * A "batch_size * num_classes" matrix. * @li labels: A Tensor of the same type as "features". batch_size vector with values in [0, num_classes). *@par Outputs: *loss: A Tensor for per example loss (a "batch_size" vector). Has the same type as "features". *backprop: A Tensor for the backpropagated gradients (a batch_size * num_classes matrix). Has the same type as "features". */ REG_OP(SparseSoftmaxCrossEntropyWithLogits) .INPUT(features, TensorType({DT_FLOAT16,DT_FLOAT})) .INPUT(labels, TensorType({DT_INT32, DT_INT64})) .OUTPUT(loss, TensorType({DT_FLOAT16,DT_FLOAT})) .OUTPUT(backprop, TensorType({DT_FLOAT16,DT_FLOAT})) .OP_END_FACTORY_REG(SparseSoftmaxCrossEntropyWithLogits) /** *@brief Computes softmax cross entropy cost and gradients to backpropagate. *@par Inputs: *Two inputs, including: * @li features: A Tensor. Must be one of the following types: half, float32, double. * A "batch_size * num_classes" matrix. * @li labels: A Tensor of the same type as "features". A "batch_size * num_classes" matrix. *@par Outputs: *loss: A Tensor for per example loss (a "batch_size" vector). Has the same type as "features". *backprop: A Tensor for the backpropagated gradients (a batch_size * num_classes matrix). Has the same type as "features". */ REG_OP(SoftmaxCrossEntropyWithLogits) .INPUT(features, TensorType({DT_DOUBLE,DT_FLOAT16,DT_FLOAT})) .INPUT(labels, TensorType({DT_DOUBLE,DT_FLOAT16,DT_FLOAT})) .OUTPUT(loss, TensorType({DT_DOUBLE,DT_FLOAT16,DT_FLOAT})) .OUTPUT(backprop, TensorType({DT_DOUBLE,DT_FLOAT16,DT_FLOAT})) .OP_END_FACTORY_REG(SoftmaxCrossEntropyWithLogits) /** *@brief Computes gradients for a softmax operation. *@par Inputs: * Two inputs, including: \n * @li softmax: Output of the softmax operator. Must be one of the following types: float16, float31, int32, int8, uint8. The format is NC1HWC0 or DN. * @li grad_softmax: A Tensor. Has the same shape and type as "softmax". The format is NC1HWC0 or DN. *@par Outputs: *grad_x: A Tensor. Has the same shape and type as "softmax". */ REG_OP(SoftmaxGrad) .INPUT(softmax, TensorType({DT_FLOAT16,DT_FLOAT,DT_INT32,DT_INT8,DT_UINT8})) .INPUT(grad_softmax, TensorType({DT_FLOAT16,DT_FLOAT,DT_INT32,DT_INT8,DT_UINT8})) .OUTPUT(grad_x, TensorType({DT_FLOAT16,DT_FLOAT,DT_INT32,DT_INT8,DT_UINT8})) .OP_END_FACTORY_REG(SoftmaxGrad) /** *@brief Computes the sigmoid cross entropy loss of "predict" and "target". *@par Inputs: * Two inputs, including: \n *@li predict: A multi-dimensional Tensor of type float16 or float32, specifying the predictive value. *@li target: A multi-dimensional Tensor of type float16 or float32, specifying the target value. *@par Outputs: *loss: Sigmoid cross entropy between the predictive value and target value. Has the same dimensions as "predict". */ REG_OP(SigmoidCrossEntropyWithLogitsGrad) .INPUT(predict, TensorType({DT_FLOAT16, DT_FLOAT})) .INPUT(target, TensorType({DT_FLOAT16, DT_FLOAT})) .INPUT(dout, TensorType({DT_FLOAT16, DT_FLOAT})) .OUTPUT(gradient, TensorType({DT_FLOAT16, DT_FLOAT})) .OP_END_FACTORY_REG(SigmoidCrossEntropyWithLogitsGrad) /** *@brief Performs the backpropagation of SigmoidCrossEntropyWithLogits for training scenarios. *@par Inputs: * Three inputs, including: \n *@li predict: A multi-dimensional Tensor of type float16 or float32, specifying the predictive value. *@li target: A multi-dimensional Tensor of type float16 or float32, specifying the target value. *@li dout: A multi-dimensional Tensor of float16 or float32, specifying the gradient transferred from the upper layer. *@par Outputs: \n *gradient: Return gradient. Has the same dimensions and type as "predict". */ REG_OP(SigmoidCrossEntropyWithLogits) .INPUT(predict, TensorType({DT_FLOAT16, DT_FLOAT})) .INPUT(target, TensorType({DT_FLOAT16, DT_FLOAT})) .OUTPUT(loss, TensorType({DT_FLOAT16, DT_FLOAT})) .OP_END_FACTORY_REG(SigmoidCrossEntropyWithLogits) /** *@brief Computes the regression box of the RPN. It is a FasterRCNN operator. *@par Inputs: * Two inputs, including: \n *@li predict: A multi-dimensional Tensor of type float16 or float32, specifying the predictive value. *@li label: A multi-dimensional Tensor of type float16 or float32, specifying the target value. *@par Attributes: * sigma: Must be a floating point number. Defaults to "1.0". *@par Outputs: *loss: Indicates the loss between the predictive value and target value. Has the same dimensions as "predict". *@attention Constraints: * This operator does not perform the "reduce" operation on the loss value. Call other reduce operators to perform "reduce" operation on the loss if required. */ REG_OP(SmoothL1Loss) .INPUT(predict, TensorType({DT_FLOAT16, DT_FLOAT})) .INPUT(label, TensorType({DT_FLOAT16, DT_FLOAT})) .OUTPUT(loss, TensorType({DT_FLOAT16, DT_FLOAT})) .ATTR(sigma, Float, 1.0) .OP_END_FACTORY_REG(SmoothL1Loss) /** *@brief Performs the backpropagation of SmoothL1Loss for training scenarios. *@par Inputs: * Three inputs, including: \n *@li predict: A multi-dimensional Tensor of type float16 or float32, specifying the predictive value. *@li label: A multi-dimensional Tensor of float16 or float32, specifying the target value. *@li dout: A multi-dimensional Tensor of float16 or float32, specifying the gradient transferred from the upper layer. *@par Attributes: * sigma: Must be a floating point number. Defaults to "1.0". *@par Outputs: *gradient: Return gradient. Has the same dimensions and type as "predict". */ REG_OP(SmoothL1LossGrad) .INPUT(predict, TensorType({DT_FLOAT16, DT_FLOAT})) .INPUT(label, TensorType({DT_FLOAT16, DT_FLOAT})) .INPUT(dout, TensorType({DT_FLOAT16, DT_FLOAT})) .OUTPUT(gradient, TensorType({DT_FLOAT16, DT_FLOAT})) .ATTR(sigma, Float, 1.0) .OP_END_FACTORY_REG(SmoothL1LossGrad) /** *@brief Creates a criterion that measures the Binary Cross Entropy between the target and the output. *@par Inputs: * Three inputs, including: \n *@li x: A 1D or 2D Tensor of type float16 or float32, specifying a predictive value. *@li y: A 1D or 2D Tensor of type float16 or float32, indicating a tag. *@li weight: An optional 1D or 2D Tensor, specifying the weight. *@par Attributes: *reduction: A character string from "none", "mean", and "sum", specifying the reduction type to be applied to the output. Defaults to "mean". *@par Outputs: *output: Output loss. Has the same dimension with the inputs. When "reduction" is set to "none", a Tensor with the same size as "x" is output. Otherwise, a Scalar is output. *@attention Constraints: *@li The value of "x" must range from 0 to 1. *@li The value of "y" must be "0" or "1". */ REG_OP(BinaryCrossEntropy) .INPUT(x, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(y, TensorType({DT_FLOAT, DT_FLOAT16})) .OPTIONAL_INPUT(weight, TensorType({DT_FLOAT, DT_FLOAT16})) .OUTPUT(output, TensorType({DT_FLOAT, DT_FLOAT16})) .ATTR(reduction, String, "mean") .OP_END_FACTORY_REG(BinaryCrossEntropy) /** *@brief Performs the backpropagation of BinaryCrossEntropy for training scenarios. *@par Inputs: * Four inputs, including: \n *@li x: A 1D or 2D Tensor of type float16 or float32, specifying a predictive value. *@li y: A 1D or 2D Tensor of type float16 or float32, indicating a tag. *@li grad_output: A 1D or 2D Tensor of type float16 or float32, specifying the backpropagation gradient. *@li weight: An optional 1D or 2D Tensor, specifying the weight. *@par Attributes: \n *reduction: A character string from "none", "mean", and "sum", specifying the gradient output mode. Defaults to "mean". *@par Outputs: \n *output: A 1D or 2D Tensor. When "reduction" is set to "none", a Tensor with the same size as "x" is output. Otherwise, a Scalar is output. *@attention Constraints: *@li The value of "x" must range from 0 to 1. *@li The value of "y" must be "0" or "1". */ REG_OP(BinaryCrossEntropyGrad) .INPUT(x, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(y, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(grad_output, TensorType({DT_FLOAT, DT_FLOAT16})) .OPTIONAL_INPUT(weight, TensorType({DT_FLOAT, DT_FLOAT16})) .OUTPUT(output, TensorType({DT_FLOAT, DT_FLOAT16})) .ATTR(reduction, String, "mean") .OP_END_FACTORY_REG(BinaryCrossEntropyGrad) /** *@brief Applies the Softmax function to an n-dimensional input Tensor rescaling them \n so that the elements of the n-dimensional output Tensor lie in the range [0,1] and sum to 1. *@par Inputs: *One input: *x: A mutable Tensor. Must be one of the following types: float16, *float32, double. Should be a Variable Tensor. *@par Attributes: *axes: A list of ints. The dimension softmax would be performed on. *@par Outputs: *y: A Tensor. Has the same dimensionality and shape as the "x" with values in the range [0, 1]. Must be one of the following types: float16, float32, int32. */ REG_OP(SoftmaxV2) .INPUT(x, TensorType({DT_DOUBLE, DT_FLOAT16, DT_FLOAT})) .OUTPUT(y, TensorType({DT_DOUBLE, DT_FLOAT16, DT_FLOAT})) .ATTR(axes, ListInt, {-1}) .OP_END_FACTORY_REG(SoftmaxV2) /** *@brief Computes log softmax activations. *@par Inputs: *One input: * logits: A Tensor. Must be one of the following types: double, float16, float32. *@par Attributes: * axes: An optional list of ints. Defaults to "{-1}". *@par Outputs: * logsoftmax: A Tensor. Has the same type as "logits". */ REG_OP(LogSoftmaxV2) .INPUT(logits, TensorType({DT_DOUBLE, DT_FLOAT16, DT_FLOAT})) .OUTPUT(logsoftmax, TensorType({DT_DOUBLE, DT_FLOAT16, DT_FLOAT})) .ATTR(axes, ListInt, {-1}) .OP_END_FACTORY_REG(LogSoftmaxV2) REG_OP(FusedBatchNormV2) .INPUT(x, TensorType{DT_FLOAT}) /* Input data tensor from the previous operator"" */ .INPUT(scale, TensorType{DT_FLOAT}) /* If spatial is true, the dimension of bias is (C) If spatial is false, the dimensions of scale are (C x D1 x ... x Dn)*/ .INPUT(b, TensorType{DT_FLOAT}) /* If spatial is true, the dimension of bias is (C) If spatial is false, the dimensions of scale are (C x D1 x ... x Dn)*/ .OPTIONAL_INPUT(mean, TensorType{DT_FLOAT}) /* If spatial is true, the dimension of the running mean (training) or the estimated mean (testing) is (C).If spatial is false, the dimensions of the running mean (training) or the estimated mean (testing) are (C x D1 x ... x Dn)*/ .OPTIONAL_INPUT(variance, TensorType{DT_FLOAT}) /* If spatial is true, the dimension of the running variance(training) or the estimated variance (testing) is (C). If spatial is false, the dimensions of the running variance(training) or the estimated variance (testing) are (C x D1 x ... x Dn).*/ .OUTPUT(y, TensorType{DT_FLOAT}) /* The output tensor of the same shape as X */ .ATTR(momentum, Float, 0.9) // Factor used in computing the running mean and variance. .ATTR(epsilon, Float, 1e-5f) // The epsilon value to use to avoid division by zero .ATTR(mode, Int, 1) // 1 means using "CC_BATCHNORM_SPATIAL"; 0 means using "CC_BATCHNORM_PER_ACTIVATION"; only support 1 now .ATTR(use_global_stats, Bool, true) .ATTR(alpha, Float, 1) .ATTR(beta, Float, 0) .OP_END_FACTORY_REG(FusedBatchNormV2) /** *@brief Confuse mul, sum and sub. *@par Inputs: *Two inputs, including: * @li grad: A Tensor. Must be one of the following types: float16, float32. * @li x: A Tensor. Must be one of the following types: float16, float32. *@par Outputs: * y: A Tensor of the same type as "grad". */ REG_OP(ConfusionSoftmaxGrad) .INPUT(grad, TensorType({DT_FLOAT16,DT_FLOAT})) .INPUT(x, TensorType({DT_FLOAT16,DT_FLOAT})) .OUTPUT(y, TensorType({DT_FLOAT16,DT_FLOAT})) .OP_END_FACTORY_REG(ConfusionSoftmaxGrad) REG_OP(SoftmaxGradExt) .INPUT(grad, TensorType({DT_FLOAT16,DT_FLOAT})) .INPUT(x1, TensorType({DT_FLOAT16,DT_FLOAT})) .INPUT(x2, TensorType({DT_FLOAT16,DT_FLOAT})) .OUTPUT(y, TensorType({DT_FLOAT16,DT_FLOAT})) .ATTR(axes, Int, 1) .ATTR(keep_dims, Bool, false) .OP_END_FACTORY_REG(SoftmaxGradExt) /** *@brief Normalizes the input. *@par Inputs: * One input: *x: An NCHW tensor of type float16 or float32. *@par Attributes: *@li normalize_variance: An optional bool specifying whether to normalize the variance, either "true" (default) or "false" * the value "false" indicates only to subtract the mean. *@li across_channels: An optional bool specifying whether to perform across-channel MVN, either "true" or "false" (default) * The value "true" indicates "CHW" is treated as a vector. *@li eps: An optional float32 epsilon for not dividing by zero. Defaults to "1e-9". *@par Outputs: *y: An NCHW tensor of type float16 or float32. *@attention Constraints:\n * The input tensor must have the NCHW format, whose shape length must be 4. */ REG_OP(MVN) .INPUT(x, TensorType({DT_FLOAT, DT_FLOAT16})) /* "First operand." */ .OUTPUT(y, TensorType({DT_FLOAT, DT_FLOAT16})) /* "Result, has same element type as inputs" */ .ATTR(normalize_variance, Bool, true) .ATTR(across_channels, Bool, false) .ATTR(eps, Float, 1e-9) .OP_END_FACTORY_REG(MVN) /** *@brief Normalizes the input "x1". *@par Inputs: * Two inputs, including: *@li x1: A required NCHW or NHWC tensor of type float32, float16, or int8. *@li x2: A required ND tensor of type float32, float16, or int8, specifying * the scaling factor. If "channel_shared" is "true", "x2" is a [1]-dimensional * vector. If "channel_shared" is "false", "x2" is a [C]-dimensional vector. *@par Attributes: *@li across_spatial: An optional bool, specifying the dimension of input "x1" * to be summed. The value "true" (default) indicates dimensions C, H, W, and * the value "false" indicates dimension C. *@li channel_shared: An optional bool, specifying the dimension count of input * "x2". The value "true" (default) indicates 1, and the value "false" indicates * dimension C of "x1". *@li eps: An optional float32, specifying the bias when "across_spatial" is * "true". Defaults to "1e-10". *@par Outputs: *y: A Tensor. Has the same type and format as "x1". */ REG_OP(Normalize) .INPUT(x1, TensorType({DT_FLOAT16, DT_FLOAT, DT_INT8})) .INPUT(x2, TensorType({DT_FLOAT16, DT_FLOAT, DT_INT8})) .OUTPUT(y, TensorType({DT_FLOAT16, DT_FLOAT, DT_INT8})) .ATTR(across_spatial, Bool, true) .ATTR(channel_shared, Bool, true) .ATTR(eps, Float, 1e-10) .OP_END_FACTORY_REG(Normalize); /** *@brief Layernorm operator interface implementation * calculating: x, gamma, beta * mean = np.mean(x, reduce_axis, keepdims=True) * variance = np.mean(np.power((x - mean),2), reduce_axis, keepdims=True) * y = gamma*((x - mean) / np.sqrt(variance + 0.001)) + beta *@par Inputs: *Three inputs, including: * @li x: A Tensor. Must be one of the following types: float16, float32. * @li gamma: A Tensor. Must be one of the following types: float16, float32. * @li beta: A Tensor. Must be one of the following types: float16, float32. *@par Attributes: * @li begin_norm_axis: A required attribute, the type is int32. * @li begin_params_axis: A required attribute,the type is int32. *@par Outputs: *Three outputs, including: * @li y: A Tensor. Must be one of the following types: float16, float32. * @li mean: A Tensor. Must be one of the following types: float16, float32. * @li variance: A Tensor. Must be one of the following types: float16, float32. */ REG_OP(LayerNorm) .INPUT(x, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(gamma, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(beta, TensorType({DT_FLOAT, DT_FLOAT16})) .OUTPUT(y, TensorType({DT_FLOAT, DT_FLOAT16})) .OUTPUT(mean, TensorType({DT_FLOAT, DT_FLOAT16})) .OUTPUT(variance, TensorType({DT_FLOAT, DT_FLOAT16})) .ATTR(begin_norm_axis, Int, 0) .ATTR(begin_params_axis, Int, 0) .ATTR(epsilon, Float, 0.0000001) .OP_END_FACTORY_REG(LayerNorm) /** *@brief LayerNormGrad operator interface implementation * calculating: dy, x, variance, mean, gamma * pd_xl = data_dy*data_gamma * pd_var = np.sum(((-0.5)*pd_xl*(data_x - data_mean) * np.power((data_variance + EPSLON), (-1.5))), * reduce_axis, keepdims=True) * pd_mean = np.sum(((-1.0)*pd_xl * np.power((data_variance + EPSLON), (-0.5))), * reduce_axis, keepdims=True) * + pd_var*(1.0/m) * np.sum(((-2.0)*(data_x - data_mean)), reduce_axis, keepdims=True) * pd_x = pd_xl*np.power((data_variance + EPSLON), (-0.5)) + * pd_var*(2.0/m)*(data_x - data_mean) + pd_mean*(1.0/m) * pd_gamma = np.sum((data_dy*(data_x - data_mean) * np.power((data_variance + EPSLON), (-0.5))), param_axis, keepdims=True) * pd_beta = np.sum(data_dy, param_axis, keepdims=True) *@par Inputs: *Three inputs, including: * @li dy: A Tensor. Must be one of the following types: float16, float32. * @li x: A Tensor. Must be one of the following types: float16, float32. * @li variance: A Tensor. Must be one of the following types: float16, float32. * @li mean: A Tensor. Must be one of the following types: float16, float32. * @li gamma: A Tensor. Must be one of the following types: float16, float32. *@par Outputs: *Three outputs, including: * @li pd_x: A Tensor. Must be one of the following types: float16, float32. * @li pd_gamma: A Tensor. Must be one of the following types: float16, float32. * @li pd_beta: A Tensor. Must be one of the following types: float16, float32. */ REG_OP(LayerNormGrad) .INPUT(dy, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(x, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(variance, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(mean, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(gamma, TensorType({DT_FLOAT, DT_FLOAT16})) .OUTPUT(pd_x, TensorType({DT_FLOAT, DT_FLOAT16})) .OUTPUT(pd_gamma, TensorType({DT_FLOAT, DT_FLOAT16})) .OUTPUT(pd_beta, TensorType({DT_FLOAT, DT_FLOAT16})) .OP_END_FACTORY_REG(LayerNormGrad) /** *@brief LayerNormXBackprop operator interface implementation * calculating: dy, x, variance, mean, gamma * pd_xl = data_dy*data_gamma * pd_var = np.sum(((-0.5)*pd_xl*(data_x - data_mean) * np.power((data_variance + EPSLON), (-1.5))), * reduce_axis, keepdims=True) * pd_mean = np.sum(((-1.0)*pd_xl * np.power((data_variance + EPSLON), (-0.5))), * reduce_axis, keepdims=True) * + pd_var*(1.0/m) * np.sum(((-2.0)*(data_x - data_mean)), reduce_axis, keepdims=True) * pd_x = pd_xl*np.power((data_variance + EPSLON), (-0.5)) + * pd_var*(2.0/m)*(data_x - data_mean) + pd_mean*(1.0/m) * pd_gamma = np.sum((data_dy*(data_x - data_mean) * np.power((data_variance + EPSLON), (-0.5))), param_axis, keepdims=True) * pd_beta = np.sum(data_dy, param_axis, keepdims=True) *@par Inputs: *Three inputs, including: * @li dy: A Tensor. Must be one of the following types: float16, float32. * @li x: A Tensor. Must be one of the following types: float16, float32. * @li variance: A Tensor. Must be one of the following types: float16, float32. * @li mean: A Tensor. Must be one of the following types: float16, float32. * @li gamma: A Tensor. Must be one of the following types: float16, float32. *@par Outputs: *Three outputs, including: * @li pd_x: A Tensor. Must be one of the following types: float16, float32. */ REG_OP(LayerNormXBackprop) .INPUT(dy, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(x, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(variance, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(mean, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(gamma, TensorType({DT_FLOAT, DT_FLOAT16})) .OUTPUT(pd_x, TensorType({DT_FLOAT, DT_FLOAT16})) .OP_END_FACTORY_REG(LayerNormXBackprop) /** *@brief LayerNormBetaGammaBackprop operator interface implementation * calculating: dy, x, variance, mean * pd_xl = data_dy*data_gamma * pd_var = np.sum(((-0.5)*pd_xl*(data_x - data_mean) * np.power((data_variance + EPSLON), (-1.5))), * reduce_axis, keepdims=True) * pd_mean = np.sum(((-1.0)*pd_xl * np.power((data_variance + EPSLON), (-0.5))), * reduce_axis, keepdims=True) * + pd_var*(1.0/m) * np.sum(((-2.0)*(data_x - data_mean)), reduce_axis, keepdims=True) * pd_x = pd_xl*np.power((data_variance + EPSLON), (-0.5)) + * pd_var*(2.0/m)*(data_x - data_mean) + pd_mean*(1.0/m) * pd_gamma = np.sum((data_dy*(data_x - data_mean) * np.power((data_variance + EPSLON), (-0.5))), param_axis, keepdims=True) * pd_beta = np.sum(data_dy, param_axis, keepdims=True) *@par Inputs: *Three inputs, including: * @li dy: A Tensor. Must be one of the following types: float16, float32. * @li x: A Tensor. Must be one of the following types: float16, float32. * @li variance: A Tensor. Must be one of the following types: float16, float32. * @li mean: A Tensor. Must be one of the following types: float16, float32. *@par Outputs: *Three outputs, including: * @li pd_gamma: A Tensor. Must be one of the following types: float16, float32. * @li pd_beta: A Tensor. Must be one of the following types: float16, float32. */ REG_OP(LayerNormBetaGammaBackprop) .INPUT(dy, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(x, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(variance, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(mean, TensorType({DT_FLOAT, DT_FLOAT16})) .OUTPUT(pd_gamma, TensorType({DT_FLOAT, DT_FLOAT16})) .OUTPUT(pd_beta, TensorType({DT_FLOAT, DT_FLOAT16})) .REQUIRED_ATTR(shape_gamma, ListInt) .OP_END_FACTORY_REG(LayerNormBetaGammaBackprop) /** *@brief Return "output" according to the algorithm of dropout_do_mask: \n * scale_x = x *(1 / keep_prob) * output = select(mask == 1, scale_x, 0) *@par Inputs: *Three inputs, including: \n * @li x: A mutable Tensor. Must be one of the following types: * float16, float32 * @li mask: A mutable Tensor. Must met all of the following rules: * shape of mask should be 1D. * dtype of mask should be uint8. * value of shape should met the following algorithm: * value = (size(x) + 128 - 1) // 128 * 128 //8 * @li keep_prob: A mutable Tensor. Must met all of the following rules: * shape of "keep_prob" should be (1,) or [1,]. * Has the same type as "x". *@par Output: *y: A mutable Tensor. Has the same type as "x". */ REG_OP(DropOutDoMask) .INPUT(x, TensorType({DT_FLOAT, DT_FLOAT16})) .INPUT(mask, TensorType({DT_UINT8})) .INPUT(keep_prob, TensorType({DT_FLOAT, DT_FLOAT16})) .OUTPUT(y, TensorType({DT_FLOAT, DT_FLOAT16})) .OP_END_FACTORY_REG(DropOutDoMask) /** *@brief Scales the input. *@par Inputs: * Three inputs, including: *@li x: An ND tensor of type float16 or float32. *@li scale: An ND tensor of type float16 or float32. *@li bias: An ND tensor of type float16 or float32. *@par Attributes: *@li axis: An optional int32 used to compute the shape of scale and bias input from the online bottoms. Defaults to "1". *@par Outputs: *y: An ND tensor of type float16 or float32. *@attention Constraints:\n * Assume that the shape length of "x" is "n" and that of "scale" is "m". *@li "axis" is within the range [-n, n-1]. num_axes >= -1. *@li If "scale_from_blob = true", "num_axes = -1", and "axis >= 0", the ith axis of "scale" and the (i+"axis")th axis of "x" must have the same size (0 <= i < n-axis).\n * If "axis < 0", the ith axis of "scale" and the (i+n+"axis")th axis of "x" must have the same size (0 <= i < -axis). *@li If "scale_from_blob = true" and "num_axes = 0", "scale" is a scalar with shape length 1 and dimension size 1. *@li If "scale_from_blob = true", "num_axes > 0, and "axis >= 0", "axis + num_axes" must be less than or equal to "n" and the ith axis of "scale" and the (i+"axis")th axis of "x" must have the same size (0 <= i < num_axes).\n * If "axis < 0", "n + axis + num_axes" must be less than or equal to "n" and the ith axis of "scale" and the (i+n+"axis")th axis of "x" must have the same size (0 <= i < num_axes). *@li If "scale_from_blob = false", "scale" is not a scalar, and "axis >= 0","axis + m" must be less than or equal to "n" and the ith axis of "scale" and the (i+"axis")th axis of "x" must have the same size (0 <= i < m).\n * If "axis < 0", "n + axis + m" must be less than or equal to "n" and the ith axis of "scale" and the (i+n+"axis")th axis of "x" must have the same size (0 <= i < m). *@li If "bias" is not None, the constraints for "bias" is the same as that for "scale". */ REG_OP(Scale) .INPUT(x, TensorType({DT_FLOAT, DT_FLOAT16})) /* "First operand." */ .INPUT(scale, TensorType({DT_FLOAT, DT_FLOAT16})) /* "Second operand." */ .OPTIONAL_INPUT(bias, TensorType({DT_FLOAT, DT_FLOAT16})) /* "Third operand." */ .OUTPUT(y, TensorType({DT_FLOAT, DT_FLOAT16})) /* "Result, has same element type as x" */ .ATTR(axis, Int, 1) .ATTR(num_axes, Int, 1) .ATTR(scale_from_blob, Bool, true) .OP_END_FACTORY_REG(Scale) /** *@brief Local Response Normalization. *@par Inputs: *One input, including: *@li x: A Tensor. Must be 4-D shape, and only support the following types: float16, float32. *@par Attributes: * depth_radius = (local_size + 1) / 2. Defaults to "5". *@li bias: An optional float32. An offset, usually > 0 to avoid dividing by 0. * Defaults to "1". *@li alpha: An optional float32. A scaling factor, usually positive. * Defaults to "1". *@li norm_region: An optional string. A mode option. "ACROSS_CHANNELS":0, "WITHIN_CHANNEL":1. Defaults to "ACROSS_CHANNELS". *@par Outputs: *y: A Tensor. Has the same data type and shape as "x". */ REG_OP(LRN) .INPUT(x, TensorType({DT_FLOAT16,DT_FLOAT})) .OUTPUT(y, TensorType({DT_FLOAT16,DT_FLOAT})) .ATTR(depth_radius, Int, 5) .ATTR(bias, Float, 1.0) .ATTR(alpha, Float, 1.0) .ATTR(beta, Float, 0.5) .ATTR(norm_region, String, "ACROSS_CHANNELS") .OP_END_FACTORY_REG(LRN) /** * @brief Computes the gradient for Local Response Normalization. * @par Inputs: * @li grads: A 4D Tensor of type float16 or float32. * @li x: A 4D Tensor of type float16 or float32. * @li y: A 4D Tensor of type float16 or float32. * @par Attributes: * @li depth_radius: An optional int, specifying the half-width of the * normalization window. Defaults to "5". * @li bias: An optional float32. An offset, usually > 0 to avoid dividing by 0. * Defaults to "1". * @li alpha: An optional float32. A scaling factor, usually positive. * Defaults to "1". * @li beta: An optional float32. An exponent. Defaults to "0.5". * @par Outputs: * z: A Tensor. Has the same type and shape as "grads". * @attention Constraints: * "x" and "y" must have the same shape and type as "grads". */ REG_OP(LRNGrad) .INPUT(grads, TensorType({DT_FLOAT16,DT_FLOAT})) .INPUT(x, TensorType({DT_FLOAT16,DT_FLOAT})) .INPUT(y, TensorType({DT_FLOAT16,DT_FLOAT})) .OUTPUT(z, TensorType({DT_FLOAT16,DT_FLOAT})) .ATTR(depth_radius, Int, 5) .ATTR(bias, Float, 1.0) .ATTR(alpha, Float, 1.0) .ATTR(beta, Float, 0.5) .OP_END_FACTORY_REG(LRNGrad) /** *@brief Calculates the RNNT Loss (log probability) for each batch entry. \n Also calculates the gradient. *@par Inputs: *@li acts: 4-D, shape: `(batch x seqLength x labelLength x outputDim)`, the logits. *@li labels: 2-D Tensor containing all the targets of the batch with zero padded. *@li input_lengths: Tensor of size (batch) containing size of each output sequence. *@li label_lengths: Tensor of (batch) containing label length of each example. *@par Outputs: *@li costs: 1-D Tensor, the cost of each example in the batch. *@li grads: A Tensor. Has the same type as acts. *@par Attributes: *@li blank_label: An optional attribute. Defaults to 0. */ REG_OP(RNNTLoss) .INPUT(acts, TensorType({DT_FLOAT})) .INPUT(labels, TensorType({DT_INT32})) .INPUT(input_lengths, TensorType({DT_INT32})) .INPUT(label_lengths, TensorType({DT_INT32})) .ATTR(blank_label, Int, 0) .OUTPUT(costs, TensorType({DT_FLOAT})) .OUTPUT(grads, TensorType({DT_FLOAT})) .OP_END_FACTORY_REG(RNNTLoss) /** *@brief Performs group normalization. *@par Inputs:\n * Five inputs, including: (NHWC, NCHW supported) *@li x: A 4D Tensor of type float16 or float32, with format NHWC or \n NCHW for 4D. *@li scale: A Tensor of type float32. Must be 1D if input "x" is with format \n NHWC or NCHW. Specifies the scaling factor. *@li offset: A Tensor of type float32. Must be 1D if input "x" is with \n format NHWC or NCHW. Specifies the offset. *@li mean: A Tensor of type float32. Must be 1D if input "x" is with format \n NHWC or NCHW. Reserved. Mu st be "None" if the operation is used for training. *@li variance: A Tensor of type float32. Must be 1D if input "x" is with \n format NHWC or NCHW. Specifies the variance used for inference. Reserved. *@par Attributes: *@li epsilon: An optional float32, specifying the small value added to \n variance to avoid dividing by zero. Defaults to "0.0001". *@li data_format: An optional string, specifying the format of "x". \n Defaults to "NHWC". *@li is_training: An optional bool, specifying if the operation is used for \n training or inference. Defaults to "True". *@par Outputs:\n * Five outputs, including: (NHWC, NCHW supported) *@li y: A 4D Tensor of type float16 or float32 for the normalized "x", \n with format NHWC or NCHW for 4D. *@li batch_mean: A Tensor of type float32. Must be 1D if input "x" is with \n format NHWC or NCHW. Specifies the mean of "x". *@li batch_variance: A Tensor of type float32. Must be 1D if input "x" is \n with format NHWC or NCHW. Specifies the variance of "x". *@li reserve_space_1: An optional Tensor of type float32. Must be 1D if \n input "x" is with format NHWC or NCHW. Specifies the mean o f "x" for gradient computation. Pass "None" to skip this output. *@li reserve_space_2: An optional Tensor of type float32. Must be 1D if \n input "x" is with format NHWC or NCHW. Specifies the varian ce of "x" for gradient computation. Pass "None" to skip this output. *@attention Constraints: *@li If the operation is used for inference and outputs "reserve_space_1" \n and "reserve_space_2" are available, then "reserve_space_1" has the same \n value as "mean" and "reserve_spa ce_2" has the same value as "variance". *@li For Ascend 310, the result accuracy fails due to the square root \n instruction. */ REG_OP(GroupNorm) .INPUT(x, TensorType({DT_FLOAT16, DT_FLOAT})) .INPUT(scale, TensorType({DT_FLOAT,})) .INPUT(offset, TensorType({DT_FLOAT,})) .OPTIONAL_INPUT(mean, TensorType({DT_FLOAT})) .OPTIONAL_INPUT(variance, TensorType({DT_FLOAT})) .OUTPUT(y, TensorType({DT_FLOAT16, DT_FLOAT})) .OUTPUT(batch_mean, TensorType({DT_FLOAT})) .OUTPUT(batch_variance, TensorType({DT_FLOAT})) .OUTPUT(reserve_space_1, TensorType({DT_FLOAT})) .OUTPUT(reserve_space_2, TensorType({DT_FLOAT})) .ATTR(epsilon, Float, 0.0001) .ATTR(data_format, String, "NHWC") .ATTR(is_training, Bool, true) .ATTR(num_groups, Int, 2) .OP_END_FACTORY_REG(GroupNorm) } // namespace ge #endif //GE_OP_NN_NORM_OPS_H
42.133588
309
0.706797
[ "shape", "vector" ]
0495fd06c6183e8165108509f0318480ebe1aeed
2,046
h
C
mindspore/lite/src/huffman_decode.h
ZLkanyo009/mindspore
0a6ed86bb443ed233504fa7eee931a24637d50bb
[ "Apache-2.0" ]
2
2021-07-08T13:10:42.000Z
2021-11-08T02:48:57.000Z
mindspore/lite/src/huffman_decode.h
peixinhou/mindspore
fcb2ec2779b753e95c762cf292b23bd81d1f561b
[ "Apache-2.0" ]
null
null
null
mindspore/lite/src/huffman_decode.h
peixinhou/mindspore
fcb2ec2779b753e95c762cf292b23bd81d1f561b
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 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_LITE_MINDSPORE_LITE_SRC_HUFFMAN_DECODE_H_ #define MINDSPORE_LITE_MINDSPORE_LITE_SRC_HUFFMAN_DECODE_H_ #include <cstring> #include <utility> #include <string> #include <vector> #include "include/errorcode.h" #include "src/common/log_adapter.h" namespace mindspore { namespace lite { const int PSEUDO_EOF = 128; struct HuffmanNode { int key; unsigned int freq; std::string code; HuffmanNode *left, *right, *parent; }; using HuffmanNodePtr = HuffmanNode *; class HuffmanDecode { public: virtual ~HuffmanDecode() = default; static STATUS DoHuffmanDecode(const std::string &input_str, void *decoded_data); private: HuffmanDecode() = default; static void FreeHuffmanNodeTree(HuffmanNodePtr root); static STATUS RebuildHuffmanTree(std::string key, std::string code, const HuffmanNodePtr &root); static STATUS DoHuffmanDecompress(HuffmanNodePtr root, std::string encoded_data, std::string *decoded_str); static std::vector<std::string> Str2Vec(std::string s) { size_t i = 0; std::vector<std::string> vec; while (i < s.length()) { size_t j = i; while (j < s.length() && s[j] != ' ') { j++; } if (j != i) { vec.push_back(s.substr(i, j - i)); i = j + 1; } else { i = j; } } return vec; } }; } // namespace lite } // namespace mindspore #endif // MINDSPORE_LITE_MINDSPORE_LITE_SRC_HUFFMAN_DECODE_H_
25.898734
109
0.697947
[ "vector" ]
049b58740a97018fa7b0cb9022845c217a22c524
5,815
h
C
3rd/xulrunner-sdk/include/nsISAXLexicalHandler.h
ShoufuLuo/csaw
0d030d5ab93e61b62dff10b27a15c83fcfce3ff3
[ "Apache-2.0" ]
null
null
null
3rd/xulrunner-sdk/include/nsISAXLexicalHandler.h
ShoufuLuo/csaw
0d030d5ab93e61b62dff10b27a15c83fcfce3ff3
[ "Apache-2.0" ]
null
null
null
3rd/xulrunner-sdk/include/nsISAXLexicalHandler.h
ShoufuLuo/csaw
0d030d5ab93e61b62dff10b27a15c83fcfce3ff3
[ "Apache-2.0" ]
null
null
null
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/slave/rel-m-rel-xr-osx64-bld/build/parser/xml/public/nsISAXLexicalHandler.idl */ #ifndef __gen_nsISAXLexicalHandler_h__ #define __gen_nsISAXLexicalHandler_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsISAXLexicalHandler */ #define NS_ISAXLEXICALHANDLER_IID_STR "23c26a56-adff-440c-8caf-95c2dc2e399b" #define NS_ISAXLEXICALHANDLER_IID \ {0x23c26a56, 0xadff, 0x440c, \ { 0x8c, 0xaf, 0x95, 0xc2, 0xdc, 0x2e, 0x39, 0x9b }} class NS_NO_VTABLE NS_SCRIPTABLE nsISAXLexicalHandler : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISAXLEXICALHANDLER_IID) /* void comment (in AString chars); */ NS_SCRIPTABLE NS_IMETHOD Comment(const nsAString & chars) = 0; /* void startDTD (in AString name, in AString publicId, in AString systemId); */ NS_SCRIPTABLE NS_IMETHOD StartDTD(const nsAString & name, const nsAString & publicId, const nsAString & systemId) = 0; /* void endDTD (); */ NS_SCRIPTABLE NS_IMETHOD EndDTD(void) = 0; /* void startCDATA (); */ NS_SCRIPTABLE NS_IMETHOD StartCDATA(void) = 0; /* void endCDATA (); */ NS_SCRIPTABLE NS_IMETHOD EndCDATA(void) = 0; /* void startEntity (in AString name); */ NS_SCRIPTABLE NS_IMETHOD StartEntity(const nsAString & name) = 0; /* void endEntity (in AString name); */ NS_SCRIPTABLE NS_IMETHOD EndEntity(const nsAString & name) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsISAXLexicalHandler, NS_ISAXLEXICALHANDLER_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSISAXLEXICALHANDLER \ NS_SCRIPTABLE NS_IMETHOD Comment(const nsAString & chars); \ NS_SCRIPTABLE NS_IMETHOD StartDTD(const nsAString & name, const nsAString & publicId, const nsAString & systemId); \ NS_SCRIPTABLE NS_IMETHOD EndDTD(void); \ NS_SCRIPTABLE NS_IMETHOD StartCDATA(void); \ NS_SCRIPTABLE NS_IMETHOD EndCDATA(void); \ NS_SCRIPTABLE NS_IMETHOD StartEntity(const nsAString & name); \ NS_SCRIPTABLE NS_IMETHOD EndEntity(const nsAString & name); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSISAXLEXICALHANDLER(_to) \ NS_SCRIPTABLE NS_IMETHOD Comment(const nsAString & chars) { return _to Comment(chars); } \ NS_SCRIPTABLE NS_IMETHOD StartDTD(const nsAString & name, const nsAString & publicId, const nsAString & systemId) { return _to StartDTD(name, publicId, systemId); } \ NS_SCRIPTABLE NS_IMETHOD EndDTD(void) { return _to EndDTD(); } \ NS_SCRIPTABLE NS_IMETHOD StartCDATA(void) { return _to StartCDATA(); } \ NS_SCRIPTABLE NS_IMETHOD EndCDATA(void) { return _to EndCDATA(); } \ NS_SCRIPTABLE NS_IMETHOD StartEntity(const nsAString & name) { return _to StartEntity(name); } \ NS_SCRIPTABLE NS_IMETHOD EndEntity(const nsAString & name) { return _to EndEntity(name); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSISAXLEXICALHANDLER(_to) \ NS_SCRIPTABLE NS_IMETHOD Comment(const nsAString & chars) { return !_to ? NS_ERROR_NULL_POINTER : _to->Comment(chars); } \ NS_SCRIPTABLE NS_IMETHOD StartDTD(const nsAString & name, const nsAString & publicId, const nsAString & systemId) { return !_to ? NS_ERROR_NULL_POINTER : _to->StartDTD(name, publicId, systemId); } \ NS_SCRIPTABLE NS_IMETHOD EndDTD(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->EndDTD(); } \ NS_SCRIPTABLE NS_IMETHOD StartCDATA(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->StartCDATA(); } \ NS_SCRIPTABLE NS_IMETHOD EndCDATA(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->EndCDATA(); } \ NS_SCRIPTABLE NS_IMETHOD StartEntity(const nsAString & name) { return !_to ? NS_ERROR_NULL_POINTER : _to->StartEntity(name); } \ NS_SCRIPTABLE NS_IMETHOD EndEntity(const nsAString & name) { return !_to ? NS_ERROR_NULL_POINTER : _to->EndEntity(name); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsSAXLexicalHandler : public nsISAXLexicalHandler { public: NS_DECL_ISUPPORTS NS_DECL_NSISAXLEXICALHANDLER nsSAXLexicalHandler(); private: ~nsSAXLexicalHandler(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsSAXLexicalHandler, nsISAXLexicalHandler) nsSAXLexicalHandler::nsSAXLexicalHandler() { /* member initializers and constructor code */ } nsSAXLexicalHandler::~nsSAXLexicalHandler() { /* destructor code */ } /* void comment (in AString chars); */ NS_IMETHODIMP nsSAXLexicalHandler::Comment(const nsAString & chars) { return NS_ERROR_NOT_IMPLEMENTED; } /* void startDTD (in AString name, in AString publicId, in AString systemId); */ NS_IMETHODIMP nsSAXLexicalHandler::StartDTD(const nsAString & name, const nsAString & publicId, const nsAString & systemId) { return NS_ERROR_NOT_IMPLEMENTED; } /* void endDTD (); */ NS_IMETHODIMP nsSAXLexicalHandler::EndDTD() { return NS_ERROR_NOT_IMPLEMENTED; } /* void startCDATA (); */ NS_IMETHODIMP nsSAXLexicalHandler::StartCDATA() { return NS_ERROR_NOT_IMPLEMENTED; } /* void endCDATA (); */ NS_IMETHODIMP nsSAXLexicalHandler::EndCDATA() { return NS_ERROR_NOT_IMPLEMENTED; } /* void startEntity (in AString name); */ NS_IMETHODIMP nsSAXLexicalHandler::StartEntity(const nsAString & name) { return NS_ERROR_NOT_IMPLEMENTED; } /* void endEntity (in AString name); */ NS_IMETHODIMP nsSAXLexicalHandler::EndEntity(const nsAString & name) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsISAXLexicalHandler_h__ */
35.457317
200
0.759587
[ "object" ]
04a1b00cecd95b8aab33a3bbf1dc2c92515264b6
1,583
h
C
include/CQChartsPropertyViewTree.h
Qt-Widgets/CQCharts
0ee923c5a2794b9e3845d0d88fa519fcdea7694a
[ "MIT" ]
14
2018-05-22T15:06:08.000Z
2022-01-20T12:18:28.000Z
include/CQChartsPropertyViewTree.h
Qt-Widgets/CQCharts
0ee923c5a2794b9e3845d0d88fa519fcdea7694a
[ "MIT" ]
6
2020-09-04T15:49:24.000Z
2022-01-12T19:06:45.000Z
include/CQChartsPropertyViewTree.h
Qt-Widgets/CQCharts
0ee923c5a2794b9e3845d0d88fa519fcdea7694a
[ "MIT" ]
9
2019-04-01T13:10:11.000Z
2022-01-22T01:46:27.000Z
#ifndef CQChartsPropertyViewTree_H #define CQChartsPropertyViewTree_H #include <CQPropertyViewTree.h> class CQChartsViewSettings; class CQPropertyViewModel; class CQChartsEditTitleDlg; class CQChartsEditKeyDlg; class CQChartsEditAxisDlg; /*! * \brief Charts Property View Tree * \ingroup Charts */ class CQChartsPropertyViewTree : public CQPropertyViewTree { Q_OBJECT Q_PROPERTY(bool filterDisplayed READ isFilterDisplayed WRITE setFilterDisplayed) Q_PROPERTY(bool showStyleItems READ isShowStyleItems WRITE setShowStyleItems ) public: CQChartsPropertyViewTree(CQChartsViewSettings *settings, CQPropertyViewModel *model); void addMenuItems(QMenu *menu) override; void printItem(CQPropertyViewItem *item) const; bool isFilterDisplayed() const { return filterDisplayed_; } void setFilterDisplayed(bool visible, bool focus=false); bool isShowStyleItems() const { return showStyleItems_; } void setShowStyleItems(bool b); void keyPressEvent(QKeyEvent *e) override; signals: void filterStateChanged(bool show, bool focus); private slots: void editSlot(); void showHideFilterSlot(bool b); void showHideStyleItemsSlot(bool b); private: void showStyleItems(CQPropertyViewItem *item, bool show); private: CQChartsViewSettings *settings_ { nullptr }; CQChartsEditTitleDlg *titleDlg_ { nullptr }; CQChartsEditKeyDlg* keyDlg_ { nullptr }; CQChartsEditAxisDlg* axisDlg_ { nullptr }; bool filterDisplayed_ { false }; bool showStyleItems_ { true }; }; #endif
26.830508
87
0.753632
[ "model" ]
04a335791f51d3b5ea4c9a756ea613a5d0710690
8,641
h
C
tree/include/btree.h
raikken/data-struct-sample
24e4a3113991f81693156aa244b0e135d282e585
[ "MIT" ]
1
2019-12-07T02:42:48.000Z
2019-12-07T02:42:48.000Z
tree/include/btree.h
Raikkenon/data-struct-sample
24e4a3113991f81693156aa244b0e135d282e585
[ "MIT" ]
null
null
null
tree/include/btree.h
Raikkenon/data-struct-sample
24e4a3113991f81693156aa244b0e135d282e585
[ "MIT" ]
null
null
null
/** * @file: base_method.cpp * @author: xxx * @mail: xxx@yyy.com * @date 2019-11-16 17:16:52 * @brief **/ #include "base_method.h" #ifndef AVL_TREE_H__ #define AVL_TREE_H__ template<typename Key, typename Value, typename KeyofValue> class Node { public: typedef Key key_type; typedef Value value_type; typedef Node* node_ptr; vector<Value> vlist; vector<Node> clist; node_ptr parent; node_ptr left; node_ptr right; int ways; Node(ways):ways(ways){}; value_type get_max_value(); value_type get_min_value(); bool full(); bool isleaf(); } template<typename Key, typename Value, typename KeyofValue> bool Node::isleaf(){ return (this->clist.size() == 0) } template<typename Key, typename Value, typename KeyofValue> value_type Node::get_max_value(){ int len = vlist.size(); return this->vlist.at(len-1); } template<typename Key, typename Value, typename KeyofValue> value_type Node::get_min_value(){ return this->vlist.at(0); } template<typename Key, typename Value, typename KeyofValue> bool Node::full(){ return (this->vlist.size() == this->ways); } template<typename Key, typename Value, typename KeyofValue, typename Compare> class BTree { public: typedef Key key_type; typedef Value value_type; typedef Value& reference; typedef const Value& const_reference; typedef Node<Key, Value, KeyofValue>* node_pointer; node_pointer header; node_pointer root; int ways; BTree(ways) { node_pointer root = new Node<Key, Value, KeyofValue>(ways); this->ways = ways; this->root = root; } //insert void insert(value_type val); //删除 void delete(value_type val); //分裂节点 node_pointer split(node_pointer xptr); //从左邻节点借值 void borrow_from_value(node_pointer xptr, int index); //从右邻节点借值 void borrow_from_value(node_pointer xptr, int index); //merge节点,默认和左节点merge void merge_node(node_pointer xptr, int index); //获取后继节点 static node_pointer get_post_node(node_pointer xptr); } /** *@desc 分裂节点,分裂主逻辑如下: * 1. 新创建节点, 保留待分裂节点中(mid, full)元素。子节点同里 * 2. 待分裂节点, 保留待分裂节点中(0, mid) 元素,子元素同里 * 3. 中位数mid元素被添加至父节点中 * 若待分裂节点为根节点, 因根节点没有父节点,则需要新创建根节点 */ template<typename Key, typename Value, typename KeyofValue, typename Compare> node_pointer BTree::split(node_pointer xptr){ node_pointer newxptr = new Node(this->ways);//新创建节点 int full = this->ways - 1;// 节点的满载个数为 阶数 - 1 int mid = full/2; //中间节点 splice(&(this->vlist), &(newxptr->vlist), mid+1, (full - mid -1)); splice(&(this->clist), &(newxptr->clist), mid+1, (this->ways - mid-1)); if (newxptr->clist.size() > 0) { //重置父节点 for (vector<Node>::iterator start = newxptr->clist.begin(); start < newxptr->vlist.end(); start++) { start->parent = newxptr; } } if (xptr == this->root) {//待分裂节点为根节点 node_pointer newrootptr = new Node(this->ways); newrootptr->vlist.emplace_back(this->vlist[mid]); newrootptr->clist.emplace_back(xptr); newrootptr->clist.emplace_back(newxptr); xptr->parent = newrootptr; newxptr->parent = newrootptr; } else {//待分裂节点为非根节点 int index = findIndex(&(xptr->parent->clist), xptr); xptr->parent->vlist.insert(xptr->parent->vlist.begin()+index, xptr->vlist[mid]); xptr->parent->clist.insert(xptr->parent->vlist.begin()+index+1, newxptr); } xptr->vlist.erase(xptr->vlist.begin() + mid, xptr->vlist.begin() + mid + 1); return xptr->parent; } /** *@desc 插入值, 递归插入 */ template<typename Key, typename Value, typename KeyofValue, typename Compare> void BTree::insert(node_pointer xptr, value_type val) { node_pointer xptr = (xptr == nullptr)? this->root: xptr; if (xptr->full()) {//当节点满载时,则先分裂节点再进行添加 this->insert(this->split(xptr), val); } else { if (xptr->vlist.size() == 0) { xptr->vlist.emplace_back(val); } else { int pos = findPos(xptr->vlist, val);//查询节点所在区间 if (xptr->leaf()){//叶子节点, 新增元素 xptr->vlist->insert(pos, val); } else {//非叶子节点递归插入 this->insert(xptr->clist[pos], val); } } } } template<typename Key, typename Value, typename KeyofValue, typename Compare> node_pointer Btree::get_post_node(node_pointer xptr){ while(xptr->clist.size() > 0) { xptr = xptr->clist[0]; } return xptr; } //从左节点处借值 template<typename Key, typename Value, typename KeyofValue, typename Compare> void Btree::borrow_from_left(node_pointer xptr, int index){ Value xparentval = xptr->vlist[index]; int leftvlistlen = xptr->clist[index].vlist.size(); xptr->vlist[index] = xptr->clist[index].vlist[leftvlistlen-1]; xptr->clist[index].vlist.earse(leftvlistlen-1); xptr->clist[index+1].vlist.insert(0, xparentval); } //从右节点处借值 template<typename Key, typename Value, typename KeyofValue, typename Compare> void Btree::borrow_from_right(node_pointer xptr, int index){ Value xparentval = xptr->vlist[index]; //int leftvlistlen = xptr->clist[index].vlist.size(); xptr->vlist[index] = xptr->clist[index+1].vlist[0]; xptr->clist[index+1].vlist.erase(0); xptr->clist[index].vlist.push_back(xparentval); } //merge左节点: template<typename Key, typename Value, typename KeyofValue, typename Compare> void Btree::merge_leftnode(node_pointer xptr, int index) { Value xmiddleValue = xptr->vlist[index-1]; xptr->vlist.erase(index-1); node_pointer xleftptr = xptr->clist[index-1]; xleftptr->vlist.push_back(xmiddleValue); xleftptr->vlist.merge(xptr->clist[index].vlist); delete xptr->clist[index]; xptr->clist.erase(index); } //merge右节点: template<typename Key, typename Value, typename KeyofValue, typename Compare> void Btree::merge_rightnode(node_pointer xptr, int index) { Value xmiddleValue = xptr->vlist[index]; xptr->vlist.erase(index); node_pointer xrightptr = xptr->clist[index+1]; xrightptr->vlist.insert(0, xmiddleValue); for (int i=0; i < xptr->clist[index].vlist.size(); i++){ xrightptr->vlist.insert(0, xptr->clist[index].vlist[i]); } delete xptr->clist[index]; xptr->clist.erase(index); } //rebalance template<typename Key, typename Value, typename KeyofValue, typename Compare> void Btree::rebalance(node_pointer xptr, int index) { int minlen = this->ways/2; int fulllen = this->ways - 1; node_pointer xrealptr = xptr->clist[index]; bool xrealstatus = xptr->clist[index].vlist.size() >= minlen; if (xrealstatus) { return ; } //删除值后, 节点值缺失 bool xleftvlistover = xptr->clist[index-1].vlist.size() > minlen; bool xrightvlistover = xptr->clist[index+1].vlist.size() > minlen; if (index == 0) {//如果为首节点 if (xrightvlistover) { borrow_from_right(xptr->clist[index], index); } else { merge_rightnode(xptr, index); } return ; } //左邻节点有节点富余 if (xleftvlistover) { borrow_from_left(xptr->clist[index], index); } else { //左右节点均无节点富余, 默认选择和左邻节点merge merge_leftnode(xptr, index); } } /** *@desc 删除 */ template<typename Key, typename Value, typename KeyofValue, typename Compare> void Btree::delete(node_pointer xrootptr, Value value) { node_pointer xptr = (xptr == nullptr) ? this->root: xptr; int index = findPos(xptr.vlist, value); //节点中最大容量 int fulllen = this->ways - 1; //节点中最小容量 int mixlen = this->ways/2; int vlistlen = this->vlist.size(); if (!xptr->leaf()) {//当前节点为非叶子节点 // 待删除的值 在非叶子节点中 if (index < vlistlen && Compare(xptr->vlist[index], value) == 0) { //寻找后继,进行替换 node_pointer xpostnodeptr = Btree::get_post_node(this->vlist[index+1]); xptr->vlist[index] = xpostnodeptr->vlist[0]; delete(xptr->clist[index+1], xpostnodeptr->vlist[0]); rebalance(xptr, index + 1); } else { //待删除的值不在当前非叶子节点中 delete(xptr->clist[index], value); rebalance(xptr, index); } } else { //待删除的值在叶子节点中, 直接删除该值 if (Compare(xptr->vlist[index], value) == 0) { xptr->vlist.earse(this->vlist[index].begin()+index, this->vlist[index].begin()+index+1); } else { //待删除的值,并不存在 return nullptr; } } } #endif
29.192568
108
0.624118
[ "vector" ]
04a474b37e52c213d129fca126025f02f42b7f9b
722
c
C
src/rmutil/test_heap.c
maguec/RediSearch
c6ecf9de36b7aa5f3603ead7c8fc18c330882668
[ "MIT", "Ruby", "Apache-2.0", "BSD-3-Clause" ]
2,098
2019-05-13T09:11:54.000Z
2022-03-31T06:24:50.000Z
src/rmutil/test_heap.c
maguec/RediSearch
c6ecf9de36b7aa5f3603ead7c8fc18c330882668
[ "MIT", "Ruby", "Apache-2.0", "BSD-3-Clause" ]
1,659
2019-05-13T07:55:29.000Z
2022-03-31T02:42:57.000Z
src/rmutil/test_heap.c
maguec/RediSearch
c6ecf9de36b7aa5f3603ead7c8fc18c330882668
[ "MIT", "Ruby", "Apache-2.0", "BSD-3-Clause" ]
227
2019-05-17T07:54:49.000Z
2022-03-28T03:50:19.000Z
#include <stdio.h> #include "heap.h" #include "assert.h" #include "redismodule.h" #include "alloc.h" int cmp(void *a, void *b) { int *__a = (int *)a; int *__b = (int *)b; return *__a - *__b; } int main(int argc, char **argv) { RMUTil_InitAlloc(); int myints[] = {10, 20, 30, 5, 15}; Vector *v = NewVector(int, 5); for (int i = 0; i < 5; i++) { Vector_Push(v, myints[i]); } Make_Heap(v, 0, v->top, cmp); int n; Vector_Get(v, 0, &n); assert(30 == n); Heap_Pop(v, 0, v->top, cmp); v->top = 4; Vector_Get(v, 0, &n); assert(20 == n); Vector_Push(v, 99); Heap_Push(v, 0, v->top, cmp); Vector_Get(v, 0, &n); assert(99 == n); Vector_Free(v); printf("PASS!\n"); return 0; }
17.609756
37
0.549861
[ "vector" ]
04a75a0a4db08ee6547b83e055e51302b8206dd8
763
h
C
data/test/cpp/04a75a0a4db08ee6547b83e055e51302b8206dd8model.h
harshp8l/deep-learning-lang-detection
2a54293181c1c2b1a2b840ddee4d4d80177efb33
[ "MIT" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
data/test/cpp/04a75a0a4db08ee6547b83e055e51302b8206dd8model.h
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
5
2018-03-29T11:50:46.000Z
2021-04-26T13:33:18.000Z
data/test/cpp/04a75a0a4db08ee6547b83e055e51302b8206dd8model.h
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
24
2017-11-22T08:31:00.000Z
2022-03-27T01:22:31.000Z
#ifndef __THERMAL_MODEL_H__ #define __THERMAL_MODEL_H__ #include "source/models/model_type.h" #include "source/misc/common_types.h" #include "source/misc/config_parser.h" namespace Thermal { class Model { public: virtual ~Model(); static Model* createModel(ModelType model_type); virtual std::string getModelName() = 0; virtual void startup() = 0; virtual void execute(Time scheduled_time) = 0; protected: // Child classes must call this constructor Model(); ConfigParser* _config; bool _ready_to_execute; Time _last_execute_time; private: }; // class Model } // namespace Thermal #endif // __THERMAL_MODEL_H__
20.078947
61
0.627785
[ "model" ]
04a91f5e182d97ea03b023c3a28067c8c68b072e
13,974
h
C
src/monosat/dgl/Dinics.h
copumpkin/monosat
cbaf79cfd01cba97b46cae5a9d7b832771ff442c
[ "MIT" ]
1
2021-11-11T14:01:44.000Z
2021-11-11T14:01:44.000Z
src/monosat/dgl/Dinics.h
copumpkin/monosat
cbaf79cfd01cba97b46cae5a9d7b832771ff442c
[ "MIT" ]
null
null
null
src/monosat/dgl/Dinics.h
copumpkin/monosat
cbaf79cfd01cba97b46cae5a9d7b832771ff442c
[ "MIT" ]
1
2021-11-11T14:01:34.000Z
2021-11-11T14:01:34.000Z
/************************************************************************************************** The MIT License (MIT) Copyright (c) 2014, Sam Bayless 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. **************************************************************************************************/ #ifndef DINICS_H #define DINICS_H #include "Graph.h" #include "MaxFlow.h" #include <vector> #include "monosat/core/Config.h" #include "EdmondsKarpAdj.h" #include <algorithm> #include <climits> namespace dgl { template<typename Weight = int> class Dinitz: public MaxFlow<Weight> { public: std::vector<Weight> F; struct LocalEdge { int from; int id; bool backward = false; LocalEdge(int from = -1, int id = -1, bool backward = false) : from(from), id(id), backward(backward) { } }; Weight curflow; int last_modification; int last_deletion; int last_addition; bool opt_dinics_recursive = false; int history_qhead; int last_history_clear; std::vector<LocalEdge> prev; std::vector<Weight> M; std::vector<int> dist; std::vector<int> pos; //position in the combined forward and backward adjacency list of each node in the DFS. std::vector<bool> changed; Graph<Weight>& g; int src=-1; int dst=-1; int source = -1; int sink = -1; Weight INF; std::vector<int> Q; int64_t stats_augmenting_rounds = 0; int64_t stats_rounds = 0; #ifdef DEBUG_MAXFLOW std::vector<int> dbg_pos; EdmondsKarpAdj<Capacity,Weight> ek; #endif public: Dinitz(Graph<Weight> & _g,int source = -1, int sink = -1) : g(_g), source(source), sink(sink), INF(0xF0F0F0) #ifdef DEBUG_MAXFLOW ,ek(_g,cap,source,sink) #endif { curflow = 0; last_modification = -1; last_deletion = -1; last_addition = -1; history_qhead = -1; last_history_clear = -1; //setAllEdgeCapacities(1); } int getSource() const override{ return source; } int getSink() const override { return sink; } void printStats() override{ printf("Dinics :\n"); printf("Rounds: %" PRId64 ", Augmenting Rounds: %" PRId64 "\n", stats_rounds, stats_augmenting_rounds); } void setCapacity(int u, int w, Weight c) { //C.resize(g.edges()); //C[ ]=c; } void setAllEdgeCapacities(Weight c) { } void dbg_print_graph(int from, int to) { #ifdef DEBUG_DGL return; static int it = 0; if (++it == 6) { int a = 1; } printf("Graph %d\n", it); printf("digraph{\n"); for (int i = 0; i < g.nodes(); i++) { if (i == from) { printf("n%d [label=\"From\", style=filled, fillcolor=blue]\n", i); } else if (i == to) { printf("n%d [label=\"To\", style=filled, fillcolor=red]\n", i); } else printf("n%d\n", i); } for (int i = 0; i < g.edges(); i++) { if (g.edgeEnabled(i)) { auto & e = g.getEdge(i); const char * s = "black"; if (dist[e.to] == dist[e.from] + 1) { s = "blue"; } /*if(value(e.v)==l_True) s="blue"; else if (value(e.v)==l_False) s="red";*/ std::cout << "n" << e.from << " -> n" << e.to << " [label=\"" << i << ": " << F[i] << "/" << g.getWeight(i) << "\" color=\"" << s << "\"]\n"; } } printf("}\n"); #endif } bool buildLevelGraph(int src, int dst) { dist.clear(); dist.resize(g.nodes(), -1); dist[src] = 0; Q.push_back(src); //Build the level graph using a simple BFS for (int i = 0; i < Q.size(); i++) { int u = Q[i]; for (int j = 0; j < g.nIncident(u); j++) { int edgeID = g.incident(u, j).id; if (!g.edgeEnabled(edgeID)) continue; int v = g.incident(u, j).node; if (dist[v] < 0 && F[edgeID] < g.getWeight(edgeID)) { dist[v] = dist[u] + 1; Q.push_back(v); } } for (int j = 0; j < g.nIncoming(u); j++) { int edgeID = g.incoming(u, j).id; if (!g.edgeEnabled(edgeID)) continue; int v = g.incoming(u, j).node; //this is a backward edge, so it has capacity exactly if the forward edge has flow if (dist[v] < 0 && F[edgeID]>0) { dist[v] = dist[u] + 1; Q.push_back(v); } } } Q.clear(); return dist[dst] >= 0; } Weight findAugmentingPath(int u) { Weight m = 0; assert(Q.size() == 0); Q.push_back(src); M[src] = INT_MAX; //this isn't safe for other types than int, fix this... while (Q.size()) { int u = Q.back(); if (u == dst) return M[u]; bool found = false; for (; pos[u] < g.nIncident(u); pos[u]++) { //int edgeID = g.adjacency[u][pos[u]].id; int edgeID = g.incident(u, pos[u]).id; if (!g.edgeEnabled(edgeID)) continue; int v = g.incident(u, pos[u]).node; if (dist[v] == dist[u] + 1 && F[edgeID] < g.getWeight(edgeID)) { //printf("%d\n",edgeID); found = true; Weight c = g.getWeight(edgeID) - F[edgeID]; M[v] = std::min(M[u], c); prev[v] = LocalEdge(u, edgeID, false); if (v == dst) { //M[v] = min(M[u], g.getWeight(edgeID) - F[id]); m = M[dst]; assert(Q.back() == u); Q.pop_back(); while (Q.size()) { pos[Q.back()]--; Q.pop_back(); } //pos[u]++; break; } else { Q.push_back(v); pos[u]++; break; } } } if (!found) { for (; pos[u] - g.nIncident(u) < g.nIncoming(u); pos[u]++) { //int edgeID = g.inverted_adjacency[u][pos[u]-g.nIncident(u)].id; int edgeID = g.incoming(u, pos[u] - g.nIncident(u)).id; if (!g.edgeEnabled(edgeID)) continue; int v = g.incoming(u, pos[u] - g.nIncident(u)).node; //these are backwards edges, which have capacity exactly if the forward edge has non-zero flow if (dist[v] == dist[u] + 1 && F[edgeID]>0) { //printf("-%d\n",edgeID); found = true; M[v] = std::min(M[u], F[edgeID]); prev[v] = LocalEdge(u, edgeID, true); //this is a backward edge if (v == dst) { m = M[dst]; assert(Q.back() == u); while (Q.size()) { pos[Q.back()]--; Q.pop_back(); } break; } else { Q.push_back(v); pos[u]++; break; } } } } if (!found) { Q.pop_back(); } } Q.clear(); if (m > 0) { //we found an augmenting flow, so update all the edge flows correspondingly. int v = dst; while (v != src) { int u = prev[v].from; int id = prev[v].id; if (prev[v].backward) { F[id] = F[id] - m; } else F[id] = F[id] + m; v = u; } } return m; } Weight dbg_findAugmentingPath_recursive(int u, Weight f) { #ifdef DEBUG_MAXFLOW if (u == dst) return f; for (;dbg_pos[u]<g.nIncident(u);dbg_pos[u]++) { int edgeID = g.incident(u,dbg_pos[u]).id; if(!g.edgeEnabled(edgeID)) continue; int v = g.incident(u,dbg_pos[u]).node; if (dist[v] == dist[u] + 1 && F[edgeID] < g.getWeight(edgeID)) { int df = dbg_findAugmentingPath_recursive(v, min(f, g.getWeight(edgeID) - F[edgeID])); if (df > 0) { //F[edgeID] += df; return df; } } } for (;dbg_pos[u]-g.nIncident(u) <g.nIncoming(u);dbg_pos[u]++) { int edgeID = g.incoming(u,dbg_pos[u]-g.nIncident(u)).id; if(!g.edgeEnabled(edgeID)) continue; int v = g.incoming(u,dbg_pos[u]-g.nIncident(u)).node; //these are backwards edges, which have capacity exactly if the forward edge has non-zero flow if (dist[v] == dist[u] + 1 && F[edgeID]>0) { int df = dbg_findAugmentingPath_recursive(v, std::min(f, F[edgeID])); if (df > 0) { //F[edgeID] -= df; return df; } } } #endif return 0; } Weight findAugmentingPath_recursive(int u, Weight f) { if (u == dst) return f; for (; pos[u] < g.nIncident(u); pos[u]++) { //int edgeID = g.adjacency[u][pos[u]].id; int edgeID = g.incident(u, pos[u]).id; if (!g.edgeEnabled(edgeID)) continue; int v = g.incident(u, pos[u]).node; if (dist[v] == dist[u] + 1 && F[edgeID] < g.getWeight(edgeID)) { //printf("%d\n",edgeID); Weight c = g.getWeight(edgeID) - F[edgeID]; Weight df = findAugmentingPath_recursive(v, std::min(f, c)); if (df > 0) { F[edgeID] += df; return df; } } } for (; pos[u] - g.nIncident(u) < g.nIncoming(u); pos[u]++) { //int edgeID = g.inverted_adjacency[u][pos[u]-g.nIncident(u)].id; int edgeID = g.incoming(u, pos[u] - g.nIncident(u)).id; if (!g.edgeEnabled(edgeID)) continue; int v = g.incoming(u, pos[u] - g.nIncident(u)).node; //these are backwards edges, which have capacity exactly if the forward edge has non-zero flow if (dist[v] == dist[u] + 1 && F[edgeID]>0) { //printf("-%d\n",edgeID); Weight df = findAugmentingPath_recursive(v, std::min(f, F[edgeID])); if (df > 0) { F[edgeID] -= df; return df; } } } return 0; } int64_t num_updates = 0; int numUpdates() const override { return num_updates; } const Weight update() override{ return maxFlow(source, sink); } std::vector<int> changed_edges; std::vector<int> & getChangedEdges()override { return changed_edges; } void clearChangedEdges()override { for (int edgeID : changed_edges) { assert(changed[edgeID]); changed[edgeID] = false; } changed_edges.clear(); } private: void markChanged(int edgeID) { if (!changed[edgeID]) { changed[edgeID] = true; changed_edges.push_back(edgeID); } } public: void setSource(int s) override{ if (source == s) { return; } source = s; last_modification = g.getCurrentHistory() - 1; } void setSink(int t) override{ if (sink == t) { return; } sink = t; last_modification = g.getCurrentHistory() - 1; } const Weight maxFlow(int s, int t) override{ Weight f = 0; if (g.outfile()) { fprintf(g.outfile(), "f %d %d\n", s, t); fflush(g.outfile()); } if (last_modification > 0 && g.getCurrentHistory() == last_modification) { return curflow; } src = s; dst = t; F.clear(); F.resize(g.edges()); dist.clear(); dist.resize(g.nodes()); M.resize(g.nodes()); prev.resize(g.nodes()); changed.resize(g.nEdgeIDs()); f = 0; dbg_print_graph(s, t); while (buildLevelGraph(s, t)) { dbg_print_graph(s, t); stats_rounds++; pos.clear(); pos.resize(g.nodes()); #ifdef DEBUG_MAXFLOW dbg_pos.clear();dbg_pos.resize(g.nodes()); #endif if (opt_dinics_recursive) { while (Weight delta = findAugmentingPath_recursive(s, INF)) { stats_augmenting_rounds++; f += delta; dbg_print_graph(s, t); } } else { //int expect = dbg_findAugmentingPath_recursive(s,INT_MAX); while (Weight delta = findAugmentingPath(s)) { //assert(delta==expect); f += delta; stats_augmenting_rounds++; dbg_print_graph(s, t); //expect = dbg_findAugmentingPath_recursive(s,INT_MAX); } } } #ifdef DEBUG_MAXFLOW Weight expected_flow =ek.maxFlow(s,t); assert(f==expected_flow); #endif //dbg_print_graph(s,t); curflow = f; num_updates++; last_modification = g.getCurrentHistory(); last_deletion = g.nDeletions(); last_addition = g.nAdditions(); history_qhead = g.historySize(); last_history_clear = g.nHistoryClears(); return f; } std::vector<bool> seen; std::vector<bool> visited; const Weight minCut(std::vector<MaxFlowEdge> & cut) override{ return minCut(source, sink, cut); } const Weight minCut(int s, int t, std::vector<MaxFlowEdge> & cut) { const Weight f = maxFlow(s, t); //ok, now find the cut Q.clear(); Q.push_back(s); seen.clear(); seen.resize(g.nodes()); seen[s] = true; cut.clear(); /* if(f==0) return 0;*/ //explore the residual graph for (int j = 0; j < Q.size(); j++) { int u = Q[j]; for (int i = 0; i < g.nIncident(u); i++) { if (!g.edgeEnabled(g.incident(u, i).id)) continue; int v = g.incident(u, i).node; int id = g.incident(u, i).id; if (g.getWeight(id) - F[id] == 0) { cut.push_back(MaxFlowEdge { u, v, id }); //potential element of the cut } else if (!seen[v]) { Q.push_back(v); seen[v] = true; } } for (int i = 0; i < g.nIncoming(u); i++) { if (!g.edgeEnabled(g.incoming(u, i).id)) continue; int v = g.incoming(u, i).node; int id = g.incoming(u, i).id; if (F[id] == 0) { } else if (!seen[v]) { Q.push_back(v); seen[v] = true; } } } //Now keep only the edges from a seen vertex to an unseen vertex int i, j = 0; for (i = 0; i < cut.size(); i++) { if (!seen[cut[i].v] && seen[cut[i].u]) { cut[j++] = cut[i]; } } cut.resize(j); #ifdef DEBUG_DGL Weight dbg_sum = 0; for (int i = 0; i < cut.size(); i++) { int id = cut[i].id; assert(F[id] == g.getWeight(id)); dbg_sum += F[id]; } assert(dbg_sum == f); #endif return f; } const Weight getEdgeCapacity(int id) override{ assert(g.edgeEnabled(id)); return g.getWeight(id); } const Weight getEdgeFlow(int id) override{ assert(g.edgeEnabled(id)); return F[id]; // reserve(id); } const Weight getEdgeResidualCapacity(int id) override{ assert(g.edgeEnabled(id)); return g.getWeight(id) - F[id]; // reserve(id); } }; } ; #endif
25.925788
111
0.585874
[ "vector" ]
04a95ae300d91543b2cb5bd04838b497852bb804
3,966
c
C
patchsum.c
philpem/riscos-romtools
22fa6945b561f5bd4874204bd43eb3d5884a3180
[ "Apache-2.0" ]
3
2020-07-12T18:23:28.000Z
2020-09-15T12:34:42.000Z
patchsum.c
philpem/riscos-romtools
22fa6945b561f5bd4874204bd43eb3d5884a3180
[ "Apache-2.0" ]
null
null
null
patchsum.c
philpem/riscos-romtools
22fa6945b561f5bd4874204bd43eb3d5884a3180
[ "Apache-2.0" ]
null
null
null
/** * Patchsum -- a tool to fix RISC OS 3.1x ROM headers and footers. * * Based on Bigsplit2 and CRC by Acorn, released by RISC OS Open Ltd: * https://gitlab.riscosopen.org/RiscOS/Utilities/Release/bigsplit2 */ #include <stdio.h> #include <stdint.h> /* A fundamental constant of the CRC algorithm */ #define CRC_MAGIC 0xA001 /* I don't think you'll want to change this one */ #define CRC_TABLE_SIZE (1<<8) /* CRC table to speed up CRC calculation */ static uint16_t crc_table[CRC_TABLE_SIZE]; /* CRC accumulator */ static uint16_t crc_acc[4] = {0,0,0,0}; /// Create CRC table, must be called at startup static void make_crc_table(void) { int i,j; uint16_t crc; for(i=0;i<CRC_TABLE_SIZE;i++) { crc=i; for(j=0;j<8;j++) crc=(crc>>1)^(crc&1?CRC_MAGIC:0); crc_table[i]=crc; }; } // Update the CRC with a 4-byte quad static void update_crc_quad(const uint8_t *quad) { for (int i=0; i<4; i++) { crc_acc[i] ^= (quad[i] & 0xFF); crc_acc[i] = (crc_acc[i] >> 8) ^ crc_table[crc_acc[i] & 0xff]; } } int main(int argc, char **argv) { uint32_t csum = 0; uint8_t bytes[4]; FILE *fp; if (argc == 1) { fprintf(stderr, "syntax: patchsum romfile\n"); return -1; } fp = fopen(argv[1], "r+b"); if (fp == NULL) { fprintf(stderr, "cannot open input file\n"); return -1; } make_crc_table(); // get the filesize fseek(fp, 0, SEEK_END); size_t romsize = ftell(fp); fseek(fp, 0, SEEK_SET); // Check ROM size is a multiple of the RISC OS word size if ((romsize % 4) != 0) { fprintf(stderr, "Input file length is not a multple of 4.\n" "The ROM file must be padded to a multiple of 4 bytes, with a minimum of\n" "12 spare bytes at the EOF for the checksums.\n"); return -1; } // // The RISC OS ROM starts with a header which looks like this: // // * 4-byte jump to startup code // * 4-byte ROM length (little endian) // * 4-byte pointer to code vector table // * 4-byte pointer to data vector table // * 4-byte pointer to branch table // * Three unused words which encode branches to the start of ROM. // // The vector tables are used to allow downloaded selftest code to use the ROM selftest subroutines. // // We need to patch the ROM length or the selftest will miscalculate the ROM checksum and fail to boot. // // Source: https://gitlab.riscosopen.org/RiscOS/Sources/Kernel/-/blob/RO_3_60/OldTestSrc/Begin#L149 // // patch ts_Rom_length printf("Setting ts_Rom_length to 0x%08lX (%lu bytes = %lu MiB)\n", romsize, romsize, romsize / 1048576); fseek(fp, 4, SEEK_SET); bytes[0] = romsize & 0xFF; bytes[1] = (romsize >> 8) & 0xFF; bytes[2] = (romsize >> 16) & 0xFF; bytes[3] = (romsize >> 24) & 0xFF; fwrite(&bytes, 1, 4, fp); ///////////////// // Checksum recalculation ///////////////// // back to the start again... fseek(fp, 0, SEEK_SET); // ignore the last 3x 32-bit words in ROM romsize -= (3*4); // checksum time! while (romsize > 0) { romsize -= 4; fread(&bytes, 1, 4, fp); csum += ((uint32_t)bytes[0]) | ((uint32_t)bytes[1] << 8) | ((uint32_t)bytes[2] << 16) | ((uint32_t)bytes[3] << 24); // update the CRC too update_crc_quad(bytes); } // calculate the expected checksum csum = 0-csum; // convert to bytes and write printf("Patching additive checksum...\n"); bytes[0] = csum & 0xFF; bytes[1] = (csum >> 8) & 0xFF; bytes[2] = (csum >> 16) & 0xFF; bytes[3] = (csum >> 24) & 0xFF; fwrite(&bytes, 1, 4, fp); // update the CRC with the additive checksum update_crc_quad(bytes); // status message and print the CRC printf("Patching CRC...\n"); for (int i=0; i<4; i++) { printf(" crc[%d] = 0x%04X\n", i, crc_acc[i]); } // patch the CRC for (int i=0; i<4; i++) { bytes[i] = crc_acc[i] & 0xFF; } fwrite(&bytes, 1, 4, fp); for (int i=0; i<4; i++) { bytes[i] = (crc_acc[i] >> 8) & 0xFF; } fwrite(&bytes, 1, 4, fp); // and... done! fclose(fp); return 0; }
23.607143
104
0.619264
[ "vector" ]
04ac6b32baf7c6d7b8c04bf8d419c94e7bd31fa4
4,769
h
C
views/window/window_delegate.h
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
2
2017-09-02T19:08:28.000Z
2021-11-15T15:15:14.000Z
views/window/window_delegate.h
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
null
null
null
views/window/window_delegate.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 VIEWS_WINDOW_WINDOW_DELEGATE_H_ #define VIEWS_WINDOW_WINDOW_DELEGATE_H_ #pragma once #include <string> #include "base/scoped_ptr.h" #include "views/accessibility/accessibility_types.h" class SkBitmap; namespace gfx { class Rect; } namespace views { class ClientView; class DialogDelegate; class View; class Window; /////////////////////////////////////////////////////////////////////////////// // // WindowDelegate // // WindowDelegate is an interface implemented by objects that wish to show a // Window. The window that is displayed uses this interface to determine how // it should be displayed and notify the delegate object of certain events. // /////////////////////////////////////////////////////////////////////////////// class WindowDelegate { public: WindowDelegate(); virtual ~WindowDelegate(); virtual DialogDelegate* AsDialogDelegate() { return NULL; } // Returns true if the window can ever be resized. virtual bool CanResize() const { return false; } // Returns true if the window can ever be maximized. virtual bool CanMaximize() const { return false; } // Returns true if the dialog should be displayed modally to the window that // opened it. Only windows with WindowType == DIALOG can be modal. virtual bool IsModal() const { return false; } virtual AccessibilityTypes::Role accessible_role() const { return AccessibilityTypes::ROLE_WINDOW; } virtual AccessibilityTypes::State accessible_state() const { return 0; } // Returns the title to be read with screen readers. virtual std::wstring GetAccessibleWindowTitle() const { return GetWindowTitle(); } // Returns the text to be displayed in the window title. virtual std::wstring GetWindowTitle() const { return L""; } // Returns the view that should have the focus when the dialog is opened. If // NULL no view is focused. virtual View* GetInitiallyFocusedView() { return NULL; } // Returns true if the window should show a title in the title bar. virtual bool ShouldShowWindowTitle() const { return true; } // Returns true if the window's client view wants a client edge. virtual bool ShouldShowClientEdge() const { return true; } // Returns the app icon for the window. On Windows, this is the ICON_BIG used // in Alt-Tab list and Win7's taskbar. virtual SkBitmap GetWindowAppIcon(); // Returns the icon to be displayed in the window. virtual SkBitmap GetWindowIcon(); // Returns true if a window icon should be shown. virtual bool ShouldShowWindowIcon() const { return false; } // Execute a command in the window's controller. Returns true if the command // was handled, false if it was not. virtual bool ExecuteWindowsCommand(int command_id) { return false; } // Returns the window's name identifier. Used to identify this window for // state restoration. virtual std::wstring GetWindowName() const { return std::wstring(); } // Saves the window's bounds and maximized states. By default this uses the // process' local state keyed by window name (See GetWindowName above). This // behavior can be overridden to provide additional functionality. virtual void SaveWindowPlacement(const gfx::Rect& bounds, bool maximized); // Retrieves the window's bounds and maximized states. // This behavior can be overridden to provide additional functionality. virtual bool GetSavedWindowBounds(gfx::Rect* bounds) const; virtual bool GetSavedMaximizedState(bool* maximized) const; // Returns true if the window's size should be restored. If this is false, // only the window's origin is restored and the window is given its // preferred size. // Default is true. virtual bool ShouldRestoreWindowSize() const; // Called when the window closes. virtual void WindowClosing() {} // Called when the window is destroyed. No events must be sent or received // after this point. The delegate can use this opportunity to delete itself at // this time if necessary. virtual void DeleteDelegate() {} // Returns the View that is contained within this Window. virtual View* GetContentsView() { return NULL; } // Called by the Window to create the Client View used to host the contents // of the window. virtual ClientView* CreateClientView(Window* window); Window* window() const { return window_; } private: friend class WindowGtk; friend class WindowWin; // The Window this delegate is bound to. Weak reference. Window* window_; }; } // namespace views #endif // VIEWS_WINDOW_WINDOW_DELEGATE_H_
30.183544
80
0.707696
[ "object" ]
04b08c8f52bf9f46ab028865f139c39ce126ca06
9,011
h
C
projects/backstroke/pluggableReverser/handlerTypes.h
maurizioabba/rose
7597292cf14da292bdb9a4ef573001b6c5b9b6c0
[ "BSD-3-Clause" ]
14
2017-03-07T00:14:33.000Z
2022-02-09T00:59:22.000Z
projects/backstroke/pluggableReverser/handlerTypes.h
maurizioabba/rose
7597292cf14da292bdb9a4ef573001b6c5b9b6c0
[ "BSD-3-Clause" ]
11
2016-11-22T13:14:55.000Z
2021-12-14T00:56:51.000Z
projects/backstroke/pluggableReverser/handlerTypes.h
maurizioabba/rose
7597292cf14da292bdb9a4ef573001b6c5b9b6c0
[ "BSD-3-Clause" ]
6
2016-11-07T13:38:45.000Z
2021-04-04T12:13:31.000Z
#ifndef HANDLERBASE_H #define HANDLERBASE_H #include <boost/shared_ptr.hpp> #include <boost/any.hpp> #include "variableVersionTable.h" #include <staticSingleAssignment.h> #include "costModel.h" //Forward declarations class ExpressionReversalHandler; class StatementReversalHandler; class ReversalHandlerBase; class EventProcessor; class IVariableFilter; struct ExpressionReversal { ExpressionReversal(SgExpression* fwd, SgExpression * rvs) : forwardExpression(fwd), reverseExpression(rvs) { } SgExpression* forwardExpression; SgExpression* reverseExpression; }; struct StatementReversal { StatementReversal(SgStatement* fwd, SgStatement * rvs) : forwardStatement(fwd), reverseStatement(rvs), commitStatement(NULL) { } StatementReversal(SgStatement* fwd, SgStatement * rvs, SgStatement* commit) : forwardStatement(fwd), reverseStatement(rvs), commitStatement(commit) { } SgStatement* forwardStatement; SgStatement* reverseStatement; SgStatement* commitStatement; }; class EvaluationResult { //TODO: This table is not necessary once the result is added to the parent results VariableVersionTable var_table_; // Cost model SimpleCostModel cost_; /** The handler which produced this evaluation result. This is used during the * generation phrase to generate the actual expression. */ ReversalHandlerBase* handler_used_; //!The expression or statement to which this evaluation result pertains SgNode* input_; /** Additional attribute that the handler may choose to attach to the evaluation result. */ boost::any attribute_; /** Evaluation choices made in order to get this result. For example, for a basic block, what * were the evaluations of all the statements? */ std::vector<EvaluationResult> child_results; //! True if this if a valid result; false if the handler couldn't deal with the input bool isValid_; public: //! Create a valid evaluation result EvaluationResult(ReversalHandlerBase* handler_used, SgNode* input, const VariableVersionTable& table, const SimpleCostModel& cost_model = SimpleCostModel()) : var_table_(table), cost_(cost_model), handler_used_(handler_used), input_(input), isValid_(true) { } //! Create an evaluation results that indicates that the AST fragment couldn't be inverted with the given handler EvaluationResult() : isValid_(false) { } /** Add an evaluation result to the evaluations used in order to construct the current one. * This adds the cost of the child result to the total cost and adds the result to the list of * evaluation results. It also replaces the variable version table! */ void addChildEvaluationResult(const EvaluationResult& result); /** Generate the reverse AST for the expression whose reversal result this class holds. */ ExpressionReversal generateReverseExpression() const; /** Generate the reverse AST for the statement whose reversal result this class holds. */ StatementReversal generateReverseStatement() const; /** Generate the commit method portion of the AST. */ SgStatement* generateCommitStatement() const; ExpressionReversalHandler* getExpressionHandler() const; StatementReversalHandler* getStatementHandler() const; const VariableVersionTable& getVarTable() const; const std::vector<EvaluationResult>& getChildResults() const; VariableVersionTable& getVarTable(); void setVarTable(const VariableVersionTable& table); const SimpleCostModel& getCost() const; void setCost(const SimpleCostModel& cost); template <class T> void setAttribute(const T& attr) { attribute_ = attr; } template<class T> T getAttribute() const { return boost::any_cast<T>(attribute_); } //! Returns the expression which was processed to produce this evaluation result SgExpression* getExpressionInput() const; //! Returns the statement which was processed to produce this evaluation result SgStatement* getStatementInput() const; //! Print all handlers inside of this result. void printHandlers() const; //! True if valid result; false if the handler couldn't reverse the given input bool isValid() const { return isValid_; } }; //! Comparison functions for structure InstrumentedStatement and InstrumentedExpression. inline bool operator<(const EvaluationResult& r1, const EvaluationResult& r2) { return r1.getCost().getCost() < r2.getCost().getCost(); } class ReversalHandlerBase { EventProcessor* event_handler_; protected: std::string name_; EvaluationResult evaluateExpression(SgExpression* exp, const VariableVersionTable& var_table, bool is_value_used); EvaluationResult evaluateStatement(SgStatement* stmt, const VariableVersionTable& var_table); /** * Given a variable and a version, returns an expression evaluating to the value of the variable * at the given version. * * @param variable name of the variable to be restored * @param availableVariables variables whose values are currently available * @param definitions the version of the variable which should be restored * @return expression that when evaluated will produce the desired version of the variable */ SgExpression* restoreVariable(VariableRenaming::VarName variable, const VariableVersionTable& availableVariables, VariableRenaming::NumNodeRenameEntry definitions); //! Restores the value of an expression given a set of currently available variables. For example, if the //! expression is (a + b), the values of a and b will be extracted from the currently available variables, and then //! the expression val(a) + val(b) will be returned. //! //! @returns expression evaluating to the same value as the original, or NULL on failure SgExpression* restoreExpressionValue(SgExpression* expression, const VariableVersionTable& availableVariables); SgExpression* pushVal(SgExpression* exp, SgType* type); SgExpression* pushVal(SgExpression* exp) { return pushVal(exp, exp->get_type()); } //! Generates an expression which pops a value from the back of a stack and evaluates to it SgExpression* popVal(SgType* type); //!Generates an expression which pops a value from the front of a stack and discards the value. //! This is used for fossil collection (commit methods) SgExpression* popVal_front(SgType* type); SgExpression* cloneValueExp(SgExpression* value, SgType* type); //! Calls the __restore__ function, which is part of the Backstroke runtime. //! It pops a value from the stack and assigns it to the given variable SgExpression* assignPointerExp(SgExpression* lhs, SgExpression* rhs, SgType* lhsType, SgType* rhsType); //! Return if the given variable is a state variable bool isStateVariable(SgExpression* exp); //! Returns an object with def-use analysis. To be replaced by SSA analysis in the future VariableRenaming* getVariableRenaming(); //! Returns an object with interprocedural SSA analysis const StaticSingleAssignment* getSsa() const; //! Returns an object that determines whether the value of a given variable nees to be reversed. const IVariableFilter* getVariableFilter() const; public: ReversalHandlerBase() : event_handler_(NULL) { } ReversalHandlerBase(const std::string& name) : event_handler_(NULL), name_(name) { } std::string getName() const { return name_; } void setEventHandler(EventProcessor* handler) { event_handler_ = handler; } virtual ~ReversalHandlerBase() { } }; class ExpressionReversalHandler : public ReversalHandlerBase { public: virtual ExpressionReversal generateReverseAST(SgExpression* exp, const EvaluationResult& evaluationResult) = 0; virtual EvaluationResult evaluate(SgExpression* exp, const VariableVersionTable& var_table, bool is_value_used) = 0; }; class StatementReversalHandler : public ReversalHandlerBase { public: virtual StatementReversal generateReverseAST(SgStatement* stmt, const EvaluationResult& evaluationResult) = 0; virtual EvaluationResult evaluate(SgStatement* stmt, const VariableVersionTable& var_table) = 0; }; /** These types of reverse handlers recalculate a specific value of a variable at a different point * in the program. */ class VariableValueRestorer { public: /** * Given a variable and a version, returns an expression evaluating to the value of the variable * at the given version. * * @param variable name of the variable to be restored * @param availableVariables variables whose values are currently available * @param definitions the version of the variable which should be restored * @return expressions that when evaluated will produce the desired version of the variable */ virtual std::vector<SgExpression*> restoreVariable(VariableRenaming::VarName variable, const VariableVersionTable& availableVariables, VariableRenaming::NumNodeRenameEntry definitions) = 0; VariableValueRestorer() : eventHandler(NULL) { } void setEventHandler(EventProcessor* eventHandler) { this->eventHandler = eventHandler; } EventProcessor* getEventHandler() { return eventHandler; } private: EventProcessor* eventHandler; }; #endif
33.250923
135
0.775386
[ "object", "vector", "model" ]
04b1f24c6f4e18b954223cab2b3550ccf566a9a0
2,925
h
C
light_node.h
giuliandenicola1/deconz-rest-plugin
f01c40bcb73f17339216bd3c15af4a6bbc3b54e4
[ "BSD-3-Clause" ]
1,765
2015-06-09T08:10:44.000Z
2022-03-29T16:20:41.000Z
light_node.h
giuliandenicola1/deconz-rest-plugin
f01c40bcb73f17339216bd3c15af4a6bbc3b54e4
[ "BSD-3-Clause" ]
5,354
2015-01-09T21:18:14.000Z
2022-03-31T21:41:56.000Z
light_node.h
giuliandenicola1/deconz-rest-plugin
f01c40bcb73f17339216bd3c15af4a6bbc3b54e4
[ "BSD-3-Clause" ]
506
2015-04-15T14:08:41.000Z
2022-03-28T09:23:35.000Z
/* * Copyright (c) 2016-2017 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #ifndef LIGHT_NODE_H #define LIGHT_NODE_H #include <QString> #include <deconz.h> #include "resource.h" #include "rest_node_base.h" #include "group_info.h" #define COLOR_CAP_HUE_SAT (1 << 0) #define COLOR_CAP_ENHANCED_HUE (1 << 1) #define COLOR_CAP_COLORLOOP (1 << 2) #define COLOR_CAP_XY (1 << 3) #define COLOR_CAP_CT (1 << 4) /*! \class LightNode Represents a HA or ZLL based light. */ class LightNode : public Resource, public RestNodeBase { public: enum State { StateNormal, StateDeleted }; LightNode(); State state() const; void setState(State state); bool isAvailable() const override; uint16_t manufacturerCode() const; void setManufacturerCode(uint16_t code); const QString &manufacturer() const; void setManufacturerName(const QString &name); const QString &modelId() const; void setModelId(const QString &modelId); const QString &swBuildId() const; void setSwBuildId(const QString & swBuildId); const QString &name() const; void setName(const QString &name); const QString &type() const; std::vector<GroupInfo> &groups(); const std::vector<GroupInfo> &groups() const; uint16_t otauClusterId() const; void setOtauClusterId(uint16_t clusterId); bool hasColor() const; void setColorLoopActive(bool colorLoopActive); bool isColorLoopActive() const; bool supportsColorLoop() const; void setColorLoopSpeed(uint8_t speed); uint8_t colorLoopSpeed() const; void didSetValue(ResourceItem *i) override; void rx(); const deCONZ::SimpleDescriptor &haEndpoint() const; void setHaEndpoint(const deCONZ::SimpleDescriptor &endpoint); uint8_t groupCapacity() const; void setGroupCapacity(uint8_t capacity); uint8_t resetRetryCount() const; void setResetRetryCount(uint8_t resetRetryCount); uint8_t zdpResetSeq() const; void setZdpResetSeq(uint8_t zdpResetSeq); uint8_t groupCount() const; void setGroupCount(uint8_t groupCount); uint8_t sceneCapacity() const; void setSceneCapacity(uint8_t sceneCapacity); void jsonToResourceItems(const QString &json); QString resourceItemsToJson(); QString etag; private: State m_state; uint8_t m_resetRetryCount; uint8_t m_zdpResetSeq; uint8_t m_groupCapacity; uint16_t m_manufacturerCode; uint16_t m_otauClusterId; std::vector<GroupInfo> m_groups; bool m_colorLoopActive; uint8_t m_colorLoopSpeed; quint8 m_haEndpoint = 255; uint8_t m_groupCount; uint8_t m_sceneCapacity; }; #endif // LIGHT_NODE_H
29.25
76
0.705983
[ "vector" ]
04b8a657f3586029b4c9413f4622e2b53919dfc6
5,484
h
C
PrivateFrameworks/iWorkImport.framework/TSKCOReplaceRangeOperation.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
36
2016-04-20T04:19:04.000Z
2018-10-08T04:12:25.000Z
PrivateFrameworks/iWorkImport.framework/TSKCOReplaceRangeOperation.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
null
null
null
PrivateFrameworks/iWorkImport.framework/TSKCOReplaceRangeOperation.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
10
2016-06-16T02:40:44.000Z
2019-01-15T03:31:45.000Z
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/iWorkImport.framework/iWorkImport */ @interface TSKCOReplaceRangeOperation : TSKCOReplaceOperation <TSKCORangeOperation, TSKCOReplaceRangeOperationSubset, TSKCOTransforming> { TSKCORangeAddress * mAddress; unsigned long long mInsertLength; bool mPreserveLowerPriorityLocation; } @property (nonatomic, readonly) TSKCORangeAddress *address; @property (nonatomic, readonly) unsigned long long insertLength; @property (nonatomic, readonly) bool preserveLowerPriorityLocation; - (id)address; - (void)dealloc; - (id)description; - (id)fromReplaceRangeOperation:(id)arg1; - (bool)hasNoEffects; - (id)initWithRangeAddress:(id)arg1 insertLength:(unsigned long long)arg2; - (id)initWithRangeAddress:(id)arg1 insertLength:(unsigned long long)arg2 noop:(bool)arg3; - (id)initWithRangeAddress:(id)arg1 insertLength:(unsigned long long)arg2 preserveLowerPriorityLocation:(bool)arg3 noop:(bool)arg4; - (id)initWithUnarchiver:(id)arg1 message:(const struct Operation { int (**x1)(); struct ExtensionSet { struct map<int, google::protobuf::internal::ExtensionSet::Extension, std::__1::less<int>, std::__1::allocator<std::__1::pair<const int, google::protobuf::internal::ExtensionSet::Extension> > > { struct __tree<std::__1::__value_type<int, google::protobuf::internal::ExtensionSet::Extension>, std::__1::__map_value_compare<int, std::__1::__value_type<int, google::protobuf::internal::ExtensionSet::Extension>, std::__1::less<int>, true>, std::__1::allocator<std::__1::__value_type<int, google::protobuf::internal::ExtensionSet::Extension> > > { struct __tree_node<std::__1::__value_type<int, google::protobuf::internal::ExtensionSet::Extension>, void *> {} *x_1_3_1; struct __compressed_pair<std::__1::__tree_end_node<std::__1::__tree_node_base<void *> *>, std::__1::allocator<std::__1::__tree_node<std::__1::__value_type<int, google::protobuf::internal::ExtensionSet::Extension>, void *> > > { struct __tree_end_node<std::__1::__tree_node_base<void *> *> { struct __tree_node_base<void *> {} *x_1_5_1; } x_2_4_1; } x_1_3_2; struct __compressed_pair<unsigned long, std::__1::__map_value_compare<int, std::__1::__value_type<int, google::protobuf::internal::ExtensionSet::Extension>, std::__1::less<int>, true> > { unsigned long long x_3_4_1; } x_1_3_3; } x_1_2_1; } x_2_1_1; } x2; struct UnknownFieldSet { struct vector<google::protobuf::UnknownField, std::__1::allocator<google::protobuf::UnknownField> > {} *x_3_1_1; } x3; unsigned int x4[1]; int x5; bool x6; }*)arg2; - (unsigned long long)insertLength; - (id)operationWithNewAddress:(id)arg1; - (id)operationWithNewAddress:(id)arg1 newPreserveLowerPriorityLocation:(bool)arg2; - (id)operationWithNewNoop:(bool)arg1; - (id)p_transformReplaceRange:(struct _NSRange { unsigned long long x1; unsigned long long x2; })arg1 replacementLength:(unsigned long long)arg2 myRange:(struct _NSRange { unsigned long long x1; unsigned long long x2; })arg3 myReplacementLength:(unsigned long long)arg4 preserveLocation:(bool)arg5; - (id)p_transformUpdateRange:(struct _NSRange { unsigned long long x1; unsigned long long x2; })arg1 myRange:(struct _NSRange { unsigned long long x1; unsigned long long x2; })arg2 replacementLength:(unsigned long long)arg3 transformBehavior:(int)arg4; - (void)p_validateAndMergeTransformedRanges:(id)arg1; - (bool)preserveLowerPriorityLocation; - (void)saveToArchiver:(id)arg1 message:(struct Operation { int (**x1)(); struct ExtensionSet { struct map<int, google::protobuf::internal::ExtensionSet::Extension, std::__1::less<int>, std::__1::allocator<std::__1::pair<const int, google::protobuf::internal::ExtensionSet::Extension> > > { struct __tree<std::__1::__value_type<int, google::protobuf::internal::ExtensionSet::Extension>, std::__1::__map_value_compare<int, std::__1::__value_type<int, google::protobuf::internal::ExtensionSet::Extension>, std::__1::less<int>, true>, std::__1::allocator<std::__1::__value_type<int, google::protobuf::internal::ExtensionSet::Extension> > > { struct __tree_node<std::__1::__value_type<int, google::protobuf::internal::ExtensionSet::Extension>, void *> {} *x_1_3_1; struct __compressed_pair<std::__1::__tree_end_node<std::__1::__tree_node_base<void *> *>, std::__1::allocator<std::__1::__tree_node<std::__1::__value_type<int, google::protobuf::internal::ExtensionSet::Extension>, void *> > > { struct __tree_end_node<std::__1::__tree_node_base<void *> *> { struct __tree_node_base<void *> {} *x_1_5_1; } x_2_4_1; } x_1_3_2; struct __compressed_pair<unsigned long, std::__1::__map_value_compare<int, std::__1::__value_type<int, google::protobuf::internal::ExtensionSet::Extension>, std::__1::less<int>, true> > { unsigned long long x_3_4_1; } x_1_3_3; } x_1_2_1; } x_2_1_1; } x2; struct UnknownFieldSet { struct vector<google::protobuf::UnknownField, std::__1::allocator<google::protobuf::UnknownField> > {} *x_3_1_1; } x3; unsigned int x4[1]; int x5; bool x6; }*)arg2; - (id)toReplaceRangeOperation; - (id)transformDynamicByAnyOperation:(id)arg1 byHigherPriority:(bool)arg2; - (id)transformIdPlacementBaseOperation:(id)arg1 isHigherPriority:(bool)arg2; - (id)transformReplaceRangeOperation:(id)arg1 isHigherPriority:(bool)arg2; - (id)transformStaticByAnyOperation:(id)arg1 byHigherPriority:(bool)arg2; - (id)transformUpdateIdOperation:(id)arg1 isHigherPriority:(bool)arg2; - (id)transformUpdateRangeOperation:(id)arg1 isHigherPriority:(bool)arg2; - (id)ut_transformByTransformer:(id)arg1; @end
127.534884
1,571
0.770058
[ "vector" ]
04bb5ad1e84ac862f7ae99556a397aacd3bcfc92
19,258
c
C
source/programs/Xserver/hw/xfree86/drivers/neomagic/neo_2200.c
binaryblob01/zfree86
e80ea992d87501b8e3e2d7c07a414591c2e11c70
[ "Xnet", "X11" ]
1
2021-09-08T21:13:25.000Z
2021-09-08T21:13:25.000Z
source/programs/Xserver/hw/xfree86/drivers/neomagic/neo_2200.c
binaryblob01/zfree86
e80ea992d87501b8e3e2d7c07a414591c2e11c70
[ "Xnet", "X11" ]
null
null
null
source/programs/Xserver/hw/xfree86/drivers/neomagic/neo_2200.c
binaryblob01/zfree86
e80ea992d87501b8e3e2d7c07a414591c2e11c70
[ "Xnet", "X11" ]
1
2021-01-22T00:19:47.000Z
2021-01-22T00:19:47.000Z
/******************************************************************** Copyright 1998, 1999 by Precision Insight, Inc., Cedar Park, Texas. All Rights Reserved Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Precision Insight not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. Precision Insight and its suppliers make no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty. PRECISION INSIGHT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, 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. **********************************************************************/ /* $XFree86: xc/programs/Xserver/hw/xfree86/drivers/neomagic/neo_2200.c,v 1.20 2003/01/12 03:55:48 tsi Exp $ */ /* * The original Precision Insight driver for * XFree86 v.3.3 has been sponsored by Red Hat. * * Authors: * Jens Owen (jens@tungstengraphics.com) * Kevin E. Martin (kevin@precisioninsight.com) * * Port to Xfree86 v.4.0 * 1998, 1999 by Egbert Eich (Egbert.Eich@Physik.TU-Darmstadt.DE) */ #include "xf86.h" #include "xf86_OSproc.h" #include "xf86_ansic.h" #include "compiler.h" /* Drivers that use XAA need this */ #include "xf86fbman.h" #include "miline.h" #include "neo.h" #include "neo_reg.h" #include "neo_macros.h" static void Neo2200Sync(ScrnInfoPtr pScrn); static void Neo2200SetupForScreenToScreenCopy(ScrnInfoPtr pScrn, int xdir, int ydir, int rop, unsigned int planemask, int trans_color); #ifdef NOT_BROKEN static void Neo2200SubsequentScreenToScreenCopy(ScrnInfoPtr pScrn, int srcX, int srcY, int dstX, int dstY, int w, int h); #else static void Neo2200SubsequentScreenToScreenCopyBroken(ScrnInfoPtr pScrn, int srcX, int srcY, int dstX, int dstY, int w, int h); #endif static void Neo2200SetupForSolidFillRect(ScrnInfoPtr pScrn, int color, int rop, unsigned int planemask); static void Neo2200SubsequentSolidFillRect(ScrnInfoPtr pScrn, int x, int y, int w, int h); static void Neo2200SetupForScanlineCPUToScreenColorExpandFill( ScrnInfoPtr pScrn, int fg, int bg, int rop, unsigned int planemask); static void Neo2200SubsequentScanlineCPUToScreenColorExpandFill( ScrnInfoPtr pScrn, int x, int y, int w, int h, int skipleft); static void Neo2200SubsequentColorExpandScanline(ScrnInfoPtr pScrn, int bufno); #if 0 static void Neo2200SetupForMono8x8PatternFill(ScrnInfoPtr pScrn, int patternx, int patterny, int bg, int fg, int rop, unsigned int planemask); static void Neo2200SubsequentMono8x8PatternFill(ScrnInfoPtr pScrn, int patternx, int patterny, int x, int y, int w, int h); #endif static unsigned int neo2200Rop[16] = { 0x000000, /* 0x0000 - GXclear */ 0x080000, /* 0x1000 - GXand */ 0x040000, /* 0x0100 - GXandReverse */ 0x0c0000, /* 0x1100 - GXcopy */ 0x020000, /* 0x0010 - GXandInvert */ 0x0a0000, /* 0x1010 - GXnoop */ 0x060000, /* 0x0110 - GXxor */ 0x0e0000, /* 0x1110 - GXor */ 0x010000, /* 0x0001 - GXnor */ 0x090000, /* 0x1001 - GXequiv */ 0x050000, /* 0x0101 - GXinvert */ 0x0d0000, /* 0x1101 - GXorReverse */ 0x030000, /* 0x0011 - GXcopyInvert */ 0x0b0000, /* 0x1011 - GXorInverted */ 0x070000, /* 0x0111 - GXnand */ 0x0f0000 /* 0x1111 - GXset */ }; Bool Neo2200AccelInit(ScreenPtr pScreen) { XAAInfoRecPtr infoPtr; ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum]; NEOPtr nPtr = NEOPTR(pScrn); NEOACLPtr nAcl = NEOACLPTR(pScrn); nPtr->AccelInfoRec = infoPtr = XAACreateInfoRec(); if(!infoPtr) return FALSE; /* * Set up the main acceleration flags. */ infoPtr->Flags = LINEAR_FRAMEBUFFER | OFFSCREEN_PIXMAPS; if(nAcl->cacheEnd > nAcl->cacheStart) infoPtr->Flags |= PIXMAP_CACHE; #if 0 infoPtr->PixmapCacheFlags |= DO_NOT_BLIT_STIPPLES; #endif /* sync */ infoPtr->Sync = Neo2200Sync; /* screen to screen copy */ infoPtr->ScreenToScreenCopyFlags = (NO_TRANSPARENCY | NO_PLANEMASK); infoPtr->SetupForScreenToScreenCopy = Neo2200SetupForScreenToScreenCopy; infoPtr->SubsequentScreenToScreenCopy #ifdef NOT_BROKEN = Neo2200SubsequentScreenToScreenCopy; #else = Neo2200SubsequentScreenToScreenCopyBroken; #endif /* solid filled rectangles */ infoPtr->SolidFillFlags = NO_PLANEMASK; infoPtr->SetupForSolidFill = Neo2200SetupForSolidFillRect; infoPtr->SubsequentSolidFillRect = Neo2200SubsequentSolidFillRect; /* cpu to screen color expansion */ /* * We do CPUToScreenColorExpand (ab)using the Scanline functions: * the neo chipsets need byte padding however we can only do dword * padding. Fortunately the graphics engine doesn't choke if we * transfer up to 3 bytes more than it wants. */ if (!nPtr->strangeLockups) { infoPtr->ScanlineCPUToScreenColorExpandFillFlags = ( NO_PLANEMASK | #ifdef NEO_DO_CLIPPING LEFT_EDGE_CLIPPING | #endif SCANLINE_PAD_DWORD | CPU_TRANSFER_PAD_DWORD | BIT_ORDER_IN_BYTE_MSBFIRST ); infoPtr->ScanlineColorExpandBuffers = (unsigned char **)xnfalloc(sizeof(char*)); infoPtr->ScanlineColorExpandBuffers[0] = (unsigned char *)(nPtr->NeoMMIOBase + 0x100000); infoPtr->NumScanlineColorExpandBuffers = 1; infoPtr->SetupForScanlineCPUToScreenColorExpandFill = Neo2200SetupForScanlineCPUToScreenColorExpandFill; infoPtr->SubsequentScanlineCPUToScreenColorExpandFill = Neo2200SubsequentScanlineCPUToScreenColorExpandFill; infoPtr->SubsequentColorExpandScanline = Neo2200SubsequentColorExpandScanline; } #if 0 /* 8x8 pattern fills */ infoPtr->Mono8x8PatternFillFlags = NO_PLANEMASK | HARDWARE_PATTERN_PROGRAMMED_ORIGIN |BIT_ORDER_IN_BYTE_MSBFIRST; infoPtr->SetupForMono8x8PatternFill = Neo2200SetupForMono8x8PatternFill; infoPtr->SubsequentMono8x8PatternFillRect = Neo2200SubsequentMono8x8PatternFill; #endif /* * Setup some global variables */ /* Initialize for 8bpp or 15/16bpp support accelerated */ switch (pScrn->bitsPerPixel) { case 8: nAcl->BltModeFlags = NEO_MODE1_DEPTH8; nAcl->PixelWidth = 1; break; case 15: case 16: nAcl->BltModeFlags = NEO_MODE1_DEPTH16; nAcl->PixelWidth = 2; break; case 24: if (nPtr->noAccelSet || nPtr->NeoChipset == NM2230 || nPtr->NeoChipset == NM2360 || nPtr->NeoChipset == NM2380) { nAcl->BltModeFlags = NEO_MODE1_DEPTH24; nAcl->PixelWidth = 3; } else return FALSE; break; default: return FALSE; } nAcl->Pitch = pScrn->displayWidth * nAcl->PixelWidth; /* Initialize for widths */ switch (pScrn->displayWidth) { case 320: nAcl->BltModeFlags |= NEO_MODE1_X_320; break; case 640: nAcl->BltModeFlags |= NEO_MODE1_X_640; break; case 800: nAcl->BltModeFlags |= NEO_MODE1_X_800; break; case 1024: nAcl->BltModeFlags |= NEO_MODE1_X_1024; break; case 1152: nAcl->BltModeFlags |= NEO_MODE1_X_1152; break; case 1280: nAcl->BltModeFlags |= NEO_MODE1_X_1280; break; case 1600: nAcl->BltModeFlags |= NEO_MODE1_X_1600; break; default: return FALSE; } return(XAAInit(pScreen, infoPtr)); } static void Neo2200Sync(ScrnInfoPtr pScrn) { NEOPtr nPtr = NEOPTR(pScrn); WAIT_ENGINE_IDLE(); } static void Neo2200SetupForScreenToScreenCopy(ScrnInfoPtr pScrn, int xdir, int ydir, int rop, unsigned int planemask, int trans_color) { NEOPtr nPtr = NEOPTR(pScrn); NEOACLPtr nAcl = NEOACLPTR(pScrn); nAcl->tmpBltCntlFlags = (NEO_BC3_SKIP_MAPPING | neo2200Rop[rop]); /* set blt control */ WAIT_ENGINE_IDLE(); /*OUTREG16(NEOREG_BLTMODE, nAcl->BltModeFlags);*/ OUTREG(NEOREG_BLTSTAT, nAcl->BltModeFlags << 16); OUTREG(NEOREG_BLTCNTL, nAcl->tmpBltCntlFlags); OUTREG(NEOREG_PITCH, (nAcl->Pitch<<16) | (nAcl->Pitch & 0xffff)); } #ifdef NOT_BROKEN static void Neo2200SubsequentScreenToScreenCopy(ScrnInfoPtr pScrn, int srcX, int srcY, int dstX, int dstY, int w, int h) { NEOPtr nPtr = NEOPTR(pScrn); NEOACLPtr nAcl = NEOACLPTR(pScrn); if ((dstY < srcY) || ((dstY == srcY) && (dstX < srcX))) { /* start with upper left corner */ WAIT_ENGINE_IDLE(); #if 0 OUTREG(NEOREG_BLTCNTL, nAcl->tmpBltCntlFlags); #endif OUTREG(NEOREG_SRCSTARTOFF, (srcY * nAcl->Pitch) + (srcX * nAcl->PixelWidth)); OUTREG(NEOREG_DSTSTARTOFF, (dstY * nAcl->Pitch) + (dstX * nAcl->PixelWidth)); OUTREG(NEOREG_XYEXT, (h<<16) | (w & 0xffff)); } else { /* start with lower right corner */ WAIT_ENGINE_IDLE(); #if 0 OUTREG(NEOREG_BLTCNTL, (nAcl->tmpBltCntlFlags | NEO_BC0_X_DEC | NEO_BC0_DST_Y_DEC | NEO_BC0_SRC_Y_DEC)); #endif OUTREG(NEOREG_SRCSTARTOFF, ((srcY+h-1) * nAcl->Pitch) + ((srcX+w-1) * nAcl->PixelWidth)); OUTREG(NEOREG_DSTSTARTOFF, ((dstY+h-1) * nAcl->Pitch) + ((dstX+w-1) * nAcl->PixelWidth)); OUTREG(NEOREG_XYEXT, (h<<16) | (w & 0xffff)); } } #else /* NOT_BROKEN */ static void Neo2200SubsequentScreenToScreenCopyBroken(ScrnInfoPtr pScrn, int srcX, int srcY, int dstX, int dstY, int w, int h) { NEOPtr nPtr = NEOPTR(pScrn); NEOACLPtr nAcl = NEOACLPTR(pScrn); if ((dstY < srcY) || ((dstY == srcY) && (dstX < srcX))) { if ((((dstX < 64) && ((srcX + w + 64) >= pScrn->displayWidth)) || ((dstX == 0) && (w > (pScrn->displayWidth - 64)))) && (w > 64)) { #define COPY_64 \ OUTREG(NEOREG_SRCSTARTOFF,\ (srcY * nAcl->Pitch) + (srcX * nAcl->PixelWidth));\ OUTREG(NEOREG_DSTSTARTOFF,\ (dstY * nAcl->Pitch) + (dstX * nAcl->PixelWidth));\ OUTREG(NEOREG_XYEXT, (h<<16) | (64)); #define COPY_W \ OUTREG(NEOREG_SRCSTARTOFF,\ (srcY * nAcl->Pitch) + (srcX1 * nAcl->PixelWidth));\ OUTREG(NEOREG_DSTSTARTOFF,\ (dstY * nAcl->Pitch) + (dstX1 * nAcl->PixelWidth));\ OUTREG(NEOREG_XYEXT, (h<<16) | (w & 0xffff)); int srcX1 = srcX + 64; int dstX1 = dstX + 64; w -= 64; /* start with upper left corner */ WAIT_ENGINE_IDLE(); OUTREG(NEOREG_BLTCNTL, nAcl->tmpBltCntlFlags); if (srcX < dstX) { COPY_W; WAIT_ENGINE_IDLE(); COPY_64; } else { COPY_64; WAIT_ENGINE_IDLE(); COPY_W; } #undef COPY_W #undef COPY_64 } else { /* start with upper left corner */ WAIT_ENGINE_IDLE(); OUTREG(NEOREG_BLTCNTL, nAcl->tmpBltCntlFlags); OUTREG(NEOREG_SRCSTARTOFF, (srcY * nAcl->Pitch) + (srcX * nAcl->PixelWidth)); OUTREG(NEOREG_DSTSTARTOFF, (dstY * nAcl->Pitch) + (dstX * nAcl->PixelWidth)); OUTREG(NEOREG_XYEXT, (h<<16) | (w & 0xffff)); } } else { if (((((dstX + w) > (pScrn->displayWidth - 64)) && (srcX == 0)) || (((dstX + w + 64) >= pScrn->displayWidth) && (w > (pScrn->displayWidth - 64)))) && (w > 64)) { #define COPY_64 \ OUTREG(NEOREG_SRCSTARTOFF, \ ((srcY+h-1) * nAcl->Pitch) + ((srcX1+64-1) \ * nAcl->PixelWidth)); \ OUTREG(NEOREG_DSTSTARTOFF, \ ((dstY+h-1) * nAcl->Pitch) + ((dstX1+64-1) \ * nAcl->PixelWidth)); \ OUTREG(NEOREG_XYEXT, (h<<16) | (64 & 0xffff)); #define COPY_W \ OUTREG(NEOREG_SRCSTARTOFF, \ ((srcY+h-1) * nAcl->Pitch) + ((srcX + w -1) \ * nAcl->PixelWidth)); \ OUTREG(NEOREG_DSTSTARTOFF, \ ((dstY+h-1) * nAcl->Pitch) + ((dstX + w -1) \ * nAcl->PixelWidth)); \ OUTREG(NEOREG_XYEXT, (h<<16) | (w & 0xffff)); int srcX1, dstX1; w -= 64; srcX1 = srcX + w; dstX1 = dstX + w; /* start with lower right corner */ WAIT_ENGINE_IDLE(); OUTREG(NEOREG_BLTCNTL, (nAcl->tmpBltCntlFlags | NEO_BC0_X_DEC | NEO_BC0_DST_Y_DEC | NEO_BC0_SRC_Y_DEC)); if (srcX < dstX) { COPY_64; WAIT_ENGINE_IDLE(); COPY_W; } else { COPY_W; WAIT_ENGINE_IDLE(); COPY_64; } #undef COPY_W #undef COPY_64 } else { /* start with lower right corner */ WAIT_ENGINE_IDLE(); OUTREG(NEOREG_BLTCNTL, (nAcl->tmpBltCntlFlags | NEO_BC0_X_DEC | NEO_BC0_DST_Y_DEC | NEO_BC0_SRC_Y_DEC)); OUTREG(NEOREG_SRCSTARTOFF, ((srcY+h-1) * nAcl->Pitch) + ((srcX+w-1) * nAcl->PixelWidth)); OUTREG(NEOREG_DSTSTARTOFF, ((dstY+h-1) * nAcl->Pitch) + ((dstX+w-1) * nAcl->PixelWidth)); OUTREG(NEOREG_XYEXT, (h<<16) | (w & 0xffff)); } } } #endif /* NOT_BROKEN */ static void Neo2200SetupForSolidFillRect(ScrnInfoPtr pScrn, int color, int rop, unsigned int planemask) { NEOPtr nPtr = NEOPTR(pScrn); NEOACLPtr nAcl = NEOACLPTR(pScrn); WAIT_ENGINE_IDLE(); /* set blt control */ /*OUTREG16(NEOREG_BLTMODE, nAcl->BltModeFlags);*/ OUTREG(NEOREG_BLTSTAT, nAcl->BltModeFlags << 16); OUTREG(NEOREG_BLTCNTL, NEO_BC0_SRC_IS_FG | NEO_BC3_SKIP_MAPPING | NEO_BC3_DST_XY_ADDR | NEO_BC3_SRC_XY_ADDR | neo2200Rop[rop]); /* set foreground color */ OUTREG(NEOREG_FGCOLOR, color); } static void Neo2200SubsequentSolidFillRect(ScrnInfoPtr pScrn, int x, int y, int w, int h) { NEOPtr nPtr = NEOPTR(pScrn); WAIT_ENGINE_IDLE(); OUTREG(NEOREG_DSTSTARTOFF, (y <<16) | (x & 0xffff)); OUTREG(NEOREG_XYEXT, (h<<16) | (w & 0xffff)); } static void Neo2200SetupForScanlineCPUToScreenColorExpandFill(ScrnInfoPtr pScrn, int fg, int bg, int rop, unsigned int planemask) { NEOPtr nPtr = NEOPTR(pScrn); NEOACLPtr nAcl = NEOACLPTR(pScrn); if (bg == -1) { /* transparent setup */ nAcl->tmpBltCntlFlags = ( NEO_BC0_SYS_TO_VID | NEO_BC0_SRC_MONO | NEO_BC0_SRC_TRANS | NEO_BC3_SKIP_MAPPING | NEO_BC3_DST_XY_ADDR | #ifdef NEO_DO_CLIPPING NEO_BC3_CLIP_ON | #endif neo2200Rop[rop]); WAIT_ENGINE_IDLE(); /*OUTREG16(NEOREG_BLTMODE, nAcl->BltModeFlags);*/ OUTREG(NEOREG_BLTSTAT, nAcl->BltModeFlags << 16); OUTREG(NEOREG_BLTCNTL, nAcl->tmpBltCntlFlags); OUTREG(NEOREG_FGCOLOR, fg); } else { /* opaque setup */ nAcl->tmpBltCntlFlags = ( NEO_BC0_SYS_TO_VID | NEO_BC0_SRC_MONO | NEO_BC3_SKIP_MAPPING | NEO_BC3_DST_XY_ADDR | #ifdef NEO_DO_CLIPPING NEO_BC3_CLIP_ON | #endif neo2200Rop[rop]); WAIT_ENGINE_IDLE(); /*OUTREG16(NEOREG_BLTMODE, nAcl->BltModeFlags);*/ OUTREG(NEOREG_BLTSTAT, nAcl->BltModeFlags << 16); OUTREG(NEOREG_FGCOLOR, fg); OUTREG(NEOREG_BGCOLOR, bg); } } static void Neo2200SubsequentScanlineCPUToScreenColorExpandFill(ScrnInfoPtr pScrn, int x, int y, int w, int h, int skipleft) { NEOPtr nPtr = NEOPTR(pScrn); NEOACLPtr nAcl = NEOACLPTR(pScrn); #ifdef NEO_DO_CLIPPING w = (w + 31) & ~31; #else nAcl->CPUToScreenColorExpandFill_x = x; nAcl->CPUToScreenColorExpandFill_y = y; nAcl->CPUToScreenColorExpandFill_w = w; nAcl->CPUToScreenColorExpandFill_h = h; nAcl->CPUToScreenColorExpandFill_skipleft = skipleft; #endif OUTREG(NEOREG_BLTCNTL, nAcl->tmpBltCntlFlags | ((skipleft << 2) & 0x1C)); #ifdef NEO_DO_CLIPPING OUTREG(NEOREG_CLIPLT, (y << 16) | (x + skipleft)); OUTREG(NEOREG_CLIPRB, ((y + h) << 16) | (x + w)); #endif OUTREG(NEOREG_SRCSTARTOFF, 0); OUTREG(NEOREG_DSTSTARTOFF, (y<<16) | (x & 0xffff)); #ifdef NEO_DO_CLIPPING OUTREG(NEOREG_XYEXT, (h<<16) | (w & 0xffff)); #else OUTREG(NEOREG_XYEXT, (1<<16) | (w & 0xffff)); #endif } static void Neo2200SubsequentColorExpandScanline(ScrnInfoPtr pScrn, int bufno) { NEOPtr nPtr = NEOPTR(pScrn); NEOACLPtr nAcl = NEOACLPTR(pScrn); #ifdef NEO_DO_CLIPPING /* Should I be waiting for fifo slots to prevent retries ? How do I do that on this engine ? */ #else if (!(--nAcl->CPUToScreenColorExpandFill_h)) return; WAIT_ENGINE_IDLE(); OUTREG(NEOREG_BLTCNTL, nAcl->tmpBltCntlFlags | ((nAcl->CPUToScreenColorExpandFill_skipleft << 2) & 0x1C)); OUTREG(NEOREG_SRCSTARTOFF, 0); OUTREG(NEOREG_DSTSTARTOFF, ((++nAcl->CPUToScreenColorExpandFill_y)<<16) | (nAcl->CPUToScreenColorExpandFill_x & 0xffff)); OUTREG(NEOREG_XYEXT, (1<<16) | (nAcl->CPUToScreenColorExpandFill_w & 0xffff)); #endif } #if 0 static void Neo2200SetupForMono8x8PatternFill(ScrnInfoPtr pScrn, int patternx, int patterny, int fg, int bg, int rop, unsigned int planemask) { NEOPtr nPtr = NEOPTR(pScrn); NEOACLPtr nAcl = NEOACLPTR(pScrn); if (bg == -1) { /* transparent setup */ nAcl->tmpBltCntlFlags = ( NEO_BC0_SRC_MONO | NEO_BC0_FILL_PAT | NEO_BC0_SRC_TRANS | NEO_BC3_SKIP_MAPPING | NEO_BC3_DST_XY_ADDR | neo2200Rop[rop]); WAIT_ENGINE_IDLE(); /*OUTREG16(NEOREG_BLTMODE, nAcl->BltModeFlags);*/ OUTREG(NEOREG_BLTSTAT, nAcl->BltModeFlags << 16); OUTREG(NEOREG_FGCOLOR, fg); OUTREG(NEOREG_SRCSTARTOFF, (patterny * pScrn->displayWidth * pScrn->bitsPerPixel + patternx) >> 3); } else { /* opaque setup */ nAcl->tmpBltCntlFlags = ( NEO_BC0_SRC_MONO | NEO_BC0_FILL_PAT | NEO_BC3_SKIP_MAPPING | NEO_BC3_DST_XY_ADDR | neo2200Rop[rop]); WAIT_ENGINE_IDLE(); /*OUTREG16(NEOREG_BLTMODE, nAcl->BltModeFlags);*/ OUTREG(NEOREG_BLTSTAT, nAcl->BltModeFlags << 16); OUTREG(NEOREG_FGCOLOR, fg); OUTREG(NEOREG_BGCOLOR, bg); OUTREG(NEOREG_SRCSTARTOFF, (patterny * pScrn->displayWidth * pScrn->bitsPerPixel + patternx) >> 3); } } static void Neo2200SubsequentMono8x8PatternFill(ScrnInfoPtr pScrn, int patternx, int patterny, int x, int y, int w, int h) { NEOPtr nPtr = NEOPTR(pScrn); NEOACLPtr nAcl = NEOACLPTR(pScrn); patterny &= 0x7; WAIT_ENGINE_IDLE(); OUTREG(NEOREG_BLTCNTL, nAcl->tmpBltCntlFlags | (patterny << 20) | ((patternx << 10) & 0x1C00)); OUTREG(NEOREG_SRCBITOFF, patternx); OUTREG(NEOREG_DSTSTARTOFF, (y<<16) | (x & 0xffff)); OUTREG(NEOREG_XYEXT, (h<<16) | (w & 0xffff)); } #endif
29.627692
111
0.645602
[ "solid" ]
04bfef0018e31091ce3ea5b5bfc190b0f7ccf3a6
3,903
h
C
Pods/Headers/Public/Metawear-iOSAPI/MBLConstants.h
aarons2222/Neofit
0acf17c3840809d17091d7d3baf3403a77c77d58
[ "Apache-2.0" ]
null
null
null
Pods/Headers/Public/Metawear-iOSAPI/MBLConstants.h
aarons2222/Neofit
0acf17c3840809d17091d7d3baf3403a77c77d58
[ "Apache-2.0" ]
null
null
null
Pods/Headers/Public/Metawear-iOSAPI/MBLConstants.h
aarons2222/Neofit
0acf17c3840809d17091d7d3baf3403a77c77d58
[ "Apache-2.0" ]
null
null
null
/** * MBLConstants.h * MetaWear * * Created by Stephen Schiffli on 7/30/14. * Copyright 2014 MbientLab Inc. All rights reserved. * * IMPORTANT: Your use of this Software is limited to those specific rights * granted under the terms of a software license agreement between the user who * downloaded the software, his/her employer (which must be your employer) and * MbientLab Inc, (the "License"). You may not use this Software unless you * agree to abide by the terms of the License which can be found at * www.mbientlab.com/terms . The License limits your use, and you acknowledge, * that the Software may not be modified, copied or distributed and can be used * solely and exclusively in conjunction with a MbientLab Inc, product. Other * than for the foregoing purpose, you may not use, reproduce, copy, prepare * derivative works of, modify, distribute, perform, display or sell this * Software and/or its documentation for any purpose. * * YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE * PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL * MBIENTLAB OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT, NEGLIGENCE, * STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE * THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED * TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST * PROFITS OR LOST DATA, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY, * SERVICES, OR ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY * DEFENSE THEREOF), OR OTHER SIMILAR COSTS. * * Should you have any questions regarding your right to use this Software, * contact MbientLab Inc, at www.mbientlab.com. */ #import <CoreBluetooth/CoreBluetooth.h> @class MBLAccelerometerData; @class MBLDeviceInfo; #pragma mark - Block Typedefs typedef void (^MBLVoidHandler)(); typedef void (^MBLErrorHandler)(NSError *error); typedef void (^MBLDataHandler)(NSData *data, NSError *error); typedef void (^MBLObjectHandler)(id obj, NSError *error); typedef void (^MBLArrayHandler)(NSArray *array); typedef void (^MBLArrayErrorHandler)(NSArray *array, NSError *error); typedef void (^MBLCentralManagerStateHandler)(CBCentralManagerState state); typedef void (^MBLPeripheralStateHandler)(CBPeripheralState state); typedef void (^MBLAccelerometerHandler)(MBLAccelerometerData *acceleration, NSError *error); typedef void (^MBLDeviceInfoHandler)(MBLDeviceInfo *deviceInfo, NSError *error); typedef void (^MBLDecimalNumberHandler)(NSDecimalNumber *number, NSError *error); typedef void (^MBLThresholdHandler)(NSDecimalNumber *number, BOOL isRising, NSError *error); typedef void (^MBLNumberHandler)(NSNumber *number, NSError *error); typedef void (^MBLSwitchStateHandler)(BOOL isPressed, NSError *error); typedef void (^MBLBoolHandler)(BOOL isTrue, NSError *error); typedef void (^MBLFloatHandler)(float number, NSError *error); typedef void (^MBLStringHandler)(NSString *string); typedef void (^MBLUrlHandler)(NSURL *url, NSError *error); #pragma mark - Errors extern NSString *const kMBLErrorDomain; /*! @abstract 100: Unexpected number of bluetooth services */ extern NSInteger const kMBLErrorUnexpectedServices; /*! @abstract 101: Unexpected number of bluetooth characteristics */ extern NSInteger const kMBLErrorUnexpectedCharacteristics; /*! @abstract 102: Couldn't connect to firmware updater */ extern NSInteger const kMBLErrorNoFirmwareUpdater; /*! @abstract 103: MetaWear object not recognized by MetaWearManager */ extern NSInteger const kMBLErrorInvalidMetaWearObject; /*! @abstract 104: MetaWear not charged enough for firmware update */ extern NSInteger const kMBLErrorInsufficientCharge;
49.405063
92
0.784525
[ "object" ]
04c0ddfee0a6b85fbf52c1e7d3adc4492b3eac95
1,343
h
C
webrtc_dsp/modules/audio_processing/echo_detector/circular_buffer.h
kovdan01/libtgvoip
6fec40ea1acd40fddba927b049f78962507d4922
[ "Unlicense" ]
null
null
null
webrtc_dsp/modules/audio_processing/echo_detector/circular_buffer.h
kovdan01/libtgvoip
6fec40ea1acd40fddba927b049f78962507d4922
[ "Unlicense" ]
null
null
null
webrtc_dsp/modules/audio_processing/echo_detector/circular_buffer.h
kovdan01/libtgvoip
6fec40ea1acd40fddba927b049f78962507d4922
[ "Unlicense" ]
null
null
null
/* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef MODULES_AUDIO_PROCESSING_ECHO_DETECTOR_CIRCULAR_BUFFER_H_ #define MODULES_AUDIO_PROCESSING_ECHO_DETECTOR_CIRCULAR_BUFFER_H_ #include <stddef.h> #include <vector> #include "absl/types/optional.h" namespace webrtc { // Ring buffer containing floating point values. struct CircularBuffer { public: explicit CircularBuffer(size_t size); ~CircularBuffer(); void Push(float value); absl::optional<float> Pop(); size_t Size() const { return nr_elements_in_buffer_; } // This function fills the buffer with zeros, but does not change its size. void Clear(); private: std::vector<float> buffer_; size_t next_insertion_index_ = 0; // This is the number of elements that have been pushed into the circular // buffer, not the allocated buffer size. size_t nr_elements_in_buffer_ = 0; }; } // namespace webrtc #endif // MODULES_AUDIO_PROCESSING_ECHO_DETECTOR_CIRCULAR_BUFFER_H_
29.195652
79
0.749069
[ "vector" ]
04c5a8dff15e2ac91fcb6ed2211dce9c49f9b47e
18,752
h
C
common/SimGeometry/MatrixAffine2.h
Mason-Wmx/ViewFramework
d8117adc646c369ad29d64477788514c7a75a797
[ "Apache-2.0" ]
1
2021-10-03T16:47:04.000Z
2021-10-03T16:47:04.000Z
common/SimGeometry/MatrixAffine2.h
Mason-Wmx/ViewFramework
d8117adc646c369ad29d64477788514c7a75a797
[ "Apache-2.0" ]
null
null
null
common/SimGeometry/MatrixAffine2.h
Mason-Wmx/ViewFramework
d8117adc646c369ad29d64477788514c7a75a797
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2012, The Cinder Project: http://libcinder.org All rights reserved. This code is intended for use with the Cinder C++ library: http://libcinder.org Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "Maths.h" #include "Vector.h" #include <iomanip> namespace SIM { namespace Geometry{ ////////////////////////////////////////////////////////////////////////////////////////////////////// // MatrixAffine2 // Represents a two dimensional affine transformation template<typename T> class MatrixAffine2 { public: typedef T TYPE; typedef T value_type; // static const size_t MEM_LEN = sizeof(T)*6; // // This class is OpenGL friendly and stores the m as how OpenGL would expect it. // m[i,j]: // | m[0,0] m[0,1] m[0,2] | // | m[1,0] m[1,1] m[1,2] | // // m[idx] // | m[0] m[2] m[4] | // | m[1] m[3] m[5] | // // mathematically this is: // | m[0] m[2] m[4] | // | m[1] m[3] m[5] | // | 0 0 1 | union { T m[6]; struct { // This looks like it's transposed from the above, but it's really not. // It just has to be written this way so it follows the right ordering // in the memory layout as well as being mathematically correct. T m00, m10; T m01, m11; T m02, m12; }; // [Cols][Rows] T mcols[3][2]; }; MatrixAffine2(); MatrixAffine2( T s ); MatrixAffine2( const T *dt ); // m[0]=d0, m[1]=d1, m[2]=d2 ... m[5]=d5 MatrixAffine2( T d0, T d1, T d2, T d3, T d4, T d5 ); // Creates matrix with column vectors vx, vy and z MatrixAffine2( const Vec2<T> &vx, const Vec2<T> &vy, const Vec2<T> &vz ); template<typename FromT> MatrixAffine2( const MatrixAffine2<FromT> &src ); MatrixAffine2( const MatrixAffine2<T> &src ); MatrixAffine2<T>& operator=( const MatrixAffine2<T>& rhs ); MatrixAffine2<T>& operator=( T rhs ); template<typename FromT> MatrixAffine2<T>& operator=( const MatrixAffine2<FromT> &rhs ); bool equalCompare( const MatrixAffine2<T>& rhs, T epsilon ) const; bool operator==( const MatrixAffine2<T> &rhs ) const { return equalCompare( rhs, (T)EPSILON ); } bool operator!=( const MatrixAffine2<T> &rhs ) const { return ! ( *this == rhs ); } MatrixAffine2<T>& operator*=( const MatrixAffine2<T> &rhs ); MatrixAffine2<T>& operator+=( const MatrixAffine2<T> &rhs ); MatrixAffine2<T>& operator-=( const MatrixAffine2<T> &rhs ); MatrixAffine2<T>& operator*=( T s ); MatrixAffine2<T>& operator/=( T s ); MatrixAffine2<T>& operator+=( T s ); MatrixAffine2<T>& operator-=( T s ); const MatrixAffine2<T> operator*( const MatrixAffine2<T> &rhs ) const; const MatrixAffine2<T> operator+( const MatrixAffine2<T> &rhs ) const; const MatrixAffine2<T> operator-( const MatrixAffine2<T> &rhs ) const; // post-multiplies column vector [rhs.x rhs.y 1] Vec2<T> transformPoint( const Vec2<T> &rhs ) const; // post-multiplies column vector [rhs.x rhs.y 1] const Vec2<T> operator*( const Vec2<T> &rhs ) const; // post-multiplies column vector [rhs.x rhs.y 0] Vec2<T> transformVec( const Vec2<T> &v ) const; const MatrixAffine2<T> operator*( T rhs ) const; const MatrixAffine2<T> operator/( T rhs ) const; const MatrixAffine2<T> operator+( T rhs ) const; const MatrixAffine2<T> operator-( T rhs ) const; // Accessors T& at( int row, int col ); const T& at( int row, int col ) const; T& operator[]( int idx ) { return m[idx]; } const T& operator[]( int idx ) const { return m[idx]; } void set( const T *dt ); // m[0]=d0, m[1]=d1, m[2]=d2 ... m[5]=d5 void set( T d0, T d1, T d2, T d3, T d4, T d5 ); Vec2<T> getColumn( int col ) const; void setColumn( int col, const Vec2<T> &v ); Vec3<T> getRow( int row ) const; void setRow( int row, const Vec3<T> &v ); void getColumns( Vec2<T> *c0, Vec2<T> *c1, Vec2<T> *c2 ) const; void setColumns( const Vec2<T> &c0, const Vec2<T> &c1, const Vec2<T> &c2 ); void getRows( Vec3<T> *r0, Vec3<T> *r1, Vec3<T> *r2 ) const; void setRows( const Vec3<T> &r0, const Vec3<T> &r1, const Vec3<T> &r2 ); // Sets the matrix to all zeros void setToNull(); // Sets the matrix to the identity matrix. void setToIdentity(); // Returns whether the matrix is singular (and consequently not invertible) or not bool isSingular() const; // Returns a copy of the matrix inverted. \a epsilon specifies the tolerance for testing for singularity. void invert(T epsilon = EPSILON ) { *this = invertCopy( epsilon ); } // Returns a copy of the matrix inverted. \a epsilon specifies the tolerance for testing for singularity. MatrixAffine2<T> invertCopy( T epsilon = EPSILON ) const; // concatenate translation by \a v (conceptually, translate is before 'this') void translate( const Vec2<T> &v ); // Returns a copy of the matrix translated by \a v MatrixAffine2 translateCopy( const Vec2<T> &v ) const { MatrixAffine2 result = *this; result.translate( v ); return result; } // concatenate rotation by \a radians (conceptually, rotate is before 'this') void rotate( T radians ) { *this *= MatrixAffine2<T>::makeRotate( radians ); } // concatenate rotation by \a radians around the point \a pt (conceptually, rotate is before 'this') void rotate( T radians, const Vec2<T> &pt ) { *this *= MatrixAffine2<T>::makeRotate( radians, pt ); } // Returns a copy of the matrix rotate by \a radians MatrixAffine2 rotateCopy( const Vec2<T> &v ) const { MatrixAffine2 result = *this; result.rotate( v ); return result; } // Returns a copy of the matrix rotate by \a radians around the point \a pt MatrixAffine2 rotateCopy( const Vec2<T> &v, const Vec2<T> &pt ) const { MatrixAffine2 result = *this; result.rotate( v, pt ); return result; } // concatenate scale (conceptually, scale is before 'this') void scale( T s ); // concatenate scale (conceptually, scale is before 'this') void scale( const Vec2<T> &v ); // Returns a copy of the matrix scaled by \a s MatrixAffine2 scaleCopy( T s ) const { MatrixAffine2 result = *this; result.scale( s ); return result; } // Returns a copy of the matrix scaled by \a v MatrixAffine2 scaleCopy( const Vec2<T> &v ) const { MatrixAffine2 result = *this; result.scale( v ); return result; } // returns an identity matrix static MatrixAffine2<T> identity() { return MatrixAffine2( 1, 0, 0, 1, 0, 0 ); } // returns 1 filled matrix static MatrixAffine2<T> one() { return MatrixAffine2( (T)1 ); } // returns 0 filled matrix static MatrixAffine2<T> zero() { return MatrixAffine2( (T)0 ); } // creates translation matrix static MatrixAffine2<T> makeTranslate( const Vec2<T> &v ); // creates rotation matrix by \a radians static MatrixAffine2<T> makeRotate( T radians ); // creates rotation matrix by \a radians around the point \a pt static MatrixAffine2<T> makeRotate( T radians, const Vec2<T> &pt ); // creates scale matrix static MatrixAffine2<T> makeScale( T s ); static MatrixAffine2<T> makeScale( const Vec2<T> &v ); static MatrixAffine2<T> makeSkewX( T radians ); static MatrixAffine2<T> makeSkewY( T radians ); friend std::ostream& operator<<( std::ostream &lhs, const MatrixAffine2<T> &rhs ) { for( int i = 0; i < 2; i++) { lhs << " |"; for( int j = 0; j < 3; j++) { lhs << std::setw( 12 ) << std::setprecision( 5 ) << rhs.m[j*2+i]; } lhs << "|" << std::endl; } return lhs; } }; template<typename T> MatrixAffine2<T>::MatrixAffine2() { setToIdentity(); } template<typename T> MatrixAffine2<T>::MatrixAffine2( T s ) { for( int i = 0; i < 6; ++i ) m[i] = s; } template<typename T> MatrixAffine2<T>::MatrixAffine2( const T *dt ) { set( dt ); } template<typename T> MatrixAffine2<T>::MatrixAffine2( T d0, T d1, T d2, T d3, T d4, T d5 ) { set( d0, d1, d2, d3, d4, d5 ); } template<typename T> MatrixAffine2<T>::MatrixAffine2( const Vec2<T> &vx, const Vec2<T> &vy, const Vec2<T> &vz ) { m00 = vx.x; m01 = vy.x; m02 = vz.x; m10 = vx.y; m11 = vy.y; m12 = vz.y; } template<typename T> template<typename FromT > MatrixAffine2<T>::MatrixAffine2( const MatrixAffine2<FromT> &src ) { for( int i = 0; i < 6; ++i ) { m[i] = static_cast<T>( src.m[i] ); } } template<typename T> MatrixAffine2<T>::MatrixAffine2( const MatrixAffine2<T>& src ) { std::memcpy( m, src.m, MEM_LEN ); } template<typename T> MatrixAffine2<T>& MatrixAffine2<T>::operator=( const MatrixAffine2<T>& rhs ) { memcpy( m, rhs.m, MEM_LEN ); return *this; } template<typename T> MatrixAffine2<T>& MatrixAffine2<T>::operator=( T rhs ) { for( int i = 0; i < 6; ++i ) { m[i] = rhs; } return *this; } template<typename T> template<typename FromT > MatrixAffine2<T>& MatrixAffine2<T>::operator=( const MatrixAffine2<FromT>& rhs ) { for( int i = 0; i < 6; i++ ) { m[i] = static_cast<T>(rhs.m[i]); } return *this; } template<typename T> bool MatrixAffine2<T>::equalCompare( const MatrixAffine2<T>& rhs, T epsilon ) const { for( int i = 0; i < 6; ++i ) { if( math<T>::abs(m[i] - rhs.m[i]) >= epsilon ) return false; } return true; } template<typename T> MatrixAffine2<T>& MatrixAffine2<T>::operator*=( const MatrixAffine2<T> &rhs ) { MatrixAffine2<T> mat; mat.m[0] = m[0]*rhs.m[0] + m[2]*rhs.m[1]; mat.m[1] = m[1]*rhs.m[0] + m[3]*rhs.m[1]; mat.m[2] = m[0]*rhs.m[2] + m[2]*rhs.m[3]; mat.m[3] = m[1]*rhs.m[2] + m[3]*rhs.m[3]; mat.m[4] = m[0]*rhs.m[4] + m[2]*rhs.m[5] + m[4]; mat.m[5] = m[1]*rhs.m[4] + m[3]*rhs.m[5] + m[5]; *this = mat; return *this; } template<typename T> MatrixAffine2<T>& MatrixAffine2<T>::operator+=( const MatrixAffine2<T> &rhs ) { for( int i = 0; i < 6; ++i ) m[i] += rhs.m[i]; return *this; } template<typename T> MatrixAffine2<T>& MatrixAffine2<T>::operator-=( const MatrixAffine2<T> &rhs ) { for( int i = 0; i < 6; ++i ) m[i] -= rhs.m[i]; return *this; } template<typename T> MatrixAffine2<T>& MatrixAffine2<T>::operator*=( T s ) { for( int i = 0; i < 6; ++i ) m[i] *= s; return *this; } template<typename T> MatrixAffine2<T>& MatrixAffine2<T>::operator/=( T s ) { T invS = 1 / s; for( int i = 0; i < 6; ++i ) m[i] *= invS; return *this; } template<typename T> MatrixAffine2<T>& MatrixAffine2<T>::operator+=( T s ) { for( int i = 0; i < 6; ++i ) m[i] += s; return *this; } template<typename T> MatrixAffine2<T>& MatrixAffine2<T>::operator-=( T s ) { for( int i = 0; i < 6; ++i ) m[i] -= s; return *this; } template<typename T> const MatrixAffine2<T> MatrixAffine2<T>::operator*( const MatrixAffine2<T> &rhs ) const { MatrixAffine2<T> ret; ret.m[0] = m[0]*rhs.m[0] + m[2]*rhs.m[1]; ret.m[1] = m[1]*rhs.m[0] + m[3]*rhs.m[1]; ret.m[2] = m[0]*rhs.m[2] + m[2]*rhs.m[3]; ret.m[3] = m[1]*rhs.m[2] + m[3]*rhs.m[3]; ret.m[4] = m[0]*rhs.m[4] + m[2]*rhs.m[5] + m[4]; ret.m[5] = m[1]*rhs.m[4] + m[3]*rhs.m[5] + m[5]; return ret; } template<typename T> const MatrixAffine2<T> MatrixAffine2<T>::operator+( const MatrixAffine2<T> &rhs ) const { MatrixAffine2<T> ret; for( int i = 0; i < 6; ++i ) ret.m[i] = m[i] + rhs.m[i]; return ret; } template<typename T> const MatrixAffine2<T> MatrixAffine2<T>::operator-( const MatrixAffine2<T> &rhs ) const { MatrixAffine2<T> ret; for( int i = 0; i < 6; ++i ) ret.m[i] = m[i] - rhs.m[i]; return ret; } template<typename T> Vec2<T> MatrixAffine2<T>::transformPoint( const Vec2<T> &rhs ) const { return Vec2<T>( rhs.x * m[0] + rhs.y * m[2] + m[4], rhs.x * m[1] + rhs.y * m[3] + m[5] ); } template<typename T> const Vec2<T> MatrixAffine2<T>::operator*( const Vec2<T> &rhs ) const { return Vec2<T>( rhs.x * m[0] + rhs.y * m[2] + m[4], rhs.x * m[1] + rhs.y * m[3] + m[5] ); } template<typename T> Vec2<T> MatrixAffine2<T>::transformVec( const Vec2<T> &v ) const { return Vec2<T>( v.x * m[0] + v.y * m[2], v.x * m[1] + v.y * m[3] ); } template<typename T> const MatrixAffine2<T> MatrixAffine2<T>::operator*( T rhs ) const { MatrixAffine2<T> ret; for( int i = 0; i < 6; ++i ) ret.m[i] = m[i]*rhs; return ret; } template<typename T> const MatrixAffine2<T> MatrixAffine2<T>::operator/( T rhs ) const { MatrixAffine2<T> ret; T invS = 1 / rhs; for( int i = 0; i < 6; ++i ) ret.m[i] = m[i] * invS; return ret; } template<typename T> const MatrixAffine2<T> MatrixAffine2<T>::operator+( T rhs ) const { MatrixAffine2<T> ret; for( int i = 0; i < 6; ++i ) ret.m[i] = m[i] + rhs; return ret; } template<typename T> const MatrixAffine2<T> MatrixAffine2<T>::operator-( T rhs ) const { MatrixAffine2<T> ret; for( int i = 0; i < 6; ++i ) ret.m[i] = m[i] - rhs; return ret; } template<typename T> T& MatrixAffine2<T>::at( int row, int col ) { assert(row >= 0 && row < 2); assert(col >= 0 && col < 3); return m[col*2 + row]; } template<typename T> const T& MatrixAffine2<T>::at( int row, int col ) const { assert(row >= 0 && row < 2); assert(col >= 0 && col < 3); return m[col*2 + row]; } template<typename T> void MatrixAffine2<T>::set( const T *d ) { m[0] = d[0]; m[3] = d[3]; m[1] = d[1]; m[4] = d[4]; m[2] = d[2]; m[5] = d[5]; } template<typename T> void MatrixAffine2<T>::set( T d0, T d1, T d2, T d3, T d4, T d5 ) { m[0] = d0; m[3] = d3; m[1] = d1; m[4] = d4; m[2] = d2; m[5] = d5; } template<typename T> Vec2<T> MatrixAffine2<T>::getColumn( int col ) const { size_t i = col*2; return Vec2<T>( m[i + 0], m[i + 1] ); } template<typename T> void MatrixAffine2<T>::setColumn( int col, const Vec2<T> &v ) { size_t i = col*2; m[i + 0] = v.x; m[i + 1] = v.y; } template<typename T> Vec3<T> MatrixAffine2<T>::getRow( int row ) const { return Vec3<T>( m[row + 0], m[row + 3], m[row + 6] ); } template<typename T> void MatrixAffine2<T>::setRow( int row, const Vec3<T> &v ) { m[row + 0] = v.x; m[row + 3] = v.y; m[row + 6] = v.z; } template<typename T> void MatrixAffine2<T>::getColumns( Vec2<T> *c0, Vec2<T> *c1, Vec2<T> *c2 ) const { *c0 = getColumn( 0 ); *c1 = getColumn( 1 ); *c2 = getColumn( 2 ); } template<typename T> void MatrixAffine2<T>::setColumns( const Vec2<T> &c0, const Vec2<T> &c1, const Vec2<T> &c2 ) { setColumn( 0, c0 ); setColumn( 1, c1 ); setColumn( 2, c2 ); } template<typename T> void MatrixAffine2<T>::getRows( Vec3<T> *r0, Vec3<T> *r1, Vec3<T> *r2 ) const { *r0 = getRow( 0 ); *r1 = getRow( 1 ); *r2 = getRow( 2 ); } template<typename T> void MatrixAffine2<T>::setRows( const Vec3<T> &r0, const Vec3<T> &r1, const Vec3<T> &r2 ) { setRow( 0, r0 ); setRow( 1, r1 ); setRow( 2, r2 ); } template<typename T> void MatrixAffine2<T>::setToNull() { std::memset( m, 0, MEM_LEN ); } template<typename T> void MatrixAffine2<T>::setToIdentity() { m[0] = 1; m[2] = 0; m[4] = 0; m[1] = 0; m[3] = 1; m[5] = 0; } template<typename T> bool MatrixAffine2<T>::isSingular() const { return fabs( m[0] * m[3] - m[2] * m[1] ) <= (T)EPSILON; } template<typename T> MatrixAffine2<T> MatrixAffine2<T>::invertCopy( T epsilon ) const { MatrixAffine2<T> inv; inv.m[0] = m[3]; inv.m[1] = -m[1]; inv.m[2] = -m[2]; inv.m[3] = m[0]; inv.m[4] = m[2]*m[5] - m[3]*m[4]; inv.m[5] = m[1]*m[4] - m[0]*m[5]; T det = m[0]*inv.m[0] + m[1]*inv.m[2]; if( fabs( det ) > epsilon ) { T invDet = 1 / det; inv.m[0] *= invDet; inv.m[1] *= invDet; inv.m[2] *= invDet; inv.m[3] *= invDet; inv.m[4] *= invDet; inv.m[5] *= invDet; } return inv; } template<typename T> void MatrixAffine2<T>::translate( const Vec2<T> &v ) { m[4] += m[0]*v.x + m[2]*v.y; m[5] += m[1]*v.x + m[3]*v.y; } template<typename T> void MatrixAffine2<T>::scale( const Vec2<T> &s ) { m[0] *= s.x; m[1] *= s.x; m[2] *= s.y; m[3] *= s.y; } template<typename T> MatrixAffine2<T> MatrixAffine2<T>::makeTranslate( const Vec2<T> &v ) { MatrixAffine2<T> ret; ret.m[0] = 1; ret.m[1] = 0; ret.m[2] = 0; ret.m[3] = 1; ret.m[4] = v.x; ret.m[5] = v.y; return ret; } template<typename T> MatrixAffine2<T> MatrixAffine2<T>::makeRotate( T radians ) { T sine = math<T>::sin( radians ); T cosine = math<T>::cos( radians ); MatrixAffine2<T> ret; ret.m[0] = cosine; ret.m[1] = sine; ret.m[2] = -sine; ret.m[3] = cosine; ret.m[4] = 0; ret.m[5] = 0; return ret; } template<typename T> MatrixAffine2<T> MatrixAffine2<T>::makeRotate( T radians, const Vec2<T> &pt ) { T sine = math<T>::sin( radians ); T cosine = math<T>::cos( radians ); MatrixAffine2<T> ret; ret.m[0] = cosine; ret.m[1] = sine; ret.m[2] = -sine; ret.m[3] = cosine; ret.m[4] = pt.x - cosine * pt.x + sine * pt.y; ret.m[5] = pt.y - sine * pt.x - cosine * pt.y; return ret; } template<typename T> MatrixAffine2<T> MatrixAffine2<T>::makeScale( T s ) { MatrixAffine2<T> ret; ret.m[0] = s; ret.m[1] = 0; ret.m[2] = 0; ret.m[3] = s; ret.m[4] = 0; ret.m[5] = 0; return ret; } template<typename T> MatrixAffine2<T> MatrixAffine2<T>::makeScale( const Vec2<T> &s ) { MatrixAffine2<T> ret; ret.m[0] = s.x; ret.m[1] = 0; ret.m[2] = 0; ret.m[3] = s.y; ret.m[4] = 0; ret.m[5] = 0; return ret; } template<typename T> MatrixAffine2<T> MatrixAffine2<T>::makeSkewX( T radians ) { MatrixAffine2<T> ret; ret.m[0] = 1; ret.m[1] = 0; ret.m[2] = math<T>::tan( radians ); ret.m[3] = 1; ret.m[4] = 0; ret.m[5] = 0; return ret; } template<typename T> MatrixAffine2<T> MatrixAffine2<T>::makeSkewY( T radians ) { MatrixAffine2<T> ret; ret.m[0] = 1; ret.m[1] = math<T>::tan( radians ); ret.m[2] = 0; ret.m[3] = 1; ret.m[4] = 0; ret.m[5] = 0; return ret; } ////////////////////////////////////////////////////////////////////////////////////////////////////// // Typedefs typedef MatrixAffine2<float> MatrixAffine2f; typedef MatrixAffine2<double> MatrixAffine2d; } // namespace internal }
24.969374
145
0.623347
[ "geometry", "vector" ]
04c6eac9211d777afc074a72f14c668411cd74f8
1,390
h
C
src/editor/private/project/scripted/QScriptedProjectExporter.h
Dandielo/mooned-editor
72f9068e3d6daaf42c1bc4be23dce2c5a260a6e8
[ "MIT" ]
null
null
null
src/editor/private/project/scripted/QScriptedProjectExporter.h
Dandielo/mooned-editor
72f9068e3d6daaf42c1bc4be23dce2c5a260a6e8
[ "MIT" ]
null
null
null
src/editor/private/project/scripted/QScriptedProjectExporter.h
Dandielo/mooned-editor
72f9068e3d6daaf42c1bc4be23dce2c5a260a6e8
[ "MIT" ]
null
null
null
#pragma once #include "project/interfaces/QProjectExporter.h" #include "scripts/CNativeScriptObject.h" #include <sstream> namespace editor { //! The script node type. class QScriptedNode; //! A AngelScript defined project exporter. class QScriptedProjectExporter : public QProjectExporter, public Scripts::CNativeScriptObject<QScriptedProjectExporter> { M_SCRIPT_TYPE(QScriptedProjectExporter, "CExporter"); public: //! The constructor takes the script related object as input. QScriptedProjectExporter(editor::script::ScriptObject&& object); //! Saves exported files on destruction? ~QScriptedProjectExporter() noexcept override; //! Serializes the given project object. //! \note Only object instances of the QScriptedProject are serialized. void export_project(QProject* project) const noexcept override; //! Serializes the given QScriptedGraph object. void export_project_element(QProjectElement* graph) const noexcept; protected: //! Writes string of text into the buffer. void write(const std::string& str) noexcept; //! Writes line into the buffer. void writeln(const std::string& str) noexcept; //! Saves the current buffer state under the given file name. //! \note This function clears the buffer. void flush(const std::string& file_name) noexcept; protected: std::stringstream _stream{ }; }; }
28.958333
119
0.745324
[ "object" ]
04c7a038d3eb73f7776c828cf7b0375bd16e1a85
3,358
h
C
IQ-TREE/pda/greedy.h
joshlvmh/iqtree_arm_neon
7bc67d3449428b0b683fb7359c8945da218f5775
[ "MIT" ]
1
2020-11-04T23:02:03.000Z
2020-11-04T23:02:03.000Z
IQ-TREE/pda/greedy.h
joshlvmh/iqtree_arm_neon
7bc67d3449428b0b683fb7359c8945da218f5775
[ "MIT" ]
4
2020-10-20T07:37:46.000Z
2022-01-11T14:31:32.000Z
IQ-TREE/pda/greedy.h
joshlvmh/iqtree_arm_neon
7bc67d3449428b0b683fb7359c8945da218f5775
[ "MIT" ]
1
2020-10-13T08:50:06.000Z
2020-10-13T08:50:06.000Z
/*************************************************************************** * Copyright (C) 2006 by BUI Quang Minh, Steffen Klaere, Arndt von Haeseler * * minh.bui@univie.ac.at * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef GREEDY_H #define GREEDY_H #include "pdtree.h" /** Implementation of greedy algorithm with complexity O(n*logk) @author BUI Quang Minh, Steffen Klaere, Arndt von Haeseler */ class Greedy : public PDTree { public: /** construct from program parameters @param params program parameters */ Greedy(Params &params) : PDTree(params) {} /** construct from a tree @param tree a tree class */ Greedy(PDTree &tree) : PDTree(tree) {} /** constructor */ Greedy() : PDTree() {}; /** run the algorithm @param params program parameters @param taxa_set (OUT) vector of PD sets */ void run(Params &params, vector<PDTaxaSet> &taxa_set); /** update the ordered list based on the recent longest path @param node the starting node @param subtree (OUT) resulted subtree @param cur_set the current set */ void updateOnLongestPath(Node *node, NodeVector &subtree, PDTaxaSet &cur_set); /** build the initial subtree based on the initial set of taxa @param node the starting node, NULL to start from the root @param dad dad of the node, used to direct the search @param subtree (OUT) resulted subtree @param nodestack (TEMP) stack of node, used only by function */ void buildOnInitialSet(NodeVector &subtree, NodeVector &nodestack, Node *node = NULL, Node *dad = NULL); /** initialize the ordered list based on the initial subtree structure @param subtree vector containing nodes in the subtree @return the subtree length */ double updateOnInitialSet(NodeVector &subtree); /** @return innodes.begin(). */ NeighborSet::iterator highestNeighbor(); /** add an edge into the NeighborSet */ void addNeighbor(Neighbor* neigh); //NodeSet innodes; /** neighbor set */ NeighborSet neighset; /** list of nodes in the subtree */ NodeVector subtree; private: /** size of list of nodes, used internally during greedy search */ int list_size; }; #endif
29.716814
105
0.589934
[ "vector" ]
04cf8b5a6143d9e5a19a766101a0cb6fe06207b9
18,646
c
C
src/plugins/RePlugin/RePlugin.c
p3anoman/vm
4bb3d87ad955dc4fa8f6465aec1f3a70109c28e5
[ "MIT" ]
null
null
null
src/plugins/RePlugin/RePlugin.c
p3anoman/vm
4bb3d87ad955dc4fa8f6465aec1f3a70109c28e5
[ "MIT" ]
null
null
null
src/plugins/RePlugin/RePlugin.c
p3anoman/vm
4bb3d87ad955dc4fa8f6465aec1f3a70109c28e5
[ "MIT" ]
null
null
null
/* Automatically generated by SmartSyntaxPluginCodeGenerator VMMaker.oscog-eem.2987 uuid: a04be31b-0684-47d9-8eab-044c097bce29 from RePlugin VMMaker.oscog-eem.2987 uuid: a04be31b-0684-47d9-8eab-044c097bce29 */ static char __buildInfo[] = "RePlugin VMMaker.oscog-eem.2987 uuid: a04be31b-0684-47d9-8eab-044c097bce29 " __DATE__ ; #include "config.h" #include <math.h> #include "sqMathShim.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> /* Do not include the entire sq.h file but just those parts needed. */ #include "sqConfig.h" /* Configuration options */ #include "sqVirtualMachine.h" /* The virtual machine proxy definition */ #include "sqPlatformSpecific.h" /* Platform specific definitions */ #include "rePlugin.h" #include "sqMemoryAccess.h" #define true 1 #define false 0 #define null 0 /* using 'null' because nil is predefined in Think C */ #ifdef SQUEAK_BUILTIN_PLUGIN # undef EXPORT # define EXPORT(returnType) static returnType # define INT_EXT "(i)" #else # define INT_EXT "(e)" #endif /*** Function Prototypes ***/ static sqInt allocateByteArrayAndSetRcvrExtraPtrFrom(sqInt anExtraPtr); static sqInt allocateByteArrayAndSetRcvrPCREPtrFromPCRE(sqInt aPCREPtr); static sqInt allocateStringAndSetRcvrErrorStrFromCStr(const char *aCStrBuffer); EXPORT(const char*) getModuleName(void); static sqInt loadRcvrFromStackAt(sqInt stackInteger); EXPORT(sqInt) primLastAlloc(void); EXPORT(sqInt) primNetMemory(void); EXPORT(sqInt) primNumAllocs(void); EXPORT(sqInt) primNumFrees(void); EXPORT(sqInt) primPCRECompile(void); EXPORT(sqInt) primPCREExec(void); EXPORT(sqInt) primPCREExecfromto(void); EXPORT(sqInt) primPCRENumSubPatterns(void); static sqInt rcvrCompileFlags(void); static sqInt rcvrErrorOffsetFrom(sqInt anInteger); static sqInt rcvrErrorStrFrom(sqInt aString); static sqInt rcvrExtraPtr(void); static sqInt rcvrExtraPtrFrom(sqInt aByteArrayOrNilObject); static sqInt rcvrMatchFlags(void); static int * rcvrMatchSpacePtr(void); static sqInt rcvrMatchSpaceSize(void); static char * rcvrPatternStrPtr(void); static sqInt rcvrPCREBufferFrom(sqInt aByteArray); static sqInt rcvrPCREBufferPtr(void); static void rePluginFree(void *aPointer); static void * rePluginMalloc(size_t anInteger); EXPORT(sqInt) setInterpreter(struct VirtualMachine *anInterpreter); /*** Variables ***/ static sqInt compileFlags; static sqInt errorStr; static const char * errorStrBuffer; static sqInt extraPtr; #if !defined(SQUEAK_BUILTIN_PLUGIN) static void * (*arrayValueOf)(sqInt oop); static sqInt (*byteSizeOf)(sqInt oop); static sqInt (*classByteArray)(void); static sqInt (*classString)(void); static sqInt (*failed)(void); static void * (*fetchArrayofObject)(sqInt fieldIndex, sqInt objectPointer); static sqInt (*fetchIntegerofObject)(sqInt fieldIndex, sqInt objectPointer); static sqInt (*fetchPointerofObject)(sqInt index, sqInt oop); static sqInt (*instantiateClassindexableSize)(sqInt classPointer, sqInt size); static sqInt (*nilObject)(void); static sqInt (*pop)(sqInt nItems); static sqInt (*popthenPush)(sqInt nItems, sqInt oop); static sqInt (*pushInteger)(sqInt integerValue); static sqInt (*stackIntegerValue)(sqInt offset); static sqInt (*stackObjectValue)(sqInt offset); static sqInt (*storeIntegerofObjectwithValue)(sqInt index, sqInt oop, sqInt integer); static sqInt (*storePointerofObjectwithValue)(sqInt index, sqInt oop, sqInt valuePointer); static sqInt (*success)(sqInt aBoolean); #else /* !defined(SQUEAK_BUILTIN_PLUGIN) */ extern void * arrayValueOf(sqInt oop); extern sqInt byteSizeOf(sqInt oop); extern sqInt classByteArray(void); extern sqInt classString(void); extern sqInt failed(void); extern void * fetchArrayofObject(sqInt fieldIndex, sqInt objectPointer); extern sqInt fetchIntegerofObject(sqInt fieldIndex, sqInt objectPointer); extern sqInt fetchPointerofObject(sqInt index, sqInt oop); extern sqInt instantiateClassindexableSize(sqInt classPointer, sqInt size); extern sqInt nilObject(void); extern sqInt pop(sqInt nItems); extern sqInt popthenPush(sqInt nItems, sqInt oop); extern sqInt pushInteger(sqInt integerValue); extern sqInt stackIntegerValue(sqInt offset); extern sqInt stackObjectValue(sqInt offset); extern sqInt storeIntegerofObjectwithValue(sqInt index, sqInt oop, sqInt integer); extern sqInt storePointerofObjectwithValue(sqInt index, sqInt oop, sqInt valuePointer); extern sqInt success(sqInt aBoolean); extern #endif struct VirtualMachine* interpreterProxy; static sqInt matchFlags; static const char *moduleName = "RePlugin VMMaker.oscog-eem.2987 " INT_EXT; static sqInt patternStr; static const char * patternStrPtr; static sqInt pcrePtr; static sqInt rcvr; static int errorOffset; static int lastAlloc = 0; static int netMemory = 0; static int numAllocs = 0; static int numFrees = 0; /* RePlugin>>#allocateByteArrayAndSetRcvrExtraPtrFrom: */ static sqInt allocateByteArrayAndSetRcvrExtraPtrFrom(sqInt anExtraPtr) { void *extraByteArrayPtr; sqInt extraObject; extraByteArrayPtr = ((void *) 0); if (anExtraPtr) { /* Allocate a Smalltalk ByteArray -- lastAlloc contains the length */ extraObject = instantiateClassindexableSize(classByteArray(), sizeof(real_pcre_extra)); /* begin loadRcvrFromStackAt: */ rcvr = stackObjectValue(0); extraByteArrayPtr = arrayValueOf(extraObject); memcpy(extraByteArrayPtr, (void *) anExtraPtr, sizeof(real_pcre_extra)); } else { extraObject = nilObject(); } /* begin rcvrExtraPtrFrom: */ storePointerofObjectwithValue(3, rcvr, extraObject); return extraObject; } /* RePlugin>>#allocateByteArrayAndSetRcvrPCREPtrFromPCRE: */ static sqInt allocateByteArrayAndSetRcvrPCREPtrFromPCRE(sqInt aPCREPtr) { void *patByteArrayPtr; sqInt patObject; /* Allocate a Smalltalk ByteArray -- lastAlloc contains the length */ patObject = instantiateClassindexableSize(classByteArray(), lastAlloc); /* begin loadRcvrFromStackAt: */ rcvr = stackObjectValue(0); patByteArrayPtr = arrayValueOf(patObject); memcpy(patByteArrayPtr, (void *) aPCREPtr, lastAlloc); /* begin rcvrPCREBufferFrom: */ storePointerofObjectwithValue(2, rcvr, patObject); return patObject; } /* RePlugin>>#allocateStringAndSetRcvrErrorStrFromCStr: */ static sqInt allocateStringAndSetRcvrErrorStrFromCStr(const char *aCStrBuffer) { sqInt errorStrObj; void *errorStrObjPtr; sqInt length; /* Allocate errorStrObj */ length = strlen(aCStrBuffer); errorStrObj = instantiateClassindexableSize(classString(), length); /* begin loadRcvrFromStackAt: */ rcvr = stackObjectValue(0); errorStrObjPtr = arrayValueOf(errorStrObj); memcpy(errorStrObjPtr,aCStrBuffer,length); /* begin rcvrErrorStrFrom: */ storePointerofObjectwithValue(4, rcvr, errorStrObj); return errorStrObj; } /* Note: This is hardcoded so it can be run from Squeak. The module name is used for validating a module *after* it is loaded to check if it does really contain the module we're thinking it contains. This is important! */ /* InterpreterPlugin>>#getModuleName */ EXPORT(const char*) getModuleName(void) { return moduleName; } /* RePlugin>>#loadRcvrFromStackAt: */ static sqInt loadRcvrFromStackAt(sqInt stackInteger) { rcvr = stackObjectValue(stackInteger); return 0; } /* RePlugin>>#primLastAlloc */ EXPORT(sqInt) primLastAlloc(void) { pop(1); pushInteger(lastAlloc); return 0; } /* RePlugin>>#primNetMemory */ EXPORT(sqInt) primNetMemory(void) { pop(1); pushInteger(netMemory); return 0; } /* RePlugin>>#primNumAllocs */ EXPORT(sqInt) primNumAllocs(void) { pop(1); pushInteger(numAllocs); return 0; } /* RePlugin>>#primNumFrees */ EXPORT(sqInt) primNumFrees(void) { pop(1); pushInteger(numFrees); return 0; } /* <rcvr primPCRECompile>, where rcvr is an object with instance variables: 'patternStr compileFlags pcrePtr extraPtr errorStr errorOffset matchFlags' Compile the regular expression in patternStr, and if the compilation is successful, attempt to optimize the compiled expression. Store the results in <pcrePtr> and <extratr>, or fill errorStr with a meaningful errorString and errorOffset with an indicator where the error was found, applying compileFlags throughout. Answer nil with a clean compile (regardless of whether an optimization is possible, and answer with the string otherwise. */ /* RePlugin>>#primPCRECompile */ EXPORT(sqInt) primPCRECompile(void) { /* begin loadRcvrFromStackAt: */ rcvr = stackObjectValue(0); patternStrPtr = ((char *) (fetchArrayofObject(0, rcvr))); compileFlags = fetchIntegerofObject(1, rcvr); if (failed()) { return null; } pcrePtr = (sqInt) pcre_compile(patternStrPtr, compileFlags, &errorStrBuffer, &errorOffset, NULL); if (pcrePtr) { allocateByteArrayAndSetRcvrPCREPtrFromPCRE(pcrePtr); extraPtr = (sqInt) pcre_study((pcre *)pcrePtr, compileFlags, &errorStrBuffer); allocateByteArrayAndSetRcvrExtraPtrFrom(extraPtr); /* begin rePluginFree: */ numFrees += 1; if ((((void *)pcrePtr)) != null) { free(((void *)pcrePtr)); } if (extraPtr) { /* begin rePluginFree: */ numFrees += 1; if ((((void *)extraPtr)) != null) { free(((void *)extraPtr)); } } if (failed()) { return null; } popthenPush(1, nilObject()); } else { errorStr = allocateStringAndSetRcvrErrorStrFromCStr(errorStrBuffer); /* begin rcvrErrorOffsetFrom: */ storeIntegerofObjectwithValue(5, rcvr, errorOffset); if (failed()) { return null; } popthenPush(1, errorStr); } return 0; } /* <rcvr primPCREExec: searchObject>, where rcvr is an object with instance variables: 'patternStr compileFlags pcrePtr extraPtr errorStr errorOffset matchFlags' Apply the regular expression (stored in <pcrePtr> and <extratr>, generated from calls to primPCRECompile), to smalltalk String searchObject using <matchOptions>. If there is no match, answer nil. Otherwise answer a ByteArray of offsets representing the results of the match. */ /* RePlugin>>#primPCREExec */ EXPORT(sqInt) primPCREExec(void) { sqInt extraObj; sqInt length; int *matchSpacePtr; sqInt matchSpaceSize; sqInt result; char *searchBuffer; sqInt searchObject; /* Load Parameters */ searchObject = stackObjectValue(0); searchBuffer = arrayValueOf(searchObject); length = byteSizeOf(searchObject); /* begin loadRcvrFromStackAt: */ rcvr = stackObjectValue(1); pcrePtr = ((sqInt) (fetchArrayofObject(2, rcvr))); /* begin rcvrExtraPtr */ extraObj = fetchPointerofObject(3, rcvr); extraPtr = ((sqInt) ((!(extraObj == (nilObject())) ? arrayValueOf(extraObj) : 0))); matchFlags = fetchIntegerofObject(6, rcvr); matchSpacePtr = ((int *) (fetchArrayofObject(7, rcvr))); matchSpaceSize = (byteSizeOf(fetchPointerofObject(7, rcvr))) / 4; if (failed()) { return null; } result = pcre_exec((pcre *)pcrePtr, (pcre_extra *)extraPtr, searchBuffer, length, 0, matchFlags, matchSpacePtr, matchSpaceSize); pop(2); pushInteger(result); return 0; } /* <rcvr primPCREExec: searchObject from: fromInteger to: toInteger>, where rcvr is an object with instance variables: 'patternStr compileFlags pcrePtr extraPtr errorStr errorOffset matchFlags' Apply the regular expression (stored in <pcrePtr> and <extratr>, generated from calls to primPCRECompile), to smalltalk String searchObject using <matchOptions>, beginning at offset <fromInteger> and continuing until offset <toInteger>. If there is no match, answer nil. Otherwise answer a ByteArray of offsets representing the results of the match. */ /* RePlugin>>#primPCREExecfromto */ EXPORT(sqInt) primPCREExecfromto(void) { sqInt extraObj; sqInt fromInteger; sqInt length; int *matchSpacePtr; sqInt matchSpaceSize; sqInt result; char *searchBuffer; sqInt searchObject; sqInt toInteger; /* Load Parameters */ toInteger = stackIntegerValue(0); fromInteger = stackIntegerValue(1); searchObject = stackObjectValue(2); searchBuffer = arrayValueOf(searchObject); length = byteSizeOf(searchObject); /* begin loadRcvrFromStackAt: */ rcvr = stackObjectValue(3); success(1 <= fromInteger); success(toInteger <= length); /* Smalltalk offsets are 1-based */ fromInteger -= 1; success(fromInteger <= toInteger); length = toInteger - fromInteger; /* Load Instance Variables */ searchBuffer += fromInteger; pcrePtr = ((sqInt) (fetchArrayofObject(2, rcvr))); /* begin rcvrExtraPtr */ extraObj = fetchPointerofObject(3, rcvr); extraPtr = ((sqInt) ((!(extraObj == (nilObject())) ? arrayValueOf(extraObj) : 0))); matchFlags = fetchIntegerofObject(6, rcvr); matchSpacePtr = ((int *) (fetchArrayofObject(7, rcvr))); matchSpaceSize = (byteSizeOf(fetchPointerofObject(7, rcvr))) / 4; if (failed()) { return null; } result = pcre_exec((pcre *)pcrePtr, (pcre_extra *)extraPtr, searchBuffer, length, 0, matchFlags, matchSpacePtr, matchSpaceSize); pop(4); pushInteger(result); return 0; } /* <rcvr primPCRENumSubPatterns>, where rcvr is an object with instance variables: 'patternStr compileFlags pcrePtr extraPtr errorStr errorOffset matchFlags' Return the number of subpatterns captured by the compiled pattern. */ /* Load Parameters */ /* RePlugin>>#primPCRENumSubPatterns */ EXPORT(sqInt) primPCRENumSubPatterns(void) { sqInt ncap; /* begin loadRcvrFromStackAt: */ rcvr = stackObjectValue(0); pcrePtr = ((sqInt) (fetchArrayofObject(2, rcvr))); pcre_fullinfo((const pcre *)pcrePtr, NULL, PCRE_INFO_CAPTURECOUNT, &ncap); pop(1); pushInteger(ncap); return 0; } /* RePlugin>>#rcvrCompileFlags */ static sqInt rcvrCompileFlags(void) { return fetchIntegerofObject(1, rcvr); } /* RePlugin>>#rcvrErrorOffsetFrom: */ static sqInt rcvrErrorOffsetFrom(sqInt anInteger) { storeIntegerofObjectwithValue(5, rcvr, anInteger); return 0; } /* RePlugin>>#rcvrErrorStrFrom: */ static sqInt rcvrErrorStrFrom(sqInt aString) { storePointerofObjectwithValue(4, rcvr, aString); return 0; } /* RePlugin>>#rcvrExtraPtr */ static sqInt rcvrExtraPtr(void) { sqInt extraObj; extraObj = fetchPointerofObject(3, rcvr); return ((sqInt) ((!(extraObj == (nilObject())) ? arrayValueOf(extraObj) : 0))); } /* RePlugin>>#rcvrExtraPtrFrom: */ static sqInt rcvrExtraPtrFrom(sqInt aByteArrayOrNilObject) { storePointerofObjectwithValue(3, rcvr, aByteArrayOrNilObject); return 0; } /* RePlugin>>#rcvrMatchFlags */ static sqInt rcvrMatchFlags(void) { return fetchIntegerofObject(6, rcvr); } /* RePlugin>>#rcvrMatchSpacePtr */ static int * rcvrMatchSpacePtr(void) { return ((int *) (fetchArrayofObject(7, rcvr))); } /* RePlugin>>#rcvrMatchSpaceSize */ static sqInt rcvrMatchSpaceSize(void) { return (byteSizeOf(fetchPointerofObject(7, rcvr))) / 4; } /* RePlugin>>#rcvrPatternStrPtr */ static char * rcvrPatternStrPtr(void) { return ((char *) (fetchArrayofObject(0, rcvr))); } /* RePlugin>>#rcvrPCREBufferFrom: */ static sqInt rcvrPCREBufferFrom(sqInt aByteArray) { storePointerofObjectwithValue(2, rcvr, aByteArray); return 0; } /* RePlugin>>#rcvrPCREBufferPtr */ static sqInt rcvrPCREBufferPtr(void) { return ((sqInt) (fetchArrayofObject(2, rcvr))); } /* Free a block of fixed memory allocated with rePluginMalloc. Instrumented version of C free() to facilitate leak analysis from Smalltalk. OS-specific variations on malloc/free, such as with MacOS, are handled by adding a C macro to the header file redefining malloc/free -- see the class comment */ /* RePlugin>>#rePluginFree: */ static void rePluginFree(void *aPointer) { numFrees += 1; if (aPointer != null) { free(aPointer); } } /* Allocate a block of fixed memory using C calls to malloc(). Instrumented to facilitate leak analysis from Smalltalk. Set global lastAlloc to anInteger. OS-specific variations on malloc/free, such as with MacOS, are handled by adding a C macro to the header file redefining malloc/free -- see the class comment */ /* RePlugin>>#rePluginMalloc: */ static void * rePluginMalloc(size_t anInteger) { void *aPointer; numAllocs += 1; if (((aPointer = malloc(anInteger))) != null) { lastAlloc = anInteger; } return aPointer; } /* Note: This is coded so that it can be run in Squeak. */ /* InterpreterPlugin>>#setInterpreter: */ EXPORT(sqInt) setInterpreter(struct VirtualMachine *anInterpreter) { sqInt ok; /* This may seem tautological, but in a real plugin it checks that the VM provides the version the plugin was compiled against which is the version the plugin expects. */ interpreterProxy = anInterpreter; ok = ((interpreterProxy->majorVersion()) == (VM_PROXY_MAJOR)) && ((interpreterProxy->minorVersion()) >= (VM_PROXY_MINOR)); if (ok) { #if !defined(SQUEAK_BUILTIN_PLUGIN) arrayValueOf = interpreterProxy->arrayValueOf; byteSizeOf = interpreterProxy->byteSizeOf; classByteArray = interpreterProxy->classByteArray; classString = interpreterProxy->classString; failed = interpreterProxy->failed; fetchArrayofObject = interpreterProxy->fetchArrayofObject; fetchIntegerofObject = interpreterProxy->fetchIntegerofObject; fetchPointerofObject = interpreterProxy->fetchPointerofObject; instantiateClassindexableSize = interpreterProxy->instantiateClassindexableSize; nilObject = interpreterProxy->nilObject; pop = interpreterProxy->pop; popthenPush = interpreterProxy->popthenPush; pushInteger = interpreterProxy->pushInteger; stackIntegerValue = interpreterProxy->stackIntegerValue; stackObjectValue = interpreterProxy->stackObjectValue; storeIntegerofObjectwithValue = interpreterProxy->storeIntegerofObjectwithValue; storePointerofObjectwithValue = interpreterProxy->storePointerofObjectwithValue; success = interpreterProxy->success; #endif /* !defined(SQUEAK_BUILTIN_PLUGIN) */ } return ok; } #ifdef SQUEAK_BUILTIN_PLUGIN static char _m[] = "RePlugin"; void* RePlugin_exports[][3] = { {(void*)_m, "getModuleName", (void*)getModuleName}, {(void*)_m, "primLastAlloc\000\377", (void*)primLastAlloc}, {(void*)_m, "primNetMemory\000\377", (void*)primNetMemory}, {(void*)_m, "primNumAllocs\000\377", (void*)primNumAllocs}, {(void*)_m, "primNumFrees\000\377", (void*)primNumFrees}, {(void*)_m, "primPCRECompile\000\000", (void*)primPCRECompile}, {(void*)_m, "primPCREExec\000\001", (void*)primPCREExec}, {(void*)_m, "primPCREExecfromto\000\001", (void*)primPCREExecfromto}, {(void*)_m, "primPCRENumSubPatterns\000\000", (void*)primPCRENumSubPatterns}, {(void*)_m, "setInterpreter", (void*)setInterpreter}, {NULL, NULL, NULL} }; #else /* ifdef SQ_BUILTIN_PLUGIN */ EXPORT(signed char) primPCRECompileAccessorDepth = 0; EXPORT(signed char) primPCREExecAccessorDepth = 1; EXPORT(signed char) primPCREExecfromtoAccessorDepth = 1; EXPORT(signed char) primPCRENumSubPatternsAccessorDepth = 0; #endif /* ifdef SQ_BUILTIN_PLUGIN */
29.271586
116
0.757964
[ "object" ]
04d23cc7cd4a64f3a614299d3ae95045fabfcffd
68,005
c
C
linux/drivers/staging/mt7621-mmc/sd.c
WUSTL-CSPL/RT-TEE
aafb3e9ff6c6e744c6bce1e42bcb198e1063efcc
[ "MIT" ]
3
2020-11-06T05:17:03.000Z
2020-11-06T07:32:34.000Z
linux/drivers/staging/mt7621-mmc/sd.c
WUSTL-CSPL/RT-TEE
aafb3e9ff6c6e744c6bce1e42bcb198e1063efcc
[ "MIT" ]
null
null
null
linux/drivers/staging/mt7621-mmc/sd.c
WUSTL-CSPL/RT-TEE
aafb3e9ff6c6e744c6bce1e42bcb198e1063efcc
[ "MIT" ]
1
2020-11-06T07:32:55.000Z
2020-11-06T07:32:55.000Z
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein * is confidential and proprietary to MediaTek Inc. and/or its licensors. * Without the prior written permission of MediaTek inc. and/or its licensors, * any reproduction, modification, use or disclosure of MediaTek Software, * and information contained herein, in whole or in part, shall be strictly prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek Software") * have been modified by MediaTek Inc. All revisions are subject to any receiver's * applicable license agreements with MediaTek Inc. */ #include <linux/module.h> #include <linux/delay.h> #include <linux/dma-mapping.h> #include <linux/spinlock.h> #include <linux/platform_device.h> #include <linux/mmc/host.h> #include <linux/mmc/mmc.h> #include <linux/mmc/sd.h> #include <linux/mmc/sdio.h> #include <asm/mach-ralink/ralink_regs.h> #include "board.h" #include "dbg.h" #include "mt6575_sd.h" #ifdef CONFIG_SOC_MT7621 #define RALINK_SYSCTL_BASE 0xbe000000 #else #define RALINK_SYSCTL_BASE 0xb0000000 #endif #define DRV_NAME "mtk-sd" #if defined(CONFIG_SOC_MT7620) #define HOST_MAX_MCLK (48000000) /* +/- by chhung */ #elif defined(CONFIG_SOC_MT7621) #define HOST_MAX_MCLK (50000000) /* +/- by chhung */ #endif #define HOST_MIN_MCLK (260000) #define HOST_MAX_BLKSZ (2048) #define MSDC_OCR_AVAIL (MMC_VDD_28_29 | MMC_VDD_29_30 | MMC_VDD_30_31 | MMC_VDD_31_32 | MMC_VDD_32_33) #define GPIO_PULL_DOWN (0) #define GPIO_PULL_UP (1) #if 0 /* --- by chhung */ #define MSDC_CLKSRC_REG (0xf100000C) #define PDN_REG (0xF1000010) #endif /* end of --- */ #define DEFAULT_DEBOUNCE (8) /* 8 cycles */ #define DEFAULT_DTOC (40) /* data timeout counter. 65536x40 sclk. */ #define CMD_TIMEOUT (HZ / 10) /* 100ms */ #define DAT_TIMEOUT (HZ / 2 * 5) /* 500ms x5 */ #define MAX_DMA_CNT (64 * 1024 - 512) /* a single transaction for WIFI may be 50K*/ #define MAX_GPD_NUM (1 + 1) /* one null gpd */ #define MAX_BD_NUM (1024) #define MAX_HW_SGMTS (MAX_BD_NUM) #define MAX_SGMT_SZ (MAX_DMA_CNT) #define MAX_REQ_SZ (MAX_SGMT_SZ * 8) static int cd_active_low = 1; //================================= #define PERI_MSDC0_PDN (15) //#define PERI_MSDC1_PDN (16) //#define PERI_MSDC2_PDN (17) //#define PERI_MSDC3_PDN (18) #if 0 /* --- by chhung */ /* gate means clock power down */ static int g_clk_gate = 0; #define msdc_gate_clock(id) \ do { \ g_clk_gate &= ~(1 << ((id) + PERI_MSDC0_PDN)); \ } while (0) /* not like power down register. 1 means clock on. */ #define msdc_ungate_clock(id) \ do { \ g_clk_gate |= 1 << ((id) + PERI_MSDC0_PDN); \ } while (0) // do we need sync object or not void msdc_clk_status(int *status) { *status = g_clk_gate; } #endif /* end of --- */ /* +++ by chhung */ struct msdc_hw msdc0_hw = { .clk_src = 0, .flags = MSDC_CD_PIN_EN | MSDC_REMOVABLE, // .flags = MSDC_WP_PIN_EN | MSDC_CD_PIN_EN | MSDC_REMOVABLE, }; /* end of +++ */ static int msdc_rsp[] = { 0, /* RESP_NONE */ 1, /* RESP_R1 */ 2, /* RESP_R2 */ 3, /* RESP_R3 */ 4, /* RESP_R4 */ 1, /* RESP_R5 */ 1, /* RESP_R6 */ 1, /* RESP_R7 */ 7, /* RESP_R1b */ }; #define msdc_dma_on() sdr_clr_bits(host->base + MSDC_CFG, MSDC_CFG_PIO) static void msdc_reset_hw(struct msdc_host *host) { sdr_set_bits(host->base + MSDC_CFG, MSDC_CFG_RST); while (readl(host->base + MSDC_CFG) & MSDC_CFG_RST) cpu_relax(); } #define msdc_clr_int() \ do { \ volatile u32 val = readl(host->base + MSDC_INT); \ writel(val, host->base + MSDC_INT); \ } while (0) static void msdc_clr_fifo(struct msdc_host *host) { sdr_set_bits(host->base + MSDC_FIFOCS, MSDC_FIFOCS_CLR); while (readl(host->base + MSDC_FIFOCS) & MSDC_FIFOCS_CLR) cpu_relax(); } #define msdc_irq_save(val) \ do { \ val = readl(host->base + MSDC_INTEN); \ sdr_clr_bits(host->base + MSDC_INTEN, val); \ } while (0) #define msdc_irq_restore(val) \ do { \ sdr_set_bits(host->base + MSDC_INTEN, val); \ } while (0) /* clock source for host: global */ #if defined(CONFIG_SOC_MT7620) static u32 hclks[] = {48000000}; /* +/- by chhung */ #elif defined(CONFIG_SOC_MT7621) static u32 hclks[] = {50000000}; /* +/- by chhung */ #endif //============================================ // the power for msdc host controller: global // always keep the VMC on. //============================================ #define msdc_vcore_on(host) \ do { \ INIT_MSG("[+]VMC ref. count<%d>", ++host->pwr_ref); \ (void)hwPowerOn(MT65XX_POWER_LDO_VMC, VOL_3300, "SD"); \ } while (0) #define msdc_vcore_off(host) \ do { \ INIT_MSG("[-]VMC ref. count<%d>", --host->pwr_ref); \ (void)hwPowerDown(MT65XX_POWER_LDO_VMC, "SD"); \ } while (0) //==================================== // the vdd output for card: global // always keep the VMCH on. //==================================== #define msdc_vdd_on(host) \ do { \ (void)hwPowerOn(MT65XX_POWER_LDO_VMCH, VOL_3300, "SD"); \ } while (0) #define msdc_vdd_off(host) \ do { \ (void)hwPowerDown(MT65XX_POWER_LDO_VMCH, "SD"); \ } while (0) #define sdc_is_busy() (readl(host->base + SDC_STS) & SDC_STS_SDCBUSY) #define sdc_is_cmd_busy() (readl(host->base + SDC_STS) & SDC_STS_CMDBUSY) #define sdc_send_cmd(cmd, arg) \ do { \ writel((arg), host->base + SDC_ARG); \ writel((cmd), host->base + SDC_CMD); \ } while (0) /* +++ by chhung */ #ifndef __ASSEMBLY__ #define PHYSADDR(a) (((unsigned long)(a)) & 0x1fffffff) #else #define PHYSADDR(a) ((a) & 0x1fffffff) #endif /* end of +++ */ static unsigned int msdc_do_command(struct msdc_host *host, struct mmc_command *cmd, int tune, unsigned long timeout); static int msdc_tune_cmdrsp(struct msdc_host *host, struct mmc_command *cmd); #ifdef MT6575_SD_DEBUG static void msdc_dump_card_status(struct msdc_host *host, u32 status) { /* N_MSG is currently a no-op */ #if 0 static char *state[] = { "Idle", /* 0 */ "Ready", /* 1 */ "Ident", /* 2 */ "Stby", /* 3 */ "Tran", /* 4 */ "Data", /* 5 */ "Rcv", /* 6 */ "Prg", /* 7 */ "Dis", /* 8 */ "Reserved", /* 9 */ "Reserved", /* 10 */ "Reserved", /* 11 */ "Reserved", /* 12 */ "Reserved", /* 13 */ "Reserved", /* 14 */ "I/O mode", /* 15 */ }; #endif if (status & R1_OUT_OF_RANGE) N_MSG(RSP, "[CARD_STATUS] Out of Range"); if (status & R1_ADDRESS_ERROR) N_MSG(RSP, "[CARD_STATUS] Address Error"); if (status & R1_BLOCK_LEN_ERROR) N_MSG(RSP, "[CARD_STATUS] Block Len Error"); if (status & R1_ERASE_SEQ_ERROR) N_MSG(RSP, "[CARD_STATUS] Erase Seq Error"); if (status & R1_ERASE_PARAM) N_MSG(RSP, "[CARD_STATUS] Erase Param"); if (status & R1_WP_VIOLATION) N_MSG(RSP, "[CARD_STATUS] WP Violation"); if (status & R1_CARD_IS_LOCKED) N_MSG(RSP, "[CARD_STATUS] Card is Locked"); if (status & R1_LOCK_UNLOCK_FAILED) N_MSG(RSP, "[CARD_STATUS] Lock/Unlock Failed"); if (status & R1_COM_CRC_ERROR) N_MSG(RSP, "[CARD_STATUS] Command CRC Error"); if (status & R1_ILLEGAL_COMMAND) N_MSG(RSP, "[CARD_STATUS] Illegal Command"); if (status & R1_CARD_ECC_FAILED) N_MSG(RSP, "[CARD_STATUS] Card ECC Failed"); if (status & R1_CC_ERROR) N_MSG(RSP, "[CARD_STATUS] CC Error"); if (status & R1_ERROR) N_MSG(RSP, "[CARD_STATUS] Error"); if (status & R1_UNDERRUN) N_MSG(RSP, "[CARD_STATUS] Underrun"); if (status & R1_OVERRUN) N_MSG(RSP, "[CARD_STATUS] Overrun"); if (status & R1_CID_CSD_OVERWRITE) N_MSG(RSP, "[CARD_STATUS] CID/CSD Overwrite"); if (status & R1_WP_ERASE_SKIP) N_MSG(RSP, "[CARD_STATUS] WP Eraser Skip"); if (status & R1_CARD_ECC_DISABLED) N_MSG(RSP, "[CARD_STATUS] Card ECC Disabled"); if (status & R1_ERASE_RESET) N_MSG(RSP, "[CARD_STATUS] Erase Reset"); if (status & R1_READY_FOR_DATA) N_MSG(RSP, "[CARD_STATUS] Ready for Data"); if (status & R1_SWITCH_ERROR) N_MSG(RSP, "[CARD_STATUS] Switch error"); if (status & R1_APP_CMD) N_MSG(RSP, "[CARD_STATUS] App Command"); N_MSG(RSP, "[CARD_STATUS] '%s' State", state[R1_CURRENT_STATE(status)]); } static void msdc_dump_ocr_reg(struct msdc_host *host, u32 resp) { if (resp & (1 << 7)) N_MSG(RSP, "[OCR] Low Voltage Range"); if (resp & (1 << 15)) N_MSG(RSP, "[OCR] 2.7-2.8 volt"); if (resp & (1 << 16)) N_MSG(RSP, "[OCR] 2.8-2.9 volt"); if (resp & (1 << 17)) N_MSG(RSP, "[OCR] 2.9-3.0 volt"); if (resp & (1 << 18)) N_MSG(RSP, "[OCR] 3.0-3.1 volt"); if (resp & (1 << 19)) N_MSG(RSP, "[OCR] 3.1-3.2 volt"); if (resp & (1 << 20)) N_MSG(RSP, "[OCR] 3.2-3.3 volt"); if (resp & (1 << 21)) N_MSG(RSP, "[OCR] 3.3-3.4 volt"); if (resp & (1 << 22)) N_MSG(RSP, "[OCR] 3.4-3.5 volt"); if (resp & (1 << 23)) N_MSG(RSP, "[OCR] 3.5-3.6 volt"); if (resp & (1 << 24)) N_MSG(RSP, "[OCR] Switching to 1.8V Accepted (S18A)"); if (resp & (1 << 30)) N_MSG(RSP, "[OCR] Card Capacity Status (CCS)"); if (resp & (1 << 31)) N_MSG(RSP, "[OCR] Card Power Up Status (Idle)"); else N_MSG(RSP, "[OCR] Card Power Up Status (Busy)"); } static void msdc_dump_rca_resp(struct msdc_host *host, u32 resp) { u32 status = (((resp >> 15) & 0x1) << 23) | (((resp >> 14) & 0x1) << 22) | (((resp >> 13) & 0x1) << 19) | (resp & 0x1fff); N_MSG(RSP, "[RCA] 0x%.4x", resp >> 16); msdc_dump_card_status(host, status); } static void msdc_dump_io_resp(struct msdc_host *host, u32 resp) { u32 flags = (resp >> 8) & 0xFF; #if 0 char *state[] = {"DIS", "CMD", "TRN", "RFU"}; #endif if (flags & (1 << 7)) N_MSG(RSP, "[IO] COM_CRC_ERR"); if (flags & (1 << 6)) N_MSG(RSP, "[IO] Illegal command"); if (flags & (1 << 3)) N_MSG(RSP, "[IO] Error"); if (flags & (1 << 2)) N_MSG(RSP, "[IO] RFU"); if (flags & (1 << 1)) N_MSG(RSP, "[IO] Function number error"); if (flags & (1 << 0)) N_MSG(RSP, "[IO] Out of range"); N_MSG(RSP, "[IO] State: %s, Data:0x%x", state[(resp >> 12) & 0x3], resp & 0xFF); } #endif static void msdc_set_timeout(struct msdc_host *host, u32 ns, u32 clks) { u32 timeout, clk_ns; host->timeout_ns = ns; host->timeout_clks = clks; clk_ns = 1000000000UL / host->sclk; timeout = ns / clk_ns + clks; timeout = timeout >> 16; /* in 65536 sclk cycle unit */ timeout = timeout > 1 ? timeout - 1 : 0; timeout = timeout > 255 ? 255 : timeout; sdr_set_field(host->base + SDC_CFG, SDC_CFG_DTOC, timeout); N_MSG(OPS, "Set read data timeout: %dns %dclks -> %d x 65536 cycles", ns, clks, timeout + 1); } static void msdc_tasklet_card(struct work_struct *work) { struct msdc_host *host = (struct msdc_host *)container_of(work, struct msdc_host, card_delaywork.work); u32 inserted; u32 status = 0; //u32 change = 0; spin_lock(&host->lock); status = readl(host->base + MSDC_PS); if (cd_active_low) inserted = (status & MSDC_PS_CDSTS) ? 0 : 1; else inserted = (status & MSDC_PS_CDSTS) ? 1 : 0; #if 0 change = host->card_inserted ^ inserted; host->card_inserted = inserted; if (change && !host->suspend) { if (inserted) host->mmc->f_max = HOST_MAX_MCLK; // work around mmc_detect_change(host->mmc, msecs_to_jiffies(20)); } #else /* Make sure: handle the last interrupt */ host->card_inserted = inserted; if (!host->suspend) { host->mmc->f_max = HOST_MAX_MCLK; mmc_detect_change(host->mmc, msecs_to_jiffies(20)); } IRQ_MSG("card found<%s>", inserted ? "inserted" : "removed"); #endif spin_unlock(&host->lock); } #if 0 /* --- by chhung */ /* For E2 only */ static u8 clk_src_bit[4] = { 0, 3, 5, 7 }; static void msdc_select_clksrc(struct msdc_host *host, unsigned char clksrc) { u32 val; BUG_ON(clksrc > 3); INIT_MSG("set clock source to <%d>", clksrc); val = readl(host->base + MSDC_CLKSRC_REG); if (readl(host->base + MSDC_ECO_VER) >= 4) { val &= ~(0x3 << clk_src_bit[host->id]); val |= clksrc << clk_src_bit[host->id]; } else { val &= ~0x3; val |= clksrc; } writel(val, host->base + MSDC_CLKSRC_REG); host->hclk = hclks[clksrc]; host->hw->clk_src = clksrc; } #endif /* end of --- */ static void msdc_set_mclk(struct msdc_host *host, int ddr, unsigned int hz) { //struct msdc_hw *hw = host->hw; u32 mode; u32 flags; u32 div; u32 sclk; u32 hclk = host->hclk; //u8 clksrc = hw->clk_src; if (!hz) { // set mmc system clock to 0 ? //ERR_MSG("set mclk to 0!!!"); msdc_reset_hw(host); return; } msdc_irq_save(flags); if (ddr) { mode = 0x2; /* ddr mode and use divisor */ if (hz >= (hclk >> 2)) { div = 1; /* mean div = 1/4 */ sclk = hclk >> 2; /* sclk = clk / 4 */ } else { div = (hclk + ((hz << 2) - 1)) / (hz << 2); sclk = (hclk >> 2) / div; } } else if (hz >= hclk) { /* bug fix */ mode = 0x1; /* no divisor and divisor is ignored */ div = 0; sclk = hclk; } else { mode = 0x0; /* use divisor */ if (hz >= (hclk >> 1)) { div = 0; /* mean div = 1/2 */ sclk = hclk >> 1; /* sclk = clk / 2 */ } else { div = (hclk + ((hz << 2) - 1)) / (hz << 2); sclk = (hclk >> 2) / div; } } /* set clock mode and divisor */ sdr_set_field(host->base + MSDC_CFG, MSDC_CFG_CKMOD, mode); sdr_set_field(host->base + MSDC_CFG, MSDC_CFG_CKDIV, div); /* wait clock stable */ while (!(readl(host->base + MSDC_CFG) & MSDC_CFG_CKSTB)) cpu_relax(); host->sclk = sclk; host->mclk = hz; msdc_set_timeout(host, host->timeout_ns, host->timeout_clks); // need? INIT_MSG("================"); INIT_MSG("!!! Set<%dKHz> Source<%dKHz> -> sclk<%dKHz>", hz / 1000, hclk / 1000, sclk / 1000); INIT_MSG("================"); msdc_irq_restore(flags); } /* Fix me. when need to abort */ static void msdc_abort_data(struct msdc_host *host) { struct mmc_command *stop = host->mrq->stop; ERR_MSG("Need to Abort."); msdc_reset_hw(host); msdc_clr_fifo(host); msdc_clr_int(); // need to check FIFO count 0 ? if (stop) { /* try to stop, but may not success */ ERR_MSG("stop when abort CMD<%d>", stop->opcode); (void)msdc_do_command(host, stop, 0, CMD_TIMEOUT); } //if (host->mclk >= 25000000) { // msdc_set_mclk(host, 0, host->mclk >> 1); //} } #if 0 /* --- by chhung */ static void msdc_pin_config(struct msdc_host *host, int mode) { struct msdc_hw *hw = host->hw; int pull = (mode == MSDC_PIN_PULL_UP) ? GPIO_PULL_UP : GPIO_PULL_DOWN; /* Config WP pin */ if (hw->flags & MSDC_WP_PIN_EN) { if (hw->config_gpio_pin) /* NULL */ hw->config_gpio_pin(MSDC_WP_PIN, pull); } switch (mode) { case MSDC_PIN_PULL_UP: //sdr_set_field(MSDC_PAD_CTL0, MSDC_PAD_CTL0_CLKPU, 1); /* Check & FIXME */ //sdr_set_field(MSDC_PAD_CTL0, MSDC_PAD_CTL0_CLKPD, 0); /* Check & FIXME */ sdr_set_field(host->base + MSDC_PAD_CTL1, MSDC_PAD_CTL1_CMDPU, 1); sdr_set_field(host->base + MSDC_PAD_CTL1, MSDC_PAD_CTL1_CMDPD, 0); sdr_set_field(host->base + MSDC_PAD_CTL2, MSDC_PAD_CTL2_DATPU, 1); sdr_set_field(host->base + MSDC_PAD_CTL2, MSDC_PAD_CTL2_DATPD, 0); break; case MSDC_PIN_PULL_DOWN: //sdr_set_field(MSDC_PAD_CTL0, MSDC_PAD_CTL0_CLKPU, 0); /* Check & FIXME */ //sdr_set_field(MSDC_PAD_CTL0, MSDC_PAD_CTL0_CLKPD, 1); /* Check & FIXME */ sdr_set_field(host->base + MSDC_PAD_CTL1, MSDC_PAD_CTL1_CMDPU, 0); sdr_set_field(host->base + MSDC_PAD_CTL1, MSDC_PAD_CTL1_CMDPD, 1); sdr_set_field(host->base + MSDC_PAD_CTL2, MSDC_PAD_CTL2_DATPU, 0); sdr_set_field(host->base + MSDC_PAD_CTL2, MSDC_PAD_CTL2_DATPD, 1); break; case MSDC_PIN_PULL_NONE: default: //sdr_set_field(MSDC_PAD_CTL0, MSDC_PAD_CTL0_CLKPU, 0); /* Check & FIXME */ //sdr_set_field(MSDC_PAD_CTL0, MSDC_PAD_CTL0_CLKPD, 0); /* Check & FIXME */ sdr_set_field(host->base + MSDC_PAD_CTL1, MSDC_PAD_CTL1_CMDPU, 0); sdr_set_field(host->base + MSDC_PAD_CTL1, MSDC_PAD_CTL1_CMDPD, 0); sdr_set_field(host->base + MSDC_PAD_CTL2, MSDC_PAD_CTL2_DATPU, 0); sdr_set_field(host->base + MSDC_PAD_CTL2, MSDC_PAD_CTL2_DATPD, 0); break; } N_MSG(CFG, "Pins mode(%d), down(%d), up(%d)", mode, MSDC_PIN_PULL_DOWN, MSDC_PIN_PULL_UP); } void msdc_pin_reset(struct msdc_host *host, int mode) { struct msdc_hw *hw = (struct msdc_hw *)host->hw; int pull = (mode == MSDC_PIN_PULL_UP) ? GPIO_PULL_UP : GPIO_PULL_DOWN; /* Config reset pin */ if (hw->flags & MSDC_RST_PIN_EN) { if (hw->config_gpio_pin) /* NULL */ hw->config_gpio_pin(MSDC_RST_PIN, pull); if (mode == MSDC_PIN_PULL_UP) sdr_clr_bits(host->base + EMMC_IOCON, EMMC_IOCON_BOOTRST); else sdr_set_bits(host->base + EMMC_IOCON, EMMC_IOCON_BOOTRST); } } static void msdc_core_power(struct msdc_host *host, int on) { N_MSG(CFG, "Turn %s %s power (copower: %d -> %d)", on ? "on" : "off", "core", host->core_power, on); if (on && host->core_power == 0) { msdc_vcore_on(host); host->core_power = 1; msleep(1); } else if (!on && host->core_power == 1) { msdc_vcore_off(host); host->core_power = 0; msleep(1); } } static void msdc_host_power(struct msdc_host *host, int on) { N_MSG(CFG, "Turn %s %s power ", on ? "on" : "off", "host"); if (on) { //msdc_core_power(host, 1); // need do card detection. msdc_pin_reset(host, MSDC_PIN_PULL_UP); } else { msdc_pin_reset(host, MSDC_PIN_PULL_DOWN); //msdc_core_power(host, 0); } } static void msdc_card_power(struct msdc_host *host, int on) { N_MSG(CFG, "Turn %s %s power ", on ? "on" : "off", "card"); if (on) { msdc_pin_config(host, MSDC_PIN_PULL_UP); //msdc_vdd_on(host); // need todo card detection. msleep(1); } else { //msdc_vdd_off(host); msdc_pin_config(host, MSDC_PIN_PULL_DOWN); msleep(1); } } static void msdc_set_power_mode(struct msdc_host *host, u8 mode) { N_MSG(CFG, "Set power mode(%d)", mode); if (host->power_mode == MMC_POWER_OFF && mode != MMC_POWER_OFF) { msdc_host_power(host, 1); msdc_card_power(host, 1); } else if (host->power_mode != MMC_POWER_OFF && mode == MMC_POWER_OFF) { msdc_card_power(host, 0); msdc_host_power(host, 0); } host->power_mode = mode; } #endif /* end of --- */ #ifdef CONFIG_PM /* register as callback function of WIFI(combo_sdio_register_pm) . can called by msdc_drv_suspend/resume too. */ static void msdc_pm(pm_message_t state, void *data) { struct msdc_host *host = (struct msdc_host *)data; int evt = state.event; if (evt == PM_EVENT_USER_RESUME || evt == PM_EVENT_USER_SUSPEND) { INIT_MSG("USR_%s: suspend<%d> power<%d>", evt == PM_EVENT_USER_RESUME ? "EVENT_USER_RESUME" : "EVENT_USER_SUSPEND", host->suspend, host->power_mode); } if (evt == PM_EVENT_SUSPEND || evt == PM_EVENT_USER_SUSPEND) { if (host->suspend) /* already suspend */ /* default 0*/ return; /* for memory card. already power off by mmc */ if (evt == PM_EVENT_SUSPEND && host->power_mode == MMC_POWER_OFF) return; host->suspend = 1; host->pm_state = state; /* default PMSG_RESUME */ } else if (evt == PM_EVENT_RESUME || evt == PM_EVENT_USER_RESUME) { if (!host->suspend) { //ERR_MSG("warning: already resume"); return; } /* No PM resume when USR suspend */ if (evt == PM_EVENT_RESUME && host->pm_state.event == PM_EVENT_USER_SUSPEND) { ERR_MSG("PM Resume when in USR Suspend"); /* won't happen. */ return; } host->suspend = 0; host->pm_state = state; } } #endif static inline u32 msdc_cmd_find_resp(struct mmc_command *cmd) { u32 opcode = cmd->opcode; u32 resp; if (opcode == MMC_SET_RELATIVE_ADDR) { resp = (mmc_cmd_type(cmd) == MMC_CMD_BCR) ? RESP_R6 : RESP_R1; } else if (opcode == MMC_FAST_IO) { resp = RESP_R4; } else if (opcode == MMC_GO_IRQ_STATE) { resp = RESP_R5; } else if (opcode == MMC_SELECT_CARD) { resp = (cmd->arg != 0) ? RESP_R1B : RESP_NONE; } else if (opcode == SD_IO_RW_DIRECT || opcode == SD_IO_RW_EXTENDED) { resp = RESP_R1; /* SDIO workaround. */ } else if (opcode == SD_SEND_IF_COND && (mmc_cmd_type(cmd) == MMC_CMD_BCR)) { resp = RESP_R1; } else { switch (mmc_resp_type(cmd)) { case MMC_RSP_R1: resp = RESP_R1; break; case MMC_RSP_R1B: resp = RESP_R1B; break; case MMC_RSP_R2: resp = RESP_R2; break; case MMC_RSP_R3: resp = RESP_R3; break; case MMC_RSP_NONE: default: resp = RESP_NONE; break; } } return resp; } /*--------------------------------------------------------------------------*/ /* mmc_host_ops members */ /*--------------------------------------------------------------------------*/ static unsigned int msdc_command_start(struct msdc_host *host, struct mmc_command *cmd, unsigned long timeout) { u32 opcode = cmd->opcode; u32 rawcmd; u32 wints = MSDC_INT_CMDRDY | MSDC_INT_RSPCRCERR | MSDC_INT_CMDTMO | MSDC_INT_ACMDRDY | MSDC_INT_ACMDCRCERR | MSDC_INT_ACMDTMO | MSDC_INT_ACMD19_DONE; u32 resp; unsigned long tmo; /* Protocol layer does not provide response type, but our hardware needs * to know exact type, not just size! */ resp = msdc_cmd_find_resp(cmd); cmd->error = 0; /* rawcmd : * vol_swt << 30 | auto_cmd << 28 | blklen << 16 | go_irq << 15 | * stop << 14 | rw << 13 | dtype << 11 | rsptyp << 7 | brk << 6 | opcode */ rawcmd = opcode | msdc_rsp[resp] << 7 | host->blksz << 16; if (opcode == MMC_READ_MULTIPLE_BLOCK) { rawcmd |= (2 << 11); } else if (opcode == MMC_READ_SINGLE_BLOCK) { rawcmd |= (1 << 11); } else if (opcode == MMC_WRITE_MULTIPLE_BLOCK) { rawcmd |= ((2 << 11) | (1 << 13)); } else if (opcode == MMC_WRITE_BLOCK) { rawcmd |= ((1 << 11) | (1 << 13)); } else if (opcode == SD_IO_RW_EXTENDED) { if (cmd->data->flags & MMC_DATA_WRITE) rawcmd |= (1 << 13); if (cmd->data->blocks > 1) rawcmd |= (2 << 11); else rawcmd |= (1 << 11); } else if (opcode == SD_IO_RW_DIRECT && cmd->flags == (unsigned int)-1) { rawcmd |= (1 << 14); } else if ((opcode == SD_APP_SEND_SCR) || (opcode == SD_APP_SEND_NUM_WR_BLKS) || (opcode == SD_SWITCH && (mmc_cmd_type(cmd) == MMC_CMD_ADTC)) || (opcode == SD_APP_SD_STATUS && (mmc_cmd_type(cmd) == MMC_CMD_ADTC)) || (opcode == MMC_SEND_EXT_CSD && (mmc_cmd_type(cmd) == MMC_CMD_ADTC))) { rawcmd |= (1 << 11); } else if (opcode == MMC_STOP_TRANSMISSION) { rawcmd |= (1 << 14); rawcmd &= ~(0x0FFF << 16); } N_MSG(CMD, "CMD<%d><0x%.8x> Arg<0x%.8x>", opcode, rawcmd, cmd->arg); tmo = jiffies + timeout; if (opcode == MMC_SEND_STATUS) { for (;;) { if (!sdc_is_cmd_busy()) break; if (time_after(jiffies, tmo)) { ERR_MSG("XXX cmd_busy timeout: before CMD<%d>", opcode); cmd->error = -ETIMEDOUT; msdc_reset_hw(host); goto end; } } } else { for (;;) { if (!sdc_is_busy()) break; if (time_after(jiffies, tmo)) { ERR_MSG("XXX sdc_busy timeout: before CMD<%d>", opcode); cmd->error = -ETIMEDOUT; msdc_reset_hw(host); goto end; } } } //BUG_ON(in_interrupt()); host->cmd = cmd; host->cmd_rsp = resp; init_completion(&host->cmd_done); sdr_set_bits(host->base + MSDC_INTEN, wints); sdc_send_cmd(rawcmd, cmd->arg); end: return cmd->error; } static unsigned int msdc_command_resp(struct msdc_host *host, struct mmc_command *cmd, int tune, unsigned long timeout) __must_hold(&host->lock) { u32 opcode = cmd->opcode; //u32 rawcmd; u32 wints = MSDC_INT_CMDRDY | MSDC_INT_RSPCRCERR | MSDC_INT_CMDTMO | MSDC_INT_ACMDRDY | MSDC_INT_ACMDCRCERR | MSDC_INT_ACMDTMO | MSDC_INT_ACMD19_DONE; BUG_ON(in_interrupt()); //init_completion(&host->cmd_done); //sdr_set_bits(host->base + MSDC_INTEN, wints); spin_unlock(&host->lock); if (!wait_for_completion_timeout(&host->cmd_done, 10 * timeout)) { ERR_MSG("XXX CMD<%d> wait_for_completion timeout ARG<0x%.8x>", opcode, cmd->arg); cmd->error = -ETIMEDOUT; msdc_reset_hw(host); } spin_lock(&host->lock); sdr_clr_bits(host->base + MSDC_INTEN, wints); host->cmd = NULL; //end: #ifdef MT6575_SD_DEBUG switch (resp) { case RESP_NONE: N_MSG(RSP, "CMD_RSP(%d): %d RSP(%d)", opcode, cmd->error, resp); break; case RESP_R2: N_MSG(RSP, "CMD_RSP(%d): %d RSP(%d)= %.8x %.8x %.8x %.8x", opcode, cmd->error, resp, cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]); break; default: /* Response types 1, 3, 4, 5, 6, 7(1b) */ N_MSG(RSP, "CMD_RSP(%d): %d RSP(%d)= 0x%.8x", opcode, cmd->error, resp, cmd->resp[0]); if (cmd->error == 0) { switch (resp) { case RESP_R1: case RESP_R1B: msdc_dump_card_status(host, cmd->resp[0]); break; case RESP_R3: msdc_dump_ocr_reg(host, cmd->resp[0]); break; case RESP_R5: msdc_dump_io_resp(host, cmd->resp[0]); break; case RESP_R6: msdc_dump_rca_resp(host, cmd->resp[0]); break; } } break; } #endif /* do we need to save card's RCA when SD_SEND_RELATIVE_ADDR */ if (!tune) return cmd->error; /* memory card CRC */ if (host->hw->flags & MSDC_REMOVABLE && cmd->error == -EIO) { /* check if has data phase */ if (readl(host->base + SDC_CMD) & 0x1800) { msdc_abort_data(host); } else { /* do basic: reset*/ msdc_reset_hw(host); msdc_clr_fifo(host); msdc_clr_int(); } cmd->error = msdc_tune_cmdrsp(host, cmd); } // check DAT0 /* if (resp == RESP_R1B) { while ((readl(host->base + MSDC_PS) & 0x10000) != 0x10000); } */ /* CMD12 Error Handle */ return cmd->error; } static unsigned int msdc_do_command(struct msdc_host *host, struct mmc_command *cmd, int tune, unsigned long timeout) { if (msdc_command_start(host, cmd, timeout)) goto end; if (msdc_command_resp(host, cmd, tune, timeout)) goto end; end: N_MSG(CMD, " return<%d> resp<0x%.8x>", cmd->error, cmd->resp[0]); return cmd->error; } #if 0 /* --- by chhung */ // DMA resume / start / stop static void msdc_dma_resume(struct msdc_host *host) { sdr_set_field(host->base + MSDC_DMA_CTRL, MSDC_DMA_CTRL_RESUME, 1); N_MSG(DMA, "DMA resume"); } #endif /* end of --- */ static void msdc_dma_start(struct msdc_host *host) { u32 wints = MSDC_INTEN_XFER_COMPL | MSDC_INTEN_DATTMO | MSDC_INTEN_DATCRCERR; sdr_set_bits(host->base + MSDC_INTEN, wints); //dsb(); /* --- by chhung */ sdr_set_field(host->base + MSDC_DMA_CTRL, MSDC_DMA_CTRL_START, 1); N_MSG(DMA, "DMA start"); } static void msdc_dma_stop(struct msdc_host *host) { //u32 retries=500; u32 wints = MSDC_INTEN_XFER_COMPL | MSDC_INTEN_DATTMO | MSDC_INTEN_DATCRCERR; N_MSG(DMA, "DMA status: 0x%.8x", readl(host->base + MSDC_DMA_CFG)); //while (readl(host->base + MSDC_DMA_CFG) & MSDC_DMA_CFG_STS); sdr_set_field(host->base + MSDC_DMA_CTRL, MSDC_DMA_CTRL_STOP, 1); while (readl(host->base + MSDC_DMA_CFG) & MSDC_DMA_CFG_STS) ; //dsb(); /* --- by chhung */ sdr_clr_bits(host->base + MSDC_INTEN, wints); /* Not just xfer_comp */ N_MSG(DMA, "DMA stop"); } /* calc checksum */ static u8 msdc_dma_calcs(u8 *buf, u32 len) { u32 i, sum = 0; for (i = 0; i < len; i++) sum += buf[i]; return 0xFF - (u8)sum; } static void msdc_dma_setup(struct msdc_host *host, struct msdc_dma *dma, struct scatterlist *sg_cmd, unsigned int sglen) { struct scatterlist *sg; struct gpd *gpd; struct bd *bd; u32 j; BUG_ON(sglen > MAX_BD_NUM); /* not support currently */ N_MSG(DMA, "DMA sglen<%d> xfersz<%d>", sglen, host->xfer_size); gpd = dma->gpd; bd = dma->bd; /* modify gpd*/ //gpd->intr = 0; gpd->hwo = 1; /* hw will clear it */ gpd->bdp = 1; gpd->chksum = 0; /* need to clear first. */ gpd->chksum = msdc_dma_calcs((u8 *)gpd, 16); /* modify bd*/ for_each_sg(sg_cmd, sg, sglen, j) { bd[j].blkpad = 0; bd[j].dwpad = 0; bd[j].ptr = (void *)sg_dma_address(sg); bd[j].buflen = sg_dma_len(sg); if (j == sglen - 1) bd[j].eol = 1; /* the last bd */ else bd[j].eol = 0; bd[j].chksum = 0; /* checksume need to clear first */ bd[j].chksum = msdc_dma_calcs((u8 *)(&bd[j]), 16); } sdr_set_field(host->base + MSDC_DMA_CFG, MSDC_DMA_CFG_DECSEN, 1); sdr_set_field(host->base + MSDC_DMA_CTRL, MSDC_DMA_CTRL_BRUSTSZ, MSDC_BRUST_64B); sdr_set_field(host->base + MSDC_DMA_CTRL, MSDC_DMA_CTRL_MODE, 1); writel(PHYSADDR((u32)dma->gpd_addr), host->base + MSDC_DMA_SA); N_MSG(DMA, "DMA_CTRL = 0x%x", readl(host->base + MSDC_DMA_CTRL)); N_MSG(DMA, "DMA_CFG = 0x%x", readl(host->base + MSDC_DMA_CFG)); N_MSG(DMA, "DMA_SA = 0x%x", readl(host->base + MSDC_DMA_SA)); } static int msdc_do_request(struct mmc_host *mmc, struct mmc_request *mrq) __must_hold(&host->lock) { struct msdc_host *host = mmc_priv(mmc); struct mmc_command *cmd; struct mmc_data *data; //u32 intsts = 0; int read = 1, send_type = 0; #define SND_DAT 0 #define SND_CMD 1 BUG_ON(mmc == NULL); BUG_ON(mrq == NULL); host->error = 0; cmd = mrq->cmd; data = mrq->cmd->data; #if 0 /* --- by chhung */ //if(host->id ==1){ N_MSG(OPS, "enable clock!"); msdc_ungate_clock(host->id); //} #endif /* end of --- */ if (!data) { send_type = SND_CMD; if (msdc_do_command(host, cmd, 1, CMD_TIMEOUT) != 0) goto done; } else { BUG_ON(data->blksz > HOST_MAX_BLKSZ); send_type = SND_DAT; data->error = 0; read = data->flags & MMC_DATA_READ ? 1 : 0; host->data = data; host->xfer_size = data->blocks * data->blksz; host->blksz = data->blksz; if (read) { if ((host->timeout_ns != data->timeout_ns) || (host->timeout_clks != data->timeout_clks)) { msdc_set_timeout(host, data->timeout_ns, data->timeout_clks); } } writel(data->blocks, host->base + SDC_BLK_NUM); //msdc_clr_fifo(host); /* no need */ msdc_dma_on(); /* enable DMA mode first!! */ init_completion(&host->xfer_done); /* start the command first*/ if (msdc_command_start(host, cmd, CMD_TIMEOUT) != 0) goto done; data->sg_count = dma_map_sg(mmc_dev(mmc), data->sg, data->sg_len, mmc_get_dma_dir(data)); msdc_dma_setup(host, &host->dma, data->sg, data->sg_count); /* then wait command done */ if (msdc_command_resp(host, cmd, 1, CMD_TIMEOUT) != 0) goto done; /* for read, the data coming too fast, then CRC error start DMA no business with CRC. */ //init_completion(&host->xfer_done); msdc_dma_start(host); spin_unlock(&host->lock); if (!wait_for_completion_timeout(&host->xfer_done, DAT_TIMEOUT)) { ERR_MSG("XXX CMD<%d> wait xfer_done<%d> timeout!!", cmd->opcode, data->blocks * data->blksz); ERR_MSG(" DMA_SA = 0x%x", readl(host->base + MSDC_DMA_SA)); ERR_MSG(" DMA_CA = 0x%x", readl(host->base + MSDC_DMA_CA)); ERR_MSG(" DMA_CTRL = 0x%x", readl(host->base + MSDC_DMA_CTRL)); ERR_MSG(" DMA_CFG = 0x%x", readl(host->base + MSDC_DMA_CFG)); data->error = -ETIMEDOUT; msdc_reset_hw(host); msdc_clr_fifo(host); msdc_clr_int(); } spin_lock(&host->lock); msdc_dma_stop(host); /* Last: stop transfer */ if (data->stop) { if (msdc_do_command(host, data->stop, 0, CMD_TIMEOUT) != 0) goto done; } } done: if (data != NULL) { host->data = NULL; dma_unmap_sg(mmc_dev(mmc), data->sg, data->sg_len, mmc_get_dma_dir(data)); host->blksz = 0; #if 0 // don't stop twice! if (host->hw->flags & MSDC_REMOVABLE && data->error) { msdc_abort_data(host); /* reset in IRQ, stop command has issued. -> No need */ } #endif N_MSG(OPS, "CMD<%d> data<%s %s> blksz<%d> block<%d> error<%d>", cmd->opcode, (dma ? "dma" : "pio"), (read ? "read " : "write"), data->blksz, data->blocks, data->error); } #if 0 /* --- by chhung */ #if 1 //if(host->id==1) { if (send_type == SND_CMD) { if (cmd->opcode == MMC_SEND_STATUS) { if ((cmd->resp[0] & CARD_READY_FOR_DATA) || (CARD_CURRENT_STATE(cmd->resp[0]) != 7)) { N_MSG(OPS, "disable clock, CMD13 IDLE"); msdc_gate_clock(host->id); } } else { N_MSG(OPS, "disable clock, CMD<%d>", cmd->opcode); msdc_gate_clock(host->id); } } else { if (read) { N_MSG(OPS, "disable clock!!! Read CMD<%d>", cmd->opcode); msdc_gate_clock(host->id); } } //} #else msdc_gate_clock(host->id); #endif #endif /* end of --- */ if (mrq->cmd->error) host->error = 0x001; if (mrq->data && mrq->data->error) host->error |= 0x010; if (mrq->stop && mrq->stop->error) host->error |= 0x100; //if (host->error) ERR_MSG("host->error<%d>", host->error); return host->error; } static int msdc_app_cmd(struct mmc_host *mmc, struct msdc_host *host) { struct mmc_command cmd; struct mmc_request mrq; u32 err; memset(&cmd, 0, sizeof(struct mmc_command)); cmd.opcode = MMC_APP_CMD; #if 0 /* bug: we meet mmc->card is null when ACMD6 */ cmd.arg = mmc->card->rca << 16; #else cmd.arg = host->app_cmd_arg; #endif cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; memset(&mrq, 0, sizeof(struct mmc_request)); mrq.cmd = &cmd; cmd.mrq = &mrq; cmd.data = NULL; err = msdc_do_command(host, &cmd, 0, CMD_TIMEOUT); return err; } static int msdc_tune_cmdrsp(struct msdc_host *host, struct mmc_command *cmd) { int result = -1; u32 rsmpl, cur_rsmpl, orig_rsmpl; u32 rrdly, cur_rrdly = 0xffffffff, orig_rrdly; u32 skip = 1; /* ==== don't support 3.0 now ==== 1: R_SMPL[1] 2: PAD_CMD_RESP_RXDLY[26:22] ==========================*/ // save the previous tune result sdr_get_field(host->base + MSDC_IOCON, MSDC_IOCON_RSPL, &orig_rsmpl); sdr_get_field(host->base + MSDC_PAD_TUNE, MSDC_PAD_TUNE_CMDRRDLY, &orig_rrdly); rrdly = 0; do { for (rsmpl = 0; rsmpl < 2; rsmpl++) { /* Lv1: R_SMPL[1] */ cur_rsmpl = (orig_rsmpl + rsmpl) % 2; if (skip == 1) { skip = 0; continue; } sdr_set_field(host->base + MSDC_IOCON, MSDC_IOCON_RSPL, cur_rsmpl); if (host->app_cmd) { result = msdc_app_cmd(host->mmc, host); if (result) { ERR_MSG("TUNE_CMD app_cmd<%d> failed: RESP_RXDLY<%d>,R_SMPL<%d>", host->mrq->cmd->opcode, cur_rrdly, cur_rsmpl); continue; } } result = msdc_do_command(host, cmd, 0, CMD_TIMEOUT); // not tune. ERR_MSG("TUNE_CMD<%d> %s PAD_CMD_RESP_RXDLY[26:22]<%d> R_SMPL[1]<%d>", cmd->opcode, (result == 0) ? "PASS" : "FAIL", cur_rrdly, cur_rsmpl); if (result == 0) return 0; if (result != -EIO) { ERR_MSG("TUNE_CMD<%d> Error<%d> not -EIO", cmd->opcode, result); return result; } /* should be EIO */ /* check if has data phase */ if (readl(host->base + SDC_CMD) & 0x1800) msdc_abort_data(host); } /* Lv2: PAD_CMD_RESP_RXDLY[26:22] */ cur_rrdly = (orig_rrdly + rrdly + 1) % 32; sdr_set_field(host->base + MSDC_PAD_TUNE, MSDC_PAD_TUNE_CMDRRDLY, cur_rrdly); } while (++rrdly < 32); return result; } /* Support SD2.0 Only */ static int msdc_tune_bread(struct mmc_host *mmc, struct mmc_request *mrq) { struct msdc_host *host = mmc_priv(mmc); u32 ddr = 0; u32 dcrc = 0; u32 rxdly, cur_rxdly0, cur_rxdly1; u32 dsmpl, cur_dsmpl, orig_dsmpl; u32 cur_dat0, cur_dat1, cur_dat2, cur_dat3; u32 cur_dat4, cur_dat5, cur_dat6, cur_dat7; u32 orig_dat0, orig_dat1, orig_dat2, orig_dat3; u32 orig_dat4, orig_dat5, orig_dat6, orig_dat7; int result = -1; u32 skip = 1; sdr_get_field(host->base + MSDC_IOCON, MSDC_IOCON_DSPL, &orig_dsmpl); /* Tune Method 2. */ sdr_set_field(host->base + MSDC_IOCON, MSDC_IOCON_DDLSEL, 1); rxdly = 0; do { for (dsmpl = 0; dsmpl < 2; dsmpl++) { cur_dsmpl = (orig_dsmpl + dsmpl) % 2; if (skip == 1) { skip = 0; continue; } sdr_set_field(host->base + MSDC_IOCON, MSDC_IOCON_DSPL, cur_dsmpl); if (host->app_cmd) { result = msdc_app_cmd(host->mmc, host); if (result) { ERR_MSG("TUNE_BREAD app_cmd<%d> failed", host->mrq->cmd->opcode); continue; } } result = msdc_do_request(mmc, mrq); sdr_get_field(host->base + SDC_DCRC_STS, SDC_DCRC_STS_POS | SDC_DCRC_STS_NEG, &dcrc); /* RO */ if (!ddr) dcrc &= ~SDC_DCRC_STS_NEG; ERR_MSG("TUNE_BREAD<%s> dcrc<0x%x> DATRDDLY0/1<0x%x><0x%x> dsmpl<0x%x>", (result == 0 && dcrc == 0) ? "PASS" : "FAIL", dcrc, readl(host->base + MSDC_DAT_RDDLY0), readl(host->base + MSDC_DAT_RDDLY1), cur_dsmpl); /* Fix me: result is 0, but dcrc is still exist */ if (result == 0 && dcrc == 0) { goto done; } else { /* there is a case: command timeout, and data phase not processed */ if (mrq->data->error != 0 && mrq->data->error != -EIO) { ERR_MSG("TUNE_READ: result<0x%x> cmd_error<%d> data_error<%d>", result, mrq->cmd->error, mrq->data->error); goto done; } } } cur_rxdly0 = readl(host->base + MSDC_DAT_RDDLY0); cur_rxdly1 = readl(host->base + MSDC_DAT_RDDLY1); /* E1 ECO. YD: Reverse */ if (readl(host->base + MSDC_ECO_VER) >= 4) { orig_dat0 = (cur_rxdly0 >> 24) & 0x1F; orig_dat1 = (cur_rxdly0 >> 16) & 0x1F; orig_dat2 = (cur_rxdly0 >> 8) & 0x1F; orig_dat3 = (cur_rxdly0 >> 0) & 0x1F; orig_dat4 = (cur_rxdly1 >> 24) & 0x1F; orig_dat5 = (cur_rxdly1 >> 16) & 0x1F; orig_dat6 = (cur_rxdly1 >> 8) & 0x1F; orig_dat7 = (cur_rxdly1 >> 0) & 0x1F; } else { orig_dat0 = (cur_rxdly0 >> 0) & 0x1F; orig_dat1 = (cur_rxdly0 >> 8) & 0x1F; orig_dat2 = (cur_rxdly0 >> 16) & 0x1F; orig_dat3 = (cur_rxdly0 >> 24) & 0x1F; orig_dat4 = (cur_rxdly1 >> 0) & 0x1F; orig_dat5 = (cur_rxdly1 >> 8) & 0x1F; orig_dat6 = (cur_rxdly1 >> 16) & 0x1F; orig_dat7 = (cur_rxdly1 >> 24) & 0x1F; } if (ddr) { cur_dat0 = (dcrc & (1 << 0) || dcrc & (1 << 8)) ? ((orig_dat0 + 1) % 32) : orig_dat0; cur_dat1 = (dcrc & (1 << 1) || dcrc & (1 << 9)) ? ((orig_dat1 + 1) % 32) : orig_dat1; cur_dat2 = (dcrc & (1 << 2) || dcrc & (1 << 10)) ? ((orig_dat2 + 1) % 32) : orig_dat2; cur_dat3 = (dcrc & (1 << 3) || dcrc & (1 << 11)) ? ((orig_dat3 + 1) % 32) : orig_dat3; } else { cur_dat0 = (dcrc & (1 << 0)) ? ((orig_dat0 + 1) % 32) : orig_dat0; cur_dat1 = (dcrc & (1 << 1)) ? ((orig_dat1 + 1) % 32) : orig_dat1; cur_dat2 = (dcrc & (1 << 2)) ? ((orig_dat2 + 1) % 32) : orig_dat2; cur_dat3 = (dcrc & (1 << 3)) ? ((orig_dat3 + 1) % 32) : orig_dat3; } cur_dat4 = (dcrc & (1 << 4)) ? ((orig_dat4 + 1) % 32) : orig_dat4; cur_dat5 = (dcrc & (1 << 5)) ? ((orig_dat5 + 1) % 32) : orig_dat5; cur_dat6 = (dcrc & (1 << 6)) ? ((orig_dat6 + 1) % 32) : orig_dat6; cur_dat7 = (dcrc & (1 << 7)) ? ((orig_dat7 + 1) % 32) : orig_dat7; cur_rxdly0 = (cur_dat0 << 24) | (cur_dat1 << 16) | (cur_dat2 << 8) | (cur_dat3 << 0); cur_rxdly1 = (cur_dat4 << 24) | (cur_dat5 << 16) | (cur_dat6 << 8) | (cur_dat7 << 0); writel(cur_rxdly0, host->base + MSDC_DAT_RDDLY0); writel(cur_rxdly1, host->base + MSDC_DAT_RDDLY1); } while (++rxdly < 32); done: return result; } static int msdc_tune_bwrite(struct mmc_host *mmc, struct mmc_request *mrq) { struct msdc_host *host = mmc_priv(mmc); u32 wrrdly, cur_wrrdly = 0xffffffff, orig_wrrdly; u32 dsmpl, cur_dsmpl, orig_dsmpl; u32 rxdly, cur_rxdly0; u32 orig_dat0, orig_dat1, orig_dat2, orig_dat3; u32 cur_dat0, cur_dat1, cur_dat2, cur_dat3; int result = -1; u32 skip = 1; // MSDC_IOCON_DDR50CKD need to check. [Fix me] sdr_get_field(host->base + MSDC_PAD_TUNE, MSDC_PAD_TUNE_DATWRDLY, &orig_wrrdly); sdr_get_field(host->base + MSDC_IOCON, MSDC_IOCON_DSPL, &orig_dsmpl); /* Tune Method 2. just DAT0 */ sdr_set_field(host->base + MSDC_IOCON, MSDC_IOCON_DDLSEL, 1); cur_rxdly0 = readl(host->base + MSDC_DAT_RDDLY0); /* E1 ECO. YD: Reverse */ if (readl(host->base + MSDC_ECO_VER) >= 4) { orig_dat0 = (cur_rxdly0 >> 24) & 0x1F; orig_dat1 = (cur_rxdly0 >> 16) & 0x1F; orig_dat2 = (cur_rxdly0 >> 8) & 0x1F; orig_dat3 = (cur_rxdly0 >> 0) & 0x1F; } else { orig_dat0 = (cur_rxdly0 >> 0) & 0x1F; orig_dat1 = (cur_rxdly0 >> 8) & 0x1F; orig_dat2 = (cur_rxdly0 >> 16) & 0x1F; orig_dat3 = (cur_rxdly0 >> 24) & 0x1F; } rxdly = 0; do { wrrdly = 0; do { for (dsmpl = 0; dsmpl < 2; dsmpl++) { cur_dsmpl = (orig_dsmpl + dsmpl) % 2; if (skip == 1) { skip = 0; continue; } sdr_set_field(host->base + MSDC_IOCON, MSDC_IOCON_DSPL, cur_dsmpl); if (host->app_cmd) { result = msdc_app_cmd(host->mmc, host); if (result) { ERR_MSG("TUNE_BWRITE app_cmd<%d> failed", host->mrq->cmd->opcode); continue; } } result = msdc_do_request(mmc, mrq); ERR_MSG("TUNE_BWRITE<%s> DSPL<%d> DATWRDLY<%d> MSDC_DAT_RDDLY0<0x%x>", result == 0 ? "PASS" : "FAIL", cur_dsmpl, cur_wrrdly, cur_rxdly0); if (result == 0) { goto done; } else { /* there is a case: command timeout, and data phase not processed */ if (mrq->data->error != -EIO) { ERR_MSG("TUNE_READ: result<0x%x> cmd_error<%d> data_error<%d>", result, mrq->cmd->error, mrq->data->error); goto done; } } } cur_wrrdly = (orig_wrrdly + wrrdly + 1) % 32; sdr_set_field(host->base + MSDC_PAD_TUNE, MSDC_PAD_TUNE_DATWRDLY, cur_wrrdly); } while (++wrrdly < 32); cur_dat0 = (orig_dat0 + rxdly) % 32; /* only adjust bit-1 for crc */ cur_dat1 = orig_dat1; cur_dat2 = orig_dat2; cur_dat3 = orig_dat3; cur_rxdly0 = (cur_dat0 << 24) | (cur_dat1 << 16) | (cur_dat2 << 8) | (cur_dat3 << 0); writel(cur_rxdly0, host->base + MSDC_DAT_RDDLY0); } while (++rxdly < 32); done: return result; } static int msdc_get_card_status(struct mmc_host *mmc, struct msdc_host *host, u32 *status) { struct mmc_command cmd; struct mmc_request mrq; u32 err; memset(&cmd, 0, sizeof(struct mmc_command)); cmd.opcode = MMC_SEND_STATUS; if (mmc->card) { cmd.arg = mmc->card->rca << 16; } else { ERR_MSG("cmd13 mmc card is null"); cmd.arg = host->app_cmd_arg; } cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC; memset(&mrq, 0, sizeof(struct mmc_request)); mrq.cmd = &cmd; cmd.mrq = &mrq; cmd.data = NULL; err = msdc_do_command(host, &cmd, 1, CMD_TIMEOUT); if (status) *status = cmd.resp[0]; return err; } static int msdc_check_busy(struct mmc_host *mmc, struct msdc_host *host) { u32 err = 0; u32 status = 0; do { err = msdc_get_card_status(mmc, host, &status); if (err) return err; /* need cmd12? */ ERR_MSG("cmd<13> resp<0x%x>", status); } while (R1_CURRENT_STATE(status) == 7); return err; } /* failed when msdc_do_request */ static int msdc_tune_request(struct mmc_host *mmc, struct mmc_request *mrq) { struct msdc_host *host = mmc_priv(mmc); struct mmc_data *data; //u32 base = host->base; int ret = 0, read; data = mrq->cmd->data; read = data->flags & MMC_DATA_READ ? 1 : 0; if (read) { if (data->error == -EIO) ret = msdc_tune_bread(mmc, mrq); } else { ret = msdc_check_busy(mmc, host); if (ret) { ERR_MSG("XXX cmd13 wait program done failed"); return ret; } /* CRC and TO */ /* Fix me: don't care card status? */ ret = msdc_tune_bwrite(mmc, mrq); } return ret; } /* ops.request */ static void msdc_ops_request(struct mmc_host *mmc, struct mmc_request *mrq) { struct msdc_host *host = mmc_priv(mmc); //=== for sdio profile === #if 0 /* --- by chhung */ u32 old_H32, old_L32, new_H32, new_L32; u32 ticks = 0, opcode = 0, sizes = 0, bRx = 0; #endif /* end of --- */ WARN_ON(host->mrq); /* start to process */ spin_lock(&host->lock); #if 0 /* --- by chhung */ if (sdio_pro_enable) { //=== for sdio profile === if (mrq->cmd->opcode == 52 || mrq->cmd->opcode == 53) GPT_GetCounter64(&old_L32, &old_H32); } #endif /* end of --- */ host->mrq = mrq; if (msdc_do_request(mmc, mrq)) { if (host->hw->flags & MSDC_REMOVABLE && ralink_soc == MT762X_SOC_MT7621AT && mrq->data && mrq->data->error) msdc_tune_request(mmc, mrq); } /* ==== when request done, check if app_cmd ==== */ if (mrq->cmd->opcode == MMC_APP_CMD) { host->app_cmd = 1; host->app_cmd_arg = mrq->cmd->arg; /* save the RCA */ } else { host->app_cmd = 0; //host->app_cmd_arg = 0; } host->mrq = NULL; #if 0 /* --- by chhung */ //=== for sdio profile === if (sdio_pro_enable) { if (mrq->cmd->opcode == 52 || mrq->cmd->opcode == 53) { GPT_GetCounter64(&new_L32, &new_H32); ticks = msdc_time_calc(old_L32, old_H32, new_L32, new_H32); opcode = mrq->cmd->opcode; if (mrq->cmd->data) { sizes = mrq->cmd->data->blocks * mrq->cmd->data->blksz; bRx = mrq->cmd->data->flags & MMC_DATA_READ ? 1 : 0; } else { bRx = mrq->cmd->arg & 0x80000000 ? 1 : 0; } if (!mrq->cmd->error) msdc_performance(opcode, sizes, bRx, ticks); } } #endif /* end of --- */ spin_unlock(&host->lock); mmc_request_done(mmc, mrq); return; } /* called by ops.set_ios */ static void msdc_set_buswidth(struct msdc_host *host, u32 width) { u32 val = readl(host->base + SDC_CFG); val &= ~SDC_CFG_BUSWIDTH; switch (width) { default: case MMC_BUS_WIDTH_1: width = 1; val |= (MSDC_BUS_1BITS << 16); break; case MMC_BUS_WIDTH_4: val |= (MSDC_BUS_4BITS << 16); break; case MMC_BUS_WIDTH_8: val |= (MSDC_BUS_8BITS << 16); break; } writel(val, host->base + SDC_CFG); N_MSG(CFG, "Bus Width = %d", width); } /* ops.set_ios */ static void msdc_ops_set_ios(struct mmc_host *mmc, struct mmc_ios *ios) { struct msdc_host *host = mmc_priv(mmc); u32 ddr = 0; #ifdef MT6575_SD_DEBUG static char *vdd[] = { "1.50v", "1.55v", "1.60v", "1.65v", "1.70v", "1.80v", "1.90v", "2.00v", "2.10v", "2.20v", "2.30v", "2.40v", "2.50v", "2.60v", "2.70v", "2.80v", "2.90v", "3.00v", "3.10v", "3.20v", "3.30v", "3.40v", "3.50v", "3.60v" }; static char *power_mode[] = { "OFF", "UP", "ON" }; static char *bus_mode[] = { "UNKNOWN", "OPENDRAIN", "PUSHPULL" }; static char *timing[] = { "LEGACY", "MMC_HS", "SD_HS" }; printk("SET_IOS: CLK(%dkHz), BUS(%s), BW(%u), PWR(%s), VDD(%s), TIMING(%s)", ios->clock / 1000, bus_mode[ios->bus_mode], (ios->bus_width == MMC_BUS_WIDTH_4) ? 4 : 1, power_mode[ios->power_mode], vdd[ios->vdd], timing[ios->timing]); #endif msdc_set_buswidth(host, ios->bus_width); /* Power control ??? */ switch (ios->power_mode) { case MMC_POWER_OFF: case MMC_POWER_UP: // msdc_set_power_mode(host, ios->power_mode); /* --- by chhung */ break; case MMC_POWER_ON: host->power_mode = MMC_POWER_ON; break; default: break; } /* Clock control */ if (host->mclk != ios->clock) { if (ios->clock > 25000000) { //if (!(host->hw->flags & MSDC_REMOVABLE)) { INIT_MSG("SD data latch edge<%d>", MSDC_SMPL_FALLING); sdr_set_field(host->base + MSDC_IOCON, MSDC_IOCON_RSPL, MSDC_SMPL_FALLING); sdr_set_field(host->base + MSDC_IOCON, MSDC_IOCON_DSPL, MSDC_SMPL_FALLING); //} /* for tuning debug */ } else { /* default value */ writel(0x00000000, host->base + MSDC_IOCON); // writel(0x00000000, host->base + MSDC_DAT_RDDLY0); // for MT7620 E2 and afterward writel(0x10101010, host->base + MSDC_DAT_RDDLY0); writel(0x00000000, host->base + MSDC_DAT_RDDLY1); // writel(0x00000000, host->base + MSDC_PAD_TUNE); // for MT7620 E2 and afterward writel(0x84101010, host->base + MSDC_PAD_TUNE); } msdc_set_mclk(host, ddr, ios->clock); } } /* ops.get_ro */ static int msdc_ops_get_ro(struct mmc_host *mmc) { struct msdc_host *host = mmc_priv(mmc); unsigned long flags; int ro = 0; if (host->hw->flags & MSDC_WP_PIN_EN) { /* set for card */ spin_lock_irqsave(&host->lock, flags); ro = (readl(host->base + MSDC_PS) >> 31); spin_unlock_irqrestore(&host->lock, flags); } return ro; } /* ops.get_cd */ static int msdc_ops_get_cd(struct mmc_host *mmc) { struct msdc_host *host = mmc_priv(mmc); unsigned long flags; int present = 1; /* for sdio, MSDC_REMOVABLE not set, always return 1 */ if (!(host->hw->flags & MSDC_REMOVABLE)) { /* For sdio, read H/W always get<1>, but may timeout some times */ #if 1 host->card_inserted = 1; return 1; #else host->card_inserted = (host->pm_state.event == PM_EVENT_USER_RESUME) ? 1 : 0; INIT_MSG("sdio ops_get_cd<%d>", host->card_inserted); return host->card_inserted; #endif } /* MSDC_CD_PIN_EN set for card */ if (host->hw->flags & MSDC_CD_PIN_EN) { spin_lock_irqsave(&host->lock, flags); #if 0 present = host->card_inserted; /* why not read from H/W: Fix me*/ #else // CD present = readl(host->base + MSDC_PS) & MSDC_PS_CDSTS; if (cd_active_low) present = present ? 0 : 1; else present = present ? 1 : 0; host->card_inserted = present; #endif spin_unlock_irqrestore(&host->lock, flags); } else { present = 0; /* TODO? Check DAT3 pins for card detection */ } INIT_MSG("ops_get_cd return<%d>", present); return present; } static struct mmc_host_ops mt_msdc_ops = { .request = msdc_ops_request, .set_ios = msdc_ops_set_ios, .get_ro = msdc_ops_get_ro, .get_cd = msdc_ops_get_cd, }; /*--------------------------------------------------------------------------*/ /* interrupt handler */ /*--------------------------------------------------------------------------*/ static irqreturn_t msdc_irq(int irq, void *dev_id) { struct msdc_host *host = (struct msdc_host *)dev_id; struct mmc_data *data = host->data; struct mmc_command *cmd = host->cmd; u32 cmdsts = MSDC_INT_RSPCRCERR | MSDC_INT_CMDTMO | MSDC_INT_CMDRDY | MSDC_INT_ACMDCRCERR | MSDC_INT_ACMDTMO | MSDC_INT_ACMDRDY | MSDC_INT_ACMD19_DONE; u32 datsts = MSDC_INT_DATCRCERR | MSDC_INT_DATTMO; u32 intsts = readl(host->base + MSDC_INT); u32 inten = readl(host->base + MSDC_INTEN); inten &= intsts; writel(intsts, host->base + MSDC_INT); /* clear interrupts */ /* MSG will cause fatal error */ /* card change interrupt */ if (intsts & MSDC_INT_CDSC) { if (host->mmc->caps & MMC_CAP_NEEDS_POLL) return IRQ_HANDLED; IRQ_MSG("MSDC_INT_CDSC irq<0x%.8x>", intsts); schedule_delayed_work(&host->card_delaywork, HZ); /* tuning when plug card ? */ } /* sdio interrupt */ if (intsts & MSDC_INT_SDIOIRQ) { IRQ_MSG("XXX MSDC_INT_SDIOIRQ"); /* seems not sdio irq */ //mmc_signal_sdio_irq(host->mmc); } /* transfer complete interrupt */ if (data != NULL) { if (inten & MSDC_INT_XFER_COMPL) { data->bytes_xfered = host->xfer_size; complete(&host->xfer_done); } if (intsts & datsts) { /* do basic reset, or stop command will sdc_busy */ msdc_reset_hw(host); msdc_clr_fifo(host); msdc_clr_int(); if (intsts & MSDC_INT_DATTMO) { IRQ_MSG("XXX CMD<%d> MSDC_INT_DATTMO", host->mrq->cmd->opcode); data->error = -ETIMEDOUT; } else if (intsts & MSDC_INT_DATCRCERR) { IRQ_MSG("XXX CMD<%d> MSDC_INT_DATCRCERR, SDC_DCRC_STS<0x%x>", host->mrq->cmd->opcode, readl(host->base + SDC_DCRC_STS)); data->error = -EIO; } //if(readl(MSDC_INTEN) & MSDC_INT_XFER_COMPL) { complete(&host->xfer_done); /* Read CRC come fast, XFER_COMPL not enabled */ } } /* command interrupts */ if ((cmd != NULL) && (intsts & cmdsts)) { if ((intsts & MSDC_INT_CMDRDY) || (intsts & MSDC_INT_ACMDRDY) || (intsts & MSDC_INT_ACMD19_DONE)) { u32 *rsp = &cmd->resp[0]; switch (host->cmd_rsp) { case RESP_NONE: break; case RESP_R2: *rsp++ = readl(host->base + SDC_RESP3); *rsp++ = readl(host->base + SDC_RESP2); *rsp++ = readl(host->base + SDC_RESP1); *rsp++ = readl(host->base + SDC_RESP0); break; default: /* Response types 1, 3, 4, 5, 6, 7(1b) */ if ((intsts & MSDC_INT_ACMDRDY) || (intsts & MSDC_INT_ACMD19_DONE)) *rsp = readl(host->base + SDC_ACMD_RESP); else *rsp = readl(host->base + SDC_RESP0); break; } } else if ((intsts & MSDC_INT_RSPCRCERR) || (intsts & MSDC_INT_ACMDCRCERR)) { if (intsts & MSDC_INT_ACMDCRCERR) IRQ_MSG("XXX CMD<%d> MSDC_INT_ACMDCRCERR", cmd->opcode); else IRQ_MSG("XXX CMD<%d> MSDC_INT_RSPCRCERR", cmd->opcode); cmd->error = -EIO; } else if ((intsts & MSDC_INT_CMDTMO) || (intsts & MSDC_INT_ACMDTMO)) { if (intsts & MSDC_INT_ACMDTMO) IRQ_MSG("XXX CMD<%d> MSDC_INT_ACMDTMO", cmd->opcode); else IRQ_MSG("XXX CMD<%d> MSDC_INT_CMDTMO", cmd->opcode); cmd->error = -ETIMEDOUT; msdc_reset_hw(host); msdc_clr_fifo(host); msdc_clr_int(); } complete(&host->cmd_done); } /* mmc irq interrupts */ if (intsts & MSDC_INT_MMCIRQ) printk(KERN_INFO "msdc[%d] MMCIRQ: SDC_CSTS=0x%.8x\r\n", host->id, readl(host->base + SDC_CSTS)); #ifdef MT6575_SD_DEBUG { /* msdc_int_reg *int_reg = (msdc_int_reg*)&intsts;*/ N_MSG(INT, "IRQ_EVT(0x%x): MMCIRQ(%d) CDSC(%d), ACRDY(%d), ACTMO(%d), ACCRE(%d) AC19DN(%d)", intsts, int_reg->mmcirq, int_reg->cdsc, int_reg->atocmdrdy, int_reg->atocmdtmo, int_reg->atocmdcrc, int_reg->atocmd19done); N_MSG(INT, "IRQ_EVT(0x%x): SDIO(%d) CMDRDY(%d), CMDTMO(%d), RSPCRC(%d), CSTA(%d)", intsts, int_reg->sdioirq, int_reg->cmdrdy, int_reg->cmdtmo, int_reg->rspcrc, int_reg->csta); N_MSG(INT, "IRQ_EVT(0x%x): XFCMP(%d) DXDONE(%d), DATTMO(%d), DATCRC(%d), DMAEMP(%d)", intsts, int_reg->xfercomp, int_reg->dxferdone, int_reg->dattmo, int_reg->datcrc, int_reg->dmaqempty); } #endif return IRQ_HANDLED; } /*--------------------------------------------------------------------------*/ /* platform_driver members */ /*--------------------------------------------------------------------------*/ /* called by msdc_drv_probe/remove */ static void msdc_enable_cd_irq(struct msdc_host *host, int enable) { struct msdc_hw *hw = host->hw; /* for sdio, not set */ if ((hw->flags & MSDC_CD_PIN_EN) == 0) { /* Pull down card detection pin since it is not avaiable */ /* if (hw->config_gpio_pin) hw->config_gpio_pin(MSDC_CD_PIN, GPIO_PULL_DOWN); */ sdr_clr_bits(host->base + MSDC_PS, MSDC_PS_CDEN); sdr_clr_bits(host->base + MSDC_INTEN, MSDC_INTEN_CDSC); sdr_clr_bits(host->base + SDC_CFG, SDC_CFG_INSWKUP); return; } N_MSG(CFG, "CD IRQ Enable(%d)", enable); if (enable) { /* card detection circuit relies on the core power so that the core power * shouldn't be turned off. Here adds a reference count to keep * the core power alive. */ //msdc_vcore_on(host); //did in msdc_init_hw() if (hw->config_gpio_pin) /* NULL */ hw->config_gpio_pin(MSDC_CD_PIN, GPIO_PULL_UP); sdr_set_field(host->base + MSDC_PS, MSDC_PS_CDDEBOUNCE, DEFAULT_DEBOUNCE); sdr_set_bits(host->base + MSDC_PS, MSDC_PS_CDEN); sdr_set_bits(host->base + MSDC_INTEN, MSDC_INTEN_CDSC); /* not in document! Fix me */ sdr_set_bits(host->base + SDC_CFG, SDC_CFG_INSWKUP); } else { if (hw->config_gpio_pin) /* NULL */ hw->config_gpio_pin(MSDC_CD_PIN, GPIO_PULL_DOWN); sdr_clr_bits(host->base + SDC_CFG, SDC_CFG_INSWKUP); sdr_clr_bits(host->base + MSDC_PS, MSDC_PS_CDEN); sdr_clr_bits(host->base + MSDC_INTEN, MSDC_INTEN_CDSC); /* Here decreases a reference count to core power since card * detection circuit is shutdown. */ //msdc_vcore_off(host); } } /* called by msdc_drv_probe */ static void msdc_init_hw(struct msdc_host *host) { /* Power on */ #if 0 /* --- by chhung */ msdc_vcore_on(host); msdc_pin_reset(host, MSDC_PIN_PULL_UP); msdc_select_clksrc(host, hw->clk_src); enable_clock(PERI_MSDC0_PDN + host->id, "SD"); msdc_vdd_on(host); #endif /* end of --- */ /* Configure to MMC/SD mode */ sdr_set_field(host->base + MSDC_CFG, MSDC_CFG_MODE, MSDC_SDMMC); /* Reset */ msdc_reset_hw(host); msdc_clr_fifo(host); /* Disable card detection */ sdr_clr_bits(host->base + MSDC_PS, MSDC_PS_CDEN); /* Disable and clear all interrupts */ sdr_clr_bits(host->base + MSDC_INTEN, readl(host->base + MSDC_INTEN)); writel(readl(host->base + MSDC_INT), host->base + MSDC_INT); #if 1 /* reset tuning parameter */ writel(0x00090000, host->base + MSDC_PAD_CTL0); writel(0x000A0000, host->base + MSDC_PAD_CTL1); writel(0x000A0000, host->base + MSDC_PAD_CTL2); // writel( 0x00000000, host->base + MSDC_PAD_TUNE); // for MT7620 E2 and afterward writel(0x84101010, host->base + MSDC_PAD_TUNE); // writel(0x00000000, host->base + MSDC_DAT_RDDLY0); // for MT7620 E2 and afterward writel(0x10101010, host->base + MSDC_DAT_RDDLY0); writel(0x00000000, host->base + MSDC_DAT_RDDLY1); writel(0x00000000, host->base + MSDC_IOCON); #if 0 // use MT7620 default value: 0x403c004f /* bit0 modified: Rx Data Clock Source: 1 -> 2.0*/ writel(0x003C000F, host->base + MSDC_PATCH_BIT0); #endif if (readl(host->base + MSDC_ECO_VER) >= 4) { if (host->id == 1) { sdr_set_field(host->base + MSDC_PATCH_BIT1, MSDC_PATCH_BIT1_WRDAT_CRCS, 1); sdr_set_field(host->base + MSDC_PATCH_BIT1, MSDC_PATCH_BIT1_CMD_RSP, 1); /* internal clock: latch read data */ sdr_set_bits(host->base + MSDC_PATCH_BIT0, MSDC_PATCH_BIT_CKGEN_CK); } } #endif /* for safety, should clear SDC_CFG.SDIO_INT_DET_EN & set SDC_CFG.SDIO in pre-loader,uboot,kernel drivers. and SDC_CFG.SDIO_INT_DET_EN will be only set when kernel driver wants to use SDIO bus interrupt */ /* Configure to enable SDIO mode. it's must otherwise sdio cmd5 failed */ sdr_set_bits(host->base + SDC_CFG, SDC_CFG_SDIO); /* disable detect SDIO device interupt function */ sdr_clr_bits(host->base + SDC_CFG, SDC_CFG_SDIOIDE); /* eneable SMT for glitch filter */ sdr_set_bits(host->base + MSDC_PAD_CTL0, MSDC_PAD_CTL0_CLKSMT); sdr_set_bits(host->base + MSDC_PAD_CTL1, MSDC_PAD_CTL1_CMDSMT); sdr_set_bits(host->base + MSDC_PAD_CTL2, MSDC_PAD_CTL2_DATSMT); #if 1 /* set clk, cmd, dat pad driving */ sdr_set_field(host->base + MSDC_PAD_CTL0, MSDC_PAD_CTL0_CLKDRVN, 4); sdr_set_field(host->base + MSDC_PAD_CTL0, MSDC_PAD_CTL0_CLKDRVP, 4); sdr_set_field(host->base + MSDC_PAD_CTL1, MSDC_PAD_CTL1_CMDDRVN, 4); sdr_set_field(host->base + MSDC_PAD_CTL1, MSDC_PAD_CTL1_CMDDRVP, 4); sdr_set_field(host->base + MSDC_PAD_CTL2, MSDC_PAD_CTL2_DATDRVN, 4); sdr_set_field(host->base + MSDC_PAD_CTL2, MSDC_PAD_CTL2_DATDRVP, 4); #else sdr_set_field(host->base + MSDC_PAD_CTL0, MSDC_PAD_CTL0_CLKDRVN, 0); sdr_set_field(host->base + MSDC_PAD_CTL0, MSDC_PAD_CTL0_CLKDRVP, 0); sdr_set_field(host->base + MSDC_PAD_CTL1, MSDC_PAD_CTL1_CMDDRVN, 0); sdr_set_field(host->base + MSDC_PAD_CTL1, MSDC_PAD_CTL1_CMDDRVP, 0); sdr_set_field(host->base + MSDC_PAD_CTL2, MSDC_PAD_CTL2_DATDRVN, 0); sdr_set_field(host->base + MSDC_PAD_CTL2, MSDC_PAD_CTL2_DATDRVP, 0); #endif /* set sampling edge */ /* write crc timeout detection */ sdr_set_field(host->base + MSDC_PATCH_BIT0, 1 << 30, 1); /* Configure to default data timeout */ sdr_set_field(host->base + SDC_CFG, SDC_CFG_DTOC, DEFAULT_DTOC); msdc_set_buswidth(host, MMC_BUS_WIDTH_1); N_MSG(FUC, "init hardware done!"); } /* called by msdc_drv_remove */ static void msdc_deinit_hw(struct msdc_host *host) { /* Disable and clear all interrupts */ sdr_clr_bits(host->base + MSDC_INTEN, readl(host->base + MSDC_INTEN)); writel(readl(host->base + MSDC_INT), host->base + MSDC_INT); /* Disable card detection */ msdc_enable_cd_irq(host, 0); // msdc_set_power_mode(host, MMC_POWER_OFF); /* make sure power down */ /* --- by chhung */ } /* init gpd and bd list in msdc_drv_probe */ static void msdc_init_gpd_bd(struct msdc_host *host, struct msdc_dma *dma) { struct gpd *gpd = dma->gpd; struct bd *bd = dma->bd; int i; /* we just support one gpd, but gpd->next must be set for desc * DMA. That's why we alloc 2 gpd structurs. */ memset(gpd, 0, sizeof(struct gpd) * 2); gpd->bdp = 1; /* hwo, cs, bd pointer */ gpd->ptr = (void *)dma->bd_addr; /* physical address */ gpd->next = (void *)((u32)dma->gpd_addr + sizeof(struct gpd)); memset(bd, 0, sizeof(struct bd) * MAX_BD_NUM); for (i = 0; i < (MAX_BD_NUM - 1); i++) bd[i].next = (void *)(dma->bd_addr + sizeof(*bd) * (i + 1)); } static int msdc_drv_probe(struct platform_device *pdev) { struct resource *res; __iomem void *base; struct mmc_host *mmc; struct msdc_host *host; struct msdc_hw *hw; int ret; hw = &msdc0_hw; if (of_property_read_bool(pdev->dev.of_node, "mtk,wp-en")) msdc0_hw.flags |= MSDC_WP_PIN_EN; /* Allocate MMC host for this device */ mmc = mmc_alloc_host(sizeof(struct msdc_host), &pdev->dev); if (!mmc) return -ENOMEM; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); base = devm_ioremap_resource(&pdev->dev, res); if (IS_ERR(base)) { ret = PTR_ERR(base); goto host_free; } /* Set host parameters to mmc */ mmc->ops = &mt_msdc_ops; mmc->f_min = HOST_MIN_MCLK; mmc->f_max = HOST_MAX_MCLK; mmc->ocr_avail = MSDC_OCR_AVAIL; mmc->caps = MMC_CAP_MMC_HIGHSPEED | MMC_CAP_SD_HIGHSPEED; //TODO: read this as bus-width from dt (via mmc_of_parse) mmc->caps |= MMC_CAP_4_BIT_DATA; cd_active_low = !of_property_read_bool(pdev->dev.of_node, "mediatek,cd-high"); if (of_property_read_bool(pdev->dev.of_node, "mediatek,cd-poll")) mmc->caps |= MMC_CAP_NEEDS_POLL; /* MMC core transfer sizes tunable parameters */ mmc->max_segs = MAX_HW_SGMTS; mmc->max_seg_size = MAX_SGMT_SZ; mmc->max_blk_size = HOST_MAX_BLKSZ; mmc->max_req_size = MAX_REQ_SZ; mmc->max_blk_count = mmc->max_req_size; host = mmc_priv(mmc); host->hw = hw; host->mmc = mmc; host->id = pdev->id; if (host->id < 0 || host->id >= 4) host->id = 0; host->error = 0; host->irq = platform_get_irq(pdev, 0); if (host->irq < 0) { ret = -EINVAL; goto host_free; } host->base = base; host->mclk = 0; /* mclk: the request clock of mmc sub-system */ host->hclk = hclks[hw->clk_src]; /* hclk: clock of clock source to msdc controller */ host->sclk = 0; /* sclk: the really clock after divition */ host->pm_state = PMSG_RESUME; host->suspend = 0; host->core_clkon = 0; host->card_clkon = 0; host->core_power = 0; host->power_mode = MMC_POWER_OFF; // host->card_inserted = hw->flags & MSDC_REMOVABLE ? 0 : 1; host->timeout_ns = 0; host->timeout_clks = DEFAULT_DTOC * 65536; host->mrq = NULL; //init_MUTEX(&host->sem); /* we don't need to support multiple threads access */ mmc_dev(mmc)->dma_mask = NULL; /* using dma_alloc_coherent*/ /* todo: using 1, for all 4 slots */ host->dma.gpd = dma_alloc_coherent(&pdev->dev, MAX_GPD_NUM * sizeof(struct gpd), &host->dma.gpd_addr, GFP_KERNEL); host->dma.bd = dma_alloc_coherent(&pdev->dev, MAX_BD_NUM * sizeof(struct bd), &host->dma.bd_addr, GFP_KERNEL); if (!host->dma.gpd || !host->dma.bd) { ret = -ENOMEM; goto release_mem; } msdc_init_gpd_bd(host, &host->dma); INIT_DELAYED_WORK(&host->card_delaywork, msdc_tasklet_card); spin_lock_init(&host->lock); msdc_init_hw(host); /* TODO check weather flags 0 is correct, the mtk-sd driver uses * IRQF_TRIGGER_LOW | IRQF_ONESHOT for flags * * for flags 0 the trigger polarity is determined by the * device tree, but not the oneshot flag, but maybe it is also * not needed because the soc could be oneshot safe. */ ret = devm_request_irq(&pdev->dev, host->irq, msdc_irq, 0, pdev->name, host); if (ret) goto release; platform_set_drvdata(pdev, mmc); ret = mmc_add_host(mmc); if (ret) goto release; /* Config card detection pin and enable interrupts */ if (hw->flags & MSDC_CD_PIN_EN) { /* set for card */ msdc_enable_cd_irq(host, 1); } else { msdc_enable_cd_irq(host, 0); } return 0; release: platform_set_drvdata(pdev, NULL); msdc_deinit_hw(host); cancel_delayed_work_sync(&host->card_delaywork); release_mem: if (host->dma.gpd) dma_free_coherent(&pdev->dev, MAX_GPD_NUM * sizeof(struct gpd), host->dma.gpd, host->dma.gpd_addr); if (host->dma.bd) dma_free_coherent(&pdev->dev, MAX_BD_NUM * sizeof(struct bd), host->dma.bd, host->dma.bd_addr); host_free: mmc_free_host(mmc); return ret; } /* 4 device share one driver, using "drvdata" to show difference */ static int msdc_drv_remove(struct platform_device *pdev) { struct mmc_host *mmc; struct msdc_host *host; mmc = platform_get_drvdata(pdev); BUG_ON(!mmc); host = mmc_priv(mmc); BUG_ON(!host); ERR_MSG("removed !!!"); platform_set_drvdata(pdev, NULL); mmc_remove_host(host->mmc); msdc_deinit_hw(host); cancel_delayed_work_sync(&host->card_delaywork); dma_free_coherent(&pdev->dev, MAX_GPD_NUM * sizeof(struct gpd), host->dma.gpd, host->dma.gpd_addr); dma_free_coherent(&pdev->dev, MAX_BD_NUM * sizeof(struct bd), host->dma.bd, host->dma.bd_addr); mmc_free_host(host->mmc); return 0; } /* Fix me: Power Flow */ #ifdef CONFIG_PM static void msdc_drv_pm(struct platform_device *pdev, pm_message_t state) { struct mmc_host *mmc = platform_get_drvdata(pdev); if (mmc) { struct msdc_host *host = mmc_priv(mmc); msdc_pm(state, (void *)host); } } static int msdc_drv_suspend(struct platform_device *pdev, pm_message_t state) { if (state.event == PM_EVENT_SUSPEND) msdc_drv_pm(pdev, state); return 0; } static int msdc_drv_resume(struct platform_device *pdev) { struct pm_message state; state.event = PM_EVENT_RESUME; msdc_drv_pm(pdev, state); return 0; } #endif static const struct of_device_id mt7620_sdhci_match[] = { { .compatible = "ralink,mt7620-sdhci" }, {}, }; MODULE_DEVICE_TABLE(of, mt7620_sdhci_match); static struct platform_driver mt_msdc_driver = { .probe = msdc_drv_probe, .remove = msdc_drv_remove, #ifdef CONFIG_PM .suspend = msdc_drv_suspend, .resume = msdc_drv_resume, #endif .driver = { .name = DRV_NAME, .of_match_table = mt7620_sdhci_match, }, }; /*--------------------------------------------------------------------------*/ /* module init/exit */ /*--------------------------------------------------------------------------*/ static int __init mt_msdc_init(void) { int ret; u32 reg; // Set the pins for sdxc to sdxc mode //FIXME: this should be done by pinctl and not by the sd driver reg = readl((void __iomem *)(RALINK_SYSCTL_BASE + 0x60)) & ~(0x3 << 18); writel(reg, (void __iomem *)(RALINK_SYSCTL_BASE + 0x60)); ret = platform_driver_register(&mt_msdc_driver); if (ret) { printk(KERN_ERR DRV_NAME ": Can't register driver"); return ret; } #if defined(MT6575_SD_DEBUG) msdc_debug_proc_init(); #endif return 0; } static void __exit mt_msdc_exit(void) { platform_driver_unregister(&mt_msdc_driver); } module_init(mt_msdc_init); module_exit(mt_msdc_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("MediaTek MT6575 SD/MMC Card Driver"); MODULE_AUTHOR("Infinity Chen <infinity.chen@mediatek.com>");
28.418303
124
0.639512
[ "object" ]
04e0b86ada2ddb56bc09c286f2ef9d7b8f019894
25,645
h
C
runtime/legion/legion_c_util.h
elliottslaughter/legion_test
9381cd25bc92a6d119aef8be9a91189080533c63
[ "Apache-2.0" ]
null
null
null
runtime/legion/legion_c_util.h
elliottslaughter/legion_test
9381cd25bc92a6d119aef8be9a91189080533c63
[ "Apache-2.0" ]
1
2017-05-11T19:48:20.000Z
2017-05-11T19:48:20.000Z
runtime/legion/legion_c_util.h
elliottslaughter/legion_test
9381cd25bc92a6d119aef8be9a91189080533c63
[ "Apache-2.0" ]
2
2017-05-11T19:18:34.000Z
2018-08-28T16:40:08.000Z
/* Copyright 2018 Stanford University * * 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 __LEGION_C_UTIL_H__ #define __LEGION_C_UTIL_H__ /** * \file legion_c_util.h * Legion C API: C++ Conversion Utilities */ #include "legion.h" #include "legion/legion_c.h" #include "legion/legion_mapping.h" #include "mappers/mapping_utilities.h" #include <stdlib.h> #include <string.h> #include <algorithm> namespace Legion { class CContext; class CObjectWrapper { public: typedef Legion::UnsafeFieldAccessor<char,1,coord_t, Realm::AffineAccessor<char,1,coord_t> > ArrayAccessor1D; typedef Legion::UnsafeFieldAccessor<char,2,coord_t, Realm::AffineAccessor<char,2,coord_t> > ArrayAccessor2D; typedef Legion::UnsafeFieldAccessor<char,3,coord_t, Realm::AffineAccessor<char,3,coord_t> > ArrayAccessor3D; #ifdef __ICC // icpc complains about "error #858: type qualifier on return type is meaningless" // but it's pretty annoying to get this macro to handle all the cases right #pragma warning (push) #pragma warning (disable: 858) #endif #define NEW_OPAQUE_WRAPPER(T_, T) \ static T_ wrap(T t) { \ T_ t_; \ t_.impl = static_cast<void *>(t); \ return t_; \ } \ static const T_ wrap_const(const T t) { \ T_ t_; \ t_.impl = const_cast<void *>(static_cast<const void *>(t)); \ return t_; \ } \ static T unwrap(T_ t_) { \ return static_cast<T>(t_.impl); \ } \ static const T unwrap_const(const T_ t_) { \ return static_cast<const T>(t_.impl); \ } NEW_OPAQUE_WRAPPER(legion_runtime_t, Runtime *); NEW_OPAQUE_WRAPPER(legion_context_t, CContext *); NEW_OPAQUE_WRAPPER(legion_domain_point_iterator_t, Domain::DomainPointIterator *); NEW_OPAQUE_WRAPPER(legion_coloring_t, Coloring *); NEW_OPAQUE_WRAPPER(legion_domain_coloring_t, DomainColoring *); NEW_OPAQUE_WRAPPER(legion_point_coloring_t, PointColoring *); NEW_OPAQUE_WRAPPER(legion_domain_point_coloring_t, DomainPointColoring *); NEW_OPAQUE_WRAPPER(legion_multi_domain_point_coloring_t, MultiDomainPointColoring *); NEW_OPAQUE_WRAPPER(legion_index_space_allocator_t, IndexSpaceAllocator *); NEW_OPAQUE_WRAPPER(legion_field_allocator_t, FieldAllocator *); NEW_OPAQUE_WRAPPER(legion_argument_map_t, ArgumentMap *); NEW_OPAQUE_WRAPPER(legion_predicate_t, Predicate *); NEW_OPAQUE_WRAPPER(legion_future_t, Future *); NEW_OPAQUE_WRAPPER(legion_future_map_t, FutureMap *); NEW_OPAQUE_WRAPPER(legion_task_launcher_t, TaskLauncher *); NEW_OPAQUE_WRAPPER(legion_index_launcher_t, IndexTaskLauncher *); NEW_OPAQUE_WRAPPER(legion_inline_launcher_t, InlineLauncher *); NEW_OPAQUE_WRAPPER(legion_copy_launcher_t, CopyLauncher *); NEW_OPAQUE_WRAPPER(legion_index_copy_launcher_t, IndexCopyLauncher *); NEW_OPAQUE_WRAPPER(legion_acquire_launcher_t, AcquireLauncher *); NEW_OPAQUE_WRAPPER(legion_release_launcher_t, ReleaseLauncher *); NEW_OPAQUE_WRAPPER(legion_attach_launcher_t, AttachLauncher *); NEW_OPAQUE_WRAPPER(legion_must_epoch_launcher_t, MustEpochLauncher *); NEW_OPAQUE_WRAPPER(legion_physical_region_t, PhysicalRegion *); NEW_OPAQUE_WRAPPER(legion_accessor_array_1d_t, ArrayAccessor1D *); NEW_OPAQUE_WRAPPER(legion_accessor_array_2d_t, ArrayAccessor2D *); NEW_OPAQUE_WRAPPER(legion_accessor_array_3d_t, ArrayAccessor3D *); #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif NEW_OPAQUE_WRAPPER(legion_index_iterator_t, IndexIterator *); #ifdef __GNUC__ #pragma GCC diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic pop #endif NEW_OPAQUE_WRAPPER(legion_task_t, Task *); NEW_OPAQUE_WRAPPER(legion_inline_t, InlineMapping *); NEW_OPAQUE_WRAPPER(legion_mappable_t, Mappable *); NEW_OPAQUE_WRAPPER(legion_region_requirement_t , RegionRequirement *); NEW_OPAQUE_WRAPPER(legion_machine_t, Machine *); NEW_OPAQUE_WRAPPER(legion_mapper_t, Mapping::Mapper *); NEW_OPAQUE_WRAPPER(legion_processor_query_t, Machine::ProcessorQuery *); NEW_OPAQUE_WRAPPER(legion_memory_query_t, Machine::MemoryQuery *); NEW_OPAQUE_WRAPPER(legion_machine_query_interface_t, Mapping::Utilities::MachineQueryInterface *); NEW_OPAQUE_WRAPPER(legion_default_mapper_t, Mapping::DefaultMapper *); NEW_OPAQUE_WRAPPER(legion_execution_constraint_set_t, ExecutionConstraintSet *); NEW_OPAQUE_WRAPPER(legion_layout_constraint_set_t, LayoutConstraintSet *); NEW_OPAQUE_WRAPPER(legion_task_layout_constraint_set_t, TaskLayoutConstraintSet *); NEW_OPAQUE_WRAPPER(legion_map_task_input_t, Mapping::Mapper::MapTaskInput *); NEW_OPAQUE_WRAPPER(legion_map_task_output_t, Mapping::Mapper::MapTaskOutput *); NEW_OPAQUE_WRAPPER(legion_slice_task_output_t, Mapping::Mapper::SliceTaskOutput *); NEW_OPAQUE_WRAPPER(legion_physical_instance_t, Mapping::PhysicalInstance *); NEW_OPAQUE_WRAPPER(legion_mapper_runtime_t, Mapping::MapperRuntime *); NEW_OPAQUE_WRAPPER(legion_mapper_context_t, Mapping::MapperContext); typedef std::map<FieldID, const char *> FieldMap; NEW_OPAQUE_WRAPPER(legion_field_map_t, FieldMap *); #undef NEW_OPAQUE_WRAPPER #ifdef __ICC // icpc complains about "error #858: type qualifier on return type is meaningless" // but it's pretty annoying to get this macro to handle all the cases right #pragma warning (pop) #endif static legion_ptr_t wrap(ptr_t ptr) { legion_ptr_t ptr_; ptr_.value = ptr.value; return ptr_; } static ptr_t unwrap(legion_ptr_t ptr_) { ptr_t ptr; ptr.value = ptr_.value; return ptr; } #define NEW_POINT_WRAPPER(T_, T, DIM) \ static T_ wrap(T t) { \ T_ t_; \ for (int i = 0; i < DIM; i++) \ t_.x[i] = t[i]; \ return t_; \ } \ static T unwrap(T_ t_) { \ T t; \ for (int i = 0; i < DIM; i++) \ t[i] = t_.x[i]; \ return t; \ } typedef Point<1,coord_t> Point1D; typedef Point<2,coord_t> Point2D; typedef Point<3,coord_t> Point3D; NEW_POINT_WRAPPER(legion_point_1d_t, Point1D, 1); NEW_POINT_WRAPPER(legion_point_2d_t, Point2D, 2); NEW_POINT_WRAPPER(legion_point_3d_t, Point3D, 3); #undef NEW_POINT_WRAPPER #define NEW_RECT_WRAPPER(T_, T, PT) \ static T_ wrap(T t) { \ T_ t_; \ t_.lo = wrap(PT(t.lo)); \ t_.hi = wrap(PT(t.hi)); \ return t_; \ } \ static T unwrap(T_ t_) { \ T t(unwrap(t_.lo), unwrap(t_.hi)); \ return t; \ } typedef Rect<1,coord_t> Rect1D; typedef Rect<2,coord_t> Rect2D; typedef Rect<3,coord_t> Rect3D; NEW_RECT_WRAPPER(legion_rect_1d_t, Rect1D, Point1D); NEW_RECT_WRAPPER(legion_rect_2d_t, Rect2D, Point2D); NEW_RECT_WRAPPER(legion_rect_3d_t, Rect3D, Point3D); #undef NEW_RECT_WRAPPER #define NEW_BLOCKIFY_WRAPPER(T_, T) \ static T unwrap(T_ t_) { \ T t(unwrap(t_.block_size), unwrap(t_.offset)); \ return t; \ } template<int DIM> struct Blockify { public: Blockify(Point<DIM,coord_t> b, Point<DIM,coord_t> o) : block_size(b), offset(o) { } public: Point<DIM,coord_t> block_size, offset; }; NEW_BLOCKIFY_WRAPPER(legion_blockify_1d_t, Blockify<1>); NEW_BLOCKIFY_WRAPPER(legion_blockify_2d_t, Blockify<2>); NEW_BLOCKIFY_WRAPPER(legion_blockify_3d_t, Blockify<3>); #undef NEW_RECT_WRAPPER #define NEW_TRANSFORM_WRAPPER(T_, T, X, Y) \ static T_ wrap(T t) { \ T_ t_; \ for (int i = 0; i < X; i++) \ for (int j = 0; j < Y; j++) \ t_.trans[i][j] = t[i][j]; \ return t_; \ } \ static T unwrap(T_ t_) { \ T t; \ for (int i = 0; i < X; i++) \ for (int j = 0; j < Y; j++) \ t[i][j] = t_.trans[i][j]; \ return t; \ } typedef Transform<1,1,coord_t> Transform1x1; typedef Transform<1,2,coord_t> Transform1x2; typedef Transform<1,3,coord_t> Transform1x3; typedef Transform<2,1,coord_t> Transform2x1; typedef Transform<2,2,coord_t> Transform2x2; typedef Transform<2,3,coord_t> Transform2x3; typedef Transform<3,1,coord_t> Transform3x1; typedef Transform<3,2,coord_t> Transform3x2; typedef Transform<3,3,coord_t> Transform3x3; NEW_TRANSFORM_WRAPPER(legion_transform_1x1_t, Transform1x1, 1, 1); NEW_TRANSFORM_WRAPPER(legion_transform_1x2_t, Transform1x2, 1, 2); NEW_TRANSFORM_WRAPPER(legion_transform_1x3_t, Transform1x3, 1, 3); NEW_TRANSFORM_WRAPPER(legion_transform_2x1_t, Transform2x1, 2, 1); NEW_TRANSFORM_WRAPPER(legion_transform_2x2_t, Transform2x2, 2, 2); NEW_TRANSFORM_WRAPPER(legion_transform_2x3_t, Transform2x3, 2, 3); NEW_TRANSFORM_WRAPPER(legion_transform_3x1_t, Transform3x1, 3, 1); NEW_TRANSFORM_WRAPPER(legion_transform_3x2_t, Transform3x2, 3, 2); NEW_TRANSFORM_WRAPPER(legion_transform_3x3_t, Transform3x3, 3, 3); #undef NEW_TRANSFORM_WRAPPER #define NEW_AFFINE_TRANSFORM_WRAPPER(T_, T) \ static T_ wrap(T t) { \ T_ t_; \ t_.transform = wrap(t.transform); \ t_.offset = wrap(t.offset); \ return t_; \ } \ static T unwrap(T_ t_) { \ T t; \ t.transform = unwrap(t_.transform); \ t.offset = unwrap(t_.offset); \ return t; \ } typedef AffineTransform<1,1,coord_t> AffineTransform1x1; typedef AffineTransform<1,2,coord_t> AffineTransform1x2; typedef AffineTransform<1,3,coord_t> AffineTransform1x3; typedef AffineTransform<2,1,coord_t> AffineTransform2x1; typedef AffineTransform<2,2,coord_t> AffineTransform2x2; typedef AffineTransform<2,3,coord_t> AffineTransform2x3; typedef AffineTransform<3,1,coord_t> AffineTransform3x1; typedef AffineTransform<3,2,coord_t> AffineTransform3x2; typedef AffineTransform<3,3,coord_t> AffineTransform3x3; NEW_AFFINE_TRANSFORM_WRAPPER(legion_affine_transform_1x1_t, AffineTransform1x1); NEW_AFFINE_TRANSFORM_WRAPPER(legion_affine_transform_1x2_t, AffineTransform1x2); NEW_AFFINE_TRANSFORM_WRAPPER(legion_affine_transform_1x3_t, AffineTransform1x3); NEW_AFFINE_TRANSFORM_WRAPPER(legion_affine_transform_2x1_t, AffineTransform2x1); NEW_AFFINE_TRANSFORM_WRAPPER(legion_affine_transform_2x2_t, AffineTransform2x2); NEW_AFFINE_TRANSFORM_WRAPPER(legion_affine_transform_2x3_t, AffineTransform2x3); NEW_AFFINE_TRANSFORM_WRAPPER(legion_affine_transform_3x1_t, AffineTransform3x1); NEW_AFFINE_TRANSFORM_WRAPPER(legion_affine_transform_3x2_t, AffineTransform3x2); NEW_AFFINE_TRANSFORM_WRAPPER(legion_affine_transform_3x3_t, AffineTransform3x3); #undef NEW_AFFINE_TRANSFORM_WRAPPER static legion_domain_t wrap(Domain domain) { legion_domain_t domain_; domain_.is_id = domain.is_id; domain_.dim = domain.dim; std::copy(domain.rect_data, domain.rect_data + 2 * MAX_RECT_DIM, domain_.rect_data); return domain_; } static Domain unwrap(legion_domain_t domain_) { Domain domain; domain.is_id = domain_.is_id; domain.dim = domain_.dim; std::copy(domain_.rect_data, domain_.rect_data + 2 * MAX_RECT_DIM, domain.rect_data); return domain; } static legion_domain_point_t wrap(DomainPoint dp) { legion_domain_point_t dp_; dp_.dim = dp.dim; std::copy(dp.point_data, dp.point_data + MAX_POINT_DIM, dp_.point_data); return dp_; } static DomainPoint unwrap(legion_domain_point_t dp_) { DomainPoint dp; dp.dim = dp_.dim; std::copy(dp_.point_data, dp_.point_data + MAX_POINT_DIM, dp.point_data); return dp; } static legion_domain_transform_t wrap(DomainTransform transform) { legion_domain_transform_t transform_; transform_.m = transform.m; transform_.n = transform.n; std::copy(transform.matrix, transform.matrix + MAX_POINT_DIM * MAX_POINT_DIM, transform_.matrix); return transform_; } static DomainTransform unwrap(legion_domain_transform_t transform_) { DomainTransform transform; transform.m = transform_.m; transform.n = transform_.n; std::copy(transform_.matrix, transform_.matrix + MAX_POINT_DIM * MAX_POINT_DIM, transform.matrix); return transform; } static legion_domain_affine_transform_t wrap(DomainAffineTransform transform) { legion_domain_affine_transform_t transform_; transform_.transform = wrap(transform.transform); transform_.offset = wrap(transform.offset); return transform_; } static DomainAffineTransform unwrap(legion_domain_affine_transform_t transform_) { DomainAffineTransform transform; transform.transform = unwrap(transform_.transform); transform.offset = unwrap(transform_.offset); return transform; } static legion_index_space_t wrap(IndexSpace is) { legion_index_space_t is_; is_.id = is.id; is_.tid = is.tid; is_.type_tag = is.type_tag; return is_; } static IndexSpace unwrap(legion_index_space_t is_) { IndexSpace is; is.id = is_.id; is.tid = is_.tid; is.type_tag = is_.type_tag; return is; } static legion_index_partition_t wrap(IndexPartition ip) { legion_index_partition_t ip_; ip_.id = ip.id; ip_.tid = ip.tid; ip_.type_tag = ip.type_tag; return ip_; } static IndexPartition unwrap(legion_index_partition_t ip_) { IndexPartition ip; ip.id = ip_.id; ip.tid = ip_.tid; ip.type_tag = ip_.type_tag; return ip; } static legion_field_space_t wrap(FieldSpace fs) { legion_field_space_t fs_; fs_.id = fs.id; return fs_; } static FieldSpace unwrap(legion_field_space_t fs_) { FieldSpace fs(fs_.id); return fs; } static legion_logical_region_t wrap(LogicalRegion r) { legion_logical_region_t r_; r_.tree_id = r.tree_id; r_.index_space = wrap(r.index_space); r_.field_space = wrap(r.field_space); return r_; } static LogicalRegion unwrap(legion_logical_region_t r_) { LogicalRegion r(r_.tree_id, unwrap(r_.index_space), unwrap(r_.field_space)); return r; } static legion_logical_partition_t wrap(LogicalPartition r) { legion_logical_partition_t r_; r_.tree_id = r.tree_id; r_.index_partition = wrap(r.index_partition); r_.field_space = wrap(r.field_space); return r_; } static LogicalPartition unwrap(legion_logical_partition_t r_) { LogicalPartition r(r_.tree_id, unwrap(r_.index_partition), unwrap(r_.field_space)); return r; } static legion_task_argument_t wrap(TaskArgument arg) { legion_task_argument_t arg_; arg_.args = arg.get_ptr(); arg_.arglen = arg.get_size(); return arg_; } static TaskArgument unwrap(legion_task_argument_t arg_) { return TaskArgument(arg_.args, arg_.arglen); } static const legion_byte_offset_t wrap(const ptrdiff_t offset) { legion_byte_offset_t offset_; offset_.offset = offset; return offset_; } static ptrdiff_t unwrap(const legion_byte_offset_t offset_) { return offset_.offset; } static const legion_input_args_t wrap_const(const InputArgs arg) { legion_input_args_t arg_; arg_.argv = arg.argv; arg_.argc = arg.argc; return arg_; } static const InputArgs unwrap_const(const legion_input_args_t args_) { InputArgs args; args.argv = args_.argv; args.argc = args_.argc; return args; } static legion_task_config_options_t wrap(TaskConfigOptions options) { legion_task_config_options_t options_; options_.leaf = options.leaf; options_.inner = options.inner; options_.idempotent = options.idempotent; return options_; } static TaskConfigOptions unwrap(legion_task_config_options_t options_) { TaskConfigOptions options(options_.leaf, options_.inner, options_.idempotent); return options; } static legion_processor_t wrap(Processor proc) { legion_processor_t proc_; proc_.id = proc.id; return proc_; } static Processor unwrap(legion_processor_t proc_) { Processor proc; proc.id = proc_.id; return proc; } static legion_processor_kind_t wrap(Processor::Kind options) { return static_cast<legion_processor_kind_t>(options); } static Processor::Kind unwrap(legion_processor_kind_t options_) { return static_cast<Processor::Kind>(options_); } static legion_memory_t wrap(Memory mem) { legion_memory_t mem_; mem_.id = mem.id; return mem_; } static Memory unwrap(legion_memory_t mem_) { Memory mem; mem.id = mem_.id; return mem; } static legion_memory_kind_t wrap(Memory::Kind options) { return static_cast<legion_memory_kind_t>(options); } static Memory::Kind unwrap(legion_memory_kind_t options_) { return static_cast<Memory::Kind>(options_); } static legion_task_slice_t wrap(Mapping::Mapper::TaskSlice task_slice) { legion_task_slice_t task_slice_; task_slice_.domain = wrap(task_slice.domain); task_slice_.proc = wrap(task_slice.proc); task_slice_.recurse = task_slice.recurse; task_slice_.stealable = task_slice.stealable; return task_slice_; } static Mapping::Mapper::TaskSlice unwrap(legion_task_slice_t task_slice_) { Mapping::Mapper::TaskSlice task_slice; task_slice.domain = unwrap(task_slice_.domain); task_slice.proc = unwrap(task_slice_.proc); task_slice.recurse = task_slice_.recurse; task_slice.stealable = task_slice_.stealable; return task_slice; } static legion_phase_barrier_t wrap(PhaseBarrier barrier) { legion_phase_barrier_t barrier_; barrier_.id = barrier.get_barrier().id; barrier_.timestamp = barrier.get_barrier().timestamp; return barrier_; } static PhaseBarrier unwrap(legion_phase_barrier_t barrier_) { PhaseBarrier barrier; barrier.phase_barrier.id = barrier_.id; barrier.phase_barrier.timestamp = barrier_.timestamp; return barrier; } static legion_dynamic_collective_t wrap(DynamicCollective collective) { legion_dynamic_collective_t collective_; collective_.id = collective.get_barrier().id; collective_.timestamp = collective.get_barrier().timestamp; collective_.redop = collective.redop; return collective_; } static DynamicCollective unwrap(legion_dynamic_collective_t collective_) { DynamicCollective collective; collective.phase_barrier.id = collective_.id; collective.phase_barrier.timestamp = collective_.timestamp; collective.redop = collective_.redop; return collective; } static legion_task_options_t wrap(Mapping::Mapper::TaskOptions& options) { legion_task_options_t options_; options_.initial_proc = CObjectWrapper::wrap(options.initial_proc); options_.inline_task = options.inline_task; options_.stealable = options.stealable; options_.map_locally = options.map_locally; options_.parent_priority = options.parent_priority; return options_; } static Mapping::Mapper::TaskOptions unwrap(legion_task_options_t& options_) { Mapping::Mapper::TaskOptions options; options.initial_proc = CObjectWrapper::unwrap(options_.initial_proc); options.inline_task = options_.inline_task; options.stealable = options_.stealable; options.map_locally = options_.map_locally; options.parent_priority = options_.parent_priority; return options; } static legion_slice_task_input_t wrap(Mapping::Mapper::SliceTaskInput& input) { legion_slice_task_input_t input_; input_.domain = CObjectWrapper::wrap(input.domain); return input_; } static legion_slice_task_input_t wrap_const(const Mapping::Mapper::SliceTaskInput& input) { legion_slice_task_input_t input_; input_.domain = CObjectWrapper::wrap(input.domain); return input_; } static Mapping::Mapper::SliceTaskInput unwrap(legion_slice_task_input_t& input_) { Mapping::Mapper::SliceTaskInput input; input.domain = CObjectWrapper::unwrap(input_.domain); return input; } }; class CContext { public: CContext(Context _ctx) : ctx(_ctx) {} CContext(Context _ctx, const std::vector<PhysicalRegion>& _physical_regions) : ctx(_ctx) , physical_regions(_physical_regions.size()) { for (size_t i = 0; i < _physical_regions.size(); i++) { physical_regions[i] = CObjectWrapper::wrap(new PhysicalRegion(_physical_regions[i])); } } ~CContext(void) { for (size_t i = 0; i < physical_regions.size(); i++) { delete CObjectWrapper::unwrap(physical_regions[i]); } } Context context(void) const { return ctx; } const legion_physical_region_t *regions(void) const { if(physical_regions.empty()) return 0; else return &physical_regions[0]; } size_t num_regions(void) const { return physical_regions.size(); } protected: Context ctx; std::vector<legion_physical_region_t> physical_regions; }; }; #endif // __LEGION_C_UTIL_H__
35.667594
106
0.609982
[ "vector", "transform" ]
04e6426ed9fb087d1e5dd3d47c957f6e7e29e404
9,429
c
C
m_fire.c
viciious/jaguardoom
7ccec30b164317ad7e0c822e3e1de32ae89f0ba7
[ "MIT" ]
null
null
null
m_fire.c
viciious/jaguardoom
7ccec30b164317ad7e0c822e3e1de32ae89f0ba7
[ "MIT" ]
null
null
null
m_fire.c
viciious/jaguardoom
7ccec30b164317ad7e0c822e3e1de32ae89f0ba7
[ "MIT" ]
null
null
null
/* Victor Luchits, Samuel Villarreal and Fabien Sanglard The MIT License (MIT) Copyright (c) 2021 Victor Luchits, Derek John Evans, id Software and ZeniMax Media Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "doomdef.h" #include "mars.h" // based on work by Samuel Villarreal and Fabien Sanglard typedef struct { unsigned char* firePal; int firePalCols; char* firePix; unsigned char *rndtable; int rndindex; jagobj_t* titlepic; int solid_fire_height; int bottom_pos; int titlepic_pos_x; } m_fire_t; #define FIRE_WIDTH 320 #define FIRE_HEIGHT 72 #define FIRE_STOP_TICON 470 const unsigned char fireRGBs[] = { 0x00, 0x00, 0x00, 0x1F, 0x07, 0x07, //0x2F, 0x0F, 0x07, 0x47, 0x0F, 0x07, 0x57, 0x17, 0x07, //0x67, 0x1F, 0x07, 0x77, 0x1F, 0x07, //0x8F, 0x27, 0x07, 0x9F, 0x2F, 0x07, 0xAF, 0x3F, 0x07, 0xBF, 0x47, 0x07, //0xC7, 0x47, 0x07, 0xDF, 0x4F, 0x07, 0xDF, 0x57, 0x07, 0xDF, 0x57, 0x07, //0xD7, 0x5F, 0x07, 0xD7, 0x5F, 0x07, 0xD7, 0x67, 0x0F, 0xCF, 0x6F, 0x0F, //0xCF, 0x77, 0x0F, 0xCF, 0x7F, 0x0F, 0xCF, 0x87, 0x17, //0xC7, 0x87, 0x17, 0xC7, 0x8F, 0x17, 0xC7, 0x97, 0x1F, 0xBF, 0x9F, 0x1F, //0xBF, 0x9F, 0x1F, 0xBF, 0xA7, 0x27, 0xBF, 0xA7, 0x27, //0xBF, 0xAF, 0x2F, 0xB7, 0xAF, 0x2F, //0xB7, 0xB7, 0x2F, 0xB7, 0xB7, 0x37, //0xCF, 0xCF, 0x6F, 0xDF, 0xDF, 0x9F, 0xEF, 0xEF, 0xC7, 0xFF, 0xFF, 0xFF }; static m_fire_t *m_fire; static inline void M_SpreadFire(int src) ATTR_OPTIMIZE_EXTREME; static inline void M_StopFire(void) ATTR_OPTIMIZE_EXTREME; static inline int M_FireRand(void) { int idx; idx = (m_fire->rndindex + 1) & 0xff; m_fire->rndindex = idx; return m_fire->rndtable[idx]; } static inline void M_SpreadFire(int src) { char newval = 0; char* firePix = m_fire->firePix; char pixel = firePix[src]; int dst = src; if (pixel > 0) { int randIdx = M_FireRand(); dst = src - randIdx + 1; newval = pixel - (randIdx & 1); } dst -= FIRE_WIDTH; firePix[dst] = newval; } static inline void M_StopFire(void) { int x, y; char* firePix = m_fire->firePix; for (y = FIRE_HEIGHT - 1; y > FIRE_HEIGHT - 8; y--) { int* row = (int *)&firePix[y * FIRE_WIDTH]; for (x = 0; x < FIRE_WIDTH; x += 4) { union { int i; char b[4]; } bs; bs.i = *row; if (bs.i != 0) { int j; for (j = 0; j < 4; j++) { int c = bs.b[j] - M_FireRand(); bs.b[j] = c <= 0 ? 0 : c; } *row = bs.i; } row++; } } } void Mars_Sec_M_AnimateFire(void) { int start; Mars_ClearCache(); start = I_GetTime(); while (MARS_SYS_COMM4 == 8) { int x, y; for (x = 0; x < FIRE_WIDTH; x += 4) { int from0 = x + FIRE_WIDTH; int from1 = x + FIRE_WIDTH + 1; int from2 = x + FIRE_WIDTH + 2; int from3 = x + FIRE_WIDTH + 3; // y = 1 M_SpreadFire(from0); from0 += FIRE_WIDTH; M_SpreadFire(from1); from1 += FIRE_WIDTH; M_SpreadFire(from2); from2 += FIRE_WIDTH; M_SpreadFire(from3); from3 += FIRE_WIDTH; for (y = 2; y < FIRE_HEIGHT; y++) { M_SpreadFire(from0); from0 += FIRE_WIDTH; M_SpreadFire(from1); from1 += FIRE_WIDTH; M_SpreadFire(from2); from2 += FIRE_WIDTH; M_SpreadFire(from3); from3 += FIRE_WIDTH; } } if (I_GetTime() - start > FIRE_STOP_TICON) { M_StopFire(); } } Mars_ClearCache(); } /* ================ = = I_InitMenuFire = ================ */ void I_InitMenuFire(jagobj_t *titlepic) { int i, j; const byte* doompalette; doompalette = W_POINTLUMPNUM(W_GetNumForName("PLAYPALS")); m_fire = Z_Malloc(sizeof(*m_fire), PU_STATIC, NULL); D_memset(m_fire, 0, sizeof(*m_fire)); m_fire->firePalCols = sizeof(fireRGBs) / 3; m_fire->firePal = Z_Malloc(sizeof(*m_fire->firePal) * m_fire->firePalCols, PU_STATIC, NULL); m_fire->firePix = Z_Malloc(sizeof(*m_fire->firePix) * FIRE_WIDTH * (FIRE_HEIGHT + 1), PU_STATIC, NULL); m_fire->firePix += FIRE_WIDTH; D_memset(m_fire->firePix, 0, sizeof(*m_fire->firePix) * FIRE_WIDTH * FIRE_HEIGHT); m_fire->rndindex = 0; m_fire->rndtable = Z_Malloc(sizeof(*m_fire->rndtable) * 256, PU_STATIC, NULL); m_fire->titlepic = titlepic; if (titlepic) m_fire->titlepic_pos_x = (320 - titlepic->width) / 2; m_fire->solid_fire_height = 18; m_fire->bottom_pos = /*I_FrameBufferHeight()*/224 - m_fire->solid_fire_height; char* dest = m_fire->firePix + FIRE_WIDTH * (FIRE_HEIGHT - 1); for (j = 0; j < FIRE_WIDTH; j++) *dest++ = m_fire->firePalCols - 1; // find the best matches for fire RGB colors in the palette unsigned char* firePal = m_fire->firePal; for (i = 0; i < m_fire->firePalCols; i++) { const byte* pal = doompalette; byte ar = fireRGBs[i * 3 + 0], ag = fireRGBs[i * 3 + 1], ab = fireRGBs[i * 3 + 2]; int best, bestdist; best = 0; bestdist = 0xFFFFFFF; for (j = 0; j < 256; j++) { byte r = *pal++, g = *pal++, b = *pal++; int dist = (ar - r) * (ar - r) + (ag - g) * (ag - g) + (ab - b) * (ab - b); if (dist < bestdist) { best = j; bestdist = dist; } } firePal[i] = best; } for (i = 0; i < 256; i++) m_fire->rndtable[i] = M_Random() & 3; if (titlepic != NULL) { for (i = 0; i < 2; i++) { short* lines = Mars_FrameBufferLines(); DrawFillRect(0, 0, 320, 224, 0); DrawJagobj2(titlepic, m_fire->titlepic_pos_x, 0, 0, 0, 0, m_fire->bottom_pos - FIRE_HEIGHT, I_FrameBuffer()); for (j = 0; j < m_fire->bottom_pos - FIRE_HEIGHT; j++) lines[j] = 224 * 320 / 2 + 0x100; UpdateBuffer(); } } Mars_M_BeginDrawFire(); } /* ================ = = I_StopMenuFire = ================ */ void I_StopMenuFire(void) { Mars_M_EndDrawFire(); Z_Free(m_fire->rndtable); Z_Free(m_fire->firePix - FIRE_WIDTH); Z_Free(m_fire->firePal); Z_Free(m_fire); Mars_ClearCache(); } /* ================ = = I_DrawMenuFire = ================ */ void I_DrawMenuFire(void) { int x, y; char* firePix = m_fire->firePix; jagobj_t* titlepic = m_fire->titlepic; unsigned char* firePal = m_fire->firePal; unsigned* row; const int pic_startpos = -28; const int pic_cutoff = 16; const int fh = FIRE_HEIGHT; const int solid_fire_height = m_fire->solid_fire_height; const int bottom_pos = m_fire->bottom_pos; unsigned* dest = (unsigned*)(I_OverwriteBuffer() + 320 / 2 * (bottom_pos + solid_fire_height - FIRE_HEIGHT)); // scroll the title pic from bottom to top // unroll the hidden part as the picture moves int pos = (ticon + pic_startpos) / 2; if (pos >= fh && pos <= bottom_pos+2) { int j; int limit = pos > bottom_pos ? 0 : bottom_pos - pos; short* lines = Mars_FrameBufferLines(); for (j = limit; j < bottom_pos - fh; j++) lines[j] = (j - limit) * 320 / 2 + 0x100; } if (titlepic != NULL) { // clear the framebuffer underneath the fire where the title pic is // no longer draw and thus can no longer as serve as the background if (ticon >= FIRE_STOP_TICON) { row = (unsigned*)(I_FrameBuffer() + 320 / 2 * (200 - pic_cutoff)); for (y = 200 - pic_cutoff; y <= bottom_pos; y++) { for (x = 0; x < 320 / 4; x += 4) *row++ = 0, *row++ = 0, *row++ = 0, *row++ = 0; } } // draw the clipped title pic // avoid drawing the part that's hidden by the fire animation at // the bottom of the screen. the upper part must mesh together // with the part that is being unfolded using the line table int y = bottom_pos - (pos < fh ? pos : fh); int src_y = pos > fh ? ((pos >= bottom_pos ? bottom_pos : pos) - fh) : 0; if (pos >= solid_fire_height) { int h = (pos >= 200 - pic_cutoff ? 0 - pic_cutoff : pos); DrawFillRect(0, y, m_fire->titlepic_pos_x, 200, 0); DrawJagobj2(titlepic, m_fire->titlepic_pos_x, y, 0, src_y, 0, h, I_FrameBuffer()); DrawFillRect(titlepic->width + m_fire->titlepic_pos_x, y, 320, 200, 0); } } // draw the fire at the bottom Mars_ClearCache(); row = (unsigned*)((intptr_t)firePix); for (y = 0; y < FIRE_HEIGHT; y++) { for (x = 0; x < FIRE_WIDTH; x += 4) { unsigned p = *row; unsigned p1 = p & 255; p >>= 8; unsigned p2 = p & 255; p >>= 8; unsigned p3 = p & 255; p >>= 8; unsigned p4 = p & 255; p >>= 8; p1 = firePal[p1]; p2 = firePal[p2]; p3 = firePal[p3]; p4 = firePal[p4]; p = (p4 << 24) | (p3 << 16) | (p2 << 8) | p1; *dest++ = p; row++; } if (y == FIRE_HEIGHT - solid_fire_height) { size_t offs = dest - (unsigned*)I_OverwriteBuffer(); dest = (unsigned*)I_FrameBuffer() + offs; } } }
23.931472
112
0.63135
[ "mesh" ]
04eab50e5f2b2a0ff08ee062cf13e09c83115f91
20,828
c
C
src/locfit/pout.c
idiv-biodiversity/cufflinks
e17bfcb3190b12ade76a5e326234dc490444bf42
[ "BSL-1.0" ]
278
2015-01-21T03:30:45.000Z
2022-03-24T02:59:53.000Z
src/locfit/pout.c
idiv-biodiversity/cufflinks
e17bfcb3190b12ade76a5e326234dc490444bf42
[ "BSL-1.0" ]
116
2015-01-07T18:57:16.000Z
2022-02-20T03:47:24.000Z
src/locfit/pout.c
idiv-biodiversity/cufflinks
e17bfcb3190b12ade76a5e326234dc490444bf42
[ "BSL-1.0" ]
148
2015-01-08T18:14:17.000Z
2022-03-17T01:45:29.000Z
/* * Copyright (c) 1996-2000 Lucent Technologies. * See README file for details. * * * print a plot structure in the format of various graph packages */ #include "local.h" #ifdef CVERSION #define XCON(x) (INT)(i0+(i1-i0)*(x-px[0])/(px[1]-px[0])) #define YCON(y) (INT)(k0+(k1-k0)*(y-py[0])/(py[1]-py[0])) extern double sin(), cos(), sqrt(), atan2(), ceil(), floor(), log10(), pow(); static INT i0, i1, k0, k1, cw, ch; #ifdef YAWN static FILE *plf; #endif extern INT curwin, lfcm[10]; #ifdef NOPIPES FILE *popen(const char *cmd,const char *mode) { return(NULL); } int pclose(FILE *file) { return(0); } #endif extern device devps, devwin; char f2(fmt) char *fmt; { char *z; z = strchr(fmt,','); if (z==NULL) return('d'); z++; return(*z); } INT pretty(xl,k,z) double *xl, *z; INT k; { double dlt, m; INT i, j, u; if (k<=0) return(0); dlt = (xl[1]-xl[0])/k; m = floor(log10(dlt)); dlt *= pow(10.0,-m); if (dlt<2) u = 2; else if (dlt<5) u = 5; else { u = 1; m++; } /* increments should be u*10^m; */ dlt = u*pow(10.0,m); i = (INT)ceil(xl[0]/dlt); j = 0; while ((j<k) && ((i+j)*dlt<=xl[1])) { z[j] = (i+j)*dlt; j++; } return(j); } void isgrid(xyz) plxyz *xyz; { INT i, n; vari *x, *y, *z; x = xyz->x; y = xyz->y; z = xyz->z; if ((x!=NULL) & (y!=NULL) & (z!=NULL)) { if ((x->n*y->n)==z->n) { xyz->nx = x->n; xyz->ny = y->n; xyz->n = z->n; xyz->t = 1; return; } if ((x->n>1) & (y->n>1)) { i = 0; n = z->n; while ((i<y->n) && (vitem(y,0)==vitem(y,i))) i++; if ((i>1) && (i*(n/i)==n)) { xyz->nx = n/i; xyz->ny = i; xyz->n = n; xyz->t = 1; return; } } } xyz->t = 0; xyz->n = 0; if ((x!=NULL) && (x->n>xyz->n)) xyz->n = x->n; if ((y!=NULL) && (y->n>xyz->n)) xyz->n = y->n; if ((z!=NULL) && (z->n>xyz->n)) xyz->n = z->n; } void getxyzitem(x,xyz,i) plxyz *x; double xyz[3]; int i; { xyz[0] = vitem(x->x,i); if (x->t==1) xyz[1] = vitem(x->y,i/x->x->n); else xyz[1] = vitem(x->y,i); xyz[2] = vitem(x->z,i); } static double xl[2], yl[2], zl[2], px[2], py[2]; void project(z,x,theta,phi) double *z, *x, theta, phi; { double z0, z1, z2; z0 = (z[0]-xl[0])/(xl[1]-xl[0]); z1 = (z[1]-yl[0])/(yl[1]-yl[0]); z2 = (z[2]-zl[0])/(zl[1]-zl[0]); x[0] = cos(theta)*z0-sin(theta)*z1; x[1] = (sin(theta)*z0+cos(theta)*z1)*cos(phi)+sin(phi)*z2; } void iproject(z,i,theta,phi) double *z, theta, phi; INT *i; { double x[2]; project(z,x,theta,phi); i[0] = XCON(x[0]); i[1] = YCON(x[1]); } void line3d(z1,z2,theta,phi,dev,col) double *z1, *z2, theta, phi; device *dev; INT col; { INT x1[2], x2[2]; iproject(z1,x1,theta,phi); iproject(z2,x2,theta,phi); dev->SetColor(lfcm[col]); dev->DrawLine(x1[0],x1[1],x2[0],x2[1]); } void xyztext(tx,x,ah,av,theta,phi,dev,col) double *x, theta, phi; INT ah, av, col; char *tx; device *dev; { INT xy[2]; iproject(x,xy,theta,phi); dev->SetColor(lfcm[col]); dev->DoText(0,xy[0],xy[1],tx,ah,av); } int getgreylevel(z) double z; { int c; c = 8+11*(z-zl[0])/(zl[1]-zl[0]); if (c<8) return(8); if (c>18)return(18); return(c); } void points3d(x,theta,phi,dev,type) plxyz *x; double theta, phi; char type; device *dev; { INT i, xy[2]; double xyz[3]; for (i=0; i<x->n; i++) { getxyzitem(x,xyz,i); iproject(xyz,xy,theta,phi); if (type=='q') dev->SetColor(getgreylevel(xyz[2])); else dev->SetColor(lfcm[CPOI]); dev->DrawPoint(xy[0],xy[1],x->pch); } } void lines3d(xyz,theta,phi,dev) plxyz *xyz; double theta, phi; device *dev; { INT i; double x0[3], x1[3]; getxyzitem(xyz,x0,0); for (i=1; i<xyz->n; i++) { if (i&1) { getxyzitem(xyz,x1,i); line3d(x0,x1,theta,phi,dev,CLIN); } else { getxyzitem(xyz,x0,i); line3d(x1,x0,theta,phi,dev,CLIN); } } } void segments(xyz0,xyz1,theta,phi,dev) plxyz *xyz0, *xyz1; double theta, phi; device *dev; { INT i, n; double x0[3], x1[3]; n = xyz0->n; if (xyz1->n>n) n = xyz1->n; for (i=0; i<n; i++) { getxyzitem(xyz0,x0,i); getxyzitem(xyz1,x1,i); line3d(x0,x1,theta,phi,dev,CSEG); } } double spl(z0,z1) double z0, z1; { if (z0-z1==0.0) return(0.5); return(z0/(z0-z1)); } void contour3d(x,theta,phi,dev,sl,nsl) plxyz *x; double theta, phi, *sl; INT nsl; device *dev; { INT i, j, k, nx, ny, s; double xyz[4][3], u[4], x0[3], x1[3], x2[3], x3[3], r; char lb[20]; if (x->t==0) ERROR(("Contour: not a grid")); if (lf_error) return; if (nsl==0) nsl = pretty(zl,10,sl); nx = x->nx; ny = x->ny; for (k=0; k<nsl; k++) { x0[2] = x1[2] = x2[2] = x3[2] = sl[k]; for (i=0; i<nx-1; i++) for (j=0; j<ny-1; j++) { sprintf(lb,"%g",sl[k]); getxyzitem(x,xyz[0],i+j*nx); getxyzitem(x,xyz[1],(i+1)+j*nx); getxyzitem(x,xyz[2],i+(j+1)*nx); getxyzitem(x,xyz[3],i+1+(j+1)*nx); u[0] = xyz[0][2]-sl[k]; u[1] = xyz[1][2]-sl[k]; u[2] = xyz[2][2]-sl[k]; u[3] = xyz[3][2]-sl[k]; if (u[0]*u[1]<=0) /* bottom of cell */ { r = spl(u[0],u[1]); x0[0] = (1-r)*xyz[0][0]+r*xyz[1][0]; x0[1] = xyz[0][1]; if (j==0) xyztext(lb,x0,-1,-1,theta,phi,dev,CCLA); } if (u[1]*u[3]<=0) /* right of cell */ { r = spl(u[1],u[3]); x1[0] = xyz[1][0]; x1[1] = (1-r)*xyz[1][1]+r*xyz[3][1]; if (i==nx-2) xyztext(lb,x1,-1,0,theta,phi,dev,CCLA); } if (u[2]*u[3]<=0) /* top of cell */ { r = spl(u[2],u[3]); x2[0] = (1-r)*xyz[2][0]+r*xyz[3][0]; x2[1] = xyz[2][1]; if (j==ny-2) xyztext(lb,x2,-1,1,theta,phi,dev,CCLA); } if (u[0]*u[2]<=0) /* left of cell */ { r = spl(u[0],u[2]); x3[0] = xyz[0][0]; x3[1] = (1-r)*xyz[0][1]+r*xyz[2][1]; if (i==0) xyztext(lb,x3,-1,0,theta,phi,dev,CCLA); } s = 8*(u[3]>0)+4*(u[2]>0)+2*(u[1]>0)+(u[0]>0); switch(s) { case 0: case 15: break; case 1: case 14: line3d(x0,x3,theta,phi,dev,CCON); break; case 2: case 13: line3d(x0,x1,theta,phi,dev,CCON); break; case 3: case 12: line3d(x3,x1,theta,phi,dev,CCON); break; case 4: case 11: line3d(x3,x2,theta,phi,dev,CCON); break; case 5: case 10: line3d(x0,x2,theta,phi,dev,CCON); break; case 6: case 9: line3d(x0,x1,theta,phi,dev,CCON); break; case 7: case 8: line3d(x1,x2,theta,phi,dev,CCON); break; default: ERROR(("severe contouring error...")); } } } } double angle(x0,x1,x2) /* rotation angle from (x0,x1) to (x0,x2) */ double *x0, *x1, *x2; /* If x0=0, ||x1=1|| then express x2 = u x1 + v y1 where y1=(-x11,x10) = 90 deg anticlk rot. i.e. u = <x1,x2> v = <y1,x2> tan(theta) = v/u atan2(v,u) returns positive for anticlkws rot; negative for clockwise rot. */ { double u, v; u = (x1[0]-x0[0])*(x2[0]-x0[0]) + (x1[1]-x0[1])*(x2[1]-x0[1]); v = -(x1[1]-x0[1])*(x2[0]-x0[0]) + (x1[0]-x0[0])*(x2[1]-x0[1]); return(atan2(v,u)); } void persp3d(xyz,theta,phi,DP,sl,nsl) plxyz *xyz; double theta, phi, *sl; void (*DP)(); INT nsl; { INT i, j, k, m, nx, ny, ii, jj, cb, cp, cx[4], cy[4], xhi, yhi; double u[4][3], w[4][2], r; if (xyz->t==0) ERROR(("persp3d: not a grid")); if (lf_error) return; /* theta=135 --- 225 | | 45 --- 315; i.e start at top right for theta=45 e.t.c. Reverse if sin(phi)<0. x starts hi if cos(theta)>0 y starts hi if sin(theta)>0 */ xhi = (cos(theta)*sin(phi)) > 0; yhi = (sin(theta)*sin(phi)) > 0; nx = xyz->nx; ny = xyz->ny; for (i=0; i<nx-1; i++) for (j=0; j<ny-1; j++) { for (k=0; k<4; k++) { /* 1 -- 2 | | 0 -- 3 */ ii = (xhi) ? nx-2-i : i; jj = (yhi) ? ny-2-j : j; ii += (k>1); jj += (k==1)+(k==2); m = jj*nx+ii; getxyzitem(xyz,u[k],m); project(u[k],w[k],theta,phi); cx[k] = XCON(w[k][0]); cy[k] = YCON(w[k][1]); } switch(xyz->type) { case 'w': /* wireframe: from top, use color CPA1 for border, CPA2 for patch angles are anti-clock from top; r approx 2pi clock from bot; r approx -2pi */ r = angle(w[0],w[3],w[1])+angle(w[1],w[0],w[2]) +angle(w[2],w[1],w[3])+angle(w[3],w[2],w[0]); if (r>0) { cb = lfcm[CPA1]; cp = lfcm[CPA2]; } else { cp = lfcm[CPA1]; cb = lfcm[CPA2]; } DP(cx,cy,cp,cb); break; case 'i': /* image */ if (nsl==0) nsl = pretty(zl,10,sl); r = u[0][2] + u[1][2] + u[2][2] + u[3][2]; cb = cp = getgreylevel(r/4); DP(cx,cy,cp,cb); break; } } } void updatelim(v,xl) vari *v; double *xl; { INT i; if ((v==NULL) || (vlength(v)==0)) return; if (xl[0]==xl[1]) xl[0] = xl[1] = vitem(v,0); for (i=0; i<vlength(v); i++) { if (vitem(v,i)<xl[0]) xl[0] = vitem(v,i); if (vitem(v,i)>xl[1]) xl[1] = vitem(v,i); } } void axis(z1,z2,zl,lab,theta,phi,a,s,dev) double *z1, *z2, *zl, theta, phi; char *lab; INT a, s; device *dev; { double x1[3], x2[3], z[50]; INT i, u0, u1, v0, v1, n, horiz; char lb[20]; dev->SetColor(lfcm[CAXI]); project(z1,x1,theta,phi); project(z2,x2,theta,phi); u0 = XCON(x1[0]); v0 = XCON(x2[0]); u1 = YCON(x1[1]); v1 = YCON(x2[1]); horiz = abs(v0-u0)>abs(v1-u1); dev->DrawLine(u0,u1,v0,v1); n = (INT)sqrt((double)((v0-u0)*(v0-u0)+(v1-u1)*(v1-u1)))/((horiz) ? 5*cw : 2*ch); if (n>50) n = 50; n = pretty(zl,n,z); if (n==0) return; x1[0] = z1[0]; x1[1] = z1[1]; x1[2] = z1[2]; if (abs(v0-u0)>abs(v1-u1)) /* horizontal axis */ { dev->SetColor(lfcm[CTEX]); if (lab!=NULL) dev->DoText(0,(u0+v0)/2,(u1+v1)/2+s*(dev->ticklength+ch),lab,0,s); for (i=0; i<n; i++) { x1[a] = z[i]; project(x1,x2,theta,phi); u0 = XCON(x2[0]); u1 = YCON(x2[1]); v0 = u0; v1 = u1+s*dev->ticklength; sprintf(lb,"%g",z[i]); dev->SetColor(lfcm[CAXI]); dev->DrawLine(u0,u1,v0,v1); dev->SetColor(lfcm[CTEX]); dev->DoText(0,v0,v1,lb,0,s); } } else /* vertical axis */ { s = 2*((2*v0)>(i0+i1))-1; dev->SetColor(lfcm[CTEX]); if (lab!=NULL) dev->DoText(0,v0,v1-ch,lab,-s,-1); for (i=0; i<n; i++) { x1[a] = z[i]; project(x1,x2,theta,phi); u0 = XCON(x2[0]); u1 = YCON(x2[1]); v0 = u0+s*dev->ticklength; v1 = u1; sprintf(lb,"%g",z[i]); dev->SetColor(lfcm[CAXI]); dev->DrawLine(u0,u1,v0,v1); dev->SetColor(lfcm[CTEX]); dev->DoText(0,v0,v1,lb,-s,0); } } } void plotxwin(pl,dev,wn,w,h,rd) plots *pl; device *dev; INT wn, w, h, rd; { INT i, j, k, s; double z[3], z2[3], xx[2], vx, vy, vz; static double theta, phi; plxyz *xyz; if (pl->ty==PLNONE) return; if (h<=0) h = dev->defth; if (w<=0) w = dev->deftw; if (!dev->makewin(&w,&h,wn,rd)) return; dev->TextDim(0,"0",&cw,&ch); i0 = 4*cw+dev->ticklength; i1 = w-2*cw; k0 = h-3*ch-dev->ticklength; k1 = 3*ch; dev->ClearScreen(lfcm[CBAK]); if (pl->xl[0]<pl->xl[1]) { xl[0] = pl->xl[0]; xl[1] = pl->xl[1]; } else { xl[0] = xl[1] = 0.0; for (i=0; i<pl->xyzs->n; i++) { xyz = (plxyz *)viptr(pl->xyzs,i); updatelim(xyz->x,xl); } if (xl[0]==xl[1]) { xl[0] -= 0.5; xl[1] += 0.5; } } if (pl->yl[0]<pl->yl[1]) { yl[0] = pl->yl[0]; yl[1] = pl->yl[1]; } else { yl[0] = yl[1] = 0.0; for (i=0; i<pl->xyzs->n; i++) { xyz = (plxyz *)viptr(pl->xyzs,i); updatelim(xyz->y,yl); } if (yl[0]==yl[1]) { yl[0] -= 0.5; yl[1] += 0.5; } } if (pl->zl[0]<pl->zl[1]) { zl[0] = pl->zl[0]; zl[1] = pl->zl[1]; } else { zl[0] = zl[1] = 0.0; for (i=0; i<pl->xyzs->n; i++) { xyz = (plxyz *)viptr(pl->xyzs,i); updatelim(xyz->z,zl); } if (zl[0]==zl[1]) { zl[0] -= 0.5; zl[1] += 0.5; } } theta = pl->theta*PI/180; phi = pl->phi*PI/180; vx = -sin(theta)*sin(phi); vy = -cos(theta)*sin(phi); vz = cos(phi); for (i=0; i<2; i++) for (j=0; j<2; j++) for (k=0; k<2; k++) { z[0] = xl[i]; z[1] = yl[j]; z[2] = zl[k]; project(z,xx,theta,phi); if ((i+j+k==0) | (xx[0]<px[0])) px[0]=xx[0]; if ((i+j+k==0) | (xx[0]>px[1])) px[1]=xx[0]; if ((i+j+k==0) | (xx[1]<py[0])) py[0]=xx[1]; if ((i+j+k==0) | (xx[1]>py[1])) py[1]=xx[1]; } s = 1-2*((cos(phi)<0)^(sin(phi)<0)); z[0] = xl[0]; z2[0] = xl[1]; z[1] = z2[1] = yl[(cos(theta)<0)^(sin(phi)<0)]; z[2] = z2[2] = zl[cos(phi)<0]; axis(z,z2,xl,pl->xlab,theta,phi,0,s,dev); z[0] = z2[0] = xl[(sin(theta)<0)^(sin(phi)<0)]; z[1] = yl[0]; z2[1] = yl[1]; z[2] = z2[2] = zl[cos(phi)<0]; axis(z,z2,yl,pl->ylab,theta,phi,1,s,dev); z[0] = z2[0] = xl[cos(theta)<0]; z[1] = z2[1] = yl[sin(theta)>0]; z[2] = zl[0]; z2[2] = zl[1]; axis(z,z2,zl,pl->zlab,theta,phi,2,s,dev); if (strlen(pl->main)>0) dev->DoText(1,(i0+i1)/2,2*ch,pl->main,0,-1); for (i=0; i<pl->xyzs->n; i++) { xyz = viptr(pl->xyzs,i); isgrid(xyz); switch (xyz->type) { case 'c': contour3d(xyz,theta,phi,dev,pl->sl,pl->nsl); break; case 'i': persp3d(xyz,theta,phi,dev->DrawPatch,pl->sl,pl->nsl); break; case 'b': points3d(xyz,theta,phi,dev,'p'); case 'l': lines3d(xyz,theta,phi,dev); break; case 'p': points3d(xyz,theta,phi,dev,'p'); break; case 'q': points3d(xyz,theta,phi,dev,'q'); break; case 's': if (i==0) { ERROR(("invalid segements")); } else segments(viptr(pl->xyzs,i-1),xyz,theta,phi,dev); break; case 'w': persp3d(xyz,theta,phi,dev->DrawPatch,pl->sl,pl->nsl); break; } } dev->wrapup(rd); } #ifdef YAWN void plotmaple(pl) plots *pl; { INT i, j; plf = fopen("lfplot","w"); switch(pl->d) { case 1: fprintf(plf,"PLOT(\n"); for (j=0; j<pl->r; j++) { fprintf(plf,"CURVES([\n"); for (i=0; i<pl->mx[j]; i++) { if (i>0) fprintf(plf,",\n"); fprintf(plf,"[%f,%f]",pl->x[j][i],pl->y[j][i]); } fprintf(plf,"],\nCOLOUR(RGB,0,0,0)),\n"); } if (pl->type[0]=='p') fprintf(plf,"STYLE(POINT),"); if (pl->main!=NULL) fprintf(plf,"TITLE(%s),",pl->main); fprintf(plf,"AXESLABELS(%s,%s)",pl->xlab,pl->ylab); fprintf(plf,");\n"); break; case 2: fprintf(plf,"PLOT3D(GRID(%f..%f,%f..%f,[[\n",pl->x[0][0],pl->x[0][pl->mx[0]-1],pl->y[0][0],pl->y[0][pl->my[0]-1]); for (i=0; i<pl->mx[0]; i++) { if (i>0) fprintf(plf,"],\n["); for (j=0; j<pl->my[0]; j++) { if (j>0) fprintf(plf,",\n"); fprintf(plf,"%f",pl->z[0][i*pl->my[0]+j]); } } fprintf(plf,"]]),\nAXESLABELS(%s,%s,%s),AXESSTYLE(FRAME)",pl->xlab,pl->ylab,pl->zlab); if (pl->type[0]=='c') fprintf(plf,",STYLE(CONTOUR),CONTOURS(DEFAULT),ORIENTATION(-90,0.1),COLOUR(ZSHADING)"); if (pl->main!=NULL) fprintf(plf,",\nTITLE(%s)\n",pl->main); fprintf(plf,");\n"); break; } fclose(plf); printf("Created lfplot file; Maple format.\n"); } void plotmathe(pl,fmt) plots *pl; char *fmt; { INT i, j, aut; static FILE *plm=NULL; aut = f2(fmt)!='m'; #ifdef NOPIPES aut = 0; #endif if (aut) { if (plm==NULL) plm = (FILE *)popen("math >/dev/null","w"); plf = plm; } else plf = fopen("lfplot","w"); switch(pl->d) { case 1: fprintf(plf,"ListPlot[{{\n"); for (i=0; i<pl->mx[0]; i++) { if (i>0) fprintf(plf,"},\n{"); fprintf(plf,"%f,%f",pl->x[0][i],pl->y[0][i]); } fprintf(plf,"}}"); fprintf(plf,",AxesLabel->{%s,%s}",pl->xlab,pl->ylab); if (pl->type[0]=='l') fprintf(plf,",PlotJoined->True"); break; case 2: if (pl->type[0]=='c') fprintf(plf,"ListContourPlot[{{"); else fprintf(plf,"ListPlot3D[{{"); for (j=0; j<pl->my[0]; j++) { if (j>0) fprintf(plf,"},\n{"); for (i=0; i<pl->mx[0]; i++) { if (i>0) fprintf(plf,",\n"); fprintf(plf,"%f",pl->z[0][i*pl->my[0]+j]); } } fprintf(plf,"}},\nMeshRange->{{"); fprintf(plf,"%f,%f},{%f,%f}}\n",pl->x[0][0],pl->x[0][pl->mx[0]-1],pl->y[0][0],pl->y[0][pl->my[0]-1]); if (pl->type[0]=='c') fprintf(plf,",FrameLabel->{%s,%s}",pl->xlab,pl->ylab); else fprintf(plf,",AxesLabel->{%s,%s,%s}",pl->xlab,pl->ylab,pl->zlab); break; } if (pl->main!=NULL) fprintf(plf,",PlotLabel->%s\n",pl->main); fprintf(plf,"];\n"); if (aut) fflush(plf); else { fclose(plf); printf("Created lfplot file; Mathematica format.\n"); } } void plotmatlb(pl) /* Matlab */ plots *pl; { INT i, j; plf = fopen("lfplot.m","w"); switch(pl->d) { case 1: fprintf(plf,"plot(["); for (i=0; i<pl->mx[0]; i++) { if (i>0) putc(',',plf); fprintf(plf,"%f",pl->x[0][i]); } fprintf(plf,"],["); for (i=0; i<pl->mx[0]; i++) { if (i>0) putc(',',plf); fprintf(plf,"%f",pl->y[0][i]); } fprintf(plf,"])\n"); break; case 2: if (pl->type[0]=='c') fprintf(plf,"contour(["); else fprintf(plf,"mesh(["); for (i=0; i<pl->my[0]; i++) fprintf(plf,"%f ",pl->y[0][i]); fprintf(plf,"],["); for (i=0; i<pl->mx[0]; i++) fprintf(plf,"%f ",pl->x[0][i]); fprintf(plf,"],[\n"); for (j=0; j<pl->my[0]; j++) { fprintf(plf,"["); for (i=0; i<pl->mx[0]; i++) fprintf(plf,"%f ",pl->z[0][i*pl->my[0]+j]); fprintf(plf,"]\n"); } fprintf(plf,"])\n"); fprintf(plf,"xlabel('%s')\n",pl->xlab); fprintf(plf,"ylabel('%s')\n",pl->ylab); break; default: ERROR(("plotmatlb: invalid dimension %d",pl->d)); } if (pl->main!=NULL) fprintf(plf,"title('%s')\n",pl->main); fclose(plf); printf("Created lfplot.m file; matlab format.\n"); } void plotgnup(pl,fmt) plots *pl; char *fmt; { INT i, j, z, aut; char m; static FILE *plc=NULL; /* first, the data file */ plf=fopen("lfplot.dat","w"); switch(pl->d) { case 1: z = pl->mx[0]; for (j=0; j<pl->r; j++) if (pl->mx[j]>z) z = pl->mx[j]; for (i=0; i<z; i++) { for (j=0; j<pl->r; j++) if (i<pl->mx[j]) fprintf(plf,"%f %f ",pl->x[j][i],pl->y[j][i]); else fprintf(plf,"%f %f ",pl->x[j][pl->mx[j]-1],pl->y[j][pl->mx[j]-1]); fprintf(plf,"\n"); } break; case 2: for (j=0; j<pl->my[0]; j++) { for (i=0; i<pl->mx[0]; i++) fprintf(plf,"%f %f %f\n",pl->x[0][i],pl->y[0][j],pl->z[0][i*pl->my[0]+j]); fprintf(plf,"\n"); } } fclose(plf); /* second, the command file */ m = f2(fmt); aut = (m!='m'); #ifdef NOPIPES aut = 0; #endif if (aut) { if ((m=='s') && (plc!=NULL)) pclose(plc); if ((m=='s') || (plc==NULL)) plc = (FILE *)popen("gnuplot","w"); plf = plc; } else plf = fopen("lfplot","w"); switch(pl->d) { case 1: fprintf(plf,"set nokey\n"); fprintf(plf,"set xlab \"%s\"\n",pl->xlab); fprintf(plf,"set ylab \"%s\"\n",pl->ylab); if (pl->main != NULL) fprintf(plf,"set title \"%s\"\n",pl->main); fprintf(plf,"plot "); for (i=0; i<pl->r; i++) { if (i>0) fprintf(plf,", "); fprintf(plf,"\"lfplot.dat\" using %d:%d ",2*i+1,2*i+2); switch(pl->type[i]) { case 'l': fprintf(plf,"with lines"); break; case 'p': fprintf(plf,"with points"); break; case 'b': fprintf(plf,"with linespoints"); break; } } fprintf(plf,"\n"); break; case 2: fprintf(plf,"set xlab \"%s\"\n",pl->xlab); fprintf(plf,"set ylab \"%s\"\n",pl->ylab); fprintf(plf,"set zlab \"%s\"\n",pl->zlab); if (pl->type[0]=='c') { fprintf(plf,"set contour\n"); fprintf(plf,"set nosurface\n"); fprintf(plf,"set key\n"); } else { fprintf(plf,"set nocontour\n"); fprintf(plf,"set surface\n"); fprintf(plf,"set nokey\n"); } fprintf(plf,"set view %g,%g\n",pl->phi,pl->theta); fprintf(plf,"set parametric\n"); if (pl->main != NULL) fprintf(plf,"set title \"%s\"\n",pl->main); fprintf(plf,"splot \"lfplot.dat\" with lines\n"); break; } if (aut) fflush(plf); else { fclose(plf); printf("Created lfplot, lfplot.dat files; gnuplot format.\n"); } } #endif #endif
26.668374
120
0.473449
[ "mesh" ]
04ecbb2f9746fedfd21971be00621f2b151f8df3
4,890
c
C
src/firmware/main/primitives/spin.c
matthewberends/Software
4681c7cffc9c1ca8f739ea692daffc490a8c1910
[ "MIT" ]
null
null
null
src/firmware/main/primitives/spin.c
matthewberends/Software
4681c7cffc9c1ca8f739ea692daffc490a8c1910
[ "MIT" ]
null
null
null
src/firmware/main/primitives/spin.c
matthewberends/Software
4681c7cffc9c1ca8f739ea692daffc490a8c1910
[ "MIT" ]
null
null
null
#include "spin.h" #include "bangbang.h" #include "control.h" #include "physics.h" #include <math.h> #include <stdio.h> #ifndef FWSIM #include "dr.h" #else #include "simulate.h" #endif #define TIME_HORIZON 0.5f static float x_final; static float y_final; static float avel_final; static float end_speed; static bool slow; static float major_vec[2]; static float minor_vec[2]; static float major_angle; /** * \brief Initializes the spin primitive. * * This function runs once at system startup. */ static void spin_init(void) { } /** * \brief Starts a movement of this type. * * This function runs each time the host computer requests to start a spin * movement. * * \param[in] params the movement parameters, which are only valid until this * function returns and must be copied into this module if needed */ // input to 3->4 matrix is quarter-degrees per 5 ms, matrix is dimensionless // linear ramp up for velocity and linear fall as robot approaches point // constant angular velocity static void spin_start(const primitive_params_t *p) { // Parameters: param[0]: g_destination_x [mm] // param[1]: g_destination_y [mm] // param[2]: g_angular_v_final [centi-rad/s] // param[3]: g_end_speed [millimeter/s] // Parse the parameters with the standard units x_final = (float)p->params[0] / 1000.0f; y_final = (float)p->params[1] / 1000.0f; avel_final = (float)p->params[2] / 100.0f; end_speed = (float)p->params[3] / 1000.0f; slow = p->slow; // Get robot current data dr_data_t now; dr_get(&now); // Construct major and minor axis for the path // get maginutude float distance = norm2(x_final-now.x, y_final-now.y); // major vector - unit vector from start to destination major_vec[0] = (x_final-now.x)/distance; major_vec[1] = (y_final-now.y)/distance; // minor vector - orthogonal to major vector minor_vec[0] = -major_vec[1]; minor_vec[1] = major_vec[0]; // major angle - angle relative to global x major_angle = atan2f(major_vec[1], major_vec[0]); } /** * \brief Ends a movement of this type. * * This function runs when the host computer requests a new movement while a * spin movement is already in progress. */ static void spin_end(void) { } /** * \brief Ticks a movement of this type. * * This function runs at the system tick rate while this primitive is active. * * \param[out] log the log record to fill with information about the tick, or * \c NULL if no record is to be filled */ static void spin_tick(log_record_t *log) { dr_data_t now; dr_get(&now); // Trajectories BBProfile major; BBProfile minor; // current to destination vector float x_disp = x_final-now.x; float y_disp = y_final-now.y; // project current to destination vector to major/minor axis float major_disp = x_disp*major_vec[0] + y_disp*major_vec[1]; float minor_disp = x_disp*minor_vec[0] + y_disp*minor_vec[1]; // project velocity vector to major/minor axis float major_vel = now.vx*major_vec[0] + now.vy*major_vec[1]; float minor_vel = now.vx*minor_vec[0] + now.vy*minor_vec[1]; // Prepare trajectory PrepareBBTrajectoryMaxV(&major, major_disp, major_vel, end_speed, MAX_X_A, MAX_X_V); PrepareBBTrajectoryMaxV(&minor, minor_disp, minor_vel, 0, MAX_Y_A, MAX_Y_V); // Plan PlanBBTrajectory(&major); PlanBBTrajectory(&minor); // Compute acceleration float major_accel = BBComputeAccel(&major, TIME_HORIZON); float minor_accel = BBComputeAccel(&minor, TIME_HORIZON); float a_accel = (avel_final-now.avel) / 0.05f; // Clamp acceleration if (a_accel > MAX_T_A) { a_accel = MAX_T_A; } if (a_accel < -MAX_T_A) { a_accel = -MAX_T_A; } // Local cartesian represented as global cartesian float local_x_vec[2] = { cosf(now.angle), sinf(now.angle) }; float local_y_vec[2] = { -sinf(now.angle), cosf(now.angle) }; // Get local x acceleration float major_dot_x = dot_product(local_x_vec, major_vec, 2); float minor_dot_x = dot_product(local_x_vec, minor_vec, 2); float x_accel = major_accel*major_dot_x + minor_accel*minor_dot_x; // Get local y acceleration float major_dot_y = dot_product(local_y_vec, major_vec, 2); float minor_dot_y = dot_product(local_y_vec, minor_vec, 2); float y_accel = major_accel*major_dot_y + minor_accel*minor_dot_y; // Apply acceleration in robot's coordinates float linear_acc[2] = { x_accel, y_accel, }; apply_accel(linear_acc, a_accel); } /** * \brief The spin movement primitive. */ const primitive_t SPIN_PRIMITIVE = { .direct = false, .init = &spin_init, .start = &spin_start, .end = &spin_end, .tick = &spin_tick, };
27.784091
88
0.671779
[ "vector" ]
04f47031ec2940d4cd6e53e344be4e9742312431
6,703
h
C
OpenSim 3.2-64bit-VS12/sdk/include/SimTK/include/SimTKcommon/internal/ReferencePtr.h
chrisdembia/opensim-metabolicsprobes
7be20df24c2a3f1f3fb4a56e244ba4a3295b4fc0
[ "Apache-2.0" ]
2
2020-01-15T05:03:30.000Z
2021-01-16T06:18:47.000Z
OpenSim 3.2-64bit-VS12/sdk/include/SimTK/include/SimTKcommon/internal/ReferencePtr.h
chrisdembia/opensim-metabolicsprobes
7be20df24c2a3f1f3fb4a56e244ba4a3295b4fc0
[ "Apache-2.0" ]
1
2021-01-11T13:45:54.000Z
2021-01-11T13:45:54.000Z
OpenSim 3.2-64bit-VS12/sdk/include/SimTK/include/SimTKcommon/internal/ReferencePtr.h
chrisdembia/opensim-metabolicsprobes
7be20df24c2a3f1f3fb4a56e244ba4a3295b4fc0
[ "Apache-2.0" ]
3
2019-05-17T02:17:10.000Z
2020-11-05T20:31:55.000Z
#ifndef SimTK_SimTKCOMMON_REFERENCE_PTR_H_ #define SimTK_SimTKCOMMON_REFERENCE_PTR_H_ /* -------------------------------------------------------------------------- * * Simbody(tm): SimTKcommon * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2012 Stanford University and the Authors. * * Authors: Michael Sherman * * Contributors: * * * * 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. * * -------------------------------------------------------------------------- */ namespace SimTK { /** This is a smart pointer that implements "cross reference" semantics where a pointer data member of some object is intended to refer to some target object in a larger data structure. Judicious use of this container will allow you to use compiler-generated copy constructors and copy assignment operators for classes which would otherwise have to implement their own in order to properly initialize these pointer data members, which must not be copied. The contained pointer is initialized to null (0) on construction, and it is reinitialized to null upon copy construction or copy assignment. That's because we are assuming this is part of copying the entire data structure and copying the old pointer would create a reference into the old data structure rather than the new copy. This pointer does not own the target to which it points, and there is no reference counting so it will become stale if the target is deleted. Whether you can write through the pointer is controlled by whether type T is a const type. For example %ReferencePtr\<int> is equivalent to an int*, while %ReferencePtr\<const int> is equivalent to a const int*. This class is entirely inline and has no computational or space overhead; it contains just a single pointer. @see ClonePtr **/ template <class T> class ReferencePtr { public: typedef T element_type; typedef T* pointer; typedef T& reference; /** Default constructor creates an empty object. **/ ReferencePtr() : p(0) { } /** Construct from a given pointer stores the pointer. **/ explicit ReferencePtr(T* tp) : p(tp) { } /** Construct from a reference stores the address of the supplied object. **/ explicit ReferencePtr(T& t) : p(&t) { } /** Copy constructor unconditionally sets the pointer to null; see class comments for why. **/ ReferencePtr(const ReferencePtr&) : p(0) { } /** Copy assignment sets the pointer to null (except for a self-assign); see class comments for why. **/ ReferencePtr& operator=(const ReferencePtr& r) { if (&r != this) clear(); return *this; } /** This form of assignment replaces the currently-referenced object by a reference to the source object; no destruction occurs. **/ ReferencePtr& operator=(T& t) { reset(&t); return *this; } /** This form of assignment replaces the current pointer with the given one; no destruction occurs. **/ ReferencePtr& operator=(T* tp) { reset(tp); return *this; } /** Destructor does nothing. **/ ~ReferencePtr() {clear();} // just being tidy /** Return the contained pointer. This will fail if the container is empty. **/ T* operator->() const { return &getRef(); } /** The "dereference" operator returns a reference to the target object. This will fail if the container is empty. **/ T& operator*() const { return getRef(); } /** This is an implicit conversion from %ReferencePtr\<T> to T*. **/ operator T*() const { return p; } /** This is an implicit conversion to type bool that returns true if the container is non-null (that is, not empty). **/ operator bool() const { return !empty(); } /** Return the contained pointer, or null if the container is empty. **/ T* get() const { return p; } /** Return a reference to the target object. Fails if the pointer is null. **/ T& getRef() const { SimTK_ERRCHK(p!=0, "ReferencePtr::getRef()", "An attempt was made to dereference a null pointer."); return *p; } /** Return true if this container is empty. **/ bool empty() const { return p==0; } /** Make this container empty; no destruction occurs. **/ void clear() { p=0; } /** Extract the pointer from this container, leaving the container empty. The pointer is returned. **/ T* release() { T* x=p; p=0; return x; } /** Replace the stored pointer with a different one; no destruction occurs. **/ void reset(T* tp) { p=tp;} /** Swap the contents of this %ReferencePtr with another one. **/ void swap(ReferencePtr& other) { T* otherp = other.release(); other.reset(p); reset(otherp); } private: // Warning: ReferencePtr must be exactly the same size as type T*. That way // one can reinterpret_cast a T* to a ReferencePtr<T> when needed. T* p; }; } // namespace SimTK namespace std { /** This is a specialization of the STL std::swap() algorithm which uses the cheap built-in swap() member of the ReferencePtr class. @relates SimTK::ReferencePtr **/ template <class T> inline void swap(SimTK::ReferencePtr<T>& p1, SimTK::ReferencePtr<T>& p2) { p1.swap(p2); } } // namespace std #endif // SimTK_SimTKCOMMON_REFERENCE_PTR_H_
45.290541
80
0.609279
[ "object" ]
04f88a3e64da7a87240d0f26addff9c4b268b230
4,863
h
C
arangod/Indexes/SortedIndexAttributeMatcher.h
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
1
2019-11-25T07:14:41.000Z
2019-11-25T07:14:41.000Z
arangod/Indexes/SortedIndexAttributeMatcher.h
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
109
2022-01-06T07:05:24.000Z
2022-03-21T01:39:35.000Z
arangod/Indexes/SortedIndexAttributeMatcher.h
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2018 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #ifndef ARANGOD_INDEXES_SORTED_INDEX_ATTRIBUTE_MATCHER_H #define ARANGOD_INDEXES_SORTED_INDEX_ATTRIBUTE_MATCHER_H 1 #include "Basics/Common.h" #include "Containers/HashSet.h" #include "Indexes/Index.h" namespace arangodb { namespace aql { class Ast; struct AstNode; class SortCondition; struct Variable; } // namespace aql class Index; namespace SortedIndexAttributeMatcher { Index::FilterCosts supportsFilterCondition(std::vector<std::shared_ptr<arangodb::Index>> const& allIndexes, arangodb::Index const* index, arangodb::aql::AstNode const* node, arangodb::aql::Variable const* reference, size_t itemsInIndex); Index::SortCosts supportsSortCondition(arangodb::Index const* index, arangodb::aql::SortCondition const* sortCondition, arangodb::aql::Variable const* reference, size_t itemsInIndex); /// @brief specializes the condition for use with the index arangodb::aql::AstNode* specializeCondition(arangodb::Index const* index, arangodb::aql::AstNode* node, arangodb::aql::Variable const* reference); /// @brief matches which index attributes of index are supported by the filter /// condition represented by the passed-in AST node. /// For example, if the query is /// /// FOR doc IN <collection-with-index> /// FILTER doc.value1 == 2 && doc.value2 == 3 /// /// then "reference" will point to the variable "doc" (this is the variable we are /// looking for inside the filter condition(s). The filter condition will be an n-ary /// AND consisting of the two sub-conditions "doc.value1 == 2" && "doc.value2 == 3". /// the function will walk through all subconditions and will put the index attribute /// that is used by the subcondition into the outvariable "found". /// if a subcondition is not covered by the index, it will increase the counter /// "postFilterConditions", so the caller can see how many subconditions need to be /// handled afterwards even when using the index. this is useful when comparing different /// indexes, and to estimate the amount of post-filtering work left when picking a /// particular index. /// "values" is a counter variable and is increased by one for every equality condition, /// and increased by the number of IN values for IN lookups. the counter is used to /// estimate the number of items coming out of the index later. /// while walking over the subconditions, the function will also populate "nonNullAttributes" /// if it can prove a specific attribute for the search variable (e.g. "doc") cannot become /// null. this can be useful later when looking at sparse indexes. void matchAttributes(arangodb::Index const* index, arangodb::aql::AstNode const* node, arangodb::aql::Variable const* reference, std::unordered_map<size_t, std::vector<arangodb::aql::AstNode const*>>& found, size_t& postFilterConditions, size_t& values, std::unordered_set<std::string>& nonNullAttributes, bool isExecution); /// @brief whether or not the access fits bool accessFitsIndex( arangodb::Index const* idx, arangodb::aql::AstNode const* access, arangodb::aql::AstNode const* other, arangodb::aql::AstNode const* op, arangodb::aql::Variable const* reference, std::unordered_map<size_t, std::vector<arangodb::aql::AstNode const*>>& found, std::unordered_set<std::string>& nonNullAttributes, bool isExecution); bool isDuplicateOperator(arangodb::aql::AstNode const* node, ::arangodb::containers::HashSet<int> const& operatorsFound); }; // namespace SortedIndexAttributeMatcher } // namespace arangodb #endif
47.676471
107
0.6533
[ "vector" ]
04fbafcc62cbdb7aec01220d438a72c0fcb299bc
707
h
C
VkEngine/Include/Rendering/Vertex.h
JanVijfhuizen/VkRenderer
5f5848f637dcf587b55ff8bd52bdb56fcf9caab4
[ "MIT" ]
null
null
null
VkEngine/Include/Rendering/Vertex.h
JanVijfhuizen/VkRenderer
5f5848f637dcf587b55ff8bd52bdb56fcf9caab4
[ "MIT" ]
null
null
null
VkEngine/Include/Rendering/Vertex.h
JanVijfhuizen/VkRenderer
5f5848f637dcf587b55ff8bd52bdb56fcf9caab4
[ "MIT" ]
null
null
null
#pragma once // Standard (optional) struct that can be used to define renderable triangles in shaders. struct Vertex final { // Using uint16_t for this, because the models for this game won't be that large. typedef uint16_t Index; glm::vec3 position{0}; // The forward vector for this vertex. glm::vec3 normal{0, 1, 0}; // Sample coordinates for texture attachments. glm::vec2 textureCoordinates{0}; // Returns a vulkan description for the vertex binding. [[nodiscard]] static VkVertexInputBindingDescription GetBindingDescription(); // Returns a vulkan description for the vertex attributes. [[nodiscard]] static vi::Vector<VkVertexInputAttributeDescription> GetAttributeDescriptions(); };
35.35
95
0.768034
[ "vector" ]
04ff1653276c2cbfb418e9db861818e65888cbfa
2,513
h
C
Event.h
bhallstein/OGLW
051871b54c89b6a7008c136867d776620bb23e8a
[ "MIT" ]
null
null
null
Event.h
bhallstein/OGLW
051871b54c89b6a7008c136867d776620bb23e8a
[ "MIT" ]
null
null
null
Event.h
bhallstein/OGLW
051871b54c89b6a7008c136867d776620bb23e8a
[ "MIT" ]
null
null
null
#ifndef WEvent_h #define WEvent_h #include <vector> namespace W { class Window; namespace EventType { typedef unsigned int T; enum { // Key KeyDown, KeyUp, // Positional LMouseUp, LMouseDown, RMouseUp, RMouseDown, MouseMove, // Mouse TouchDown, TouchMoved, TouchUp, TouchCancelled, // Touch // Scroll wheel ScrollWheel, // Windowing WinClosed, WinResized, WinMinimized, WinDeminimized, WinBecameKey, WinStoppedBeingKey, // Application activeness AppBecameForeground, AppBecameBackground, // Other Unknown, Count }; } namespace KeyCode { typedef int T; enum { _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U, _V, _W, _X, _Y, _Z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, SPACE, LEFT_ARROW, RIGHT_ARROW, UP_ARROW, DOWN_ARROW, ESC, RETURN, BACKSPACE, _DELETE, TAB, HOME, END, UNKNOWN }; } class Event { public: // Information for different event types is saved in a struct type. // To limit object size, the structs are stored in a union - use whichever // member of the union is appropriate. // (This is based on SFML's event class.) Event(EventType::T); struct MouseEvent { int x, y; Window *window; }; struct KeyEvent { KeyCode::T keyCode; }; struct ScrollEvent { float dx, dy; Window *window; }; struct WindowEvent { Window *window; }; struct TouchEvent { int x, y; int touchID; }; struct UIEvent { std::string *element; }; EventType::T type; union { KeyEvent keyEvent; MouseEvent mouseEvent; ScrollEvent scrollEvent; TouchEvent touchEvent; WindowEvent winEvent; UIEvent uiEvent; }; bool is_positional() const; // Turn event harvesting on/off by setting this property. static bool on; // When event harvesting is on, events are stored in newEvents. // Iterate over them in your update cycle, then clear them. static std::vector<Event> getNewEvents(); static void addNewEvent(const W::Event &); // Register custom event types using registerType(): // .h: extern W::EventType::T MyEventType; // .cpp: W::EventType::T MyEventType = Event::registerType(); static EventType::T registerType(); static KeyCode::T charToKeycode(unsigned int c); private: static std::vector<Event> newEvents; static unsigned int typecounter; }; } #endif
18.343066
76
0.6347
[ "object", "vector" ]
ca10e74faeda85bb9c21ec5ae026dd8b2be066a8
3,177
h
C
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/shp/ESRIShapeParser.h
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
3
2018-08-20T12:12:43.000Z
2021-06-06T09:43:27.000Z
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/shp/ESRIShapeParser.h
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
null
null
null
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/shp/ESRIShapeParser.h
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
1
2022-03-31T03:12:23.000Z
2022-03-31T03:12:23.000Z
#ifndef ESRI_SHAPE_PARSER_H #define ESRI_SHAPE_PARSER_H #include <string> #include <osg/Geode> #include "ESRIShape.h" namespace ESRIShape { class ArrayHelper { public: ArrayHelper(bool useDouble) { if (useDouble) _vec3darray = new osg::Vec3dArray; else _vec3farray = new osg::Vec3Array; } osg::Array* get() { return _vec3farray.valid() ? static_cast<osg::Array*>(_vec3farray.get()) : static_cast<osg::Array*>(_vec3darray.get()); } unsigned int size() { return _vec3farray.valid() ? _vec3farray->size() : _vec3darray->size(); } void add(double x, double y, double z) { if (_vec3farray.valid()) _vec3farray->push_back(osg::Vec3(x,y,z)); else _vec3darray->push_back(osg::Vec3d(x,y,z)); } void add(const osg::Vec3& v) { if (_vec3farray.valid()) _vec3farray->push_back(v); else _vec3darray->push_back(osg::Vec3d(v.x(),v.y(),v.z())); } void add(const osg::Vec3d& v) { if (_vec3farray.valid()) _vec3farray->push_back(osg::Vec3(v.x(),v.y(),v.z())); else _vec3darray->push_back(v); } void add(osg::Array* array, unsigned int index) { osg::Vec3Array* vec3Array = dynamic_cast<osg::Vec3Array*>(array); if (vec3Array && index<vec3Array->size()) add((*vec3Array)[index]); osg::Vec3dArray* vec3dArray = dynamic_cast<osg::Vec3dArray*>(array); if (vec3dArray && index<vec3dArray->size()) add((*vec3dArray)[index]); } osg::ref_ptr<osg::Vec3Array> _vec3farray; osg::ref_ptr<osg::Vec3dArray> _vec3darray; }; class ESRIShapeParser { public: ESRIShapeParser( const std::string fileName, bool useDouble); osg::Geode *getGeode(); #if 0 #if 1 typedef osg::Vec3d ShapeVec3; typedef osg::Vec3dArray ShapeVec3Array; #else typedef osg::Vec3 ShapeVec3; typedef osg::Vec3Array ShapeVec3Array; #endif #endif private: bool _valid; bool _useDouble; osg::ref_ptr<osg::Geode> _geode; void _combinePointToMultipoint(); void _process( const std::vector<ESRIShape::Point> &); void _process( const std::vector<ESRIShape::MultiPoint> &); void _process( const std::vector<ESRIShape::PolyLine> &); void _process( const std::vector<ESRIShape::Polygon> &); void _process( const std::vector<ESRIShape::PointM> &); void _process( const std::vector<ESRIShape::MultiPointM> &); void _process( const std::vector<ESRIShape::PolyLineM> &); void _process( const std::vector<ESRIShape::PolygonM> &); void _process( const std::vector<ESRIShape::PointZ> &); void _process( const std::vector<ESRIShape::MultiPointZ> &); void _process( const std::vector<ESRIShape::PolyLineZ> &); void _process( const std::vector<ESRIShape::PolygonZ> &); void _process( const std::vector<ESRIShape::MultiPatch> &); }; } #endif
29.146789
90
0.590809
[ "vector" ]
ca11580d3f5a24d618b4daa25081ab836c2327a8
5,153
h
C
scenegraph-camera/include/Root.h
nickveys/opengl-play
a297b4ea804255fd54e4b1e78fb7d79d3e185b23
[ "MIT" ]
null
null
null
scenegraph-camera/include/Root.h
nickveys/opengl-play
a297b4ea804255fd54e4b1e78fb7d79d3e185b23
[ "MIT" ]
null
null
null
scenegraph-camera/include/Root.h
nickveys/opengl-play
a297b4ea804255fd54e4b1e78fb7d79d3e185b23
[ "MIT" ]
null
null
null
#ifndef ROOT_H_ #define ROOT_H_ #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <glui.h> #include "Camera.h" /* * Unique implementation of Group. This class is a singleton meant to be the sole root * of the scene graph. In addition to simply being a group, it maintains which object * is the 'current' object. This is the object currently being manipulated by the ui. */ class Root : public Group { public: Root() { axisScale = 1.0; // larger than normal, this is the 'world' current = NULL; openGroup = NULL; min.x = min.y = min.z = -1.0f; max.x = max.y = max.z = 1.0f; } ~Root() { if(openGroup) delete openGroup; } // add the current object (if any) to the open group, if no group // current exists, one will be created void addToGroup() { if(!current) return; if(!openGroup) openGroup = new Group(); Object* o = current; if(list.size() == 1) { setCurrent(NULL); } else { next(); } removeObject(o); openGroup->addObject(o); } // close the open group if there is one void closeGroup() { if(!openGroup) return; addObject(openGroup); openGroup = NULL; } void reopenGroup() { if(openGroup) return; if(!current) return; if(typeid(*current) == typeid(Group)) { openGroup = (Group*) current; next(); removeObject(openGroup); } } void addObject(Object *r) { Group::addObject(r); // set current whenever something is added to the root setCurrent(r); } // select the next object to be active, wrap around if needed void next() { if(list.size() <= 1) return; // no 'next' to select // find current, increment list to next, unless at end for(unsigned int i = 0; i < list.size(); i++) { if(list[i] == current) { if(i == list.size() - 1) setCurrent(list[0]); else setCurrent(list[i+1]); break; } } } // set the given object to be the new current, also de-select the previous // current object, tie up new object to UI controls, and sync void setCurrent(Object* r) { // Unselect the old current if(current) current->setSelected(false); // Remember the new current. If its null, we're done current = r; if(!r) return; // If current is not null, set it selected current->setSelected(true); // Update the interface to match the current object for(int i = 0; i < 3; i++) { obj_rdelta[i] = 0; obj_scale[i] = current->scale[i]; obj_xlate[i] = current->xlate[i]; previousRotation[i] = current->rot[i]; } GLUI_Master.sync_live_all(); // sync ui w/vars } // called when a UI widget manipulating the current object had changed void xformHandler() { if(!current) return; // Getting all the values and storing them in the // current object ensures we get whichever // one changed to generate this callback for(int i=0; i<3; i++) { current->scale[i] = obj_scale[i]; current->xlate[i] = obj_xlate[i]; // This is the ugly business needed to make the glui slider // work as an incremental value instead of an absolute value. current->rot[i] = obj_rdelta[i] * 90 - previousRotation[i]; previousRotation[i] = obj_rdelta[i] * 90; } GLUI_Master.sync_live_all(); // Compose the incremental rotation into the current object's rotation matrix current->composeRotation(); } void reshape(int x, int y) { int tx, ty, tw, th; GLUI_Master.get_viewport_area( &tx, &ty, &tw, &th ); glViewport( tx, ty, tw, th ); xy_aspect = (float)tw / (float)th; glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, xy_aspect, 1.0, 128.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); GLfloat light_position[4] = { 1.0, 1.0, 1.0, 0.0 }; glLightfv(GL_LIGHT0, GL_POSITION, light_position); } void display(Camera& camera) { // Clear the frame glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Set the view based on the matrix in the glui interface glMatrixMode(GL_MODELVIEW); glLoadIdentity(); camera.applyTransform(); draw(); // If there is an open group, draw it if(openGroup) openGroup->draw(); // Swap the buffers glutSwapBuffers(); } virtual void printSceneGraph(int *tab) { cout << "Current Scene Graph" << endl << "Root" << endl; std::vector< Object* >::const_iterator itr = list.begin(); while(itr != list.end()) { (*itr)->printSceneGraph(tab); itr++; } } // Interface connections... static float obj_scale[3]; static float obj_xlate[3]; static float previousRotation[3]; static float obj_rdelta[3]; // points to the current object. Null if there isn't one. Object* current; // points to the current group. Null if there isn't one. Group* openGroup; // aspect ratio of the window. learned in resize, used to set projection. float xy_aspect; }; // Defintion of the root singleton and all of the Root classes static members. Root root; float Root::obj_scale[] = { 1.0, 1.0, 1.0}; float Root::obj_xlate[] = { 0.0, 0.0, 0.0 }; float Root::obj_rdelta[] = { 0.0, 0.0, 0.0 }; float Root::previousRotation[] = { 0.0, 0.0, 0.0 }; #endif /*ROOT_H_*/
25.014563
87
0.651853
[ "object", "vector" ]
ca14c4c1b1e0047114485dd131f41d0d0c17e683
16,281
h
C
src/lib/OpenEXRCore/openexr_attr.h
waebbl/openexr
b624e1cb037651fc7de69adba47c764570382410
[ "BSD-3-Clause" ]
null
null
null
src/lib/OpenEXRCore/openexr_attr.h
waebbl/openexr
b624e1cb037651fc7de69adba47c764570382410
[ "BSD-3-Clause" ]
null
null
null
src/lib/OpenEXRCore/openexr_attr.h
waebbl/openexr
b624e1cb037651fc7de69adba47c764570382410
[ "BSD-3-Clause" ]
null
null
null
/* ** SPDX-License-Identifier: BSD-3-Clause ** Copyright Contributors to the OpenEXR Project. */ #ifndef OPENEXR_ATTR_H #define OPENEXR_ATTR_H #include "openexr_context.h" #include <stddef.h> #include <stdint.h> #ifdef __cplusplus extern "C" { #endif /** * @defgroup AttributeTypes Attribute / metadata value types and struct declarations * * @brief These are a group of enum values defining valid values for * some attributes and then associated structs for other types. * * Some of these types will be directly representable / storable in * the file, some not. There is some overlap here with Imath, and they * should be kept in the same order for compatibility. However do note * that these are just the raw data, and no useful functions are * declared at this layer, that is what Imath is for. * * @{ */ /** enum declaring allowed values for uint8_t value stored in built-in compression type */ typedef enum { EXR_COMPRESSION_NONE = 0, EXR_COMPRESSION_RLE = 1, EXR_COMPRESSION_ZIPS = 2, EXR_COMPRESSION_ZIP = 3, EXR_COMPRESSION_PIZ = 4, EXR_COMPRESSION_PXR24 = 5, EXR_COMPRESSION_B44 = 6, EXR_COMPRESSION_B44A = 7, EXR_COMPRESSION_DWAA = 8, EXR_COMPRESSION_DWAB = 9, EXR_COMPRESSION_LAST_TYPE /**< invalid value, provided for range checking */ } exr_compression_t; /** enum declaring allowed values for uint8_t value stored in built-in env map type */ typedef enum { EXR_ENVMAP_LATLONG = 0, EXR_ENVMAP_CUBE = 1, EXR_ENVMAP_LAST_TYPE /**< invalid value, provided for range checking */ } exr_envmap_t; /** enum declaring allowed values for uint8_t value stored in lineOrder type */ typedef enum { EXR_LINEORDER_INCREASING_Y = 0, EXR_LINEORDER_DECREASING_Y = 1, EXR_LINEORDER_RANDOM_Y = 2, EXR_LINEORDER_LAST_TYPE /**< invalid value, provided for range checking */ } exr_lineorder_t; /** enum declaring allowed values for part type */ typedef enum { EXR_STORAGE_SCANLINE = 0, /**< corresponds to type of 'scanlineimage' */ EXR_STORAGE_TILED, /**< corresponds to type of 'tiledimage' */ EXR_STORAGE_DEEP_SCANLINE, /**< corresponds to type of 'deepscanline' */ EXR_STORAGE_DEEP_TILED, /**< corresponds to type of 'deeptile' */ EXR_STORAGE_LAST_TYPE /**< invalid value, provided for range checking */ } exr_storage_t; /** @brief Enum representing what type of tile information is contained */ typedef enum { EXR_TILE_ONE_LEVEL = 0, /**< single level of image data */ EXR_TILE_MIPMAP_LEVELS = 1, /**< mipmapped image data */ EXR_TILE_RIPMAP_LEVELS = 2, /**< ripmapped image data */ EXR_TILE_LAST_TYPE /**< guard / out of range type */ } exr_tile_level_mode_t; /** @brief Enum representing how to scale positions between levels */ typedef enum { EXR_TILE_ROUND_DOWN = 0, EXR_TILE_ROUND_UP = 1, EXR_TILE_ROUND_LAST_TYPE } exr_tile_round_mode_t; /** @brief Enum capturing the underlying data type on a channel */ typedef enum { EXR_PIXEL_UINT = 0, EXR_PIXEL_HALF = 1, EXR_PIXEL_FLOAT = 2, EXR_PIXEL_LAST_TYPE } exr_pixel_type_t; /* /////////////////////////////////////// */ /* First set of structs are data where we can read directly with no allocation needed... */ /* Most are naturally aligned, but force some of these * structs to be tightly packed */ #pragma pack(push, 1) /** @brief struct to hold an integer box / region definition */ typedef struct { int32_t x_min; int32_t y_min; int32_t x_max; int32_t y_max; } exr_attr_box2i_t; /** @brief struct to hold a floating-point box / region definition */ typedef struct { float x_min; float y_min; float x_max; float y_max; } exr_attr_box2f_t; /** @brief struct to hold color chromaticities to interpret the tristimulus color values in the image data */ typedef struct { float red_x; float red_y; float green_x; float green_y; float blue_x; float blue_y; float white_x; float white_y; } exr_attr_chromaticities_t; /** @brief struct to hold keycode information */ typedef struct { int32_t film_mfc_code; int32_t film_type; int32_t prefix; int32_t count; int32_t perf_offset; int32_t perfs_per_frame; int32_t perfs_per_count; } exr_attr_keycode_t; /** @brief struct to hold a 32-bit floating-point 3x3 matrix */ typedef struct { float m[9]; } exr_attr_m33f_t; /** @brief struct to hold a 64-bit floating-point 3x3 matrix */ typedef struct { double m[9]; } exr_attr_m33d_t; /** @brief struct to hold a 32-bit floating-point 4x4 matrix */ typedef struct { float m[16]; } exr_attr_m44f_t; /** @brief struct to hold a 64-bit floating-point 4x4 matrix */ typedef struct { double m[16]; } exr_attr_m44d_t; /** @brief struct to hold an integer ratio value */ typedef struct { int32_t num; uint32_t denom; } exr_attr_rational_t; /** @brief struct to hold timecode information */ typedef struct { uint32_t time_and_flags; uint32_t user_data; } exr_attr_timecode_t; /** @brief struct to hold a 2-element integer vector */ typedef struct { union { struct { int32_t x, y; }; int32_t arr[2]; }; } exr_attr_v2i_t; /** @brief struct to hold a 2-element 32-bit float vector */ typedef struct { union { struct { float x, y; }; float arr[2]; }; } exr_attr_v2f_t; /** @brief struct to hold a 2-element 64-bit float vector */ typedef struct { union { struct { double x, y; }; double arr[2]; }; } exr_attr_v2d_t; /** @brief struct to hold a 3-element integer vector */ typedef struct { union { struct { int32_t x, y, z; }; int32_t arr[3]; }; } exr_attr_v3i_t; /** @brief struct to hold a 3-element 32-bit float vector */ typedef struct { union { struct { float x, y, z; }; float arr[3]; }; } exr_attr_v3f_t; /** @brief struct to hold a 3-element 64-bit float vector */ typedef struct { union { struct { double x, y, z; }; double arr[3]; }; } exr_attr_v3d_t; /** @brief Struct holding base tiledesc attribute type defined in spec * * NB: this is in a tightly packed area so it can be read directly, be * careful it doesn't become padded to the next uint32_t boundary */ typedef struct { uint32_t x_size; uint32_t y_size; uint8_t level_and_round; } exr_attr_tiledesc_t; /** @brief macro to access type of tiling from packed structure */ #define EXR_GET_TILE_LEVEL_MODE(tiledesc) \ ((exr_tile_level_mode_t) (((tiledesc).level_and_round) & 0xF)) /** @brief macro to access the rounding mode of tiling from packed structure */ #define EXR_GET_TILE_ROUND_MODE(tiledesc) \ ((exr_tile_round_mode_t) ((((tiledesc).level_and_round) >> 4) & 0xF)) /** @brief macro to pack the tiling type and rounding mode into packed structure */ #define EXR_PACK_TILE_LEVEL_ROUND(lvl, mode) \ ((uint8_t) ((((uint8_t) ((mode) &0xF) << 4)) | ((uint8_t) ((lvl) &0xF)))) #pragma pack(pop) /* /////////////////////////////////////// */ /* Now structs that involve heap allocation to store data. */ /** Storage for a string */ typedef struct { int32_t length; /** if this is non-zero, the string owns the data, if 0, is a const ref to a static string */ int32_t alloc_size; const char* str; } exr_attr_string_t; /** storage for a string vector */ typedef struct { int32_t n_strings; /** if this is non-zero, the string vector owns the data, if 0, is a const ref */ int32_t alloc_size; const exr_attr_string_t* strings; } exr_attr_string_vector_t; /** float vector storage struct */ typedef struct { int32_t length; /** if this is non-zero, the float vector owns the data, if 0, is a const ref */ int32_t alloc_size; const float* arr; } exr_attr_float_vector_t; /** Hint for lossy compression methods about how to treat values * (logarithmic or linear), meaning a human sees values like R, G, B, * luminance difference between 0.1 and 0.2 as about the same as 1.0 * to 2.0 (logarithmic), where chroma coordinates are closer to linear * (0.1 and 0.2 is about the same difference as 1.0 and 1.1) */ typedef enum { EXR_PERCEPTUALLY_LOGARITHMIC = 0, EXR_PERCEPTUALLY_LINEAR = 1 } exr_perceptual_treatment_t; /** Individual channel information*/ typedef struct { exr_attr_string_t name; /** Data representation for these pixels: uint, half, float */ exr_pixel_type_t pixel_type; /** Possible values are 0 and 1 per docs @sa exr_perceptual_treatment_t */ uint8_t p_linear; uint8_t reserved[3]; int32_t x_sampling; int32_t y_sampling; } exr_attr_chlist_entry_t; /** List of channel information (sorted alphabetically) */ typedef struct { int num_channels; int num_alloced; const exr_attr_chlist_entry_t* entries; } exr_attr_chlist_t; /** @brief Struct to define attributes of an embedded preview image */ typedef struct { uint32_t width; uint32_t height; /** if this is non-zero, the preview owns the data, if 0, is a const ref */ size_t alloc_size; const uint8_t* rgba; } exr_attr_preview_t; /** Custom storage structure for opaque data * * Handlers for opaque types can be registered, then when a * non-builtin type is encountered with a registered handler, the * function pointers to unpack / pack it will be set up. * * @sa exr_register_attr_type_handler */ typedef struct { int32_t size; int32_t unpacked_size; /** if this is non-zero, the struct owns the data, if 0, is a const ref */ int32_t packed_alloc_size; uint8_t pad[4]; void* packed_data; /** when an application wants to have custom data, they can store an unpacked form here which will * be requested to be destroyed upon destruction of the attribute */ void* unpacked_data; /* an application can register an attribute handler which then * fills in these function pointers. This allows a user to delay * the expansion of the custom type until access is desired, and * similarly, to delay the packing of the data until write time */ exr_result_t (*unpack_func_ptr) ( exr_context_t ctxt, const void* data, int32_t attrsize, int32_t* outsize, void** outbuffer); exr_result_t (*pack_func_ptr) ( exr_context_t ctxt, const void* data, int32_t datasize, int32_t* outsize, void* outbuffer); void (*destroy_unpacked_func_ptr) ( exr_context_t ctxt, void* data, int32_t attrsize); } exr_attr_opaquedata_t; /* /////////////////////////////////////// */ /** @brief built-in / native attribute type enum * * This will enable us to do a tagged type struct to generically store * attributes. */ typedef enum { EXR_ATTR_UNKNOWN = 0, /**< type indicating an error or uninitialized attribute */ EXR_ATTR_BOX2I, /**< integer region definition. @see exr_box2i */ EXR_ATTR_BOX2F, /**< float region definition. @see exr_box2f */ EXR_ATTR_CHLIST, /**< Definition of channels in file @see exr_chlist_entry */ EXR_ATTR_CHROMATICITIES, /**< Values to specify color space of colors in file @see exr_attr_chromaticities_t */ EXR_ATTR_COMPRESSION, /**< uint8_t declaring compression present */ EXR_ATTR_DOUBLE, /**< double precision floating point number */ EXR_ATTR_ENVMAP, /**< uint8_t declaring environment map type */ EXR_ATTR_FLOAT, /**< a normal (4 byte) precision floating point number */ EXR_ATTR_FLOAT_VECTOR, /**< a list of normal (4 byte) precision floating point numbers */ EXR_ATTR_INT, /**< a 32-bit signed integer value */ EXR_ATTR_KEYCODE, /**< structure recording keycode @see exr_attr_keycode_t */ EXR_ATTR_LINEORDER, /**< uint8_t declaring scanline ordering */ EXR_ATTR_M33F, /**< 9 32-bit floats representing a 3x3 matrix */ EXR_ATTR_M33D, /**< 9 64-bit floats representing a 3x3 matrix */ EXR_ATTR_M44F, /**< 16 32-bit floats representing a 4x4 matrix */ EXR_ATTR_M44D, /**< 16 64-bit floats representing a 4x4 matrix */ EXR_ATTR_PREVIEW, /**< 2 unsigned ints followed by 4 x w x h uint8_t image */ EXR_ATTR_RATIONAL, /**< int followed by unsigned int */ EXR_ATTR_STRING, /**< int (length) followed by char string data */ EXR_ATTR_STRING_VECTOR, /**< 0 or more text strings (int + string). number is based on attribute size */ EXR_ATTR_TILEDESC, /**< 2 unsigned ints xSize, ySize followed by mode */ EXR_ATTR_TIMECODE, /**< 2 unsigned ints time and flags, user data */ EXR_ATTR_V2I, /**< pair of 32-bit integers */ EXR_ATTR_V2F, /**< pair of 32-bit floats */ EXR_ATTR_V2D, /**< pair of 64-bit floats */ EXR_ATTR_V3I, /**< set of 3 32-bit integers */ EXR_ATTR_V3F, /**< set of 3 32-bit floats */ EXR_ATTR_V3D, /**< set of 3 64-bit floats */ EXR_ATTR_OPAQUE, /**< user / unknown provided type */ EXR_ATTR_LAST_KNOWN_TYPE } exr_attribute_type_t; /** @brief storage, name and type information for an attribute. * * Attributes (metadata) for the file cause a surprising amount of * overhead. It is not uncommon for a production-grade EXR to have * many attributes. As such, the attribute struct is designed in a * slightly more complicated manner. It is optimized to have the * storage for that attribute: the struct itself, the name, the type, * and the data all allocated as one block. Further, the type and * standard names may use a static string to avoid allocating space * for those as necessary with the pointers pointing to static strings * (not to be freed). Finally, small values are optimized for. */ typedef struct _exr_attribute_t { /** name of the attribute */ const char* name; /** string type name of the attribute */ const char* type_name; /** length of name string (short flag is 31 max, long allows 255) */ uint8_t name_length; /** length of type string (short flag is 31 max, long allows 255) */ uint8_t type_name_length; uint8_t pad[2]; /** enum of the attribute type */ exr_attribute_type_t type; /** Union of pointers of different types that can be used to type * pun to an appropriate type for builtins. Do note that while * this looks like a big thing, it is only the size of a single * pointer. these are all pointers into some other data block * storing the value you want, with the exception of the pod types * which are just put in place (i.e. small value optimization) * * The attribute type @sa type should directly correlate to one of * these entries */ union { // NB: not pointers for POD types uint8_t uc; double d; float f; int32_t i; exr_attr_box2i_t* box2i; exr_attr_box2f_t* box2f; exr_attr_chlist_t* chlist; exr_attr_chromaticities_t* chromaticities; exr_attr_keycode_t* keycode; exr_attr_float_vector_t* floatvector; exr_attr_m33f_t* m33f; exr_attr_m33d_t* m33d; exr_attr_m44f_t* m44f; exr_attr_m44d_t* m44d; exr_attr_preview_t* preview; exr_attr_rational_t* rational; exr_attr_string_t* string; exr_attr_string_vector_t* stringvector; exr_attr_tiledesc_t* tiledesc; exr_attr_timecode_t* timecode; exr_attr_v2i_t* v2i; exr_attr_v2f_t* v2f; exr_attr_v2d_t* v2d; exr_attr_v3i_t* v3i; exr_attr_v3f_t* v3f; exr_attr_v3d_t* v3d; exr_attr_opaquedata_t* opaque; uint8_t* rawptr; }; } exr_attribute_t; /** @} */ #ifdef __cplusplus } /* extern "C" */ #endif #endif /* OPENEXR_ATTR_H */
30.431776
115
0.658068
[ "vector" ]
ca16c8670da0965a3e0b79a1997cc5fa18d988cd
41,982
c
C
Software/RN2483_LoRAWAN_v1.10.X/mcc_generated_files/LoRaWAN/lorawan_eu.c
kamval/RN2483
3d7abf6deac1c315faf2d1c6fd8420c931fd1436
[ "MIT" ]
1
2020-03-22T11:37:55.000Z
2020-03-22T11:37:55.000Z
Software/RN2483_LoRAWAN_v1.20.X/mcc_generated_files/LoRaWAN/lorawan_eu.c
kamval/RN2483
3d7abf6deac1c315faf2d1c6fd8420c931fd1436
[ "MIT" ]
null
null
null
Software/RN2483_LoRAWAN_v1.20.X/mcc_generated_files/LoRaWAN/lorawan_eu.c
kamval/RN2483
3d7abf6deac1c315faf2d1c6fd8420c931fd1436
[ "MIT" ]
1
2021-02-13T20:30:49.000Z
2021-02-13T20:30:49.000Z
/******************************************************************** * Copyright (C) 2016 Microchip Technology Inc. and its subsidiaries * (Microchip). All rights reserved. * * You are permitted to use the software and its derivatives with Microchip * products. See the license agreement accompanying this software, if any, for * more info about your rights and obligations. * * SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF * MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR * PURPOSE. IN NO EVENT SHALL MICROCHIP, SMSC, OR ITS LICENSORS BE LIABLE OR * OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH * OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY FOR ANY DIRECT OR INDIRECT * DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, * INDIRECT OR CONSEQUENTIAL DAMAGES, OR OTHER SIMILAR COSTS. To the fullest * extend allowed by law, Microchip and its licensors liability will not exceed * the amount of fees, if any, that you paid directly to Microchip to use this * software. ************************************************************************* * * lorawan_eu.c * * LoRaWAN EU file * ******************************************************************************/ /****************************** INCLUDES **************************************/ #include <math.h> #include <stdbool.h> #include "lorawan.h" #include "lorawan_aes.h" #include "lorawan_aes_cmac.h" #include "lorawan_private.h" #include "lorawan_defs.h" #include "AES.h" #include "radio_interface.h" #include "sw_timer.h" #include "lorawan_eu.h" /****************************** VARIABLES *************************************/ const uint8_t rxWindowSize[] = {8, 10, 14, 26, 49, 88, 60, 8}; // Max Payload Size const uint8_t maxPayloadSize[8] = {51, 51, 51, 115, 242, 242, 242, 56}; // for FSK max message size should be 64 bytes // Channels by ism band ChannelParams_t Channels[MAX_EU_SINGLE_BAND_CHANNELS]; static const int8_t rxWindowOffset[] = {-33, -50, -58, -62, -66, -68, -15, -2}; // Tx power possibilities by ism band static const int8_t txPower868[] = {20, 14, 11, 8, 5, 2}; static const int8_t txPower433[] = {10, 7, 4, 1, -2, -5}; // Spreading factor possibilities static const uint8_t spreadingFactor[] = {12, 11, 10, 9, 8, 7, 7}; // Bandwidth possibilities static const uint8_t bandwidth[] = {BW_125KHZ, BW_125KHZ, BW_125KHZ, BW_125KHZ, BW_125KHZ, BW_125KHZ, BW_250KHZ}; // Modulation possibilities static const uint8_t modulation[] = {MODULATION_LORA, MODULATION_LORA, MODULATION_LORA, MODULATION_LORA, MODULATION_LORA, MODULATION_LORA, MODULATION_LORA, MODULATION_FSK}; static const ChannelParams_t DefaultChannels868[] = { LC0_868, LC1_868, LC2_868, }; static const ChannelParams_t DefaultChannels433[] = { LC0_433, LC1_433, LC2_433, }; static const uint8_t FskSyncWordBuff[3] = {0xC1, 0x94, 0xC1}; /************************ PRIVATE FUNCTION PROTOTYPES *************************/ static void CreateAllSoftwareTimers (void); static void SetCallbackSoftwareTimers (void); static void StopAllSoftwareTimers (void); static void InitDefault868Channels (void); static void InitDefault433Channels (void); static void UpdateDataRange (uint8_t channelId, uint8_t dataRangeNew); static void UpdateChannelIdStatus (uint8_t channelId, bool statusNew); static LorawanError_t ValidateRxOffset (uint8_t rxOffset); static LorawanError_t ValidateFrequency (uint32_t frequencyNew); static LorawanError_t ValidateDataRange (uint8_t dataRangeNew); static LorawanError_t ValidateChannelId (uint8_t channelId, bool allowedForDefaultChannels); static LorawanError_t ValidateChannelMaskCntl (uint8_t channelMaskCntl); static void EnableChannels (uint16_t channelMask, uint8_t channelMaskCntl); static void UpdateFrequency (uint8_t channelId, uint32_t frequencyNew ); static void UpdateDutyCycle (uint8_t channelId, uint16_t dutyCycleNew); static LorawanError_t ValidateChannelMask (uint16_t channelMask); static void EnableChannels1 (uint16_t channelMask, uint8_t channelMaskCntl, uint8_t channelIndexMin, uint8_t channelIndexMax); static void DutyCycleCallback (uint8_t param); static void ConfigureRadioTx(uint8_t dataRate, uint32_t freq); /****************************** FUNCTIONS *************************************/ void LORAWAN_Init(RxAppDataCb_t RxPayload, RxJoinResponseCb_t RxJoinResponse) // this function resets everything to the default values { // Allocate software timers and their callbacks if (loRa.macInitialized == DISABLED) { CreateAllSoftwareTimers (); SetCallbackSoftwareTimers (); loRa.macInitialized = ENABLED; } else { StopAllSoftwareTimers (); } rxPayload.RxAppData = RxPayload; rxPayload.RxJoinResponse = RxJoinResponse; RADIO_Init(&radioBuffer[16], EU868_CALIBRATION_FREQ); srand (RADIO_ReadRandom ()); // for the loRa random function we need a seed that is obtained from the radio LORAWAN_Reset (ISM_EU868); } void LORAWAN_Reset (IsmBand_t ismBandNew) { if (loRa.macInitialized == ENABLED) { StopAllSoftwareTimers (); } loRa.syncWord = 0x34; RADIO_SetLoRaSyncWord(loRa.syncWord); loRa.macStatus.value = 0; loRa.linkCheckMargin = 255; // reserved loRa.linkCheckGwCnt = 0; loRa.lastTimerValue = 0; loRa.lastPacketLength = 0; loRa.fCntDown.value = 0; loRa.fCntUp.value = 0; loRa.devNonce = 0; loRa.prescaler = 1; loRa.adrAckCnt = 0; loRa.counterAdrAckDelay = 0; loRa.offset = 0; loRa.lastTimerValue = 0; // link check mechanism should be disabled loRa.macStatus.linkCheck = DISABLED; //flags all 0-es loRa.macStatus.value = 0; loRa.lorawanMacStatus.value = 0; loRa.maxRepetitionsConfirmedUplink = 7; // 7 retransmissions should occur for each confirmed frame sent until ACK is received loRa.maxRepetitionsUnconfirmedUplink = 0; // 0 retransmissions should occur for each unconfirmed frame sent until a response is received loRa.counterRepetitionsConfirmedUplink = 1; loRa.counterRepetitionsUnconfirmedUplink = 1; loRa.batteryLevel = BATTERY_LEVEL_INVALID; // the end device was not able to measure the battery level loRa.ismBand = ismBandNew; loRa.deviceClass = CLASS_A; // initialize default channels loRa.maxChannels = MAX_EU_SINGLE_BAND_CHANNELS; if(ISM_EU868 == ismBandNew) { RADIO_Init(&radioBuffer[16], EU868_CALIBRATION_FREQ); InitDefault868Channels (); loRa.receiveWindow2Parameters.dataRate = EU868_DEFAULT_RX_WINDOW2_DR; loRa.receiveWindow2Parameters.frequency = EU868_DEFAULT_RX_WINDOW2_FREQ; } else { RADIO_Init(&radioBuffer[16], EU433_CALIBRATION_FREQ); InitDefault433Channels (); loRa.receiveWindow2Parameters.dataRate = EU433_DEFAULT_RX_WINDOW2_DR; loRa.receiveWindow2Parameters.frequency = EU433_DEFAULT_RX_WINDOW2_FREQ; } loRa.txPower = 1; loRa.currentDataRate = DR0; UpdateMinMaxChDataRate (); //keys will be filled with 0 loRa.macKeys.value = 0; //no keys are set memset (&loRa.activationParameters, 0, sizeof(loRa.activationParameters)); //protocol parameters receive the default values loRa.protocolParameters.receiveDelay1 = RECEIVE_DELAY1; loRa.protocolParameters.receiveDelay2 = RECEIVE_DELAY2; loRa.protocolParameters.joinAcceptDelay1 = JOIN_ACCEPT_DELAY1; loRa.protocolParameters.joinAcceptDelay2 = JOIN_ACCEPT_DELAY2; loRa.protocolParameters.ackTimeout = ACK_TIMEOUT; loRa.protocolParameters.adrAckDelay = ADR_ACK_DELAY; loRa.protocolParameters.adrAckLimit = ADR_ACK_LIMIT; loRa.protocolParameters.maxFcntGap = MAX_FCNT_GAP; loRa.protocolParameters.maxMultiFcntGap = MAX_MCAST_FCNT_GAP; LORAWAN_LinkCheckConfigure (DISABLED); // disable the link check mechanism } LorawanError_t LORAWAN_SetReceiveWindow2Parameters (uint32_t frequency, uint8_t dataRate) { LorawanError_t result = OK; if ( (ValidateFrequency (frequency) == OK) && (ValidateDataRate (dataRate) == OK) ) { UpdateReceiveWindow2Parameters (frequency, dataRate); } else { result = INVALID_PARAMETER; } return result; } uint32_t LORAWAN_GetFrequency (uint8_t channelId) { return Channels[channelId].frequency; } LorawanError_t LORAWAN_SetDataRange (uint8_t channelId, uint8_t dataRangeNew) { LorawanError_t result = OK; if ( (ValidateChannelId (channelId, ALL_CHANNELS) != OK) || (ValidateDataRange (dataRangeNew) != OK) ) { result = INVALID_PARAMETER; } else { UpdateDataRange (channelId, dataRangeNew); } return result; } uint8_t LORAWAN_GetDataRange (uint8_t channelId) { uint8_t result = 0xFF; if (ValidateChannelId (channelId, ALL_CHANNELS) == OK) { result = Channels[channelId].dataRange.value; } return result; } LorawanError_t LORAWAN_SetChannelIdStatus (uint8_t channelId, bool statusNew) { LorawanError_t result = OK; if (ValidateChannelId (channelId, ALL_CHANNELS) != OK) { result = INVALID_PARAMETER; } else { if ( (Channels[channelId].parametersDefined & (FREQUENCY_DEFINED | DATA_RANGE_DEFINED | DUTY_CYCLE_DEFINED) ) == (FREQUENCY_DEFINED | DATA_RANGE_DEFINED | DUTY_CYCLE_DEFINED) ) { UpdateChannelIdStatus (channelId, statusNew); } else { result = INVALID_PARAMETER; } } return result; } bool LORAWAN_GetChannelIdStatus (uint8_t channelId) { bool result = DISABLED; if (ValidateChannelId (channelId, ALL_CHANNELS) == OK) { result = Channels[channelId].status; } return result; } LorawanError_t LORAWAN_SetFrequency (uint8_t channelId, uint32_t frequencyNew) { LorawanError_t result = OK; if ( (ValidateChannelId (channelId, 0) != OK) || (ValidateFrequency (frequencyNew) != OK) ) { return INVALID_PARAMETER; } UpdateFrequency (channelId, frequencyNew); return result; } LorawanError_t LORAWAN_SetDutyCycle (uint8_t channelId, uint16_t dutyCycleValue) { LorawanError_t result = OK; if (ValidateChannelId (channelId, ALL_CHANNELS) == OK) { UpdateDutyCycle (channelId, dutyCycleValue); } else { result = INVALID_PARAMETER; } return result; } uint16_t LORAWAN_GetDutyCycle (uint8_t channelId) { uint16_t result = UINT16_MAX; if (ValidateChannelId (channelId, ALL_CHANNELS) == OK) { result = Channels[channelId].dutyCycle; } return result; } uint8_t LORAWAN_GetIsmBand(void) //returns the ISM band { return loRa.ismBand; } void LORAWAN_TxDone(uint16_t timeOnAir) { if (loRa.macStatus.macPause == DISABLED) { bool found = false; uint8_t i; uint32_t delta = 0, minim = UINT32_MAX, ticks; //This flag is used when the reception in RX1 is overlapping the opening of RX2 loRa.rx2DelayExpired = 0; loRa.macStatus.macState = BEFORE_RX1; i = loRa.lastUsedChannelIndex; // the join request should never exceed 0.1% if (loRa.lorawanMacStatus.joining == 1) { SwTimerSetTimeout(loRa.joinAccept1TimerId, MS_TO_TICKS_SHORT(loRa.protocolParameters.joinAcceptDelay1 + rxWindowOffset[loRa.receiveWindow1Parameters.dataRate])); SwTimerSetTimeout(loRa.joinAccept2TimerId, MS_TO_TICKS_SHORT(loRa.protocolParameters.joinAcceptDelay2 + rxWindowOffset[loRa.receiveWindow2Parameters.dataRate])); SwTimerStart(loRa.joinAccept1TimerId); SwTimerStart(loRa.joinAccept2TimerId); Channels[i].channelTimer = ((uint32_t)timeOnAir) * (((uint32_t)DUTY_CYCLE_JOIN_REQUEST + 1) * ((uint32_t)loRa.prescaler) - 1); } else { SwTimerSetTimeout(loRa.receiveWindow1TimerId, MS_TO_TICKS_SHORT(loRa.protocolParameters.receiveDelay1 + rxWindowOffset[loRa.receiveWindow1Parameters.dataRate])); SwTimerSetTimeout(loRa.receiveWindow2TimerId, MS_TO_TICKS_SHORT(loRa.protocolParameters.receiveDelay2 + rxWindowOffset[loRa.receiveWindow2Parameters.dataRate])); SwTimerStart(loRa.receiveWindow1TimerId); if (CLASS_A == loRa.deviceClass) { SwTimerStart(loRa.receiveWindow2TimerId); } Channels[i].channelTimer = ((uint32_t)timeOnAir) * (((uint32_t)Channels[i].dutyCycle + 1) * ((uint32_t)loRa.prescaler) - 1); } if(SwTimerIsRunning(loRa.dutyCycleTimerId)) { SwTimerStop(loRa.dutyCycleTimerId); ticks = SwTimerReadValue (loRa.dutyCycleTimerId); delta = loRa.lastTimerValue - TICKS_TO_MS(ticks); } for (i=0; i < MAX_EU_SINGLE_BAND_CHANNELS; i++) { if ((Channels[i].status == ENABLED) && ( Channels[i].channelTimer != 0 )) { if( i != loRa.lastUsedChannelIndex ) { if (Channels[i].channelTimer > delta) { Channels[i].channelTimer = Channels[i].channelTimer - delta; } else { Channels[i].channelTimer = 0; } } if ( (Channels[i].channelTimer <= minim) && (Channels[i].channelTimer !=0) ) { minim = Channels[i].channelTimer; found = true; } } } if (found == true) { loRa.lastTimerValue = minim; SwTimerSetTimeout (loRa.dutyCycleTimerId, MS_TO_TICKS (minim)); SwTimerStart (loRa.dutyCycleTimerId); } if (CLASS_C == loRa.deviceClass) { loRa.macStatus.macState = CLASS_C_RX2_1_OPEN; LORAWAN_EnterContinuousReceive(); } } else { if ((RADIO_GetStatus() & RADIO_FLAG_TIMEOUT) != 0) { // Radio transmission ended by watchdog timer rxPayload.RxAppData( NULL, 0, RADIO_NOT_OK ); } else { //Standalone radio transmissions finished OK, using the same callback as in LoRaWAN tx if ( rxPayload.RxAppData != NULL ) { rxPayload.RxAppData( NULL, 0, RADIO_OK ); } } } } // this function is called by the radio when the first or the second receive window expired without receiving any message (either for join accept or for message) void LORAWAN_RxTimeout(void) { uint8_t i; uint32_t minim = UINT32_MAX; if (loRa.macStatus.macPause == 0) { // if the timeout is after the first receive window, we have to wait for the second receive window.... if ( loRa.macStatus.macState == RX1_OPEN ) { if (CLASS_A == loRa.deviceClass) { loRa.macStatus.macState = BETWEEN_RX1_RX2; } else if (CLASS_C == loRa.deviceClass) { LORAWAN_ReceiveWindow2Callback(0); } } else { // if last message sent was a join request, the join was not accepted after the second window expired if (loRa.lorawanMacStatus.joining == 1) { SetJoinFailState(); } // if last message sent was a data message, and there was no reply... else if (loRa.macStatus.networkJoined == 1) { if (loRa.lorawanMacStatus.ackRequiredFromNextDownlinkMessage == ENABLED) // if last uplink packet was confirmed, we have to send this packet by the number indicated by NbRepConfFrames { if (loRa.counterRepetitionsConfirmedUplink <= loRa.maxRepetitionsConfirmedUplink) { loRa.macStatus.macState = RETRANSMISSION_DELAY; SwTimerSetTimeout(loRa.ackTimeoutTimerId, MS_TO_TICKS_SHORT(loRa.protocolParameters.ackTimeout)); SwTimerStart(loRa.ackTimeoutTimerId); } else { ResetParametersForConfirmedTransmission (); if (rxPayload.RxAppData != NULL) { rxPayload.RxAppData (NULL, 0, MAC_NOT_OK); } } } else { if (loRa.counterRepetitionsUnconfirmedUplink <= loRa.maxRepetitionsUnconfirmedUplink) { loRa.macStatus.macState = RETRANSMISSION_DELAY; if (SelectChannelForTransmission (1) == OK) { //resend the last packet if the radio transmit function succeedes if (RADIO_Transmit (&macBuffer[16], loRa.lastPacketLength) == OK) { loRa.counterRepetitionsUnconfirmedUplink ++ ; //for each retransmission, the counter increments loRa.macStatus.macState = TRANSMISSION_OCCURRING; // set the state of MAC to transmission occurring. No other packets can be sent afterwards } else // if radio cannot transmit, then no more retransmissions will occur for this packet { ResetParametersForUnconfirmedTransmission (); if (rxPayload.RxAppData != NULL) { rxPayload.RxAppData(NULL, 0, MAC_NOT_OK); // inform the application layer that no message was received back from the server } } } else { // if no channel was found due to duty cycle limitations, start a timer and send the packet when the first channel will be free for (i = 0; i <= loRa.maxChannels; i ++) { if ( (Channels[i].status == ENABLED) && (Channels[i].channelTimer != 0) && (Channels[i].channelTimer <= minim) && (loRa.currentDataRate >= Channels[i].dataRange.min) && (loRa.currentDataRate <= Channels[i].dataRange.max) ) { minim = Channels[i].channelTimer; } } SwTimerSetTimeout (loRa.unconfirmedRetransmisionTimerId, MS_TO_TICKS_SHORT(minim + 50) ); SwTimerStart (loRa.unconfirmedRetransmisionTimerId); } } else { ResetParametersForUnconfirmedTransmission (); if (rxPayload.RxAppData != NULL) { rxPayload.RxAppData(NULL, 0, MAC_OK); // inform the application layer that no message was received back from the server } } } } } } else { //Standalone radio reception NOK, using the same callback as in LoRaWAN rx if (rxPayload.RxAppData != NULL) { rxPayload.RxAppData(NULL, 0, RADIO_NOT_OK); } } } LorawanError_t ValidateDataRate (uint8_t dataRate) { LorawanError_t result = OK; if ( dataRate > DR7 ) { result = INVALID_PARAMETER; } return result; } LorawanError_t ValidateTxPower (uint8_t txPowerNew) { LorawanError_t result = OK; if (((ISM_EU868 == loRa.ismBand) && (0 == txPowerNew)) || (txPowerNew > 5)) { result = INVALID_PARAMETER; } return result; } uint8_t* ExecuteDutyCycle (uint8_t *ptr) { uint8_t maxDCycle; maxDCycle = *(ptr++); if (maxDCycle < 15) { loRa.prescaler = 1 << maxDCycle; // Execute the 2^maxDCycle here loRa.macStatus.prescalerModified = ENABLED; } if (maxDCycle == 255) { loRa.macStatus.silentImmediately = ENABLED; } return ptr; } uint8_t* ExecuteLinkAdr (uint8_t *ptr) { uint8_t txPower, dataRate; uint16_t channelMask; txPower = *(ptr) & LAST_NIBBLE; dataRate = ( *(ptr) & FIRST_NIBBLE ) >> SHIFT4; ptr++; channelMask = (*((uint16_t*)ptr)); ptr = ptr + sizeof (channelMask); Redundancy_t *redundancy; redundancy = (Redundancy_t*)(ptr++); if (ENABLED == loRa.macStatus.adr) { if ( (ValidateChannelMaskCntl(redundancy->chMaskCntl) == OK) && (ValidateChannelMask(channelMask) == OK) ) // If the ChMask field value is one of values meaning RFU, the end-device should reject the command and unset the Channel mask ACK bit in its response. { loRa.macCommands[loRa.crtMacCmdIndex].channelMaskAck = 1; } if ( (ValidateDataRate (dataRate) == OK) && (dataRate >= loRa.minDataRate) && (dataRate <= loRa.maxDataRate) ) { loRa.macCommands[loRa.crtMacCmdIndex].dataRateAck = 1; } if (ValidateTxPower (txPower) == OK) { loRa.macCommands[loRa.crtMacCmdIndex].powerAck = 1; } if ( (loRa.macCommands[loRa.crtMacCmdIndex].powerAck == 1) && (loRa.macCommands[loRa.crtMacCmdIndex].dataRateAck == 1) && (loRa.macCommands[loRa.crtMacCmdIndex].channelMaskAck == 1) ) { EnableChannels (channelMask, redundancy->chMaskCntl); UpdateTxPower (txPower); loRa.macStatus.txPowerModified = ENABLED; // the current tx power was modified, so the user is informed about the change via this flag UpdateCurrentDataRate (dataRate); if (redundancy->nbRep == 0) { loRa.maxRepetitionsUnconfirmedUplink = 0; } else { loRa.maxRepetitionsUnconfirmedUplink = redundancy->nbRep - 1; } loRa.macStatus.nbRepModified = 1; } } else { loRa.macCommands[loRa.crtMacCmdIndex].channelMaskAck = 0; loRa.macCommands[loRa.crtMacCmdIndex].dataRateAck = 0; loRa.macCommands[loRa.crtMacCmdIndex].powerAck = 0; } return ptr; } uint8_t* ExecuteDevStatus (uint8_t *ptr) { return ptr; } uint8_t* ExecuteNewChannel (uint8_t *ptr) { uint8_t channelIndex; DataRange_t drRange; uint32_t frequency = 0; channelIndex = *(ptr++); frequency = (*((uint32_t*)ptr)) & 0x00FFFFFF; frequency = frequency * 100; ptr = ptr + 3; // 3 bytes for frequecy drRange.value = *(ptr++); if (ValidateChannelId (channelIndex, WITHOUT_DEFAULT_CHANNELS) == OK) { if ( (ValidateFrequency (frequency) == OK) || (frequency == 0) ) { loRa.macCommands[loRa.crtMacCmdIndex].channelFrequencyAck = 1; } if (ValidateDataRange (drRange.value) == OK) { loRa.macCommands[loRa.crtMacCmdIndex].dataRateRangeAck = 1; } } if ( (loRa.macCommands[loRa.crtMacCmdIndex].channelFrequencyAck == 1) && (loRa.macCommands[loRa.crtMacCmdIndex].dataRateRangeAck == 1) ) { if (loRa.lastUsedChannelIndex < 16) { if (frequency != 0) { UpdateFrequency (channelIndex, frequency); UpdateDataRange (channelIndex, drRange.value); UpdateDutyCycle (channelIndex, DUTY_CYCLE_DEFAULT); UpdateChannelIdStatus (channelIndex, ENABLED); } else { LORAWAN_SetChannelIdStatus (channelIndex, DISABLED); // according to the spec, a frequency value of 0 disables the channel } } else { if (frequency != 0) { UpdateFrequency (channelIndex + 16, frequency); UpdateDataRange (channelIndex + 16, drRange.value); UpdateDutyCycle (channelIndex + 16, DUTY_CYCLE_DEFAULT); UpdateChannelIdStatus (channelIndex + 16, ENABLED); } else { LORAWAN_SetChannelIdStatus (channelIndex + 16, DISABLED); // according to the spec, a frequency value of 0 disables the channel } } loRa.macStatus.channelsModified = 1; // a new channel was added, so the flag is set to inform the user } return ptr; } uint8_t* ExecuteRxParamSetupReq (uint8_t *ptr) { DlSettings_t dlSettings; uint32_t frequency = 0; //In the status field (response) we have to include the following: channle ACK, RX2 data rate ACK, RX1DoffsetACK dlSettings.value = *(ptr++); frequency = (*((uint32_t*)ptr)) & 0x00FFFFFF; frequency = frequency * 100; ptr = ptr + 3; //3 bytes for frequency if (ValidateFrequency (frequency) == OK) { loRa.macCommands[loRa.crtMacCmdIndex].channelAck = 1; } if (ValidateDataRate (dlSettings.bits.rx2DataRate) == OK) { loRa.macCommands[loRa.crtMacCmdIndex].dataRateReceiveWindowAck = 1; } if (ValidateRxOffset (dlSettings.bits.rx1DROffset) == OK) { loRa.macCommands[loRa.crtMacCmdIndex].rx1DROffestAck = 1; } if ( (loRa.macCommands[loRa.crtMacCmdIndex].dataRateReceiveWindowAck == 1) && (loRa.macCommands[loRa.crtMacCmdIndex].channelAck == 1) && (loRa.macCommands[loRa.crtMacCmdIndex].rx1DROffestAck == 1)) { loRa.offset = dlSettings.bits.rx1DROffset; UpdateReceiveWindow2Parameters (frequency, dlSettings.bits.rx2DataRate); loRa.macStatus.secondReceiveWindowModified = 1; } return ptr; } LorawanError_t SearchAvailableChannel (uint8_t maxChannels, bool transmissionType, uint8_t* channelIndex) { uint8_t randomNumberCopy, randomNumber, i; LorawanError_t result = OK; randomNumber = Random (maxChannels) + 1; //this is a guard so that randomNumber is not 0 and the search will happen randomNumberCopy = randomNumber; while (randomNumber) { for (i=0; (i < maxChannels) && (randomNumber != 0) ; i++) { if ( ( Channels[i].status == ENABLED ) && ( Channels[i].channelTimer == 0 ) && ( loRa.currentDataRate >= Channels[i].dataRange.min ) && ( loRa.currentDataRate <= Channels[i].dataRange.max ) ) { if (transmissionType == 0) // if transmissionType is join request, then check also for join request channels { if ( Channels[i].joinRequestChannel == 1 ) { randomNumber --; } } else { randomNumber --; } } } // if after one search in all the vector no valid channel was found, exit the loop and return an error if ( randomNumber == randomNumberCopy ) { result = NO_CHANNELS_FOUND; break; } } if ( i != 0) { *channelIndex = i - 1; } else { result = NO_CHANNELS_FOUND; } return result; } void UpdateCfList (uint8_t bufferLength, JoinAccept_t *joinAccept) { uint8_t i; uint32_t frequency; uint8_t channelIndex; if ( (bufferLength == SIZE_JOIN_ACCEPT_WITH_CFLIST) ) { // 3 is the minimum channel index for single band channelIndex = 3; for (i = 0; i < NUMBER_CFLIST_FREQUENCIES; i++ ) { frequency = 0; memcpy (&frequency, joinAccept->members.cfList + 3*i, 3); frequency *= 100; if (frequency != 0) { if (ValidateFrequency (frequency) == OK) { Channels[i+channelIndex].frequency = frequency; Channels[i+channelIndex].dataRange.max = DR5; Channels[i+channelIndex].dataRange.min = DR0; Channels[i+channelIndex].dutyCycle = DUTY_CYCLE_DEFAULT_NEW_CHANNEL; Channels[i+channelIndex].parametersDefined = 0xFF; //all parameters defined LORAWAN_SetChannelIdStatus(i+channelIndex, ENABLED); loRa.macStatus.channelsModified = ENABLED; // a new channel was added, so the flag is set to inform the user } } else { LORAWAN_SetChannelIdStatus(i+channelIndex, DISABLED); } } loRa.macStatus.channelsModified = ENABLED; } } void ConfigureRadio(uint8_t dataRate, uint32_t freq) { RADIO_SetModulation (modulation[dataRate]); RADIO_SetChannelFrequency (freq); RADIO_SetFrequencyHopPeriod (DISABLED); if (dataRate <= DR6) { //LoRa modulation RADIO_SetSpreadingFactor (spreadingFactor[dataRate]); RADIO_SetBandwidth (bandwidth[dataRate]); RADIO_SetLoRaSyncWord(loRa.syncWord); } else { //FSK modulation RADIO_SetFSKSyncWord(sizeof(FskSyncWordBuff) / sizeof(FskSyncWordBuff[0]), (uint8_t*)FskSyncWordBuff); } } uint32_t GetRx1Freq (void) { return loRa.receiveWindow1Parameters.frequency; } void UpdateDLSettings(uint8_t dlRx2Dr, uint8_t dlRx1DrOffset) { if (dlRx2Dr <= DR7) { loRa.receiveWindow2Parameters.dataRate = dlRx2Dr; } if (dlRx1DrOffset <= 5) { // update the offset between the uplink data rate and the downlink data rate used to communicate with the end device on the first reception slot loRa.offset = dlRx1DrOffset; } } void StartReTxTimer(void) { uint8_t i; uint32_t minim = UINT32_MAX; for (i = 0; i <= loRa.maxChannels; i++) { if ( (Channels[i].status == ENABLED) && (Channels[i].channelTimer != 0) && (Channels[i].channelTimer <= minim) && (loRa.currentDataRate >= Channels[i].dataRange.min) && (loRa.currentDataRate <= Channels[i].dataRange.max) ) { minim = Channels[i].channelTimer; } } loRa.macStatus.macState = RETRANSMISSION_DELAY; SwTimerSetTimeout (loRa.automaticReplyTimerId, MS_TO_TICKS_SHORT(minim) ); SwTimerStart (loRa.automaticReplyTimerId); } LorawanError_t SelectChannelForTransmission (bool transmissionType) // transmission type is 0 means join request, transmission type is 1 means data message mode { LorawanError_t result = OK; uint8_t channelIndex; result = SearchAvailableChannel (MAX_EU_SINGLE_BAND_CHANNELS, transmissionType, &channelIndex); if (result == OK) { loRa.lastUsedChannelIndex = channelIndex; loRa.receiveWindow1Parameters.frequency = Channels[channelIndex].frequency; loRa.receiveWindow1Parameters.dataRate = loRa.currentDataRate; ConfigureRadioTx(loRa.receiveWindow1Parameters.dataRate, loRa.receiveWindow1Parameters.frequency); } return result; } static void CreateAllSoftwareTimers (void) { loRa.joinAccept1TimerId = SwTimerCreate(); loRa.joinAccept2TimerId = SwTimerCreate(); loRa.receiveWindow1TimerId = SwTimerCreate(); loRa.receiveWindow2TimerId = SwTimerCreate(); loRa.linkCheckTimerId = SwTimerCreate(); loRa.ackTimeoutTimerId = SwTimerCreate(); loRa.automaticReplyTimerId = SwTimerCreate(); loRa.unconfirmedRetransmisionTimerId = SwTimerCreate(); loRa.abpJoinTimerId = SwTimerCreate(); loRa.dutyCycleTimerId = SwTimerCreate(); } static void SetCallbackSoftwareTimers (void) { SwTimerSetCallback(loRa.joinAccept1TimerId, LORAWAN_ReceiveWindow1Callback, 0); SwTimerSetCallback(loRa.joinAccept2TimerId, LORAWAN_ReceiveWindow2Callback, 0); SwTimerSetCallback(loRa.linkCheckTimerId, LORAWAN_LinkCheckCallback, 0); SwTimerSetCallback(loRa.receiveWindow1TimerId, LORAWAN_ReceiveWindow1Callback, 0); SwTimerSetCallback(loRa.receiveWindow2TimerId, LORAWAN_ReceiveWindow2Callback, 0); SwTimerSetCallback(loRa.ackTimeoutTimerId, AckRetransmissionCallback, 0); SwTimerSetCallback(loRa.automaticReplyTimerId, AutomaticReplyCallback, 0); SwTimerSetCallback(loRa.unconfirmedRetransmisionTimerId, UnconfirmedTransmissionCallback, 0); SwTimerSetCallback(loRa.abpJoinTimerId, UpdateJoinSuccessState, 0); SwTimerSetCallback (loRa.dutyCycleTimerId, DutyCycleCallback, 0); } static void StopAllSoftwareTimers (void) { SwTimerStop(loRa.joinAccept1TimerId); SwTimerStop(loRa.joinAccept2TimerId); SwTimerStop(loRa.linkCheckTimerId); SwTimerStop(loRa.receiveWindow1TimerId); SwTimerStop(loRa.receiveWindow2TimerId); SwTimerStop(loRa.ackTimeoutTimerId); SwTimerStop(loRa.automaticReplyTimerId); SwTimerStop(loRa.unconfirmedRetransmisionTimerId); SwTimerStop(loRa.abpJoinTimerId); SwTimerStop(loRa.dutyCycleTimerId); } static void InitDefault868Channels (void) { uint8_t i; memset (Channels, 0, sizeof(Channels) ); memcpy (Channels, DefaultChannels868, sizeof(DefaultChannels868) ); for (i = 3; i < MAX_EU_SINGLE_BAND_CHANNELS; i++) { // for undefined channels the duty cycle should be a very big value, and the data range a not-valid value //duty cycle 0 means no duty cycle limitation, the bigger the duty cycle value, the greater the limitation Channels[i].dutyCycle = UINT16_MAX; Channels[i].dataRange.value = UINT8_MAX; } } static void InitDefault433Channels (void) { uint8_t i; memset (Channels, 0, sizeof(Channels) ); memcpy (Channels, DefaultChannels433, sizeof(DefaultChannels433) ); for (i = 3; i < MAX_EU_SINGLE_BAND_CHANNELS; i++) { // for undefined channels the duty cycle should be a very big value, and the data range a not-valid value //duty cycle 0 means no duty cycle limitation, the bigger the duty cycle value, the greater the limitation Channels[i].dutyCycle = UINT16_MAX; Channels[i].dataRange.value = UINT8_MAX; } } static void UpdateDataRange (uint8_t channelId, uint8_t dataRangeNew) { uint8_t i; // after updating the data range of a channel we need to check if the minimum dataRange has changed or not. // The user cannot set the current data rate outside the range of the data range loRa.minDataRate = DR7; loRa.maxDataRate = DR0; Channels[channelId].dataRange.value = dataRangeNew; Channels[channelId].parametersDefined |= DATA_RANGE_DEFINED; for (i=0; i < loRa.maxChannels; i++) { if ( (Channels[i].dataRange.min < loRa.minDataRate) && (Channels[i].status == ENABLED) ) { loRa.minDataRate = Channels[i].dataRange.min; } if ( (Channels[i].dataRange.max > loRa.maxDataRate) && (Channels[i].status == ENABLED) ) { loRa.maxDataRate = Channels[i].dataRange.max; } } if (loRa.currentDataRate > loRa.maxDataRate) { loRa.currentDataRate = loRa.maxDataRate; } if (loRa.currentDataRate < loRa.minDataRate) { loRa.currentDataRate = loRa.minDataRate; } } static void UpdateChannelIdStatus (uint8_t channelId, bool statusNew) { uint8_t i; Channels[channelId].status = statusNew; if(Channels[channelId].status == DISABLED) { //Clear the dutycycle timer of the channel Channels[channelId].channelTimer = 0; } for (i = 0; i < loRa.maxChannels; i++) { if ( (Channels[i].dataRange.min < loRa.minDataRate) && (Channels[i].status == ENABLED) ) { loRa.minDataRate = Channels[i].dataRange.min; } if ( (Channels[i].dataRange.max > loRa.maxDataRate) && (Channels[i].status == ENABLED) ) { loRa.maxDataRate = Channels[i].dataRange.max; } } if (loRa.currentDataRate > loRa.maxDataRate) { loRa.currentDataRate = loRa.maxDataRate; } if (loRa.currentDataRate < loRa.minDataRate) { loRa.currentDataRate = loRa.minDataRate; } } static LorawanError_t ValidateRxOffset (uint8_t rxOffset) { LorawanError_t result = OK; if (rxOffset > 5) { result = INVALID_PARAMETER; } return result; } static LorawanError_t ValidateFrequency (uint32_t frequencyNew) { LorawanError_t result = OK; if(ISM_EU868 == loRa.ismBand) { if ( (frequencyNew > FREQ_870000KHZ) || (frequencyNew < FREQ_863000KHZ) ) { result = INVALID_PARAMETER ; } } else { if ( (frequencyNew > FREQ_434790KHZ) || (frequencyNew < FREQ_433050KHZ) ) { result = INVALID_PARAMETER ; } } return result; } static LorawanError_t ValidateDataRange (uint8_t dataRangeNew) { LorawanError_t result = OK; uint8_t dataRateMax, dataRateMin; dataRateMin = dataRangeNew & LAST_NIBBLE; dataRateMax = (dataRangeNew & FIRST_NIBBLE) >> SHIFT4; if ( (ValidateDataRate (dataRateMax) != OK) || (ValidateDataRate (dataRateMin) != OK ) || (dataRateMax < dataRateMin) ) { result = INVALID_PARAMETER; } return result; } static LorawanError_t ValidateChannelId (uint8_t channelId, bool allowedForDefaultChannels) //if allowedForDefaultChannels is 1, all the channels can be modified, if it is 0 channels 0, 1, 2 and 16, 17, and 18 (dual band) cannot be modified { LorawanError_t result = OK; if ( (channelId >= MAX_EU_SINGLE_BAND_CHANNELS) || ( (allowedForDefaultChannels == WITHOUT_DEFAULT_CHANNELS) && (channelId < 3) ) ) { result = INVALID_PARAMETER ; } return result; } static LorawanError_t ValidateChannelMaskCntl (uint8_t channelMaskCntl) { LorawanError_t result = OK; if ( (channelMaskCntl != 0) && (channelMaskCntl != 6) ) { result = INVALID_PARAMETER; } return result; } static void EnableChannels (uint16_t channelMask, uint8_t channelMaskCntl) { EnableChannels1 (channelMask, channelMaskCntl, 0, MAX_EU_SINGLE_BAND_CHANNELS); } static void UpdateFrequency (uint8_t channelId, uint32_t frequencyNew ) { Channels[channelId].frequency = frequencyNew; Channels[channelId].parametersDefined |= FREQUENCY_DEFINED; } static void UpdateDutyCycle (uint8_t channelId, uint16_t dutyCycleNew) { Channels[channelId].dutyCycle = dutyCycleNew; Channels[channelId].parametersDefined |= DUTY_CYCLE_DEFINED; } static LorawanError_t ValidateChannelMask (uint16_t channelMask) { uint8_t i = 0; if(channelMask != 0x0000U) { for (i = 0; i < MAX_EU_SINGLE_BAND_CHANNELS; i++) { if ( ( (channelMask & BIT0) == BIT0) && ( (Channels[i].parametersDefined & (FREQUENCY_DEFINED | DATA_RANGE_DEFINED | DUTY_CYCLE_DEFINED) ) != (FREQUENCY_DEFINED | DATA_RANGE_DEFINED | DUTY_CYCLE_DEFINED) ) ) // if the channel mask sent enables a yet undefined channel, the command is discarded and the device state is not changed { return INVALID_PARAMETER; } else { channelMask = channelMask >> SHIFT1; } } return OK; } else { //ChMask set to 0x0000 in ADR may be used as a DoS attack so receiving this results in an error return INVALID_PARAMETER; } } static void EnableChannels1 (uint16_t channelMask, uint8_t channelMaskCntl, uint8_t channelIndexMin, uint8_t channelIndexMax) { uint8_t i; if (channelMaskCntl == 6) { for ( i = channelIndexMin; i < channelIndexMax; i++ ) { UpdateChannelIdStatus (i, ENABLED); } } else if (channelMaskCntl == 0) { for ( i = channelIndexMin; i < channelIndexMax; i++ ) { if ( channelMask & BIT0 == BIT0) { UpdateChannelIdStatus (i, ENABLED); } else { UpdateChannelIdStatus (i, DISABLED); } channelMask = channelMask >> SHIFT1; } } } static void DutyCycleCallback (uint8_t param) { uint32_t minim = UINT32_MAX; bool found = false; uint8_t i; for (i=0; i < MAX_EU_SINGLE_BAND_CHANNELS; i++) { //Validate this only for enabled channels if ((Channels[i].status == ENABLED) && ( Channels[i].channelTimer != 0 )) { if ( Channels[i].channelTimer > loRa.lastTimerValue ) { Channels[i].channelTimer = Channels[i].channelTimer - loRa.lastTimerValue; } else { Channels[i].channelTimer = 0; } if ( (Channels[i].channelTimer <= minim) && (Channels[i].channelTimer != 0) ) { minim = Channels[i].channelTimer; found = true; } } } if ( found == true ) { loRa.lastTimerValue = minim; SwTimerSetTimeout (loRa.dutyCycleTimerId, MS_TO_TICKS(minim)); SwTimerStart (loRa.dutyCycleTimerId); } } static void ConfigureRadioTx(uint8_t dataRate, uint32_t freq) { int8_t txPower; ConfigureRadio(dataRate, freq); if (ISM_EU868 == loRa.ismBand) { txPower = txPower868[loRa.txPower]; } else { txPower = txPower868[loRa.txPower]; } RADIO_SetOutputPower (txPower); RADIO_SetCRC(ENABLED); RADIO_SetIQInverted(DISABLED); }
32.901254
342
0.62291
[ "vector" ]
ca183fe53eb0efbb1ce25f1826fee47d68a1ec27
3,469
h
C
ui/views/controls/combobox/native_combobox_views.h
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2016-03-10T09:13:57.000Z
2016-03-10T09:13:57.000Z
ui/views/controls/combobox/native_combobox_views.h
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2022-03-13T08:39:05.000Z
2022-03-13T08:39:05.000Z
ui/views/controls/combobox/native_combobox_views.h
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
null
null
null
// 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 UI_VIEWS_CONTROLS_COMBOBOX_NATIVE_COMBOBOX_VIEWS_H_ #define UI_VIEWS_CONTROLS_COMBOBOX_NATIVE_COMBOBOX_VIEWS_H_ #pragma once #include "ui/views/controls/combobox/native_combobox_wrapper.h" #include "ui/views/controls/menu/menu_delegate.h" #include "ui/views/view.h" namespace gfx { class Canvas; class Font; } namespace views { class FocusableBorder; class MenuRunner; // A views/skia only implementation of NativeComboboxWrapper. // No platform specific code is used. class NativeComboboxViews : public views::View, public NativeComboboxWrapper, public views::MenuDelegate { public: static const char kViewClassName[]; explicit NativeComboboxViews(Combobox* combo_box); virtual ~NativeComboboxViews(); // views::View overrides: virtual bool OnMousePressed(const views::MouseEvent& mouse_event) OVERRIDE; virtual bool OnMouseDragged(const views::MouseEvent& mouse_event) OVERRIDE; virtual bool OnKeyPressed(const views::KeyEvent& key_event) OVERRIDE; virtual bool OnKeyReleased(const views::KeyEvent& key_event) OVERRIDE; virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE; virtual void OnFocus() OVERRIDE; virtual void OnBlur() OVERRIDE; // NativeComboboxWrapper overrides: virtual void UpdateFromModel() OVERRIDE; virtual void UpdateSelectedIndex() OVERRIDE; virtual void UpdateEnabled() OVERRIDE; virtual int GetSelectedIndex() const OVERRIDE; virtual bool IsDropdownOpen() const OVERRIDE; virtual gfx::Size GetPreferredSize() OVERRIDE; virtual View* GetView() OVERRIDE; virtual void SetFocus() OVERRIDE; virtual bool HandleKeyPressed(const views::KeyEvent& event) OVERRIDE; virtual bool HandleKeyReleased(const views::KeyEvent& event) OVERRIDE; virtual void HandleFocus() OVERRIDE; virtual void HandleBlur() OVERRIDE; virtual gfx::NativeView GetTestingHandle() const OVERRIDE; // MenuDelegate overrides: virtual bool IsItemChecked(int id) const OVERRIDE; virtual bool IsCommandEnabled(int id) const OVERRIDE; virtual void ExecuteCommand(int id) OVERRIDE; virtual bool GetAccelerator(int id, ui::Accelerator* accelerator) OVERRIDE; private: // Given bounds within our View, this helper routine mirrors the bounds if // necessary. void AdjustBoundsForRTLUI(gfx::Rect* rect) const; // Draw the selected value of the drop down list void PaintText(gfx::Canvas* canvas); // Show the drop down list void ShowDropDownMenu(); // The parent combobox, the owner of this object. Combobox* combobox_; // The reference to the border class. The object is owned by View::border_. FocusableBorder* text_border_; // The disclosure arrow next to the currently selected item from the list. const SkBitmap* disclosure_arrow_; // Responsible for showing the context menu. scoped_ptr<MenuRunner> dropdown_list_menu_runner_; // Is the drop down list showing bool dropdown_open_; // The selected index in the model. The default value is -1, which means no // selection. int selected_index_; // The maximum dimensions of the content in the dropdown int content_width_; int content_height_; DISALLOW_COPY_AND_ASSIGN(NativeComboboxViews); }; } // namespace views #endif // UI_VIEWS_CONTROLS_COMBOBOX_NATIVE_COMBOBOX_VIEWS_H_
33.355769
77
0.764485
[ "object", "model" ]
ca1dac477dbdedf6468b5e7117275068b17dca2b
3,898
h
C
aws-cpp-sdk-s3/include/aws/s3/model/PutBucketAccelerateConfigurationRequest.h
capeanalytics/aws-sdk-cpp
e88f75add5a9433601b6d46fe738e493da56ac3b
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-s3/include/aws/s3/model/PutBucketAccelerateConfigurationRequest.h
capeanalytics/aws-sdk-cpp
e88f75add5a9433601b6d46fe738e493da56ac3b
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-s3/include/aws/s3/model/PutBucketAccelerateConfigurationRequest.h
capeanalytics/aws-sdk-cpp
e88f75add5a9433601b6d46fe738e493da56ac3b
[ "Apache-2.0" ]
null
null
null
/* * 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/s3/S3_EXPORTS.h> #include <aws/s3/S3Request.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/s3/model/AccelerateConfiguration.h> #include <utility> namespace Aws { namespace S3 { namespace Model { /** */ class AWS_S3_API PutBucketAccelerateConfigurationRequest : public S3Request { public: PutBucketAccelerateConfigurationRequest(); Aws::String SerializePayload() const override; /** * Name of the bucket for which the accelerate configuration is set. */ inline const Aws::String& GetBucket() const{ return m_bucket; } /** * Name of the bucket for which the accelerate configuration is set. */ inline void SetBucket(const Aws::String& value) { m_bucketHasBeenSet = true; m_bucket = value; } /** * Name of the bucket for which the accelerate configuration is set. */ inline void SetBucket(Aws::String&& value) { m_bucketHasBeenSet = true; m_bucket = std::move(value); } /** * Name of the bucket for which the accelerate configuration is set. */ inline void SetBucket(const char* value) { m_bucketHasBeenSet = true; m_bucket.assign(value); } /** * Name of the bucket for which the accelerate configuration is set. */ inline PutBucketAccelerateConfigurationRequest& WithBucket(const Aws::String& value) { SetBucket(value); return *this;} /** * Name of the bucket for which the accelerate configuration is set. */ inline PutBucketAccelerateConfigurationRequest& WithBucket(Aws::String&& value) { SetBucket(std::move(value)); return *this;} /** * Name of the bucket for which the accelerate configuration is set. */ inline PutBucketAccelerateConfigurationRequest& WithBucket(const char* value) { SetBucket(value); return *this;} /** * Specifies the Accelerate Configuration you want to set for the bucket. */ inline const AccelerateConfiguration& GetAccelerateConfiguration() const{ return m_accelerateConfiguration; } /** * Specifies the Accelerate Configuration you want to set for the bucket. */ inline void SetAccelerateConfiguration(const AccelerateConfiguration& value) { m_accelerateConfigurationHasBeenSet = true; m_accelerateConfiguration = value; } /** * Specifies the Accelerate Configuration you want to set for the bucket. */ inline void SetAccelerateConfiguration(AccelerateConfiguration&& value) { m_accelerateConfigurationHasBeenSet = true; m_accelerateConfiguration = std::move(value); } /** * Specifies the Accelerate Configuration you want to set for the bucket. */ inline PutBucketAccelerateConfigurationRequest& WithAccelerateConfiguration(const AccelerateConfiguration& value) { SetAccelerateConfiguration(value); return *this;} /** * Specifies the Accelerate Configuration you want to set for the bucket. */ inline PutBucketAccelerateConfigurationRequest& WithAccelerateConfiguration(AccelerateConfiguration&& value) { SetAccelerateConfiguration(std::move(value)); return *this;} private: Aws::String m_bucket; bool m_bucketHasBeenSet; AccelerateConfiguration m_accelerateConfiguration; bool m_accelerateConfigurationHasBeenSet; }; } // namespace Model } // namespace S3 } // namespace Aws
35.761468
175
0.728066
[ "model" ]
ca1ed30db2ea7812174b92ae4bfb20a6ea1b9ae3
212
h
C
iv/lv5/hint.h
ste72phen/iv
64c3a9c7c517063f29d90d449180ea8f6f4d946f
[ "MIT", "BSD-2-Clause", "BSD-3-Clause" ]
248
2015-01-06T00:05:11.000Z
2022-03-03T23:33:32.000Z
iv/lv5/hint.h
ste72phen/iv
64c3a9c7c517063f29d90d449180ea8f6f4d946f
[ "MIT", "BSD-2-Clause", "BSD-3-Clause" ]
3
2015-01-10T09:37:33.000Z
2018-08-17T14:28:22.000Z
iv/lv5/hint.h
mmalinin/iv
e73342707510436254a4120ae1f9ff19a2b88083
[ "MIT", "BSD-2-Clause", "BSD-3-Clause" ]
32
2015-07-19T13:32:12.000Z
2022-03-17T19:52:45.000Z
#ifndef IV_LV5_HINT_H_ #define IV_LV5_HINT_H_ namespace iv { namespace lv5 { struct Hint { enum Object { NONE = 0, STRING = 1, NUMBER = 2 }; }; } } // namespace iv::lv5 #endif // IV_LV5_HINT_H_
15.142857
25
0.636792
[ "object" ]
ca20b2316ee991a5588f37916006d807ff75d66e
6,362
h
C
third_party/ipus/tools/include/ipu/poplar_executable_runner.h
chenzhengda/tensorflow
8debb698097670458b5f21d728bc6f734a7b5a53
[ "Apache-2.0" ]
74
2020-07-06T17:11:39.000Z
2022-01-28T06:31:28.000Z
third_party/ipus/tools/include/ipu/poplar_executable_runner.h
chenzhengda/tensorflow
8debb698097670458b5f21d728bc6f734a7b5a53
[ "Apache-2.0" ]
9
2020-10-13T23:25:29.000Z
2022-02-10T06:54:48.000Z
third_party/ipus/tools/include/ipu/poplar_executable_runner.h
chenzhengda/tensorflow
8debb698097670458b5f21d728bc6f734a7b5a53
[ "Apache-2.0" ]
12
2020-07-08T07:27:17.000Z
2021-12-27T08:54:27.000Z
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_COMPILER_PLUGIN_POPLAR_TOOLS_POPLAR_EXECUTABLE_RUNNER_H_ #define TENSORFLOW_COMPILER_PLUGIN_POPLAR_TOOLS_POPLAR_EXECUTABLE_RUNNER_H_ #include <fstream> #include <iostream> #include <list> #include <map> #include <memory> #include <set> #include <sstream> #include <stdexcept> #include <string> #include <vector> #include <poplar/DeviceManager.hpp> #include <poplar/Engine.hpp> #include "include/json/json.h" #include "ipu/poplar_executable_data.h" namespace ipu { class BinaryLoader; /* Base class for all executables */ class IExecutable { public: IExecutable(StreamReader& stream, const Metadata& meta, int64_t length); poplar::Engine& Engine(); std::string StreamsList(bool summary = false) const; virtual ~IExecutable() = default; protected: std::unique_ptr<poplar::Engine> engine_; }; /* Class to use for executables which use verified data transfers. * is_verified should be set to true if the executable itself is verified too. * * This type of executables is expected to only contain one single program. */ class VerifiedExecutable : public IExecutable { public: VerifiedExecutable(StreamReader& stream, const Metadata& meta, int64_t length, bool is_verified); void Prepare(poplar::Device& device); void Deploy(); void Run(); bool IsVerified() const; private: bool is_verified_; }; /* Class to use for regular Poplar executables. * * This type of executable is expected to contain 3 distinct programs: * - HOST_TO_DEVICE * - MAIN_SEQUENCE * - DEVICE_TO_HOST */ class Executable : public IExecutable { public: explicit Executable(StreamReader& stream, const Metadata& meta, int64_t length = 0); void Load(const poplar::Device& device); void Run(); void DeviceToHostCopy(); }; /* Helper class to select which device to run on. */ class DeviceManager { public: DeviceManager(); poplar::Device GetDevice(int64_t num_ipus, const Metadata& meta); poplar::Device GetSpecificDevice(int64_t device_id, const Metadata& meta); private: poplar::DeviceManager manager_; }; /* Infeed instance (Made of one or more InfeedStream) */ class Infeed { public: explicit Infeed(const FeedInfo& infeed); void InitializeDataSources(const BinaryLoader& loader); const std::string& Name() const; std::vector<InfeedStream>& MutableStreams(); const std::vector<InfeedStream>& Streams() const; private: const std::string name_; std::vector<InfeedStream> streams_; }; /* Owns and keep track of all the tensors and feeds for a given graph. */ class TensorManager { public: explicit TensorManager(const Metadata& meta); const std::vector<Tensor>& Inputs() const; const std::vector<Tensor>& Outputs() const; const std::vector<Infeed>& Infeeds() const; // Create a non-verified checkpoint: save the position of all the infeeds so // that they can be fast forwarded to the same position at the beginning of // the next iteration. void CreateCheckpointMetadataJson(const std::string& filename) const; // Load a non-verified checkpoint. void LoadCheckpointMetadataFromJson(const std::string& filename); // Sets the folder where the outfeeds will save the tensors produced by the // graph. void SetOutfeedsFolder(const std::string& output_folder); // Don't save the outfeeds produced by the graph: just discard them. void IgnoreOutfeeds(); std::vector<Infeed>& MutableInfeeds(); // Allocate all the tensors. void AllocateTensors(); std::list<Tensor*> InputDataTensors(); // Ensure the loader contains data for all the tensors stored in thie manager. void AssertAllTensorsProvided(const BinaryLoader& loader); // Load data for all the inputs and parameters from the provided loader. void LoadInputsAndParameters(const BinaryLoader& loader); // Load a verified checkpoint from the loader with the given index. void LoadVerifiedCheckpoint(const BinaryLoader& loader, int64_t checkpoint_index); // Create a verified checkpoint void SaveVerifiedCheckpoint(BinaryWriter& writer); // Connect the infeeds from the provided loader. void LoadInfeeds(const BinaryLoader& loader); // Export all the outputs using the provided binary writer. void SaveOutputs(TensorType type, BinaryWriter& writer, bool allow_duplicates = false) const; // Export all the outputs to individual Json files in the specified folder void SaveOutputsToJson(TensorType type, const std::string& folder) const; // Connect all the tensors and feeds to the provided executable. void ConnectStreams(IExecutable& executable); // Does this manager contains a check point ? i.e does it contain any infeeds // whose position needs saving. bool ContainsCheckpoint() const; int64_t NumIpus() const; private: std::vector<Tensor> inputs_; std::vector<Tensor> outputs_; std::vector<Infeed> infeeds_; std::vector<Outfeed> outfeeds_; std::vector<std::string> feeds_order_; std::vector<uint64_t> seeds_; int64_t num_ipus_; int64_t replication_count_; std::string random_number_seed_handle_; }; /* TensorManager / Executable / VerifiedExecutable factories from * one or more binary files. */ class BinaryLoader : public BinaryReader { public: std::unique_ptr<TensorManager> CreateTensorManager( const std::string& metadata_name = "") const; std::unique_ptr<Executable> CreateExecutable( const std::string& executable_name = "") const; std::unique_ptr<VerifiedExecutable> CreateVerifiedExecutable( const std::string& executable_name = "") const; }; } // namespace ipu #endif // TENSORFLOW_COMPILER_PLUGIN_POPLAR_TOOLS_POPLAR_EXECUTABLE_RUNNER_H_
33.840426
80
0.738133
[ "vector" ]
ca23559f984d4d268fe49df55730d86331c5e2ee
4,878
h
C
devices/LinearScanMirror.h
MouseLightProject/Fetch
48114d648db6794aae91554310172680b8c5b1af
[ "BSD-3-Clause" ]
2
2015-08-18T18:07:32.000Z
2016-03-24T23:07:18.000Z
devices/LinearScanMirror.h
MouseLightProject/MouseLight_Microscope_Software
48114d648db6794aae91554310172680b8c5b1af
[ "BSD-3-Clause" ]
57
2016-08-17T21:10:51.000Z
2020-03-11T15:00:51.000Z
devices/LinearScanMirror.h
MouseLightProject/MouseLight_Microscope_Software
48114d648db6794aae91554310172680b8c5b1af
[ "BSD-3-Clause" ]
2
2017-10-21T20:17:50.000Z
2019-12-29T16:27:04.000Z
/* * LinearScanMirror.h * * Created on: Apr 20, 2010 * Author: Nathan Clack <clackn@janelia.hhmi.org> */ /* * Copyright 2010 Howard Hughes Medical Institute. * All rights reserved. * Use is subject to Janelia Farm Research Campus Software Copyright 1.1 * license terms (http://license.janelia.org/license/jfrc_copyright_1_1.html). */ #pragma once #include "DAQChannel.h" #include "../agent.h" #include "linear_scan_mirror.pb.h" #include "object.h" #define LINEAR_SCAN_MIRROR__MAX_CHAN_STRING 32 namespace fetch { bool operator==(const cfg::device::NIDAQLinearScanMirror& a, const cfg::device::NIDAQLinearScanMirror& b) ; bool operator==(const cfg::device::SimulatedLinearScanMirror& a, const cfg::device::SimulatedLinearScanMirror& b); bool operator==(const cfg::device::LinearScanMirror& a, const cfg::device::LinearScanMirror& b) ; bool operator!=(const cfg::device::NIDAQLinearScanMirror& a, const cfg::device::NIDAQLinearScanMirror& b) ; bool operator!=(const cfg::device::SimulatedLinearScanMirror& a, const cfg::device::SimulatedLinearScanMirror& b); bool operator!=(const cfg::device::LinearScanMirror& a, const cfg::device::LinearScanMirror& b) ; namespace device { class ILSM { public: /* TODO: add methods to change vpp on the fly*/ virtual void computeSawtooth(float64 *data, int flyback, int n)=0; virtual IDAQPhysicalChannel* physicalChannel() = 0; virtual double getAmplitudeVolts() = 0; virtual void setAmplitudeVolts(double vpp) = 0; virtual void setAmplitudeVoltsNoWait(double vpp) = 0; }; template<class T> class LSMBase:public ILSM,public IConfigurableDevice<T> { public: LSMBase(Agent *agent) :IConfigurableDevice<T>(agent) {} LSMBase(Agent *agent, Config* cfg):IConfigurableDevice<T>(agent,cfg) {} }; class NIDAQLinearScanMirror : public LSMBase<cfg::device::NIDAQLinearScanMirror> { NIDAQChannel daq; IDAQPhysicalChannel _pchan; public: NIDAQLinearScanMirror(Agent *agent); NIDAQLinearScanMirror(Agent *agent, Config *cfg); virtual unsigned int on_attach() {return daq.on_attach();} virtual unsigned int on_detach() {return daq.on_detach();} virtual void _set_config(Config IN *cfg) {_pchan.set(cfg->ao_channel());} virtual void computeSawtooth(float64 *data, int flyback, int n); virtual IDAQPhysicalChannel* physicalChannel() {return &_pchan;} virtual double getAmplitudeVolts() {return _config->vpp();} virtual void setAmplitudeVolts(double vpp) {Config c = get_config(); c.set_vpp(vpp); set_config(c);} virtual void setAmplitudeVoltsNoWait(double vpp) {Config c = get_config(); c.set_vpp(vpp); Guarded_Assert_WinErr(set_config_nowait(c));} }; class SimulatedLinearScanMirror : public LSMBase<cfg::device::SimulatedLinearScanMirror> { SimulatedDAQChannel _chan; IDAQPhysicalChannel _pchan; public: SimulatedLinearScanMirror(Agent *agent); SimulatedLinearScanMirror(Agent *agent, Config *cfg); virtual unsigned int on_attach() {return 0;} virtual unsigned int on_detach() {return 0;} virtual void computeSawtooth(float64 *data, int flyback, int n); virtual IDAQPhysicalChannel* physicalChannel() {return &_pchan;} virtual double getAmplitudeVolts() {return _config->val();} virtual void setAmplitudeVolts(double vpp) {Config c = get_config(); c.set_val(vpp); set_config(c);} virtual void setAmplitudeVoltsNoWait(double vpp) {Config c = get_config(); c.set_val(vpp); Guarded_Assert_WinErr(set_config_nowait(c));} }; class LinearScanMirror:public LSMBase<cfg::device::LinearScanMirror> { NIDAQLinearScanMirror *_nidaq; SimulatedLinearScanMirror *_simulated; IDevice *_idevice; ILSM *_ilsm; public: LinearScanMirror(Agent *agent); LinearScanMirror(Agent *agent, Config *cfg); ~LinearScanMirror(); void setKind(Config::LinearScanMirrorType kind); virtual unsigned int on_attach() {return _idevice->on_attach();} virtual unsigned int on_detach() {return _idevice->on_detach();} void _set_config( Config IN *cfg ); void _set_config( const Config &cfg ); virtual void computeSawtooth(float64 *data, int flyback, int n); virtual IDAQPhysicalChannel* physicalChannel() {return _ilsm->physicalChannel();} virtual double getAmplitudeVolts() {return _ilsm->getAmplitudeVolts();} virtual void setAmplitudeVolts(double vpp) {_ilsm->setAmplitudeVolts(vpp);} virtual void setAmplitudeVoltsNoWait(double vpp) {_ilsm->setAmplitudeVoltsNoWait(vpp);} }; //end namespace fetch::device } }
38.409449
162
0.689832
[ "object" ]
ca24a31a505ea07aa0643d3286b1f6c260ec7e61
163
h
C
tools/gfx/d3d11/render-d3d11.h
djohansson/slang
69227ad7d46b8741274c93a42a891d70458f2d45
[ "MIT" ]
2
2019-08-16T13:33:28.000Z
2020-08-12T21:48:24.000Z
tools/gfx/d3d11/render-d3d11.h
djohansson/slang
69227ad7d46b8741274c93a42a891d70458f2d45
[ "MIT" ]
null
null
null
tools/gfx/d3d11/render-d3d11.h
djohansson/slang
69227ad7d46b8741274c93a42a891d70458f2d45
[ "MIT" ]
null
null
null
// render-d3d11.h #pragma once #include <slang.h> namespace gfx { class Renderer; namespace dx11 { SLANG_API Renderer* createD3D11Renderer(); } // dx11 } // gfx
13.583333
42
0.711656
[ "render" ]
ca262b1db600a0e8440a060dfffab02257e810b0
7,686
h
C
content/common/gpu/client/command_buffer_proxy_impl.h
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-01-25T10:18:18.000Z
2021-01-23T15:29:56.000Z
content/common/gpu/client/command_buffer_proxy_impl.h
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/common/gpu/client/command_buffer_proxy_impl.h
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:24:13.000Z
2020-11-04T07:24:13.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 CONTENT_COMMON_GPU_CLIENT_COMMAND_BUFFER_PROXY_IMPL_H_ #define CONTENT_COMMON_GPU_CLIENT_COMMAND_BUFFER_PROXY_IMPL_H_ #include <map> #include <queue> #include <string> #include "base/callback.h" #include "base/compiler_specific.h" #include "base/containers/hash_tables.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "gpu/command_buffer/client/gpu_control.h" #include "gpu/command_buffer/common/command_buffer.h" #include "gpu/command_buffer/common/command_buffer_shared.h" #include "gpu/command_buffer/common/gpu_memory_allocation.h" #include "ipc/ipc_listener.h" #include "ui/events/latency_info.h" struct GPUCommandBufferConsoleMessage; namespace base { class SharedMemory; } namespace gfx { class GpuMemoryBuffer; } namespace gpu { struct Mailbox; } namespace media { class VideoDecodeAccelerator; class VideoEncodeAccelerator; } namespace content { class GpuChannelHost; // Client side proxy that forwards messages synchronously to a // CommandBufferStub. class CommandBufferProxyImpl : public gpu::CommandBuffer, public gpu::GpuControl, public IPC::Listener, public base::SupportsWeakPtr<CommandBufferProxyImpl> { public: class DeletionObserver { public: // Called during the destruction of the CommandBufferProxyImpl. virtual void OnWillDeleteImpl() = 0; protected: virtual ~DeletionObserver() {} }; typedef base::Callback<void( const std::string& msg, int id)> GpuConsoleMessageCallback; CommandBufferProxyImpl(GpuChannelHost* channel, int route_id); virtual ~CommandBufferProxyImpl(); // Sends an IPC message to create a GpuVideoDecodeAccelerator. Creates and // returns it as an owned pointer to a media::VideoDecodeAccelerator. Returns // NULL on failure to create the GpuVideoDecodeAcceleratorHost. // Note that the GpuVideoDecodeAccelerator may still fail to be created in // the GPU process, even if this returns non-NULL. In this case the VDA client // is notified of an error later, after Initialize(). scoped_ptr<media::VideoDecodeAccelerator> CreateVideoDecoder(); // Sends an IPC message to create a GpuVideoEncodeAccelerator. Creates and // returns it as an owned pointer to a media::VideoEncodeAccelerator. Returns // NULL on failure to create the GpuVideoEncodeAcceleratorHost. // Note that the GpuVideoEncodeAccelerator may still fail to be created in // the GPU process, even if this returns non-NULL. In this case the VEA client // is notified of an error later, after Initialize(); scoped_ptr<media::VideoEncodeAccelerator> CreateVideoEncoder(); // IPC::Listener implementation: virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE; virtual void OnChannelError() OVERRIDE; // CommandBuffer implementation: virtual bool Initialize() OVERRIDE; virtual State GetLastState() OVERRIDE; virtual int32 GetLastToken() OVERRIDE; virtual void Flush(int32 put_offset) OVERRIDE; virtual void WaitForTokenInRange(int32 start, int32 end) OVERRIDE; virtual void WaitForGetOffsetInRange(int32 start, int32 end) OVERRIDE; virtual void SetGetBuffer(int32 shm_id) OVERRIDE; virtual scoped_refptr<gpu::Buffer> CreateTransferBuffer(size_t size, int32* id) OVERRIDE; virtual void DestroyTransferBuffer(int32 id) OVERRIDE; // gpu::GpuControl implementation: virtual gpu::Capabilities GetCapabilities() OVERRIDE; virtual gfx::GpuMemoryBuffer* CreateGpuMemoryBuffer(size_t width, size_t height, unsigned internalformat, unsigned usage, int32* id) OVERRIDE; virtual void DestroyGpuMemoryBuffer(int32 id) OVERRIDE; virtual uint32 InsertSyncPoint() OVERRIDE; virtual void SignalSyncPoint(uint32 sync_point, const base::Closure& callback) OVERRIDE; virtual void SignalQuery(uint32 query, const base::Closure& callback) OVERRIDE; virtual void SetSurfaceVisible(bool visible) OVERRIDE; virtual void Echo(const base::Closure& callback) OVERRIDE; virtual uint32 CreateStreamTexture(uint32 texture_id) OVERRIDE; int GetRouteID() const; bool ProduceFrontBuffer(const gpu::Mailbox& mailbox); void SetChannelErrorCallback(const base::Closure& callback); typedef base::Callback<void(const gpu::MemoryAllocation&)> MemoryAllocationChangedCallback; void SetMemoryAllocationChangedCallback( const MemoryAllocationChangedCallback& callback); void AddDeletionObserver(DeletionObserver* observer); void RemoveDeletionObserver(DeletionObserver* observer); bool EnsureBackbuffer(); void SetOnConsoleMessageCallback( const GpuConsoleMessageCallback& callback); void SetLatencyInfo(const std::vector<ui::LatencyInfo>& latency_info); // TODO(apatrick): this is a temporary optimization while skia is calling // ContentGLContext::MakeCurrent prior to every GL call. It saves returning 6 // ints redundantly when only the error is needed for the // CommandBufferProxyImpl implementation. virtual gpu::error::Error GetLastError() OVERRIDE; GpuChannelHost* channel() const { return channel_; } private: typedef std::map<int32, scoped_refptr<gpu::Buffer> > TransferBufferMap; typedef base::hash_map<uint32, base::Closure> SignalTaskMap; typedef std::map<int32, gfx::GpuMemoryBuffer*> GpuMemoryBufferMap; // Send an IPC message over the GPU channel. This is private to fully // encapsulate the channel; all callers of this function must explicitly // verify that the context has not been lost. bool Send(IPC::Message* msg); // Message handlers: void OnUpdateState(const gpu::CommandBuffer::State& state); void OnDestroyed(gpu::error::ContextLostReason reason); void OnEchoAck(); void OnConsoleMessage(const GPUCommandBufferConsoleMessage& message); void OnSetMemoryAllocation(const gpu::MemoryAllocation& allocation); void OnSignalSyncPointAck(uint32 id); // Try to read an updated copy of the state from shared memory. void TryUpdateState(); // The shared memory area used to update state. gpu::CommandBufferSharedState* shared_state() const; // Unowned list of DeletionObservers. ObserverList<DeletionObserver> deletion_observers_; // The last cached state received from the service. State last_state_; // The shared memory area used to update state. scoped_ptr<base::SharedMemory> shared_state_shm_; // |*this| is owned by |*channel_| and so is always outlived by it, so using a // raw pointer is ok. GpuChannelHost* channel_; int route_id_; unsigned int flush_count_; int32 last_put_offset_; // Tasks to be invoked in echo responses. std::queue<base::Closure> echo_tasks_; base::Closure channel_error_callback_; MemoryAllocationChangedCallback memory_allocation_changed_callback_; GpuConsoleMessageCallback console_message_callback_; // Tasks to be invoked in SignalSyncPoint responses. uint32 next_signal_id_; SignalTaskMap signal_tasks_; // Local cache of id to gpu memory buffer mapping. GpuMemoryBufferMap gpu_memory_buffers_; gpu::Capabilities capabilities_; DISALLOW_COPY_AND_ASSIGN(CommandBufferProxyImpl); }; } // namespace content #endif // CONTENT_COMMON_GPU_CLIENT_COMMAND_BUFFER_PROXY_IMPL_H_
36.77512
80
0.747073
[ "vector" ]
ca2851c9777139a5d306db20d79e55b9d9984874
4,798
h
C
src/ValProfile.h
data-bridge/build
1bd37f7061d9bd5caf0c1bd9c5cbbd85c7a45486
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
src/ValProfile.h
data-bridge/build
1bd37f7061d9bd5caf0c1bd9c5cbbd85c7a45486
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
src/ValProfile.h
data-bridge/build
1bd37f7061d9bd5caf0c1bd9c5cbbd85c7a45486
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
/* Part of BridgeData. Copyright (C) 2016-17 by Soren Hein. See LICENSE and README. */ #ifndef BRIDGE_VALPROF_H #define BRIDGE_VALPROF_H #include <string> #include <iostream> #include <vector> #include "bconst.h" using namespace std; enum ValError { // This group of errors covers different or missing headers. // These are to expected in conversions, as not all file formats // contain the complete information. BRIDGE_VAL_TITLE = 0, BRIDGE_VAL_DATE = 1, BRIDGE_VAL_LOCATION = 2, BRIDGE_VAL_EVENT = 3, BRIDGE_VAL_SESSION = 4, BRIDGE_VAL_PLAYERS_HEADER = 5, BRIDGE_VAL_BOARDS_HEADER = 6, BRIDGE_VAL_SCORES_HEADER = 7, BRIDGE_VAL_SCORING = 8, BRIDGE_VAL_TEAMS = 9, BRIDGE_VAL_ROOM = 10, BRIDGE_VAL_DEAL = 11, BRIDGE_VAL_VUL = 12, BRIDGE_VAL_AUCTION = 13, BRIDGE_VAL_PLAY = 14, BRIDGE_VAL_SCORE = 15, BRIDGE_VAL_DD = 16, BRIDGE_VAL_NAMES_SHORT = 17, BRIDGE_VAL_TXT_DASHES = 18, BRIDGE_VAL_VG_MD = 19, BRIDGE_VAL_VG_CHAT = 20, // These include Pavlicek bugs and some not so harmful LIN issues. BRIDGE_VAL_TXT_ALL_PASS = 21, BRIDGE_VAL_LIN_AH_EXTRA = 22, BRIDGE_VAL_LIN_AN_ERROR = 23, BRIDGE_VAL_LIN_AN_EXTRA = 24, BRIDGE_VAL_LIN_MC_EXTRA = 25, BRIDGE_VAL_LIN_MD = 26, BRIDGE_VAL_LIN_PC_ROTATED = 27, BRIDGE_VAL_LIN_PN_EXTRA = 28, BRIDGE_VAL_LIN_PN_MISSING = 29, BRIDGE_VAL_LIN_QX = 30, BRIDGE_VAL_LIN_RH_EXTRA = 31, BRIDGE_VAL_LIN_ST_EXTRA = 32, BRIDGE_VAL_LIN_ST_MISSING = 33, BRIDGE_VAL_LIN_SV_MISSING = 34, BRIDGE_VAL_LIN_PLAY_NL = 35, BRIDGE_VAL_PLAY_SHORT = 36, BRIDGE_VAL_REC_MADE_32 = 37, BRIDGE_VAL_TXT_RESULT = 38, BRIDGE_VAL_RECORD_NUMBER = 39, // These are real errors. BRIDGE_VAL_ERROR = 40, BRIDGE_VAL_OUT_SHORT = 41, BRIDGE_VAL_REF_SHORT = 42, BRIDGE_VAL_VG_MC = 43, BRIDGE_VAL_SIZE = 44 }; struct ValErrorBundle { ValError valError; string nameLong; string nameShort; }; const vector<ValErrorBundle> ValErrors = { {BRIDGE_VAL_TITLE, "Title", "T"}, {BRIDGE_VAL_DATE, "Date", "D"}, {BRIDGE_VAL_LOCATION, "Location", "L"}, {BRIDGE_VAL_EVENT, "Event", "E"}, {BRIDGE_VAL_SESSION, "Session", "S"}, {BRIDGE_VAL_PLAYERS_HEADER, "Players list", "Plist"}, {BRIDGE_VAL_BOARDS_HEADER, "Board numbers", "Bnos"}, {BRIDGE_VAL_SCORES_HEADER, "Scores list", "List"}, {BRIDGE_VAL_SCORING, "Scoring", "F"}, {BRIDGE_VAL_TEAMS, "Teams", "K"}, {BRIDGE_VAL_ROOM, "Room", "Room"}, {BRIDGE_VAL_DEAL, "Deal", "Deal"}, {BRIDGE_VAL_VUL, "Vul", "Vul"}, {BRIDGE_VAL_AUCTION, "Auction", "Auct"}, {BRIDGE_VAL_PLAY, "Play", "Play"}, {BRIDGE_VAL_SCORE, "Score", "Scor"}, {BRIDGE_VAL_DD, "Double-dummy", "DD"}, {BRIDGE_VAL_NAMES_SHORT, "Names-short", "Nsht"}, {BRIDGE_VAL_TXT_DASHES, "TXT-dashes", "Dash"}, {BRIDGE_VAL_VG_MD, "VG-cards", "Hlen"}, {BRIDGE_VAL_VG_CHAT, "VG-chat", "Chat"}, {BRIDGE_VAL_TXT_ALL_PASS, "All-pass", "Apass"}, {BRIDGE_VAL_LIN_AH_EXTRA, "Lin-ah+", "ah+"}, {BRIDGE_VAL_LIN_AN_ERROR, "Lin-an", "an"}, {BRIDGE_VAL_LIN_AN_EXTRA, "Lin-an+", "an+"}, {BRIDGE_VAL_LIN_MC_EXTRA, "Lin-mc+", "mc+"}, {BRIDGE_VAL_LIN_MD, "Lin-md", "md"}, {BRIDGE_VAL_LIN_PC_ROTATED, "Lin-pc rot", "pcrot"}, {BRIDGE_VAL_LIN_PN_EXTRA, "Lin-pn+", "pn+"}, {BRIDGE_VAL_LIN_PN_MISSING, "Lin-pn-", "pn-"}, {BRIDGE_VAL_LIN_QX, "Lin-qx", "qx"}, {BRIDGE_VAL_LIN_RH_EXTRA, "Lin-rh+", "rh+"}, {BRIDGE_VAL_LIN_ST_EXTRA, "Lin-st+", "st+"}, {BRIDGE_VAL_LIN_ST_MISSING, "Lin-st-", "st-"}, {BRIDGE_VAL_LIN_SV_MISSING, "Lin-sv-", "sv-"}, {BRIDGE_VAL_LIN_PLAY_NL, "Play-newline", "Pline"}, {BRIDGE_VAL_PLAY_SHORT, "Play-short", "Psht"}, {BRIDGE_VAL_REC_MADE_32, "Made-32", "R32"}, {BRIDGE_VAL_TXT_RESULT, "TXT-result", "RTXT"}, {BRIDGE_VAL_RECORD_NUMBER, "Rec-comment", "Comm"}, {BRIDGE_VAL_ERROR, "Error", "Error"}, {BRIDGE_VAL_OUT_SHORT, "Out-short", "Osht"}, {BRIDGE_VAL_REF_SHORT, "Ref-short", "Rsht"}, {BRIDGE_VAL_VG_MC, "VG-mc", "mc"}, {BRIDGE_VAL_SIZE, "", ""}, }; class ValProfile { private: struct ValSide { string line; unsigned lno; }; struct ValExample { ValSide out; ValSide ref; }; vector<ValExample> example; vector<unsigned> count; public: ValProfile(); ~ValProfile(); void reset(); void log( const ValError label, const LineData& dataOut, const LineData& dataRef); bool labelIsSet(const unsigned label) const; bool hasError(const bool minorFlag = false) const; unsigned getCount(const unsigned label) const; void operator += (const ValProfile& prof2); void addRange( const ValProfile& prof, const unsigned lower, const unsigned upper, bool& flag); void print( ostream& fstr = cout, const bool minorFlag = false) const; }; #endif
24.731959
68
0.682993
[ "vector" ]
ca314d335b7df87a73ff10ca9b982e3d1c770369
5,439
c
C
src/ViennaRNA/part_func_wrappers.c
visigoth/ViennaRNA
0b8ca4c6604e7a8bea366af62d82f8f40cea49bf
[ "Python-2.0" ]
157
2016-10-12T22:11:56.000Z
2022-03-20T05:45:15.000Z
src/ViennaRNA/part_func_wrappers.c
visigoth/ViennaRNA
0b8ca4c6604e7a8bea366af62d82f8f40cea49bf
[ "Python-2.0" ]
136
2016-11-07T19:06:30.000Z
2022-03-10T23:50:55.000Z
src/ViennaRNA/part_func_wrappers.c
visigoth/ViennaRNA
0b8ca4c6604e7a8bea366af62d82f8f40cea49bf
[ "Python-2.0" ]
59
2016-11-17T20:23:55.000Z
2022-01-27T15:23:17.000Z
#ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include "ViennaRNA/fold_compound.h" #include "ViennaRNA/model.h" #include "ViennaRNA/utils/basic.h" #include "ViennaRNA/utils/structures.h" #include "ViennaRNA/mfe.h" #include "ViennaRNA/part_func.h" #include "ViennaRNA/part_func_window.h" PUBLIC float vrna_pf_fold(const char *seq, char *structure, vrna_ep_t **pl) { float free_energy; double mfe; vrna_fold_compound_t *vc; vrna_md_t md; vrna_md_set_default(&md); /* no need to backtrack MFE structure */ md.backtrack = 0; if (!pl) /* no need for pair probability computations if we do not store them somewhere */ md.compute_bpp = 0; vc = vrna_fold_compound(seq, &md, 0); mfe = (double)vrna_mfe(vc, NULL); vrna_exp_params_rescale(vc, &mfe); free_energy = vrna_pf(vc, structure); /* fill plist */ if (pl) *pl = vrna_plist_from_probs(vc, /*cut_off:*/ 1e-6); vrna_fold_compound_free(vc); return free_energy; } PUBLIC float vrna_pf_circfold(const char *seq, char *structure, vrna_ep_t **pl) { float free_energy; double mfe; vrna_fold_compound_t *vc; vrna_md_t md; vrna_md_set_default(&md); md.circ = 1; /* no need to backtrack MFE structure */ md.backtrack = 0; if (!pl) /* no need for pair probability computations if we do not store them somewhere */ md.compute_bpp = 0; vc = vrna_fold_compound(seq, &md, 0); mfe = (double)vrna_mfe(vc, NULL); vrna_exp_params_rescale(vc, &mfe); free_energy = vrna_pf(vc, structure); /* fill plist */ if (pl) *pl = vrna_plist_from_probs(vc, /*cut_off:*/ 1e-6); vrna_fold_compound_free(vc); return free_energy; } PUBLIC float vrna_pf_alifold(const char **strings, char *structure, vrna_ep_t **pl) { float free_energy; double mfe; vrna_fold_compound_t *vc; vrna_md_t md; vrna_md_set_default(&md); /* no need to backtrack MFE structure */ md.backtrack = 0; if (!pl) /* no need for pair probability computations if we do not store them somewhere */ md.compute_bpp = 0; vc = vrna_fold_compound_comparative(strings, &md, VRNA_OPTION_DEFAULT); mfe = (double)vrna_pf(vc, structure); vrna_exp_params_rescale(vc, &mfe); free_energy = vrna_pf(vc, structure); /* fill plist */ if (pl) *pl = vrna_plist_from_probs(vc, /*cut_off:*/ 1e-6); vrna_fold_compound_free(vc); return free_energy; } PUBLIC float vrna_pf_circalifold(const char **sequences, char *structure, vrna_ep_t **pl) { float free_energy; double mfe; vrna_fold_compound_t *vc; vrna_md_t md; vrna_md_set_default(&md); md.circ = 1; /* no need to backtrack MFE structure */ md.backtrack = 0; if (!pl) /* no need for pair probability computations if we do not store them somewhere */ md.compute_bpp = 0; vc = vrna_fold_compound_comparative(sequences, &md, VRNA_OPTION_DEFAULT); mfe = (double)vrna_mfe(vc, structure); vrna_exp_params_rescale(vc, &mfe); free_energy = vrna_pf(vc, structure); /* fill plist */ if (pl) *pl = vrna_plist_from_probs(vc, /*cut_off:*/ 1e-6); vrna_fold_compound_free(vc); return free_energy; } PUBLIC int vrna_pfl_fold_cb(const char *sequence, int window_size, int max_bp_span, vrna_probs_window_callback *cb, void *data) { unsigned int options; int r; vrna_fold_compound_t *vc; vrna_md_t md; vrna_md_set_default(&md); /* get default parameters */ md.compute_bpp = 1; /* turn on base pair probability computations */ md.window_size = window_size; /* set size of sliding window */ md.max_bp_span = max_bp_span; /* set maximum base pair span */ vc = vrna_fold_compound(sequence, &md, VRNA_OPTION_PF | VRNA_OPTION_WINDOW); options = VRNA_PROBS_WINDOW_BPP; /* always compute base pair probabilities */ r = vrna_probs_window(vc, 0, options, cb, data); vrna_fold_compound_free(vc); return r; } PUBLIC int vrna_pfl_fold_up_cb(const char *sequence, int ulength, int window_size, int max_bp_span, vrna_probs_window_callback *cb, void *data) { unsigned int options; int r; vrna_fold_compound_t *vc; vrna_md_t md; vrna_md_set_default(&md); /* get default parameters */ md.compute_bpp = 1; /* turn on base pair probability computations */ md.window_size = window_size; /* set size of sliding window */ md.max_bp_span = max_bp_span; /* set maximum base pair span */ vc = vrna_fold_compound(sequence, &md, VRNA_OPTION_PF | VRNA_OPTION_WINDOW); options = VRNA_PROBS_WINDOW_UP; /* compute unpaired probabilties */ r = vrna_probs_window(vc, ulength, options, cb, data); vrna_fold_compound_free(vc); return r; }
25.777251
92
0.602317
[ "model" ]
ca32bc471344033e9dcb9789524cbd82d9a681f5
11,445
h
C
src/lib/3rdParty/osqp++/osqp++.h
magic3007/AMF-Placer
b6fbc10c37c3259c2b4f99ce0bb03c9d96bc29bd
[ "Apache-2.0" ]
37
2021-09-25T04:31:27.000Z
2022-03-24T13:46:52.000Z
src/lib/3rdParty/osqp++/osqp++.h
magic3007/AMF-Placer
b6fbc10c37c3259c2b4f99ce0bb03c9d96bc29bd
[ "Apache-2.0" ]
5
2021-11-01T13:27:46.000Z
2022-03-10T07:52:51.000Z
src/lib/3rdParty/osqp++/osqp++.h
magic3007/AMF-Placer
b6fbc10c37c3259c2b4f99ce0bb03c9d96bc29bd
[ "Apache-2.0" ]
7
2021-09-26T07:34:09.000Z
2022-02-15T08:06:20.000Z
// Copyright 2020 Google LLC // // 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 // // https://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 OSQP_CPP_H_ #define OSQP_CPP_H_ // A C++ wrapper for OSQP (https://osqp.org/). See README.md for an overview. #include <memory> #include <string> #include "absl/base/attributes.h" #include "absl/status/status.h" #include "Eigen/Core" #include "Eigen/SparseCore" namespace osqp { // Must match the typedef in osqp/include/glob_opts.h (if not, it will trigger // a static_assert failure in osqp++.cc). using c_int = long long; // NOLINT // A memory-safe mirror of the OSQPData struct defined in osqp/include/types.h. // The number of variables and constraints is implied by the shape of // constraint_matrix. The format of the struct is further discussed in // README.md. See also osqp++_test.cc for example usage. struct OsqpInstance { c_int num_variables() const { return constraint_matrix.cols(); } c_int num_constraints() const { return constraint_matrix.rows(); } // Only the upper triangle of the objective matrix is read. The lower triangle // is ignored. Eigen::SparseMatrix<double, Eigen::ColMajor, c_int> objective_matrix; Eigen::VectorXd objective_vector; Eigen::SparseMatrix<double, Eigen::ColMajor, c_int> constraint_matrix; Eigen::VectorXd lower_bounds; Eigen::VectorXd upper_bounds; }; // This is a mirror of the OSQPSettings struct defined in // osqp/include/types.h and documented at // http://osqp.readthedocs.io/en/latest/interfaces/solver_settings.html. The // names are unchanged and (hence) violate Google naming conventions. The // default values are defined in osqp/include/constants.h. Note, OSQP's default // settings are looser than other QP solvers. Do choose appropriate values of // eps_abs and eps_rel for your application. struct OsqpSettings { OsqpSettings(); // Sets default values. double rho; double sigma; c_int scaling; bool adaptive_rho; c_int adaptive_rho_interval; double adaptive_rho_tolerance; double adaptive_rho_fraction; c_int max_iter; double eps_abs; double eps_rel; double eps_prim_inf; double eps_dual_inf; double alpha; // linsys_solver is omitted. We don't change this. double delta; bool polish; c_int polish_refine_iter; bool verbose; bool scaled_termination; c_int check_termination; bool warm_start; double time_limit; }; // Type-safe wrapper for OSQP's status codes that are defined at // osqp/include/constants.h. enum class OsqpExitCode { kOptimal, // Optimal solution found. kPrimalInfeasible, // Certificate of primal infeasibility found. kDualInfeasible, // Certificate of dual infeasibility found. kOptimalInaccurate, // Optimal solution found subject to reduced tolerances kPrimalInfeasibleInaccurate, // Certificate of primal infeasibility found // subject to reduced tolerances. kDualInfeasibleInaccurate, // Certificate of dual infeasibility found // subject to reduced tolerances. kMaxIterations, // Maximum number of iterations reached. kInterrupted, // Interrupted by signal or CTRL-C. kTimeLimitReached, // Ran out of time. kNonConvex, // The problem was found to be non-convex. kUnknown, // Unknown problem in solver. }; std::string ToString(OsqpExitCode exitcode); // This is a workaround to avoid including OSQP's header file. We can't directly // forward-declare OSQPWorkspace because it is defined as a typedef of an // anonymous struct. struct OSQPWorkspaceHelper; // This class is the main interface for calling OSQP. See example usage in // README.md. class OsqpSolver { public: OsqpSolver() = default; // Move-only. OsqpSolver(OsqpSolver &&rhs) = default; OsqpSolver &operator=(OsqpSolver &&rhs) = default; OsqpSolver(const OsqpSolver &) = delete; OsqpSolver &operator=(const OsqpSolver &) = delete; // Creates the internal OSQP workspace given the instance data and settings. // It is valid to call Init() multiple times. absl::Status Init(const OsqpInstance &instance, const OsqpSettings &settings, bool MKLorNot = false); // Updates the elements of matrix the objective matrix P (upper triangular). // The new matrix should have the same sparsity structure. // // The solve will start from the previous optimal solution, which might not be // a good starting point given the new objective matrix. If that's the // case, one can call SetWarmStart with zero vectors to reset the state of the // solver. absl::Status UpdateObjectiveMatrix(const Eigen::SparseMatrix<double, Eigen::ColMajor, c_int> &objective_matrix); // Updates the elements of matrix the constraint matrix A. // The new matrix should have the same sparsity structure. absl::Status UpdateConstraintMatrix(const Eigen::SparseMatrix<double, Eigen::ColMajor, c_int> &constraint_matrix); // Combines call of UpdateObjectiveMatrix and UpdateConstraintMatrix. absl::Status UpdateObjectiveAndConstraintMatrices(const Eigen::SparseMatrix<double, Eigen::ColMajor, c_int> &objective_matrix, const Eigen::SparseMatrix<double, Eigen::ColMajor, c_int> &constraint_matrix); // Returns true if Init() has been called successfully. bool IsInitialized() const { return workspace_ != nullptr; } // Solves the instance by calling osqp_solve(). CHECK-fails if IsInitialized() // is false. ABSL_MUST_USE_RESULT OsqpExitCode Solve(); // The number of iterations taken. CHECK-fails if IsInitialized() is false. c_int iterations() const; // The objective value of the primal solution. CHECK-fails if IsInitialized() // is false. double objective_value() const; // The primal solution, i.e., x. The Map is valid only for the lifetime of the // OSQP workspace. It will be invalidated by a call to Init() or if the // OsqpSolver is deleted. CHECK-fails if IsInitialized() is false. // Implementation details (do not depend on these): The underlying memory is // overwritten by SetPrimalWarmStart(). Modification of the problem data does // not destroy the solution. Eigen::Map<const Eigen::VectorXd> primal_solution() const; // The vector of lagrange multipliers on the linear constraints. The Map is // valid only for the lifetime of the OSQP workspace. It will be invalidated // by a call to Init() or if the OsqpSolver is deleted. CHECK-fails if // IsInitialized() is false. Implementation details (do not depend on these): // The underlying memory is overwritten by SetDualWarmStart(). Modification of // the problem data does not destroy the solution. Eigen::Map<const Eigen::VectorXd> dual_solution() const; // The primal infeasibility certificate. It is valid to query this only if // Solve() returns kPrimalInfeasible or kPrimalInfeasibleInaccurate. The // Map is valid only for the lifetime of the OSQP workspace. It will be // invalidated by a call to Init() or of the OsqpSolver is deleted. Eigen::Map<const Eigen::VectorXd> primal_infeasibility_certificate() const; // TODO(ml): Implement dual_infeasibility_certificate. // Sets a primal and dual warm-start for the next solve. Equivalent to // SetPrimalWarmStart(primal_vector) and SetDualWarmStart(dual_vector). // Returns: // - FailedPreconditionError if IsInitialized() is false // - InvalidArgumentError if the vectors do not have expected dimensions // - UnknownError if the internal OSQP call fails // - OkStatus on success absl::Status SetWarmStart(const Eigen::Ref<const Eigen::VectorXd> &primal_vector, const Eigen::Ref<const Eigen::VectorXd> &dual_vector); // Sets a warm-start for the primal iterate for the next solve. Use a vector // of zeros to reset to the default initialization. // - FailedPreconditionError if IsInitialized() is false // - InvalidArgumentError if the vector does not have expected dimensions // - UnknownError if the internal OSQP call fails // - OkStatus on success absl::Status SetPrimalWarmStart(const Eigen::Ref<const Eigen::VectorXd> &primal_vector); // Sets a warm-start for the dual iterate for the next solve. Use a vector // of zeros to reset to the default initialization. // - FailedPreconditionError if IsInitialized() is false // - InvalidArgumentError if the vector does not have expected dimensions // - UnknownError if the internal OSQP call fails // - OkStatus on success absl::Status SetDualWarmStart(const Eigen::Ref<const Eigen::VectorXd> &dual_vector); // Sets the objective vector for the next solve. Returns: // - FailedPreconditionError if IsInitialized() is false // - InvalidArgumentError if the vectors do not have expected dimensions // - UnknownError if the internal OSQP call fails // - OkStatus on success absl::Status SetObjectiveVector(const Eigen::Ref<const Eigen::VectorXd> &objective_vector); // Sets the lower_bounds and upper_bounds vectors for the next solve. Returns: // - FailedPreconditionError if IsInitialized() is false // - InvalidArgumentError if the vectors do not have expected dimensions // - InvalidArgumentError if lower_bounds[i] > upper_bounds[i] for some i // - UnknownError if the internal OSQP call fails // - OkStatus on success absl::Status SetBounds(const Eigen::Ref<const Eigen::VectorXd> &lower_bounds, const Eigen::Ref<const Eigen::VectorXd> &upper_bounds); // Updates the max_iter setting for this solver. Returns: // - FailedPreconditionError if IsInitialized() is false // - InvalidArgumentError if max_iter_new <= 0 // - OkStatus on success absl::Status UpdateMaxIter(int max_iter_new); // Updates the eps_abs setting for this solver. Returns: // - FailedPreconditionError if IsInitialized() is false // - InvalidArgumentError if eps_abs_new <= 0.0 // - OkStatus on success absl::Status UpdateEpsAbs(double eps_abs_new); // Updates the time_limit setting for this solver. // The time limit is expressed in seconds. // Setting the time limit to zero disables time-limiting. // Returns: // - FailedPreconditionError if IsInitialized() is false // - InvalidArgumentError if time_limit_new < 0.0 // - OkStatus on success absl::Status UpdateTimeLimit(double time_limit_new); private: struct OsqpDeleter { void operator()(OSQPWorkspaceHelper *workspace) const; }; std::unique_ptr<OSQPWorkspaceHelper, OsqpDeleter> workspace_; }; } // namespace osqp #endif // OSQP_CPP_H_
42.388889
119
0.710004
[ "shape", "vector" ]
ca331783c9eb809566c54f2345bdea8b13c6d530
5,444
h
C
headers/C/PDF/TRN_Font.h
NityaNandPandey/AndroidPDF
7a61d488c718dcb1246ed168502a6a3e6921fc87
[ "Apache-2.0" ]
1
2019-04-25T01:24:43.000Z
2019-04-25T01:24:43.000Z
headers/C/PDF/TRN_Font.h
NityaNandPandey/AndroidPDF
7a61d488c718dcb1246ed168502a6a3e6921fc87
[ "Apache-2.0" ]
null
null
null
headers/C/PDF/TRN_Font.h
NityaNandPandey/AndroidPDF
7a61d488c718dcb1246ed168502a6a3e6921fc87
[ "Apache-2.0" ]
null
null
null
//--------------------------------------------------------------------------------------- // Copyright (c) 2001-2018 by PDFTron Systems Inc. All Rights Reserved. // Consult legal.txt regarding legal and license information. //--------------------------------------------------------------------------------------- #ifndef PDFTRON_H_CPDFFont #define PDFTRON_H_CPDFFont #ifdef __cplusplus extern "C" { #endif #include <C/Common/TRN_Types.h> #include <C/Common/TRN_Exception.h> enum TRN_FontStandardType1Font { e_Font_times_roman = 0, e_Font_times_bold, e_Font_times_italic, e_Font_times_bold_italic, e_Font_helvetica, e_Font_helvetica_bold, e_Font_helvetica_oblique, e_Font_helvetica_bold_oblique, e_Font_courier, e_Font_courier_bold, e_Font_courier_oblique, e_Font_courier_bold_oblique, e_Font_symbol, e_Font_zapf_dingbats, e_Font_null }; enum TRN_FontEncoding { e_Font_IdentityH = 0, e_Font_Indices }; TRN_API TRN_FontCreateFromObj(TRN_Obj font_dict,TRN_Font* result); TRN_API TRN_FontCreate(TRN_SDFDoc doc , enum TRN_FontStandardType1Font type, TRN_Font* result); TRN_API TRN_FontCreateFromFontDescriptor(TRN_SDFDoc doc , TRN_Font from, const TRN_UString char_set, TRN_Font* result); TRN_API TRN_FontCreateFromName(TRN_SDFDoc doc, const char* name, const TRN_UString char_set, TRN_Font* result); TRN_API TRN_FontCreateAndEmbed(TRN_SDFDoc doc , enum TRN_FontStandardType1Font type, TRN_Font* result); TRN_API TRN_FontCreateTrueTypeFont(TRN_SDFDoc doc , TRN_UString font_path, TRN_Bool embed, TRN_Bool subset, TRN_Font* result); #ifdef _WIN32 TRN_API TRN_FontCreateTrueTypeFont2(TRN_SDFDoc doc , const void* type, TRN_Bool embed, TRN_Bool subset,TRN_Font* result); #endif TRN_API TRN_FontCreateCIDTrueTypeFont(TRN_SDFDoc doc , TRN_UString type, TRN_Bool embed, TRN_Bool subset, enum TRN_FontEncoding encoding, TRN_UInt32 ttc_font_index, TRN_Font* result); #ifdef _WIN32 TRN_API TRN_FontCreateCIDTrueTypeFont2(TRN_SDFDoc doc , const void* logfont, TRN_Bool embed, TRN_Bool subset, enum TRN_FontEncoding encoding, TRN_Font* result); #endif TRN_API TRN_FontCreateType1Font(TRN_SDFDoc doc, TRN_UString font_path, TRN_Bool embed, TRN_Font* result); TRN_API TRN_FontAssign(TRN_Font left, TRN_Font right); TRN_API TRN_FontDestroy(TRN_Font font); enum TRN_FontType { e_Font_Type1, e_Font_TrueType, e_Font_MMType1, e_Font_Type3, e_Font_Type0, e_Font_CIDType0, e_Font_CIDType2, }; TRN_API TRN_FontGetType(TRN_Font font, enum TRN_FontType* result); TRN_API TRN_FontIsSimple(TRN_Font font, TRN_Bool* result); TRN_API TRN_FontGetTypeFromObj(TRN_Obj font_dict, enum TRN_FontType* result); TRN_API TRN_FontGetSDFObj(TRN_Font font, TRN_Obj* result); TRN_API TRN_FontGetDescriptor(TRN_Font font, TRN_Obj* result); TRN_API TRN_FontGetName(TRN_Font font, const char** result); TRN_API TRN_FontGetFamilyName(TRN_Font font,const char** result); TRN_API TRN_FontIsFixedWidth(TRN_Font font, TRN_Bool* result); TRN_API TRN_FontIsSerif(TRN_Font font,TRN_Bool* result); TRN_API TRN_FontIsSymbolic(TRN_Font font,TRN_Bool* result); TRN_API TRN_FontIsItalic(TRN_Font font, TRN_Bool* result); TRN_API TRN_FontIsAllCap(TRN_Font font, TRN_Bool* result); TRN_API TRN_FontIsForceBold(TRN_Font font, TRN_Bool* result); TRN_API TRN_FontIsHorizontalMode(TRN_Font font, TRN_Bool* result); TRN_API TRN_FontGetWidth(TRN_Font font, TRN_UInt32 char_code,double* result); TRN_API TRN_FontGetMaxWidth(TRN_Font font, double* result); TRN_API TRN_FontGetMissingWidth(TRN_Font font, double* result); TRN_API TRN_FontGetCharCodeIterator(TRN_Font font,TRN_Iterator* result); TRN_API TRN_FontGetGlyphPath(TRN_Font font, TRN_UInt32 char_code, TRN_UChar* buf_oprs, int* out_buf_oprs_sz, double* buf_data, int* out_buf_data_sz, int* out_glyph_indesx, TRN_Bool conics2cubics, TRN_Matrix2D* transform, TRN_Bool* result); TRN_API TRN_FontMapToUnicode(TRN_Font font, TRN_UInt32 char_code, TRN_Unicode* out_uni_arr, const int in_uni_sz, int* out_chars, TRN_Bool* result); TRN_API TRN_FontGetEncoding(TRN_Font font, const char*** result); TRN_API TRN_FontIsEmbedded(TRN_Font font, TRN_Bool* result); TRN_API TRN_FontGetEmbeddedFontName(TRN_Font font, const char** result); TRN_API TRN_FontGetEmbeddedFont(TRN_Font font, TRN_Obj* result); TRN_API TRN_FontGetEmbeddedFontBufSize(TRN_Font font,int* result); TRN_API TRN_FontGetUnitsPerEm(TRN_Font font, TRN_UInt16* result); TRN_API TRN_FontGetBBox(TRN_Font font, TRN_Rect* result); TRN_API TRN_FontGetAscent(TRN_Font font, double* result); TRN_API TRN_FontGetDescent(TRN_Font font, double* result); TRN_API TRN_FontGetStandardType1FontType(TRN_Font font, int* result); TRN_API TRN_FontIsCFF(TRN_Font font, TRN_Bool* result); TRN_API TRN_FontGetType3FontMatrix(TRN_Font font, TRN_Matrix2D* result); TRN_API TRN_FontGetType3GlyphStream(TRN_Font font, TRN_UInt32 char_code, TRN_Obj* result); TRN_API TRN_FontGetVerticalAdvance(TRN_Font font, TRN_UInt32 char_code, double* out_pos_vect_x, double* out_pos_vect_y, double* result); TRN_API TRN_FontGetDescendant(TRN_Font font, TRN_Font* result); TRN_API TRN_FontMapToCID(TRN_Font font, TRN_UInt32 char_code, TRN_UInt32* result); TRN_API TRN_FontMapToCID2(TRN_Font font, const TRN_UChar* char_data, int char_data_avail, TRN_UInt32* out_charcode, TRN_UInt32* out_cid, int* result); #ifdef __cplusplus } // extern C #endif #endif // PDFTRON_H_CPDFFont
40.029412
150
0.786003
[ "transform" ]
ca3548813ff2039531de668aacc6729e62fc605f
69,892
c
C
generic/vectcl.c
auriocus/VecTcl
61fff4f7a8a733e2d59b8b80729f36483d4fe49b
[ "TCL", "BSD-2-Clause", "BSD-3-Clause" ]
26
2015-01-12T07:53:02.000Z
2021-09-22T16:52:45.000Z
generic/vectcl.c
auriocus/VecTcl
61fff4f7a8a733e2d59b8b80729f36483d4fe49b
[ "TCL", "BSD-2-Clause", "BSD-3-Clause" ]
7
2015-06-13T17:00:24.000Z
2020-04-01T08:35:36.000Z
generic/vectcl.c
auriocus/VecTcl
61fff4f7a8a733e2d59b8b80729f36483d4fe49b
[ "TCL", "BSD-2-Clause", "BSD-3-Clause" ]
5
2016-10-27T10:37:28.000Z
2020-02-22T07:16:52.000Z
/* * vectcl.c -- */ #include "vectclInt.h" #include "arrayshape.h" #include "linalg.h" #include "fft.h" #include "svd.h" #include "eig.h" #include "schur.h" #include "bcexecute.h" #include "vmparser.h" #include "intconv.h" #include <string.h> #include <stdlib.h> #include <math.h> /* Copy of this, because it is not exported (but uses only public functionality) */ /* *---------------------------------------------------------------- * Macro used by the Tcl core to clean out an object's internal * representation. Does not actually reset the rep's bytes. The ANSI C * "prototype" for this macro is: * * MODULE_SCOPE void TclFreeIntRep(Tcl_Obj *objPtr); *---------------------------------------------------------------- */ #define TclFreeIntRep(objPtr) \ if ((objPtr)->typePtr != NULL) { \ if ((objPtr)->typePtr->freeIntRepProc != NULL) { \ (objPtr)->typePtr->freeIntRepProc(objPtr); \ } \ (objPtr)->typePtr = NULL; \ } /* * Functions hndling the Tcl_ObjType */ static void DupNumArrayInternalRep(Tcl_Obj *srcPtr, Tcl_Obj *copyPtr); static void FreeNumArrayInternalRep(Tcl_Obj *listPtr); static int SetNumArrayFromAny(Tcl_Interp *interp, Tcl_Obj *objPtr); static void UpdateStringOfNumArray(Tcl_Obj *listPtr); #ifdef LIST_INJECT static int SetListFromNumArray(Tcl_Interp *interp, Tcl_Obj *objPtr); #endif const Tcl_ObjType NumArrayTclType = { "NumArray", /* name */\ FreeNumArrayInternalRep, /* freeIntRepProc */ DupNumArrayInternalRep, /* dupIntRepProc */ UpdateStringOfNumArray, /* updateStringProc */ SetNumArrayFromAny /* setFromAnyProc */ }; Tcl_ObjType * tclListType; const Tcl_ObjType * tclDoubleType; const Tcl_ObjType * tclIntType; #ifndef TCL_WIDE_INT_IS_LONG const Tcl_ObjType * tclWideIntType; #endif Tcl_SetFromAnyProc *listSetFromAny; const char * NumArray_typename[NumArray_SentinelType+1]=NUMARRAYTYPESTRINGS; //const char * NumArray_typesuffixes[NumArray_SentinelType+1]=NUMARRAYTYPESUFFIXES; static int CreateNumArrayInfoFromList(Tcl_Interp *interp, Tcl_Obj* dimlist, NumArrayType dtype, NumArrayInfo **infoptr) { /* Create information with dimensions as in dimlist * TODO catch out of memory */ int d = 0; int nDim; index_t *dims = NULL; if (Tcl_ListObjLength(interp, dimlist, &nDim) != TCL_OK) { return TCL_ERROR; } if (nDim == 0) { Tcl_SetResult(interp, "Empty dimension list", NULL); return TCL_ERROR; } dims = ckalloc(sizeof(index_t)*nDim); for (d=0; d<nDim; d++) { Tcl_WideInt dim; Tcl_Obj *dimObj; Tcl_ListObjIndex(NULL, dimlist, d, &dimObj); /* can't fail */ if (Tcl_GetWideIntFromObj(interp, dimObj, &dim) != TCL_OK) { goto cleandims; } /* only the first dim can be zero (for empty vector) */ if (dim==0 && d!=0) { Tcl_SetResult(interp, "Zero dimension", NULL); goto cleandims; } if (dim<0) { Tcl_SetResult(interp, "Negative dimension", NULL); goto cleandims; } dims[d]=dim; } *infoptr = CreateNumArrayInfo(nDim, dims, dtype); ckfree(dims); return TCL_OK; cleandims: if (dims) ckfree(dims); *infoptr = NULL; return TCL_ERROR; } int NumArrayCompatibleDimensions(NumArrayInfo *info1, NumArrayInfo *info2) { /* return 1 if the dimensions are equal apart from singleton dimensions, * i.e. if we can copy from one into the other by iterating */ int d1=0, d2=0; while (d1 < info1->nDim && d2 < info2 -> nDim) { if (info1 -> dims[d1] == 1) { d1++; continue; } if (info2 -> dims[d2] == 1) { d2++; continue; } if (info1 -> dims[d1] != info2 -> dims[d2]) { return 0; } d1++; d2++; } while (d1 < info1->nDim && info1 -> dims[d1] == 1) d1++; while (d2 < info2->nDim && info2 -> dims[d2] == 1) d2++; return (d1 >= info1->nDim && d2 >= info2->nDim); } /* * Table of numarray subcommand names and implementations. */ typedef struct { const char *name; /* The name of the subcommand. */ Tcl_ObjCmdProc *proc; /* The implementation of the subcommand. */ const char *altname; /* Name of the command in the namespace */ } EnsembleMap; static const EnsembleMap implementationMap[] = { /* create fresh array from nested lists */ {"create", NumArrayCreateCmd, NULL }, /* create fresh array initialized to constant */ {"constfill", NumArrayConstFillCmd, NULL}, /* create identity matrix */ {"eye", NumArrayEyeCmd, NULL}, /* commands that return metadata */ {"info", NumArrayInfoCmd, "__builtin__info"}, {"dimensions", NumArrayDimensionsCmd, NULL}, {"shape", NumArrayShapeCmd, NULL}, /* element accessors */ {"get", NumArrayGetCmd, NULL}, {"set", NumArraySetCmd, "__builtin__set"}, /* copying and elementwise addition on canonical * arrays for benchmark purposes */ {"fastcopy", NumArrayFastCopyCmd, NULL}, {"fastadd", NumArrayFastAddCmd, NULL}, /* linear regression, for benchmarking */ {"linreg", NumArrayLinRegCmd, NULL}, /* commands that change the shape */ {"reshape", NumArrayReshapeCmd, NULL}, {"transpose", NumArrayTransposeCmd, NULL}, {"adjoint", NumArrayAdjointCmd, NULL}, {"slice", NumArraySliceCmd, NULL}, {"concat", NumArrayConcatCmd, NULL}, {"diag", NumArrayDiagCmd, NULL}, /* data type conversion operators */ {"int", NumArrayConvIntCmd, NULL}, {"bool", NumArrayConvBoolCmd, NULL}, {"int8", NumArrayConvInt8Cmd, NULL}, {"uint8", NumArrayConvUint8Cmd, NULL}, {"int16", NumArrayConvInt16Cmd, NULL}, {"uint16", NumArrayConvUint16Cmd, NULL}, {"int32", NumArrayConvInt32Cmd, NULL}, {"uint32", NumArrayConvUint32Cmd, NULL}, {"int64", NumArrayConvInt64Cmd, NULL}, {"uint64", NumArrayConvUint64Cmd, NULL}, {"float32", NumArrayConvFloat32Cmd, NULL}, {"float64", NumArrayConvFloat64Cmd, NULL}, {"complex64", NumArrayConvComplex64Cmd, NULL}, {"complex128", NumArrayConvComplex128Cmd, NULL}, {"double", NumArrayConvDoubleCmd, NULL}, {"complex", NumArrayConvComplexCmd, NULL}, /* elementary manipulations of complex values*/ {"abs", NumArrayAbsCmd, NULL}, {"sign", NumArraySignCmd, NULL}, {"real", NumArrayRealCmd, NULL}, {"imag", NumArrayImagCmd, NULL}, {"arg", NumArrayArgCmd, NULL}, {"conj", NumArrayConjCmd, NULL}, /* elementwise binary operators */ {"+", NumArrayPlusCmd, NULL}, {".+", NumArrayPlusCmd, NULL}, {"-", NumArrayMinusCmd, NULL}, {".-", NumArrayMinusCmd, NULL}, {".*", NumArrayTimesCmd, NULL}, {"./", NumArrayRdivideCmd, NULL}, {".\\", NumArrayLdivideCmd, NULL}, {".^", NumArrayPowCmd, NULL}, {"binarymin", NumArrayMinCmd, NULL}, {"binarymax", NumArrayMaxCmd, NULL}, {"%", NumArrayReminderCmd, NULL}, /* relation operators */ {">", NumArrayGreaterCmd, NULL}, {"<", NumArrayLesserCmd, NULL}, {">=", NumArrayGreaterEqualCmd, NULL}, {"<=", NumArrayLesserEqualCmd, NULL}, {"==", NumArrayEqualCmd, NULL}, {"!=", NumArrayUnequalCmd, NULL}, /* boolean operators */ {"not", NumArrayNotCmd, NULL}, {"&&", NumArrayAndCmd, NULL}, {"||", NumArrayOrCmd, NULL}, /* binary matrix product */ {"*", NumArrayDotCmd, NULL}, {"\\", NumArrayBackslashCmd, NULL}, {"/", NumArraySlashCmd, NULL}, {"^", NumArrayMatrixPowCmd, NULL}, {"**", NumArrayMatrixPowCmd, NULL}, /* elementwise binary assignment operators */ {"=", NumArraySetAssignCmd, NULL}, {"+=", NumArrayPlusAssignCmd, NULL}, {".+=", NumArrayPlusAssignCmd, NULL}, {"-=", NumArrayMinusAssignCmd, NULL}, {".-=", NumArrayMinusAssignCmd, NULL}, {".*=", NumArrayTimesAssignCmd, NULL}, {"./=", NumArrayRdivideAssignCmd, NULL}, {".\\=", NumArrayLdivideAssignCmd, NULL}, {".^=", NumArrayPowAssignCmd, NULL}, /* elementwise unary minus */ {"neg", NumArrayNegCmd, NULL}, /* elementwise elementary transcendental functions */ {"sin", NumArraySinCmd, NULL}, {"cos", NumArrayCosCmd, NULL}, {"tan", NumArrayTanCmd, NULL}, {"exp", NumArrayExpCmd, NULL}, {"log", NumArrayLogCmd, NULL}, {"log10", NumArrayLog10Cmd, NULL}, {"sqrt", NumArraySqrtCmd, NULL}, {"sinh", NumArraySinhCmd, NULL}, {"cosh", NumArrayCoshCmd, NULL}, {"tanh", NumArrayTanhCmd, NULL}, /* Inverse circular and hyperbolic functions */ {"asin", NumArrayAsinCmd, NULL}, {"acos", NumArrayAcosCmd, NULL}, {"atan", NumArrayAtanCmd, NULL}, {"asinh", NumArrayAsinhCmd, NULL}, {"acosh", NumArrayAcoshCmd, NULL}, {"atanh", NumArrayAtanhCmd, NULL}, /* Matrix decompositions */ {"qreco", NumArrayQRecoCmd, NULL}, {"eigv", NumArrayEigVCmd, NULL}, {"eig", NumArrayEigCmd, NULL}, {"svd1", NumArraySVD1Cmd, NULL}, {"svd", NumArraySVDCmd, NULL}, {"schur", NumArraySchurCmd, NULL}, /* Reductions */ {"sum", NumArraySumCmd, NULL}, {"axismin", NumArrayAxisMinCmd, NULL}, {"axismax", NumArrayAxisMaxCmd, NULL}, {"mean", NumArrayMeanCmd, NULL}, {"std", NumArrayStdCmd, NULL}, {"std1", NumArrayStd1Cmd, NULL}, {"all", NumArrayAllCmd, NULL}, {"any", NumArrayAnyCmd, NULL}, /* FFT */ {"fft", NumArrayFFTCmd, NULL}, {"ifft", NumArrayIFFTCmd, NULL}, /* Execute bytecode */ {"bcexecute", NumArrayBCExecuteCmd, NULL}, {NULL, NULL, NULL} }; /* *---------------------------------------------------------------------- * * myTclMakeEnsemble -- * * Create an ensemble from a table of implementation commands. * * Adapted and simplified from a private function in 8.6 * * Results: * Handle for the new ensemble, or NULL on failure. * * Side effects: */ static Tcl_Command myTcl_MakeEnsemble( Tcl_Interp *interp, const char *cmdname, const char *nsname, /* The ensemble name (as explained above) */ const EnsembleMap map[]) /* The subcommands to create */ { Tcl_Command ensemble; Tcl_Namespace *ns; Tcl_Obj *prefix; int i, ensembleFlags = 0; /* * Construct the path for the ensemble namespace and create it. */ ns = Tcl_CreateNamespace(interp, nsname, NULL, NULL); if (!ns) { Tcl_Panic("unable to create %s namespace!", nsname); } ensemble = Tcl_CreateEnsemble(interp, cmdname, ns, ensembleFlags); /* * Create the ensemble mapping dictionary and the ensemble command procs. */ prefix = Tcl_NewStringObj(nsname, -1); Tcl_IncrRefCount(prefix); Tcl_AppendToObj(prefix, "::", -1); if (ensemble != NULL) { Tcl_Obj *mapDict, *fromObj, *toObj; mapDict=Tcl_NewObj(); for (i=0; map[i].name != NULL ; i++) { fromObj = Tcl_NewStringObj(map[i].name, -1); toObj = Tcl_DuplicateObj(prefix); if (map[i].altname != NULL) { Tcl_AppendToObj(toObj, map[i].altname, -1); } else { Tcl_AppendToObj(toObj, map[i].name, -1); } Tcl_DictObjPut(NULL, mapDict, fromObj, toObj); if (map[i].proc) { Tcl_CreateObjCommand(interp, Tcl_GetString(toObj), map[i].proc, NULL, NULL); } } Tcl_SetEnsembleMappingDict(interp, ensemble, mapDict); } Tcl_DecrRefCount(prefix); return ensemble; } /* *---------------------------------------------------------------------- * * myTcl_GetDoubleFromObj -- * * Copied from the Tcl source, but allow NaN values in the result * Attempt to return a double from the Tcl object "objPtr". If the object * is not already a double, an attempt will be made to convert it to one. * * Results: * The return value is a standard Tcl object result. If an error occurs * during conversion, an error message is left in the interpreter's * result unless "interp" is NULL. * * Side effects: * If the object is not already a double, the conversion will free any * old internal representation. * *---------------------------------------------------------------------- */ static int myTcl_GetDoubleFromObj( Tcl_Interp *interp, /* Used for error reporting if not NULL. */ register Tcl_Obj *objPtr, /* The object from which to get a double. */ register double *dblPtr) /* Place to store resulting double. */ { if (objPtr->typePtr == tclDoubleType) { *dblPtr = (double) objPtr->internalRep.doubleValue; return TCL_OK; } if (Tcl_ConvertToType(interp, objPtr, tclDoubleType) != TCL_OK) { return TCL_ERROR; } /* This is really buggy & braindead. SetDoubleFromAny fails to convert * a string into the double type, if it fits into an integer. */ if (objPtr->typePtr == tclDoubleType) { *dblPtr = (double) objPtr->internalRep.doubleValue; return TCL_OK; } else if (objPtr->typePtr == tclIntType) { *dblPtr = objPtr->internalRep.longValue; return TCL_OK; } #ifndef TCL_WIDE_INT_IS_LONG if (objPtr->typePtr == tclWideIntType) { *dblPtr = (double) objPtr->internalRep.wideValue; return TCL_OK; } #endif /* Any other case is handled by the standard code */ return Tcl_GetDoubleFromObj(interp, objPtr, dblPtr); } int NumArrayCreateCmd( ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { Tcl_Obj *naObj; if (objc != 2) { Tcl_SetResult(interp, "numarray create <valuelist>", NULL); return TCL_ERROR; } naObj = objv[1]; if (Tcl_ConvertToType(interp, naObj, &NumArrayTclType) != TCL_OK) { return TCL_ERROR; } Tcl_SetObjResult(interp, naObj); return TCL_OK; } int NumArrayConstFillCmd( ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { Tcl_Obj *naObj; double value; NumArrayInfo *info; NumArraySharedBuffer *sharedbuf; if (objc < 3) { Tcl_WrongNumArgs(interp, 1, objv, "value dim1 ?dim2 ...?"); return TCL_ERROR; } if (myTcl_GetDoubleFromObj(interp, objv[1], &value) != TCL_OK) { return TCL_ERROR; } int ndim = objc-2; index_t *dims = ckalloc(sizeof(index_t)*ndim); index_t nelem = 1; int d; for (d=0; d<ndim; d++) { Tcl_WideInt dim; if (Tcl_GetWideIntFromObj(interp, objv[2+d], &dim) != TCL_OK) { goto cleandims; } /* only the first dim can be zero (for empty vector) */ if (dim==0 && d!=0) { Tcl_SetResult(interp, "Zero dimension", NULL); goto cleandims; } if (dim<0) { Tcl_SetResult(interp, "Negative dimension", NULL); goto cleandims; } dims[d] = dim; nelem *= dim; } info = CreateNumArrayInfo(ndim, dims, NumArray_Float64); sharedbuf = NumArrayNewSharedBuffer(info->bufsize); /* Fill the buffer */ double *bufptr = (double*) NumArrayGetPtrFromSharedBuffer(sharedbuf); index_t i; for (i=0; i<nelem; i++) { bufptr[i] = value; } /* put into result */ naObj = Tcl_NewObj(); NumArraySetInternalRep(naObj, sharedbuf, info); Tcl_SetObjResult(interp, naObj); ckfree(dims); return TCL_OK; cleandims: ckfree(dims); return TCL_ERROR; } int NumArrayEyeCmd( ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { Tcl_Obj *naObj; index_t m, n; NumArrayInfo *info; NumArraySharedBuffer *sharedbuf; if (objc != 2 && objc != 3) { Tcl_WrongNumArgs(interp, 1, objv, "dim1 ?dim2?"); return TCL_ERROR; } Tcl_WideInt temp; if (Tcl_GetWideIntFromObj(interp, objv[1], &temp) != TCL_OK) { return TCL_ERROR; } m=temp; if (objc == 2) { n=m; } else { if (Tcl_GetWideIntFromObj(interp, objv[2], &temp) != TCL_OK) { return TCL_ERROR; } n=temp; } if (m<0 || n<0) { Tcl_SetResult(interp, "Dimensions must be positive", NULL); return TCL_ERROR; } index_t *dims = ckalloc(sizeof(index_t)*2); dims[0]=m; dims[1]=n; info = CreateNumArrayInfo((n==1)? 1:2, dims, NumArray_Float64); sharedbuf = NumArrayNewSharedBuffer(info->bufsize); /* Fill the buffer */ double *bufptr = (double*) NumArrayGetPtrFromSharedBuffer(sharedbuf); index_t i; for (i=0; i<m; i++) { index_t j; for (j=0; j<n; j++) { *bufptr++ = ((i==j)?1.0:0.0); } } /* put into result */ naObj = Tcl_NewObj(); NumArraySetInternalRep(naObj, sharedbuf, info); Tcl_SetObjResult(interp, naObj); ckfree(dims); return TCL_OK; } /* return the metadata from the info object as dictionary */ int NumArrayInfoCmd( ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { Tcl_Obj *naObj, *plist, *infodict; NumArrayInfo * info; NumArraySharedBuffer *sharedbuf; int i; if (objc != 2) { Tcl_WrongNumArgs(interp, 1, objv, "<numarray>"); return TCL_ERROR; } naObj = objv[1]; if (Tcl_ConvertToType(interp, naObj, &NumArrayTclType) != TCL_OK) { return TCL_ERROR; } info = naObj->internalRep.twoPtrValue.ptr2; sharedbuf = naObj -> internalRep.twoPtrValue.ptr1; infodict = Tcl_NewDictObj(); plist = Tcl_NewObj(); for (i=0; i<info->nDim; i++) { Tcl_ListObjAppendElement(interp, plist, Tcl_NewWideIntObj(info->dims[i])); } Tcl_DictObjPut(interp, infodict, Tcl_NewStringObj("dimensions", -1), plist); Tcl_DictObjPut(interp, infodict, Tcl_NewStringObj("offset", -1), Tcl_NewWideIntObj(info->offset)); plist = Tcl_NewObj(); for (i=0; i<info->nDim; i++) { Tcl_ListObjAppendElement(interp, plist, Tcl_NewWideIntObj(info->pitches[i])); } Tcl_DictObjPut(interp, infodict, Tcl_NewStringObj("pitches", -1), plist); Tcl_DictObjPut(interp, infodict, Tcl_NewStringObj("canonical", -1), Tcl_NewBooleanObj(info->canonical)); Tcl_DictObjPut(interp, infodict, Tcl_NewStringObj("bufsize", -1), Tcl_NewWideIntObj(info->bufsize)); Tcl_DictObjPut(interp, infodict, Tcl_NewStringObj("refcount", -1), Tcl_NewIntObj(sharedbuf->refcount)); Tcl_DictObjPut(interp, infodict, Tcl_NewStringObj("type", -1), Tcl_NewIntObj(info->type)); Tcl_SetObjResult(interp, infodict); return TCL_OK; } /* TODO return a single element */ int NumArrayGetCmd( ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { NumArrayInfo *info; char *bufptr; int d; if (objc < 3) { Tcl_WrongNumArgs(interp, 1, objv, "numarray ind ?ind ...?"); return TCL_ERROR; } Tcl_Obj *naObj=objv[1]; if (!(bufptr = NumArrayGetPtrFromObj(interp, naObj))) { return TCL_ERROR; } info = naObj -> internalRep.twoPtrValue.ptr2; if (info -> nDim != objc - 2) { Tcl_SetResult(interp, "Dimension mismatch", NULL); return TCL_ERROR; } for (d=0; d < info->nDim; d++) { index_t ind; Tcl_WideInt temp; if (Tcl_GetWideIntFromObj(interp, objv[d+2], &temp) != TCL_OK) { return TCL_ERROR; } ind=temp; /* negative index counts backward from the end */ if (ind < 0) { ind += info->dims[d]; } if (ind >= info->dims[d] || ind < 0) { Tcl_SetResult(interp, "Index out of bounds", NULL); return TCL_ERROR; } bufptr += ind*info->pitches[d]; } switch (info->type) { case NumArray_Float64: { double value = *((double *) bufptr); Tcl_SetObjResult(interp, Tcl_NewDoubleObj(value)); break; } case NumArray_Int: { NaWideInt value = *((NaWideInt *) bufptr); Tcl_SetObjResult(interp, Tcl_NewLongObj(value)); break; } case NumArray_Complex128: { NumArray_Complex value = *((NumArray_Complex *) bufptr); Tcl_SetObjResult(interp, NumArray_NewComplexObj(value)); break; } default: { RESULTPRINTF(("Error: unknown data type %d", info->type)); return TCL_ERROR; } } return TCL_OK; } /* set a single element */ int NumArraySetCmd( ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { Tcl_Obj *naObj, *resultPtr; NumArrayInfo *info; NumArraySharedBuffer *sharedbuf; char *bufptr; int allocobj=0; int d; if (objc < 4) { Tcl_WrongNumArgs(interp, 1, objv, "<numarrvariable> ?index index ...? value"); return TCL_ERROR; } naObj = Tcl_ObjGetVar2(interp, objv[1], NULL, TCL_LEAVE_ERR_MSG); if (naObj == NULL) { return TCL_ERROR; } if (Tcl_IsShared(naObj)) { naObj = Tcl_DuplicateObj(naObj); allocobj = 1; } if (Tcl_ConvertToType(interp, naObj, &NumArrayTclType) != TCL_OK) { goto cleanobj; } /* copy on write */ NumArrayEnsureWriteable(naObj); sharedbuf = naObj->internalRep.twoPtrValue.ptr1; info = naObj->internalRep.twoPtrValue.ptr2; bufptr = NumArrayGetPtrFromSharedBuffer(sharedbuf); bufptr += info->offset; if (objc-3 != info->nDim) { Tcl_SetResult(interp, "Dimension mismatch.", NULL); goto cleanobj; } /* compute index into buffer */ for (d=0; d<info->nDim; d++) { index_t index; Tcl_WideInt temp; if (Tcl_GetWideIntFromObj(interp, objv[d+2], &temp) != TCL_OK) { goto cleanobj; } index=temp; if (index<0 || index >= info->dims[d]) { Tcl_SetResult(interp, "Index out of range.", NULL); goto cleanobj; } bufptr += info->pitches[d]*index; } /* get value to set */ switch (info->type) { case NumArray_Float64: { double value; if (myTcl_GetDoubleFromObj(interp, objv[objc-1], &value) != TCL_OK) { goto cleanobj; } /* set value */ *((double*)bufptr) = value; break; } case NumArray_Int: { Tcl_WideInt temp; if (Tcl_GetWideIntFromObj(interp, objv[objc-1], &temp) != TCL_OK) { goto cleanobj; } /* set value */ *((NaWideInt*)bufptr) = temp; break; } case NumArray_Complex128: { NumArray_Complex value; if (NumArray_GetComplexFromObj(interp, objv[objc-1], &value) != TCL_OK) { goto cleanobj; } /* set value */ *((NumArray_Complex*)bufptr) = value; break; } default: { RESULTPRINTF(("Error: unknown data type %d", info->type)); return TCL_ERROR; } } Tcl_InvalidateStringRep(naObj); /* put back into variable and interp result */ resultPtr = Tcl_ObjSetVar2(interp, objv[1], NULL, naObj, TCL_LEAVE_ERR_MSG); if (resultPtr == NULL) { return TCL_ERROR; } Tcl_SetObjResult(interp, resultPtr); return TCL_OK; cleanobj: if (allocobj) Tcl_DecrRefCount(naObj); return TCL_ERROR; } int NumArrayFastCopyCmd( ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { Tcl_Obj *naObj, *value, *resultPtr; int allocobj = 0; int d=0; NumArraySharedBuffer * sharedbuf, *valuebuf; NumArrayInfo *info, *valueinfo; if (objc != 3) { Tcl_WrongNumArgs(interp, 1, objv, "numarrayvar numarray"); return TCL_ERROR; } value = objv[2]; naObj = Tcl_ObjGetVar2(interp, objv[1], NULL, TCL_LEAVE_ERR_MSG); if (naObj == NULL) { return TCL_ERROR; } if (Tcl_ConvertToType(interp, naObj, &NumArrayTclType) != TCL_OK) { return TCL_ERROR; } if (Tcl_ConvertToType(interp, value, &NumArrayTclType) != TCL_OK) { return TCL_ERROR; } info = naObj -> internalRep.twoPtrValue.ptr2; valueinfo = value -> internalRep.twoPtrValue.ptr2; /* Check if the arrays are compatible and can be copied */ if (info -> type != valueinfo -> type) { Tcl_SetResult(interp, "Incompatible datatypes", NULL); return TCL_ERROR; } if (info->nDim != valueinfo -> nDim) { Tcl_SetResult(interp, "Dimension mismatch", NULL); return TCL_ERROR; } /* compare dimensions */ for (d=0; d<info->nDim; d++) { if (info->dims[d] != valueinfo -> dims[d]) { Tcl_SetResult(interp, "Size mismatch", NULL); return TCL_ERROR; } } /* check for canonical source array */ if (!valueinfo -> canonical) { Tcl_SetResult(interp, "Source must be a canonical array", NULL); return TCL_ERROR; } /* in-place - handle sharing */ if (Tcl_IsShared(naObj)) { naObj = Tcl_DuplicateObj(naObj); allocobj = 1; } NumArrayEnsureWriteable(naObj); info = naObj -> internalRep.twoPtrValue.ptr2; sharedbuf = naObj -> internalRep.twoPtrValue.ptr1; valuebuf = value -> internalRep.twoPtrValue.ptr1; if (info->bufsize != valueinfo -> bufsize) { Tcl_SetResult(interp, "Internal error", NULL); goto cleanobj; } /* copy by memcopying */ memcpy(NumArrayGetPtrFromSharedBuffer(sharedbuf), NumArrayGetPtrFromSharedBuffer(valuebuf), info -> bufsize); Tcl_InvalidateStringRep(naObj); resultPtr = Tcl_ObjSetVar2(interp, objv[1], NULL, naObj, TCL_LEAVE_ERR_MSG); if (resultPtr == NULL) { goto cleanobj; } Tcl_SetObjResult(interp, resultPtr); return TCL_OK; cleanobj: if (allocobj) Tcl_DecrRefCount(naObj); return TCL_ERROR; } int NumArrayLinRegCmd( ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { Tcl_Obj *xval, *yval, *result; NumArraySharedBuffer *xbuf, *ybuf; NumArrayInfo *xvalinfo, *yvalinfo; if (objc != 3) { Tcl_WrongNumArgs(interp, 1, objv, "vectorx vectory"); return TCL_ERROR; } xval = objv[1]; yval = objv[2]; if (Tcl_ConvertToType(interp, xval, &NumArrayTclType) != TCL_OK) { return TCL_ERROR; } if (Tcl_ConvertToType(interp, yval, &NumArrayTclType) != TCL_OK) { return TCL_ERROR; } xbuf = xval -> internalRep.twoPtrValue.ptr1; ybuf = yval -> internalRep.twoPtrValue.ptr1; xvalinfo = xval -> internalRep.twoPtrValue.ptr2; yvalinfo = yval -> internalRep.twoPtrValue.ptr2; /* Check that we have two double vectors */ if (xvalinfo -> type != NumArray_Float64 || yvalinfo -> type != NumArray_Float64) { Tcl_SetResult(interp, "Datatype must be double", NULL); return TCL_ERROR; } if (xvalinfo->nDim != 1 || yvalinfo -> nDim != 1) { Tcl_SetResult(interp, "Input data must be vectors", NULL); return TCL_ERROR; } if (xvalinfo->dims[0] != yvalinfo -> dims[0]) { Tcl_SetResult(interp, "Input data must have the same length", NULL); return TCL_ERROR; } index_t length = xvalinfo->dims[0]; index_t xpitch = xvalinfo->pitches[0]/sizeof(double); index_t ypitch = yvalinfo->pitches[0]/sizeof(double); /* add value to dest by simple loop */ double *x= (double *)NumArrayGetPtrFromSharedBuffer(xbuf); double *y= (double *)NumArrayGetPtrFromSharedBuffer(ybuf); /* Now compute the mean values */ index_t i; double xm=0.0; double ym=0.0; for (i=0; i<length; i++) { xm+=x[i*xpitch]; ym+=y[i*ypitch]; } xm /= length; ym /= length; double xsum = 0.0; double ysum = 0.0; for (i=0; i<length; i++) { double dx=x[i*xpitch]-xm; double dy=y[i*ypitch]-ym; xsum += dx*dy; ysum += dx*dx; } double b = xsum / ysum; double a = ym - b*xm; result = Tcl_NewObj(); Tcl_ListObjAppendElement(interp, result, Tcl_NewDoubleObj(a)); Tcl_ListObjAppendElement(interp, result, Tcl_NewDoubleObj(b)); Tcl_SetObjResult(interp, result); return TCL_OK; } int NumArrayFastAddCmd( ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { Tcl_Obj *naObj, *value, *resultPtr; int allocobj = 0; int d=0; NumArraySharedBuffer * sharedbuf, *valuebuf; NumArrayInfo *info, *valueinfo; if (objc != 3) { Tcl_WrongNumArgs(interp, 1, objv, "numarrayvar numarray"); return TCL_ERROR; } value = objv[2]; naObj = Tcl_ObjGetVar2(interp, objv[1], NULL, TCL_LEAVE_ERR_MSG); if (naObj == NULL) { return TCL_ERROR; } if (Tcl_ConvertToType(interp, naObj, &NumArrayTclType) != TCL_OK) { return TCL_ERROR; } if (Tcl_ConvertToType(interp, value, &NumArrayTclType) != TCL_OK) { return TCL_ERROR; } info = naObj -> internalRep.twoPtrValue.ptr2; valueinfo = value -> internalRep.twoPtrValue.ptr2; /* Check if the arrays are compatible and can be copied */ if (info -> type != NumArray_Float64 || valueinfo -> type != NumArray_Float64) { Tcl_SetResult(interp, "Datatype must be double", NULL); return TCL_ERROR; } if (info->nDim != valueinfo -> nDim) { Tcl_SetResult(interp, "Dimension mismatch", NULL); return TCL_ERROR; } /* compare dimensions */ for (d=0; d<info->nDim; d++) { if (info->dims[d] != valueinfo -> dims[d]) { Tcl_SetResult(interp, "Size mismatch", NULL); return TCL_ERROR; } } /* check for canonical source array */ if (!valueinfo -> canonical) { Tcl_SetResult(interp, "Source must be a canonical array", NULL); return TCL_ERROR; } /* in-place - handle sharing */ if (Tcl_IsShared(naObj)) { naObj = Tcl_DuplicateObj(naObj); allocobj = 1; } NumArrayEnsureWriteable(naObj); info = naObj -> internalRep.twoPtrValue.ptr2; sharedbuf = naObj -> internalRep.twoPtrValue.ptr1; valuebuf = value -> internalRep.twoPtrValue.ptr1; if (info->bufsize != valueinfo -> bufsize) { Tcl_SetResult(interp, "Internal error", NULL); goto cleanobj; } /* Compute number of elements */ index_t nelem=1; for (d=0; d<info->nDim; d++) { nelem *= info->dims[d]; } /* add value to dest by simple loop */ double *dest= (double *)NumArrayGetPtrFromSharedBuffer(sharedbuf); double *src= (double *)NumArrayGetPtrFromSharedBuffer(valuebuf); index_t i; for (i=0; i<nelem; i++) { (*dest++)+=*src++; } Tcl_InvalidateStringRep(naObj); resultPtr = Tcl_ObjSetVar2(interp, objv[1], NULL, naObj, TCL_LEAVE_ERR_MSG); if (resultPtr == NULL) { goto cleanobj; } Tcl_SetObjResult(interp, resultPtr); return TCL_OK; cleanobj: if (allocobj) Tcl_DecrRefCount(naObj); return TCL_ERROR; } int NumArrayReshapeCmd( ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { Tcl_Obj *naObj; NumArrayInfo *info; NumArrayInfo *reshapeinfo; int i; index_t nelem=1; index_t reshapenelem=1; int reshapedim; int allocobj = 0; if (objc < 3) { Tcl_WrongNumArgs(interp, 1, objv, "numarray dim1 ?dim2 ...?"); return TCL_ERROR; } naObj = objv[1]; if (Tcl_ConvertToType(interp, naObj, &NumArrayTclType) != TCL_OK) { return TCL_ERROR; } if (Tcl_IsShared(naObj)) { naObj = Tcl_DuplicateObj(naObj); allocobj = 1; } /* handle slices by unsharing/canonalizing */ NumArrayEnsureContiguous(naObj); info = naObj->internalRep.twoPtrValue.ptr2; /* compute number of elements */ for (i=0; i<info->nDim; i++) { nelem *= info->dims[i]; } reshapedim = objc-2; reshapeinfo = CreateNumArrayInfo(reshapedim, NULL, info -> type); reshapeinfo -> nDim = reshapedim; reshapeinfo -> bufsize = info -> bufsize; for (i=0; i<reshapedim; i++) { int dim; if (Tcl_GetIntFromObj(interp, objv[2+i], &dim) != TCL_OK) { goto cleaninfo; } reshapenelem *= dim; reshapeinfo -> dims[i] = dim; } if (nelem != reshapenelem) { Tcl_SetResult(interp, "Dimension mismatch", NULL); goto cleaninfo; } reshapeinfo -> pitches[reshapedim-1] = NumArrayType_SizeOf(info -> type); for (i=reshapedim-2; i>=0; i--) { reshapeinfo -> pitches[i] = reshapeinfo -> pitches[i+1] * reshapeinfo ->dims[i+1]; } /* no error so far - replace info in variable */ DeleteNumArrayInfo(info); naObj -> internalRep.twoPtrValue.ptr2 = reshapeinfo; Tcl_InvalidateStringRep(naObj); Tcl_SetObjResult(interp, naObj); return TCL_OK; cleaninfo: DeleteNumArrayInfo(reshapeinfo); if (allocobj) Tcl_DecrRefCount(naObj); return TCL_ERROR; } static void DupNumArrayInternalRep(Tcl_Obj *srcPtr, Tcl_Obj *copyPtr) { NumArrayInfo *info = srcPtr -> internalRep.twoPtrValue.ptr2; copyPtr -> internalRep.twoPtrValue.ptr2 = DupNumArrayInfo (info); NumArraySharedBuffer * sharedbuf = srcPtr -> internalRep.twoPtrValue.ptr1; copyPtr -> internalRep.twoPtrValue.ptr1 = sharedbuf; NumArraySharedBufferIncrRefcount(sharedbuf); copyPtr -> typePtr = &NumArrayTclType; DEBUGPRINTF(("DupNumArrayInternalRep, refocunt %d\n", sharedbuf -> refcount)); } static void FreeNumArrayInternalRep(Tcl_Obj *naPtr) { NumArrayInfo *info = naPtr -> internalRep.twoPtrValue.ptr2; DeleteNumArrayInfo(info); NumArrayDecrRefcount(naPtr); } static int SingletonDimension(Tcl_Obj* list) { /* test a list for singleton dimension */ int length; int llength; int lengthFirstElement; Tcl_Obj* first; Tcl_GetStringFromObj(list, &length); if (Tcl_ListObjLength(NULL, list, &llength) != TCL_OK) { return 0; } if (llength == 0) return 0; if (Tcl_ListObjIndex(NULL, list, 0, &first) != TCL_OK) { return 0; } Tcl_GetStringFromObj(first, &lengthFirstElement); return (length != lengthFirstElement); } static int ScanNumArrayDimensionsFromValue(Tcl_Interp *interp, Tcl_Obj* valobj, Tcl_Obj **result, NumArrayType *dtype) { Tcl_Obj *itobj, *dimlist; int nDim = 0; int allocobj = 0; dimlist = Tcl_NewListObj(0, NULL); int firstdim; /* Try if this is already a NumArray */ if (valobj->typePtr == &NumArrayTclType) { int d; NumArrayInfo *info = valobj -> internalRep.twoPtrValue.ptr2; for (d=0; d<info->nDim; d++) { Tcl_ListObjAppendElement(interp, dimlist, Tcl_NewWideIntObj(info->dims[d])); } *result=dimlist; *dtype = info->type; return TCL_OK; } /* Try if this is an empty object/list */ if (Tcl_ListObjLength(interp, valobj, &firstdim) != TCL_OK) { return TCL_ERROR; } if (firstdim == 0) { Tcl_ListObjAppendElement(interp, dimlist, Tcl_NewWideIntObj(0)); *result=dimlist; *dtype=NumArray_Int; return TCL_OK; } if (Tcl_IsShared(valobj)) { valobj = Tcl_DuplicateObj(valobj); Tcl_IncrRefCount(valobj); allocobj = 1; } itobj = valobj; nDim = 0; /* TODO: Remove dimension limit * if it works reliably */ while (nDim<20) { if (itobj -> typePtr == tclDoubleType || itobj -> typePtr == tclIntType) { /* we have arrived at the leaf */ /* Handle case of a single number, */ /* else just break out of the loop */ if (nDim==0) { nDim=1; Tcl_ListObjAppendElement(interp, dimlist, Tcl_NewWideIntObj(1)); } if (itobj -> typePtr == tclDoubleType) { *dtype = NumArray_Float64; } if (itobj -> typePtr == tclIntType) { *dtype = NumArray_Int; } /* complex doesn't have a Tcl type */ break; } else if (itobj -> typePtr == tclListType) { /* there is one more level */ int length; Tcl_Obj* next; if (Tcl_ListObjLength(interp, itobj, &length) != TCL_OK) { goto cleanobj; } if (length < 1) { Tcl_SetResult(interp, "Zero length dimension", NULL); goto cleanobj; } /* can't fail */ if (Tcl_ListObjAppendElement(interp, dimlist, Tcl_NewIntObj(length)) != TCL_OK) { goto cleanobj; } if (Tcl_ListObjIndex(interp, itobj, 0, &next) != TCL_OK) { goto cleanobj; } itobj = next; nDim++; } else { /* treat everything else as a string */ double dummy_float64; long dummy_long; NumArray_Complex dummy_complex128; /* try to convert to int, then double, then complex */ if (Tcl_GetLongFromObj(interp, itobj, &dummy_long) == TCL_OK) { /* 1st: Try to convert to int. If succeeds, we are at the leaf * Handle case of a single number, * else just break out of the loop */ if (nDim==0) { nDim=1; Tcl_ListObjAppendElement(interp, dimlist, Tcl_NewIntObj(1)); } *dtype = NumArray_Int; break; } if (myTcl_GetDoubleFromObj(interp, itobj, &dummy_float64) == TCL_OK) { /* 2nd: Try to convert to double. If succeeds, we are at the leaf * Handle case of a single number, * else just break out of the loop */ if (nDim==0) { nDim=1; Tcl_ListObjAppendElement(interp, dimlist, Tcl_NewIntObj(1)); } *dtype = NumArray_Float64; break; } if (NumArray_GetComplexFromObj(interp, itobj, &dummy_complex128) == TCL_OK) { /* 2nd: Try to convert to double. If succeeds, we are at the leaf * Handle case of a single number, * else just break out of the loop */ if (nDim==0) { nDim=1; Tcl_ListObjAppendElement(interp, dimlist, Tcl_NewIntObj(1)); } *dtype = NumArray_Complex128; break; } else { /* now the tricky part. Converting to list only fails * for a malformed list. But a single non-double element * like "foo", can be converted to a single-element list * if ([string length $foo] == [string length [lindex $foo 0]]) * then we are at the leaf. */ int llength; if (Tcl_ListObjLength(interp, itobj, &llength) != TCL_OK) { goto cleanobj; } if (llength == 0) { Tcl_SetResult(interp, "Zero length dimension", NULL); goto cleanobj; } if (llength > 1 || SingletonDimension(itobj)) { /* it is a dimension */ Tcl_Obj *next; if (Tcl_ListObjAppendElement(interp, dimlist, Tcl_NewIntObj(llength)) != TCL_OK) { goto cleanobj; } if (Tcl_ListObjIndex(interp, itobj, 0, &next) != TCL_OK) { goto cleanobj; } itobj = next; nDim++; } else { /* Can't be identified? */ *dtype = -1; break; } } } } *result = dimlist; if (allocobj) Tcl_DecrRefCount(valobj); return TCL_OK; cleanobj: if (allocobj) Tcl_DecrRefCount(valobj); Tcl_DecrRefCount(dimlist); return TCL_ERROR; } int NumArrayShapeCmd( ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { NumArrayInfo *info; if (objc != 2) { Tcl_WrongNumArgs(interp, 1, objv, "numarray"); return TCL_ERROR; } if (Tcl_ConvertToType(interp, objv[1], &NumArrayTclType) != TCL_OK) { return TCL_ERROR; } info = objv[1] -> internalRep.twoPtrValue.ptr2; Tcl_Obj *result = Tcl_NewObj(); int d; for (d=0; d<info->nDim; d++) { Tcl_ListObjAppendElement(interp, result, Tcl_NewWideIntObj(info->dims[d])); } Tcl_SetObjResult(interp, result); return TCL_OK; } int NumArrayDimensionsCmd( ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { NumArrayInfo *info; if (objc != 2) { Tcl_WrongNumArgs(interp, 1, objv, "numarray"); return TCL_ERROR; } if (Tcl_ConvertToType(interp, objv[1], &NumArrayTclType) != TCL_OK) { return TCL_ERROR; } info = objv[1] -> internalRep.twoPtrValue.ptr2; Tcl_SetObjResult(interp, Tcl_NewIntObj(info->nDim)); return TCL_OK; } int NumArrayTransposeAdjointCmd(ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv, int adjoint); int NumArrayAdjointCmd( ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { return NumArrayTransposeAdjointCmd(dummy, interp, objc, objv, 1); } int NumArrayTransposeCmd( ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { return NumArrayTransposeAdjointCmd(dummy, interp, objc, objv, 0); } int NumArrayTransposeAdjointCmd( ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv, int adjoint) { Tcl_Obj *naObj; NumArrayInfo *info, *transposeinfo; int dim1, dim2; int allocobj = 0; if (objc != 2 && objc != 4) { Tcl_WrongNumArgs(interp, 1, objv, "numarray ?dim1 dim2?"); return TCL_ERROR; } naObj = objv[1]; if (objc == 2 ) { dim1 = 0; dim2 = 1; } if (objc == 4) { if (Tcl_GetIntFromObj(interp, objv[2], &dim1) != TCL_OK) { return TCL_ERROR; } if (Tcl_GetIntFromObj(interp, objv[3], &dim2) != TCL_OK) { return TCL_ERROR; } if (dim1 == dim2) { Tcl_SetObjResult(interp, naObj); return TCL_OK; } } if (Tcl_ConvertToType(interp, naObj, &NumArrayTclType) != TCL_OK) { return TCL_ERROR; } if (Tcl_IsShared(naObj)) { naObj = Tcl_DuplicateObj(naObj); allocobj = 1; } info = naObj->internalRep.twoPtrValue.ptr2; /* handle special cases: * 1D transposition creates 2D array * empty object remains empty */ if (info->nDim == 1) { if (info -> dims[0] == 0) { /* empty object. Just cleanup and leave */ Tcl_SetObjResult(interp, naObj); return TCL_OK; } /* Check for scalar */ if (info -> dims[0] == 1) { transposeinfo = DupNumArrayInfo(info); /* that's it */ } else if ((dim1 == 0 && dim2 ==1) || (dim1 == 1 && dim2 == 0)) { /* in case of a columnvector, * create rowvector, i.e. 1xN 2D array */ transposeinfo = CreateNumArrayInfo(2, NULL, info->type); transposeinfo -> bufsize = info -> bufsize; /* a rowvector from canonical column vector * is in canonical form, too! */ transposeinfo -> canonical = info -> canonical; transposeinfo -> dims[0] = 1; transposeinfo -> dims[1] = info->dims[0]; transposeinfo -> offset = info->offset; transposeinfo -> pitches[0] = info->pitches[0]*info->dims[0]; transposeinfo -> pitches[1] = info->pitches[0]; } else { Tcl_SetResult(interp, "Dimension index out of range for columnvector", NULL); goto cleanobj; } } else if (info->nDim == 2 && info -> dims[0] == 1) { /* rowvector, to be transposed back to columnvector */ if ((dim1 == 0 && dim2 ==1) || (dim1 == 1 && dim2 == 0)) { transposeinfo = CreateNumArrayInfo(1, NULL, info->type); transposeinfo -> bufsize = info -> bufsize; transposeinfo -> canonical = info -> canonical; transposeinfo -> dims[0] = info->dims[1]; transposeinfo -> offset = info->offset; transposeinfo -> pitches[0] = info->pitches[1]; } else { Tcl_SetResult(interp, "Dimension index out of range for columnvector", NULL); goto cleanobj; } } else { /* General case. * Swap dims, offsets, and pitches for the given dimensions */ if (dim1 < 0 || dim1 >= info->nDim || dim2 < 0 || dim2 >= info->nDim) { Tcl_SetResult(interp, "Dimension index out of range", NULL); goto cleanobj; } transposeinfo = DupNumArrayInfo(info); transposeinfo -> dims[dim1] = info -> dims[dim2]; transposeinfo -> dims[dim2] = info -> dims[dim1]; transposeinfo -> pitches[dim1] = info -> pitches[dim2]; transposeinfo -> pitches[dim2] = info -> pitches[dim1]; transposeinfo -> canonical = 0; } /* no error so far */ if (info -> type == NumArray_Complex128 && adjoint) { /* for complex values and if adjoint is requested, * copy data and conjugate values.*/ NumArrayInfo *conjinfo = CreateNumArrayInfo(transposeinfo->nDim, transposeinfo->dims, info->type); NumArraySharedBuffer *conjbuf = NumArrayNewSharedBuffer(conjinfo -> bufsize); NumArraySharedBuffer *srcbuf = naObj -> internalRep.twoPtrValue.ptr1; NumArrayIterator it; NumArray_Complex *bufptr = (NumArray_Complex *)NumArrayGetPtrFromSharedBuffer(conjbuf); NumArrayIteratorInit(transposeinfo, srcbuf, &it); for (; !NumArrayIteratorFinished(&it); NumArrayIteratorAdvance(&it)) { *bufptr++ = NumArray_ComplexConj(NumArrayIteratorDeRefComplex(&it)); } NumArraySharedBufferDecrRefcount(srcbuf); NumArraySetInternalRep(naObj, conjbuf, conjinfo); DeleteNumArrayInfo(transposeinfo); DeleteNumArrayInfo(info); } else { /* replace info in variable */ DeleteNumArrayInfo(info); naObj -> internalRep.twoPtrValue.ptr2 = transposeinfo; Tcl_InvalidateStringRep(naObj); } Tcl_SetObjResult(interp, naObj); return TCL_OK; /*cleaninfo: DeleteNumArrayInfo(transposeinfo); */ cleanobj: if (allocobj) Tcl_DecrRefCount(naObj); return TCL_ERROR; } int NumArraySliceCmd( ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { Tcl_Obj *naObj; NumArrayInfo *info, *sliceinfo; NumArraySharedBuffer* sharedbuffer; Tcl_Obj *result; if (objc != 3) { Tcl_WrongNumArgs(interp, 1, objv, "numarrayvalue slicelist"); return TCL_ERROR; } naObj = objv[1]; result = Tcl_NewObj(); if (Tcl_ConvertToType(interp, naObj, &NumArrayTclType) != TCL_OK) { goto cleanobj; } sharedbuffer = naObj ->internalRep.twoPtrValue.ptr1; info = naObj -> internalRep.twoPtrValue.ptr2; if (NumArrayInfoSlice(interp, info, objv[2], &sliceinfo) != TCL_OK) { goto cleanobj; } NumArraySetInternalRep(result, sharedbuffer, sliceinfo); Tcl_SetObjResult(interp, result); return TCL_OK; cleanobj: Tcl_DecrRefCount(result); return TCL_ERROR; } #define CONVERTER(TYPE) \ int NumArrayConv ## TYPE ## Cmd(\ ClientData dummy,\ Tcl_Interp *interp,\ int objc,\ Tcl_Obj *const *objv)\ {\ if (objc != 2) {\ Tcl_WrongNumArgs(interp, 1, objv, "numarray");\ return TCL_ERROR;\ }\ \ Tcl_Obj *result;\ Tcl_Obj *naObj = objv[1];\ \ if (NumArrayConvertToType(interp, naObj, NumArray_ ## TYPE, &result) != TCL_OK) {\ return TCL_ERROR;\ }\ Tcl_SetObjResult(interp, result);\ return TCL_OK;\ } MAP(CONVERTER, Int8, Uint8, Int16, Uint16, Int32, Uint32, Int64, Uint64, Float32, Float64, Complex64, Complex128, Bool) #undef CONVERTER /* createNumArraySharedBufferFromTypedList * * Expect a nested list representation compatible with info * Creates a matching memory buffer and copies/converts the data from * the nested list into the buffer. */ static int createNumArraySharedBufferFromTypedList(Tcl_Interp *interp, Tcl_Obj *list, NumArrayInfo const *info, NumArraySharedBuffer **sharedbuf) { /* reserve memory for data */ *sharedbuf = NumArrayNewSharedBuffer(info->bufsize); char *bufptr = NumArrayGetPtrFromSharedBuffer(*sharedbuf); NumArraySharedBufferIncrRefcount(*sharedbuf); int nDim = info->nDim; /* in a canonical array, the innermost pitch * is space between adjacent elements */ index_t pitch = info -> pitches[nDim-1]; /* loop over data. Create a counter */ index_t *counter = ckalloc(sizeof(index_t)*nDim); int d; for (d=0; d<nDim; d++) { counter[d]=0; } /* matroska is a counting structure for the nested list representation * Its first element points to the whole array, and successive elements are * pointers to the current sublist of the parent list for this index */ Tcl_Obj **matroska; /* set all list pointers to first branch of nested structs */ matroska = ckalloc(sizeof(Tcl_Obj*)*(nDim+1)); matroska[0] = list; for (d=1; d<=nDim; d++) { if (Tcl_ListObjIndex(interp, matroska[d-1], 0, &matroska[d]) != TCL_OK) { goto cleanbuffer; } } /* Loop over all elements. * skip copying if this is the empty element */ while (info->dims[0] != 0) { /* store the current element to shared buffer */ switch (info->type) { case NumArray_Int: { Tcl_WideInt temp; if (Tcl_GetWideIntFromObj(interp, matroska[nDim], &temp) != TCL_OK) { goto cleanbuffer; } *(NaWideInt *) bufptr = temp; bufptr += pitch; break; } case NumArray_Float64: if (myTcl_GetDoubleFromObj(interp, matroska[nDim], (double *)bufptr) != TCL_OK) { goto cleanbuffer; } bufptr += pitch; break; case NumArray_Complex128: if (NumArray_GetComplexFromObj(interp, matroska[nDim], (NumArray_Complex *)bufptr) != TCL_OK) { goto cleanbuffer; } bufptr += pitch; break; default: /* Error */ printf("Unknown data type\n"); goto cleanbuffer; } /* end of switch datatype */ /* advance the count * count indices one up, handle carry */ for (d=nDim-1; d>=0; d--) { /* advance this by one */ counter[d]++; /* check for carry */ if (counter[d] == info->dims[d]) { counter[d] = 0; } else { break; } } /* when all counters are back to zero, * we are finished */ if (d<0) break; /* recalculate matroska list for wrapped-over counters */ for (d=d+1; d<=nDim; d++) { int dlength; if (Tcl_ListObjLength(interp, matroska[d-1], &dlength) != TCL_OK) { goto cleanbuffer; } if (dlength != info->dims[d-1]) { Tcl_SetResult(interp, "Non-matching dimensions in nested list", NULL); goto cleanbuffer; } if (Tcl_ListObjIndex(interp, matroska[d-1], counter[d-1], &matroska[d]) != TCL_OK) { goto cleanbuffer; } } } ckfree(matroska); ckfree(counter); return TCL_OK; cleanbuffer: /* in case of error release the intermediate structures */ ckfree(matroska); ckfree(counter); NumArraySharedBufferDecrRefcount(*sharedbuf); return TCL_ERROR; } static int SetNumArrayFromAny(Tcl_Interp *interp, Tcl_Obj *objPtr) { /* Parse nested list of numeric values */ NumArrayInfo* info; NumArraySharedBuffer *sharedbuf; Tcl_Obj *dimlist; NumArrayType dtype=NumArray_NoType; /* parse dimensions and update info */ if (ScanNumArrayDimensionsFromValue(interp, objPtr, &dimlist, &dtype) != TCL_OK) { return TCL_ERROR; } while (dtype != NumArray_NoType) { if (CreateNumArrayInfoFromList(interp, dimlist, dtype, &info) != TCL_OK) { goto cleanlist; } int result = createNumArraySharedBufferFromTypedList(interp, objPtr, info, &sharedbuf); if (result == TCL_OK) { /* This conversion round was successful */ TclFreeIntRep(objPtr); objPtr -> internalRep.twoPtrValue.ptr1 = sharedbuf; objPtr -> internalRep.twoPtrValue.ptr2 = info; objPtr -> typePtr = &NumArrayTclType; Tcl_DecrRefCount(dimlist); return TCL_OK; } /* If this was unsuccessful, try a higher dtype */ dtype = NumArray_UpcastType(dtype); DeleteNumArrayInfo(info); } cleanlist: Tcl_DecrRefCount(dimlist); return TCL_ERROR; } static void UpdateStringOfNumArray(Tcl_Obj *naPtr) { Tcl_DString srep; NumArrayInfo* info = naPtr -> internalRep.twoPtrValue.ptr2; char *buffer=NULL; int nDim = info -> nDim; index_t *counter = ckalloc(sizeof(index_t)*nDim); char **baseptr = ckalloc(sizeof(char*)*nDim); int d=0; /* d is the dimension counter */ /* handle case of empty array */ if (info->dims[0]==0) { naPtr -> length = 0; naPtr -> bytes = ckalloc(1); *(naPtr -> bytes) = '\0'; ckfree(counter); ckfree(baseptr); return; } buffer = NumArrayGetPtrFromObj(NULL, naPtr); /* can't fail */ Tcl_DStringInit(&srep); /* set all counters to initial value */ for (d=0; d<nDim; d++) { counter[d] = 0; } baseptr[0] = buffer; for (d=1; d<nDim; d++) { baseptr[d] = baseptr[d-1]; } while (1) { /* count from backwards * for every counter that is 0, start a list */ for (d=nDim-1; d>0; d--) { if (counter[d] == 0) { Tcl_DStringStartSublist(&srep); } else { break; } } /* Print this element */ switch (info -> type) { /* handle integers */ case NumArray_Int: { char intbuf[NA_INTSPACE+MAX_SUFFIX]; int64_t el = *(NaWideInt *) (baseptr[nDim-1]); int len = format_int64(el, intbuf); Tcl_DStringAppendElement(&srep, intbuf); break; } case NumArray_Bool: { char intbuf[NA_INTSPACE+MAX_SUFFIX]; uint64_t el = *(int *) (baseptr[nDim-1]); int len = format_bool(el, intbuf); Tcl_DStringAppendElement(&srep, intbuf); break; } case NumArray_Int8: { char intbuf[NA_INTSPACE+MAX_SUFFIX]; int64_t el = *(int8_t *) (baseptr[nDim-1]); int len = format_int64(el, intbuf); strncpy(intbuf+len, "i8", MAX_SUFFIX); Tcl_DStringAppendElement(&srep, intbuf); break; } case NumArray_Uint8: { char intbuf[NA_INTSPACE+MAX_SUFFIX]; uint64_t el = *(uint8_t *) (baseptr[nDim-1]); int len = format_uint64(el, intbuf); strncpy(intbuf+len, "u8", MAX_SUFFIX); Tcl_DStringAppendElement(&srep, intbuf); break; } case NumArray_Int16: { char intbuf[NA_INTSPACE+MAX_SUFFIX]; int64_t el = *(int16_t *) (baseptr[nDim-1]); int len = format_int64(el, intbuf); strncpy(intbuf+len, "i16", MAX_SUFFIX); Tcl_DStringAppendElement(&srep, intbuf); break; } case NumArray_Uint16: { char intbuf[NA_INTSPACE+MAX_SUFFIX]; uint64_t el = *(uint16_t *) (baseptr[nDim-1]); int len = format_uint64(el, intbuf); strncpy(intbuf+len, "u16", MAX_SUFFIX); Tcl_DStringAppendElement(&srep, intbuf); break; } case NumArray_Int32: { char intbuf[NA_INTSPACE+MAX_SUFFIX]; int64_t el = *(int32_t *) (baseptr[nDim-1]); int len = format_int64(el, intbuf); strncpy(intbuf+len, "i32", MAX_SUFFIX); Tcl_DStringAppendElement(&srep, intbuf); break; } case NumArray_Uint32: { char intbuf[NA_INTSPACE+MAX_SUFFIX]; uint64_t el = *(uint32_t *) (baseptr[nDim-1]); int len = format_uint64(el, intbuf); strncpy(intbuf+len, "u32", MAX_SUFFIX); Tcl_DStringAppendElement(&srep, intbuf); break; } case NumArray_Int64: { char intbuf[NA_INTSPACE+MAX_SUFFIX]; int64_t el = *(int64_t *) (baseptr[nDim-1]); int len = format_int64(el, intbuf); strncpy(intbuf+len, "i64", MAX_SUFFIX); Tcl_DStringAppendElement(&srep, intbuf); break; } case NumArray_Uint64: { char intbuf[NA_INTSPACE+MAX_SUFFIX]; uint64_t el = *(uint64_t *) (baseptr[nDim-1]); int len = format_uint64(el, intbuf); strncpy(intbuf+len, "u64", MAX_SUFFIX); Tcl_DStringAppendElement(&srep, intbuf); break; } case NumArray_Float32: { char dblbuf[TCL_DOUBLE_SPACE+1]; float elptr = *(float *) (baseptr[nDim-1]); Tcl_PrintDouble(NULL, elptr, dblbuf); Tcl_DStringAppendElement(&srep, dblbuf); Tcl_DStringAppend(&srep, "f", 1); break; } case NumArray_Float64: { char dblbuf[TCL_DOUBLE_SPACE]; double *elptr = (double *) (baseptr[nDim-1]); Tcl_PrintDouble(NULL, *elptr, dblbuf); Tcl_DStringAppendElement(&srep, dblbuf); break; } case NumArray_Complex128: { char cplxbuf[NUMARRAY_COMPLEX_SPACE]; NumArray_Complex *elptr = (NumArray_Complex *) (baseptr[nDim-1]); NumArray_PrintComplex(*elptr, cplxbuf); Tcl_DStringAppendElement(&srep, cplxbuf); break; } default: printf("Error: unknown data type %d", info -> type); } /* count indices one up, handle carry */ for (d=nDim-1; d>=0; d--) { /* advance this by one */ counter[d]++; baseptr[d]+=info->pitches[d]; /* check for carry */ if (counter[d] == info->dims[d]) { counter[d] = 0; if (d!=0) Tcl_DStringEndSublist(&srep); } else { break; } } /* when all counters are back to zero, */ /* we are finished */ if (d<0) break; /* recalculate indices for wrapped-over counters */ for (d=d+1; d<nDim; d++) { baseptr[d] = baseptr[d-1]; } } /* there should be a way to move */ /* the pointer from DString to Tcl_Obj, here use memcpy */ naPtr -> length = Tcl_DStringLength(&srep); naPtr -> bytes = Tcl_Alloc(naPtr->length+1); memcpy(naPtr -> bytes, Tcl_DStringValue(&srep), naPtr -> length); naPtr -> bytes[naPtr->length] = '\0'; /* cleanup temp memory */ Tcl_DStringFree(&srep); ckfree(baseptr); ckfree(counter); } #ifdef LIST_INJECT static int SetListFromNumArray(Tcl_Interp *interp, Tcl_Obj *objPtr) { /* check if we got a NumArray as input * if not, handle by original proc * likewise, if there is */ if (objPtr -> typePtr != &NumArrayTclType || objPtr -> bytes) { return listSetFromAny(interp, objPtr); } DEBUGPRINTF(("Converting NumArray to list\n")); /* extract internal rep */ NumArrayInfo *info = objPtr -> internalRep.twoPtrValue.ptr2; NumArraySharedBuffer *sharedbuf = objPtr -> internalRep.twoPtrValue.ptr1; /* First check for the empty info. This must be handled by the original * proc, because it is the only way to create an empty list * without getting back a reference to the empty object */ if (ISEMPTYINFO(info)) { return listSetFromAny(interp, objPtr); } /* Create a new object the internal rep of which * is then duplicated to objPtr */ Tcl_Obj * result = Tcl_NewListObj(0, NULL); if (info -> nDim == 1) { /* 1d-case: Construct list of values */ NumArrayIterator it; NumArrayIteratorInit(info, sharedbuf, &it); switch (info->type) { case NumArray_Int: for (; !NumArrayIteratorFinished(&it); NumArrayIteratorAdvance(&it)) { long value = NumArrayIteratorDeRefInt(&it); Tcl_ListObjAppendElement(interp, result, Tcl_NewLongObj(value)); } break; case NumArray_Float64: for (; !NumArrayIteratorFinished(&it); NumArrayIteratorAdvance(&it)) { double value = NumArrayIteratorDeRefDouble(&it); Tcl_ListObjAppendElement(interp, result, Tcl_NewDoubleObj(value)); } break; case NumArray_Complex128: for (; !NumArrayIteratorFinished(&it); NumArrayIteratorAdvance(&it)) { NumArray_Complex value = NumArrayIteratorDeRefComplex(&it); Tcl_ListObjAppendElement(interp, result, NumArray_NewComplexObj(value)); } break; default: Tcl_SetResult(interp, "Unknown datatype (shimmer to list)", NULL); return TCL_ERROR; } } else { /* multidimensional case: create slices for each * row and add to list */ index_t i; index_t nelem = info -> dims[0]; for (i=0; i< nelem; i++) { Tcl_Obj *slice=Tcl_NewObj(); NumArrayInfo *sliceinfo=DupNumArrayInfo(info); NumArrayInfoSlice1Axis(NULL, sliceinfo, 0, i, i, 1); NumArrayStripSingletonDimensions(sliceinfo); NumArraySetInternalRep(slice, sharedbuf, sliceinfo); Tcl_ListObjAppendElement(interp, result, slice); } } FreeNumArrayInternalRep(objPtr); /* now transfer the internal rep from the list obj */ /* objPtr -> internalRep = result -> internalRep; */ if (result -> typePtr) { /* copy the internal rep from result into objPtr, * unless it is a pure string (empty object) */ result -> typePtr -> dupIntRepProc(result, objPtr); } else { objPtr -> typePtr = result -> typePtr; /* necessary in case of empty string. * Lists set it in dupIntRepProc. */ } Tcl_DecrRefCount(result); return TCL_OK; } #endif void NumArrayIncrRefcount(Tcl_Obj *naObj) { if (naObj -> typePtr == &NumArrayTclType) { NumArraySharedBuffer *sharedbuf = naObj -> internalRep.twoPtrValue.ptr1; NumArraySharedBufferIncrRefcount(sharedbuf); } } void NumArrayDecrRefcount(Tcl_Obj *naObj) { if (naObj -> typePtr == &NumArrayTclType) { NumArraySharedBuffer *sharedbuf = naObj -> internalRep.twoPtrValue.ptr1; NumArraySharedBufferDecrRefcount(sharedbuf); } } /* sign function */ static inline int isign(int x) { if (x==0) return 0; if (x<0) return -1; return 1; } static inline double fsign(double x) { /* NaN is a sign in it's own right */ if (x!=x) return x; if (x<0) return -1.0; if (x>0) return 1.0; return 0.0; } /* Implement elementwise binary operators */ #define CMD NumArrayPlus #define OPINT *result = op1 + op2; #define OPDBL *result = op1 + op2; #define OPCPLX *result = NumArray_ComplexAdd(op1, op2); #include "binop.h" #define CMD NumArrayMinus #define OPINT *result = op1 - op2; #define OPDBL *result = op1 - op2; #define OPCPLX *result = NumArray_ComplexSubtract(op1, op2); #include "binop.h" #define CMD NumArrayTimes #define OPINT *result = op1 * op2; #define OPDBL *result = op1 * op2; #define OPCPLX *result = NumArray_ComplexMultiply(op1, op2); #include "binop.h" #define CMD NumArrayLdivide #define OPINT if (op1!=0) { \ *result = op2 / op1; \ } else { \ *resultObj=Tcl_NewStringObj("Integer division by zero", -1);\ return TCL_ERROR;\ } #define OPDBL *result = op2 / op1; #define OPCPLX *result = NumArray_ComplexDivide(op2, op1); #include "binop.h" #define CMD NumArrayRdivide #define OPINT if (op2!=0) { \ *result = op1 / op2; \ } else { \ *resultObj=Tcl_NewStringObj("Integer division by zero", -1);\ return TCL_ERROR;\ } #define OPDBL *result = op1 / op2; #define OPCPLX *result = NumArray_ComplexDivide(op1, op2); #include "binop.h" #define CMD NumArrayReminder #define OPINT if (op2!=0) { \ *result = op1 % op2; \ } else { \ *resultObj=Tcl_NewStringObj("Integer division by zero", -1);\ return TCL_ERROR;\ } #include "binop.h" #define CMD NumArrayGreater #define OPINT *result = (op1>op2); #define OPDBL *result = (op1>op2); #define DBLRES NaWideInt #include "binop.h" #define CMD NumArrayLesser #define OPINT *result = (op1<op2); #define OPDBL *result = (op1<op2); #define DBLRES NaWideInt #include "binop.h" #define CMD NumArrayGreaterEqual #define OPINT *result = (op1>=op2); #define OPDBL *result = (op1<=op2); #define DBLRES NaWideInt #include "binop.h" #define CMD NumArrayLesserEqual #define OPINT *result = (op1<=op2); #define OPDBL *result = (op1<=op2); #define DBLRES NaWideInt #include "binop.h" #define CMD NumArrayEqual #define OPINT *result = (op1==op2); #define OPDBL *result = (op1==op2); #define DBLRES NaWideInt #define OPCPLX *result = ((op1.re==op2.re) && (op1.im==op2.im)) #define CPLXRES NaWideInt #include "binop.h" #define CMD NumArrayUnequal #define OPINT *result = (op1!=op2); #define OPDBL *result = (op1!=op2); #define DBLRES NaWideInt #define OPCPLX *result = ((op1.re!=op2.re) || (op1.im!=op2.im)) #define CPLXRES NaWideInt #include "binop.h" /* boolean operators */ #define CMD NumArrayNot #define INTOP *result = !op; #define INTRES NaWideInt #include "uniop.h" #define CMD NumArrayAnd #define OPINT *result = (op1 && op2); #include "binop.h" #define CMD NumArrayOr #define OPINT *result = (op1 || op2); #include "binop.h" #define CMD NumArrayPow #define OPINT *result = pow(op1,op2); #define INTRES double #define OPDBL *result = pow(op1,op2); #define OPCPLX *result = NumArray_ComplexPow(op1,op2); #include "binop.h" #define CMD NumArrayMin #define OPINT *result = op1 < op2 ? op1 : op2; #define OPDBL *result = op1 < op2 ? op1 : op2; #include "binop.h" #define CMD NumArrayMax #define OPINT *result = op1 > op2 ? op1 : op2; #define OPDBL *result = op1 > op2 ? op1 : op2; #include "binop.h" /* Implement elementwise binary assignment operators */ #define CMD NumArraySetAssignCmd #define OPINT *result = op; #define OPDBL *result = op; #define OPCPLX *result = op; #include "assignop.h" #define CMD NumArrayPlusAssignCmd #define OPINT *result += op; #define OPDBL *result += op; #define OPCPLX *result = NumArray_ComplexAdd(*result, op); #include "assignop.h" #define CMD NumArrayMinusAssignCmd #define OPINT *result -= op; #define OPDBL *result -= op; #define OPCPLX *result = NumArray_ComplexSubtract(*result, op); #include "assignop.h" #define CMD NumArrayTimesAssignCmd #define OPINT *result *= op; #define OPDBL *result *= op; #define OPCPLX *result = NumArray_ComplexMultiply(*result, op); #include "assignop.h" #define CMD NumArrayLdivideAssignCmd #define OPINT if (*result!=0) { \ *result = op / *result; \ } else { \ Tcl_SetResult(interp, "Integer division by zero", NULL);\ return TCL_ERROR;\ } #define OPDBL *result = op / (*result); #define OPCPLX *result = NumArray_ComplexDivide(op, *result); #include "assignop.h" #define CMD NumArrayRdivideAssignCmd #define OPINT if (op!=0) { \ *result /= op; \ } else { \ Tcl_SetResult(interp, "Integer division by zero", NULL);\ return TCL_ERROR;\ } #define OPDBL *result /= op; #define OPCPLX *result = NumArray_ComplexDivide(op, *result); #include "assignop.h" #define CMD NumArrayPowAssignCmd #define OPDBL *result = pow(*result,op); #include "assignop.h" /* Implement unary functions/operators */ /* Data type conversion */ #define CMD NumArrayConvInt #define INTRES NaWideInt #define INTOP *result = op; #define DBLRES NaWideInt #define DBLOP *result = (NaWideInt)op; #include "uniop.h" #define CMD NumArrayConvDouble #define INTRES double #define INTOP *result = op; #define DBLRES double #define DBLOP *result = op; #include "uniop.h" #define CMD NumArrayConvComplex #define INTRES NumArray_Complex #define INTOP *result = NumArray_mkComplex(op, 0.0); #define DBLRES NumArray_Complex #define DBLOP *result = NumArray_mkComplex(op, 0.0); #define CPLXRES NumArray_Complex #define CPLXOP *result = op; #include "uniop.h" #define CMD NumArrayAbs #define INTRES NaWideInt #define INTOP *result = labs(op); #define DBLRES double #define DBLOP *result = fabs(op); #define CPLXRES double #define CPLXOP *result = NumArray_ComplexAbs(op); #include "uniop.h" #define CMD NumArraySign #define INTRES NaWideInt #define INTOP *result = isign(op); #define DBLRES double #define DBLOP *result = fsign(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexSign(op); #include "uniop.h" #define CMD NumArrayArg #define INTRES NaWideInt #define INTOP *result = 0; #define DBLRES double #define DBLOP *result = 0.0; #define CPLXRES double #define CPLXOP *result = NumArray_ComplexArg(op); #include "uniop.h" #define CMD NumArrayConj #define INTRES NaWideInt #define INTOP *result = op; #define DBLRES double #define DBLOP *result = op; #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexConj(op); #include "uniop.h" #define CMD NumArrayReal #define INTRES NaWideInt #define INTOP *result = op; #define DBLRES double #define DBLOP *result = op; #define CPLXRES double #define CPLXOP *result = op.re; #include "uniop.h" #define CMD NumArrayImag #define INTRES NaWideInt #define INTOP *result = 0; #define DBLRES double #define DBLOP *result = 0.0; #define CPLXRES double #define CPLXOP *result = op.im; #include "uniop.h" #define CMD NumArrayNeg #define INTRES NaWideInt #define INTOP *result = -op; #define DBLRES double #define DBLOP *result = -op; #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexNeg(op); #include "uniop.h" #define CMD NumArraySin #define INTRES double #define DBLRES double #define INTOP DBLOP #define DBLOP *result = sin(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexSin(op); #include "uniop.h" #define CMD NumArrayCos #define INTRES double #define DBLRES double #define INTOP DBLOP #define DBLOP *result = cos(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexCos(op); #include "uniop.h" #define CMD NumArrayTan #define INTRES double #define DBLRES double #define INTOP DBLOP #define DBLOP *result = tan(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexTan(op); #include "uniop.h" #define CMD NumArrayExp #define INTRES double #define DBLRES double #define INTOP DBLOP #define DBLOP *result = exp(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexExp(op); #include "uniop.h" #define CMD NumArrayLog #define INTRES double #define DBLRES double #define INTOP DBLOP #define DBLOP *result = log(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexLog(op); #include "uniop.h" #define CMD NumArrayLog10 #define INTRES double #define DBLRES double #define INTOP DBLOP #define DBLOP *result = log10(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexLog(op); #include "uniop.h" #define CMD NumArraySqrt #define INTRES double #define DBLRES double #define INTOP DBLOP #define DBLOP *result = sqrt(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexSqrt(op); #include "uniop.h" #define CMD NumArraySinh #define INTRES double #define DBLRES double #define INTOP DBLOP #define DBLOP *result = sinh(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexSinh(op); #include "uniop.h" #define CMD NumArrayCosh #define INTRES double #define DBLRES double #define INTOP DBLOP #define DBLOP *result = cosh(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexCosh(op); #include "uniop.h" #define CMD NumArrayTanh #define INTRES double #define DBLRES double #define INTOP DBLOP #define DBLOP *result = tanh(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexTanh(op); #include "uniop.h" #define CMD NumArrayAsin #define INTRES double #define DBLRES double #define INTOP DBLOP #define DBLOP *result = asin(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexAsin(op); #include "uniop.h" #define CMD NumArrayAcos #define INTRES double #define DBLRES double #define INTOP DBLOP #define DBLOP *result = acos(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexAcos(op); #include "uniop.h" #define CMD NumArrayAtan #define INTRES double #define DBLRES double #define INTOP DBLOP #define DBLOP *result = atan(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexAtan(op); #include "uniop.h" #define CMD NumArrayAsinh #define INTRES double #define DBLRES double #define INTOP DBLOP #define DBLOP *result = asinh(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexAsinh(op); #include "uniop.h" #define CMD NumArrayAcosh #define INTRES double #define DBLRES double #define INTOP DBLOP #define DBLOP *result = acosh(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexAcosh(op); #include "uniop.h" #define CMD NumArrayAtanh #define INTRES double #define DBLRES double #define INTOP DBLOP #define DBLOP *result = atanh(op); #define CPLXRES NumArray_Complex #define CPLXOP *result = NumArray_ComplexAtanh(op); #include "uniop.h" /* Implement reductions with optional dimension */ #define CMD NumArraySum #define INIT ; #define FIRST accum=op; #define INTOP accum+=op; #define DBLOP accum+=op; #define CPLXOP accum=NumArray_ComplexAdd(accum, op); #define RETURN ; #include "reduction.h" #define CMD NumArrayMean #define INIT ; #define FIRST accum=op; #define INTRES double #define INTOP accum+=op; #define DBLOP accum+=op; #define CPLXOP accum=NumArray_ComplexAdd(accum, op); #define RETURN accum /= nlength; #define CPLXRETURN accum.re /= nlength; accum.im /= nlength; #include "reduction.h" #define CMD NumArrayAxisMin #define INIT ; #define FIRST accum=op; #define INTOP if (op < accum) accum=op; #define DBLOP if (op < accum) accum=op; #define RETURN ; #include "reduction.h" #define CMD NumArrayAxisMax #define INIT ; #define FIRST accum=op; #define INTOP if (op > accum) accum=op; #define DBLOP if (op > accum) accum=op; #define RETURN ; #include "reduction.h" #define CMD NumArrayStd #define INIT double first; double sum=0; #define FIRST accum=0; first=op; #define DBLOP accum+=(op-first)*(op-first); sum+=(op-first); #define INTOP DBLOP #define INTRES double #define RETURN accum = (nlength==1)?0:sqrt(accum/(nlength-1) - (sum*sum/nlength)/(nlength-1)); #include "reduction.h" #define CMD NumArrayStd1 #define INIT double first; double sum=0; #define FIRST accum=0; first=op; #define DBLOP accum+=(op-first)*(op-first); sum+=(op-first); #define INTOP DBLOP #define INTRES double #define RETURN accum = sqrt(accum/nlength - (sum/nlength)*(sum/nlength)); #include "reduction.h" #define CMD NumArrayAll #define INIT ; #define FIRST if (op) { accum=1; } else { accum=0; } #define INTOP if (!op) { accum=0; break; } #define RETURN ; #include "reduction.h" #define CMD NumArrayAny #define INIT ; #define FIRST if (!op) { accum=0; } else { accum=1; } #define INTOP if (op) { accum=1; break; } #define RETURN ; #include "reduction.h" int Vectcl_Init(Tcl_Interp* interp) { if (interp == 0) return TCL_ERROR; if (Tcl_InitStubs(interp, TCL_VERSION, 0) == NULL) { return TCL_ERROR; } Tcl_PkgProvide(interp, PACKAGE_NAME, PACKAGE_VERSION); VecTclNumArrayObjType = &NumArrayTclType; Tcl_RegisterObjType(&NumArrayTclType); myTcl_MakeEnsemble(interp, "::numarray", "::numarray", implementationMap); /* Initialize complex data type */ if (Complex_Init(interp) != TCL_OK) { return TCL_ERROR; } /* Initialize expression parser */ if (Vmparser_Init(interp) != TCL_OK) { return TCL_ERROR; } /* casting away const is intended for the dirty hack */ tclListType = (Tcl_ObjType *) Tcl_GetObjType("list"); tclDoubleType = Tcl_GetObjType("double"); tclIntType = Tcl_GetObjType("int"); #ifndef TCL_WIDE_INT_IS_LONG tclWideIntType = Tcl_GetObjType("wideInt"); #endif #ifdef LIST_INJECT /* copy list object proc from list type */ listSetFromAny = tclListType -> setFromAnyProc; /* inject list conversion code * WARNING may break Tcl */ tclListType->setFromAnyProc = SetListFromNumArray; Tcl_RegisterObjType(tclListType); #endif return TCL_OK; }
25.667279
147
0.683311
[ "object", "shape", "vector" ]
ca36ab63c7baf7ecf8f03eaca86a2939f65f9540
6,170
h
C
molecular/util/Mesh.h
cmdrf/molecular-util
20c25140da377525f2699147a56569c0634fbebf
[ "MIT" ]
null
null
null
molecular/util/Mesh.h
cmdrf/molecular-util
20c25140da377525f2699147a56569c0634fbebf
[ "MIT" ]
null
null
null
molecular/util/Mesh.h
cmdrf/molecular-util
20c25140da377525f2699147a56569c0634fbebf
[ "MIT" ]
null
null
null
/* Mesh.h MIT License Copyright (c) 2018-2019 Fabian Herb 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. */ #ifndef MOLECULAR_MESH_H #define MOLECULAR_MESH_H #include "BufferInfo.h" #include <molecular/util/Hash.h> #include <molecular/util/Vector3.h> #include <molecular/util/Vector4.h> #include <cassert> #include <unordered_map> #include <vector> namespace molecular { namespace util { /// Extract scalar type and array size from commonly used vector types template<class T> struct AttributeTraits {}; /// Specialization of AttributeTraits for float template<> struct AttributeTraits<float> { static const VertexAttributeInfo::Type type = VertexAttributeInfo::kFloat; static const unsigned int components = 1; }; /// Specialization of AttributeTraits for Vector2 template<> struct AttributeTraits<Vector2> { static const VertexAttributeInfo::Type type = VertexAttributeInfo::kFloat; static const unsigned int components = 2; }; /// Specialization of AttributeTraits for Vector3 template<> struct AttributeTraits<Vector3> { static const VertexAttributeInfo::Type type = VertexAttributeInfo::kFloat; static const unsigned int components = 3; }; /// Specialization of AttributeTraits for Vector4 template<> struct AttributeTraits<Vector4> { static const VertexAttributeInfo::Type type = VertexAttributeInfo::kFloat; static const unsigned int components = 4; }; /// Specialization of AttributeTraits for IntVector4 template<> struct AttributeTraits<IntVector4> { static const VertexAttributeInfo::Type type = VertexAttributeInfo::kInt32; static const unsigned int components = 4; }; /// Intermediate representation of mesh data class Mesh { public: /// Single attribute buffer class Attribute { friend class Mesh; public: /// Get attribute data template<typename T> const T* GetData() const { assert(mNumComponents == AttributeTraits<T>::components); assert(mType == AttributeTraits<T>::type); return static_cast<const T*>(static_cast<const void*>(mData.data())); } /// Get attribute data template<typename T> T* GetData() { assert(mNumComponents == AttributeTraits<T>::components); assert(mType == AttributeTraits<T>::type); return static_cast<T*>(static_cast<void*>(mData.data())); } /// Set attribute data from raw data void SetData(VertexAttributeInfo::Type type, unsigned int components, const void* data, size_t size) { mType = type; mNumComponents = components; auto begin = static_cast<const uint8_t*>(data); mData.assign(begin, begin + size); } /// Get pointer to raw data /** Use GetData() to get a typed representation. */ const void* GetRawData() const {return mData.data();} /// Get data size in bytes size_t GetRawSize() const {return mData.size();} VertexAttributeInfo::Type GetType() const {return mType;} unsigned int GetNumComponents() const {return mNumComponents;} private: VertexAttributeInfo::Type mType; unsigned int mNumComponents; std::vector<uint8_t> mData; }; /// Construct from number of vertices /** @param numVertices Number of vertices. NOT number of indices. */ explicit Mesh(unsigned int numVertices, IndexBufferInfo::Mode mode = IndexBufferInfo::Mode::kTriangles) : mNumVertices(numVertices), mMode(mode) {} Mesh(const Mesh&) = delete; Mesh(Mesh&&) = default; template<typename T> void SetAttributeData(Hash name, const T* data, size_t count) { assert(count == mNumVertices); Attribute attr; attr.mType = AttributeTraits<T>::type; attr.mNumComponents = AttributeTraits<T>::components; auto begin = static_cast<const uint8_t*>(static_cast<const void*>(data)); attr.mData.assign(begin, begin + count * sizeof(T)); mAttributes.emplace(name, std::move(attr)); } /// Set attribute data from raw data void SetAttributeData(Hash name, VertexAttributeInfo::Type type, unsigned int components, const void* data, size_t size) { Attribute attr; attr.mType = type; attr.mNumComponents = components; auto begin = static_cast<const uint8_t*>(data); attr.mData.assign(begin, begin + size); mAttributes.emplace(name, std::move(attr)); } std::vector<uint32_t>& GetIndices() {return mIndices;} const std::vector<uint32_t>& GetIndices() const {return mIndices;} IndexBufferInfo::Mode GetMode() const {return mMode;} void SetMode(IndexBufferInfo::Mode mode) {mMode = mode;} const std::string& GetMaterial() const {return mMaterial;} void SetMaterial(const std::string& material) {mMaterial = material;} unsigned int GetNumVertices() const {return mNumVertices;} const std::unordered_map<Hash, Attribute>& GetAttributes() const {return mAttributes;} std::unordered_map<Hash, Attribute>& GetAttributes() {return mAttributes;} const Attribute& GetAttribute(Hash name) const {return mAttributes.at(name);} Attribute& GetAttribute(Hash name) {return mAttributes.at(name);} void RemoveAttribute(Hash name) {mAttributes.erase(name);} private: std::vector<uint32_t> mIndices; unsigned int mNumVertices; IndexBufferInfo::Mode mMode; std::string mMaterial; std::unordered_map<Hash, Attribute> mAttributes; }; /// Collection of meshes using MeshSet = std::vector<Mesh>; } } #endif // MOLECULAR_MESH_H
30.245098
121
0.753323
[ "mesh", "vector" ]
ca396c9e0673f3114070d20c8e1fa4c1f4b11cfd
2,933
h
C
Win32.Carberp/all source/BJWJ/include/dom/nsIDOM3DocumentEvent.h
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
2
2021-02-04T06:47:45.000Z
2021-07-28T10:02:10.000Z
Win32.Carberp/all source/BlackJoeWhiteJoe/include/dom/nsIDOM3DocumentEvent.h
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
null
null
null
Win32.Carberp/all source/BlackJoeWhiteJoe/include/dom/nsIDOM3DocumentEvent.h
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
null
null
null
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/mozilla-1.9.1-win32-xulrunner/build/dom/public/idl/events/nsIDOM3DocumentEvent.idl */ #ifndef __gen_nsIDOM3DocumentEvent_h__ #define __gen_nsIDOM3DocumentEvent_h__ #ifndef __gen_domstubs_h__ #include "domstubs.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIDOM3DocumentEvent */ #define NS_IDOM3DOCUMENTEVENT_IID_STR "090ecc19-b7cb-4f47-ae47-ed68d4926249" #define NS_IDOM3DOCUMENTEVENT_IID \ {0x090ecc19, 0xb7cb, 0x4f47, \ { 0xae, 0x47, 0xed, 0x68, 0xd4, 0x92, 0x62, 0x49 }} /** * The nsIDOMDocumentEvent interface is the interface to the event * factory method on a DOM document object. * * For more information on this interface please see * http://www.w3.org/TR/DOM-Level-3-Events/ */ class NS_NO_VTABLE NS_SCRIPTABLE nsIDOM3DocumentEvent : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOM3DOCUMENTEVENT_IID) /* nsIDOMEventGroup createEventGroup (); */ NS_SCRIPTABLE NS_IMETHOD CreateEventGroup(nsIDOMEventGroup **_retval NS_OUTPARAM) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOM3DocumentEvent, NS_IDOM3DOCUMENTEVENT_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDOM3DOCUMENTEVENT \ NS_SCRIPTABLE NS_IMETHOD CreateEventGroup(nsIDOMEventGroup **_retval NS_OUTPARAM); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDOM3DOCUMENTEVENT(_to) \ NS_SCRIPTABLE NS_IMETHOD CreateEventGroup(nsIDOMEventGroup **_retval NS_OUTPARAM) { return _to CreateEventGroup(_retval); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDOM3DOCUMENTEVENT(_to) \ NS_SCRIPTABLE NS_IMETHOD CreateEventGroup(nsIDOMEventGroup **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->CreateEventGroup(_retval); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDOM3DocumentEvent : public nsIDOM3DocumentEvent { public: NS_DECL_ISUPPORTS NS_DECL_NSIDOM3DOCUMENTEVENT nsDOM3DocumentEvent(); private: ~nsDOM3DocumentEvent(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsDOM3DocumentEvent, nsIDOM3DocumentEvent) nsDOM3DocumentEvent::nsDOM3DocumentEvent() { /* member initializers and constructor code */ } nsDOM3DocumentEvent::~nsDOM3DocumentEvent() { /* destructor code */ } /* nsIDOMEventGroup createEventGroup (); */ NS_IMETHODIMP nsDOM3DocumentEvent::CreateEventGroup(nsIDOMEventGroup **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIDOM3DocumentEvent_h__ */
29.626263
158
0.785544
[ "object" ]
ca3c8cd7d88fb4eddd0c1c5e3e787413f6858326
6,695
h
C
webrtc/include/third_party/blink/public/web/web_plugin_container.h
yxlao/webrtc-cpp-sample
60bb1948f714693e7c8ade2fc6ffba218ea13859
[ "MIT" ]
null
null
null
webrtc/include/third_party/blink/public/web/web_plugin_container.h
yxlao/webrtc-cpp-sample
60bb1948f714693e7c8ade2fc6ffba218ea13859
[ "MIT" ]
null
null
null
webrtc/include/third_party/blink/public/web/web_plugin_container.h
yxlao/webrtc-cpp-sample
60bb1948f714693e7c8ade2fc6ffba218ea13859
[ "MIT" ]
null
null
null
/* * Copyright (C) 2009 Google Inc. All rights reserved. * Copyright (C) 2014 Opera Software ASA. 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 THIRD_PARTY_BLINK_PUBLIC_WEB_WEB_PLUGIN_CONTAINER_H_ #define THIRD_PARTY_BLINK_PUBLIC_WEB_WEB_PLUGIN_CONTAINER_H_ #include "third_party/blink/public/platform/web_common.h" #include "ui/gfx/geometry/point.h" #include "v8/include/v8.h" namespace cc { class Layer; } namespace blink { class WebDocument; class WebElement; class WebPlugin; class WebString; class WebURLRequest; class WebDOMMessageEvent; struct WebRect; class WebPluginContainer { public: enum TouchEventRequestType { kTouchEventRequestTypeNone, kTouchEventRequestTypeRaw, kTouchEventRequestTypeRawLowLatency, kTouchEventRequestTypeSynthesizedMouse, }; // Returns the element containing this plugin. virtual WebElement GetElement() = 0; // Returns the owning document for the plugin. virtual WebDocument GetDocument() = 0; // Synchronously dispatches the progress event. virtual void DispatchProgressEvent(const WebString& type, bool length_computable, uint64_t loaded, uint64_t total, const WebString& url) = 0; // Enqueue's a task to dispatch the event. // TODO(esprehn): Why are progress events sync and message events async!? virtual void EnqueueMessageEvent(const WebDOMMessageEvent&) = 0; virtual void Invalidate() = 0; virtual void InvalidateRect(const WebRect&) = 0; // Schedules an animation of the WebView that contains the plugin, as well as // the plugin. virtual void ScheduleAnimation() = 0; // Causes the container to report its current geometry via // WebPlugin::updateGeometry. virtual void ReportGeometry() = 0; // Returns the scriptable object associated with the DOM element // containing the plugin as a native v8 object. virtual v8::Local<v8::Object> V8ObjectForElement() = 0; // Loads an URL in the specified frame (or the frame containing this // plugin if target is empty). If notifyNeeded is true, then upon // completion, WebPlugin::didFinishLoadingFrameRequest is called if the // load was successful or WebPlugin::didFailLoadingFrameRequest is // called if the load failed. The given notifyData is passed along to // the callback. virtual void LoadFrameRequest(const WebURLRequest&, const WebString& target) = 0; // Determines whether the given rectangle in this plugin is above all other // content. The rectangle is in the plugin's coordinate system. virtual bool IsRectTopmost(const WebRect&) = 0; // Notifies when the plugin changes the kind of touch-events it accepts. virtual void RequestTouchEventType(TouchEventRequestType) = 0; // Notifies when the plugin starts/stops accepting wheel events. Without // calling the function with true, the container might not always able to // receive wheel events in some cases (such as when threaded compositing // is in use but a scroll bar is not in use). virtual void SetWantsWheelEvents(bool) = 0; // Converts root frame's coordinates to plugin's local coordinates. virtual gfx::Point RootFrameToLocalPoint(const gfx::Point&) = 0; // Converts plugin's local coordinate to root frame's coordinates. virtual gfx::Point LocalToRootFramePoint(const gfx::Point&) = 0; // Returns the plugin this container owns. This plugin will be // automatically destroyed when the container is destroyed. virtual WebPlugin* Plugin() = 0; // Sets the plugin owned by this container. If the container already owned // a different plugin before this call, that old plugin is now unowned. // The caller is then responsible for destroying the old plugin. virtual void SetPlugin(WebPlugin*) = 0; // Sets |this| as find handler for the associated frame. virtual void UsePluginAsFindHandler() = 0; virtual void ReportFindInPageMatchCount(int identifier, int total, bool final_update) = 0; virtual void ReportFindInPageSelection(int identifier, int index) = 0; virtual float DeviceScaleFactor() = 0; virtual float PageScaleFactor() = 0; virtual float PageZoomFactor() = 0; // Sets the layer representing the plugin for compositing. The // WebPluginContainer does *not* take ownership. virtual void SetCcLayer(cc::Layer*) = 0; virtual void RequestFullscreen() = 0; virtual bool IsFullscreenElement() const = 0; virtual void CancelFullscreen() = 0; // Returns true if this container was the target for the last mouse event. virtual bool WasTargetForLastMouseEvent() = 0; // Whether this plugin current has the mouse lock or not. virtual bool IsMouseLocked() = 0; // Request to lock the mouse. A subsequent callback on // WebPlugin::DidReceiveMouseLockResult will be called. virtual bool LockMouse(bool request_unadjusted_movement) = 0; // Request to unlock a current mouse lock. virtual void UnlockMouse() = 0; protected: ~WebPluginContainer() = default; }; } // namespace blink #endif
39.152047
79
0.728603
[ "geometry", "object" ]
ca40f3c7aaebbb2e3232016b926f4d2bb8cbbbd3
3,226
h
C
Gems/Atom/RHI/Metal/Code/Source/RHI/CommandListPool.h
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
1
2022-03-12T14:13:45.000Z
2022-03-12T14:13:45.000Z
Gems/Atom/RHI/Metal/Code/Source/RHI/CommandListPool.h
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
2
2022-01-13T04:29:38.000Z
2022-03-12T01:05:31.000Z
Gems/Atom/RHI/Metal/Code/Source/RHI/CommandListPool.h
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <Atom/RHI/ObjectPool.h> #include <Atom/RHI/ThreadLocalContext.h> #include <Atom/RHI.Reflect/AttachmentEnums.h> #include <Atom/RHI.Reflect/Limits.h> #include <AzCore/std/containers/array.h> namespace AZ { namespace Metal { class Device; class CommandList; class CommandListFactory : public RHI::ObjectFactoryBase<CommandList> { using Base = RHI::ObjectFactoryBase<CommandList>; public: struct Descriptor { RHI::HardwareQueueClass m_hardwareQueueClass = RHI::HardwareQueueClass::Graphics; Device* m_device = nullptr; }; void Init(const Descriptor& descriptor); RHI::Ptr<CommandList> CreateObject(); void ResetObject(CommandList& commandList); void ShutdownObject(CommandList& commandList, bool isPoolShutdown); private: Descriptor m_descriptor; }; struct CommandListPoolTraits : public RHI::ObjectPoolTraits { using ObjectType = CommandList; using ObjectFactoryType = CommandListFactory; using MutexType = AZStd::recursive_mutex; }; using CommandListPool = RHI::ObjectPool<CommandListPoolTraits>; /////////////////////////////////////////////////////////////////// // CommandListSubAllocator class CommandListSubAllocator final { public: ~CommandListSubAllocator(); void Init(CommandListPool& commandListPool); CommandList* Allocate(); void Reset(); private: CommandListPool* m_commandListPool = nullptr; AZStd::vector<CommandList*> m_activeLists; }; class CommandListAllocator final { public: CommandListAllocator() = default; struct Descriptor { // The maximum number of frames to keep buffered on the CPU timeline. uint32_t m_frameCountMax = RHI::Limits::Device::FrameCountMax; }; void Init(const Descriptor& descriptor, Device* device); void Shutdown(); CommandList* Allocate(RHI::HardwareQueueClass hardwareQueueClass); // Call this once per frame to retire the current frame and reclaim // elements from completed frames void Collect(); private: CommandListPool* m_commandListPool = nullptr; AZStd::vector<CommandList*> m_activeLists; AZStd::array<CommandListPool, RHI::HardwareQueueClassCount> m_commandListPools; AZStd::array<RHI::ThreadLocalContext<CommandListSubAllocator>, RHI::HardwareQueueClassCount> m_commandListSubAllocators; bool m_isInitialized = false; }; } }
31.320388
132
0.584315
[ "vector", "3d" ]
ca414ac45d8a25388e9884e3e37a4e5ea9921702
1,286
h
C
dcmcore/dicom_reader.h
feliwir/dcmlite
70a5891b0c8409f351242da8f5c9cd8649453950
[ "MIT" ]
6
2019-05-20T11:16:55.000Z
2022-01-03T08:48:53.000Z
dcmcore/dicom_reader.h
feliwir/dcmlite
70a5891b0c8409f351242da8f5c9cd8649453950
[ "MIT" ]
null
null
null
dcmcore/dicom_reader.h
feliwir/dcmlite
70a5891b0c8409f351242da8f5c9cd8649453950
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include <string_view> #include <vector> #include "dcmcore/defs.h" namespace dcmcore { class DataElement; class DataSet; class BinaryFile; class ReadHandler; class Tag; // DICOM reader reads data set from a DICOM file. class DicomReader { public: explicit DicomReader(ReadHandler* handler); DicomReader(); // Read a DICOM file. bool ReadFile(std::string_view file_path); private: // Read data element sequentially from the file. // \param Maximum value length to read for the current data set. // Could be kUndefinedLength (0xFFFFFFFF). // \param check_endian Check endian type during the reading. // \return The length read. std::uint32_t ReadFile(BinaryFile& file, std::size_t max_length, bool check_endian); bool ReadTag(BinaryFile& file, Tag& tag); bool ReadUint16(BinaryFile& file, std::uint16_t& value); bool ReadUint32(BinaryFile& file, std::uint32_t& value); // Reverse the byte order if endian types are different. void AdjustBytesUint16(std::uint16_t& value) const; void AdjustBytesUint32(std::uint32_t& value) const; private: ReadHandler* handler_; Endian endian_; // Endian type of DICOM file. bool explicit_vr_; // Explicit or implicit VR. }; } // namespace dcmcore
24.730769
66
0.726283
[ "vector" ]
ca41ebcefe6c1e866abe40248435e0bd87951017
1,030
h
C
hphp/runtime/ext/curl/curl-multi-await.h
lavagetto/hhvm
f9ed7ff466944c533733f3d49dcf6405c22ce57d
[ "PHP-3.01", "Zend-2.0" ]
3
2015-07-05T07:32:31.000Z
2015-07-13T02:31:10.000Z
hphp/runtime/ext/curl/curl-multi-await.h
lavagetto/hhvm
f9ed7ff466944c533733f3d49dcf6405c22ce57d
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/ext/curl/curl-multi-await.h
lavagetto/hhvm
f9ed7ff466944c533733f3d49dcf6405c22ce57d
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
#ifndef incl_HPHP_CURL_MULTI_AWAIT_H #define incl_HPHP_CURL_MULTI_AWAIT_H #include "hphp/runtime/ext/asio/asio-external-thread-event.h" #include "hphp/runtime/ext/curl/curl-multi-resource.h" namespace HPHP { ///////////////////////////////////////////////////////////////////////////// struct CurlEventHandler; struct CurlTimeoutHandler; struct CurlMultiAwait : AsioExternalThreadEvent { CurlMultiAwait(req::ptr<CurlMultiResource> multi, double timeout); ~CurlMultiAwait(); void unserialize(Cell& c) override; private: friend struct CurlEventHandler; friend struct CurlTimeoutHandler; void setFinished(int fd); void addHandle(int fd, int events); int addLowHandles(req::ptr<CurlMultiResource> multi); int addHighHandles(req::ptr<CurlMultiResource> multi); std::shared_ptr<CurlTimeoutHandler> m_timeout; std::vector<std::shared_ptr<CurlEventHandler>> m_handlers; int m_result{-1}; bool m_finished{false}; }; ///////////////////////////////////////////////////////////////////////////// } #endif
27.837838
77
0.664078
[ "vector" ]
ca60b4d435968c5cfd50d425e0acb68f62eb7eb6
3,457
h
C
SpatialUnderstanding/Src/Engine/Vec2f_Z.h
matthejo/MixedRealityToolkit
c97ace84cfc4cdf97044b35b568bd9182497497a
[ "MIT" ]
300
2017-08-12T12:57:42.000Z
2019-05-06T00:31:29.000Z
SpatialUnderstanding/Src/Engine/Vec2f_Z.h
matthejo/MixedRealityToolkit
c97ace84cfc4cdf97044b35b568bd9182497497a
[ "MIT" ]
84
2017-08-14T11:03:37.000Z
2019-04-24T22:59:59.000Z
SpatialUnderstanding/Src/Engine/Vec2f_Z.h
matthejo/MixedRealityToolkit
c97ace84cfc4cdf97044b35b568bd9182497497a
[ "MIT" ]
114
2017-08-12T03:51:58.000Z
2019-05-06T03:36:26.000Z
// Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #ifndef _MATH_VECTOR2D_Z_H #define _MATH_VECTOR2D_Z_H #include <BeginDef_Z.h> struct Vec3f; //---------------------------------------------------------------- // Vec2f //---------------------------------------------------------------- struct Vec2f { // Data Float x,y; // Init Method #ifdef _DEBUG Vec2f() { // memset(this, 0xFF, sizeof(*this)); TROP LENT EN DEBUG !!! U32 *ptr = (U32*)this; *ptr++ = 0xFFFFFFFF; *ptr = 0xFFFFFFFF; } #else Vec2f() {} #endif Vec2f( const Float _xy) : x(_xy ),y( _xy ) {} Vec2f( const Float _x, const Float _y) : x(_x ),y( _y ) {} Vec2f(const Vec3f &_o); Vec2f &Set(const Float _x, const Float _y) {x=_x;y=_y;return *this;} Vec2f &Set(const Vec2f &_v) {x=_v.x;y=_v.y; return *this;} // Operator Vec2f &operator=(const Vec2f &_v) {x=_v.x; y=_v.y; return *this;} Vec2f &operator=(const Vec3f &_v); Vec2f operator+(const Vec2f &_v) const {return Vec2f(x+_v.x,y+_v.y);} Vec2f &operator+=(const Vec2f &_v) {x+=_v.x;y+=_v.y; return *this;} Vec2f operator+() const {return *this;} Vec2f operator-(const Vec2f &_v) const {return Vec2f(x-_v.x,y-_v.y);} Vec2f &operator-=(const Vec2f &_v) {x-=_v.x;y-=_v.y; return *this;} Vec2f operator-() const {return Vec2f(-x,-y);} Vec2f operator*(Float _f) const {return Vec2f(x*_f,y*_f);} Vec2f &operator*=(Float _f) {x*=_f;y*=_f; return *this;} Float operator*(const Vec2f &_v) const {return x*_v.x+y*_v.y;} Vec2f operator/(Float _f) const {ASSERT_Z(_f!=0.f);float inv=1.f/_f;return Vec2f(x*inv,y*inv);} Vec2f &operator/=(Float _f) {ASSERT_Z(_f!=0.f);float inv=1.f/_f;x*=inv;y*=inv;return *this;} Vec2f operator/(const Vec2f &_v) const {ASSERT_Z(_v.x!=0.f&&_v.y!=0.f);return Vec2f(x/_v.x,y/_v.y);} Vec2f &operator/=(const Vec2f &_v) {ASSERT_Z(_v.x!=0.f&&_v.y!=0.f);x/=_v.x;y/=_v.y;return *this;} Float operator^(const Vec2f &_v) const {return x*_v.y-y*_v.x;} Vec2f operator&(const Vec2f &_v) const {return Vec2f(x*_v.x, y*_v.y);} Float &operator[](int _i) {ASSERT_Z(_i>=0&&_i<2);return (&x)[_i];} const Float &operator[](int _i) const {ASSERT_Z(_i>=0&&_i<2);return (&x)[_i];} Bool operator==(const Vec2f& v) const {Vec2f Diff=*this-v;return (Abs(Diff.x)<Float_Eps)&&(Abs(Diff.y)<Float_Eps);} Bool operator!=(const Vec2f& v) const { return !operator==(v); }; // Utils Float GetNorm2() const {return (*this)*(*this);} Float GetNorm() const {return Sqrt(GetNorm2());} Vec2f &Normalize() {return (*this)/=GetNorm();} Bool CNormalize(const Float NormValue = 1.f) // J'ai modifi� le CNormalize pour que l'on puisse normer avec autre chose que 1... Plus rapide ! A faire en Vec3f { Float n=(*this)*(*this); if (n > Float_Eps) // Using Float_Eps generates precision problems { (*this)*=InvSqrt(NormValue,n); return TRUE; } return FALSE; } }; inline Vec2f operator*(Float _f, const Vec2f &_v) {return _v*_f;} EXTERN_Z Float CalcArea2D(Vec2f *Shape,S32 NbPoints); EXTERN_Z Float SignedCalcArea2D(Vec2f *Shape,S32 NbPoints); EXTERN_Z void RotateVector2D(Vec2f &vec, Float Angle); const EXTERN_Z Vec2f VEC2F_NULL; const EXTERN_Z Vec2f VEC2F_HALF; const EXTERN_Z Vec2f VEC2F_ONE; const EXTERN_Z Vec2f VEC2F_RIGHT; const EXTERN_Z Vec2f VEC2F_DOWN; #endif //_MATH_VECTOR2D_Z_H
38.842697
160
0.631472
[ "shape" ]
ca61616187ae5151b854a10a3d11c0aa6908ae00
10,091
h
C
thirdparty/geogram/src/lib/geogram/basic/quaternion.h
AmericaMakes/OASIS-marcwang
7aa10040251d7a1b807a773a45d123e1a52faac5
[ "BSD-2-Clause" ]
1
2021-03-07T14:47:09.000Z
2021-03-07T14:47:09.000Z
thirdparty/geogram/src/lib/geogram/basic/quaternion.h
AmericaMakes/OASIS-marcwang
7aa10040251d7a1b807a773a45d123e1a52faac5
[ "BSD-2-Clause" ]
null
null
null
thirdparty/geogram/src/lib/geogram/basic/quaternion.h
AmericaMakes/OASIS-marcwang
7aa10040251d7a1b807a773a45d123e1a52faac5
[ "BSD-2-Clause" ]
1
2021-03-07T00:24:57.000Z
2021-03-07T00:24:57.000Z
/* * Copyright (c) 2010-2016, Inria, project ALICE * 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 ALICE Project-Team nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * If you modify this software, you should include a notice giving the * name of the person performing the modification, the date of modification, * and the reason for such modification. * * Contact: Bruno Levy * * Bruno.Levy@inria.fr * http://www.loria.fr/~levy * * ALICE Project * LORIA, INRIA Lorraine, * Campus Scientifique, BP 239 * 54506 VANDOEUVRE LES NANCY CEDEX * FRANCE * */ #ifndef GEOGRAM_BASIC_QUATERNION #define GEOGRAM_BASIC_QUATERNION #include <geogram/basic/common.h> #include <geogram/basic/geometry.h> #include <iostream> /** * \file geogram/basic/quaternion.h * \brief a class that represents quaternions (eases * manipulation of 3D rotations) */ namespace GEO { /** * \brief Quaternions are useful for representing rotations. * \details This class is inspired by an implementation written * by Paul Rademacher, in his glui library. */ class GEOGRAM_API Quaternion { public: /** * \brief Constructs a new Quaternion. */ Quaternion() : v_(0.0,0.0,0.0), s_(1.0) { } /** * \brief Copy-constructs a new Quaternion. * \param[in] rhs the Quaternion to be copied. */ Quaternion(const Quaternion& rhs) : v_(rhs.v_), s_(rhs.s_) { } /** * \brief Constructs a new quaternion from its coefficients * \param[in] x a coefficient of the quaternion * \param[in] y a coefficient of the quaternion * \param[in] z a coefficient of the quaternion * \param[in] w a coefficient of the quaternion */ Quaternion( double x, double y, double z, double w ) : v_(x,y,z), s_(w) { } /** * \brief Constructs a new Quaternion from a vector and * a scalar. * \param[in] v a const reference to the vector * \param[in] s the scalalr */ Quaternion( const vec3& v, double s ) : v_(v), s_(s) { } /** * \brief Copies a Quaternion * \param[in] q the Quaternion to be copied * \return a reference to this Quaternion */ Quaternion& operator = ( const Quaternion &q ) { v_ = q.v_ ; s_ = q.s_ ; return *this ; } /** * \brief Sets the coefficients of this quaterion * \param[in] v a const reference to the vector components * \param[in] s the scalar component */ void set( const vec3& v, double s ) { v_ = v; s_ = s; } /** * \brief Displays this Quaternion * \param[in] out a reference to the std::ostream * where this Quaternion should be displayed */ void print( std::ostream& out ) const { out << v_.x << " " << v_.y << " " << v_.z << " " << s_ ; } /** * \brief Converts this Quaternion into a matrix * \return a matrix (mat4) that represents this Quaternion */ mat4 to_matrix() const; /** * \brief Sets the rotation angle. * \param[in] f the rotation angle */ void set_angle( double f ) { vec3 ax = axis(); s_ = ::cos(f / 2.0); v_ = ax * ::sin(f / 2.0); } /** * \brief Scales the rotation angle. */ void scale_angle( double f ) { set_angle( f * angle() ); } /** * \brief Gets the rotation angle * \return the angle */ double angle() const { return 2.0 * acos( s_ ) ; } /** * \brief Gets the axis. * \return The axis. */ vec3 axis() const; /** * \brief Computes the interpolation between two quaternions * \param[in] from a const reference to the first quaternion * \param[in] to a const reference to the second quaternion * \param[in] t time, in [0.0,1.0] * \return a smooth interpolation between \p from and \p to * parameterized by \p t */ static Quaternion spherical_interpolation( const Quaternion& from, const Quaternion& to, double t ); /** * \brief Gets the vector component * \return the vector component * \note the vector part is not the axis of rotation. * The axis of rotation is obtained by calling axis(). */ const vec3& v() const { return v_; } /** * \brief Gets the scalar component * \return the scalar component * \note the scalar component is not the rotation angle. * The rotation angle is obtained by calling angle(). */ double s() const { return s_; } private: vec3 v_ ; double s_ ; } ; /*************************************************************************/ /** * \brief Writes a Quaternion to a stream * \param[in,out] out the stream * \param[in] q a const reference to the quaternion * \return a reference to the stream */ inline std::ostream& operator<<(std::ostream& out, const Quaternion& q) { q.print(out) ; return out ; } /** * \brief Reads a Quaternion from a stream * \param[in,out] in the stream * \param[out] q a reference to the quaternion * \return a reference to the stream */ inline std::istream& operator>>(std::istream& in, Quaternion& q) { double x=0.0,y=0.0,z=0.0,w=0.0 ; in >> x >> y >> z >> w ; q.set(vec3(x,y,z),w) ; return in ; } /** * \brief Computes the sum of two Quaternion * \param[in] a a const reference to the first Quaternion * \param[in] b a const reference to the second Quaternion * \return the sum of \p a and \p b */ inline Quaternion operator + (const Quaternion& a, const Quaternion& b) { return Quaternion( a.v() + b.v(), a.s() + b.s() ) ; } /** * \brief Computes the difference between two Quaternion * \param[in] a a const reference to the first Quaternion * \param[in] b a const reference to the second Quaternion * \return the difference between \p a and \p b */ inline Quaternion operator - (const Quaternion& a, const Quaternion& b) { return Quaternion( a.v() - b.v(), a.s() - b.s() ) ; } /** * \brief Computes the opposite of a Quaternion * \param[in] a a const reference to the Quaternion * \return the opposite of \p a */ inline Quaternion operator - (const Quaternion& a ) { return Quaternion( -1.0 * a.v(), -a.s() ); } /** * \brief Computes the product of two Quaternion * \param[in] a a const reference to the first Quaternion * \param[in] b a const reference to the second Quaternion * \return the product of \p a and \p b */ inline Quaternion operator * ( const Quaternion& a, const Quaternion& b) { return Quaternion( a.s() * b.v() + b.s() * a.v() + cross(a.v(),b.v()), a.s() * b.s() - dot(a.v() , b.v()) ); } /** * \brief Computes the product of a Quaternion and a scalar * \param[in] a a const reference to the Quaternion * \param[in] t the scalar * \return the product of \p a and \p t */ inline Quaternion operator * ( const Quaternion& a, double t ) { return Quaternion( t * a.v(), a.s() * t ); } /** * \brief Computes the product of a scalar and a Quaternion * \param[in] t the scalar * \param[in] a a const reference to the second Quaternion * \return the product of \p t and \p a */ inline Quaternion operator * ( double t, const Quaternion& a ) { return Quaternion( t * a.v(), a.s() * t ); } } #endif
32.446945
81
0.547121
[ "geometry", "vector", "3d" ]
ca62587c6736804c72d377164c5ff6562e7fd251
7,173
h
C
deps/libgeos/geos/include/geos/operation/buffer/OffsetCurveBuilder.h
khrushjing/node-gdal-async
6546b0c8690f2db677d5385b40b407523503b314
[ "Apache-2.0" ]
42
2021-03-26T17:34:52.000Z
2022-03-18T14:15:31.000Z
deps/libgeos/geos/include/geos/operation/buffer/OffsetCurveBuilder.h
khrushjing/node-gdal-async
6546b0c8690f2db677d5385b40b407523503b314
[ "Apache-2.0" ]
29
2021-06-03T14:24:01.000Z
2022-03-23T15:43:58.000Z
deps/libgeos/geos/include/geos/operation/buffer/OffsetCurveBuilder.h
khrushjing/node-gdal-async
6546b0c8690f2db677d5385b40b407523503b314
[ "Apache-2.0" ]
8
2021-05-14T19:26:37.000Z
2022-03-21T13:44:42.000Z
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2009-2011 Sandro Santilli <strk@kbt.io> * Copyright (C) 2006-2007 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: operation/buffer/OffsetCurveBuilder.java r378 (JTS-1.12) * **********************************************************************/ #ifndef GEOS_OP_BUFFER_OFFSETCURVEBUILDER_H #define GEOS_OP_BUFFER_OFFSETCURVEBUILDER_H #include <geos/export.h> #include <geos/operation/buffer/BufferParameters.h> // for composition #include <geos/operation/buffer/OffsetSegmentGenerator.h> #include <vector> #include <memory> // for unique_ptr #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4251) // warning C4251: needs to have dll-interface to be used by clients of class #endif // Forward declarations namespace geos { namespace geom { class CoordinateSequence; class PrecisionModel; } } namespace geos { namespace operation { // geos.operation namespace buffer { // geos.operation.buffer /** * \class OffsetCurveBuilder * * \brief * Computes the raw offset curve for a * single Geometry component (ring, line or point). * * A raw offset curve line is not noded - * it may contain self-intersections (and usually will). * The final buffer polygon is computed by forming a topological graph * of all the noded raw curves and tracing outside contours. * The points in the raw curve are rounded to a given geom::PrecisionModel. * */ class GEOS_DLL OffsetCurveBuilder { public: /* * @param nBufParams buffer parameters, this object will * keep a reference to the passed parameters * so caller must make sure the object is * kept alive for the whole lifetime of * the buffer builder. */ OffsetCurveBuilder(const geom::PrecisionModel* newPrecisionModel, const BufferParameters& nBufParams) : distance(0.0), precisionModel(newPrecisionModel), bufParams(nBufParams) {} /** \brief * Gets the buffer parameters being used to generate the curve. * * @return the buffer parameters being used */ const BufferParameters& getBufferParameters() const { return bufParams; } /** * Tests whether the offset curve for line or point geometries * at the given offset distance is empty (does not exist). * This is the case if: * <ul> * <li>the distance is zero, * <li>the distance is negative, except for the case of singled-sided buffers * </ul> * * @param distance the offset curve distance * @return true if the offset curve is empty */ bool isLineOffsetEmpty(double distance); /** \brief * This method handles single points as well as lines. * * Lines are assumed to **not** be closed (the function will not * fail for closed lines, but will generate superfluous line caps). * * @param inputPts input points * @param distance offset distance * @param lineList the std::vector to which the newly created * CoordinateSequences will be pushed_back. * Caller is responsible to delete these new elements. */ void getLineCurve(const geom::CoordinateSequence* inputPts, double distance, std::vector<geom::CoordinateSequence*>& lineList); /** \brief * This method handles single points as well as lines. * * Lines are assumed to **not** be closed (the function will not * fail for closed lines, but will generate superfluous line caps). * * @param inputPts input points * @param distance offset distance * @param lineList the std::vector to which newly created * CoordinateSequences will be pushed_back. * Caller will be responsible to delete them. * @param leftSide indicates that the left side buffer will be * obtained/skipped * @param rightSide indicates that the right side buffer will * be obtained/skipped * * @note This is a GEOS extension. */ void getSingleSidedLineCurve(const geom::CoordinateSequence* inputPts, double distance, std::vector<geom::CoordinateSequence*>& lineList, bool leftSide, bool rightSide) ; /** \brief * This method handles the degenerate cases of single points and lines, * as well as rings. * * @param inputPts input points * @param side a [Position](@ref geom::Position) * @param distance offset distance * @param lineList the std::vector to which CoordinateSequences will * be pushed_back */ void getRingCurve(const geom::CoordinateSequence* inputPts, int side, double distance, std::vector<geom::CoordinateSequence*>& lineList); private: double distance; const geom::PrecisionModel* precisionModel; const BufferParameters& bufParams; /** \brief * Use a value which results in a potential distance error which is * significantly less than the error due to the quadrant segment discretization. * * For QS = 8 a value of 100 is reasonable. * This should produce a maximum of 1% distance error. */ static const double SIMPLIFY_FACTOR; // 100.0; /** \brief * Computes the distance tolerance to use during input * line simplification. * * @param bufDistance the buffer distance * @return the simplification tolerance */ double simplifyTolerance(double bufDistance); void computeLineBufferCurve(const geom::CoordinateSequence& inputPts, OffsetSegmentGenerator& segGen); void computeSingleSidedBufferCurve(const geom::CoordinateSequence& inputPts, bool isRightSide, OffsetSegmentGenerator& segGen); void computeRingBufferCurve(const geom::CoordinateSequence& inputPts, int side, OffsetSegmentGenerator& segGen); std::unique_ptr<OffsetSegmentGenerator> getSegGen(double dist); void computePointCurve(const geom::Coordinate& pt, OffsetSegmentGenerator& segGen); // Declare type as noncopyable OffsetCurveBuilder(const OffsetCurveBuilder& other) = delete; OffsetCurveBuilder& operator=(const OffsetCurveBuilder& rhs) = delete; }; } // namespace geos::operation::buffer } // namespace geos::operation } // namespace geos #ifdef _MSC_VER #pragma warning(pop) #endif #endif // ndef GEOS_OP_BUFFER_OFFSETCURVEBUILDER_H
33.518692
107
0.633766
[ "geometry", "object", "vector" ]
ca62b9bef8953a93669c33e16f5ce7dd0169b947
1,562
h
C
Engine/Source/Runtime/CoreUObject/Public/Serialization/ArchiveObjectCrc32.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/CoreUObject/Public/Serialization/ArchiveObjectCrc32.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/CoreUObject/Public/Serialization/ArchiveObjectCrc32.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Serialization/ArchiveUObject.h" #include "Serialization/MemoryWriter.h" #include "Containers/Queue.h" /*---------------------------------------------------------------------------- FArchiveObjectCrc32 ----------------------------------------------------------------------------*/ /** * Calculates a checksum on an object's serialized data stream. */ class COREUOBJECT_API FArchiveObjectCrc32 : public FArchiveUObject { public: /** * Default constructor. */ FArchiveObjectCrc32(); //~ Begin FArchive Interface virtual void Serialize(void* Data, int64 Length); virtual FArchive& operator<<(class FName& Name); virtual FArchive& operator<<(class UObject*& Object); virtual FString GetArchiveName() const { return TEXT("FArchiveObjectCrc32"); } //~ End FArchive Interface /** * Serialize the given object, calculate and return its checksum. */ uint32 Crc32(UObject* Object, uint32 CRC = 0); protected: /** Return if object was already serialized */ virtual bool CustomSerialize(class UObject* Object) { return false; } /** Internal byte array used for serialization */ TArray<uint8> SerializedObjectData; /** Internal archive used for serialization */ FMemoryWriter MemoryWriter; /** Internal queue of object references awaiting serialization */ TQueue<UObject*> ObjectsToSerialize; /** Internal currently serialized object */ const UObject* ObjectBeingSerialized; /** Internal root object */ const UObject* RootObject; };
30.038462
79
0.678617
[ "object" ]
ca62e8d5d31f3a54831bef37f583e47922df5120
3,170
h
C
content/public/browser/background_fetch_response.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
content/public/browser/background_fetch_response.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
content/public/browser/background_fetch_response.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2017 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 CONTENT_PUBLIC_BROWSER_BACKGROUND_FETCH_RESPONSE_H_ #define CONTENT_PUBLIC_BROWSER_BACKGROUND_FETCH_RESPONSE_H_ #include <vector> #include "base/files/file_path.h" #include "base/time/time.h" #include "content/common/content_export.h" #include "net/http/http_response_headers.h" #include "storage/browser/blob/blob_data_handle.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "url/gurl.h" namespace content { // Contains the response after a background fetch has started. struct CONTENT_EXPORT BackgroundFetchResponse { BackgroundFetchResponse( const std::vector<GURL>& url_chain, const scoped_refptr<const net::HttpResponseHeaders>& headers); BackgroundFetchResponse(const BackgroundFetchResponse&) = delete; BackgroundFetchResponse& operator=(const BackgroundFetchResponse&) = delete; ~BackgroundFetchResponse(); const std::vector<GURL> url_chain; const scoped_refptr<const net::HttpResponseHeaders> headers; // May be null. }; struct CONTENT_EXPORT BackgroundFetchResult { // Failures that happen after the download has already started and are // reported via |BackgroundFetchDelegate::Client::OnDownloadComplete|. enum class FailureReason { // None of below failures occurred, although the fetch could still have // failed with an error code such as 404. NONE, // Used when the download has been aborted after reaching a threshold where // it was decided it is not worth attempting to start again. This could be // either due to a specific number of failed retry attempts or a specific // number of wasted bytes due to the download restarting. NETWORK, // Used when the download was not completed before the timeout. TIMEDOUT, // Used when the download was cancelled by the user. CANCELLED, // Catch-all error. Used when the failure reason is unknown or not exposed // to the developer. FETCH_ERROR, }; // Constructor for failed downloads. BackgroundFetchResult(std::unique_ptr<BackgroundFetchResponse> response, base::Time response_time, FailureReason failure_reason); // Constructor for successful downloads. BackgroundFetchResult(std::unique_ptr<BackgroundFetchResponse> response, base::Time response_time, const base::FilePath& path, absl::optional<storage::BlobDataHandle> blob_handle, uint64_t file_size); BackgroundFetchResult(const BackgroundFetchResult&) = delete; BackgroundFetchResult& operator=(const BackgroundFetchResult&) = delete; ~BackgroundFetchResult(); std::unique_ptr<BackgroundFetchResponse> response; const base::Time response_time; const base::FilePath file_path; absl::optional<storage::BlobDataHandle> blob_handle; const uint64_t file_size = 0; FailureReason failure_reason; }; } // namespace content #endif // CONTENT_PUBLIC_BROWSER_BACKGROUND_FETCH_RESPONSE_H_
36.022727
79
0.738801
[ "vector" ]
ca73627d56219452afb6a6e674558740d8ab1b99
6,161
h
C
Modules/Filtering/ImageGrid/include/itkSliceImageFilter.h
floryst/ITK
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
[ "Apache-2.0" ]
1
2020-10-09T18:12:53.000Z
2020-10-09T18:12:53.000Z
Modules/Filtering/ImageGrid/include/itkSliceImageFilter.h
floryst/ITK
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
[ "Apache-2.0" ]
1
2017-08-18T19:28:52.000Z
2017-08-18T19:28:52.000Z
Modules/Filtering/ImageGrid/include/itkSliceImageFilter.h
floryst/ITK
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
[ "Apache-2.0" ]
1
2017-08-18T19:07:39.000Z
2017-08-18T19:07:39.000Z
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkSliceImageFilter_h #define itkSliceImageFilter_h #include "itkImageToImageFilter.h" namespace itk { /** \class SliceImageFilter * \brief Slices an image based on a starting index and a stopping * index, and a step size. * * This class is designed to facilitate the implementation of extended * sliced based indexing into images. * * The input and output image must be of the same dimension. * * The input parameters are a starting and stopping index as well as a * stepping size. The starting index indicates the first pixels to be * used and for each dimension the index is incremented by the step * until the index is equal to or "beyond" the stopping index. If the * step is negative then the image will be reversed in the dimension, * and the stopping index is expected to be less then the starting * index. If the stopping index is already beyond the starting index * then an image of size zero will be returned. * * The output image's starting index is always zero. The origin is the * physical location of the starting index. The output directions * cosine matrix is that of the input but with sign changes matching * that of the step's sign. * * \note In certain combinations such as with start=1, and step>1 while * the physical location of the center of the pixel remains the same, * the extent (edge to edge space) of the output image will be beyond the * extent of the original image. * * \ingroup ITKImageGrid */ template< class TInputImage, class TOutputImage > class ITK_TEMPLATE_EXPORT SliceImageFilter: public ImageToImageFilter< TInputImage, TOutputImage > { public: ITK_DISALLOW_COPY_AND_ASSIGN(SliceImageFilter); /** Standard class type aliases. */ using Self = SliceImageFilter; using Superclass = ImageToImageFilter< TInputImage, TOutputImage >; using Pointer = SmartPointer< Self >; using ConstPointer = SmartPointer< const Self >; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(SliceImageFilter, ImageToImageFilter); /** Typedef to images */ using OutputImageType = TOutputImage; using InputImageType = TInputImage; using OutputImagePointer = typename OutputImageType::Pointer; using InputImagePointer = typename InputImageType::Pointer; using InputImageConstPointer = typename InputImageType::ConstPointer; using OutputIndexType = typename TOutputImage::IndexType; using InputIndexType = typename TInputImage::IndexType; using OutputOffsetType = typename TOutputImage::OffsetType; /** Typedef to describe the output image region type. */ using OutputImageRegionType = typename TOutputImage::RegionType; /** ImageDimension enumeration. */ static constexpr unsigned int ImageDimension = TInputImage::ImageDimension; static constexpr unsigned int OutputImageDimension = TOutputImage::ImageDimension; using IndexType = typename InputImageType::IndexType; using IndexValueType = typename InputIndexType::IndexValueType; using ArrayType = FixedArray< int, ImageDimension >; /** Set/Get the first index extracted from the input image */ itkSetMacro(Start, IndexType); itkGetConstReferenceMacro(Start, IndexType); void SetStart(IndexValueType start); /** Set/Get the excluded end of the range */ itkSetMacro(Stop, IndexType); itkGetConstReferenceMacro(Stop, IndexType); void SetStop(IndexValueType stop); /** Set/Get the stride of indexes extracted * * An exception will be generated if 0. */ itkSetMacro(Step, ArrayType); itkGetConstReferenceMacro(Step, ArrayType); void SetStep( int step); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro( InputConvertibleToOutputCheck, ( Concept::Convertible< typename TInputImage::PixelType, typename TOutputImage::PixelType > ) ); itkConceptMacro( SameDimensionCheck, ( Concept::SameDimension< ImageDimension, OutputImageDimension > ) ); /** End concept checking */ #endif protected: SliceImageFilter(); ~SliceImageFilter() override = default; void PrintSelf(std::ostream & os, Indent indent) const override; /** SliceImageFilter produces an image which is a different * resolution and with a different pixel spacing than its input * image. * \sa ProcessObject::GenerateOutputInformaton() */ void GenerateOutputInformation() override; void GenerateInputRequestedRegion() override; /** SliceImageFilter can be implemented as a multithreaded filter. * Therefore, this implementation provides a DynamicThreadedGenerateData() routine * which is called for each processing thread. The output image data is * allocated automatically by the superclass prior to calling * DynamicThreadedGenerateData(). DynamicThreadedGenerateData can only write to the * portion of the output image specified by the parameter * "outputRegionForThread" * * \sa ImageToImageFilter::ThreadedGenerateData(), * ImageToImageFilter::GenerateData() */ void DynamicThreadedGenerateData(const OutputImageRegionType & outputRegionForThread) override; void VerifyInputInformation() ITKv5_CONST override; private: IndexType m_Start; IndexType m_Stop; ArrayType m_Step; }; } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkSliceImageFilter.hxx" #endif #endif
37.339394
115
0.73949
[ "object" ]
ca76322125c5ed295270cb0060f17fd1c358381b
2,535
h
C
contrib/edi/EDIConfig.h
akhand1010/ODR-AudioEnc
550dcf24ce19e9819c0bad0061fbd5ce9dbd34e3
[ "Apache-2.0" ]
null
null
null
contrib/edi/EDIConfig.h
akhand1010/ODR-AudioEnc
550dcf24ce19e9819c0bad0061fbd5ce9dbd34e3
[ "Apache-2.0" ]
null
null
null
contrib/edi/EDIConfig.h
akhand1010/ODR-AudioEnc
550dcf24ce19e9819c0bad0061fbd5ce9dbd34e3
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2019 Matthias P. Braendli, matthias.braendli@mpb.li http://www.opendigitalradio.org EDI output, UDP and TCP transports and their configuration */ /* This file is part of the ODR-mmbTools. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "config.h" #include <vector> #include <string> #include <memory> #include <cstdint> namespace edi { /** Configuration for EDI output */ struct destination_t { virtual ~destination_t() {}; }; // Can represent both unicast and multicast destinations struct udp_destination_t : public destination_t { std::string dest_addr; std::string source_addr; unsigned int source_port = 0; unsigned int ttl = 10; }; // TCP server that can accept multiple connections struct tcp_server_t : public destination_t { unsigned int listen_port = 0; size_t max_frames_queued = 1024; }; // TCP client that connects to one endpoint struct tcp_client_t : public destination_t { std::string dest_addr; unsigned int dest_port = 0; size_t max_frames_queued = 1024; }; struct configuration_t { unsigned chunk_len = 207; // RSk, data length of each chunk unsigned fec = 0; // number of fragments that can be recovered bool dump = false; // dump a file with the EDI packets bool verbose = false; bool enable_pft = false; // Enable protection and fragmentation unsigned int tagpacket_alignment = 0; std::vector<std::shared_ptr<destination_t> > destinations; unsigned int dest_port = 0; // common destination port, because it's encoded in the transport layer unsigned int latency_frames = 0; // if nonzero, enable interleaver with a latency of latency_frames * 24ms bool enabled() const { return destinations.size() > 0; } bool interleaver_enabled() const { return latency_frames > 0; } void print() const; }; }
29.823529
110
0.704931
[ "vector" ]
ca772b1f5a112767429d4aad19292c495220c850
11,348
c
C
control/estimator/estimator.c
leozz37/makani
c94d5c2b600b98002f932e80a313a06b9285cc1b
[ "Apache-2.0" ]
1,178
2020-09-10T17:15:42.000Z
2022-03-31T14:59:35.000Z
control/estimator/estimator.c
leozz37/makani
c94d5c2b600b98002f932e80a313a06b9285cc1b
[ "Apache-2.0" ]
1
2020-05-22T05:22:35.000Z
2020-05-22T05:22:35.000Z
control/estimator/estimator.c
leozz37/makani
c94d5c2b600b98002f932e80a313a06b9285cc1b
[ "Apache-2.0" ]
107
2020-09-10T17:29:30.000Z
2022-03-18T09:00:14.000Z
/* * Copyright 2020 Makani Technologies LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "control/estimator/estimator.h" #include <assert.h> #include <math.h> #include <stdbool.h> #include <stdint.h> #include <string.h> #include "common/c_math/filter.h" #include "common/c_math/geometry.h" #include "common/c_math/linalg_common.h" #include "common/c_math/mat3.h" #include "common/c_math/util.h" #include "common/c_math/vec3.h" #include "common/macros.h" #include "control/control_params.h" #include "control/control_telemetry.h" #include "control/control_types.h" #include "control/estimator/estimator_apparent_wind.h" #include "control/estimator/estimator_encoders.h" #include "control/estimator/estimator_experiment.h" #include "control/estimator/estimator_ground_station.h" #include "control/estimator/estimator_joystick.h" #include "control/estimator/estimator_nav_kite.h" #include "control/estimator/estimator_perch_azi.h" #include "control/estimator/estimator_tether_anchor.h" #include "control/estimator/estimator_tether_force.h" #include "control/estimator/estimator_tether_ground_angles.h" #include "control/estimator/estimator_types.h" #include "control/estimator/estimator_weather.h" #include "control/estimator/estimator_winch.h" #include "control/estimator/estimator_wind.h" #include "control/ground_frame.h" #include "control/sensor_types.h" #include "control/sensor_util.h" #include "control/system_params.h" #include "control/system_types.h" #define GS_UNPAUSE_TRANSFORM_CYCLES 10 void EstimatorInit(const SystemParams *system_params, const EstimatorParams *params, EstimatorState *state) { assert(system_params != NULL && params != NULL && state != NULL); memset(state, 0, sizeof(*state)); state->tether_release_latched = false; state->time = 0.0; EstimatorApparentWindInit(&state->apparent_wind); EstimatorEncodersInit(&state->encoders); EstimatorExperimentInit(&state->experiment); EstimatorGroundStationInit(&state->ground_station); EstimatorJoystickInit(&state->joystick); EstimatorNavKiteInit(&params->nav, system_params->ground_frame.heading, &state->nav); EstimatorPerchAziInit(&state->perch_azi); EstimatorTetherAnchorPointInit(&state->tether_anchor); EstimatorTetherGroundAnglesInit(&state->tether_ground_angles); EstimatorTetherForceInit(&state->tether_force); EstimatorVesselInit(&state->vessel); EstimatorWeatherInit(&params->weather, &state->weather); EstimatorWinchInit(system_params->flight_plan, system_params->gs_model, system_params->winch.r_drum, &state->winch); EstimatorWindInit(&state->wind); EstimatorWindInit(&state->wind_aloft); state->gs_unpause_transform_count = 0; } // Test that valid messages are simultaneously available for a critical // list of sensors. This must return true before the control system will // advance out of the kInitializationStateWaitForValidData. bool EstimatorIsDataReady(FlightPlan flight_plan, const FaultMask faults[]) { if (flight_plan == kFlightPlanManual) { return !HasAnyFault(&faults[kSubsysJoystick]); } else { if (HasAnyFault(&faults[kSubsysGsGpsPos])) return false; if (HasAnyFault(&faults[kSubsysJoystick])) return false; if (HasAnyFault(&faults[kSubsysWingGpsCrosswindPos])) return false; if (HasAnyFault(&faults[kSubsysWingGpsCrosswindVel])) return false; if (HasAnyFault(&faults[kSubsysWingGpsHoverPos])) return false; if (HasAnyFault(&faults[kSubsysWingGpsHoverVel])) return false; if (flight_plan == kFlightPlanHoverInPlace) { if (HasAnyFault(&faults[kSubsysGsCompass])) return false; } } return true; } void EstimatorStep(const FlightStatus *flight_status, const ControlInput *control_input, const SystemParams *system_params, const FaultMask faults[], const EstimatorParams *params, EstimatorState *state, StateEstimate *state_est) { assert(flight_status != NULL && control_input != NULL && system_params != NULL && faults != NULL && params != NULL && state != NULL && state_est != NULL); // Handle initialization. bool initializing = state->time < params->t_initialize; // Encoder angles. EncodersEstimate encoders; EstimatorEncodersStep( control_input->gsg, &faults[SUBSYS_GSG_A], &faults[SUBSYS_GSG_B], control_input->perch.levelwind_ele, &faults[kSubsysLevelwindEleA], &faults[kSubsysLevelwindEleB], control_input->perch.perch_azi, &faults[kSubsysPerchAziA], &faults[kSubsysPerchAziB], &state->encoders, &encoders); // Estimate air density. EstimatorWeatherStep(initializing, &control_input->weather, &faults[kSubsysWeather], &params->weather, &state->weather, &state_est->rho); // Sensor values required by the controller. state_est->stacking_state = control_input->stacking_state; EstimatorJoystickStep(&control_input->joystick, &faults[kSubsysJoystick], &params->joystick, &state->joystick, &state_est->joystick); EstimatorExperimentStep(state_est->joystick.pitch_f, control_input->experiment_type, control_input->experiment_case_id, &state->experiment, &state_est->experiment); // Convert loadcell tensions to tether tension and tether roll angle. EstimatorTetherForceStep(control_input->loadcells, &faults[SUBSYS_LOADCELLS], &system_params->wing, system_params->loadcells, &params->tether_force, &state->tether_force, &state_est->tether_force_b); // Determine whether the the tether has been released. state->tether_release_latched |= control_input->tether_released; state_est->tether_released = state->tether_release_latched; // Determine if the operator is commanding a gs mode or unpause. state_est->force_high_tension = control_input->force_high_tension; state_est->force_reel = control_input->force_reel; if (control_input->gs_unpause_transform) { state->gs_unpause_transform_count = GS_UNPAUSE_TRANSFORM_CYCLES; } else if (state->gs_unpause_transform_count > 0) { state->gs_unpause_transform_count--; } state_est->gs_unpause_transform = state->gs_unpause_transform_count > 0; // Estimate the heading and position of the ground station. GroundStationEstimate ground_station; EstimatorGroundStationStep( &control_input->gs_gps, &faults[kSubsysGsGpsPos], control_input->gs_sensors.mode, &faults[kSubsysGroundStation], control_input->gs_sensors.detwist_pos, &faults[kSubsysDetwist], control_input->gs_sensors.transform_stage, &system_params->ground_frame, &params->ground_station, &state->ground_station, &ground_station); state_est->gs_mode = ground_station.mode; state_est->gs_transform_stage = ground_station.transform_stage; // Move detwist through an extra revolution, if commanded. state_est->force_detwist_turn_once = control_input->force_detwist_turn_once; EstimatorPerchAziStep(encoders.perch_azi, encoders.perch_azi_valid, &params->perch_azi, &state->perch_azi, &state_est->perch_azi); EstimatorVesselStep(&control_input->ground_estimate, &state_est->perch_azi, &faults[kSubsysGroundEstimatorPosition], &state->vessel, &state_est->vessel); // Estimate the tether payout and winch position. EstimatorWinchStep( control_input->gs_sensors.winch_pos, &faults[kSubsysDrum], control_input->gs_sensors.proximity, &faults[kSubsysGroundStation], flight_status->flight_mode == kFlightModePerched, system_params->gs_model, &system_params->winch, &state->winch, &state_est->winch); // Estimate the wind direction. EstimatorWindStep(initializing, &control_input->wind_ws, &faults[kSubsysWindSensor], &state_est->vessel, &system_params->wind_sensor, &params->wind, &state->wind, &state_est->wind_g); Vec3 acc_b; EstimatorNavKiteStep( initializing, control_input->imus, control_input->wing_gps, &control_input->gs_gps, control_input->pitots, &ground_station.pose, &state_est->wind_g, &encoders, &state_est->perch_azi, &state_est->tether_force_b, &state_est->winch, flight_status->flight_mode, faults, system_params, &params->nav, &state->nav, &state_est->pqr, &state_est->dcm_g2b, &state_est->Ag, &state_est->gps_active, &state_est->Vg, &state_est->Xg, &state_est->pqr_f, &state_est->Ab_f, &acc_b, &state_est->acc_norm_f, &state_est->Vb, &state_est->Vb_f, &state_est->Vg_f); ApparentWindSph apparent_wind_pitot; EstimatorApparentWindStep( control_input->pitots, &state_est->tether_force_b, &state_est->wind_g, &state_est->dcm_g2b, &state_est->pqr, &acc_b, &state_est->Ab_f, &state_est->Vg, faults, system_params, &params->apparent_wind, &state->apparent_wind, &state_est->apparent_wind, &apparent_wind_pitot); EstimatorWindAloftStep(initializing, &state_est->apparent_wind, &apparent_wind_pitot, &state_est->Vg, &state_est->dcm_g2b, &state_est->wind_g, &params->wind, &state->wind_aloft, &state_est->wind_aloft_g); // Saturate wind aloft playbook direction within limits. double wind_aloft_dir_allow_start = Wrap(state_est->wind_g.dir_f_playbook - params->wind.playbook_aloft_azi_offset_max, -PI, PI); double wind_aloft_dir_allow_end = Wrap(state_est->wind_g.dir_f_playbook + params->wind.playbook_aloft_azi_offset_max, -PI, PI); state_est->wind_aloft_g.dir_f_playbook = SaturateWrapped( state_est->wind_aloft_g.dir_f_playbook, wind_aloft_dir_allow_start, wind_aloft_dir_allow_end, -PI, PI); if (state->time < params->t_initialize) state->time += *g_sys.ts; // Update telemetry. GetEstimatorTelemetry()->initializing = initializing; GetEstimatorTelemetry()->ground_station = ground_station; EstimatorTetherGroundAnglesStep( initializing, system_params->gs_model, &ground_station, &state_est->winch, &state_est->vessel, &system_params->winch, &params->tether_ground_angles, &encoders, system_params->ground_station.gs02.detwist_elevation, &state->tether_ground_angles, &state_est->tether_ground_angles); EstimatorTetherAnchorPointStep(initializing, &state_est->winch, &state_est->vessel, state_est->winch.payout, &params->tether_anchor, &state->tether_anchor, &state_est->tether_anchor); }
44.677165
80
0.717131
[ "geometry" ]
ca77537b285a501c77ca35f08e97e91ce650805d
2,035
c
C
RfCore/uart/src/uart.c
kaseat/HC-12
bec7d50b1172c93bd03799880051801e9e351448
[ "Apache-2.0" ]
null
null
null
RfCore/uart/src/uart.c
kaseat/HC-12
bec7d50b1172c93bd03799880051801e9e351448
[ "Apache-2.0" ]
null
null
null
RfCore/uart/src/uart.c
kaseat/HC-12
bec7d50b1172c93bd03799880051801e9e351448
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Oleg Petrochenko // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "uart.h" #include "STM8S003F3.h" #include "platform.h" #include "clock.h" #include <string.h> static void(*reception_handler) (uint8_t) = 0; static uint32_t actual_baudrate; void uart_init(uint32_t baudrate) { // Configure GPIOs GPIOD->ODR |= 1 << 5; GPIOD->DDR |= 1 << 5; GPIOD->DDR &= ~(1 << 6); GPIOD->CR1 &= ~(1 << 6); GPIOD->CR2 &= ~(1 << 6); // Baudrate configuration. uart_set_baudrate(baudrate); // UART configuration. UART1->CR1 = 0; UART1->CR2 = UART_CR2_TEN | UART_CR2_REN; UART1->CR3 = 0; } void uart_set_baudrate(uint32_t baudrate) { actual_baudrate = baudrate; const uint32_t brr = get_cpu_freq() / baudrate; UART1->BRR2 = brr & 0x000F; UART1->BRR2 |= (brr >> 8) & 0x00F0; UART1->BRR1 = (brr >> 4) & 0x00FF; } uint32_t uart_get_baudrate() { return actual_baudrate; } void uart_send_byte(uint8_t data) { while (!(UART1->SR & UART_SR_TXE)) ; UART1->DR = data; } void uart_send_data(uint8_t* data, uint8_t len) { while (len--) uart_send_byte(*data++); } void uart_send_string(char* s) { uart_send_data((uint8_t*)s, strlen(s)); } void uart_subscribe_byte_reception(void(*handler) (uint8_t)) { reception_handler = handler; UART1->CR2 |= UART_CR2_RIEN; } void uart_unsubscribe_byte_reception() { reception_handler = 0; UART1->CR2 |= UART_CR2_RIEN; } #pragma vector = UART1_R_RXNE_ISR __interrupt void uart_byte_received() { if (reception_handler != 0) reception_handler(UART1->DR); }
22.611111
75
0.7086
[ "vector" ]
ca7a21a90affdbcbaae4e42819546ff79c47cf02
11,959
h
C
Frameworks/MaxLeap.framework/Headers/MLPrivateFile.h
LeapAppServices/LAS-Demo-PrivateFile-iOS
381021079f896fee10e25d5cad99f9b91179b353
[ "CC0-1.0" ]
1
2020-02-29T08:35:21.000Z
2020-02-29T08:35:21.000Z
Frameworks/MaxLeap.framework/Headers/MLPrivateFile.h
MaxLeap/Demo-PrivateFile-iOS
381021079f896fee10e25d5cad99f9b91179b353
[ "CC0-1.0" ]
null
null
null
Frameworks/MaxLeap.framework/Headers/MLPrivateFile.h
MaxLeap/Demo-PrivateFile-iOS
381021079f896fee10e25d5cad99f9b91179b353
[ "CC0-1.0" ]
null
null
null
// // MLPrivateFile.h // MaxLeap // // Created by Sun Jin on 15/4/8. // Copyright (c) 2015年 ilegendsoft. All rights reserved. // #ifdef EXTENSION_IOS #import <MaxLeapExt/MLConstants.h> #else #import <MaxLeap/MLConstants.h> #endif /** * A MaxLeap Framework object that represents metadata of private file. */ @interface MLPrivateFile : NSObject #pragma mark - ///-------------------------------------- /// @name Creating a Private File ///-------------------------------------- /** * Initialize a privateFile with localPath and remotePath. * * @param localPath The path of the file on local disk. * @param remotePath The path of the file on remote server, shouldn't be nil. * * @return A private file instance. */ - (instancetype)initWithLocalFileAtPath:(NSString *)localPath remotePath:(NSString *)remotePath NS_DESIGNATED_INITIALIZER; /** * Create a privateFile with remotePath. * * @param remotePath The path of the file on remote server, shouldn't be nil. * * @return A private file instance */ + (instancetype)fileWithRemotePath:(NSString *)remotePath; #pragma mark - ///-------------------------------------- /// @name Properties - File Metadata ///-------------------------------------- /** * A formated string representing the item size, eg: "1.1 MB", "832.5 KB". */ @property (nonatomic, readonly) NSString *size; /** * A number indicates the size of item in bytes. */ @property (nonatomic, readonly) NSUInteger bytes; /** * The file's MIMEType. */ @property (nonatomic, readonly) NSString *MIMEType; /** * Hash of the source file. */ @property (nonatomic, copy) NSString *fileHash; /** * When the file or directory was created. */ @property (nonatomic, readonly) NSDate *createdAt; /** * When the file or directory was last updated. */ @property (nonatomic, readonly) NSDate *updatedAt; /** * The item's path on remote server. */ @property (nonatomic, readonly) NSString *remotePath; /** * The local path of the item. */ @property (nonatomic, copy) NSString *localPath; /** * Whether this item is a directory. */ @property (nonatomic, readonly) BOOL isDirectory; /** * The contents of the dir. If this item is not a directory, contents is nil. */ @property (nonatomic, readonly) NSArray *contents; /** * Whether the item is deleted from remote server. */ @property (nonatomic, readonly) BOOL isDeleted; /** * Whether the item is shared from another user. */ @property (nonatomic, readonly) BOOL isShared; /** * The id of user who shared this item. */ @property (nonatomic, readonly) NSString *shareFrom; /** * The share url. */ @property (nonatomic, readonly) NSURL *url; #pragma mark - /*! @name Upload Private Files */ /** * *Asynchronously* upload file at file.localPath to MaxLeap file servers. * * @disscussion If the file's fileHash is not set, the md5 of file will be calculated and used. * If file exists on remote path, the uploading will fail with a kMLErrorPathTaken error. * * @param block Block to excute on main thread after uploading file, it should have the following argument signature: (BOOL success, NSError *error) */ - (void)saveInBackgroundWithBlock:(MLBooleanResultBlock)block; /** * *Asynchronously* upload file at file.localPath and save at the file.remotePath on MaxLeap file servers. * * @disscussion If the file's fileHash is not set, the md5 of file will be calculated and used. * If file exists on remote path, it will be overwrite. * * @param block Block to excute on main thread after uploading file, it should have the following argument signature: (BOOL success, NSError *error) */ - (void)saveAndOverwriteInBackgroundWithBlock:(MLBooleanResultBlock)block; /** * *Asynchronously* upload file at file.localPath and save at the file.remotePath on MaxLeap file servers. * * @disscussion If the file's fileHash is not set, the md5 of file will be calculated and used. * If file exists on remote path, the uploading will fail with a kMLErrorPathTaken error. * * @param block Block to excute on main thread after uploading file, it should have the following argument signature: (BOOL success, NSError *error) * @param progressBlock Block to notify the upload progress, it should have the following argument signature: (int percentDone) */ - (void)saveInBackgroundWithBlock:(MLBooleanResultBlock)block progressBlock:(MLProgressBlock)progressBlock; /** * *Asynchronously* upload file at file.localPath and save at the file.remotePath on MaxLeap file servers. * * @disscussion If the file's fileHash is not set, the md5 of file will be calculated and used. * If file exists on remote path, it will be overwrite. * * @param block Block to excute on main thread after uploading file, it should have the following argument signature: (BOOL success, NSError *error) * @param progressBlock Block to notify the upload progress, it should have the following argument signature: (int percentDone) */ - (void)saveAndOverwriteInBackgroundWithBlock:(MLBooleanResultBlock)block progressBlock:(MLProgressBlock)progressBlock; #pragma mark - /*! @name Download Private Files */ /** * Download and save the data at file.localPath. If the local path is nil, default path will be used. * * @param block Block to excute after file downloading. It should have the following argument signature: (NSString *filePath, NSError *error) */ - (void)downloadInBackgroundWithBlock:(MLBooleanResultBlock)block; /** * Download and save the data at file.localPath. If the local path is nil, default path will be used. * * @param block Block to excute after file downloading. It should have the following argument signature: (NSString *filePath, NSError *error) * @param progressBlock Block to notify the upload progress, it should have the following argument signature: (int percentDone) */ - (void)downloadInBackgroundWithBlock:(MLBooleanResultBlock)block progressBlock:(MLProgressBlock)progressBlock; /*! Cancels the current request (whether upload or download of file data). */ - (void)cancel; #pragma mark - /*! @name Delete Private Files */ /** * Delete the file at file.remotePath from remote server. * * @param block Block to excute after deleting, it should have the following argument signature: (BOOL success, NSError *error) */ - (void)deleteInBackgroundWithBlock:(MLBooleanResultBlock)block; /** * Delete the file at the path from remote server. * * @param path the remote path to delete * @param block Block to excute after deleting, it should have the following argument signature: (BOOL success, NSError *error) */ + (void)deletePathInBackground:(NSString *)path block:(MLBooleanResultBlock)block; /** * Deletes a collection of files all at once asynchronously and excutes the block when done. * * @param filePaths The remote paths of files to delete. * @param block The block should have the following argument signature: (BOOL success, NSError *error) */ + (void)deleteAllInBackground:(NSArray<NSString*> *)filePaths block:(void (^)(BOOL isAllDeleted, NSArray<NSString*> *deleted, NSError *error))block; #pragma mark - /*! @name Get Metadata of a Private File */ /** * Gets the metadata of a file and then excutes the block. * * @param block The block should have the following argument signature: (BOOL success, NSError *error) */ - (void)getMetadataInBackgroundWithBlock:(MLBooleanResultBlock)block; /** * Gets the metadata of a file including its children if it's a directory and then excutes the block. * * @param block The block should have the following argument signature: (BOOL success, NSError *error) */ - (void)getMetadataIncludeChildrenInBackgroundWithBlock:(MLBooleanResultBlock)block; /** * Gets the metadata of a file and excutes the block when done. * * @param skip The number of file metadata to skip before returning any. * @param limit A limit on the number of file metadata to return. The default limit is 200, with a maximum of 2000 results being returned at a time. * @param block The block should have the following argument signature: (BOOL success, NSError *error) */ - (void)getMetadataInBackgroundWithSkip:(int)skip andLimit:(int)limit block:(MLBooleanResultBlock)block; #pragma mark - /*! @name Get usage */ /** * Get the usage of current user. * * @param block The block parameter represents usage of current user. It has 3 parameters. 1. fileCount: How many private files the current user save on MaxLeap file servers. 2. usedCapacity: The capacity current user used in bytes. 3. error: If there is an error, both fileCount and usedCapacity are -1. */ + (void)getUsage:(MLUsageResultBlock)block; #pragma mark - /*! @name Copy Private Files */ /** * Copys a file to another remote path. * * @param dstPath The destination remote path. * @param block Block should have the following argument signature: (MLPrivateFile *newFile, NSError *error) */ - (void)copyToPathInBackground:(NSString *)dstPath block:(MLPrivateFileResultBlock)block; /** * Copys a collection of private files at `scrPaths` to remote paths `dstPaths`. The result will pass in the `block`. * The block has three parameters: `isAllCompleted` indicates whether all files was copied; `completed` contains an array of path pairs which was copied successfully, its structure: [{"from":scrPath, "to":dstPath}]; `error` is nil unless the network request failed or `scrPaths` does not match with `dstPaths`. * * @param scrPaths An array of private file remote path. * @param dstPaths An orderedSet of destination remote path. These paths must match with scrPaths. * @param block Block should have the following argument signature: (BOOL isAllCompleted, NSArray *completed, NSError *error) */ + (void)copyAllInBackground:(NSArray<NSString*> *)scrPaths toPaths:(NSOrderedSet<NSString*> *)dstPaths block:(void(^)(BOOL isAllCompleted, NSArray<NSString*> *completed, NSError *error))block; #pragma mark - /*! @name Move Private Files */ /** * Moves a file to another remote path. * * @param dstPath The destination remote path. * @param block Block should have the following argument signature: (MLPrivateFile *newFile, NSError *error) */ - (void)moveToPathInBackground:(NSString *)dstPath block:(MLBooleanResultBlock)block; /** * Moves a collection of private files at `scrPaths` to remote paths `dstPaths`. The result will pass in the `block`. * The block has three parameters: `isAllCompleted` indicates whether all files was moved; `completed` contains an array of path pairs which was copied successfully, its structure: [{"from":scrPath, "to":dstPath}]; `error` is nil unless the network request failed or `scrPaths` does not match with `dstPaths`. * * @param scrPaths An array of private file remote path. * @param dstPaths An orderedSet of destination remote path. These paths must match with `scrPaths`. * @param block Block should have the following argument signature: (BOOL isAllCompleted, NSArray *completed, NSError *error) */ + (void)moveAllInBackground:(NSOrderedSet<NSString*> *)scrPaths toPaths:(NSOrderedSet<NSString*> *)dstPaths block:(void(^)(BOOL isAllCompleted, NSArray<NSString*> *completed, NSError *error))block; #pragma mark - /*! @name Create Folder */ /** * Create a folder at remote path file.remotePath. * * @param path The remote path of a directory. * @param block Block should have the following argument signature: (BOOL success, NSError *error) */ + (void)createFolderAtPathInBackground:(NSString *)path block:(MLPrivateFileResultBlock)block; #pragma mark - /*! @name Share (Mock) */ /** * Share a file or directory. (Mock) * * @param block Block should have the following argument signature: (BOOL success, NSError *error) */ - (void)shareInBackgroundWithBlock:(MLBooleanResultBlock)block; @end
38.085987
311
0.721549
[ "object" ]
ca7dbe4f73c364277f141a3293809dc37832631d
11,918
h
C
source/blender/editors/space_outliner/outliner_intern.h
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_outliner/outliner_intern.h
1-MillionParanoidTterabytes/Blender-2.79b-blackened
e8d767324e69015aa66850d13bee7db1dc7d084b
[ "Unlicense" ]
null
null
null
source/blender/editors/space_outliner/outliner_intern.h
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) 2008 Blender Foundation. * All rights reserved. * * * Contributor(s): Blender Foundation * * ***** END GPL LICENSE BLOCK ***** */ /** \file blender/editors/space_outliner/outliner_intern.h * \ingroup spoutliner */ #ifndef __OUTLINER_INTERN_H__ #define __OUTLINER_INTERN_H__ #include "RNA_types.h" /* internal exports only */ struct wmOperatorType; struct TreeStoreElem; struct bContext; struct Scene; struct ID; struct Object; struct bPoseChannel; struct EditBone; typedef struct TreeElement { struct TreeElement *next, *prev, *parent; ListBase subtree; int xs, ys; // do selection TreeStoreElem *store_elem; // element in tree store short flag; // flag for non-saved stuff short index; // index for data arrays short idcode; // from TreeStore id short xend; // width of item display, for select const char *name; void *directdata; // Armature Bones, Base, Sequence, Strip... PointerRNA rnaptr; // RNA Pointer } TreeElement; #define TREESTORE_ID_TYPE(_id) \ (ELEM(GS((_id)->name), ID_SCE, ID_LI, ID_OB, ID_ME, ID_CU, ID_MB, ID_NT, ID_MA, ID_TE, ID_IM, ID_LT, ID_LA, ID_CA) || \ ELEM(GS((_id)->name), ID_KE, ID_WO, ID_SPK, ID_GR, ID_AR, ID_AC, ID_BR, ID_PA, ID_GD, ID_LS) || \ ELEM(GS((_id)->name), ID_SCR, ID_WM, ID_TXT, ID_VF, ID_SO, ID_CF, ID_PAL)) /* Only in 'blendfile' mode ... :/ */ /* TreeElement->flag */ #define TE_ACTIVE 1 #define TE_ICONROW 2 #define TE_LAZY_CLOSED 4 #define TE_FREE_NAME 8 /* button events */ #define OL_NAMEBUTTON 1 typedef enum { OL_DRAWSEL_NONE = 0, /* inactive (regular black text) */ OL_DRAWSEL_NORMAL = 1, /* active object (draws white text) */ OL_DRAWSEL_ACTIVE = 2, /* active obdata (draws a circle around the icon) */ } eOLDrawState; typedef enum { OL_SETSEL_NONE = 0, /* don't change the selection state */ OL_SETSEL_NORMAL = 1, /* select the item */ OL_SETSEL_EXTEND = 2, /* select the item and extend (also toggles selection) */ } eOLSetState; /* get TreeStoreElem associated with a TreeElement * < a: (TreeElement) tree element to find stored element for */ #define TREESTORE(a) ((a)->store_elem) /* size constants */ #define OL_Y_OFFSET 2 #define OL_TOG_RESTRICT_VIEWX (UI_UNIT_X * 3.0f) #define OL_TOG_RESTRICT_SELECTX (UI_UNIT_X * 2.0f) #define OL_TOG_RESTRICT_RENDERX UI_UNIT_X #define OL_TOGW OL_TOG_RESTRICT_VIEWX #define OL_RNA_COLX (UI_UNIT_X * 15) #define OL_RNA_COL_SIZEX (UI_UNIT_X * 7.5f) #define OL_RNA_COL_SPACEX (UI_UNIT_X * 2.5f) /* Outliner Searching -- * * Are we looking for something in the outliner? * If so finding matches in child items makes it more useful * * - We want to flag parents to act as being open to filter child matches * - and also flag matches so we can highlight them * - Flags are stored in TreeStoreElem->flag * - Flag options defined in DNA_outliner_types.h * - SO_SEARCH_RECURSIVE defined in DNA_space_types.h * * - NOT in datablocks view - searching all datablocks takes way too long * to be useful * - not searching into RNA items helps but isn't the complete solution */ #define SEARCHING_OUTLINER(sov) (sov->search_flags & SO_SEARCH_RECURSIVE) /* is the currrent element open? if so we also show children */ #define TSELEM_OPEN(telm, sv) ( (telm->flag & TSE_CLOSED) == 0 || (SEARCHING_OUTLINER(sv) && (telm->flag & TSE_CHILDSEARCH)) ) /* outliner_tree.c ----------------------------------------------- */ void outliner_free_tree(ListBase *lb); void outliner_cleanup_tree(struct SpaceOops *soops); TreeElement *outliner_find_tse(struct SpaceOops *soops, const TreeStoreElem *tse); TreeElement *outliner_find_tree_element(ListBase *lb, const TreeStoreElem *store_elem); TreeElement *outliner_find_id(struct SpaceOops *soops, ListBase *lb, const struct ID *id); TreeElement *outliner_find_posechannel(ListBase *lb, const struct bPoseChannel *pchan); TreeElement *outliner_find_editbone(ListBase *lb, const struct EditBone *ebone); struct ID *outliner_search_back(SpaceOops *soops, TreeElement *te, short idcode); void outliner_build_tree(struct Main *mainvar, struct Scene *scene, struct SpaceOops *soops); /* outliner_draw.c ---------------------------------------------- */ void draw_outliner(const struct bContext *C); void restrictbutton_gr_restrict_flag(void *poin, void *poin2, int flag); /* outliner_select.c -------------------------------------------- */ eOLDrawState tree_element_type_active( struct bContext *C, struct Scene *scene, struct SpaceOops *soops, TreeElement *te, TreeStoreElem *tselem, const eOLSetState set, bool recursive); eOLDrawState tree_element_active(struct bContext *C, struct Scene *scene, SpaceOops *soops, TreeElement *te, const eOLSetState set, const bool handle_all_types); void outliner_item_do_activate_from_tree_element( struct bContext *C, TreeElement *te, TreeStoreElem *tselem, bool extend, bool recursive); int outliner_item_do_activate_from_cursor( struct bContext *C, const int mval[2], bool extend, bool recursive); /* outliner_edit.c ---------------------------------------------- */ typedef void (*outliner_operation_cb)( struct bContext *C, struct ReportList *, struct Scene *scene, struct TreeElement *, struct TreeStoreElem *, TreeStoreElem *, void *); void outliner_do_object_operation_ex( struct bContext *C, ReportList *reports, struct Scene *scene, struct SpaceOops *soops, struct ListBase *lb, outliner_operation_cb operation_cb, bool recurse_selected); void outliner_do_object_operation( struct bContext *C, ReportList *reports, struct Scene *scene, struct SpaceOops *soops, struct ListBase *lb, outliner_operation_cb operation_cb); int common_restrict_check(struct bContext *C, struct Object *ob); int outliner_has_one_flag(ListBase *lb, short flag, const int curlevel); void outliner_set_flag(ListBase *lb, short flag, short set); void object_toggle_visibility_cb( struct bContext *C, struct ReportList *reports, struct Scene *scene, TreeElement *te, struct TreeStoreElem *tsep, struct TreeStoreElem *tselem, void *user_data); void object_toggle_selectability_cb( struct bContext *C, struct ReportList *reports, struct Scene *scene, TreeElement *te, struct TreeStoreElem *tsep, struct TreeStoreElem *tselem, void *user_data); void object_toggle_renderability_cb( struct bContext *C, struct ReportList *reports, struct Scene *scene, TreeElement *te, struct TreeStoreElem *tsep, struct TreeStoreElem *tselem, void *user_data); void group_toggle_visibility_cb( struct bContext *C, struct ReportList *reports, struct Scene *scene, TreeElement *te, struct TreeStoreElem *tsep, struct TreeStoreElem *tselem, void *user_data); void group_toggle_selectability_cb( struct bContext *C, struct ReportList *reports, struct Scene *scene, TreeElement *te, struct TreeStoreElem *tsep, struct TreeStoreElem *tselem, void *user_data); void group_toggle_renderability_cb( struct bContext *C, struct ReportList *reports, struct Scene *scene, TreeElement *te, struct TreeStoreElem *tsep, struct TreeStoreElem *tselem, void *user_data); void item_rename_cb( struct bContext *C, struct ReportList *reports, struct Scene *scene, TreeElement *te, struct TreeStoreElem *tsep, struct TreeStoreElem *tselem, void *user_data); void lib_relocate_cb( struct bContext *C, struct ReportList *reports, struct Scene *scene, struct TreeElement *te, struct TreeStoreElem *tsep, struct TreeStoreElem *tselem, void *user_data); void lib_reload_cb( struct bContext *C, struct ReportList *reports, struct Scene *scene, struct TreeElement *te, struct TreeStoreElem *tsep, struct TreeStoreElem *tselem, void *user_data); void id_delete_cb( struct bContext *C, struct ReportList *reports, struct Scene *scene, struct TreeElement *te, struct TreeStoreElem *tsep, struct TreeStoreElem *tselem, void *user_data); void id_remap_cb( struct bContext *C, struct ReportList *reports, struct Scene *scene, struct TreeElement *te, struct TreeStoreElem *tsep, struct TreeStoreElem *tselem, void *user_data); TreeElement *outliner_dropzone_find(const struct SpaceOops *soops, const float fmval[2], const bool children); /* ...................................................... */ void OUTLINER_OT_item_activate(struct wmOperatorType *ot); void OUTLINER_OT_item_openclose(struct wmOperatorType *ot); void OUTLINER_OT_item_rename(struct wmOperatorType *ot); void OUTLINER_OT_lib_relocate(struct wmOperatorType *ot); void OUTLINER_OT_lib_reload(struct wmOperatorType *ot); void OUTLINER_OT_id_delete(struct wmOperatorType *ot); void OUTLINER_OT_show_one_level(struct wmOperatorType *ot); void OUTLINER_OT_show_active(struct wmOperatorType *ot); void OUTLINER_OT_show_hierarchy(struct wmOperatorType *ot); void OUTLINER_OT_select_border(struct wmOperatorType *ot); void OUTLINER_OT_selected_toggle(struct wmOperatorType *ot); void OUTLINER_OT_expanded_toggle(struct wmOperatorType *ot); void OUTLINER_OT_scroll_page(struct wmOperatorType *ot); void OUTLINER_OT_renderability_toggle(struct wmOperatorType *ot); void OUTLINER_OT_selectability_toggle(struct wmOperatorType *ot); void OUTLINER_OT_visibility_toggle(struct wmOperatorType *ot); void OUTLINER_OT_keyingset_add_selected(struct wmOperatorType *ot); void OUTLINER_OT_keyingset_remove_selected(struct wmOperatorType *ot); void OUTLINER_OT_drivers_add_selected(struct wmOperatorType *ot); void OUTLINER_OT_drivers_delete_selected(struct wmOperatorType *ot); void OUTLINER_OT_orphans_purge(struct wmOperatorType *ot); void OUTLINER_OT_parent_drop(struct wmOperatorType *ot); void OUTLINER_OT_parent_clear(struct wmOperatorType *ot); void OUTLINER_OT_scene_drop(struct wmOperatorType *ot); void OUTLINER_OT_material_drop(struct wmOperatorType *ot); void OUTLINER_OT_group_link(struct wmOperatorType *ot); /* outliner_tools.c ---------------------------------------------- */ void OUTLINER_OT_operation(struct wmOperatorType *ot); void OUTLINER_OT_scene_operation(struct wmOperatorType *ot); void OUTLINER_OT_object_operation(struct wmOperatorType *ot); void OUTLINER_OT_group_operation(struct wmOperatorType *ot); void OUTLINER_OT_lib_operation(struct wmOperatorType *ot); void OUTLINER_OT_id_operation(struct wmOperatorType *ot); void OUTLINER_OT_id_remap(struct wmOperatorType *ot); void OUTLINER_OT_data_operation(struct wmOperatorType *ot); void OUTLINER_OT_animdata_operation(struct wmOperatorType *ot); void OUTLINER_OT_action_set(struct wmOperatorType *ot); void OUTLINER_OT_constraint_operation(struct wmOperatorType *ot); void OUTLINER_OT_modifier_operation(struct wmOperatorType *ot); /* ---------------------------------------------------------------- */ /* outliner_ops.c */ void outliner_operatortypes(void); void outliner_keymap(struct wmKeyConfig *keyconf); #endif /* __OUTLINER_INTERN_H__ */
43.025271
129
0.732841
[ "object" ]
ca7e4aadf7b552404525518b5204a84515543ecc
3,573
h
C
src/resource_manager.h
anneriet/OpenQL
f47ded9c2ab3840c7c8e6709d2444ff1b010f5dc
[ "Apache-2.0" ]
null
null
null
src/resource_manager.h
anneriet/OpenQL
f47ded9c2ab3840c7c8e6709d2444ff1b010f5dc
[ "Apache-2.0" ]
null
null
null
src/resource_manager.h
anneriet/OpenQL
f47ded9c2ab3840c7c8e6709d2444ff1b010f5dc
[ "Apache-2.0" ]
null
null
null
/** \file * Resource manager interface for the scheduler. */ #pragma once #include "utils/num.h" #include "utils/str.h" #include "utils/vec.h" #include "platform.h" namespace ql { typedef enum { forward_scheduling = 0, backward_scheduling = 1 } scheduling_direction_t; namespace arch { class resource_t { public: utils::Str name; utils::UInt count; scheduling_direction_t direction; resource_t(const utils::Str &n, scheduling_direction_t dir); virtual ~resource_t() = default; virtual utils::Bool available(utils::UInt op_start_cycle, gate *ins, const quantum_platform &platform) = 0; virtual void reserve(utils::UInt op_start_cycle, gate *ins, const quantum_platform &platform) = 0; virtual resource_t *clone() const & = 0; virtual resource_t *clone() && = 0; void Print(const utils::Str &s); }; class platform_resource_manager_t { public: utils::Vec<resource_t*> resource_ptrs; // constructor needed by mapper::FreeCycle to bridge time from its construction to its Init // see the note on the use of constructors and Init functions at the start of mapper.h platform_resource_manager_t() = default; platform_resource_manager_t( const quantum_platform &platform, scheduling_direction_t dir ); virtual platform_resource_manager_t *clone() const & = 0; virtual platform_resource_manager_t *clone() && = 0; void Print(const utils::Str &s); // copy constructor doing a deep copy // *org_resource_ptr->clone() does the trick to create a copy of the actual derived class' object platform_resource_manager_t(const platform_resource_manager_t &org); // copy-assignment operator // follow pattern to use tmp copy to allow self-assignment and to be exception safe platform_resource_manager_t &operator=(const platform_resource_manager_t &rhs); utils::Bool available(utils::UInt op_start_cycle, gate *ins, const quantum_platform &platform); void reserve(utils::UInt op_start_cycle, gate *ins, const quantum_platform &platform); // destructor destroying deep resource_t's // runs before shallow destruction which is done by synthesized platform_resource_manager_t destructor virtual ~platform_resource_manager_t(); }; class resource_manager_t { public: platform_resource_manager_t *platform_resource_manager_ptr; // pointer to specific platform_resource_manager resource_manager_t(); // (platform,dir) parameterized resource_manager_t // dynamically allocating platform specific platform_resource_manager_t depending on platform resource_manager_t(const quantum_platform &platform, scheduling_direction_t dir); // copy constructor doing a deep copy // *org_resource_manager.platform_resource_manager_ptr->clone() does the trick // to create a copy of the actual derived class' object resource_manager_t(const resource_manager_t &org_resource_manager); // copy-assignment operator // follow pattern to use tmp copy to allow self-assignment and to be exception safe resource_manager_t &operator=(const resource_manager_t &rhs); utils::Bool available(utils::UInt op_start_cycle, gate *ins, const quantum_platform &platform); void reserve(utils::UInt op_start_cycle, gate *ins, const quantum_platform &platform); // destructor destroying deep platform_resource_managert_t // runs before shallow destruction which is done by synthesized resource_manager_t destructor virtual ~resource_manager_t(); }; } // namespace arch } // namespacq ql
34.68932
116
0.747551
[ "object" ]
ca8018d6dc49db4335bcb799eed8b8bf88a62837
6,093
h
C
src/main/cpp/hw/DragonLimelight.h
Team302/mainRepotest
4d0099ae5fc9597126adc420e1eea3a70a6ba9a8
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/main/cpp/hw/DragonLimelight.h
Team302/mainRepotest
4d0099ae5fc9597126adc420e1eea3a70a6ba9a8
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/main/cpp/hw/DragonLimelight.h
Team302/mainRepotest
4d0099ae5fc9597126adc420e1eea3a70a6ba9a8
[ "BSD-3-Clause", "MIT" ]
null
null
null
//==================================================================================================================================================== // Copyright 2020 Lake Orion Robotics FIRST Team 302 // // 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 // C++ Includes #include <string> #include <vector> // FRC includes #include <networktables/NetworkTable.h> #include <units/angle.h> #include <units/length.h> #include <units/time.h> // Team 302 includes #include <hw/interfaces/IDragonSensor.h> #include <hw/interfaces/IDragonDistanceSensor.h> // Third Party Includes class DragonLimelight //: public IDragonSensor, public IDragonDistanceSensor { public: //Enums enum LED_MODE { LED_DEFAULT, LED_OFF, LED_BLINK, LED_ON }; enum CAM_MODE { CAM_VISION, CAM_DRIVER }; enum STREAM_MODE { STREAM_DEFAULT, // side by side if two cams STREAM_MAIN_AND_SECOND, // Second Cam bottom right of Main Cam STREAM_SECOND_AND_MAIN // Main Cam bottom right of Second Cam }; enum SNAPSHOT_MODE { SNAP_OFF, SNAP_ON }; ///----------------------------------------------------------------------------------- /// Method: DragonLimelight (constructor) /// Description: Create the object ///----------------------------------------------------------------------------------- DragonLimelight() = delete; DragonLimelight ( std::string tableName, /// <I> - network table name units::length::inch_t mountingHeight, /// <I> - mounting height of the limelight units::length::inch_t mountingHorizontalOffset, /// <I> - mounting horizontal offset from the middle of the robot units::angle::degree_t rotation, /// <I> - clockwise rotation of limelight units::angle::degree_t mountingAngle, /// <I> - mounting angle of the camera units::length::inch_t targetHeight, /// <I> - height the target units::length::inch_t targetHeight2 /// <I> - height of second target ); ///----------------------------------------------------------------------------------- /// Method: ~DragonLimelight (destructor) /// Description: Delete the object ///----------------------------------------------------------------------------------- ~DragonLimelight() = default; // Getters bool HasTarget() const; units::angle::degree_t GetTargetHorizontalOffset() const; units::angle::degree_t GetTargetVerticalOffset() const; double GetTargetArea() const; units::angle::degree_t GetTargetSkew() const; units::time::microsecond_t GetPipelineLatency() const; units::length::inch_t EstimateTargetDistance() const; std::vector<double> Get3DSolve() const; // Setters void SetTargetHeight ( units::length::inch_t targetHeight ); void SetLEDMode ( DragonLimelight::LED_MODE mode // 0-Default, 1-Off, 2-Blink, 3-On ); void SetCamMode ( DragonLimelight::CAM_MODE mode // 0-Vision, 1-Driver ); void SetPipeline ( int pipeline // 0-9 ); void SetStreamMode ( DragonLimelight::STREAM_MODE mode // 0-Side By Side, 1-Second cam bottom right of main, 2-Main bottom right second ); void ToggleSnapshot ( DragonLimelight::SNAPSHOT_MODE toggle // 0-No snapshots 1- two snapshots/second: Max of 32 saved ); void SetCrosshairPos ( double crosshairPosX, double crosshairPosY ); void SetSecondaryCrosshairPos ( double crosshairPosX, double crosshairPosY ); void PrintValues(); // Prints out all values to ensure everything is working and connected units::angle::degree_t GetMountingAngle() const {return m_mountingAngle;} units::length::inch_t GetMountingHeight() const {return m_mountHeight;} units::length::inch_t GetTargetHeight() const {return m_targetHeight;} private: std::shared_ptr<nt::NetworkTable> m_networktable; units::length::inch_t m_mountHeight; units::length::inch_t m_mountingHorizontalOffset; units::angle::degree_t m_rotation; units::angle::degree_t m_mountingAngle; units::length::inch_t m_targetHeight; units::length::inch_t m_targetHeight2; double PI = 3.14159265; };
37.152439
150
0.549811
[ "object", "vector" ]
ca806aa4d25c52282bca6cb5a010e00b6987a32f
5,014
h
C
model/sources/util.h
CATIA-Systems/FMU-Standalone-App
d2203eaea0723809466e2541d428897dcc35f518
[ "BSD-2-Clause" ]
8
2020-10-28T08:39:08.000Z
2021-09-02T21:46:35.000Z
model/sources/util.h
CATIA-Systems/FMU-Standalone-App
d2203eaea0723809466e2541d428897dcc35f518
[ "BSD-2-Clause" ]
3
2022-02-17T14:47:32.000Z
2022-03-17T07:39:15.000Z
model/sources/util.h
CATIA-Systems/FMU-Standalone-App
d2203eaea0723809466e2541d428897dcc35f518
[ "BSD-2-Clause" ]
3
2021-01-26T18:39:33.000Z
2022-01-29T21:43:07.000Z
/* Utility header file for Dymosim FMI implementation. */ #ifndef util_h #define util_h /* need to include first so that correct files are included */ #include "conf.h" #include "types.h" #include <float.h> /* ----------------- macros ----------------- */ /* Standard value reference */ /* idemand: 31-28, category: 27-24, index: 23-0 */ #define FMI_IDEMAND(valueRef) ((valueRef) >> 28) #define FMI_CATEGORY(valueRef) (((valueRef) & 0xf000000) >> 24) #define FMI_INDEX(valueRef) ((valueRef) & 0xffffff) /* Value reference for embedded systems */ /* idemand: 31-28, restricted: 27, FMI type size: 26-23, index: 22-0 */ #define MIN(A, B) ((A) <= (B) ? (A) : (B)) #define SMALL_TIME_DEV(curtime) (4 * DBL_EPSILON * (1 + fabs(curtime))) #define LOG(c, status, msg) util_logger(c, c->instanceName, status, "", msg) #define HANDLE_STATUS_RETURN(status) return (status == FMIError) ? util_error(comp) : status; #define MAX_STRING_SIZE 500 /*TODO support larger string sizes and allocate more memory if needed*/ /* ------------------ function declarations ----------------- */ /* logger wrapper for handling off enabled/disabled logging */ DYMOLA_STATIC void util_logger(Component* comp, FMIString instanceName, FMIStatus status, FMIString category, FMIString message, ...); /* buffered variant used when line breaks should be omitted */ DYMOLA_STATIC void util_buflogger(Component* comp, FMIString instanceName, FMIStatus status, FMIString category, FMIString message, ...); /* cannot use strdup since direct use of malloc not allowed */ DYMOLA_STATIC FMIString util_strdup(const FMICallbackFunctions *functions, FMIString s); /* locally modified variant from Sundials to store in buffer instead of printing */ DYMOLA_STATIC int util_check_flag(void *flagvalue, char *funcname, int opt, Component* comp); /* refresh variable values using dsblock_ */ DYMOLA_STATIC int util_refresh_cache(Component* comp, int idemand, const char* label, FMIBoolean* iterationConverged); /* handle termination due to an error */ DYMOLA_STATIC FMIStatus util_error(Component* comp); /* Initialize model, partly or completely, depending on argument "complete". */ DYMOLA_STATIC FMIStatus util_initialize_model(FMIComponent c, FMIBoolean toleranceControlled, FMIReal relativeTolerance, FMIBoolean complete); /* Perform event iteration. */ DYMOLA_STATIC FMIStatus util_event_update(FMIComponent c, FMIBoolean intermediateResults, #ifdef FMI_2 /* needs another argument since not in eventInfo for FMI 2*/ FMIBoolean* terminateSolution #else FMIEventInfo* eventInfo #endif ); /* Initialize slave, partly or completely, depending on FMI version */ DYMOLA_STATIC FMIStatus util_initialize_slave(FMIComponent c, FMIReal relativeTolerance, FMIReal tStart, FMIBoolean StopTimeDefined, FMIReal tStop); DYMOLA_STATIC void util_print_dymola_timers(FMIComponent c); /* Handle reference counting for external objects */ /* Use cases: - Add new or increment: count > 0. For new reference counter, count will be set to 2 (for original and first copy) - Decrement if exists: count < 0. - Just check for existence: count = 0. Note: If objAddr == NULL, -1 is returned and nothing is performed. */ /* Returns: count after update if exists or could be created, else -1 */ DYMOLA_STATIC int util_handle_external_object_ref_count(void* objAddr, int count); #ifdef FMI_2 /* Exit initialization mode. */ DYMOLA_STATIC FMIStatus util_exit_model_initialization_mode(FMIComponent c, const char* label, ModelStatus nextStatus); /* -------------------------------------------------------------------------------------------------------- API functions defined in earlier version of fmi 2.0 still in use internally ----------------------------------------------------------------------------------------------------------*/ /* Creation and destruction of model instances and setting debug status */ DYMOLA_STATIC FMIComponent fmiInstantiateModel_(FMIString, FMIString, FMIString, const FMICallbackFunctions*, FMIBoolean, FMIBoolean); DYMOLA_STATIC void fmiFreeModelInstance_(FMIComponent); /* Evaluation of the model equations */ DYMOLA_STATIC FMIStatus fmiEnterModelInitializationMode_(FMIComponent, FMIBoolean, FMIReal); DYMOLA_STATIC FMIStatus fmiExitModelInitializationMode_(FMIComponent); DYMOLA_STATIC FMIStatus fmiTerminateModel_(FMIComponent); /* Creation and destruction of slave instances */ DYMOLA_STATIC FMIComponent fmiInstantiateSlave_(FMIString, FMIString, FMIString, const FMICallbackFunctions*, FMIBoolean, FMIBoolean); DYMOLA_STATIC void fmiFreeSlaveInstance_(FMIComponent); /* Simulating the slave */ DYMOLA_STATIC FMIStatus fmiEnterSlaveInitializationMode_(FMIComponent, FMIReal, FMIReal, FMIBoolean, FMIReal); DYMOLA_STATIC FMIStatus fmiExitSlaveInitializationMode_(FMIComponent); DYMOLA_STATIC FMIStatus fmiTerminateSlave_(FMIComponent); DYMOLA_STATIC FMIStatus fmiResetSlave_(FMIComponent); #endif #endif /* util_h */
44.371681
148
0.726964
[ "model" ]
ca80e98a365745ea14170c747328d8cffac2d1f6
7,466
h
C
cytofpipe/v1.3/Rlibs/Rclusterpp/include/Rclusterpp/algorithm.h
UCL-BLIC/legion-buildscripts
5fd6c4e2a36b5ca35fa06577b2face58174a7d78
[ "MIT" ]
null
null
null
cytofpipe/v1.3/Rlibs/Rclusterpp/include/Rclusterpp/algorithm.h
UCL-BLIC/legion-buildscripts
5fd6c4e2a36b5ca35fa06577b2face58174a7d78
[ "MIT" ]
null
null
null
cytofpipe/v1.3/Rlibs/Rclusterpp/include/Rclusterpp/algorithm.h
UCL-BLIC/legion-buildscripts
5fd6c4e2a36b5ca35fa06577b2face58174a7d78
[ "MIT" ]
null
null
null
#ifndef RCLUSTERP_ALGORITHM_H #define RCLUSTERP_ALGORITHM_H #include <limits> #include <utility> #include <algorithm> #include <functional> #include <stack> #include <Rclusterpp/cluster.h> #include <Rclusterpp/util.h> namespace Rclusterpp { template<class RandomIterator, class Distancer> std::pair<RandomIterator, typename Distancer::result_type> nearest_neighbor( const RandomIterator& first, const RandomIterator& last, Distancer distancer, typename Distancer::result_type max_dist=std::numeric_limits<typename Distancer::result_type>::max() ) { typedef typename Distancer::result_type Dist_t; RandomIterator min_i = last; Dist_t min_d = max_dist; #ifdef _OPENMP #pragma omp parallel shared(min_i, min_d, distancer) #endif { RandomIterator min_i_l; Dist_t min_d_l = min_d; #ifdef _OPENMP #pragma omp for nowait #endif for (ssize_t i=0; i<(last-first); i++) { Dist_t dist = distancer(*(first+i), min_d_l); if (dist < min_d_l) { min_i_l = first + i; min_d_l = dist; } } #ifdef _OPENMP #pragma omp critical #endif { if (min_d_l < min_d) { min_i = min_i_l; min_d = min_d_l; } } } return std::make_pair(min_i, min_d); } template<class ClusteringMethod, class ClusterVector> void cluster_via_rnn(ClusteringMethod method, ClusterVector& clusters) { typedef ClusterVector clusters_type; typedef typename clusters_type::cluster_type cluster_type; typedef typename ClusteringMethod::distance_type distance_type; // Result from nearest neighbor scan typedef std::pair<typename clusters_type::iterator, distance_type> nearn_type; #define nn_cluster(x) (x).first #define distance_to_nn(x) (x).second // Nearest neighbor chain typedef std::pair<typename clusters_type::value_type, distance_type> entry_type; std::stack<entry_type> chain; #define cluster_at_tip(x) (x).top().first #define distance_to_tip(x) (x).top().second // Expand the size of clusters vector to the contain exactly the newly created clusters size_t initial_clusters = clusters.size(), result_clusters = (initial_clusters * 2) - 1; clusters.reserve(result_clusters); // List of valid clusters (used in mer Util::IndexList valid(initial_clusters); typename clusters_type::iterator next_unchained = clusters.begin(); while (clusters.size() != result_clusters) { if (chain.empty()) { // Pick next "unchained" cluster as default chain.push( entry_type(*next_unchained, std::numeric_limits<distance_type>::max()) ); ++next_unchained; } else { // Find next nearest neighbor from remaining "unchained" clusters nearn_type nn = nearest_neighbor( next_unchained, clusters.end(), Util::cluster_bind(method.distancer, cluster_at_tip(chain)), // Bind tip into distance function for computing nearest neighbor distance_to_tip(chain) ); if (nn.first != clusters.end()) { std::iter_swap(next_unchained, nn_cluster(nn)); chain.push( entry_type(*next_unchained, distance_to_nn(nn)) ); ++next_unchained; } else { // Tip of chain is recursive nearest neighbor cluster_type* r = cluster_at_tip(chain); distance_type d = distance_to_tip(chain); chain.pop(); cluster_type* l = cluster_at_tip(chain); chain.pop(); // Remove "tip" and "next tip" from chain and merge into new cluster appended to "unchained" clusters cluster_type* cn = ClusterVector::make_cluster(std::min(l->idx(), r->idx()), l, r, d); valid.remove(std::max(r->idx(), l->idx())); method.merger(*cn, *(cn->parent1()), *(cn->parent2()), valid); clusters.push_back(cn); } } } // Cleanup cluster listing // Re-order the clusters, with initial clusters in the beginning, ordered by id // from -1 .. -initial_clusters, followed by the agglomerated clusters sorted by // increasing disimilarity. Stable partition and stable sorting is required for // the latter to ensure merge order is maintaining for clusters with identical // dissimilarity. // Note, sort requires strict weak ordering and will fail in a data dependent way // if the comparison function does not satisfy that requirement typename clusters_type::iterator part = std::stable_partition(clusters.begin(), clusters.end(), std::mem_fun(&cluster_type::initial)); std::sort(clusters.begin(), part, &compare_id<cluster_type>); std::stable_sort(part, clusters.end(), std::ptr_fun(&compare_disimilarity<cluster_type>)); for (size_t i=initial_clusters; i<result_clusters; i++) { clusters[i]->set_id(i - initial_clusters + 1); // Use R hclust 1-indexed convention for Id's } } namespace { typedef std::pair<size_t, size_t> Merge_t; inline Merge_t make_merge(size_t from, size_t into) { return std::make_pair(from, into); } inline size_t from(const Merge_t& m) { return m.first; } inline size_t into(const Merge_t& m) { return m.second; } template<class Distance> struct MergeCMP { const Distance& height; MergeCMP(const Distance& height_) : height(height_) {} bool operator()(const Merge_t& a, const Merge_t& b) const { return height[from(a)] < height[from(b)]; } }; } // end of anonymous namespace template<class Distancer, class ClusterVector> void cluster_via_slink(const Distancer& distancer, ClusterVector& clusters) { typedef typename Distancer::result_type distance_type; size_t initial_clusters = clusters.size(), result_clusters = (initial_clusters * 2) - 1; clusters.reserve(result_clusters); std::vector<size_t> P = std::vector<size_t>(initial_clusters); std::vector<distance_type> L = std::vector<distance_type>(initial_clusters); std::vector<distance_type> M = std::vector<distance_type>(initial_clusters); for (size_t i=0; i<initial_clusters; i++) { // Step 1: Initialize P[i] = i; L[i] = std::numeric_limits<distance_type>::max(); // Step 2: Build out pairwise distances from objects in pointer // represenation to the new object #ifdef _OPENMP #pragma omp parallel for shared(i, M) #endif for (ssize_t j=0; j<(ssize_t)i; j++) { M[j] = distancer(i, j); } // Step 3: Update M, P, L for (size_t j=0; j<i; j++) { distance_type l = L[j], m = M[j]; if (l >= m) { M[P[j]] = std::min(M[P[j]], l); L[j] = m; P[j] = i; } else { M[P[j]] = std::min(M[P[j]], m); } } // Step 4: Actualize the clusters for (size_t j=0; j<i; j++) { if (L[j] >= L[P[j]]) P[j] = i; } } // Convert the pointer representation to dendogram std::vector<Merge_t> merges = std::vector<Merge_t>(initial_clusters-1); for (size_t i=0; i<(initial_clusters-1); i++) { merges[i] = make_merge(i, P[i]); // from, into } std::sort(merges.begin(), merges.end(), MergeCMP<std::vector<distance_type> >(L)); for (size_t i=0; i<initial_clusters; i++) { P[i] = i; } for (size_t i=0; i<(initial_clusters-1); i++) { size_t f = from(merges[i]), t = into(merges[i]); clusters.push_back(ClusterVector::make_cluster( 0, clusters[P[f]], clusters[P[t]], L[f] )); P[t] = i + initial_clusters; } for (size_t i=initial_clusters; i<result_clusters; i++) { clusters[i]->set_id(i - initial_clusters + 1); // Use R hclust 1-indexed convention for Id's } } } // end of Rclustercpp namespace #endif
31.238494
136
0.674123
[ "object", "vector" ]
ca841fb48bf3bc1e3121c2c315b03befd3230f6a
69,163
c
C
gromacs-4.6.5/src/mdlib/fftpack.c
farajilab/gifs_release
ffa674110bcd15de851a8b6a703b4f4bc96fcd2d
[ "MIT" ]
2
2022-03-04T18:56:08.000Z
2022-03-22T16:49:22.000Z
gromacs-4.6.5/src/mdlib/fftpack.c
farajilab/gifs_release
ffa674110bcd15de851a8b6a703b4f4bc96fcd2d
[ "MIT" ]
null
null
null
gromacs-4.6.5/src/mdlib/fftpack.c
farajilab/gifs_release
ffa674110bcd15de851a8b6a703b4f4bc96fcd2d
[ "MIT" ]
1
2022-02-08T00:11:00.000Z
2022-02-08T00:11:00.000Z
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2012, The GROMACS development team, * check out http://www.gromacs.org for more information. * Copyright (c) 2012,2013, by the GROMACS development team, led by * David van der Spoel, Berk Hess, Erik Lindahl, and including many * others, as listed in the AUTHORS file in the top-level source * directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /* ************************************************************ Copy of fftpack from Numpy with very minor modifications: - usage of fftpack.h (replacement for Treal define) - [cr]fft[ifb]1 non-static - Added Copyright headers - Added fftpack_ prefix Original version is from Numpy 1.6 ************************************************************ Copyright (c) 2005-2011, NumPy Developers. 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 NumPy Developers nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE 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. fftpack.c : A set of FFT routines in C. Algorithmically based on Fortran-77 FFTPACK by Paul N. Swarztrauber (Version 4, 1985). */ /* isign is +1 for backward and -1 for forward transforms */ #include <math.h> #include <stdio.h> #include "fftpack.h" #define ref(u, a) u[a] #define MAXFAC 13 /* maximum number of factors in factorization of n */ #define NSPECIAL 4 /* number of factors for which we have special-case routines */ #ifdef __cplusplus extern "C" { #endif /* ---------------------------------------------------------------------- passf2, passf3, passf4, passf5, passf. Complex FFT passes fwd and bwd. ---------------------------------------------------------------------- */ static void passf2(int ido, int l1, const Treal cc[], Treal ch[], const Treal wa1[], int isign) /* isign==+1 for backward transform */ { int i, k, ah, ac; Treal ti2, tr2; if (ido <= 2) { for (k = 0; k < l1; k++) { ah = k*ido; ac = 2*k*ido; ch[ah] = ref(cc, ac) + ref(cc, ac + ido); ch[ah + ido*l1] = ref(cc, ac) - ref(cc, ac + ido); ch[ah+1] = ref(cc, ac+1) + ref(cc, ac + ido + 1); ch[ah + ido*l1 + 1] = ref(cc, ac+1) - ref(cc, ac + ido + 1); } } else { for (k = 0; k < l1; k++) { for (i = 0; i < ido-1; i += 2) { ah = i + k*ido; ac = i + 2*k*ido; ch[ah] = ref(cc, ac) + ref(cc, ac + ido); tr2 = ref(cc, ac) - ref(cc, ac + ido); ch[ah+1] = ref(cc, ac+1) + ref(cc, ac + 1 + ido); ti2 = ref(cc, ac+1) - ref(cc, ac + 1 + ido); ch[ah+l1*ido+1] = wa1[i]*ti2 + isign*wa1[i+1]*tr2; ch[ah+l1*ido] = wa1[i]*tr2 - isign*wa1[i+1]*ti2; } } } } /* passf2 */ static void passf3(int ido, int l1, const Treal cc[], Treal ch[], const Treal wa1[], const Treal wa2[], int isign) /* isign==+1 for backward transform */ { static const Treal taur = -0.5; static const Treal taui = 0.866025403784439; int i, k, ac, ah; Treal ci2, ci3, di2, di3, cr2, cr3, dr2, dr3, ti2, tr2; if (ido == 2) { for (k = 1; k <= l1; k++) { ac = (3*k - 2)*ido; tr2 = ref(cc, ac) + ref(cc, ac + ido); cr2 = ref(cc, ac - ido) + taur*tr2; ah = (k - 1)*ido; ch[ah] = ref(cc, ac - ido) + tr2; ti2 = ref(cc, ac + 1) + ref(cc, ac + ido + 1); ci2 = ref(cc, ac - ido + 1) + taur*ti2; ch[ah + 1] = ref(cc, ac - ido + 1) + ti2; cr3 = isign*taui*(ref(cc, ac) - ref(cc, ac + ido)); ci3 = isign*taui*(ref(cc, ac + 1) - ref(cc, ac + ido + 1)); ch[ah + l1*ido] = cr2 - ci3; ch[ah + 2*l1*ido] = cr2 + ci3; ch[ah + l1*ido + 1] = ci2 + cr3; ch[ah + 2*l1*ido + 1] = ci2 - cr3; } } else { for (k = 1; k <= l1; k++) { for (i = 0; i < ido-1; i += 2) { ac = i + (3*k - 2)*ido; tr2 = ref(cc, ac) + ref(cc, ac + ido); cr2 = ref(cc, ac - ido) + taur*tr2; ah = i + (k-1)*ido; ch[ah] = ref(cc, ac - ido) + tr2; ti2 = ref(cc, ac + 1) + ref(cc, ac + ido + 1); ci2 = ref(cc, ac - ido + 1) + taur*ti2; ch[ah + 1] = ref(cc, ac - ido + 1) + ti2; cr3 = isign*taui*(ref(cc, ac) - ref(cc, ac + ido)); ci3 = isign*taui*(ref(cc, ac + 1) - ref(cc, ac + ido + 1)); dr2 = cr2 - ci3; dr3 = cr2 + ci3; di2 = ci2 + cr3; di3 = ci2 - cr3; ch[ah + l1*ido + 1] = wa1[i]*di2 + isign*wa1[i+1]*dr2; ch[ah + l1*ido] = wa1[i]*dr2 - isign*wa1[i+1]*di2; ch[ah + 2*l1*ido + 1] = wa2[i]*di3 + isign*wa2[i+1]*dr3; ch[ah + 2*l1*ido] = wa2[i]*dr3 - isign*wa2[i+1]*di3; } } } } /* passf3 */ static void passf4(int ido, int l1, const Treal cc[], Treal ch[], const Treal wa1[], const Treal wa2[], const Treal wa3[], int isign) /* isign == -1 for forward transform and +1 for backward transform */ { int i, k, ac, ah; Treal ci2, ci3, ci4, cr2, cr3, cr4, ti1, ti2, ti3, ti4, tr1, tr2, tr3, tr4; if (ido == 2) { for (k = 0; k < l1; k++) { ac = 4*k*ido + 1; ti1 = ref(cc, ac) - ref(cc, ac + 2*ido); ti2 = ref(cc, ac) + ref(cc, ac + 2*ido); tr4 = ref(cc, ac + 3*ido) - ref(cc, ac + ido); ti3 = ref(cc, ac + ido) + ref(cc, ac + 3*ido); tr1 = ref(cc, ac - 1) - ref(cc, ac + 2*ido - 1); tr2 = ref(cc, ac - 1) + ref(cc, ac + 2*ido - 1); ti4 = ref(cc, ac + ido - 1) - ref(cc, ac + 3*ido - 1); tr3 = ref(cc, ac + ido - 1) + ref(cc, ac + 3*ido - 1); ah = k*ido; ch[ah] = tr2 + tr3; ch[ah + 2*l1*ido] = tr2 - tr3; ch[ah + 1] = ti2 + ti3; ch[ah + 2*l1*ido + 1] = ti2 - ti3; ch[ah + l1*ido] = tr1 + isign*tr4; ch[ah + 3*l1*ido] = tr1 - isign*tr4; ch[ah + l1*ido + 1] = ti1 + isign*ti4; ch[ah + 3*l1*ido + 1] = ti1 - isign*ti4; } } else { for (k = 0; k < l1; k++) { for (i = 0; i < ido-1; i += 2) { ac = i + 1 + 4*k*ido; ti1 = ref(cc, ac) - ref(cc, ac + 2*ido); ti2 = ref(cc, ac) + ref(cc, ac + 2*ido); ti3 = ref(cc, ac + ido) + ref(cc, ac + 3*ido); tr4 = ref(cc, ac + 3*ido) - ref(cc, ac + ido); tr1 = ref(cc, ac - 1) - ref(cc, ac + 2*ido - 1); tr2 = ref(cc, ac - 1) + ref(cc, ac + 2*ido - 1); ti4 = ref(cc, ac + ido - 1) - ref(cc, ac + 3*ido - 1); tr3 = ref(cc, ac + ido - 1) + ref(cc, ac + 3*ido - 1); ah = i + k*ido; ch[ah] = tr2 + tr3; cr3 = tr2 - tr3; ch[ah + 1] = ti2 + ti3; ci3 = ti2 - ti3; cr2 = tr1 + isign*tr4; cr4 = tr1 - isign*tr4; ci2 = ti1 + isign*ti4; ci4 = ti1 - isign*ti4; ch[ah + l1*ido] = wa1[i]*cr2 - isign*wa1[i + 1]*ci2; ch[ah + l1*ido + 1] = wa1[i]*ci2 + isign*wa1[i + 1]*cr2; ch[ah + 2*l1*ido] = wa2[i]*cr3 - isign*wa2[i + 1]*ci3; ch[ah + 2*l1*ido + 1] = wa2[i]*ci3 + isign*wa2[i + 1]*cr3; ch[ah + 3*l1*ido] = wa3[i]*cr4 -isign*wa3[i + 1]*ci4; ch[ah + 3*l1*ido + 1] = wa3[i]*ci4 + isign*wa3[i + 1]*cr4; } } } } /* passf4 */ static void passf5(int ido, int l1, const Treal cc[], Treal ch[], const Treal wa1[], const Treal wa2[], const Treal wa3[], const Treal wa4[], int isign) /* isign == -1 for forward transform and +1 for backward transform */ { static const Treal tr11 = 0.309016994374947; static const Treal ti11 = 0.951056516295154; static const Treal tr12 = -0.809016994374947; static const Treal ti12 = 0.587785252292473; int i, k, ac, ah; Treal ci2, ci3, ci4, ci5, di3, di4, di5, di2, cr2, cr3, cr5, cr4, ti2, ti3, ti4, ti5, dr3, dr4, dr5, dr2, tr2, tr3, tr4, tr5; if (ido == 2) { for (k = 1; k <= l1; ++k) { ac = (5*k - 4)*ido + 1; ti5 = ref(cc, ac) - ref(cc, ac + 3*ido); ti2 = ref(cc, ac) + ref(cc, ac + 3*ido); ti4 = ref(cc, ac + ido) - ref(cc, ac + 2*ido); ti3 = ref(cc, ac + ido) + ref(cc, ac + 2*ido); tr5 = ref(cc, ac - 1) - ref(cc, ac + 3*ido - 1); tr2 = ref(cc, ac - 1) + ref(cc, ac + 3*ido - 1); tr4 = ref(cc, ac + ido - 1) - ref(cc, ac + 2*ido - 1); tr3 = ref(cc, ac + ido - 1) + ref(cc, ac + 2*ido - 1); ah = (k - 1)*ido; ch[ah] = ref(cc, ac - ido - 1) + tr2 + tr3; ch[ah + 1] = ref(cc, ac - ido) + ti2 + ti3; cr2 = ref(cc, ac - ido - 1) + tr11*tr2 + tr12*tr3; ci2 = ref(cc, ac - ido) + tr11*ti2 + tr12*ti3; cr3 = ref(cc, ac - ido - 1) + tr12*tr2 + tr11*tr3; ci3 = ref(cc, ac - ido) + tr12*ti2 + tr11*ti3; cr5 = isign*(ti11*tr5 + ti12*tr4); ci5 = isign*(ti11*ti5 + ti12*ti4); cr4 = isign*(ti12*tr5 - ti11*tr4); ci4 = isign*(ti12*ti5 - ti11*ti4); ch[ah + l1*ido] = cr2 - ci5; ch[ah + 4*l1*ido] = cr2 + ci5; ch[ah + l1*ido + 1] = ci2 + cr5; ch[ah + 2*l1*ido + 1] = ci3 + cr4; ch[ah + 2*l1*ido] = cr3 - ci4; ch[ah + 3*l1*ido] = cr3 + ci4; ch[ah + 3*l1*ido + 1] = ci3 - cr4; ch[ah + 4*l1*ido + 1] = ci2 - cr5; } } else { for (k = 1; k <= l1; k++) { for (i = 0; i < ido-1; i += 2) { ac = i + 1 + (k*5 - 4)*ido; ti5 = ref(cc, ac) - ref(cc, ac + 3*ido); ti2 = ref(cc, ac) + ref(cc, ac + 3*ido); ti4 = ref(cc, ac + ido) - ref(cc, ac + 2*ido); ti3 = ref(cc, ac + ido) + ref(cc, ac + 2*ido); tr5 = ref(cc, ac - 1) - ref(cc, ac + 3*ido - 1); tr2 = ref(cc, ac - 1) + ref(cc, ac + 3*ido - 1); tr4 = ref(cc, ac + ido - 1) - ref(cc, ac + 2*ido - 1); tr3 = ref(cc, ac + ido - 1) + ref(cc, ac + 2*ido - 1); ah = i + (k - 1)*ido; ch[ah] = ref(cc, ac - ido - 1) + tr2 + tr3; ch[ah + 1] = ref(cc, ac - ido) + ti2 + ti3; cr2 = ref(cc, ac - ido - 1) + tr11*tr2 + tr12*tr3; ci2 = ref(cc, ac - ido) + tr11*ti2 + tr12*ti3; cr3 = ref(cc, ac - ido - 1) + tr12*tr2 + tr11*tr3; ci3 = ref(cc, ac - ido) + tr12*ti2 + tr11*ti3; cr5 = isign*(ti11*tr5 + ti12*tr4); ci5 = isign*(ti11*ti5 + ti12*ti4); cr4 = isign*(ti12*tr5 - ti11*tr4); ci4 = isign*(ti12*ti5 - ti11*ti4); dr3 = cr3 - ci4; dr4 = cr3 + ci4; di3 = ci3 + cr4; di4 = ci3 - cr4; dr5 = cr2 + ci5; dr2 = cr2 - ci5; di5 = ci2 - cr5; di2 = ci2 + cr5; ch[ah + l1*ido] = wa1[i]*dr2 - isign*wa1[i+1]*di2; ch[ah + l1*ido + 1] = wa1[i]*di2 + isign*wa1[i+1]*dr2; ch[ah + 2*l1*ido] = wa2[i]*dr3 - isign*wa2[i+1]*di3; ch[ah + 2*l1*ido + 1] = wa2[i]*di3 + isign*wa2[i+1]*dr3; ch[ah + 3*l1*ido] = wa3[i]*dr4 - isign*wa3[i+1]*di4; ch[ah + 3*l1*ido + 1] = wa3[i]*di4 + isign*wa3[i+1]*dr4; ch[ah + 4*l1*ido] = wa4[i]*dr5 - isign*wa4[i+1]*di5; ch[ah + 4*l1*ido + 1] = wa4[i]*di5 + isign*wa4[i+1]*dr5; } } } } /* passf5 */ static void passf(int *nac, int ido, int ip, int l1, int idl1, Treal cc[], Treal ch[], const Treal wa[], int isign) /* isign is -1 for forward transform and +1 for backward transform */ { int idij, idlj, idot, ipph, i, j, k, l, jc, lc, ik, idj, idl, inc, idp; Treal wai, war; idot = ido / 2; /* nt = ip*idl1;*/ ipph = (ip + 1) / 2; idp = ip*ido; if (ido >= l1) { for (j = 1; j < ipph; j++) { jc = ip - j; for (k = 0; k < l1; k++) { for (i = 0; i < ido; i++) { ch[i + (k + j*l1)*ido] = ref(cc, i + (j + k*ip)*ido) + ref(cc, i + (jc + k*ip)*ido); ch[i + (k + jc*l1)*ido] = ref(cc, i + (j + k*ip)*ido) - ref(cc, i + (jc + k*ip)*ido); } } } for (k = 0; k < l1; k++) { for (i = 0; i < ido; i++) { ch[i + k*ido] = ref(cc, i + k*ip*ido); } } } else { for (j = 1; j < ipph; j++) { jc = ip - j; for (i = 0; i < ido; i++) { for (k = 0; k < l1; k++) { ch[i + (k + j*l1)*ido] = ref(cc, i + (j + k*ip)*ido) + ref(cc, i + (jc + k* ip)*ido); ch[i + (k + jc*l1)*ido] = ref(cc, i + (j + k*ip)*ido) - ref(cc, i + (jc + k* ip)*ido); } } } for (i = 0; i < ido; i++) { for (k = 0; k < l1; k++) { ch[i + k*ido] = ref(cc, i + k*ip*ido); } } } idl = 2 - ido; inc = 0; for (l = 1; l < ipph; l++) { lc = ip - l; idl += ido; for (ik = 0; ik < idl1; ik++) { cc[ik + l*idl1] = ch[ik] + wa[idl - 2]*ch[ik + idl1]; cc[ik + lc*idl1] = isign*wa[idl-1]*ch[ik + (ip-1)*idl1]; } idlj = idl; inc += ido; for (j = 2; j < ipph; j++) { jc = ip - j; idlj += inc; if (idlj > idp) { idlj -= idp; } war = wa[idlj - 2]; wai = wa[idlj-1]; for (ik = 0; ik < idl1; ik++) { cc[ik + l*idl1] += war*ch[ik + j*idl1]; cc[ik + lc*idl1] += isign*wai*ch[ik + jc*idl1]; } } } for (j = 1; j < ipph; j++) { for (ik = 0; ik < idl1; ik++) { ch[ik] += ch[ik + j*idl1]; } } for (j = 1; j < ipph; j++) { jc = ip - j; for (ik = 1; ik < idl1; ik += 2) { ch[ik - 1 + j*idl1] = cc[ik - 1 + j*idl1] - cc[ik + jc*idl1]; ch[ik - 1 + jc*idl1] = cc[ik - 1 + j*idl1] + cc[ik + jc*idl1]; ch[ik + j*idl1] = cc[ik + j*idl1] + cc[ik - 1 + jc*idl1]; ch[ik + jc*idl1] = cc[ik + j*idl1] - cc[ik - 1 + jc*idl1]; } } *nac = 1; if (ido == 2) { return; } *nac = 0; for (ik = 0; ik < idl1; ik++) { cc[ik] = ch[ik]; } for (j = 1; j < ip; j++) { for (k = 0; k < l1; k++) { cc[(k + j*l1)*ido + 0] = ch[(k + j*l1)*ido + 0]; cc[(k + j*l1)*ido + 1] = ch[(k + j*l1)*ido + 1]; } } if (idot <= l1) { idij = 0; for (j = 1; j < ip; j++) { idij += 2; for (i = 3; i < ido; i += 2) { idij += 2; for (k = 0; k < l1; k++) { cc[i - 1 + (k + j*l1)*ido] = wa[idij - 2]*ch[i - 1 + (k + j*l1)*ido] - isign*wa[idij-1]*ch[i + (k + j*l1)*ido]; cc[i + (k + j*l1)*ido] = wa[idij - 2]*ch[i + (k + j*l1)*ido] + isign*wa[idij-1]*ch[i - 1 + (k + j*l1)*ido]; } } } } else { idj = 2 - ido; for (j = 1; j < ip; j++) { idj += ido; for (k = 0; k < l1; k++) { idij = idj; for (i = 3; i < ido; i += 2) { idij += 2; cc[i - 1 + (k + j*l1)*ido] = wa[idij - 2]*ch[i - 1 + (k + j*l1)*ido] - isign*wa[idij-1]*ch[i + (k + j*l1)*ido]; cc[i + (k + j*l1)*ido] = wa[idij - 2]*ch[i + (k + j*l1)*ido] + isign*wa[idij-1]*ch[i - 1 + (k + j*l1)*ido]; } } } } } /* passf */ /* ---------------------------------------------------------------------- radf2,radb2, radf3,radb3, radf4,radb4, radf5,radb5, radfg,radbg. Treal FFT passes fwd and bwd. ---------------------------------------------------------------------- */ static void radf2(int ido, int l1, const Treal cc[], Treal ch[], const Treal wa1[]) { int i, k, ic; Treal ti2, tr2; for (k = 0; k < l1; k++) { ch[2*k*ido] = ref(cc, k*ido) + ref(cc, (k + l1)*ido); ch[(2*k+1)*ido + ido-1] = ref(cc, k*ido) - ref(cc, (k + l1)*ido); } if (ido < 2) { return; } if (ido != 2) { for (k = 0; k < l1; k++) { for (i = 2; i < ido; i += 2) { ic = ido - i; tr2 = wa1[i - 2]*ref(cc, i-1 + (k + l1)*ido) + wa1[i - 1]*ref(cc, i + (k + l1)*ido); ti2 = wa1[i - 2]*ref(cc, i + (k + l1)*ido) - wa1[i - 1]*ref(cc, i-1 + (k + l1)*ido); ch[i + 2*k*ido] = ref(cc, i + k*ido) + ti2; ch[ic + (2*k+1)*ido] = ti2 - ref(cc, i + k*ido); ch[i - 1 + 2*k*ido] = ref(cc, i - 1 + k*ido) + tr2; ch[ic - 1 + (2*k+1)*ido] = ref(cc, i - 1 + k*ido) - tr2; } } if (ido % 2 == 1) { return; } } for (k = 0; k < l1; k++) { ch[(2*k+1)*ido] = -ref(cc, ido-1 + (k + l1)*ido); ch[ido-1 + 2*k*ido] = ref(cc, ido-1 + k*ido); } } /* radf2 */ static void radb2(int ido, int l1, const Treal cc[], Treal ch[], const Treal wa1[]) { int i, k, ic; Treal ti2, tr2; for (k = 0; k < l1; k++) { ch[k*ido] = ref(cc, 2*k*ido) + ref(cc, ido-1 + (2*k+1)*ido); ch[(k + l1)*ido] = ref(cc, 2*k*ido) - ref(cc, ido-1 + (2*k+1)*ido); } if (ido < 2) { return; } if (ido != 2) { for (k = 0; k < l1; ++k) { for (i = 2; i < ido; i += 2) { ic = ido - i; ch[i-1 + k*ido] = ref(cc, i-1 + 2*k*ido) + ref(cc, ic-1 + (2*k+1)*ido); tr2 = ref(cc, i-1 + 2*k*ido) - ref(cc, ic-1 + (2*k+1)*ido); ch[i + k*ido] = ref(cc, i + 2*k*ido) - ref(cc, ic + (2*k+1)*ido); ti2 = ref(cc, i + (2*k)*ido) + ref(cc, ic + (2*k+1)*ido); ch[i-1 + (k + l1)*ido] = wa1[i - 2]*tr2 - wa1[i - 1]*ti2; ch[i + (k + l1)*ido] = wa1[i - 2]*ti2 + wa1[i - 1]*tr2; } } if (ido % 2 == 1) { return; } } for (k = 0; k < l1; k++) { ch[ido-1 + k*ido] = 2*ref(cc, ido-1 + 2*k*ido); ch[ido-1 + (k + l1)*ido] = -2*ref(cc, (2*k+1)*ido); } } /* radb2 */ static void radf3(int ido, int l1, const Treal cc[], Treal ch[], const Treal wa1[], const Treal wa2[]) { static const Treal taur = -0.5; static const Treal taui = 0.866025403784439; int i, k, ic; Treal ci2, di2, di3, cr2, dr2, dr3, ti2, ti3, tr2, tr3; for (k = 0; k < l1; k++) { cr2 = ref(cc, (k + l1)*ido) + ref(cc, (k + 2*l1)*ido); ch[3*k*ido] = ref(cc, k*ido) + cr2; ch[(3*k+2)*ido] = taui*(ref(cc, (k + l1*2)*ido) - ref(cc, (k + l1)*ido)); ch[ido-1 + (3*k + 1)*ido] = ref(cc, k*ido) + taur*cr2; } if (ido == 1) { return; } for (k = 0; k < l1; k++) { for (i = 2; i < ido; i += 2) { ic = ido - i; dr2 = wa1[i - 2]*ref(cc, i - 1 + (k + l1)*ido) + wa1[i - 1]*ref(cc, i + (k + l1)*ido); di2 = wa1[i - 2]*ref(cc, i + (k + l1)*ido) - wa1[i - 1]*ref(cc, i - 1 + (k + l1)*ido); dr3 = wa2[i - 2]*ref(cc, i - 1 + (k + l1*2)*ido) + wa2[i - 1]*ref(cc, i + (k + l1*2)*ido); di3 = wa2[i - 2]*ref(cc, i + (k + l1*2)*ido) - wa2[i - 1]*ref(cc, i - 1 + (k + l1*2)*ido); cr2 = dr2 + dr3; ci2 = di2 + di3; ch[i - 1 + 3*k*ido] = ref(cc, i - 1 + k*ido) + cr2; ch[i + 3*k*ido] = ref(cc, i + k*ido) + ci2; tr2 = ref(cc, i - 1 + k*ido) + taur*cr2; ti2 = ref(cc, i + k*ido) + taur*ci2; tr3 = taui*(di2 - di3); ti3 = taui*(dr3 - dr2); ch[i - 1 + (3*k + 2)*ido] = tr2 + tr3; ch[ic - 1 + (3*k + 1)*ido] = tr2 - tr3; ch[i + (3*k + 2)*ido] = ti2 + ti3; ch[ic + (3*k + 1)*ido] = ti3 - ti2; } } } /* radf3 */ static void radb3(int ido, int l1, const Treal cc[], Treal ch[], const Treal wa1[], const Treal wa2[]) { static const Treal taur = -0.5; static const Treal taui = 0.866025403784439; int i, k, ic; Treal ci2, ci3, di2, di3, cr2, cr3, dr2, dr3, ti2, tr2; for (k = 0; k < l1; k++) { tr2 = 2*ref(cc, ido-1 + (3*k + 1)*ido); cr2 = ref(cc, 3*k*ido) + taur*tr2; ch[k*ido] = ref(cc, 3*k*ido) + tr2; ci3 = 2*taui*ref(cc, (3*k + 2)*ido); ch[(k + l1)*ido] = cr2 - ci3; ch[(k + 2*l1)*ido] = cr2 + ci3; } if (ido == 1) { return; } for (k = 0; k < l1; k++) { for (i = 2; i < ido; i += 2) { ic = ido - i; tr2 = ref(cc, i - 1 + (3*k + 2)*ido) + ref(cc, ic - 1 + (3*k + 1)*ido); cr2 = ref(cc, i - 1 + 3*k*ido) + taur*tr2; ch[i - 1 + k*ido] = ref(cc, i - 1 + 3*k*ido) + tr2; ti2 = ref(cc, i + (3*k + 2)*ido) - ref(cc, ic + (3*k + 1)*ido); ci2 = ref(cc, i + 3*k*ido) + taur*ti2; ch[i + k*ido] = ref(cc, i + 3*k*ido) + ti2; cr3 = taui*(ref(cc, i - 1 + (3*k + 2)*ido) - ref(cc, ic - 1 + (3*k + 1)*ido)); ci3 = taui*(ref(cc, i + (3*k + 2)*ido) + ref(cc, ic + (3*k + 1)*ido)); dr2 = cr2 - ci3; dr3 = cr2 + ci3; di2 = ci2 + cr3; di3 = ci2 - cr3; ch[i - 1 + (k + l1)*ido] = wa1[i - 2]*dr2 - wa1[i - 1]*di2; ch[i + (k + l1)*ido] = wa1[i - 2]*di2 + wa1[i - 1]*dr2; ch[i - 1 + (k + 2*l1)*ido] = wa2[i - 2]*dr3 - wa2[i - 1]*di3; ch[i + (k + 2*l1)*ido] = wa2[i - 2]*di3 + wa2[i - 1]*dr3; } } } /* radb3 */ static void radf4(int ido, int l1, const Treal cc[], Treal ch[], const Treal wa1[], const Treal wa2[], const Treal wa3[]) { static const Treal hsqt2 = 0.7071067811865475; int i, k, ic; Treal ci2, ci3, ci4, cr2, cr3, cr4, ti1, ti2, ti3, ti4, tr1, tr2, tr3, tr4; for (k = 0; k < l1; k++) { tr1 = ref(cc, (k + l1)*ido) + ref(cc, (k + 3*l1)*ido); tr2 = ref(cc, k*ido) + ref(cc, (k + 2*l1)*ido); ch[4*k*ido] = tr1 + tr2; ch[ido-1 + (4*k + 3)*ido] = tr2 - tr1; ch[ido-1 + (4*k + 1)*ido] = ref(cc, k*ido) - ref(cc, (k + 2*l1)*ido); ch[(4*k + 2)*ido] = ref(cc, (k + 3*l1)*ido) - ref(cc, (k + l1)*ido); } if (ido < 2) { return; } if (ido != 2) { for (k = 0; k < l1; k++) { for (i = 2; i < ido; i += 2) { ic = ido - i; cr2 = wa1[i - 2]*ref(cc, i - 1 + (k + l1)*ido) + wa1[i - 1]*ref(cc, i + (k + l1)*ido); ci2 = wa1[i - 2]*ref(cc, i + (k + l1)*ido) - wa1[i - 1]*ref(cc, i - 1 + (k + l1)*ido); cr3 = wa2[i - 2]*ref(cc, i - 1 + (k + 2*l1)*ido) + wa2[i - 1]*ref(cc, i + (k + 2*l1)* ido); ci3 = wa2[i - 2]*ref(cc, i + (k + 2*l1)*ido) - wa2[i - 1]*ref(cc, i - 1 + (k + 2*l1)* ido); cr4 = wa3[i - 2]*ref(cc, i - 1 + (k + 3*l1)*ido) + wa3[i - 1]*ref(cc, i + (k + 3*l1)* ido); ci4 = wa3[i - 2]*ref(cc, i + (k + 3*l1)*ido) - wa3[i - 1]*ref(cc, i - 1 + (k + 3*l1)* ido); tr1 = cr2 + cr4; tr4 = cr4 - cr2; ti1 = ci2 + ci4; ti4 = ci2 - ci4; ti2 = ref(cc, i + k*ido) + ci3; ti3 = ref(cc, i + k*ido) - ci3; tr2 = ref(cc, i - 1 + k*ido) + cr3; tr3 = ref(cc, i - 1 + k*ido) - cr3; ch[i - 1 + 4*k*ido] = tr1 + tr2; ch[ic - 1 + (4*k + 3)*ido] = tr2 - tr1; ch[i + 4*k*ido] = ti1 + ti2; ch[ic + (4*k + 3)*ido] = ti1 - ti2; ch[i - 1 + (4*k + 2)*ido] = ti4 + tr3; ch[ic - 1 + (4*k + 1)*ido] = tr3 - ti4; ch[i + (4*k + 2)*ido] = tr4 + ti3; ch[ic + (4*k + 1)*ido] = tr4 - ti3; } } if (ido % 2 == 1) { return; } } for (k = 0; k < l1; k++) { ti1 = -hsqt2*(ref(cc, ido-1 + (k + l1)*ido) + ref(cc, ido-1 + (k + 3*l1)*ido)); tr1 = hsqt2*(ref(cc, ido-1 + (k + l1)*ido) - ref(cc, ido-1 + (k + 3*l1)*ido)); ch[ido-1 + 4*k*ido] = tr1 + ref(cc, ido-1 + k*ido); ch[ido-1 + (4*k + 2)*ido] = ref(cc, ido-1 + k*ido) - tr1; ch[(4*k + 1)*ido] = ti1 - ref(cc, ido-1 + (k + 2*l1)*ido); ch[(4*k + 3)*ido] = ti1 + ref(cc, ido-1 + (k + 2*l1)*ido); } } /* radf4 */ static void radb4(int ido, int l1, const Treal cc[], Treal ch[], const Treal wa1[], const Treal wa2[], const Treal wa3[]) { static const Treal sqrt2 = 1.414213562373095; int i, k, ic; Treal ci2, ci3, ci4, cr2, cr3, cr4, ti1, ti2, ti3, ti4, tr1, tr2, tr3, tr4; for (k = 0; k < l1; k++) { tr1 = ref(cc, 4*k*ido) - ref(cc, ido-1 + (4*k + 3)*ido); tr2 = ref(cc, 4*k*ido) + ref(cc, ido-1 + (4*k + 3)*ido); tr3 = ref(cc, ido-1 + (4*k + 1)*ido) + ref(cc, ido-1 + (4*k + 1)*ido); tr4 = ref(cc, (4*k + 2)*ido) + ref(cc, (4*k + 2)*ido); ch[k*ido] = tr2 + tr3; ch[(k + l1)*ido] = tr1 - tr4; ch[(k + 2*l1)*ido] = tr2 - tr3; ch[(k + 3*l1)*ido] = tr1 + tr4; } if (ido < 2) { return; } if (ido != 2) { for (k = 0; k < l1; ++k) { for (i = 2; i < ido; i += 2) { ic = ido - i; ti1 = ref(cc, i + 4*k*ido) + ref(cc, ic + (4*k + 3)*ido); ti2 = ref(cc, i + 4*k*ido) - ref(cc, ic + (4*k + 3)*ido); ti3 = ref(cc, i + (4*k + 2)*ido) - ref(cc, ic + (4*k + 1)*ido); tr4 = ref(cc, i + (4*k + 2)*ido) + ref(cc, ic + (4*k + 1)*ido); tr1 = ref(cc, i - 1 + 4*k*ido) - ref(cc, ic - 1 + (4*k + 3)*ido); tr2 = ref(cc, i - 1 + 4*k*ido) + ref(cc, ic - 1 + (4*k + 3)*ido); ti4 = ref(cc, i - 1 + (4*k + 2)*ido) - ref(cc, ic - 1 + (4*k + 1)*ido); tr3 = ref(cc, i - 1 + (4*k + 2)*ido) + ref(cc, ic - 1 + (4*k + 1)*ido); ch[i - 1 + k*ido] = tr2 + tr3; cr3 = tr2 - tr3; ch[i + k*ido] = ti2 + ti3; ci3 = ti2 - ti3; cr2 = tr1 - tr4; cr4 = tr1 + tr4; ci2 = ti1 + ti4; ci4 = ti1 - ti4; ch[i - 1 + (k + l1)*ido] = wa1[i - 2]*cr2 - wa1[i - 1]*ci2; ch[i + (k + l1)*ido] = wa1[i - 2]*ci2 + wa1[i - 1]*cr2; ch[i - 1 + (k + 2*l1)*ido] = wa2[i - 2]*cr3 - wa2[i - 1]*ci3; ch[i + (k + 2*l1)*ido] = wa2[i - 2]*ci3 + wa2[i - 1]*cr3; ch[i - 1 + (k + 3*l1)*ido] = wa3[i - 2]*cr4 - wa3[i - 1]*ci4; ch[i + (k + 3*l1)*ido] = wa3[i - 2]*ci4 + wa3[i - 1]*cr4; } } if (ido % 2 == 1) { return; } } for (k = 0; k < l1; k++) { ti1 = ref(cc, (4*k + 1)*ido) + ref(cc, (4*k + 3)*ido); ti2 = ref(cc, (4*k + 3)*ido) - ref(cc, (4*k + 1)*ido); tr1 = ref(cc, ido-1 + 4*k*ido) - ref(cc, ido-1 + (4*k + 2)*ido); tr2 = ref(cc, ido-1 + 4*k*ido) + ref(cc, ido-1 + (4*k + 2)*ido); ch[ido-1 + k*ido] = tr2 + tr2; ch[ido-1 + (k + l1)*ido] = sqrt2*(tr1 - ti1); ch[ido-1 + (k + 2*l1)*ido] = ti2 + ti2; ch[ido-1 + (k + 3*l1)*ido] = -sqrt2*(tr1 + ti1); } } /* radb4 */ static void radf5(int ido, int l1, const Treal cc[], Treal ch[], const Treal wa1[], const Treal wa2[], const Treal wa3[], const Treal wa4[]) { static const Treal tr11 = 0.309016994374947; static const Treal ti11 = 0.951056516295154; static const Treal tr12 = -0.809016994374947; static const Treal ti12 = 0.587785252292473; int i, k, ic; Treal ci2, di2, ci4, ci5, di3, di4, di5, ci3, cr2, cr3, dr2, dr3, dr4, dr5, cr5, cr4, ti2, ti3, ti5, ti4, tr2, tr3, tr4, tr5; for (k = 0; k < l1; k++) { cr2 = ref(cc, (k + 4*l1)*ido) + ref(cc, (k + l1)*ido); ci5 = ref(cc, (k + 4*l1)*ido) - ref(cc, (k + l1)*ido); cr3 = ref(cc, (k + 3*l1)*ido) + ref(cc, (k + 2*l1)*ido); ci4 = ref(cc, (k + 3*l1)*ido) - ref(cc, (k + 2*l1)*ido); ch[5*k*ido] = ref(cc, k*ido) + cr2 + cr3; ch[ido-1 + (5*k + 1)*ido] = ref(cc, k*ido) + tr11*cr2 + tr12*cr3; ch[(5*k + 2)*ido] = ti11*ci5 + ti12*ci4; ch[ido-1 + (5*k + 3)*ido] = ref(cc, k*ido) + tr12*cr2 + tr11*cr3; ch[(5*k + 4)*ido] = ti12*ci5 - ti11*ci4; } if (ido == 1) { return; } for (k = 0; k < l1; ++k) { for (i = 2; i < ido; i += 2) { ic = ido - i; dr2 = wa1[i - 2]*ref(cc, i - 1 + (k + l1)*ido) + wa1[i - 1]*ref(cc, i + (k + l1)*ido); di2 = wa1[i - 2]*ref(cc, i + (k + l1)*ido) - wa1[i - 1]*ref(cc, i - 1 + (k + l1)*ido); dr3 = wa2[i - 2]*ref(cc, i - 1 + (k + 2*l1)*ido) + wa2[i - 1]*ref(cc, i + (k + 2*l1)*ido); di3 = wa2[i - 2]*ref(cc, i + (k + 2*l1)*ido) - wa2[i - 1]*ref(cc, i - 1 + (k + 2*l1)*ido); dr4 = wa3[i - 2]*ref(cc, i - 1 + (k + 3*l1)*ido) + wa3[i - 1]*ref(cc, i + (k + 3*l1)*ido); di4 = wa3[i - 2]*ref(cc, i + (k + 3*l1)*ido) - wa3[i - 1]*ref(cc, i - 1 + (k + 3*l1)*ido); dr5 = wa4[i - 2]*ref(cc, i - 1 + (k + 4*l1)*ido) + wa4[i - 1]*ref(cc, i + (k + 4*l1)*ido); di5 = wa4[i - 2]*ref(cc, i + (k + 4*l1)*ido) - wa4[i - 1]*ref(cc, i - 1 + (k + 4*l1)*ido); cr2 = dr2 + dr5; ci5 = dr5 - dr2; cr5 = di2 - di5; ci2 = di2 + di5; cr3 = dr3 + dr4; ci4 = dr4 - dr3; cr4 = di3 - di4; ci3 = di3 + di4; ch[i - 1 + 5*k*ido] = ref(cc, i - 1 + k*ido) + cr2 + cr3; ch[i + 5*k*ido] = ref(cc, i + k*ido) + ci2 + ci3; tr2 = ref(cc, i - 1 + k*ido) + tr11*cr2 + tr12*cr3; ti2 = ref(cc, i + k*ido) + tr11*ci2 + tr12*ci3; tr3 = ref(cc, i - 1 + k*ido) + tr12*cr2 + tr11*cr3; ti3 = ref(cc, i + k*ido) + tr12*ci2 + tr11*ci3; tr5 = ti11*cr5 + ti12*cr4; ti5 = ti11*ci5 + ti12*ci4; tr4 = ti12*cr5 - ti11*cr4; ti4 = ti12*ci5 - ti11*ci4; ch[i - 1 + (5*k + 2)*ido] = tr2 + tr5; ch[ic - 1 + (5*k + 1)*ido] = tr2 - tr5; ch[i + (5*k + 2)*ido] = ti2 + ti5; ch[ic + (5*k + 1)*ido] = ti5 - ti2; ch[i - 1 + (5*k + 4)*ido] = tr3 + tr4; ch[ic - 1 + (5*k + 3)*ido] = tr3 - tr4; ch[i + (5*k + 4)*ido] = ti3 + ti4; ch[ic + (5*k + 3)*ido] = ti4 - ti3; } } } /* radf5 */ static void radb5(int ido, int l1, const Treal cc[], Treal ch[], const Treal wa1[], const Treal wa2[], const Treal wa3[], const Treal wa4[]) { static const Treal tr11 = 0.309016994374947; static const Treal ti11 = 0.951056516295154; static const Treal tr12 = -0.809016994374947; static const Treal ti12 = 0.587785252292473; int i, k, ic; Treal ci2, ci3, ci4, ci5, di3, di4, di5, di2, cr2, cr3, cr5, cr4, ti2, ti3, ti4, ti5, dr3, dr4, dr5, dr2, tr2, tr3, tr4, tr5; for (k = 0; k < l1; k++) { ti5 = 2*ref(cc, (5*k + 2)*ido); ti4 = 2*ref(cc, (5*k + 4)*ido); tr2 = 2*ref(cc, ido-1 + (5*k + 1)*ido); tr3 = 2*ref(cc, ido-1 + (5*k + 3)*ido); ch[k*ido] = ref(cc, 5*k*ido) + tr2 + tr3; cr2 = ref(cc, 5*k*ido) + tr11*tr2 + tr12*tr3; cr3 = ref(cc, 5*k*ido) + tr12*tr2 + tr11*tr3; ci5 = ti11*ti5 + ti12*ti4; ci4 = ti12*ti5 - ti11*ti4; ch[(k + l1)*ido] = cr2 - ci5; ch[(k + 2*l1)*ido] = cr3 - ci4; ch[(k + 3*l1)*ido] = cr3 + ci4; ch[(k + 4*l1)*ido] = cr2 + ci5; } if (ido == 1) { return; } for (k = 0; k < l1; ++k) { for (i = 2; i < ido; i += 2) { ic = ido - i; ti5 = ref(cc, i + (5*k + 2)*ido) + ref(cc, ic + (5*k + 1)*ido); ti2 = ref(cc, i + (5*k + 2)*ido) - ref(cc, ic + (5*k + 1)*ido); ti4 = ref(cc, i + (5*k + 4)*ido) + ref(cc, ic + (5*k + 3)*ido); ti3 = ref(cc, i + (5*k + 4)*ido) - ref(cc, ic + (5*k + 3)*ido); tr5 = ref(cc, i - 1 + (5*k + 2)*ido) - ref(cc, ic - 1 + (5*k + 1)*ido); tr2 = ref(cc, i - 1 + (5*k + 2)*ido) + ref(cc, ic - 1 + (5*k + 1)*ido); tr4 = ref(cc, i - 1 + (5*k + 4)*ido) - ref(cc, ic - 1 + (5*k + 3)*ido); tr3 = ref(cc, i - 1 + (5*k + 4)*ido) + ref(cc, ic - 1 + (5*k + 3)*ido); ch[i - 1 + k*ido] = ref(cc, i - 1 + 5*k*ido) + tr2 + tr3; ch[i + k*ido] = ref(cc, i + 5*k*ido) + ti2 + ti3; cr2 = ref(cc, i - 1 + 5*k*ido) + tr11*tr2 + tr12*tr3; ci2 = ref(cc, i + 5*k*ido) + tr11*ti2 + tr12*ti3; cr3 = ref(cc, i - 1 + 5*k*ido) + tr12*tr2 + tr11*tr3; ci3 = ref(cc, i + 5*k*ido) + tr12*ti2 + tr11*ti3; cr5 = ti11*tr5 + ti12*tr4; ci5 = ti11*ti5 + ti12*ti4; cr4 = ti12*tr5 - ti11*tr4; ci4 = ti12*ti5 - ti11*ti4; dr3 = cr3 - ci4; dr4 = cr3 + ci4; di3 = ci3 + cr4; di4 = ci3 - cr4; dr5 = cr2 + ci5; dr2 = cr2 - ci5; di5 = ci2 - cr5; di2 = ci2 + cr5; ch[i - 1 + (k + l1)*ido] = wa1[i - 2]*dr2 - wa1[i - 1]*di2; ch[i + (k + l1)*ido] = wa1[i - 2]*di2 + wa1[i - 1]*dr2; ch[i - 1 + (k + 2*l1)*ido] = wa2[i - 2]*dr3 - wa2[i - 1]*di3; ch[i + (k + 2*l1)*ido] = wa2[i - 2]*di3 + wa2[i - 1]*dr3; ch[i - 1 + (k + 3*l1)*ido] = wa3[i - 2]*dr4 - wa3[i - 1]*di4; ch[i + (k + 3*l1)*ido] = wa3[i - 2]*di4 + wa3[i - 1]*dr4; ch[i - 1 + (k + 4*l1)*ido] = wa4[i - 2]*dr5 - wa4[i - 1]*di5; ch[i + (k + 4*l1)*ido] = wa4[i - 2]*di5 + wa4[i - 1]*dr5; } } } /* radb5 */ static void radfg(int ido, int ip, int l1, int idl1, Treal cc[], Treal ch[], const Treal wa[]) { static const Treal twopi = 6.28318530717959; int idij, ipph, i, j, k, l, j2, ic, jc, lc, ik, is, nbd; Treal dc2, ai1, ai2, ar1, ar2, ds2, dcp, arg, dsp, ar1h, ar2h; arg = twopi / ip; dcp = cos(arg); dsp = sin(arg); ipph = (ip + 1) / 2; nbd = (ido - 1) / 2; if (ido != 1) { for (ik = 0; ik < idl1; ik++) { ch[ik] = cc[ik]; } for (j = 1; j < ip; j++) { for (k = 0; k < l1; k++) { ch[(k + j*l1)*ido] = cc[(k + j*l1)*ido]; } } if (nbd <= l1) { is = -ido; for (j = 1; j < ip; j++) { is += ido; idij = is-1; for (i = 2; i < ido; i += 2) { idij += 2; for (k = 0; k < l1; k++) { ch[i - 1 + (k + j*l1)*ido] = wa[idij - 1]*cc[i - 1 + (k + j*l1)*ido] + wa[idij]*cc[i + (k + j*l1)*ido]; ch[i + (k + j*l1)*ido] = wa[idij - 1]*cc[i + (k + j*l1)*ido] - wa[idij]*cc[i - 1 + (k + j*l1)*ido]; } } } } else { is = -ido; for (j = 1; j < ip; j++) { is += ido; for (k = 0; k < l1; k++) { idij = is-1; for (i = 2; i < ido; i += 2) { idij += 2; ch[i - 1 + (k + j*l1)*ido] = wa[idij - 1]*cc[i - 1 + (k + j*l1)*ido] + wa[idij]*cc[i + (k + j*l1)*ido]; ch[i + (k + j*l1)*ido] = wa[idij - 1]*cc[i + (k + j*l1)*ido] - wa[idij]*cc[i - 1 + (k + j*l1)*ido]; } } } } if (nbd >= l1) { for (j = 1; j < ipph; j++) { jc = ip - j; for (k = 0; k < l1; k++) { for (i = 2; i < ido; i += 2) { cc[i - 1 + (k + j*l1)*ido] = ch[i - 1 + (k + j*l1)*ido] + ch[i - 1 + (k + jc*l1)*ido]; cc[i - 1 + (k + jc*l1)*ido] = ch[i + (k + j*l1)*ido] - ch[i + (k + jc*l1)*ido]; cc[i + (k + j*l1)*ido] = ch[i + (k + j*l1)*ido] + ch[i + (k + jc*l1)*ido]; cc[i + (k + jc*l1)*ido] = ch[i - 1 + (k + jc*l1)*ido] - ch[i - 1 + (k + j*l1)*ido]; } } } } else { for (j = 1; j < ipph; j++) { jc = ip - j; for (i = 2; i < ido; i += 2) { for (k = 0; k < l1; k++) { cc[i - 1 + (k + j*l1)*ido] = ch[i - 1 + (k + j*l1)*ido] + ch[i - 1 + (k + jc*l1)*ido]; cc[i - 1 + (k + jc*l1)*ido] = ch[i + (k + j*l1)*ido] - ch[i + (k + jc*l1)*ido]; cc[i + (k + j*l1)*ido] = ch[i + (k + j*l1)*ido] + ch[i + (k + jc*l1)*ido]; cc[i + (k + jc*l1)*ido] = ch[i - 1 + (k + jc*l1)*ido] - ch[i - 1 + (k + j*l1)*ido]; } } } } } else /* now ido == 1 */ { for (ik = 0; ik < idl1; ik++) { cc[ik] = ch[ik]; } } for (j = 1; j < ipph; j++) { jc = ip - j; for (k = 0; k < l1; k++) { cc[(k + j*l1)*ido] = ch[(k + j*l1)*ido] + ch[(k + jc*l1)*ido]; cc[(k + jc*l1)*ido] = ch[(k + jc*l1)*ido] - ch[(k + j*l1)*ido]; } } ar1 = 1; ai1 = 0; for (l = 1; l < ipph; l++) { lc = ip - l; ar1h = dcp*ar1 - dsp*ai1; ai1 = dcp*ai1 + dsp*ar1; ar1 = ar1h; for (ik = 0; ik < idl1; ik++) { ch[ik + l*idl1] = cc[ik] + ar1*cc[ik + idl1]; ch[ik + lc*idl1] = ai1*cc[ik + (ip-1)*idl1]; } dc2 = ar1; ds2 = ai1; ar2 = ar1; ai2 = ai1; for (j = 2; j < ipph; j++) { jc = ip - j; ar2h = dc2*ar2 - ds2*ai2; ai2 = dc2*ai2 + ds2*ar2; ar2 = ar2h; for (ik = 0; ik < idl1; ik++) { ch[ik + l*idl1] += ar2*cc[ik + j*idl1]; ch[ik + lc*idl1] += ai2*cc[ik + jc*idl1]; } } } for (j = 1; j < ipph; j++) { for (ik = 0; ik < idl1; ik++) { ch[ik] += cc[ik + j*idl1]; } } if (ido >= l1) { for (k = 0; k < l1; k++) { for (i = 0; i < ido; i++) { ref(cc, i + k*ip*ido) = ch[i + k*ido]; } } } else { for (i = 0; i < ido; i++) { for (k = 0; k < l1; k++) { ref(cc, i + k*ip*ido) = ch[i + k*ido]; } } } for (j = 1; j < ipph; j++) { jc = ip - j; j2 = 2*j; for (k = 0; k < l1; k++) { ref(cc, ido-1 + (j2 - 1 + k*ip)*ido) = ch[(k + j*l1)*ido]; ref(cc, (j2 + k*ip)*ido) = ch[(k + jc*l1)*ido]; } } if (ido == 1) { return; } if (nbd >= l1) { for (j = 1; j < ipph; j++) { jc = ip - j; j2 = 2*j; for (k = 0; k < l1; k++) { for (i = 2; i < ido; i += 2) { ic = ido - i; ref(cc, i - 1 + (j2 + k*ip)*ido) = ch[i - 1 + (k + j*l1)*ido] + ch[i - 1 + (k + jc*l1)*ido]; ref(cc, ic - 1 + (j2 - 1 + k*ip)*ido) = ch[i - 1 + (k + j*l1)*ido] - ch[i - 1 + (k + jc*l1)*ido]; ref(cc, i + (j2 + k*ip)*ido) = ch[i + (k + j*l1)*ido] + ch[i + (k + jc*l1)*ido]; ref(cc, ic + (j2 - 1 + k*ip)*ido) = ch[i + (k + jc*l1)*ido] - ch[i + (k + j*l1)*ido]; } } } } else { for (j = 1; j < ipph; j++) { jc = ip - j; j2 = 2*j; for (i = 2; i < ido; i += 2) { ic = ido - i; for (k = 0; k < l1; k++) { ref(cc, i - 1 + (j2 + k*ip)*ido) = ch[i - 1 + (k + j*l1)*ido] + ch[i - 1 + (k + jc*l1)*ido]; ref(cc, ic - 1 + (j2 - 1 + k*ip)*ido) = ch[i - 1 + (k + j*l1)*ido] - ch[i - 1 + (k + jc*l1)*ido]; ref(cc, i + (j2 + k*ip)*ido) = ch[i + (k + j*l1)*ido] + ch[i + (k + jc*l1)*ido]; ref(cc, ic + (j2 - 1 + k*ip)*ido) = ch[i + (k + jc*l1)*ido] - ch[i + (k + j*l1)*ido]; } } } } } /* radfg */ static void radbg(int ido, int ip, int l1, int idl1, Treal cc[], Treal ch[], const Treal wa[]) { static const Treal twopi = 6.28318530717959; int idij, ipph, i, j, k, l, j2, ic, jc, lc, ik, is; Treal dc2, ai1, ai2, ar1, ar2, ds2; int nbd; Treal dcp, arg, dsp, ar1h, ar2h; arg = twopi / ip; dcp = cos(arg); dsp = sin(arg); nbd = (ido - 1) / 2; ipph = (ip + 1) / 2; if (ido >= l1) { for (k = 0; k < l1; k++) { for (i = 0; i < ido; i++) { ch[i + k*ido] = ref(cc, i + k*ip*ido); } } } else { for (i = 0; i < ido; i++) { for (k = 0; k < l1; k++) { ch[i + k*ido] = ref(cc, i + k*ip*ido); } } } for (j = 1; j < ipph; j++) { jc = ip - j; j2 = 2*j; for (k = 0; k < l1; k++) { ch[(k + j*l1)*ido] = ref(cc, ido-1 + (j2 - 1 + k*ip)*ido) + ref(cc, ido-1 + (j2 - 1 + k*ip)* ido); ch[(k + jc*l1)*ido] = ref(cc, (j2 + k*ip)*ido) + ref(cc, (j2 + k*ip)*ido); } } if (ido != 1) { if (nbd >= l1) { for (j = 1; j < ipph; j++) { jc = ip - j; for (k = 0; k < l1; k++) { for (i = 2; i < ido; i += 2) { ic = ido - i; ch[i - 1 + (k + j*l1)*ido] = ref(cc, i - 1 + (2*j + k*ip)*ido) + ref(cc, ic - 1 + (2*j - 1 + k*ip)*ido); ch[i - 1 + (k + jc*l1)*ido] = ref(cc, i - 1 + (2*j + k*ip)*ido) - ref(cc, ic - 1 + (2*j - 1 + k*ip)*ido); ch[i + (k + j*l1)*ido] = ref(cc, i + (2*j + k*ip)*ido) - ref(cc, ic + (2*j - 1 + k*ip)*ido); ch[i + (k + jc*l1)*ido] = ref(cc, i + (2*j + k*ip)*ido) + ref(cc, ic + (2*j - 1 + k*ip)*ido); } } } } else { for (j = 1; j < ipph; j++) { jc = ip - j; for (i = 2; i < ido; i += 2) { ic = ido - i; for (k = 0; k < l1; k++) { ch[i - 1 + (k + j*l1)*ido] = ref(cc, i - 1 + (2*j + k*ip)*ido) + ref(cc, ic - 1 + (2*j - 1 + k*ip)*ido); ch[i - 1 + (k + jc*l1)*ido] = ref(cc, i - 1 + (2*j + k*ip)*ido) - ref(cc, ic - 1 + (2*j - 1 + k*ip)*ido); ch[i + (k + j*l1)*ido] = ref(cc, i + (2*j + k*ip)*ido) - ref(cc, ic + (2*j - 1 + k*ip)*ido); ch[i + (k + jc*l1)*ido] = ref(cc, i + (2*j + k*ip)*ido) + ref(cc, ic + (2*j - 1 + k*ip)*ido); } } } } } ar1 = 1; ai1 = 0; for (l = 1; l < ipph; l++) { lc = ip - l; ar1h = dcp*ar1 - dsp*ai1; ai1 = dcp*ai1 + dsp*ar1; ar1 = ar1h; for (ik = 0; ik < idl1; ik++) { cc[ik + l*idl1] = ch[ik] + ar1*ch[ik + idl1]; cc[ik + lc*idl1] = ai1*ch[ik + (ip-1)*idl1]; } dc2 = ar1; ds2 = ai1; ar2 = ar1; ai2 = ai1; for (j = 2; j < ipph; j++) { jc = ip - j; ar2h = dc2*ar2 - ds2*ai2; ai2 = dc2*ai2 + ds2*ar2; ar2 = ar2h; for (ik = 0; ik < idl1; ik++) { cc[ik + l*idl1] += ar2*ch[ik + j*idl1]; cc[ik + lc*idl1] += ai2*ch[ik + jc*idl1]; } } } for (j = 1; j < ipph; j++) { for (ik = 0; ik < idl1; ik++) { ch[ik] += ch[ik + j*idl1]; } } for (j = 1; j < ipph; j++) { jc = ip - j; for (k = 0; k < l1; k++) { ch[(k + j*l1)*ido] = cc[(k + j*l1)*ido] - cc[(k + jc*l1)*ido]; ch[(k + jc*l1)*ido] = cc[(k + j*l1)*ido] + cc[(k + jc*l1)*ido]; } } if (ido == 1) { return; } if (nbd >= l1) { for (j = 1; j < ipph; j++) { jc = ip - j; for (k = 0; k < l1; k++) { for (i = 2; i < ido; i += 2) { ch[i - 1 + (k + j*l1)*ido] = cc[i - 1 + (k + j*l1)*ido] - cc[i + (k + jc*l1)*ido]; ch[i - 1 + (k + jc*l1)*ido] = cc[i - 1 + (k + j*l1)*ido] + cc[i + (k + jc*l1)*ido]; ch[i + (k + j*l1)*ido] = cc[i + (k + j*l1)*ido] + cc[i - 1 + (k + jc*l1)*ido]; ch[i + (k + jc*l1)*ido] = cc[i + (k + j*l1)*ido] - cc[i - 1 + (k + jc*l1)*ido]; } } } } else { for (j = 1; j < ipph; j++) { jc = ip - j; for (i = 2; i < ido; i += 2) { for (k = 0; k < l1; k++) { ch[i - 1 + (k + j*l1)*ido] = cc[i - 1 + (k + j*l1)*ido] - cc[i + (k + jc*l1)*ido]; ch[i - 1 + (k + jc*l1)*ido] = cc[i - 1 + (k + j *l1)*ido] + cc[i + (k + jc*l1)*ido]; ch[i + (k + j*l1)*ido] = cc[i + (k + j*l1)*ido] + cc[i - 1 + (k + jc*l1)*ido]; ch[i + (k + jc*l1)*ido] = cc[i + (k + j*l1)*ido] - cc[i - 1 + (k + jc*l1)*ido]; } } } } for (ik = 0; ik < idl1; ik++) { cc[ik] = ch[ik]; } for (j = 1; j < ip; j++) { for (k = 0; k < l1; k++) { cc[(k + j*l1)*ido] = ch[(k + j*l1)*ido]; } } if (nbd <= l1) { is = -ido; for (j = 1; j < ip; j++) { is += ido; idij = is-1; for (i = 2; i < ido; i += 2) { idij += 2; for (k = 0; k < l1; k++) { cc[i - 1 + (k + j*l1)*ido] = wa[idij - 1]*ch[i - 1 + (k + j*l1)*ido] - wa[idij]* ch[i + (k + j*l1)*ido]; cc[i + (k + j*l1)*ido] = wa[idij - 1]*ch[i + (k + j*l1)*ido] + wa[idij]*ch[i - 1 + (k + j*l1)*ido]; } } } } else { is = -ido; for (j = 1; j < ip; j++) { is += ido; for (k = 0; k < l1; k++) { idij = is - 1; for (i = 2; i < ido; i += 2) { idij += 2; cc[i - 1 + (k + j*l1)*ido] = wa[idij-1]*ch[i - 1 + (k + j*l1)*ido] - wa[idij]* ch[i + (k + j*l1)*ido]; cc[i + (k + j*l1)*ido] = wa[idij-1]*ch[i + (k + j*l1)*ido] + wa[idij]*ch[i - 1 + (k + j*l1)*ido]; } } } } } /* radbg */ /* ---------------------------------------------------------------------- cfftf1, cfftf, cfftb, cffti1, cffti. Complex FFTs. ---------------------------------------------------------------------- */ void fftpack_cfftf1(int n, Treal c[], Treal ch[], const Treal wa[], const int ifac[MAXFAC+2], int isign) { int idot, i; int k1, l1, l2; int na, nf, ip, iw, ix2, ix3, ix4, nac, ido, idl1; Treal *cinput, *coutput; nf = ifac[1]; na = 0; l1 = 1; iw = 0; for (k1 = 2; k1 <= nf+1; k1++) { ip = ifac[k1]; l2 = ip*l1; ido = n / l2; idot = ido + ido; idl1 = idot*l1; if (na) { cinput = ch; coutput = c; } else { cinput = c; coutput = ch; } switch (ip) { case 4: ix2 = iw + idot; ix3 = ix2 + idot; passf4(idot, l1, cinput, coutput, &wa[iw], &wa[ix2], &wa[ix3], isign); na = !na; break; case 2: passf2(idot, l1, cinput, coutput, &wa[iw], isign); na = !na; break; case 3: ix2 = iw + idot; passf3(idot, l1, cinput, coutput, &wa[iw], &wa[ix2], isign); na = !na; break; case 5: ix2 = iw + idot; ix3 = ix2 + idot; ix4 = ix3 + idot; passf5(idot, l1, cinput, coutput, &wa[iw], &wa[ix2], &wa[ix3], &wa[ix4], isign); na = !na; break; default: passf(&nac, idot, ip, l1, idl1, cinput, coutput, &wa[iw], isign); if (nac != 0) { na = !na; } } l1 = l2; iw += (ip - 1)*idot; } if (na == 0) { return; } for (i = 0; i < 2*n; i++) { c[i] = ch[i]; } } /* cfftf1 */ void fftpack_cfftf(int n, Treal c[], Treal wsave[]) { int iw1, iw2; if (n == 1) { return; } iw1 = 2*n; iw2 = iw1 + 2*n; fftpack_cfftf1(n, c, wsave, wsave+iw1, (int*)(wsave+iw2), -1); } /* cfftf */ void fftpack_cfftb(int n, Treal c[], Treal wsave[]) { int iw1, iw2; if (n == 1) { return; } iw1 = 2*n; iw2 = iw1 + 2*n; fftpack_cfftf1(n, c, wsave, wsave+iw1, (int*)(wsave+iw2), +1); } /* cfftb */ static void factorize(int n, int ifac[MAXFAC+2], const int ntryh[NSPECIAL]) /* Factorize n in factors in ntryh and rest. On exit, ifac[0] contains n and ifac[1] contains number of factors, the factors start from ifac[2]. */ { int ntry = 3, i, j = 0, ib, nf = 0, nl = n, nq, nr; startloop: if (j < NSPECIAL) { ntry = ntryh[j]; } else { ntry += 2; } j++; do { nq = nl / ntry; nr = nl - ntry*nq; if (nr != 0) { goto startloop; } nf++; ifac[nf + 1] = ntry; nl = nq; if (ntry == 2 && nf != 1) { for (i = 2; i <= nf; i++) { ib = nf - i + 2; ifac[ib + 1] = ifac[ib]; } ifac[2] = 2; } } while (nl != 1); ifac[0] = n; ifac[1] = nf; } void fftpack_cffti1(int n, Treal wa[], int ifac[MAXFAC+2]) { static const Treal twopi = 6.28318530717959; Treal arg, argh, argld, fi; int idot, i, j; int i1, k1, l1, l2; int ld, ii, nf, ip; int ido, ipm; static const int ntryh[NSPECIAL] = { 3, 4, 2, 5 }; /* Do not change the order of these. */ factorize(n, ifac, ntryh); nf = ifac[1]; argh = twopi/(Treal)n; i = 1; l1 = 1; for (k1 = 1; k1 <= nf; k1++) { ip = ifac[k1+1]; ld = 0; l2 = l1*ip; ido = n / l2; idot = ido + ido + 2; ipm = ip - 1; for (j = 1; j <= ipm; j++) { i1 = i; wa[i-1] = 1; wa[i] = 0; ld += l1; fi = 0; argld = ld*argh; for (ii = 4; ii <= idot; ii += 2) { i += 2; fi += 1; arg = fi*argld; wa[i-1] = cos(arg); wa[i] = sin(arg); } if (ip > 5) { wa[i1-1] = wa[i-1]; wa[i1] = wa[i]; } } l1 = l2; } } /* cffti1 */ void fftpack_cffti(int n, Treal wsave[]) { int iw1, iw2; if (n == 1) { return; } iw1 = 2*n; iw2 = iw1 + 2*n; fftpack_cffti1(n, wsave+iw1, (int*)(wsave+iw2)); } /* cffti */ /* ---------------------------------------------------------------------- rfftf1, rfftb1, rfftf, rfftb, rffti1, rffti. Treal FFTs. ---------------------------------------------------------------------- */ void fftpack_rfftf1(int n, Treal c[], Treal ch[], const Treal wa[], const int ifac[MAXFAC+2]) { int i; int k1, l1, l2, na, kh, nf, ip, iw, ix2, ix3, ix4, ido, idl1; Treal *cinput, *coutput; nf = ifac[1]; na = 1; l2 = n; iw = n-1; for (k1 = 1; k1 <= nf; ++k1) { kh = nf - k1; ip = ifac[kh + 2]; l1 = l2 / ip; ido = n / l2; idl1 = ido*l1; iw -= (ip - 1)*ido; na = !na; if (na) { cinput = ch; coutput = c; } else { cinput = c; coutput = ch; } switch (ip) { case 4: ix2 = iw + ido; ix3 = ix2 + ido; radf4(ido, l1, cinput, coutput, &wa[iw], &wa[ix2], &wa[ix3]); break; case 2: radf2(ido, l1, cinput, coutput, &wa[iw]); break; case 3: ix2 = iw + ido; radf3(ido, l1, cinput, coutput, &wa[iw], &wa[ix2]); break; case 5: ix2 = iw + ido; ix3 = ix2 + ido; ix4 = ix3 + ido; radf5(ido, l1, cinput, coutput, &wa[iw], &wa[ix2], &wa[ix3], &wa[ix4]); break; default: if (ido == 1) { na = !na; } if (na == 0) { radfg(ido, ip, l1, idl1, c, ch, &wa[iw]); na = 1; } else { radfg(ido, ip, l1, idl1, ch, c, &wa[iw]); na = 0; } } l2 = l1; } if (na == 1) { return; } for (i = 0; i < n; i++) { c[i] = ch[i]; } } /* rfftf1 */ void fftpack_rfftb1(int n, Treal c[], Treal ch[], const Treal wa[], const int ifac[MAXFAC+2]) { int i; int k1, l1, l2, na, nf, ip, iw, ix2, ix3, ix4, ido, idl1; Treal *cinput, *coutput; nf = ifac[1]; na = 0; l1 = 1; iw = 0; for (k1 = 1; k1 <= nf; k1++) { ip = ifac[k1 + 1]; l2 = ip*l1; ido = n / l2; idl1 = ido*l1; if (na) { cinput = ch; coutput = c; } else { cinput = c; coutput = ch; } switch (ip) { case 4: ix2 = iw + ido; ix3 = ix2 + ido; radb4(ido, l1, cinput, coutput, &wa[iw], &wa[ix2], &wa[ix3]); na = !na; break; case 2: radb2(ido, l1, cinput, coutput, &wa[iw]); na = !na; break; case 3: ix2 = iw + ido; radb3(ido, l1, cinput, coutput, &wa[iw], &wa[ix2]); na = !na; break; case 5: ix2 = iw + ido; ix3 = ix2 + ido; ix4 = ix3 + ido; radb5(ido, l1, cinput, coutput, &wa[iw], &wa[ix2], &wa[ix3], &wa[ix4]); na = !na; break; default: radbg(ido, ip, l1, idl1, cinput, coutput, &wa[iw]); if (ido == 1) { na = !na; } } l1 = l2; iw += (ip - 1)*ido; } if (na == 0) { return; } for (i = 0; i < n; i++) { c[i] = ch[i]; } } /* rfftb1 */ void fftpack_rfftf(int n, Treal r[], Treal wsave[]) { if (n == 1) { return; } fftpack_rfftf1(n, r, wsave, wsave+n, (int*)(wsave+2*n)); } /* rfftf */ void fftpack_rfftb(int n, Treal r[], Treal wsave[]) { if (n == 1) { return; } fftpack_rfftb1(n, r, wsave, wsave+n, (int*)(wsave+2*n)); } /* rfftb */ void fftpack_rffti1(int n, Treal wa[], int ifac[MAXFAC+2]) { static const Treal twopi = 6.28318530717959; Treal arg, argh, argld, fi; int i, j; int k1, l1, l2; int ld, ii, nf, ip, is; int ido, ipm, nfm1; static const int ntryh[NSPECIAL] = { 4, 2, 3, 5 }; /* Do not change the order of these. */ factorize(n, ifac, ntryh); nf = ifac[1]; argh = twopi / n; is = 0; nfm1 = nf - 1; l1 = 1; if (nfm1 == 0) { return; } for (k1 = 1; k1 <= nfm1; k1++) { ip = ifac[k1 + 1]; ld = 0; l2 = l1*ip; ido = n / l2; ipm = ip - 1; for (j = 1; j <= ipm; ++j) { ld += l1; i = is; argld = (Treal) ld*argh; fi = 0; for (ii = 3; ii <= ido; ii += 2) { i += 2; fi += 1; arg = fi*argld; wa[i - 2] = cos(arg); wa[i - 1] = sin(arg); } is += ido; } l1 = l2; } } /* rffti1 */ void fftpack_rffti(int n, Treal wsave[]) { if (n == 1) { return; } fftpack_rffti1(n, wsave+n, (int*)(wsave+2*n)); } /* rffti */ #ifdef __cplusplus } #endif
36.078769
125
0.337464
[ "transform" ]
ca8a237f4e304e0c45fcc1fb654c298bf7a912a2
375
h
C
MVP/MVP/Models/Model.h
yimao009/MVC-MVP-MVVM
07af63249a05d09818d4034bbc4d55279acaec32
[ "MIT" ]
1
2020-07-27T07:31:17.000Z
2020-07-27T07:31:17.000Z
MVP/MVP/Models/Model.h
yimao009/MVC-MVP-MVVM
07af63249a05d09818d4034bbc4d55279acaec32
[ "MIT" ]
1
2020-08-18T01:43:56.000Z
2020-08-18T01:43:56.000Z
NormalMVC/NormalMVC/Models/Model.h
yimao009/MVC-MVP-MVVM
07af63249a05d09818d4034bbc4d55279acaec32
[ "MIT" ]
null
null
null
// // Model.h // MVCDemo // // Created by guoruize on 2020/6/16. // Copyright © 2020 guoruize. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface Model : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *imageUrl; @property (nonatomic, copy) NSString *num; @end NS_ASSUME_NONNULL_END
18.75
51
0.733333
[ "model" ]