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
5200a7b94d4fd2a7be8bf4be0fff62c8d97a8d36
1,230
h
C
Classes/Base/SceneBase.h
9chu/cocos2dx-sokoban
92d8123453f7b285855ba7de24b44736996ae933
[ "Naumen", "Condor-1.1", "MS-PL" ]
6
2015-10-24T15:08:50.000Z
2019-02-08T02:14:35.000Z
Classes/Base/SceneBase.h
9chu/cocos2dx-sokoban
92d8123453f7b285855ba7de24b44736996ae933
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
Classes/Base/SceneBase.h
9chu/cocos2dx-sokoban
92d8123453f7b285855ba7de24b44736996ae933
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
/* * \file SceneBase.h * \author chu * \date 2015/10/11 */ #pragma once #include "../Common.h" namespace sokoban { /// \brief 场景基类 /// \note 增加一些实用函数 class SceneBase : public AutoInvokeInit<cocos2d::Scene> { private: using TouchPair = std::pair<cocos2d::RefPtr<cocos2d::Touch>, cocos2d::RefPtr<cocos2d::Layer>>; std::vector<cocos2d::RefPtr<cocos2d::Layer>> m_vecLayerList; // 层列表 // 触摸事件分发器 cocos2d::RefPtr<cocos2d::EventListenerTouchAllAtOnce> m_pTouchEventListener; std::unordered_map<cocos2d::Touch*, TouchPair> m_umTouchRouter; public: SceneBase(); public: /// \brief 增加一个层用于分发触摸事件 /// \note 新增加的层拥有最高的优先级来获得触摸事件的分发 void AddLayer(cocos2d::RefPtr<cocos2d::Layer> pLayer, int32_t iLocalZOrder=0); /// \brief 向Scene发送消息 void ReceiveMessage(int32_t iEventId, cocos2d::Event* unused_event=nullptr) { onMessage(iEventId, unused_event); } protected: // events void onEnter()override; void onExit()override; // 用于接收传递的事件 virtual void onMessage(int32_t iEventId, cocos2d::Event* unused_event); }; }
27.954545
102
0.613821
[ "vector" ]
d599de59736c8d5e172bb1a5e51c754eb9fc3d0f
4,737
h
C
smb2/libsmb2-dcerpc.h
Serizao/libsmb2-go
2c58843d7b3bbf22d67886a701c637d924bdf61d
[ "Apache-2.0" ]
null
null
null
smb2/libsmb2-dcerpc.h
Serizao/libsmb2-go
2c58843d7b3bbf22d67886a701c637d924bdf61d
[ "Apache-2.0" ]
null
null
null
smb2/libsmb2-dcerpc.h
Serizao/libsmb2-go
2c58843d7b3bbf22d67886a701c637d924bdf61d
[ "Apache-2.0" ]
null
null
null
/* -*- mode:c; tab-width:8; c-basic-offset:8; indent-tabs-mode:nil; -*- */ /* Copyright (C) 2018 by Ronnie Sahlberg <ronniesahlberg@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ #ifndef _LIBSMB2_DCERPC_H_ #define _LIBSMB2_DCERPC_H_ #ifdef __cplusplus extern "C" { #endif /* Data representation */ /* Integer */ #define DCERPC_DR_BIG_ENDIAN 0x00 #define DCERPC_DR_LITTLE_ENDIAN 0x10 /* Character */ #define DCERPC_DR_ASCII 0x00 #define DCERPC_DR_EBCDIC 0x01 struct dcerpc_context; struct dcerpc_pdu; /* Encoder/Decoder for a DCERPC object */ typedef int (*dcerpc_coder)(struct dcerpc_context *dce, struct dcerpc_pdu *pdu, struct smb2_iovec *iov, int offset, void *ptr); enum ptr_type { PTR_REF = 0, PTR_UNIQUE = 1, PTR_FULL = 2 }; typedef struct dcerpc_uuid { uint32_t v1; uint16_t v2; uint16_t v3; uint64_t v4; } dcerpc_uuid_t; typedef struct p_syntax_id { dcerpc_uuid_t uuid; uint16_t vers; uint16_t vers_minor; } p_syntax_id_t; struct ndr_transfer_syntax { dcerpc_uuid_t uuid; uint16_t vers; }; struct ndr_context_handle { uint32_t context_handle_attributes; dcerpc_uuid_t context_handle_uuid; }; extern p_syntax_id_t lsa_interface; extern p_syntax_id_t srvsvc_interface; typedef void (*dcerpc_cb)(struct dcerpc_context *dce, int status, void *command_data, void *cb_data); struct dcerpc_context *dcerpc_create_context(struct smb2_context *smb2); void dcerpc_free_data(struct dcerpc_context *dce, void *data); const char *dcerpc_get_error(struct dcerpc_context *dce); int dcerpc_connect_context_async(struct dcerpc_context *dce, const char *path, p_syntax_id_t *syntax, dcerpc_cb cb, void *cb_data); void dcerpc_destroy_context(struct dcerpc_context *dce); struct smb2_context *dcerpc_get_smb2_context(struct dcerpc_context *dce); void *dcerpc_get_pdu_payload(struct dcerpc_pdu *pdu); int dcerpc_open_async(struct dcerpc_context *dce, dcerpc_cb cb, void *cb_data); int dcerpc_call_async(struct dcerpc_context *dce, int opnum, dcerpc_coder req_coder, void *req, dcerpc_coder rep_coder, int rep_size, dcerpc_cb cb, void *cb_data); int dcerpc_ptr_coder(struct dcerpc_context *dce, struct dcerpc_pdu *pdu, struct smb2_iovec *iov, int offset, void *ptr, enum ptr_type type, dcerpc_coder coder); int dcerpc_uint8_coder(struct dcerpc_context *ctx, struct dcerpc_pdu *pdu, struct smb2_iovec *iov, int offset, void *ptr); int dcerpc_uint16_coder(struct dcerpc_context *ctx, struct dcerpc_pdu *pdu, struct smb2_iovec *iov, int offset, void *ptr); int dcerpc_uint32_coder(struct dcerpc_context *ctx, struct dcerpc_pdu *pdu, struct smb2_iovec *iov, int offset, void *ptr); int dcerpc_uint3264_coder(struct dcerpc_context *ctx, struct dcerpc_pdu *pdu, struct smb2_iovec *iov, int offset, void *ptr); int dcerpc_utf16_coder(struct dcerpc_context *ctx, struct dcerpc_pdu *pdu, struct smb2_iovec *iov, int offset, void *ptr); int dcerpc_utf16z_coder(struct dcerpc_context *ctx, struct dcerpc_pdu *pdu, struct smb2_iovec *iov, int offset, void *ptr); int dcerpc_context_handle_coder(struct dcerpc_context *dce, struct dcerpc_pdu *pdu, struct smb2_iovec *iov, int offset, void *ptr); #define DCERPC_DECODE 0 #define DCERPC_ENCODE 1 struct dcerpc_pdu *dcerpc_allocate_pdu(struct dcerpc_context *dce, int direction, int payload_size); void dcerpc_free_pdu(struct dcerpc_context *dce, struct dcerpc_pdu *pdu); #ifdef __cplusplus } #endif #endif /* !_LIBSMB2_DCERPC_H_ */
38.201613
79
0.668355
[ "object" ]
d5a6eaeb6743ebecfb3021d8c1d29ab5eaedf875
647
h
C
observer/model.h
yijiem/design-pattern-cpp
ec1e114f69af2a3cf28323a070f018744040226d
[ "MIT" ]
null
null
null
observer/model.h
yijiem/design-pattern-cpp
ec1e114f69af2a3cf28323a070f018744040226d
[ "MIT" ]
null
null
null
observer/model.h
yijiem/design-pattern-cpp
ec1e114f69af2a3cf28323a070f018744040226d
[ "MIT" ]
null
null
null
// // Created by Yijie Ma on 1/29/17. // #ifndef DESIGN_PATTERN_CPP_MODEL_H #define DESIGN_PATTERN_CPP_MODEL_H #include <string> #include "subject_interface.h" // // Model plugins SubjectInterface which implements pub/sub functions, // it just need to define the message type and call notify at the right time // // Model does not and should not know about View // class Model : public SubjectInterface { public: Model() = default; ~Model() = default; void set_name(std::string name); void set_magic(int magic); enum { NAME, MAGIC }; private: std::string name_; int magic_; }; #endif //DESIGN_PATTERN_CPP_MODEL_H
20.21875
76
0.712519
[ "model" ]
d5b385ba277fa9fc5be87de0747f6c8361dc2166
545
h
C
src/webserver.h
Tolmeros/ESPPlane
b87d818aaeb2395d65703fffbf706d76573af2bb
[ "MIT" ]
4
2020-08-28T23:00:26.000Z
2022-01-26T16:44:21.000Z
src/webserver.h
Tolmeros/ESPPlane
b87d818aaeb2395d65703fffbf706d76573af2bb
[ "MIT" ]
1
2022-01-30T09:13:56.000Z
2022-02-10T00:21:58.000Z
src/webserver.h
Tolmeros/ESPPlane
b87d818aaeb2395d65703fffbf706d76573af2bb
[ "MIT" ]
3
2021-02-08T03:09:39.000Z
2022-01-29T14:06:22.000Z
#include <ESP8266WebServer.h> ESP8266WebServer server(80); // Create a webserver object that listens for HTTP request on port 80 void handleRoot() { server.send(200, "text/plain", "Hola mundo!"); } void handleNotFound() { // if the requested file or page doesn't exist, return a 404 not found error server.send(404, "text/plain", "404: File Not Found"); } void startWebServer(){ server.onNotFound(handleNotFound); server.begin(); Serial.println("[INFO] WebServer started"); }
32.058824
104
0.647706
[ "object" ]
d5cb31a0e875b487602e268c0edb62ac36ecb6ce
1,629
h
C
src/game/src/states/editor/EditorState.h
walter-strazak/chimarrao-platformer
b7878b84324b8347c6ca8c20c5a6128b349fdc41
[ "MIT" ]
6
2021-04-20T10:32:29.000Z
2021-06-05T11:48:56.000Z
src/game/src/states/editor/EditorState.h
walter-strazak/chimarrao-platformer
b7878b84324b8347c6ca8c20c5a6128b349fdc41
[ "MIT" ]
1
2021-05-18T21:00:12.000Z
2021-06-02T07:59:03.000Z
src/game/src/states/editor/EditorState.h
walter-strazak/chimarrao-platformer
b7878b84324b8347c6ca8c20c5a6128b349fdc41
[ "MIT" ]
3
2020-09-12T08:54:04.000Z
2021-04-17T11:16:36.000Z
#pragma once #include <vector> #include "ComponentOwnersManager.h" #include "LayoutTile.h" #include "State.h" #include "TileMap.h" #include "Timer.h" #include "UIConfig.h" #include "UIManager.h" namespace game { class EditorStateUIConfigBuilder; class EditorState : public State { public: friend class EditorStateUIConfigBuilder; EditorState(const std::shared_ptr<window::Window>&, const std::shared_ptr<graphics::RendererPool>&, std::shared_ptr<utils::FileAccess>, States&, std::shared_ptr<components::ui::UIManager>, std::shared_ptr<TileMap>, const std::shared_ptr<components::core::SharedContext>&, std::unique_ptr<ComponentOwnersManager>); NextState update(const utils::DeltaTime&, const input::Input&) override; void lateUpdate(const utils::DeltaTime&, const input::Input&) override; void render() override; StateType getType() const override; void activate() override; void deactivate() override; void pause(); private: void setTileMap(); bool paused; std::unique_ptr<utils::Timer> pauseTimer; const float timeAfterStateCouldBePaused; std::vector<std::shared_ptr<components::core::ComponentOwner>> clickableTileMap; std::shared_ptr<TileType> currentTileType; std::vector<LayoutTile> layoutTileMap; std::shared_ptr<TileMap> tileMap; std::shared_ptr<components::ui::UIManager> uiManager; const std::shared_ptr<components::core::SharedContext>& sharedContext; std::shared_ptr<components::core::ComponentOwner> camera; std::unique_ptr<ComponentOwnersManager> componentOwnersManager; }; }
32.58
104
0.726826
[ "render", "vector" ]
d5f664f8714f3427a4db10980227ea8fec29275d
3,981
h
C
cc_code/src/hmm/hmm/generic-hmm.h
erisyon/whatprot
176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c
[ "MIT" ]
null
null
null
cc_code/src/hmm/hmm/generic-hmm.h
erisyon/whatprot
176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c
[ "MIT" ]
1
2021-06-12T00:50:08.000Z
2021-06-15T17:59:12.000Z
cc_code/src/hmm/hmm/generic-hmm.h
erisyon/whatprot
176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c
[ "MIT" ]
1
2021-06-11T19:34:43.000Z
2021-06-11T19:34:43.000Z
/******************************************************************************\ * Author: Matthew Beauregard Smith * * Affiliation: The University of Texas at Austin * * Department: Oden Institute and Institute for Cellular and Molecular Biology * * PI: Edward Marcotte * * Project: Protein Fluorosequencing * \******************************************************************************/ #ifndef WHATPROT_HMM_HMM_GENERIC_HMM_H #define WHATPROT_HMM_HMM_GENERIC_HMM_H // Standard C++ library headers: #include <vector> // Local project headers: #include "hmm/fit/error-model-fitter.h" #include "hmm/step/step.h" namespace whatprot { template <typename SV> // SV is the state vector type. class GenericHMM { public: GenericHMM(int num_timesteps) : num_timesteps(num_timesteps) {} virtual SV create_states() const = 0; // This computes the probability of the provided dye seq producing the // provided radiometry. To do this efficiently, it uses a modified version // of the forward algorithm. double probability() const { int num_edmans = 0; auto step = steps.begin(); // const_iterator type SV states = create_states(); states.initialize_from_start(); while (step != steps.end()) { (*step)->forward(&num_edmans, &states); step++; } return states.sum(); } // This will fit the data the HMM was provided with. It also computes the // probability as a side effect, so it returns this in case that is useful // to the caller. double improve_fit(ErrorModelFitter* fitter) const { // There is one less Edman than the number of timesteps, because no // Edman is done before the zeroth timestep. int num_edmans = num_timesteps - 1; auto step = steps.end(); // const_iterator type std::vector<SV> backward_sv; backward_sv.reserve(steps.size()); // For efficiency, backwards_states is in the reverse order of what we // would like. Yes this is confusing... backward_sv.push_back(create_states()); backward_sv.back().initialize_from_finish(); while (step != steps.begin()) { step--; backward_sv.push_back(create_states()); SV* left_states = &backward_sv.back(); const SV& right_states = *(&backward_sv.back() - 1); (*step)->backward(right_states, &num_edmans, left_states); } double probability = backward_sv.back().source(); // We will end up adding NaN results to the fitter if the probability is // 0, because the numerators and denominators of parameter estimates // will both be 0 - parameter estimates are less than or equal to the // full probability always. Then we end up adding 0/0 to the numerator // AND the denominator, putting a NaN in both cases. // // To avoid this, we just return early. if (probability == 0.0) { return probability; } auto backward_states = backward_sv.end(); // iterator type SV forward_states = create_states(); forward_states.initialize_from_start(); while (step != steps.end()) { backward_states--; (*step)->improve_fit(forward_states, *backward_states, *(backward_states - 1), num_edmans, probability, fitter); (*step)->forward(&num_edmans, &forward_states); step++; } return probability; } std::vector<const Step<SV>*> steps; int num_timesteps; }; } // namespace whatprot #endif // WHATPROT_HMM_HMM_GENERIC_HMM_H
40.622449
80
0.563929
[ "vector", "model" ]
4147cac2a22145e0d1f375dbe11ed3fde9b5359b
3,319
h
C
libshaderc_util/include/libshaderc_util/mutex.h
hbirchtree/shaderc
d7f7261c2273bd690275e5f6db3f08072ea03a0f
[ "Apache-2.0" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
libshaderc_util/include/libshaderc_util/mutex.h
hbirchtree/shaderc
d7f7261c2273bd690275e5f6db3f08072ea03a0f
[ "Apache-2.0" ]
907
2015-08-07T16:01:29.000Z
2022-03-14T18:02:39.000Z
libshaderc_util/include/libshaderc_util/mutex.h
hbirchtree/shaderc
d7f7261c2273bd690275e5f6db3f08072ea03a0f
[ "Apache-2.0" ]
344
2015-08-07T14:17:44.000Z
2022-03-30T02:25:08.000Z
// Copyright 2015 The Shaderc 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 LIBSHADERC_UTIL_INC_MUTEX_H #define LIBSHADERC_UTIL_INC_MUTEX_H // shaderc_util::mutex will be defined and specialized // depending on the platform that is being compiled. // It is more or less conformant to the C++11 specification of std::mutex. // However it does not implement try_lock. #ifdef _WIN32 // windows.h #defines min and max if we don't define this. // this means things like std::min and std::max break #ifndef NOMINMAX #define NOMINMAX #endif #include <windows.h> namespace shaderc_util { // As the name suggests, this mutex class is for running on windows. // It conforms to the c++11 mutex implementation, and should be a // drop in replacement. class windows_mutex { public: using native_handle_type = HANDLE; windows_mutex() { mutex_ = CreateMutex(nullptr, false, nullptr); } ~windows_mutex() { if (mutex_ != INVALID_HANDLE_VALUE) { CloseHandle(mutex_); } } windows_mutex(const windows_mutex&) = delete; windows_mutex& operator=(const windows_mutex&) = delete; // Locks this mutex, waiting until the mutex is unlocked if it is not already. // It is not valid to lock a mutex that has already been locked. void lock() { WaitForSingleObject(mutex_, INFINITE); } // Unlocks this mutex. It is invalid to unlock a mutex that this thread // has not already locked. void unlock() { ReleaseMutex(mutex_); } // Returns the native handle for this mutex. In this case a HANDLE object. native_handle_type native_handle() { return mutex_; } private: HANDLE mutex_; }; using mutex = windows_mutex; } #else #include <pthread.h> #include <memory> namespace shaderc_util { // As the name suggests, this mutex class is for running with pthreads. // It conforms to the c++11 mutex implementation, and should be a // drop in replacement. class posix_mutex { public: using native_handle_type = pthread_mutex_t*; posix_mutex() { pthread_mutex_init(&mutex_, nullptr); } ~posix_mutex() { pthread_mutex_destroy(&mutex_); } posix_mutex(const posix_mutex&) = delete; posix_mutex& operator=(const posix_mutex&) = delete; // Locks this mutex, waiting until the mutex is unlocked if it is not already. // It is not valid to lock a mutex that has already been locked. void lock() { pthread_mutex_lock(&mutex_); } // Unlocks this mutex. It is invalid to unlock a mutex that this thread // has not already locked. void unlock() { pthread_mutex_unlock(&mutex_); } // Returns the native handle for this mutex. In this case a pthread_mutex_t*. native_handle_type native_handle() { return &mutex_; } private: pthread_mutex_t mutex_; }; using mutex = posix_mutex; } #endif #endif // LIBSHADERC_UTIL_INC_MUTEX_H
30.731481
80
0.736065
[ "object" ]
4152d152779b2ffa94682d5dc1517488e7f450c0
2,736
h
C
chrome/browser/media/router/discovery/dial/device_description_fetcher.h
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/media/router/discovery/dial/device_description_fetcher.h
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/media/router/discovery/dial/device_description_fetcher.h
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 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_MEDIA_ROUTER_DISCOVERY_DIAL_DEVICE_DESCRIPTION_FETCHER_H_ #define CHROME_BROWSER_MEDIA_ROUTER_DISCOVERY_DIAL_DEVICE_DESCRIPTION_FETCHER_H_ #include <memory> #include <string> #include "base/callback.h" #include "base/threading/thread_checker.h" #include "content/public/browser/browser_thread.h" #include "net/url_request/url_fetcher_delegate.h" #include "url/gurl.h" namespace net { class URLFetcher; class URLRequestContextGetter; } namespace media_router { struct DialDeviceDescriptionData; // Used to make a single HTTP GET request with |device_description_url| to fetch // a uPnP device description from a DIAL device. If successful, |success_cb| is // invoked with the result; otherwise, |error_cb| is invoked with an error // reason. // This class is not thread safe. class DeviceDescriptionFetcher : public net::URLFetcherDelegate { public: // Used to identify the net::URLFetcher instance for tests. static constexpr int kURLFetcherIDForTest = 1; // |request_context| is unowned; the caller must ensure that this object does // not outlive it. DeviceDescriptionFetcher( const GURL& device_description_url, net::URLRequestContextGetter* request_context, base::OnceCallback<void(const DialDeviceDescriptionData&)> success_cb, base::OnceCallback<void(const std::string&)> error_cb); ~DeviceDescriptionFetcher() override; const GURL& device_description_url() { return device_description_url_; } void Start(); private: // net::URLFetcherDelegate implementation. void OnURLFetchComplete(const net::URLFetcher* source) override; void OnURLFetchDownloadProgress(const net::URLFetcher* source, int64_t current, int64_t total, int64_t current_network_bytes) override; void OnURLFetchUploadProgress(const net::URLFetcher* source, int64_t current, int64_t total) override; // Runs |error_cb_| with |message| and clears it. void ReportError(const std::string& message); const GURL device_description_url_; const scoped_refptr<net::URLRequestContextGetter> request_context_; base::ThreadChecker thread_checker_; base::OnceCallback<void(const DialDeviceDescriptionData&)> success_cb_; base::OnceCallback<void(const std::string&)> error_cb_; std::unique_ptr<net::URLFetcher> fetcher_; }; } // namespace media_router #endif // CHROME_BROWSER_MEDIA_ROUTER_DISCOVERY_DIAL_DEVICE_DESCRIPTION_FETCHER_H_
36
83
0.741594
[ "object" ]
41672e7a015ee6f9fb3bb8f5ee82b4d5b1822852
8,499
h
C
src/esp/assets/managers/SceneAttributesManager.h
wkentaro/habitat-sim
f0e4a770196a2ea11557230977c4840b68b2e5cf
[ "MIT" ]
1
2020-07-23T03:39:27.000Z
2020-07-23T03:39:27.000Z
src/esp/assets/managers/SceneAttributesManager.h
Jthon/habitat-sim
27b920f19c53c15818f6d3b320b50b8adcda4e11
[ "MIT" ]
null
null
null
src/esp/assets/managers/SceneAttributesManager.h
Jthon/habitat-sim
27b920f19c53c15818f6d3b320b50b8adcda4e11
[ "MIT" ]
1
2021-07-06T05:32:03.000Z
2021-07-06T05:32:03.000Z
// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #ifndef ESP_ASSETS_MANAGERS_SCENEATTRIBUTEMANAGER_H_ #define ESP_ASSETS_MANAGERS_SCENEATTRIBUTEMANAGER_H_ #include "AttributesManagerBase.h" #include "ObjectAttributesManager.h" namespace esp { namespace assets { namespace managers { class SceneAttributesManager : public AttributesManager<PhysicsSceneAttributes::ptr> { public: SceneAttributesManager(assets::ResourceManager& resourceManager, ObjectAttributesManager::ptr objectAttributesMgr) : AttributesManager<PhysicsSceneAttributes::ptr>::AttributesManager( resourceManager), objectAttributesMgr_(objectAttributesMgr) { buildCtorFuncPtrMaps(); } /** * @brief Creates an instance of a scene template described by passed string. * For scene templates, this a file name. * * If a template exists with this handle, this existing template will be * overwritten with the newly created one if @ref registerTemplate is true. * * @param sceneAttributesHandle the origin of the desired template to be * created, in this case, a file name. * @param registerTemplate whether to add this template to the library. * If the user is going to edit this template, this should be false - any * subsequent editing will require re-registration. Defaults to true. If * specified as true, then this function returns a copy of the registered * template. * @return a reference to the desired template. */ PhysicsSceneAttributes::ptr createAttributesTemplate( const std::string& sceneAttributesHandle, bool registerTemplate = true) override; /** * @brief Creates a an instance of scene attributes template populated with * default values. Assigns the @ref templateName as the template's handle, * and render and collision handles. * * If a template exists with this handle, the existing template will be * overwritten with the newly created one if @ref registerTemplate is true. * This method is specifically intended to directly construct an attributes * template for editing, and so defaults to false for @ref registerTemplate * * @param templateName Name to use for the attributes handle. * @param registerTemplate whether to add this template to the library. * If the user is going to edit this template, this should be false - any * subsequent editing will require re-registration. Defaults to false. If * specified as true, then this function returns a copy of the registered * template. * @return a reference to the desired template, or nullptr if fails. */ PhysicsSceneAttributes::ptr createDefaultAttributesTemplate( const std::string& templateName, bool registerTemplate = false) override; /** * @brief Sets all relevant attributes to all scenes based on passed @ref * physicsManagerAttributes. * * @param physicsManagerAttributes The attributes describing the physics world * this scene lives in. */ void setSceneValsFromPhysicsAttributes( const PhysicsManagerAttributes::cptr physicsManagerAttributes) { for (auto sceneAttrPair : this->templateLibrary_) { auto sceneAttr = this->getTemplateCopyByHandle(sceneAttrPair.first); sceneAttr->setFrictionCoefficient( physicsManagerAttributes->getFrictionCoefficient()); sceneAttr->setRestitutionCoefficient( physicsManagerAttributes->getRestitutionCoefficient()); this->addTemplateToLibrary(sceneAttr, sceneAttrPair.first); } } // SceneAttributesManager::setSceneValsFromPhysicsAttributes /** * @brief Creates an instance of a scene template described by passed * string, which should be a reference to an existing primitive asset template * to be used in the construction of the scene (as render and collision * mesh). It returns existing instance if there is one, and nullptr if fails. * * @param primAttrTemplateHandle The handle to an existing primitive asset * template. Fails if does not. * @param registerTemplate whether to add this template to the library. * If the user is going to edit this template, this should be false - any * subsequent editing will require re-registration. Defaults to true. * @return a reference to the desired scene template, or nullptr if fails. */ PhysicsSceneAttributes::ptr createPrimBasedAttributesTemplate( const std::string& primAttrTemplateHandle, bool registerTemplate = true); protected: /** * @brief Scene is file-based, described by @ref sceneFilename; populate a * returned scene attributes with appropriate data. This method's intended * use is to support backwards compatibility for when scene meshes are loaded * without JSON files. * * @param sceneFilename The mesh file name * @param registerTemplate whether to add this template to the library or not. * @return a reference to the desired scene template, or nullptr if fails. */ PhysicsSceneAttributes::ptr createFileBasedAttributesTemplate( const std::string& sceneFilename, bool registerTemplate = true); /** * @brief Read and parse the json file @ref sceneFilename and populate a * returned scene attributes with appropriate data. * * @param sceneFilename The configuration file to parse. * @param registerTemplate whether to add this template to the library or not. * @return a reference to the desired scene template, or nullptr if fails. */ PhysicsSceneAttributes::ptr createJSONFileBasedAttributesTemplate( const std::string& sceneFilename, bool registerTemplate = true); /** * @brief Instantiate a @ref PhysicsSceneAttributes for a * synthetic(primitive-based render) scene. NOTE : Must be registered to be * available for use via @ref registerObjectTemplate. This method is provided * so the user can modify a specified physics scene template before * registering it. * * @param primAssetHandle The string name of the primitive asset attributes to * be used to synthesize a render asset and solve collisions implicitly for * the desired scene. Will also become the default handle of the resultant * @ref PhysicsSceneAttributes template * @return The @ref PhysicsSceneAttributes template based on the passed * primitive */ PhysicsSceneAttributes::ptr buildPrimBasedPhysObjTemplate( const std::string& primAssetHandle); /** * @brief Add a @ref std::shared_ptr<attributesType> object to the * @ref templateLibrary_. Verify that render and collision handles have been * set properly. We are doing this since these values can be modified by the * user. * * @param sceneAttributesTemplate The attributes template. * @param sceneAttributesHandle The key for referencing the template in the * @ref templateLibrary_. * @return The index in the @ref templateLibrary_ of object * template. */ int registerAttributesTemplateFinalize( PhysicsSceneAttributes::ptr sceneAttributesTemplate, const std::string& sceneAttributesHandle) override; /** * @brief Whether template described by passed handle is read only, or can be * deleted. All SceneAttributes templates are removable, by default */ bool isTemplateReadOnly(const std::string&) override { return false; }; /** * @brief Any scene-attributes-specific resetting that needs to happen on * reset. */ void resetFinalize() override {} /** * @brief This function will assign the appropriately configured function * pointer for the copy constructor as required by * AttributesManager<PhysicsSceneAttributes::ptr> */ void buildCtorFuncPtrMaps() override { this->copyConstructorMap_["PhysicsSceneAttributes"] = &SceneAttributesManager::createAttributesCopy< assets::PhysicsSceneAttributes>; } // SceneAttributesManager::buildCtorFuncPtrMaps // instance vars /** * @brief Reference to ObjectAttributesManager to give access to setting * object template library using paths specified in SceneAttributes json */ ObjectAttributesManager::ptr objectAttributesMgr_ = nullptr; public: ESP_SMART_POINTERS(SceneAttributesManager) }; // SceneAttributesManager } // namespace managers } // namespace assets } // namespace esp #endif // ESP_ASSETS_MANAGERS_SCENEATTRIBUTEMANAGER_H_
41.661765
80
0.743499
[ "mesh", "render", "object" ]
41693afbc264428fda38ab1140a1d032332c84a6
3,082
h
C
src/Synet/Layers/HardSigmoidLayer.h
ermig1979/Synet
a6c8fc1b8931947f070bcbc0f597c6889501e168
[ "MIT" ]
111
2018-01-12T09:08:08.000Z
2022-01-22T17:44:42.000Z
src/Synet/Layers/HardSigmoidLayer.h
ermig1979/Synet
a6c8fc1b8931947f070bcbc0f597c6889501e168
[ "MIT" ]
18
2018-04-08T09:38:16.000Z
2022-02-16T10:14:11.000Z
src/Synet/Layers/HardSigmoidLayer.h
ermig1979/Synet
a6c8fc1b8931947f070bcbc0f597c6889501e168
[ "MIT" ]
26
2018-01-30T15:31:43.000Z
2021-03-29T07:14:05.000Z
/* * Synet Framework (http://github.com/ermig1979/Synet). * * Copyright (c) 2018-2021 Yermalayeu Ihar. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #include "Synet/Common.h" #include "Synet/Layer.h" #include "Synet/Utils/Math.h" namespace Synet { namespace Detail { template <class T> SYNET_INLINE T HardSigmoidCpu(T value, T scale, T shift) { return Max(T(0), Min(value * scale + shift, T(1))); } template <class T> void HardSigmoidLayerForwardCpu(const T * src, size_t size, T scale, T shift, T * dst) { for (size_t i = 0; i < size; ++i) dst[i] = HardSigmoidCpu(src[i], scale, shift); } #ifdef SYNET_SIMD_LIBRARY_ENABLE template <> SYNET_INLINE void HardSigmoidLayerForwardCpu(const float * src, size_t size, float scale, float shift, float * dst) { ::SimdSynetHardSigmoid32f(src, size, &scale, &shift, dst); } #endif } template <class T> class HardSigmoidLayer : public Synet::Layer<T> { public: typedef T Type; typedef Layer<T> Base; typedef typename Base::TensorPtrs TensorPtrs; HardSigmoidLayer(const LayerParam & param, Context* context) : Base(param, context) { } virtual void Reshape(const TensorPtrs & src, const TensorPtrs & buf, const TensorPtrs & dst) { HardSigmoidParam hardSigmoid = this->Param().hardSigmoid(); _scale = hardSigmoid.scale(); _shift = hardSigmoid.shift(); dst[0]->Reshape(src[0]->Shape(), src[0]->Format()); this->UsePerfStat(); } protected: virtual void ForwardCpu(const TensorPtrs & src, const TensorPtrs & buf, const TensorPtrs & dst) { Detail::HardSigmoidLayerForwardCpu(src[0]->CpuData(), src[0]->Size(), _scale, _shift, dst[0]->CpuData()); } private: Type _scale, _shift; }; }
36.690476
136
0.640818
[ "shape" ]
416da5745b75be2cfbce467347f625c9963d5b31
4,164
h
C
Userland/Libraries/LibTLS/Certificate.h
densogiaichned/serenity
99c0b895fed02949b528437d6b450d85befde7a5
[ "BSD-2-Clause" ]
2
2022-02-16T02:12:38.000Z
2022-02-20T18:40:41.000Z
Userland/Libraries/LibTLS/Certificate.h
densogiaichned/serenity
99c0b895fed02949b528437d6b450d85befde7a5
[ "BSD-2-Clause" ]
null
null
null
Userland/Libraries/LibTLS/Certificate.h
densogiaichned/serenity
99c0b895fed02949b528437d6b450d85befde7a5
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2020, the SerenityOS developers. * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/ByteBuffer.h> #include <AK/Forward.h> #include <AK/Optional.h> #include <AK/Singleton.h> #include <AK/Types.h> #include <LibCore/DateTime.h> #include <LibCrypto/BigInt/UnsignedBigInteger.h> #include <LibCrypto/PK/RSA.h> namespace TLS { enum class CertificateKeyAlgorithm { Unsupported = 0x00, RSA_RSA = 0x01, RSA_MD5 = 0x04, RSA_SHA1 = 0x05, RSA_SHA256 = 0x0b, RSA_SHA384 = 0x0c, RSA_SHA512 = 0x0d, }; class Certificate { public: u16 version { 0 }; CertificateKeyAlgorithm algorithm { CertificateKeyAlgorithm::Unsupported }; CertificateKeyAlgorithm key_algorithm { CertificateKeyAlgorithm::Unsupported }; CertificateKeyAlgorithm ec_algorithm { CertificateKeyAlgorithm::Unsupported }; ByteBuffer exponent {}; Crypto::PK::RSAPublicKey<Crypto::UnsignedBigInteger> public_key {}; Crypto::PK::RSAPrivateKey<Crypto::UnsignedBigInteger> private_key {}; struct Name { String country; String state; String location; String entity; String subject; String unit; } issuer, subject; Core::DateTime not_before; Core::DateTime not_after; Vector<String> SAN; u8* ocsp { nullptr }; Crypto::UnsignedBigInteger serial_number; ByteBuffer sign_key {}; ByteBuffer fingerprint {}; ByteBuffer der {}; ByteBuffer data {}; CertificateKeyAlgorithm signature_algorithm { CertificateKeyAlgorithm::Unsupported }; ByteBuffer signature_value {}; ByteBuffer original_asn1 {}; bool is_allowed_to_sign_certificate { false }; bool is_certificate_authority { false }; Optional<size_t> path_length_constraint {}; static Optional<Certificate> parse_asn1(ReadonlyBytes, bool client_cert = false); bool is_valid() const; String subject_identifier_string() const { StringBuilder cert_name; if (!subject.country.is_empty()) { cert_name.append("/C="); cert_name.append(subject.country); } if (!subject.state.is_empty()) { cert_name.append("/ST="); cert_name.append(subject.state); } if (!subject.location.is_empty()) { cert_name.append("/L="); cert_name.append(subject.location); } if (!subject.entity.is_empty()) { cert_name.append("/O="); cert_name.append(subject.entity); } if (!subject.unit.is_empty()) { cert_name.append("/OU="); cert_name.append(subject.unit); } if (!subject.subject.is_empty()) { cert_name.append("/CN="); cert_name.append(subject.subject); } return cert_name.build(); } String issuer_identifier_string() const { StringBuilder cert_name; if (!issuer.country.is_empty()) { cert_name.append("/C="); cert_name.append(issuer.country); } if (!issuer.state.is_empty()) { cert_name.append("/ST="); cert_name.append(issuer.state); } if (!issuer.location.is_empty()) { cert_name.append("/L="); cert_name.append(issuer.location); } if (!issuer.entity.is_empty()) { cert_name.append("/O="); cert_name.append(issuer.entity); } if (!issuer.unit.is_empty()) { cert_name.append("/OU="); cert_name.append(issuer.unit); } if (!issuer.subject.is_empty()) { cert_name.append("/CN="); cert_name.append(issuer.subject); } return cert_name.build(); } }; class DefaultRootCACertificates { public: DefaultRootCACertificates(); Vector<Certificate> const& certificates() const { return m_ca_certificates; } static DefaultRootCACertificates& the() { return s_the; } private: static Singleton<DefaultRootCACertificates> s_the; Vector<Certificate> m_ca_certificates; }; } using TLS::Certificate; using TLS::DefaultRootCACertificates;
28.520548
89
0.62536
[ "vector" ]
417197a999965734d8fbb2a79bbdd4c7077ec296
4,113
h
C
tests/traversal.h
data-man/glob-cpp
1aca32f9c4b4b3072a00defd400eaf9f77606bc2
[ "Apache-2.0" ]
7
2019-05-10T20:17:49.000Z
2021-08-03T04:15:25.000Z
tests/traversal.h
data-man/glob-cpp
1aca32f9c4b4b3072a00defd400eaf9f77606bc2
[ "Apache-2.0" ]
2
2021-08-03T04:13:36.000Z
2022-02-05T20:16:30.000Z
tests/traversal.h
data-man/glob-cpp
1aca32f9c4b4b3072a00defd400eaf9f77606bc2
[ "Apache-2.0" ]
2
2021-01-06T15:21:47.000Z
2021-10-15T06:22:28.000Z
#ifndef GLOB_CPP_TRAVERSAL_H #define GLOB_CPP_TRAVERSAL_H #include<iostream> #include "glob-cpp/glob.h" namespace glob { template<class charT> class PrintTraversal: public AstVisitor<charT> { public: void Visit(AstNode<charT> *node) { level_ = 0; after_simple_ = false; node->Accept(this); } void VisitCharNode(CharNode<charT>* char_node) override { char c = char_node->GetValue(); std::cout << "[" << c << "]"; after_simple_ = true; } void VisitRangeNode(RangeNode<charT>* node) override { after_simple_ = false; NewLine(false); Level(); std::cout << "<range start: "; node->GetStart()->Accept(this); std::cout << ", end: "; node->GetEnd()->Accept(this); std::cout << ">"; NewLine(); after_simple_ = false; } void VisitSetItemsNode(SetItemsNode<charT>* node) override { after_simple_ = false; auto& vec = node->GetItems(); for (auto& item_node : vec) { item_node.get()->Accept(this); } after_simple_ = false; } void VisitPositiveSetNode(PositiveSetNode<charT>* node) override { NewLine(false); after_simple_ = false; Level(); std::cout << "<set-positive>"; NewLine(); ++level_; node->GetSet()->Accept(this); --level_; Level(); std::cout << "</set-positive>"; NewLine(); after_simple_ = false; } void VisitNegativeSetNode(NegativeSetNode<charT>* node) override { NewLine(false); after_simple_ = false; Level(); std::cout << "<neg-positive>"; NewLine(); ++level_; node->GetSet()->Accept(this); --level_; Level(); std::cout << "</neg-positive>"; NewLine(); after_simple_ = false; } void VisitStarNode(StarNode<charT>* node) override { std::cout << "[star]"; after_simple_ = true; } void VisitAnyNode(AnyNode<charT>* node) override { std::cout << "[any]"; after_simple_ = true; } void VisitGroupNode(GroupNode<charT>* node) override { NewLine(false); after_simple_ = false; Level(); std::cout << "<group>"; NewLine(); ++level_; node->GetGlob()->Accept(this); --level_; Level(); std::cout << "</group>"; NewLine(); } void VisitConcatNode(ConcatNode<charT>* node) override { NewLine( ); after_simple_ = false; auto& vec = node->GetBasicGlobs(); Level(); std::cout << "<concat>"; NewLine(); ++level_; Level(); for (auto& item_node : vec) { item_node.get()->Accept(this); } --level_; NewLine(false); Level(); std::cout << "</concat>"; NewLine(); after_simple_ = false; } void VisitUnionNode(UnionNode<charT>* node) override { after_simple_ = false; auto& vec = node->GetItems(); Level(); std::cout << "<union>"; NewLine(); for (auto& item_node : vec) { ++level_; Level(); std::cout << "<item>"; item_node.get()->Accept(this); Level(); std::cout << "</item>"; --level_; } NewLine(false); Level(); std::cout << "</union>"; NewLine(); after_simple_ = false; } void VisitGlobNode(GlobNode<charT>* node) override { after_simple_ = false; ++level_; Level(); std::cout << "<glob>"; NewLine(); node->GetConcat()->Accept(this); Level(); std::cout << "</glob>"; NewLine(); --level_; after_simple_ = false; } private: void NewLine(bool v = true) { if (v) { std::cout << "\n"; } else { if (after_simple_) { std::cout << "\n"; } } } void Level() { for (int i = 0; i < level_-1; i++) { std::cout << " │"; } std::cout << " ├"; std::cout << "─"; } bool after_simple_; int level_; }; template<class charT> void PrintAst(const String<charT>& str) { Lexer<charT> l(str); std::vector<Token<charT>> tokens = l.Scanner(); Parser<charT> p(std::move(tokens)); AstNodePtr<charT> ast_ptr = p.GenAst(); PrintTraversal<charT> visitor; visitor.Visit(ast_ptr.get()); std::cout << "\n"; } } // namespace glob #endif // GLOB_CPP_TRAVERSAL_H
20.878173
68
0.571116
[ "vector" ]
417ab75810750cd2f3a9e79f6635a4887a27cae0
4,496
h
C
include/SafeDynMemAlloc.h
spurious/safecode-mirror
238e1a381674528f642e1ee6be1e1b7df465672e
[ "NCSA" ]
5
2015-07-23T09:47:12.000Z
2019-11-28T01:34:01.000Z
include/SafeDynMemAlloc.h
spurious/safecode-mirror
238e1a381674528f642e1ee6be1e1b7df465672e
[ "NCSA" ]
null
null
null
include/SafeDynMemAlloc.h
spurious/safecode-mirror
238e1a381674528f642e1ee6be1e1b7df465672e
[ "NCSA" ]
3
2015-10-28T18:21:02.000Z
2019-05-06T18:35:41.000Z
//===- SafeDynMemAlloc.h - CZero passes -----------------*- C++ -*---------=// // // The SAFECode Compiler // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a set of utilities for EmbeC checks on pointers and // dynamic memory. // // FIXME: // This pass is currently disabled and a subset of its functinality moved to // the Check Insertion Pass. However, removing it from the sc tool seems to // cause the other SAFECode passes grief. Therefore, this pass is left in // place, but it does nothing. // // FIXME: // Note that this pass preserves all other passes. This must be left intact; // otherwise, it will invalidate the pool allocation results and cause // SAFECode to erronously re-execute the pool allocation pass. // // This file defines the interface to the EmbeCFreeRemoval pass. This pass // appears to do two things: // // o) It ensures that there are load/store checks on pointers that point to // type-known data but are loaded from type-unknown partitions. // // o) It seems to perform some sort of sanity/correctness checking of pool // creation/destruction. // //===----------------------------------------------------------------------===// #ifndef LLVM_EMBEC_H #define LLVM_EMBEC_H #include "dsa/DataStructure.h" #include "dsa/DSGraph.h" #include "safecode/Config/config.h" #include "llvm/Pass.h" #include "llvm/Transforms/IPO.h" #include "llvm/ADT/PostOrderIterator.h" #include "llvm/DerivedTypes.h" #include "llvm/Constants.h" #include "llvm/Support/CFG.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/Support/Debug.h" #include "poolalloc/PoolAllocate.h" #include <set> #include <map> #include <string> using std::set; using std::map; using namespace llvm; using namespace PA; Pass* createEmbeCFreeRemovalPass(); namespace { static const std::string PoolI = "poolinit"; static const std::string PoolA = "poolalloc"; static const std::string PoolF = "poolfree"; static const std::string PoolD = "pooldestroy"; static const std::string PoolMUF = "poolmakeunfreeable"; static const std::string PoolCh = "poolcheck"; static const std::string PoolAA = "poolregister"; } namespace llvm { struct EmbeCFreeRemoval : public ModulePass { // The function representing 'poolmakeunfreeable' Constant *PoolMakeUnfreeable; Constant *PoolCheck; bool runOnModule(Module &M); std::vector<Value *> Visited; static char ID; EmbeCFreeRemoval () : ModulePass ((intptr_t) &ID) {} const char *getPassName() const { return "Embedded C Free Removal"; } void checkPoolSSAVarUses(Function *F, Value *V, map<Value *, set<Instruction *> > &FuncAllocs, map<Value *, set<Instruction *> > &FuncFrees, map<Value *, set<Instruction *> > &FuncDestroy); void propagateCollapsedInfo(Function *F, Value *V); DSNode *guessDSNode(Value *v, DSGraph &G, PA::FuncInfo *PAFI); void guessPoolPtrAndInsertCheck(PA::FuncInfo *PAFI, Value *oldI, Instruction *I, Value *pOpI, DSGraph &oldG); void insertNonCollapsedChecks(Function *Forig, Function *F, DSNode *DSN); void addRuntimeChecks(Function *F, Function *Forig); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<PoolAllocateGroup>(); AU.addPreserved<PoolAllocateGroup>(); AU.addRequired<CallGraph>(); AU.setPreservesAll(); } // Maps from a function to a set of Pool pointers and DSNodes from the // original function corresponding to collapsed pools. map <Function *, set<Value *> > CollapsedPoolPtrs; private: Module *CurModule; TDDataStructures *TDDS; PoolAllocateGroup *PoolInfo; bool moduleChanged; bool hasError; // The following maps are only for pool pointers that escape a function. // Associates function with set of pools that are freed or alloc'ed using // pool_free or pool_alloc but not destroyed within the function. // These have to be pool pointer arguments to the function map<Function *, set<Value *> > FuncFreedPools; map<Function *, set<Value *> > FuncAllocedPools; map<Function *, set<Value *> > FuncDestroyedPools; }; } #endif
32.817518
114
0.661922
[ "vector" ]
41806c6a323059326cc767aa29adc36cac0fc0ba
1,135
h
C
include/Astar.h
zzjkf2009/Acme-Robotics-Project
3864a3428f87e3d5245d08eeeca35aedcc63ab04
[ "MIT" ]
null
null
null
include/Astar.h
zzjkf2009/Acme-Robotics-Project
3864a3428f87e3d5245d08eeeca35aedcc63ab04
[ "MIT" ]
null
null
null
include/Astar.h
zzjkf2009/Acme-Robotics-Project
3864a3428f87e3d5245d08eeeca35aedcc63ab04
[ "MIT" ]
null
null
null
/** *@file WeightedAstar.h *@Copyright (C) 2017 Zejiang Zeng - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, please visit : https://github.com/zzjkf2009/Acme-Robotics-Project/blob/master/LICENSE *@brief This header define the <Astar> calss, which is an algorithm for path * planning */ #ifndef INCLUDE_ASTAR_H_ #define INCLUDE_ASTAR_H_ #include<iostream> #include<set> #include<vector> #include<stack> #include<cmath> #include<cstring> #include<utility> class Astar { public: #define ROW 10 #define COL 10 #define FLT_MAX __FLT_MAX__ struct node { int parent_x; int parent_y; double F, H, G; }; typedef std::pair<int, int> coordinate; typedef std::pair<double, std::pair<int, int> > Open_list; bool isValid(const int& x, const int& y); bool isUnblocked(int grid[][COL], const int& x, const int& y); bool isGoalNode(const int& x, const int& y, coordinate goal); double calculate_H(const int& x, const int& y, coordinate goal); std::stack<coordinate> GeneratePath(node nodepath[][COL], coordinate goal); }; #endif // INCLUDE_ASTAR_H_
27.02381
77
0.719824
[ "vector" ]
4195bc0ffec3be370a72bfa65b48686d1a6146bc
3,227
h
C
rcgen/cpp/model_constants.h
kmarkus/ublx-ur5_sim
51efa12446a7ef9ab5e3e783ce2a6409a3db390f
[ "BSD-3-Clause" ]
1
2020-11-07T11:39:31.000Z
2020-11-07T11:39:31.000Z
rcgen/cpp/model_constants.h
kmarkus/ublx-ur5_sim
51efa12446a7ef9ab5e3e783ce2a6409a3db390f
[ "BSD-3-Clause" ]
1
2020-11-10T16:03:37.000Z
2020-11-10T16:03:37.000Z
rcgen/cpp/model_constants.h
kmarkus/ublx-ur5_sim
51efa12446a7ef9ab5e3e783ce2a6409a3db390f
[ "BSD-3-Clause" ]
1
2020-11-07T10:57:43.000Z
2020-11-07T10:57:43.000Z
#ifndef RCG_UR5_MODEL_CONSTANTS_H_ #define RCG_UR5_MODEL_CONSTANTS_H_ #include "rbd_types.h" /** * \file * This file contains the definitions of all the non-zero numerical * constants of the robot model (i.e. the numbers appearing in the * .kindsl file). * * Varying these values (and recompiling) is a quick & dirty * way to vary the kinematics/dynamics model. For a much more * flexible way of exploring variations of the model, consider * using the parametrization feature of RobCoGen (see the wiki). * * Beware of inconsistencies when changing any of the inertia * properties. */ namespace ur5 { namespace rcg { // Do not use 'constexpr' to allow for non-literal scalar types const Scalar tz_shoulder_pan = 0.08915899693965912; const Scalar tx_shoulder_lift = 0.1358499974012375; const Scalar tx_elbow = 0.42500001192092896; const Scalar tz_elbow = -0.11969999969005585; const Scalar tx_wr1 = 0.3922500014305115; const Scalar tz_wr1 = 0.09314999729394913; const Scalar tx_wr2 = 0.09475000202655792; const Scalar tx_wr3 = 0.08250000327825546; const Scalar m_base = 4.0; const Scalar comz_base = 0.02500000037252903; const Scalar ix_base = 0.006930000148713589; const Scalar iy_base = 0.006930000148713589; const Scalar iz_base = 0.007199999876320362; const Scalar m_shoulder = 3.700000047683716; const Scalar comy_shoulder = 0.001930000027641654; const Scalar comz_shoulder = -0.025609999895095825; const Scalar ix_shoulder = 0.01271000038832426; const Scalar iy_shoulder = 0.012690000236034393; const Scalar iyz_shoulder = -1.8000000272877514E-4; const Scalar iz_shoulder = 0.006670000031590462; const Scalar m_upper_arm = 8.392999649047852; const Scalar comy_upper_arm = -0.02419999986886978; const Scalar comz_upper_arm = 0.21250000596046448; const Scalar ix_upper_arm = 0.6093699932098389; const Scalar iy_upper_arm = 0.604449987411499; const Scalar iyz_upper_arm = -0.04315999895334244; const Scalar iz_upper_arm = 0.017149999737739563; const Scalar m_forearm = 2.2750000953674316; const Scalar comy_forearm = 0.026499999687075615; const Scalar comz_forearm = 0.11992999911308289; const Scalar ix_forearm = 0.08263000100851059; const Scalar iy_forearm = 0.0810299962759018; const Scalar iyz_forearm = 0.007230000104755163; const Scalar iz_forearm = 0.0034199999645352364; const Scalar m_wrist_1 = 1.218999981880188; const Scalar comy_wrist_1 = 0.11095000058412552; const Scalar comz_wrist_1 = 0.016340000554919243; const Scalar ix_wrist_1 = 0.017410000786185265; const Scalar iy_wrist_1 = 0.002409999957308173; const Scalar iyz_wrist_1 = 0.0022100000642240047; const Scalar iz_wrist_1 = 0.01624000072479248; const Scalar m_wrist_2 = 1.218999981880188; const Scalar comy_wrist_2 = 0.0017999999690800905; const Scalar comz_wrist_2 = 0.1109900027513504; const Scalar ix_wrist_2 = 0.017100000753998756; const Scalar iy_wrist_2 = 0.017100000753998756; const Scalar iyz_wrist_2 = 2.3999999393709004E-4; const Scalar iz_wrist_2 = 0.0012400000123307109; const Scalar m_wrist_3 = 0.18790000677108765; const Scalar comy_wrist_3 = 0.0011599999852478504; const Scalar ix_wrist_3 = 3.1999999191612005E-4; const Scalar iy_wrist_3 = 3.1999999191612005E-4; const Scalar iz_wrist_3 = 1.900000061141327E-4; } } #endif
38.879518
67
0.809111
[ "model" ]
419c651093e87466905ddc58b197ad7eaf8ecc6d
2,318
c
C
kungfu/skill/shenghuo-shengong.c
zhangyifei/mud
b2090bbd2a8d3d82b86148d794a7ca59cd2429f3
[ "MIT" ]
69
2018-03-08T18:24:44.000Z
2022-02-24T13:43:53.000Z
kungfu/skill/shenghuo-shengong.c
zhangyifei/mud
b2090bbd2a8d3d82b86148d794a7ca59cd2429f3
[ "MIT" ]
3
2019-04-24T12:21:19.000Z
2021-03-28T23:34:58.000Z
kungfu/skill/shenghuo-shengong.c
zhangyifei/mud
b2090bbd2a8d3d82b86148d794a7ca59cd2429f3
[ "MIT" ]
33
2017-12-23T05:06:58.000Z
2021-08-16T02:42:59.000Z
inherit FORCE; #include <ansi.h> int valid_enable(string usage) { return usage == "force"; } int query_neili_improve(object me) { int lvl; lvl = (int)me->query_skill("shenghuo-shengong", 1); return lvl * lvl * 15 * 16 / 100 / 200; } int valid_force(string force) { return (force == "shenghuo-xinfa"); } int valid_learn(object me) { if (me->query("gender") == "无性" && (int)me->query_skill("shenghuo-shengong", 1) > 49) return notify_fail("你无根无性,阴阳不调,难以领会高深的圣火神功。\n"); if (me->query("int") < 32) return notify_fail("你先天悟性不够,无法领悟圣火神功。\n"); if ((int)me->query_skill("force", 1) < 180) return notify_fail("你的基本内功火候还不够,还不能学习圣火神功。\n"); return ::valid_learn(me); } int practice_skill(object me) { return notify_fail("圣火神功只能用学(learn)的来增加熟练度。\n"); } mixed hit_ob(object me, object victim, int damage_bonus, int factor) { int lvl, i; int flvl, attack_time; object weapon; lvl = me->query_skill("shenghuo-shengong", 1); flvl = me->query_skill("shenghuo-ling"); if (lvl < 140 || !damage_bonus || me->query_skill_mapped("force") != "shenghuo-shengong" || me->query_skill_mapped("sword") != "shenghuo-ling" || !objectp(weapon = me->query_temp("weapon")) || (string)weapon->query("skill_type") != "sword" || flvl < 140 || me->query_temp("shenghuo-ling/hit") || me->query("neili") < 200) return 0; attack_time = (int)(me->query_skill("shenghuo-ling", 1) / 40); if (attack_time > 8) attack_time = 8; if (lvl / 2 + random(lvl) > victim->query_skill("force", 1) && !me->query_temp("shenghuo-ling/max_hit")) { message_vision(HIR "\n刹那间$N" HIR "身法陡然加快,剑招连绵而出,招式诡异无比" ",令$n" HIR "难以琢磨。\n" NOR, me, victim); me->start_busy(1 + random(attack_time)); me->add("neili", -attack_time * 20); me->add_temp("shenghuo-ling/hit", 1); for (i = 0; i < attack_time; i++) { if (!me->is_fighting(victim)) break; COMBAT_D->do_attack(me, victim, weapon, 0); } me->delete_temp("shenghuo-ling/hit"); return 1; } } string exert_function_file(string func) { return __DIR__ "shenghuo-shengong/" + func; }
24.924731
68
0.580242
[ "object" ]
41a6d5373812949da21d98b052f45fa339476e28
4,396
c
C
libvirt/pileus-libvirt-1.2.12/tools/virsh-edit.c
SIIS-cloud/pileus
de7546845cf03862cdd2b9884fefb2033d8b11ab
[ "Apache-2.0" ]
3
2017-09-22T15:10:01.000Z
2018-03-30T02:11:54.000Z
libvirt/pileus-libvirt-1.2.12/tools/virsh-edit.c
SIIS-cloud/Pileus
de7546845cf03862cdd2b9884fefb2033d8b11ab
[ "Apache-2.0" ]
null
null
null
libvirt/pileus-libvirt-1.2.12/tools/virsh-edit.c
SIIS-cloud/Pileus
de7546845cf03862cdd2b9884fefb2033d8b11ab
[ "Apache-2.0" ]
null
null
null
/* * virsh-edit.c: Implementation of generic virsh *-edit intelligence * * Copyright (C) 2012 Red Hat, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see * <http://www.gnu.org/licenses/>. * * Usage: * Define macros: * EDIT_GET_XML - expression which produces a pointer to XML string, e.g: * #define EDIT_GET_XML virDomainGetXMLDesc(dom, flags) * * EDIT_NOT_CHANGED - this action is taken if the XML wasn't changed. * Note, that you don't want to jump to cleanup but edit_cleanup label * where temporary variables are free()-d and temporary file is deleted: * #define EDIT_NOT_CHANGED vshPrint(ctl, _("Domain %s XML not changed"), \ * virDomainGetName(dom)); \ * ret = true; goto edit_cleanup; * Note that this is a statement. * * EDIT_DEFINE - expression which redefines the object. The edited XML from * user is in 'doc_edited' variable. Don't overwrite the pointer to the * object, as we may iterate once more over and therefore the pointer * would be invalid. Hence assign object to a different variable. * Moreover, this needs to be an expression where: * - 0 is taken as error (our virDefine* APIs often return NULL on error) * - everything else is taken as success * For example: * #define EDIT_DEFINE (dom_edited = virDomainDefineXML(ctl->conn, doc_edited)) * * Michal Privoznik <mprivozn@redhat.com> */ #ifndef EDIT_GET_XML # error Missing EDIT_GET_XML definition #endif #ifndef EDIT_NOT_CHANGED # error Missing EDIT_NOT_CHANGED definition #endif #ifndef EDIT_DEFINE # error Missing EDIT_DEFINE definition #endif do { char *tmp = NULL; char *doc = NULL; char *doc_edited = NULL; char *doc_reread = NULL; const char *msg = NULL; bool edit_success = false; /* Get the XML configuration of the object. */ doc = (EDIT_GET_XML); if (!doc) goto edit_cleanup; /* Create and open the temporary file. */ tmp = vshEditWriteToTempFile(ctl, doc); if (!tmp) goto edit_cleanup; reedit: /* Start the editor. */ if (vshEditFile(ctl, tmp) == -1) goto edit_cleanup; /* Read back the edited file. */ VIR_FREE(doc_edited); doc_edited = vshEditReadBackFile(ctl, tmp); if (!doc_edited) goto edit_cleanup; /* Compare original XML with edited. Has it changed at all? */ if (STREQ(doc, doc_edited)) EDIT_NOT_CHANGED; redefine: msg = NULL; /* Now re-read the object XML. Did someone else change it while * it was being edited? This also catches problems such as us * losing a connection or the object going away. */ VIR_FREE(doc_reread); doc_reread = (EDIT_GET_XML); if (!doc_reread) goto edit_cleanup; if (STRNEQ(doc, doc_reread)) { msg = _("The XML configuration was changed by another user."); VIR_FREE(doc); doc = doc_reread; doc_reread = NULL; } /* Everything checks out, so redefine the object. */ if (!msg && !(EDIT_DEFINE)) msg = _("Failed."); if (msg) { int c = vshAskReedit(ctl, msg); switch (c) { case 'y': goto reedit; break; case 'f': goto redefine; break; case 'n': goto edit_cleanup; break; default: vshError(ctl, "%s", msg); break; } } edit_success = true; edit_cleanup: VIR_FREE(doc); VIR_FREE(doc_edited); VIR_FREE(doc_reread); if (tmp) { unlink(tmp); VIR_FREE(tmp); } if (!edit_success) goto cleanup; } while (0); #undef EDIT_GET_XML #undef EDIT_NOT_CHANGED #undef EDIT_DEFINE
28.36129
84
0.634213
[ "object" ]
84b18a526c79aaf7fae1082aef86cf854a2ad86b
64,838
c
C
gempak/source/programs/gui/nmap2/nmap_dsp.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
42
2015-06-03T15:26:21.000Z
2022-02-28T22:36:03.000Z
gempak/source/programs/gui/nmap2/nmap_dsp.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
60
2015-05-11T21:36:08.000Z
2022-03-29T16:22:42.000Z
gempak/source/programs/gui/nmap2/nmap_dsp.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
27
2016-06-06T21:55:14.000Z
2022-03-18T18:23:28.000Z
#include "geminc.h" #include "gemprm.h" #include "nmapprm.h" #include "nmap_data.h" #include "nmap_mainw.h" #include "Nxm.h" #define LOGO_SMALL_OFFSET ( 0.10F ) #define LOGO_LARGE_OFFSET ( 0.15F ) static char _transferInterrupt = 0; static int _ifnt = 1; static int _ihwsw = 2; static int _ibrdr = 111; static float _tsize = 1.0F; static int _iwid = 1; static int _irot = 1; static int _ijust = 1; /* * Private functions */ void dsp_getPlotOrdr ( int lp, int nsrcs, int plot_ordr[], Boolean *img_data, int *npltsrc); void dsp_getSingleTmOrdr ( int lp, int nsrcs, int frm, int plot_ordr[], int *ndata, Boolean *img_data); static void dsp_getTime ( int lp, dattm_t dttm, int *iret ); void dsp_loadFrame ( int lp, int frm, int pxm, dattm_t ctime, dttms_t ftime, Boolean view_frm, int nsrcs, Boolean fst_frm, Boolean reload ); void dsp_loadLoop ( int lp, Boolean view_lp, int *loaded ); void dsp_loadSingleTime ( int lp, Boolean view_lp, int *loaded ); void dsp_showLoadErr ( void ); void dsp_updatePage ( int current, int total ); /************************************************************************ * nmap_dsp.c * * * * This module takes care of data display for nmap. * * * * CONTENTS: * * dsp_loadAllLoops() load all selected data * * dsp_reloadLoop() reloads all data for a specific loop * * dsp_reloadFrame() reload the data for one specific frame * * dsp_updtDisplay() updates the displayed loop * * dsp_addLogo() adds logo to all frames in one loop * * dsp_drawLogo() draws logo to specific frame * * dsp_setBusy() set the busy animation (upper right corner) * * * * dsp_getPlotOrdr() determine the plot order within a pixmap * * dsp_getSingleTmOrdr()determine the plot order for single time loops* * dsp_updatePage() update the page (x of y) lower left corner) * * dsp_setProj() set up the correct map projection/garea * * * * dsp_loadLoop() load the specified loop * * dsp_loadSingleTime() load the single time loop * * dsp_loadFrame() load the specified frame * * dsp_print() print the specified loop or frame * * dsp_showLoadErr() display a load error message * * dsp_getTime() get the current or set time as reference * ***********************************************************************/ /*=====================================================================*/ void dsp_loadAllLoops ( void ) /************************************************************************ * dsp_loadAllLoops * * * * This function loads each frame into a pixmap. * * * * void dsp_loadAllLoops ( ) * * * * Input parameters: * * Output parameters: * * Return parameters: * * NONE * * * ** * * E. Safford/GSC 07/99 initial coding * * S. Law/GSC 10/99 _WWN -> _MSC * * S. Jacobs/NCEP 10/99 Added setting LUT file for images * * S. Jacobs/NCEP 10/99 Changed ss_gtim to css_gtim * * S. Jacobs/NCEP 10/99 Removed check for mdl_loaded * * E. Safford/GSC 10/99 use dsp_loadLoop * * E. Safford/GSC 11/99 trim param list, clean up * * E. Safford/GSC 04/00 remove params, rename(was dsp_loadData) * * T. Lee/GSC 02/01 added single time loops * * T. Lee/GSC 03/01 changed call seq. of loop_getTmMode * * H. Zeng/EAI 04/01 modified to use dsp_reloadLoop() * ***********************************************************************/ { int cur_lp, lp, ier; /*---------------------------------------------------------------------*/ dsp_setBusy(TRUE); cur_lp = loop_getCurLoop(); /* * Load the current loop first */ dsp_reloadLoop (cur_lp, &ier); /* * Load all remaining loops. */ for (lp=0; lp < MAX_LOOP; lp++) { if (lp == cur_lp) { continue; } dsp_reloadLoop(lp, &ier); } dsp_setBusy(FALSE); } /*=====================================================================*/ void dsp_reloadLoop ( int lp, int *iret ) /************************************************************************ * dsp_reloadLoop * * * * This function reloads the data for one specific loop. * * * * void dsp_reloadLoop ( lp, iret ) * * * * Input parameters: * * lp int loop number for reload * * * * Output parameters: * * *iret int return code * * 0 = normal * * -1 = no available pixmaps for load * * -2 = invalid loop number * * 1 = quit due to user interruption * ** * * Log: * * E. Safford/GSC 10/99 initial coding * * E. Safford/GSC 11/99 fix crash when roaming the base map * * E. Safford/GSC 12/99 add iret param * * S. Law/GSC 01/00 changed final xmloop_switchLoop to TRUE * * E. Safford/GSC 04/00 param chg dsp_loadLoop & clean up * * E. Safford/GSC 07/00 remove dsp_setBusy() * * T. Lee/GSC 2/01 added single time loops * * T. Lee/GSC 03/01 changed call seq. of loop_getTmMode * * H. Zeng/EAI 04/01 added the check of _transferInterrupt * * H. Zeng/EAI 07/01 updated time line for unloaded loops * * E. Safford/SAIC 08/01 made usr interrupt a warning not error * * E. Safford/SAIC 10/01 move nmp calls here from dataw_clearLoop* * E. Safford/SAIC 01/04 add call to loop_restoreLut * ***********************************************************************/ { int loaded, cur_lp, ier; Boolean in_view; Widget drawingW; static int xdpth = -1; /*---------------------------------------------------------------------*/ *iret = 0; if ( xdpth == -1 ) { drawingW = mcanvw_getDrawingW(); xdpth = DefaultDepth( XtDisplay( drawingW ), DefaultScreen( XtDisplay( drawingW ) )); } if (lp < 0 || lp > MAX_LOOP-1) { *iret = -2; return; } /* * If user has interrupted the loading, clear the previously selected * data, update the time line and return with flag -3. */ if (_transferInterrupt) { dataw_clearLoop(lp); nmp_sdefmap(lp, &ier); nmp_sproj(lp, &ier); zoomw_clearZoom(lp); dataw_updateTmln(); *iret = 1; return; } /* * in_view is true if we're loading into the current loop */ cur_lp = loop_getCurLoop(); in_view = (Boolean) (cur_lp == lp); /* * Make sure the lut is set when using 16 or 24-bit screen mode */ if ( !in_view && xdpth != 8 ) { loop_restoreLut( lp ); } if (loop_getTmMode(lp)) { dsp_loadSingleTime(lp, in_view, &loaded); } else { dsp_loadLoop(lp, in_view, &loaded); } if (!in_view) { /* * reset the xw driver to the cur_lp */ xmloop_switchLoop (cur_lp, FALSE); } /* * Store some loop information */ loop_setNumFrames (lp, loaded); } /*=====================================================================*/ void dsp_reloadFrame ( int lp, int frm ) /************************************************************************ * dsp_reloadFrame * * * * This function reloads the data for one specific frame. * * * * void dsp_reloadFrame ( lp, frm ) * * * * Input parameters: * * lp int loop number * * frm int frame number * * * * Output parameters: * * NONE * ** * * Log: * * E. Safford/GSC 10/99 initial coding * * E. Safford/GSC 11/99 add roamw_setup * * S. Jacobs/NCEP 11/99 Added print functionality * * E. Safford/GSC 05/00 add call to mbtnw_loopSelBtnCb * * E. Safford/GSC 05/00 add call to xmfrmtg_setFrmTag * * E. Safford/GSC 05/00 param change to dsp_loadFrame * * S. Law/GSC 06/00 removed loop parameter from xpgsvfrm2 * * E. Safford/GSC 06/00 rm pageSet call and clean up * * E. Safford/GSC 07/00 remove dsp_setBusy() * * E. Safford/GSC 12/00 replace css_gtime with dsp_getTime * * H. Zeng/EAI 04/01 moved blank map before the 1st pixmap * * E. Safford/GSC 06/01 use lp, not cur_lp in dsp_getTime() * * J. Wu/SAIC 11/01 add param in cvg_load() calling * * J. Wu/SAIC 12/01 add layer in cvg_load() call * * J. Wu/SAIC 12/01 rebuild range record after xpgrfrsh() * * J. Wu/SAIC 12/01 replace cvg_load with cvg_redraw() * * T. Piper/SAIC 4/03 added the resetting of projection and * * roam factor from auto_performUpdt * ***********************************************************************/ { int pxm, cur_lp, nfrms, nsrcs, ier; Boolean view_lp, frst_frm, prtflg; dattm_t ctime; dattm_t ftime; /*---------------------------------------------------------------------*/ prtflg = (Boolean) NxmPrt_isPrtFlgSet (); cur_lp = loop_getCurLoop(); dsp_getTime ( lp, ctime, &ier ); pxm = loop_getFramePxm (lp, frm); loop_getFrameTm(lp, frm, ftime); nfrms = loop_getNumFrames (lp); nsrcs = dataw_getNumSrcs(lp); /* * frst_frm is true if it is the first (most recent) frame in a loop */ frst_frm = (Boolean) (nfrms-1 == frm); /* * view_lp is true if we're loading into the current loop */ view_lp = (Boolean) (cur_lp == lp); if (!view_lp) { xmloop_switchLoop (lp, FALSE); if ( ! prtflg ) { roamw_setup (lp, FALSE); } } dsp_loadFrame(lp, frm, pxm, ctime, ftime, view_lp, nsrcs, frst_frm, TRUE); if (! prtflg) { /* * Set the frame tag to TRUE. */ xmfrmtg_setFrmTag (lp, frm, FALSE); if (pgpalw_isUp() && view_lp) { xpgsvfrm2 (frm); xpgrfrsh(); crg_rebuild(); } } else if (pgpalw_isUp() && view_lp) { cvg_redraw ( NULL, &ier ); } /* * return settings to the current loop */ if (!view_lp) { /* * reset the xw driver to the cur_lp and * reset the projection and roam factor */ xmloop_switchLoop (cur_lp, FALSE); nmp_rstrproj (cur_lp, &ier); roamw_setup (cur_lp, TRUE); } } /*=====================================================================*/ void dsp_updtDisplay ( void ) /************************************************************************ * dsp_updtDisplay * * * * This function updates the display of the current loop. It is * * normally called at the conclusion of a data load operation (ie after * * all loops have been loaded). * * * * void dsp_updtDisplay ( ) * * * * Input parameters: * * Output parameters: * * NONE * ** * * E. Safford/GSC 04/00 initial coding * ***********************************************************************/ { xmloop_switchLoop (loop_getCurLoop(), TRUE); } /*=====================================================================*/ void dsp_setBusy ( Boolean state ) /************************************************************************ * dsp_setBusy * * * * This function disables or enables the zoom, roam, and loop controls * * and displays or ends the busy animation. * * * * void dsp_setBusy (state) * * * * Input parameters: * * state Boolean true = disable zoom/roam/loop * * false = enable zoom/roam/loop * * * * Output parameters: * * Return parameters: * * NONE * * * ** * * E. Safford/GSC 08/99 initial coding * * E. Safford/GSC 11/99 add auto-update stop/start * * S. Law/GSC 01/00 loopw_resetHide -> loopw_setHide * * S. Jacobs/NCEP 5/00 Reodered function calls * * E. Safford/GSC 07/00 add prev_state checks * * E. Safford/GSC 10/00 loopw_setHide -> loopw_resetHide * * H. Zeng/EAI 04/01 reset _transferInterrupt to 0 * * T. Piper/SAIC 07/03 Removed NxmBusy_setBusyPid * ***********************************************************************/ { Widget draw_wid; static Boolean prev_state = FALSE; /*---------------------------------------------------------------------*/ if (prev_state == state) { return; } prev_state = state; if (state) { draw_wid = mcanvw_getDrawingW(); _transferInterrupt = 0; NxmBusy_invoke(draw_wid, &_transferInterrupt); auto_stopAutoUpdt(); mbtnw_zoomSensitive(False); loopw_sensitive(False); roamw_sensitive(False); } else { mbtnw_zoomSensitive(TRUE); loopw_sensitive(TRUE); loopw_resetHide (); roamw_sensitive(TRUE); auto_startAutoUpdt(); if (!_transferInterrupt) { NxmBusy_animateFinish(); } _transferInterrupt = 0; } } /*=====================================================================*/ void dsp_getPlotOrdr ( int lp, int nsrcs, int plot_ordr[], Boolean *img_data, int *npltsrc ) /************************************************************************ * dsp_getPlotOrdr * * * * This function determines the plot order for the data in the given * * panel. * * * * void dsp_getPlotOrdr (lp, nsrcs, plot_ordr, img_data, npltsrc ) * * * * Input parameters: * * lp int loop number * * nsrcs int number of sources in panel * * * * Output parameters: * * plot_ordr[] int array of indicies to data sources * * *img_data Boolean True if image data in panel * * *npltsrc int number of source to plot * * * ** * * E. Safford/GSC 09/99 initial coding * * S. Law/GSC 10/99 _WWN -> _MSC * * E. Safford/GSC 10/99 remove mdl_data pararm * * S. Law/GSC 11/99 changed to use new defines * * E. Safford/GSC 02/00 add cnt < nsrcs condition to kk for loop* * M. Li/GSC 06/01 add a check for off-data source * * S. Jacobs/NCEP 11/02 Changed order of VGF and MSC data * * M. Li/SAIC 03/08 added CAT_ENS * ***********************************************************************/ { dsrc_t *dsrc; int ii, cnt; Cardinal kk; int catg_ordr[] = {CAT_IMG, CAT_GRD, CAT_ENS, CAT_SFC, CAT_SND, CAT_SFF, CAT_SNF, CAT_VGF, CAT_MSC, CAT_NIL}; /*---------------------------------------------------------------------*/ *img_data = FALSE; *npltsrc = 0; for (ii=0; ii<nsrcs; ii++) { plot_ordr[ii] = -1; } if (nsrcs == 1) { plot_ordr[0] = 0; dsrc = dataw_getDataSrc(lp, 0); if (dsrc->catg == CAT_IMG && dsrc->src_on ) { *img_data = TRUE; } *npltsrc = nsrcs; } else { cnt = 0; for (kk=0; kk < XtNumber(catg_ordr) && cnt < nsrcs; kk++) { for (ii=0; ii < nsrcs; ii++) { dsrc = dataw_getDataSrc(lp, ii); if (dsrc->src_on) { if (dsrc->catg == CAT_IMG) { *img_data = TRUE; } if (dsrc->catg == catg_ordr[kk]) { plot_ordr[cnt] = ii; cnt++; } } } } *npltsrc = cnt; } } /*=====================================================================*/ void dsp_updatePage ( int current, int total ) /************************************************************************ * dsp_updatePage * * * * This function calls mbotw_pageSet to set the current frame (page) * * number and total number of frame (pages) information and * * pghdlb_displayAllSel to update any selected vgf elements * * * * void dsp_updatePage (current, total) * * * * Input parameters: * * current int current page (frame) number * * total int total number of frames * * * * Output parameters: * * Return parameters: * * NONE * * * ** * * Log: * * E. Safford/GSC 06/98 initial coding * * E. Safford/GSC 09/98 change pgpalw_isPgen to pgpalw_isUp * * E. Safford/GSC 03/99 use pghdlb_showAllSel * ***********************************************************************/ { mbotw_pageSet (current, total); if (pgpalw_isUp()) { pghdlb_showAllSel(); } } /*=====================================================================*/ void dsp_loadLoop ( int lp, Boolean view_lp, int *loaded ) /************************************************************************ * dsp_loadLoop * * * * This function loads each loop into a series of pixmaps. * * * * void dsp_loadLoop( lp, view_lp, loaded ) * * * * Input parameters: * * lp int loop number * * view_lp Boolean True if loop is to be in view after load* * * * Output parameters: * * *loaded int number of pixmaps loaded * * * * Return parameters: * * NONE * * * ** * * E. Safford/GSC 10/99 initial coding * * S. Jacobs/NCEP 10/99 ss_gtim -> css_gtim * * S. Jacobs/NCEP 10/99 removed check for mdl_loaded * * E. Safford/GSC 11/99 rename dsrc_srcs to nsrcs * * E. Safford/GSC 11/99 fix crash when roaming the base map * * E. Safford/GSC 11/99 add switchloop call to avoid extra pxms * * E. Safford/GSC 11/99 save pxm info on blank frame * * S. Jacobs/NCEP 11/99 Added print functionality * * S. Law/GSC 01/00 removed time check when showing last frm* * E. Safford/GSC 01/00 use xpgsvfrm2 & display vgf immediately * * S. Law/GSC 01/00 changed to use view_lp for roamw_setup * * S. Law/GSC 01/00 changed so that model loads first 2 last* * E. Safford/GSC 02/00 add call to mbotw_loadingLoopSet * * E. Safford/GSC 04/00 simplify params, clean up * * E. Safford/GSC 04/00 move _switchLoop ahead of roam_setup * * E. Safford/GSC 04/00 fix bug with *loaded assignment * * E. Safford/GSC 05/00 add call to xfrmtg_resetLp * * S. Jacobs/NCEP 5/00 Added call to function to draw NOAA logo* * S. Law/GSC 05/00 added call to cvg_load/geplot * * S. Law/GSC 05/00 reworked max frames checking * * E. Safford/GSC 05/00 add blank map idx to pxmarry * * E. Safford/GSC 05/00 fix miscount on times * * S. Law/GSC 06/00 removed loop parameter from xpgsvfrm2 * * E. Safford/GSC 06/00 removed cvg_load/geplot on map frame * * E. Safford/GSC 07/00 initialize array times * * S. Jacobs/NCEP 7/00 Check sub-cat number instead of category* * S. Jacobs/NCEP 9/00 Moved get panel out of times>0 check * * E. Safford/GSC 12/00 replace css_gtime with dsp_getTime * * H. Zeng/EAI 04/01 moved blank map before the 1st pixmap * * H. Zeng/EAI 04/01 added stop function * * J. Wu/GSC 4/01 change logo drawing to be loop-specific * * H. Zeng/EAI 04/01 fixed a bug for stop function * * E. Safford/GSC 05/01 fixed a bug in pgen mstr pxmap creation * * A. Hardy/GSC 7/01 added queries and saves for text attr. * * E. Safford/GSC 08/01 rmv pxmarry[] param from xmloop_loopSet * * H. Zeng/EAI 11/01 modified total_frm value * * J. Wu/SAIC 11/01 add param in cvg_load() calling * * J. Wu/SAIC 12/01 add layer in cvg_load() call * * J. Wu/SAIC 12/01 rebuild range record after xpgrfrsh() * * J. Wu/SAIC 12/01 replace cvg_load() with cvg_redraw() * * J. Wu/SAIC 05/03 fix MAX_FRAME bug - out of boundary * * T. Lee/SAIC 09/04 added bin hours to call sequences * * m.gamazaychikov/SAIC 12/04 add dionoff flag to ctb_dtget CS * * m.gamazaychikov/SAIC 04/06 add dtmch flag to ctb_dtget CS * * M. Li/SAIC 03/08 call dslw_getFrstMod in case of CAT_ENS * * F. J. Yen/NCEP 4/08 add bin mins and mstrct to ctb_dtget CSC* ***********************************************************************/ { int ii, jj, kk, frm, count, ier, times; int curr=0, incr, nsrcs, total_frm, maxfrm, cur_lp, start; int isbcat, d3, d4, d5, d6, d7, d7m, d8, d8m, mstrct, dionoff, dtmch; int from, to, offset, new_load; int jtxfn, jtxhw, jtxwid, jbrdr, jrrotn, jjust; float ssztxt; char asrc[256], *alias, d1[256], d2[256], tmpstr[256]; char plot_area[5]; Boolean exceeded_pxms, prtflg, view_frm; dttms_t tarry[MAX_FRAME+1]; dattm_t c_tm, ftime; Widget wid; dsrc_t *dom; /*---------------------------------------------------------------------*/ prtflg = (Boolean) NxmPrt_isPrtFlgSet (); cur_lp = loop_getCurLoop(); /* * initialize times */ for (ii=0; ii < MAX_FRAME+1; ii++) { tarry[ii][0] = '\0'; } /* * Tell the xw driver which loop is getting loaded. */ xmloop_switchLoop (lp, FALSE); /* * Set the roam environment. */ if ( ! prtflg ) { roamw_setup (lp, view_lp); } *loaded = 0; exceeded_pxms = FALSE; dataw_getDataW(&wid); /* * Get the times for this loop, based on the dominant source */ times = 0; maxfrm = MAX_FRAME; exceeded_pxms = FALSE; total_frm = loop_getTotalFrames(lp) + 1 - MAX_LOOP; dom = (dsrc_t *)dataw_getDomSrc(lp); if (dom != NULL) { /* * Get the data alias name to find the sub-cat number. * This is used to determine the direction of the time line. */ if ( dom->catg == CAT_VGF ) { strcpy ( tmpstr, "VGF" ); } else if ( dom->catg == CAT_ENS ) { dslw_getFrstMod ( dom->path, tmpstr ); } else { strcpy (asrc, dom->path); alias = strtok(asrc, "/"); alias = strtok(NULL, "/"); strcpy ( tmpstr, alias ); } ctb_dtget ( tmpstr, d1, d2, &d3, &isbcat, &d4, &d5, &d6, &dionoff, &d7, &d7m, &d8, &d8m, &mstrct, &dtmch, &ier ); /* * Forecast data loads first to last, all others last to first */ if ( isbcat == SCAT_FCT || isbcat == SCAT_SFF || isbcat == SCAT_SNF ) { curr = 0; incr = 1; } else { curr = maxfrm-1; incr = -1; } for (count = 0, ii = curr; count < MAX_FRAME; count++, ii += incr) { if (total_frm == maxfrm) { dom->frm[ii].selected = FALSE; exceeded_pxms = TRUE; } else if (dom->frm[ii].selected) { strcpy(tarry[times+1], dom->frm[ii].ftime); times++; total_frm++; } } } dataw_getPanelLoc (lp, plot_area); if (times > 0) { /* * Grid data loads first to last, all others last to first */ if ( isbcat == SCAT_FCT || isbcat == SCAT_SFF || isbcat == SCAT_SNF ) { curr = 1; incr = 1; } else { curr = times; incr = -1; } mbotw_loadingLoopSet(TRUE, lp); dsp_getTime ( lp, c_tm, &ier ); /* * FOR EACH FRAME */ view_frm = TRUE; nsrcs = dataw_getNumSrcs(lp); for (count = 1, frm = curr; count<=times && !_transferInterrupt; count++, frm+=incr) { mbotw_pageSet(frm, times); dsp_loadFrame(lp, frm, frm, c_tm, tarry[count], view_lp, nsrcs, view_frm, FALSE); if ( ! prtflg && pgpalw_isUp() && lp == cur_lp) { xpgsvfrm2 (frm); } /* * Display the most recent frame of the current loop * (view_lp) while everything else loads */ if (view_lp && (view_frm || prtflg)) { if (pgpalw_isUp()) { cvg_redraw ( NULL, &ier ); } geplot(&ier); } view_frm = FALSE; /* * check the stop button before going to next frame * this should be the LAST ACTION before advancing * to next frame */ NxmBusy_checkStopBtn(); } } else { /* * No sources -- just load the default map and tell the xw driver * we have just the one pixmap. */ xmloop_loopSet (wid, lp, view_lp, 0, 0, dsp_updatePage, &ier); } /* * Finish the loop up */ if (!prtflg) { /* * Check if the total # of frames changed because the user clicked on * the STOP button. */ new_load = count - 1; if ( _transferInterrupt && (new_load < times) ) { /* * For non-forecast data, shift loaded pixmaps from high end * to low end. */ if ( isbcat != SCAT_FCT && isbcat != SCAT_SFF && isbcat != SCAT_SNF ) { offset = times - new_load; for (jj=offset+1; jj<=times; jj++) { from = jj; to = jj-offset; xscpxm( to, &ier ); gclear(&ier); xcpypxm2 (lp, from, to, &ier); /* * shift the frame times */ loop_getFrameTm (lp, from, ftime); loop_setFrameTm (lp, to, ftime); /* * set pixmap index for low end frames */ loop_setFramePxm(lp, to, to); } } /* the end of if( isbcat !=...) */ /* * Update the time line to show correct frame info. */ if ( isbcat == SCAT_FCT || isbcat == SCAT_SFF || isbcat == SCAT_SNF ) { start = 0; incr = 1; } else { start = maxfrm-1; incr = -1; } ii = start; for(kk = new_load+1; kk <= times; kk++) { while ( strcmp(tarry[kk], dom->frm[ii].ftime) != 0 ) { ii += incr; } dom->frm[ii].selected = FALSE; } /* the end of for(kk =...) */ dataw_updateTmln(); /* * Set new total # of pixmap and current pixmap index. */ if( curr == times ) { times = new_load; curr = times; } else { times = new_load; } } /* the end of if (_transferInterrupt...) */ /* * add blank map as the first frame of each loop */ xscpxm (0, &ier); loop_setFramePxm (lp, 0, 0); gclear(&ier); /* * Set up animation loop. */ xmloop_loopSet (wid, lp, view_lp, curr, times, dsp_updatePage, &ier); gqtext (&jtxfn, &jtxhw, &ssztxt, &jtxwid, &jbrdr, &jrrotn, &jjust, &ier ); gstext (&_ifnt, &_ihwsw, &_tsize, &_iwid, &_ibrdr, &_irot, &_ijust, &ier ); nmp_plot(lp, 0, plot_area, &ier); gstext (&jtxfn, &jtxhw, &ssztxt, &jtxwid, &jbrdr, &jrrotn, &jjust, &ier ); /* * if we've only loaded a base map (times == 0) and the loop * is currently in view, then plot the map. */ if (times == 0 && view_lp) { geplot(&ier); } dsp_drawLogo ( lp ); if (pgpalw_isUp() && view_lp) { xpgsvfrm2 (0); xpgrfrsh(); crg_rebuild(); } } /* the end of if(!prtflg...) */ /* * Write out an error message if all requested frames are not * displayed */ if (exceeded_pxms) { dsp_showLoadErr(); } /* * Tell the xw driver to reset the bad frame tags for this loop. */ xmfrmtg_resetLp(lp, &ier); *loaded = times+1; mbotw_loadingLoopSet(FALSE, lp); } /*=====================================================================*/ void dsp_loadFrame ( int lp, int frm, int pxm, dattm_t ctime, dttms_t ftime, Boolean view_frm, int nsrcs, Boolean fst_frm, Boolean reload ) /************************************************************************ * dsp_loadFrame * * * * This function loads each frame into a pixmap. * * * * void dsp_loadFrame( lp, frm, pxm, ctime, ftime, view_frm, nsrcs, * * fst_frm, reload ) * * * * Input parameters: * * lp int loop number * * frm int frame number * * pxm int pixmap number * * ctime dattm_t current time * * ftime dttms_t frame time * * view_frm Boolean True if this frame(lp)is in view now * * nsrcs int number of data sources in loop * * fst_frm Boolean True if this is the first frame in a lp * * reload Boolean True if this is a frame reload * * * * Output parameters: * * Return parameters: * * NONE * * * ** * * E. Safford/GSC 10/99 initial coding * * S. Jacobs/NCEP 10/99 ss_gtim -> css_gtim * * S. Jacobs/NCEP 10/99 removed check for mdl_loaded * * E. Safford/GSC 11/99 remove references to _lpInfo * * S. Jacobs/NCEP 11/99 Added print functionality * * S. Law/GSC 11/99 changed to use new defines * * E. Safford/GSC 01/00 use subcat code for plotting UAIR data * * E. Safford/GSC 03/00 mod param list for dataw_setProj * * E. Safford/GSC 03/00 add call to im_lutf & fix init load bug * * E. Safford/GSC 04/00 remove call to dsp_getMapAttr * * E. Safford/GSC 05/00 param change to dsp_setProj * * S. Jacobs/NCEP 5/00 Added call to function to draw NOAA logo* * E. Safford/GSC 06/00 remove panel references * * E. Safford/GSC 06/00 remove lut setting * * S. Law/GSC 07/00 replaced lut setting if printing * * S. Jacobs/NCEP 2/01 Fixed time match for observed data * * T. Lee/GSC 02/00 added call to dsp_getSingleTmOrdr * * T. Lee/GSC 03/01 changed call seq. of loop_getTmMode * * J. Wu/GSC 4/01 change logo drawing to be loop-specific * * E. Safford/GSC 05/01 add NxmErr_update() call at end * * M. Li/GSC 06/01 add parameter to dsp_getPlotOrdr * * A. Hardy/GSC 7/01 added queries and saves for text attr. * * S. Jacobs/NCEP 2/02 Added error message after ngd_plot * * T. Piper/SAIC 4/02 Added st_null to fix UMR * * S. Jacobs/NCEP 10/02 Added check for print flag to set proj * * S. Jacobs/NCEP 11/02 Changed plot order to plot map before * * misc data types, but after VG files * * T. Lee/SAIC 8/03 added range/intv to n**_plot * * E. Safford/SAIC 1/04 always apply lut for 16 & 24-bit mode * * E. Safford/SAIC 1/04 add mbotw_restoreFade call * * E. Safford/SAIC 1/04 mv mbotw_restoreFade call (my bad) * * T. Lee/SAIC 7/04 get TIME_MATCH from pref. table * * T. Lee/SAIC 09/04 added bin hours to call sequences * * m.gamazaychikov/SAIC 12/04 add dionoff flag to ctb_dtget CS * * T. Piper/SAIC 01/05 Added check on dsrc->ionoff == 1 * * m.gamazaychikov/SAIC 04/06 change way time matching scheme is set * * M. Li/SAIC 03/08 Added case CAT_ENS * * F. J. Yen/NCEP 04/08 Get bin mins & most recent flag to pass * * M. James/Unidata 04/15 Added check to not plot map for VAD * ***********************************************************************/ { int kk, ier, which, ignore; int lens, title, idx; int plot_ordr[MAX_FRMSRC], frmsrc, nplot; int isbcat, icat, nframe, irang, jrang, intrvl; int hrsbfr, hraftr, dionoff, ibf, iaf; int mnsbfr, mnaftr, dmstrct, mbf, maf; int nmin, itarr[5], ndata, dtmch; int jtxfn, jtxhw, jtxwid, jbrdr, jrrotn, jjust; float ssztxt; char img_garea[256], plot_area[5]; char imtype[81], iminfo[81], imlutf[81]; char asrc[256], *alias, path[256], tmplt[256], tmpstr[256]; nmpstr_t mapInp, projDrp, gareaDrp[2]; dattm_t endtim; dsrc_t *dsrc, *dom; Boolean img_loaded, sat_src, rad_src, prtflg, mapdone; static Boolean sat_lutset = FALSE; static Boolean rad_lutset = FALSE; static Boolean nvw = FALSE; /*---------------------------------------------------------------------*/ if (nsrcs <= 0) { return; } /* * set the current pixmap and order it cleared */ xscpxm( pxm, &ier ); gclear(&ier); /* * store some frame information */ loop_setFrameTm (lp, frm, ftime); loop_setFramePxm (lp, frm, pxm); title = -2; dataw_getPanelLoc (lp, plot_area); dom = (dsrc_t *)dataw_getDomSrc(lp); /* * Determine order of plot */ if (loop_getTmMode(lp)) { dsp_getSingleTmOrdr (lp, nsrcs, frm, plot_ordr, &ndata, &img_loaded); } else { dsp_getPlotOrdr(lp, nsrcs, plot_ordr, &img_loaded, &nplot); ndata = nplot; } /* * If printing, or displaying the "first frame", then set the * projection. * * "First frame" has two meanings: * (1) When loading a loop, the first frame is the frame that * is in view while loading the remaining frames. * (2) When reloading a frame, "first frame" is True for the * highest frame number. A frame reload is executed when * the user selects the "Reload Frame" button or the * "Print" button on the interface. */ prtflg = (Boolean) NxmPrt_isPrtFlgSet (); if ( fst_frm || prtflg ) { if (img_loaded) { dsrc = dataw_getDataSrc (lp, plot_ordr[0]); } else { dsrc = (dsrc_t *)NULL; } nmp_sproj(lp, &ier); } /* * FOR EACH SOURCE */ mapdone = False; for (kk=0; kk < ndata; kk++) { frmsrc = plot_ordr[kk]; dsrc = dataw_getDataSrc(lp, frmsrc); /* * Check for NVW product and set flag to NOT draw map * and latlon for VAD display (kludgy but works) */ if ( strstr(dsrc->path,"NVW") != NULL ) { nvw = TRUE; } else { nvw = FALSE; } /* * Get the table entry info for this data source. */ if ( dsrc->catg == CAT_VGF ) { strcpy ( tmpstr, "VGF" ); } else if ( dsrc->catg == CAT_ENS ) { dslw_getFrstMod ( dsrc->path, tmpstr ); } else { strcpy (asrc, dsrc->path); alias = strtok(asrc, "/"); alias = strtok(NULL, "/"); strcpy ( tmpstr, alias ); } ctb_dtget ( tmpstr, path, tmplt, &icat, &isbcat, &nframe, &irang, &intrvl, &dionoff, &hrsbfr, &mnsbfr, &hraftr, &mnaftr, &dmstrct, &dtmch, &ier ); /* * Only reset the end time for observed data. */ if ( ( isbcat == SCAT_SFF ) || ( isbcat == SCAT_SNF ) || ( isbcat == SCAT_FCT ) ) { strcpy ( endtim, ctime ); } else { /* * Set the end time, for the time match, to the frame * time plus half the range. */ jrang = irang / 2; ti_ctoi ( ftime, itarr, &ier, strlen(ftime) ); ti_addm ( itarr, &jrang, itarr, &ier ); ti_itoc ( itarr, endtim, &ier, sizeof(endtim) ); st_null ( endtim, endtim, &lens, &ier, sizeof(endtim), sizeof(endtim) ); /* * If the end time is after the current time, * use the current time. */ ti_diff ( ctime, endtim, &nmin, &ier, strlen(ctime), strlen(endtim) ); if ( nmin <= 0 ) { strcpy ( endtim, ctime ); } } switch (dsrc->catg) { case CAT_IMG: nmp_gmapattr(lp, mapInp, projDrp, gareaDrp, &ier); which = ( strlen(gareaDrp[1]) > (size_t)0 ) ? 1 : 0; strcpy(img_garea, gareaDrp[which]); if ((Boolean) NxmPrt_isPrtFlgSet ()) { sat_src = dataw_isSatSelect(lp, &idx); rad_src = dataw_isRadSelect(lp, &idx); if ( view_frm || (sat_src && !sat_lutset) || (rad_src && !rad_lutset)) { nim_qatt (dsrc->attridx, imtype, iminfo, imlutf, &ier); im_lutf (imlutf, &ier, strlen(imlutf)); if (sat_src) { sat_lutset = TRUE; } else { rad_lutset = TRUE; } } } /* * Initialize text attributes before loading image. */ gqtext (&jtxfn, &jtxhw, &ssztxt, &jtxwid, &jbrdr, &jrrotn, &jjust, &ier ); gstext (&_ifnt, &_ihwsw, &_tsize, &_iwid, &_ibrdr, &_irot, &_ijust, &ier ); nim_plot ((Pixmap)pxm, dsrc->attridx, img_garea, plot_area, ftime, endtim, dsrc->range, -1, dom->domtmmtch, 0, title, &ier ); gstext (&jtxfn, &jtxhw, &ssztxt, &jtxwid, &jbrdr, &jrrotn, &jjust, &ier ); break; case CAT_SFC: case CAT_SFF: case CAT_SND: case CAT_SNF: if ( dsrc->ionoff == 1 ) { ibf = dsrc->bfhr; mbf = dsrc->bfmn; iaf = dsrc->afhr; maf = dsrc->afmn; dmstrct = dsrc->mstrctf; } else { ibf = 0; mbf = 0; iaf = 0; maf = 0; dmstrct = 0; } if (isbcat == SCAT_SND || isbcat == SCAT_SNF) { nsn_plot ( (Pixmap)pxm, dsrc->attridx, plot_area, ftime, endtim, dsrc->range, -1, dom->domtmmtch, 0, title, ibf, mbf, iaf, maf, dmstrct, &ier); } else { nsf_plot ( (Pixmap)pxm, dsrc->attridx, plot_area, ftime, endtim, dsrc->range, -1, dom->domtmmtch, 0, title, ibf, mbf, iaf, maf, dmstrct, &ier); } break; case CAT_GRD: case CAT_ENS: ngd_plot ((Pixmap)pxm, dsrc->attridx, plot_area, ftime, endtim, dsrc->range, -1, dom->domtmmtch, 0, title, &ier); if ( ier != 0 ) er_wmsg ( "NGD", &ier, NULL, &ignore, strlen("NGD"), 0 ); break; case CAT_VGF: nms_plot ((Pixmap)pxm, dsrc->attridx, plot_area, ftime, endtim, irang, dom->domtmmtch, 0, title, &ier); break; case CAT_MSC: if ( !mapdone ) { gqtext (&jtxfn, &jtxhw, &ssztxt, &jtxwid, &jbrdr, &jrrotn, &jjust, &ier ); gstext (&_ifnt, &_ihwsw, &_tsize, &_iwid, &_ibrdr, &_irot, &_ijust, &ier ); nmp_plot(lp, (Pixmap)pxm, plot_area, &ier); gstext (&jtxfn, &jtxhw, &ssztxt, &jtxwid, &jbrdr, &jrrotn, &jjust, &ier ); mapdone = True; } nms_plot ((Pixmap)pxm, dsrc->attridx, plot_area, ftime, endtim, irang, dom->domtmmtch, 0, title, &ier); break; default: break; } /* switch */ title--; } /* kk or SOURCE */ /* * Draw map */ if ( !mapdone ) { gqtext (&jtxfn, &jtxhw, &ssztxt, &jtxwid, &jbrdr, &jrrotn, &jjust, &ier ); gstext (&_ifnt, &_ihwsw, &_tsize, &_iwid, &_ibrdr, &_irot, &_ijust, &ier ); if (!nvw) { nmp_plot(lp, (Pixmap)pxm, plot_area, &ier); } gstext (&jtxfn, &jtxhw, &ssztxt, &jtxwid, &jbrdr, &jrrotn, &jjust, &ier ); } /* * Draw the logo, if it is active. */ dsp_drawLogo ( lp ); NxmErr_update(); } /*=====================================================================*/ void dsp_print ( void ) /************************************************************************ * dsp_print * * * * This function prints an entire loop or an individual frame. * * * * void dsp_print ( ) * * * * Input parameters: * * Output parameters: * * Return parameters: * * NONE * * * ** * * S. Jacobs/NCEP 11/99 Created * * E. Safford/GSC 12/99 Fixed palette reset bug * * S. Jacobs/NCEP 5/00 Added call to function to draw NOAA logo* * E. Safford/GSC 07/00 add setBusy calls * * S. Jacobs/NCEP 2/01 Added load prod gen file if no data * * J. Wu/GSC 4/01 change logo drawing to be loop-specific * * A. Hardy/GSC 7/01 added queries and saves for text attr. * * J. Wu/SAIC 11/01 add param in cvg_load() calling * * J. Wu/SAIC 12/01 add layer in cvg_load() call * * J. Wu/SAIC 12/01 rebuild range record after xpgrfrsh() * * J. Wu/SAIC 12/01 replace cvg_load() with cvg_redraw() * ***********************************************************************/ { int loop, ifrm, ier; int jtxfn, jtxhw, jtxwid, jbrdr, jrrotn, jjust; float ssztxt; char plot_area[5]; Boolean lpflg; /*---------------------------------------------------------------------*/ dsp_setBusy (TRUE); loop = loop_getCurLoop (); ifrm = loop_getCurFrame (); lpflg = dataw_isLoopActv ( loop ); if ( lpflg ) { if ( NxmPrt_isPgFlgSet () ) { dsp_reloadLoop ( loop, &ier ); } else { dsp_reloadFrame ( loop, ifrm ); } } else { dataw_getPanelLoc ( loop, plot_area ); gqtext (&jtxfn, &jtxhw, &ssztxt, &jtxwid, &jbrdr, &jrrotn, &jjust, &ier ); gstext (&_ifnt, &_ihwsw, &_tsize, &_iwid, &_ibrdr, &_irot, &_ijust, &ier ); nmp_plot ( loop, 0, plot_area, &ier ); gstext (&jtxfn, &jtxhw, &ssztxt, &jtxwid, &jbrdr, &jrrotn, &jjust, &ier ); dsp_drawLogo ( loop ); if ( pgpalw_isUp() ) { cvg_redraw ( NULL, &ier ); } } if ( pgpalw_isUp() ) { xpgrfrsh(); pgpalw_setupOper(); } dsp_setBusy (FALSE); } /*=====================================================================*/ void dsp_showLoadErr ( void ) /************************************************************************ * dsp_showLoadErr * * * * This function displays an error message to the user. At present * * only the only condition that is flagged as an error is attempting to * * load more than MAP_PIX pixmaps. * * * * void dsp_showLoadErr ( ) * * * * Input parameters: * * Output parameters: * * Return parameters: * * NONE * ** * * E. Safford/GSC 04/00 inital coding * ***********************************************************************/ { int error, ignore; /*---------------------------------------------------------------------*/ error = G_NMAXFR; er_wmsg("gemplt", &error, NULL, &ignore, strlen("gemplt"), 0 ); NxmErr_update(); } /*=====================================================================*/ void dsp_drawLogo ( int lp ) /************************************************************************ * dsp_drawLogo * * * * This function draws the logo to the current pixmap. * * * * void dsp_drawLogo ( lp ) * * * * Input parameters: * * lp int loop number * * * * Output parameters: * * Return parameters: * * NONE * * * ** * * S. Jacobs/NCEP 5/00 Created * * A. Hardy/GSC 11/00 renamed coordinate system declaration * * J. Wu/GSC 3/01 Added logo emblem ID * * J. Wu/GSC 4/01 Enabled drawing multiple logos * * J. Wu/GSC 5/01 Added drawing NWS logo * ***********************************************************************/ { int logo_mode, icm, bw, curclr, ilog, ier, ii; float size, xn, yn, xloc, x_ll_offset, x_ur_offset; char name[15]; /*---------------------------------------------------------------------*/ x_ll_offset = 0.0F; x_ur_offset = 0.0F; if ( logo_lpLogoActv( lp ) ) { for ( ii = 0; ii < MAX_LOGO; ii++ ) { if ( logo_isLogoActv ( lp, ii ) ) { logo_mode = logo_getCurLogo ( lp, ii ); logo_getInfo ( logo_mode, name, &size, &xn, &yn, &icm ); if ( icm == 1 ) { gqcolr ( &curclr, &ier ); bw = 1; gscolr ( &bw, &ier ); } ilog = ii + 1; /* Logo ID defined from 1 as NOAA_LOGO */ /* * Count the offset and draw logo. */ if ( xn < 0.5F ) xloc = xn + x_ll_offset; /* Lower left corner */ else xloc = xn + x_ur_offset; /* upper right corner */ glogo ( sys_N, &xloc, &yn, &size, &icm, &ilog, &ier, strlen(sys_N) ); if ( icm == 1 ) gscolr ( &curclr, &ier ); /* * Update the offset for drawing next logo. */ switch( logo_mode ) { case 1: case 3: x_ll_offset += LOGO_SMALL_OFFSET; break; case 2: x_ll_offset += LOGO_LARGE_OFFSET; break; case 4: case 6: x_ur_offset -= LOGO_SMALL_OFFSET; break; case 5: x_ur_offset -= LOGO_LARGE_OFFSET; break; } /* end of switch */ } /* end of drawing one logo */ } /* end of drawing all logos */ } } /*=====================================================================*/ static void dsp_getTime ( int lp, dattm_t dttm, int *iret ) /************************************************************************ * dsp_getTime * * * * This function returns the reference time for the loop. This will * * either be the current time, or the time set in the data window. * * This will always be in GMT. * * * * static void dsp_getTime ( lp, dttm, iret ) * * * * Input parameters: * * lp int loop number * * * * Output parameters: * * dttm dattm_t date time string * * *iret int return code 0 = normal -1 = error * * * * Return parameters: * * NONE * ** * * E. Safford/GSC 12/00 initial coding * * B. Yin/SAIC 03/04 changed css_gtim calling sequences * ***********************************************************************/ { int ier, itype = 1; dttmi_t *date; /*---------------------------------------------------------------------*/ *iret = 0; if ( dataw_useRefTm(lp) ) { date = (dttmi_t *)dataw_getRefTm(lp); sprintf ( dttm, "%02d%02d%02d/%02d%02d", date->year%100, date->mon+1, date->day, date->hour, date->min ); } else { css_gtim (&itype, dttm, &ier); if ( ier != 0 ) { *iret = -1; } } } /*=====================================================================*/ void dsp_loadSingleTime ( int lp, Boolean view_lp, int *loaded ) /************************************************************************ * dsp_loadSingleTime * * * * This function loads a loop with one grid field and multiple products * * which all valid at the same time. * * * * void dsp_loadSingleTime( lp, view_lp, loaded ) * * * * Input parameters: * * lp int loop number * * view_lp Boolean True if loop is to be in view after load* * * * Output parameters: * * *loaded int number of pixmaps loaded * * * * Return parameters: * * NONE * * * ** * * T. Lee/GSC 2/01 initial coding * * H. Zeng/EAI 04/01 moved blank map before the 1st pixmap * * H. Zeng/EAI 04/01 add stop function for NMAP2 * * J. Wu/GSC 4/01 change logo drawing to be loop-specific * * H. Zeng/EAI 05/01 modified to fix clearing VG from data * * M. Li/GSC 07/01 added a check for the off source * * A. Hardy/GSC 7/01 added queries and saves for text attr. * * E. Safford/GSC 08/01 rmv pxmarry[] param from xmloop_loopSet * * J. Wu/SAIC 11/01 add param in cvg_load() calling * * J. Wu/SAIC 12/01 add layer in cvg_load() call * * J. Wu/SAIC 12/01 rebuild range record after xpgrfrsh() * * J. Wu/SAIC 12/01 replace cvg_load() with cvg_redraw() * * J. Wu/SAIC 05/03 fix MAX_FRAME bug - out of boundary * * M. Li/SAIC 03/08 Added case CAT_ENS * ***********************************************************************/ { int ii, jj, frm, ier; int nsrcs, total_frm, maxfrm, cur_lp; int nframs; int jtxfn, jtxhw, jtxwid, jbrdr, jrrotn, jjust; float ssztxt; char plot_area[5]; Boolean exceeded_pxms, prtflg, view_frm; dttms_t tarry[MAX_FRAME+1]; dattm_t c_tm; Widget wid; dsrc_t *dom, *dsrc; /*---------------------------------------------------------------------*/ prtflg = (Boolean) NxmPrt_isPrtFlgSet (); cur_lp = loop_getCurLoop(); /* * initialize times */ for (ii=0; ii < MAX_FRAME+1; ii++) { tarry[ii][0] = '\0'; } /* * Tell the xw driver which loop is getting loaded. */ xmloop_switchLoop (lp, FALSE); /* * Set the roam environment. */ if ( ! prtflg ) { roamw_setup (lp, view_lp); } *loaded = 0; exceeded_pxms = FALSE; dataw_getDataW(&wid); /* * Get the number of frames for this loop, based on the number * of the grid fields selected. */ maxfrm = MAX_FRAME; exceeded_pxms = FALSE; total_frm = loop_getTotalFrames(lp); nframs = 0; dom = (dsrc_t *)dataw_getDomSrc(lp); nsrcs = dataw_getNumSrcs(lp); if (dom != NULL && (dom->catg == CAT_GRD || dom->catg == CAT_ENS) ) { for ( ii = 0; ii < nsrcs; ii++ ) { if ( total_frm == maxfrm ) { exceeded_pxms = TRUE; dom->frm[ii].selected = FALSE; break; } else { dsrc = (dsrc_t *)dataw_getDataSrc (lp, ii); if ( (dsrc->catg == CAT_GRD || dom->catg == CAT_ENS) && dsrc->src_on ) { total_frm++; for ( jj = 0; jj < maxfrm; jj++) { if (dom->frm[jj].selected) { strcpy (tarry[nframs+1], dom->frm[jj].ftime); } } nframs++; } } } } dataw_getPanelLoc (lp, plot_area); if ( nframs > 0 ) { mbotw_loadingLoopSet(TRUE, lp); dsp_getTime ( lp, c_tm, &ier ); /* * For each frame, load one grid field and the rest of the non-grid * field. */ view_frm = TRUE; for (frm = 1; frm<=nframs && !_transferInterrupt; frm++) { mbotw_pageSet(frm, nframs); dsp_loadFrame(lp, frm, frm, c_tm, tarry[frm], view_lp, nsrcs, view_frm, FALSE); if ( ! prtflg && pgpalw_isUp() && lp == cur_lp) { xpgsvfrm2 (frm); } /* * Display the most recent frame of the current loop * (view_lp) while everything else loads */ if (view_lp && (view_frm || prtflg)) { if (pgpalw_isUp()) { cvg_redraw ( NULL, &ier ); } geplot(&ier); } view_frm = FALSE; /* * check the stop button before going to next frame * this should be the LAST ACTION before advancing * to next frame */ NxmBusy_checkStopBtn(); } } else { /* * No sources -- just load the default map and tell the xw driver * we have just the one pixmap. */ xmloop_loopSet (wid, lp, view_lp, 0, 0, dsp_updatePage, &ier); } /* * Finish the loop up */ if (!prtflg) { /* * add blank map to each loop */ xscpxm (0, &ier); loop_setFramePxm (lp, 0, 0); gclear(&ier); /* * Check if the total # of frames changed because the user clicked on * the STOP button. */ if (_transferInterrupt) { nframs = frm - 1; } /* * Set up animation loop. */ xmloop_loopSet (wid, lp, view_lp, 1, nframs, dsp_updatePage, &ier); gqtext (&jtxfn, &jtxhw, &ssztxt, &jtxwid, &jbrdr, &jrrotn, &jjust, &ier ); gstext (&_ifnt, &_ihwsw, &_tsize, &_iwid, &_ibrdr, &_irot, &_ijust, &ier ); nmp_plot(lp, 0, plot_area, &ier); gstext (&jtxfn, &jtxhw, &ssztxt, &jtxwid, &jbrdr, &jrrotn, &jjust, &ier ); dsp_drawLogo ( lp ); if (pgpalw_isUp() && view_lp) { xpgsvfrm2 (0); xpgrfrsh(); crg_rebuild(); } /* * if we've only loaded a base map (nframs == 0) and the loop * is currently in view, then plot the map. */ if (nframs == 0 && view_lp) { geplot(&ier); } } /* * Write out an error message if all requested frames are not * displayed */ if (exceeded_pxms ) { dsp_showLoadErr(); } /* * Tell the xw driver to reset the bad frame tags for this loop. */ xmfrmtg_resetLp(lp, &ier); *loaded = nframs+1; mbotw_loadingLoopSet(FALSE, lp); } /*=====================================================================*/ void dsp_getSingleTmOrdr ( int lp, int nsrcs, int frm, int plot_ordr[], int *ndata, Boolean *img_data ) /************************************************************************ * dsp_getSingleTmOrdr * * * * This function determines the plot order for the single time loop * * data in the given panel. * * * * void dsp_getSingleTmOrdr(lp, nsrcs, frm, plot_ordr, ndata, img_data) * * * * Input parameters: * * lp int loop number * * nsrcs int number of data sources * * frm int panel number * * * * Output parameters: * * plot_ordr[] int array of indicies to data sources * * *ndata int number of data per panel * * *img_data Boolean True if image data in panel * * * ** * * T. Lee/GSC 2/01 initial coding * * H. Zeng/EAI 04/01 moved blank map before the 1st pixmap * * M. Li/GSC 06/01 add a check for off-data source * * M. Li/GSC 07/01 subtract ndata by the "off" grid source * * E. Safford/GSC 07/01 revise noff calculation * * M. Li/SAIC 03/08 Added case CAT_ENS * ***********************************************************************/ { dsrc_t *dsrc, *dom; Cardinal kk; int ii, cnt, idoms, ngds, noff; int catg_ordr[] = {CAT_IMG, CAT_GRD, CAT_ENS, CAT_SFC, CAT_SND, CAT_SFF, CAT_SNF, CAT_MSC, CAT_VGF, CAT_NIL}; /*---------------------------------------------------------------------*/ *img_data = FALSE; /* * initial output */ for (ii=0; ii<nsrcs; ii++) { plot_ordr[ii] = -1; } cnt = 0; ngds = 0; noff = 0; if (nsrcs == 1) { plot_ordr[0] = 0; ngds++; } else { idoms = 1; dom = (dsrc_t *)dataw_getDomSrc (lp); /* * Count the number of sources switched off. These won't be plotted. */ for (ii = 0; ii < nsrcs; ii++) { dsrc = dataw_getDataSrc(lp, ii); if (!dsrc->src_on) { noff++; } } /* * Step through each data category and put data in plotting order. */ for ( kk = 0; kk < XtNumber(catg_ordr) && cnt < nsrcs; kk++ ) { for (ii = 0; ii < nsrcs; ii++) { dsrc = dataw_getDataSrc(lp, ii); if (dsrc->catg == CAT_IMG && dsrc->src_on ) { *img_data = TRUE; } if ( dsrc->src_on ) { /* * One grid data at a time. */ if ( dsrc->catg == catg_ordr[kk] ) { if (dsrc->catg == CAT_GRD || dsrc->catg == CAT_ENS ) { ngds++; if ( frm == 1 ) { if ( dom->attridx == dsrc->attridx ) { plot_ordr [cnt] = ii; cnt++; } } else { if ( dom->attridx != dsrc->attridx ) { idoms++; if ( frm == idoms ) { plot_ordr [cnt] = ii; cnt++; } } } } else { plot_ordr [cnt] = ii; cnt++; } } } } } } /* * * The new nsrcs is recomputed. * */ *ndata = nsrcs - ngds - noff + 1; } /*=====================================================================*/ void dsp_addLogo ( int lp ) /************************************************************************ * dsp_addLogo * * * * This function adds a new logo to each frame in a given loop. * * * * void dsp_addLogo ( lp ) * * * * Input parameters: * * lp int loop number * * * * Output parameters: * * none * * * * Return parameters: * * none * * * ** * * J. Wu/GSC 4/01 Moved from dsp_addAllLogo() * * T. Piper/SAIC 09/06 Removed xmloop_switchLoop * ***********************************************************************/ { int frm, pxm, ier, cur_lp, nfrms; Boolean prtflg, view_lp; /*---------------------------------------------------------------------*/ prtflg = (Boolean) NxmPrt_isPrtFlgSet (); cur_lp = loop_getCurLoop ( ); /* * Add the logo to each frame in the loop. */ if ( lp == cur_lp ) { view_lp = TRUE; } else { view_lp = FALSE; } /* * Set the roam environment. */ if ( ! prtflg ) { roamw_setup (lp, view_lp); } nfrms = loop_getNumFrames ( lp ); for ( frm = 1; frm <= nfrms; frm++ ) { /* * For each frame, get the pixmap and draw the logo to it. */ pxm = loop_getFramePxm ( lp, frm ); xscpxm ( pxm, &ier ); dsp_drawLogo ( lp ); } } /*=====================================================================*/
33.097499
79
0.437799
[ "model" ]
84c1d00ff8c61e92bceff7cab626cd426afa0964
1,455
h
C
include/orchid/common/stack_array.h
funrunskypalace/greatwall_memory_trading_libs
d01931e3a85a352f644a9cef5f7f5f569fd7aed7
[ "Apache-2.0" ]
null
null
null
include/orchid/common/stack_array.h
funrunskypalace/greatwall_memory_trading_libs
d01931e3a85a352f644a9cef5f7f5f569fd7aed7
[ "Apache-2.0" ]
null
null
null
include/orchid/common/stack_array.h
funrunskypalace/greatwall_memory_trading_libs
d01931e3a85a352f644a9cef5f7f5f569fd7aed7
[ "Apache-2.0" ]
null
null
null
#pragma once #ifdef WIN32 #include <malloc.h> #else #include <alloca.h> #endif #include <cstddef> #include "orchid/common/assert.h" namespace orchid { // This macro is intended to be used as a replacement for variable-length // arrays. Note that the StackArray wrapper object will be destructed and each // element's destructor will be called when it leaves scope. However, the memory // containing the array won't be deallocated until the function containing the // macro returns. We can't call alloca in the StackArray constructor since the // memory would be freed when the constructor returns. #define STACK_ARRAY(var, type, num) \ StackArray<type> var(::alloca(sizeof(type) * num), num) template <typename T> class StackArray { public: StackArray(void* buf, size_t num_items) { ASSERT(buf != nullptr, "StackArray received null pointer"); begin_ = static_cast<T*>(buf); end_ = static_cast<T*>(buf) + num_items; for (T& ref : *this) { new (&ref) T; } } ~StackArray() { for (T& ref : *this) { ref.~T(); } } T* begin() { return begin_; } T* end() { return end_; } T& operator[](size_t idx) { return begin_[idx]; } void* operator new(size_t) = delete; void* operator new[](size_t) = delete; private: T* begin_; T* end_; }; } // namespace orchid
22.734375
80
0.612371
[ "object" ]
84c99842e1f13bad4a1a594993d4716b650f420a
1,547
h
C
src/types/extra/iter.h
fy0/python_lite
f59850b6093ec8260d96302af25c2bc3bdababc9
[ "Zlib" ]
91
2016-05-12T21:10:13.000Z
2022-03-29T14:20:36.000Z
src/types/extra/iter.h
fy0/python_lite
f59850b6093ec8260d96302af25c2bc3bdababc9
[ "Zlib" ]
1
2017-01-11T23:17:43.000Z
2021-11-17T05:30:23.000Z
src/types/extra/iter.h
fy0/python_lite
f59850b6093ec8260d96302af25c2bc3bdababc9
[ "Zlib" ]
5
2017-01-02T12:23:34.000Z
2022-03-29T14:20:41.000Z
 #ifndef PYLITE_TYPES_ITER_H #define PYLITE_TYPES_ITER_H #include "../object.h" // Common Iterator typedef struct PyLiteIterObject { PyLiteObject_HEAD; PyLiteObject *base; PyLiteIterFunc iter_func; union { struct { pl_int_t count; pl_int_t index; } array; struct { pl_int_t count; pl_int32_t k; } hashmap; }; struct PyLiteIterObject *backup; } PyLiteIterObject; PyLiteIterObject* pylt_obj_iter_new(PyLiteInterpreter *I, PyLiteObject *obj); PyLiteObject* pylt_obj_iter_next(PyLiteInterpreter *I, PyLiteIterObject *iter); PyLiteObject* pylt_obj_bytes_iternext(PyLiteInterpreter *I, PyLiteIterObject *iter); PyLiteObject* pylt_obj_str_iternext(PyLiteInterpreter *I, PyLiteIterObject *iter); PyLiteObject* pylt_obj_tuple_iternext(PyLiteInterpreter *I, PyLiteIterObject *iter); PyLiteObject* pylt_obj_list_iternext(PyLiteInterpreter *I, PyLiteIterObject *iter); PyLiteObject* pylt_obj_set_iternext(PyLiteInterpreter *I, PyLiteIterObject *iter); PyLiteObject* pylt_obj_dict_iternext(PyLiteInterpreter *I, PyLiteIterObject *iter); PyLiteObject* pylt_obj_dict_items_iternext(PyLiteInterpreter *I, PyLiteIterObject *iter); PyLiteObject* pylt_obj_range_iternext(PyLiteInterpreter *I, PyLiteIterObject *iter); PyLiteObject* pylt_obj_custom_iternext(PyLiteInterpreter *I, PyLiteIterObject *iter); void pylt_obj_iter_rfree(PyLiteInterpreter *I, PyLiteIterObject* self); void pylt_obj_iter_free(PyLiteInterpreter *I, PyLiteIterObject* self); #endif
36.833333
89
0.777634
[ "object" ]
84cd834eb2ddeb97ec5d7e5215d640fc96b1a600
1,649
h
C
Areas/NewbieIsle/Mansion/o/def.h
yodakingdoms/kingdoms
831b74ba4a086de69cce213ad2398f646c3efb39
[ "MIT" ]
null
null
null
Areas/NewbieIsle/Mansion/o/def.h
yodakingdoms/kingdoms
831b74ba4a086de69cce213ad2398f646c3efb39
[ "MIT" ]
null
null
null
Areas/NewbieIsle/Mansion/o/def.h
yodakingdoms/kingdoms
831b74ba4a086de69cce213ad2398f646c3efb39
[ "MIT" ]
null
null
null
//======================================================== // Definitions for Mansion domain. //======================================================== // Standard mudlib includes //-------------------------------------------------------- #include <macros.h> #include <mudlib.h> #include <sysdefs.h> #include <levels.h> #include <guild.h> #include <items.h> #define STD_LORE "/std/toolbox/lore" // Subrace for the goblins so later xp isn't affected by killing // the wimpy monsters here #define MANSION_GOBLIN_SUBRACE_FLAG 18 //-------------------------------------------------------- // Domain path definitions //-------------------------------------------------------- #define MANSION "/areas/NewbieIsle/Mansion/o/" #define ROOM MANSION + "Room/" #define MONSTER MANSION + "Monster/" #define OBJECT MANSION + "Object/" #define WEAPON MANSION + "Weapon/" #define ARMOUR MANSION + "Armour/" //-------------------------------------------------------- // Master stuff //-------------------------------------------------------- #define MASTER_ROOM MANSION + "Master/master_room" #define MASTER_INDOORS_ROOM MANSION + "Master/master_indoors_room" #define ITEMS_MODULE MANSION + "Master/items_module" #define SYS_DESTRUCT "/sys/room/destruct_room" //-------------------------------------------------------- // Exits to Playground area //-------------------------------------------------------- #define PLAYGROUND "/areas/NewbieIsle/Playground/o/Rooms/entrance" //-------------------------------------------------------- // Log //-------------------------------------------------------- #define QUEST_LOG "/areas/NewbieIsle/Mansion/log/quest_solvers"
38.348837
66
0.46513
[ "object" ]
170b6d8b5e90723dd59436ce8553f28e23824db6
588
h
C
src/ListenerComponent.h
NoVariableGlobal/global-engine
b682dccbae6c5a4794e94960dfeb220addfe7773
[ "MIT" ]
null
null
null
src/ListenerComponent.h
NoVariableGlobal/global-engine
b682dccbae6c5a4794e94960dfeb220addfe7773
[ "MIT" ]
3
2020-03-09T21:34:04.000Z
2021-03-28T17:30:31.000Z
src/ListenerComponent.h
NoVariableGlobal/one-thousand-years
b682dccbae6c5a4794e94960dfeb220addfe7773
[ "MIT" ]
3
2020-08-15T06:33:32.000Z
2021-03-28T14:23:31.000Z
#pragma once #include "Component.h" namespace Ogre { struct FrameEvent; } // Abstract subcomponent from which every input component should inherit class ListenerComponent : public Component { public: // Destroys the ListenerComponent, setting itself as inactive and // removing itself from the scene. virtual void destroy(); // called by Ogre after all render targets have had their rendering commands // issued, but before render windows have been asked to flip their buffers // over. virtual void frameRendered(const Ogre::FrameEvent& evt) = 0; };
28
80
0.731293
[ "render" ]
41c793fe1d1a339f4ed7b984c40c33c970b85fcf
4,136
h
C
Core/MAGESLAM/Source/Device/CameraCalibration.h
syntheticmagus/mageslam
ba79a4e6315689c072c29749de18d70279a4c5e4
[ "MIT" ]
70
2020-05-07T03:09:09.000Z
2022-02-11T01:04:54.000Z
Core/MAGESLAM/Source/Device/CameraCalibration.h
syntheticmagus/mageslam
ba79a4e6315689c072c29749de18d70279a4c5e4
[ "MIT" ]
3
2020-06-01T00:34:01.000Z
2020-10-08T07:43:32.000Z
Core/MAGESLAM/Source/Device/CameraCalibration.h
syntheticmagus/mageslam
ba79a4e6315689c072c29749de18d70279a4c5e4
[ "MIT" ]
16
2020-05-07T03:09:13.000Z
2022-03-31T15:36:49.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "Data\Data.h" #include "arcana\utils\serialization\serializable.h" #include "arcana\type_traits.h" #include "Serialization\cv_serialization.h" #include <opencv2\core\types.hpp> #include <array> namespace mage { class CameraCalibration : public mira::serializable<CameraCalibration> { public: CameraCalibration(); CameraCalibration(std::shared_ptr<const calibration::CameraModel> cameraModel); template<typename StreamT, typename = mira::is_stream_t<StreamT>> explicit CameraCalibration(StreamT& stream) { deserialize(stream); } static constexpr auto members() { return declare_members( &CameraCalibration::m_cameraMatrix, &CameraCalibration::m_invCameraMatrix, &CameraCalibration::m_cvDistortionCoeffs, &CameraCalibration::m_distortionType, &CameraCalibration::m_width, &CameraCalibration::m_height ); } const cv::Matx33f& GetCameraMatrix() const { return m_cameraMatrix; }; const cv::Matx33f& GetInverseCameraMatrix() const { return m_invCameraMatrix; } calibration::DistortionType GetDistortionType() const { return m_distortionType; } uint32_t GetCalibrationWidth() const { return m_width; } uint32_t GetCalibrationHeight() const { return m_height; } Intrinsics CameraCalibration::GetScaledIntrinsics(float scale) const; CameraCalibration GetScaledCalibration(float scale) const; // vector of distortion coefficients in opencv ordering K0 K1 P1 P2 K2 [K3, K4, K5] cv::Mat GetCVDistortionCoeffs() const; // vector of the linear intrinsics CX CY FX FY cv::Vec4f GetLinearIntrinsics() const; float GetFocalLengthX() const { return m_cameraMatrix(0, 0); } float GetFocalLengthY() const { return m_cameraMatrix(1, 1); } float GetPrincipalPointX() const { return m_cameraMatrix(0, 2); } float GetPrincipalPointY() const { return m_cameraMatrix(1, 2); } float GetK1() const { return m_cvDistortionCoeffs(0); } //radial distortion coefficient R^2 float GetK2() const { return m_cvDistortionCoeffs(1); } //radial distortion coefficient R^4 float GetP1() const { return m_cvDistortionCoeffs(2); } //tangential distortion coefficient float GetP2() const { return m_cvDistortionCoeffs(3); } //tangential distortion coefficient float GetK3() const { return m_cvDistortionCoeffs(4); } //radial distortion coefficient R^6 float GetK4() const { assert(m_distortionType == calibration::DistortionType::Rational6k && "invalid distortion term"); return m_cvDistortionCoeffs(5); } //radial distortion coefficient for rational 6k float GetK5() const { assert(m_distortionType == calibration::DistortionType::Rational6k && "invalid distortion term"); return m_cvDistortionCoeffs(6); } //radial distortion coefficient for rational 6k float GetK6() const { assert(m_distortionType == calibration::DistortionType::Rational6k && "invalid distortion term"); return m_cvDistortionCoeffs(7); } //radial distortion coefficient for rational 6k std::shared_ptr<const calibration::CameraModel> CreateCameraModel() const; bool operator==(const CameraCalibration& other) const; bool operator!=(const CameraCalibration& other) const { return !(*this == other); } private: cv::Matx33f m_cameraMatrix; cv::Matx33f m_invCameraMatrix; cv::Matx<float, 8, 1> m_cvDistortionCoeffs; // vector of opencv distortion coefficients K1 K2 P1 P2 K3 K4 K5 K6 calibration::DistortionType m_distortionType; uint32_t m_width; uint32_t m_height; }; std::ostream& operator <<(std::ostream& stream, const calibration::DistortionType t); std::istream& operator >>(std::istream& stream, calibration::DistortionType& t); }
45.450549
213
0.681093
[ "vector" ]
41c9005c5c4571337381e4950dac0ccaede1584e
283
c
C
mud/bin/fish.c
shentino/simud
644b7d4f56bf8d4695442b8efcfd56e0a561fe21
[ "Apache-2.0" ]
3
2015-07-18T00:19:51.000Z
2016-02-20T17:25:37.000Z
mud/bin/fish.c
shentino/simud
644b7d4f56bf8d4695442b8efcfd56e0a561fe21
[ "Apache-2.0" ]
2
2021-03-04T19:24:03.000Z
2021-03-08T10:17:34.000Z
mud/bin/fish.c
shentino/simud
644b7d4f56bf8d4695442b8efcfd56e0a561fe21
[ "Apache-2.0" ]
2
2015-12-22T06:16:53.000Z
2016-11-18T16:32:50.000Z
int main() { object ob; foreach( ob : all_inventory(environment(this_player())) ) { if( ob->query_is_ocean() ) { clone_object("/world/game/fishing")->move(this_player()); return 1; } } notify_fail("You can't fish here.\n"); return 0; }
20.214286
66
0.568905
[ "object" ]
41cb9346e9cfc7b9951cedb6dbd5c05522a0f480
8,496
c
C
DIR819_v1.06/src/kernel/linux-2.6.36.x/drivers/net/eip93_drivers/quickSec/src/lib/sshtls/tls_kt_RClientHello.c
Sirherobrine23/Dir819gpl_code
8af92d65416198755974e3247b7bbe7f1151d525
[ "BSD-2-Clause" ]
1
2022-03-19T06:38:01.000Z
2022-03-19T06:38:01.000Z
DIR819_v1.06/src/kernel/linux-2.6.36.x/drivers/net/eip93_drivers/quickSec/src/lib/sshtls/tls_kt_RClientHello.c
Sirherobrine23/Dir819gpl_code
8af92d65416198755974e3247b7bbe7f1151d525
[ "BSD-2-Clause" ]
null
null
null
DIR819_v1.06/src/kernel/linux-2.6.36.x/drivers/net/eip93_drivers/quickSec/src/lib/sshtls/tls_kt_RClientHello.c
Sirherobrine23/Dir819gpl_code
8af92d65416198755974e3247b7bbe7f1151d525
[ "BSD-2-Clause" ]
1
2022-03-19T06:38:03.000Z
2022-03-19T06:38:03.000Z
/* tls_kt_RClientHello.c Copyright: Copyright 2002-2007, SafeNet Inc. All rights reserved. All rights reserved. */ #include "sshtlskextrans.h" SshTlsTransStatus ssh_tls_trans_read_client_hello( SshTlsProtocolState s, SshTlsHandshakeType type, unsigned char *data, int data_len) { int sessid_len; int cipher_suites; int compression_methods; int i; SshTlsCipherSuite suite; SshTlsCipherSuiteDetailsStruct details; unsigned char degraded_major, degraded_minor; unsigned char *ptr; CHECKTYPE(SSH_TLS_HS_CLIENT_HELLO); /* Minimum length after the header has been stripped: client_version 2 bytes, random 32 bytes, session_id 1 byte, cipher_suites 2 bytes, compression_methods 1 byte. */ MIN_LENGTH(2 + 32 + 1 + 2 + 1); /* Remember the original client version. */ s->kex.client_version.major = data[0]; s->kex.client_version.minor = data[1]; degraded_major = data[0]; degraded_minor = data[1]; /* Degrade the client version if necessary. */ ssh_tls_degrade_version(s, &degraded_major, &degraded_minor); SSH_DEBUG(5, ("Client version %d.%d, degraded %d.%d, protocol %d.%d.", data[0], data[1], degraded_major, degraded_minor, s->protocol_version.major, s->protocol_version.minor)); /* Check that the degraded version can be supported. */ if (!(ssh_tls_supported_version(s, degraded_major, degraded_minor))) { FAIL(SSH_TLS_ALERT_PROTOCOL_VERSION, ("Unsupported protocol version %d.%d.", degraded_major, degraded_minor)); } /* Now degraded_major . degraded_minor is the highest common version. Use it. */ s->protocol_version.major = degraded_major; s->protocol_version.minor = degraded_minor; /* The client cannot send more messages before receiving the ServerHello packet, so the version number can be fixed now. */ s->flags |= SSH_TLS_FLAG_VERSION_FIXED; /* Get the random value. */ memcpy(s->kex.client_random, data + 2, 32); /* Show the unix time. */ #ifdef DEBUG_LIGHT { SshUInt32 client_time; struct SshCalendarTimeRec calendar_time; client_time = SSH_GET_32BIT(data + 2); ssh_calendar_time((SshTime)client_time, &calendar_time, TRUE); SSH_DEBUG(4, ("Client time: %04d/%02d/%02d %02d:%02d:%02d.", (int)calendar_time.year, (int)calendar_time.month + 1, (int)calendar_time.monthday, (int)calendar_time.hour, (int)calendar_time.minute, (int)calendar_time.second)); } #endif /* Get the session id. */ ptr = data + 2 + 32; sessid_len = *ptr; SSH_DEBUG(6, ("Session identifier length %d bytes.", sessid_len)); /* Let's look at the session identifier. */ ptr += 1; s->kex.flags |= SSH_TLS_KEX_NEW_SESSION; /* Initially. */ if (sessid_len > 0 && s->conf.session_cache != NULL && !(s->kex.flags & SSH_TLS_KEX_NO_CACHING)) { SshTlsCachedSession session; session = ssh_tls_find_cached_session(s->conf.session_cache, ptr, sessid_len); if (session != NULL) { SSH_DEBUG(5, ("The client wants to reuse a session that we have " "cached; do that.")); memcpy(s->kex.master_secret, session->master_secret, 48); s->kex.flags |= SSH_TLS_KEX_HAVE_MASTER_SECRET; s->kex.cipher_suite = session->cipher_suite; memcpy(s->kex.session_id, session->session_id, session->id_len); s->kex.id_len = session->id_len; s->kex.peer_certs = ssh_tls_duplicate_ber_cert_chain(session->peer_certs); /* Drop the new session flag. */ s->kex.flags &= ~SSH_TLS_KEX_NEW_SESSION; /* Check the protocol version! We should perhaps check (?) that the record layer was also initially using the same version, but this seems quite unnecessary as the version is now anyway that of the cached version, and it is trusted. */ if (s->protocol_version.major != session->protocol_version.major || s->protocol_version.minor != session->protocol_version.minor) { FAIL(SSH_TLS_ALERT_ILLEGAL_PARAMETER, ("The client is trying to resume an old session but uses " "different protocol version than that of the " "cached session.")); } /* We still proceed on to parse the rest of the packet to make sure it is correctly structured. However, the absence of the NEW_SESSION flag causes the parsed values to be discarded. */ } } ptr += sessid_len; /* Skip the ID no matter what. */ if (ptr + 2 > data + data_len) FAILMF; cipher_suites = SSH_GET_16BIT(ptr); if (cipher_suites % 2 != 0) FAIL(SSH_TLS_ALERT_DECODE_ERROR, ("Cipher suite vector length is not a multiple of two.")); cipher_suites /= 2; ptr += 2; SSH_DEBUG(6, ("%d cipher suites enumerated.", cipher_suites)); if (s->kex.flags & SSH_TLS_KEX_NEW_SESSION) { s->kex.cipher_suite = SSH_TLS_CIPHERSUITE_NOT_AVAILABLE; s->kex.num_client_cipher_suites = 0; for (i = 0; i < cipher_suites; i++) { if (ptr + 2 > data + data_len) FAILMF; suite = SSH_GET_16BIT(ptr); ptr += 2; ssh_tls_get_ciphersuite_details(suite, &details); if (details.kex_method == SSH_TLS_UNKNOWN_SUITE) { SSH_DEBUG(6, ("Unknown cipher suite number %d (ignored).", suite)); } else { SSH_DEBUG(6, ("Client supports the cipher suite `%s'.", ssh_tls_format_suite(suite))); SSH_ASSERT(s->kex.num_client_cipher_suites < SSH_TLS_NUM_CIPHERSUITES); { int j; for (j = 0; j < s->kex.num_client_cipher_suites; j++) { if (s->kex.client_cipher_suites[j] == suite) { SSH_DEBUG(6, ("Multiply defined cipher suite, latter " "instance ignored.")); goto skip_over; } } s->kex.client_cipher_suites[s->kex.num_client_cipher_suites++] = suite; skip_over: continue; } } } } else { ptr += cipher_suites * 2; } if (ptr >= data + data_len) FAILMF; if (s->kex.flags & SSH_TLS_KEX_NEW_SESSION) { /* At this point, sort the client's cipher suites if a preference list has been given. */ if (s->conf.preferred_suites != NULL) { ssh_tls_sort_suites(s->kex.client_cipher_suites, &(s->kex.num_client_cipher_suites), s->conf.preferred_suites); } } compression_methods = *ptr; ptr++; SSH_DEBUG(6, ("%d compression methods enumerated.", compression_methods)); { int support_no_compression = 0; for (i = 0; i < compression_methods; i++) { if (ptr >= data + data_len) FAILMF; SSH_DEBUG(6, ("Client supports the compression method %d.", *ptr)); if (*ptr == 0) { support_no_compression = 1; } ptr++; } if (!support_no_compression) { FAIL(SSH_TLS_ALERT_HANDSHAKE_FAILURE, ("`No compression' is not supported.")); } } /* There can be extra data at the end of the ClientHello message. This is dictated by the standard. */ if (ptr > data + data_len) FAILMF; #ifdef SSHDIST_VALIDATOR if (s->kex.flags & SSH_TLS_KEX_NEW_SESSION) { return ssh_tls_get_own_certificates(s); } else /* Resumed session. */ { s->kex.state = SSH_TLS_KEX_SEND_S_HELLO; return SSH_TLS_TRANS_OK; } #else /* SSHDIST_VALIDATOR */ /* When no SSHDIST_VALIDATOR is defined the server already has its certificates ready. */ s->kex.state = SSH_TLS_KEX_SEND_S_HELLO; return ssh_tls_choose_suite(s); #endif /* SSHDIST_VALIDATOR */ }
30.782609
78
0.581215
[ "vector" ]
41d7407f5eb8eef5d74f3e796920c70b0ff5aacc
1,208
h
C
src/region_utils.h
Zomega/transverse
058b5dfc28a5ef1dab880f6112a27f2664725dff
[ "MIT" ]
null
null
null
src/region_utils.h
Zomega/transverse
058b5dfc28a5ef1dab880f6112a27f2664725dff
[ "MIT" ]
null
null
null
src/region_utils.h
Zomega/transverse
058b5dfc28a5ef1dab880f6112a27f2664725dff
[ "MIT" ]
null
null
null
// Copyright 2015 Will Oursler #ifndef REGION_UTILS_H_ #define REGION_UTILS_H_ #include <iostream> #include <vector> #include "edge.h" #include "region_graph.h" #include "shape.h" #include "predicate.h" class RegionPrimativeMatchPredicate : public Predicate<Region> { private: RegionPrimative label; public: bool matches(const Region region); // TODO(woursler): check if label is part of region... }; // TODO(woursler) RegionGraph CombineRegions(const RegionGraph a, const RegionGraph b); // TODO(woursler): Use ray std::shared_ptr<Region> Locate(const RegionGraph regions, const Point p); // TODO(woursler): Use Green's theorem. float area(const RegionGraph regions, const std::shared_ptr<Region> r); float area(const Shape shape); // TODO(woursler): // Remove all regions that are sufficiently small by joining them with the region along // their longest edge. // Should this be a RegionRedicate instead? RegionGraph DeburrRegions(RegionGraph regions, float minimumArea); // TODO(woursler): implement. Shape FilterRegions(const RegionGraph regions, std::shared_ptr<Predicate<Region>> predicate); std::vector<Shape> BreakApartRegions(const RegionGraph regions); #endif // REGION_UTILS_H_
28.093023
93
0.770695
[ "shape", "vector" ]
41df4fc23ad5a7c8e43fa6bc0ade0fd3addb6f0f
17,327
h
C
core/src/postprocessing/parallel_fiber_estimation/parallel_fiber_estimation.h
maierbn/opendihu
577650e2f6b36a7306766b0f4176f8124458cbf0
[ "MIT" ]
17
2018-11-25T19:29:34.000Z
2021-09-20T04:46:22.000Z
core/src/postprocessing/parallel_fiber_estimation/parallel_fiber_estimation.h
maierbn/opendihu
577650e2f6b36a7306766b0f4176f8124458cbf0
[ "MIT" ]
1
2020-11-12T15:15:58.000Z
2020-12-29T15:29:24.000Z
core/src/postprocessing/parallel_fiber_estimation/parallel_fiber_estimation.h
maierbn/opendihu
577650e2f6b36a7306766b0f4176f8124458cbf0
[ "MIT" ]
4
2018-10-17T12:18:10.000Z
2021-05-28T13:24:20.000Z
#pragma once #include <Python.h> // has to be the first included header #include <vector> #include "function_space/function_space.h" #include "postprocessing/streamline_tracer_base.h" #include "interfaces/discretizable_in_time.h" #include "interfaces/runnable.h" #include "data_management/parallel_fiber_estimation.h" #include "quadrature/gauss.h" #include "spatial_discretization/neumann_boundary_conditions/01_neumann_boundary_conditions.h" #include "spatial_discretization/dirichlet_boundary_conditions/01_dirichlet_boundary_conditions.h" namespace Postprocessing { /** A class that creates a parallel mesh and at the same time traces streamlines through a Δu=0 field. */ template<typename BasisFunctionType> class ParallelFiberEstimation : public StreamlineTracerBase<FunctionSpace::FunctionSpace<Mesh::StructuredDeformableOfDimension<3>,BasisFunctionType>>, public Runnable { public: //! constructor ParallelFiberEstimation(DihuContext context); //! initialize void initialize(); //! run tracing of stream lines void run(); //! open result file and interpolate fine fibers in between, the new file has the suffix ".fine" void interpolateFineFibersFromFile(); //! open the result file and interpolate all missing fibers, write fixed fibers to same file void fixInvalidFibersInFile(std::string filename); //! function space to use, i.e. 3D structured deformable grid typedef FunctionSpace::FunctionSpace<Mesh::StructuredDeformableOfDimension<3>, BasisFunctionType> FunctionSpaceType; typedef SpatialDiscretization::FiniteElementMethod< Mesh::StructuredDeformableOfDimension<3>, BasisFunctionType, Quadrature::Gauss<3>, Equation::Static::Laplace > FiniteElementMethodType; protected: //! load the checkpoint data before the algorithm starts void loadInitialCheckpoints(std::array<std::vector<std::vector<Vec3>>,4> &boundaryPoints, std::array<bool,4> &subdomainIsAtBoundary); //! perform the algorithm to recursively, collectively refine the mesh and trace fibers for the boundaries of the subdomains void generateParallelMesh(); //! recursive part of the algorithm void generateParallelMeshRecursion(std::array<std::vector<std::vector<Vec3>>,4> &boundaryPoints, std::array<bool,4> subdomainIsAtBoundary); //! take the streamlines at equidistant z points in streamlineZPoints and copy them to the array boundaryPointsSubdomain void rearrangeStreamlinePoints(std::vector<std::vector<Vec3>> &streamlineZPoints, std::array<std::array<std::vector<std::vector<Vec3>>,4>,8> &boundaryPointsSubdomain, std::array<std::vector<Vec3>,4> &cornerStreamlines, std::array<std::array<std::vector<bool>,4>,8> &boundaryPointsSubdomainAreValid, std::array<bool,4> &subdomainIsAtBoundary); //! interpolate points for invalid streamlines void fixIncompleteStreamlines(std::array<std::array<std::vector<std::vector<Vec3>>,4>,8> &boundaryPointsSubdomain, std::array<std::array<std::vector<bool>,4>,8> &boundaryPointsSubdomainAreValid, bool streamlineDirectionUpwards, const std::array<bool,4> &subdomainIsAtBoundary, std::array<std::vector<std::vector<Vec3>>,4> boundaryPoints); //! refine the given boundary points (boundaryPointsOld) in x and y direction void refineBoundaryPoints(std::array<std::vector<std::vector<Vec3>>,4> &boundaryPointsOld, std::array<std::vector<std::vector<Vec3>>,4> &boundaryPoints); //! create the mesh with given boundaryPoints, using harmonic maps by calling the python script void createMesh(std::array<std::vector<std::vector<Vec3>>,4> &boundaryPoints, std::vector<Vec3> &nodePositions, std::array<int,3> &nElementsPerCoordinateDirectionLocal); //! check if the algorithm is at the stage where no more subdomains are created and the final fibers are traced, this sets the current level_ bool checkTraceFinalFibers(); //! create Dirichlet BC object void createDirichletBoundaryConditions(std::shared_ptr<SpatialDiscretization::DirichletBoundaryConditions<FunctionSpaceType,1>> &dirichletBoundaryConditions); //! create Neumann BC object void createNeumannBoundaryConditions(std::shared_ptr<SpatialDiscretization::NeumannBoundaryConditions<FunctionSpaceType,Quadrature::Gauss<3>, 1>> &neumannBoundaryConditions); //! communicate ghost values for gradient and solution value to neighbouring processes, the ghost elements are obtained from the mesh partition void exchangeGhostValues(const std::array<bool,4> &subdomainIsAtBoundary); //! create the seed points in form of a cross at the center of the current domain void createSeedPoints(const std::array<bool,4> &subdomainIsAtBoundary, int seedPointsZIndex, const std::vector<Vec3> &nodePositions, std::vector<Vec3> &seedPoints); //! trace the fibers that are evenly distributed in the subdomain, this is the final step of the algorithm. It uses boundaryPointsSubdomain as starting dataset void traceResultFibers(double streamlineDirection, int seedPointsZIndex, const std::vector<Vec3> &nodePositions, const std::array<std::array<std::vector<std::vector<Vec3>>,4>,8> &boundaryPointsSubdomain, bool finalFile); //! trace the streamlines starting from the seed points, this uses functionality from the parent class void traceStreamlines(int nRanksZ, int rankZNo, double streamlineDirection, bool streamlineDirectionUpwards, std::vector<Vec3> &seedPoints, std::vector<std::vector<Vec3>> &streamlinePoints); //! send seed points from rank int(nRanksZ/2) to rank int(nRanksZ/2)-1 void exchangeBoundarySeedPoints(int nRanksZ, int rankZNo, bool streamlineDirectionUpwards, std::vector<Vec3> &seedPoints); //! determine if previously set seedPoints are used or if they are received from neighbouring rank, on rank int(nRanksZ/2), send seed points to rank below void exchangeSeedPointsBeforeTracingKeyFibers(int nRanksZ, int rankZNo, bool streamlineDirectionUpwards, std::vector<Vec3> &seedPoints); //! send end points of streamlines to next rank that continues the streamline, only iterate over key fibers void exchangeSeedPointsAfterTracingKeyFibers(int nRanksZ, int rankZNo, bool streamlineDirectionUpwards, int nFibersX, std::vector<Vec3> &seedPoints, std::vector<std::vector<Vec3>> &fibers); //! receive boundary seed points void exchangeBoundarySeedPointsBeforeTracing(int nRanksZ, int rankZNo, bool streamlineDirectionUpwards, std::vector<Vec3> &seedPoints); //! send boundary seed points as the end of the streamlines //void exchangeBoundarySeedPointsAfterTracing(int nRanksZ, int rankZNo, bool streamlineDirectionUpwards, std::vector<std::vector<Vec3>> &streamlinePoints); //! send boundary seed points from boundaryPointsSubdomain void exchangeBoundarySeedPointsAfterTracing(int nRanksZ, int rankZNo, bool streamlineDirectionUpwards, const std::array<bool,4> &subdomainIsAtBoundary, const std::array<std::array<std::vector<std::vector<Vec3>>,4>,8> &boundaryPointsSubdomain, const std::array<std::vector<Vec3>,4> &cornerStreamlines); //! extract seed points for the next rank from boundaryPoints, at the end of the streamlines void extractSeedPointsFromBoundaryPoints(const std::array<std::array<std::vector<std::vector<Vec3>>,4>,8> &boundaryPointsSubdomain, std::array<std::vector<Vec3>,4> cornerStreamlines, const std::array<bool,4> &subdomainIsAtBoundary, bool streamlineDirectionUpwards, std::vector<Vec3> &seedPoints); //! sample the streamlines at equidistant z points, if the streamline does not run from bottom to top, only add seedPoint void sampleAtEquidistantZPoints(std::vector<std::vector<Vec3>> &streamlinePoints, const std::vector<Vec3> &seedPoints, std::vector<std::vector<Vec3>> &streamlineZPoints); //! sample one streamline at equidistant z points, if the streamline does not run from bottom to top, only add seedPoint, i is a number for debugging output void sampleStreamlineAtEquidistantZPoints(std::vector<Vec3> &streamlinePoints, const Vec3 &seedPoint, double bottomZClip, double topZClip, std::vector<Vec3> &streamlineZPoints, int streamlineNoForDebugging, std::vector<std::vector<Vec3>> &rawSampledStreamlinesForDebugging); //! compute the starting end end value of z for the current subdomain, uses meshPartition_ void computeBottomTopZClip(double &bottomZClip, double &topZClip); //! fill in missing points at the boundarys, where no streamlines were traced void fillBoundaryPoints(std::array<std::vector<std::vector<Vec3>>,4> &boundaryPoints, std::array<std::array<std::vector<std::vector<Vec3>>,4>,8> &boundaryPointsSubdomain, std::array<std::vector<Vec3>,4> &cornerStreamlines, std::array<std::array<std::vector<bool>,4>,8> &boundaryPointsSubdomainAreValid, std::array<bool,4> &subdomainIsAtBoundary); //! send boundary points to those ranks that will handle them in the next subdomain void sendBoundaryPoints(std::array<std::array<std::vector<std::vector<Vec3>>,4>,8> &boundaryPointsSubdomain, std::vector<std::vector<double>> &sendBuffers, std::vector<MPI_Request> &sendRequests); //! receive the boundary points void receiveBoundaryPoints(int nRanksPerCoordinateDirectionPreviously, std::array<std::vector<std::vector<Vec3>>,4> &boundaryPointsNew, std::array<bool,4> &subdomainIsAtBoundaryNew); //! write all boundary points to a common file void outputBoundaryPoints(std::array<std::array<std::vector<std::vector<Vec3>>,4>,8> &boundaryPointsSubdomain, std::string name); //! output boundary points as connected streamlines void outputStreamlines(std::array<std::array<std::vector<std::vector<Vec3>>,4>,8> &boundaryPointsSubdomain, std::string name); //! if there are streamlines at the edge between two processes' subdomains that are valid on one process and invalid on the other, send them from the valid process to the invalid void communicateEdgeStreamlines(std::array<std::array<std::vector<std::vector<Vec3>>,4>,8> &boundaryPointsSubdomain, std::array<std::array<std::vector<bool>,4>,8> &boundaryPointsSubdomainAreValid); //! fill invalid streamlines at corners from boundary points void fixStreamlinesCorner(std::array<std::array<std::vector<std::vector<Vec3>>,4>,8> &boundaryPointsSubdomain, std::array<std::array<std::vector<bool>,4>,8> &boundaryPointsSubdomainAreValid, const std::array<bool,4> &subdomainIsAtBoundary, std::array<std::vector<std::vector<Vec3>>,4> boundaryPoints); //! set invalid streamlines between two streamlines that are valid as a weighted sum of them void fixStreamlinesInterior(std::array<std::array<std::vector<std::vector<Vec3>>,4>,8> &boundaryPointsSubdomain, std::array<std::array<std::vector<bool>,4>,8> &boundaryPointsSubdomainAreValid, bool streamlineDirectionUpwards); //! determine if the subdomain is at which boundarys, from rank no void setSubdomainIsAtBoundary(int rankNo, std::array<bool,4> &subdomainIsAtBoundaryNew); //! fix the invalid key fibers at the end of the algorithm void fixInvalidKeyFibers(int nFibersX, std::vector<std::vector<bool>> &fiberIsValid, std::vector<std::vector<Vec3>> &fibers, int &nFibersFixed); //! resamples the final fibers in the output file to match the required number of nodes per fiber void resampleFibersInFile(int nPointsPerFiber, std::string filename); //! stretches the mesh in x-y planes at the corner points such that the 180° angle is less severe void stretchMeshAtCornersInFile(std::string filename); //! if the filename is something like path/fibers0x0.bin, replace 0 by nFibersX, return true if replacement was performed bool adjustFilename(std::string &filename, int nFibersX); //! create output file with fibers in it void writeToFile(std::string filename, std::vector<std::vector<Vec3>> &fibers, int nFibersX, bool withBoundaryLayer); //! compute the current level_ = log2(nRanksPerCoordinateDirection_) void determineLevel(); //! determine if a neighor rank exists in the given face or edge bool neighbourExists(const std::array<bool,4> &subdomainIsAtBoundary, Mesh::face_or_edge_t faceOrEdge); //! print if one of the surrounding neighbors is a boundary void printRanksInNeighbourhood(const std::array<bool,4> &subdomainIsAtBoundary); const DihuContext context_; //< object that contains the python config for the current context and the global singletons meshManager and solverManager std::shared_ptr<FiniteElementMethodType> problem_; //< the DiscretizableInTime object that is managed by this class Data::ParallelFiberEstimation<FunctionSpaceType> data_; //< the data object that holds the gradient field variable //std::shared_ptr<FunctionSpaceType> functionSpace_; //< current function space / mesh PythonConfig specificSettings_; //< the specific python config for this module std::vector<Vec3> seedPositions_; //< the seed points from where the streamlines start std::string inputMeshFilename_; //< the filename of the input mesh file std::string resultFilename_; //< the filename of the output result file double bottomZClip_; //< bottom z-value of the volume to consider double topZClip_; //< top z-value of the volume to consider double finalBottomZClip_; //< bottom z-value of the final fibers double finalTopZClip_; //< top z-value of the final fibers int nBoundaryPointsX_; //< number of subdivisions of the line int nBoundaryPointsZ_; //< number of subdivisions in z direction int maxLevel_; //< the maximum level up to which the domain will be subdivided, number of final domains is 8^maxLevel_ (octree structure) int nBoundaryPointsXNew_; //< the value of nBoundaryPointsX_ in the next subdomain int nBoundaryPointsZNew_; //< the value of nBoundaryPointsZ_ in the next subdomain int nFineGridFibers_; //< the number of additional fibers between "key" fibers in one coordinate direction int nNodesPerFiber_; //< the number of nodes of the final fiber, this is assured at the end, then the fibers get resampled to the required number of nodes per fiber bool improveMesh_; //< if the improveMesh_ flag should be set to the algorithm that creates the 3D mesh. This make the mesh smoother but it takes more time int level_; //< current level of the recursion, 0=1 process, 1=8 processes, 2=64 processes bool useNeumannBoundaryConditions_; //< if neumann instead of dirichlet boundary conditions should be used int laplacianSmoothingNIterations_; //< number of iterations of Laplacian smoothing that is applied prior to tracing the fine grid fibers int ghostLayerWidth_; //< width of the ghost layer in elements that is created in parallel execution double maxAreaFactor_; //< factor only for triangulation_type 1, approximately the minimum number of triangles that will be created because of a maximum triangle area constraint std::map<int,int> nFibersFixed_; //< [recursionLevel] number of fibers that was fixed on each recursion level std::array<int,3> refinementFactors_; //< factors by which the mesh should be refined prior to solving the Laplace problem and tracing the streamlines PyObject *moduleStlCreateMesh_; //< python module, file "stl_create_mesh.py" PyObject *moduleStlCreateRings_; //< python module, file "stl_create_rings.py" PyObject *moduleStlDebugOutput_; //< python module, file "stl_debug_output.py" PyObject *functionCreateRingSection_; //< python function create_ring_section PyObject *functionCreateBoundaryPoints_; //< function that creates the initial boundary points of the mesh as loops PyObject *functionOutputPoints_; //< output_points PyObject *functionOutputBoundaryPoints_; //< output_boundary_points PyObject *functionOutputGhostElements_; //< output_ghots_elements PyObject *functionCreate3dMeshFromBoundaryPointsFaces_; //< create_3d_mesh_from_boundary_points_faces PyObject *functionOutputStreamline_; //< function to output connected points as streamline PyObject *functionOutputStreamlines_; //< function to output boundary points as connected streamlines PyObject *functionOutputRings_; //< function to output boundary point rings as connected and closed lines std::shared_ptr<Partition::RankSubset> currentRankSubset_; //< the rank subset of the ranks that are used at the current stage of the algorithm std::array<int,3> nRanksPerCoordinateDirection_; //< the numbers of ranks in each coordinate direction at the current stage of the algorithm std::shared_ptr<Partition::MeshPartition<FunctionSpace::FunctionSpace<Mesh::StructuredDeformableOfDimension<3>, BasisFunctionType>>> meshPartition_; //< the mesh partition of this subdomain which contains information about the neighbouring ranks and the own index in the ranks grid OutputWriter::Manager outputWriterManager_; //< manager object holding all output writer }; } // namespace #include "postprocessing/parallel_fiber_estimation/parallel_fiber_estimation.tpp"
71.896266
283
0.760028
[ "mesh", "object", "vector", "3d" ]
41f2d6d8c61c6898495de0927d1a1e843342220e
1,651
h
C
YYOCFramework/Classes/CYUITVDSD_base.h
yanyanforest/YYOCFramework
43279ecf2f1fe024e8c3a944e7f16308253ea31f
[ "MIT" ]
1
2017-08-05T01:25:07.000Z
2017-08-05T01:25:07.000Z
YYOCFramework/Classes/CYUITVDSD_base.h
yanyanforest/YYOCFramework
43279ecf2f1fe024e8c3a944e7f16308253ea31f
[ "MIT" ]
null
null
null
YYOCFramework/Classes/CYUITVDSD_base.h
yanyanforest/YYOCFramework
43279ecf2f1fe024e8c3a944e7f16308253ea31f
[ "MIT" ]
null
null
null
// // CYUITVDSD_base.h // KHMall // // Created by 198 on 16/5/21. // Copyright © 2016年 198. All rights reserved. // #import <Foundation/Foundation.h> #import "CYBlock.h" #define kTableCellDataSourceId @"content" #define kTableSectionDataSourceId @"header" #define kTableSectionSystemTitleDataSourceId @"headerTitle"//系统显示的titles typedef enum CYTableViewCellSelectionType{ CYTableViewCell_SelectionTypeNone, CYTableViewCell_SelectionTypeSingleSelection, CYTableViewCell_SelectionTypeMultipleSelection }CYTableViewCell_SelectionType; @interface CYUITVDSD_base : NSObject<UITableViewDelegate,UITableViewDataSource> @property(nonatomic,strong)UITableView *tableView; @property(nonatomic,strong)CYBlock_Object block_itemSelected; @property(nonatomic,strong)CYBlock_Object block_indexPathSelected; @property(nonatomic,strong)CYBlock_ObjectIndexpath block_itemAtSelectedIndexPath; @property(nonatomic,strong)CYBlock_ObjectIndexpath block_itemDeleteIndexPath; @property(nonatomic,strong)NSString *deleteTitle;//删除的文字 @property(nonatomic,strong)NSDictionary *classesIdbyReusedCells; @property(nonatomic,strong)NSString *reusedCellIdentifier; @property(nonatomic,strong)id object;//tableView的数据[content:[[]]] @property(nonatomic,assign)CYTableViewCell_SelectionType selectionType;//cell的单选或者多选 @property(nonatomic,strong)NSArray *defaultSelected; @property(nonatomic,strong)NSArray *defaultSelectedObject; @property(nonatomic,assign)BOOL showSelectedState; @property(nonatomic,assign)BOOL isForbidEditing;//是否禁止编辑 @property(nonatomic,strong)NSDictionary *classesIdBySupplementView; @property(nonatomic,assign)CGFloat sectionHeaderHeight; @end
43.447368
84
0.84676
[ "object" ]
51020d6397e8e48337fc72602c52753d99635b95
3,326
c
C
lib/makeup_demo/examples/c/example.c
elixir-makeup/makeup_demo
dcb524d8b6b44885ac51486daffa62db3f7b413f
[ "Apache-2.0" ]
null
null
null
lib/makeup_demo/examples/c/example.c
elixir-makeup/makeup_demo
dcb524d8b6b44885ac51486daffa62db3f7b413f
[ "Apache-2.0" ]
null
null
null
lib/makeup_demo/examples/c/example.c
elixir-makeup/makeup_demo
dcb524d8b6b44885ac51486daffa62db3f7b413f
[ "Apache-2.0" ]
null
null
null
#include <string.h> #include <stdlib.h> #include <stdio.h> #include "codegen.h" #include "symboltable.h" #include "stringbuffer.h" extern void yyerror(char* msg); static stringBuffer* staticVariableBuffer; static stringBuffer* classInitBuffer; static stringBuffer* currentMethodBuffer; static stringBuffer* finishedMethodsBuffer; static stringBuffer* mainBuffer; static int currentMethodBufferIndex; static int currentMethodStackSize; static int currentMethodStackSizeMax; static int currentMethodNumberOfLocals; char tempString[MAX_LENGTH_OF_COMMAND]; extern char* className; /* from minako-syntax.y */ /* forward declarations */ static void increaseStackby(int stackdiff); char convertType(int type); void codegenInit() { staticVariableBuffer = newStringBuffer(); classInitBuffer = newStringBuffer(); currentMethodBuffer = 0; finishedMethodsBuffer = newStringBuffer(); mainBuffer = newStringBuffer(); stringBufferAppend(mainBuffer, "; ------- Header --------------------------------------------"); sprintf(tempString, ".class public synchronized %s", className); stringBufferAppend(mainBuffer, tempString); stringBufferAppend(mainBuffer, ".super java/lang/Object"); stringBufferAppend(mainBuffer, "; -----------------------------------------------------------"); stringBufferAppend(mainBuffer, ""); stringBufferAppend(finishedMethodsBuffer, "; ------- Constructor ---------------------------------------"); stringBufferAppend(finishedMethodsBuffer, ".method public <init>()V"); stringBufferAppend(finishedMethodsBuffer, "\t.limit stack 1"); stringBufferAppend(finishedMethodsBuffer, "\t.limit locals 1"); stringBufferAppend(finishedMethodsBuffer, "\taload_0"); stringBufferAppend(finishedMethodsBuffer, "\tinvokenonvirtual java/lang/Object/<init>()V"); stringBufferAppend(finishedMethodsBuffer, "\treturn"); stringBufferAppend(finishedMethodsBuffer, ".end method"); stringBufferAppend(finishedMethodsBuffer, "; -----------------------------------------------------------"); stringBufferAppend(finishedMethodsBuffer, ""); stringBufferAppend(staticVariableBuffer, "; ------- Class Variables -----------------------------------"); stringBufferAppend(classInitBuffer, "; ------- Class Initializer ---------------------------------"); stringBufferAppend(classInitBuffer, ".method static <clinit>()V"); classInitBufferIndex = classInitBuffer->numberOfNextElement; stringBufferAppend(classInitBuffer, "\t.limit locals 0"); } void codegenAppendCommand(char* cmd, int stackdiff) { char tempString[MAX_LENGTH_OF_COMMAND]; sprintf(tempString, "\t%s", cmd); if (global) stringBufferAppend(classInitBuffer, tempString); else stringBufferAppend(currentMethodBuffer, tempString); increaseStackby(stackdiff); } void codegenInsertCommand(int address, char* cmd, int stackdiff) { char tempString[MAX_LENGTH_OF_COMMAND]; sprintf(tempString, "\t%s", cmd); if (global) stringBufferInsert(classInitBuffer, address, tempString); else stringBufferInsert(currentMethodBuffer, address, tempString); increaseStackby(stackdiff); } void codegenAppendLabel(int label) { char tempString[MAX_LENGTH_OF_COMMAND]; sprintf(tempString, "Label%d:", label); if (global) stringBufferAppend(classInitBuffer, tempString); else stringBufferAppend(currentMethodBuffer, tempString); }
39.595238
108
0.718581
[ "object" ]
5103a6b7c6003c57e8d1097867a8598dc8706aae
6,649
c
C
examples/freertos/cifar10/src/model_runner/cifar10_task.c
danielpieczko/xcore_sdk
abb3bdc62d72fa8c13e77f778312ba9f8b29c0f4
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
examples/freertos/cifar10/src/model_runner/cifar10_task.c
danielpieczko/xcore_sdk
abb3bdc62d72fa8c13e77f778312ba9f8b29c0f4
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
examples/freertos/cifar10/src/model_runner/cifar10_task.c
danielpieczko/xcore_sdk
abb3bdc62d72fa8c13e77f778312ba9f8b29c0f4
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
// Copyright 2021 XMOS LIMITED. // This Software is subject to the terms of the XMOS Public Licence: Version 1. #include <platform.h> #include <xs1.h> #include "FreeRTOS.h" #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "fs_support.h" #include "app_conf.h" #include "cifar10_task.h" #include "cifar10_model_data.h" #include "cifar10_model_runner.h" #include "model_runner.h" typedef struct model_runner_args { QueueHandle_t input_queue; rtos_intertile_address_t *intertile_addr; } model_runner_args_t; #define TENSOR_ARENA_SIZE 58000 static int argmax(const int8_t *A, const int N) { int m = 0; for (int i = 1; i < N; i++) { if (A[i] > A[m]) { m = i; } } return m; } static const char *test_input_files[] = { "airplane.bin", "bird.bin", "cat.bin", "deer.bin", "frog.bin", "horse.bin", "truck.bin"}; static void cifar10_task_app(void *args) { rtos_intertile_address_t *adr = (rtos_intertile_address_t *)args; FIL current_file; unsigned int file_size; uint8_t *data = NULL; FRESULT result; unsigned int bytes_read = 0; uint8_t *output_tensor; int output_tensor_len; char classification[12] = {0}; while (1) { for (int i = 0; i < (sizeof(test_input_files) / sizeof(test_input_files[0])); i++) { if (rtos_ff_get_file(test_input_files[i], &current_file, &file_size) == 0) { rtos_printf("Failed to load file %s\n", test_input_files[i]); continue; } data = pvPortMalloc(sizeof(unsigned char) * file_size); configASSERT(data != NULL); /* Failed to allocate memory for file data */ result = f_read(&current_file, data, file_size, &bytes_read); rtos_intertile_tx(adr->intertile_ctx, adr->port, data, file_size); vPortFree(data); output_tensor_len = rtos_intertile_rx(adr->intertile_ctx, adr->port, (void **)&output_tensor, portMAX_DELAY); switch (argmax((int8_t *)output_tensor, 10)) { case 0: rtos_snprintf(classification, 9, "Airplane"); break; case 1: rtos_snprintf(classification, 11, "Automobile"); break; case 2: rtos_snprintf(classification, 5, "Bird"); break; case 3: rtos_snprintf(classification, 4, "Cat"); break; case 4: rtos_snprintf(classification, 5, "Deer"); break; case 5: rtos_snprintf(classification, 4, "Dog"); break; case 6: rtos_snprintf(classification, 5, "Frog"); break; case 7: rtos_snprintf(classification, 6, "Horse"); break; case 8: rtos_snprintf(classification, 5, "Ship"); break; case 9: rtos_snprintf(classification, 6, "Truck"); break; default: break; } rtos_printf("Classification of file %s is %s\n", test_input_files[i], classification); vPortFree(output_tensor); } rtos_printf("All files complete. Repeating in 5 seconds...\n"); vTaskDelay(pdMS_TO_TICKS(5000)); } } static void cifar10_runner_rx(void *args) { model_runner_args_t *targs = (model_runner_args_t *)args; QueueHandle_t q = targs->input_queue; rtos_intertile_address_t *adr = targs->intertile_addr; uint8_t *input_tensor; int input_tensor_len; while (1) { input_tensor_len = rtos_intertile_rx(adr->intertile_ctx, adr->port, (void **)&input_tensor, portMAX_DELAY); xQueueSend(q, &input_tensor, portMAX_DELAY); } } static void cifar10_task_runner(void *args) { model_runner_args_t *targs = (model_runner_args_t *)args; QueueHandle_t q = targs->input_queue; rtos_intertile_address_t *adr = targs->intertile_addr; size_t req_size = 0; uint8_t *interpreter_buf = NULL; int8_t *input_buffer = NULL; size_t input_size = 0; int8_t *output_buffer = NULL; size_t output_size = 0; model_runner_t *model_runner_ctx = NULL; uint8_t *tensor_arena = NULL; uint8_t *input_tensor; dispatcher_t *dispatcher; tensor_arena = pvPortMalloc(TENSOR_ARENA_SIZE); dispatcher = dispatcher_create(); dispatcher_thread_init(dispatcher, appconfDISPATCHER_LENGTH, appconfDISPATCHER_THREAD_COUNT, appconfDISPATCHER_THREAD_PRIORITY); model_runner_init(tensor_arena, TENSOR_ARENA_SIZE); req_size = model_runner_buffer_size_get(); interpreter_buf = pvPortMalloc(req_size); model_runner_ctx = pvPortMalloc(sizeof(model_runner_t)); cifar10_model_runner_create(model_runner_ctx, interpreter_buf); model_runner_dispatcher_create(model_runner_ctx, dispatcher); if (model_runner_allocate(model_runner_ctx, cifar10_model_data) != 0) { rtos_printf("Invalid model provided!\n"); vPortFree(tensor_arena); vPortFree(interpreter_buf); vPortFree(model_runner_ctx); vTaskDelete(NULL); } input_buffer = model_runner_input_buffer_get(model_runner_ctx); input_size = model_runner_input_size_get(model_runner_ctx); output_buffer = model_runner_output_buffer_get(model_runner_ctx); output_size = model_runner_output_size_get(model_runner_ctx); while (1) { rtos_printf("Wait for input tensor...\n"); xQueueReceive(q, &input_tensor, portMAX_DELAY); memcpy(input_buffer, input_tensor, input_size); vPortFree(input_tensor); rtos_printf("Running inference...\n"); model_runner_invoke(model_runner_ctx); model_runner_profiler_summary_print(model_runner_ctx); rtos_intertile_tx(adr->intertile_ctx, adr->port, output_buffer, output_size); } } void cifar10_app_task_create(rtos_intertile_address_t *intertile_addr, unsigned priority) { xTaskCreate((TaskFunction_t)cifar10_task_app, "cifar10", RTOS_THREAD_STACK_SIZE(cifar10_task_app), intertile_addr, priority, NULL); } void cifar10_model_runner_task_create(rtos_intertile_address_t *intertile_addr, unsigned priority) { model_runner_args_t *args = pvPortMalloc(sizeof(model_runner_args_t)); QueueHandle_t input_queue = xQueueCreate(1, sizeof(int32_t *)); configASSERT(args); configASSERT(input_queue); args->input_queue = input_queue; args->intertile_addr = intertile_addr; xTaskCreate((TaskFunction_t)cifar10_task_runner, "cifar10", 500, args, priority, NULL); xTaskCreate((TaskFunction_t)cifar10_runner_rx, "cifar10_rx", RTOS_THREAD_STACK_SIZE(cifar10_runner_rx), args, priority - 1, NULL); }
29.95045
80
0.677846
[ "model" ]
510bfadb7e4e4e972feb93e911bc6d6f709313dd
539
h
C
Graph.h
Eason-Sun/Breadth-First-Search
36164d87af48eacacece6f34cf1f6b9d9d2eab9b
[ "OLDAP-2.6" ]
null
null
null
Graph.h
Eason-Sun/Breadth-First-Search
36164d87af48eacacece6f34cf1f6b9d9d2eab9b
[ "OLDAP-2.6" ]
null
null
null
Graph.h
Eason-Sun/Breadth-First-Search
36164d87af48eacacece6f34cf1f6b9d9d2eab9b
[ "OLDAP-2.6" ]
null
null
null
#ifndef GRAPG_H #define GRAPG_H #include "Vertex.h" #include <map> #include <vector> using namespace std; class Graph { private: map<int, vector<int> > m; vector<Vertex*> vertexVect; int maxId; public: Graph(int); void graphPrinter(); void setM(vector<int>); void configVertexVect(); void updateVertexVect(int dstId); string shortestPath(int, int); void printShortestPath(int, int); }; template <typename T> string ToString(T val); bool isRemoved(char); vector<int> inputParser(string); #endif
17.387097
37
0.690167
[ "vector" ]
5de8873a380e9f7ca0d25a062a0f1219666fccae
202
h
C
src/samples/game/ship.h
opala-studios/ck
dff23ff3912de114ef0c7ca57da6506f0a9bee51
[ "Zlib" ]
23
2020-02-23T23:20:22.000Z
2021-12-30T16:09:23.000Z
src/samples/game/ship.h
opala-studios/ck
dff23ff3912de114ef0c7ca57da6506f0a9bee51
[ "Zlib" ]
3
2020-03-17T05:50:40.000Z
2020-10-12T18:18:44.000Z
src/samples/game/ship.h
opala-studios/ck
dff23ff3912de114ef0c7ca57da6506f0a9bee51
[ "Zlib" ]
10
2020-03-02T15:07:32.000Z
2022-01-29T03:34:55.000Z
#pragma once #include "transform.h" class Ship { public: Ship(); void setTransform(const Vector3& position, float rotationAngle); void draw(); private: Transform m_transform; };
10.1
68
0.668317
[ "transform" ]
5deb4c37a1d602b1c12089c8122df5c3cd990e90
23,779
c
C
examples/common/common.c
iyocode/BHY2-Sensor-API
5b26dc4802f500f75e1086c2a156e3ecf800560c
[ "BSD-3-Clause" ]
10
2020-05-04T11:08:36.000Z
2022-01-24T09:07:08.000Z
examples/common/common.c
iyocode/BHY2-Sensor-API
5b26dc4802f500f75e1086c2a156e3ecf800560c
[ "BSD-3-Clause" ]
2
2022-01-24T09:05:28.000Z
2022-03-14T14:56:40.000Z
examples/common/common.c
iyocode/BHY2-Sensor-API
5b26dc4802f500f75e1086c2a156e3ecf800560c
[ "BSD-3-Clause" ]
3
2021-11-11T00:21:29.000Z
2021-11-25T03:46:12.000Z
/** * Copyright (c) 2020 Bosch Sensortec GmbH. All rights reserved. * * BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @file common.c * @date 24 Mar 2020 * @brief Common source file for the BHI260/BHA260 examples * */ #include "common.h" #include <stdio.h> #include <string.h> #include <stdbool.h> #include <stdlib.h> #include "bhy2_parse.h" #include "bhy2.h" #include "coines.h" #define BHA260_SHUTTLE_ID 0x139 #define BHI260_SHUTTLE_ID 0x119 bool get_interrupt_status(void) { enum coines_pin_direction pin_direction = COINES_PIN_DIRECTION_IN; enum coines_pin_value pin_value = COINES_PIN_VALUE_LOW; coines_get_pin_config(BHY260_INT_PIN, &pin_direction, &pin_value); return (pin_value == COINES_PIN_VALUE_HIGH) ? true : false; } char* get_coines_error(int16_t rslt) { char *ret = " "; switch (rslt) { case COINES_SUCCESS: break; case COINES_E_FAILURE: ret = "[COINES Error] Generic failure"; break; case COINES_E_COMM_IO_ERROR: ret = "[COINES Error] Communication IO failed. Check connections with the sensor"; break; case COINES_E_COMM_INIT_FAILED: ret = "[COINES Error] Communication initialization failed"; break; case COINES_E_UNABLE_OPEN_DEVICE: ret = "[COINES Error] Unable to open device. Check if the board is in use"; break; case COINES_E_DEVICE_NOT_FOUND: ret = "[COINES Error] Device not found. Check if the board is powered on"; break; case COINES_E_UNABLE_CLAIM_INTF: ret = "[COINES Error] Unable to claim interface. Check if the board is in use"; break; case COINES_E_MEMORY_ALLOCATION: ret = "[COINES Error] Error allocating memory"; break; case COINES_E_NOT_SUPPORTED: ret = "[COINES Error] Feature not supported"; break; case COINES_E_NULL_PTR: ret = "[COINES Error] Null pointer error"; break; case COINES_E_COMM_WRONG_RESPONSE: ret = "[COINES Error] Unexpected response"; break; default: ret = "[COINES Error] Unknown error code"; } return ret; } char* get_api_error(int8_t error_code) { char *ret = " "; switch (error_code) { case BHY2_OK: break; case BHY2_E_NULL_PTR: ret = "[API Error] Null pointer"; break; case BHY2_E_INVALID_PARAM: ret = "[API Error] Invalid parameter"; break; case BHY2_E_IO: ret = "[API Error] IO error"; break; case BHY2_E_MAGIC: ret = "[API Error] Invalid firmware"; break; case BHY2_E_TIMEOUT: ret = "[API Error] Timed out"; break; case BHY2_E_BUFFER: ret = "[API Error] Invalid buffer"; break; case BHY2_E_INVALID_FIFO_TYPE: ret = "[API Error] Invalid FIFO type"; break; case BHY2_E_INVALID_EVENT_SIZE: ret = "[API Error] Invalid Event size"; break; case BHY2_E_PARAM_NOT_SET: ret = "[API Error] Parameter not set"; break; default: ret = "[API Error] Unknown API error code"; } return ret; } void setup_interfaces(bool reset_power, enum bhy2_intf intf) { int16_t coines_rslt = coines_open_comm_intf(COINES_COMM_INTF_USB); enum coines_pin_direction pin_direction = COINES_PIN_DIRECTION_IN; enum coines_pin_value pin_value = COINES_PIN_VALUE_LOW; if (coines_rslt) { printf("%s\n", get_coines_error(coines_rslt)); } struct coines_board_info board_info; coines_rslt = coines_get_board_info(&board_info); if (coines_rslt == COINES_SUCCESS) { if (BHA260_SHUTTLE_ID == board_info.shuttle_id) { /*printf("Found BHA260 Shuttle\n"); */ } else if (BHI260_SHUTTLE_ID == board_info.shuttle_id) { /*printf("Found BHI260 Shuttle\n"); */ } else { /*printf("Expecting a BHA260 or BHI260 shuttle\n"); */ } } else { printf("%s\r\n", get_coines_error(coines_rslt)); } if (reset_power) { coines_set_shuttleboard_vdd_vddio_config(0, 0); coines_delay_msec(10); } if (intf == BHY2_SPI_INTERFACE) { coines_config_spi_bus(COINES_SPI_BUS_0, COINES_SPI_SPEED_1_MHZ, COINES_SPI_MODE0); } else { coines_config_i2c_bus(COINES_I2C_BUS_0, COINES_I2C_FAST_MODE); } coines_set_shuttleboard_vdd_vddio_config(1800, 1800); coines_set_pin_config(BHY260_INT_PIN, pin_direction, pin_value); coines_delay_msec(10); } void close_interfaces(void) { coines_close_comm_intf(COINES_COMM_INTF_USB); } int8_t bhy2_spi_read(uint8_t reg_addr, uint8_t *reg_data, uint32_t length, void *intf_ptr) { (void)intf_ptr; return coines_read_spi(BHY260_CS_PIN, reg_addr, reg_data, (uint16_t)length); } int8_t bhy2_spi_write(uint8_t reg_addr, const uint8_t *reg_data, uint32_t length, void *intf_ptr) { (void)intf_ptr; return coines_write_spi(BHY260_CS_PIN, reg_addr, (uint8_t*)reg_data, (uint16_t)length); } int8_t bhy2_i2c_read(uint8_t reg_addr, uint8_t *reg_data, uint32_t length, void *intf_ptr) { (void)intf_ptr; return coines_read_i2c(0x28, reg_addr, reg_data, (uint16_t)length); } int8_t bhy2_i2c_write(uint8_t reg_addr, const uint8_t *reg_data, uint32_t length, void *intf_ptr) { (void)intf_ptr; return coines_write_i2c(0x28, reg_addr, (uint8_t*)reg_data, (uint16_t)length); } void bhy2_delay_us(uint32_t us, void *private_data) { (void)private_data; coines_delay_usec(us); } char* get_sensor_error_text(uint8_t sensor_error) { char *ret; switch (sensor_error) { case 0x00: break; case 0x10: ret = "[Sensor error] Bootloader reports: Firmware Expected Version Mismatch"; break; case 0x11: ret = "[Sensor error] Bootloader reports: Firmware Upload Failed: Bad Header CRC"; break; case 0x12: ret = "[Sensor error] Bootloader reports: Firmware Upload Failed: SHA Hash Mismatch"; break; case 0x13: ret = "[Sensor error] Bootloader reports: Firmware Upload Failed: Bad Image CRC"; break; case 0x14: ret = "[Sensor error] Bootloader reports: Firmware Upload Failed: ECDSA Signature Verification Failed"; break; case 0x15: ret = "[Sensor error] Bootloader reports: Firmware Upload Failed: Bad Public Key CRC"; break; case 0x16: ret = "[Sensor error] Bootloader reports: Firmware Upload Failed: Signed Firmware Required"; break; case 0x17: ret = "[Sensor error] Bootloader reports: Firmware Upload Failed: FW Header Missing"; break; case 0x19: ret = "[Sensor error] Bootloader reports: Unexpected Watchdog Reset"; break; case 0x1A: ret = "[Sensor error] ROM Version Mismatch"; break; case 0x1B: ret = "[Sensor error] Bootloader reports: Fatal Firmware Error"; break; case 0x1C: ret = "[Sensor error] Chained Firmware Error: Next Payload Not Found"; break; case 0x1D: ret = "[Sensor error] Chained Firmware Error: Payload Not Valid"; break; case 0x1E: ret = "[Sensor error] Chained Firmware Error: Payload Entries Invalid"; break; case 0x1F: ret = "[Sensor error] Bootloader reports: Bootloader Error: OTP CRC Invalid"; break; case 0x20: ret = "[Sensor error] Firmware Init Failed"; break; case 0x21: ret = "[Sensor error] Sensor Init Failed: Unexpected Device ID"; break; case 0x22: ret = "[Sensor error] Sensor Init Failed: No Response from Device"; break; case 0x23: ret = "[Sensor error] Sensor Init Failed: Unknown"; break; case 0x24: ret = "[Sensor error] Sensor Error: No Valid Data"; break; case 0x25: ret = "[Sensor error] Slow Sample Rate"; break; case 0x26: ret = "[Sensor error] Data Overflow (saturated sensor data)"; break; case 0x27: ret = "[Sensor error] Stack Overflow"; break; case 0x28: ret = "[Sensor error] Insufficient Free RAM"; break; case 0x29: ret = "[Sensor error] Sensor Init Failed: Driver Parsing Error"; break; case 0x2A: ret = "[Sensor error] Too Many RAM Banks Required"; break; case 0x2B: ret = "[Sensor error] Invalid Event Specified"; break; case 0x2C: ret = "[Sensor error] More than 32 On Change"; break; case 0x2D: ret = "[Sensor error] Firmware Too Large"; break; case 0x2F: ret = "[Sensor error] Invalid RAM Banks"; break; case 0x30: ret = "[Sensor error] Math Error"; break; case 0x40: ret = "[Sensor error] Memory Error"; break; case 0x41: ret = "[Sensor error] SWI3 Error"; break; case 0x42: ret = "[Sensor error] SWI4 Error"; break; case 0x43: ret = "[Sensor error] Illegal Instruction Error"; break; case 0x44: ret = "[Sensor error] Bootloader reports: Unhandled Interrupt Error / Exception / Postmortem Available"; break; case 0x45: ret = "[Sensor error] Invalid Memory Access"; break; case 0x50: ret = "[Sensor error] Algorithm Error: BSX Init"; break; case 0x51: ret = "[Sensor error] Algorithm Error: BSX Do Step"; break; case 0x52: ret = "[Sensor error] Algorithm Error: Update Sub"; break; case 0x53: ret = "[Sensor error] Algorithm Error: Get Sub"; break; case 0x54: ret = "[Sensor error] Algorithm Error: Get Phys"; break; case 0x55: ret = "[Sensor error] Algorithm Error: Unsupported Phys Rate"; break; case 0x56: ret = "[Sensor error] Algorithm Error: Cannot find BSX Driver"; break; case 0x60: ret = "[Sensor error] Sensor Self-Test Failure"; break; case 0x61: ret = "[Sensor error] Sensor Self-Test X Axis Failure"; break; case 0x62: ret = "[Sensor error] Sensor Self-Test Y Axis Failure"; break; case 0x64: ret = "[Sensor error] Sensor Self-Test Z Axis Failure"; break; case 0x65: ret = "[Sensor error] FOC Failure"; break; case 0x66: ret = "[Sensor error] Sensor Busy"; break; case 0x6F: ret = "[Sensor error] Self-Test or FOC Test Unsupported"; break; case 0x72: ret = "[Sensor error] No Host Interrupt Set"; break; case 0x73: ret = "[Sensor error] Event ID Passed to Host Interface Has No Known Size"; break; case 0x75: ret = "[Sensor error] Host Download Channel Underflow (Host Read Too Fast)"; break; case 0x76: ret = "[Sensor error] Host Upload Channel Overflow (Host Wrote Too Fast)"; break; case 0x77: ret = "[Sensor error] Host Download Channel Empty"; break; case 0x78: ret = "[Sensor error] DMA Error"; break; case 0x79: ret = "[Sensor error] Corrupted Input Block Chain"; break; case 0x7A: ret = "[Sensor error] Corrupted Output Block Chain"; break; case 0x7B: ret = "[Sensor error] Buffer Block Manager Error"; break; case 0x7C: ret = "[Sensor error] Input Channel Not Word Aligned"; break; case 0x7D: ret = "[Sensor error] Too Many Flush Events"; break; case 0x7E: ret = "[Sensor error] Unknown Host Channel Error"; break; case 0x81: ret = "[Sensor error] Decimation Too Large"; break; case 0x90: ret = "[Sensor error] Master SPI/I2C Queue Overflow"; break; case 0x91: ret = "[Sensor error] SPI/I2C Callback Error"; break; case 0xA0: ret = "[Sensor error] Timer Scheduling Error"; break; case 0xB0: ret = "[Sensor error] Invalid GPIO for Host IRQ"; break; case 0xB1: ret = "[Sensor error] Error Sending Initialized Meta Events"; break; case 0xC0: ret = "[Sensor error] Bootloader reports: Command Error"; break; case 0xC1: ret = "[Sensor error] Bootloader reports: Command Too Long"; break; case 0xC2: ret = "[Sensor error] Bootloader reports: Command Buffer Overflow"; break; case 0xD0: ret = "[Sensor error] User Mode Error: Sys Call Invalid"; break; case 0xD1: ret = "[Sensor error] User Mode Error: Trap Invalid"; break; case 0xE1: ret = "[Sensor error] Firmware Upload Failed: Firmware header corrupt"; break; case 0xE2: ret = "[Sensor error] Sensor Data Injection: Invalid input stream"; break; default: ret = "[Sensor error] Unknown error code"; } return ret; } char* get_sensor_name(uint8_t sensor_id) { char *ret; switch (sensor_id) { case BHY2_SENSOR_ID_ACC_PASS: ret = "Accelerometer passthrough"; break; case BHY2_SENSOR_ID_ACC_RAW: ret = "Accelerometer uncalibrated"; break; case BHY2_SENSOR_ID_ACC: ret = "Accelerometer corrected"; break; case BHY2_SENSOR_ID_ACC_BIAS: ret = "Accelerometer offset"; break; case BHY2_SENSOR_ID_ACC_WU: ret = "Accelerometer corrected wake up"; break; case BHY2_SENSOR_ID_ACC_RAW_WU: ret = "Accelerometer uncalibrated wake up"; break; case BHY2_SENSOR_ID_GYRO_PASS: ret = "Gyroscope passthrough"; break; case BHY2_SENSOR_ID_GYRO_RAW: ret = "Gyroscope uncalibrated"; break; case BHY2_SENSOR_ID_GYRO: ret = "Gyroscope corrected"; break; case BHY2_SENSOR_ID_GYRO_BIAS: ret = "Gyroscope offset"; break; case BHY2_SENSOR_ID_GYRO_WU: ret = "Gyroscope wake up"; break; case BHY2_SENSOR_ID_GYRO_RAW_WU: ret = "Gyroscope uncalibrated wake up"; break; case BHY2_SENSOR_ID_MAG_PASS: ret = "Magnetometer passthrough"; break; case BHY2_SENSOR_ID_MAG_RAW: ret = "Magnetometer uncalibrated"; break; case BHY2_SENSOR_ID_MAG: ret = "Magnetometer corrected"; break; case BHY2_SENSOR_ID_MAG_BIAS: ret = "Magnetometer offset"; break; case BHY2_SENSOR_ID_MAG_WU: ret = "Magnetometer wake up"; break; case BHY2_SENSOR_ID_MAG_RAW_WU: ret = "Magnetometer uncalibrated wake up"; break; case BHY2_SENSOR_ID_GRA: ret = "Gravity vector"; break; case BHY2_SENSOR_ID_GRA_WU: ret = "Gravity vector wake up"; break; case BHY2_SENSOR_ID_LACC: ret = "Linear acceleration"; break; case BHY2_SENSOR_ID_LACC_WU: ret = "Linear acceleration wake up"; break; case BHY2_SENSOR_ID_RV: ret = "Rotation vector"; break; case BHY2_SENSOR_ID_RV_WU: ret = "Rotation vector wake up"; break; case BHY2_SENSOR_ID_GAMERV: ret = "Game rotation vector"; break; case BHY2_SENSOR_ID_GAMERV_WU: ret = "Game rotation vector wake up"; break; case BHY2_SENSOR_ID_GEORV: ret = "Geo-magnetic rotation vector"; break; case BHY2_SENSOR_ID_GEORV_WU: ret = "Geo-magnetic rotation vector wake up"; break; case BHY2_SENSOR_ID_ORI: ret = "Orientation"; break; case BHY2_SENSOR_ID_ORI_WU: ret = "Orientation wake up"; break; case BHY2_SENSOR_ID_TILT_DETECTOR: ret = "Tilt detector"; break; case BHY2_SENSOR_ID_STD: ret = "Step detector"; break; case BHY2_SENSOR_ID_STC: ret = "Step counter"; break; case BHY2_SENSOR_ID_STC_WU: ret = "Step counter wake up"; break; case BHY2_SENSOR_ID_SIG: ret = "Significant motion"; break; case BHY2_SENSOR_ID_WAKE_GESTURE: ret = "Wake gesture"; break; case BHY2_SENSOR_ID_GLANCE_GESTURE: ret = "Glance gesture"; break; case BHY2_SENSOR_ID_PICKUP_GESTURE: ret = "Pickup gesture"; break; case BHY2_SENSOR_ID_AR: ret = "Activity recognition"; break; case BHY2_SENSOR_ID_WRIST_TILT_GESTURE: ret = "Wrist tilt gesture"; break; case BHY2_SENSOR_ID_DEVICE_ORI: ret = "Device orientation"; break; case BHY2_SENSOR_ID_DEVICE_ORI_WU: ret = "Device orientation wake up"; break; case BHY2_SENSOR_ID_STATIONARY_DET: ret = "Stationary detect"; break; case BHY2_SENSOR_ID_MOTION_DET: ret = "Motion detect"; break; case BHY2_SENSOR_ID_ACC_BIAS_WU: ret = "Accelerometer offset wake up"; break; case BHY2_SENSOR_ID_GYRO_BIAS_WU: ret = "Gyroscope offset wake up"; break; case BHY2_SENSOR_ID_MAG_BIAS_WU: ret = "Magnetometer offset wake up"; break; case BHY2_SENSOR_ID_STD_WU: ret = "Step detector wake up"; break; case BHY2_SENSOR_ID_TEMP: ret = "Temperature"; break; case BHY2_SENSOR_ID_BARO: ret = "Barometer"; break; case BHY2_SENSOR_ID_HUM: ret = "Humidity"; break; case BHY2_SENSOR_ID_GAS: ret = "Gas"; break; case BHY2_SENSOR_ID_TEMP_WU: ret = "Temperature wake up"; break; case BHY2_SENSOR_ID_BARO_WU: ret = "Barometer wake up"; break; case BHY2_SENSOR_ID_HUM_WU: ret = "Humidity wake up"; break; case BHY2_SENSOR_ID_GAS_WU: ret = "Gas wake up"; break; case BHY2_SENSOR_ID_STC_HW: ret = "Hardware Step counter"; break; case BHY2_SENSOR_ID_STD_HW: ret = "Hardware Step detector"; break; case BHY2_SENSOR_ID_SIG_HW: ret = "Hardware Significant motion"; break; case BHY2_SENSOR_ID_STC_HW_WU: ret = "Hardware Step counter wake up"; break; case BHY2_SENSOR_ID_STD_HW_WU: ret = "Hardware Step detector wake up"; break; case BHY2_SENSOR_ID_SIG_HW_WU: ret = "Hardware Significant motion wake up"; break; case BHY2_SENSOR_ID_ANY_MOTION: ret = "Any motion"; break; case BHY2_SENSOR_ID_ANY_MOTION_WU: ret = "Any motion wake up"; break; case BHY2_SENSOR_ID_EXCAMERA: ret = "External camera trigger"; break; case BHY2_SENSOR_ID_GPS: ret = "GPS"; break; case BHY2_SENSOR_ID_LIGHT: ret = "Light"; break; case BHY2_SENSOR_ID_PROX: ret = "Proximity"; break; case BHY2_SENSOR_ID_LIGHT_WU: ret = "Light wake up"; break; case BHY2_SENSOR_ID_PROX_WU: ret = "Proximity wake up"; break; default: if ((sensor_id >= BHY2_SENSOR_ID_CUSTOM_START) && (sensor_id <= BHY2_SENSOR_ID_CUSTOM_END)) { ret = "Custom sensor ID "; } else { ret = "Undefined sensor ID "; } } return ret; }
33.210894
117
0.548257
[ "vector" ]
5df1cd691282d4089f836e7f881b6406fe474d99
8,756
c
C
MultiSource/Benchmarks/MallocBench/gs/gsmatrix.c
gmlueck/llvm-test-suite
7ff842b8fec970561fed78c9347e496538cf74f5
[ "Apache-2.0" ]
70
2019-01-15T03:03:55.000Z
2022-03-28T02:16:13.000Z
MultiSource/Benchmarks/MallocBench/gs/gsmatrix.c
gmlueck/llvm-test-suite
7ff842b8fec970561fed78c9347e496538cf74f5
[ "Apache-2.0" ]
519
2020-09-15T07:40:51.000Z
2022-03-31T20:51:15.000Z
MultiSource/Benchmarks/MallocBench/gs/gsmatrix.c
gmlueck/llvm-test-suite
7ff842b8fec970561fed78c9347e496538cf74f5
[ "Apache-2.0" ]
117
2020-06-24T13:11:04.000Z
2022-03-23T15:44:23.000Z
/* Copyright (C) 1989, 1990 Aladdin Enterprises. All rights reserved. Distributed by Free Software Foundation, Inc. This file is part of Ghostscript. Ghostscript is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. No author or distributor accepts responsibility to anyone for the consequences of using it or for whether it serves any particular purpose or works at all, unless he says so in writing. Refer to the Ghostscript General Public License for full details. Everyone is granted permission to copy, modify and redistribute Ghostscript, but only under the conditions described in the Ghostscript General Public License. A copy of this license is supposed to have been given to you along with Ghostscript so you can know your rights and responsibilities. It should be in a file named COPYING. Among other things, the copyright notice and this notice must be preserved on all copies. */ /* gsmatrix.c */ /* Matrix operators for GhostScript library */ #include "math_.h" #include "gx.h" #include "gserrors.h" #include "gxfixed.h" #include "gxarith.h" #include "gxmatrix.h" /* The identity matrix */ /* This should be private (static), but the interpreter */ /* has to be able to fill in the "unused" words. */ /*static*/ gs_matrix gs_identity_matrix = { identity_matrix_body }; /* ------ Matrix creation ------ */ /* Create an identity matrix */ void gs_make_identity(gs_matrix *pmat) { *pmat = gs_identity_matrix; } /* Create a translation matrix */ int gs_make_translation(floatp dx, floatp dy, register gs_matrix *pmat) { *pmat = gs_identity_matrix; pmat->tx = dx; pmat->ty = dy; return 0; } /* Create a scaling matrix */ int gs_make_scaling(floatp sx, floatp sy, register gs_matrix *pmat) { *pmat = gs_identity_matrix; pmat->xx = sx; pmat->yy = sy; return 0; } /* Create a rotation matrix. */ /* The angle is in degrees. */ int gs_make_rotation(floatp ang, register gs_matrix *pmat) { float theta = ang * (M_PI / 180.0); *pmat = gs_identity_matrix; pmat->xx = pmat->yy = cos(theta); pmat->yx = -(pmat->xy = sin(theta)); return 0; } /* ------ Matrix arithmetic ------ */ /* Multiply two matrices. We should check for floating exceptions, */ /* but for the moment it's just too awkward. */ /* Since this is used heavily, we check for shortcuts. */ int gs_matrix_multiply(gs_matrix *pm1, gs_matrix *pm2, register gs_matrix *pmr) { float xx1 = pm1->xx, yy1 = pm1->yy; float tx1 = pm1->tx, ty1 = pm1->ty; float xx2 = pm2->xx, yy2 = pm2->yy; float xy2 = pm2->xy, yx2 = pm2->yx; if ( !is_skewed(pm1) ) { pmr->tx = tx1 * xx2 + pm2->tx; pmr->ty = ty1 * yy2 + pm2->ty; if ( is_fzero(xy2) ) pmr->xy = 0; else pmr->xy = xx1 * xy2, pmr->ty += tx1 * xy2; pmr->xx = xx1 * xx2; if ( is_fzero(yx2) ) pmr->yx = 0; else pmr->yx = yy1 * yx2, pmr->tx += ty1 * yx2; pmr->yy = yy1 * yy2; } else { pmr->xx = xx1 * xx2 + pm1->xy * yx2; pmr->xy = xx1 * xy2 + pm1->xy * yy2; pmr->yy = pm1->yx * xy2 + yy1 * yy2; pmr->yx = pm1->yx * xx2 + yy1 * yx2; pmr->tx = tx1 * xx2 + ty1 * yx2 + pm2->tx; pmr->ty = tx1 * xy2 + ty1 * yy2 + pm2->ty; } return 0; } /* Invert a matrix. Return gs_error_undefinedresult if not invertible. */ int gs_matrix_invert(register gs_matrix *pm, register gs_matrix *pmr) { /* We have to be careful about fetch/store order, */ /* because pm might be the same as pmr. */ if ( !is_skewed(pm) ) { if ( is_fzero(pm->xx) || is_fzero(pm->yy) ) return_error(gs_error_undefinedresult); pmr->tx = - (pmr->xx = 1.0 / pm->xx) * pm->tx; pmr->xy = 0.0; pmr->yx = 0.0; pmr->ty = - (pmr->yy = 1.0 / pm->yy) * pm->ty; } else { double det = pm->xx * pm->yy - pm->xy * pm->yx; float mxx = pm->xx, mtx = pm->tx; if ( det == 0 ) return_error(gs_error_undefinedresult); pmr->xx = pm->yy / det; pmr->xy = - pm->xy / det; pmr->yx = - pm->yx / det; pmr->yy = mxx / det; /* xx is already changed */ pmr->tx = - (mtx * pmr->xx + pm->ty * pmr->yx); pmr->ty = - (mtx * pmr->xy + pm->ty * pmr->yy); /* tx is already changed */ } return 0; } /* Rotate a matrix, possibly in place. The angle is in degrees. */ int gs_matrix_rotate(register gs_matrix *pm, floatp ang, register gs_matrix *pmr) { float mxx, mxy; int quads; float tsin, tcos; /* We do some special checking for multiples of 90, */ /* so we don't get any rounding errors. */ if ( ang >= -360 && ang <= 360 && ang == (quads = (int)ang / 90) * 90 ) { int isin = 0, icos = 1, t; quads &= 3; while ( quads-- ) t = isin, isin = icos, icos = -t; tsin = isin, tcos = icos; } else { float theta = ang * (M_PI / 180.0); tsin = sin(theta); tcos = cos(theta); } mxx = pm->xx, mxy = pm->xy; pmr->xx = tcos * mxx + tsin * pm->yx; pmr->xy = tcos * mxy + tsin * pm->yy; pmr->yx = tcos * pm->yx - tsin * mxx; pmr->yy = tcos * pm->yy - tsin * mxy; pmr->tx = pm->tx; pmr->ty = pm->ty; return 0; } /* ------ Coordinate transformations (floating point) ------ */ /* Note that all the transformation routines take separate */ /* x and y arguments, but return their result in a point. */ /* Transform a point. */ int gs_point_transform(floatp x, floatp y, register gs_matrix *pmat, register gs_point *ppt) { ppt->x = x * pmat->xx + pmat->tx; ppt->y = y * pmat->yy + pmat->ty; if ( !is_fzero(pmat->yx) ) ppt->x += y * pmat->yx; if ( !is_fzero(pmat->xy) ) ppt->y += x * pmat->xy; return 0; } /* Inverse-transform a point. */ /* Return gs_error_undefinedresult if the matrix is not invertible. */ int gs_point_transform_inverse(floatp x, floatp y, register gs_matrix *pmat, register gs_point *ppt) { if ( !is_skewed(pmat) ) { ppt->x = (x - pmat->tx) / pmat->xx; ppt->y = (y - pmat->ty) / pmat->yy; return 0; } else { /* There are faster ways to do this, */ /* but we won't implement one unless we have to. */ gs_matrix imat; int code = gs_matrix_invert(pmat, &imat); if ( code < 0 ) return code; return gs_point_transform(x, y, &imat, ppt); } } /* Transform a distance. */ int gs_distance_transform(floatp dx, floatp dy, register gs_matrix *pmat, register gs_point *pdpt) { pdpt->x = dx * pmat->xx; pdpt->y = dy * pmat->yy; if ( !is_fzero(pmat->yx) ) pdpt->x += dy * pmat->yx; if ( !is_fzero(pmat->xy) ) pdpt->y += dx * pmat->xy; return 0; } /* Inverse-transform a distance. */ /* Return gs_error_undefinedresult if the matrix is not invertible. */ int gs_distance_transform_inverse(floatp dx, floatp dy, register gs_matrix *pmat, register gs_point *pdpt) { if ( !is_skewed(pmat) ) { pdpt->x = dx / pmat->xx; pdpt->y = dy / pmat->yy; } else { double det = pmat->xx * pmat->yy - pmat->xy * pmat->yx; if ( det == 0 ) return_error(gs_error_undefinedresult); pdpt->x = (dx * pmat->yy - dy * pmat->yx) / det; pdpt->y = (dy * pmat->xx - dx * pmat->xy) / det; } return 0; } /* Inverse-transform a bounding box. */ /* Return gs_error_undefinedresult if the matrix is not invertible. */ int gs_bbox_transform_inverse(gs_rect *pbox_in, gs_matrix *pmat, gs_rect *pbox_out) { int code; gs_point p, w, h; float xmin, ymin, xmax, ymax; /* We must recompute the max and min after transforming, */ /* since a rotation may be involved. */ if ( (code = gs_point_transform_inverse(pbox_in->p.x, pbox_in->p.y, pmat, &p)) < 0 || (code = gs_distance_transform_inverse((float)(pbox_in->q.x - pbox_in->p.x), 0.0, pmat, &w)) < 0 || (code = gs_distance_transform_inverse(0.0, (float)(pbox_in->q.y - pbox_in->p.y), pmat, &h)) < 0 ) return code; xmin = xmax = p.x; if ( w.x < 0 ) xmin += w.x; else xmax += w.x; if ( h.x < 0 ) xmin += h.x; else xmax += h.x; ymin = ymax = p.y; if ( w.y < 0 ) ymin += w.y; else ymax += w.y; if ( h.y < 0 ) ymin += h.y; else ymax += h.y; pbox_out->p.x = xmin, pbox_out->p.y = ymin; pbox_out->q.x = xmax, pbox_out->q.y = ymax; return 0; } /* ------ Coordinate transformations (to fixed point) ------ */ /* Transform a point with a fixed-point result. */ int gs_point_transform2fixed(register gs_matrix_fixed *pmat, floatp x, floatp y, gs_fixed_point *ppt) { ppt->x = float2fixed(x * pmat->xx) + pmat->tx_fixed; ppt->y = float2fixed(y * pmat->yy) + pmat->ty_fixed; if ( !is_fzero(pmat->yx) ) ppt->x += float2fixed(y * pmat->yx); if ( !is_fzero(pmat->xy) ) ppt->y += float2fixed(x * pmat->xy); return 0; } /* Transform a distance with a fixed-point result. */ int gs_distance_transform2fixed(register gs_matrix_fixed *pmat, floatp dx, floatp dy, gs_fixed_point *ppt) { ppt->x = float2fixed(dx * pmat->xx); ppt->y = float2fixed(dy * pmat->yy); if ( !is_fzero(pmat->yx) ) ppt->x += float2fixed(dy * pmat->yx); if ( !is_fzero(pmat->xy) ) ppt->y += float2fixed(dx * pmat->xy); return 0; }
29.782313
100
0.63328
[ "transform" ]
5df21e0880de4b8d323294f027d937ab324e3984
3,136
h
C
lib/OTExtensionEncrypto/extern/ENCRYPTO_utils/src/ENCRYPTO_utils/parse_options.h
cryptobiu/libscapi
49eee7aee9eb3544a7facb199d0a6e98097b058a
[ "MIT" ]
160
2016-05-11T09:45:56.000Z
2022-03-06T09:32:19.000Z
ABY/extern/OTExtension/extern/ENCRYPTO_utils/src/ENCRYPTO_utils/parse_options.h
encryptogroup/VASA
828a6a7e07e5089b9185b677d6c5ae7fb97c7ec2
[ "MIT" ]
57
2016-12-26T07:02:12.000Z
2022-03-06T16:34:31.000Z
ABY/extern/OTExtension/extern/ENCRYPTO_utils/src/ENCRYPTO_utils/parse_options.h
encryptogroup/VASA
828a6a7e07e5089b9185b677d6c5ae7fb97c7ec2
[ "MIT" ]
67
2016-10-10T17:56:22.000Z
2022-03-15T22:56:39.000Z
/** \file parse_options.h \author michael.zohner@ec-spride.de \copyright ABY - A Framework for Efficient Mixed-protocol Secure Two-party Computation Copyright (C) 2019 ENCRYPTO Group, TU Darmstadt This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ABY is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. \brief Parse Options Implementation */ #ifndef UTIL_PARSE_OPTIONS_H_ #define UTIL_PARSE_OPTIONS_H_ #include <cstdint> #include <string> #include <vector> /** \enum etype \brief Data types for command line parameters */ enum etype { T_NUM, //uint32_t number T_STR, //string T_FLAG, //boolean flag T_DOUBLE //double number }; /** \struct parsing_ctx \brief holds information about parameters that should be parsed in the command line input */ struct parsing_ctx { void* val; //value of the option, is written into by parse_options etype type; //type of value std::string opt_name; //name to set the parameter via command line std::string help_str; //definition of the parameter that is printed in print_usage bool required; //is the parameter required to run the program? If required and not set by the invocation, program will exit bool set; //has the value for the parameter been set previously? In case the parameter is read, this will be set to true }; /** This method parses the command line arguments from a C program, given in argcp and argcv, using the flags and parameters specified in options where nops gives the number of parameters that are parsed. The values for the parameters are written into options. \param argcp - Pointer to argc \param argvp - Pointer to argv \param options - A list of parameters that the command line input should be parsed for \param nops - Number of parameters in options \return 0 if the command line string was faulty and 1 otherwise. */ int32_t parse_options(int32_t* argcp, char*** argvp, parsing_ctx* options, uint32_t nops); /** This method prints the command line parameters together with a short help description in help_str \param progname - Name of the program \param options - Parameters that should be printed \param nops - Number of parameters in options */ void print_usage(std::string progname, parsing_ctx* options, uint32_t nops); void tokenize(const std::string& str, std::vector<uint32_t>& tokens, const std::string& delimiters = "| \t"); void tokenize_verilog(const std::string& str, std::vector<uint32_t>& tokens, const std::string& delimiters = " \t"); #endif /* PARSE_OPTIONS_H_ */
40.727273
131
0.735969
[ "vector" ]
b9006690a995f1e9e18f2de3ba72faa8221d2836
2,358
h
C
src/planner/planners/MatchVertexIndexSeekPlanner.h
critical27/nebula-graph
04d00e779e860ed3ddb226c416c335a22acc1147
[ "Apache-2.0" ]
null
null
null
src/planner/planners/MatchVertexIndexSeekPlanner.h
critical27/nebula-graph
04d00e779e860ed3ddb226c416c335a22acc1147
[ "Apache-2.0" ]
null
null
null
src/planner/planners/MatchVertexIndexSeekPlanner.h
critical27/nebula-graph
04d00e779e860ed3ddb226c416c335a22acc1147
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #ifndef PLANNER_PLANNERS_MATCHVERTEXINDEXSEEKPLANNER_H_ #define PLANNER_PLANNERS_MATCHVERTEXINDEXSEEKPLANNER_H_ #include "common/expression/LabelExpression.h" #include "context/QueryContext.h" #include "planner/Planner.h" #include "validator/MatchValidator.h" namespace nebula { namespace graph { class MatchVertexIndexSeekPlanner final : public Planner { public: static std::unique_ptr<MatchVertexIndexSeekPlanner> make() { return std::unique_ptr<MatchVertexIndexSeekPlanner>(new MatchVertexIndexSeekPlanner()); } static bool match(AstContext* astCtx); StatusOr<SubPlan> transform(AstContext* astCtx) override; private: using VertexProp = nebula::storage::cpp2::VertexProp; using EdgeProp = nebula::storage::cpp2::EdgeProp; static Expression* makeIndexFilter(const std::string& label, const MapExpression* map, QueryContext* qctx); static Expression* makeIndexFilter(const std::string& label, const std::string& alias, const Expression* filter, QueryContext* qctx); MatchVertexIndexSeekPlanner() = default; Status buildScanNode(); Status buildSteps(); Status buildStep(); Status buildGetTailVertices(); Status buildStepJoin(); Status buildTailJoin(); Status buildFilter(); template <typename T> T* saveObject(T *obj) const { return matchCtx_->qctx->objPool()->add(obj); } SubPlan subPlan_; MatchAstContext *matchCtx_; bool startFromNode_{true}; int32_t startIndex_{0}; int32_t curStep_{-1}; PlanNode *thisStepRoot_{nullptr}; PlanNode *prevStepRoot_{nullptr}; Expression *gnSrcExpr_{nullptr}; }; } // namespace graph } // namespace nebula #endif
32.30137
95
0.588634
[ "transform" ]
b903f264b8f92e6b839004c460975b748f222e74
44,983
c
C
netbsdsrc/sys/arch/pmax/pmax/machdep.c
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
netbsdsrc/sys/arch/pmax/pmax/machdep.c
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
netbsdsrc/sys/arch/pmax/pmax/machdep.c
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
/* $NetBSD: machdep.c,v 1.99 1997/10/18 19:48:02 mhitch Exp $ */ /* * Copyright (c) 1988 University of Utah. * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * the Systems Programming Group of the University of Utah Computer * Science Department, The Mach Operating System project at * Carnegie-Mellon University and Ralph Campbell. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)machdep.c 8.3 (Berkeley) 1/12/94 */ #include <sys/cdefs.h> /* RCS ID & Copyright macro defns */ __KERNEL_RCSID(0, "$NetBSD: machdep.c,v 1.99 1997/10/18 19:48:02 mhitch Exp $"); /* from: Utah Hdr: machdep.c 1.63 91/04/24 */ #include <sys/param.h> #include <sys/systm.h> #include <sys/signalvar.h> #include <sys/kernel.h> #include <sys/map.h> #include <sys/proc.h> #include <sys/buf.h> #include <sys/reboot.h> #include <sys/conf.h> #include <sys/file.h> #include <sys/clist.h> #include <sys/callout.h> #include <sys/malloc.h> #include <sys/mbuf.h> #include <sys/msgbuf.h> #include <sys/ioctl.h> #include <sys/tty.h> #include <sys/device.h> #include <sys/user.h> #include <sys/exec.h> #include <vm/vm.h> #include <sys/sysctl.h> #include <sys/mount.h> #include <sys/syscallargs.h> #ifdef SYSVMSG #include <sys/msg.h> #endif #ifdef SYSVSEM #include <sys/sem.h> #endif #ifdef SYSVSHM #include <sys/shm.h> #endif #include <vm/vm_kern.h> #include <ufs/mfs/mfs_extern.h> /* mfs_initminiroot() */ #include <machine/cpu.h> #include <machine/reg.h> #include <machine/psl.h> #include <machine/pte.h> #include <machine/autoconf.h> #include <mips/locore.h> /* wbflush() */ #include <mips/mips/mips_mcclock.h> /* mclock CPU setimation */ #ifdef DDB #include <mips/db_machdep.h> #endif #include <pmax/stand/dec_prom.h> #include <pmax/dev/ascreg.h> #include <pmax/pmax/clockreg.h> #include <pmax/pmax/kn01.h> #include <pmax/pmax/kn02.h> #include <pmax/pmax/kmin.h> #include <pmax/pmax/maxine.h> #include <pmax/pmax/kn03.h> #include <pmax/pmax/asic.h> #include <pmax/pmax/turbochannel.h> #include <pmax/pmax/pmaxtype.h> #include <pmax/pmax/trap.h> /* mboard-specific interrupt fns */ #include <pmax/pmax/cons.h> #include "pm.h" #include "cfb.h" #include "mfb.h" #include "xcfb.h" #include "sfb.h" #include "dtop.h" #include "scc.h" #include "le_ioasic.h" #include "asc.h" extern struct consdev *cn_tab; /* Console I/O table... */ extern struct consdev cd; #if defined(DS5000_25) || defined(DS5000_100) || defined(DS5000_240) /* Will scan from max to min, inclusive */ static int tc_max_slot = KN02_TC_MAX; static int tc_min_slot = KN02_TC_MIN; static u_int tc_slot_phys_base [TC_MAX_SLOTS] = { /* use 3max for default values */ KN02_PHYS_TC_0_START, KN02_PHYS_TC_1_START, KN02_PHYS_TC_2_START, KN02_PHYS_TC_3_START, KN02_PHYS_TC_4_START, KN02_PHYS_TC_5_START, KN02_PHYS_TC_6_START, KN02_PHYS_TC_7_START }; #endif /* the following is used externally (sysctl_hw) */ char machine[] = MACHINE; /* from <machine/param.h> */ char cpu_model[30]; vm_map_t buffer_map; /* * Declare these as initialized data so we can patch them. */ int nswbuf = 0; #ifdef NBUF int nbuf = NBUF; #else int nbuf = 0; #endif #ifdef BUFPAGES int bufpages = BUFPAGES; #else int bufpages = 0; #endif caddr_t msgbufaddr; int msgbufmapped = 0; /* set when safe to use msgbuf */ int maxmem; /* max memory per process */ int physmem; /* max supported memory, changes to actual */ int physmem_boardmax; /* {model,simm}-specific bound on physmem */ int pmax_boardtype; /* Mother board type */ u_long le_iomem; /* 128K for lance chip via. ASIC */ #ifdef ASC_IOASIC_BOUNCE u_long asc_iomem; /* and 7 * 8K buffers for the scsi */ #endif u_long ioasic_base; /* Base address of I/O asic */ const struct callback *callv; /* pointer to PROM entry points */ extern void (*tc_enable_interrupt) __P ((u_int slotno, int (*handler) __P((void *sc)), void *sc, int onoff)); void (*tc_enable_interrupt) __P ((u_int slotno, int (*handler) __P ((void *sc)), void *sc, int onoff)); #ifdef DS3100 #include <pmax/pmax/kn01var.h> void kn01_enable_intr __P ((u_int slotno, int (*handler) __P ((intr_arg_t sc)), intr_arg_t sc, int onoff)); #endif /* DS3100 */ #ifdef DS5100 /* mipsmate */ # include <pmax/pmax/kn230var.h> /* kn230_establish_intr(), kn230_intr() */ #endif /* * Interrupt-blocking functions defined in locore. These names aren't used * directly except here and in interrupt handlers. */ /* Block out one hardware interrupt-enable bit. */ extern int Mach_spl0 __P((void)), Mach_spl1 __P((void)); extern int Mach_spl2 __P((void)), Mach_spl3 __P((void)); /* Block out nested interrupt-enable bits. */ extern int cpu_spl0 __P((void)), cpu_spl1 __P((void)); extern int cpu_spl2 __P((void)), cpu_spl3 __P((void)); extern int splhigh __P((void)); /* * Instead, we declare the standard splXXX names as function pointers, * and initialie them to point to the above functions to match * the way a specific motherboard is wired up. */ int (*Mach_splbio) __P((void)) = splhigh; int (*Mach_splnet)__P((void)) = splhigh; int (*Mach_spltty)__P((void)) = splhigh; int (*Mach_splimp)__P((void)) = splhigh; int (*Mach_splclock)__P((void)) = splhigh; int (*Mach_splstatclock)__P((void)) = splhigh; volatile struct chiptime *mcclock_addr; u_long kmin_tc3_imask, xine_tc3_imask; int savectx __P((struct user *up)); /* XXX save state b4 crash*/ tc_option_t tc_slot_info[TC_MAX_LOGICAL_SLOTS]; /* * Local functions. */ #ifdef DS5000_240 /* XXX */ static void asic_init __P((int isa_maxine)); #endif extern int atoi __P((const char *cp)); int initcpu __P((void)); #if defined(DS5000_240) || defined(DS5000_25) static u_long clkread __P((void)); /* get usec-resolution clock */ #endif void dumpsys __P((void)); /* do a dump */ /* initialize bss, etc. from kernel start, before main() is called. */ extern void mach_init __P((int argc, char *argv[], u_int code, const struct callback *cv)); #ifdef DS5000_200 void kn02_enable_intr __P ((u_int slotno, int (*handler) __P((intr_arg_t sc)), intr_arg_t sc, int onoff)); #endif /*DS5000_200*/ #ifdef DS5000_100 void kmin_enable_intr __P ((u_int slotno, int (*handler) (intr_arg_t sc), intr_arg_t sc, int onoff)); void kmin_mcclock_cpuspeed __P((volatile struct chiptime *mcclock_addr, int clockmask)); #endif /*DS5000_100*/ #ifdef DS5000_25 void xine_enable_intr __P ((u_int slotno, int (*handler) (intr_arg_t sc), intr_arg_t sc, int onoff)); #endif /*DS5000_25*/ #ifdef DS5000_240 u_long kn03_tc3_imask; void kn03_tc_reset __P((void)); /* XXX unused? */ void kn03_enable_intr __P ((u_int slotno, int (*handler) (intr_arg_t sc), intr_arg_t sc, int onoff)); #endif /*DS5000_240*/ #if defined(DS5000_200) || defined(DS5000_25) || defined(DS5000_100) || \ defined(DS5000_240) volatile u_int *Mach_reset_addr; #endif /* DS5000_200 || DS5000_25 || DS5000_100 || DS5000_240 */ void prom_halt __P((int, char *)) __attribute__((__noreturn__)); #ifdef DEBUG /* stacktrace code violates prototypes to get callee's registers */ extern void stacktrace __P((void)); /*XXX*/ #endif extern caddr_t esym; void ddb_init(void); /* * safepri is a safe priority for sleep to set for a spin-wait * during autoconfiguration or after a panic. Used as an argument to splx(). * XXX disables interrupt 5 to disable mips3 on-chip clock, which also * disables mips1 FPU interrupts. */ int safepri = MIPS3_PSL_LOWIPL; /* XXX */ struct user *proc0paddr; struct proc nullproc; /* for use by switch_exit() */ /* locore callback-vector setup */ extern void mips_vector_init __P((void)); /* * Do all the stuff that locore normally does before calling main(). * Process arguments passed to us by the prom monitor. * Return the first page address following the system. */ void mach_init(argc, argv, code, cv) int argc; char *argv[]; u_int code; const struct callback *cv; { register char *cp; register int i; register unsigned firstaddr; register caddr_t v; caddr_t start; extern char edata[], end[]; /* clear the BSS segment */ #ifdef DDB if (((struct exec *)edata)->a_midmag == 0x07018b00 && /* exec hdr? */ (i = ((struct exec *)edata)->a_syms) != 0) { /* a_syms */ *(long *)end = i; i += (*(long *)(end + i + 4) + 3) & ~3; /* strings */ esym = end + i + 4; v = (caddr_t)mips_round_page(esym); bzero(edata, end - edata); } else #endif { v = (caddr_t)mips_round_page(end); bzero(edata, v - edata); } /* Initialize callv so we can do PROM output... */ if (code == DEC_PROM_MAGIC) { callv = cv; } else { callv = &callvec; } /* Use PROM console output until we initialize a console driver. */ cn_tab = &cd; /* check for direct boot from DS5000 PROM */ if (argc > 0 && strcmp(argv[0], "boot") == 0) { argc--; argv++; } /* * Copy exception-dispatch code down to exception vector. * Initialize locore-function vector. * Clear out the I and D caches. */ mips_vector_init(); #ifdef DDB /* * Initialize machine-dependent DDB commands, in case of early panic. */ db_machine_init(); if (esym) ddb_init(); /* init symbols if present */ #endif /* look at argv[0] and compute bootdev */ makebootdev(argv[0]); /* * Look at arguments passed to us and compute boothowto. */ boothowto = RB_SINGLE; #ifdef KADB boothowto |= RB_KDB; #endif if (argc > 1) { for (i = 1; i < argc; i++) { for (cp = argv[i]; *cp; cp++) { switch (*cp) { case 'a': /* autoboot */ boothowto &= ~RB_SINGLE; break; case 'd': /* use compiled in default root */ boothowto |= RB_DFLTROOT; break; case 'm': /* mini root present in memory */ boothowto |= RB_MINIROOT; break; case 'n': /* ask for names */ boothowto |= RB_ASKNAME; break; case 'N': /* don't ask for names */ boothowto &= ~RB_ASKNAME; } } } } #ifdef MFS /* * Check to see if a mini-root was loaded into memory. It resides * at the start of the next page just after the end of BSS. */ if (boothowto & RB_MINIROOT) { boothowto |= RB_DFLTROOT; v += mfs_initminiroot(v); } #endif /* * Init mapping for u page(s) for proc[0], pm_tlbpid 1. */ start = v; proc0.p_addr = proc0paddr = (struct user *)v; curpcb = (struct pcb *)proc0.p_addr; proc0.p_md.md_regs = proc0paddr->u_pcb.pcb_regs; firstaddr = MIPS_KSEG0_TO_PHYS(v); if (CPUISMIPS3) for (i = 0; i < UPAGES; i+=2) { struct tlb tlb; tlb.tlb_mask = MIPS3_PG_SIZE_4K; tlb.tlb_hi = mips3_vad_to_vpn((UADDR + (i << PGSHIFT))) | 1; tlb.tlb_lo0 = vad_to_pfn(firstaddr) | MIPS3_PG_V | MIPS3_PG_M | MIPS3_PG_CACHED; tlb.tlb_lo1 = vad_to_pfn(firstaddr + NBPG) | MIPS3_PG_V | MIPS3_PG_M | MIPS3_PG_CACHED; proc0.p_md.md_upte[i] = tlb.tlb_lo0; proc0.p_md.md_upte[i+1] = tlb.tlb_lo1; mips3_TLBWriteIndexedVPS(i,&tlb); firstaddr += NBPG * 2; } else for (i = 0; i < UPAGES; i++) { mips1_TLBWriteIndexed(i, (UADDR + (i << PGSHIFT)) | (1 << MIPS1_TLB_PID_SHIFT), proc0.p_md.md_upte[i] = firstaddr | MIPS1_PG_V | MIPS1_PG_M); firstaddr += NBPG; } v += UPAGES * NBPG; MachSetPID(1); /* * init nullproc for switch_exit(). * init mapping for u page(s), pm_tlbpid 0 * This could be used for an idle process. */ nullproc.p_addr = (struct user *)v; nullproc.p_md.md_regs = nullproc.p_addr->u_pcb.pcb_regs; bcopy("nullproc", nullproc.p_comm, sizeof("nullproc")); if (CPUISMIPS3) { /* mips3 */ for (i = 0; i < UPAGES; i+=2) { nullproc.p_md.md_upte[i] = vad_to_pfn(firstaddr) | MIPS3_PG_V | MIPS3_PG_M | MIPS3_PG_CACHED; nullproc.p_md.md_upte[i+1] = vad_to_pfn(firstaddr + NBPG) | MIPS3_PG_V | MIPS3_PG_M | MIPS3_PG_CACHED; firstaddr += NBPG * 2; } } else { /* mips1 */ for (i = 0; i < UPAGES; i++) { nullproc.p_md.md_upte[i] = firstaddr | MIPS1_PG_V | MIPS1_PG_M; firstaddr += NBPG; } } v += UPAGES * NBPG; /* clear pages for u areas */ bzero(start, v - start); if (CPUISMIPS3) { mips3_FlushDCache(MIPS_KSEG0_TO_PHYS(start), v - start); mips3_HitFlushDCache(UADDR, UPAGES * NBPG); } /* * Determine what model of computer we are running on. */ if (code == DEC_PROM_MAGIC) { i = (*cv->_getsysid)(); cp = ""; } else { cp = (*callv->_getenv)("systype"); if (cp) i = atoi(cp); else { cp = ""; i = 0; } } /* check for MIPS based platform */ /* 0x82 -> MIPS1, 0x84 -> MIPS3 */ if (((i >> 24) & 0xFF) != 0x82 && ((i >> 24) & 0xff) != 0x84) { printf("Unknown System type '%s' 0x%x\n", cp, i); cpu_reboot(RB_HALT | RB_NOSYNC, NULL); } /* * Initialize physmem_boardmax; assume no SIMM-bank limits. * Adjst later in model-specific code if necessary. */ physmem_boardmax = MIPS_MAX_MEM_ADDR; /* check what model platform we are running on */ pmax_boardtype = ((i >> 16) & 0xff); switch (pmax_boardtype) { #ifdef DS3100 case DS_PMAX: /* DS3100 Pmax */ /* * Set up interrupt handling and I/O addresses. */ mips_hardware_intr = kn01_intr; tc_enable_interrupt = kn01_enable_intr; /*XXX*/ Mach_splbio = cpu_spl0; Mach_splnet = cpu_spl1; Mach_spltty = cpu_spl2; Mach_splimp = splhigh; /*XXX Mach_spl1(), if not for malloc()*/ Mach_splclock = cpu_spl3; Mach_splstatclock = cpu_spl3; mcclock_addr = (volatile struct chiptime *) MIPS_PHYS_TO_KSEG1(KN01_SYS_CLOCK); mc_cpuspeed(mcclock_addr, MIPS_INT_MASK_3); strcpy(cpu_model, "3100"); break; #endif /* DS3100 */ #ifdef DS5100 case DS_MIPSMATE: /* DS5100 aka mipsmate aka kn230 */ /* XXX just a guess */ /* * Set up interrupt handling and I/O addresses. */ mips_hardware_intr = kn230_intr; tc_enable_interrupt = kn01_enable_intr; /*XXX*/ Mach_splbio = Mach_spl0; Mach_splnet = Mach_spl1; Mach_spltty = Mach_spl2; Mach_splimp = Mach_spl2; Mach_splclock = Mach_spl3; Mach_splstatclock = Mach_spl3; mcclock_addr = (volatile struct chiptime *) MIPS_PHYS_TO_KSEG1(KN01_SYS_CLOCK); strcpy(cpu_model, "5100"); break; #endif /* DS5100 */ #ifdef DS5000_200 case DS_3MAX: /* DS5000/200 3max */ { volatile int *csr_addr = (volatile int *)MIPS_PHYS_TO_KSEG1(KN02_SYS_CSR); Mach_reset_addr = (unsigned *)MIPS_PHYS_TO_KSEG1(KN02_SYS_ERRADR); /* clear any memory errors from new-config probes */ *Mach_reset_addr = 0; /* * Enable ECC memory correction, turn off LEDs, and * disable all TURBOchannel interrupts. */ i = *csr_addr; *csr_addr = (i & ~(KN02_CSR_WRESERVED | KN02_CSR_IOINTEN)) | KN02_CSR_CORRECT | 0xff; mips_hardware_intr = kn02_intr; tc_enable_interrupt = kn02_enable_intr; Mach_splbio = Mach_spl0; Mach_splnet = Mach_spl0; Mach_spltty = Mach_spl0; Mach_splimp = Mach_spl0; Mach_splclock = cpu_spl1; Mach_splstatclock = cpu_spl1; mcclock_addr = (volatile struct chiptime *) MIPS_PHYS_TO_KSEG1(KN02_SYS_CLOCK); } mc_cpuspeed(mcclock_addr, MIPS_INT_MASK_1); strcpy(cpu_model, "5000/200"); break; #endif /* DS5000_200 */ #ifdef DS5000_100 case DS_3MIN: /* DS5000/1xx 3min */ tc_max_slot = KMIN_TC_MAX; tc_min_slot = KMIN_TC_MIN; tc_slot_phys_base[0] = KMIN_PHYS_TC_0_START; tc_slot_phys_base[1] = KMIN_PHYS_TC_1_START; tc_slot_phys_base[2] = KMIN_PHYS_TC_2_START; ioasic_base = MIPS_PHYS_TO_KSEG1(KMIN_SYS_ASIC); mips_hardware_intr = kmin_intr; tc_enable_interrupt = kmin_enable_intr; kmin_tc3_imask = (KMIN_INTR_CLOCK | KMIN_INTR_PSWARN | KMIN_INTR_TIMEOUT); /* * Since all the motherboard interrupts come through the * I/O ASIC, it has to be turned off for all the spls and * since we don't know what kinds of devices are in the * turbochannel option slots, just splhigh(). */ Mach_splbio = splhigh; Mach_splnet = splhigh; Mach_spltty = splhigh; Mach_splimp = splhigh; Mach_splclock = splhigh; Mach_splstatclock = splhigh; mcclock_addr = (volatile struct chiptime *) MIPS_PHYS_TO_KSEG1(KMIN_SYS_CLOCK); kmin_mcclock_cpuspeed(mcclock_addr, MIPS_INT_MASK_3); /* * Initialize interrupts. */ *(u_int *)IOASIC_REG_IMSK(ioasic_base) = KMIN_IM0; *(u_int *)IOASIC_REG_INTR(ioasic_base) = 0; /* clear any memory errors from probes */ Mach_reset_addr = (u_int*)MIPS_PHYS_TO_KSEG1(KMIN_REG_TIMEOUT); (*Mach_reset_addr) = 0; sprintf(cpu_model, "5000/1%d", cpu_mhz); /* * The kmin memory hardware seems to wrap memory addresses * with 4Mbyte SIMMs, which causes the physmem computation * to lose. Find out how big the SIMMS are and set * max_ physmem accordingly. * XXX Do MAXINEs lose the same way? */ physmem_boardmax = KMIN_PHYS_MEMORY_END + 1; if ((*(int*)(MIPS_PHYS_TO_KSEG1(KMIN_REG_MSR)) & KMIN_MSR_SIZE_16Mb) == 0) physmem_boardmax = physmem_boardmax >> 2; physmem_boardmax = MIPS_PHYS_TO_KSEG1(physmem_boardmax); break; #endif /* ds5000_100 */ #ifdef DS5000_25 case DS_MAXINE: /* DS5000/xx maxine */ tc_max_slot = XINE_TC_MAX; tc_min_slot = XINE_TC_MIN; tc_slot_phys_base[0] = XINE_PHYS_TC_0_START; tc_slot_phys_base[1] = XINE_PHYS_TC_1_START; ioasic_base = MIPS_PHYS_TO_KSEG1(XINE_SYS_ASIC); mips_hardware_intr = xine_intr; tc_enable_interrupt = xine_enable_intr; /* On the MAXINE ioasic interrupts at level 3. */ Mach_splbio = Mach_spl3; Mach_splnet = Mach_spl3; Mach_spltty = Mach_spl3; Mach_splimp = Mach_spl3; /* * Note priority inversion of ioasic and clock: * clock interrupts are at hw priority 1, and when blocking * clock interrups we we must block hw priority 3 * (bio,net,tty) also. * * XXX hw priority 2 is used for memory errors, we * should not disable memory errors during clock interrupts! */ Mach_splclock = cpu_spl3; Mach_splstatclock = cpu_spl3; mcclock_addr = (volatile struct chiptime *) MIPS_PHYS_TO_KSEG1(XINE_SYS_CLOCK); mc_cpuspeed(mcclock_addr, MIPS_INT_MASK_1); /* * Initialize interrupts. */ *(u_int *)IOASIC_REG_IMSK(ioasic_base) = XINE_IM0; *(u_int *)IOASIC_REG_INTR(ioasic_base) = 0; /* clear any memory errors from probes */ Mach_reset_addr = (u_int*)MIPS_PHYS_TO_KSEG1(XINE_REG_TIMEOUT); (*Mach_reset_addr) = 0; sprintf(cpu_model, "5000/%d", cpu_mhz); break; #endif /*DS5000_25*/ #ifdef DS5000_240 case DS_3MAXPLUS: /* DS5000/240 3max+ */ tc_max_slot = KN03_TC_MAX; tc_min_slot = KN03_TC_MIN; tc_slot_phys_base[0] = KN03_PHYS_TC_0_START; tc_slot_phys_base[1] = KN03_PHYS_TC_1_START; tc_slot_phys_base[2] = KN03_PHYS_TC_2_START; ioasic_base = MIPS_PHYS_TO_KSEG1(KN03_SYS_ASIC); mips_hardware_intr = kn03_intr; tc_enable_interrupt = kn03_enable_intr; Mach_reset_addr = (u_int *)MIPS_PHYS_TO_KSEG1(KN03_SYS_ERRADR); *Mach_reset_addr = 0; /* * Reset interrupts, clear any errors from newconf probes */ Mach_splbio = Mach_spl0; Mach_splnet = Mach_spl0; Mach_spltty = Mach_spl0; Mach_splimp = Mach_spl0; /* XXX */ /* * Clock interrupts at hw priority 1 must block bio,net,tty * at hw priority 0. */ Mach_splclock = cpu_spl1; Mach_splstatclock = cpu_spl1; mcclock_addr = (volatile struct chiptime *) MIPS_PHYS_TO_KSEG1(KN03_SYS_CLOCK); mc_cpuspeed(mcclock_addr, MIPS_INT_MASK_1); asic_init(0); /* * Initialize interrupts. */ kn03_tc3_imask = KN03_IM0 & ~(KN03_INTR_TC_0|KN03_INTR_TC_1|KN03_INTR_TC_2); *(u_int *)IOASIC_REG_IMSK(ioasic_base) = kn03_tc3_imask; *(u_int *)IOASIC_REG_INTR(ioasic_base) = 0; wbflush(); /* XXX hard-reset LANCE */ *(u_int *)IOASIC_REG_CSR(ioasic_base) |= 0x100; /* clear any memory errors from probes */ *Mach_reset_addr = 0; sprintf(cpu_model, "5000/2%d", cpu_mhz); break; #endif /* DS5000_240 */ default: printf("kernel not configured for systype 0x%x\n", i); cpu_reboot(RB_HALT | RB_NOSYNC, NULL); } /* * Find out how much memory is available. * Be careful to save and restore the original contents for msgbuf. */ physmem = btoc((vm_offset_t)v - KERNBASE); cp = (char *)MIPS_PHYS_TO_KSEG1(physmem << PGSHIFT); while (cp < (char *)physmem_boardmax) { int j; if (badaddr(cp, 4)) break; i = *(int *)cp; j = ((int *)cp)[4]; *(int *)cp = 0xa5a5a5a5; /* * Data will persist on the bus if we read it right away. * Have to be tricky here. */ ((int *)cp)[4] = 0x5a5a5a5a; wbflush(); if (*(int *)cp != 0xa5a5a5a5) break; *(int *)cp = i; ((int *)cp)[4] = j; cp += NBPG; physmem++; } maxmem = physmem; #if NLE_IOASIC > 0 /* * Grab 128K at the top of physical memory for the lance chip * on machines where it does dma through the I/O ASIC. * It must be physically contiguous and aligned on a 128K boundary. */ if (pmax_boardtype == DS_3MIN || pmax_boardtype == DS_MAXINE || pmax_boardtype == DS_3MAXPLUS) { maxmem -= btoc(128 * 1024); le_iomem = (maxmem << PGSHIFT); } #endif /* NLE_IOASIC */ #if (NASC > 0) && defined(ASC_IOASIC_BOUNCE) /* * Ditto for the scsi chip. There is probably a way to make asc.c * do dma without these buffers, but it would require major * re-engineering of the asc driver. * They must be 8K in size and page aligned. * (now 16K, as that's how big clustered FFS reads/writes get). */ if (pmax_boardtype == DS_3MIN || pmax_boardtype == DS_MAXINE || pmax_boardtype == DS_3MAXPLUS) { maxmem -= btoc(ASC_NCMD * (16 *1024)); asc_iomem = (maxmem << PGSHIFT); } #endif /* NASC */ /* * Initialize error message buffer (at end of core). */ maxmem -= btoc(MSGBUFSIZE); msgbufaddr = (caddr_t)(MIPS_PHYS_TO_KSEG0(maxmem << PGSHIFT)); initmsgbuf(msgbufaddr, mips_round_page(MSGBUFSIZE)); /* * Allocate space for system data structures. * The first available kernel virtual address is in "v". * As pages of kernel virtual memory are allocated, "v" is incremented. * * These data structures are allocated here instead of cpu_startup() * because physical memory is directly addressable. We don't have * to map these into virtual address space. */ start = v; #define valloc(name, type, num) \ (name) = (type *)v; v = (caddr_t)((name)+(num)) #define valloclim(name, type, num, lim) \ (name) = (type *)v; v = (caddr_t)((lim) = ((name)+(num))) #ifdef REAL_CLISTS valloc(cfree, struct cblock, nclist); #endif valloc(callout, struct callout, ncallout); #ifdef SYSVSHM valloc(shmsegs, struct shmid_ds, shminfo.shmmni); #endif #ifdef SYSVSEM valloc(sema, struct semid_ds, seminfo.semmni); valloc(sem, struct sem, seminfo.semmns); /* This is pretty disgusting! */ valloc(semu, int, (seminfo.semmnu * seminfo.semusz) / sizeof(int)); #endif #ifdef SYSVMSG valloc(msgpool, char, msginfo.msgmax); valloc(msgmaps, struct msgmap, msginfo.msgseg); valloc(msghdrs, struct msg, msginfo.msgtql); valloc(msqids, struct msqid_ds, msginfo.msgmni); #endif /* * Determine how many buffers to allocate. * We allocate more buffer space than the BSD standard of * using 10% of memory for the first 2 Meg, 5% of remaining. * We just allocate a flat 10%. Ensure a minimum of 16 buffers. * We allocate 1/2 as many swap buffer headers as file i/o buffers. */ if (bufpages == 0) bufpages = physmem / 10 / CLSIZE; if (nbuf == 0) { nbuf = bufpages; if (nbuf < 16) nbuf = 16; } if (nswbuf == 0) { nswbuf = (nbuf / 2) &~ 1; /* force even */ if (nswbuf > 256) nswbuf = 256; /* sanity */ } valloc(swbuf, struct buf, nswbuf); valloc(buf, struct buf, nbuf); /* * Clear allocated memory. */ bzero(start, v - start); /* * Initialize the virtual memory system. */ pmap_bootstrap((vm_offset_t)v); } /* * cpu_startup: allocate memory for variable-sized tables, * initialize cpu, and do autoconfiguration. */ void cpu_startup() { register unsigned i; int base, residual; vm_offset_t minaddr, maxaddr; vm_size_t size; #ifdef DEBUG extern int pmapdebug; int opmapdebug = pmapdebug; pmapdebug = 0; #endif /* * Good {morning,afternoon,evening,night}. */ printf(version); printf("real mem = %d\n", ctob(physmem)); /* * Allocate virtual address space for file I/O buffers. * Note they are different than the array of headers, 'buf', * and usually occupy more virtual memory than physical. */ size = MAXBSIZE * nbuf; buffer_map = kmem_suballoc(kernel_map, (vm_offset_t *)&buffers, &maxaddr, size, TRUE); minaddr = (vm_offset_t)buffers; if (vm_map_find(buffer_map, vm_object_allocate(size), (vm_offset_t)0, &minaddr, size, FALSE) != KERN_SUCCESS) panic("startup: cannot allocate buffers"); base = bufpages / nbuf; residual = bufpages % nbuf; for (i = 0; i < nbuf; i++) { vm_size_t curbufsize; vm_offset_t curbuf; /* * First <residual> buffers get (base+1) physical pages * allocated for them. The rest get (base) physical pages. * * The rest of each buffer occupies virtual space, * but has no physical memory allocated for it. */ curbuf = (vm_offset_t)buffers + i * MAXBSIZE; curbufsize = CLBYTES * (i < residual ? base+1 : base); vm_map_pageable(buffer_map, curbuf, curbuf+curbufsize, FALSE); vm_map_simplify(buffer_map, curbuf); } /* * Allocate a submap for exec arguments. This map effectively * limits the number of processes exec'ing at any time. */ exec_map = kmem_suballoc(kernel_map, &minaddr, &maxaddr, 16 * NCARGS, TRUE); /* * Allocate a submap for physio */ phys_map = kmem_suballoc(kernel_map, &minaddr, &maxaddr, VM_PHYS_SIZE, TRUE); /* * Finally, allocate mbuf cluster submap. */ mb_map = kmem_suballoc(kernel_map, (vm_offset_t *)&mbutl, &maxaddr, VM_MBUF_SIZE, FALSE); /* * Initialize callouts */ callfree = callout; for (i = 1; i < ncallout; i++) callout[i-1].c_next = &callout[i]; callout[i-1].c_next = NULL; #ifdef DEBUG pmapdebug = opmapdebug; #endif printf("avail mem = %ld\n", ptoa(cnt.v_free_count)); printf("using %d buffers containing %d bytes of memory\n", nbuf, bufpages * CLBYTES); /* * Set up buffers, so they can be used to read disk labels. */ bufinit(); /* * Set up CPU-specific registers, cache, etc. */ initcpu(); /* * Configure the system. */ configure(); } /* * machine dependent system variables. */ int cpu_sysctl(name, namelen, oldp, oldlenp, newp, newlen, p) int *name; u_int namelen; void *oldp; size_t *oldlenp; void *newp; size_t newlen; struct proc *p; { /* all sysctl names at this level are terminal */ if (namelen != 1) return (ENOTDIR); /* overloaded */ switch (name[0]) { case CPU_CONSDEV: return (sysctl_rdstruct(oldp, oldlenp, newp, &cn_tab->cn_dev, sizeof cn_tab->cn_dev)); default: return (EOPNOTSUPP); } /* NOTREACHED */ } int waittime = -1; struct user dumppcb; /* Actually, struct pcb would do. */ /* * These variables are needed by /sbin/savecore */ int dumpmag = (int)0x8fca0101; /* magic number for savecore */ int dumpsize = 0; /* also for savecore */ long dumplo = 0; void cpu_dumpconf() { int nblks; dumpsize = physmem; if (dumpdev != NODEV && bdevsw[major(dumpdev)].d_psize) { nblks = (*bdevsw[major(dumpdev)].d_psize)(dumpdev); if (dumpsize > btoc(dbtob(nblks - dumplo))) dumpsize = btoc(dbtob(nblks - dumplo)); else if (dumplo == 0) dumplo = nblks - btodb(ctob(physmem)); } /* * Don't dump on the first CLBYTES (why CLBYTES?) * in case the dump device includes a disk label. */ if (dumplo < btodb(CLBYTES)) dumplo = btodb(CLBYTES); } /* * Doadump comes here after turning off memory management and * getting on the dump stack, either when called above, or by * the auto-restart code. */ void dumpsys() { int error; /* Save registers. */ savectx(&dumppcb); msgbufmapped = 0; if (dumpdev == NODEV) return; /* * For dumps during autoconfiguration, * if dump device has already configured... */ if (dumpsize == 0) cpu_dumpconf(); if (dumplo < 0) return; printf("\ndumping to dev %x, offset %ld\n", dumpdev, dumplo); printf("dump "); /* * XXX * All but first arguments to dump() bogus. * What should blkno, va, size be? */ error = (*bdevsw[major(dumpdev)].d_dump)(dumpdev, 0, 0, 0); switch (error) { case ENXIO: printf("device bad\n"); break; case EFAULT: printf("device not ready\n"); break; case EINVAL: printf("area improper\n"); break; case EIO: printf("i/o error\n"); break; default: printf("error %d\n", error); break; case 0: printf("succeeded\n"); } } /* * call PROM to halt or reboot. */ volatile void prom_halt(howto, bootstr) int howto; char *bootstr; { if (callv != &callvec) { if (howto & RB_HALT) (*callv->_rex)('h'); else { (*callv->_rex)('b'); } } else if (howto & RB_HALT) { volatile void (*f) __P((void)) = (volatile void (*) __P((void))) DEC_PROM_REINIT; (*f)(); /* jump back to prom monitor */ } else { volatile void (*f) __P((void)) = (volatile void (*) __P((void)))DEC_PROM_AUTOBOOT; (*f)(); /* jump back to prom monitor and do 'auto' cmd */ } while(1) ; /* fool gcc */ /*NOTREACHED*/ } void cpu_reboot(howto, bootstr) /*register*/ int howto; char *bootstr; { extern int cold; /* take a snap shot before clobbering any registers */ if (curproc) savectx((struct user *)curpcb); #ifdef DEBUG if (panicstr) stacktrace(); #endif /* If system is cold, just halt. */ if (cold) { howto |= RB_HALT; goto haltsys; } /* If "always halt" was specified as a boot flag, obey. */ if ((boothowto & RB_HALT) != 0) howto |= RB_HALT; boothowto = howto; if ((howto & RB_NOSYNC) == 0 && waittime < 0) { /* * Synchronize the disks.... */ waittime = 0; vfs_shutdown(); /* * If we've been adjusting the clock, the todr * will be out of synch; adjust it now. */ resettodr(); } /* Disable interrupts. */ splhigh(); /* If rebooting and a dump is requested do it. */ #if 0 if ((howto & (RB_DUMP | RB_HALT)) == RB_DUMP) #else if (howto & RB_DUMP) #endif dumpsys(); haltsys: /* run any shutdown hooks */ doshutdownhooks(); /* Finally, halt/reboot the system. */ printf("%s\n\n", howto & RB_HALT ? "halted." : "rebooting..."); prom_halt(howto & RB_HALT, bootstr); /*NOTREACHED*/ } /* * Read a high-resolution clock, if one is available, and return * the current microsecond offset from time-of-day. */ #if !defined(DS5000_240) && !defined(DS5000_25) # define clkread() (0) #else /* * IOASIC TC cycle counter, latched on every interrupt from RTC chip. * [Or free-running microsecond counter on Maxine.] */ u_long latched_cycle_cnt; /* * On a Decstation 5000/240, use the turbochannel bus-cycle counter * to interpolate micro-seconds since the last RTC clock tick. * The interpolation base is the copy of the bus cycle-counter taken * by the RTC interrupt handler. * On XINE, use the microsecond free-running counter. * */ static inline u_long clkread() { #ifdef DS5000_240 register u_long usec, cycles; /* really 32 bits? */ #endif #ifdef DS5000_25 if (pmax_boardtype == DS_MAXINE) return (*(u_long*)(MIPS_PHYS_TO_KSEG1(XINE_REG_FCTR)) - latched_cycle_cnt); else #endif #ifdef DS5000_240 if (pmax_boardtype == DS_3MAXPLUS) /* 5k/240 TC bus counter */ cycles = *(u_long*)IOASIC_REG_CTR(ioasic_base); else #endif return (0); #ifdef DS5000_240 /* Compute difference in cycle count from last hardclock() to now */ #if 1 /* my code, using u_ints */ cycles = cycles - latched_cycle_cnt; #else /* Mills code, using (signed) ints */ if (cycles >= latched_cycle_cnt) cycles = cycles - latched_cycle_cnt; else cycles = latched_cycle_cnt - cycles; #endif /* * Scale from 40ns to microseconds. * Avoid a kernel FP divide (by 25) using the approximation * 1/25 = 40/1000 =~ 41/ 1024, which is good to 0.0975 % */ usec = cycles + (cycles << 3) + (cycles << 5); usec = usec >> 10; #ifdef CLOCK_DEBUG if (usec > 3906 +4) { addlog("clkread: usec %d, counter=%lx\n", usec, latched_cycle_cnt); stacktrace(); } #endif /*CLOCK_DEBUG*/ return usec; #endif /*DS5000_240*/ } #if 0 void microset() { latched_cycle_cnt = *(u_long*)(IOASIC_REG_CTR(ioasic_base)); } #endif #endif /*DS5000_240 || DS5000_25*/ /* * Return the best possible estimate of the time in the timeval * to which tvp points. Unfortunately, we can't read the hardware registers. * We guarantee that the time will be greater than the value obtained by a * previous call. */ void microtime(tvp) register struct timeval *tvp; { int s = splclock(); static struct timeval lasttime; *tvp = time; tvp->tv_usec += clkread(); if (tvp->tv_usec >= 1000000) { tvp->tv_usec -= 1000000; tvp->tv_sec++; } if (tvp->tv_sec == lasttime.tv_sec && tvp->tv_usec <= lasttime.tv_usec && (tvp->tv_usec = lasttime.tv_usec + 1) > 1000000) { tvp->tv_sec++; tvp->tv_usec -= 1000000; } lasttime = *tvp; splx(s); } int initcpu() { register volatile struct chiptime *c; int i = 0; #if defined(DS5000_200) || defined(DS5000_25) || defined(DS5000_100) || \ defined(DS5000_240) /* Reset after bus errors during probe */ if (Mach_reset_addr) { *Mach_reset_addr = 0; wbflush(); } #endif /* clear any pending interrupts */ switch (pmax_boardtype) { case DS_PMAX: break; /* nothing to do for KN01. */ case DS_3MAXPLUS: case DS_3MIN: case DS_MAXINE: *(u_int *)IOASIC_REG_INTR(ioasic_base) = 0; break; case DS_3MAX: *(u_int *)MIPS_PHYS_TO_KSEG1(KN02_SYS_CHKSYN) = 0; wbflush(); break; default: printf("initcpu(): unknown system type 0x%x\n", pmax_boardtype); break; } /* * With newconf, this should be done elswhere, but without it * we hang (?) */ #if 1 /*XXX*/ /* disable clock interrupts (until startrtclock()) */ if (mcclock_addr) { c = mcclock_addr; c->regb = REGB_DATA_MODE | REGB_HOURS_FORMAT; i = c->regc; } return (i); #endif } /* * Convert an ASCII string into an integer. */ int atoi(s) const char *s; { int c; unsigned base = 10, d; int neg = 0, val = 0; if (s == 0 || (c = *s++) == 0) goto out; /* skip spaces if any */ while (c == ' ' || c == '\t') c = *s++; /* parse sign, allow more than one (compat) */ while (c == '-') { neg = !neg; c = *s++; } /* parse base specification, if any */ if (c == '0') { c = *s++; switch (c) { case 'X': case 'x': base = 16; break; case 'B': case 'b': base = 2; break; default: base = 8; } } /* parse number proper */ for (;;) { if (c >= '0' && c <= '9') d = c - '0'; else if (c >= 'a' && c <= 'z') d = c - 'a' + 10; else if (c >= 'A' && c <= 'Z') d = c - 'A' + 10; else break; val *= base; val += d; c = *s++; } if (neg) val = -val; out: return val; } #ifdef DS3100 /* * Enable an interrupt from a slot on the KN01 internal bus. * * The 4.4bsd kn01 interrupt handler hard-codes r3000 CAUSE register * bits to particular device interrupt handlers. We may choose to store * function and softc pointers at some future point. */ void kn01_enable_intr(slotno, handler, sc, on) register unsigned int slotno; int (*handler) __P((void* softc)); void *sc; int on; { /* */ if (on) { tc_slot_info[slotno].intr = handler; tc_slot_info[slotno].sc = sc; } else { tc_slot_info[slotno].intr = 0; tc_slot_info[slotno].sc = 0; } } #endif /* DS3100 */ #ifdef DS5000_200 /* * Enable/Disable interrupts for a TURBOchannel slot on the 3MAX. */ void kn02_enable_intr(slotno, handler, sc, on) register u_int slotno; int (*handler) __P((void* softc)); void *sc; int on; { register volatile int *p_csr = (volatile int *)MIPS_PHYS_TO_KSEG1(KN02_SYS_CSR); int csr; int s; #if 0 printf("3MAX enable_intr: imask %x, %sabling slot %d, sc %p\n", kn03_tc3_imask, (on? "en" : "dis"), slotno, sc); #endif if (slotno > TC_MAX_LOGICAL_SLOTS) panic("kn02_enable_intr: bogus slot %d\n", slotno); if (on) { /*printf("kn02: slot %d handler 0x%x\n", slotno, handler);*/ tc_slot_info[slotno].intr = handler; tc_slot_info[slotno].sc = sc; } else { tc_slot_info[slotno].intr = 0; tc_slot_info[slotno].sc = 0; } slotno = 1 << (slotno + KN02_CSR_IOINTEN_SHIFT); s = Mach_spl0(); csr = *p_csr & ~(KN02_CSR_WRESERVED | 0xFF); if (on) *p_csr = csr | slotno; else *p_csr = csr & ~slotno; splx(s); } #endif /*DS5000_200*/ #ifdef DS5000_100 /* * Object: * kmin_enable_intr EXPORTED function * * Enable/Disable interrupts from a TURBOchannel slot. * * We pretend we actually have 8 slots even if we really have * only 4: TCslots 0-2 maps to slots 0-2, TCslot3 maps to * slots 3-7 (see pmax/tc/ds-asic-conf.c). * * 3MIN TURBOchannel interrupts are unlike other decstations, * in that interrupt requests from the option slots (0-2) map * directly to R3000 interrupt lines, not to IOASIC interrupt * bits. If it weren't for that, the 3MIN and 3MAXPLUS could * share interrupt handlers and interrupt-enable code */ void kmin_enable_intr(slotno, handler, sc, on) register unsigned int slotno; int (*handler) __P((void* softc)); void *sc; int on; { register unsigned mask; switch (slotno) { /* slots 0-2 don't interrupt through the IOASIC. */ case 0: mask = MIPS_INT_MASK_0; break; case 1: mask = MIPS_INT_MASK_1; break; case 2: mask = MIPS_INT_MASK_2; break; case KMIN_SCSI_SLOT: mask = (KMIN_INTR_SCSI | KMIN_INTR_SCSI_PTR_LOAD | KMIN_INTR_SCSI_OVRUN | KMIN_INTR_SCSI_READ_E); break; case KMIN_LANCE_SLOT: mask = KMIN_INTR_LANCE; break; case KMIN_SCC0_SLOT: mask = KMIN_INTR_SCC_0; break; case KMIN_SCC1_SLOT: mask = KMIN_INTR_SCC_1; break; case KMIN_ASIC_SLOT: mask = KMIN_INTR_ASIC; break; default: return; } #if defined(DEBUG) || defined(DIAGNOSTIC) printf("3MIN: imask %lx, %sabling slot %d, sc %p handler %p\n", kmin_tc3_imask, (on? "en" : "dis"), slotno, sc, handler); #endif /* * Enable the interrupt handler, and if it's an IOASIC * slot, set the IOASIC interrupt mask. * Otherwise, set the appropriate spl level in the R3000 * register. * Be careful to set handlers before enabling, and disable * interrupts before clearing handlers. */ if (on) { /* Set the interrupt handler and argument ... */ tc_slot_info[slotno].intr = handler; tc_slot_info[slotno].sc = sc; /* ... and set the relevant mask */ if (slotno <= 2) { /* it's an option slot */ int s = splhigh(); s |= mask; splx(s); } else { /* it's a baseboard device going via the ASIC */ kmin_tc3_imask |= mask; } } else { /* Clear the relevant mask... */ if (slotno <= 2) { /* it's an option slot */ int s = splhigh(); printf("kmin_intr: cannot disable option slot %d\n", slotno); s &= ~mask; splx(s); } else { /* it's a baseboard device going via the ASIC */ kmin_tc3_imask &= ~mask; } /* ... and clear the handler */ tc_slot_info[slotno].intr = 0; tc_slot_info[slotno].sc = 0; } } /* * Count instructions between 4ms mcclock interrupt requests, * using the ioasic clock-interrupt-pending bit to determine * when clock ticks occur. * Set up iosiac to allow only clock interrupts, then * call */ void kmin_mcclock_cpuspeed(mcclock_addr, clockmask) volatile struct chiptime *mcclock_addr; int clockmask; { register volatile u_int * ioasic_intrmaskp = (volatile u_int *)MIPS_PHYS_TO_KSEG1(KMIN_REG_IMSK); register int saved_imask = *ioasic_intrmaskp; /* Allow only clock interrupts through ioasic. */ *ioasic_intrmaskp = KMIN_INTR_CLOCK; wbflush(); mc_cpuspeed(mcclock_addr, clockmask); *ioasic_intrmaskp = saved_imask; wbflush(); } #endif /*DS5000_100*/ #ifdef DS5000_25 /* * Object: * xine_enable_intr EXPORTED function * * Enable/Disable interrupts from a TURBOchannel slot. * * We pretend we actually have 11 slots even if we really have * only 3: TCslots 0-1 maps to slots 0-1, TCslot 2 is used for * the system (TCslot3), TCslot3 maps to slots 3-10 * (see pmax/tc/ds-asic-conf.c). * Note that all these interrupts come in via the IMR. */ void xine_enable_intr(slotno, handler, sc, on) register unsigned int slotno; int (*handler) __P((void* softc)); void *sc; int on; { register unsigned mask; switch (slotno) { case 0: /* a real slot, but */ mask = XINE_INTR_TC_0; break; case 1: /* a real slot, but */ mask = XINE_INTR_TC_1; break; case XINE_FLOPPY_SLOT: mask = XINE_INTR_FLOPPY; break; case XINE_SCSI_SLOT: mask = (XINE_INTR_SCSI | XINE_INTR_SCSI_PTR_LOAD | XINE_INTR_SCSI_OVRUN | XINE_INTR_SCSI_READ_E); break; case XINE_LANCE_SLOT: mask = XINE_INTR_LANCE; break; case XINE_SCC0_SLOT: mask = XINE_INTR_SCC_0; break; case XINE_DTOP_SLOT: mask = XINE_INTR_DTOP_RX; break; case XINE_ISDN_SLOT: mask = XINE_INTR_ISDN; break; case XINE_ASIC_SLOT: mask = XINE_INTR_ASIC; break; default: return;/* ignore */ } if (on) { xine_tc3_imask |= mask; tc_slot_info[slotno].intr = handler; tc_slot_info[slotno].sc = sc; } else { xine_tc3_imask &= ~mask; tc_slot_info[slotno].intr = 0; tc_slot_info[slotno].sc = 0; } *(u_int *)IOASIC_REG_IMSK(ioasic_base) = xine_tc3_imask; } #endif /*DS5000_25*/ #ifdef DS5000_240 void kn03_tc_reset() { /* * Reset interrupts, clear any errors from newconf probes */ *(u_int *)IOASIC_REG_INTR(ioasic_base) = 0; *(unsigned *)MIPS_PHYS_TO_KSEG1(KN03_SYS_ERRADR) = 0; } /* * Object: * kn03_enable_intr EXPORTED function * * Enable/Disable interrupts from a TURBOchannel slot. * * We pretend we actually have 8 slots even if we really have * only 4: TCslots 0-2 maps to slots 0-2, TCslot3 maps to * slots 3-7 (see pmax/tc/ds-asic-conf.c). */ void kn03_enable_intr(slotno, handler, sc, on) register unsigned int slotno; int (*handler) __P((void* softc)); void *sc; int on; { register unsigned mask; #if 0 printf("3MAXPLUS: imask %x, %sabling slot %d, unit %d addr 0x%x\n", kn03_tc3_imask, (on? "en" : "dis"), slotno, unit, handler); #endif switch (slotno) { case 0: mask = KN03_INTR_TC_0; break; case 1: mask = KN03_INTR_TC_1; break; case 2: mask = KN03_INTR_TC_2; break; case KN03_SCSI_SLOT: mask = (KN03_INTR_SCSI | KN03_INTR_SCSI_PTR_LOAD | KN03_INTR_SCSI_OVRUN | KN03_INTR_SCSI_READ_E); break; case KN03_LANCE_SLOT: mask = KN03_INTR_LANCE; mask |= IOASIC_INTR_LANCE_READ_E; break; case KN03_SCC0_SLOT: mask = KN03_INTR_SCC_0; break; case KN03_SCC1_SLOT: mask = KN03_INTR_SCC_1; break; case KN03_ASIC_SLOT: mask = KN03_INTR_ASIC; break; default: #ifdef DIAGNOSTIC printf("warning: enabling unknown intr %x\n", slotno); #endif goto done; } if (on) { kn03_tc3_imask |= mask; tc_slot_info[slotno].intr = handler; tc_slot_info[slotno].sc = sc; } else { kn03_tc3_imask &= ~mask; tc_slot_info[slotno].intr = 0; tc_slot_info[slotno].sc = 0; } done: *(u_int *)IOASIC_REG_IMSK(ioasic_base) = kn03_tc3_imask; wbflush(); } #endif /* DS5000_240 */ #ifdef DS5000_240 /* XXX */ /* * Initialize the I/O asic */ static void asic_init(isa_maxine) int isa_maxine; { volatile u_int *decoder; /* These are common between 3min and maxine */ decoder = (volatile u_int *)IOASIC_REG_LANCE_DECODE(ioasic_base); *decoder = KMIN_LANCE_CONFIG; /* set the SCSI DMA configuration map */ decoder = (volatile u_int *) IOASIC_REG_SCSI_DECODE(ioasic_base); (*decoder) = 0x00000000e; } #endif /* DS5000_240 XXX */
24.797685
80
0.677634
[ "object", "vector", "model" ]
b93206fa965123de18a184b23965b56e0e56e6e6
1,226
h
C
sources/main.h
sfztools/sfzfoo
8344c7fd94a4a8b681014aa66cdd0f02d79b8731
[ "BSD-2-Clause" ]
3
2019-12-31T10:53:03.000Z
2021-12-16T22:31:42.000Z
sources/main.h
sfztools/sfzfoo
8344c7fd94a4a8b681014aa66cdd0f02d79b8731
[ "BSD-2-Clause" ]
1
2020-01-04T01:11:24.000Z
2020-01-04T08:40:50.000Z
sources/main.h
sfztools/sfz-opcode-checker
8344c7fd94a4a8b681014aa66cdd0f02d79b8731
[ "BSD-2-Clause" ]
null
null
null
#pragma once #ifndef _WIN32 #include <curl/curl.h> #else #include <windows.h> #include <wininet.h> #endif #include <ghc/filesystem.hpp> #include <vector> #include <memory> #include <unordered_set> typedef std::vector<std::string> OpcodeNameList; typedef std::unordered_set<std::string> OpcodeNameSet; void displayHelp(); int runValidate(int argc, char *argv[]); int runPrint(int argc, char *argv[]); int runUpdate(int argc, char *argv[]); int runList(int argc, char *argv[]); bool performUpdate(); bool scanFileOpcodes(const ghc::filesystem::path &path, OpcodeNameSet &set); const ghc::filesystem::path &getDbCacheDir(); bool downloadNewDb(const ghc::filesystem::path &path); #ifndef _WIN32 struct CURL_delete { void operator()(CURL *x) const noexcept { curl_easy_cleanup(x); } }; typedef std::unique_ptr<CURL, CURL_delete> CURL_u; #else struct HINTERNET_delete { void operator()(HINTERNET x) const noexcept { InternetCloseHandle(x); } }; typedef std::unique_ptr<std::remove_pointer<HINTERNET>::type, HINTERNET_delete> HINTERNET_u; #endif #define SFZ_DB_HOST "raw.githubusercontent.com" #define SFZ_DB_PATH "/sfzformat/sfzformat.github.io/source/_data/sfz/syntax.yml" #define SFZ_DB_URL "https://" SFZ_DB_HOST SFZ_DB_PATH
33.135135
100
0.76509
[ "vector" ]
b93365098237c379c41f172a8867516984b24bf4
4,443
h
C
driver/chain.h
ipa-tys/canopen_old
1d1a04d300b5ce7b69649e9e659a88a20dd5d131
[ "MIT" ]
null
null
null
driver/chain.h
ipa-tys/canopen_old
1d1a04d300b5ce7b69649e9e659a88a20dd5d131
[ "MIT" ]
null
null
null
driver/chain.h
ipa-tys/canopen_old
1d1a04d300b5ce7b69649e9e659a88a20dd5d131
[ "MIT" ]
1
2019-12-26T08:46:14.000Z
2019-12-26T08:46:14.000Z
// Copyright (c) 2012 Fraunhofer Institute // for Manufacturing Engineering and Automation (IPA) // See the file license.txt for copying permission. #ifndef CHAIN_H #define CHAIN_H #include <iostream> #include <string> #include <libpcan.h> #include <cmath> #include <map> #include <queue> #include <cassert> #include <regex> #include "canopen_highlevel.h" #include "chain_description.h" #define _USE_MATH_DEFINES namespace canopen { extern std::chrono::milliseconds syncInterval; template <class T> void printVector(std::string name, std::vector<T> v) { std::cout << name << ": "; for (auto it : v) std::cout << it << " "; std::cout << std::endl; } class Device { // [positions]=rad, [velocities]=rad/sec public: inline Device(std::string alias, std::string CANbus, uint16_t CANid): alias_(alias), CANbus_(CANbus), CANid_(CANid), actualPos_(0), desiredPos_(0), actualVel_(0), desiredVel_(0), initialized_(false), timeStamp_msec_(std::chrono::milliseconds(0)), timeStamp_usec_(std::chrono::microseconds(0)) {} void CANopenInit(); void update(Message m); inline void setVel(double vel) { desiredVel_ = vel; // desiredPos_ = desiredPos_ + vel * (syncInterval.count() / 1000.0); } inline void updateDesiredPos() { desiredPos_ = desiredPos_ + desiredVel_ * (syncInterval.count() / 1000.0); } double actualPos_; // unit = rad double desiredPos_; // unit = rad double actualVel_; // unit = rad/sec double desiredVel_; // unit = rad/sec std::chrono::milliseconds timeStamp_msec_; std::chrono::microseconds timeStamp_usec_; std::string alias_; std::string CANbus_; uint16_t CANid_; bool initialized_; }; struct ChainState { std::vector<double> actualPos; std::vector<double> desiredPos; std::vector<double> actualVel; std::vector<double> desiredVel; bool initialized; bool fault; void print() { std::cout << "Initialized? " << initialized << std::endl; printVector("actualPos: ", actualPos); printVector("desiredPos: ", desiredPos); printVector("actualVel: ", actualVel); printVector("desiredVel: ", desiredVel); std::cout << std::endl; } }; class Chain { // [positions]=rad, [velocities]=rad/sec public: inline Chain(ChainDescription chainDesc): alias_(chainDesc.name), initialized_(false), fault_(false) { for (auto d : chainDesc.devices) { Device* dev = new Device(d.name, d.bus, d.id); deviceMap_[d.id] = dev; devices_.push_back(dev); } } inline void CANopenInit() { for (auto device : devices_) device->CANopenInit(); } inline void updateDesiredPos() { if (initialized_ & !fault_) for (auto device : devices_) device->updateDesiredPos(); } inline void sendPos() { if (initialized_ & !fault_) for (auto device : devices_) canopen::sendPos(device->CANid_, device->desiredPos_); } inline void setVel(std::vector<double> velocities) { for (int i=0; i<velocities.size(); i++) devices_[i]->setVel(velocities[i]); } inline ChainState getChainState() { ChainState cs; for (auto device : devices_) { cs.actualPos.push_back(device->actualPos_); cs.desiredPos.push_back(device->desiredPos_); cs.actualVel.push_back(device->actualVel_); cs.desiredVel.push_back(device->desiredVel_); } cs.initialized = initialized_; cs.fault = fault_; return cs; } inline void update(Message m) { //if (m.contains("position_actual_value")) { // std::cout << "Timestamp: " // << std::chrono::duration_cast<std::chrono::milliseconds>(m.timeStamp_).count() // << std::endl; //getChainState().print(); //} deviceMap_[m.nodeID_]->update(m); if (!initialized_) { bool allInitialized = true; for (auto device : devices_) if (! device->initialized_) allInitialized = false; if (allInitialized) initialized_ = true; } } std::string alias_; // two alternative access modes for the devices in a chain: std::map<uint16_t, Device*> deviceMap_; std::vector<Device*> devices_; bool initialized_; bool fault_; }; extern std::map<std::string, Chain*> chainMap; inline void initChainMap(std::vector<ChainDescription> chainDesc) { for (auto c : chainDesc) chainMap[c.name] = new Chain(c); } } #endif
27.596273
84
0.649786
[ "vector" ]
b935d41cc9ced255830f1ee2bd7998c6950f03c6
5,253
h
C
trunk/projects/desktop/angsys/test/test.h
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
trunk/projects/desktop/angsys/test/test.h
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
trunk/projects/desktop/angsys/test/test.h
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
#pragma once namespace ang { ang_declare_object(test); ang_declare_object(camera); ang_declare_object(object3D); ang_declare_object(library); namespace graphics { ang_declare_object(gl_context); ang_declare_object(gl_resource); ang_declare_object(gl_shaders); ang_declare_object(gl_mesh); ang_declare_object(gl_texture); } struct ANG_ALIGN(16) vertex { maths::float3 position; maths::float3 normal; maths::float3 binormal; maths::float3 tangent; maths::float2 texcoord; }; struct ANG_ALIGN(16) vertex2 { maths::float3 position; maths::float4 color; }; } #include "context.h" #include "shaders.h" #include "mesh.h" #include "texture.h" namespace ang { class camera : public implement<camera , iid("ang::camera") , framework::aligned> { private: maths::float4x4 m_projection; maths::float4 m_position; maths::float4 m_rotation; float m_movement_speed; float m_rotation_speed; public: camera(); bool load(graphics::size<float> screen, maths::float3 const& position = { 0,0,0 }, maths::float3 const& rotation = { 0,0,0 }); void update(core::time::step_timer const&); maths::float4x4 view_matrix()const; maths::float4x4 projection_matrix()const; maths::float4x4 world_matrix()const; void projection(float fov, float aspect, float near_plane, float far_plane); void projection(const maths::float4&); void move_x(float deltaTime); void move_y(float deltaTime); void move_z(float deltaTime); void rotate_yaw(float deltaTime); void rotate_pitch(float deltaTime); void rotate_roll(float deltaTime); private: virtual~camera(); }; class object3D : public implement<object3D , iid("ang::object3D") , framework::aligned> { private: maths::float4 m_position; maths::float3 m_rotation; maths::float3 m_scale; core::async::mutex_t m_mutex; graphics::gl_mesh_t m_mesh; graphics::gl_shaders_t m_shaders; vector<graphics::gl_texture_t> m_textures; public: object3D(); virtual bool load(graphics::gl_context_t, string vshader, string fshader, string model, array<string> textures); virtual void update(core::time::step_timer const&); virtual void draw(graphics::gl_context_t, camera_t); virtual void dispose()override; maths::float4x4 world_matrix()const; }; class library : public implement<library , iid("ang::resource_manager")> { private: collections::hash_map<string, string> m_sources; collections::hash_map<string, graphics::gl_mesh_t> m_meshes; collections::hash_map<string, graphics::gl_shaders_t> m_shaders; collections::hash_map<string, graphics::gl_texture_t> m_textures; public: library(); void load(dom::xml::ixml_node_t); void load_sources(dom::xml::ixml_node_t); void load_resources(dom::xml::ixml_node_t); core::async::iasync<library_t> load_async(dom::xml::ixml_node_t); void load_resources(dom::xml::ixml_node_t); }; class test : public implement<test , iid("ang::test")> { public: static int main(array<string> args) { test_t game = new test(); game->run("puyopuyo"_s, "Puyo Puyo"_s); return 0; } private: test(); virtual~test(); virtual void dispose()override; error run(string app_name, string app_title); void init(); void update(const core::time::step_timer&); void draw(); void exit(); virtual void on_initialize(objptr sender, platform::events::icreated_event_args_t args); virtual void on_update(objptr sender, platform::events::imsg_event_args_t args); virtual void on_finalize(objptr sender, platform::events::imsg_event_args_t args); virtual void on_pointer_pressed(objptr sender, platform::events::ipointer_event_args_t args); virtual void on_pointer_moved(objptr sender, platform::events::ipointer_event_args_t args); virtual void on_pointer_released(objptr sender, platform::events::ipointer_event_args_t args); virtual void on_pointer_entered(objptr sender, platform::events::ipointer_event_args_t args); virtual void on_pointer_leaved(objptr sender, platform::events::ipointer_event_args_t args); virtual void on_key_pressed(objptr sender, platform::events::ikey_event_args_t args); virtual void on_key_released(objptr sender, platform::events::ikey_event_args_t args); virtual void on_text_changed(objptr sender, platform::events::itext_change_event_args_t args); virtual void on_size_changed(objptr sender, platform::events::idisplay_info_event_args_t args); virtual void on_display_changed(objptr sender, platform::events::idisplay_info_event_args_t args); virtual void on_controller_connected(objptr, platform::events::icontroller_status_args_t args); virtual void on_controller_disconnected(objptr, platform::events::icontroller_status_args_t args); virtual void on_controller_analog_event(objptr, platform::events::icontroller_analog_input_args_t args); virtual void on_controller_digital_event(objptr, platform::events::icontroller_digital_input_args_t args); graphics::gl_context_t m_context; object3D_t m_object; float m_angle; camera_t m_camera; core::time::step_timer m_timer; platform::input::icontroller_t m_controller; platform::events::event_token_t m_analog_event_token; platform::events::event_token_t m_digital_event_token; }; }
27.941489
128
0.758614
[ "mesh", "vector", "model" ]
b93c820a79eebb20fe52cab17bcccce5d9aeb5e2
3,530
h
C
examples/volcano/swapchain.h
djohansson/slang
69227ad7d46b8741274c93a42a891d70458f2d45
[ "MIT" ]
2
2019-08-16T13:33:28.000Z
2020-08-12T21:48:24.000Z
examples/volcano/swapchain.h
djohansson/slang
69227ad7d46b8741274c93a42a891d70458f2d45
[ "MIT" ]
null
null
null
examples/volcano/swapchain.h
djohansson/slang
69227ad7d46b8741274c93a42a891d70458f2d45
[ "MIT" ]
null
null
null
#pragma once #include "device.h" #include "frame.h" #include "rendertarget.h" #include "types.h" #include "queue.h" #include <memory> template <GraphicsBackend B> struct SwapchainConfiguration { Extent2d<B> extent = {}; SurfaceFormat<B> surfaceFormat = {}; PresentMode<B> presentMode = {}; uint8_t imageCount = 0; }; template <GraphicsBackend B> class Swapchain : public IRenderTarget<B>, public DeviceObject<B> { public: constexpr Swapchain() noexcept = default; Swapchain(Swapchain&& other) noexcept; Swapchain( const std::shared_ptr<DeviceContext<B>>& deviceContext, const SwapchainConfiguration<B>& config, SurfaceHandle<B>&& surface, // takes ownership SwapchainHandle<B> previous); ~Swapchain(); Swapchain& operator=(Swapchain&& other) noexcept; operator auto() const noexcept { return mySwapchain; } void swap(Swapchain& rhs) noexcept; friend void swap(Swapchain& lhs, Swapchain& rhs) noexcept { lhs.swap(rhs); } virtual const RenderTargetCreateDesc<B>& getRenderTargetDesc() const final; virtual ImageLayout<B> getColorImageLayout(uint32_t index) const final; virtual ImageLayout<B> getDepthStencilImageLayout() const final; virtual void blit( CommandBufferHandle<B> cmd, const IRenderTarget<Vk>& srcRenderTarget, const ImageSubresourceLayers<B>& srcSubresource, uint32_t srcIndex, const ImageSubresourceLayers<B>& dstSubresource, uint32_t dstIndex, Filter<B> filter = {}) final; virtual void clearSingleAttachment( CommandBufferHandle<B> cmd, const ClearAttachment<B>& clearAttachment) const final; virtual void clearAllAttachments( CommandBufferHandle<B> cmd, const ClearColorValue<B>& color = {}, const ClearDepthStencilValue<B>& depthStencil = {}) const final; virtual void clearColor(CommandBufferHandle<B> cmd, const ClearColorValue<B>& color, uint32_t index) final; virtual void clearDepthStencil(CommandBufferHandle<B> cmd, const ClearDepthStencilValue<B>& depthStencil) final; virtual void transitionColor(CommandBufferHandle<B> cmd, ImageLayout<B> layout, uint32_t index) final; virtual void transitionDepthStencil(CommandBufferHandle<B> cmd, ImageLayout<B> layout) final; virtual const std::optional<RenderPassBeginInfo<B>>& begin(CommandBufferHandle<B> cmd, SubpassContents<B> contents) final; virtual void end(CommandBufferHandle<B> cmd) final; auto getSurface() const noexcept { return mySurface; } auto getRenderPass() { return static_cast<RenderPassHandle<B>>(myFrames[myFrameIndex]); } // todo: potentially remove this if the drivers will allow us to completely rely on the timeline in the future... std::tuple<SemaphoreHandle<B>, SemaphoreHandle<B>> getFrameSyncSemaphores() const noexcept { const auto& lastFrame = myFrames[myLastFrameIndex]; const auto& frame = myFrames[myFrameIndex]; return std::make_tuple(lastFrame.getNewImageAcquiredSemaphore(), frame.getRenderCompleteSemaphore()); } // std::tuple<bool, uint64_t> flip(); QueuePresentInfo<B> preparePresent(uint64_t timelineValue); protected: auto internalGetFrameIndex() const noexcept { return myFrameIndex; } void internalCreateSwapchain( const SwapchainConfiguration<B>& config, SwapchainHandle<B> previous); private: RenderTargetCreateDesc<B> myDesc = {}; SurfaceHandle<B> mySurface = {}; SwapchainHandle<B> mySwapchain = {}; std::vector<Frame<B>> myFrames; uint32_t myFrameIndex = 0; uint32_t myLastFrameIndex = 0; }; #include "swapchain.inl"
33.301887
123
0.749292
[ "vector" ]
b9474a5344c690bc98515bd7be4e4e07b1ab479b
8,999
c
C
test/perftest/perftest.c
mwahlroos/libcoll-c
801d1883f0a561c77b9bee6805266e4c313e6680
[ "MIT" ]
1
2021-02-13T14:35:12.000Z
2021-02-13T14:35:12.000Z
test/perftest/perftest.c
mwahlroos/libcoll-c
801d1883f0a561c77b9bee6805266e4c313e6680
[ "MIT" ]
null
null
null
test/perftest/perftest.c
mwahlroos/libcoll-c
801d1883f0a561c77b9bee6805266e4c313e6680
[ "MIT" ]
null
null
null
/* * Basic performance test code for libcoll. * * The purpose of these tests is mainly to have some basic facilities for * evaluating whether e.g. optimizations or other changes made to the library * code have an impact on the performance of basic operations on collections. * * They are not inteded as a full-fledged benchmark suite, or, in their present * state, representative of any particular real-world workload. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> /* for getopt, POSIX-specific */ #include <getopt.h> /* for getopt, POSIX-specific */ #include "../helpers.h" #include "comparators.h" #include "hash.h" #include "hashmap.h" #include "treemap.h" #include "types.h" #include "vector.h" #define BENCHMARK_SEED 1U #define BENCHMARK_SIZE_DEFAULT 10000000LU #define BENCHMARK_RUNS_DEFAULT 1 #define KEY_STR_LEN 5 #define BENCHMARK_RETRIEVE_PROPORTION 1 /* one in how many inserted values to get in retrieval tests */ typedef enum { NONE, HASHMAP, TREEMAP, VECTOR } BenchmarkTarget; static FILE* get_null_output() { return fopen("/dev/null", "a"); } static void randstr(char *buf, size_t len) { char range_start = 'a'; char range_end = 'z'; for (size_t i=0; i<len; i++) { int r = rand() % (range_end - range_start) + range_start; buf[i] = (char) r; } } static void generate_key_value_data(libcoll_pair_voidptr_t *buf, size_t n) { srand(BENCHMARK_SEED); size_t strlen = 5; for (unsigned long i=0; i<n; i++) { char *key = malloc(strlen * sizeof(char)); int *value = malloc(sizeof(int)); randstr(key, strlen); *value = rand(); libcoll_pair_voidptr_t kvpair = {key, value}; buf[i] = kvpair; } } static void populate_hashmap(libcoll_hashmap_t *hm, libcoll_pair_voidptr_t *data, size_t n) { for (size_t i=0; i<n; i++) { libcoll_pair_voidptr_t kvpair = data[i]; libcoll_hashmap_put(hm, kvpair.a, kvpair.b); } } static void populate_treemap(libcoll_treemap_t *tm, libcoll_pair_voidptr_t *data, size_t n) { for (size_t i=0; i<n; i++) { libcoll_pair_voidptr_t kvpair = data[i]; libcoll_treemap_add(tm, kvpair.a, kvpair.b); } } static void populate_vector(libcoll_vector_t *v, libcoll_pair_voidptr_t *data, size_t n) { for (size_t i=0; i<n; i++) { libcoll_vector_append(v, data + i); } } static void benchmark_hashmap(unsigned long testsize) { clock_t start_time; unsigned long retrieve_count = testsize / BENCHMARK_RETRIEVE_PROPORTION; /* null output for printing values retrieved during retrieval tests, * to prevent the compiler from optimizing the retrievals out */ FILE *null_out = get_null_output(); libcoll_hashmap_t *map = libcoll_hashmap_init_with_params( LIBCOLL_HASHMAP_DEFAULT_INIT_SIZE, LIBCOLL_HASHMAP_DEFAULT_MAX_LOAD_FACTOR, libcoll_hashcode_str, libcoll_strcmp_wrapper, libcoll_intptrcmp ); libcoll_pair_voidptr_t *data = malloc(testsize * sizeof(libcoll_pair_voidptr_t)); generate_key_value_data(data, testsize); printf("Populating a hashmap with %lu entries... \t", testsize); start_time = clock(); populate_hashmap(map, data, testsize); printf("%.3f s\n", ((double) (clock() - start_time) / CLOCKS_PER_SEC)); start_time = clock(); printf("Retrieving %lu items... \t", retrieve_count); for (unsigned long i=0; i<retrieve_count; i++) { size_t key_idx = i * (BENCHMARK_RETRIEVE_PROPORTION); int *value = (int*) libcoll_hashmap_get(map, data[key_idx].a); /* This can be used to print the retrieved value to null output * in case the compiler attempts to optimize out the whole thing * due to the retrieved value being unused. * * It takes time and alters the measured results, though. */ // fprintf(null_out, "%d", *value); } printf("%.3f s\n", ((double) (clock() - start_time) / CLOCKS_PER_SEC)); fclose(null_out); free(data); libcoll_hashmap_deinit(map); } static void benchmark_treemap(unsigned long testsize) { clock_t start_time; unsigned long retrieve_count = testsize / BENCHMARK_RETRIEVE_PROPORTION; /* null output for printing values retrieved during retrieval tests, * to prevent the compiler from optimizing the retrievals out */ FILE *null_out = get_null_output(); libcoll_treemap_t *map = libcoll_treemap_init_with_comparator(libcoll_strcmp_wrapper); libcoll_pair_voidptr_t *data = malloc(testsize * sizeof(libcoll_pair_voidptr_t)); generate_key_value_data(data, testsize); printf("Populating a treemap with %lu entries... \t", testsize); start_time = clock(); populate_treemap(map, data, testsize); printf("%.3f s\n", ((double) (clock() - start_time) / CLOCKS_PER_SEC)); start_time = clock(); printf("Retrieving %lu items... \t", retrieve_count); for (unsigned long i=0; i<retrieve_count; i++) { size_t key_idx = i * (BENCHMARK_RETRIEVE_PROPORTION); int *value = (int*) libcoll_treemap_get(map, data[key_idx].a); /* This can be used to print the retrieved value to null output * in case the compiler attempts to optimize out the whole thing * due to the retrieved value being unused. * * It takes time and alters the measured results, though. */ // fprintf(null_out, "%d", *value); } printf("%.3f s\n", ((double) (clock() - start_time) / CLOCKS_PER_SEC)); fclose(null_out); free(data); libcoll_treemap_deinit(map); } static void benchmark_vector(unsigned long testsize) { clock_t start_time; libcoll_vector_t *vect = libcoll_vector_init_with_params(1, libcoll_memaddrcmp); libcoll_pair_voidptr_t *data = malloc(testsize * sizeof(libcoll_pair_voidptr_t)); generate_key_value_data(data, testsize); printf("Appending %lu values into an empty vector, one by one... \t", testsize); start_time = clock(); populate_vector(vect, data, testsize); printf("%.3f s\n", ((double) (clock() - start_time) / CLOCKS_PER_SEC)); free(data); libcoll_vector_deinit(vect); } int main(int argc, char *argv[]) { /* disable buffering for stdout so that partial output lines get printed * without needing to wait for a line feed first */ setbuf(stdout, NULL); BenchmarkTarget target = NONE; /* parse options given on the command line */ int option_char; long benchmark_size = BENCHMARK_SIZE_DEFAULT; int benchmark_runs = BENCHMARK_RUNS_DEFAULT; while ((option_char = getopt(argc, argv, "n:t:")) != -1) { switch (option_char) { case 'n': if (sscanf(optarg, "%ld", &benchmark_size) != 1 || benchmark_size <= 0) { fprintf(stderr, "-n requires a positive integer argument\n"); return EXIT_FAILURE; } break; case 't': if (sscanf(optarg, "%d", &benchmark_runs) != 1 || benchmark_runs <= 0) { fprintf(stderr, "-t requires a positive integer argument\n"); return EXIT_FAILURE; } break; case '?': /* invalid option, either unknown or lacking a required argument */ switch (optopt) { case 'n': case 't': fprintf(stderr, "-%c requires a positive integer argument\n", optopt); return EXIT_FAILURE; default: fprintf(stderr, "Unknown option\n"); return EXIT_FAILURE; } } } if (argc > optind) { char *s = argv[optind]; if (strcmp(s, "hashmap") == 0) { target = HASHMAP; } else if (strcmp(s, "treemap") == 0) { target = TREEMAP; } else if (strcmp(s, "vector") == 0) { target = VECTOR; } } switch (target) { case HASHMAP: for (int i=0; i<benchmark_runs; i++) { printf("Benchmark run %u\n", i+1); benchmark_hashmap(benchmark_size); } break; case TREEMAP: for (int i=0; i<benchmark_runs; i++) { printf("Benchmark run %u\n", i+1); benchmark_treemap(benchmark_size); } break; case VECTOR: for (int i=0; i<benchmark_runs; i++) { printf("Benchmark run %u\n", i+1); benchmark_vector(benchmark_size); } break; case NONE: default: fprintf(stderr, "No benchmark selected\n"); break; } }
31.246528
106
0.610179
[ "vector" ]
b94ac613c032187b8a8a710a3b55a7eb35b11c3d
17,287
h
C
VecGeom/volumes/kernel/EllipticalConeImplementation.h
cxwx/VecGeom
c86c00bd7d4db08f4fc20a625020da329784aaac
[ "ECL-2.0", "Apache-2.0" ]
1
2020-06-27T18:43:36.000Z
2020-06-27T18:43:36.000Z
VecGeom/volumes/kernel/EllipticalConeImplementation.h
cxwx/VecGeom
c86c00bd7d4db08f4fc20a625020da329784aaac
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
VecGeom/volumes/kernel/EllipticalConeImplementation.h
cxwx/VecGeom
c86c00bd7d4db08f4fc20a625020da329784aaac
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// This file is part of VecGeom and is distributed under the // conditions in the file LICENSE.txt in the top directory. // For the full list of authors see CONTRIBUTORS.txt and `git log`. /// This file implements the algorithms for EllipticalCone /// @file volumes/kernel/EllipticalConeImplementation.h /// @author Raman Sehgal, Evgueni Tcherniaev #ifndef VECGEOM_VOLUMES_KERNEL_ELLIPTICALCONEIMPLEMENTATION_H_ #define VECGEOM_VOLUMES_KERNEL_ELLIPTICALCONEIMPLEMENTATION_H_ #include "VecGeom/base/Vector3D.h" #include "VecGeom/volumes/EllipticalConeStruct.h" #include "VecGeom/volumes/kernel/GenericKernels.h" #include <VecCore/VecCore> #include <cstdio> #include <iomanip> namespace vecgeom { VECGEOM_DEVICE_FORWARD_DECLARE(struct EllipticalConeImplementation;); VECGEOM_DEVICE_DECLARE_CONV(struct, EllipticalConeImplementation); inline namespace VECGEOM_IMPL_NAMESPACE { class PlacedEllipticalCone; template <typename T> struct EllipticalConeStruct; class UnplacedEllipticalCone; struct EllipticalConeImplementation { using PlacedShape_t = PlacedEllipticalCone; using UnplacedStruct_t = EllipticalConeStruct<double>; using UnplacedVolume_t = UnplacedEllipticalCone; VECCORE_ATT_HOST_DEVICE static void PrintType() { // printf("SpecializedEllipticalCone<%i, %i>", transCodeT, rotCodeT); } template <typename Stream> static void PrintType(Stream &st, int transCodeT = translation::kGeneric, int rotCodeT = rotation::kGeneric) { st << "SpecializedEllipticalCone<" << transCodeT << "," << rotCodeT << ">"; } template <typename Stream> static void PrintImplementationType(Stream &st) { (void)st; // st << "EllipticalConeImplementation<" << transCodeT << "," << rotCodeT << ">"; } template <typename Stream> static void PrintUnplacedType(Stream &st) { (void)st; // TODO: this is wrong // st << "UnplacedEllipticalCone"; } template <typename Real_v, typename Bool_v> VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void Contains(UnplacedStruct_t const &ellipticalcone, Vector3D<Real_v> const &point, Bool_v &inside) { Bool_v unused, outside; GenericKernelForContainsAndInside<Real_v, Bool_v, false>(ellipticalcone, point, unused, outside); inside = !outside; } // BIG QUESTION: DO WE WANT TO GIVE ALL 3 TEMPLATE PARAMETERS // -- OR -- DO WE WANT TO DEDUCE Bool_v, Index_t from Real_v??? template <typename Real_v, typename Inside_t> VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void Inside(UnplacedStruct_t const &ellipticalcone, Vector3D<Real_v> const &point, Inside_t &inside) { using Bool_v = vecCore::Mask_v<Real_v>; using InsideBool_v = vecCore::Mask_v<Inside_t>; Bool_v completelyinside, completelyoutside; GenericKernelForContainsAndInside<Real_v, Bool_v, true>(ellipticalcone, point, completelyinside, completelyoutside); inside = EInside::kSurface; vecCore::MaskedAssign(inside, (InsideBool_v)completelyoutside, Inside_t(EInside::kOutside)); vecCore::MaskedAssign(inside, (InsideBool_v)completelyinside, Inside_t(EInside::kInside)); } template <typename Real_v, typename Bool_v, bool ForInside> VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void GenericKernelForContainsAndInside(UnplacedStruct_t const &ellipticalcone, Vector3D<Real_v> const &point, Bool_v &completelyinside, Bool_v &completelyoutside) { /* TODO : Logic to check where the point is inside or not. ** ** if ForInside is false then it will only check if the point is outside, ** and is used by Contains function ** ** if ForInside is true then it will check whether the point is inside or outside, ** and if neither inside nor outside then it is on the surface. ** and is used by Inside function */ Real_v px = point.x() * ellipticalcone.invDx; Real_v py = point.y() * ellipticalcone.invDy; Real_v pz = point.z(); Real_v hp = vecCore::math::Sqrt(px * px + py * py) + pz; Real_v ds = (hp - ellipticalcone.fDz) * ellipticalcone.cosAxisMin; Real_v dz = vecCore::math::Abs(pz) - ellipticalcone.fZCut; Real_v safety = vecCore::math::Max(ds, dz); completelyoutside = safety > kHalfTolerance; if (ForInside) completelyinside = safety <= -kHalfTolerance; return; } template <typename Real_v> VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void DistanceToIn(UnplacedStruct_t const &ellipticalcone, Vector3D<Real_v> const &point, Vector3D<Real_v> const &direction, Real_v const & /*stepMax*/, Real_v &distance) { /* TODO : Logic to calculate Distance from outside point to the EllipticalCone surface */ using Bool_v = vecCore::Mask_v<Real_v>; Real_v kTwoEpsilon = 2. * kEpsilon; distance = Real_v(kInfLength); Real_v offset(0.); Vector3D<Real_v> p(point); // Move point closer, if required Real_v Rfar2(1024. * ellipticalcone.fRsph * ellipticalcone.fRsph); // 1024 = 32 * 32 vecCore__MaskedAssignFunc(offset, ((p.Mag2() > Rfar2) && (direction.Dot(p) < 0.)), p.Mag() - 2. * ellipticalcone.fRsph); p += offset * direction; // Special cases to keep in mind: // 0) Point is on the surface and leaving the solid // 1) Trajectory is parallel to the surface (A = 0, single root at t = -C/2B) // 2) No intersection (D < 0) or touch (D < eps) with lateral surface // 3) Exception: when the trajectory traverses the apex (D < eps) and A < 0 // then always there is an intersection with the solid // Set working variables, transform elliptican cone to cone Real_v px = p.x() * ellipticalcone.invDx; Real_v py = p.y() * ellipticalcone.invDy; Real_v pz = p.z(); Real_v pz0 = p.z() - ellipticalcone.fDz; // pz if apex would be in origin Real_v vx = direction.x() * ellipticalcone.invDx; Real_v vy = direction.y() * ellipticalcone.invDy; Real_v vz = direction.z(); // Compute coefficients of the quadratic equation: A t^2 + 2B t + C = 0 Real_v Ar = vx * vx + vy * vy; Real_v Br = px * vx + py * vy; Real_v Cr = px * px + py * py; // 1) Check if A = 0 // If so, slightly modify vz to avoid degeneration of the quadratic equation // The magnitude of vz will be modified in a way that preserves correct behavior when 0) point is leaving the solid Real_v vzvz = vz * vz; Bool_v tinyA = vecCore::math::Abs(Ar - vzvz) < kTwoEpsilon * vzvz; vecCore__MaskedAssignFunc(vz, tinyA, vz + vecCore::math::Abs(vz) * kTwoEpsilon); Real_v Az = vz * vz; Real_v Bz = pz0 * vz; Real_v Cz = pz0 * pz0; Real_v A = Ar - Az; Real_v B = Br - Bz; Real_v B0 = Br - pz0 * direction.z(); // B calculated with original v.z() Real_v C = Cr - Cz; Real_v D = B * B - A * C; // 0) Check if point is leaving the solid Real_v sfz = vecCore::math::Abs(pz) - ellipticalcone.fZCut; Real_v nz = vecCore::math::Sqrt(Cr); Real_v sfr = (nz + pz0) * ellipticalcone.cosAxisMin; vecCore::MaskedAssign(nz, (vecCore::math::Abs(p.x()) + vecCore::math::Abs(p.y()) < 0.1 * kHalfTolerance), Real_v(1.)); // point is on z-axis Real_v pzA = pz0 + ellipticalcone.dApex; // slightly shifted apex position for "flying away" check Bool_v done = (sfz >= -kHalfTolerance && pz * vz >= 0.) || (sfr >= -kHalfTolerance && Br + nz * vz >= 0.) || (pz0 * ellipticalcone.cosAxisMin > -kHalfTolerance && (Cr - pzA * pzA) <= 0. && A >= 0.); // 2) Check if scratching (D < eps & A > 0) or no intersection (D < 0) // 3) if (D < eps & A < 0) then trajectory traverses the apex area - continue calculation vecCore__MaskedAssignFunc(D, (sfr <= 0. && D < 0.), Real_v(0.)); done |= (D < 0.) || ((D < kTwoEpsilon * B * B) && (A >= 0.)); // Find intersection with Z planes Real_v invz = Real_v(-1.) / NonZero(vz); Real_v dz = vecCore::math::CopySign(Real_v(ellipticalcone.fZCut), invz); Real_v tzin = (pz - dz) * invz; Real_v tzout = (pz + dz) * invz; // Find roots of the quadratic equation Real_v tmp(0.), t1(0.), t2(0.); vecCore__MaskedAssignFunc(tmp, !done, -B - vecCore::math::CopySign(vecCore::math::Sqrt(D), B)); vecCore__MaskedAssignFunc(t1, !done, tmp / A); vecCore__MaskedAssignFunc(t2, !done && tmp != 0, C / tmp); vecCore__MaskedAssignFunc(t2, !done && tinyA && B != 0., -C / (2. * B0)); // A ~ 0, t = -C / 2B Real_v tmin = vecCore::math::Min(t1, t2); Real_v tmax = vecCore::math::Max(t1, t2); // Set default - intersection with lower nappe (A > 0) Real_v trin = tmin; Real_v trout = tmax; // Check if intersection with upper nappe only, return infinity done |= (A >= 0. && pz0 + vz * tmin >= 0.); // Check if intersection with both nappes (A < 0) vecCore__MaskedAssignFunc(trin, (!done && A < 0.), Real_v(-kInfLength)); vecCore__MaskedAssignFunc(trout, (!done && A < 0.), Real_v(kInfLength)); vecCore__MaskedAssignFunc(trin, (!done && A < 0. && vz < 0.), tmax); vecCore__MaskedAssignFunc(trout, (!done && A < 0. && vz > 0.), tmin); // Set distance // No special check for inside points, distance for inside points will be negative Real_v tin = vecCore::math::Max(tzin, trin); Real_v tout = vecCore::math::Min(tzout, trout); vecCore__MaskedAssignFunc(distance, !done && (tout - tin) >= kHalfTolerance, tin + offset); } template <typename Real_v> VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void DistanceToOut(UnplacedStruct_t const &ellipticalcone, Vector3D<Real_v> const &point, Vector3D<Real_v> const &direction, Real_v const & /* stepMax */, Real_v &distance) { /* TODO : Logic to calculate Distance from inside point to the EllipticalCone surface */ using Bool_v = vecCore::Mask_v<Real_v>; Real_v kTwoEpsilon = 2. * kEpsilon; distance = Real_v(0.); // Special cases to keep in mind: // 0) Point is on the surface and leaving the solid // 1) Trajectory is parallel to the surface (A = 0, single root at t = -C/2B) // 2) No intersection (D < 0) or touch (D < eps) with lateral surface // 3) Exception: when the trajectory traverses the apex (D < eps) and A < 0 // then always there is an intersection with the solid // Set working variables, transform elliptican cone to cone Real_v px = point.x() * ellipticalcone.invDx; Real_v py = point.y() * ellipticalcone.invDy; Real_v pz = point.z(); Real_v pz0 = pz - ellipticalcone.fDz; // pz if apex would be in origin Real_v hp = vecCore::math::Sqrt(px * px + py * py) + pz; Real_v sfr = (hp - ellipticalcone.fDz) * ellipticalcone.cosAxisMin; Real_v sfz = vecCore::math::Abs(pz) - ellipticalcone.fZCut; // Check if point is outside Bool_v outside = vecCore::math::Max(sfr, sfz) > kHalfTolerance; vecCore__MaskedAssignFunc(distance, outside, Real_v(-1.)); Bool_v done = outside; // Compute coefficients of the quadratic equation: A t^2 + 2B t + C = 0 Real_v vx = direction.x() * ellipticalcone.invDx; Real_v vy = direction.y() * ellipticalcone.invDy; Real_v vz = direction.z(); Real_v Ar = vx * vx + vy * vy; Real_v Br = px * vx + py * vy; Real_v Cr = px * px + py * py; // 1) Check if A = 0 // If so, slightly modify vz to avoid degeneration of the quadratic equation // The magnitude of vz will be modified in a way that point is leaving the solid Bool_v tinyA = vecCore::math::Abs(Ar - vz * vz) < kTwoEpsilon * vz * vz; vecCore__MaskedAssignFunc(vz, tinyA, vz + vecCore::math::Abs(vz) * kTwoEpsilon); Real_v Az = vz * vz; Real_v Bz = pz0 * vz; Real_v Cz = pz0 * pz0; Real_v A = Ar - Az; Real_v B = Br - Bz; Real_v B0 = Br - pz0 * direction.z(); // B calculated with original v.z() Real_v C = Cr - Cz; Real_v D = B * B - A * C; vecCore__MaskedAssignFunc(D, (sfr <= 0. && D < 0.), Real_v(0.)); // 2) Check if scratching (D < eps & A > 0) or no intersection (D < 0) // 3) if (D < eps & A < 0) then trajectory traverses the apex area - continue calculation done |= (D < 0.) || (D < kTwoEpsilon * B * B && A >= 0.); // Find intersection with Z planes Real_v tzout = kMaximum; vecCore__MaskedAssignFunc(tzout, vz != 0., (vecCore::math::CopySign(Real_v(ellipticalcone.fZCut), vz) - pz) / direction.z()); // Find roots of the quadratic equation Real_v tmp(0.), t1(0.), t2(0.); vecCore__MaskedAssignFunc(tmp, !done, -B - vecCore::math::CopySign(vecCore::math::Sqrt(D), B)); vecCore__MaskedAssignFunc(t1, !done, tmp / A); vecCore__MaskedAssignFunc(t2, !done && tmp != 0., C / tmp); vecCore__MaskedAssignFunc(t2, !done && tinyA && B0 != 0., -C / (2. * B0)); // A ~ 0, t = -C / 2B Real_v tmin = vecCore::math::Min(t1, t2); Real_v tmax = vecCore::math::Max(t1, t2); // Set default - intersection with lower nappe (A > 0) Real_v trout = tmax; // Check if intersection with upper nappe only or flying away, return 0 done |= ((A >= 0. && pz0 + vz * tmax >= 0.) || (pz0 >= 0. && vz >= 0.)); // Check if intersection with both nappes (A < 0) vecCore__MaskedAssignFunc(trout, (!done && A < 0.), Real_v(kInfLength)); vecCore__MaskedAssignFunc(trout, (!done && A < 0. && vz > 0.), tmin); // Set distance // No special check for inside points, distance for inside points will be negative vecCore__MaskedAssignFunc(distance, !done, vecCore::math::Min(tzout, trout)); } template <typename Real_v> VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void SafetyToIn(UnplacedStruct_t const &ellipticalcone, Vector3D<Real_v> const &point, Real_v &safety) { /* TODO : Logic to calculate Safety from outside point to the EllipticalCone surface */ Real_v px = point.x() * ellipticalcone.invDx; Real_v py = point.y() * ellipticalcone.invDy; Real_v pz = point.z(); Real_v hp = vecCore::math::Sqrt(px * px + py * py) + pz; Real_v ds = (hp - ellipticalcone.fDz) * ellipticalcone.cosAxisMin; Real_v dz = vecCore::math::Abs(pz) - ellipticalcone.fZCut; safety = vecCore::math::Max(ds, dz); vecCore::MaskedAssign(safety, vecCore::math::Abs(safety) <= kHalfTolerance, Real_v(0.)); } template <typename Real_v> VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void SafetyToOut(UnplacedStruct_t const &ellipticalcone, Vector3D<Real_v> const &point, Real_v &safety) { /* TODO : Logic to calculate Safety from inside point to the EllipticalCone surface */ Real_v px = point.x() * ellipticalcone.invDx; Real_v py = point.y() * ellipticalcone.invDy; Real_v pz = point.z(); Real_v hp = vecCore::math::Sqrt(px * px + py * py) + pz; Real_v ds = (ellipticalcone.fDz - hp) * ellipticalcone.cosAxisMin; Real_v dz = ellipticalcone.fZCut - vecCore::math::Abs(pz); safety = vecCore::math::Min(ds, dz); vecCore::MaskedAssign(safety, vecCore::math::Abs(safety) <= kHalfTolerance, Real_v(0.)); } template <typename Real_v> VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static Vector3D<Real_v> NormalKernel(UnplacedStruct_t const &ellipticalcone, Vector3D<Real_v> const &point, typename vecCore::Mask_v<Real_v> &valid) { // Computes the normal on a surface and returns it as a unit vector // In case if the point is further than kHalfTolerance from the surface, set valid=false // Must return a valid vector (even if the point is not on the surface) // // On an edge provide an average normal of the corresponding base and lateral surface Vector3D<Real_v> normal(0., 0., 0.); valid = true; // Check z planes Real_v px = point.x(); Real_v py = point.y(); Real_v pz = point.z(); Real_v dz = vecCore::math::Abs(pz) - ellipticalcone.fZCut; vecCore__MaskedAssignFunc(normal[2], vecCore::math::Abs(dz) <= kHalfTolerance, vecCore::math::Sign(pz)); // Check lateral surface Real_v nx = px * ellipticalcone.invDx * ellipticalcone.invDx; Real_v ny = py * ellipticalcone.invDy * ellipticalcone.invDy; Real_v nz = vecCore::math::Sqrt(px * nx + py * ny); vecCore__MaskedAssignFunc(nz, (nx * nx + ny * ny) == 0., 1.); // z-axis Vector3D<Real_v> nside(nx, ny, nz); Real_v ds = (nz + pz - ellipticalcone.fDz) * ellipticalcone.cosAxisMin; vecCore__MaskedAssignFunc(normal, vecCore::math::Abs(ds) <= kHalfTolerance, (normal + nside.Unit()).Unit()); // Check if done vecCore::Mask_v<Real_v> done = normal.Mag2() > 0.; if (vecCore::MaskFull(done)) return normal; // Point is not on the surface - normally, this should never be // Return normal to the nearest surface vecCore__MaskedAssignFunc(valid, !done, false); vecCore__MaskedAssignFunc(normal[2], !done, vecCore::math::Sign(pz)); vecCore__MaskedAssignFunc(normal, !done && ds > dz, nside.Unit()); return normal; } }; } // namespace VECGEOM_IMPL_NAMESPACE } // namespace vecgeom #endif // VECGEOM_VOLUMES_KERNEL_ELLIPTICALCONEIMPLEMENTATION_H_
44.439589
120
0.660323
[ "vector", "transform", "solid" ]
b94dd4ef8930457c441efad392b0491e9c080ffe
1,763
h
C
src/Regex.h
guluchen/Trau
ed474504041b3890833b2273361108c578f9d34d
[ "MIT" ]
5
2017-07-06T16:11:56.000Z
2018-08-06T06:02:20.000Z
src/Regex.h
guluchen/Trau
ed474504041b3890833b2273361108c578f9d34d
[ "MIT" ]
4
2019-06-27T18:47:51.000Z
2019-07-15T18:34:17.000Z
src/Regex.h
guluchen/Trau
ed474504041b3890833b2273361108c578f9d34d
[ "MIT" ]
2
2018-09-12T03:36:41.000Z
2019-03-27T02:30:29.000Z
/* * regex.h * * Created on: Jan 31, 2017 * Author: diepbp */ #ifndef REGEX_H_ #define REGEX_H_ #include "Automaton.h" #include "RegexState.h" class RegEx { public: RegEx(); ~RegEx(); bool Compile(std::string strRegEx); bool Match(std::string strText); bool MatchAll(std::string strText); typedef std::vector<RegExState*> Table; typedef Table::reverse_iterator TableReverseIterator; typedef Table::iterator TableIterator; typedef std::set<RegExState*>::iterator StateIterator; Automaton CreateAutomaton(std::string name); private: Table m_NFATable; Table m_DFATable; std::stack<Table > m_CharacterClassStack; std::stack<char> m_ExpressionStack; std::set<char> m_InputSet; std::string m_strText; std::string m_PostStrRegEx; char* m_InfixRegEx; char m_CurPreProcChar; int m_nNextStateID; bool ConstructThompsonNFA(); void PushOnCharacterStack(char chInput); bool PopTable(Table &NFATable); bool Concatenate(); bool Closure(); bool ClosureOptional(); bool ClosurePlus(); bool Or(); bool IsMetaChar(char inputCh); bool IsInput(char inputCh); bool IsLeftParan(char inputCh); bool IsRightParan(char inputCh); void EpsilonClosure(std::set<RegExState*> T, std::set<RegExState*> &Res); void Move(char chInput, std::set<RegExState*> T, std::set<RegExState*> &Res); void ConvertNFAtoDFA(); void ReduceDFA(); void CleanUp(); int CovertToPostfix(); int PreProcessLiterals(); int PreProcessClosure(); int PrePreprocessConcatenation(); int PreProcessOr(); std::string PreProcessBracket( std::string strRegEx); void MinimizeDFA (); void PrintTable(Table &table); protected: }; #endif /* REGEX_H_ */
23.506667
78
0.693137
[ "vector" ]
b95106347f03e19746b57495f626e7ff31b7ad5f
2,654
h
C
planning/mission_planning/mission_planner/include/mission_planner/mission_planner_base.h
betsyweilin/Pilot.Auto
41946ba1f5b521d347581cb7bdaffe1e39a7ba33
[ "Apache-2.0" ]
null
null
null
planning/mission_planning/mission_planner/include/mission_planner/mission_planner_base.h
betsyweilin/Pilot.Auto
41946ba1f5b521d347581cb7bdaffe1e39a7ba33
[ "Apache-2.0" ]
null
null
null
planning/mission_planning/mission_planner/include/mission_planner/mission_planner_base.h
betsyweilin/Pilot.Auto
41946ba1f5b521d347581cb7bdaffe1e39a7ba33
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Autoware Foundation. 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 MISSION_PLANNER_MISSION_PLANNER_BASE_H #define MISSION_PLANNER_MISSION_PLANNER_BASE_H // ROS #include <rclcpp/rclcpp.hpp> #include <tf2_ros/transform_listener.h> #include <visualization_msgs/msg/marker_array.hpp> // Autoware #include <autoware_planning_msgs/msg/route.hpp> #include <geometry_msgs/msg/pose_stamped.hpp> #include <geometry_msgs/msg/pose_with_covariance_stamped.hpp> // others #include <string> #include <vector> namespace mission_planner { class MissionPlanner : public rclcpp::Node { protected: MissionPlanner(const std::string & node_name); geometry_msgs::msg::PoseStamped goal_pose_; geometry_msgs::msg::PoseStamped start_pose_; std::vector<geometry_msgs::msg::PoseStamped> checkpoints_; std::string base_link_frame_; std::string map_frame_; rclcpp::Publisher<visualization_msgs::msg::MarkerArray>::SharedPtr marker_publisher_; virtual bool isRoutingGraphReady() const = 0; virtual autoware_planning_msgs::msg::Route planRoute() = 0; virtual void visualizeRoute(const autoware_planning_msgs::msg::Route & route) const = 0; virtual void publishRoute(const autoware_planning_msgs::msg::Route & route) const; private: rclcpp::Publisher<autoware_planning_msgs::msg::Route>::SharedPtr route_publisher_; rclcpp::Subscription<geometry_msgs::msg::PoseStamped>::SharedPtr goal_subscriber_; rclcpp::Subscription<geometry_msgs::msg::PoseStamped>::SharedPtr checkpoint_subscriber_; tf2_ros::Buffer tf_buffer_; tf2_ros::TransformListener tf_listener_; bool getEgoVehiclePose(geometry_msgs::msg::PoseStamped * ego_vehicle_pose); void goalPoseCallback(const geometry_msgs::msg::PoseStamped::ConstSharedPtr goal_msg_ptr); void checkpointCallback(const geometry_msgs::msg::PoseStamped::ConstSharedPtr checkpoint_msg_ptr); bool transformPose( const geometry_msgs::msg::PoseStamped & input_pose, geometry_msgs::msg::PoseStamped * output_pose, const std::string target_frame); }; } // namespace mission_planner #endif // MISSION_PLANNER_MISSION_PLANNER_BASE_H
36.356164
102
0.788244
[ "vector" ]
b95635f1bdc64cbb2c821dd39070a937247e7fa7
4,093
h
C
WinDBG/Exts/CodeAnalyzer/gdbplus/gdb-7.7/gdb/decode.h
QuincyWork/DebugExt
95fbd81aad609ed41853b5d25129d2385f5593b2
[ "MIT" ]
1
2019-01-15T14:36:41.000Z
2019-01-15T14:36:41.000Z
WinDBG/Exts/CodeAnalyzer/gdbplus/gdb-7.7/gdb/decode.h
QuincyWork/DebugExt
95fbd81aad609ed41853b5d25129d2385f5593b2
[ "MIT" ]
null
null
null
WinDBG/Exts/CodeAnalyzer/gdbplus/gdb-7.7/gdb/decode.h
QuincyWork/DebugExt
95fbd81aad609ed41853b5d25129d2385f5593b2
[ "MIT" ]
1
2019-01-15T14:36:42.000Z
2019-01-15T14:36:42.000Z
/* * decode.h * * Created on: Aug 22, 2014 * Author: myan */ #ifndef DECODE_H_ #define DECODE_H_ #include "x_dep.h" #include "x_type.h" #include "opcode/i386.h" /* * types for decode function */ // Register index #define RAX 0 #define RCX 1 #define RDX 2 #define RBX 3 #define RSP 4 #define RBP 5 #define RSI 6 #define RDI 7 #define R8 8 #define R9 9 #define R10 10 #define R11 11 #define R12 12 #define R13 13 #define R14 14 #define R15 15 #define RIP 16 #define RXMM0 17 #define RXMM1 18 #define RXMM2 19 #define RXMM3 20 #define RXMM4 21 #define RXMM5 22 #define RXMM6 23 #define RXMM7 24 #define RXMM8 25 #define RXMM9 26 #define RXMM10 27 #define RXMM11 28 #define RXMM12 29 #define RXMM13 30 #define RXMM14 31 #define RXMM15 32 #define TOTAL_REGS 33 /* * structure for an instruction operand */ enum ca_operand_type { CA_OP_UNSET, CA_OP_REGISTER, CA_OP_IMMEDIATE, CA_OP_MEMORY, }; struct ca_op_register { const char* name; int size; int index; }; struct ca_op_immediate { bfd_vma immediate; }; struct ca_op_memory { struct ca_op_register base_reg; struct ca_op_register index_reg; struct ca_op_immediate disp; int scale; }; struct ca_operand { enum ca_operand_type type; union { struct ca_op_register reg; struct ca_op_immediate immed; struct ca_op_memory mem; }; }; /* * Structure to record a disassembled instruction */ #define MAX_OPCODE_NAME_SZ 8 struct ca_dis_insn { // instruction address CORE_ADDR pc; // disassembled text char* dis_string; // opcode name char opcode_name[MAX_OPCODE_NAME_SZ]; // operands struct ca_operand operands[MAX_OPERANDS]; int op_size; int num_operand; // the following members are set with help of current context CORE_ADDR branch_pc; // destination address of a branch instruction unsigned int annotate:1; // this instruction is suitable for annotation unsigned int branch:1; // branch instruction unsigned int call:1; // call instruction unsigned int lea:1; // lea instruction unsigned int push:1; // push instruction unsigned int jmp:1; // jmp instruction unsigned int jmp_target:1; // current instruction is the target of another jmp instruciton unsigned int reserved:26; }; /* * Register value/symbol/type at certain "pc" */ struct ca_reg_value { // instruction address at which the value is set CORE_ADDR pc; char* sym_name; struct type* type; size_t value; // flags unsigned int has_value:1; unsigned int vptr:1; // _vptr, i.e. pointer to "vtable for class T" unsigned int reserved:30; }; #define REG_KNOWN(reg) ((reg)->has_value || (reg)->sym_name || (reg)->type) /* * Values of a register at various (ascending) instruction addresses * [0] is for the initial value, e.g. input parameters * [1], [2], .., are values/symbols/types when the register is changed */ struct ca_reg_vector { struct ca_reg_value* start; struct ca_reg_value* finish; struct ca_reg_value* end_of_storage; }; #define REG_SET_SZ sizeof(struct ca_reg_value [TOTAL_REGS]) /* * A table of all registers interested */ struct ca_reg_table { struct ca_reg_vector vecs[TOTAL_REGS]; // vector of each register expands as it changes struct ca_reg_value* cur_regs[TOTAL_REGS]; // pointers to registers at current "pc" }; /* * Context of a decoded function */ struct decode_control_block { struct gdbarch* gdbarch; struct ui_out* uiout; struct disassemble_info* di; CORE_ADDR low; // User picked instruction range [low, hight] CORE_ADDR high; CORE_ADDR current; // Instruction being executed, i.e. "call" if not innermost frame CORE_ADDR func_start; // Function range [start, end] CORE_ADDR func_end; struct ca_dis_insn* insn; struct ca_reg_value* param_regs; // parameters known at the function entry struct ca_reg_value* user_regs; // user-inputed register values unsigned int verbose:1; unsigned int innermost_frame:1; unsigned int reserved:30; }; extern void decode_func(char *arg); extern int decode_insns(struct decode_control_block*); extern int ca_print_insn_i386(bfd_vma pc, struct decode_control_block*); #endif // DECODE_H_
22.005376
91
0.739311
[ "vector" ]
b95f29ab41cb8b2fa385dca65782ce93cdf28e0e
3,532
c
C
d/shadow/room/deep_echos/enter.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/shadow/room/deep_echos/enter.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/shadow/room/deep_echos/enter.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
//ce1 #include <std.h> #include <rooms.h> #include <daemons.h> #include "deep_echo.h" inherit ROOM; void create(){ ::create(); set_property("light",-1); set_terrain(NAT_CAVE); set_travel(RUTTED_TRACK); set_name("On the ledge of a cliff."); set_short("A very unstable ledge."); set_long((:TO,"ldesc":)); set_smell("default","A bad smell floats out of the cave."); set_listen("default","The wind howls as it races past you."); set_items(([ "ledge":"The ledge is made of some sort of very unstable rock that is " "cracked and crumbling. The ledge itself is only about two feet wide and six " "feet long.", ({"cliff","cliff face"}):"The cliff face is is sheer"+ " here, with the exception of this little ledge."+ " It is one hundred feet to the bottom and"+ " another five hundred or so to the top. "+ "The rocks look too unstable to climb or _descend_ easily.", ({"opening","cave","cave opening"}):"The opening in"+ " the side of the cliff leads into a dark cave."+ " It is about twenty feet in height and leads"+ " into the darkness. From here you cannot tell "+ "where it leads or what is inside."])); set_search("default", "Nothing but wet rocks."); set_exits((["east":"/d/shadow/room/mountain/cave30"])); set_climb_exits((["descend":({ROOMS"up.c",20,roll_dice(10,8),100})])); new(OBJ"sign")->move(TO); } string ldesc(string str){ return("%^BOLD%^%^BLACK%^This is a very narrow "+ "%^RESET%^ledge%^BOLD%^%^BLACK%^ on the %^RESET%^cliff%^BOLD%^%^BLACK%^ that"+ " is perhaps only two feet in width and six feet long. The"+ " rocks"+ " are slippery from water dripping down. "+ " The cliff face is sheer as it extends "+ "further up and down. A large %^RESET%^opening%^BOLD%^%^BLACK%^ is here,"+ " leading into a cave that seems to be about twenty feet"+ " in height. The wind races past. One is barely able to hold on.\n"); } void fallen_angels(){ object *livings,*inven; int i,j,x; livings = ({}); livings =filter_array(all_living(TO),"is_non_immortal_player",FILTERS_D); j= sizeof(inven); tell_room(TO,"Wind blows through the area, shaking you on the wet rocks."); j = sizeof(livings); if(!sizeof(livings)) return; for(i=0;i<j;i++){ if((random(25)-5) > livings[i]->query_stats("dexterity")){ tell_room(TO,""+livings[i]->query_cap_name()+ "slips on the wet ledge and disappears down"+ " the dark chasm!",livings[i]); tell_object(livings[i],"You slip and fall down the"+ " chasm! You hit several jagged rocks on "+ "the way down."); if (!livings[i]->query_ghost()){ livings[i]->move_player(ROOMS"up"); livings[i]->add_attacker(TO); for(x=1;x<10;x++) livings[i]->do_damage("torso",roll_dice(1,8)); livings[i]->continue_attack(); if(!objectp(livings[i])) continue; livings[i]->remove_attacker(TO); tell_room(find_object_or_load(ROOMS"up"),""+ livings[i]->query_cap_name()+ " falls down with a thud!",livings[i]); } } else{ tell_room(TO,""+livings[i]->query_cap_name()+ " slips but manages not to fall!",livings[i]); tell_object(livings[i],"You slip but"+ " manage to keep from falling!"); } } call_out("fallen_angels",30+random(30)); } void init(){ ::init(); if(find_call_out("fallen_angels")==-1) fallen_angels(); }
34.970297
83
0.6141
[ "object" ]
b966520f7b4da7e2b5f8639f3fac68121d7d97e3
5,470
c
C
student/student.c
weslse/SystemProgramming_HansungUni_2018
60d033af496f27759594600acde60c0d40737ae2
[ "MIT" ]
null
null
null
student/student.c
weslse/SystemProgramming_HansungUni_2018
60d033af496f27759594600acde60c0d40737ae2
[ "MIT" ]
null
null
null
student/student.c
weslse/SystemProgramming_HansungUni_2018
60d033af496f27759594600acde60c0d40737ae2
[ "MIT" ]
null
null
null
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> struct student { int rollno; char name[50]; int p_marks, c_marks; double per; char grade; }st; int fd; void write_student() { fd = open("student.dat", O_RDWR|O_CREAT, 0644); while ((read(fd, &st, sizeof(st))) > 0) { if (st.rollno == -100){ lseek(fd, -(long)sizeof(st), SEEK_CUR); break; } } printf("\nPlease Enter The New Details of student \n"); printf("\nEnter The roll number of student "); scanf(" %d", &st.rollno); getchar(); printf("\nEnter The Name of student "); fgets(st.name, sizeof(st.name), stdin); st.name[strlen(st.name) - 1] = '\0'; printf("\nEnter The marks in physics out of 100 : "); scanf(" %d", &st.p_marks); printf("\nEnter The marks in chemistry out of 100 : "); scanf(" %d", &st.c_marks); st.per = (st.p_marks + st.c_marks) / 2.0; if (st.per >= 60) st.grade = 'A'; else if (st.per >=50 && st.per < 60) st.grade = 'B'; else if (st.per >= 33 && st.per < 50) st.grade = 'C'; else st.grade = 'F'; //lseek(fd, 0, SEEK_END); write(fd, &st, sizeof(st)); close(fd); printf("\n\nStudent Record Has Been Created. Press any key.... "); getchar(); getchar(); } void display_all() { system("clear"); printf("\n\n\n\n\t\tDISPLAY ALL RECORD !!!\n\n"); printf("===========================================================\n"); printf("R.No. Name P C Ave Grade\n"); printf("===========================================================\n"); fd = open("student.dat", O_RDONLY); if (fd == -1) return; while ((read(fd, &st, sizeof(st))) > 0) { if (st.rollno == -100) continue; printf("%-6d %-10s %-3d %-3d %-3.2f %-1c\n", st.rollno, st.name, st.p_marks, st.c_marks, st.per, st.grade); } close(fd); getchar(); } void display_sp(int n) { int flag = 0; fd = open("student.dat", O_RDONLY); if (fd == -1) return; while ((read(fd, &st, sizeof(st))) > 0) { if (st.rollno == -100) break; if (st.rollno == n) { system("clear"); printf("\nRoll number of student : %d", st.rollno); printf("\nName of student : %s", st.name); printf("\nMarks in Physics : %d", st.p_marks); printf("\nMarks in Chemistry : %d", st.c_marks); printf("\nPercentage of student is : %.2f", st.per); printf("\nGrade of student is : %c", st.grade); printf("\n\n"); flag = 1; } } close(fd); if (flag == 0) printf("\n\nrecord not exist"); getchar(); getchar(); } void modify_student() { int no, found = 0; system("clear"); printf("\n\n\tTo Modify "); printf("\n\n\tPlease Enter The roll number of student >> "); scanf(" %d", &no); fd = open("student.dat", O_RDWR); if (fd == -1) return; while ((read(fd, &st, sizeof(st))) > 0 && found == 0) { if(no == -100) break; if (st.rollno == no) { printf("\nRoll number of student : %d", st.rollno); printf("\nName of student : %s", st.name); printf("\nMarks in Physics : %d", st.p_marks); printf("\nMarks in Chemistry : %d", st.c_marks); printf("\nPercentage of student is : %.2f", st.per); printf("\nGrade of student is : %c", st.grade); printf("\nPlease Enter The New Details of student \n"); printf("\nEnter The roll number of student "); scanf(" %d", &st.rollno); getchar(); printf("\n\nEnter The Name of student "); fgets(st.name, sizeof(st.name), stdin); st.name[strlen(st.name) - 1] = '\0'; printf("\nEnter The marks in physics out of 100 : "); scanf(" %d", &st.p_marks); printf("\nEnter The marks in chemistry out of 100 : "); scanf(" %d", &st.c_marks); st.per = (st.p_marks + st.c_marks) / 2.0; if (st.per >= 60) st.grade = 'A'; else if (st.per >= 50 && st.per < 60) st.grade = 'B'; else if (st.per >= 33 & st.per < 50) st.grade = 'C'; else st.grade = 'F'; lseek(fd, -(long)sizeof(st), SEEK_CUR); write(fd, &st, sizeof(st)); printf("\n\n\t Record Updated"); found = 1; } } close(fd); if (found == 0) printf("\n\n Record Not Found "); getchar(); } void delete_student() { int no; int found = 0; system("clear"); printf("\n\n\n\tDelete Record"); printf("\n\nPlease Enter The roll number of student You Want To Delete >>"); scanf(" %d", &no); fd = open("student.dat", O_RDWR); if (fd == -1) return; while((read(fd, &st, sizeof(st)) > 0) && found == 0 ) { if(st.rollno == no) { st.rollno = -100; found = 1; lseek(fd, -(long)sizeof(st), SEEK_CUR); write(fd, &st, sizeof(st)); printf("\n\n\tRecord Deleted .. "); break; } } close(fd); if (found == 0) printf("\n\n Record Not Found "); getchar(); getchar(); } int main() { char ch; int num; do { system("clear"); printf("\n\n\t1.CREATE STUDENT RECORD"); printf("\n\n\t2.DISPLAY ALL STUDENTS RECORDS"); printf("\n\n\t3.SEARCH STUDENT RECORD"); printf("\n\n\t4.MODIFY STUDENT RECORD"); printf("\n\n\t5.DELETE STUDENT RECORD"); printf("\n\n\t6.exit"); printf("\n\n\tPlease Enter Your Choice (1-6) "); ch = getchar(); getchar(); switch(ch) { case '1': system("clear"); write_student(); break; case '2': display_all(); break; case '3': system("clear"); printf("\n\n\tPlease Enter The roll number "); scanf(" %d", &num); display_sp(num); break; case '4': modify_student(); break; case '5': delete_student(); break; case '6': break; default: printf("\a"); } } while (ch != '6'); }
22.887029
77
0.56691
[ "3d" ]
570aa1407e586f5b683cb88c949fe84a9793dd11
61,706
c
C
ps4000a/ps4000aCon/ps4000aCon.c
stefanos1316/picosdk-c-examples
56b174f7ad31f1a7195809dd576853e73dcc61c8
[ "ISC" ]
34
2018-01-27T03:29:31.000Z
2022-03-22T00:13:58.000Z
ps4000a/ps4000aCon/ps4000aCon.c
stefanos1316/picosdk-c-examples
56b174f7ad31f1a7195809dd576853e73dcc61c8
[ "ISC" ]
6
2017-12-14T13:56:31.000Z
2019-04-17T11:00:15.000Z
ps4000a/ps4000aCon/ps4000aCon.c
stefanos1316/picosdk-c-examples
56b174f7ad31f1a7195809dd576853e73dcc61c8
[ "ISC" ]
38
2017-05-16T08:47:10.000Z
2021-06-07T18:53:34.000Z
/******************************************************************************* * * Filename: ps4000aCon.c * * Description: * This is a console mode program that demonstrates how to use the * PicoScope 4000 Series (ps4000a) driver API functions. * * Supported PicoScope models: * * PicoScope 4225 & 4425 * PicoScope 4444 * PicoScope 4824 * * Examples: * Collect a block of samples immediately * Collect a block of samples when a trigger event occurs * Collect data in rapid block mode * Collect a stream of data immediately * Collect a stream of data when a trigger event occurs * Set Signal Generator, using standard or custom signals * Change timebase & voltage scales * Display data in mV or ADC counts * * To build this application:- * * If Microsoft Visual Studio (including Express) is being used: * * Select the solution configuration (Debug/Release) and platform (x86/x64) * Ensure that the 32-/64-bit ps4000a.lib can be located * Ensure that the ps4000aApi.h, PicoConnectProbes.h and PicoStatus.h * files can be located * * Otherwise: * * Set up a project for a 32-/64-bit console mode application * Add this file to the project * Add ps4000a.lib to the project (Microsoft C only) * Add ps4000aApi.h, PicoConnectProbes.h and PicoStatus.h to the project * Build the project * * Linux platforms: * * Ensure that the libps4000a driver package has been installed using the * instructions from https://www.picotech.com/downloads/linux * * Place this file in the same folder as the files from the linux-build-files * folder. In a terminal window, use the following commands to build * the ps4000aCon application: * * ./autogen.sh <ENTER> * make <ENTER> * * Copyright (C) 2013-2018 Pico Technology Ltd. See LICENSE file for terms. * ******************************************************************************/ #include <stdio.h> /* Headers for Windows */ #ifdef _WIN32 #include "windows.h" #include <conio.h> #include "ps4000aApi.h" #else #include <sys/types.h> #include <string.h> #include <termios.h> #include <sys/ioctl.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <ctype.h> #include <libps4000a-1.0/ps4000aApi.h> #ifndef PICO_STATUS #include <libps4000a-1.0/PicoStatus.h> #endif #define Sleep(a) usleep(1000*a) #define scanf_s scanf #define fscanf_s fscanf #define memcpy_s(a,b,c,d) memcpy(a,c,d) typedef enum enBOOL{FALSE,TRUE} BOOL; /* A function to detect a keyboard press on Linux */ int32_t _getch() { struct termios oldt, newt; int32_t ch; int32_t bytesWaiting; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~( ICANON | ECHO ); tcsetattr(STDIN_FILENO, TCSANOW, &newt); setbuf(stdin, NULL); do { ioctl(STDIN_FILENO, FIONREAD, &bytesWaiting); if (bytesWaiting) getchar(); } while (bytesWaiting); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); return ch; } int32_t _kbhit() { struct termios oldt, newt; int32_t bytesWaiting; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~( ICANON | ECHO ); tcsetattr(STDIN_FILENO, TCSANOW, &newt); setbuf(stdin, NULL); ioctl(STDIN_FILENO, FIONREAD, &bytesWaiting); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); return bytesWaiting; } int32_t fopen_s(FILE ** a, const char * b, const char * c) { FILE * fp = fopen(b,c); *a = fp; return (fp>0)?0:-1; } /* A function to get a single character on Linux */ #define max(a,b) ((a) > (b) ? a : b) #define min(a,b) ((a) < (b) ? a : b) #endif int32_t cycles = 0; #define BUFFER_SIZE 1024 #define OCTO_SCOPE 8 #define QUAD_SCOPE 4 #define DUAL_SCOPE 2 #define MAX_PICO_DEVICES 64 #define TIMED_LOOP_STEP 500 typedef struct { int16_t DCcoupled; int16_t range; int16_t enabled; float analogueOffset; }CHANNEL_SETTINGS; typedef struct tPwq { PS4000A_CONDITION * conditions; int16_t nConditions; PS4000A_THRESHOLD_DIRECTION direction; uint32_t lower; uint32_t upper; PS4000A_PULSE_WIDTH_TYPE type; }PWQ; typedef enum { MODEL_NONE = 0, MODEL_PS4824 = 0x12d8, MODEL_PS4225 = 0x1081, MODEL_PS4425 = 0x1149, MODEL_PS4444 = 0x115C } MODEL_TYPE; typedef enum { SIGGEN_NONE = 0, SIGGEN_FUNCTGEN = 1, SIGGEN_AWG = 2 } SIGGEN_TYPE; typedef struct { int16_t handle; MODEL_TYPE model; int8_t modelString[8]; int8_t serial[11]; int16_t complete; int16_t openStatus; int16_t openProgress; PS4000A_RANGE firstRange; PS4000A_RANGE lastRange; int16_t channelCount; int16_t maxADCValue; SIGGEN_TYPE sigGen; int16_t hasETS; uint16_t AWGFileSize; CHANNEL_SETTINGS channelSettings [PS4000A_MAX_CHANNELS]; uint16_t hasFlexibleResolution; uint16_t hasIntelligentProbes; PS4000A_DEVICE_RESOLUTION resolution; }UNIT; // Struct to store intelligent probe information typedef struct tUserProbeInfo { PICO_STATUS status; PS4000A_USER_PROBE_INTERACTIONS userProbeInteractions[PS4000A_MAX_4_CHANNELS]; uint32_t numberOfProbes; }USER_PROBE_INFO; uint32_t timebase = 8; BOOL scaleVoltages = TRUE; uint16_t inputRanges [PS4000A_MAX_RANGES] = { 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000}; int16_t g_autoStopped; int16_t g_ready = FALSE; uint64_t g_times [PS4000A_MAX_CHANNELS]; int16_t g_timeUnit; int32_t g_sampleCount; uint32_t g_startIndex; int16_t g_trig = 0; uint32_t g_trigAt = 0; int16_t g_probeStateChanged = 0; USER_PROBE_INFO userProbeInfo; int8_t BlockFile[20] = "block.txt"; int8_t StreamFile[20] = "stream.txt"; typedef struct tBufferInfo { UNIT * unit; int16_t **driverBuffers; int16_t **appBuffers; } BUFFER_INFO; /**************************************************************************** * Streaming Callback * used by ps4000a data streaming collection calls, on receipt of data. * used to set global flags etc checked by user routines ****************************************************************************/ void PREF4 CallBackStreaming( short handle, int32_t noOfSamples, uint32_t startIndex, int16_t overflow, uint32_t triggerAt, int16_t triggered, int16_t autoStop, void *pParameter) { int32_t channel; BUFFER_INFO * bufferInfo = NULL; if (pParameter != NULL) { bufferInfo = (BUFFER_INFO *) pParameter; } // used for streaming g_sampleCount = noOfSamples; g_startIndex = startIndex; g_autoStopped = autoStop; // flag to say done reading data g_ready = TRUE; // flags to show if & where a trigger has occurred g_trig = triggered; g_trigAt = triggerAt; if (bufferInfo != NULL && noOfSamples) { for (channel = 0; channel < bufferInfo->unit->channelCount; channel++) { if (bufferInfo->unit->channelSettings[channel].enabled) { if (bufferInfo->appBuffers && bufferInfo->driverBuffers) { // Max buffers if (bufferInfo->appBuffers[channel * 2] && bufferInfo->driverBuffers[channel * 2]) { memcpy_s (&bufferInfo->appBuffers[channel * 2][startIndex], noOfSamples * sizeof(int16_t), &bufferInfo->driverBuffers[channel * 2][startIndex], noOfSamples * sizeof(int16_t)); } // Min buffers if (bufferInfo->appBuffers[channel * 2 + 1] && bufferInfo->driverBuffers[channel * 2 + 1]) { memcpy_s (&bufferInfo->appBuffers[channel * 2 + 1][startIndex], noOfSamples * sizeof(int16_t), &bufferInfo->driverBuffers[channel * 2 + 1][startIndex], noOfSamples * sizeof(int16_t)); } } } } } } /**************************************************************************** * Block Callback * used by ps4000a data block collection calls, on receipt of data. * used to set global flags etc checked by user routines ****************************************************************************/ void PREF4 CallBackBlock( int16_t handle, PICO_STATUS status, void * pParameter) { if (status != PICO_CANCELLED) { g_ready = TRUE; } } /**************************************************************************** * Probe Interaction Callback * * See ps4000aProbeInteractions (callback) * ****************************************************************************/ void PREF4 CallBackProbeInteractions(int16_t handle, PICO_STATUS status, PS4000A_USER_PROBE_INTERACTIONS * probes, uint32_t nProbes) { uint32_t i = 0; userProbeInfo.status = status; userProbeInfo.numberOfProbes = nProbes; for (i = 0; i < nProbes; ++i) { userProbeInfo.userProbeInteractions[i].connected = probes[i].connected; userProbeInfo.userProbeInteractions[i].channel = probes[i].channel; userProbeInfo.userProbeInteractions[i].enabled = probes[i].enabled; userProbeInfo.userProbeInteractions[i].probeName = probes[i].probeName; userProbeInfo.userProbeInteractions[i].requiresPower_ = probes[i].requiresPower_; userProbeInfo.userProbeInteractions[i].isPowered_ = probes[i].isPowered_; userProbeInfo.userProbeInteractions[i].status_ = probes[i].status_; userProbeInfo.userProbeInteractions[i].probeOff = probes[i].probeOff; userProbeInfo.userProbeInteractions[i].rangeFirst_ = probes[i].rangeFirst_; userProbeInfo.userProbeInteractions[i].rangeLast_ = probes[i].rangeLast_; userProbeInfo.userProbeInteractions[i].rangeCurrent_ = probes[i].rangeLast_; userProbeInfo.userProbeInteractions[i].couplingFirst_ = probes[i].couplingFirst_; userProbeInfo.userProbeInteractions[i].couplingLast_ = probes[i].couplingLast_; userProbeInfo.userProbeInteractions[i].couplingCurrent_ = probes[i].couplingCurrent_; userProbeInfo.userProbeInteractions[i].filterFlags_ = probes[i].filterFlags_; userProbeInfo.userProbeInteractions[i].filterCurrent_ = probes[i].filterCurrent_; userProbeInfo.userProbeInteractions[i].defaultFilter_ = probes[i].defaultFilter_; } g_probeStateChanged = 1; } /**************************************************************************** * SetDefaults - restore default settings ****************************************************************************/ void SetDefaults(UNIT * unit) { PICO_STATUS status; PICO_STATUS powerStatus; int32_t i; if (unit->hasETS) { status = ps4000aSetEts(unit->handle, PS4000A_ETS_OFF, 0, 0, NULL); // Turn off ETS printf(status?"SetDefaults:ps4000aSetEts------ 0x%08x \n":"", status); } powerStatus = ps4000aCurrentPowerSource(unit->handle); for (i = 0; i < unit->channelCount; i++) // reset channels to most recent settings { status = ps4000aSetChannel(unit->handle, (PS4000A_CHANNEL)(PS4000A_CHANNEL_A + i), unit->channelSettings[PS4000A_CHANNEL_A + i].enabled, (PS4000A_COUPLING)unit->channelSettings[PS4000A_CHANNEL_A + i].DCcoupled, (PS4000A_RANGE)unit->channelSettings[PS4000A_CHANNEL_A + i].range, unit->channelSettings[PS4000A_CHANNEL_A + i].analogueOffset); printf(status?"SetDefaults:ps4000aSetChannel------ 0x%08x \n":"", status); } } /**************************************************************************** * adc_to_mv * * Convert an 16-bit ADC count into millivolts ****************************************************************************/ int32_t adc_to_mv(int32_t raw, int32_t rangeIndex, UNIT * unit) { return (raw * inputRanges[rangeIndex]) / unit->maxADCValue; } /**************************************************************************** * mv_to_adc * * Convert a millivolt value into a 16-bit ADC count * * (useful for setting trigger thresholds) ****************************************************************************/ int16_t mv_to_adc(int16_t mv, int16_t rangeIndex, UNIT * unit) { return (mv * unit->maxADCValue) / inputRanges[rangeIndex]; } /****************************************************************************** * ChangePowerSource - * function to handle switches between USB 3.0 and non-USB 3.0 connections *******************************************************************************/ PICO_STATUS ChangePowerSource(int16_t handle, PICO_STATUS status) { int8_t ch = 'Y'; switch (status) { case PICO_POWER_SUPPLY_NOT_CONNECTED: do { printf("\n5 V power supply not connected."); printf("\nDo you want to run using USB only Y/N?\n"); ch = toupper(_getch()); if (ch == 'Y') { printf("\nPower OK\n"); status = ps4000aChangePowerSource(handle, PICO_POWER_SUPPLY_NOT_CONNECTED); // Tell the driver that's ok } } while(ch != 'Y' && ch != 'N'); printf(ch == 'N'?"Please set correct USB connection setting for this device\n":""); break; case PICO_USB3_0_DEVICE_NON_USB3_0_PORT: // User must acknowledge they want to power via USB do { printf("\nUSB 3.0 device on non-USB 3.0 port.\n"); status = ps4000aChangePowerSource(handle, PICO_USB3_0_DEVICE_NON_USB3_0_PORT); // Tell the driver that's ok } while(ch != 'Y' && ch != 'N'); printf(ch == 'N'?"Please set correct USB connection setting for this device\n":""); break; } return status; } /**************************************************************************** * ClearDataBuffers * * stops GetData writing values to memory that has been released ****************************************************************************/ PICO_STATUS ClearDataBuffers(UNIT * unit) { int32_t i; PICO_STATUS status; for (i = 0; i < unit->channelCount; i++) { if (unit->channelSettings[i].enabled) { if ((status = ps4000aSetDataBuffers(unit->handle, (PS4000A_CHANNEL) i, NULL, NULL, 0, 0, PS4000A_RATIO_MODE_NONE)) != PICO_OK) { printf("ClearDataBuffers:ps4000aSetDataBuffers(channel %d) ------ 0x%08x \n", i, status); } } } return status; } /**************************************************************************** * BlockDataHandler * - Used by all block data routines * - acquires data (user sets trigger mode before calling), displays 10 items * and saves all to block.txt * Input : * - unit : the unit to use. * - text : the text to display before the display of data slice * - offset : the offset into the data buffer to start the display's slice. ****************************************************************************/ void BlockDataHandler(UNIT * unit, int8_t * text, int32_t offset) { int32_t timeIndisposed; int32_t maxSamples; int32_t i, j; float timeInterval; int32_t sampleCount = BUFFER_SIZE; int16_t * buffers[PS4000A_MAX_CHANNEL_BUFFERS]; FILE * fp = NULL; PICO_STATUS status; for (i = 0; i < unit->channelCount; i++) { if (unit->channelSettings[i].enabled) { buffers[i * 2] = (int16_t*) calloc(sampleCount, sizeof(int16_t)); buffers[i * 2 + 1] = (int16_t*) calloc(sampleCount, sizeof(int16_t)); // Min data, if aggregation is used status = ps4000aSetDataBuffers(unit->handle, (PS4000A_CHANNEL)i, buffers[i * 2], buffers[i * 2 + 1], sampleCount, 0, PS4000A_RATIO_MODE_NONE); printf(status?"BlockDataHandler:ps4000aSetDataBuffers(channel %d) ------ 0x%08x \n":"", i, status); } } /* find the maximum number of samples, the time interval (in timeUnits), * the most suitable time units */ while (ps4000aGetTimebase2(unit->handle, timebase, sampleCount, &timeInterval, &maxSamples, 0)) { timebase++; } printf("\nTimebase: %u SampleInterval: %.1f ns\n", timebase, timeInterval); /* Start it collecting, then wait for completion*/ g_ready = FALSE; status = ps4000aRunBlock(unit->handle, 0, sampleCount, timebase, &timeIndisposed, 0, CallBackBlock, NULL); if (status != PICO_OK) { printf("BlockDataHandler:ps4000aRunBlock ------ 0x%08x \n", status); return; } printf("Waiting for trigger...Press a key to abort\n"); while (!g_ready && !_kbhit()) { Sleep(0); } if (g_ready) { status = ps4000aGetValues(unit->handle, 0, (uint32_t*) &sampleCount, 1, PS4000A_RATIO_MODE_NONE, 0, NULL); if (status != PICO_OK) { printf("BlockDataHandler:ps4000aGetValues ------ 0x%08x \n", status); } else { /* Print out the first 10 readings, converting the readings to mV if required */ printf("%s\n",text); printf("Channel readings are in %s.\n\n", ( scaleVoltages ) ? ("mV") : ("ADC Counts")); for (j = 0; j < unit->channelCount; j++) { if (unit->channelSettings[j].enabled) { printf("Channel%c: ", 'A' + j); } } printf("\n"); for (i = offset; i < offset+10; i++) { for (j = 0; j < unit->channelCount; j++) { if (unit->channelSettings[j].enabled) { printf(" %6d ", scaleVoltages ? adc_to_mv(buffers[j * 2][i], unit->channelSettings[PS4000A_CHANNEL_A + j].range, unit) // If scaleVoltages, print mV value : buffers[j * 2][i]); // else print ADC Count } } printf("\n"); } sampleCount = min(sampleCount, BUFFER_SIZE); fopen_s(&fp, BlockFile, "w"); if (fp != NULL) { fprintf(fp, "Block Data log\n\n"); fprintf(fp,"Results shown for each of the %d Channels are......\n",unit->channelCount); fprintf(fp,"Maximum Aggregated value ADC Count & mV, Minimum Aggregated value ADC Count & mV\n\n"); fprintf(fp, "Time "); for (i = 0; i < unit->channelCount; i++) { if (unit->channelSettings[i].enabled) { fprintf(fp," Ch Max ADC Max mV Min ADC Min mV "); } } fprintf(fp, "\n"); for (i = 0; i < sampleCount; i++) { fprintf(fp, "%I64d ", g_times[0] + (uint64_t)(i * timeInterval)); for (j = 0; j < unit->channelCount; j++) { if (unit->channelSettings[j].enabled) { fprintf( fp, "Ch%C %d = %dmV, %d = %dmV ", 'A' + j, buffers[j * 2][i], adc_to_mv(buffers[j * 2][i], unit->channelSettings[PS4000A_CHANNEL_A + j].range, unit), buffers[j * 2 + 1][i], adc_to_mv(buffers[j * 2 + 1][i], unit->channelSettings[PS4000A_CHANNEL_A + j].range, unit)); } } fprintf(fp, "\n"); } } else { printf( "Cannot open the file %s for writing.\n" "Please ensure that you have permission to access the file.\n", BlockFile); } } } else { printf("data collection aborted\n"); _getch(); } if ((status = ps4000aStop(unit->handle)) != PICO_OK) { printf("BlockDataHandler:ps4000aStop ------ 0x%08x \n", status); } if (fp != NULL) { fclose(fp); } for (i = 0; i < unit->channelCount; i++) { if (unit->channelSettings[i].enabled) { free(buffers[i * 2]); free(buffers[i * 2 + 1]); } } ClearDataBuffers(unit); } /**************************************************************************** * Stream Data Handler * - Used by the two stream data examples - untriggered and triggered * Inputs: * - unit - the unit to sample on * - preTrigger - the number of samples in the pre-trigger phase * (0 if no trigger has been set) ***************************************************************************/ void StreamDataHandler(UNIT * unit, uint32_t preTrigger) { int16_t retry = 0; int16_t autostop = 0; int32_t index = 0; int32_t totalSamples = 0; uint32_t sampleInterval; uint32_t postTrigger; uint32_t downsampleRatio; uint32_t triggeredAt = 0; int32_t i, j; uint32_t sampleCount = 200000; /* Make sure buffer size is large enough to copy data into on each iteration */ FILE * fp = NULL; int16_t * buffers[PS4000A_MAX_CHANNEL_BUFFERS]; int16_t * appBuffers[PS4000A_MAX_CHANNEL_BUFFERS]; // Temporary application buffers to copy data into from driver buffers. PICO_STATUS status; PS4000A_TIME_UNITS timeUnits; PS4000A_RATIO_MODE ratioMode; BUFFER_INFO bufferInfo; for (i = 0; i < unit->channelCount; i++) { if (unit->channelSettings[i].enabled) { buffers[i * 2] = (int16_t*) calloc(sampleCount, sizeof(int16_t)); buffers[i * 2 + 1] = (int16_t*) calloc(sampleCount, sizeof(int16_t)); status = ps4000aSetDataBuffers(unit->handle, (PS4000A_CHANNEL)i, buffers[i * 2], buffers[i * 2 + 1], sampleCount, 0, PS4000A_RATIO_MODE_NONE); appBuffers[i * 2] = (int16_t*) calloc(sampleCount, sizeof(int16_t)); appBuffers[i * 2 + 1] = (int16_t*) calloc(sampleCount, sizeof(int16_t)); printf(status?"StreamDataHandler:ps4000aSetDataBuffers(channel %d) ------ 0x%08x \n":"", i, status); } } downsampleRatio = 1; timeUnits = PS4000A_US; sampleInterval = 1; ratioMode = PS4000A_RATIO_MODE_NONE; postTrigger = 1000000; autostop = TRUE; bufferInfo.unit = unit; bufferInfo.driverBuffers = buffers; bufferInfo.appBuffers = appBuffers; if (autostop) { printf("\nStreaming Data for %u samples", postTrigger / downsampleRatio); if (preTrigger) // we pass 0 for preTrigger if we're not setting up a trigger { printf(" after the trigger occurs\nNote: %u Pre Trigger samples before Trigger arms\n\n", preTrigger / downsampleRatio); } else { printf("\n\n"); } } else { printf("\nStreaming Data continually...\n\n"); } g_autoStopped = FALSE; status = ps4000aRunStreaming(unit->handle, &sampleInterval, timeUnits, preTrigger, postTrigger, autostop, downsampleRatio, ratioMode, sampleCount); if (status != PICO_OK) { printf("StreamDataHandler:ps4000aRunStreaming ------ 0x%08x \n", status); return; } printf("Streaming data...Press a key to stop\n"); fopen_s(&fp, StreamFile, "w"); if (fp != NULL) { fprintf(fp,"For each of the %d Channels, results shown are....\n",unit->channelCount); fprintf(fp,"Maximum Aggregated value ADC Count & mV, Minimum Aggregated value ADC Count & mV\n\n"); for (i = 0; i < unit->channelCount; i++) { if (unit->channelSettings[i].enabled) { fprintf(fp," Max ADC Max mV Min ADC Min mV "); } } fprintf(fp, "\n"); } totalSamples = 0; while (!_kbhit() && !g_autoStopped) { /* Poll until data is received. Until then, GetStreamingLatestValues wont call the callback */ Sleep(1); g_ready = FALSE; status = ps4000aGetStreamingLatestValues(unit->handle, CallBackStreaming, &bufferInfo); if (status != PICO_OK) { printf("\nStreamDataHandler:ps4000aGetStreamingLatestValues ------ 0x%08x \n", status); } index ++; if (g_ready && g_sampleCount > 0) /* can be ready and have no data, if autoStop has fired */ { if (g_trig) { triggeredAt = totalSamples += g_trigAt; // calculate where the trigger occurred in the total samples collected } totalSamples += g_sampleCount; printf("\nCollected %3i samples, index = %6u, Total: %d samples ", g_sampleCount, g_startIndex, totalSamples); if (g_trig) { printf("Trig. at index %u", triggeredAt); // show where trigger occurred } for (i = g_startIndex; i < (int32_t)(g_startIndex + g_sampleCount); i++) { if (fp != NULL) { for (j = 0; j < unit->channelCount; j++) { if (unit->channelSettings[j].enabled) { fprintf( fp, "Ch%C %d = %dmV, %d = %dmV ", (int8_t)('A' + j), appBuffers[j * 2][i], adc_to_mv(appBuffers[j * 2][i], unit->channelSettings[PS4000A_CHANNEL_A + j].range, unit), appBuffers[j * 2 + 1][i], adc_to_mv(appBuffers[j * 2 + 1][i], unit->channelSettings[PS4000A_CHANNEL_A + j].range, unit)); } } fprintf(fp, "\n"); } else { printf("Cannot open the file %s for writing.\n", StreamFile); } } } } ps4000aStop(unit->handle); if (!g_autoStopped) { printf("\nData collection aborted.\n"); _getch(); } else { printf("\nData collection complete.\n\n"); } if (fp != NULL) { fclose(fp); } for (i = 0; i < unit->channelCount; i++) { if (unit->channelSettings[i].enabled) { free(buffers[i * 2]); free(appBuffers[i * 2]); free(buffers[i * 2 + 1]); free(appBuffers[i * 2 + 1]); } } ClearDataBuffers(unit); } /**************************************************************************** * SetTrigger * * - Used to call aall the functions required to set up triggering * ***************************************************************************/ PICO_STATUS SetTrigger( UNIT * unit, struct tPS4000ATriggerChannelProperties * channelProperties, int16_t nChannelProperties, PS4000A_CONDITION * triggerConditions, int16_t nTriggerConditions, PS4000A_DIRECTION * directions, int16_t nDirections, struct tPwq * pwq, uint32_t delay, int16_t auxOutputEnabled, int32_t autoTriggerMs) { PICO_STATUS status; PS4000A_CONDITIONS_INFO info = PS4000A_CLEAR; PS4000A_CONDITIONS_INFO pwqInfo = PS4000A_CLEAR; if ((status = ps4000aSetTriggerChannelProperties(unit->handle, channelProperties, nChannelProperties, auxOutputEnabled, autoTriggerMs)) != PICO_OK) { printf("SetTrigger:ps4000aSetTriggerChannelProperties ------ Ox%08x \n", status); return status; } if (nTriggerConditions != 0) { info = (PS4000A_CONDITIONS_INFO)(PS4000A_CLEAR | PS4000A_ADD); // Clear and add trigger condition specified unless no trigger conditions have been specified } if ((status = ps4000aSetTriggerChannelConditions(unit->handle, triggerConditions, nTriggerConditions, info) != PICO_OK)) { printf("SetTrigger:ps4000aSetTriggerChannelConditions ------ 0x%08x \n", status); return status; } if ((status = ps4000aSetTriggerChannelDirections(unit->handle, directions, nDirections)) != PICO_OK) { printf("SetTrigger:ps4000aSetTriggerChannelDirections ------ 0x%08x \n", status); return status; } if ((status = ps4000aSetTriggerDelay(unit->handle, delay)) != PICO_OK) { printf("SetTrigger:ps4000aSetTriggerDelay ------ 0x%08x \n", status); return status; } if ((status = ps4000aSetPulseWidthQualifierProperties(unit->handle, pwq->direction, pwq->lower, pwq->upper, pwq->type)) != PICO_OK) { printf("SetTrigger:ps4000aSetPulseWidthQualifierProperties ------ 0x%08x \n", status); return status; } // Clear and add pulse width qualifier condition, clear if no pulse width qualifier has been specified if (pwq->nConditions != 0) { pwqInfo = (PS4000A_CONDITIONS_INFO)(PS4000A_CLEAR | PS4000A_ADD); } if ((status = ps4000aSetPulseWidthQualifierConditions(unit->handle, pwq->conditions, pwq->nConditions, pwqInfo)) != PICO_OK) { printf("SetTrigger:ps4000aSetPulseWidthQualifierConditions ------ 0x%08x \n", status); return status; } return status; } /**************************************************************************** * CollectBlockImmediate * this function demonstrates how to collect a single block of data * from the unit (start collecting immediately) ****************************************************************************/ void CollectBlockImmediate(UNIT * unit) { struct tPwq pulseWidth; struct tPS4000ADirection directions; memset(&directions, 0, sizeof(struct tPS4000ADirection)); memset(&pulseWidth, 0, sizeof(struct tPwq)); printf("Collect block immediate...\n"); printf("Press a key to start\n"); _getch(); SetDefaults(unit); /* Trigger disabled */ SetTrigger(unit, NULL, 0, NULL, 0, &directions, 1, &pulseWidth, 0, 0, 0); BlockDataHandler(unit, "First 10 readings\n", 0); } /**************************************************************************** * CollectBlockEts * this function demonstrates how to collect a block of * data using equivalent time sampling (ETS). ****************************************************************************/ void CollectBlockEts(UNIT * unit) { int32_t ets_sampletime; int16_t triggerVoltage = mv_to_adc(1000, unit->channelSettings[PS4000A_CHANNEL_A].range, unit); uint32_t delay = 0; struct tPwq pulseWidth; struct tPS4000ADirection directions; struct tPS4000ATriggerChannelProperties sourceDetails = { triggerVoltage, 256 * 10, triggerVoltage, 256 * 10, PS4000A_CHANNEL_A, PS4000A_LEVEL }; struct tPS4000ACondition conditions[1] = {{ PS4000A_CHANNEL_A, PS4000A_CONDITION_TRUE }}; memset(&pulseWidth, 0, sizeof(struct tPwq)); directions.channel = (conditions[0]).source; directions.direction = PS4000A_RISING; printf("Collect ETS block...\n"); printf("Collects when value rises past %d", scaleVoltages? adc_to_mv(sourceDetails.thresholdUpper, unit->channelSettings[PS4000A_CHANNEL_A].range, unit) // If scaleVoltages, print mV value : sourceDetails.thresholdUpper); // else print ADC Count printf(scaleVoltages? "mV\n" : "ADC Counts\n"); printf("Press a key to start...\n"); _getch(); SetDefaults(unit); //Trigger enabled //Rising edge //Threshold = 1000mV SetTrigger(unit, &sourceDetails, 1, conditions, 1, &directions, 1, &pulseWidth, delay, 0, 0); ps4000aSetEts(unit->handle, PS4000A_ETS_FAST, 20, 4, &ets_sampletime); printf("ETS Sample Time is: %d\n", ets_sampletime); BlockDataHandler(unit, "Ten readings after trigger\n", BUFFER_SIZE / 10 - 5); // 10% of data is pre-trigger ps4000aSetEts(unit->handle, PS4000A_ETS_OFF, 0, 0, &ets_sampletime); } /**************************************************************************** * CollectBlockTriggered * this function demonstrates how to collect a single block of data from the * unit, when a trigger event occurs. ****************************************************************************/ void CollectBlockTriggered(UNIT * unit) { int16_t triggerVoltage = mv_to_adc(1000, unit->channelSettings[PS4000A_CHANNEL_A].range, unit); struct tPS4000ATriggerChannelProperties sourceDetails = { triggerVoltage, 256 * 10, triggerVoltage, 256 * 10, PS4000A_CHANNEL_A, PS4000A_LEVEL}; struct tPS4000ACondition conditions = {sourceDetails.channel, PS4000A_CONDITION_TRUE}; struct tPwq pulseWidth; struct tPS4000ADirection directions; directions.channel = conditions.source; directions.direction = PS4000A_RISING; memset(&pulseWidth, 0, sizeof(struct tPwq)); printf("Collect block triggered...\n"); printf("Collects when value rises past %d", scaleVoltages? adc_to_mv(sourceDetails.thresholdUpper, unit->channelSettings[sourceDetails.channel].range, unit) // If scaleVoltages, print mV value : sourceDetails.thresholdUpper); // else print ADC Count printf(scaleVoltages?"mV\n" : "ADC Counts\n"); printf("Press a key to start...\n"); _getch(); SetDefaults(unit); /* Trigger enabled * Rising edge * Threshold = 1000mV */ SetTrigger(unit, &sourceDetails, 1, &conditions, 1, &directions, 1, &pulseWidth, 0, 0, 0); BlockDataHandler(unit, "Ten readings after trigger\n", 0); } /**************************************************************************** * CollectRapidBlock * This function demonstrates how to collect a set of captures using * rapid block mode. ****************************************************************************/ void CollectRapidBlock(UNIT * unit) { int16_t i; int16_t channel; int16_t triggerVoltage = mv_to_adc(1000, unit->channelSettings[PS4000A_CHANNEL_A].range, unit); uint16_t capture; int32_t nMaxSamples; int32_t timeIndisposed; uint32_t nCaptures; uint32_t nSamples = 1000; uint32_t nCompletedCaptures; int16_t ***rapidBuffers; int16_t *overflow; PICO_STATUS status; struct tPS4000ATriggerChannelProperties sourceDetails = { triggerVoltage, 256 * 10, triggerVoltage, 256 * 10, PS4000A_CHANNEL_A, PS4000A_LEVEL}; struct tPS4000ACondition conditions = { PS4000A_CHANNEL_A, PS4000A_CONDITION_TRUE }; struct tPwq pulseWidth; struct tPS4000ADirection directions; directions.channel = conditions.source; directions.direction = PS4000A_RISING; memset(&pulseWidth, 0, sizeof(struct tPwq)); printf("Collect rapid block triggered...\n"); printf("Collects when value rises past %d", scaleVoltages? adc_to_mv(sourceDetails.thresholdUpper, unit->channelSettings[PS4000A_CHANNEL_A].range, unit) // If scaleVoltages, print mV value : sourceDetails.thresholdUpper); // else print ADC Count printf(scaleVoltages?"mV\n" : "ADC Counts\n"); printf("Press any key to abort\n"); SetDefaults(unit); // Trigger enabled SetTrigger(unit, &sourceDetails, 1, &conditions, 1, &directions, 1, &pulseWidth, 0, 0, 0); //Set the number of captures nCaptures = 10; //Segment the memory status = ps4000aMemorySegments(unit->handle, nCaptures, &nMaxSamples); //Set the number of captures status = ps4000aSetNoOfCaptures(unit->handle, nCaptures); //Run timebase = 7; // 10 MS/s status = ps4000aRunBlock(unit->handle, 0, nSamples, timebase, &timeIndisposed, 0, CallBackBlock, NULL); if (status != PICO_OK) { printf("BlockDataHandler:ps4000aRunBlock ------ 0x%08x \n", status); } //Wait until data ready g_ready = 0; while(!g_ready && !_kbhit()) { Sleep(0); } if (!g_ready) { _getch(); status = ps4000aStop(unit->handle); status = ps4000aGetNoOfCaptures(unit->handle, &nCompletedCaptures); printf("Rapid capture aborted. %u complete blocks were captured\n", nCompletedCaptures); printf("\nPress any key...\n\n"); _getch(); if (nCompletedCaptures == 0) { return; } // Only display the blocks that were captured nCaptures = (uint16_t) nCompletedCaptures; } // Allocate memory rapidBuffers = (int16_t ***) calloc(unit->channelCount, sizeof(int16_t*)); overflow = (int16_t *) calloc(unit->channelCount * nCaptures, sizeof(int16_t)); for (channel = 0; channel < unit->channelCount; channel++) { if (unit->channelSettings[channel].enabled) { rapidBuffers[channel] = (int16_t **) calloc(nCaptures, sizeof(int16_t*)); } } for (channel = 0; channel < unit->channelCount; channel++) { if (unit->channelSettings[channel].enabled) { for (capture = 0; capture < nCaptures; capture++) { rapidBuffers[channel][capture] = (int16_t *) calloc(nSamples, sizeof(int16_t)); } } } for (channel = 0; channel < unit->channelCount; channel++) { if (unit->channelSettings[channel].enabled) { for (capture = 0; capture < nCaptures; capture++) { status = ps4000aSetDataBuffer(unit->handle, (PS4000A_CHANNEL)channel, rapidBuffers[channel][capture], nSamples, capture, PS4000A_RATIO_MODE_NONE); } } } // Get data status = ps4000aGetValuesBulk(unit->handle, &nSamples, 0, nCaptures - 1, 1, PS4000A_RATIO_MODE_NONE, overflow); if (status == PICO_POWER_SUPPLY_CONNECTED || status == PICO_POWER_SUPPLY_NOT_CONNECTED) { printf("\nPower Source Changed. Data collection aborted.\n"); } if (status == PICO_OK) { // Print first 10 samples from each capture for (capture = 0; capture < nCaptures; capture++) { printf("\nCapture %d:-\n\n", capture + 1); for (channel = 0; channel < unit->channelCount; channel++) { printf("Channel %c:\t", 'A' + channel); } printf("\n"); for(i = 0; i < 10; i++) { for (channel = 0; channel < unit->channelCount; channel++) { if (unit->channelSettings[channel].enabled) { printf(" %6d ", scaleVoltages ? adc_to_mv(rapidBuffers[channel][capture][i], unit->channelSettings[PS4000A_CHANNEL_A +channel].range, unit) // If scaleVoltages, print mV value : rapidBuffers[channel][capture][i]); // else print ADC Count } } printf("\n"); } } } // Stop status = ps4000aStop(unit->handle); // Free memory free(overflow); for (channel = 0; channel < unit->channelCount; channel++) { if (unit->channelSettings[channel].enabled) { for (capture = 0; capture < nCaptures; capture++) { free(rapidBuffers[channel][capture]); } } } for (channel = 0; channel < unit->channelCount; channel++) { free(rapidBuffers[channel]); } free(rapidBuffers); } /**************************************************************************** * Initialise unit' structure with Variant specific defaults ****************************************************************************/ void set_info(UNIT * unit) { int8_t description [11][25]= { "Driver Version", "USB Version", "Hardware Version", "Variant Info", "Serial", "Cal Date", "Kernel Version", "Digital H/W", "Analogue H/W", "Firmware 1", "Firmware 2"}; int16_t i = 0; int16_t requiredSize = 0; int8_t line [80] = {0}; int16_t minArbitraryWaveformValue = 0; int16_t maxArbitraryWaveformValue = 0; int32_t variant; uint32_t minArbitraryWaveformBufferSize = 0; uint32_t maxArbitraryWaveformBufferSize = 0; PICO_STATUS status = PICO_OK; PS4000A_DEVICE_RESOLUTION deviceResolution = PS4000A_DR_12BIT; // For the PicoScope 4444 if (unit->handle) { for (i = 0; i < 11 && status == PICO_OK; i++) { status = ps4000aGetUnitInfo(unit->handle, (int8_t *)line, sizeof (line), &requiredSize, i); // info = 3 - PICO_VARIANT_INFO if (i == PICO_VARIANT_INFO) { variant = atoi(line); memcpy(&(unit->modelString), line, sizeof(unit->modelString)==5?5:sizeof(unit->modelString)); } else if (i == PICO_BATCH_AND_SERIAL) // info = 4 - PICO_BATCH_AND_SERIAL { memcpy(&(unit->serial), line, requiredSize); } printf("%s: %s\n", description[i], line); } printf("\n"); // Find the maxiumum AWG buffer size status = ps4000aSigGenArbitraryMinMaxValues(unit->handle, &minArbitraryWaveformValue, &maxArbitraryWaveformValue, &minArbitraryWaveformBufferSize, &maxArbitraryWaveformBufferSize); switch (variant) { case MODEL_PS4824: unit->model = MODEL_PS4824; unit->sigGen = SIGGEN_AWG; unit->firstRange = PS4000A_10MV; unit->lastRange = PS4000A_50V; unit->channelCount = OCTO_SCOPE; unit->hasETS = FALSE; unit->AWGFileSize = maxArbitraryWaveformBufferSize; unit->hasFlexibleResolution = FALSE; unit->hasIntelligentProbes = FALSE; break; case MODEL_PS4225: unit->model = MODEL_PS4225; unit->sigGen = SIGGEN_NONE; unit->firstRange = PS4000A_50MV; unit->lastRange = PS4000A_200V; unit->channelCount = DUAL_SCOPE; unit->hasETS = FALSE; unit->AWGFileSize = 0; unit->hasFlexibleResolution = FALSE; unit->hasIntelligentProbes = FALSE; break; case MODEL_PS4425: unit->model = MODEL_PS4425; unit->sigGen = SIGGEN_NONE; unit->firstRange = PS4000A_50MV; unit->lastRange = PS4000A_200V; unit->channelCount = QUAD_SCOPE; unit->hasETS = FALSE; unit->AWGFileSize = 0; unit->hasFlexibleResolution = FALSE; unit->hasIntelligentProbes = FALSE; break; case MODEL_PS4444: unit->model = MODEL_PS4444; unit->sigGen = SIGGEN_NONE; unit->firstRange = PS4000A_10MV; unit->lastRange = PS4000A_50V; unit->channelCount = QUAD_SCOPE; unit->hasETS = FALSE; unit->AWGFileSize = 0; unit->hasFlexibleResolution = TRUE; unit->hasIntelligentProbes = TRUE; break; default: unit->model = MODEL_NONE; break; } if (unit->hasFlexibleResolution) { status = ps4000aGetDeviceResolution(unit->handle, &unit->resolution); if (status != PICO_OK) { printf("set_info:ps4000aGetDeviceResolution ------ 0x%08lx \n", status); } } else { unit->resolution = PS4000A_DR_12BIT; } } } /**************************************************************************** * Select input voltage ranges for channels ****************************************************************************/ void SetVoltages(UNIT * unit) { int32_t i, ch; int32_t count = 0; /* See what ranges are available... */ for (i = unit->firstRange; i <= unit->lastRange; i++) { printf("%d -> %d mV\n", i, inputRanges[i]); } do { /* Ask the user to select a range */ printf("Specify voltage range (%d..%d)\n", unit->firstRange, unit->lastRange); printf("99 - switches channel off\n"); for (ch = 0; ch < unit->channelCount; ch++) { printf("\n"); do { printf("Channel %c: ", 'A' + ch); fflush(stdin); scanf_s("%hd", &(unit->channelSettings[ch].range)); } while (unit->channelSettings[ch].range != 99 && (unit->channelSettings[ch].range < unit->firstRange || unit->channelSettings[ch].range > unit->lastRange)); if (unit->channelSettings[ch].range != 99) { printf(" - %d mV\n", inputRanges[unit->channelSettings[ch].range]); unit->channelSettings[ch].enabled = TRUE; count++; } else { printf("Channel Switched off\n"); unit->channelSettings[ch].enabled = FALSE; unit->channelSettings[ch].range = PS4000A_MAX_RANGES-1; } } printf(count == 0? "\n** At least 1 channel must be enabled **\n\n":""); } while(count == 0); // Must have at least one channel enabled SetDefaults(unit); // Put these changes into effect } /**************************************************************************** * * Select timebase, set time units as nano seconds * ****************************************************************************/ void SetTimebase(UNIT * unit) { float timeInterval; int32_t maxSamples; printf("Specify desired timebase: "); fflush(stdin); scanf_s("%ud", &timebase); while (ps4000aGetTimebase2(unit->handle, timebase, BUFFER_SIZE, &timeInterval, &maxSamples, 0)) { timebase++; // Increase timebase if the one specified can't be used. } printf("Timebase used %u = %.1f ns sample interval\n", timebase, timeInterval); } /**************************************************************************** * printResolution * * Outputs the resolution in text format to the console window ****************************************************************************/ void printResolution(PS4000A_DEVICE_RESOLUTION resolution) { switch (resolution) { case PS4000A_DR_12BIT: printf("12 bits"); break; case PS4000A_DR_14BIT: printf("14 bits"); break; default: printf("Invalid resolution for this device."); break; } printf("\n"); } /**************************************************************************** * setResolution * Set resolution for the device * ****************************************************************************/ void setResolution(UNIT * unit) { int16_t value; int16_t i; int16_t numEnabledChannels = 0; int16_t retry; int32_t resolutionInput; PICO_STATUS status; PS4000A_DEVICE_RESOLUTION resolution; PS4000A_DEVICE_RESOLUTION newResolution = PS4000A_DR_12BIT; // Determine number of channels enabled for (i = 0; i < unit->channelCount; i++) { if (unit->channelSettings[i].enabled == TRUE) { numEnabledChannels++; } } if (numEnabledChannels == 0) { printf("setResolution: Please enable channels.\n"); return; } status = ps4000aGetDeviceResolution(unit->handle, &resolution); if (status == PICO_OK) { printf("Current resolution: "); printResolution(resolution); } else { printf("setResolution:ps4000aGetDeviceResolution ------ 0x%08lx \n", status); return; } printf("\n"); printf("Select device resolution:\n"); printf("1: 12 bits\n"); printf("2: 14 bits\n"); retry = TRUE; do { printf("Resolution [1...2]: "); fflush(stdin); scanf_s("%lud", &resolutionInput); newResolution = (PS4000A_DEVICE_RESOLUTION)resolutionInput; // Verify if resolution can be selected for number of channels enabled if (newResolution < PS4000A_DR_12BIT && newResolution > PS4000A_DR_14BIT) { printf("setResolution: Resolution index selected out of bounds.\n"); } else { retry = FALSE; } } while (retry); printf("\n"); status = ps4000aSetDeviceResolution(unit->handle, (PS4000A_DEVICE_RESOLUTION)newResolution); if (status == PICO_OK) { unit->resolution = newResolution; printf("Resolution selected: "); printResolution(newResolution); } else { printf("setResolution:ps4000aSetDeviceResolution ------ 0x%08lx \n", status); } } /**************************************************************************************************** * Sets the signal generator * - allows user to set frequency and waveform * - allows for custom waveform (values -32768..32767) of up to 16384 samples (for the PicoScope 4824) ****************************************************************************************************/ void SetSignalGenerator(UNIT * unit) { PICO_STATUS status; int16_t waveform; uint32_t frequency = 1; int8_t fileName [128]; FILE * fp = NULL; int16_t * arbitraryWaveform; int32_t waveformSize = 0; uint32_t pkpk = 4000000; //2V int32_t offset = 0; int8_t ch; int16_t choice; uint32_t delta; while (_kbhit()) // use up keypress { _getch(); } do { printf("\nSignal Generator\n================\n"); printf("0 - SINE 1 - SQUARE\n"); printf("2 - TRIANGLE 3 - DC VOLTAGE\n"); if (unit->sigGen == SIGGEN_AWG) { printf("4 - RAMP UP 5 - RAMP DOWN\n"); printf("6 - SINC 7 - GAUSSIAN\n"); printf("8 - HALF SINE A - AWG WAVEFORM\n"); } printf("F - SigGen Off\n\n"); ch = _getch(); if (ch >= '0' && ch <='9') { choice = ch -'0'; } else { ch = toupper(ch); } } while((unit->sigGen == SIGGEN_FUNCTGEN && ch != 'F' && (ch < '0' || ch > '3')) || (unit->sigGen == SIGGEN_AWG && ch != 'A' && ch != 'F' && (ch < '0' || ch > '8'))); if (ch == 'F') // If we're going to turn off siggen { printf("Signal generator Off\n"); waveform = PS4000A_DC_VOLTAGE; // DC Voltage pkpk = 0; // 0V waveformSize = 0; } else { if (ch == 'A' && unit->sigGen == SIGGEN_AWG) // Set the AWG { arbitraryWaveform = (int16_t*) calloc( unit->AWGFileSize, sizeof(int16_t)); memset(arbitraryWaveform, 0, unit->AWGFileSize * sizeof(int16_t)); waveformSize = 0; printf("Select a waveform file to load: "); scanf_s("%s", fileName, 128); if (fopen_s(&fp, fileName, "r") == 0) { // Having opened file, read in data - one number per line while (EOF != fscanf_s(fp, "%hi", (arbitraryWaveform + waveformSize)) && waveformSize++ < unit->AWGFileSize - 1); fclose(fp); printf("File successfully loaded\n"); } else { printf("Invalid filename\n"); return; } } else // Set one of the built in waveforms { switch (choice) { case 0: waveform = PS4000A_SINE; break; case 1: waveform = PS4000A_SQUARE; break; case 2: waveform = PS4000A_TRIANGLE; break; case 3: waveform = PS4000A_DC_VOLTAGE; do { printf("\nEnter offset in uV: (0 to 2000000)\n"); // Ask user to enter DC offset level; scanf_s("%u", &offset); } while (offset < 0 || offset > 2000000); break; case 4: waveform = PS4000A_RAMP_UP; break; case 5: waveform = PS4000A_RAMP_DOWN; break; case 6: waveform = PS4000A_SINC; break; case 7: waveform = PS4000A_GAUSSIAN; break; case 8: waveform = PS4000A_HALF_SINE; break; default: waveform = PS4000A_SINE; break; } } if (waveform < 8 || (ch == 'A' && unit->sigGen == SIGGEN_AWG)) // Find out frequency if required { do { printf("\nEnter frequency in Hz: (1 to 1000000)\n"); // Ask user to enter signal frequency, signal will be output at constant frequency scanf_s("%u", &frequency); } while (frequency <= 0 || frequency > 1000000); } if (waveformSize > 0) { // Find the delta phase corresponding to the frequency status = ps4000aSigGenFrequencyToPhase(unit->handle, frequency, PS4000A_SINGLE, waveformSize, &delta); status = ps4000aSetSigGenArbitrary( unit->handle, 0, // offset voltage pkpk, // PkToPk in microvolts. Max = 4000000 uV +2v to -2V delta, // start delta delta, // stop delta 0, 0, arbitraryWaveform, waveformSize, (PS4000A_SWEEP_TYPE)0, (PS4000A_EXTRA_OPERATIONS)0, PS4000A_SINGLE, 0, 0, PS4000A_SIGGEN_RISING, PS4000A_SIGGEN_NONE, 0); printf(status?"\nps4000aSetSigGenArbitrary: Status Error 0x%x \n":"", status); // If status != 0, show the error } else { status = ps4000aSetSigGenBuiltIn(unit->handle, offset, pkpk, (PS4000A_WAVE_TYPE) waveform, (double) frequency, (double) frequency, 0, 0, (PS4000A_SWEEP_TYPE) 0, (PS4000A_EXTRA_OPERATIONS) 0, 0, 0, (PS4000A_SIGGEN_TRIG_TYPE) 0, (PS4000A_SIGGEN_TRIG_SOURCE) 0, 0); printf(status?"\nps4000aSetSigGenBuiltIn: Status Error 0x%x \n":"", status); // If status != 0, show the error } } } /**************************************************************************** * CollectStreamingImmediate * this function demonstrates how to collect a stream of data * from the unit (start collecting immediately) ***************************************************************************/ void CollectStreamingImmediate(UNIT * unit) { struct tPwq pulseWidth; struct tPS4000ADirection directions; memset(&pulseWidth, 0, sizeof(struct tPwq)); memset(&directions, 0, sizeof(struct tPS4000ADirection)); SetDefaults(unit); printf("Collect streaming...\n"); printf("Data is written to disk file (stream.txt)\n"); printf("Press a key to start\n"); _getch(); /* Trigger disabled */ SetTrigger(unit, NULL, 0, NULL, 0, &directions, 1, &pulseWidth, 0, 0, 0); StreamDataHandler(unit, 0); } /**************************************************************************** * CollectStreamingTriggered * this function demonstrates how to collect a stream of data * from the unit (start collecting on trigger) ***************************************************************************/ void CollectStreamingTriggered(UNIT * unit) { int16_t triggerVoltage = mv_to_adc(1000, unit->channelSettings[PS4000A_CHANNEL_A].range, unit); // ChannelInfo stores ADC counts struct tPwq pulseWidth; struct tPS4000ATriggerChannelProperties sourceDetails = { triggerVoltage, 256 * 10, triggerVoltage, 256 * 10, PS4000A_CHANNEL_A, PS4000A_LEVEL }; struct tPS4000ACondition conditions [1] = {{PS4000A_CHANNEL_A, PS4000A_CONDITION_TRUE }}; struct tPS4000ADirection directions [1]; directions[0].channel = conditions[0].source; directions[0].direction = PS4000A_RISING; memset(&pulseWidth, 0, sizeof(struct tPwq)); printf("Collect streaming triggered...\n"); printf("Data is written to disk file (stream.txt)\n"); printf("Press a key to start\n"); _getch(); SetDefaults(unit); /* Trigger enabled * Rising edge * Threshold = 1000mV */ SetTrigger(unit, &sourceDetails, 1, conditions, 1, directions, 1, &pulseWidth, 0, 0, 0); StreamDataHandler(unit, 100000); } /**************************************************************************** * DisplaySettings * Displays information about the user configurable settings in this example * Parameters * - unit pointer to the UNIT structure * * Returns none ***************************************************************************/ void DisplaySettings(UNIT *unit) { int32_t ch; int32_t voltage; PS4000A_DEVICE_RESOLUTION resolution = PS4000A_DR_12BIT; PICO_STATUS status = PICO_OK; printf("\nChannel Voltage Settings:\n\n"); for (ch = 0; ch < unit->channelCount; ch++) { if (!(unit->channelSettings[ch].enabled)) { printf("Channel %c Voltage Range = Off\n", 'A' + ch); } else { voltage = inputRanges[unit->channelSettings[ch].range]; printf("Channel %c Voltage Range = ", 'A' + ch); if (voltage < 1000) { printf("%dmV\n", voltage); } else { printf("%dV\n", voltage / 1000); } } } printf("\n"); printf("\nReadings will be scaled in (%s)\n\n", (scaleVoltages)? ("mV") : ("ADC counts")); if (unit->hasFlexibleResolution) { status = ps4000aGetDeviceResolution(unit->handle, &resolution); printf("Device Resolution: "); printResolution(resolution); } } /**************************************************************************** * OpenDevice * Parameters * - unit pointer to the UNIT structure, where the handle will be stored * - serial pointer to the char array containing serial number * * Returns * - PICO_STATUS to indicate success, or if an error occurred ***************************************************************************/ PICO_STATUS OpenDevice(UNIT *unit, int8_t *serial) { PICO_STATUS status; int16_t asyncStatus = 0; int16_t progressPercent = 0; int16_t complete = 0; int16_t count = 0; if (serial == NULL) { status = ps4000aOpenUnit(&unit->handle, NULL); } else { status = ps4000aOpenUnit(&unit->handle, (int8_t *) serial); } unit->openStatus = (int16_t) status; unit->complete = 1; return status; } /**************************************************************************** * HandleDevice * Parameters * - unit pointer to the UNIT structure, where the handle will be stored * * Returns * - PICO_STATUS to indicate success, or if an error occurred ***************************************************************************/ PICO_STATUS HandleDevice(UNIT * unit) { int16_t value = 0; int32_t i; struct tPwq pulseWidth; struct tPS4000ADirection directions; PICO_STATUS currentPowerStatus; PICO_STATUS status; if (unit->openStatus == PICO_USB3_0_DEVICE_NON_USB3_0_PORT || unit->openStatus == PICO_POWER_SUPPLY_NOT_CONNECTED) { unit->openStatus = (int16_t) ChangePowerSource(unit->handle, unit->openStatus); currentPowerStatus = ps4000aCurrentPowerSource(unit->handle); if (currentPowerStatus == PICO_POWER_SUPPLY_NOT_CONNECTED) { printf("USB Powered"); } else { printf("5 V Power Supply Connected"); } printf("\n"); } printf("Handle: %d\n", unit->handle); if (unit->openStatus != PICO_OK && unit->openStatus != PICO_POWER_SUPPLY_NOT_CONNECTED) { printf("Unable to open device\n"); printf("Error code : 0x%08x\n", (uint32_t) unit->openStatus); while(!_kbhit()); exit(99); // exit program } printf("Device opened successfully, cycle %d\n", ++cycles); // setup device info - unless it's set already if (unit->model == MODEL_NONE) { set_info(unit); } // Register probe interaction callback if (unit->hasIntelligentProbes) { status = ps4000aSetProbeInteractionCallback(unit->handle, CallBackProbeInteractions); // Wait for information to populate (callback will be called twice initially) Sleep(2000); } timebase = 1; ps4000aMaximumValue(unit->handle, &value); unit->maxADCValue = value; ps4000aCurrentPowerSource(unit->handle); for (i = 0; i < unit->channelCount; i++) { unit->channelSettings[i].enabled = TRUE; unit->channelSettings[i].DCcoupled = TRUE; unit->channelSettings[i].range = PS4000A_5V; unit->channelSettings[i].analogueOffset = 0.0f; } memset(&directions, 0, sizeof(struct tPS4000ADirection)); memset(&pulseWidth, 0, sizeof(struct tPwq)); SetDefaults(unit); /* Trigger disabled */ SetTrigger(unit, NULL, 0, NULL, 0, &directions, 1, &pulseWidth, 0, 0, 0); return unit->openStatus; } /**************************************************************************** * CloseDevice ****************************************************************************/ void CloseDevice(UNIT *unit) { ps4000aCloseUnit(unit->handle); } /**************************************************************************** * MainMenu * Controls default functions of the seelected unit * Parameters * - unit pointer to the UNIT structure * * Returns none ***************************************************************************/ void MainMenu(UNIT *unit) { int8_t ch = '.'; while (ch != 'X') { DisplaySettings(unit); printf("\n"); printf("Please select an operation:\n\n"); printf("B - Immediate block V - Set voltages\n"); printf("T - Triggered block I - Set timebase\n"); if (unit->hasETS) { printf("E - Collect a block of data using ETS A - ADC counts/mV\n"); } else { printf("A - ADC counts/mV\n"); } printf("R - Collect set of rapid captures\n"); printf("S - Immediate streaming\n"); printf("W - Triggered streaming\n"); if (unit->sigGen != SIGGEN_NONE) { printf("G - Signal generator\n"); } if (unit->hasFlexibleResolution) { printf("D - Set device resolution\n"); } printf(" X - Exit\n"); printf("Operation:"); ch = toupper(_getch()); printf("\n\n"); switch (ch) { case 'B': CollectBlockImmediate(unit); break; case 'T': CollectBlockTriggered(unit); break; case 'R': CollectRapidBlock(unit); break; case 'S': CollectStreamingImmediate(unit); break; case 'W': CollectStreamingTriggered(unit); break; case 'E': if (unit->hasETS == FALSE) { printf("This model does not support ETS.\n\n"); break; } CollectBlockEts(unit); break; case 'G': if (unit->sigGen == SIGGEN_NONE) { printf("This model does not have a signal generator.\n\n"); break; } SetSignalGenerator(unit); break; case 'D': if (unit->hasFlexibleResolution == FALSE) { printf("This device does not have flexible resolution.\n\n"); break; } setResolution(unit); break; case 'V': SetVoltages(unit); break; case 'I': SetTimebase(unit); break; case 'A': scaleVoltages = !scaleVoltages; break; case 'X': printf("Exit main menu."); break; default: printf("Invalid operation\n"); break; } } } /**************************************************************************** * main * ***************************************************************************/ int32_t main(void) { int8_t ch; uint16_t devCount = 0, listIter = 0, openIter = 0; //device indexer - 64 chars - 64 is maximum number of PicoScope devices handled by driver int8_t devChars[] = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#"; PICO_STATUS status = PICO_OK; UNIT allUnits[MAX_PICO_DEVICES]; int16_t count = 0; int8_t serials[100]; int16_t serialsLength = 100; printf("PicoScope 4000 Series (ps4000a) Driver Example Program\n"); printf("\nEnumerating Units...\n"); status = ps4000aEnumerateUnits(&count, serials, &serialsLength); if (status == PICO_OK) { printf("Found %d devices - serial numbers: %s\n", count, serials); } do { status = OpenDevice(&(allUnits[devCount]), NULL); if (status == PICO_OK || status == PICO_USB3_0_DEVICE_NON_USB3_0_PORT || status == PICO_POWER_SUPPLY_NOT_CONNECTED) { allUnits[devCount++].openStatus = (int16_t) status; } } while(status != PICO_NOT_FOUND); if (devCount == 0) { printf("Picoscope devices not found\n"); _getch(); return 1; } // If there is only one device, open and handle it here if (devCount == 1) { printf("Found one device, opening...\n\n"); status = allUnits[0].openStatus; if (status == PICO_OK || status == PICO_POWER_SUPPLY_NOT_CONNECTED || status == PICO_USB3_0_DEVICE_NON_USB3_0_PORT) { set_info(&allUnits[0]); status = HandleDevice(&allUnits[0]); } if (status != PICO_OK && status != PICO_POWER_SUPPLY_NOT_CONNECTED) { printf("Picoscope devices open failed, error code 0x%x\n",(uint32_t)status); _getch(); return 1; } MainMenu(&allUnits[0]); CloseDevice(&allUnits[0]); printf("Exit...\n"); return 0; } else { // More than one unit printf("Found %d devices, initializing...\n\n", devCount); for (listIter = 0; listIter < devCount; listIter++) { if (allUnits[listIter].openStatus == PICO_OK || allUnits[listIter].openStatus == PICO_USB3_0_DEVICE_NON_USB3_0_PORT) { set_info(&allUnits[listIter]); openIter++; } } } // None if (openIter == 0) { printf("Picoscope devices init failed\n"); _getch(); return 1; } // Just one - handle it here if (openIter == 1) { for (listIter = 0; listIter < devCount; listIter++) { if (!(allUnits[listIter].openStatus == PICO_OK || allUnits[listIter].openStatus == PICO_USB3_0_DEVICE_NON_USB3_0_PORT)) { break; } } printf("One device opened successfully\n"); printf("Model\t: %s\nS/N\t: %s\n", allUnits[listIter].modelString, allUnits[listIter].serial); status = HandleDevice(&allUnits[listIter]); if (status != PICO_OK) { printf("Picoscope device open failed, error code 0x%x\n", (uint32_t)status); return 1; } MainMenu(&allUnits[listIter]); CloseDevice(&allUnits[listIter]); printf("Exit...\n"); return 0; } printf("Found %d devices, pick one to open from the list:\n", devCount); for (listIter = 0; listIter < devCount; listIter++) { printf("%c) Picoscope %7s S/N: %s\n", devChars[listIter], allUnits[listIter].modelString, allUnits[listIter].serial); } printf("ESC) Cancel\n"); ch = '.'; // If Escape while (ch != 27) { ch = _getch(); // If Escape if (ch == 27) { continue; } for (listIter = 0; listIter < devCount; listIter++) { if (ch == devChars[listIter]) { printf("Option %c) selected, opening Picoscope %7s S/N: %s\n", devChars[listIter], allUnits[listIter].modelString, allUnits[listIter].serial); if ((allUnits[listIter].openStatus == PICO_OK || allUnits[listIter].openStatus == PICO_POWER_SUPPLY_NOT_CONNECTED)) { status = HandleDevice(&allUnits[listIter]); } if (status != PICO_OK) { printf("Picoscope devices open failed, error code 0x%x\n", (uint32_t)status); _getch(); return 1; } MainMenu(&allUnits[listIter]); printf("Found %d devices, pick one to open from the list:\n",devCount); for (listIter = 0; listIter < devCount; listIter++) { printf("%c) Picoscope %7s S/N: %s\n", devChars[listIter], allUnits[listIter].modelString, allUnits[listIter].serial); } printf("ESC) Cancel\n"); } } } for (listIter = 0; listIter < devCount; listIter++) { CloseDevice(&allUnits[listIter]); } printf("Exit...\n"); return 0; }
26.191002
182
0.620896
[ "model" ]
5719e23893361ff91d964aed74fb836b5d8d62f9
973
h
C
dependencies/panda/Panda3D-1.10.0-x64/include/eggToObj.h
CrankySupertoon01/Toontown-2
60893d104528a8e7eb4aced5d0015f22e203466d
[ "MIT" ]
3
2018-03-09T12:07:29.000Z
2021-02-25T06:50:25.000Z
pandatool/src/objprogs/eggToObj.h
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
1
2018-07-28T20:07:04.000Z
2018-07-30T18:28:34.000Z
pandatool/src/objprogs/eggToObj.h
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
2
2019-12-02T01:39:10.000Z
2021-02-13T22:41:00.000Z
// Filename: eggToObj.h // Created by: drose (25Feb12) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #ifndef EGGTOOBJ_H #define EGGTOOBJ_H #include "pandatoolbase.h" #include "eggToSomething.h" #include "eggToObjConverter.h" //////////////////////////////////////////////////////////////////// // Class : EggToObj // Description : //////////////////////////////////////////////////////////////////// class EggToObj : public EggToSomething { public: EggToObj(); void run(); protected: virtual bool handle_args(Args &args); private: bool _triangulate_polygons; }; #endif
24.325
70
0.513875
[ "3d" ]
57249b1eb27a4a20de0b8d55d60c07eb023d32a1
12,297
c
C
lib/pbio/platform/motors/settings.c
ysard/pybricks-micropython
28c453a95230c4c36280fc6cd9674108b90c6f4c
[ "MIT" ]
null
null
null
lib/pbio/platform/motors/settings.c
ysard/pybricks-micropython
28c453a95230c4c36280fc6cd9674108b90c6f4c
[ "MIT" ]
null
null
null
lib/pbio/platform/motors/settings.c
ysard/pybricks-micropython
28c453a95230c4c36280fc6cd9674108b90c6f4c
[ "MIT" ]
null
null
null
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2018-2020 The Pybricks Authors #include <pbio/control.h> #include <pbio/observer.h> #include <pbio/iodev.h> #if PBDRV_CONFIG_NUM_MOTOR_CONTROLLER != 0 #if PBIO_CONFIG_CONTROL_MINIMAL #define SCALE(value, scalar) ((int32_t)((value) * (scalar))) #else #define SCALE(value, scalar) ((value) * (scalar)) #endif #if PBDRV_CONFIG_COUNTER_EV3DEV_STRETCH_IIO || PBDRV_CONFIG_COUNTER_NXT static const pbio_observer_model_t model_ev3_m = { .phi_01 = SCALE(0.0f, PBIO_OBSERVER_SCALE_HIGH), .phi_11 = SCALE(0.0f, PBIO_OBSERVER_SCALE_LOW), .gam_0 = SCALE(0.0f, PBIO_OBSERVER_SCALE_LOW), .gam_1 = SCALE(0.0f, PBIO_OBSERVER_SCALE_LOW), .k_0 = SCALE(0.02222706190764267f, PBIO_OBSERVER_SCALE_HIGH), .k_1 = SCALE(0.000204397590361446f, PBIO_OBSERVER_SCALE_HIGH), .k_2 = SCALE(0.00262048192771084f, PBIO_OBSERVER_SCALE_HIGH), .f_low = SCALE(0.009158620689655174f, PBIO_OBSERVER_SCALE_TRQ), .obs_gains = 0, }; static const pbio_control_settings_t settings_ev3_m = { .max_rate = 2000, .abs_acceleration = 8000, .rate_tolerance = 100, .count_tolerance = 10, .stall_rate_limit = 30, .stall_time = 200 * US_PER_MS, .pid_kp = 3000, .pid_kd = 30, .integral_rate = 10, .use_estimated_rate = false, }; static const pbio_observer_model_t model_ev3_l = { .phi_01 = SCALE(0.0f, PBIO_OBSERVER_SCALE_HIGH), .phi_11 = SCALE(0.0f, PBIO_OBSERVER_SCALE_LOW), .gam_0 = SCALE(0.0f, PBIO_OBSERVER_SCALE_LOW), .gam_1 = SCALE(0.0f, PBIO_OBSERVER_SCALE_LOW), .k_0 = SCALE(0.049886243386243395f, PBIO_OBSERVER_SCALE_HIGH), .k_1 = SCALE(0.000433486238532110f, PBIO_OBSERVER_SCALE_HIGH), .k_2 = SCALE(0.00412844036697248f, PBIO_OBSERVER_SCALE_HIGH), .f_low = SCALE(0.00823809523809524f, PBIO_OBSERVER_SCALE_TRQ), .obs_gains = 0, }; static const pbio_control_settings_t settings_ev3_l = { .max_rate = 1600, .abs_acceleration = 3200, .rate_tolerance = 100, .count_tolerance = 10, .stall_rate_limit = 30, .stall_time = 200 * US_PER_MS, .pid_kp = 15000, .pid_kd = 250, .integral_rate = 10, .use_estimated_rate = false, }; #endif // PBDRV_CONFIG_COUNTER_EV3DEV_STRETCH_IIO || PBDRV_CONFIG_COUNTER_NXT #if PBDRV_CONFIG_IOPORT_LPF2 || PBDRV_CONFIG_COUNTER_TEST static const pbio_observer_model_t model_technic_s_angular = { .phi_01 = SCALE(0.00468582248829651f, PBIO_OBSERVER_SCALE_HIGH), .phi_11 = SCALE(0.877017999120650f, PBIO_OBSERVER_SCALE_LOW), .gam_0 = SCALE(4.49747292641861f, PBIO_OBSERVER_SCALE_LOW), .gam_1 = SCALE(1760.49589416085f, PBIO_OBSERVER_SCALE_LOW), .k_0 = SCALE(0.010402524000000002f, PBIO_OBSERVER_SCALE_HIGH), .k_1 = SCALE(0.000255865711052433f, PBIO_OBSERVER_SCALE_HIGH), .k_2 = SCALE(0.00671533699371639f, PBIO_OBSERVER_SCALE_HIGH), .f_low = SCALE(0.0005f, PBIO_OBSERVER_SCALE_TRQ), .obs_gains = PBIO_OBSERVER_GAINS(100, 500, 500), }; static const pbio_control_settings_t settings_technic_s_angular = { .max_rate = 620, .abs_acceleration = 2000, .rate_tolerance = 50, .count_tolerance = 10, .stall_rate_limit = 20, .stall_time = 200 * US_PER_MS, .pid_kp = 7500, .pid_kd = 1000, .integral_rate = 15, .use_estimated_rate = true, }; static const pbio_observer_model_t model_technic_m_angular = { .phi_01 = SCALE(0.00465623814072756f, PBIO_OBSERVER_SCALE_HIGH), .phi_11 = SCALE(0.865721137934373f, PBIO_OBSERVER_SCALE_LOW), .gam_0 = SCALE(2.36522158991640f, PBIO_OBSERVER_SCALE_LOW), .gam_1 = SCALE(923.893256509643f, PBIO_OBSERVER_SCALE_LOW), .k_0 = SCALE(0.02258435646747968f, PBIO_OBSERVER_SCALE_HIGH), .k_1 = SCALE(0.000223154509118161f, PBIO_OBSERVER_SCALE_HIGH), .k_2 = SCALE(0.00643543836108826f, PBIO_OBSERVER_SCALE_HIGH), .f_low = SCALE(0.01218641268292683f, PBIO_OBSERVER_SCALE_TRQ), .obs_gains = PBIO_OBSERVER_GAINS(100, 800, 2000), }; static const pbio_control_settings_t settings_technic_m_angular = { .max_rate = 1080, .abs_acceleration = 2000, .rate_tolerance = 50, .count_tolerance = 10, .stall_rate_limit = 20, .stall_time = 200 * US_PER_MS, .pid_kp = 15000, .pid_kd = 1800, .integral_rate = 15, .use_estimated_rate = true, }; static const pbio_observer_model_t model_technic_l_angular = { .phi_01 = SCALE(0.00476139134919619f, PBIO_OBSERVER_SCALE_HIGH), .phi_11 = SCALE(0.906099484723787f, PBIO_OBSERVER_SCALE_LOW), .gam_0 = SCALE(0.684051954862549f, PBIO_OBSERVER_SCALE_LOW), .gam_1 = SCALE(269.197410994572f, PBIO_OBSERVER_SCALE_LOW), .k_0 = SCALE(0.052359221241860474f, PBIO_OBSERVER_SCALE_HIGH), .k_1 = SCALE(0.000337807915176920f, PBIO_OBSERVER_SCALE_HIGH), .k_2 = SCALE(0.00666198910636721f, PBIO_OBSERVER_SCALE_HIGH), .f_low = SCALE(0.011619602790697674f, PBIO_OBSERVER_SCALE_TRQ), .obs_gains = PBIO_OBSERVER_GAINS(1000, 2000, 4000), }; static const pbio_control_settings_t settings_technic_l_angular = { .max_rate = 970, .abs_acceleration = 1500, .rate_tolerance = 50, .count_tolerance = 10, .stall_rate_limit = 20, .stall_time = 200 * US_PER_MS, .pid_kp = 35000, .pid_kd = 6000, .integral_rate = 15, .use_estimated_rate = true, }; static const pbio_observer_model_t model_interactive = { .phi_01 = SCALE(0.00476271917080314f, PBIO_OBSERVER_SCALE_HIGH), .phi_11 = SCALE(0.906613349592095f, PBIO_OBSERVER_SCALE_LOW), .gam_0 = SCALE(2.93111612537300f, PBIO_OBSERVER_SCALE_LOW), .gam_1 = SCALE(1153.59979915647f, PBIO_OBSERVER_SCALE_LOW), .k_0 = SCALE(0.01500933205496964f, PBIO_OBSERVER_SCALE_HIGH), .k_1 = SCALE(0.000275066965901687f, PBIO_OBSERVER_SCALE_HIGH), .k_2 = SCALE(0.00539346991964092f, PBIO_OBSERVER_SCALE_HIGH), .f_low = SCALE(0.005613422818791947f, PBIO_OBSERVER_SCALE_TRQ), .obs_gains = PBIO_OBSERVER_GAINS(2000, 2000, 2000), }; static const pbio_control_settings_t settings_interactive = { .max_rate = 1000, .abs_acceleration = 2000, .rate_tolerance = 50, .count_tolerance = 5, .stall_rate_limit = 15, .stall_time = 200 * US_PER_MS, .pid_kp = 13500, .pid_kd = 1350, .integral_rate = 10, .use_estimated_rate = true, }; #if PBDRV_CONFIG_COUNTER_STM32F0_GPIO_QUAD_ENC static const pbio_observer_model_t model_movehub = { .phi_01 = SCALE(0.00482560542071840f, PBIO_OBSERVER_SCALE_HIGH), .phi_11 = SCALE(0.931062779704023f, PBIO_OBSERVER_SCALE_LOW), .gam_0 = SCALE(2.20557850267909f, PBIO_OBSERVER_SCALE_LOW), .gam_1 = SCALE(871.853080213830f, PBIO_OBSERVER_SCALE_LOW), .k_0 = SCALE(0.02120903269295585f, PBIO_OBSERVER_SCALE_HIGH), .k_1 = SCALE(0.000260968229954614f, PBIO_OBSERVER_SCALE_HIGH), .k_2 = SCALE(0.00372811757078020f, PBIO_OBSERVER_SCALE_HIGH), .f_low = SCALE(0.012417391304347828f, PBIO_OBSERVER_SCALE_TRQ), .obs_gains = PBIO_OBSERVER_GAINS(2000, 2000, 2000), }; static const pbio_control_settings_t settings_movehub = { .max_rate = 1500, .abs_acceleration = 5000, .rate_tolerance = 50, .count_tolerance = 6, .stall_rate_limit = 15, .stall_time = 200 * US_PER_MS, .pid_kp = 15000, .pid_kd = 500, .integral_rate = 5, .use_estimated_rate = true, }; #endif // PBDRV_CONFIG_COUNTER_STM32F0_GPIO_QUAD_ENC static const pbio_observer_model_t model_technic_l = { .phi_01 = SCALE(0.00480673379919289f, PBIO_OBSERVER_SCALE_HIGH), .phi_11 = SCALE(0.923702638108050f, PBIO_OBSERVER_SCALE_LOW), .gam_0 = SCALE(1.53998720733930f, PBIO_OBSERVER_SCALE_LOW), .gam_1 = SCALE(607.954007356971f, PBIO_OBSERVER_SCALE_LOW), .k_0 = SCALE(0.029291367521367528f, PBIO_OBSERVER_SCALE_HIGH), .k_1 = SCALE(0.000269922879177378f, PBIO_OBSERVER_SCALE_HIGH), .k_2 = SCALE(0.00428449014567267f, PBIO_OBSERVER_SCALE_HIGH), .f_low = SCALE(0.013215000000000001f, PBIO_OBSERVER_SCALE_TRQ), .obs_gains = PBIO_OBSERVER_GAINS(1000, 2000, 2000), }; static const pbio_control_settings_t settings_technic_l = { .max_rate = 1470, .abs_acceleration = 1500, .rate_tolerance = 50, .count_tolerance = 10, .stall_rate_limit = 20, .stall_time = 200 * US_PER_MS, .pid_kp = 20000, .pid_kd = 2500, .integral_rate = 5, .use_estimated_rate = true, }; static const pbio_observer_model_t model_technic_xl = { .phi_01 = SCALE(0.00481529951016882f, PBIO_OBSERVER_SCALE_HIGH), .phi_11 = SCALE(0.927040916512593f, PBIO_OBSERVER_SCALE_LOW), .gam_0 = SCALE(1.66041757033247f, PBIO_OBSERVER_SCALE_LOW), .gam_1 = SCALE(655.886425902678f, PBIO_OBSERVER_SCALE_LOW), .k_0 = SCALE(0.025904742547425474f, PBIO_OBSERVER_SCALE_HIGH), .k_1 = SCALE(0.000283410138248848f, PBIO_OBSERVER_SCALE_HIGH), .k_2 = SCALE(0.00429409300377042f, PBIO_OBSERVER_SCALE_HIGH), .f_low = SCALE(0.002f, PBIO_OBSERVER_SCALE_TRQ), .obs_gains = PBIO_OBSERVER_GAINS(500, 1500, 2000), }; static const pbio_control_settings_t settings_technic_xl = { .max_rate = 1525, .abs_acceleration = 2500, .rate_tolerance = 50, .count_tolerance = 10, .stall_rate_limit = 20, .stall_time = 200 * US_PER_MS, .pid_kp = 17500, .pid_kd = 2500, .integral_rate = 5, .use_estimated_rate = true, }; #endif // PBDRV_CONFIG_IOPORT_LPF2 || PBDRV_CONFIG_COUNTER_TEST pbio_error_t pbio_servo_load_settings(pbio_control_settings_t *settings, const pbio_observer_model_t **model, pbio_iodev_type_id_t id) { switch (id) { case PBIO_IODEV_TYPE_ID_NONE: return PBIO_ERROR_NOT_SUPPORTED; #if PBDRV_CONFIG_COUNTER_EV3DEV_STRETCH_IIO || PBDRV_CONFIG_COUNTER_NXT case PBIO_IODEV_TYPE_ID_EV3_MEDIUM_MOTOR: *model = &model_ev3_m; *settings = settings_ev3_m; break; case PBIO_IODEV_TYPE_ID_EV3_LARGE_MOTOR: *model = &model_ev3_l; *settings = settings_ev3_l; break; #endif // PBDRV_CONFIG_COUNTER_EV3DEV_STRETCH_IIO || PBDRV_CONFIG_COUNTER_NXT #if PBDRV_CONFIG_IOPORT_LPF2 || PBDRV_CONFIG_COUNTER_TEST case PBIO_IODEV_TYPE_ID_INTERACTIVE_MOTOR: *model = &model_interactive; *settings = settings_interactive; break; #if PBDRV_CONFIG_COUNTER_STM32F0_GPIO_QUAD_ENC case PBIO_IODEV_TYPE_ID_MOVE_HUB_MOTOR: *model = &model_movehub; *settings = settings_movehub; break; #endif // PBDRV_CONFIG_COUNTER_STM32F0_GPIO_QUAD_ENC case PBIO_IODEV_TYPE_ID_TECHNIC_L_MOTOR: *model = &model_technic_l; *settings = settings_technic_l; break; case PBIO_IODEV_TYPE_ID_TECHNIC_XL_MOTOR: *model = &model_technic_xl; *settings = settings_technic_xl; break; case PBIO_IODEV_TYPE_ID_SPIKE_S_MOTOR: *model = &model_technic_s_angular; *settings = settings_technic_s_angular; break; case PBIO_IODEV_TYPE_ID_TECHNIC_L_ANGULAR_MOTOR: case PBIO_IODEV_TYPE_ID_SPIKE_L_MOTOR: *model = &model_technic_l_angular; *settings = settings_technic_l_angular; break; case PBIO_IODEV_TYPE_ID_TECHNIC_M_ANGULAR_MOTOR: case PBIO_IODEV_TYPE_ID_SPIKE_M_MOTOR: *model = &model_technic_m_angular; *settings = settings_technic_m_angular; break; #endif // PBDRV_CONFIG_IOPORT_LPF2 || PBDRV_CONFIG_COUNTER_TEST default: return PBIO_ERROR_NOT_SUPPORTED; } // Given the configured settings, now calculate dependent settings. // Initialize maximum torque as the stall torque for maximum voltage. settings->max_torque = pbio_observer_voltage_to_torque(*model, pbio_dcmotor_get_max_voltage(id)); // Initialize ki such that integral control saturates in about twos second // if the motor were stuck at the position tolerance. settings->pid_ki = settings->max_torque / settings->count_tolerance / 2; return PBIO_SUCCESS; } int32_t pbio_dcmotor_get_max_voltage(pbio_iodev_type_id_t id) { if (id == PBIO_IODEV_TYPE_ID_SPIKE_S_MOTOR) { return 6000; } return 9000; } #endif // PBDRV_CONFIG_NUM_MOTOR_CONTROLLER != 0
37.836923
136
0.719769
[ "model" ]
5726834f1e3564c84b24b552f6b634346474e682
4,194
h
C
src/m3/chains/dynamatics.h
ahoarau/m3meka
237739f0266ce60aaa3013b0d2b22fc07b6374c4
[ "MIT" ]
1
2015-06-19T12:14:18.000Z
2015-06-19T12:14:18.000Z
src/m3/chains/dynamatics.h
semeyerz/m3meka
6e5d6b73ad3ebdd8429497923e601eae65d8b2fe
[ "MIT" ]
null
null
null
src/m3/chains/dynamatics.h
semeyerz/m3meka
6e5d6b73ad3ebdd8429497923e601eae65d8b2fe
[ "MIT" ]
2
2015-11-27T09:25:54.000Z
2021-08-16T16:29:22.000Z
/* M3 -- Meka Robotics Robot Components Copyright (c) 2010 Meka Robotics Author: edsinger@mekabot.com (Aaron Edsinger) M3 is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. M3 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 M3. If not, see <http://www.gnu.org/licenses/>. */ #ifndef M3_DYNAMATICS_H #define M3_DYNAMATICS_H #include "m3rt/base/component.h" #include "m3/chains/dynamatics.pb.h" #include "m3/toolbox/toolbox.h" #include <google/protobuf/message.h> #include "m3/chains/joint_chain.h" namespace m3 { using namespace std; using namespace KDL; /////////////////////////////////////////////////////////////////////////// class M3JointChain; class M3Dynamatics : public m3rt::M3Component { public: M3Dynamatics() : M3Component(DYNAMATICS_PRIORITY), m3chain(NULL),fksolver_vel(NULL), idsolver(NULL), jjsolver(NULL) ,tmp_cnt(0) { RegisterVersion("default",DEFAULT); //RBL RegisterVersion("iss",ISS); //ISS. Safe as DEFAULT //RegisterVersion("iq",IQ); } ~M3Dynamatics() { if (fksolver_vel!=NULL) delete fksolver_vel;fksolver_vel=NULL; if (idsolver!=NULL) delete idsolver;idsolver=NULL; if (jjsolver!=NULL) delete jjsolver;jjsolver=NULL; } google::protobuf::Message * GetCommand(){return &command;} google::protobuf::Message * GetStatus(){return &status;} google::protobuf::Message * GetParam(){return &param;} int GetNumDof(){return ndof;} Vector GetEndPos(){return end_pos;} Rotation GetEndRot(){return end_rot;} Twist GetEndTwist(){return end_twist;} mReal GetG(int i){return G(i+3);} Vector GetPayloadCom(){return payload_com;} mReal GetPayloadMass(){return param.payload_mass();} void SetGrav(Vector new_grav){grav = new_grav;} Wrench GetBaseWrench(){return base_wrench;} void SetEndWrench(Wrench wrench){end_wrench = wrench;} mReal GetMass(){return chain_mass+GetPayloadMass();} int GetNumSegments(){return kdlchain.getNrOfSegments();} RotationalInertia GetPayloadInertia(){return payload_I;} private: enum {DEFAULT, ISS}; M3JointChain * m3chain; string chain_name; Rotation end_rot; FrameVel end_2_base_framevel; // Using Inverse Jacobian should be avoided in favor of faster numerical solvers... Jacobian J; //6x(ndof) Jacobian JntArray G; //gravity , (ndof)x1 JntArray qdotdot_id; JntArray qdot_id; JntArray zero_vec; Twist end_twist; Vector end_pos; Chain kdlchain; JntArrayVel q; // both q and qdot // for end frame with no load Vector z_com; RotationalInertia z_I; mReal z_m; Vector grav; ChainIdSolver_RNE * idsolver; std::vector<Wrench> f_ext; ChainFkSolverVel_recursive * fksolver_vel; //ChainFkSolverPos_recursive * fksolver_pos; ChainJntToJacSolver * jjsolver; int ndof; Vector payload_com; Wrench end_wrench; Wrench base_wrench; mReal chain_mass; vector<mReal> d; vector<mReal> a; vector<mReal> alpha; vector<mReal> joint_offset; vector<mReal> m; vector<mReal> cx; vector<mReal> cy; vector<mReal> cz; vector<mReal> Ixx; vector<mReal> Ixy; vector<mReal> Ixz; vector<mReal> Iyy; vector<mReal> Iyz; vector<mReal> Izz; RotationalInertia payload_I; bool use_velocities; bool use_accelerations; // A.H : pre allocate in setpayload() //Segment* ToTipSeg; RigidBodyInertia rb_inertia; RotationalInertia rot_inertia; Vector com; Vector ecom; Frame toTip; int tmp_cnt; protected: bool ReadConfig(const char * filename); void Startup(); void Shutdown(); void StepStatus(); void StepCommand(); bool LinkDependentComponents(); M3BaseStatus * GetBaseStatus(){return status.mutable_base();} M3DynamaticsStatus status; M3DynamaticsCommand command; M3DynamaticsParam param; void SetPayload(); }; } #endif
29.125
129
0.725083
[ "vector" ]
5728457ac13d9e22c37c2d89d0d5ef162092ff44
708
h
C
fontObject.h
odiminox/PuzzleQuestPlanet
18ebd14e85ecd8ecb7662075dc97b5ea4c8cbac9
[ "Apache-2.0" ]
null
null
null
fontObject.h
odiminox/PuzzleQuestPlanet
18ebd14e85ecd8ecb7662075dc97b5ea4c8cbac9
[ "Apache-2.0" ]
null
null
null
fontObject.h
odiminox/PuzzleQuestPlanet
18ebd14e85ecd8ecb7662075dc97b5ea4c8cbac9
[ "Apache-2.0" ]
null
null
null
// // fontObject.h // oglApp // // Created by Simon Jordan on 10/02/2013. // Copyright (c) 2013 Simon Jordan. All rights reserved. // #ifndef __oglApp__fontObject__ #define __oglApp__fontObject__ #include "GLKit/GLKit.h" #include "OBJECT.h" class fontObject : public OBJECT{ public: private: CGImageRef m_imageRef; GLKTextureInfo * m_textureInfo; GLuint vertexBufferID; GLuint indexBufferID; GLuint textureBufferID; int m_imageWidth; int m_imageHeight; int m_imageFrameWidth; int m_imageFrameHeight; int m_cellWidth; int m_cellHeight; int m_numFrames; int m_startFrame; int m_endFrame; }; #endif /* defined(__oglApp__fontObject__) */
19.135135
57
0.707627
[ "object" ]
573472b82e0903f55a45307458fd3a507383dda6
56,477
h
C
src/ExprLib/exprman.h
asminer/smart
269747c4578b670e5c3973f93a1e6ec71d95be78
[ "Apache-2.0" ]
6
2018-05-30T23:02:14.000Z
2022-01-19T07:30:46.000Z
src/ExprLib/exprman.h
asminer/smart
269747c4578b670e5c3973f93a1e6ec71d95be78
[ "Apache-2.0" ]
null
null
null
src/ExprLib/exprman.h
asminer/smart
269747c4578b670e5c3973f93a1e6ec71d95be78
[ "Apache-2.0" ]
2
2018-07-13T18:53:27.000Z
2021-04-12T17:54:02.000Z
/** This is a first step towards the ultimate goal of a completely general, extensible expression library. In such a library we will: - Register every type - Register every operation - Register solution engine types - Register solution engines */ #ifndef EXPRMAN_H #define EXPRMAN_H #include "../Streams/streams.h" #include "type.h" #include "expr.h" class symbol; class function; class measure; class engine; class engtype; class unary_op; class binary_op; class trinary_op; class assoc_op; class option; class option_const; class general_conv; class specific_conv; /** Abstract base class for external libraries. Right now, this is used only for "credits". To register an external library, derive a class from this one and implement the virtual functions. */ class library { bool has_copyright; bool has_release_date; public: library(bool has_cr, bool has_date); virtual ~library(); /** Can the library be determined from the pointer address? If so, we can very quickly check for duplicates; otherwise, we have to compare strings. @return true iff getVersionString() is unique for the library. */ virtual bool hasFixedPointer() const = 0; /// Get the version string for a library. virtual const char* getVersionString() const = 0; /// Does the library have copyright info. inline bool hasCopyright() const { return has_copyright; } /** Print copyright info for a library. Default is to dump core, i.e., assuming there is no copyright info then this should not be called. Otherwise, if there is copyright info, then this must be overridden in the derived class. */ virtual void printCopyright(doc_formatter *df) const; /// Does the library have a release date. inline bool hasReleaseDate() const { return has_release_date; } /** Print release date for a library. Default is to dump core. */ virtual void printReleaseDate(doc_formatter *df) const; }; /** Struct for dealing with groups of named messages. Used almost entirely automatically by struct named_msg. */ class group_of_named { int alloc; int curr; option_const** items; public: group_of_named(int max); ~group_of_named(); void AddItem(option_const* foo); /** Finish the group, and add an appropriate checklist item to the owner. */ void Finish(option* owner, const char* n, const char* docs); }; /** Struct for named report/warning/debug messages. */ class named_msg { static io_environ* io; bool active; const char* name; friend exprman* Initialize_Expressions(io_environ* io, option_manager* om); public: /** Initialize. @param owner If nonzero, a new checklist constant for this item will be created and added to owner. @param n Name of the item. @param d Documentation (not required if \a owner is 0). @param act Are we initially active or not. @return Created option constant, if any. */ option_const* Initialize(option* owner, const char* n, const char* docs, bool act); inline bool isActive() const { return active; } inline bool canWrite() const { return active && io; } inline bool startWarning() const { if (!active) return false; if (!io) return false; io->StartWarning(); return true; } inline bool startReport() const { if (!active) return false; if (!io) return false; io->StartReport(name); return true; } inline void causedBy(const expr* x) const { DCASSERT(io); if (x) io->CausedBy(x->Filename(), x->Linenumber()); else io->NoCause(); } inline void causedBy(const char* fn, int ln) const { DCASSERT(io); io->CausedBy(fn, ln); } inline void noCause() const { DCASSERT(io); io->NoCause(); } inline void newLine() const { DCASSERT(io); io->NewLine(name); } inline void stopIO() const { DCASSERT(io); io->Stop(); } inline DisplayStream& report() const { DCASSERT(io); return io->Report; } inline FILE* Freport() const { if (io) return io->Report.getDisplay(); return stdout; } inline DisplayStream& warn() const { DCASSERT(io); return io->Warning; } inline bool caughtTerm() const { DCASSERT(io); return io->caughtTerm(); } }; /** Expression manager class. This is an abstract base class, to provide the interface and hide the (possibly vast) implementation details. This huge class manages all modules that one can register for building and solving expressions. In essence, the class encapsulates all of the "state" of the expression library. Members that require a "registry" are virtual, and are implemented in a derived class. Otherwise, members are not virtual, and are provided. To save our sanity, there is at most one expression manager created during the lifetime of an application. This way, we can store the expression manager as a static member of every expression without memory overhead. Included in this class are centralized collections of options, engines, libraries, and types (including formalisms). Before the manager is "finalize()d", new engines, engine types, and options may be added, but engines may not be launched. After the manager is "finalize()d", new engines, options, libraries cannot be added. */ class exprman { io_environ* io; protected: bool is_finalized; option_manager* om; // warnings and such named_msg promote_arg; public: // "Fundamental" types, these need to be known lots of places. simple_type* VOID; simple_type* NULTYPE; simple_type* BOOL; simple_type* INT; simple_type* REAL; simple_type* MODEL; // Internal, for next state computations. const type* NEXT_STATE; // Optional types, placed in standalone modules. simple_type* EXPO; simple_type* STRING; simple_type* BIGINT; simple_type* STATESET; simple_type* STATEDIST; simple_type* STATEPROBS; simple_type* TEMPORAL; simple_type* TRACE; // Indicates "no engine". This does NOT necessarily mean "easy to compute" engtype* NO_ENGINE; // Indicates a measure whose classification is waiting for dependencies. engtype* BLOCKED_ENGINE; /// Unary operators. enum unary_opcode { /// Boolean negation. uop_not = 0, /// Arithmetic negation. uop_neg = 1, /// Temporal operator "A". uop_forall = 2, /// Temporal operator "E". uop_exists = 3, /// Temporal operator "F" uop_future = 4, /// Temporal operator "G" uop_globally = 5, /// Temporal operator "X" uop_next = 6, /// no operation (placeholder). MUST BE THE LARGEST INTEGER. uop_none = 7 }; /// Binary operators. enum binary_opcode { /// Boolean implication bop_implies = 0, /// Modulo operator bop_mod = 1, /// Set difference bop_diff = 2, /// Check for equality bop_equals = 3, /// Check for inequality bop_nequal = 4, /// Greater than bop_gt = 5, /// Greater or equal bop_ge = 6, /// Less than bop_lt = 7, /// Less or equal bop_le = 8, /// Temporal operator "U" bop_until = 9, /// Temporal operator "AND" bop_and = 10, /// no operation (placeholder). MUST BE THE LARGEST INTEGER. bop_none = 11 }; /// Trinary operators. enum trinary_opcode { /// Set intervals. top_interval = 0, /// If-then-else top_ite = 1, /// no operation (placeholder). MUST BE THE LARGEST INTEGER. top_none = 2 }; /// Associative operators. enum assoc_opcode { /// Boolean AND aop_and = 0, /// Boolean OR aop_or = 1, /// Addition aop_plus = 2, /// Multiplication aop_times = 3, /// Aggregation aop_colon = 4, /// Aggregation of void expressions aop_semi = 5, /// Union of sets aop_union = 6, /// no operation (placeholder). aop_none = 7 }; public: exprman(io_environ* io, option_manager* om); inline bool isFinalized() const { return is_finalized; } /// Called when we are done registering objects. virtual void finalize() = 0; inline const option_manager* OptMan() const { return om; } void addOption(option* o); option* findOption(const char* name) const; // +-----------------------------------------------------------------+ // | | // | Handy I/O hooks | // | | // +-----------------------------------------------------------------+ inline bool hasIO() const { return io; } inline bool isInteractive() const { if (io) return io->IsInteractive(); else return false; } inline void setInteractive() { if (io) io->SetInteractive(); } inline void setBatch() { if (io) io->SetBatch(); } inline bool startInternal(const char* fn, int ln) const { if (!io) return false; io->StartInternal(fn, ln); return true; } inline bool startError() const { if (!io) return false; io->StartError(); return true; } inline bool startWarning() const { if (!io) return false; io->StartWarning(); return true; } inline void causedBy(const expr* x) const { DCASSERT(io); if (x) io->CausedBy(x->Filename(), x->Linenumber()); else io->NoCause(); } inline void causedBy(const char* fn, int ln) const { DCASSERT(io); io->CausedBy(fn, ln); } inline void noCause() const { DCASSERT(io); io->NoCause(); } inline void newLine(int delta = 0) const { DCASSERT(io); io->ChangeIndent(delta); io->NewLine(); } inline void changeIndent(int delta) const { DCASSERT(io); io->ChangeIndent(delta); } inline void stopIO() const { DCASSERT(io); io->Stop(); } inline InputStream& cin() const { DCASSERT(io); return io->Input; } inline DisplayStream& cout() const { DCASSERT(io); return io->Output; } inline FILE* Fstdout() const { if (io) return io->Output.getDisplay(); return stdout; } inline DisplayStream& cerr() const { DCASSERT(io); return io->Error; } inline DisplayStream& warn() const { DCASSERT(io); return io->Warning; } inline DisplayStream& report() const { DCASSERT(io); return io->Report; } inline FILE* Freport() const { if (io) return io->Report.getDisplay(); return stdout; } inline DisplayStream& internal() const { DCASSERT(io); return io->Internal; } inline bool caughtTerm() const { DCASSERT(io); return io->caughtTerm(); } inline void waitTerm() { DCASSERT(io); io->WaitTerm(); } inline void resumeTerm() { DCASSERT(io); io->ResumeTerm(); } inline void Exit() { DCASSERT(io); io->Exit(); } // +-----------------------------------------------------------------+ // | | // | Special expressions | // | | // +-----------------------------------------------------------------+ /** Build a special "error" expression. Should be used for, say, compile-time errors. */ virtual expr* makeError() const = 0; /// Is the given expression the special "error" expression? virtual bool isError(const expr* e) const = 0; /** Build a special "default" expression. Used as a placeholder for defaults in function declarations. */ virtual expr* makeDefault() const = 0; /// Is the given expression the special "default" expression? virtual bool isDefault(const expr* e) const = 0; /** Is the given expression "ordinary"? This is shorthand for: not null, not Error, not Default. */ virtual bool isOrdinary(const expr* e) const = 0; // +-----------------------------------------------------------------+ // | | // | Types | // | | // +-----------------------------------------------------------------+ /** Register a data type. This gives a much nicer mechanism for dealing with types, and for adding new types. In particular, it allows us to add formalisms. @param f The formalism to register. @return true, on success. false, if the operation could not be completed for any reason. */ virtual bool registerType(type* t) = 0; /** Set the fundamental types. Should be called after the fundamental types have been registered, but before they are used. @return true iff all the required fundamental types were found. */ virtual bool setFundamentalTypes() = 0; /** Find "one-word, definable" types. A type is "definable" iff a user can declare a function or a variable of that type. A type is "one word" if its name consists of a single word (i.e., it is "deterministic" and not "proc"). Not extremely efficient, but since this is normally used only at compile time, should be fine. @param name A one-word name. @return A definable type whose name matches \a name, or 0 if none exists. */ virtual const type* findOWDType(const char* name) const = 0; /** Find a "simple" type with the given name. Not constant, so we can use this when initializing types. @param name A type name. @return A definable type whose name matches \a name, or 0 if none exists. */ virtual simple_type* findSimple(const char* name) = 0; /** Find a type with the given name. May catch types that findOWDType() misses. Not extremely efficient, but used at compile or initialization time, it should be fine. @param name A type name. @return A definable type whose name matches \a name, or 0 if none exists. */ virtual const type* findType(const char* name) const = 0; /// Returns the modifier with given name, or NO_SUCH_MODIF. virtual modifier findModifier(const char* name) const = 0; /// Get the current number of registered types. virtual int getNumTypes() const = 0; /// Get the ith registered type. virtual const type* getTypeNumber(int i) const = 0; /// Safe way to get expression type inline const type* SafeType(const expr *e, int comp) const { if (e) return e->Type(comp); else return NULTYPE; } /// Safe way to get (known simple) expression type inline const type* SafeType(const expr* e) const { if (e) return e->Type(); else return NULTYPE; } // +-----------------------------------------------------------------+ // | | // | Building constants | // | | // +-----------------------------------------------------------------+ /** Make a "literal" value. @param file Filename of definition. @param line Line number of definition. @param t Type of the value. @param c The value to draw from. @return A new expression. */ expr* makeLiteral(const char* file, int line, const type* t, const result& c) const; // +-----------------------------------------------------------------+ // | | // | Building symbols | // | | // +-----------------------------------------------------------------+ /** Make an iterator variable. I.e., a variable used as an array index, also as for-loop iterators. Implemented in forloops.cc. @param fn Filename of the variable. @param ln Line number of the variable. @param t Type of the variable. @param name Name of the variable. @param vals Set of values for the variable. @return 0, if some error occurred. A new expression, otherwise. */ symbol* makeIterator(const char* fn, int ln, const type* t, char* name, expr* vals) const; /** Make a "constant" (function with no parameters) symbol, not within a converge block. Implemented in symbols.cc. @param fn Filename of the variable. @param ln Line number of the variable. @param t Type of the variable. @param name Name of the variable. @param rhs Expression to assign to this symbol. @param deps List of symbols that must be "computed" before this one. @return 0, if some error occurred. A new expression, otherwise. */ symbol* makeConstant(const char* fn, int ln, const type* t, char* name, expr* rhs, List <symbol> *deps) const; /** Make a "constant" (function with no parameters) symbol, not within a converge block. Implemented in symbols.cc. @param w Wrapper symbol around this one. @param rhs Expression to assign to this symbol. @param deps List of symbols that must be "computed" before this one. @return 0, if some error occurred. A new expression, otherwise. */ symbol* makeConstant(const symbol* w, expr* rhs, List <symbol> *deps) const; // +-----------------------------------------------------------------+ // | | // | Building statements | // | | // +-----------------------------------------------------------------+ /** Make an expression statement. Normally this is allowed only for void expressions, and in this case the expression is returned unchanged. In the mean time, we also allow statements of the form: 5+7; which will simply cause the expression to be computed and printed. Implemented in stmts.cc. @param fn Filename. @param ln Line number. @param e Expression @return ERROR, if an error ocurred. A new "compute statement", otherwise. */ expr* makeExprStatement(const char* file, int line, expr* e) const; /** Make an option-setting statement. Implemented in stmts.cc. @param file Filename. @param line Line number. @param o Option to set. @param e Value to assign to the option. @return ERROR, if an error occurred. A new statement, otherwise. */ expr* makeOptionStatement(const char* file, int line, option *o, expr *e) const; /** Make an option-setting statement. Implemented in stmts.cc. @param file Filename. @param line Line number. @param o Option to set. @param v Constant to assign to the option. @return ERROR, if an error occurred. A new statement, otherwise. */ expr* makeOptionStatement(const char* file, int line, option *o, option_const *v) const; /** Make a checkbox-setting statement. Used for checkbox-style options. Note that the action is performed directly on the option constant. The option is provided only for display purposes. Implemented in stmts.cc. @param file Filename. @param line Line number. @param o Option. @param check If true, we will "check the box"; otherwise, we will "uncheck the box". @param vlist List of items to check or uncheck. @param nv Number of list items. @return ERROR, if an error occurred. A new statement, otherwise. */ expr* makeOptionStatement(const char* file, int line, option* o, bool check, option_const **vlist, int nv) const; /** Make a for loop statement. This is an expression with type "void" which, when computed, will set all possible assignments to a set of iterator variables, and for each assignment, will execute another statement (void-type expression). Implemented in forloops.cc. @param fn Filename. @param ln Line number. @param iters Array of iterators. @param dim Dimension of the loop (number of iterators). @param stmt The statement to execute within the loop. (can be a statement block). @return ERROR, if some error occurred. A new void-type expression, otherwise. */ expr* makeForLoop(const char* fn, int ln, symbol** iters, int dim, expr* stmt) const; // +-----------------------------------------------------------------+ // | | // | Arrays 'n' such | // | | // +-----------------------------------------------------------------+ /** Make a new array. Implemented in arrays.cc. @param fn Filename of the array. @param ln Line number of the array. @param t Type of the array. @param name Name of the array. @param indexes List of iterators, which define the "shape" of the array. Each iterator must have been created by calling MakeIterator(). @param dim Length of the list of indexes. Can be considered the dimension of the array. @return 0, if some error occurred (will make noise). A new array, otherwise. */ symbol* makeArray(const char* fn, int ln, const type* t, char* n, symbol** indexes, int dim) const; /** Make an array assignment statement, not within a converge block. These handle statements of the form int a[i][j][k] := rhs; Implemented in arrays.cc. @param fn Filename of the statement. @param ln Line number of the statement. @param array Array to use for the assignment. Must have been created by a call to MakeArray(). @param rhs The right-hand side of the assignment. @return ERROR, if some error occurred (will make noise). A new statement, otherwise. */ expr* makeArrayAssign(const char* fn, int ln, symbol* array, expr* rhs) const; // +-----------------------------------------------------------------+ // | | // | Array and function "calls" | // | | // +-----------------------------------------------------------------+ /** Make an array dereferencing expression. These handle expressions of the form a[3][5+n][4-3*foobar(7, x)] Implemented in arrays.cc. @param fn Filename of the expression. @param ln Line number of the expression. @param array Array to use. Must have been created by a call to MakeArray(). @param indexes List of indices to be "passed" to the array. @param dim Number of indices in the list \a indexes. @return ERROR, if some error occurred (will make noise). A new expression, otherwise. */ expr* makeArrayCall(const char* fn, int ln, symbol* array, expr** indexes, int dim) const; /** Make an expression to call a function. Passed parameters must match exactly in type. @param fn Filename we are declared in. @param ln line number we are declared on. @param f The function to call. Can be user-defined, internal, or pretty much anything. @param p The parameters to pass, as an array of expressions. @param np Number of passed parameters. */ expr* makeFunctionCall(const char* fn, int ln, symbol *f, expr **p, int np) const; /** Find a (list of) function callable within a model. @param mt Type of model we are calling within. @param n Name of the function. @return A list of functions with name \a n that can be called inside a model of type \a mt. This will either be a list of "generic" functions, callable within any type of model, or a list of functions specific to models of type \a mt. 0 signifies an empty list. */ symbol* findFunction(const type* mt, const char* n); // +-----------------------------------------------------------------+ // | | // | Converge statements | // | | // +-----------------------------------------------------------------+ /** Make a variable within a converge block. Implemented in converge.cc. @param fn Filename of the variable. @param ln Line number of the variable. @param t Type of the variable. @param n Name of the variable. @return 0, if some error occurred (will make noise). A new variable, otherwise. */ symbol* makeCvgVar(const char* fn, int ln, const type* t, char* name) const; /** Make a converge statement. Implemented in converge.cc. @param fn Filename. @param ln Line number. @param stmt The statement to execute within the converge. (can be a statement block). @param top True iff this is the topmost converge statement. (If so we will "affix" variables after executing.) @return ERROR, if some error occurred. A new void-type expression, otherwise. */ expr* makeConverge(const char* fn, int ln, expr* stmt, bool top) const; /** Make a guess statement for inside a converge block. These handle statements of the form real foo guess rhs; Implemented in converge.cc. @param fn Filename of the statement. @param ln Line number of the statement. @param cvgvar Converge variable to use. Must have been created by a call to MakeCvgVar(). @param rhs The right-hand side of the guess. @return 0, if some error occurred (will make noise). A new statement, otherwise. */ expr* makeCvgGuess(const char* fn, int ln, symbol* cvgvar, expr* rhs) const; /** Make an assignment statement for inside a converge block. These handle statements of the form real foo := rhs; that appear within a converge block. Implemented in converge.cc. @param fn Filename of the statement. @param ln Line number of the statement. @param cvgvar Converge variable to use. Must have been created by a call to MakeCvgVar(). @param rhs The right-hand side of the assignment. @return 0, if some error occurred (will make noise). A new statement, otherwise. */ expr* makeCvgAssign(const char* fn, int ln, symbol* cvgvar, expr* rhs) const; /** Make an array guess statement for inside a converge block. These handle statements of the form real foo[i][j] guess rhs; Implemented in converge.cc. @param fn Filename of the statement. @param ln Line number of the statement. @param cvgvar Converge variable to use. Must have been created by a call to MakeCvgVar(). @param rhs The right-hand side of the guess. @return 0, if some error occurred (will make noise). A new statement, otherwise. */ expr* makeArrayCvgGuess(const char* fn, int ln, symbol* array, expr* guess) const; /** Make an array assignment statement, within a converge block. These handle statements of the form int a[i][j][k] := rhs; that appear within a converge block. Implemented in converge.cc. @param fn Filename of the statement. @param ln Line number of the statement. @param array Array to use for the assignment. Must have been created by a call to MakeArray(). @param rhs The right-hand side of the assignment. @return ERROR, if some error occurred (will make noise). A new statement, otherwise. */ expr* makeArrayCvgAssign(const char* fn, int ln, symbol* array, expr* rhs) const; // +-----------------------------------------------------------------+ // | | // | Changing types | // | | // +-----------------------------------------------------------------+ /// Register a general type conversion rule. virtual void registerConversion(general_conv *) = 0; /// Register a specific type conversion rule. virtual void registerConversion(specific_conv *) = 0; /** Returns the "promotion distance" from type t1 to t2. For example: - getPromoteDistance(INT, BOOL) = -1 - getPromoteDistance(INT, INT) = 0 - getPromoteDistance(INT, REAL) = 1 - getPromoteDistance(INT, PH_INT) = 2 - getPromoteDistance(INT, PROC_INT) = 4 - getPromoteDistance(INT, PROC_RAND_INT) = 6 - getPromoteDistance(INT, PROC_RAND_REAL) = 7 - getPromoteDistance(INT, SET_REAL) = 9 @param t1 Original type @param t2 Target type @return -1, if the promotion is impossible 0, if the types are equal n, a binary encoding of which level(s) needs changing: 1 for base type, 2 for rand / phase / determ, 4 for proc / non-proc, 8 for set / non-set. */ virtual int getPromoteDistance(const type* t1, const type* t2) const = 0; /// Returns true if type t1 can be promoted to type t2. inline bool isPromotable(const type* t1, const type* t2) const { return getPromoteDistance(t1, t2) >= 0; } /** Least common type that types a and b can be promoted to. Useful for, say, determining the type of rand int + proc real (which is proc rand real). @param a First type. @param b Second type. @return If such a type \a c exists, return the \a c that minimizes the (non-negative) promotion distance from a to c, and the non-negative promotion distance from b to c. Otherwise, return 0. */ const type* getLeastCommonType(const type* a, const type* b) const; /** Returns true if type t1 can be cast to type t2. This includes both promotions and explicit casts. @param t1 Original type @param t2 Target type @return true iff it is possible to change from type \a t1 to type \a t2. */ virtual bool isCastable(const type* t1, const type* t2) const = 0; /** Make a type conversion expression. @param file Filename of the expression. @param line Line number of the expression. @param newtype The desired type. @param e The original expression. @return 0, if e is 0. ERROR, if e is ERROR, or if the change of type is impossible. e, if e already has type \a newtype. a new expression, otherwise. */ virtual expr* makeTypecast(const char* file, int line, const type* newtype, expr* e) const = 0; /** Make a type conversion expression. If a component of e is not promotable as requested, we return ERROR. If all components of e are already of the specified type, we return it. @param file Filename of the expression. @param line Line number of the expression. @param proc Should components of fp be promoted to proc. @param rand Should components of fp be promoted to rand. @param fp An expression whose type we want to match. @param e The original expression. both \a e and \a fp must have the same number of components. @return 0, if e is 0. ERROR, if e is ERROR, or if the change of type is impossible. e, if e already has type \a newtype. a new expression, otherwise. */ expr* makeTypecast(const char* file, int line, bool proc, bool rand, const expr *fp, expr* e) const; /** Make a type conversion expression. Like MakeTypecast(), but rules out type casts (e.g., real to int). It is assumed that this is for parameter passing, so the new expression will have the same filename and linenumber as the original. @param e The original expression. @param newtype The desired type. @return 0, if e is 0. ERROR, if e is ERROR, or if no promotion is possible. e, if e already has type \a newtype. a new expression, otherwise. */ expr* promote(expr* e, const type* newtype) const; /** Make a type conversion expression. Like MakeTypecast(), but rules out type casts (e.g., real to int). It is assumed that this is for parameter passing, so the new expression will have the same filename and linenumber as the original. @param e The original expression. @param proc Should fp components be promoted to proc. @param rand Should fp components be promoted to rand. @param fp An expression (e.g., formal parameter) whose type we want to match. @return 0, if e is 0. ERROR, if e is ERROR, or if no promotion is possible. e, if e already has type \a newtype. a new expression, otherwise. */ expr* promote(expr* e, bool proc, bool rand, const expr* fp) const; // +-----------------------------------------------------------------+ // | | // | Registration of operator handlers | // | | // +-----------------------------------------------------------------+ /** Register a unary operation. @param op Unary operation to register. @return true, on success. false, if any error occurred. */ virtual bool registerOperation(unary_op* op) = 0; /** Register a binary operation. @param op Binary operation to register. @return true, on success. false, if any error occurred. */ virtual bool registerOperation(binary_op* op) = 0; /** Register a trinary operation. @param op Trinary operation to register. @return true, on success. false, if any error occurred. */ virtual bool registerOperation(trinary_op* op) = 0; /** Register an associative operation. @param op Associative operation to register. @return true, on success. false, if any error occurred. */ virtual bool registerOperation(assoc_op* op) = 0; // +-----------------------------------------------------------------+ // | | // | Building expressions with operators | // | | // +-----------------------------------------------------------------+ static const char* getOp(unary_opcode op); static const char* getOp(binary_opcode op); static const char* getFirst(trinary_opcode op); static const char* getSecond(trinary_opcode op); static const char* getOp(bool flip, assoc_opcode op); static const char* documentOp(unary_opcode op); static const char* documentOp(binary_opcode op); static const char* documentOp(trinary_opcode op); static const char* documentOp(bool flip, assoc_opcode op); /** Determine the type of a unary operation expression. @param op The operation to perform. @param opnd The operand type. @return 0, on any kind of error; the type of the operation, otherwise. */ virtual const type* getTypeOf(unary_opcode op, const type* x) const = 0; /** Determine the type of a binary operation expression. @param left The left operand type. @param op The operation to perform. @param right The right operand type. @return 0, on any kind of error; the type of the operation, otherwise. */ virtual const type* getTypeOf(const type* left, binary_opcode op, const type* right) const = 0; /** Determine the type of a trinary operation expression. @param op The operation to perform. @param left The left operand type. @param middle The middle operand type. @param right The right operand type. @return 0, on any kind of error; the type of the operation, otherwise. */ virtual const type* getTypeOf(trinary_opcode op, const type* left, const type* middle, const type* right) const = 0; /** Determine the type of an associative operation (sub)expression. @param left The left operand type. @param flip Do we "flip" the operation. @param op The operation to perform. @param right The right operand type. @return 0, on any kind of error; the type of the operation, otherwise. */ virtual const type* getTypeOf(const type* left, bool flip, assoc_opcode op, const type* right) const = 0; /** Make a unary operation expression. @param file Filename of the expression. @param line Line number of the expression. @param op The operation to perform. @param opnd The operand. @return NULL, if opnd is NULL. ERROR, if opnd is ERROR, or if there is a type mismatch. a new expression, otherwise. */ virtual expr* makeUnaryOp(const char* file, int line, unary_opcode op, expr* opnd) const = 0; /** Make a binary operation expression. @param fn Filename of the expression. @param ln Line number of the expression. @param left The left operand. @param op The operation to perform. @param rt The right operand. @return NULL, if either opnd is NULL. ERROR, if either opnd is ERROR, or if the operand cannot be applied (i.e., type mismatch). a new expression, otherwise. */ virtual expr* makeBinaryOp(const char* fn, int ln, expr* left, binary_opcode op, expr* rt) const = 0; /** Make a trinary operation expression. @param fn Filename of the expression. @param ln Line number of the expression. @param op The operation to perform. @param l The left operand. @param m The middle operand. @param r The right operand. @return ERROR, if any opnd is ERROR, or if the operand cannot be applied (i.e., type mismatch). a new expression, otherwise. */ virtual expr* makeTrinaryOp(const char* fn, int ln, trinary_opcode op, expr* l, expr* m, expr* r) const = 0; /** Make an associative operation expression. @param fn Filename of the expression. @param ln Line number of the expression. @param op The operation to perform. @param opnds Array of operands. @param f For each operand, should it be "flipped"? If missing (null), we assume that no operands should be flipped. @param nops Number of operands. @return NULL, if any opnd is NULL. ERROR, if any opnd is ERROR, or if the operand cannot be applied (i.e., type mismatch). a new expression, otherwise. */ virtual expr* makeAssocOp(const char* fn, int ln, assoc_opcode op, expr** opnds, bool* f, int nops) const = 0; // +-----------------------------------------------------------------+ // | | // | Building models | // | | // +-----------------------------------------------------------------+ /** Start construction of a model definition, for a given model type. @param fn Filename of the model definition. @param ln Line number of the model definition. @param t Type of formalism. @param name Name of the model. @param formals List of formal parameters. @param np Number of formal parameters. @return NULL, if some error occurred. A new model definition, otherwise. */ model_def* makeModel(const char* fn, int ln, const type* t, char* name, symbol** formals, int np) const; /** Make a symbol within a model definition. The symbol is simply a "placeholder" that will be replaced each time the model is instantiated. Implemented in mod_vars.cc. @param fn Filename of the symbol. @param ln Line number of the symbol. @param t Type of the symbol. @param name Name of the symbol. @return a new placeholder symbol. */ symbol* makeModelSymbol(const char* fn, int ln, const type* t, char* name) const; /** Make an array within a model definition. The array is simply a "placeholder" that will be replaced each time the model is instantiated. Implemented in mod_vars.cc. @param fn Filename of the array. @param ln Line number of the array. @param t Type of the array. @param name Name of the array. @param indexes List of iterators, which define the "shape" of the array. Each iterator must have been created by calling MakeIterator(). @param dim Length of the list of indexes. Can be considered the dimension of the array. @return 0, if some error occurred (will make noise). A new array, otherwise. */ symbol* makeModelArray(const char* fn, int ln, const type* t, char* n, symbol** indexes, int dim) const; /** Make a statement for constructing model variables. This handles declarations of the form place p, q, r, s; within a model. Implemented in mod_vars.cc. @param fn Filename of the declaration. @param ln Line number of the declaration. @param p Model definition block containing the declaration. @param t Type of the variables. @param bounds Bounds for the variables (a set of something), or 0. @param names Names of the variables (they already exist as placeholder symbols). @param N Number of names. @return NULL, if any name is NULL, ERROR, if any error occurs, a new statement (void expression), otherwise. */ expr* makeModelVarDecs(const char* fn, int ln, model_def* p, const type* t, expr* bounds, symbol** names, int N) const; /** Make a statement for constructing model array variables. This handles declarations of the form place p[i], q[i], r[i], s[i]; within a model. Implemented in mod_vars.cc. @param fn Filename of the declaration. @param ln Line number of the declaration. @param p Model definition block containing the declaration. @param t Type of the arrays. @param arrays Names of the arrays (they already exist as placeholder symbols). @param N Number of arrays. @return NULL, if any name is NULL, ERROR, if any error occurs, a new statement (void expression), otherwise. */ expr* makeModelArrayDecs(const char* fn, int ln, model_def* p, const type* t, symbol** arrays, int N) const; /** Make a statement to build a measure in a model. Implemented in mod_vars.cc. @param fn Filename of the statement. @param ln Line number of the statement. @param p Model definition block containing the statement. @param m The measure. @param rhs Right-hand side of the measure assignment. @return NULL, if p, m, or rhs is NULL. ERROR, if some error occurs (will make noise). A new statement, otherwise. */ expr* makeModelMeasureAssign(const char* fn, int ln, model_def* p, symbol* m, expr* rhs) const; /** Make a statement to build an array of measures in a model. Implemented in mod_vars.cc. @param fn Filename of the statement. @param ln Line number of the statement. @param p Model definition block containing the statement. @param am The array of measures. @param rhs Right-hand side of the measure assignment. @return NULL, if p, m, or rhs is NULL. ERROR, if some error occurs (will make noise). A new statement, otherwise. */ expr* makeModelMeasureArray(const char* fn, int ln, model_def* p, symbol* am, expr* rhs) const; /** Finish a model definition. Implemented in mod_def.cc. @param p Model "header", everything is ready except for the statements and symbols within the model. @param stmts Block of statements to execute when instantiating the model. @param st Array of externally-visible symbols (usually measures, or arrays of measures) of the model. @param ns Number of externally-visible symbols. */ void finishModelDef(model_def* p, expr* stmts, symbol** st, int ns) const; // +-----------------------------------------------------------------+ // | | // | Building model and measure calls | // | | // +-----------------------------------------------------------------+ /** Determine if a function is actually a model definition. (The compiler is unable to determine this by itself.) */ static model_def* isAModelDef(symbol* f); /** Make a measure call expression. For expressions of the form foo(3.4, 7).msr; I.e., to be used when we call the model definition directly. Implemented in mod_def.cc. @param fn Filename of the expression. @param ln Line number of the expression. @param p Model definition block containing the measure. @param pass Parameters to pass to the model definition. @param np Number of passed parameters. @param name Name of the measure. @return ERROR, if some error occurs (e.g., no measure with the given name), with error messages relayed as appropriate on the error channel. A new expression p(pass).name, otherwise. */ expr* makeMeasureCall(const char* fn, int ln, model_def* p, expr** pass, int np, const char* name) const; /** Make a measure array call expression. For expressions of the form foo(3.4, 7).msr[i, j, k]; I.e., to be used when we call the model definition directly. Implemented in mod_def.cc. @param fn Filename of the expression. @param ln Line number of the expression. @param p Model definition block containing the measure. @param pass Parameters to pass to the model definition. @param np Number of passed parameters. @param name Name of the measure array. @param i Passed array indexes. @param ni Number of passed indexes. @return ERROR, if some error occurs (e.g., no measure with the given name, wrong dimension), with error messages relayed as appropriate on the error channel. A new expression p(pass).name[i], otherwise. */ expr* makeMeasureCall(const char* fn, int ln, model_def* p, expr** pass, int np, const char* name, expr** i, int ni) const; /** Make a measure call expression. For expressions of the form m.msr; where m is a constant with type "model". Implemented in mod_inst.cc. @param fn Filename of the expression. @param ln Line number of the expression. @param mi A model instance. @param name Name of the measure. @return ERROR, if some error occurs (will make noise). A new measure call expression, otherwise. */ expr* makeMeasureCall(const char* fn, int ln, symbol* mi, const char* name) const; /** Make a measure array call expression. For expressions of the form m.msr[i, j, k]; where m is a constant with type "model". Implemented in mod_inst.cc. @param fn Filename of the expression. @param ln Line number of the expression. @param mi A model instance. @param name Name of the measure. @param i Passed array indexes. @param ni Number of passed indexes. @return ERROR, if some error occurs (will make noise). A new measure call expression, otherwise. */ expr* makeMeasureCall(const char* fn, int ln, symbol* mi, const char* name, expr** i, int ni) const; /** Make a measure array call expression. For expressions of the form m[i, j, k].msr; where m is a constant with type "model". Implemented in mod_inst.cc. @param fn Filename of the expression. @param ln Line number of the expression. @param mi A model instance array. @param i Passed array indexes. @param ni Number of passed indexes. @param name Name of the measure. @return ERROR, if some error occurs (will make noise). A new measure call expression, otherwise. */ expr* makeMeasureCall(const char* fn, int ln, symbol* mi, expr** i, int ni, const char* name) const; /** Make a measure array call expression. For expressions of the form m[i].msr[j]; where m is a constant with type "model". Implemented in mod_inst.cc. @param fn Filename of the expression. @param ln Line number of the expression. @param mi A model instance array. @param i Passed array indexes, for mi. @param ni Number of passed indexes for mi. @param name Name of the measure. @param j Passed array indexes, for name. @param nj Number of passed indexes for name. @return ERROR, if some error occurs (will make noise). A new measure call expression, otherwise. */ expr* makeMeasureCall(const char* fn, int ln, symbol* mi, expr** i, int ni, const char* name, expr** j, int nj) const; // +-----------------------------------------------------------------+ // | | // | Solution engines | // | | // +-----------------------------------------------------------------+ /** Register a new type of solution engine. @param et Engine type to register (see engine.h) @return true on success */ virtual bool registerEngineType(engtype* et) = 0; /** Find the engine type with the given name, if there is one. @param name Name of engine type to look for. @return The desired engine type, or 0 if none found. */ virtual engtype* findEngineType(const char* name) const = 0; /// Get the current number of registered engine types. virtual int getNumEngineTypes() const = 0; /// Get the ith registered engine type. virtual const engtype* getEngineTypeNumber(int i) const = 0; // +-----------------------------------------------------------------+ // | | // | Supporting libraries | // | | // +-----------------------------------------------------------------+ /** Register an external supporting library. @param lib The library to register. @return 0, on success. 1, if \a lib is 0. 2, if the manager is already finalized. 3, if there is no version string for this library. 4, if this library is a duplicate of another one registered. */ virtual char registerLibrary(const library* lib) = 0; /// Print version info for all registered supporting libraries. virtual void printLibraryVersions(OutputStream &s) const = 0; /// Print copyright info for all registered supporting libraries. virtual void printLibraryCopyrights(doc_formatter* df) const = 0; protected: virtual ~exprman(); // don't want user to delete one... friend void destroyExpressionManager(exprman* em); // ... except this way }; // ****************************************************************** // * * // * Front end * // * * // ****************************************************************** /** Initialize the expression manager and return it. @param io Streams to use for errors and such. @param om Collection to add any expression-related options into. If 0, the options will still be created, but it will be impossible to change them from their default values. @return The existing expression manager (and ignoring the parameters) if one already exists. Otherwise, creates and returns an expression manager. */ exprman* Initialize_Expressions(io_environ* io, option_manager* om); /// Return the expression manager, or 0 if none exists. exprman* getExpressionManager(); /// Destroy the expression manager. void destroyExpressionManager(exprman* em); #endif
35.83566
85
0.553765
[ "shape", "model" ]
57524311b64e54b53c9135fbdc743fe68e75de0b
10,095
h
C
include/xspf/XspfProps.h
ezdev128/libxspf
ba71431e24293510c44d6581e2c05b901a372880
[ "BSD-3-Clause" ]
null
null
null
include/xspf/XspfProps.h
ezdev128/libxspf
ba71431e24293510c44d6581e2c05b901a372880
[ "BSD-3-Clause" ]
null
null
null
include/xspf/XspfProps.h
ezdev128/libxspf
ba71431e24293510c44d6581e2c05b901a372880
[ "BSD-3-Clause" ]
null
null
null
/* * libxspf - XSPF playlist handling library * * Copyright (C) 2006-2008, Sebastian Pipping / Xiph.Org Foundation * 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 Xiph.Org Foundation 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. * * Sebastian Pipping, sping@xiph.org */ /** * @file XspfProps.h * Interface of XspfProps. */ #ifndef XSPF_PROPS_H #define XSPF_PROPS_H #include "XspfData.h" namespace Xspf { class XspfPropsPrivate; class XspfDateTime; /** * Represents the properties of playlist * without extensions. This includes all * information except the track list. */ class XspfProps : public XspfData { friend class XspfPropsPrivate; // Give access to static helpers private: /// @cond DOXYGEN_NON_API XspfPropsPrivate * const d; ///< D pointer /// @endcond public: /** * Creates a new, blank playlist property package. */ XspfProps(); /** * Copy constructor. * * @param source Source to copy from */ XspfProps(XspfProps const & source); /** * Assignment operator. * * @param source Source to copy from */ XspfProps & operator=(XspfProps const & source); /** * Destroys this XspfProps object and deletes all * memory associated with it that has not been stolen before. */ ~XspfProps(); /** * Overwrites the identifier property. If <c>copy</c> is true * the string will be copied, otherwise just assigned. * In both cases the associated memory will be deleted on * object destruction. * * @param identifier Identifier string to set * @param copy Copy flag */ void giveIdentifier(XML_Char const * identifier, bool copy); /** * Overwrites the license property. If <c>copy</c> is true * the string will be copied, otherwise just assigned. * In both cases the associated memory will be deleted on * object destruction. * * @param license License string to set * @param copy Copy flag */ void giveLicense(XML_Char const * license, bool copy); /** * Overwrites the location property. If <c>copy</c> is true * the string will be copied, otherwise just assigned. * In both cases the associated memory will be deleted on * object destruction. * * @param location Location string to set * @param copy Copy flag */ void giveLocation(XML_Char const * location, bool copy); /** * Appends an identifier to the attribution list. * * @param identifier Identifier to append * @param copy Copy flag */ void giveAppendAttributionIdentifier(XML_Char const * identifier, bool copy); /** * Appends an location to the attribution list. * * @param location Location to append * @param copy Copy flag */ void giveAppendAttributionLocation(XML_Char const * location, bool copy); /** * Overwrites the date property. If <c>copy</c> is true * the date object will be copied, otherwise just assigned. * In both cases the associated memory will be deleted on * object destruction. * * @param date Date object to set * @param copy Copy flag */ void giveDate(XspfDateTime const * date, bool copy); /** * Overwrites the identifier property. The string is * only assigned not copied. The ownership is * not transferred. * * @param identifier Identifier string to set */ void lendIdentifier(XML_Char const * identifier); /** * Overwrites the license property. The string is * only assigned not copied. The ownership is * not transferred. * * @param license License string to set */ void lendLicense(XML_Char const * license); /** * Overwrites the location property. The string is * only assigned not copied. The ownership is * not transferred. * * @param location Location string to set */ void lendLocation(XML_Char const * location); /** * Appends an identifier to the attribution list. * The associated memory is neither copied nor * deleted on onject destruction. * * @param identifier Identifier to append */ void lendAppendAttributionIdentifier(XML_Char const * identifier); /** * Appends an location to the attribution list. * The associated memory is neither copied nor * deleted on onject destruction. * * @param location Location to append */ void lendAppendAttributionLocation(XML_Char const * location); /** * Overwrites the date property. The date object is * only assigned not copied. The ownership is * not transferred. * * @param date Date object to set */ void lendDate(XspfDateTime const * date); /** * Overwrites the XSPF version property. * * @param version XSPF version (0 or 1) */ void setVersion(int version); /** * Steals the license property. * * @return License URI, can be NULL */ XML_Char * stealLicense(); /** * Steals the location property. * * @return Location URI, can be NULL */ XML_Char * stealLocation(); /** * Steals the identifier property. * * @return Identifier URI, can be NULL */ XML_Char * stealIdentifier(); /** * Steals the first attribution entry from the list. * If the list is empty <c>NULL</c> is returned. * * NOTE: Do not forget to delete the pair! * * @return First attribution entry, can be NULL */ std::pair<bool, XML_Char *> * stealFirstAttribution(); /** * Steals the date object property. * * @return Date object, can be NULL */ XspfDateTime * stealDate(); /** * Returns the license property. * * @return License, can be NULL */ XML_Char const * getLicense() const; /** * Returns the location property. * * @return Location, can be NULL */ XML_Char const * getLocation() const; /** * Returns the identifier property. * * @return Identifier, can be NULL */ XML_Char const * getIdentifier() const; /** * Gets the specific attribution entry from the list. * If the list is empty <c>NULL</c> is returned. * * NOTE: The returned pair has to be deleted manually! * * @return Specified attribution entry, can be NULL */ std::pair<bool, XML_Char const *> * getAttribution(int index) const; /** * Returns the number of attributions. * * @return Number of attributions */ int getAttributionCount() const; /** * Returns the date object property. * * @return Date object, can be NULL */ XspfDateTime const * getDate() const; /** * Returns the XSPF version property. * * @return XSPF version (0 or 1) */ int getVersion() const; private: /** * Appends a location or identifier to a container. * * @param container Container to work with * @param value Value * @param ownership Ownership flag * @param isLocation Location/identifier switch */ static void appendHelper(std::deque<std::pair<bool, std::pair<XML_Char const *, bool> *> *> * & container, XML_Char const * value, bool ownership, bool isLocation); /** * Returns a specific entry from a container * or <c>NULL</c> if the entry does not exist. * * NOTE: The returned pair has to be deleted manually! * * @param container Container to work with * @param index Index of the entry to return * @return Entry content, can be NULL */ static std::pair<bool, XML_Char const *> * getHelper( std::deque<std::pair<bool, std::pair<XML_Char const *, bool> *> *> * & container, int index); /** * Steals a XspfDateTime. If its memory is not owned * a clone is returned. In any case you own the memory * return and have to delete it. * * @param dateTime XspfDateTime to steal * @param own Owner flag * @return Stolen XspfDateTime value, can be NULL */ static XspfDateTime * stealHelper(XspfDateTime const * & dateTime, bool own); /** * Steals the first entry from a container. * * @param container Container to steal from * @return First entry, can be NULL */ static std::pair<bool, XML_Char *> * stealFirstHelper( std::deque<std::pair<bool, std::pair<XML_Char const *, bool> *> *> * & container); /** * Replaces the date object in <c>dest</c> by a duplicate of the date object * in <c>src</c> (using new() not malloc()). The old object is deleted. * If <c>destOwnership</c> is false the old string is not deleted. * If <c>sourceCopy</c> is false only <c>source</c>'s pointer is copied, * not the whole object. * * @param dest Destination date object * @param destOwnership Destination ownership flag * @param source Source date object * @param sourceCopy Source copy flag */ static void deleteNewAndCopy(XspfDateTime const * & dest, bool & destOwnership, XspfDateTime const * source, bool sourceCopy); }; } #endif // XSPF_PROPS_H
26.777188
107
0.68737
[ "object" ]
5765ba2c8262f051bd46daa4f77e6e46e79079e1
2,082
h
C
src/common/system/udp_socket.h
hangqiu/pixie
1dd4af47d40ff856c4d52a1d6de81f78a76ff31e
[ "Apache-2.0" ]
1,821
2020-04-08T00:45:27.000Z
2021-09-01T14:56:25.000Z
src/common/system/udp_socket.h
hangqiu/pixie
1dd4af47d40ff856c4d52a1d6de81f78a76ff31e
[ "Apache-2.0" ]
142
2020-04-09T06:23:46.000Z
2021-08-24T06:02:12.000Z
src/common/system/udp_socket.h
hangqiu/pixie
1dd4af47d40ff856c4d52a1d6de81f78a76ff31e
[ "Apache-2.0" ]
105
2021-09-08T10:26:50.000Z
2022-03-29T09:13:36.000Z
/* * Copyright 2018- The Pixie Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ #pragma once #include <netinet/in.h> #include <memory> #include <string> #include <vector> namespace px { namespace system { /** * A simple wrapper of the syscalls for IPv4 UDP socket. * * Note: Not meant for use in production code. This class uses CHECKs instead of Status/error. */ class UDPSocket { public: UDPSocket(); ~UDPSocket(); void BindAndListen(int port = 0); void Close(); int sockfd() const { return sockfd_; } const struct sockaddr_in sockaddr() const { return addr_; } const struct in_addr& addr() const { return addr_.sin_addr; } in_port_t port() const { return addr_.sin_port; } /** * Sends data to the specified destination socket. */ ssize_t SendTo(std::string_view data, const struct sockaddr_in& dst, int flags = 0) const; ssize_t SendMsg(std::string_view data, const struct sockaddr_in& dst, int flags = 0) const; ssize_t SendMMsg(std::string_view data, const struct sockaddr_in& dst, int flags = 0) const; /** * Receives data from the socket, returns the remote address from which the data is received. */ struct sockaddr_in RecvFrom(std::string* data, int flags = 0) const; struct sockaddr_in RecvMsg(std::string* data, int flags = 0) const; struct sockaddr_in RecvMMsg(std::string* data, int flags = 0) const; private: int sockfd_ = 0; struct sockaddr_in addr_; static constexpr int kBufSize = 128; }; } // namespace system } // namespace px
29.323944
95
0.713737
[ "vector" ]
57668052c66c893606aad1d977b1f683c2c77c52
1,317
h
C
includes/CrossNetSystem/System/Net/Various.h
KonajuGames/CrossNetSystem
23c516d79b16224745b05ba1044fd9786f3a5a14
[ "MS-PL" ]
2
2019-10-23T09:14:29.000Z
2021-02-02T15:01:35.000Z
includes/CrossNetSystem/System/Net/Various.h
KonajuGames/CrossNetSystem
23c516d79b16224745b05ba1044fd9786f3a5a14
[ "MS-PL" ]
null
null
null
includes/CrossNetSystem/System/Net/Various.h
KonajuGames/CrossNetSystem
23c516d79b16224745b05ba1044fd9786f3a5a14
[ "MS-PL" ]
null
null
null
/* * CrossNetSystem * .NET API Copyrighted by Microsoft */ #ifndef __SYSTEM_NET_VARIOUS_H__ #define __SYSTEM_NET_VARIOUS_H__ #ifndef CN_NO_SYSTEM_NET_VARIOUS #include "CrossNetRuntime/System/Object.h" namespace System { namespace Net { /* class EndPoint { public: int get_Port(); }; namespace Sockets { class Socket : public System::Object { public: void Close(); }; class TcpListener : public System::Object { public: void __ctor__(int port); Socket * get_Server(); System::Net::EndPoint * get_LocalEndpoint(); void Start(); }; class NetworkStream : public System::Object { public: static NetworkStream * __Create__(Socket *); static NetworkStream * __Create__(Socket *, System::Boolean); static NetworkStream * __Create__(Socket *, System::IO::FileAccess); static NetworkStream * __Create__(Socket *, System::IO::FileAccess, System::Boolean); }; } class IPEndPoint : public EndPoint { }; */ } } #endif #endif
21.241935
101
0.520121
[ "object" ]
576d1da3d7c94e1b99f8046614bdc38ea9562ed1
1,895
h
C
Includes/Core/Emitter/ParticleEmitterSet3.h
utilForever/CubbyFlow-v1
d85c136d8eaa91ecce456c3356c7e578dda5d5bd
[ "MIT" ]
3
2020-04-15T13:41:16.000Z
2020-12-29T11:23:59.000Z
Includes/Core/Emitter/ParticleEmitterSet3.h
utilForever/CubbyFlow-v1
d85c136d8eaa91ecce456c3356c7e578dda5d5bd
[ "MIT" ]
null
null
null
Includes/Core/Emitter/ParticleEmitterSet3.h
utilForever/CubbyFlow-v1
d85c136d8eaa91ecce456c3356c7e578dda5d5bd
[ "MIT" ]
null
null
null
/************************************************************************* > File Name: ParticleEmitterSet3.h > Project Name: CubbyFlow > Author: Chan-Ho Chris Ohk > Purpose: 3-D particle-based emitter set. > Created Time: 2017/05/10 > Copyright (c) 2018, Chan-Ho Chris Ohk *************************************************************************/ #ifndef CUBBYFLOW_PARTICLE_EMITTER_SET3_H #define CUBBYFLOW_PARTICLE_EMITTER_SET3_H #include <Core/Emitter/ParticleEmitter3.h> namespace CubbyFlow { //! //! \brief 3-D particle-based emitter set. //! class ParticleEmitterSet3 final : public ParticleEmitter3 { public: class Builder; //! Constructs an emitter. ParticleEmitterSet3(); //! Constructs an emitter with sub-emitters. explicit ParticleEmitterSet3(const std::vector<ParticleEmitter3Ptr>& emitters); //! Destructor. virtual ~ParticleEmitterSet3(); //! Adds sub-emitter. void AddEmitter(const ParticleEmitter3Ptr& emitter); //! Returns builder fox ParticleEmitterSet3. static Builder GetBuilder(); private: std::vector<ParticleEmitter3Ptr> m_emitters; void OnSetTarget(const ParticleSystemData3Ptr& particles) override; void OnUpdate(double currentTimeInSeconds, double timeIntervalInSecond) override; }; //! Shared pointer type for the ParticleEmitterSet3. using ParticleEmitterSet3Ptr = std::shared_ptr<ParticleEmitterSet3>; //! //! \brief Front-end to create ParticleEmitterSet3 objects step by step. //! class ParticleEmitterSet3::Builder final { public: //! Returns builder with list of sub-emitters. Builder& WithEmitters(const std::vector<ParticleEmitter3Ptr>& emitters); //! Builds ParticleEmitterSet3. ParticleEmitterSet3 Build() const; //! Builds shared pointer of ParticleEmitterSet3 instance. ParticleEmitterSet3Ptr MakeShared() const; private: std::vector<ParticleEmitter3Ptr> m_emitters; }; } #endif
27.071429
83
0.702375
[ "vector" ]
576fab266d0672dcd18977968430171ab76ebe90
3,929
h
C
src/ring_buf.h
dimhoff/rf_pkt_drv
b3c8e2ebd9340e9a527dc8682671e6ebf146a93d
[ "BSD-3-Clause" ]
1
2019-09-29T21:16:50.000Z
2019-09-29T21:16:50.000Z
src/ring_buf.h
dimhoff/rf_pkt_drv
b3c8e2ebd9340e9a527dc8682671e6ebf146a93d
[ "BSD-3-Clause" ]
null
null
null
src/ring_buf.h
dimhoff/rf_pkt_drv
b3c8e2ebd9340e9a527dc8682671e6ebf146a93d
[ "BSD-3-Clause" ]
null
null
null
/** * ring_buf.h - Byte based ring buffer * * Copyright (c) 2018, David Imhoff <dimhoff.devel@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author 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 AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __RING_BUF_H__ #define __RING_BUF_H__ #include <stdlib.h> #include <stdint.h> #include <stdbool.h> typedef struct { uint8_t *buf; size_t size; size_t woff; size_t roff; } ring_buf_t; /** * Initialize ring buffer object * * Initialized the ring buffer, to be able to store size-1 bytes. * * @param obj Object to initialize * @param size Size of buffer */ void ring_buf_init(ring_buf_t *obj, size_t size); /** * Destroy buffer object * * @param obj Ring buffer object */ void ring_buf_destroy(ring_buf_t *obj); /** * Copy data into buffer * * Copy data into ring buffer. When 'len' is bigger then the space available in * the buffer then old data is silently overwriten. * * @param obj Ring buffer object * @param data Data to copy into buffer * @param len Length of data */ void ring_buf_add(ring_buf_t *obj, const uint8_t *data, size_t len); /** * Move bytes out of buffer * * Copy bytes from ring buffer into provided buffer. And move the read pointer * forward. * * @param obj Ring buffer object * @param data Target buffer to copy bytes into * @param len Amount of bytes to copy */ void ring_buf_get(ring_buf_t *obj, uint8_t *data, size_t len); /** * Consume bytes from buffer * * Consume bytes by moving the read pointer 'cnt' bytes forward. * * @param obj Ring buffer object * @param cnt Amount of bytes to consume */ void ring_buf_consume(ring_buf_t *obj, size_t cnt); /** * Clear all bytes from buffer * * Clears all bytes form the buffer and resets the read and write pointers. * * @param obj Ring buffer object */ void ring_buf_clear(ring_buf_t *obj); /** * Return begin of data * * Return raw pointer to the first byte of data in the buffer. Use * ring_buf_bytes_readable() to determine how many consecquitive bytes of data * can be read starting at the begin. * * @param obj Ring buffer object * * @returns Pointer to begin of data */ uint8_t *ring_buf_begin(ring_buf_t *obj); size_t ring_buf_size(ring_buf_t *obj); size_t ring_buf_bytes_free(const ring_buf_t *obj); size_t ring_buf_bytes_used(const ring_buf_t *obj); size_t ring_buf_bytes_readable(const ring_buf_t *obj); size_t ring_buf_bytes_writable(const ring_buf_t *obj); bool ring_buf_empty(const ring_buf_t *obj); bool ring_buf_full(const ring_buf_t *obj); #endif // __RING_BUF_H__
31.432
79
0.739119
[ "object" ]
57727e9f9f8e0521543341f4d08d6142a9ca231b
417
c
C
src/gdb/gdb-8.3/gdb/testsuite/gdb.base/huge.c
aps337/unum-sdk
2de3ae625e474c5064f6a88b720ec2ffdcdefad9
[ "Apache-2.0" ]
31
2018-08-01T21:25:24.000Z
2022-02-14T07:52:34.000Z
gdb/testsuite/gdb.base/huge.c
greyblue9/binutils-gdb
05377632b124fe7600eea7f4ee0e9a35d1b0cbdc
[ "BSD-3-Clause" ]
40
2018-12-03T19:48:52.000Z
2021-03-10T06:34:26.000Z
gdb/testsuite/gdb.base/huge.c
greyblue9/binutils-gdb
05377632b124fe7600eea7f4ee0e9a35d1b0cbdc
[ "BSD-3-Clause" ]
20
2018-11-16T21:19:22.000Z
2021-10-18T23:08:24.000Z
/* * Test GDB's ability to read a very large data object from target memory. */ #include <string.h> /* A value that will produce a target data object large enough to crash GDB. 0x200000 is big enough on GNU/Linux, other systems may need a larger number. */ #ifndef CRASH_GDB #define CRASH_GDB 0x200000 #endif static int a[CRASH_GDB], b[CRASH_GDB]; int main() { memcpy (a, b, sizeof (a)); return 0; }
19.857143
74
0.70024
[ "object" ]
577b0a27cd38c2997aefc755c21c36ef5472f120
712
h
C
src/Pipeline.h
ryuichiueda/GlueLang
7ad3e5b1d631d8482bb49c397abc6b2b3f38e249
[ "MIT" ]
40
2015-01-13T15:05:47.000Z
2021-11-17T11:05:55.000Z
src/Pipeline.h
ryuichiueda/GlueLang
7ad3e5b1d631d8482bb49c397abc6b2b3f38e249
[ "MIT" ]
13
2015-01-02T13:19:50.000Z
2021-04-20T12:23:00.000Z
src/Pipeline.h
ryuichiueda/GlueLang
7ad3e5b1d631d8482bb49c397abc6b2b3f38e249
[ "MIT" ]
3
2015-02-04T23:11:46.000Z
2019-04-28T06:38:58.000Z
// Copyright 2014 Ryuichi Ueda // Released under the MIT License. #ifndef __PIPELINE_H_ #define __PIPELINE_H_ #include "Element.h" #include <iostream> #include <vector> using namespace std; class Element; class Feeder; class Environment; class Arg; class Executable; class DefFile; class DefStr; class Where; class Pipeline : public Element { public: Pipeline(Feeder *f, Environment *env,vector<int> *scopes);; virtual ~Pipeline(); virtual void print(int indent_level = 0); virtual int exec(DefFile *f, DefStr *s); virtual bool parse(void); int execWait(void); bool m_has_and; bool m_has_then; bool m_has_or; bool m_is_then; protected: void waitCommands(int pid); vector<int> m_pids; }; #endif
17.8
60
0.748596
[ "vector" ]
577cea896e47db39b15a5a4a3ee5e05ef2bfaa34
867
c
C
cmds/feats/b/_bladesong.c
guille-valencia/shadowgate
a5c63b535e50020b58435d6fbb5b4f60d8f25639
[ "MIT" ]
1
2021-06-10T00:35:51.000Z
2021-06-10T00:35:51.000Z
cmds/feats/b/_bladesong.c
guille-valencia/shadowgate
a5c63b535e50020b58435d6fbb5b4f60d8f25639
[ "MIT" ]
null
null
null
cmds/feats/b/_bladesong.c
guille-valencia/shadowgate
a5c63b535e50020b58435d6fbb5b4f60d8f25639
[ "MIT" ]
null
null
null
#include <std.h> #include <daemons.h> #include <dirs.h> inherit FEAT; int MAX; void create() { ::create(); feat_type("permanent"); feat_category("Duelist"); feat_name("bladesong"); feat_desc("With this feat one learns how to use just one hand to channel their spells. The caster can use their spells while wielding a weapon in their second hand. This feat requiers you not to wield a second weapon or shield to work."); permanent(1); } int allow_shifted() { return 0; } int prerequisites(object ob) { object *weapons; if(!objectp(ob)) { return 0; } return ::prerequisites(ob); if(ob->is_wearing_type("shield")) { dest_effect(); return 0; } } void execute_feat() { ::execute_feat(); dest_effect(); return; } void dest_effect() { ::dest_effect(); remove_feat(TO); return; }
18.847826
242
0.642445
[ "object" ]
5798da3dd2c1ab26585f9a4751619f9f4ec11d86
1,916
h
C
plugins/goose/src/pub/GooseMessageVisitor.h
openenergysolutions/openfmb.adapters
3c95b1c460a8967190bdd9ae16677a4e2a5d9861
[ "Apache-2.0" ]
1
2021-08-20T12:14:11.000Z
2021-08-20T12:14:11.000Z
plugins/goose/src/pub/GooseMessageVisitor.h
openenergysolutions/openfmb.adapters
3c95b1c460a8967190bdd9ae16677a4e2a5d9861
[ "Apache-2.0" ]
3
2021-06-16T19:25:23.000Z
2021-09-02T14:39:10.000Z
plugins/goose/src/pub/GooseMessageVisitor.h
openenergysolutions/openfmb.adapters
3c95b1c460a8967190bdd9ae16677a4e2a5d9861
[ "Apache-2.0" ]
null
null
null
// SPDX-FileCopyrightText: 2021 Open Energy Solutions Inc // // SPDX-License-Identifier: Apache-2.0 #ifndef OPENFMB_ADAPTER_GOOSE_PUB_GOOSEMESSAGEVISITOR_H #define OPENFMB_ADAPTER_GOOSE_PUB_GOOSEMESSAGEVISITOR_H #include "goose-cpp/messages/IDatasetVisitor.h" #include "pub/Mappings.h" #include <functional> namespace adapter { namespace goose { class GooseMessageVisitor final : public goose_cpp::IDatasetVisitor { public: GooseMessageVisitor(const Mappings& mappings); ~GooseMessageVisitor() = default; size_t get_num_elements_visited() const; void handle_array(const goose_cpp::Dataset& item) final; void handle_structure(const goose_cpp::Dataset& item) final; void handle_boolean(bool item) final; void handle_bit_string(const goose_cpp::BitString& item) final; void handle_integer(int64_t item) final; void handle_unsigned_integer(uint64_t item) final; void handle_floatingpoint(double item) final; void handle_octet_string(const std::vector<uint8_t>& item) final; void handle_visible_string(const std::string& item) final; void handle_generalizedtime(std::chrono::system_clock::time_point item) final; void handle_binarytime(std::chrono::system_clock::time_point item) final; void handle_bcd(uint64_t item) final; void handle_boolean_array(const goose_cpp::BitString& item) final; void handle_mms_string(const std::string& item) final; void handle_utctime(std::chrono::system_clock::time_point item) final; private: template <typename T> void handle(const T& item, std::function<bool(size_t, meas_fn_t<T>&)> getter); void handle_not_supported(); const Mappings& m_mappings; size_t m_current_idx; }; } // namespace goose } // namespace adapter #endif //OPENFMB_ADAPTER_GOOSE_PUB_GOOSEMESSAGEVISITOR_H
37.568627
86
0.728601
[ "vector" ]
708a57dbd6859c864f8c77341eefe4ea75d3d8ac
3,519
h
C
libs/sge_core/src/sge_core/application/application.h
Alekssasho/sge_source
2db4ae08f7b3434d32dd9767fe1136234cb70b83
[ "MIT" ]
null
null
null
libs/sge_core/src/sge_core/application/application.h
Alekssasho/sge_source
2db4ae08f7b3434d32dd9767fe1136234cb70b83
[ "MIT" ]
null
null
null
libs/sge_core/src/sge_core/application/application.h
Alekssasho/sge_source
2db4ae08f7b3434d32dd9767fe1136234cb70b83
[ "MIT" ]
null
null
null
#pragma once #include "input.h" #include "sge_core/sgecore_api.h" #include "sge_utils/sge_utils.h" #include <map> #include <string> #include <vector> namespace sge { //----------------------------------------------- // Events and Event data. //----------------------------------------------- /// An enum window messages. enum WindowEvent : int { WE_Create, WE_Destroying, WE_Resize, WE_FileDrop, }; /// @brief The message data of the WE_Resize event. struct WE_Resize_Data { WE_Resize_Data() = default; WE_Resize_Data(int width, int height) : width(width) , height(height) {} int width; int height; }; /// @brief The message data of the WE_FileDrop event. struct WE_FileDrop_Data { std::string filename; }; struct WindowBase; struct WindowImplData; /// @brief Application handler manages all opened windows. struct SGE_CORE_API ApplicationHandler { private: ApplicationHandler() = default; public: ~ApplicationHandler() = default; static ApplicationHandler* get() { static ApplicationHandler inst; return &inst; } // Polls and dispatches recieved events to the respective windows. void PollEvents(); template <typename T> T* NewWindow(const char* windowName, int width, int height, bool isMaximized, bool noResize = false) { T* wnd = new T; NewWindowInternal(wnd, windowName, width, height, isMaximized, noResize); return wnd; } void DeregisterWindowInternal(WindowBase* wnd); bool HasAliveWindows() const { return m_wnds.size() != 0; } const std::vector<WindowBase*>& getAllWindows() { return m_wnds; } bool shouldStopRunning() const { return m_isAppQuitRequested || HasAliveWindows() == false; } private: WindowBase* findWindowBySDLId(const uint32 id); void removeWindow(WindowBase* const wndToRemove); void NewWindowInternal(WindowBase* window, const char* windowName, int width, int height, bool isMaximized, bool noResize); private: bool m_isAppQuitRequested = false; std::vector<WindowBase*> m_wnds; std::map<int, int> sdlJoystickInstanceIdIdToIndex; // To be honest having a global input state makes a lot of sense, however, // I'm not sure if this is the corrent approch as there is going to be a main window // sooo. I'm not going to implement that for now. InputState m_inputState; }; /// @brief An instance of a native window. struct SGE_CORE_API WindowBase { WindowBase(); virtual ~WindowBase(); virtual void HandleEvent(const WindowEvent UNUSED(event), const void* const UNUSED(eventData)){}; WindowBase(WindowBase&) = delete; WindowBase& operator=(WindowBase&) = delete; void* GetNativeHandle() const; bool IsActive() const; const InputState& GetInputState() { return m_inputState; } void resizeWindow(int width, int height); int GetClientWidth() const; int GetClientHeight() const; bool isMaximized() const; vec2f getClientSizef() const { return vec2f((float)GetClientWidth(), (float)GetClientHeight()); } void setWindowTitle(const char* title); public: InputState m_inputState; WindowImplData* m_implData; }; /// @brief Enables/Disables the mouse being captured. /// @param isRelative if true the mouse /// will be invisible and will not go ouside the current window. Useful for /// camera controls like FPS. /// If you are using the SGEEditor with GameWorld, do not call this directly, /// instead use GameWorld::setNeedsLockedCursor void setMouseCaptureAndCenter(bool isRelative); /// @brief Retrieves if the mouse if currently captured or not. bool getMouseCaptureAndCenter(); } // namespace sge
28.152
124
0.724638
[ "vector" ]
70970a853386fb3ed467a3bdf3ba51a443e992fa
1,552
h
C
RecoVertex/VertexTools/interface/DeterministicAnnealing.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
RecoVertex/VertexTools/interface/DeterministicAnnealing.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
RecoVertex/VertexTools/interface/DeterministicAnnealing.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#ifndef DeterministicAnnealing_H #define DeterministicAnnealing_H #include "RecoVertex/VertexTools/interface/AnnealingSchedule.h" #include <vector> class DeterministicAnnealing : public AnnealingSchedule { public: /** * \class DeterministicAnnealing. * A very simple class that returns the association probabilty of a (any) * chi2 value, given a cutoff. Default schedule is 256 64 16 4 2 1 * Note that cutoff is given "sigma-like", i.e. as a sqrt ( chi2 )!! */ DeterministicAnnealing(float cutoff = 3.0); DeterministicAnnealing(const std::vector<float>& sched, float cutoff = 3.0); void anneal() override; //< One annealing step. theT *= theRatio. void resetAnnealing() override; //< theT = theT0. /** * phi ( chi2 ) = e^( -.5*chi2 / T ) */ double phi(double chi2) const override; /** * Returns phi(chi2) / ( phi(cutoff^2) + phi(chi2) ), */ double weight(double chi2) const override; /** * is it annealed yet? */ bool isAnnealed() const override; void debug() const override; /** * Returns phi(chi2) / ( phi(cutoff^2) + sum_i { phi(chi2s[i]) } ) */ // double weight ( double chi2, const vector < double > & chi2s ) const; double cutoff() const override; double currentTemp() const override; double initialTemp() const override; DeterministicAnnealing* clone() const override { return new DeterministicAnnealing(*this); }; private: std::vector<float> theTemperatures; unsigned int theIndex; double theChi2cut; bool theIsAnnealed; }; #endif
26.758621
95
0.676546
[ "vector" ]
709ee7f1f9f9918674d71bc67aa066f6c4a0b2e3
14,215
h
C
src/utils/CLHEP/Vector/Vector/Rotation.h
lukaszgaza/winhacplusplus
6f3c71a507ced4e3e8fff05d239478c823cdbbc6
[ "MIT" ]
null
null
null
src/utils/CLHEP/Vector/Vector/Rotation.h
lukaszgaza/winhacplusplus
6f3c71a507ced4e3e8fff05d239478c823cdbbc6
[ "MIT" ]
null
null
null
src/utils/CLHEP/Vector/Vector/Rotation.h
lukaszgaza/winhacplusplus
6f3c71a507ced4e3e8fff05d239478c823cdbbc6
[ "MIT" ]
null
null
null
// -*- C++ -*- // CLASSDOC OFF // $Id: Rotation.h,v 1.3 2003/10/23 21:29:52 garren Exp $ // --------------------------------------------------------------------------- // CLASSDOC ON // // This file is a part of the CLHEP - a Class Library for High Energy Physics. // // This is the definition of the HepRotation class for performing rotations // on objects of the Hep3Vector (and HepLorentzVector) class. // // HepRotation is a concrete implementation of Hep3RotationInterface. // // .SS See Also // RotationInterfaces.h // ThreeVector.h, LorentzVector.h, LorentzRotation.h // // .SS Author // Leif Lonnblad, Mark Fischler #ifndef HEP_ROTATION_H #define HEP_ROTATION_H #ifdef GNUPRAGMA #pragma interface #endif //#include "CLHEP/Vector/defs.h" #include "RotationInterfaces.h" #include "RotationX.h" #include "RotationY.h" #include "RotationZ.h" #include "LorentzVector.h" namespace CLHEP { // Declarations of classes and global methods class HepRotation; inline HepRotation inverseOf ( const HepRotation & r ); inline HepRotation operator * (const HepRotationX & rx, const HepRotation & r); inline HepRotation operator * (const HepRotationY & ry, const HepRotation & r); inline HepRotation operator * (const HepRotationZ & rz, const HepRotation & r); /** * @author * @ingroup vector */ class HepRotation { public: // ---------- Constructors and Assignment: inline HepRotation(); // Default constructor. Gives a unit matrix. inline HepRotation(const HepRotation & m); // Copy constructor. inline HepRotation(const HepRotationX & m); inline HepRotation(const HepRotationY & m); inline HepRotation(const HepRotationZ & m); // Construct from specialized rotation. HepRotation & set( const Hep3Vector & axis, double delta ); HepRotation ( const Hep3Vector & axis, double delta ); // Construct from axis and angle. HepRotation & set( const HepAxisAngle & ax ); HepRotation ( const HepAxisAngle & ax ); // Construct from AxisAngle structure. HepRotation & set( double phi, double theta, double psi ); HepRotation ( double phi, double theta, double psi ); // Construct from three Euler angles (in radians). HepRotation & set( const HepEulerAngles & e ); HepRotation ( const HepEulerAngles & e ); // Construct from EulerAngles structure. HepRotation ( const Hep3Vector & colX, const Hep3Vector & colY, const Hep3Vector & colZ ); // Construct from three *orthogonal* unit vector columns. // NOTE: // This constructor, and the two set methods below, // will check that the columns (or rows) form an orthonormal // matrix, and will adjust values so that this relation is // as exact as possible. HepRotation & set( const Hep3Vector & colX, const Hep3Vector & colY, const Hep3Vector & colZ ); // supply three *orthogonal* unit vectors for the columns. HepRotation & setRows( const Hep3Vector & rowX, const Hep3Vector & rowY, const Hep3Vector & rowZ ); // supply three *orthogonal* unit vectors for the rows. inline HepRotation & set(const HepRotationX & r); inline HepRotation & set(const HepRotationY & r); inline HepRotation & set(const HepRotationZ & r); // set from specialized rotation. inline HepRotation & operator = (const HepRotation & r); // Assignment. inline HepRotation & operator = (const HepRotationX & r); inline HepRotation & operator = (const HepRotationY & r); inline HepRotation & operator = (const HepRotationZ & r); // Assignment from specialized rotation. inline HepRotation &set( const HepRep3x3 & m ); inline HepRotation ( const HepRep3x3 & m ); // WARNING - NO CHECKING IS DONE! // Constructon directly from from a 3x3 representation, // which is required to be an orthogonal matrix. inline ~HepRotation(); // Trivial destructor. // ---------- Accessors: inline Hep3Vector colX() const; inline Hep3Vector colY() const; inline Hep3Vector colZ() const; // orthogonal unit-length column vectors inline Hep3Vector rowX() const; inline Hep3Vector rowY() const; inline Hep3Vector rowZ() const; // orthogonal unit-length row vectors inline double xx() const; inline double xy() const; inline double xz() const; inline double yx() const; inline double yy() const; inline double yz() const; inline double zx() const; inline double zy() const; inline double zz() const; // Elements of the rotation matrix (Geant4). inline HepRep3x3 rep3x3() const; // 3x3 representation: // ------------ Subscripting: class HepRotation_row { public: inline HepRotation_row(const HepRotation &, int); inline double operator [] (int) const; private: const HepRotation & rr; int ii; }; // Helper class for implemention of C-style subscripting r[i][j] inline const HepRotation_row operator [] (int) const; // Returns object of the helper class for C-style subscripting r[i][j] // i and j range from 0 to 2. double operator () (int, int) const; // Fortran-style subscripting: returns (i,j) element of the rotation matrix. // Note: i and j still range from 0 to 2. [Rotation.cc] // ------------ Euler angles: inline double getPhi () const; inline double getTheta() const; inline double getPsi () const; double phi () const; double theta() const; double psi () const; HepEulerAngles eulerAngles() const; // ------------ axis & angle of rotation: inline double getDelta() const; inline Hep3Vector getAxis () const; double delta() const; Hep3Vector axis () const; HepAxisAngle axisAngle() const; void getAngleAxis(double & delta, Hep3Vector & axis) const; // Returns the rotation angle and rotation axis (Geant4). [Rotation.cc] // ------------- Angles of rotated axes double phiX() const; double phiY() const; double phiZ() const; double thetaX() const; double thetaY() const; double thetaZ() const; // Return angles (RADS) made by rotated axes against original axes (Geant4). // [Rotation.cc] // ---------- Other accessors treating pure rotation as a 4-rotation inline HepLorentzVector col1() const; inline HepLorentzVector col2() const; inline HepLorentzVector col3() const; // orthosymplectic 4-vector columns - T component will be zero inline HepLorentzVector col4() const; // Will be (0,0,0,1) for this pure Rotation. inline HepLorentzVector row1() const; inline HepLorentzVector row2() const; inline HepLorentzVector row3() const; // orthosymplectic 4-vector rows - T component will be zero inline HepLorentzVector row4() const; // Will be (0,0,0,1) for this pure Rotation. inline double xt() const; inline double yt() const; inline double zt() const; inline double tx() const; inline double ty() const; inline double tz() const; // Will be zero for this pure Rotation inline double tt() const; // Will be one for this pure Rotation inline HepRep4x4 rep4x4() const; // 4x4 representation. // --------- Mutators void setPhi (double phi); // change Euler angle phi, leaving theta and psi unchanged. void setTheta (double theta); // change Euler angle theta, leaving phi and psi unchanged. void setPsi (double psi); // change Euler angle psi, leaving theta and phi unchanged. void setAxis (const Hep3Vector & axis); // change rotation axis, leaving delta unchanged. void setDelta (double delta); // change angle of rotation, leaving rotation axis unchanged. // ---------- Decomposition: void decompose (HepAxisAngle & rotation, Hep3Vector & boost) const; void decompose (Hep3Vector & boost, HepAxisAngle & rotation) const; // These are trivial, as the boost vector is 0. [RotationP.cc] // ---------- Comparisons: bool isIdentity() const; // Returns true if the identity matrix (Geant4). [Rotation.cc] int compare( const HepRotation & r ) const; // Dictionary-order comparison, in order zz, zy, zx, yz, ... xx // Used in operator<, >, <=, >= inline bool operator== ( const HepRotation & r ) const; inline bool operator!= ( const HepRotation & r ) const; inline bool operator< ( const HepRotation & r ) const; inline bool operator> ( const HepRotation & r ) const; inline bool operator<= ( const HepRotation & r ) const; inline bool operator>= ( const HepRotation & r ) const; double distance2( const HepRotation & r ) const; // 3 - Tr ( this/r ) -- This works with RotationX, Y or Z also double howNear( const HepRotation & r ) const; bool isNear( const HepRotation & r, double epsilon=Hep4RotationInterface::tolerance) const; double distance2( const HepBoost & lt ) const; // 3 - Tr ( this ) + |b|^2 / (1-|b|^2) double distance2( const HepLorentzRotation & lt ) const; // 3 - Tr ( this/r ) + |b|^2 / (1-|b|^2) where b is the boost vector of lt double howNear( const HepBoost & lt ) const; double howNear( const HepLorentzRotation & lt ) const; bool isNear( const HepBoost & lt, double epsilon=Hep4RotationInterface::tolerance) const; bool isNear( const HepLorentzRotation & lt, double epsilon=Hep4RotationInterface::tolerance) const; // ---------- Properties: double norm2() const; // distance2 (IDENTITY), which is 3 - Tr ( *this ) void rectify(); // non-const but logically moot correction for accumulated roundoff errors // rectify averages the matrix with the transpose of its actual // inverse (absent accumulated roundoff errors, the transpose IS // the inverse)); this removes to first order those errors. // Then it formally extracts axis and delta, and forms a true // HepRotation with those values of axis and delta. // ---------- Application: inline Hep3Vector operator() (const Hep3Vector & p) const; // Rotate a Hep3Vector. inline Hep3Vector operator * (const Hep3Vector & p) const; // Multiplication with a Hep3Vector. inline HepLorentzVector operator()( const HepLorentzVector & w ) const; // Rotate (the space part of) a HepLorentzVector. inline HepLorentzVector operator* ( const HepLorentzVector & w ) const; // Multiplication with a HepLorentzVector. // ---------- Operations in the group of Rotations inline HepRotation operator * (const HepRotation & r) const; // Product of two rotations (this) * r - matrix multiplication inline HepRotation operator * (const HepRotationX & rx) const; inline HepRotation operator * (const HepRotationY & ry) const; inline HepRotation operator * (const HepRotationZ & rz) const; // Product of two rotations (this) * r - faster when specialized type inline HepRotation & operator *= (const HepRotation & r); inline HepRotation & transform (const HepRotation & r); // Matrix multiplication. // Note a *= b; <=> a = a * b; while a.transform(b); <=> a = b * a; inline HepRotation & operator *= (const HepRotationX & r); inline HepRotation & operator *= (const HepRotationY & r); inline HepRotation & operator *= (const HepRotationZ & r); inline HepRotation & transform (const HepRotationX & r); inline HepRotation & transform (const HepRotationY & r); inline HepRotation & transform (const HepRotationZ & r); // Matrix multiplication by specialized matrices HepRotation & rotateX(double delta); // Rotation around the x-axis; equivalent to R = RotationX(delta) * R HepRotation & rotateY(double delta); // Rotation around the y-axis; equivalent to R = RotationY(delta) * R HepRotation & rotateZ(double delta); // Rotation around the z-axis; equivalent to R = RotationZ(delta) * R HepRotation & rotate(double delta, const Hep3Vector & axis); inline HepRotation & rotate(double delta, const Hep3Vector * axis); // Rotation around a specified vector. // r.rotate(d,a) is equivalent to r = Rotation(d,a) * r HepRotation & rotateAxes(const Hep3Vector & newX, const Hep3Vector & newY, const Hep3Vector & newZ); // Rotation of local axes defined by 3 orthonormal vectors (Geant4). // Equivalent to r = Rotation (newX, newY, newZ) * r inline HepRotation inverse() const; // Returns the inverse. inline HepRotation & invert(); // Inverts the Rotation matrix. // ---------- I/O: std::ostream & print( std::ostream & os ) const; // Aligned six-digit-accurate output of the rotation matrix. [RotationIO.cc] // ---------- Identity Rotation: static const HepRotation IDENTITY; // ---------- Tolerance static inline double getTolerance(); static inline double setTolerance(double tol); protected: inline HepRotation(double mxx, double mxy, double mxz, double myx, double myy, double myz, double mzx, double mzy, double mzz); // Protected constructor. // DOES NOT CHECK FOR VALIDITY AS A ROTATION. friend HepRotation operator* (const HepRotationX & rx, const HepRotation & r); friend HepRotation operator* (const HepRotationY & ry, const HepRotation & r); friend HepRotation operator* (const HepRotationZ & rz, const HepRotation & r); double rxx, rxy, rxz, ryx, ryy, ryz, rzx, rzy, rzz; // The matrix elements. private: bool setCols ( const Hep3Vector & u1, // Vectors assume to be of unit length const Hep3Vector & u2, const Hep3Vector & u3, double u1u2, Hep3Vector & v1, // Returned vectors Hep3Vector & v2, Hep3Vector & v3 ) const; void setArbitrarily (const Hep3Vector & colX, // assumed to be of unit length Hep3Vector & v1, Hep3Vector & v2, Hep3Vector & v3) const; }; // HepRotation inline std::ostream & operator << ( std::ostream & os, const HepRotation & r ) {return r.print(os);} } // namespace CLHEP #include "Rotation.icc" #ifdef ENABLE_BACKWARDS_COMPATIBILITY // backwards compatibility will be enabled ONLY in CLHEP 1.9 using namespace CLHEP; #endif #endif /* HEP_ROTATION_H */
33.525943
80
0.667605
[ "object", "vector", "transform" ]
70a73ab50db108cdfd72b7a206bfb9dd4d9bf208
2,929
h
C
reactions/src/MonteCarlo.h
PedroCarrilho/ReACT
507866e9462ecf10c298fcd3e2c81249f32e7d50
[ "MIT" ]
3
2020-07-07T11:34:02.000Z
2021-07-15T12:48:05.000Z
reactions/src/MonteCarlo.h
PedroCarrilho/ReACT
507866e9462ecf10c298fcd3e2c81249f32e7d50
[ "MIT" ]
11
2020-05-29T16:26:06.000Z
2022-02-07T08:59:52.000Z
reactions/src/MonteCarlo.h
PedroCarrilho/ReACT
507866e9462ecf10c298fcd3e2c81249f32e7d50
[ "MIT" ]
1
2021-08-31T15:35:28.000Z
2021-08-31T15:35:28.000Z
#ifndef MONTE_CARLO_H #define MONTE_CARLO_H #include <vector> #define NBINS 128 #define DEFAULT_MAXEVAL 100000 #define DEFAULT_BATCHSIZE 1000 #define DEFAULT_EPSREL 1e-3 #define DEFAULT_EPSABS 1e-12 #define DEFAULT_NSTART 1000 #define DEFAULT_NINCREASE 1000 /* MonteCarloIntegral * * n-dimensional Monte-Carlo integration, based on the implementation of the * VEGAS importance-sampling algorithm found in the Cuba library. Uses GSL for * quasi-random number generation. */ class MonteCarloIntegral { public: struct Range { double a; double b; }; /* Initialize integral. * n is the dimension of the integration region * m is the number of components of the integrand (m > 1 for vector integrands) * V is an array of n Range objects specifying the domain of integration */ MonteCarloIntegral(int n, int m = 1, const Range* V = 0); virtual ~MonteCarloIntegral(); /* Set domain of integration */ void SetDomain(const Range* domain); /* Evaluate the integrand f(x). Here x is an n-dimensional vector, and f * is an m-dimensional array. */ virtual void Integrand(const double x[], double* f, double* param) const = 0; /* Evaluate the integral $I = \int f(x) d^nx$ */ virtual void Integrate(double* I, double* param = 0, double* error = 0, int* neval = 0, double epsrel = 0, double epsabs = 0) const; public: int n; // dimension of integral int m; // number of components of f(x) std::vector<Range> V; // domain of integration /* Parameters */ int maxeval; // maximum number of evaluations of integrand int nstart; // number of samples in first iteration int nincrease; // number of extra samples in each successive iteration int nbatch; // number of samples per batch (so everything fits in CPU cache) protected: struct Cumulants { double sum; double sqsum; double weightsum; double avgsum; double chisum; double chisqsum; double guess; double avg; double err; double chisq; }; struct Grid { double g[NBINS]; double& operator[](int k) { return g[k]; } operator double*() { return &g[0]; } }; struct State { int niter; int nsamples; int neval; std::vector<Cumulants> cumul; std::vector<Grid> grid; }; static double Weight(double sum, double sqsum, int nsamples); static void RefineGrid(Grid& grid, Grid& margsum); }; #if 0 typedef void (*Integrand)(const double x[], double* f, double* param); template<int n, int m = 1> void Integrate(Integrand f, const Range[] domain, double* F, double* param = 0, double* error = 0, int* neval = 0) { MonteCarloIntegral(n, m, domain); } #endif #endif // MONTE_CARLO_H
29.585859
136
0.630932
[ "vector" ]
70aefc27d7a608e27022ea94cbacacda20af3ec9
9,638
h
C
dev/Gems/CryLegacy/Code/Source/CryAISystem/Navigation/MNM/FixedVec3.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/CryLegacy/Code/Source/CryAISystem/Navigation/MNM/FixedVec3.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/CryLegacy/Code/Source/CryAISystem/Navigation/MNM/FixedVec3.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * 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. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #ifndef CRYINCLUDE_CRYAISYSTEM_NAVIGATION_MNM_FIXEDVEC3_H #define CRYINCLUDE_CRYAISYSTEM_NAVIGATION_MNM_FIXEDVEC3_H #pragma once #include <FixedPoint.h> namespace MNM { template<typename BaseType, size_t IntegerBitCount> struct FixedVec3 { typedef fixed_t<BaseType, IntegerBitCount> value_type; typedef typename CryFixedPoint::unsigned_overflow_type<BaseType>::type unsigned_overflow_type; value_type x, y, z; inline FixedVec3() { } inline FixedVec3(const value_type& _x) : x(_x) , y(_x) , z(_x) { } template<typename OBaseType, size_t OIntegerBitCount> inline FixedVec3(const FixedVec3<OBaseType, OIntegerBitCount>& _x) : x(value_type(_x.x)) , y(value_type(_x.y)) , z(value_type(_x.z)) { } inline FixedVec3(const value_type& _x, const value_type& _y, const value_type& _z) : x(_x) , y(_y) , z(_z) { } inline FixedVec3(const Vec3& _vec) : x(value_type(_vec.x)) , y(value_type(_vec.y)) , z(value_type(_vec.z)) { } inline const value_type& operator[](size_t i) const { assert(i < 3); return ((value_type*)&x)[i]; } inline value_type& operator[](size_t i) { assert(i < 3); return ((value_type*)&x)[i]; } template<typename OBaseType, size_t OIntegerBitCount> inline FixedVec3 operator+(const FixedVec3<OBaseType, OIntegerBitCount>& other) const { return FixedVec3(x + other.x, y + other.y, z + other.z); } template<typename OBaseType, size_t OIntegerBitCount> inline FixedVec3 operator-(const FixedVec3<OBaseType, OIntegerBitCount>& other) const { return FixedVec3(x - other.x, y - other.y, z - other.z); } template<typename OBaseType, size_t OIntegerBitCount> inline FixedVec3& operator+=(const FixedVec3<OBaseType, OIntegerBitCount>& other) { x += other.x; y += other.y; z += other.z; return *this; } template<typename OBaseType, size_t OIntegerBitCount> inline FixedVec3& operator-=(const FixedVec3<OBaseType, OIntegerBitCount>& other) { x -= other.x; y -= other.y; z -= other.z; return *this; } template<typename OBaseType, size_t OIntegerBitCount> inline FixedVec3 operator/(const FixedVec3<OBaseType, OIntegerBitCount>& other) const { return FixedVec3(x / other.x, y / other.y, z / other.z); } template<typename OBaseType, size_t OIntegerBitCount> inline FixedVec3 operator*(const FixedVec3<OBaseType, OIntegerBitCount>& other) const { return FixedVec3(x * other.x, y * other.y, z * other.z); } template<typename OBaseType, size_t OIntegerBitCount> inline FixedVec3 operator/(const fixed_t<OBaseType, OIntegerBitCount>& value) const { return FixedVec3(x / value, y / value, z / value); } template<typename OBaseType, size_t OIntegerBitCount> inline FixedVec3 operator*(const fixed_t<OBaseType, OIntegerBitCount>& value) const { return FixedVec3(x * value, y * value, z * value); } template<typename OBaseType, size_t OIntegerBitCount> inline bool operator==(const FixedVec3<OBaseType, OIntegerBitCount>& other) const { return (x == other.x) && (y == other.y) && (z == other.z); } template<typename OBaseType, size_t OIntegerBitCount> inline bool operator!=(const FixedVec3<OBaseType, OIntegerBitCount>& other) const { return (x != other.x) || (y != other.y || (z != other.z)); } inline void Set(const value_type& _x, const value_type& _y, const value_type& _z) { x = _x; y = _y; z = _z; } inline value_type dot(const FixedVec3& other) const { return x * other.x + y * other.y + z * other.z; } inline value_type approximatedLen() const { const value_type heuristicFactor1(0.5f * (1.0f + (1.0f / (4.0f * sqrtf(3.0f))))); const value_type heuristicFactor2(1.0f / sqrtf(3.0f)); const value_type targetDistAbsX = fabsf(x), targetDistAbsY = fabsf(y), targetDistAbsZ = fabsf(z); return heuristicFactor1 * min(heuristicFactor2 * (targetDistAbsX + targetDistAbsY + targetDistAbsZ), max(max(targetDistAbsX, targetDistAbsY), targetDistAbsZ)); } // Be careful. This function can be safely used only when the vector length // respects len^2 <= value_type::max(). // In all the other cases the value returned is incorrect and undefined inline value_type len() const { return sqrtf(lenSq()); } // Be careful. This function can be safely used only when the vector length // respects len^2 <= value_type::max(). // In all the other cases the value returned is incorrect and undefined template<typename BaseTypeO, size_t IntegerBitCountO> inline fixed_t<BaseTypeO, IntegerBitCountO> len() const { return sqrtf(lenSq<BaseTypeO, IntegerBitCountO>()); } inline value_type lenNoOverflow() const { assert(value_type::sqrtf(lenSqNoOverflow()) >= value_type(0)); return value_type::sqrtf(lenSqNoOverflow()); } // Note: This function can overflow inline value_type lenSq() const { assert((x * x + y * y + z * z) >= value_type(0)); return x * x + y * y + z * z; } inline unsigned_overflow_type lenSqNoOverflow() const { return x.sqr() + y.sqr() + z.sqr(); } template<typename BaseTypeO, size_t IntegerBitCountO> inline fixed_t<BaseTypeO, IntegerBitCountO> lenSq() const { return fixed_t<BaseTypeO, IntegerBitCountO>(x) * fixed_t<BaseTypeO, IntegerBitCountO>(x) + fixed_t<BaseTypeO, IntegerBitCountO>(y) * fixed_t<BaseTypeO, IntegerBitCountO>(y) + fixed_t<BaseTypeO, IntegerBitCountO>(z) * fixed_t<BaseTypeO, IntegerBitCountO>(z); } inline FixedVec3 abs() const { return FixedVec3(fabsf(x), fabsf(y), fabsf(z)); } // This function uses the len() value to normalize the vector. // If the vector is really long, len() could overflow and the normalized // resulting vector could be not correct. inline FixedVec3 normalized() const { const value_type invLen = value_type(1) / len(); return FixedVec3(x * invLen, y * invLen, z * invLen); } // This function uses the len() value to normalize the vector. // If the vector is really long, len() could overflow and the normalized // resulting vector could be not correct. template<typename BaseTypeO, size_t IntegerBitCountO> inline FixedVec3 normalized() const { const fixed_t<BaseTypeO, IntegerBitCountO> invLen = fixed_t<BaseTypeO, IntegerBitCountO>(1) / len<BaseTypeO, IntegerBitCountO>(); return FixedVec3(fixed_t<BaseTypeO, IntegerBitCountO>(x) * invLen, fixed_t<BaseTypeO, IntegerBitCountO>(y) * invLen, fixed_t<BaseTypeO, IntegerBitCountO>(z) * invLen); } inline static FixedVec3 minimize(const FixedVec3& a, const FixedVec3& b) { return FixedVec3(std::min(a.x, b.x), std::min(a.y, b.y), std::min(a.z, b.z)); } inline static FixedVec3 minimize(const FixedVec3& a, const FixedVec3& b, const FixedVec3& c) { return FixedVec3(std::min(std::min(a.x, b.x), c.x), std::min(std::min(a.y, b.y), c.y), std::min(std::min(a.z, b.z), c.z)); } inline static FixedVec3 maximize(const FixedVec3& a, const FixedVec3& b) { return FixedVec3(std::max(a.x, b.x), std::max(a.y, b.y), std::max(a.z, b.z)); } inline static FixedVec3 maximize(const FixedVec3& a, const FixedVec3& b, const FixedVec3& c) { return FixedVec3(std::max(std::max(a.x, b.x), c.x), std::max(std::max(a.y, b.y), c.y), std::max(std::max(a.z, b.z), c.z)); } inline Vec3 GetVec3() const { return Vec3(x.as_float(), y.as_float(), z.as_float()); } AUTO_STRUCT_INFO }; } #endif // CRYINCLUDE_CRYAISYSTEM_NAVIGATION_MNM_FIXEDVEC3_H
35.304029
171
0.58591
[ "vector" ]
70affa5fe15e6e79507e15b1450ca3331a26f96a
8,968
c
C
src/debug.c
BenStigsen/blade
119fd687b1e4969b657a9158c0d1d9715f3a104e
[ "MIT" ]
46
2021-07-16T07:49:07.000Z
2022-03-22T21:15:58.000Z
src/debug.c
BenStigsen/blade
119fd687b1e4969b657a9158c0d1d9715f3a104e
[ "MIT" ]
32
2021-08-30T12:24:36.000Z
2022-03-07T18:08:57.000Z
src/debug.c
BenStigsen/blade
119fd687b1e4969b657a9158c0d1d9715f3a104e
[ "MIT" ]
13
2021-08-30T14:29:08.000Z
2022-03-31T14:20:04.000Z
#include "debug.h" #include "object.h" #include "value.h" #include <stdio.h> void disassemble_blob(b_blob *blob, const char *name) { printf("== %s ==\n", name); for (int offset = 0; offset < blob->count;) { offset = disassemble_instruction(blob, offset); } } int simple_instruction(const char *name, int offset) { printf("%s\n", name); return offset + 1; } int constant_instruction(const char *name, b_blob *blob, int offset) { uint16_t constant = (blob->code[offset + 1] << 8) | blob->code[offset + 2]; printf("%-16s %8d '", name, constant); print_value(blob->constants.values[constant]); printf("'\n"); return offset + 3; } int short_instruction(const char *name, b_blob *blob, int offset) { uint16_t slot = (blob->code[offset + 1] << 8) | blob->code[offset + 2]; printf("%-16s %8d\n", name, slot); return offset + 3; } static int byte_instruction(const char *name, b_blob *blob, int offset) { uint8_t slot = blob->code[offset + 1]; printf("%-16s %8d\n", name, slot); return offset + 2; } static int jump_instruction(const char *name, int sign, b_blob *blob, int offset) { uint16_t jump = (uint16_t) (blob->code[offset + 1] << 8); jump |= blob->code[offset + 2]; printf("%-16s %8d -> %d\n", name, offset, offset + 3 + sign * jump); return offset + 3; } static int try_instruction(const char *name, b_blob *blob, int offset) { uint16_t type = (uint16_t) (blob->code[offset + 1] << 8); type |= blob->code[offset + 2]; uint16_t address = (uint16_t) (blob->code[offset + 3] << 8); address |= blob->code[offset + 4]; uint16_t finally = (uint16_t) (blob->code[offset + 5] << 8); finally |= blob->code[offset + 6]; printf("%-16s %8d -> %d, %d\n", name, type, address, finally); return offset + 7; } static int invoke_instruction(const char *name, b_blob *blob, int offset) { uint16_t constant = (uint16_t) (blob->code[offset + 1] << 8); constant |= blob->code[offset + 2]; uint8_t arg_count = blob->code[offset + 3]; printf("%-16s (%d args) %8d '", name, arg_count, constant); print_value(blob->constants.values[constant]); printf("'\n"); return offset + 4; } int disassemble_instruction(b_blob *blob, int offset) { printf("%08d ", offset); if (offset > 0 && blob->lines[offset] == blob->lines[offset - 1]) { printf(" | "); } else { printf("%8d ", blob->lines[offset]); } uint8_t instruction = blob->code[offset]; switch (instruction) { case OP_JUMP_IF_FALSE: return jump_instruction("f_jump", 1, blob, offset); case OP_JUMP: return jump_instruction("jump", 1, blob, offset); case OP_TRY: return try_instruction("i_try", blob, offset); case OP_LOOP: return jump_instruction("loop", -1, blob, offset); case OP_DEFINE_GLOBAL: return constant_instruction("d_glob", blob, offset); case OP_GET_GLOBAL: return constant_instruction("g_glob", blob, offset); case OP_SET_GLOBAL: return constant_instruction("s_glob", blob, offset); case OP_GET_LOCAL: return short_instruction("g_loc", blob, offset); case OP_SET_LOCAL: return short_instruction("s_loc", blob, offset); case OP_GET_PROPERTY: return constant_instruction("g_prop", blob, offset); case OP_GET_SELF_PROPERTY: return constant_instruction("g_props", blob, offset); case OP_SET_PROPERTY: return constant_instruction("s_prop", blob, offset); case OP_GET_UP_VALUE: return short_instruction("g_up_v", blob, offset); case OP_SET_UP_VALUE: return short_instruction("s_up_v", blob, offset); case OP_POP_TRY: return simple_instruction("p_try", offset); case OP_PUBLISH_TRY: return simple_instruction("pub_try", offset); case OP_CONSTANT: return constant_instruction("load", blob, offset); case OP_EQUAL: return simple_instruction("eq", offset); case OP_GREATER: return simple_instruction("gt", offset); case OP_LESS: return simple_instruction("less", offset); case OP_EMPTY: return simple_instruction("em", offset); case OP_NIL: return simple_instruction("nil", offset); case OP_TRUE: return simple_instruction("true", offset); case OP_FALSE: return simple_instruction("false", offset); case OP_ADD: return simple_instruction("add", offset); case OP_SUBTRACT: return simple_instruction("sub", offset); case OP_MULTIPLY: return simple_instruction("mul", offset); case OP_DIVIDE: return simple_instruction("div", offset); case OP_F_DIVIDE: return simple_instruction("f_div", offset); case OP_REMINDER: return simple_instruction("r_mod", offset); case OP_POW: return simple_instruction("pow", offset); case OP_NEGATE: return simple_instruction("neg", offset); case OP_NOT: return simple_instruction("not", offset); case OP_BIT_NOT: return simple_instruction("b_not", offset); case OP_AND: return simple_instruction("b_and", offset); case OP_OR: return simple_instruction("b_or", offset); case OP_XOR: return simple_instruction("b_xor", offset); case OP_LSHIFT: return simple_instruction("l_shift", offset); case OP_RSHIFT: return simple_instruction("r_shift", offset); case OP_ONE: return simple_instruction("one", offset); case OP_CALL_IMPORT: return short_instruction("c_import", blob, offset); case OP_NATIVE_MODULE: return short_instruction("f_import", blob, offset); case OP_SELECT_IMPORT: return short_instruction("s_import", blob, offset); case OP_SELECT_NATIVE_IMPORT: return short_instruction("sn_import", blob, offset); case OP_EJECT_IMPORT: return short_instruction("e_import", blob, offset); case OP_EJECT_NATIVE_IMPORT: return short_instruction("en_import", blob, offset); case OP_IMPORT_ALL: return simple_instruction("a_import", offset); case OP_IMPORT_ALL_NATIVE: return simple_instruction("an_import", offset); case OP_ECHO: return simple_instruction("echo", offset); case OP_STRINGIFY: return simple_instruction("str", offset); case OP_CHOICE: return simple_instruction("cho", offset); case OP_DIE: return simple_instruction("die", offset); case OP_POP: return simple_instruction("pop", offset); case OP_CLOSE_UP_VALUE: return simple_instruction("cl_up_v", offset); case OP_DUP: return simple_instruction("dup", offset); case OP_ASSERT: return simple_instruction("assrt", offset); case OP_POP_N: return short_instruction("pop_n", blob, offset); // non-user objects... case OP_SWITCH: return short_instruction("sw", blob, offset); // data container manipulators case OP_RANGE: return short_instruction("rng", blob, offset); case OP_LIST: return short_instruction("list", blob, offset); case OP_DICT: return short_instruction("dict", blob, offset); case OP_GET_INDEX: return byte_instruction("g_ind", blob, offset); case OP_GET_RANGED_INDEX: return byte_instruction("gr_ind", blob, offset); case OP_SET_INDEX: return simple_instruction("s_ind", offset); case OP_CLOSURE: { offset++; uint16_t constant = blob->code[offset++] << 8; constant |= blob->code[offset++]; printf("%-16s %8d ", "clsur", constant); print_value(blob->constants.values[constant]); printf("\n"); b_obj_func *function = AS_FUNCTION(blob->constants.values[constant]); for (int j = 0; j < function->up_value_count; j++) { int is_local = blob->code[offset++]; uint16_t index = blob->code[offset++] << 8; index |= blob->code[offset++]; printf("%04d | %s %d\n", offset - 3, is_local ? "local" : "up-value", (int) index); } return offset; } case OP_CALL: return byte_instruction("call", blob, offset); case OP_INVOKE: return invoke_instruction("invk", blob, offset); case OP_INVOKE_SELF: return invoke_instruction("invk_s", blob, offset); case OP_RETURN: return simple_instruction("ret", offset); case OP_CLASS: return constant_instruction("class", blob, offset); case OP_METHOD: return constant_instruction("meth", blob, offset); case OP_CLASS_PROPERTY: return constant_instruction("cl_prop", blob, offset); case OP_GET_SUPER: return constant_instruction("g_sup", blob, offset); case OP_INHERIT: return simple_instruction("inher", offset); case OP_SUPER_INVOKE: return invoke_instruction("s_invk", blob, offset); case OP_SUPER_INVOKE_SELF: return byte_instruction("s_invk_s", blob, offset); default: printf("unknown opcode %d\n", instruction); return offset + 1; } }
32.970588
77
0.657003
[ "object" ]
70b33a44e429eb85e98445c0ea5110c1a0fdfc45
626
h
C
example/DetectPortsUDP/detectports.h
jef42/pcapwrapper
6e5356fabfe2e49f96fdbd8bfbb0f8555e497969
[ "MIT" ]
6
2017-08-07T09:22:34.000Z
2019-05-11T09:11:45.000Z
example/DetectPortsUDP/detectports.h
jef42/pcapwrapper
6e5356fabfe2e49f96fdbd8bfbb0f8555e497969
[ "MIT" ]
null
null
null
example/DetectPortsUDP/detectports.h
jef42/pcapwrapper
6e5356fabfe2e49f96fdbd8bfbb0f8555e497969
[ "MIT" ]
2
2018-05-15T23:28:43.000Z
2021-11-13T09:53:40.000Z
#ifndef DETECTPORTS_H #define DETECTPORTS_H #include <string> #include <vector> #include <pcapwrapper/listeners/packagelistener.h> #include <pcapwrapper/network/addresses/ipaddress.h> #include <pcapwrapper/network/packages/icmppackage.h> static const int MAX_PORT = 65000; class DetectPorts : public PCAP::PackageListener<PCAP::ICMPPackage> { public: DetectPorts(PCAP::IpAddress desiredIp); void receive_package(PCAP::ICMPPackage package) override; std::vector<int> get_ports(); private: const PCAP::IpAddress m_expectedip; bool m_ports[MAX_PORT]; void reset(); }; #endif // DETECTPORTS_H
21.586207
69
0.752396
[ "vector" ]
70b63a435ab3b6effff6101d8cef0d385e04bef2
2,355
h
C
src/ProceduralTexturesLibrary/include/babylon/proceduraltextureslibrary/starfield/starfield_procedural_texture_fragment_fx.h
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
277
2017-05-18T08:27:10.000Z
2022-03-26T01:31:37.000Z
src/ProceduralTexturesLibrary/include/babylon/proceduraltextureslibrary/starfield/starfield_procedural_texture_fragment_fx.h
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
77
2017-09-03T15:35:02.000Z
2022-03-28T18:47:20.000Z
src/ProceduralTexturesLibrary/include/babylon/proceduraltextureslibrary/starfield/starfield_procedural_texture_fragment_fx.h
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
37
2017-03-30T03:36:24.000Z
2022-01-28T08:28:36.000Z
#ifndef BABYLON_PROCEDURAL_TEXTURES_LIBRARY_STARFIELD_STARFIELD_PROCEDURAL_TEXTURE_FRAGMENT_FX_H #define BABYLON_PROCEDURAL_TEXTURES_LIBRARY_STARFIELD_STARFIELD_PROCEDURAL_TEXTURE_FRAGMENT_FX_H namespace BABYLON { extern const char* starfieldProceduralTexturePixelShader; const char* starfieldProceduralTexturePixelShader = R"ShaderCode( #ifdef GL_ES precision highp float; #endif //defined as const as fragment shaders does not support uniforms in loops #define volsteps 20 #define iterations 15 varying vec2 vPosition; varying vec2 vUV; uniform float time; uniform float alpha; uniform float beta; uniform float zoom; uniform float formuparam; uniform float stepsize; uniform float tile; uniform float brightness; uniform float darkmatter; uniform float distfading; uniform float saturation; void main() { vec3 dir = vec3(vUV * zoom, 1.); float localTime = time * 0.0001; // Rotation mat2 rot1 = mat2(cos(alpha), sin(alpha), -sin(alpha), cos(alpha)); mat2 rot2 = mat2(cos(beta), sin(beta), -sin(beta), cos(beta)); dir.xz *= rot1; dir.xy *= rot2; vec3 from = vec3(1., .5, 0.5); from += vec3(-2., localTime*2., localTime); from.xz *= rot1; from.xy *= rot2; //volumetric rendering float s = 0.1, fade = 1.; vec3 v = vec3(0.); for (int r = 0; r < volsteps; r++) { vec3 p = from + s*dir*.5; p = abs(vec3(tile) - mod(p, vec3(tile*2.))); // tiling fold float pa, a = pa = 0.; for (int i = 0; i < iterations; i++) { p = abs(p) / dot(p, p) - formuparam; // the magic formula a += abs(length(p) - pa); // absolute sum of average change pa = length(p); } float dm = max(0., darkmatter - a*a*.001); //dark matter a *= a*a; // add contrast if (r > 6) fade *= 1. - dm; // dark matter, don't render near //v+=vec3(dm,dm*.5,0.); v += fade; v += vec3(s, s*s, s*s*s*s)*a*brightness*fade; // coloring based on distance fade *= distfading; // distance fading s += stepsize; } v = mix(vec3(length(v)), v, saturation); //color adjust gl_FragColor = vec4(v*.01, 1.); } )ShaderCode"; } // end of namespace BABYLON #endif // end of BABYLON_PROCEDURAL_TEXTURES_LIBRARY_STARFIELD_STARFIELD_PROCEDURAL_TEXTURE_FRAGMENT_FX_H
29.4375
105
0.639915
[ "render" ]
70b653301b022a52a70fa82699ef61ab5a4f249f
1,019
h
C
assignment-client/src/audio/AudioMixerClientData.h
judasshuffle/hifi
f6778588914f803f63bd0e965fae9dfcbd22fd6d
[ "Apache-2.0" ]
null
null
null
assignment-client/src/audio/AudioMixerClientData.h
judasshuffle/hifi
f6778588914f803f63bd0e965fae9dfcbd22fd6d
[ "Apache-2.0" ]
null
null
null
assignment-client/src/audio/AudioMixerClientData.h
judasshuffle/hifi
f6778588914f803f63bd0e965fae9dfcbd22fd6d
[ "Apache-2.0" ]
null
null
null
// // AudioMixerClientData.h // assignment-client/src/audio // // Created by Stephen Birarda on 10/18/13. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef hifi_AudioMixerClientData_h #define hifi_AudioMixerClientData_h #include <vector> #include <NodeData.h> #include <PositionalAudioRingBuffer.h> #include "AvatarAudioRingBuffer.h" class AudioMixerClientData : public NodeData { public: AudioMixerClientData(); ~AudioMixerClientData(); const QList<PositionalAudioRingBuffer*> getRingBuffers() const { return _ringBuffers; } AvatarAudioRingBuffer* getAvatarAudioRingBuffer() const; int parseData(const QByteArray& packet); void checkBuffersBeforeFrameSend(int jitterBufferLengthSamples); void pushBuffersAfterFrameSend(); private: QList<PositionalAudioRingBuffer*> _ringBuffers; }; #endif // hifi_AudioMixerClientData_h
26.815789
91
0.764475
[ "vector" ]
70b918eaafd0e520724a3efd7b650f9522755703
871
h
C
Engine/Graphics/World/ShadowMapping.h
i0r/huisclos
930c641ab64f1deff4c15a6e1617fc596cf8118f
[ "X11" ]
null
null
null
Engine/Graphics/World/ShadowMapping.h
i0r/huisclos
930c641ab64f1deff4c15a6e1617fc596cf8118f
[ "X11" ]
null
null
null
Engine/Graphics/World/ShadowMapping.h
i0r/huisclos
930c641ab64f1deff4c15a6e1617fc596cf8118f
[ "X11" ]
null
null
null
#pragma once struct texture_t; struct renderContext_t; class TextureManager; #include <Engine/Graphics/LightManager.h> #include <Engine/Graphics/Mesh.h> #include <Engine/Graphics/CBuffer.h> class ShadowMapping { public: ShadowMapping(); ShadowMapping( ShadowMapping& ) = delete; ~ShadowMapping() = default; void Destroy(); const int Create( const renderContext_t* context ); void RenderDiskAreaLight( const renderContext_t* context, const mesh_t* mesh, const diskAreaLight_t& light ); void RenderSun( const renderContext_t* context, sunLight_t& sun ); private: ID3D11VertexShader* vertexShader; ID3D11PixelShader* pixelShader; ID3D11InputLayout* shaderLayout; ID3D11SamplerState* samplerState; struct { DirectX::XMMATRIX lightMatrix; DirectX::XMMATRIX modelMatrix; } matricesData; CBuffer matricesCbuffer; };
22.921053
115
0.750861
[ "mesh" ]
70cd26b8fc1f8d480374ec642a4f7c6751d7bd3e
4,827
h
C
examples/ConstraintIB/falling_sphere/ForceProjector.h
akashdhruv/IBAMR
a2b47946d795fb5a40c181b43e44a6ec387585a9
[ "BSD-3-Clause" ]
264
2015-01-04T12:11:02.000Z
2022-03-31T13:10:37.000Z
examples/ConstraintIB/falling_sphere/ForceProjector.h
syam-s/IBAMR
b6502f2f818835961d103fd2a2827d9336e68640
[ "BSD-3-Clause" ]
1,057
2015-04-27T04:27:57.000Z
2022-03-31T13:14:59.000Z
examples/ConstraintIB/falling_sphere/ForceProjector.h
drwells/IBAMR
0ceda3873405a35da4888c99e7d2b24d132f9071
[ "BSD-3-Clause" ]
126
2015-02-13T15:36:02.000Z
2022-03-27T21:59:50.000Z
// --------------------------------------------------------------------- // // Copyright (c) 2016 - 2019 by the IBAMR developers // All rights reserved. // // This file is part of IBAMR. // // IBAMR is free software and is distributed under the 3-clause BSD // license. The full text of the license can be found in the file // COPYRIGHT at the top level directory of IBAMR. // // --------------------------------------------------------------------- /////////////////////// INCLUDE GUARD //////////////////////////////////// #ifndef included_ForceProjector #define included_ForceProjector ///////////////////////////// INCLUDES /////////////////////////////////// #include <ibtk/LData.h> #include <ibtk/LDataManager.h> #include <tbox/Database.h> #include <tbox/Pointer.h> #include <PatchHierarchy.h> #include <SideVariable.h> #include <VariableContext.h> #include <string> namespace IBTK { /*! * Pre processing call back function to be hooked into IBAMR::INSStaggeredHierachyIntegrator class. * * \param current_time is the time at t_n. * \param new_time is the time at t_n+1 = t_n + dt. * \param cycle_num is the cycle of predictor-corrector scheme. * \param ctx is the pointer to IBTK::ForceProjector class object. */ void callForceProjectorCallBackFunction(const double current_time, const double new_time, const int cycle_num, void* ctx); /*! * \brief Class ForceProjector is a utility class which projects force from * Lagrangian points onto the background mesh. * */ class ForceProjector { public: /*! * \brief Constructor. */ ForceProjector(const std::string& object_name, IBTK::LDataManager* lag_data_manager, SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > patch_hierarchy, SAMRAI::tbox::Pointer<SAMRAI::tbox::Database> input_db, const std::string solver_type = "STAGGERED"); /*! * \brief Destructor. */ ~ForceProjector(); /*! * \brief Register the name of Lagrangian quantities to be used to calculate forces on Lagrangian * points. */ void registerLagrangianQuantityName(const std::string& lag_quantity_name); void registerLagrangianQuantitiesName(const std::vector<std::string>& lag_quantities_name); /*! * \brief Register volume associated with each material point. */ void associateVolumeElement(const double vol_lag_pt); /*! * \brief Calculate forcing on Lagrangian points. */ void calculateLagrangianBodyForce(const double new_time, const double current_time); /*! * \brief Spread the Lagrangian forcing on the background mesh. */ void calculateEulerianBodyForce(const double new_time, const double current_time); /*! * \brief Get the patch index associated with Eulerian force. */ inline int getEulerianForcePatchDataIndex() const { return d_body_force_idx; } // getEulerianForcePatchDataIndex private: /*! * \brief Default constructor is not implemented and should not be used. */ ForceProjector(); /*! * Default assignment operator is not implemented and should not be used. */ ForceProjector& operator=(const ForceProjector& that); /*! * \brief Default copy constructor is not implemented and should not be used. */ ForceProjector(const ForceProjector& from); /*! * \brief Get the values from input_db. */ void getFromInput(SAMRAI::tbox::Pointer<SAMRAI::tbox::Database> input_db); /*! * Name of this object. */ std::string d_object_name; /*! * Pointer to LDataManager. */ IBTK::LDataManager* d_lag_data_manager; /*! * Pointer to Patch Hierarchy. */ SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > d_patch_hierarchy; /*! * Fluid solver type. */ std::string d_solver_type; /*! * Pointer to Lagrangian force data. */ std::vector<SAMRAI::tbox::Pointer<IBTK::LData> > d_lag_force; /*! * Variables and variable context associated with calculating Eulerian force. */ SAMRAI::tbox::Pointer<SAMRAI::hier::Variable<NDIM> > d_body_force_var; SAMRAI::tbox::Pointer<SAMRAI::hier::VariableContext> d_body_force_context; int d_body_force_idx; /*! * Name of Lagrangian quantities to be used in calculating forces. */ std::vector<std::string> d_lag_quantities_name; /*! * Volume associated with each element. */ double d_vol_lag_pt; /*! * Densities of fluid and body. */ double d_rho_fluid, d_rho_body; /*! * Gravitational force constants. */ SAMRAI::tbox::Array<double> d_grav_const; }; // ForceProjector } // namespace IBTK #endif // #ifndef included_ForceProjector
27.117978
117
0.635384
[ "mesh", "object", "vector" ]
70d3c6882901649527d07ddb383ae3d0952281d9
968
h
C
Absorption.h
NadjaLessing/OscProb
78c0576fe942167d63dab1e4c0a386c5424ab62a
[ "MIT" ]
11
2017-06-13T15:51:29.000Z
2021-05-21T13:10:08.000Z
Absorption.h
NadjaLessing/OscProb
78c0576fe942167d63dab1e4c0a386c5424ab62a
[ "MIT" ]
5
2017-09-29T05:03:22.000Z
2022-02-25T12:03:57.000Z
Absorption.h
NadjaLessing/OscProb
78c0576fe942167d63dab1e4c0a386c5424ab62a
[ "MIT" ]
13
2017-12-20T14:36:52.000Z
2022-03-16T13:56:53.000Z
//#ifndef Absorption //#define Absorption #include "NuPath.h" #include <vector> #include <numeric> #include <iterator> #include <iostream> namespace OscProb { class Absorption{ public: Absorption(); virtual ~Absorption(); //virtual double Trans(int flvi, double E); virtual double Trans(double xsec); virtual void SetPath(std::vector<OscProb::NuPath> paths); ///< Set a path sequence protected: std::vector<OscProb::NuPath> fNuPaths; ///< Vector of neutrino paths // Set the neutrino path //virtual void SetPath(OscProb::NuPath p); ///< Set a single path //virtual void SetPath(double length, double density, // double zoa=0.5, int layer=0); ///< Set a single path //virtual void SetPath(std::vector<OscProb::NuPath> paths); ///< Set a path sequence static const double kNA; //Avogardo constant static const double kU; //atomich mass unit }; }
27.657143
89
0.640496
[ "vector" ]
70d8b5da20f8f17670608f5b38f2b0da8d47378a
266,516
c
C
eurasia/tools/intern/usc2/groupinst.c
shaqfu786/GFX_Linux_DDK
f184ac914561fa100a5c92a488df777de8785f93
[ "FSFAP" ]
3
2020-03-13T23:37:00.000Z
2021-09-03T06:34:04.000Z
eurasia/tools/intern/usc2/groupinst.c
zzpianoman/GFX_Linux_DDK
f184ac914561fa100a5c92a488df777de8785f93
[ "FSFAP" ]
null
null
null
eurasia/tools/intern/usc2/groupinst.c
zzpianoman/GFX_Linux_DDK
f184ac914561fa100a5c92a488df777de8785f93
[ "FSFAP" ]
6
2015-02-05T03:01:01.000Z
2021-07-24T01:07:18.000Z
/****************************************************************************** * Name : groupinst.c * Title : Instruction grouping and other MOE setup * Created : May 2005 * * Copyright : 2002-2007 by Imagination Technologies Limited. * : All rights reserved. No part of this software, either * : material or conceptual may be copied or distributed, * : transmitted, transcribed, stored in a retrieval system or * : translated into any human or computer language in any form * : by any means, electronic, mechanical, manual or otherwise, * : or disclosed to third parties without the express written * : permission of Imagination Technologies Limited, * : Home Park Estate, Kings Langley, Hertfordshire, * : WD4 8LZ, U.K. * * Modifications:- * $Log: groupinst.c $ * * Fixed assert on instructions partially writing an index register. * --- Revision Logs Removed --- * of 4. * --- Revision Logs Removed --- *****************************************************************************/ #include "uscshrd.h" #include "bitops.h" #define MOE_OPERAND_DEST (0) #define MOE_OPERAND_DEST_MASK (1U << MOE_OPERAND_DEST) #define MOE_OPERAND_SRC0 (1) #define MOE_OPERAND_SRC0_MASK (1U << MOE_OPERAND_SRC0) #define MOE_OPERAND_SRC1 (2) #define MOE_OPERAND_SRC1_MASK (1U << MOE_OPERAND_SRC1) #define MOE_OPERAND_SRC2 (3) #define MOE_OPERAND_SRC2_MASK (1U << MOE_OPERAND_SRC2) #define MOE_OPERAND_SOURCES_MASK (MOE_OPERAND_SRC0_MASK | MOE_OPERAND_SRC1_MASK | MOE_OPERAND_SRC2_MASK) typedef struct _SMLSI_STATE { IMG_BOOL pbInvalid[4]; MOE_DATA psMoeData[4]; } SMLSI_STATE, *PSMLSI_STATE; typedef struct _SMBO_STATE { IMG_BOOL pbInvalidBaseOffsets[USC_MAX_MOE_OPERANDS]; IMG_UINT32 puBaseOffsets[USC_MAX_MOE_OPERANDS]; } SMBO_STATE, *PSMBO_STATE; /* Possible states for the MOE flags affecting whether U8/C10 or F16/F32 format selects are enabled for colour instructions and EFO instruction respectively. */ typedef enum { FORMAT_CONTROL_FLAG_ON, FORMAT_CONTROL_FLAG_OFF, FORMAT_CONTROL_FLAG_UNDEFINED, } FORMAT_CONTROL_FLAG; /* Format select flags supported by the MOE. */ typedef enum { FORMAT_CONTROL_FLAG_TYPE_EFO = 0, FORMAT_CONTROL_FLAG_TYPE_COLOUR = 1, FORMAT_CONTROL_FLAG_TYPE_COUNT = 2, } FORMAT_CONTROL_FLAG_TYPE; typedef struct _SETFC_STATE { FORMAT_CONTROL_FLAG_TYPE aeFlag[FORMAT_CONTROL_FLAG_TYPE_COUNT]; } SETFC_STATE, *PSETFC_STATE; /* USC_SMSLI_STATE_DEFAULT_VALUE: The default SMLSI state */ #define USC_SMSLI_STATE_DEFAULT_VALUE \ { \ {IMG_FALSE, IMG_FALSE, IMG_FALSE, IMG_FALSE}, /* pbInvalid */ \ {USC_MOE_DATA_DEFAULT_VALUE, USC_MOE_DATA_DEFAULT_VALUE, /* psMoeData */ \ USC_MOE_DATA_DEFAULT_VALUE, USC_MOE_DATA_DEFAULT_VALUE}, \ } static const SMLSI_STATE sDefaultSmsliState = USC_SMSLI_STATE_DEFAULT_VALUE; /* DEFAULT_GROUP_TRIGGER: The number of instructions normally needed to form a group. */ #define DEFAULT_GROUP_TRIGGER (3) /* MIN_GROUP_TRIGGER: The absolute minimum number of instructions needed to form a group. */ #define MIN_GROUP_TRIGGER (2) /* USC_MAX_SMALL_INCREMENT_INC: Maximum increment when using reduced grouping (selected by cli option -mingroup). */ #define USC_MAX_SMALL_INCREMENT_INC (1) /* USC_MIN_SMALL_INCREMENT_INC: Minimum increment when using reduced grouping. (selected by cli option -mingroup). */ #define USC_MIN_SMALL_INCREMENT_INC (0) /* GROUPINST_STATE: Instruction grouping data. */ typedef struct _GROUPINST_FUNCSTATE { /* TRUE if a call to the function has been encountered in the program so far. */ IMG_BOOL bUsed; /* Accumulated MOE state at the start of the function. */ IMG_PVOID pvInitialState; } GROUPINST_FUNCSTATE, *PGROUPINST_FUNCSTATE; typedef struct _GROUPINST_STATE { /* Points to state for each function. */ PGROUPINST_FUNCSTATE asFunc; /* asInstGroupData: Instructions linked by opcodes */ PINST asInstGroup[IOPCODE_MAX]; /* UseDef record */ USEDEF_RECORD sUseDef; } GROUPINST_STATE, *PGROUPINST_STATE; #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) typedef struct { /* If TRUE this is a repeat of dotproduct (VDP_CP/VDP_GPI) instructions. */ IMG_BOOL bDotProduct; /* Increment mode to use for the repeat. */ SVEC_REPEATMODE eRepeatMode; } SINGLEISSUE_VECTOR_STATE, *PSINGLEISSUE_VECTOR_STATE; #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ typedef struct { /* If TRUE this instruction can use MOE increments directly specified in the instruction encoding. */ IMG_BOOL bInstMoeIncrement; /* If TRUE this instruction only uses MOE increments from the instruction encoding. */ IMG_BOOL bNeverUseMoe; /* Mode and increment/swizzle needed to group each operand. */ MOE_DATA psMoeData[USC_MAX_MOE_OPERANDS]; /* Set to TRUE if each instruction in the group has a different predicate. */ IMG_BOOL bPredModN; /* Set to TRUE if the instruction is a dotproduct. */ IMG_BOOL bDotProduct; /* Set to TRUE if the instruction is a double dotproduct. */ IMG_BOOL bDoubleDotProduct; /* First instruction in the repeat. */ PINST psFirstInst; /* Last instruction in the repeat. */ PINST psLastInst; /* Count of the operands (including the destination) used by instructions in the repeat. */ IMG_UINT32 uArgCount; /* Bit mask of operands not used by the instructions in the repeat. Indexed by instruction operand index. */ IMG_UINT32 uDontCareMask; /* Bit mask of operands which are in the special constant bank and point to the start of a run of constants with the same value. */ IMG_UINT32 uSpecialConstMask; /* Length of the run of constants with the same value. */ IMG_UINT32 uSpecialConstGroupLimit; /* Offset to use for the dotproduct destination in a repeated instruction. */ IMG_UINT32 uNewDPDestNum; /* Count of instructions in the repeat. */ IMG_UINT32 uInstCount; /* A pointer to each instruction in the repeat. */ PINST apsInst[EURASIA_USE_MAXIMUM_REPEAT]; #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) /* TRUE if this repeat is for single-issue vector instruction. */ IMG_BOOL bSVecInst; /* Increment data that will be only used for repeats that are not using moe mode. */ MOE_DATA psIncData[USC_MAX_MOE_OPERANDS]; /* State specific to making repeats from the single-issue vector instructions. */ SINGLEISSUE_VECTOR_STATE sVec; #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ } CANDIDATE_GROUP_DATA, *PCANDIDATE_GROUP_DATA; IMG_INTERNAL IMG_BOOL TypeUsesFormatControl(IMG_UINT32 uType) /***************************************************************************** FUNCTION : TypeUsesFormatControl PURPOSE : Checks if a register is one that is affected by the format control. PARAMETERS : uType - The type to check. RETURNS : IMG_TRUE or IMG_FALSE. *****************************************************************************/ { if (uType == USEASM_REGTYPE_TEMP || uType == USEASM_REGTYPE_PRIMATTR || uType == USEASM_REGTYPE_SECATTR || uType == USEASM_REGTYPE_OUTPUT || uType == USEASM_REGTYPE_FPINTERNAL || uType == USC_REGTYPE_REGARRAY) { return IMG_TRUE; } return IMG_FALSE; } static IMG_BOOL GetMOEDestIdx(PINST psInst) /***************************************************************************** FUNCTION : GetMOEDestIdx PURPOSE : Check for an instruction not affected by the destination MOE state. PARAMETERS : psInst - Instruction to check. RETURNS : TRUE or FALSE. *****************************************************************************/ { IMG_UINT32 uMOEDestIdx; if ((g_psInstDesc[psInst->eOpcode].uFlags2 & DESC_FLAGS2_TEST) != 0) { if (g_psInstDesc[psInst->eOpcode].uFlags & DESC_FLAGS_VECTORDEST) { uMOEDestIdx = VTEST_UNIFIEDSTORE_DESTIDX; } else { uMOEDestIdx = TEST_UNIFIEDSTORE_DESTIDX; } } else { uMOEDestIdx = 0; } if (uMOEDestIdx >= psInst->uDestCount) { return USC_UNDEF; } return uMOEDestIdx; } static IMG_BOOL HasMOEDest(PINST psInst) /***************************************************************************** FUNCTION : HasMOEDest PURPOSE : Check for an instruction not affected by the destination MOE state. PARAMETERS : psInst - Instruction to check. RETURNS : TRUE or FALSE. *****************************************************************************/ { return (GetMOEDestIdx(psInst) != USC_UNDEF) ? IMG_TRUE : IMG_FALSE; } static IMG_BOOL Src0AliasesDest(PINTERMEDIATE_STATE psState, PINST psInst) /***************************************************************************** FUNCTION : Src0AliasesDest PURPOSE : Check for an instruction where source 0 and the destination must use the same MOE state. PARAMETERS : psState - Compiler state. psInst - Instruction to check. RETURNS : TRUE or FALSE. *****************************************************************************/ { IMG_UINT32 uDestMask; PVR_UNREFERENCED_PARAMETER(psState); /* No aliasing for an instruction with no destinations. */ if (!HasMOEDest(psInst)) { return IMG_FALSE; } #if defined(OUTPUT_USPBIN) /* The USP will handle masking for these texture sample instructions when it expands them. */ if ( ( (psInst->eOpcode >= ISMP_USP) && (psInst->eOpcode <= ISMP_USP_NDR) ) || (psInst->eOpcode == ISMPUNPACK_USP) ) { return IMG_FALSE; } #endif /* defined(OUTPUT_USPBIN) */ /* This instruction supports masking on the destination without requiring the MOE state for the destination and source 0 to be the same. */ if ((g_psInstDesc[psInst->eOpcode].uFlags2 & DESC_FLAGS2_DESTMASKNOSRC0) != 0) { return IMG_FALSE; } #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) if (g_psInstDesc[psInst->eOpcode].uFlags & DESC_FLAGS_VECTORDEST) { IMG_UINT32 uDestIdx; for (uDestIdx = 0; uDestIdx < psInst->uDestCount; uDestIdx++) { if (psInst->auDestMask[uDestIdx] != 0 && psInst->auDestMask[uDestIdx] != USC_ALL_CHAN_MASK) { return IMG_TRUE; } } return IMG_FALSE; } #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ uDestMask = psInst->auDestMask[0]; #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) if (g_psInstDesc[psInst->eOpcode].uFlags & DESC_FLAGS_C10VECTORDEST) { ASSERT(psInst->uDestCount == 1 || psInst->uDestCount == 2); if (psInst->uDestCount > 1 && (psInst->auDestMask[1] & USC_RED_CHAN_MASK) != 0) { uDestMask |= USC_ALPHA_CHAN_MASK; } } #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ return (uDestMask != USC_ALL_CHAN_MASK) ? IMG_TRUE : IMG_FALSE; } static IMG_BOOL ConvertIncrementToSwizzle(PINTERMEDIATE_STATE psState, PMOE_DATA psMoeData, IMG_UINT32 uGroupCount) /***************************************************************************** FUNCTION : ConvertIncrementToSwizzle PURPOSE : Check if an argument which has been repeated using MOE increment mode to MOE swizzle mode. PARAMETERS : psState - Compiler state. psMoeData - MOE state. uGroupCount - Count of instructions in the repeat. RETURNS : IMG_TRUE or IMG_FALSE. *****************************************************************************/ { IMG_INT32 iIncrement; IMG_UINT32 uIteration; ASSERT(psMoeData->eOperandMode == MOE_INCREMENT); iIncrement = psMoeData->u.iIncrement; /* Check if the existing increments can be represented using swizzle mode. */ if (uGroupCount >= USC_MAX_SWIZZLE_SLOTS) { return IMG_FALSE; } if ((labs(iIncrement) * uGroupCount) > USC_MAX_SWIZZLE_INC) { return IMG_FALSE; } /* Fill out the swizzle entries from the increment. */ psMoeData->eOperandMode = MOE_SWIZZLE; if (iIncrement >= 0) { for (uIteration = 0; uIteration <= uGroupCount; uIteration++) { psMoeData->u.s.auSwizzle[uIteration] = iIncrement * uIteration; } psMoeData->u.s.uLargest = iIncrement * uGroupCount; } else { for (uIteration = 0; uIteration <= uGroupCount; uIteration++) { psMoeData->u.s.auSwizzle[uIteration] = (-iIncrement) * (uGroupCount - uIteration); } psMoeData->u.s.uLargest = (-iIncrement) * uGroupCount; } return IMG_TRUE; } static IMG_BOOL CheckArgSwizzleMode(IMG_UINT32 uFirstRegNumber, IMG_UINT32 uNextRegNumber, IMG_UINT32 uIterationIndex, PMOE_DATA psMoeData) /***************************************************************************** FUNCTION : CheckArgSwizzleMode PURPOSE : Check if an instruction argument could be included in an existing repeat which is already using MOE swizzle mode. PARAMETERS : uFirstRegNumber - Register number for the argument to the first instruction. uNextRegNumber - Register number for the argument to the instruction we are trying to add to the repeat. uIterationIndex - Index of the MOE iteration to check for. psMoeData - Existing MOE state for the argument. RETURNS : IMG_TRUE or IMG_FALSE. *****************************************************************************/ { IMG_INT32 iJump; IMG_UINT32 uPrevOffset; IMG_UINT32 uPrevLargest; IMG_UINT32 uNewLargest; IMG_UINT32 uNewSwizzle; IMG_UINT32 uBaseRegister; IMG_UINT32 uNewBaseReg; IMG_UINT32 uNewOffset; IMG_UINT32 uOffsetDiff; IMG_UINT32 uAbsJump; IMG_UINT32 i; /* First operand is in swizzle mode */ /* Get the distance between the previous and the current instructions */ iJump = uNextRegNumber - uFirstRegNumber; /* The previous largest increment, from the last swizzle value */ uPrevLargest = psMoeData->u.s.uLargest; /* The previous offset from the first swizzle value (at index 0) */ uPrevOffset = psMoeData->u.s.auSwizzle[0]; /* Calculate the base register from the previous offset */ uBaseRegister = uFirstRegNumber - uPrevOffset; /* The non-negative jump (the distance from the first to the current register) */ uAbsJump = (iJump < 0) ? -iJump : iJump; /* Make sure there is a slot available */ if (uIterationIndex >= USC_MAX_SWIZZLE_SLOTS) { IMG_UINT32 uSlot; IMG_UINT32 uSwizzleSel; /* We are reusing a slot that is already used by a previous iteration so the swizzle selections match for both iterations. */ if (uNextRegNumber < uBaseRegister) { return IMG_FALSE; } uSlot = uIterationIndex % USC_MAX_SWIZZLE_SLOTS; uSwizzleSel = uNextRegNumber - uBaseRegister; if (psMoeData->u.s.auSwizzle[uSlot] != uSwizzleSel) { return IMG_FALSE; } return IMG_TRUE; } /* The new base register and difference to be added to the swizzle values */ if (uNextRegNumber < uBaseRegister) { uNewBaseReg = uNextRegNumber; uNewOffset = uAbsJump; uOffsetDiff = uNewOffset - uPrevOffset; } else { uNewBaseReg = uBaseRegister; uNewOffset = uPrevOffset; uOffsetDiff = 0; } /* The new swizzle */ uNewSwizzle = uNextRegNumber - uNewBaseReg; /* The new largest swizzle */ uNewLargest = uPrevLargest + uOffsetDiff; if (uNewLargest < uNewSwizzle) { uNewLargest = uNewSwizzle; } /* Test whether swizzle mode could continue */ if (USC_MIN_SWIZZLE_INC <= (IMG_INT32)uNewOffset && (IMG_INT32)uNewOffset <= USC_MAX_SWIZZLE_INC && USC_MIN_SWIZZLE_INC <= (IMG_INT32)uNewLargest && (IMG_INT32)uNewLargest <= USC_MAX_SWIZZLE_INC) { /* Swizzlable */ /* Store the largest distance. */ psMoeData->u.s.uLargest = uNewLargest; if (uNewOffset != uPrevOffset) { /* Rebuild the swizzle values array */ for (i = 0; i < uIterationIndex; i++) { /* Get the old swizzle increment */ psMoeData->u.s.auSwizzle[i] += uOffsetDiff; } } /* Store the last swizzle */ psMoeData->u.s.auSwizzle[uIterationIndex] = uNewSwizzle; /* Can include this instruction argument in the group. */ return IMG_TRUE; } else { /* Unswizzlable */ return IMG_FALSE; } } static IMG_BOOL CheckArg(PINTERMEDIATE_STATE psState, PCANDIDATE_GROUP_DATA psGroup, PARG psFirstArg, PARG psNextArg, IMG_UINT32 uArg, IMG_UINT32 uIterationIndex, PMOE_DATA psMoeData) /***************************************************************************** FUNCTION : CheckArg PURPOSE : Check if two instruction arguments could be grouped together. PARAMETERS : psFirstInst - First instruction in the group psFirstArg - The argument from the first instruction in the group psNextArg - The argument from the candidate instruction. uArg - The index of the argument (0: dest, 1..n: src0..srcn) uIterationIndex - INPUT/OUTPUT: psMoeData - MOE data for instructions already grouped. OUTPUT: pbSwizzle - Whether an operand switches to swizzle mode. RETURNS : IMG_TRUE if the arguments could be grouped; IMG_FALSE if they couldn't. *****************************************************************************/ { IMG_INT32 iMinIncrement, iMaxIncrement; IMG_INT32 iMinSwizzle, iMaxSwizzle; IMG_UINT32 uFirstRegNum, uNextRegNum; /* Instructions with different arguments can't be grouped. */ if (psNextArg->uType != psFirstArg->uType || psNextArg->uIndexType != psFirstArg->uIndexType || psNextArg->uIndexNumber != psFirstArg->uIndexNumber || (psNextArg->eFmt != psFirstArg->eFmt)) { return IMG_FALSE; } uFirstRegNum = psFirstArg->uNumber; uNextRegNum = psNextArg->uNumber; /* Immediate arguments aren't affected by the MOE increments. Index registers used as destinations aren't affected by MOE increments */ if (psFirstArg->uType == USEASM_REGTYPE_IMMEDIATE || (psFirstArg->uType == USEASM_REGTYPE_INDEX && uArg == 0)) { if (uFirstRegNum != uNextRegNum) { return IMG_FALSE; } psMoeData->eOperandMode = MOE_INCREMENT; psMoeData->u.iIncrement = 0; return IMG_TRUE; } /* Set the minimum and maximum increments and swizzles for each chip */ if (psGroup->bInstMoeIncrement) { /* SGX545 increments and swizzles */ iMinIncrement = USC_MIN_SMALL_INCREMENT_INC; iMaxIncrement = USC_MAX_SMALL_INCREMENT_INC; iMinSwizzle = USC_MIN_SWIZZLE_INC; iMaxSwizzle = USC_MAX_SWIZZLE_INC; } else { /* Other chip increments and swizzles */ iMinIncrement = USC_MIN_INCREMENT_INC; iMaxIncrement = USC_MAX_INCREMENT_INC; iMinSwizzle = USC_MIN_SWIZZLE_INC; iMaxSwizzle = USC_MAX_SWIZZLE_INC; } /* Two instructions which have all their arguments of the same type can always be grouped by changing the macro operation expander increments or swizzles. */ if (uIterationIndex == 1) { /* First and second instructions in the group. Set mode to increment. */ psMoeData->eOperandMode = MOE_INCREMENT; psMoeData->u.iIncrement = uNextRegNum - uFirstRegNum; /* Check for an increment outside the ranges supported by the hardware. */ if (psMoeData->u.iIncrement < iMinIncrement || psMoeData->u.iIncrement > iMaxIncrement) { IMG_INT32 iIncr = psMoeData->u.iIncrement; IMG_UINT32 uAbsIncr; uAbsIncr = (iIncr < 0) ? -iIncr : iIncr; /* Check for a swizzle outside the range */ if (uAbsIncr < (IMG_UINT32)iMinSwizzle || uAbsIncr > (IMG_UINT32)iMaxSwizzle) { return IMG_FALSE; } else { IMG_UINT32 uSwizzle1, uSwizzle2; IMG_UINT32 uLargest; /* Switch to swizzle mode */ psMoeData->eOperandMode = MOE_SWIZZLE; /* Work out the swizzles */ if (iIncr < 0) { /* Negative swizzle */ uSwizzle1 = uAbsIncr; uSwizzle2 = 0; } else { /* Positive swizzle */ uSwizzle1 = 0; uSwizzle2 = uAbsIncr; } psMoeData->u.s.auSwizzle[0] = uSwizzle1; psMoeData->u.s.auSwizzle[1] = uSwizzle2; uLargest = max(uSwizzle1, uSwizzle2); psMoeData->u.s.uLargest = uLargest; } } } else { /* Instructions after the first two in the group */ /* Get the distance between the previous and the current instructions */ IMG_INT32 iJump = uNextRegNum - uFirstRegNum; switch (psMoeData->eOperandMode) { case MOE_INCREMENT: { /* First operand is in increment mode */ if (iJump != ((IMG_INT32)uIterationIndex * psMoeData->u.iIncrement)) { /* Increments differ so can't continue this group in increment mode, try to switch to swizzle. */ if (!ConvertIncrementToSwizzle(psState, psMoeData, uIterationIndex - 1)) { return IMG_FALSE; } if (!CheckArgSwizzleMode(uFirstRegNum, uNextRegNum, uIterationIndex, psMoeData)) { /* Can't switch to swizzle mode so end the group */ return IMG_FALSE; } } break; } case MOE_SWIZZLE: { if (!CheckArgSwizzleMode(uFirstRegNum, uNextRegNum, uIterationIndex, psMoeData)) { /* Can't add this instruction to the group. */ return IMG_FALSE; } break; } default: { /* Operand is not in increment or swizzle mode. End grouping. */ return IMG_FALSE; } } } /* The instructions group. */ return IMG_TRUE; } static IMG_BOOL IsDoubleDotProduct(PINST psInst, IMG_PBOOL pbLast, IMG_BOOL bRotateArgs) /***************************************************************************** FUNCTION : IsDoubleDotProduct PURPOSE : Is this instruction part of a double dot-product. PARAMETERS : psInst - Instruction to check. pbLast - Set to TRUE if this is the last instruction. RETURNS : True or false. *****************************************************************************/ { if (!bRotateArgs && !(psInst->u.psEfo->eM0Src0 == SRC0 && psInst->u.psEfo->eM0Src1 == SRC1 && psInst->u.psEfo->eM1Src0 == SRC0 && psInst->u.psEfo->eM1Src1 == SRC2)) { return IMG_FALSE; } if (bRotateArgs && !(psInst->u.psEfo->eM0Src0 == SRC0 && psInst->u.psEfo->eM0Src1 == SRC2 && psInst->u.psEfo->eM1Src0 == SRC1 && psInst->u.psEfo->eM1Src1 == SRC2)) { return IMG_FALSE; } if (!(psInst->u.psEfo->eA0Src0 == M0 && psInst->u.psEfo->eA0Src1 == I0 && psInst->u.psEfo->eA1Src0 == I1 && psInst->u.psEfo->eA1Src1 == M1)) { return IMG_FALSE; } if (psInst->u.psEfo->bA0RightNeg || psInst->u.psEfo->bA1LeftNeg) { return IMG_FALSE; } if (psInst->u.psEfo->bWriteI0 && psInst->u.psEfo->bWriteI1 && psInst->u.psEfo->eI0Src == A0 && psInst->u.psEfo->eI1Src == A1 && psInst->u.psEfo->bIgnoreDest) { return IMG_TRUE; } if (!psInst->u.psEfo->bIgnoreDest && !(psInst->u.psEfo->bWriteI0 && psInst->u.psEfo->bWriteI1) && (psInst->u.psEfo->bWriteI0 || psInst->u.psEfo->bWriteI1) && (psInst->u.psEfo->eDSrc == A0 || psInst->u.psEfo->eDSrc == A1)) { EFO_SRC eOtherSrc = psInst->u.psEfo->bWriteI0 ? psInst->u.psEfo->eI0Src : psInst->u.psEfo->eI1Src; if ((eOtherSrc == A0 || eOtherSrc == A1) && (psInst->u.psEfo->eDSrc != eOtherSrc)) { *pbLast = IMG_TRUE; return IMG_TRUE; } } return IMG_FALSE; } static IMG_BOOL CheckPredicateSource(PINTERMEDIATE_STATE psState, PCANDIDATE_GROUP_DATA psGroup, PINST psFirstInst, PINST psNextInst, IMG_UINT32 uIterationIndex) /***************************************************************************** FUNCTION : CheckPredicateSource PURPOSE : Check whether two instructions have compatible source predicates allowing them both to be part of the same repeat. PARAMETERS : psState - Compiler state. psGroup - Information about the repeat. If this is the first instruction to be added then bPredNMod4 flag is set up. psFirstInst - First instruction in the repeat. psNextInst - Subsequent instruction in the repeat. uIterationIndex - Index of the subsequent instruction. RETURNS : TRUE if the instructions can be part of a repeat. *****************************************************************************/ { IMG_UINT32 uFirstInstPredSrc, uNextInstPredSrc; IMG_BOOL bFirstInstPredNeg, bNextInstPredNeg; IMG_BOOL bFirstInstPredPerChan, bNextInstPredPerChan; if (psFirstInst->uPredCount != psNextInst->uPredCount) { return IMG_FALSE; } if (psFirstInst->uPredCount == 0) { return IMG_TRUE; } GetPredicate(psFirstInst, &uFirstInstPredSrc, &bFirstInstPredNeg, &bFirstInstPredPerChan, 0); GetPredicate(psNextInst, &uNextInstPredSrc, &bNextInstPredNeg, &bNextInstPredPerChan, 0); if (bFirstInstPredPerChan || bNextInstPredPerChan) { return IMG_FALSE; } ASSERT(psFirstInst->uPredCount == 1 && psNextInst->uPredCount == 1); if (bFirstInstPredNeg != bNextInstPredNeg) { return IMG_FALSE; } if (uIterationIndex == 1) { /* For the first repeat set the predicate mode - either all the predicates must be equal or the predicate numbers must equal the iteration number mod 4. */ if (uNextInstPredSrc == uFirstInstPredSrc) { psGroup->bPredModN = IMG_FALSE; } else if (!GetBit(psFirstInst->auFlag, INST_PRED_NEG) && uFirstInstPredSrc == 0 && uNextInstPredSrc == 1 && GetInstPredicateSupport(psState, psFirstInst) == INST_PRED_EXTENDED) { psGroup->bPredModN = IMG_TRUE; } else { return IMG_FALSE; } } else { /* Check that this instruction uses the same predicate modes as the previous ones. */ if (psGroup->bPredModN) { if (uNextInstPredSrc != (uIterationIndex % 4)) { return IMG_FALSE; } } else { if (uNextInstPredSrc != uFirstInstPredSrc) { return IMG_FALSE; } } } return IMG_TRUE; } #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) static IMG_BOOL GetVDPSingleDestinationChannel(PINTERMEDIATE_STATE psState, PINST psInst, IMG_PUINT32 puWrittenChannel) /***************************************************************************** FUNCTION : GetVDPSingleDestinationChannel PURPOSE : Get the single channel (if there is just one) written by a single-issue vector dotproduct instruction. PARAMETERS : psState - Compiler state. psInst - Instruction to check. puWrittenChannel - Returns the index of the channel written in the array of instruction destinations. RETURNS : TRUE if the instruction only writes one channel; FALSE if it writes more than one. *****************************************************************************/ { IMG_UINT32 uWrittenChannel; IMG_UINT32 uDestIdx; /* Look for an instruction */ uWrittenChannel = USC_UNDEF; for (uDestIdx = 0; uDestIdx < psInst->uDestCount; uDestIdx++) { if (psInst->auDestMask[uDestIdx] != 0) { /* Instructions which are part of a repeat can only write one channel. */ if (uWrittenChannel != USC_UNDEF) { return IMG_FALSE; } uWrittenChannel = uDestIdx; } } ASSERT(uWrittenChannel != USC_UNDEF); *puWrittenChannel = uWrittenChannel; return IMG_TRUE; } static IMG_BOOL SetupVDPInstGroup(PINTERMEDIATE_STATE psState, PCANDIDATE_GROUP_DATA psGroup, PINST psFirstInst) /***************************************************************************** FUNCTION : SetupVDPInstGroup PURPOSE : Initializes information specific to making a repeated instruction from single-issue dotproducts. PARAMETERS : psState - Compiler state. psGroup - Information about the repeated instruction. psFirstInst - First instruction in the repeat. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 uDestIdx; /* Check the first instruction is writing the first channel only in its vector destination. */ if (!(GetVDPSingleDestinationChannel(psState, psFirstInst, &uDestIdx) && uDestIdx == 0)) { return IMG_FALSE; } /* Set default repeat mode. */ psGroup->sVec.eRepeatMode = SVEC_REPEATMODE_USEMOE; /* A repeat formed from dotproduct instructions. */ psGroup->sVec.bDotProduct = IMG_TRUE; return IMG_TRUE; } static IMG_VOID SetupVMADInstGroup(PCANDIDATE_GROUP_DATA psGroup) /***************************************************************************** FUNCTION : SetupMADInstGroup PURPOSE : Initializes information specific to making a repeated instruction from single-issue vector mad. PARAMETERS : psGroup - Information about the repeated instruction. RETURNS : Nothing. *****************************************************************************/ { /* Set default repeat mode. */ psGroup->sVec.eRepeatMode = SVEC_REPEATMODE_USEMOE; /* Not a repeat formed from dotproduct instructions. */ psGroup->sVec.bDotProduct = IMG_FALSE; } static IMG_BOOL CheckInstGroupVDP_NonMOEDest(PINTERMEDIATE_STATE psState, PINST psFirstInst, PINST psNextInst, IMG_UINT32 uIterationIndex) /***************************************************************************** FUNCTION : CheckInstGroupVDP_NonMOEDest PURPOSE : Checks if an instruction's destination is suitable for adding to repeated single-issue vector instruction using non-MOE mode. PARAMETERS : psState - Compiler state. psFirstInst - First instruction in the repeat. psNextInst - Instruction we are trying to add to the repeat. uIterationIndex - Iteration to add the instruction at. RETURNS : TRUE or FALSE. *****************************************************************************/ { IMG_UINT32 uWrittenChannel; PARG psFirstDest = &psFirstInst->asDest[0]; PARG psNextDest = &psNextInst->asDest[0]; IMG_UINT32 uChannelDifference; /* Check the new instruction is writing only a single channel in its vector destination and get the index of the written channel. */ if (!GetVDPSingleDestinationChannel(psState, psNextInst, &uWrittenChannel)) { return IMG_FALSE; } /* Check both instructions are writing the same type of destination. */ if (psFirstDest->uType != psNextDest->uType) { return IMG_FALSE; } /* Check the channels written by each iteration are consecutive 32-bit channels of an 128-bit vector. */ if (psFirstDest->uType == USEASM_REGTYPE_FPINTERNAL) { /* For GPI registers the register number is in 128-bit units. */ if (psFirstDest->uNumber != psNextDest->uNumber) { return IMG_FALSE; } uChannelDifference = uWrittenChannel; } else { IMG_UINT32 uChannelBase; /* For other register types the register nubmer is in 64-bit units. */ if (psFirstDest->uNumber > psNextDest->uNumber) { return IMG_FALSE; } uChannelBase = (psNextDest->uNumber - psFirstDest->uNumber) * (QWORD_SIZE / LONG_SIZE); uChannelDifference = uChannelBase + uWrittenChannel; } /* The channel written must the same as the current iteration. */ if (uChannelDifference != uIterationIndex) { return IMG_FALSE; } return IMG_TRUE; } static IMG_BOOL CheckInstGroupVDP(PINTERMEDIATE_STATE psState, PCANDIDATE_GROUP_DATA psGroup, PINST psFirstInst, PINST psNextInst, IMG_UINT32 uIterationIndex, PMOE_DATA psIncData) /***************************************************************************** FUNCTION : CheckInstGroupVDP PURPOSE : Checks if an instruction is suitable for adding to repeated single-issue vector instruction. PARAMETERS : psState - Compiler state. psGroup - Information about the repeated instruction. psFirstInst - First instruction in the repeat. psNextInst - Instruction we are trying to add to the repeat. uIterationIndex - Iteration to add the instruction at. psIncData - MOE state needed to group the operands. RETURNS : TRUE or FALSE. *****************************************************************************/ { IMG_UINT32 uSrcIdx; /* Check both instructions use the same opcode. */ if (psNextInst->eOpcode != psFirstInst->eOpcode) { return IMG_FALSE; } /* Check both instructions use the same predicate. */ if (!CheckPredicateSource(psState, psGroup, psFirstInst, psNextInst, uIterationIndex)) { return IMG_FALSE; } /* Get both instructions uses the same SKIPINVALID flag. */ if (GetBit(psFirstInst->auFlag, INST_SKIPINV) != GetBit(psNextInst->auFlag, INST_SKIPINV)) { return IMG_FALSE; } /* Check if we can add the instruction to this repeat using non-MOE mode for the destination. */ if (!CheckInstGroupVDP_NonMOEDest(psState, psFirstInst, psNextInst, uIterationIndex)) { return IMG_FALSE; } /* For VDP_CP check the difference in the written clipplane P-flag is the same as the iteration. */ if (psFirstInst->eOpcode == IVDP_CP) { if ((psFirstInst->u.psVec->uClipPlaneOutput + uIterationIndex) != psNextInst->u.psVec->uClipPlaneOutput) { return IMG_FALSE; } } for (uSrcIdx = 0; uSrcIdx < 2; uSrcIdx++) { IMG_UINT32 uVectorBaseArg = VEC_MOESOURCE_ARGINDEX(uSrcIdx); /* Check both instructions are using the same swizzles. */ if (psNextInst->u.psVec->auSwizzle[uSrcIdx] != psFirstInst->u.psVec->auSwizzle[uSrcIdx]) { return IMG_FALSE; } /* Check both instructions are using the same source modifiers. */ if (psNextInst->u.psVec->asSrcMod[uSrcIdx].bNegate != psFirstInst->u.psVec->asSrcMod[uSrcIdx].bNegate || psNextInst->u.psVec->asSrcMod[uSrcIdx].bAbs != psFirstInst->u.psVec->asSrcMod[uSrcIdx].bAbs) { return IMG_FALSE; } if (!CheckArg(psState, psGroup, &psFirstInst->asArg[uVectorBaseArg], &psNextInst->asArg[uVectorBaseArg], 1 + uSrcIdx /* uArg */, uIterationIndex, &psIncData[1 + uSrcIdx])) { return IMG_FALSE; } } return IMG_TRUE; } static IMG_BOOL CheckInstGroupVMAD(PINTERMEDIATE_STATE psState, PCANDIDATE_GROUP_DATA psGroup, PINST psFirstInst, PINST psNextInst, IMG_UINT32 uIterationIndex, PMOE_DATA psIncData) /***************************************************************************** FUNCTION : CheckInstGroupVMAD PURPOSE : Checks if an instruction is suitable for adding to repeated single-issue vector instruction. PARAMETERS : psState - Compiler state. psGroup - Information about the repeated instruction. psFirstInst - First instruction in the repeat. psNextInst - Instruction we are trying to add to the repeat. uIterationIndex - Iteration to add the instruction at. psIncData - MOE state needed to group the operands. RETURNS : TRUE or FALSE. *****************************************************************************/ { IMG_UINT32 uSrcIdx; IMG_UINT32 uSrcCount; IMG_UINT32 uDestIdx; /* Check both instructions use the same opcode. */ if (psNextInst->eOpcode != psFirstInst->eOpcode) { return IMG_FALSE; } /* Check both instructions use the same predicate. */ if (!CheckPredicateSource(psState, psGroup, psFirstInst, psNextInst, uIterationIndex)) { return IMG_FALSE; } /* Get both instructions uses the same SKIPINVALID flag. */ if (GetBit(psFirstInst->auFlag, INST_SKIPINV) != GetBit(psNextInst->auFlag, INST_SKIPINV)) { return IMG_FALSE; } /* Check both instructions have the same destination masks. */ if (psFirstInst->uDestCount != psNextInst->uDestCount) { return IMG_FALSE; } for (uDestIdx = 0; uDestIdx < psFirstInst->uDestCount; uDestIdx++) { if (psFirstInst->auDestMask[uDestIdx] != psNextInst->auDestMask[uDestIdx]) { return IMG_FALSE; } } /* Check whether the destination register number for the new instruction can be added to the repeat. */ if (!CheckArg(psState, psGroup, &psFirstInst->asDest[0], &psNextInst->asDest[0], 0 /* uArg */, uIterationIndex, &psIncData[0])) { return IMG_FALSE; } if (psFirstInst->eOpcode == IVMAD4) { uSrcCount = 3; } else { ASSERT(psFirstInst->eOpcode == IVMUL3 || psFirstInst->eOpcode == IVADD3); uSrcCount = 2; } for (uSrcIdx = 0; uSrcIdx < uSrcCount; uSrcIdx++) { IMG_UINT32 uVectorBaseArg = VEC_MOESOURCE_ARGINDEX(uSrcIdx); /* Check both instructions are using the same swizzles. */ if (psNextInst->u.psVec->auSwizzle[uSrcIdx] != psFirstInst->u.psVec->auSwizzle[uSrcIdx]) { return IMG_FALSE; } /* Check both instructions are using the same source modifiers. */ if (psNextInst->u.psVec->asSrcMod[uSrcIdx].bNegate != psFirstInst->u.psVec->asSrcMod[uSrcIdx].bNegate || psNextInst->u.psVec->asSrcMod[uSrcIdx].bAbs != psFirstInst->u.psVec->asSrcMod[uSrcIdx].bAbs) { return IMG_FALSE; } if (!CheckArg(psState, psGroup, &psFirstInst->asArg[uVectorBaseArg], &psNextInst->asArg[uVectorBaseArg], 1 + uSrcIdx /* uArg */, uIterationIndex, &psIncData[1 + uSrcIdx])) { return IMG_FALSE; } } return IMG_TRUE; } #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ static IMG_BOOL TryAddToGroup(PINTERMEDIATE_STATE psState, PCANDIDATE_GROUP_DATA psGroup, IMG_UINT32 uIterationIndex, PINST psFirstInst, PINST psNextInst) /***************************************************************************** FUNCTION : CheckInstGroup PURPOSE : Check if two instructions could be grouped together. PARAMETERS : psState - The compiler state psGroup - Information about the group. On success the MOE state required for the group is updated. psNextInst - The candidate instruction to be checked uIterationIndex - MOE iteration number for the candidate instruction. RETURNS : IMG_TRUE if the instructions could be grouped; IMG_FALSE if they couldn't. NOTES : If swizzle mode is selected for an operand r, the swizzle array is is constructed for a base register which is chosen as the smallest register in the sequence. The first value v in the swizzle array is the offset which must be removed from the first register r to calculate the number of the base register (r-v). *****************************************************************************/ { IMG_UINT32 i; IMG_UINT32 uMoeNumSrcArgs = g_psInstDesc[psFirstInst->eOpcode].uMoeArgumentCount; IMG_UINT32 uNumSrcArgs = psFirstInst->uArgumentCount; PMOE_DATA psMoeData = psGroup->psMoeData; MOE_DATA asNewMoeData[USC_MAX_MOE_OPERANDS]; #if defined(OUTPUT_USPBIN) if (psState->uFlags & USC_FLAGS_COMPILE_FOR_USPBIN) { if (IsInstReferingShaderResult(psState, psNextInst)) { /* Instruction is referencing a shader result so it can not be grouped with other instructions. */ return IMG_FALSE; } } #endif /* defined(OUTPUT_USPBIN) */ #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) /* Do special checks for single-issue vector instruction. */ if (psGroup->bSVecInst) { if (psGroup->sVec.bDotProduct) { return CheckInstGroupVDP(psState, psGroup, psFirstInst, psNextInst, uIterationIndex, psGroup->psIncData); } else { return CheckInstGroupVMAD(psState, psGroup, psFirstInst, psNextInst, uIterationIndex, psGroup->psIncData); } } #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ /* Instructions with different opcodes can't be grouped. */ if (!EqualInstructionModes(psState, psFirstInst, psNextInst)) { return IMG_FALSE; } /* Check operands, getting MOE data if operand works */ /* Set the default values of the MOE state needed for the new repeat from the MOE state for the existing repeat. */ memcpy(asNewMoeData, psMoeData, sizeof(asNewMoeData[0]) * USC_MAX_MOE_OPERANDS); /* Check any predicate source to the instruction. */ if (!CheckPredicateSource(psState, psGroup, psFirstInst, psNextInst, uIterationIndex)) { return IMG_FALSE; } /* The predicate destination for a test must be the same as the iteration number. */ if ((g_psInstDesc[psFirstInst->eOpcode].uFlags2 & DESC_FLAGS2_TEST) != 0 && !psGroup->bDotProduct) { PARG psPredDest; PARG psFirstPredDest; if (g_psInstDesc[psNextInst->eOpcode].uFlags & DESC_FLAGS_VECTORDEST) { ASSERT(psNextInst->uDestCount >= VTEST_PREDICATE_DESTIDX); psPredDest = &psNextInst->asDest[VTEST_PREDICATE_DESTIDX]; ASSERT(psPredDest->uType == USEASM_REGTYPE_PREDICATE); ASSERT(psFirstInst->uDestCount >= VTEST_PREDICATE_DESTIDX); psFirstPredDest = &psFirstInst->asDest[VTEST_PREDICATE_DESTIDX]; ASSERT(psFirstPredDest->uType == USEASM_REGTYPE_PREDICATE); } else { ASSERT(psNextInst->uDestCount >= TEST_PREDICATE_DESTIDX); psPredDest = &psNextInst->asDest[TEST_PREDICATE_DESTIDX]; ASSERT(psPredDest->uType == USEASM_REGTYPE_PREDICATE); ASSERT(psFirstInst->uDestCount >= TEST_PREDICATE_DESTIDX); psFirstPredDest = &psFirstInst->asDest[TEST_PREDICATE_DESTIDX]; ASSERT(psFirstPredDest->uType == USEASM_REGTYPE_PREDICATE); } if (psPredDest->uNumber != (psFirstPredDest->uNumber + uIterationIndex)) { return IMG_FALSE; } } /* Test destination if not a dotproduct */ { IMG_UINT32 uMOEDestIdx = GetMOEDestIdx(psFirstInst); if (uMOEDestIdx != USC_UNDEF) { if (!CheckArg(psState, psGroup, &psFirstInst->asDest[uMOEDestIdx], &psNextInst->asDest[uMOEDestIdx], 0, uIterationIndex, &asNewMoeData[0])) { return IMG_FALSE; } } } /* For texture samples all the destinations must have consecutive register numbers so it's enough to check that the numbers for the first destination can be made into a repeat. For FDDP the extra destination (always an internal register) isn't written until the last iteration anyway so ignore it. For other instructions the extra destinations represent fixed parameters which aren't affected by the MOE so check they are exactly equal. */ if ( (g_psInstDesc[psFirstInst->eOpcode].uFlags & (DESC_FLAGS_TEXTURESAMPLE | DESC_FLAGS_MULTIPLEDEST)) == 0 && !psGroup->bDotProduct && !psGroup->bDoubleDotProduct ) { IMG_UINT32 uDestIdx; ASSERT(psFirstInst->uDestCount == psNextInst->uDestCount); for (uDestIdx = 1; uDestIdx < psNextInst->uDestCount; uDestIdx++) { if (!EqualArgs(&psFirstInst->asDest[uDestIdx], &psNextInst->asDest[uDestIdx])) { return IMG_FALSE; } } } /* Test source operands */ for (i = 1; i < USC_MAX_MOE_OPERANDS; i++) { IMG_UINT32 uInstArg; uInstArg = MoeArgToInstArg(psState, psFirstInst, i - 1); if (uInstArg == DESC_ARGREMAP_DONTCARE || (uInstArg & DESC_ARGREMAP_ALIASMASK) != 0) { continue; } ASSERT(uInstArg < psFirstInst->uArgumentCount); if (!CheckArg(psState, psGroup, &psFirstInst->asArg[uInstArg], &psNextInst->asArg[uInstArg], i, uIterationIndex, &asNewMoeData[i])) { return IMG_FALSE; } } /* For extra sources whose register numbers can't be altered by the MOE just check that they are exactly equal for both instructions. */ for (i = uMoeNumSrcArgs; i < uNumSrcArgs; i++) { if (!EqualArgs(&psFirstInst->asArg[i], &psNextInst->asArg[i])) { return IMG_FALSE; } } /* Update the MOE state with the settings required to include this instruction in the repeat. */ memcpy(psMoeData, asNewMoeData, sizeof(asNewMoeData[0]) * USC_MAX_MOE_OPERANDS); return IMG_TRUE; } static IMG_UINT32 GetMaxAddressableRegNum(PINTERMEDIATE_STATE psState, PINST psInst, IMG_BOOL bDest, IMG_UINT32 uArgIdx, PARG psArg, IMG_BOOL bFormatControl, IMG_BOOL bF16FormatControl) /***************************************************************************** FUNCTION : GetMaxAddressableRegNum PURPOSE : Gets the maximum register number which can be directly encoded in an instruction. PARAMETERS : psState - Compiler state. psInst - Instruction to check. bDest - Is this the destination of an instruction. uArgIdx - Index of the source or destination to check. psArg - Points to the source or destination to check. bFormatControl - Whether the top-bit of the register number is used to select the format. bF16FormatControl - Whether the top-bit of the register number selects between F16 and F32 format. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 uRegisterNumberFieldBitCount; IMG_UINT32 uMaxAddressableRegNum; IMG_BOOL bTopBitIsFormatSel; PVR_UNREFERENCED_PARAMETER(uArgIdx); #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) if (psInst->eOpcode == IVMOVC_I32 || psInst->eOpcode == IVMOVCU8) { uMaxAddressableRegNum = SGXVEC_USE0_VMOVC_INT_REGISTER_NUMBER_MAX - 1; if (psArg->uType == USEASM_REGTYPE_TEMP) { uMaxAddressableRegNum -= EURASIA_USE_NUM_TEMPS_MAPPED_TO_FPI; } return uMaxAddressableRegNum; } #else PVR_UNREFERENCED_PARAMETER(psInst); PVR_UNREFERENCED_PARAMETER(psState); #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ /* Does the top-bit of the register number choose between two different interpretations of the register contents? In this case the maximum register number is reduced. */ bTopBitIsFormatSel = IMG_FALSE; if (bFormatControl && TypeUsesFormatControl(psArg->uType) && !(bDest && bF16FormatControl)) { bTopBitIsFormatSel = IMG_TRUE; } /* Indexed arguments have special restrictions on the maximum register number. */ if (psArg->uIndexType != USC_REGTYPE_NOINDEX) { if (bTopBitIsFormatSel) { return EURASIA_USE_FCINDEX_MAXIMUM_OFFSET; } else { return EURASIA_USE_INDEX_MAXIMUM_OFFSET; } } /* Get the width of the register number field in this instruction. */ if (bDest) { uRegisterNumberFieldBitCount = g_psInstDesc[psInst->eOpcode].uDestRegisterNumberBitCount; } else { uRegisterNumberFieldBitCount = g_psInstDesc[psInst->eOpcode].uSourceRegisterNumberBitCount; } /* Does the top-bit of the register number select between alternate interpretations of the register contents. */ if (bTopBitIsFormatSel) { uRegisterNumberFieldBitCount--; } /* What's the maximum register number that can be used in this instruction? */ uMaxAddressableRegNum = (1U << uRegisterNumberFieldBitCount) - 1; /* The top registers in the temporary bank are aliases for the internal registers. */ if (psArg->uType == USEASM_REGTYPE_TEMP) { uMaxAddressableRegNum -= EURASIA_USE_NUM_TEMPS_MAPPED_TO_FPI; } #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) /* Some vector instructions have special restrictions on one of their sources. */ if ((g_psInstDesc[psInst->eOpcode].uFlags2 & DESC_FLAGS2_WIDEVECTORSOURCE) != 0 && !bDest && uArgIdx == 1) { IMG_UINT32 uWideRegisterNumberMax; uWideRegisterNumberMax = SGXVEC_USE_VEC2_WIDE_USSOURCE_REGISTER_NUMBER_MAX; if (!(psInst->eOpcode == IVDUAL && !IsVDUALUnifiedStoreVectorSource(psState, psInst))) { uWideRegisterNumberMax >>= SGXVEC_USE_VEC2_REGISTER_NUMBER_ALIGNSHIFT; } uMaxAddressableRegNum = min(uMaxAddressableRegNum, uWideRegisterNumberMax); } #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ return uMaxAddressableRegNum; } static IMG_VOID GetArgumentFormatControlRequirements(PINTERMEDIATE_STATE psState, PINST psInst, IMG_BOOL bDest, IMG_UINT32 uArgIdx, PARG psArg, IMG_BOOL bF16FmtControl, IMG_PBOOL pbNeedsFmtCtrlOff, IMG_PBOOL pbNeedsFmtCtrlOn, IMG_PBOOL pbNeedsFmtCtrlDefined) /***************************************************************************** FUNCTION : GetArgumentFormatControlRequirements PURPOSE : Get the state of the format control required by an instruction argument. PARAMETERS : psState - Compiler state. psInst - Instruction to check. bDest - TRUE if the argument is the instruction destination. uArgIdx - Index of the argument to check. bF16FmtControl - TRUE if the format control for this instruction selects between F16 and F32 format registers. pbNeedsFmtCtrlOff - Set to TRUE if the argument requires the format control to be off. pbNeedsFmtCtrlOn - Set to TRUE if the argument requires the format control to be on. pbNeedsFmtCtrlDefined - Set to TRUE if the argument requires the format control to have a defined state. RETURNS : Nothing. *****************************************************************************/ { if (TypeUsesFormatControl(psArg->uType)) { UF_REGFORMAT eFormatCmtFmt; if (bF16FmtControl) { eFormatCmtFmt = UF_REGFORMAT_F16; } else { eFormatCmtFmt = UF_REGFORMAT_C10; } if (psArg->eFmt == eFormatCmtFmt) { /* If this argument is in the alternate format for the instruction then the MOE format control flag must be on. */ *pbNeedsFmtCtrlOn = IMG_TRUE; } else { IMG_UINT32 uMaxRegNum; /* If the register number for this argument is larger than the maximum number which is addressable when the MOE format control flag is on then switch the flag off. */ uMaxRegNum = GetMaxAddressableRegNum(psState, psInst, bDest, uArgIdx, psArg, IMG_TRUE /* bFormatControl */, bF16FmtControl); if (psArg->uNumber > uMaxRegNum) { *pbNeedsFmtCtrlOff = IMG_TRUE; } } /* For the fpinternal register bank the setting of the format control flag affects the encoding of the register number so it must have a defined value. */ if (pbNeedsFmtCtrlDefined != NULL) { if (psArg->uType == USEASM_REGTYPE_FPINTERNAL) { *pbNeedsFmtCtrlDefined = IMG_TRUE; } } } } static IMG_VOID GetFormatControlRequirements(PINTERMEDIATE_STATE psState, PINST psInst, IMG_PBOOL pbNeedsFmtCtrlOff, IMG_PBOOL pbNeedsFmtCtrlOn, IMG_PBOOL pbNeedsFmtCtrlDefined) /***************************************************************************** FUNCTION : GetFormatControlRequirements PURPOSE : Get the state of the format control required by an instruction. PARAMETERS : psState - Compiler state. psInst - Instruction to check. pbNeedsFmtCtrlOff - Set to TRUE if the instruction requires the format control to be off. pbNeedsFmtCtrlOn - Set to TRUE if the instruction requires the format control to be on. pbNeedsFmtCtrlDefined - Set to TRUE if the argument requires the format control to have a defined state. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 uMoeArg; IMG_BOOL bF16FmtControl; *pbNeedsFmtCtrlOff = IMG_FALSE; *pbNeedsFmtCtrlOn = IMG_FALSE; if (pbNeedsFmtCtrlDefined != NULL) { *pbNeedsFmtCtrlDefined = IMG_FALSE; } /* Get the type of alternate format for this instruction. */ if (psInst->eOpcode != IEFO) { bF16FmtControl = IMG_FALSE; } else { bF16FmtControl = IMG_TRUE; } /* Check if the destination needs the format control either on or off. */ if (psInst->eOpcode != IEFO && psInst->uDestCount > 0) { GetArgumentFormatControlRequirements(psState, psInst, IMG_TRUE /* bDest */, 0 /* uArgIdx */, &psInst->asDest[0], bF16FmtControl, pbNeedsFmtCtrlOff, pbNeedsFmtCtrlOn, pbNeedsFmtCtrlDefined); } /* For each source argument check whether it needs the format control either off or on. */ for (uMoeArg = 0; uMoeArg < (USC_MAX_MOE_OPERANDS - 1); uMoeArg++) { IMG_UINT32 uInstArg; uInstArg = MoeArgToInstArg(psState, psInst, uMoeArg); ASSERT(uInstArg != DESC_ARGREMAP_INVALID); /* Skip unreferenced arguments. */ if (uInstArg == DESC_ARGREMAP_DONTCARE || (uInstArg & DESC_ARGREMAP_ALIASMASK) != 0) { continue; } GetArgumentFormatControlRequirements(psState, psInst, IMG_FALSE /* bDest */, uInstArg, &psInst->asArg[uInstArg], bF16FmtControl, pbNeedsFmtCtrlOff, pbNeedsFmtCtrlOn, pbNeedsFmtCtrlDefined); } } static IMG_VOID InsertSetfcInstruction(PINTERMEDIATE_STATE psState, PCODEBLOCK psCodeBlock, PINST psInsertBeforeInst, PSETFC_STATE psMoeState) /***************************************************************************** FUNCTION : InsertSetfcInstruction PURPOSE : Add a SETFC instruction to a block. PARAMETERS : psState - Compiler state. psCodeBlock - The block to insert the instruction in. psInsertBeforeInst - Instruction to insert the SETFC instruction immediately before. psMoeState - State to set the format control enables to. RETURNS : Nothing. *****************************************************************************/ { PINST psSetfcInst; IMG_UINT32 uArg; ASSERT(psState->psMainProg->sCfg.psEntry);//->uType == CBTYPE_BASIC); psSetfcInst = AllocateInst(psState, psInsertBeforeInst); SetOpcode(psState, psSetfcInst, ISETFC); psSetfcInst->asDest[0].uType = USC_REGTYPE_DUMMY; psSetfcInst->asDest[0].uNumber = 0; for (uArg = 0; uArg < FORMAT_CONTROL_FLAG_TYPE_COUNT; uArg++) { PARG psArg = &psSetfcInst->asArg[uArg]; psArg->uType = USEASM_REGTYPE_IMMEDIATE; if (psMoeState->aeFlag[uArg] == FORMAT_CONTROL_FLAG_ON) { psArg->uNumber = 1; } else { ASSERT(psMoeState->aeFlag[uArg] == FORMAT_CONTROL_FLAG_OFF); psArg->uNumber = 0; } } InsertInstBefore(psState, psCodeBlock, psSetfcInst, psInsertBeforeInst); } static IMG_VOID CheckFormatControl(PINTERMEDIATE_STATE psState, PCODEBLOCK psCodeBlock, PINST psFirstInst, PSETFC_STATE psMoeState, IMG_BOOL bInsertInst) /***************************************************************************** FUNCTION : CheckFormatControl PURPOSE : Check if a SETFC instruction is needed before a instruction. PARAMETERS : psState - Compiler state. psCodeBlock - The block containing the instruction to be checked. psFirstInst - The instruction to be checked. psMoeState - The current state of the MOE bInsertInst - Whether to actually insert a SETFC instr (or just model state) RETURNS : Nothing. *****************************************************************************/ { if (psFirstInst->eOpcode == IEFO || HasC10FmtControl(psFirstInst)) { IMG_BOOL bNeedsFmtCtrlOn; IMG_BOOL bNeedsFmtCtrlOff; IMG_BOOL bNeedsFmtCtrlDefined; IMG_BOOL bNeedsSetFc = IMG_FALSE; FORMAT_CONTROL_FLAG_TYPE eType; FORMAT_CONTROL_FLAG_TYPE eOtherType; FORMAT_CONTROL_FLAG eFlag; /* Check if the instruction needs the format control either on or off. */ GetFormatControlRequirements(psState, psFirstInst, &bNeedsFmtCtrlOff, &bNeedsFmtCtrlOn, &bNeedsFmtCtrlDefined); ASSERT(!(bNeedsFmtCtrlOn && bNeedsFmtCtrlOff)); /* Check the format control flag used by this instruction type. */ if (psFirstInst->eOpcode == IEFO) { eType = FORMAT_CONTROL_FLAG_TYPE_EFO; eOtherType = FORMAT_CONTROL_FLAG_TYPE_COLOUR; } else { eType = FORMAT_CONTROL_FLAG_TYPE_COLOUR; eOtherType = FORMAT_CONTROL_FLAG_TYPE_EFO; } /* If this instruction needs a particular state of the format control check if either the current state is undefined or doesn't match the required state. */ eFlag = psMoeState->aeFlag[eType]; if ((bNeedsFmtCtrlOn || bNeedsFmtCtrlOff || bNeedsFmtCtrlDefined) && eFlag == FORMAT_CONTROL_FLAG_UNDEFINED) { bNeedsSetFc = IMG_TRUE; } if ((bNeedsFmtCtrlOn && eFlag == FORMAT_CONTROL_FLAG_OFF) || (bNeedsFmtCtrlOff && eFlag == FORMAT_CONTROL_FLAG_ON)) { bNeedsSetFc = IMG_TRUE; } /* Insert a setfc instruction if required. */ if (bNeedsSetFc) { static const FORMAT_CONTROL_FLAG aeDefaultFlag[FORMAT_CONTROL_FLAG_TYPE_COUNT] = { FORMAT_CONTROL_FLAG_OFF, /* FORMAT_CONTROL_FLAG_TYPE_EFO */ FORMAT_CONTROL_FLAG_ON, /* FORMAT_CONTROL_FLAG_TYPE_COLOUR */ }; /* Set the new state required by this instruction. */ if (bNeedsFmtCtrlOn) { psMoeState->aeFlag[eType] = FORMAT_CONTROL_FLAG_ON; } else if (bNeedsFmtCtrlOff) { psMoeState->aeFlag[eType] = FORMAT_CONTROL_FLAG_OFF; } else { ASSERT(bNeedsFmtCtrlDefined); psMoeState->aeFlag[eType] = aeDefaultFlag[eType]; } /* If the other format control flag has an undefined state then set it to the default value. */ if (psMoeState->aeFlag[eOtherType] == FORMAT_CONTROL_FLAG_UNDEFINED) { psMoeState->aeFlag[eOtherType] = aeDefaultFlag[eType]; } if (bInsertInst) { /* Add a SETFC instruction before the current instruction to set the required state of the format control flags. */ InsertSetfcInstruction(psState, psCodeBlock, psFirstInst, psMoeState); } } if (bInsertInst) { /* For instructions which use the format control flags record what the flag's value's will be when the instruction is executed. */ if (psMoeState->aeFlag[eType] == FORMAT_CONTROL_FLAG_ON) { SetBit(psFirstInst->auFlag, INST_FORMAT_SELECT, 1); } } } } static IMG_VOID MoeToInst(PINTERMEDIATE_STATE psState, const SMLSI_STATE* psMoeState, PINST psInst) /***************************************************************************** FUNCTION : MoeToInst PURPOSE : Make an instruction to set the MOE operand modes. INPUT : psState - Compiler state psMoeState - The moe state to be set OUTPUT : pInst - The instruction to set to the MOE values. RETURNS : Nothing. DESCRIPTION: Sets psInst to an SMLSI setting the MOE operand modes. *****************************************************************************/ { IMG_UINT32 indx; SetOpcode(psState, psInst, ISMLSI); psInst->asDest[0].uType = USC_REGTYPE_DUMMY; /* Set increment/swizzle values for each operand For operand i, psInst->asArg[i] is the operand value and pSInst->asArg[i+4] enables(=1)/disables(=0) swizzle mode. */ for (indx = 0; indx < 4; indx++) { PARG psIncrArg = &psInst->asArg[indx + 0]; PARG psModeArg = &psInst->asArg[indx + 4]; psModeArg->uType = USEASM_REGTYPE_IMMEDIATE; if (psMoeState->psMoeData[indx].eOperandMode == MOE_SWIZZLE) { IMG_UINT32 uSwizzle; IMG_UINT32 uSlot; uSwizzle = 0; for (uSlot = 0; uSlot < USC_MAX_SWIZZLE_SLOTS; uSlot++) { IMG_UINT32 uSel; uSel = psMoeState->psMoeData[indx].u.s.auSwizzle[uSlot]; uSwizzle |= (uSel << (USEASM_SWIZZLE_FIELD_SIZE * uSlot)); } psIncrArg->uNumber = uSwizzle; psIncrArg->uType = USEASM_REGTYPE_SWIZZLE; psModeArg->uNumber = 1; } else { psIncrArg->uNumber = psMoeState->psMoeData[indx].u.iIncrement; psIncrArg->uType = USEASM_REGTYPE_IMMEDIATE; psModeArg->uNumber = 0; } } } static IMG_BOOL EqualMoeData(const MOE_DATA* psFst, const MOE_DATA* psSnd, IMG_UINT32 uNum) /***************************************************************************** FUNCTION : EqualMoeData PURPOSE : Compare an array of MOE_DATA structures for equality (same mode, same value) INPUT : psFst, psSnd - The first strutures in the arrays of MOE data to compare uNum - The number of strutures to compare. RETURNS : IMG_TRUE if the structures are equal, IMG_FALSE otherwise *****************************************************************************/ { IMG_UINT32 indx; for (indx = 0; indx < uNum; indx ++) { const MOE_DATA* psFstArg = &psFst[indx]; const MOE_DATA* psSndArg = &psSnd[indx]; if (psFstArg->eOperandMode != psSndArg->eOperandMode) { return IMG_FALSE; } if (psFstArg->eOperandMode == MOE_INCREMENT) { if (psFstArg->u.iIncrement != psSndArg->u.iIncrement) { return IMG_FALSE; } } else { IMG_UINT32 uSlot; for (uSlot = 0; uSlot < USC_MAX_SWIZZLE_SLOTS; uSlot++) { if (psFstArg->u.s.auSwizzle[uSlot] != psSndArg->u.s.auSwizzle[uSlot]) { return IMG_FALSE; } } } } return IMG_TRUE; } static IMG_VOID ResetMoeOpState(PSMLSI_STATE psState) /***************************************************************************** FUNCTION : ResetMoeOpState PURPOSE : Reset the MOE operand modes to the default values (increment 1 mode). Clear operand invalid flags. INPUT : psState - The MOE state to reset RETURNS : Nothing *****************************************************************************/ { MOE_DATA sTemp = USC_MOE_DATA_DEFAULT_VALUE; IMG_UINT32 indx; for (indx = 0; indx < USC_MAX_MOE_OPERANDS; indx++) { psState->pbInvalid[indx] = IMG_FALSE; memcpy(&psState->psMoeData[indx], &sTemp, sizeof(psState->psMoeData[indx])); } } static IMG_UINT32 RemapMoeArg(PINTERMEDIATE_STATE psState, PINST psInst, IMG_UINT32 uArg) /***************************************************************************** FUNCTION : RemapMoeArg PURPOSE : Convert between an MOE argument number and the corresponding argument in the intermediate format. PARAMETERS : psState - Compiler state. psInst - Instruction to convert for. uArg - The MOE argument number. RETURNS : The argument number for the intermediate instruction. *****************************************************************************/ { if ((psState->psTargetFeatures->ui32Flags & SGX_FEATURE_FLAGS_USE_FCLAMP) != 0 && (psInst->eOpcode == IFMIN || psInst->eOpcode == IFMAX)) { static const IMG_UINT32 puMinRemap[] = {0, 0, 1}; static const IMG_UINT32 puMaxRemap[] = {0, 1, 0}; if (psInst->eOpcode == IFMIN) { return puMinRemap[uArg]; } else { return puMaxRemap[uArg]; } } else if (psInst->eOpcode == ITESTPRED || psInst->eOpcode == ITESTMASK) { if (psInst->u.psTest->eAluOpcode == IFPADD8 || psInst->u.psTest->eAluOpcode == IFPSUB8 || psInst->u.psTest->eAluOpcode == IIADD8 || psInst->u.psTest->eAluOpcode == IISUB8 || psInst->u.psTest->eAluOpcode == IIADDU8 || psInst->u.psTest->eAluOpcode == IISUBU8) { /* Remap: MOE source 0 -> Instruction source 1 MOE source 1 -> Instruction source 0 MOE source 2 -> Unused */ static const IMG_UINT32 auFPTestRemap[] = {1, 0, DESC_ARGREMAP_DONTCARE}; return auFPTestRemap[uArg]; } #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) else if (psInst->u.psTest->eAluOpcode == IIADDU32 || psInst->u.psTest->eAluOpcode == IIADD32 || psInst->u.psTest->eAluOpcode == IISUBU32 || psInst->u.psTest->eAluOpcode == IISUB32) { /* Remap: MOE source 0 -> Instruction source 0 MOE source 1 -> Unused MOE source 2 -> Instruction source 1 */ static const IMG_UINT32 auInt32TestRemap[] = {0, DESC_ARGREMAP_DONTCARE, 1}; return auInt32TestRemap[uArg]; } #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ else { return g_psInstDesc[psInst->eOpcode].puMoeArgRemap[uArg]; } } #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) else if (psInst->eOpcode == IFPTESTPRED_VEC || psInst->eOpcode == IFPTESTMASK_VEC) { /* Remap: MOE source 0 -> Instruction vector source 1 MOE source 1 -> Instruction vector source 0 MOE source 2 -> Unused */ static const IMG_UINT32 auFPTestRemap_Vec[] = {C10VEC_MOESOURCE_ARGINDEX(1), C10VEC_MOESOURCE_ARGINDEX(0), DESC_ARGREMAP_DONTCARE}; ASSERT(psInst->u.psTest->eAluOpcode == IFPADD8_VEC || psInst->u.psTest->eAluOpcode == IFPSUB8_VEC); return auFPTestRemap_Vec[uArg]; } #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ else { return g_psInstDesc[psInst->eOpcode].puMoeArgRemap[uArg]; } } IMG_INTERNAL IMG_UINT32 MoeArgToInstArg(PINTERMEDIATE_STATE psState, PINST psInst, IMG_UINT32 uArg) /***************************************************************************** FUNCTION : MoeArgToInstArg PURPOSE : Convert between an MOE argument number and the corresponding argument in the intermediate format. PARAMETERS : psInst - Instruction to convert for. uArg - The MOE argument number. RETURNS : The argument number for the intermediate instruction. *****************************************************************************/ { if (uArg == 0 && Src0AliasesDest(psState, psInst)) { ASSERT(RemapMoeArg(psState, psInst, uArg) == DESC_ARGREMAP_DONTCARE); return DESC_ARGREMAP_DESTALIAS; } return RemapMoeArg(psState, psInst, uArg); } /* Information about a possible location for inserting an SMLSI instruction. When an MOE repeat is created the location of the instruction is recorded in this structure. Then we accumulate information about the restrictions on the MOE state which could be set by an SMLSI instruction inserted at the site based on the instructions in between it and the current instruction. */ typedef struct { /* Pointer to the site to insert the SMLSI instruction after. */ PINST psLocation; /* Minimum register number used by instructions between the site and the current instruction for each MOE operand. */ IMG_UINT32 auMinOperandNum[USC_MAX_MOE_OPERANDS]; /* For each MOE operand either USC_UNDEF or the index of a previous MOE operand. In the latter case both MOE operands require the same state. */ IMG_UINT32 auArgAlias[USC_MAX_MOE_OPERANDS]; #if defined(OUTPUT_USPBIN) /* For each MOE operand either IMG_FALSE or IMG_TRUE if MOE operand is a Shader Result Reference. */ IMG_BOOL abShaderResultRef[USC_MAX_MOE_OPERANDS]; #endif /* defined(OUTPUT_USPBIN) */ IMG_BOOL bInCompatibleInst; } MOE_SMLSI_SITE, *PMOE_SMLSI_SITE; static IMG_VOID GetArgumentsAffectedByMOESwizzles(PINTERMEDIATE_STATE psState, PINST psInst, IMG_BOOL bAdjustToPerInstIncrements, PARG apsArgs[], IMG_UINT32 auArgIdxs[], IMG_UINT32 auArgAliases[]) /***************************************************************************** FUNCTION : GetArgumentsAffectedByMOESwizzles PURPOSE : Fills out an array of the instruction arguments which are affected by the state for MOE operand. PARAMETERS : psState - Compiler state. psInst - Instruction to get the arguments for. bAdjustToPerInstIncrements - If TRUE don't return any arguments for instructions which support MOE increments directly encoded in the instruction. apsArg - Returns pointers to the instruction argument corresponding to each MOE operand. auArgIdxs - Returns the indexes (into either the destination or source arrays) corresponding to each MOE operand. auArgAliases - For each MOE operand either USC_UNDEF or the index of another MOE operand. In the latter case both operands must have exactly the same MOE state. RETURNS : None. *****************************************************************************/ { IMG_UINT32 uMoeArg; IMG_UINT32 uReferencedInstSrcs = 0; PVR_UNREFERENCED_PARAMETER(bAdjustToPerInstIncrements); /* Initialize return data. */ for (uMoeArg = 0; uMoeArg < USC_MAX_MOE_OPERANDS; uMoeArg++) { apsArgs[uMoeArg] = NULL; auArgAliases[uMoeArg] = USC_UNDEF; if (auArgIdxs != NULL) { auArgIdxs[uMoeArg] = USC_UNDEF; } } #if defined(SUPPORT_SGX545) if (bAdjustToPerInstIncrements) { /* If the instruction supports MOE increments directly encoded in the instruction then we can switch that mode on to ignore the global MOE increments/swizzles. */ ASSERT(GetBit(psInst->auFlag, INST_MOE)); if (SupportsPerInstMoeIncrements(psState, psInst)) { return; } } #endif /* defined(SUPPORT_SGX545) */ /* Go through the MOE operands, changing any which are in swizzle mode */ for (uMoeArg = 0; uMoeArg < USC_MAX_MOE_OPERANDS; uMoeArg++) { PARG psArg; /* Get the operand number */ if (uMoeArg == 0) { IMG_UINT32 uMOEDestIdx = GetMOEDestIdx(psInst); /* Skip an unused destination. */ if (uMOEDestIdx == USC_UNDEF) { continue; } /* Get the destination operand */ psArg = &psInst->asDest[uMOEDestIdx]; if (auArgIdxs != NULL) { auArgIdxs[0] = 0; } } else { IMG_UINT32 uSrcArg; uSrcArg = MoeArgToInstArg(psState, psInst, uMoeArg - 1); ASSERT(uSrcArg != DESC_ARGREMAP_INVALID); /* Skip MOE arguments not referenced by the instruction. */ if (uSrcArg == DESC_ARGREMAP_DONTCARE) { continue; } if ((uSrcArg & DESC_ARGREMAP_ALIASMASK) != 0) { IMG_UINT32 uAliasArg = DESC_ARGREMAP_GETALIASOP(uSrcArg); ASSERT(uAliasArg < uMoeArg); /* Update this MOE operand using the same argument as the aliased operand. */ psArg = apsArgs[uAliasArg]; /* Don't return any state for this operand if the operand it aliases isn't affected by the MOE. */ if (psArg == NULL) { continue; } /* Flag that this MOE operand requires exactly the same MOE state as its alias. */ auArgAliases[uMoeArg] = uAliasArg; } else { /* Each instruction argument must correspond to only one MOE operand. */ ASSERT((uReferencedInstSrcs & (1U << uSrcArg)) == 0); uReferencedInstSrcs |= (1U << uSrcArg); /* Get the source operand */ ASSERT(uSrcArg < psInst->uArgumentCount); psArg = &psInst->asArg[uSrcArg]; if (auArgIdxs != NULL) { auArgIdxs[uMoeArg] = uSrcArg; } } } /* Immediate arguments aren't affected by the MOE swizzle/increments. */ if (psArg->uType == USEASM_REGTYPE_IMMEDIATE || psArg->uType == USC_REGTYPE_UNUSEDSOURCE) { continue; } /* Index registers aren't subject to MOE offset when being written */ if (uMoeArg == 0 && psArg->uType == USEASM_REGTYPE_INDEX) { continue; } /* Store the instruction argument corresponding to MOE operand. */ apsArgs[uMoeArg] = psArg; } } static IMG_VOID UpdateSMLSISiteConstraints(PINTERMEDIATE_STATE psState, PMOE_SMLSI_SITE psSite, PINST psInst) /***************************************************************************** FUNCTION : UpdateSMLSISiteConstraints PURPOSE : Update information about which MOE states are compatible with a range of instruction. PARAMETERS : psState - Compiler state. psSite - Information about to. psInst - Instruction to whose information is to be added. RETURNS : None. *****************************************************************************/ { PARG apsArgs[USC_MAX_MOE_OPERANDS]; IMG_UINT32 auArgAlias[USC_MAX_MOE_OPERANDS]; IMG_UINT32 uMOEArg; if (GetBit(psInst->auFlag, INST_NOEMIT)) { psSite->bInCompatibleInst |= IMG_TRUE; return; } GetArgumentsAffectedByMOESwizzles(psState, psInst, IMG_TRUE /* bAdjustToPerInstIncrements */, apsArgs, NULL /* auArgIdxs */, auArgAlias); for (uMOEArg = 0; uMOEArg < USC_MAX_MOE_OPERANDS; uMOEArg++) { /* Copy information about MOE operands which require the same state. */ if (psSite->auArgAlias[uMOEArg] == USC_UNDEF) { psSite->auArgAlias[uMOEArg] = auArgAlias[uMOEArg]; } else { ASSERT(auArgAlias[uMOEArg] == USC_UNDEF || psSite->auArgAlias[uMOEArg] == auArgAlias[uMOEArg]); } if (apsArgs[uMOEArg] != NULL) { IMG_UINT32 uRegNum; uRegNum = apsArgs[uMOEArg]->uNumber; /* Update the minimum register number used with this MOE operand. */ psSite->auMinOperandNum[uMOEArg] = min(psSite->auMinOperandNum[uMOEArg], uRegNum); } #if defined(OUTPUT_USPBIN) if (psState->uFlags & USC_FLAGS_COMPILE_FOR_USPBIN) { if(uMOEArg == 0) { /* Skip an unused destination. */ if (psInst->uDestCount > 0) { psSite->abShaderResultRef[uMOEArg] |= IsInstDestShaderResult(psState, psInst); } } else { IMG_UINT32 uInstArg; uInstArg = MoeArgToInstArg(psState, psInst, uMOEArg - 1); if (uInstArg == DESC_ARGREMAP_DONTCARE || (uInstArg & DESC_ARGREMAP_ALIASMASK) != 0) { continue; } psSite->abShaderResultRef[uMOEArg] |= IsInstSrcShaderResultRef(psState, psInst, uInstArg); } } #endif /* defined(OUTPUT_USPBIN) */ } } static IMG_INT32 GetRegisterOffsetAtIteration(PINTERMEDIATE_STATE psState, PMOE_DATA psMoeData, IMG_UINT32 uIteration) /***************************************************************************** FUNCTION : GetRegisterOffsetAtIteration PURPOSE : Get the offset applied by the MOE to a register number on a particular iteration. PARAMETERS : psState - Compiler state. psMoeData - MOE state for the argument. uIteration - Iteration to check the offset for. RETURNS : The signed offset. *****************************************************************************/ { if (psMoeData->eOperandMode == MOE_INCREMENT) { return psMoeData->u.iIncrement * (IMG_INT32)uIteration; } else { IMG_UINT32 uSel; ASSERT(psMoeData->eOperandMode == MOE_SWIZZLE); uSel = psMoeData->u.s.auSwizzle[uIteration % USC_MAX_SWIZZLE_SLOTS]; return (IMG_INT32)uSel; } } static IMG_VOID AdjustRegisterNumbersForMOESwizzle(PINTERMEDIATE_STATE psState, PMOE_DATA asMoeData, PINST psFirstInst, PINST psLastInst, IMG_BOOL bAdjustToPerInstIncrements, IMG_BOOL bIgnoreDest) /***************************************************************************** FUNCTION : AdjustRegisterNumbersForMOESwizzle PURPOSE : Adjust the register numbers of arguments to instructions in a range so when they are executed while a given MOE state is setup the post-MOE register numbers are the same as the pre-adjusted ones. PARAMETERS : psState - Compiler state. asMoeData - MOE state to adjust for. psFirstInst - First instruction in the range. psLastInst - First instruction after the range. RETURNS : None. *****************************************************************************/ { PINST psInst; IMG_UINT32 uMOEArg; IMG_UINT32 auRegisterNumberAdjust[USC_MAX_MOE_OPERANDS]; PVR_UNREFERENCED_PARAMETER(bAdjustToPerInstIncrements); for (uMOEArg = 0; uMOEArg < USC_MAX_MOE_OPERANDS; uMOEArg++) { auRegisterNumberAdjust[uMOEArg] = GetRegisterOffsetAtIteration(psState, &asMoeData[uMOEArg], 0 /* uIteration */); } for (psInst = psFirstInst; psInst != psLastInst; psInst = psInst->psNext) { PARG apsArgs[USC_MAX_MOE_OPERANDS]; IMG_UINT32 auArgAlias[USC_MAX_MOE_OPERANDS]; #if defined(SUPPORT_SGX545) /* For an instruction which support MOE increments encoded directly in the instruction switch that mode on (even though the instruction isn't repeated) so the global MOE increments/swizzles are ignored. */ if (bAdjustToPerInstIncrements && SupportsPerInstMoeIncrements(psState, psInst)) { ASSERT(GetBit(psInst->auFlag, INST_MOE) == 1); SetBit(psInst->auFlag, INST_MOE, 0); continue; } #endif /* defined(SUPPORT_SGX545) */ GetArgumentsAffectedByMOESwizzles(psState, psInst, bAdjustToPerInstIncrements, apsArgs, NULL /* uArgIdxs */, auArgAlias); /* Clear the state for the destination. */ if (bIgnoreDest) { for (uMOEArg = 0; uMOEArg < USC_MAX_MOE_OPERANDS; uMOEArg++) { ASSERT(auArgAlias[uMOEArg] != 0); } apsArgs[0] = NULL; } for (uMOEArg = 0; uMOEArg < USC_MAX_MOE_OPERANDS; uMOEArg++) { IMG_UINT32 uAdjustForInst; if (auArgAlias[uMOEArg] != USC_UNDEF) { ASSERT(auRegisterNumberAdjust[uMOEArg] == auRegisterNumberAdjust[auArgAlias[uMOEArg]]); continue; } if (apsArgs[uMOEArg] == NULL) { continue; } /* Subtract the MOE increment on iteration 0 from the register number encoded in the instruction. Then when the hardware adds the increment when executing the instruction we'll get back to the original register number. */ uAdjustForInst = auRegisterNumberAdjust[uMOEArg]; ASSERT(apsArgs[uMOEArg]->uNumber >= uAdjustForInst); apsArgs[uMOEArg]->uNumber -= uAdjustForInst; } } } IMG_INTERNAL IMG_BOOL IsValidSwapInst(PINST psInst) /***************************************************************************** FUNCTION : IsInvalidSwapInst PURPOSE : Check if an instruction can be moved around (and is valid for InstsCanSwap) PARAMETERS : psInst - Instruction to test. RETURNS : IMG_TRUE if the instruction can be moved; IMG_FALSE otherwise. *****************************************************************************/ { if (psInst == NULL) { return IMG_FALSE; } /* Don't move tests or repeated instructions */ if (psInst->uRepeat > 0) { return IMG_FALSE; } /* Test by opcode */ switch (psInst->eOpcode) { /* These instructions can't be moved */ case IBR: case ICALL: case ILABEL: case ILAPC: case IIDF: case IWDF: case ISMLSI: case ISMR: case ISETFC: case ISMBO: case IDRVPADDING: #if defined(OUTPUT_USPBIN) case ISMP_USP: case ISMPBIAS_USP: case ISMPREPLACE_USP: case ISMPGRAD_USP: case ISMP_USP_NDR: #endif /* defined(OUTPUT_USPBIN) */ { return IMG_FALSE; } /* These instructions can sometimes be moved */ case ILDAB: case ILDLB: case ILDAW: case ILDLW: case ILDAD: case ILDLD: #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) case ILDAQ: #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ #if defined(SUPPORT_SGX545) case IELDD: case IELDQ: #endif /* defined(SUPPORT_SGX545) */ case ISTAB: case ISTLB: case ISTAW: case ISTLW: case ISTAD: case ISTLD: case ISPILLREAD: case ISPILLWRITE: { if (GetBit(psInst->auFlag, INST_FETCH)) return IMG_FALSE; } default: break; } return IMG_TRUE; } static IMG_UINT32 UpdateLiveChansInDestForInst(PINTERMEDIATE_STATE psState, PINST psInst, IMG_UINT32 uLiveChansInDest, PARG psArg, IMG_UINT32 uNewLiveChansInArg) /***************************************************************************** FUNCTION : UpdateLiveChansInDestForInst PURPOSE : When moving an instruction to form an MOE repeat update an intermediate instruction. PARAMETERS : psState - Compiler state psInst - Instruction to update. uLiveChansInDest - Mask of channels live in the argument immediately after the instruction to update. psArg - The destination of the moving instruction to update. uNewLiveChansInArg - Mask of channels written in the destination by the moving instruction. RETURNS : The mask of channels live in the argument immediately before the instruction to update. *****************************************************************************/ { IMG_UINT32 uDestIdx; IMG_UINT32 uSrcIdx; for (uDestIdx = 0; uDestIdx < psInst->uDestCount; uDestIdx++) { PARG psInstDest = &psInst->asDest[uDestIdx]; PARG psInstOldDest = psInst->apsOldDest[uDestIdx]; if (psInstDest->uType == psArg->uType && psInstDest->uNumberPreMoe == psArg->uNumberPreMoe) { IMG_UINT32 uNewLiveChansInDest; if (psInstOldDest != NULL) { ASSERT(psInstOldDest->uType == psArg->uType); ASSERT(psInstOldDest->uNumberPreMoe == psArg->uNumberPreMoe); uNewLiveChansInDest = GetPreservedChansInPartialDest(psState, psInst, uDestIdx); } else { uNewLiveChansInDest = 0; } uNewLiveChansInDest |= uNewLiveChansInArg; ASSERT((psInst->auLiveChansInDest[uDestIdx] & uNewLiveChansInArg) == 0); psInst->auLiveChansInDest[uDestIdx] |= uNewLiveChansInArg; if (psInst->apsOldDest[uDestIdx] == NULL) { SetPartiallyWrittenDest(psState, psInst, uDestIdx, psInstDest); } uLiveChansInDest = uNewLiveChansInDest; } } for (uSrcIdx = 0; uSrcIdx < psInst->uArgumentCount; uSrcIdx++) { PARG psSrc = &psInst->asArg[uSrcIdx]; if (psSrc->uType == psArg->uType && psSrc->uNumberPreMoe == psArg->uNumberPreMoe) { IMG_UINT32 uLiveChansInArg; uLiveChansInArg = GetLiveChansInArg(psState, psInst, uSrcIdx); ASSERT((uLiveChansInArg & uNewLiveChansInArg) == 0); uLiveChansInDest |= uLiveChansInArg; } } return uLiveChansInDest; } static IMG_VOID UpdateLiveChansInDest(PINTERMEDIATE_STATE psState, PINST psInstToMove, PINST psNewInstLocation) /***************************************************************************** FUNCTION : UpdateLiveChansInDest PURPOSE : Update the recorded masks of channels used from the destination of each instruction when moving two instructions together to form an MOE repeat. PARAMETERS : psState - Compiler state psInstToMove - Instruction which is moving. psNewInstLocation - Location of the MOE repeat. RETURNS : Nothing *****************************************************************************/ { IMG_UINT32 uDestIdx; for (uDestIdx = 0; uDestIdx < psInstToMove->uDestCount; uDestIdx++) { IMG_UINT32 uLiveChansInDest; IMG_UINT32 uChansWritten; PARG psDest; PINST psInst; uLiveChansInDest = psInstToMove->auLiveChansInDest[uDestIdx]; uChansWritten = psInstToMove->auDestMask[uDestIdx] & uLiveChansInDest; psDest = &psInstToMove->asDest[uDestIdx]; if (psDest->uType == USC_REGTYPE_DUMMY) { /* Skip instruction destinations which aren't real registers. */ continue; } /* Update the live channels for the destinations of instructions in between the new and old locations. */ for (psInst = psInstToMove->psPrev; psInst != psNewInstLocation; psInst = psInst->psPrev) { uLiveChansInDest = UpdateLiveChansInDestForInst(psState, psInst, uLiveChansInDest, psDest, uChansWritten); } /* Record the new mask of channels live in the moving instruction's destination. */ psInstToMove->auLiveChansInDest[uDestIdx] = uLiveChansInDest; /* Update the moving instruction if it is no longer completely defining the destination. */ if ((uLiveChansInDest & ~psInstToMove->auDestMask[uDestIdx]) != 0) { if (psInstToMove->apsOldDest[uDestIdx] == NULL) { SetPartiallyWrittenDest(psState, psInstToMove, uDestIdx, psDest); } } } } static IMG_VOID FreeRepeatGroup(PINTERMEDIATE_STATE psState, PREPEAT_GROUP *ppsElem) /***************************************************************************** FUNCTION : FreeRepeatGroup PURPOSE : Release memory used for a repeat group PARAMETERS : psState - Compiler state psElem - Element to free RETURNS : Nothing *****************************************************************************/ { if (ppsElem != NULL) { _UscFree(psState, (IMG_PVOID*)ppsElem); } } static PREPEAT_GROUP AllocRepeatGroup(PINTERMEDIATE_STATE psState) /***************************************************************************** FUNCTION : AllocRepeatGroup PURPOSE : Allocate and initialise a repeat group PARAMETERS : psState - Compiler state RETURNS : A dynamically allocated, initialised repeat group *****************************************************************************/ { PREPEAT_GROUP psRet = UscAlloc(psState, sizeof(REPEAT_GROUP)); memset(psRet, 0, sizeof(REPEAT_GROUP)); return psRet; } static IMG_BOOL IsReplicatedHardwareConstant(IMG_UINT32 uNumber, IMG_PUINT32 puReplicateCount) /***************************************************************************** FUNCTION : IsReplicatedHardwareConstant PURPOSE : Checks for a hardware constants where the next N hardware constants have the same value. PARAMETERS : uNumber - Index of the constant to check. puReplicateCount - Returns the length of the range of replicated constants. RETURNS : TRUE or FALSE. *****************************************************************************/ { switch (uNumber) { case EURASIA_USE_SPECIAL_CONSTANT_FLOAT16ONE: { *puReplicateCount = min(*puReplicateCount, 2); return IMG_TRUE; } case EURASIA_USE_SPECIAL_CONSTANT_ZERO: case EURASIA_USE_SPECIAL_CONSTANT_FLOAT1: case EURASIA_USE_SPECIAL_CONSTANT_INT32ONE: case EURASIA_USE_SPECIAL_CONSTANT_S16ONE: { *puReplicateCount = min(*puReplicateCount, 3); return IMG_TRUE; } default: { return IMG_FALSE; } } } #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) typedef enum { MOE_MODE_COMPLEX, MOE_MODE_NOINCREMENT, MOE_MODE_INCREMENT, } MOE_MODE; static MOE_MODE CheckIncrementMode(PMOE_DATA psMoeData, PARG psArg) /***************************************************************************** FUNCTION : CheckIncrementMode PURPOSE : Check if an increment/swizzle state is one of two simple forms: either no increment or increment by a fixed value. PARAMETERS : psMoeData - MOE state to check. psArg - Corresponding source/destination argument to the instruction. RETURNS : The MOE increment mode. *****************************************************************************/ { IMG_INT32 iIncrementStep; if (psArg->uType == USEASM_REGTYPE_FPINTERNAL) { /* Increment by one GPI register (=128 bit vector). */ iIncrementStep = 1; } else { /* Increment by two unified store registers (=2x64 bit vector) */ iIncrementStep = 2; } if (psMoeData->eOperandMode != MOE_INCREMENT) { return MOE_MODE_COMPLEX; } if (psMoeData->u.iIncrement == 0) { return MOE_MODE_NOINCREMENT; } else if (psMoeData->u.iIncrement == iIncrementStep) { return MOE_MODE_INCREMENT; } else { return MOE_MODE_COMPLEX; } } static IMG_BOOL CheckSingleIssueVectorIncrementMode(PCANDIDATE_GROUP_DATA psGroup, PINST psInst) /***************************************************************************** FUNCTION : CheckSingleIssueVectorIncrementMode PURPOSE : Checks the repeat/increment mode to use for a repeated single-issue vector instruction. PARAMETERS : psGroup - Information about the repeated instruction. psInst - Instruction to check repeat mode for. RETURNS : TRUE if the vector instruction can be repeated. *****************************************************************************/ { PMOE_DATA psDest = &psGroup->psIncData[0]; PMOE_DATA psUSSrc = &psGroup->psIncData[1]; PMOE_DATA psGPISrc = &psGroup->psIncData[2]; MOE_MODE eUnifiedStoreSrcMode; MOE_MODE eGPISrcMode; PINST psFirstInst = psGroup->psFirstInst; if (psGroup->sVec.bDotProduct) { /* We already checked while finding the instructions to include in the repeat that the destination register numbers were incrementing in the right pattern. */ } else { /* Check the destination increases by an 128-bit vector on each iteration. */ if (CheckIncrementMode(psDest, &psFirstInst->asDest[0]) != MOE_MODE_INCREMENT) { return IMG_FALSE; } } /* Single issue vector instructions never use MOE state for the destination or source 0. */ psGroup->uDontCareMask |= MOE_OPERAND_DEST_MASK | MOE_OPERAND_SRC0_MASK; /* Check for both the unified store and the GPI source whether they have either no increment or increment by a 128-bit vector on each iteration. */ eUnifiedStoreSrcMode = CheckIncrementMode(psUSSrc, &psFirstInst->asArg[VEC_MOESOURCE_ARGINDEX(0)]); eGPISrcMode = CheckIncrementMode(psGPISrc, &psFirstInst->asArg[VEC_MOESOURCE_ARGINDEX(1)]); /* VMAD has two GPI sources: both must have the same increment mode. */ if (psInst->eOpcode == IVMAD4) { PMOE_DATA psGPISrc2 = &psGroup->psIncData[3]; MOE_MODE eGPISrc2Mode; eGPISrc2Mode = CheckIncrementMode(psGPISrc2, &psFirstInst->asArg[VEC_MOESOURCE_ARGINDEX(2)]); if (eGPISrc2Mode != eGPISrcMode) { return IMG_FALSE; } } /* Check if pattern of the register numbers for the unified store and GPI sources match one of the instruction modes. */ if (eGPISrcMode == MOE_MODE_INCREMENT && eUnifiedStoreSrcMode == MOE_MODE_INCREMENT) { /* Increment both the unified store and GPI sources. */ psGroup->sVec.eRepeatMode = SVEC_REPEATMODE_INCREMENTBOTH; } else if (eGPISrcMode == MOE_MODE_INCREMENT && eUnifiedStoreSrcMode == MOE_MODE_NOINCREMENT) { /* Increment just the GPI source. */ psGroup->sVec.eRepeatMode = SVEC_REPEATMODE_INCREMENTGPI; } else if (eGPISrcMode == MOE_MODE_NOINCREMENT && eUnifiedStoreSrcMode == MOE_MODE_INCREMENT) { /* Increment just the unified store source. */ psGroup->sVec.eRepeatMode = SVEC_REPEATMODE_INCREMENTUS; } else if (eGPISrcMode == MOE_MODE_NOINCREMENT) { /* Use the MOE state for the unified store source and don't increment the GPI source. */ psGroup->sVec.eRepeatMode = SVEC_REPEATMODE_USEMOE; } else { return IMG_FALSE; } if (psGroup->sVec.eRepeatMode == SVEC_REPEATMODE_USEMOE) { /* Set both MOE source 1 and source 2 to the state required for the unified store source. */ psGroup->uArgCount = 4; psGroup->psMoeData[2] = *psUSSrc; psGroup->psMoeData[3] = *psUSSrc; } else { /* Ignore the MOE state for both source 1 and source 2. */ psGroup->uDontCareMask |= MOE_OPERAND_SRC1_MASK | MOE_OPERAND_SRC2_MASK; } return IMG_TRUE; } #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ static IMG_BOOL RemapIncrements(PINTERMEDIATE_STATE psState, PINST psInst, PCANDIDATE_GROUP_DATA psGroup) /***************************************************************************** FUNCTION : RemapIncrements PURPOSE : Remaps the per-argument increments/swizzle to correspond to the MOE. PARAMETERS : psState - Compiler state. psInst - Instruction to remap for. psGroup - On return updated with information about the arguments. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 uOpIdx; // Operand index /* Initialize return arguments. */ psGroup->uSpecialConstMask = 0; psGroup->uDontCareMask = 0; psGroup->uArgCount = 1; /* Where some arguments point to a range of hardware constants with the same value the size of the range. */ psGroup->uSpecialConstGroupLimit = 3; #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) if (psGroup->bSVecInst) { /* Check if we can use one of the special single issue vector increment modes. */ return CheckSingleIssueVectorIncrementMode(psGroup, psInst); } #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ /* For each of the arguments in the MOE order. */ for (uOpIdx = 1; uOpIdx < USC_MAX_MOE_OPERANDS; uOpIdx++) { IMG_UINT32 uInstArg; IMG_UINT32 uArgIdx = uOpIdx - 1; // Source operand index /* Map the MOE argument to the index of an argument to the instruction or a special value. */ uInstArg = MoeArgToInstArg(psState, psInst, uArgIdx); if (uInstArg == DESC_ARGREMAP_DONTCARE) { /* Add to the mask of MOE arguments we are ignoring. */ psGroup->uDontCareMask |= (1U << uOpIdx); } else if ((uInstArg & DESC_ARGREMAP_ALIASMASK) != 0) { IMG_UINT32 uAliasArg = DESC_ARGREMAP_GETALIASOP(uInstArg); /* Use the same MOE state for this argument and its alias. */ psGroup->psMoeData[uOpIdx] = psGroup->psMoeData[uAliasArg]; psGroup->uArgCount = max(psGroup->uArgCount, uOpIdx + 1); } else { PARG psArg; PMOE_DATA psMoeData = &psGroup->psMoeData[uOpIdx]; ASSERT(uInstArg < psInst->uArgumentCount); psArg = &psInst->asArg[uInstArg]; if (psArg->uType == USEASM_REGTYPE_IMMEDIATE) { /* Immediate arguments aren't modified by the MOE. We already checked that all the instructions in the repeat are using the same immediate value so just ignore the MOE state for this argument. */ ASSERT(psMoeData->eOperandMode == MOE_INCREMENT); ASSERT(psMoeData->u.iIncrement == 0); psGroup->uDontCareMask |= (1U << uOpIdx); continue; } /* Flag arguments which point to the start of a range of hardware constants all of which have the same value. */ if (psArg->uType == USEASM_REGTYPE_FPCONSTANT && psMoeData->eOperandMode == MOE_INCREMENT && psMoeData->u.iIncrement == 0 && IsReplicatedHardwareConstant(psArg->uNumber, &psGroup->uSpecialConstGroupLimit)) { psGroup->uSpecialConstMask |= (1U << uOpIdx); } /* Track how many MOE arguments are actually referenced. */ psGroup->uArgCount = max(psGroup->uArgCount, uOpIdx + 1); } } return IMG_TRUE; } #if defined(SUPPORT_SGX545) static IMG_BOOL CheckPerInstMoeIncrements(PCANDIDATE_GROUP_DATA psGroup) /***************************************************************************** FUNCTION : CheckPerInstMoeIncrements PURPOSE : Check if a set of instructions can be grouped using per-instruction increment. PARAMETERS : psGroup - Details of the group we are trying to create. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 uArg; IMG_UINT32 uMOEDestIdx = GetMOEDestIdx(psGroup->psFirstInst); /* Ignore the destination if we aren't writing. */ if (uMOEDestIdx != USC_UNDEF) { if (psGroup->bDotProduct || psGroup->bDoubleDotProduct) { IMG_UINT32 uDestNumber; uDestNumber = psGroup->psFirstInst->asDest[uMOEDestIdx].uNumber; /* A dot-product only writes on the last iteration and with per-instruction increments LAST_DEST = ENCODED_DEST + REPEAT_COUNT so check the encoded destination wouldn't have to be negative. */ if (uDestNumber < (psGroup->uInstCount - 1)) { return IMG_FALSE; } } else { /* The increment for the destination must be one. */ if (psGroup->psMoeData[0].eOperandMode == MOE_SWIZZLE) { return IMG_FALSE; } if (psGroup->psMoeData[0].u.iIncrement != 1) { return IMG_FALSE; } } } /* The increment for the source arguments must 0 or 1. */ for (uArg = 1; uArg < psGroup->uArgCount; uArg++) { if (psGroup->psMoeData[uArg].eOperandMode == MOE_SWIZZLE) { return IMG_FALSE; } if (!(psGroup->psMoeData[uArg].u.iIncrement >= 0 && psGroup->psMoeData[uArg].u.iIncrement <= 1)) { return IMG_FALSE; } } return IMG_TRUE; } #endif /* defined(SUPPORT_SGX545) */ static IMG_BOOL NeedSMSLIForDPDestination(PINTERMEDIATE_STATE psState, PSMLSI_STATE psMoeState, PCANDIDATE_GROUP_DATA psGroup, IMG_UINT32 uLastIteration, IMG_PUINT32 puNewDPDestNum) /***************************************************************************** FUNCTION : NeedSMSLIForDPDestination PURPOSE : Checks if a dot-product grouped instruction can write to the right register given the current MOE state. PARAMETERS : psState - Compiler state. psMoeState - Existing MOE state. psGroup - Information about the set of instruction we are trying to group. uLastIteration - Index of the last iteration. puNewDPDestNum - On return the encoded number for the dot-product destination. RETURNS : TRUE or FALSE. *****************************************************************************/ { IMG_INT32 iDestNumber; PMOE_DATA psMoeData; IMG_UINT32 uMOEDestIdx; /* Need an SMLSI if the MOE state for the destination is unknown. */ if (psMoeState->pbInvalid[0]) { return IMG_TRUE; } /* For a dotproduct a writeback is only done on the last iteration so check that we can encode the required destination register number. */ psMoeData = &psMoeState->psMoeData[0]; uMOEDestIdx = GetMOEDestIdx(psGroup->psFirstInst); iDestNumber = (IMG_INT32)psGroup->psFirstInst->asDest[uMOEDestIdx].uNumber; iDestNumber -= GetRegisterOffsetAtIteration(psState, psMoeData, uLastIteration); if (iDestNumber < 0 || iDestNumber >= (IMG_INT32)EURASIA_USE_REGISTER_NUMBER_MAX) { return IMG_TRUE; } *puNewDPDestNum = (IMG_UINT32)iDestNumber; return IMG_FALSE; } static IMG_BOOL IsMOEStateCompatibleWithInstructionRange(PINTERMEDIATE_STATE psState, PMOE_DATA psMoeData, PMOE_SMLSI_SITE psSiteData) /***************************************************************************** FUNCTION : IsMOEStateCompatibleWithInstructionRange PURPOSE : Checks if the register numbers of the arguments to each instruction in a range can be encoded given a particular MOE state. PARAMETERS : psState - Compiler state. psMoeData - MOE increments/swizzle state. psSiteData - Information about the instructions in the range. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 uMoeArg; if(psSiteData->bInCompatibleInst == IMG_TRUE) { return IMG_FALSE; } /* For each MOE operand if we want to use swizzle mode and the increment applied by the swizzle on the first iteration is N then we'll need to subtract N from the register number for any instruction argument which uses the same operand so the post-MOE register numbers remain the same. */ for (uMoeArg = 0; uMoeArg < USC_MAX_MOE_OPERANDS; uMoeArg++) { IMG_UINT32 uMOEOffset = GetRegisterOffsetAtIteration(psState, &psMoeData[uMoeArg], 0 /* uIteration */); /* If the range contains instructions where different MOE operands correspond to the same argument that the adjustment for each operand is the same. */ if (psSiteData->auArgAlias[uMoeArg] != USC_UNDEF) { IMG_UINT32 uAliasArg = psSiteData->auArgAlias[uMoeArg]; IMG_UINT32 uAliasOffset = GetRegisterOffsetAtIteration(psState, &psMoeData[uAliasArg], 0 /* uIteration */); if (uMOEOffset != uAliasOffset) { return IMG_FALSE; } } /* Check for all the instructions in between the last repeated instructions and here if the register number for any instruction is less than the adjustment needed */ if (uMOEOffset > psSiteData->auMinOperandNum[uMoeArg]) { return IMG_FALSE; } #if defined(OUTPUT_USPBIN) if (psState->uFlags & USC_FLAGS_COMPILE_FOR_USPBIN) { if(psSiteData->abShaderResultRef[uMoeArg] == IMG_TRUE) { /* Some MOE argument is contaning a Shader Result reference */ return IMG_FALSE; } } #endif /* defined(OUTPUT_USPBIN) */ } return IMG_TRUE; } static IMG_BOOL CheckExistingMoeState(PINTERMEDIATE_STATE psState, PSMLSI_STATE psMoeState, PCANDIDATE_GROUP_DATA psGroup) /***************************************************************************** FUNCTION : CheckExistingMoeState PURPOSE : Checks if a group of instructions can be formed into a repeat given the existing MOE state. PARAMETERS : psState - Compiler state. psMoeState - Existing MOE state. psGroup - Information about the set of instruction we are trying to group. RETURNS : TRUE if these instructions can't be grouped using the current MOE state. *****************************************************************************/ { IMG_UINT32 uArg; uArg = 0; /* Ignore the destination if we aren't writing. */ if (!HasMOEDest(psGroup->psFirstInst)) { ASSERT((g_psInstDesc[psGroup->psFirstInst->eOpcode].uFlags2 & DESC_FLAGS2_TEST) != 0); uArg = 1; } else if (psGroup->bDotProduct || psGroup->bDoubleDotProduct) { /* Destination gets special treatment for a dotproduct */ if (NeedSMSLIForDPDestination(psState, psMoeState, psGroup, psGroup->uInstCount - 1, &psGroup->uNewDPDestNum)) { return IMG_TRUE; } uArg = 1; } for ( ; uArg < psGroup->uArgCount; uArg++) { PMOE_DATA psMoeData; /* Ignore arguments not referenced by the instruction. */ if (psGroup->uDontCareMask & (1U << uArg)) { continue; } /* Need an SMLSI if the MOE state is unknown. */ if (psMoeState->pbInvalid[uArg]) { return IMG_TRUE; } psMoeData = &psMoeState->psMoeData[uArg]; if (psGroup->uSpecialConstMask & (1U << uArg)) { IMG_UINT32 uMaxOffset; /* For a special constant (e.g. c48) the next 2 or 4 registers hold the same value so if the existing MOE increment is 0 or 1 we don't need an SMLSI. */ if (psMoeData->eOperandMode == MOE_INCREMENT) { if (psMoeData->u.iIncrement < 0) { return IMG_TRUE; } uMaxOffset = psMoeData->u.iIncrement * (psGroup->uInstCount - 1); } else { IMG_UINT32 uGroup; uMaxOffset = 0; for (uGroup = 0; uGroup < psGroup->uInstCount; uGroup++) { IMG_UINT32 uSel; uSel = psMoeData->u.s.auSwizzle[uGroup]; uMaxOffset = max(uMaxOffset, uSel); } } if (uMaxOffset > psGroup->uSpecialConstGroupLimit) { return IMG_TRUE; } } else { /* Check if the existing MOE state is the same as that needed for this argument. */ if (!EqualMoeData(&psGroup->psMoeData[uArg], psMoeData, 1)) { return IMG_TRUE; } } } return IMG_FALSE; } static IMG_BOOL SwitchToRepeatSpecialConstArg(PINTERMEDIATE_STATE psState, PCANDIDATE_GROUP_DATA psGroup, PMOE_DATA psCurrentMoeData, IMG_UINT32 uLastIterationInMask, IMG_UINT32 uRepeatMask) /***************************************************************************** FUNCTION : SwitchToRepeatSpecialConstArg PURPOSE : Check if switching to a repeat mask for an MOE repeat would be compatible with an argument in the special constant register bank. PARAMETERS : psState - Compiler state. psGroup - MOE repeat we are trying to create. psCurrentMoeState - Currently set MOE state. uLastIterationInMask - Highest bit set in the repeat mask. uRepeatMask - Repeat mask to check. RETURNS : TRUE or FALSE. *****************************************************************************/ { IMG_UINT32 uIteration; /* For each iteration in the mask check the offset to the register number wouldn't go outside the block of special constants with the same value. */ for (uIteration = 0; uIteration <= uLastIterationInMask; uIteration++) { if ((uRepeatMask & (1U << uIteration)) != 0) { IMG_INT32 iRegisterNumberOffset; iRegisterNumberOffset = GetRegisterOffsetAtIteration(psState, psCurrentMoeData, uIteration); if (iRegisterNumberOffset < 0 || iRegisterNumberOffset > (IMG_INT32)psGroup->uSpecialConstGroupLimit) { return IMG_FALSE; } } } return IMG_TRUE; } static IMG_BOOL SwitchToRepeatArg(PINTERMEDIATE_STATE psState, PCANDIDATE_GROUP_DATA psGroup, IMG_UINT32 uArg, PMOE_DATA psCurrentMoeData, IMG_UINT32 uMaxRepeatMaskLength, IMG_PUINT32 puRepeatMask, IMG_PUINT32 puLastIterationInMask) /***************************************************************************** FUNCTION : SwitchToRepeatArg PURPOSE : Check if there is a repeat mask which, in conjunction with the currently set MOE state, would give the sequence of register numbers required for an argument in a repeat. PARAMETERS : psState - Compiler state. psGroup - Details of the group we are trying to create. psCurrentMoeState - Currently set MOE state. uMaxRepeatMaskLength - Maximum length of the repeat mask. puRepeatMask - Returns the repeat mask (if it exists). puLastIterationInMask - Returns the highest set bit in the mask. RETURNS : TRUE if a repeat mask exists. *****************************************************************************/ { IMG_UINT32 uIteration; IMG_UINT32 uMaskChan; IMG_UINT32 uRepeatMask; PMOE_DATA psGroupMoeData = &psGroup->psMoeData[uArg]; uRepeatMask = 0; uMaskChan = 0; for (uIteration = 0; uIteration < psGroup->uInstCount; uIteration++) { IMG_UINT32 uRequiredOffset; IMG_BOOL bFoundMatchingChannel; /* Get the offset to the register number required by the repeat on this iteration. */ uRequiredOffset = GetRegisterOffsetAtIteration(psState, psGroupMoeData, uIteration); /* Check for an iteration which would give the same offset when used with the current MOE state. */ bFoundMatchingChannel = IMG_FALSE; for (; uMaskChan < uMaxRepeatMaskLength; uMaskChan++) { IMG_UINT32 uCurrentOffset = GetRegisterOffsetAtIteration(psState, psCurrentMoeData, uMaskChan); if (uCurrentOffset == uRequiredOffset) { bFoundMatchingChannel = IMG_TRUE; break; } } if (!bFoundMatchingChannel) { return IMG_FALSE; } /* Add the found channel to the repeat mask. */ uRepeatMask |= (1U << uMaskChan); uMaskChan++; } *puRepeatMask = uRepeatMask; *puLastIterationInMask = uMaskChan - 1; return IMG_TRUE; } static IMG_BOOL SwitchToRepeatMask(PINTERMEDIATE_STATE psState, PSMLSI_STATE psMoeState, PCANDIDATE_GROUP_DATA psGroup, IMG_PUINT32 puRepeatMask) /***************************************************************************** FUNCTION : SwitchToRepeatMask PURPOSE : Check if using a repeat mask (rather than a repeat count) for a group of instructions would avoid having to insert an SMLSI instruction. PARAMETERS : psState - Compiler state. psMoeState - Existing MOE state. psGroup - Information about the set of instruction we are trying to group. piMoePrevInc - puRepeatMask - On success returns the repeat mask to use. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 uArg; IMG_UINT32 uRepeatMask; IMG_UINT32 uMaxRepeatCount; IMG_UINT32 uMaxRepeatMaskLength; IMG_UINT32 uLastIterationInMask; /* Check if this group can use a repeat mask; not available on SGX545. */ if (!CanUseRepeatMask(psState, psGroup->psFirstInst)) { return IMG_FALSE; } /* If the group has a different predicate for each iteration then we can't switch to a mask without changing the predicate numbers. */ if (psGroup->bPredModN) { return IMG_FALSE; } /* Convert the maximum repeat count to a mask (one bit per iteration). */ uMaxRepeatCount = GetMaxRepeatCountInst(psState, psGroup->psFirstInst); if (uMaxRepeatCount >= 16) { uMaxRepeatMaskLength = 4; } else if (uMaxRepeatCount >= 8) { uMaxRepeatMaskLength = 3; } else { return IMG_FALSE; } /* Check the bit width of the repeat mask supported by this instruction can fit all the iterations with at least one gap. */ if (uMaxRepeatMaskLength < (psGroup->uInstCount - 1)) { return IMG_FALSE; } uRepeatMask = USC_UNDEF; uLastIterationInMask = USC_UNDEF; for (uArg = 0; uArg < psGroup->uArgCount; uArg++) { PMOE_DATA psCurrentMoeData; IMG_UINT32 uArgRepeatMask; IMG_UINT32 uArgLastIterationInMask; /* Ignore an unwritten destination. Handle dotproduct destinations specially since they are only written on the last iteration. */ if (uArg == 0 && (!HasMOEDest(psGroup->psFirstInst) || psGroup->bDotProduct || psGroup->bDoubleDotProduct)) { continue; } /* Ignore MOE arguments not used by the instruction. */ if (psGroup->uDontCareMask & (1U << uArg)) { continue; } /* We'll always need an SMLSI if the MOE state is unknown. */ if (psMoeState->pbInvalid[uArg]) { return IMG_FALSE; } /* Check arguments using the special constant bank in another pass. */ if (psGroup->uSpecialConstMask & (1U << uArg)) { continue; } /* Look for a repeat mask which would give the right sequence of register numbers for this argument when using the currently set MOE state. */ psCurrentMoeData = &psMoeState->psMoeData[uArg]; if (!SwitchToRepeatArg(psState, psGroup, uArg, psCurrentMoeData, uMaxRepeatMaskLength, &uArgRepeatMask, &uArgLastIterationInMask)) { return IMG_FALSE; } if (uRepeatMask == USC_UNDEF) { uRepeatMask = uArgRepeatMask; uLastIterationInMask = uArgLastIterationInMask; } else { /* Check each argument can use the same repeat mask. */ if (uRepeatMask != uArgRepeatMask) { return IMG_FALSE; } ASSERT(uLastIterationInMask == uArgLastIterationInMask); } } /* Check for any arguments using the special constant bank if for any iteration the register offset would take the register number outside the range of special constants with the same value. */ for (uArg = 0; uArg < psGroup->uArgCount; uArg++) { if (psGroup->uSpecialConstMask & (1U << uArg)) { PMOE_DATA psCurrentMoeData; psCurrentMoeData = &psMoeState->psMoeData[uArg]; if (!SwitchToRepeatSpecialConstArg(psState, psGroup, psCurrentMoeData, uLastIterationInMask, uRepeatMask)) { return IMG_FALSE; } } } if (HasMOEDest(psGroup->psFirstInst) && (psGroup->bDotProduct || psGroup->bDoubleDotProduct)) { IMG_UINT32 uNewDPDestNum; /* Check if we can set up the instruction so we write to the right register number on the last iteration. */ if (NeedSMSLIForDPDestination(psState, psMoeState, psGroup, uLastIterationInMask, &uNewDPDestNum)) { return IMG_FALSE; } else { psGroup->uNewDPDestNum = uNewDPDestNum; } } *puRepeatMask = uRepeatMask; return IMG_TRUE; } static IMG_BOOL IsNonZeroSwizzle(PMOE_DATA psMoeData, IMG_UINT32 uCount) /***************************************************************************** FUNCTION : IsNonZeroSwizzle PURPOSE : Check if the MOE state for any argument is swizzle mode with the selector for the first iteration not equal to zero. PARAMETERS : psMoeData - Points to an array of per-argument MOE state. uCount - Count of arguments to check. RETURNS : TRUE or FALSE. *****************************************************************************/ { IMG_UINT32 uArg; for (uArg = 0; uArg < uCount; uArg++) { if (psMoeData[uArg].eOperandMode == MOE_SWIZZLE && psMoeData[uArg].u.s.auSwizzle[0] != 0) { return IMG_TRUE; } } return IMG_FALSE; } static IMG_BOOL CheckIncrements(PINTERMEDIATE_STATE psState, PSMLSI_STATE psMoeState, PCANDIDATE_GROUP_DATA psGroup, PMOE_SMLSI_SITE psSiteData, IMG_PBOOL pbUseMoeSite, IMG_PBOOL pbUseMoe, IMG_PBOOL pbNeedSmlsi, IMG_PBOOL pbUseMask, IMG_PUINT32 puRepeatMask) /***************************************************************************** FUNCTION : CheckIncrements PURPOSE : Check if we should create a group of instructions and whether an SMLSI instruction needs to be inserted before. PARAMETERS : psState - Compiler state. psMoeState - Current MOE state. psGroup - Information about the set of instructions we are trying to group. uMinTrigger - bLastWasGrouped pbUseMoe - On return FALSE to use per-instruction increments. or TRUE to use MOE increments. pbNeedSmlsi - On return TRUE if an SMSLI must be inserted before the group. pbUseMask - On return TRUE to use a repeat mask. puRepeatMask - On return the repeat mask to use. RETURNS : TRUE if the instructions should be grouped. *****************************************************************************/ { IMG_UINT32 uMinTrigger; /* Initialize return data. */ *pbUseMoe = IMG_TRUE; *pbNeedSmlsi = IMG_FALSE; *pbUseMask = IMG_FALSE; *puRepeatMask = 0; *pbUseMoeSite = IMG_FALSE; #if defined(SUPPORT_SGX545) if (psGroup->bInstMoeIncrement) { /* Check if we can create a group using the per-instruction increments without needing an SMLSI. */ if (CheckPerInstMoeIncrements(psGroup)) { *pbUseMoe = IMG_FALSE; return IMG_TRUE; } /* Some instructions don't support MOE increments so don't group if MOE increments are required to make a repeat. */ if (psGroup->bNeverUseMoe) { return IMG_FALSE; } } #endif /* defined(SUPPORT_SGX545) */ /* The test instruction must always use a mask. */ *pbUseMask = IMG_FALSE; if (UseRepeatMaskOnly(psState, psGroup->psFirstInst)) { *pbUseMask = IMG_TRUE; *puRepeatMask = (1U << psGroup->uInstCount) - 1; } /* If some of the instructions between the point where the current MOE state was set up and here aren't compatible with the current state then don't bother trying to use it since we'd need to insert an SMLSI anyway. */ if ( psSiteData->psLocation == NULL || IsMOEStateCompatibleWithInstructionRange(psState, psMoeState->psMoeData, psSiteData) ) { /* Check if the current instructions can be grouped using the existing MOE state. */ if (!CheckExistingMoeState(psState, psMoeState, psGroup)) { return IMG_TRUE; } /* Check if we could get away without an smlsi instruction by inserting gaps in the mask. */ if (!(*pbUseMask)) { if (SwitchToRepeatMask(psState, psMoeState, psGroup, puRepeatMask)) { *pbUseMask = IMG_TRUE; return IMG_TRUE; } } } /* We'll definitely need to insert an SMLSI instruction. */ *pbNeedSmlsi = IMG_TRUE; /* Can we insert the SMLSI instruction after the last repeated instruction? */ *pbUseMoeSite = IMG_TRUE; if (psSiteData->psLocation == NULL) { /* No repeated instructions generated yet. */ *pbUseMoeSite = IMG_FALSE; } else { *pbUseMoeSite = IsMOEStateCompatibleWithInstructionRange(psState, psGroup->psMoeData, psSiteData); } /* We must form a group for a set of DP/DDP instructions. */ if (psGroup->bDotProduct || psGroup->bDoubleDotProduct) { return IMG_TRUE; } /* If we can insert an SMLSI instruction for free then reduce the number of instructions required to trigger a repeat. */ uMinTrigger = (*pbUseMoeSite) ? MIN_GROUP_TRIGGER : DEFAULT_GROUP_TRIGGER; if (psGroup->uInstCount >= uMinTrigger) { return IMG_TRUE; } /* Don't form a group. */ return IMG_FALSE; } static IMG_VOID FindPotentialGroup(PINTERMEDIATE_STATE psState, PCANDIDATE_GROUP_DATA psGroup, PINST psFirstInstInGroup, PUSEDEF_RECORD psUseDef) /***************************************************************************** FUNCTION : FindPotentialGroup PURPOSE : Check if we should create a group of instructions and whether an SMLSI instruction needs to be inserted before. PARAMETERS : psState - Compiler state. psGroup - Information about the set of instructions we are trying to group. psFirstInstInGroup - Instruction to find others to group with. psUseDef - Preallocated USE/DEF record to use. RETURNS : Nothing. *****************************************************************************/ { PINST psCandidateInst; PINST psFirstInstNotInUseDefRecord; IMG_UINT32 uMaxRepeatCount; IMG_BOOL bExcludeRAW; /* The registers defined in the group so far. */ REGISTER_USEDEF sGroupDef; uMaxRepeatCount = GetMaxRepeatCountInst(psState, psFirstInstInGroup); psCandidateInst = psFirstInstInGroup; psFirstInstNotInUseDefRecord = psFirstInstInGroup->psNext; /* psUseDef: Use-def record for instructions between the instructions which form a group. */ ClearUseDef(psState, psUseDef); /* Check for cases where we can't make groups which include an instruction which defines a register then another instruction which uses the same register. For asynchronous writeback instructions this is because we need a WDF between the define and the use. For per-instance mode there is a big pipeline stall between the define and the use. */ bExcludeRAW = IMG_FALSE; if (IsAsyncWBInst(psState, psFirstInstInGroup)) { bExcludeRAW = IMG_TRUE; } if (psState->uNumDynamicBranches > 0) { bExcludeRAW = IMG_TRUE; } /* Initialise a USE/DEF record to track register written in instructions added to the group. */ if (bExcludeRAW) { InitRegUseDef(&sGroupDef); InstDef(psState, psFirstInstInGroup, &sGroupDef); } /* Run through instructions until no more fit in group. psCurrInst: The instruction to be tested. psFirstInst: The first instruction in the group psPrevInst: The last instruction to succeed. First a candidate is found: If a dotproduct, the candidate is always psCurrInst. Otherwise, the list of instructions beginning with psCurrInst is searched for an instruction with the same opcode as psFirstInst and which could be moved to the end of the group. (The end of the group of instructions is taken to be marked by psFirstInst, with any other instructions in the group ignored.) When a candidate is found, it is passed to CheckInstGroup for inclusion in the group. If this fails, the group ends otherwise the instruction is marked for removal and the process is repeated with the instruction following the candidate in the list. Flag bContiguous is used so that processing a single block of instructions does not mean that each instruction in the block is tested to see if it can be moved. Efficiency of the search depends on the instructions listed in IsValidSwapInst. The more isntructions rejected by IsValidSwapInst, the sooner the search and grouping will stop. At the end, psNextInst points to the last instruction (psCurrInt) to be tested. */ for (;;) { PINST psIntermediateInst; IMG_BOOL bValidSwapInst; /* Advance to the next candidate instruction (but not if handling a dotproduct). */ psCandidateInst = psCandidateInst->psRepeatGroup->psNext; /* No suitable instructions left? */ if (psCandidateInst == NULL) { break; } if (psCandidateInst->eOpcode != psFirstInstInGroup->eOpcode) { continue; } ASSERT(IsValidSwapInst(psCandidateInst)); /* Accumulate a USE/DEF record for all the instructions between the current candidate and the instructions it will be in a repeat with. */ bValidSwapInst = IMG_TRUE; for (psIntermediateInst = psFirstInstNotInUseDefRecord; psIntermediateInst != psCandidateInst; psIntermediateInst = psIntermediateInst->psNext) { /* Skip instructions which have already been included in a group. */ if (psIntermediateInst->psRepeatGroup == NULL) { continue; } /* Check for an instruction which a future instruction can never be moved backwards over. If we find one then we can stop looking. */ if (!IsValidSwapInst(psIntermediateInst)) { bValidSwapInst = IMG_FALSE; break; } /* Instruction can be moved past, update use-def record */ ComputeInstUseDef(psState, psUseDef, psIntermediateInst, psIntermediateInst); } if (!bValidSwapInst) { break; } /* Save the first instruction after the group not included in the USE/DEF record. */ psFirstInstNotInUseDefRecord = psCandidateInst; /* Check none of the sources used by the candidate instruction are defined by an intermediate instruction. */ if (InstUseDefined(psState, &psUseDef->sDef, psCandidateInst)) { continue; } /* Check none of the registers defined by the candidate instruction are used by an intermediate instruction. */ if (InstDefReferenced(psState, &psUseDef->sUse, psCandidateInst)) { continue; } /* Check none of the registers defined by the candidate instruction are defined by an intermediate instruction. */ if (InstDefReferenced(psState, &psUseDef->sDef, psCandidateInst)) { continue; } if (bExcludeRAW) { /* Check that no register used by this instruction is defined by an earlier instruction in the group. */ if (InstUseDefined(psState, &sGroupDef, psCandidateInst)) { break; } } /* Can the instruction be added to this group using any possible MOE increment/swizzle state? */ if (TryAddToGroup(psState, psGroup, psGroup->uInstCount, psFirstInstInGroup, psCandidateInst)) { /* Don't add instructions included in the group to the USE/DEF record. */ psFirstInstNotInUseDefRecord = psCandidateInst->psNext; /* Instruction will be removed */ psGroup->apsInst[psGroup->uInstCount] = psCandidateInst; /* Add the registers efined by this instruction to the overall set for the group. */ if (bExcludeRAW) { InstDef(psState, psCandidateInst, &sGroupDef); } /* Increment the group count */ psGroup->uInstCount++; if (psGroup->uInstCount >= uMaxRepeatCount) { break; } } else { break; } } /* Free memory used to track registers used/defined in the group. */ if (bExcludeRAW) { ClearRegUseDef(psState, &sGroupDef); } } static IMG_VOID GetDotProductMOEState(PINTERMEDIATE_STATE psState, PINST psInst, PCANDIDATE_GROUP_DATA psGroup) /***************************************************************************** FUNCTION : GetDotProductMOEState PURPOSE : Get the MOE state required for a dotproduct instruction. PARAMETERS : psState - Compiler state. psInst - Dotproduct instruction. psGroup - Updated with the required MOE state. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 uIteration; IMG_UINT32 uArg; IMG_UINT32 uArgCountPerIteration; IMG_UINT32 uMOEArgStart; if (psInst->eOpcode == IFDDP_RPT) { uArgCountPerIteration = FDDP_PER_ITERATION_ARGUMENT_COUNT; uMOEArgStart = 1; } else { uArgCountPerIteration = FDP_RPT_PER_ITERATION_ARGUMENT_COUNT; uMOEArgStart = 2; } psGroup->uInstCount = psInst->u.psFdp->uRepeatCount; for (uIteration = 1; uIteration < psInst->u.psFdp->uRepeatCount; uIteration++) { for (uArg = 0; uArg < uArgCountPerIteration; uArg++) { PARG psFirstArg = &psInst->asArg[uArg]; PARG psNextArg = &psInst->asArg[uIteration * uArgCountPerIteration + uArg]; IMG_BOOL bRet; bRet = CheckArg(psState, psGroup, psFirstArg, psNextArg, uArg, uIteration, &psGroup->psMoeData[uMOEArgStart + uArg]); ASSERT(bRet); } } } static IMG_BOOL GroupInstructions(PINTERMEDIATE_STATE psState, PCODEBLOCK psCodeBlock, PINST psFirstInst, PSMLSI_STATE psMoeState, PUSEDEF_RECORD psUseDef, PMOE_SMLSI_SITE psSiteData, IMG_BOOL bInsert) /***************************************************************************** FUNCTION : GroupInstructions PURPOSE : Check if an instruction could be grouped together with those immediately following it. PARAMETERS : psState - Compiler state. psCodeBlock - The block containing the instruction to be grouped. psFirstInst - The instruction to be checked for grouping. psMoeState - The current state of the MOE increments. bLastWasGrouped - Whether the instructions preceding psFirstInst was grouped. uMinTrigger - The minimum number of instruction needed to create group . psUseDef - A use-def record for use by the routine. bInsert - If TRUE, actually group the instructions and insert MOE commands; if FALSE, just update the MOE state. OUTPUT: ppsMoeSite - Where to add any SMLSI instruction. pbHasMoeControl - True if the function (hypothetically) added any MOE control instruction. RETURNS : IMG_TRUE iff a group is formed. DESCRIPTION: Collapse a group of one or more instructions, beginning with psFirstInst to a single instruction, pointed to be psFirstInst. May emit a SMLSI instruction, if so the SMLSI is added immediately before psFirstInst. *****************************************************************************/ { IMG_UINT32 uRepeatMask = 0; /* The repeat mask */ IMG_BOOL bUseMask; IMG_BOOL bNeedSmlsi; IMG_UINT32 uArg; IMG_BOOL bUseMoe = IMG_TRUE; CANDIDATE_GROUP_DATA sGroup = {0 }; IMG_BOOL bUseMoeSite; /* Check for an instruction which can never be repeated. */ if (!CanRepeatInst(psState, psFirstInst)) { return IMG_FALSE; } /* Test instructions with repeats can only write the same predicate register as the iteration number. */ if ((g_psInstDesc[psFirstInst->eOpcode].uFlags2 & DESC_FLAGS2_TEST) != 0 && psFirstInst->u.psTest->eAluOpcode != IFDP) { PARG psPredDest; ASSERT(psFirstInst->uDestCount >= TEST_PREDICATE_DESTIDX); psPredDest = &psFirstInst->asDest[TEST_PREDICATE_DESTIDX]; ASSERT(psPredDest->uType == USEASM_REGTYPE_PREDICATE); if (psPredDest->uNumber != 0) { return IMG_FALSE; } } /* Initialize information about the candidate group. */ for (uArg = 0; uArg < (sizeof(sGroup.psMoeData) / sizeof(sGroup.psMoeData[0])); uArg++) { sGroup.psMoeData[uArg].eOperandMode = MOE_INCREMENT; sGroup.psMoeData[uArg].u.iIncrement = 1; #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) sGroup.psIncData[uArg].eOperandMode = MOE_INCREMENT; sGroup.psIncData[uArg].u.iIncrement = 1; #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ } sGroup.bPredModN = IMG_FALSE; /* Check for the dotproduct special case. */ sGroup.bDotProduct = IMG_FALSE; sGroup.bDoubleDotProduct = IMG_FALSE; sGroup.uNewDPDestNum = USC_UNDEF; if ( psFirstInst->eOpcode == IFDP_RPT || psFirstInst->eOpcode == IFDPC_RPT || psFirstInst->eOpcode == IFDP_RPT_TESTPRED || psFirstInst->eOpcode == IFDP_RPT_TESTMASK ) { sGroup.bDotProduct = IMG_TRUE; } /* Check for the double dotproduct special case. */ if (psFirstInst->eOpcode == IFDDP_RPT) { sGroup.bDoubleDotProduct = IMG_TRUE; } /* Check for no emit */ if (GetBit(psFirstInst->auFlag, INST_NOEMIT)) { return IMG_FALSE; } #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) /* Initialize special state for single issue vector instructions. */ sGroup.bSVecInst = IMG_FALSE; if (psFirstInst->eOpcode == IVDP_CP || psFirstInst->eOpcode == IVDP_GPI || psFirstInst->eOpcode == IVDP3_GPI) { sGroup.bSVecInst = IMG_TRUE; if (!SetupVDPInstGroup(psState, &sGroup, psFirstInst)) { return IMG_FALSE; } } else if (psFirstInst->eOpcode == IVADD3 || psFirstInst->eOpcode == IVMUL3 || psFirstInst->eOpcode == IVMAD4) { sGroup.bSVecInst = IMG_TRUE; SetupVMADInstGroup(&sGroup); } #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ #if defined(OUTPUT_USPBIN) if (psState->uFlags & USC_FLAGS_COMPILE_FOR_USPBIN) { if(IsInstReferingShaderResult(psState, psFirstInst)) { /* Instruction is referencing a shader result so it can not be grouped with other instructions. */ return IMG_FALSE; } } #endif /* defined(OUTPUT_USPBIN) */ /* Set capabilities */ sGroup.bInstMoeIncrement = IMG_FALSE; sGroup.bNeverUseMoe = IMG_FALSE; #if defined (SUPPORT_SGX545) /* Check for SGX545 repeats: Increments of 0 or 1 specified by the instruction or standard swizzle mode. Currently, only supported in sgx545. */ if (SupportsPerInstMoeIncrements(psState, psFirstInst)) { sGroup.bInstMoeIncrement = IMG_TRUE; } if (psState->psTargetFeatures->ui32Flags & SGX_FEATURE_FLAGS_USE_FMAD16_SWIZZLES) { if (g_psInstDesc[psFirstInst->eOpcode].uFlags & DESC_FLAGS_FARITH16) { sGroup.bNeverUseMoe = IMG_TRUE; } } #endif /* #if defined(SUPPORT_SGX545) */ /* bUseMask: Whether to use repeat mask. */ bUseMask = IMG_FALSE; /* Initialize the list of instructions in the group. */ sGroup.uInstCount = 1; sGroup.apsInst[0] = psFirstInst; if (sGroup.bDotProduct || sGroup.bDoubleDotProduct) { /* For a dotproduct a single intermediate instruction represents all the hardware instructions in the repeat. So just extract the MOE state we need to set up from the instruction. */ GetDotProductMOEState(psState, psFirstInst, &sGroup); sGroup.uInstCount = psFirstInst->u.psFdp->uRepeatCount; } else { /* Look for other instructions which can be grouped together with this one. */ FindPotentialGroup(psState, &sGroup, psFirstInst, psUseDef); } /* Return if no instructions can be grouped with this one. */ if (sGroup.uInstCount == 1) { return IMG_FALSE; } sGroup.psFirstInst = psFirstInst; sGroup.psLastInst = sGroup.apsInst[sGroup.uInstCount - 1]; /* Switch the order of the MOE increments around to match the expansion of the instructions. */ if (!RemapIncrements(psState, psFirstInst, &sGroup)) { return IMG_FALSE; } /* Check if we should create a group and whether we need to insert an SMLSI. */ if (!CheckIncrements(psState, psMoeState, &sGroup, psSiteData, &bUseMoeSite, &bUseMoe, &bNeedSmlsi, &bUseMask, &uRepeatMask)) { /* Not going to continue with the group, clean up and bail out */ return IMG_FALSE; } /* Remove the instructions which have been grouped with the first one. */ if (!sGroup.bDotProduct && !sGroup.bDoubleDotProduct) { IMG_UINT32 uInst; PINST psLastGroupChild; psLastGroupChild = psFirstInst; for (uInst = 1; uInst < sGroup.uInstCount; uInst++) { PINST psInst = sGroup.apsInst[uInst]; PINST psRepeatNext = psInst->psRepeatGroup->psNext; PINST psRepeatPrev = psInst->psRepeatGroup->psPrev; /* Remove from the per-opcode lists. */ if (psRepeatNext != NULL) psRepeatNext->psRepeatGroup->psPrev = psRepeatPrev; if (psRepeatPrev != NULL) psRepeatPrev->psRepeatGroup->psNext = psRepeatNext; if (bInsert) { UpdateLiveChansInDest(psState, psInst, psFirstInst); /* Remove the grouped instruction from the basic block and add it to a list linked from the main instruction. */ SetAsGroupChild(psState, psFirstInst, psLastGroupChild, psInst); psLastGroupChild = psInst; } else { /* First pass - don't actually modify block. Hence, rather than removing the instruction from the block, we mark it as "would have been removed" by setting its psRepeatGroup to NULL.... */ FreeRepeatGroup(psState, &psInst->psRepeatGroup); } } } /* Update the instruction flags with the repeat count/mask */ if (bInsert) { if (bUseMask) { psFirstInst->uMask = uRepeatMask; psFirstInst->uRepeat = 0; } else { psFirstInst->uMask = 0; psFirstInst->uRepeat = sGroup.uInstCount; } /* Update the predicate mode if we are repeating a predicated instruction. */ if (sGroup.bPredModN) { PARG psPredSrc = psFirstInst->apsPredSrc[0]; ASSERT(psPredSrc->uType == USEASM_REGTYPE_PREDICATE); psPredSrc->uNumber = USC_PREDREG_PNMOD4; } /* Calculate the destination register for dotproducts */ if (sGroup.bDotProduct || sGroup.bDoubleDotProduct) { IMG_UINT32 uMOEDestIdx; uMOEDestIdx = GetMOEDestIdx(sGroup.psFirstInst); if (uMOEDestIdx != USC_UNDEF) { PARG psFirstInstMOEDest; psFirstInstMOEDest = &psFirstInst->asDest[uMOEDestIdx]; /* If per-instruction MOE increments are used then the destination increment is always 1. */ if (!bUseMoe) { ASSERT(psFirstInstMOEDest->uNumber >= (sGroup.uInstCount - 1)); psFirstInstMOEDest->uNumber -= sGroup.uInstCount - 1; } /* Otherwise adjust the destination register number for the currently set MOE state. */ else if (!bNeedSmlsi) { psFirstInstMOEDest->uNumber = sGroup.uNewDPDestNum; ASSERT(psFirstInstMOEDest->uNumber <= EURASIA_USE_REGISTER_NUMBER_MAX); } } } if (bUseMoe) { IMG_BOOL bIgnoreDest; /* For dotproducts we already updated the destination register number to a value taking into account the MOE state. */ bIgnoreDest = IMG_FALSE; if (sGroup.bDotProduct) { bIgnoreDest = IMG_TRUE; } /* If we used MOE swizzle mode for any arguments then we might need to adjust the register numbers encoded in the instruction. */ AdjustRegisterNumbersForMOESwizzle(psState, sGroup.psMoeData, psFirstInst, psFirstInst->psNext, IMG_FALSE /* bAdjustToPerInstIncrements */, bIgnoreDest); } #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) /* For single-issue vector instructions set the increment mode encoded in the instruction. */ if (sGroup.bSVecInst) { psFirstInst->u.psVec->eRepeatMode = sGroup.sVec.eRepeatMode; } #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ } /* Set the instruction moe flag - even if !bInsert, as will be read by RecalcInstRegs */ SetBit(psFirstInst->auFlag, INST_MOE, bUseMoe ? 1 : 0); /* Check for a previous repeated instruction but we aren't going to make use of the MOE site directly after it. */ if (psSiteData->psLocation != NULL && (!bUseMoeSite || !bNeedSmlsi)) { /* Check if the MOE state used by the previous repeat is compatible with the instructions in between it and this instruction. */ if (IsMOEStateCompatibleWithInstructionRange(psState, psMoeState->psMoeData, psSiteData)) { if (IsNonZeroSwizzle(psMoeState->psMoeData, USC_MAX_MOE_OPERANDS)) { if (bInsert) { /* Modify the register numbers of the instructions inbetween for the previous repeat's MOE state. */ AdjustRegisterNumbersForMOESwizzle(psState, psMoeState->psMoeData, psSiteData->psLocation->psNext, psFirstInst, IMG_TRUE /* bAdjustToPerInstIncrements */, IMG_FALSE /* bIgnoreDest */); } } } else { PINST psSMLSIResetInst; /* If the current repeat is using the MOE state set up before the previous repeat then we've already checked the state is compatible with the instructions in between. */ ASSERT(bNeedSmlsi || !bUseMoe); /* Insert an SMLSI directly after the previous repeated instruction to reset the MOE state to the default */ ResetMoeOpState(psMoeState); if (bInsert) { psSMLSIResetInst = AllocateInst(psState, NULL); MoeToInst(psState, psMoeState, psSMLSIResetInst); InsertInstBefore(psState, psCodeBlock, psSMLSIResetInst, psSiteData->psLocation->psNext); } } } /* Insert an smia instruction if necessary. */ if (bUseMoe && bNeedSmlsi) { MOE_DATA sZeroData = {MOE_INCREMENT, {0}}; /* n.b. sTemp CANNOT be {MOE_INCREMENT, 1} */ MOE_DATA sDefaultData = USC_MOE_DATA_DEFAULT_VALUE; /* Set increment/swizzle values for each operand */ for (uArg = 0; uArg < sGroup.uArgCount; uArg++) { if ((sGroup.bDotProduct || sGroup.bDoubleDotProduct) && uArg == 0) { /* Zero out the MOE data for the destination */ memcpy(&sGroup.psMoeData[uArg], &sZeroData, sizeof(sZeroData)); } else if (sGroup.uSpecialConstMask & (1U << uArg)) { /* Zero out the MOE data for source which are special constants */ memcpy(&sGroup.psMoeData[uArg], &sZeroData, sizeof(sZeroData)); } else { if ((sGroup.uDontCareMask & (1U << uArg))) { /* Set MOE operands not referenced by the instruction to default values. */ memcpy(&sGroup.psMoeData[uArg], &sDefaultData, sizeof(sDefaultData)); } } } /* Handle any extra operands */ for (; uArg < USC_MAX_MOE_OPERANDS; uArg++) { if (psMoeState->pbInvalid[uArg]) { /* Reset invalid source operands */ memcpy(&sGroup.psMoeData[uArg], &sDefaultData, sizeof(sDefaultData)); } } /* Update the MOE state with the new data */ for(uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { memcpy(&psMoeState->psMoeData[uArg], &sGroup.psMoeData[uArg], sizeof(psMoeState->psMoeData[uArg])); psMoeState->pbInvalid[uArg] = IMG_FALSE; } if (bInsert) { PINST psSmiaInst; /* Form the SMLSI instruction */ #ifdef SRC_DEBUG ASSERT(psFirstInst != IMG_NULL); #endif psSmiaInst = AllocateInst(psState, psFirstInst); MoeToInst(psState, psMoeState, psSmiaInst); if (bUseMoeSite) { ASSERT(psSiteData->psLocation != NULL); /* Add the SMLSI to the code block immediately after the last repeated instruction. */ InsertInstBefore(psState, psCodeBlock, psSmiaInst, psSiteData->psLocation->psNext); /* If any of the MOE operands are using swizzle mode with a non-zero increment on iteration 0 then they affect the execution of non-repeated instructions so go through the instructions between the last repeat and the current repeat and adjust the register numbers they use to compensate. */ if (IsNonZeroSwizzle(psMoeState->psMoeData, USC_MAX_MOE_OPERANDS)) { AdjustRegisterNumbersForMOESwizzle(psState, psMoeState->psMoeData, psSmiaInst->psNext, psFirstInst, IMG_TRUE /* bAdjustToPerInstIncrements */, IMG_FALSE /* bIgnoreDest */); } } else { /* Add the SMLSI to the code block immediate before the current instruction. */ InsertInstBefore(psState, psCodeBlock, psSmiaInst, psFirstInst); } } } else if (bInsert && !bUseMoe) { ASSERT(sGroup.bInstMoeIncrement); ASSERT(sGroup.psMoeData[0].u.iIncrement == 1); /* if don't need to use MOE control, set up the instruction increment */ for (uArg = 1; uArg < USC_MAX_MOE_OPERANDS; uArg++) { IMG_INT32 iIncrement; ASSERT(sGroup.psMoeData[uArg].eOperandMode == MOE_INCREMENT); iIncrement = sGroup.psMoeData[uArg].u.iIncrement; ASSERT(iIncrement == 0 || iIncrement == 1); if (iIncrement == 0) { SetBit(psFirstInst->puSrcInc, uArg - 1, 0); } else { SetBit(psFirstInst->puSrcInc, uArg - 1, 1); } } } /* Start collecting information about whether the next repeated instruction can insert any SMLSI needed after this instruction. */ psSiteData->psLocation = psFirstInst; psSiteData->bInCompatibleInst = IMG_FALSE; for (uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { psSiteData->auMinOperandNum[uArg] = USC_UNDEF; psSiteData->auArgAlias[uArg] = USC_UNDEF; #if defined(OUTPUT_USPBIN) if (psState->uFlags & USC_FLAGS_COMPILE_FOR_USPBIN) { psSiteData->abShaderResultRef[uArg] = IMG_FALSE; } #endif /* defined(OUTPUT_USPBIN) */ } return IMG_TRUE; } static IMG_VOID SaveRegNumsBP(PINTERMEDIATE_STATE psState, PCODEBLOCK psBlock, IMG_PVOID pvNull) /***************************************************************************** FUNCTION : SaveRegNumsBP PURPOSE : Save the register numbers for each source and destination into another field. PARAMETERS : psState - Compiler state. psBlock - Block to process. pvNull - Ignored. RETURNS : Nothing. *****************************************************************************/ { PINST psInst; PVR_UNREFERENCED_PARAMETER(psState); PVR_UNREFERENCED_PARAMETER(pvNull); /* Save the old register numbers before we adjust them for the MOE. */ for (psInst = psBlock->psBody; psInst; psInst = psInst->psNext) { IMG_UINT32 i; for (i = 0; i < psInst->uDestCount; i++) { psInst->asDest[i].uNumberPreMoe = psInst->asDest[i].uNumber; if (psInst->apsOldDest[i] != NULL) { psInst->apsOldDest[i]->uNumberPreMoe = psInst->apsOldDest[i]->uNumber; } } for (i = 0; i < psInst->uArgumentCount; i++) { psInst->asArg[i].uNumberPreMoe = psInst->asArg[i].uNumber; } } } static IMG_VOID InstUsesFormatControl(PINST psInst, IMG_PBOOL pbFmtControl, IMG_PBOOL pbF16FmtControl) /***************************************************************************** FUNCTION : InstUsesFormatControl PURPOSE : Checks if an instruction will use the top-bit of the register number to select the register format. PARAMETERS : psInst - Instruction to check. pbFmtControl - Returns TRUE if the instruction uses format control. pbF16FmtControl - Returns TRUE if the format control selects between F16 and F32 register formats. RETURNS : Nothing. *****************************************************************************/ { *pbFmtControl = IMG_FALSE; if (InstUsesF16FmtControl(psInst) || HasC10FmtControl(psInst)) { IMG_UINT32 uArg; UF_REGFORMAT eFmt; if (InstUsesF16FmtControl(psInst)) { eFmt = UF_REGFORMAT_F16; *pbF16FmtControl = IMG_TRUE; } else { eFmt = UF_REGFORMAT_C10; *pbF16FmtControl = IMG_FALSE; } if (eFmt == UF_REGFORMAT_C10 && psInst->uDestCount > 0 && psInst->asDest[0].eFmt == eFmt) { *pbFmtControl = IMG_TRUE; return; } for (uArg = 0; uArg < psInst->uArgumentCount; uArg++) { if (psInst->asArg[uArg].eFmt == eFmt) { *pbFmtControl = IMG_TRUE; return; } } } } typedef struct _SMBO_ARG_DATA { /* The minimum and maximum possible values for the MOE base offset for this argument. */ IMG_UINT32 uMinBaseOffset; IMG_UINT32 uMaxBaseOffset; /* TRUE if the MOE base offset for this argument can have any value. */ IMG_UINT32 bDontCare; /* Either USC_UNDEF or the index of another MOE operand. If another operand then both operands must have exactly the same base offset. */ IMG_UINT32 uAliasArg; } SMBO_ARG_DATA, *PSMBO_ARG_DATA; static IMG_VOID GetBaseOffsetRange(PINTERMEDIATE_STATE psState, PINST psFirstInst, PINST* ppsRangeEnd, PSMBO_ARG_DATA psArgData) /***************************************************************************** FUNCTION : GetBaseOffsetRange PURPOSE : Gets the range of instructions which can use a single base offset setting. PARAMETERS : psState - Compiler state. psFirstInst - Instruction to start the range from. bFormatControl - TRUE if using the top-bit of the register number to select the register format is on for this instruction. ppsRangeEnd - Returns the first instruction not in the range. auRegNumMin - For each argument returns the range of auRegNumMax register numbers used in the argument. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 uArg; PINST psInst; *ppsRangeEnd = psFirstInst->psNext; /* Initialize the return data for each argument. */ for (uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { psArgData[uArg].bDontCare = IMG_TRUE; psArgData[uArg].uAliasArg = USC_UNDEF; } /* Find all the instructions which can share a single base offset setting. */ for (psInst = psFirstInst; psInst != NULL; psInst = psInst->psNext) { SMBO_ARG_DATA asNewArgData[USC_MAX_MOE_OPERANDS]; IMG_BOOL bFormatControl; IMG_BOOL bF16FormatControl; PARG apsArgs[USC_MAX_MOE_OPERANDS]; IMG_UINT32 auArgIdxs[USC_MAX_MOE_OPERANDS]; IMG_UINT32 auArgAliases[USC_MAX_MOE_OPERANDS]; InstUsesFormatControl(psInst, &bFormatControl, &bF16FormatControl); for (uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { /* Default to no change in the data for this argument. */ asNewArgData[uArg] = psArgData[uArg]; } /* Get the mapping of MOE operands to sources/destinations of this instruction. */ GetArgumentsAffectedByMOESwizzles(psState, psInst, IMG_FALSE /* bAdjustToPerInstIncrements */, apsArgs, auArgIdxs, auArgAliases); for (uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { PSMBO_ARG_DATA psOldArgData = &psArgData[uArg]; PSMBO_ARG_DATA psNewArgData = &asNewArgData[uArg]; SMBO_ARG_DATA sInstArgData; PARG psArg = apsArgs[uArg]; IMG_UINT32 uMaxAddressableRegNum; IMG_UINT32 uArgAlias = auArgAliases[uArg]; IMG_BOOL bDest = (uArg == 0) ? IMG_TRUE : IMG_FALSE; /* Check for an MOE operand which requires the same MOE state as a previous operand. */ if (uArgAlias != USC_UNDEF) { /* For simplicity don't include in a range both instructions which require the same base offset setting for multiple MOE operands and instructions which directly reference the aliased operands. */ if ( !psOldArgData->bDontCare || ( psOldArgData->uAliasArg != USC_UNDEF && psOldArgData->uAliasArg != uArgAlias ) ) { return; } /* Flag that this MOE operand must be given exactly the same base offset as the previous operand. */ psNewArgData->uAliasArg = uArgAlias; continue; } /* Skip MOE operands not used by the instruction. */ if (psArg == NULL) { continue; } /* For simplicity don't include in a range both instructions which require the same base offset setting for multiple MOE operands and instructions which directly reference the aliased operands. */ if (psOldArgData->uAliasArg != USC_UNDEF) { return; } /* Get the maximum register number which can be directly encoded by this instruction. */ uMaxAddressableRegNum = GetMaxAddressableRegNum(psState, psInst, bDest, auArgIdxs[uArg], psArg, bFormatControl, bF16FormatControl); /* Get the maximum and minimum base offsets which can be used with this instruction argument. */ sInstArgData.uMaxBaseOffset = psArg->uNumber; if (psArg->uNumber < uMaxAddressableRegNum) { sInstArgData.uMinBaseOffset = 0; } else { sInstArgData.uMinBaseOffset = psArg->uNumber - uMaxAddressableRegNum; } ASSERT(sInstArgData.uMinBaseOffset <= sInstArgData.uMaxBaseOffset); if (psOldArgData->bDontCare) { /* If this argument wasn't previously referenced in the range then set all the data from this instruction. */ psNewArgData->bDontCare = IMG_FALSE; psNewArgData->uMinBaseOffset = sInstArgData.uMinBaseOffset; psNewArgData->uMaxBaseOffset = sInstArgData.uMaxBaseOffset; } else { /* Finish the range if the range of register numbers is too large to be handled by a single base offset setting. */ if (sInstArgData.uMaxBaseOffset < psNewArgData->uMinBaseOffset || sInstArgData.uMinBaseOffset > psNewArgData->uMaxBaseOffset) { return; } /* Store the updated data for this argument. */ psNewArgData->uMinBaseOffset = max(psNewArgData->uMinBaseOffset, sInstArgData.uMinBaseOffset); psNewArgData->uMaxBaseOffset = min(psNewArgData->uMaxBaseOffset, sInstArgData.uMaxBaseOffset); } } /* We are including this instruction in the range so update the information about register numbers used. */ for (uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { psArgData[uArg] = asNewArgData[uArg]; } /* Set the first instruction not in the range. */ *ppsRangeEnd = psInst->psNext; } } static IMG_VOID AdjustArgumentByBaseOffset(PINTERMEDIATE_STATE psState, PSMBO_STATE psMoeState, PARG psArg, IMG_UINT32 uMOEArg) /***************************************************************************** FUNCTION : AdjustArgumentByBaseOffset PURPOSE : Adjust an instruction argument for the currently set MOE base offset. PARAMETERS : psState - Compiler state. psMoeState - Base offset state. psArg - Argument to adjust. uMOEArg - MOE operand used by this argument. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 uArgBaseOffset; uArgBaseOffset = psMoeState->puBaseOffsets[uMOEArg]; ASSERT(psArg->uNumber >= uArgBaseOffset); psArg->uNumber -= uArgBaseOffset; } static IMG_VOID CheckBaseOffset(PINTERMEDIATE_STATE psState, PCODEBLOCK psBlock, PINST psFirstInst, PSMBO_STATE psMoeState, PINST* ppsNextInst, //*always* set IMG_BOOL bInsertInst) /***************************************************************************** FUNCTION : CheckBaseOffset PURPOSE : Insert any SMBO instruction needed by a range of instructions. PARAMETERS : psState - Compiler state. psBlock - Block which contains the instructions to check. psFirstInst - First instruction in the range. psMoeState - Current base offset state. ppsNextInst - Returns the first instruction after the range checked. bInsertInst - If TRUE then the SMBO is actually inserted. If FALSE then only the state is updated. RETURNS : Nothing. *****************************************************************************/ { IMG_BOOL bNeedSMBO = IMG_FALSE; IMG_UINT32 uArg; IMG_UINT32 puNewBaseOffset[USC_MAX_MOE_OPERANDS]; PINST psRangeStart, psRangeEnd; PINST psInst; SMBO_ARG_DATA asRangeArgData[USC_MAX_MOE_OPERANDS]; /* Get the range of instruction to set a single set of base offset values for and the range of register numbers used in the instructions. */ GetBaseOffsetRange(psState, psFirstInst, &psRangeEnd, asRangeArgData); psRangeStart = psFirstInst; *ppsNextInst = psRangeEnd; for (uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { PSMBO_ARG_DATA psArgData = &asRangeArgData[uArg]; /* Set the default for the new base offset from the current state. */ if (psMoeState->pbInvalidBaseOffsets[uArg]) { puNewBaseOffset[uArg] = 0; } else { puNewBaseOffset[uArg] = psMoeState->puBaseOffsets[uArg]; } /* Check for an operand which must have the same base offset as another operand. */ if (psArgData->uAliasArg != USC_UNDEF) { IMG_UINT32 uAliasArg; uAliasArg = psArgData->uAliasArg; ASSERT(uAliasArg < USC_MAX_MOE_OPERANDS); ASSERT(!asRangeArgData[uAliasArg].bDontCare); ASSERT(psArgData->bDontCare); puNewBaseOffset[uArg] = puNewBaseOffset[uAliasArg]; if (psMoeState->pbInvalidBaseOffsets[uArg] || psMoeState->puBaseOffsets[uArg] != psMoeState->puBaseOffsets[uAliasArg]) { bNeedSMBO = IMG_TRUE; } } /* Skip MOE arguments not used by an instruction in the range. */ if (psArgData->bDontCare) { continue; } ASSERT(psArgData->uMinBaseOffset <= psArgData->uMaxBaseOffset); ASSERT(psArgData->uMaxBaseOffset < EURASIA_USE_NUM_UNIFIED_REGISTERS); /* Can the register number for this argument be encoded given the current base offset setting? */ if ( psMoeState->pbInvalidBaseOffsets[uArg] || psMoeState->puBaseOffsets[uArg] < psArgData->uMinBaseOffset || psMoeState->puBaseOffsets[uArg] > psArgData->uMaxBaseOffset ) { bNeedSMBO = IMG_TRUE; /* If possible set the base offset to 0 to avoid having to insert more SMBOs before future instructions which use lower register numbers. */ if (psArgData->uMinBaseOffset == 0) { puNewBaseOffset[uArg] = 0; } else { puNewBaseOffset[uArg] = psArgData->uMinBaseOffset; } } } /* Insert an SMBO instruction before the current instruction to set the MOE base offsets. */ if (bNeedSMBO) { for (uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { psMoeState->pbInvalidBaseOffsets[uArg] = IMG_FALSE; psMoeState->puBaseOffsets[uArg] = puNewBaseOffset[uArg]; } if (bInsertInst) { PINST psSmboInst; psSmboInst = AllocateInst(psState, psFirstInst); SetOpcodeAndDestCount(psState, psSmboInst, ISMBO, 0 /* uDestCount */); for (uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { psSmboInst->asArg[uArg].uType = USEASM_REGTYPE_IMMEDIATE; psSmboInst->asArg[uArg].uNumber = puNewBaseOffset[uArg]; } /* Initialise instruction group data. */ FreeRepeatGroup(psState, &psSmboInst->psRepeatGroup); InsertInstBefore(psState, psBlock, psSmboInst, psFirstInst); } } if (bInsertInst) { /* Adjust all the registers number down by the currently set base offset values. */ for (psInst = psRangeStart; psInst != psRangeEnd; psInst = psInst->psNext) { PARG apsArgs[USC_MAX_MOE_OPERANDS]; IMG_UINT32 auArgAliases[USC_MAX_MOE_OPERANDS]; if (GetBit(psInst->auFlag, INST_NOEMIT)) { continue; } /* Get the mapping of MOE operands to sources/destinations of this instruction. */ GetArgumentsAffectedByMOESwizzles(psState, psInst, IMG_FALSE /* bAdjustToPerInstIncrements */, apsArgs, NULL /* uArgIdxs */, auArgAliases); for (uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { IMG_UINT32 uArgAlias = auArgAliases[uArg]; PARG psArg = apsArgs[uArg]; /* Where a single argument to the instruction corresponds to multiple MOE operands adjust the register number only for the first operand. */ if (uArgAlias != USC_UNDEF) { ASSERT(asRangeArgData[uArg].uAliasArg == uArgAlias); ASSERT(psMoeState->puBaseOffsets[uArgAlias] == psMoeState->puBaseOffsets[uArg]); continue; } /* Skip MOE operands not used by this instruction. */ if (psArg == NULL) { continue; } /* Subtract the MOE base offset from the register number. */ AdjustArgumentByBaseOffset(psState, psMoeState, psArg, uArg); } } } } #if defined(OUTPUT_USPBIN) /***************************************************************************** FUNCTION : RecordSetfcStateForBlock PURPOSE : Record the MOE format control state at the start of a basic-block PARAMETERS : psBlock - The block in which to record the MOE state psMoeState - MOE state at the start of the block RETURNS : Nothing. *****************************************************************************/ static IMG_VOID RecordSetfcStateForBlock(PCODEBLOCK psBlock, PSETFC_STATE psMoeState) { if (psMoeState->aeFlag[FORMAT_CONTROL_FLAG_TYPE_EFO] == FORMAT_CONTROL_FLAG_ON) { psBlock->bEfoFmtCtl = IMG_TRUE; } else { psBlock->bEfoFmtCtl = IMG_FALSE; } if (psMoeState->aeFlag[FORMAT_CONTROL_FLAG_TYPE_COLOUR] == FORMAT_CONTROL_FLAG_ON) { psBlock->bColFmtCtl = IMG_TRUE; } else { psBlock->bColFmtCtl = IMG_FALSE; } } /***************************************************************************** FUNCTION : RecordSmboStateForBlock PURPOSE : Record the MOE base offsets state at the start of a basic-block PARAMETERS : psBlock - The block in which to record the MOE state psMoeState - MOE state at the start of the block RETURNS : Nothing. *****************************************************************************/ static IMG_VOID RecordSmboStateForBlock(PCODEBLOCK psBlock, PSMBO_STATE psMoeState) { IMG_UINT32 uArg; for (uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { psBlock->auMoeBaseOffset[uArg] = psMoeState->puBaseOffsets[uArg]; } } /***************************************************************************** FUNCTION : RecordSmlsiStateForBlock PURPOSE : Record the MOE increment state at the start of a basic-block PARAMETERS : psBlock - The block in which to record the MOE state psMoeState - MOE state at the start of the block RETURNS : Nothing. *****************************************************************************/ static IMG_VOID RecordSmlsiStateForBlock(PCODEBLOCK psBlock, PSMLSI_STATE psMoeState) { IMG_UINT32 uArg; for (uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { psBlock->asMoeIncSwiz[uArg] = psMoeState->psMoeData[uArg]; } } #endif /* defined(OUTPUT_USPBIN) */ static IMG_VOID FreeGroupInstState(PINTERMEDIATE_STATE psState, PGROUPINST_STATE psGIState) /***************************************************************************** FUNCTION : FreeGroupInstState PURPOSE : Finalise and free instruction grouping data PARAMETERS : psState - Compiler state. OUTPUT : ppsGIState - Instruction grouping state RETURNS : Nothing. *****************************************************************************/ { UscFree(psState, psGIState->asFunc); ClearUseDef(psState, &psGIState->sUseDef); UscFree(psState, psGIState); } static IMG_UINT32 CheckPossibleSwizzle(PINTERMEDIATE_STATE psState, IMG_UINT32 uArgCount, IMG_UINT32 puArgMap[][USC_MAX_MOE_OPERANDS], IMG_UINT32 puArgMin[], IMG_UINT32 uInstCount) /***************************************************************************** FUNCTION : CheckPossibleSwizzle PURPOSE : Check if a sequence of register number could be generated by an MOE increment or swizzle. PARAMETERS : uArgCount - Count of the arguments to check. puArgMap - Register numbers for each argument. puArgMin - Minimum register number for each argument. uInstCount - Sequence length. RETURNS : The maximum sequence length. *****************************************************************************/ { IMG_UINT32 uArg, uMaxRepeat; IMG_INT32 iMinIncrement, iMaxIncrement; #if !defined(SUPPORT_SGX545) PVR_UNREFERENCED_PARAMETER(psState); #endif #if defined(SUPPORT_SGX545) if (psState->psTargetFeatures->ui32Flags & SGX_FEATURE_FLAGS_USE_PER_INST_MOE_INCREMENTS) { uMaxRepeat = SGX545_USE1_FLOAT_RCOUNT_MAXIMUM; iMinIncrement = USC_MIN_SMALL_INCREMENT_INC; iMaxIncrement = USC_MAX_SMALL_INCREMENT_INC; } else #endif /* defined(SUPPORT_SGX545) */ { uMaxRepeat = EURASIA_USE_MAXIMUM_REPEAT; iMinIncrement = USC_MIN_INCREMENT_INC; iMaxIncrement = USC_MAX_INCREMENT_INC; } for (uArg = 0; uArg < uArgCount; uArg++) { IMG_UINT32 uInst, uIncrMax, uSwizMax; IMG_INT32 piGap[USC_MAX_MOE_OPERANDS]; /* Check if an increment is possible - if the first register number is M then we need G so the nth register number is M + Gn */ piGap[uArg] = puArgMap[1][uArg] - puArgMap[0][uArg]; if (piGap[uArg] > iMaxIncrement || piGap[uArg] < iMinIncrement) { uIncrMax = 0; } else { for (uInst = 2; uInst < uInstCount; uInst++) { if (puArgMap[uInst][uArg] != ((piGap[uArg] * uInst) + puArgMap[0][uArg])) { break; } } uIncrMax = min(uInst, uInstCount); } /* Check if a swizzle is possible - the maximum range of register numbers needs to be 3 or less. */ for (uInst = 0; uInst < min(uInstCount, 4); uInst++) { if ((puArgMap[uInst][uArg] - puArgMin[uArg]) > USC_MAX_SWIZZLE_INC) { break; } } uSwizMax = min(uInst, uInstCount); /* The overall repeat is maximum available through either increment or swizzle mode. */ uMaxRepeat = min(uMaxRepeat, max(uIncrMax, uSwizMax)); } return uMaxRepeat; } static IMG_UINT32 GetMOERegisterNumber(PINTERMEDIATE_STATE psState, PINST psNextInst, IMG_UINT32 uArg) /***************************************************************************** FUNCTION : GetMOERegisterNumber PURPOSE : Get the register number for an argument as it would be encoded in the hardware instruction. PARAMETERS : psNextInst - Instruction to get the register number from. uArg - Argument index to get the register number from. RETURNS : The register number. *****************************************************************************/ { IMG_UINT32 uNumber; PARG psArg = &psNextInst->asArg[uArg]; if (psArg->eFmt == UF_REGFORMAT_F16) { IMG_UINT32 uComponent; uNumber = psArg->uNumber << EURASIA_USE_FMTF16_REGNUM_SHIFT; uComponent = GetComponentSelect(psState, psNextInst, uArg); ASSERT(uComponent == 0 || uComponent == 2); if (uComponent == 2) { uNumber |= EURASIA_USE_FMTF16_SELECTHIGH; } } else { uNumber = psArg->uNumber; } return uNumber; } static IMG_BOOL EqualArgModes(PINTERMEDIATE_STATE psState, PINST psInst1, IMG_UINT32 uArg1Idx, PINST psInst2, IMG_UINT32 uArg2Idx) /***************************************************************************** FUNCTION : EqualArgModes PURPOSE : Check if two arguments are equal apart from the register number. PARAMETERS : psState - Compiler state. psInst1 - First argument to compare. uArg1Idx psInst2 - Second argument to compare. uArg2Idx RETURNS : TRUE or FALSE. *****************************************************************************/ { PARG psArg1 = &psInst1->asArg[uArg1Idx]; PARG psArg2 = &psInst2->asArg[uArg2Idx]; PFLOAT_SOURCE_MODIFIER psMod1; PFLOAT_SOURCE_MODIFIER psMod2; psMod1 = GetFloatMod(psState, psInst1, uArg1Idx); psMod2 = GetFloatMod(psState, psInst2, uArg2Idx); if (psArg1->uType != psArg2->uType || psArg1->uIndexType != psArg2->uIndexType || psArg1->uIndexNumber != psArg2->uIndexNumber || psArg1->uIndexStrideInBytes != psArg2->uIndexStrideInBytes || psArg1->eFmt != psArg2->eFmt) { return IMG_FALSE; } if (psMod1->bNegate != psMod2->bNegate || psMod1->bAbsolute != psMod2->bAbsolute) { return IMG_FALSE; } return IMG_TRUE; } static IMG_VOID CopyArgumentToDP(PINTERMEDIATE_STATE psState, PINST psDPInst, IMG_UINT32 uDestArg, PINST psSrcInst, IMG_UINT32 uSrcArg) /***************************************************************************** FUNCTION : CopyArgumentToDP PURPOSE : Copy an argument from a floating point instruction to a FDP_RPT/FDDP instruction. PARAMETERS : psState - Compiler state. psDPInst - Instruction to copy to. uDestArg - Argument to copy to. psSrcInst - Instruction to copy from. uSrcArg - Argument to copy from. RETURNS : Nothing. *****************************************************************************/ { MoveSrc(psState, psDPInst, uDestArg, psSrcInst, uSrcArg); SetComponentSelect(psState, psDPInst, uDestArg, GetComponentSelect(psState, psSrcInst, uSrcArg)); } static IMG_VOID CopyNegateAbsoluteModifierToFDP(PINTERMEDIATE_STATE psState, PINST psDPInst, IMG_UINT32 uArgCountPerIteration, PINST psFloatInst) /***************************************************************************** FUNCTION : CopyNegateAbsoluteModifierToFDP PURPOSE : Copy the negate and absolute source modifiers for each argument from a floating point instruction to a FDP_RPT or FDDP instruction. PARAMETERS : psState - Compiler state. psDPInst - Instruction to copy to. uArgCountPerIteration - Number of source arguments read on each iteration. psFloatInst - Instruction to copy from. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 uArg; for (uArg = 0; uArg < uArgCountPerIteration; uArg++) { PFLOAT_SOURCE_MODIFIER psMod = GetFloatMod(psState, psFloatInst, uArg); psDPInst->u.psFdp->abNegate[uArg] = psMod->bNegate; psDPInst->u.psFdp->abAbsolute[uArg] = psMod->bAbsolute; } } static IMG_BOOL GenerateFDP(PINTERMEDIATE_STATE psState, PCODEBLOCK psBlock, PINST psFirstInst, PINST* ppsNextInst) /***************************************************************************** FUNCTION : GenerateFDP PURPOSE : Generate dotproduct instructions. PARAMETERS : psState - Compiler state. psBlock - Block containing the first instruction. psInst - First instruction in the DP sequence. ppsNextInst - Updated with the first valid instruction after psInst. RETURNS : TRUE if a dotproduct was generated. *****************************************************************************/ { PINST psNextInst, psPrevInst; IMG_UINT32 uDotCount; IMG_UINT32 uRepeatCount; IMG_UINT32 uArg; IMG_BOOL abSwapArgs[EURASIA_USE_MAXIMUM_REPEAT]; PARG psAccumSrc; PINST psFDPInst; IMG_UINT32 uInst; PINST psNextNextInst; IMG_UINT32 puArgMap[EURASIA_USE_MAXIMUM_REPEAT][USC_MAX_MOE_OPERANDS]; IMG_UINT32 puArgMin[USC_MAX_MOE_OPERANDS]; uDotCount = 1; abSwapArgs[0] = IMG_FALSE; /* Get the register numbers for the first instruction. */ for (uArg = 0; uArg < FDP_RPT_PER_ITERATION_ARGUMENT_COUNT; uArg++) { puArgMap[0][uArg] = puArgMin[uArg] = GetMOERegisterNumber(psState, psFirstInst, uArg); } for (psNextInst = psFirstInst->psNext, psPrevInst = psFirstInst; psNextInst != NULL; psPrevInst = psNextInst, psNextInst = psNextInst->psNext) { #if defined(OUTPUT_USPBIN) if (psState->uFlags & USC_FLAGS_COMPILE_FOR_USPBIN) { if(IsInstReferingShaderResult(psState, psNextInst)) { break; } } #endif /* defined(OUTPUT_USPBIN) */ /* Check for different instruction modes. */ if (!(psNextInst->eOpcode == IFMAD && EqualPredicates(psNextInst, psFirstInst))) { break; } /* Check the arguments are of the same type and have the same modes. */ if (EqualArgModes(psState, psNextInst, 0 /* uArgIdx */, psFirstInst, 0 /* uArgIdx */) && EqualArgModes(psState, psNextInst, 1 /* uArgIdx */, psFirstInst, 1 /* uArgIdx */)) { abSwapArgs[uDotCount] = IMG_FALSE; } else if (EqualArgModes(psState, psNextInst, 0 /* uArgIdx */, psFirstInst, 1 /* uArgIdx */) && EqualArgModes(psState, psNextInst, 1 /* uArgIdx */, psFirstInst, 0 /* uArgIdx */)) { abSwapArgs[uDotCount] = IMG_TRUE; } else { break; } /* Check the third source to theMAD instruction is the same as the result of the previous dotproduct stage. */ psAccumSrc = &psNextInst->asArg[2]; if (!EqualArgs(psAccumSrc, &psPrevInst->asDest[0])) { break; } /* Check the third source to the next MAD instruction has no source modifiers. */ if (HasNegateOrAbsoluteModifier(psState, psNextInst, 2 /* uArgIdx */)) { break; } /* Check the result of the previous dotproduct stage is used only here. */ if (!UseDefIsSingleSourceRegisterUse(psState, psNextInst, 2 /* uSrcIdx */)) { break; } /* Save the register numbers. */ for (uArg = 0; uArg < FDP_RPT_PER_ITERATION_ARGUMENT_COUNT; uArg++) { IMG_UINT32 uNumber; IMG_UINT32 uSrcArg; if (abSwapArgs[uDotCount]) { uSrcArg = 1 - uArg; } else { uSrcArg = uArg; } uNumber = GetMOERegisterNumber(psState, psNextInst, uSrcArg); puArgMap[uDotCount][uArg] = uNumber; puArgMin[uArg] = min(puArgMin[uArg], uNumber); } uDotCount++; if (uDotCount == EURASIA_USE_MAXIMUM_REPEAT) { break; } } if (uDotCount <= 1) { return IMG_FALSE; } /* Check if we could group the dotproducts using the MOE. */ uRepeatCount = CheckPossibleSwizzle(psState, FDP_RPT_PER_ITERATION_ARGUMENT_COUNT, puArgMap, puArgMin, uDotCount); if (uRepeatCount <= 1) { return IMG_FALSE; } /* Create the new dotproduct instruction. */ psFDPInst = AllocateInst(psState, psFirstInst); SetOpcode(psState, psFDPInst, IFDP_RPT); /* Insert before the first instruction in the sequence. */ InsertInstBefore(psState, psBlock, psFDPInst, psFirstInst); #if defined(SRC_DEBUG) /* Flag that this instruction will cost the same number of cycles as the number of iterations in the repeat. */ IncrementCostCounter(psState, psFDPInst->uAssociatedSrcLine, uRepeatCount - 1); #endif /* defined(SRC_DEBUG) */ /* Copy the source predicate from the first instruction in the sequence. */ CopyPredicate(psState, psFDPInst, psFirstInst); /* Set the number of iterations. */ psFDPInst->u.psFdp->uRepeatCount = uRepeatCount; /* Copy the source modifiers from the first instruction in the sequence. */ CopyNegateAbsoluteModifierToFDP(psState, psFDPInst, FDP_RPT_PER_ITERATION_ARGUMENT_COUNT, psFirstInst); /* Copy the SKIPINVALID flag from the first instruction in the sequence. Because the result of each instruction is only used in the next instruction in the dotproduct sequence the SKIPINV flag must be the same for all instructions. */ SetBit(psFDPInst->auFlag, INST_SKIPINV, GetBit(psFirstInst->auFlag, INST_SKIPINV)); for (uInst = 0, psNextInst = psFirstInst; uInst < uRepeatCount; uInst++, psNextInst = psNextNextInst) { IMG_UINT32 uIterationArgBase; psNextNextInst = psNextInst->psNext; ASSERT(GetBit(psFDPInst->auFlag, INST_SKIPINV) == GetBit(psNextInst->auFlag, INST_SKIPINV)); uIterationArgBase = uInst * FDP_RPT_PER_ITERATION_ARGUMENT_COUNT; /* Copy the source arguments from the instruction for this iteration of the dotproduct. */ if (abSwapArgs[uInst]) { ASSERT(uInst > 0); CopyArgumentToDP(psState, psFDPInst, uIterationArgBase + 0, psNextInst, 1 /* uSrcArg */); CopyArgumentToDP(psState, psFDPInst, uIterationArgBase + 1, psNextInst, 0 /* uSrcArg */); } else { CopyArgumentToDP(psState, psFDPInst, uIterationArgBase + 0, psNextInst, 0 /* uSrcArg */); CopyArgumentToDP(psState, psFDPInst, uIterationArgBase + 1, psNextInst, 1 /* uSrcArg */); } /* Copy the dotproduct destination from the last instruction in the sequence. */ if (uInst == (uRepeatCount - 1)) { MoveDest(psState, psFDPInst, 0 /* uMoveToDestIdx */, psNextInst, 0 /* uMoveFromDestIdx */); } /* Free the old instruction. */ if ((*ppsNextInst) == psNextInst) { (*ppsNextInst) = psNextInst->psNext; } RemoveInst(psState, psBlock, psNextInst); FreeInst(psState, psNextInst); } return IMG_TRUE; } static IMG_BOOL GenerateFDDP(PINTERMEDIATE_STATE psState, PCODEBLOCK psBlock, PINST psFirstInst, PINST* ppsNextInst) /***************************************************************************** FUNCTION : GenerateFDDP PURPOSE : Generate double dotproduct instructions. PARAMETERS : psState - Compiler state. psBlock - Block containing the first instruction. psInst - First instruction in the DDP sequence. ppsNextInst - Updated with the first valid instruction after psInst. RETURNS : TRUE if a double dotproduct was generated. *****************************************************************************/ { EFO_SRC eOtherSrc; IMG_UINT32 uIRegDestNum; IMG_BOOL bRotateArgs = IMG_FALSE; PINST psNextInst; IMG_BOOL bLast = IMG_FALSE; IMG_UINT32 uDotCount; IMG_BOOL bSwapArgs = IMG_FALSE; IMG_UINT32 uArg; PINST psFDDPInst; PINST psNextNextInst; IMG_UINT32 uInst; IMG_UINT32 const* puArgRemap; IMG_UINT32 puArgMap[EURASIA_USE_MAXIMUM_REPEAT][USC_MAX_MOE_OPERANDS]; IMG_UINT32 puArgMin[USC_MAX_MOE_OPERANDS]; static const IMG_UINT32 auNoRotateNoSwap[FDDP_PER_ITERATION_ARGUMENT_COUNT] = {0, 1, 2}; static const IMG_UINT32 auRotateNoSwap[FDDP_PER_ITERATION_ARGUMENT_COUNT] = {2, 0, 1}; static const IMG_UINT32 auNoRotateSwap[FDDP_PER_ITERATION_ARGUMENT_COUNT] = {0, 2, 1}; static const IMG_UINT32 auRotateSwap[FDDP_PER_ITERATION_ARGUMENT_COUNT] = {2, 1, 0}; #if defined(OUTPUT_USPBIN) if(psState->uFlags & USC_FLAGS_COMPILE_FOR_USPBIN) { if(IsInstReferingShaderResult(psState, psFirstInst)) { return IMG_FALSE; } } #endif /* defined(OUTPUT_USPBIN) */ /* Check that the EFO is suitable to be the first stage in a DDP. */ if ((psState->psTargetFeatures->ui32Flags & SGX_FEATURE_FLAGS_USE_NEW_EFO_OPTIONS) == 0 && psFirstInst->u.psEfo->bIgnoreDest && psFirstInst->u.psEfo->bWriteI0 && psFirstInst->u.psEfo->bWriteI1 && psFirstInst->u.psEfo->eI0Src == M0 && psFirstInst->u.psEfo->eI1Src == M1 && psFirstInst->u.psEfo->eM0Src0 == SRC0 && psFirstInst->u.psEfo->eM0Src1 == SRC1 && psFirstInst->u.psEfo->eM1Src0 == SRC0 && psFirstInst->u.psEfo->eM1Src1 == SRC2) { } else if ((psState->psTargetFeatures->ui32Flags & SGX_FEATURE_FLAGS_USE_NEW_EFO_OPTIONS) != 0 && psFirstInst->u.psEfo->bIgnoreDest && psFirstInst->u.psEfo->bWriteI0 && psFirstInst->u.psEfo->bWriteI1 && psFirstInst->u.psEfo->eI0Src == M0 && psFirstInst->u.psEfo->eI1Src == M1 && psFirstInst->u.psEfo->eM0Src0 == SRC0 && psFirstInst->u.psEfo->eM0Src1 == SRC2 && psFirstInst->u.psEfo->eM1Src0 == SRC1 && psFirstInst->u.psEfo->eM1Src1 == SRC2 && CanUseSource0(psState, psBlock->psOwner->psFunc, &psFirstInst->asArg[2])) { bRotateArgs = IMG_TRUE; } else { return IMG_FALSE; } /* Save the register numbers for the first instruction. */ for (uArg = 0; uArg < FDDP_PER_ITERATION_ARGUMENT_COUNT; uArg++) { puArgMap[0][uArg] = puArgMin[uArg] = GetMOERegisterNumber(psState, psFirstInst, uArg); } uDotCount = 1; for (psNextInst = psFirstInst->psNext; psNextInst != NULL; psNextInst = psNextInst->psNext) { #if defined(OUTPUT_USPBIN) if (psState->uFlags & USC_FLAGS_COMPILE_FOR_USPBIN) { if(IsInstReferingShaderResult(psState, psNextInst)) { break; } } #endif /* defined(OUTPUT_USPBIN) */ if (psNextInst->eOpcode != IEFO) { break; } /* Check for different argument types or modes. */ for (uArg = 0; uArg < FDDP_PER_ITERATION_ARGUMENT_COUNT; uArg++) { if (!EqualArgModes(psState, psNextInst, uArg, psFirstInst, uArg)) { break; } } if (uArg < FDDP_PER_ITERATION_ARGUMENT_COUNT) { break; } /* Check for a different instruction predicate. */ if (!EqualPredicates(psNextInst, psFirstInst)) { break; } /* Check that the EFO has the right modes to be the next stage in a DDP. */ if (!IsDoubleDotProduct(psNextInst, &bLast, bRotateArgs)) { break; } /* Save the register numbers. */ for (uArg = 0; uArg < FDDP_PER_ITERATION_ARGUMENT_COUNT; uArg++) { IMG_UINT32 uNumber; uNumber = GetMOERegisterNumber(psState, psNextInst, uArg); puArgMap[uDotCount][uArg] = uNumber; puArgMin[uArg] = min(puArgMin[uArg], uNumber); } uDotCount++; if (uDotCount == FDDP_MAXIMUM_REPEAT) { break; } if (bLast) { break; } } if (!bLast || uDotCount <= 1) { return IMG_FALSE; } /* Check if we need to swap the arguments to a double dotproduct. */ eOtherSrc = psNextInst->u.psEfo->bWriteI0 ? psNextInst->u.psEfo->eI0Src : psNextInst->u.psEfo->eI1Src; if (eOtherSrc == A0) { ASSERT(psNextInst->u.psEfo->eDSrc == A1); bSwapArgs = IMG_TRUE; } uIRegDestNum = psNextInst->u.psEfo->bWriteI0 ? 0 : 1; /* Check if we can group the EFOs into a DDP using the MOE. */ if (CheckPossibleSwizzle(psState, FDDP_PER_ITERATION_ARGUMENT_COUNT, puArgMap, puArgMin, uDotCount) != uDotCount) { return IMG_FALSE; } if (bRotateArgs) { puArgRemap = bSwapArgs ? auRotateSwap : auRotateNoSwap; } else { puArgRemap = bSwapArgs ? auNoRotateSwap : auNoRotateNoSwap; } /* Create the new dotproduct instruction. */ psFDDPInst = AllocateInst(psState, psFirstInst); SetOpcodeAndDestCount(psState, psFDDPInst, IFDDP_RPT, 2 /* uNewDestCount */); /* Insert before the first instruction in the sequence. */ InsertInstBefore(psState, psBlock, psFDDPInst, psFirstInst); #if defined(SRC_DEBUG) /* Flag that this instruction will cost the same number of cycles as the number of iterations in the repeat. */ IncrementCostCounter(psState, psFDDPInst->uAssociatedSrcLine, uDotCount - 1); #endif /* defined(SRC_DEBUG) */ /* Copy the source predicate from the first instruction in the sequence. */ CopyPredicate(psState, psFDDPInst, psFirstInst); /* Set the number of iterations. */ psFDDPInst->u.psFdp->uRepeatCount = uDotCount; /* Copy the source modifiers from the first instruction in the sequence. */ for (uArg = 0; uArg < FDDP_PER_ITERATION_ARGUMENT_COUNT; uArg++) { PFLOAT_SOURCE_MODIFIER psMod = GetFloatMod(psState, psFirstInst, puArgRemap[uArg]); psFDDPInst->u.psFdp->abNegate[uArg] = psMod->bNegate; psFDDPInst->u.psFdp->abAbsolute[uArg] = psMod->bAbsolute; } /* Copy the destination for the first dot-product result from the last instruction in the sequence. */ MoveDest(psState, psFDDPInst, 0 /* uMoveDestIdx */, psNextInst, EFO_US_DEST /* uMoveFromDestIdx */); psFDDPInst->auLiveChansInDest[0] = psNextInst->auLiveChansInDest[EFO_US_DEST]; /* Add the internal register for the second dot-product result as an extra destination. */ SetDest(psState, psFDDPInst, 1 /* uDestIdx */, USEASM_REGTYPE_FPINTERNAL, uIRegDestNum, UF_REGFORMAT_F32); psFDDPInst->auLiveChansInDest[1] = USC_ALL_CHAN_MASK; /* Copy the SKIPINVALID flag from the first instruction in the sequence. */ SetBit(psFDDPInst->auFlag, INST_SKIPINV, GetBit(psFirstInst->auFlag, INST_SKIPINV)); for (uInst = 0, psNextInst = psFirstInst; uInst < uDotCount; uInst++, psNextInst = psNextNextInst) { IMG_UINT32 uIterationArgBase; psNextNextInst = psNextInst->psNext; ASSERT(GetBit(psFDDPInst->auFlag, INST_SKIPINV) == GetBit(psNextInst->auFlag, INST_SKIPINV)); uIterationArgBase = + uInst * FDDP_PER_ITERATION_ARGUMENT_COUNT; /* Copy the source arguments from the instruction for this iteration of the double dotproduct. */ for (uArg = 0; uArg < FDDP_PER_ITERATION_ARGUMENT_COUNT; uArg++) { CopyArgumentToDP(psState, psFDDPInst, uIterationArgBase + uArg, psNextInst, puArgRemap[uArg] /* uSrcArg */); } /* Free the old instruction. */ if ((*ppsNextInst) == psNextInst) { (*ppsNextInst) = psNextInst->psNext; } RemoveInst(psState, psBlock, psNextInst); FreeInst(psState, psNextInst); } return IMG_TRUE; } static IMG_BOOL GenerateDotProducts(PINTERMEDIATE_STATE psState, PCODEBLOCK psBlock, PINST psInst, PINST* ppsNextInst) /***************************************************************************** FUNCTION : GenerateDotProducts PURPOSE : Generate dotproduct/double dotproduct instructions. PARAMETERS : psState - Compiler state. psBlock - Block containing the first instruction. psInst - First instruction in the DP/DDP sequence. ppsNextInst - Updated with the first valid instruction after psInst. RETURNS : TRUE if a dotproduct was generated and the instructions in sequence were freed. *****************************************************************************/ { #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) /* No scalar dot-product instructions on this core. */ if (psState->psTargetFeatures->ui32Flags & SGX_FEATURE_FLAGS_USE_VEC34) { return IMG_FALSE; } #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ #if defined(OUTPUT_USPBIN) if (psState->uFlags & USC_FLAGS_COMPILE_FOR_USPBIN) { if(IsInstReferingShaderResult(psState, psInst)) { return IMG_FALSE; } } #endif /* defined(OUTPUT_USPBIN) */ if (psInst->eOpcode == IFMUL) { return GenerateFDP(psState, psBlock, psInst, ppsNextInst); } /* Check for the double dotproduct special case. */ if (psInst->eOpcode == IEFO) { return GenerateFDDP(psState, psBlock, psInst, ppsNextInst); } return IMG_FALSE; } static IMG_VOID InitGroupInstState(PINTERMEDIATE_STATE psState, PGROUPINST_STATE *ppsGIState) /***************************************************************************** FUNCTION : InitGroupInstState PURPOSE : Allocate and initialise instruction grouping data PARAMETERS : psState - Compiler state. OUTPUT : ppsGIState - Instruction grouping state RETURNS : Nothing. *****************************************************************************/ { PGROUPINST_STATE psGIState; IMG_UINT32 uLabel; /* Allocate the state */ psGIState = (PGROUPINST_STATE)UscAlloc(psState, sizeof(GROUPINST_STATE)); /* Allocate state for each function. */ psGIState->asFunc = UscAlloc(psState, psState->uMaxLabel * sizeof(psGIState->asFunc[0])); /* Initialise the data */ for (uLabel = 0; uLabel < psState->uMaxLabel; uLabel++) { psGIState->asFunc[uLabel].bUsed = IMG_FALSE; psGIState->asFunc[uLabel].pvInitialState = NULL; } InitUseDef(&psGIState->sUseDef); /* Done */ *ppsGIState = psGIState; } static IMG_VOID SetHardwareConst(PARG psArg, IMG_UINT32 uNumber) /***************************************************************************** FUNCTION : SetHardwareConst PURPOSE : Set up an instruction argument to point to a hardware constant. PARAMETERS : psArg - Argument to initialize. uNumber - Index of the hardware constant. RETURNS : Nothing. *****************************************************************************/ { InitInstArg(psArg); psArg->uType = USEASM_REGTYPE_FPCONSTANT; psArg->uNumber = uNumber; } #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) static IMG_VOID ShiftVecPCKInstruction(PINTERMEDIATE_STATE psState, PINST psInst) /***************************************************************************** FUNCTION : ShiftVecPCKInstruction PURPOSE : Update a PCK instruction for the limitations of the hardware. PARAMETERS : psState - Compiler state. psInst - Instruction to shift. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 uMaxConverts; IMG_UINT32 uChan; IMG_UINT32 uWriteMask; IMG_INT32 iWrittenChan; /* For some combinations of PCK source and destination formats the hardware only supports writing the X channel. Up to this point we've representing these instructions as writing any channel (but only one). Now change the instruction so the scalar register corresponding to the written channel is the first destination and update the swizzle to match. */ /* Get the maximum number of channels we can convert in a single instruction. */ uMaxConverts = GetPackMaximumSimultaneousConversions(psState, psInst); /* Convert the write mask from bytes to F32 or F16 channels. */ uWriteMask = 0; if (psInst->asDest[0].eFmt == UF_REGFORMAT_F32) { for (uChan = 0; uChan < psInst->uDestCount; uChan++) { if (psInst->auDestMask[uChan] != 0) { uWriteMask |= (1U << uChan); } } } else { ASSERT(psInst->asDest[0].eFmt == UF_REGFORMAT_F16); for (uChan = 0; uChan < psInst->uDestCount; uChan++) { if ((psInst->auDestMask[uChan] & USC_DESTMASK_LOW) != 0) { uWriteMask |= (1U << ((uChan * 2) + 0)); } if ((psInst->auDestMask[uChan] & USC_DESTMASK_HIGH) != 0) { uWriteMask |= (1U << ((uChan * 2) + 1)); } } } /* Nothing more to do if we aren't trying to convert more channels than the hardware supports. */ if ((uWriteMask & ~((1U << uMaxConverts) - 1)) == 0) { return; } iWrittenChan = g_aiSingleComponent[uWriteMask]; ASSERT(iWrittenChan != -1); /* Move the destination for the written channel to the first destination. */ ASSERT(psInst->asDest[iWrittenChan].uType != USEASM_REGTYPE_FPINTERNAL); if (psInst->asDest[0].eFmt == UF_REGFORMAT_F32) { psInst->asDest[0] = psInst->asDest[iWrittenChan]; psInst->auDestMask[0] = psInst->auDestMask[iWrittenChan]; psInst->auLiveChansInDest[0] = psInst->auLiveChansInDest[iWrittenChan]; } else { ASSERT(psInst->asDest[0].eFmt == UF_REGFORMAT_F16); ASSERT(uMaxConverts >= 2); psInst->asDest[0] = psInst->asDest[iWrittenChan / 2]; psInst->auDestMask[0] = psInst->auDestMask[iWrittenChan / 2]; psInst->auLiveChansInDest[0] = psInst->auLiveChansInDest[iWrittenChan / 2]; } SetDestCount(psState, psInst, 1 /* uNewDestCount */); /* Shift the swizzle selector corresponding to the written channel to the first slot in the swizzle. */ switch (GetChan(psInst->u.psVec->auSwizzle[0], iWrittenChan)) { case USEASM_SWIZZLE_SEL_X: psInst->u.psVec->auSwizzle[0] = USEASM_SWIZZLE(X, X, X, X); break; case USEASM_SWIZZLE_SEL_Y: psInst->u.psVec->auSwizzle[0] = USEASM_SWIZZLE(Y, Y, Y, Y); break; case USEASM_SWIZZLE_SEL_Z: psInst->u.psVec->auSwizzle[0] = USEASM_SWIZZLE(Z, Z, Z, Z); break; case USEASM_SWIZZLE_SEL_W: psInst->u.psVec->auSwizzle[0] = USEASM_SWIZZLE(W, W, W, W); break; } } static IMG_VOID ExpandVecPCKInstruction(PINTERMEDIATE_STATE psState, PINST psOrigInst) /***************************************************************************** FUNCTION : ExpandVecPCKInstruction PURPOSE : In the hardware a PCK instruction with an F32 format, unified store source actually reads the X and Y channels from SRC1 and the Z and W channels from SRC2. So expand the number of instruction sources to reflect this arrangement. This simplifies the MOE set up code. PARAMETERS : psState - Compiler state. psOrigInst - Instruction to expand. RETURNS : Nothing. *****************************************************************************/ { IOPCODE eNewOpcode; IMG_UINT32 uSwizzle; IMG_UINT32 uArg; IMG_UINT32 uSrc0Base; IMG_UINT32 uSrc1Base; /* Expand only PCK instructions with an F32 format, VEC3 or VEC4 source in the unified store. */ if ( psOrigInst->u.psVec->aeSrcFmt[0] == UF_REGFORMAT_F16 || psOrigInst->asArg[1].uType == USEASM_REGTYPE_FPINTERNAL || ( GetLiveChansInArg(psState, psOrigInst, 1 + USC_Z_CHAN) == 0 && GetLiveChansInArg(psState, psOrigInst, 1 + USC_W_CHAN) == 0 ) ) { return; } ASSERT(psOrigInst->u.psVec->aeSrcFmt[0] == UF_REGFORMAT_F32); /* Get the new opcode. */ switch (psOrigInst->eOpcode) { case IVPCKU8FLT: eNewOpcode = IVPCKU8FLT_EXP; break; case IVPCKC10FLT: eNewOpcode = IVPCKC10FLT_EXP; break; case IVPCKS16FLT: eNewOpcode = IVPCKS16FLT_EXP; break; case IVPCKU16FLT: eNewOpcode = IVPCKU16FLT_EXP; break; case IVPCKFLTFLT: eNewOpcode = IVPCKFLTFLT_EXP; break; default: imgabort(); } /* Save the current instruction swizzle. */ uSwizzle = psOrigInst->u.psVec->auSwizzle[0]; /* Change to the new opcode. */ ModifyOpcode(psState, psOrigInst, eNewOpcode); /* Set up information about the two source arguments. */ psOrigInst->u.psVec->auSwizzle[0] = USEASM_SWIZZLE(X, Y, Z, W); psOrigInst->u.psVec->auSwizzle[1] = USEASM_SWIZZLE(X, Y, Z, W); psOrigInst->u.psVec->uPackSwizzle = uSwizzle; psOrigInst->u.psVec->aeSrcFmt[0] = UF_REGFORMAT_F32; psOrigInst->u.psVec->aeSrcFmt[1] = UF_REGFORMAT_F32; uSrc0Base = 0 * SOURCE_ARGUMENTS_PER_VECTOR; uSrc1Base = 1 * SOURCE_ARGUMENTS_PER_VECTOR; ASSERT(psOrigInst->asArg[uSrc0Base].uType == USC_REGTYPE_UNUSEDSOURCE); psOrigInst->asArg[uSrc1Base].uType = USC_REGTYPE_UNUSEDSOURCE; for (uArg = 0; uArg <= 1; uArg++) { PARG psOrigArg = &psOrigInst->asArg[uSrc0Base + 1 + USC_Z_CHAN + uArg]; /* Copy the Z and W components of the first source to the X and Y components of the second source. */ psOrigInst->asArg[uSrc1Base + 1 + uArg] = *psOrigArg; /* Clear the Z and W components of the first source. */ InitInstArg(psOrigArg); psOrigArg->uType = USC_REGTYPE_UNUSEDSOURCE; } /* Clear the Z and W components of the second source. */ for (uArg = 0; uArg <= 1; uArg++) { psOrigInst->asArg[uSrc1Base + 1 + USC_Z_CHAN + uArg].uType = USC_REGTYPE_UNUSEDSOURCE; } } static IMG_VOID NormaliseVMOVSwizzle(PINTERMEDIATE_STATE psState, PINST psInst) /***************************************************************************** FUNCTION : NormaliseVMOVSwizzle PURPOSE : If a VMOV instruction accesses the Z or W channels but not X or Y then increase the source register number so the channels it was accessed become the X and Y channels. PARAMETERS : psState - Compiler state. psInst - Instruction to normalise. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 uNewSwizzle; IMG_UINT32 uChanIdx; IMG_UINT32 uChanMask; /* Don't normalise if X or Y are accessed. */ if (GetLiveChansInArg(psState, psInst, 1 + USC_X_CHAN) != 0 || GetLiveChansInArg(psState, psInst, 1 + USC_Y_CHAN) != 0) { return; } /* Calculate a new swizzle by replacing selectors of Z by X and W by Y. */ uNewSwizzle = 0; uChanMask = 0; for (uChanIdx = 0; uChanIdx < psInst->uDestCount; uChanIdx++) { if ((psInst->auDestMask[uChanIdx] & psInst->auLiveChansInDest[uChanIdx]) != 0) { IMG_UINT32 uSel; uSel = GetChan(psInst->u.psVec->auSwizzle[0], uChanIdx); if (uSel == USEASM_SWIZZLE_SEL_Z) { uSel = USEASM_SWIZZLE_SEL_X; } else { ASSERT(uSel == USEASM_SWIZZLE_SEL_W); uSel = USEASM_SWIZZLE_SEL_Y; } uNewSwizzle |= (uSel << (USEASM_SWIZZLE_FIELD_SIZE * uChanIdx)); /* Record which channels are used from the swizzle. */ uChanMask |= (1U << uChanIdx); } } /* Check the new swizzle is supported by the VMOV instruction. */ if (!IsSwizzleSupported(psState, psInst, psInst->eOpcode, 0 /* uSwizzleSlotIdx */, uNewSwizzle, uChanMask, &uNewSwizzle)) { return; } /* Update the swizzle in the instruction. */ psInst->u.psVec->auSwizzle[0] = uNewSwizzle; /* Shift the source registers so the data selected by the Z and W channels are now selected by the X and Y channels. */ for (uChanIdx = 0; uChanIdx < 2; uChanIdx++) { PARG psOrigArg = &psInst->asArg[1 + USC_Z_CHAN + uChanIdx]; psInst->asArg[1 + uChanIdx] = *psOrigArg; InitInstArg(psOrigArg); psOrigArg->uType = USC_REGTYPE_UNUSEDSOURCE; } } static IMG_VOID ExpandVecMovInstruction(PINTERMEDIATE_STATE psState, PINST psOrigInst) /***************************************************************************** FUNCTION : ExpandVecMovInstruction PURPOSE : Expand a vector move instruction which isn't supported directly by the hardware. PARAMETERS : psState - Compiler state. psOrigInst - Instruction to expand. RETURNS : Nothing. *****************************************************************************/ { IMG_BOOL bConvertToVPCK = IMG_FALSE; IMG_UINT32 uDestIdx; /* Expand a vector MOV with an F32 format source/destination and reading the Z or W channels from a unified store source. */ if ( psOrigInst->asDest[0].eFmt == UF_REGFORMAT_F32 && psOrigInst->asArg[1].uType != USEASM_REGTYPE_FPINTERNAL ) { /* If only Z and W are used then try to change to using X and Y by increasing the source register number. */ NormaliseVMOVSwizzle(psState, psOrigInst); if (GetLiveChansInArg(psState, psOrigInst, 1 + USC_Z_CHAN) != 0 || GetLiveChansInArg(psState, psOrigInst, 1 + USC_W_CHAN) != 0) { bConvertToVPCK = IMG_TRUE; } } /* Expand a VMOV converting between different formats. */ if (psOrigInst->asDest[0].eFmt != psOrigInst->u.psVec->aeSrcFmt[0]) { bConvertToVPCK = IMG_TRUE; } /* Expand a VMOV writing subcomponents of a 32-bit register. */ for (uDestIdx = 0; uDestIdx < psOrigInst->uDestCount; uDestIdx++) { IMG_UINT32 uChansToPreserve; uChansToPreserve = psOrigInst->auLiveChansInDest[uDestIdx] & ~psOrigInst->auDestMask[uDestIdx]; if (uChansToPreserve != 0 && uChansToPreserve != USC_XYZW_CHAN_MASK) { bConvertToVPCK = IMG_TRUE; break; } } /* Expand a vector MOV if the swizzle isn't supported by the hardware VMOV. */ if (!bConvertToVPCK) { IMG_UINT32 uNewSwizzle; IMG_UINT32 uLiveChans; /* Get the mask of channels accessed from the source before the current swizzle is applied. */ GetLiveChansInSourceSlot(psState, psOrigInst, 0 /* uSlotIdx */, &uLiveChans, NULL /* puChansUsedPostSwizzle */); /* Check if the swizzle (or an equivalent) is supported by the hardware VMOV instruction. */ if (!IsSwizzleSupported(psState, psOrigInst, IVMOV_EXP, 0 /* uSwizzleSlotIdx */, psOrigInst->u.psVec->auSwizzle[0], uLiveChans, &uNewSwizzle)) { bConvertToVPCK = IMG_TRUE; } else { psOrigInst->u.psVec->auSwizzle[0] = uNewSwizzle; } } /* Convert the instruction to a VPCK. */ if (bConvertToVPCK) { ModifyOpcode(psState, psOrigInst, IVPCKFLTFLT); ExpandVecPCKInstruction(psState, psOrigInst); } else { ModifyOpcode(psState, psOrigInst, IVMOV_EXP); for (uDestIdx = 0; uDestIdx < psOrigInst->uDestCount; uDestIdx++) { if (psOrigInst->auDestMask[uDestIdx] != 0) { psOrigInst->auDestMask[uDestIdx] = USC_XYZW_CHAN_MASK; } } } } static IMG_VOID ExpandNonFltPCKInstruction(PINTERMEDIATE_STATE psState, PCODEBLOCK psCodeBlock, PINST psOrigPCKInst) /***************************************************************************** FUNCTION : ExpandNonFltPCKInstruction PURPOSE : Expand a PCKU16U16 or PCKS16S8 instruction to the equivalent for a vector core. PARAMETERS : psState - Compiler state. psCodeBlock - Basic block containing the instruction to expand. psInst - Instruction to expand. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 auChanWriteMask[2]; IMG_UINT32 uSrcIdx; IMG_UINT32 uChan; IOPCODE eNewOpcode; switch (psOrigPCKInst->eOpcode) { case IUNPCKU16U16: eNewOpcode = IVPCKU16U16; break; case IUNPCKS16S8: eNewOpcode = IVPCKS16S8; break; case IUNPCKU16U8: eNewOpcode = IVPCKU16U8; break; default: imgabort(); } for (uChan = 0; uChan < 2; uChan++) { auChanWriteMask[uChan] = psOrigPCKInst->auDestMask[0] & (USC_XY_CHAN_MASK << (uChan * 2)); } uSrcIdx = 0; for (uChan = 0; uChan < 2; uChan++) { IMG_UINT32 uChanDestMask; PINST psPCKInst; IMG_UINT32 uOrigPCKComponent; /* Get the bytes written in this destination channel. */ uChanDestMask = auChanWriteMask[uChan]; if (uChanDestMask == 0) { continue; } psPCKInst = AllocateInst(psState, psOrigPCKInst); SetOpcode(psState, psPCKInst, eNewOpcode); InsertInstBefore(psState, psCodeBlock, psPCKInst, psOrigPCKInst); /* Copy the old PCK's destination to the new instruction. */ SetDestFromArg(psState, psPCKInst, 0 /* uDestIdx */, &psOrigPCKInst->asDest[0]); /* Flag we are not completely defining the instructon if either (i) Either the original instruction didn't completely define it's destination. (ii) Or this is the second instruction in the expanded sequence (so we need to preserve the channels written by the first instruction). */ if (psOrigPCKInst->apsOldDest[0] != NULL || (uChan == 1 && auChanWriteMask[0] != 0)) { SetPartiallyWrittenDest(psState, psPCKInst, 0 /* uCopyToDestIdx */, &psPCKInst->asDest[0]); } /* Copy the old PCK's predicate to the new instruction. */ CopyPredicate(psState, psPCKInst, psOrigPCKInst); /* Copy the SKIPINVALID flag from the old PCK to the new instruction. */ SetBit(psPCKInst->auFlag, INST_SKIPINV, GetBit(psOrigPCKInst->auFlag, INST_SKIPINV)); /* Copy the NOEMIT flag from the old PCK to the new instruction. */ SetBit(psPCKInst->auFlag, INST_NOEMIT, GetBit(psOrigPCKInst->auFlag, INST_NOEMIT)); /* Unused by this instruction. */ psPCKInst->u.psVec->aeSrcFmt[0] = UF_REGFORMAT_INVALID; #if defined(OUTPUT_USPBIN) if (psState->uFlags & USC_FLAGS_COMPILE_FOR_USPBIN) { /* Copy information about which shader results are read/written by this instruction. */ psPCKInst->uShaderResultHWOperands = psOrigPCKInst->uShaderResultHWOperands; } #endif /* defined(OUTPUT_USPBIN) */ psPCKInst->auDestMask[0] = uChanDestMask; psPCKInst->auLiveChansInDest[0] = psOrigPCKInst->auLiveChansInDest[0]; if (uChan == 0) { psPCKInst->auLiveChansInDest[0] &= ~auChanWriteMask[1]; } /* Copy the source register which the old PCK wrote to the current channel in the destination. */ CopySrc(psState, psPCKInst, 0, psOrigPCKInst, uSrcIdx); /* Convert the component select on the source register to a swizzle. */ uOrigPCKComponent = GetPCKComponent(psState, psOrigPCKInst, uSrcIdx); if (psOrigPCKInst->eOpcode == IUNPCKU16U16) { switch (uOrigPCKComponent) { case 0: psPCKInst->u.psVec->auSwizzle[0] = USEASM_SWIZZLE(X, X, X, X); break; case 1: imgabort(); case 2: psPCKInst->u.psVec->auSwizzle[0] = USEASM_SWIZZLE(Y, Y, Y, Y); break; case 3: imgabort(); } } else { psPCKInst->u.psVec->auSwizzle[0] = g_auReplicateSwizzles[uOrigPCKComponent]; } uSrcIdx = (uSrcIdx + 1) % 2; } RemoveInst(psState, psCodeBlock, psOrigPCKInst); FreeInst(psState, psOrigPCKInst); } static IMG_VOID ExpandIMOVC_I32Instruction(PINTERMEDIATE_STATE psState, PCODEBLOCK psCodeBlock, PINST psOrigMovcInst) /***************************************************************************** FUNCTION : ExpandIMOVC_I32Instruction PURPOSE : Expand a IMOVC_I32 instruction to the equivalent for a vector core. PARAMETERS : psState - Compiler state. psCodeBlock - Basic block containing the instruction to expand. psOrigMovcInst - Instruction to expand. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 uSrcIdx; PINST psVmovcInst; psVmovcInst = AllocateInst(psState, psOrigMovcInst); SetOpcode(psState, psVmovcInst, IVMOVC_I32); /* Copy the old MOVC's destination to the new instruction. */ psVmovcInst->asDest[0] = psOrigMovcInst->asDest[0]; /* Copy the old MOVC's predicate to the new instruction. */ CopyPredicate(psState, psVmovcInst, psOrigMovcInst); /* Copy the SKIPINVALID flag from the old MOVC to the new instruction. */ SetBit(psVmovcInst->auFlag, INST_SKIPINV, GetBit(psOrigMovcInst->auFlag, INST_SKIPINV)); /* Copy the NOEMIT flag from the old MOVC to the new instruction. */ SetBit(psVmovcInst->auFlag, INST_NOEMIT, GetBit(psOrigMovcInst->auFlag, INST_NOEMIT)); #if defined(OUTPUT_USPBIN) if (psState->uFlags & USC_FLAGS_COMPILE_FOR_USPBIN) { /* Copy information about which shader results are read/written by this instruction. */ psVmovcInst->uShaderResultHWOperands = psOrigMovcInst->uShaderResultHWOperands; } #endif /* defined(OUTPUT_USPBIN) */ psVmovcInst->auDestMask[0] = psOrigMovcInst->auDestMask[0]; psVmovcInst->auLiveChansInDest[0] = psOrigMovcInst->auLiveChansInDest[0]; /* Copy test from the old MOVC instruction. */ *psVmovcInst->u.psMovc = *psOrigMovcInst->u.psMovc; for (uSrcIdx = 0; uSrcIdx < 3; uSrcIdx++) { /* Copy the source register which the old MOVC wrote to the current channel in the destination. */ psVmovcInst->asArg[uSrcIdx] = psOrigMovcInst->asArg[uSrcIdx]; } InsertInstBefore(psState, psCodeBlock, psVmovcInst, psOrigMovcInst->psNext); RemoveInst(psState, psCodeBlock, psOrigMovcInst); FreeInst(psState, psOrigMovcInst); } static IMG_BOOL IsValidSingleIssueSource(PINTERMEDIATE_STATE psState, IMG_UINT32 uNewSlotIdx, IOPCODE eSingleIssueOpcode, IMG_UINT32 uChansUsed, PINST psInst, IMG_UINT32 uOldSlotIdx, IMG_PUINT32 puNewSwizzle) /***************************************************************************** FUNCTION : IsValidSingleIssueSource PURPOSE : Checks whether a source to an instruction would be valid as a source to a single-issue GPI oriented instruction. PARAMETERS : psState - Compiler state. uNewSlotIdx - Source slot to check. eSingleIssueOpcode - Single-issue instruction type. uChansUsed - Mask of the channels referenced from the source. psInst - Instruction to which the source is currently an argument. uOldSlotIdx - Source slot currently used. puNewSwizzle - Returns this swizzle to use with the source. RETURNS : TRUE if the source is valid. *****************************************************************************/ { PARG psArg = &psInst->asArg[VEC_MOESOURCE_ARGINDEX(uOldSlotIdx)]; IMG_UINT32 uSwizzle = psInst->u.psVec->auSwizzle[uOldSlotIdx]; if (uNewSlotIdx == 0) { /* The unified store source can't be F16 format. */ if (psArg->eFmt != UF_REGFORMAT_F32) { return IMG_FALSE; } } else { /* The other sources must be GPI registers. */ if (psArg->uType != USEASM_REGTYPE_FPINTERNAL) { return IMG_FALSE; } } /* Check the swizzle on this source is supported by the single-issue instruction. */ if (!IsSwizzleSupported(psState, psInst, eSingleIssueOpcode, uNewSlotIdx, uSwizzle, uChansUsed, puNewSwizzle)) { return IMG_FALSE; } return IMG_TRUE; } static IMG_BOOL TryConvertToSingleIssue(PINTERMEDIATE_STATE psState, PINST psInst) /***************************************************************************** FUNCTION : TryConvertToSingleIssue PURPOSE : Try and convert an instruction to its single-issue GPI-oriented variant. These have some extra restrictions on the arguments but can be grouped into an MOE repeat. PARAMETERS : psState - Compiler state. psInst - Instruction to convert. RETURNS : TRUE if the instruction was converted. *****************************************************************************/ { IMG_UINT32 uChansUsed; IOPCODE eNewOpcode; IMG_UINT32 i; IMG_UINT32 uWrittenDestCount; uWrittenDestCount = psInst->uDestCount; while (uWrittenDestCount > 0) { if (psInst->auDestMask[uWrittenDestCount - 1] != 0) { break; } uWrittenDestCount--; } /* Get the single-issue version of this opcode. */ switch (psInst->eOpcode) { case IVDP: { uChansUsed = USC_XYZW_CHAN_MASK; eNewOpcode = IVDP_GPI; break; } case IVDP3: { uChansUsed = USC_XYZ_CHAN_MASK; eNewOpcode = IVDP3_GPI; /* The hardware doesn't support writing to the W component of the destination from a single-issue VDP3 instruction. */ if (uWrittenDestCount > 3) { return IMG_FALSE; } break; } case IVMAD: { uChansUsed = USC_XYZW_CHAN_MASK; eNewOpcode = IVMAD4; break; } case IVADD: { if (uWrittenDestCount > 3) { /* We can support a repeated VADD by using VMAD with a dummy second source with a swizzle of 1111. But this swizzle is only supported on a VEC3 VMAD. */ return IMG_FALSE; } uChansUsed = USC_XYZ_CHAN_MASK; eNewOpcode = IVADD3; break; } case IVMUL: { if (uWrittenDestCount > 3) { /* We can support a repeated VADD by using VMAD with a dummy third source with a swizzle of 0000. But this swizzle is only supported on a VEC3 VMAD. */ return IMG_FALSE; } uChansUsed = USC_XYZ_CHAN_MASK; eNewOpcode = IVMUL3; break; } default: { return IMG_FALSE; } } /* The single-issue instructions only support F32 sources/destinations. */ if (psInst->asDest[0].eFmt != UF_REGFORMAT_F32) { return IMG_FALSE; } /* Check the sources would still be legal if the instruction was converted to the single-issue variant. The first two sources to the single-issue all commute so try also with the first two sources swapped. */ for (i = 0; i < 2; i++) { IMG_UINT32 auNewSwizzles[VECTOR_MAX_SOURCE_SLOT_COUNT]; IMG_BOOL bValidSources; IMG_UINT32 uOldSlotIdx; bValidSources = IMG_TRUE; for (uOldSlotIdx = 0; uOldSlotIdx < GetSwizzleSlotCount(psState, psInst); uOldSlotIdx++) { IMG_UINT32 uNewSlotIdx; if (i == 0) { uNewSlotIdx = uOldSlotIdx; } else { switch (uOldSlotIdx) { case 0: uNewSlotIdx = 1; break; case 1: uNewSlotIdx = 0; break; default: uNewSlotIdx = uOldSlotIdx; break; } } if (!IsValidSingleIssueSource(psState, uNewSlotIdx, eNewOpcode, uChansUsed, psInst, uOldSlotIdx, &auNewSwizzles[uNewSlotIdx])) { bValidSources = IMG_FALSE; break; } } if (bValidSources) { if (i == 1) { SwapVectorSources(psState, psInst, 0 /* uArg1Idx */, psInst, 1 /* uArg2Idx */); } ModifyOpcode(psState, psInst, eNewOpcode); memcpy(psInst->u.psVec->auSwizzle, auNewSwizzles, sizeof(psInst->u.psVec->auSwizzle)); return IMG_TRUE; } } return IMG_FALSE; } #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ static IMG_VOID SetFloatHardwareConst(PINST psInst, IMG_UINT32 uArgIdx, IMG_UINT32 uConstNum) /***************************************************************************** FUNCTION : SetFloatHardwareConst PURPOSE : Set a hardware constant as an argument to a floating point instruction. PARAMETERS : psInst - Instruction to modify. uArgIdx - Index of the argument to modify. uConstNum - Index of the constant to set. RETURNS : Nothing. *****************************************************************************/ { SetHardwareConst(&psInst->asArg[uArgIdx], uConstNum); psInst->u.psFloat->asSrcMod[uArgIdx].bNegate = IMG_FALSE; psInst->u.psFloat->asSrcMod[uArgIdx].bAbsolute = IMG_FALSE; psInst->u.psFloat->asSrcMod[uArgIdx].uComponent = 0; } static IMG_VOID SetFMAD16Constant(PINST psInst, IMG_UINT32 uArgIdx, IMG_UINT32 uConstNum) /***************************************************************************** FUNCTION : SetFMAD16Constant PURPOSE : Set a hardware constant as an argument to a FMAD16 instruction. PARAMETERS : psInst - Instruction to modify. uArgIdx - Index of the argument to modify. uConstNum - Index of the constant to set. RETURNS : Nothing. *****************************************************************************/ { SetHardwareConst(&psInst->asArg[uArgIdx], uConstNum); psInst->u.psArith16->aeSwizzle[uArgIdx] = FMAD16_SWIZZLE_LOWHIGH; psInst->u.psArith16->sFloat.asSrcMod[uArgIdx].bNegate = IMG_FALSE; psInst->u.psArith16->sFloat.asSrcMod[uArgIdx].bAbsolute = IMG_FALSE; psInst->u.psArith16->sFloat.asSrcMod[uArgIdx].uComponent = 0; } static IMG_VOID ExpandMacroInstruction(PINTERMEDIATE_STATE psState, PCODEBLOCK psCodeBlock, PINST psInst) /***************************************************************************** FUNCTION : ExpandMacroInstruction PURPOSE : Expand instructions which don't have an exact equivalent in the hardware. PARAMETERS : psState - Compiler state. psInst - Instruction to expand. RETURNS : Nothing. *****************************************************************************/ { switch (psInst->eOpcode) { case IFMOV: { /* Similarly for an FMOV expand it to either FDP or FMAD. */ if (!CanUseSource0(psState, psCodeBlock->psOwner->psFunc, &psInst->asArg[0])) { ModifyOpcode(psState, psInst, IFDP); SetFloatHardwareConst(psInst, 1 /* uArgIdx */, EURASIA_USE_SPECIAL_CONSTANT_FLOAT1); } else { ModifyOpcode(psState, psInst, IFMAD); SetFloatHardwareConst(psInst, 1 /* uArgIdx */, EURASIA_USE_SPECIAL_CONSTANT_FLOAT1); SetFloatHardwareConst(psInst, 2 /* uArgIdx */, EURASIA_USE_SPECIAL_CONSTANT_ZERO); } break; } case ITESTPRED: case ITESTMASK: { if (psInst->u.psTest->eAluOpcode == IFMOV) { psInst->u.psTest->eAluOpcode = IFADD; SetHardwareConst(&psInst->asArg[1], EURASIA_USE_SPECIAL_CONSTANT_ZERO); InitPerArgumentParameters(psState, psInst, 1 /* uArgIdx */); } break; } case INOT: { ASSERT(!psInst->u.psBitwise->bInvertSrc2); /* NOT DEST, SRC -> XOR DEST, SRC, #0xFFFFFFFF */ ModifyOpcode(psState, psInst, IXOR); SetSrc(psState, psInst, 1 /* uSrcIdx */, USEASM_REGTYPE_IMMEDIATE, 0xFFFFFFFF /* uNumber */, UF_REGFORMAT_F32); break; } case IFMUL: { /* For a FMUL instruction expand it to either FDP (if neither source can go in source 0 of an FMAD) or FMAD otherwise. */ if (!CanUseSource0(psState, psCodeBlock->psOwner->psFunc, &psInst->asArg[0]) && !CanUseSource0(psState, psCodeBlock->psOwner->psFunc, &psInst->asArg[1])) { ModifyOpcode(psState, psInst, IFDP); } else { ModifyOpcode(psState, psInst, IFMAD); if (!CanUseSource0(psState, psCodeBlock->psOwner->psFunc, &psInst->asArg[0])) { CommuteSrc01(psState, psInst); } SetFloatHardwareConst(psInst, 2 /* uArgIdx */, EURASIA_USE_SPECIAL_CONSTANT_ZERO); InvertNegateModifier(psState, psInst, 2); } break; } case IFADD: case IFSUB: { if (psInst->eOpcode == IFSUB) { InvertNegateModifier(psState, psInst, 1 /* uArgIdx */); } /* ADD D, A, B -> MAD D, A, 1, B */ ModifyOpcode(psState, psInst, IFMAD); MoveFloatSrc(psState, psInst, 2 /* uDestArgIdx */, psInst, 1 /* uSrcArgIdx */); SetFloatHardwareConst(psInst, 1 /* uArgIdx */, EURASIA_USE_SPECIAL_CONSTANT_FLOAT1); break; } case IFMOV16: { /* MOV16 D, A -> MAD16 D, A, 1, 0 */ ModifyOpcode(psState, psInst, IFMAD16); SetFMAD16Constant(psInst, 1, EURASIA_USE_SPECIAL_CONSTANT_FLOAT16ONE); SetFMAD16Constant(psInst, 2, EURASIA_USE_SPECIAL_CONSTANT_ZERO); break; } case IFADD16: { /* ADD16 D, A, B -> MAD16 D, A, 1, B */ ModifyOpcode(psState, psInst, IFMAD16); MoveFloatSrc(psState, psInst, 2 /* uDestArgIdx */, psInst, 1 /* uSrcArgIdx */); SetFMAD16Constant(psInst, 1, EURASIA_USE_SPECIAL_CONSTANT_FLOAT16ONE); break; } case IFMUL16: { /* MUL16 D, A, B -> MAD16 D, A, B, 0 */ ModifyOpcode(psState, psInst, IFMAD16); SetFMAD16Constant(psInst, 2, EURASIA_USE_SPECIAL_CONSTANT_ZERO); break; } #if defined(SUPPORT_SGX545) case IFMIN: { if (psState->psTargetFeatures->ui32Flags & SGX_FEATURE_FLAGS_USE_FCLAMP) { /* D = min(X, Y) -> D = min(max(X, X), Y) */ ModifyOpcode(psState, psInst, IFMINMAX); CopySrcAndModifiers(psState, psInst, 2 /* uDestArgIdx */, psInst, 1 /* uSrcArgIdx */); CopySrcAndModifiers(psState, psInst, 1 /* uDestArgIdx */, psInst, 0 /* uSrcArgIdx */); } break; } case IFMAX: { if (psState->psTargetFeatures->ui32Flags & SGX_FEATURE_FLAGS_USE_FCLAMP) { /* D = max(X, Y) -> D = max(min(X, X), Y) */ ModifyOpcode(psState, psInst, IFMAXMIN); CopySrcAndModifiers(psState, psInst, 2 /* uDestArgIdx */, psInst, 0 /* uSrcArgIdx */); } break; } #endif /* defined(SUPPORT_SGX545) */ #if defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) case IUNPCKU16U16: case IUNPCKS16S8: case IUNPCKU16U8: { if ((psState->psTargetFeatures->ui32Flags & SGX_FEATURE_FLAGS_USE_VEC34) != 0) { ExpandNonFltPCKInstruction(psState, psCodeBlock, psInst); } break; } case IMOVC_I32: { if (psState->psTargetFeatures->ui32Flags & SGX_FEATURE_FLAGS_USE_VEC34) { ExpandIMOVC_I32Instruction(psState, psCodeBlock, psInst); } break; } case IVMOV: { ExpandVecMovInstruction(psState, psInst); break; } case IVMOVC: case IVMOVCU8_FLT: { if (psInst->u.psVec->eMOVCTestType == TEST_TYPE_GTE_ZERO) { psInst->u.psVec->eMOVCTestType = TEST_TYPE_LT_ZERO; SwapVectorSources(psState, psInst, 1 /* uArg1Idx */, psInst, 2 /* uArg2Idx */); } else if (psInst->u.psVec->eMOVCTestType == TEST_TYPE_GT_ZERO) { psInst->u.psVec->eMOVCTestType = TEST_TYPE_LTE_ZERO; SwapVectorSources(psState, psInst, 1 /* uArg1Idx */, psInst, 2 /* uArg2Idx */); } break; } case IVPCKU8FLT: case IVPCKC10FLT: case IVPCKS16FLT: case IVPCKU16FLT: case IVPCKFLTFLT: { ExpandVecPCKInstruction(psState, psInst); break; } case IVPCKFLTU8: case IVPCKFLTS8: case IVPCKFLTU16: case IVPCKFLTS16: { ShiftVecPCKInstruction(psState, psInst); break; } case IVDP2: { ModifyOpcode(psState, psInst, IVDP3_GPI); psInst->u.psVec->auSwizzle[0] = SetChan(psInst->u.psVec->auSwizzle[0], USC_Z_CHAN, USEASM_SWIZZLE_SEL_0); psInst->u.psVec->auSwizzle[1] = SetChan(psInst->u.psVec->auSwizzle[1], USC_Z_CHAN, USEASM_SWIZZLE_SEL_1); break; } case IVDP3: { /* First try converting the instruction to the single-issue GPI vec3 dotproduct. */ if (!TryConvertToSingleIssue(psState, psInst)) { /* Convert VDP3 A, B.xyz, C.xyz -> VDP A, B.xyz0, C.xyz1 */ ModifyOpcode(psState, psInst, IVDP); psInst->u.psVec->auSwizzle[0] &= ~(USEASM_SWIZZLE_VALUE_MASK << (USEASM_SWIZZLE_FIELD_SIZE * USC_W_CHAN)); psInst->u.psVec->auSwizzle[0] |= (USEASM_SWIZZLE_SEL_0 << (USEASM_SWIZZLE_FIELD_SIZE * USC_W_CHAN)); ASSERT(IsSwizzleSupported(psState, psInst, psInst->eOpcode, 0 /* uSwizzleSlotIdx */, psInst->u.psVec->auSwizzle[0], USC_XYZW_CHAN_MASK, NULL /* puMatchedSwizzle */)); psInst->u.psVec->auSwizzle[1] &= ~(USEASM_SWIZZLE_VALUE_MASK << (USEASM_SWIZZLE_FIELD_SIZE * USC_W_CHAN)); psInst->u.psVec->auSwizzle[1] |= (USEASM_SWIZZLE_SEL_1 << (USEASM_SWIZZLE_FIELD_SIZE * USC_W_CHAN)); ASSERT(IsSwizzleSupported(psState, psInst, psInst->eOpcode, 1 /* uSwizzleSlotIdx */, psInst->u.psVec->auSwizzle[1], USC_XYZW_CHAN_MASK, NULL /* puMatchedSwizzle */)); } break; } case IVDP: case IVMAD: case IVADD: case IVMUL: { /* Try converting to a variant of this instruction which can be grouped into an MOE repeat. */ (IMG_VOID)TryConvertToSingleIssue(psState, psInst); break; } #endif /* defined(SUPPORT_SGX543) || defined(SUPPORT_SGX544) || defined(SUPPORT_SGX554) */ default: { break; } } } static IMG_VOID GenerateExtraDPCIteration(PINTERMEDIATE_STATE psState, PCODEBLOCK psBlock, PINST psOrigDPCInst) /***************************************************************************** FUNCTION : GenerateExtraDPCIteration PURPOSE : Add extra instructions so a DPC instruction has a minimum of two iterations. PARAMETERS : psState - Compiler state. psBlock - Block containing the DPC instruction. psOrigDPCInst - DPC instruction to fix. RETURNS : Nothing. *****************************************************************************/ { PINST psNewDPCInst; IMG_UINT32 uIteration; /* Create a new DPC instruction. */ psNewDPCInst = AllocateInst(psState, psOrigDPCInst); SetOpcode(psState, psNewDPCInst, IFDPC_RPT); InsertInstBefore(psState, psBlock, psNewDPCInst, psOrigDPCInst); /* Copy the instruction parameters from the original instruction. */ SetBit(psNewDPCInst->auFlag, INST_SKIPINV, GetBit(psOrigDPCInst->auFlag, INST_SKIPINV)); CopyNegateAbsoluteModifierToFDP(psState, psNewDPCInst, FDP_RPT_PER_ITERATION_ARGUMENT_COUNT, psOrigDPCInst); /* Do two dotproduct iterations (as required by the hardware). */ psNewDPCInst->u.psFdp->uRepeatCount = 2; /* Copy the clipplane P-flag destination. */ psNewDPCInst->u.psFdp->uClipPlane = psOrigDPCInst->u.psDpc->uClipplane; #if defined(SRC_DEBUG) /* Add an extra cycle for the second DPC iteration. */ IncrementCostCounter(psState, psNewDPCInst->uAssociatedSrcLine, 1); #endif /* defined(SRC_DEBUG) */ /* Copy the dotproduct destination. */ MoveDest(psState, psNewDPCInst, 0, psOrigDPCInst, 0); /* Setup the calculation for the first iteration to FIRST_DPC_SOURCE * ONE where FIRST_DPC_SOURCE contains the clipplane result. Setup the calculation for the second iteration to SECOND_DPC_SOURCE * ONE + (first iteration) where SECOND_DPC_SOURCE is a temporary register containing zero. The two DPC source register have been given consecutive register numbers so we can always form a repeat from the two iterations. */ for (uIteration = 0; uIteration < 2; uIteration++) { IMG_UINT32 uArgBase; PARG psSecondArg; uArgBase = uIteration * FDP_RPT_PER_ITERATION_ARGUMENT_COUNT; CopyArgumentToDP(psState, psNewDPCInst, uArgBase + 0 /* uDestArg */, psOrigDPCInst, uIteration /* uSrcArg */); psSecondArg = &psNewDPCInst->asArg[uArgBase + 1]; psSecondArg->uType = USEASM_REGTYPE_FPCONSTANT; psSecondArg->uNumber = EURASIA_USE_SPECIAL_CONSTANT_FLOAT1; SetComponentSelect(psState, psNewDPCInst, uArgBase + 1 /* uDestArg */, 0 /* uComponent */); } /* Free the DPC instruction. */ RemoveInst(psState, psBlock, psOrigDPCInst); FreeInst(psState, psOrigDPCInst); } static IMG_BOOL OptimizePFlagCalc(PINTERMEDIATE_STATE psState, PCODEBLOCK psBlock, PINST psDPCInst) /***************************************************************************** FUNCTION : OptimizePFlagCalc PURPOSE : Try to combine an instruction writing a P flag with a dotproduct instruction writing its source. PARAMETERS : psState - Compiler state. psBlock - Block containing the DPC instruction. psOrigDPCInst - DPC instruction to try and optimize. RETURNS : Nothing. *****************************************************************************/ { REGISTER_USEDEF sDPCUse; REGISTER_USEDEF sDPCDef; PINST psPrevInst; IMG_BOOL bOptimized; PARG psClipValue = &psDPCInst->asArg[0]; /* Check the DPC doesn't have any modifiers on its source argument. */ if ( !( psClipValue->uIndexType == USC_REGTYPE_NOINDEX && !psDPCInst->u.psDpc->sFloat.asSrcMod[0].bNegate && !psDPCInst->u.psDpc->sFloat.asSrcMod[0].bAbsolute ) ) { return IMG_FALSE; } /* Check this is the last use of the DPC source. */ if (!UseDefIsSingleSourceRegisterUse(psState, psDPCInst, 0 /* uSrcIdx */)) { return IMG_FALSE; } /* Set up a record of the registers used by the DPC instruction. */ InitRegUseDef(&sDPCUse); InstUse(psState, psDPCInst, &sDPCUse); /* The second DPC source is only needed if we don't manage to optimize the DPC together with a previous dot-product so clear its entry in the use-def record. */ ReduceRegUseDef(psState, &sDPCUse, psDPCInst->asArg[1].uType, psDPCInst->asArg[1].uNumber, USC_DESTMASK_FULL); /* Set up a record of the registers defined by the DPC instruction. */ InitRegUseDef(&sDPCDef); InstDef(psState, psDPCInst, &sDPCDef); bOptimized = IMG_FALSE; for (psPrevInst = psDPCInst->psPrev; psPrevInst != NULL; psPrevInst = psPrevInst->psPrev) { REGISTER_USEDEF sPrevInstDef, sPrevInstUse; IMG_BOOL bNotDisjoint; /* Check for a repeated DP instruction writing the DPC instruction's source. */ if (psPrevInst->eOpcode == IFDP_RPT && psPrevInst->u.psFdp->uRepeatCount > 1 && NoPredicate(psState, psPrevInst) && psPrevInst->asDest[0].uType == psClipValue->uType && psPrevInst->asDest[0].uNumber == psClipValue->uNumber && psPrevInst->asDest[0].uIndexType == USC_REGTYPE_NOINDEX) { /* Switch the previous instruction to write a clipplane result. */ ModifyOpcode(psState, psPrevInst, IFDPC_RPT); /* Copy the DPC's destination to the DP. We've already checked there are no instructions using the DPC's result in between. */ psPrevInst->asDest[0] = psDPCInst->asDest[0]; /* Copy the clipplane destination from the DPC to the repeated dotproduct. */ psPrevInst->u.psFdp->uClipPlane = psDPCInst->u.psDpc->uClipplane; /* Remove and free the DPC instruction. */ RemoveInst(psState, psBlock, psDPCInst); FreeInst(psState, psDPCInst); bOptimized = IMG_TRUE; break; } /* Calculate register def */ InitRegUseDef(&sPrevInstDef); InstDef(psState, psPrevInst, &sPrevInstDef); /* Check if this instruction defines any register used or defined by the DPC. */ bNotDisjoint = DisjointUseDef(psState, &sDPCUse, &sPrevInstDef); if (bNotDisjoint) { bNotDisjoint = DisjointUseDef(psState, &sDPCDef, &sPrevInstDef); } ClearRegUseDef(psState, &sPrevInstDef); if (!bNotDisjoint) { break; } /* Calculate register use */ InitRegUseDef(&sPrevInstUse); InstUse(psState, psPrevInst, &sPrevInstUse); /* Check if this instruction uses any register either used or defined by the DPC. */ bNotDisjoint = DisjointUseDef(psState, &sDPCUse, &sPrevInstUse); if (bNotDisjoint) { bNotDisjoint = DisjointUseDef(psState, &sDPCDef, &sPrevInstUse); } ClearRegUseDef(psState, &sPrevInstUse); if (!bNotDisjoint) { break; } } /* Free the USE/DEF information for the DPC instruction. */ ClearRegUseDef(psState, &sDPCDef); ClearRegUseDef(psState, &sDPCUse); return bOptimized; } static IMG_BOOL MergeDPWithTest(PINTERMEDIATE_STATE psState, PCODEBLOCK psBlock, PINST psInst) /***************************************************************************** FUNCTION : MergeDPWithTest PURPOSE : Try to merge a dotproduct instruction together with a test on the result. PARAMETERS : psState - Compiler state. psBlock - Block containing the instruction. psInst - Instruction to try to merge. RETURNS : TRUE if the instruction was merged. *****************************************************************************/ { PINST psPrevInst; IMG_BOOL bTestMask; IOPCODE eNewOpcode; IMG_BOOL bKilledTestSource; /* Check the current instruction is a TEST or a TESTMASK. */ if (psInst->eOpcode == ITESTPRED && psInst->u.psTest->eAluOpcode == IFMOV) { bTestMask = IMG_FALSE; } else if (psInst->eOpcode == ITESTMASK && psInst->u.psTest->eAluOpcode == IFMOV) { bTestMask = IMG_TRUE; } else { return IMG_FALSE; } /* Check the previous instruction is a dotproduct writing the source to the test. */ if (psInst->psPrev == NULL) { return IMG_FALSE; } psPrevInst = psInst->psPrev; if ( !( psPrevInst->eOpcode == IFDP_RPT && psPrevInst->asDest[0].uType == psInst->asArg[0].uType && psPrevInst->asDest[0].uNumber == psInst->asArg[0].uNumber ) ) { return IMG_FALSE; } /* Either the result of the dotproduct is only used here or the TEST instruction doesn't do a writeback. */ bKilledTestSource = UseDefIsSingleSourceRegisterUse(psState, psInst, 0 /* uSrcIdx */); if (!bKilledTestSource && (bTestMask || psInst->uDestCount != TEST_PREDICATE_ONLY_DEST_COUNT)) { return IMG_FALSE; } /* No source modifiers on TEST instructions. */ if ( psPrevInst->u.psFdp->abNegate[0] || psPrevInst->u.psFdp->abAbsolute[0] || psPrevInst->u.psFdp->abNegate[1] || psPrevInst->u.psFdp->abAbsolute[1] ) { return IMG_FALSE; } /* DP with test is broken on some cores */ if (!bTestMask && (psState->psTargetBugs->ui32Flags & SGX_BUG_FLAGS_FIX_HW_BRN_23164) != 0) { return IMG_FALSE; } /* Check for too many repeats for a TEST instruction with a dot-product ALU op. */ if (psPrevInst->u.psFdp->uRepeatCount > EURASIA_USE1_TEST_MAX_REPEAT) { return IMG_FALSE; } /* Convert the dotproduct to a TEST. */ eNewOpcode = bTestMask ? IFDP_RPT_TESTMASK : IFDP_RPT_TESTPRED; ModifyOpcode(psState, psPrevInst, eNewOpcode); /* Copy the condition to test for from the old TEST instruction. */ psPrevInst->u.psFdp->sTest = psInst->u.psTest->sTest; /* If the DP result isn't only used in the old TEST instruction then enable the TEST instruction's unified store writeback. */ if (!bKilledTestSource) { ASSERT(!bTestMask); ASSERT(psInst->uDestCount == TEST_PREDICATE_ONLY_DEST_COUNT); SetDestCount(psState, psPrevInst, TEST_MAXIMUM_DEST_COUNT); /* Set the unified store destination to the old DP destination. */ MoveDest(psState, psPrevInst, TEST_UNIFIEDSTORE_DESTIDX, psPrevInst, 0); /* Copy the predicate destination from the old TEST instruction. */ MoveDest(psState, psPrevInst, TEST_PREDICATE_DESTIDX, psInst, TEST_PREDICATE_DESTIDX); } else { /* Otherwise copy the TEST/TESTMASK's destination to the dotproduct. */ MoveDest(psState, psPrevInst, 0, psInst, 0); } /* Free the TEST instruction. */ RemoveInst(psState, psBlock, psInst); FreeInst(psState, psInst); return IMG_TRUE; } static IMG_VOID GenerateDotProdBP(PINTERMEDIATE_STATE psState, PCODEBLOCK psBlock, IMG_PVOID pvNull) /* Generate DP/DDP instructions. */ { PINST psInst, psNextInst; IMG_BOOL bDeadInstructions; PVR_UNREFERENCED_PARAMETER (pvNull); bDeadInstructions = IMG_FALSE; for (psInst = psBlock->psBody; psInst; psInst = psNextInst) { psNextInst = psInst->psNext; /* Try to combine this instruction with following ones into a DOTPRODUCT */ if (GenerateDotProducts(psState, psBlock, psInst, &psNextInst)) { continue; } /* Check if we can convert a test on the result of the dotproduct into a test instruction with DP alu opcode. */ if (MergeDPWithTest(psState, psBlock, psInst)) { continue; } /* Try to optimize DPC instructions. */ if (psInst->eOpcode == IFDPC) { if (!OptimizePFlagCalc(psState, psBlock, psInst)) { GenerateExtraDPCIteration(psState, psBlock, psInst); } else { bDeadInstructions = IMG_TRUE; } continue; } /* Expand intermediate instructions which don't have an exact equivalent in the hardware. */ ExpandMacroInstruction(psState, psBlock, psInst); } /* Optimizing a DPC instruction might now mean some instructions have unused results. */ if (bDeadInstructions) { DeadCodeEliminationBP(psState, psBlock, (IMG_PVOID)(IMG_UINTPTR_T)IMG_TRUE); } } static IMG_VOID AdjustToMOEUnitsInstArg(PINTERMEDIATE_STATE psState, PINST psInst, IMG_BOOL bDest, IMG_UINT32 uArgIdx, IMG_UINT32 uGroupCount, HWREG_ALIGNMENT eGroupAlign, IMG_PVOID pvContext) /***************************************************************************** FUNCTION : AdjustToMOEUnitsInstArg PURPOSE : Convert a register number to the units of the MOE state. PARAMETERS : psState - Compiler state. psInst - Instruction to which the argument is a source or a destination. bDest - TRUE if the argument is a destination. FALSE if the argument is a source. uArgIdx - Argument. uGroupCount - Ignored. eGroupAlign - Ignored. pvContext - Ignored. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 uMOEUnitsInBytesLog2; PARG psArg; PVR_UNREFERENCED_PARAMETER(uGroupCount); PVR_UNREFERENCED_PARAMETER(eGroupAlign); PVR_UNREFERENCED_PARAMETER(pvContext); if (bDest) { ASSERT(uArgIdx < psInst->uDestCount); psArg = &psInst->asDest[uArgIdx]; } else { ASSERT(uArgIdx < psInst->uArgumentCount); psArg = &psInst->asArg[uArgIdx]; } if (psArg->uType == USEASM_REGTYPE_IMMEDIATE || psArg->uType == USEASM_REGTYPE_INDEX || psArg->uType == USEASM_REGTYPE_PREDICATE) { return; } uMOEUnitsInBytesLog2 = GetMOEUnitsLog2(psState, psInst, bDest, uArgIdx); if (uMOEUnitsInBytesLog2 > LONG_SIZE_LOG2) { IMG_UINT32 uAdjustLog2 = uMOEUnitsInBytesLog2 - LONG_SIZE_LOG2; ASSERT((psArg->uNumber % (1U << uAdjustLog2)) == 0); psArg->uNumber >>= uAdjustLog2; } else if (uMOEUnitsInBytesLog2 < LONG_SIZE_LOG2) { IMG_UINT32 uAdjustLog2 = LONG_SIZE_LOG2 - uMOEUnitsInBytesLog2; IMG_UINT32 uCompInRegUnits; IMG_UINT32 uComponent; ASSERT(!bDest); psArg->uNumber <<= uAdjustLog2; uComponent = GetComponentSelect(psState, psInst, uArgIdx); uCompInRegUnits = uComponent >> uMOEUnitsInBytesLog2; uComponent &= ((1U << uMOEUnitsInBytesLog2) - 1); ASSERT(uComponent == 0); psArg->uNumber += uCompInRegUnits; } } static IMG_VOID AdjustToMOEUnitsBP(PINTERMEDIATE_STATE psState, PCODEBLOCK psBlock, IMG_PVOID pvIgnored) /***************************************************************************** FUNCTION : AdjustToMOEUnitsBP PURPOSE : Convert register numbers to the units of the MOE state. PARAMETERS : psState - Compiler state. psBlock - Block to process. pvIgnored - Ignored. RETURNS : Nothing. *****************************************************************************/ { PINST psInst; PVR_UNREFERENCED_PARAMETER(pvIgnored); /* Convert register numbers to the units of the MOE state. */ for (psInst = psBlock->psBody; psInst; psInst = psInst->psNext) { if (GetBit(psInst->auFlag, INST_NOEMIT)) { continue; } ProcessSourceRegisterGroups(psState, psInst, AdjustToMOEUnitsInstArg, NULL /* pvContext */); ProcessDestRegisterGroups(psState, psInst, AdjustToMOEUnitsInstArg, NULL /* pvContext */); } } /* Is format control ever required to be on or off? */ typedef struct { IMG_BOOL bEfoFmtCtrlEverOff, bEfoFmtCtrlEverOn; IMG_BOOL bColFmtCtrlEverOff, bColFmtCtrlEverOn; IMG_BOOL bFormatChangeAfterFeedback; } FMT_CTRL_EVER, *PFMT_CTRL_EVER; static IMG_VOID SearchFormatControlBP(PINTERMEDIATE_STATE psState, PCODEBLOCK psBlock, IMG_PVOID pvFmtCtrl) /***************************************************************************** FUNCTION : SearchFormatControlBP PURPOSE : Checks if a block contains any instructions that require the MOE format control to be either on or off. PARAMETERS : psState - Compiler state. psBlock - Block to process. pvIgnored - Ignored. RETURNS : Nothing. *****************************************************************************/ { PFMT_CTRL_EVER psFmtCtrl = (PFMT_CTRL_EVER)pvFmtCtrl; PINST psInst; IMG_BOOL bNeedControl = IMG_FALSE; /* now look for needing a SETFC, but not in the SA program. */ if (psBlock->psOwner->psFunc == psState->psSecAttrProg) return; for (psInst = psBlock->psBody; psInst; psInst = psInst->psNext) { IMG_BOOL bNeedsFmtCtrlOff, bNeedsFmtCtrlOn; if (!(psInst->eOpcode == IEFO || HasC10FmtControl(psInst))) { continue; } GetFormatControlRequirements(psState, psInst, &bNeedsFmtCtrlOff, &bNeedsFmtCtrlOn, NULL); if (psInst->eOpcode == IEFO) { if (bNeedsFmtCtrlOff) { psFmtCtrl->bEfoFmtCtrlEverOff = IMG_TRUE; bNeedControl = IMG_TRUE; } if (bNeedsFmtCtrlOn) { psFmtCtrl->bEfoFmtCtrlEverOn = IMG_TRUE; bNeedControl = IMG_TRUE; } } else { if (bNeedsFmtCtrlOff) { psFmtCtrl->bColFmtCtrlEverOff = IMG_TRUE; bNeedControl = IMG_TRUE; } if (bNeedsFmtCtrlOn) { psFmtCtrl->bColFmtCtrlEverOn = IMG_TRUE; bNeedControl = IMG_TRUE; } } } /* Check whether this block is after a feedback phase */ if ((psState->uFlags & USC_FLAGS_SPLITFEEDBACKCALC) != 0 && bNeedControl) { IMG_UINT32 uBlock; for (uBlock = 0; uBlock < psBlock->psOwner->uNumBlocks; uBlock++) { PCODEBLOCK psPrevBlock = psBlock->psOwner->apsAllBlocks[uBlock]; if (psPrevBlock == psBlock) { break; } if (psPrevBlock == psState->psPreFeedbackDriverEpilogBlock) { psFmtCtrl->bFormatChangeAfterFeedback = IMG_TRUE; break; } } } } static IMG_VOID CheckBaseOffsetBasicBlock(PINTERMEDIATE_STATE psState, PGROUPINST_STATE psGIState, PCODEBLOCK psBlock, IMG_PVOID pvMoeState, IMG_BOOL bInsert) /***************************************************************************** FUNCTION : CheckBaseOffsetBasicBlock PURPOSE : Inserts any SMBO instructions needed by a block. PARAMETERS : psState - Compiler state. psGIState - Module state. psBlock - Block to process. psMoeState - On entry the MOE state before the first instruction. On exit the MOE state after the last instruction. bInsert - If TRUE actually insert SMBO instructions. If FALSE only update the MOE state. RETURNS : Nothing. *****************************************************************************/ { PINST psInst; PINST psNextInst; PSMBO_STATE psMoeState = (PSMBO_STATE)pvMoeState; PVR_UNREFERENCED_PARAMETER(psGIState); #if defined(OUTPUT_USPBIN) if (psState->uFlags & USC_FLAGS_COMPILE_FOR_USPBIN) { /* For the patcher record the MOE base offset state before the first instruction. */ RecordSmboStateForBlock(psBlock, psMoeState); } #endif /* defined(OUTPUT_USPBIN) */ /* Use the MOE base offset feature to access registers whose numbers are too large to be reached directly. */ for (psInst = psBlock->psBody; psInst; psInst = psNextInst) { CheckBaseOffset(psState, psBlock, psInst, psMoeState, &psNextInst, bInsert); } } static IMG_VOID CheckFormatControlBasicBlock(PINTERMEDIATE_STATE psState, PGROUPINST_STATE psGIState, PCODEBLOCK psBlock, IMG_PVOID pvMoeState, IMG_BOOL bInsert) /***************************************************************************** FUNCTION : CheckFormatControlBasicBlock PURPOSE : Inserts any SETFC instructions needed by a block. PARAMETERS : psState - Compiler state. psGIState - Module state. psBlock - Block to process. psMoeState - On entry the MOE state before the first instruction. On exit the MOE state after the last instruction. bInsert - If TRUE actually insert SETFC instructions. If FALSE only update the MOE state. RETURNS : Nothing. *****************************************************************************/ { PINST psInst; PSETFC_STATE psMoeState = (PSETFC_STATE)pvMoeState; PVR_UNREFERENCED_PARAMETER(psGIState); #if defined(OUTPUT_USPBIN) if (psState->uFlags & USC_FLAGS_COMPILE_FOR_USPBIN) { /* For the patcher record the MOE format control state before the first instruction. */ RecordSetfcStateForBlock(psBlock, psMoeState); } #endif /* defined(OUTPUT_USPBIN) */ for (psInst = psBlock->psBody; psInst; psInst = psInst->psNext) { /* Check for needing a SETFC instruction. */ CheckFormatControl(psState, psBlock, psInst, psMoeState, bInsert); } } static IMG_VOID GroupInstructionsBasicBlock(PINTERMEDIATE_STATE psState, PGROUPINST_STATE psGIState, PCODEBLOCK psBlock, IMG_PVOID pvMoeState, IMG_BOOL bInsert) /***************************************************************************** FUNCTION : GroupInstructionsBlock PURPOSE : Generate repeating instructions for a block of code. PARAMETERS : psState - Compiler state. psBlock - Code block. pvMoeState - PSMLSI_STATE to MOE state before the block. bInsert - If TRUE, actually inserts MOE instructions; if FALSE, only updates the MOE state. RETURNS : Nothing, but sets psMoeState to state at end. *****************************************************************************/ { PINST psInst; PINST* psInstGroup; MOE_SMLSI_SITE sMoeSite; PSMLSI_STATE psMoeState = (PSMLSI_STATE)pvMoeState; /* Record the MOE state at the start of this block */ #if defined(OUTPUT_USPBIN) if (psState->uFlags & USC_FLAGS_COMPILE_FOR_USPBIN) { RecordSmlsiStateForBlock(psBlock, psMoeState); } #endif /* defined(OUTPUT_USPBIN) */ /* Prepare each instruction for repeat grouping by initialising the repeat group data and linking instructions with the same opcode so that GroupInstructions doesn't have to search through the code-block. */ memset(psGIState->asInstGroup, (IMG_UINT32)(IMG_UINTPTR_T)NULL, sizeof(psGIState->asInstGroup)); psInstGroup = psGIState->asInstGroup; for (psInst = psBlock->psBody; psInst; psInst = psInst->psNext) { PINST psPrevInst; PINST* ppsInstGroup; if (GetBit(psInst->auFlag, INST_NOEMIT)) { continue; } /* Initialise instruction data. */ if (psInst->psRepeatGroup != NULL) { memset(psInst->psRepeatGroup, 0, sizeof(REPEAT_GROUP)); } else { psInst->psRepeatGroup = AllocRepeatGroup(psState); } if (psInst->eOpcode == IFMAD && psInst->asArg[1].uType == USEASM_REGTYPE_FPCONSTANT && psInst->asArg[1].uNumberPreMoe == EURASIA_USE_SPECIAL_CONSTANT_FLOAT1 && !IsNegated(psState, psInst, 1 /* uArgIdx */)) { ppsInstGroup = &psInstGroup[IFADD]; } else if (psInst->eOpcode == IFMAD && psInst->asArg[2].uType == USEASM_REGTYPE_FPCONSTANT && psInst->asArg[2].uNumberPreMoe == EURASIA_USE_SPECIAL_CONSTANT_ZERO) { ppsInstGroup = &psInstGroup[IFMUL]; } else { ppsInstGroup = &psInstGroup[psInst->eOpcode]; } /* Link together instructions with the same opcode. */ psPrevInst = *ppsInstGroup; if (psPrevInst != NULL) { psInst->psRepeatGroup->psPrev = psPrevInst; psPrevInst->psRepeatGroup->psNext = psInst; } *ppsInstGroup = psInst; } /* Reset information about a possible location to insert an SMLSI costing zero cycles. */ sMoeSite.psLocation = NULL; /* Group instructions */ for (psInst = psBlock->psBody; psInst; psInst = psInst->psNext) { ASSERT(psInst->eOpcode != ISMLSI); if (GetBit(psInst->auFlag, INST_NOEMIT) /* no psRepeatGroup, but still need to RecalcInstRegs */ || psInst->psRepeatGroup) { IMG_BOOL bCreatedRepeat; /* Check if we could group this instruction with those following. */ bCreatedRepeat = GroupInstructions(psState, psBlock, psInst, psMoeState, &(psGIState->sUseDef), &sMoeSite, bInsert); /* At this point, the assumption is that GroupInstructions ended by collapsing a group of one or more instruction to one instruction possibly adding an smlsi immediately before the instruction. */ if (!bCreatedRepeat) { psBlock->uFlags |= USC_CODEBLOCK_NEED_DEP_RECALC; /* Record the constraints on what MOE state can be loaded by an SMLSI instruction inserted after the last repeat. */ if (sMoeSite.psLocation != NULL) { UpdateSMLSISiteConstraints(psState, &sMoeSite, psInst); } } } /* Remove repeat group if we definitely don't need it any more */ if (bInsert) FreeRepeatGroup(psState, &psInst->psRepeatGroup); } /* If the state at the end of a block has non-zero offsets for the first iteration for any operand then reset it to the default. This means successor blocks can rely on the MOE state not affecting non-repeated instructions even if the MOE state is unknown because the block has multiple predecessors. */ if (IsNonZeroSwizzle(psMoeState->psMoeData, USC_MAX_MOE_OPERANDS)) { ResetMoeOpState(psMoeState); if (bInsert) { PINST psSMLSIInst = AllocateInst(psState, NULL); ASSERT(sMoeSite.psLocation != NULL); MoeToInst(psState, psMoeState, psSMLSIInst); InsertInstBefore(psState, psBlock, psSMLSIInst, sMoeSite.psLocation->psNext); } } } typedef struct _CALC_STATE /* captures all state needed for GroupInstsDF dataflow function */ { PGROUPINST_STATE psGIState; /* Size in bytes of a state structure. */ IMG_UINT32 uStateSize; /* MOE state at the start of the main program. */ IMG_PVOID pvInitial; /* MOE state that is set after a function call returns. */ IMG_PVOID pvPostFuncState; /* Writes the default MOE state into the state structure pointed to by the argument. */ IMG_VOID (*pfSetDefault)(IMG_PVOID); /* Merges the second MOE state into the first. */ IMG_VOID (*pfMerge)(IMG_PVOID, IMG_PVOID); /* Insert MOE control instructions into a basic block. */ IMG_VOID (*pfProcessBasicBlock)(PINTERMEDIATE_STATE, PGROUPINST_STATE, PCODEBLOCK, IMG_PVOID, IMG_BOOL); /* Insert an extra MOE control instruction needed to reset the MOE state in a function epilog. */ IMG_VOID (*pfProcessFuncEnd)(PINTERMEDIATE_STATE, PFUNC, struct _CALC_STATE*, IMG_PVOID); /* If TRUE, actually insert MOE instructions; if FALSE, only compute MOE state (only affects behaviour by being passed to callbacks, apart from that data for functions is ONLY accumulated if FALSE) */ IMG_BOOL bInsert; } CALC_STATE, *PCALC_STATE; static IMG_BOOL GroupInstsDF(PINTERMEDIATE_STATE psState, PCODEBLOCK psBlock, IMG_PVOID pvResult, IMG_PVOID *ppvArgs, IMG_PVOID pvCalcState) { PCALC_STATE psCalcState = (PCALC_STATE)pvCalcState; PGROUPINST_STATE psGIState = psCalcState->psGIState; IMG_UINT32 uPred; IMG_PVOID pvBlockState; /* Allocate space for the state before the block. */ pvBlockState = UscAlloc(psState, psCalcState->uStateSize); /* 1. compute value at block entry by merging predecessors */ if (psBlock == psBlock->psOwner->psEntry) { memcpy(pvBlockState, psCalcState->pvInitial, psCalcState->uStateSize); uPred = 0; } else if (psBlock->uNumPreds == 0) { //no predecessors - must be unreachable exit (silly program) ASSERT (psBlock == psBlock->psOwner->psExit); psCalcState->pfSetDefault(pvBlockState); //doesn't really matter... uPred = 0; } else if ( (psState->uFlags & USC_FLAGS_SPLITFEEDBACKCALC) != 0 && psState->psPreFeedbackDriverEpilogBlock == psBlock->asPreds[0].psDest ) { ASSERT (psState->psPreFeedbackDriverEpilogBlock->eType == CBTYPE_UNCOND); ASSERT (psBlock->uNumPreds == 1); // state after resumption is simply the default state. psCalcState->pfSetDefault(pvBlockState); uPred = 1; // (Ignore state at end of pre-feedback stage) } else if ((psState->uFlags2 & USC_FLAGS2_SPLITCALC) && (psState->psPreSplitBlock == psBlock->asPreds[0].psDest)) { ASSERT (psState->psPreSplitBlock->eType == CBTYPE_UNCOND); ASSERT (psBlock->uNumPreds == 1); // state after resumption is simply the default state. psCalcState->pfSetDefault(pvBlockState); uPred = 1; // (Ignore state at end of pre-split stage) } else { memcpy(pvBlockState, ppvArgs[0], psCalcState->uStateSize); uPred = 1; } for ( /*uPred set already*/ ; uPred < psBlock->uNumPreds; uPred++) { psCalcState->pfMerge(pvBlockState, ppvArgs[uPred]); } //2. process instructions in body if (IsCall(psState, psBlock)) { IMG_UINT32 uLabel = psBlock->psBody->u.psCall->psTarget->uLabel; ASSERT (psBlock->psOwner->psFunc != psState->psSecAttrProg); /* Are we gathering data on CALLs? if bInsert, we aren't, as gathered already; however, possible that bInsert is FALSE but we still aren't, 'coz we're just scanning through a function body while trying to insert instructions only into caller (and not callee)... */ if (!psCalcState->bInsert) { PGROUPINST_FUNCSTATE psFuncState = &psGIState->asFunc[uLabel]; /* Accumulate the possible states before the function. */ if (psFuncState->bUsed) { psCalcState->pfMerge(psFuncState->pvInitialState, pvBlockState); } else { psFuncState->bUsed = IMG_TRUE; memcpy(psFuncState->pvInitialState, pvBlockState, psCalcState->uStateSize); } } /* The state after the function will be reset to a fixed value. */ if (psCalcState->pvPostFuncState != NULL) { memcpy(pvBlockState, psCalcState->pvPostFuncState, psCalcState->uStateSize); } else { psCalcState->pfSetDefault(pvBlockState); } } else { /* Process instructions in the block. Updates pvBlockState to the state after the last instruction. */ psCalcState->pfProcessBasicBlock(psState, psGIState, psBlock, pvBlockState, psCalcState->bInsert); } { /* check to see if the result at the end of the block has changed. (certainly true on the first pass!). If so, will re-process successors; hence, this'll handle loops, which'll get a reset at the beginning to deal with the merge of loop entry/repeat states (if necessary!). */ IMG_BOOL bDifferent = memcmp(pvResult, pvBlockState, psCalcState->uStateSize) ? IMG_TRUE : IMG_FALSE; ASSERT (!bDifferent || !psCalcState->bInsert); /* If the result at the end of the block has changed update the stored state for the block. */ if (bDifferent) { memcpy(pvResult, pvBlockState, psCalcState->uStateSize); } /* Free space for the old state. */ UscFree(psState, pvBlockState); return bDifferent; } } static IMG_PVOID DoGroupInsts(PINTERMEDIATE_STATE psState, PFUNC psFunc, IMG_PVOID pvInitial, PGROUPINST_STATE psGIState, PCALC_STATE psCalcState) { IMG_PVOID asBlockEnds; IMG_UINT32 uBlockIdx; asBlockEnds = UscAlloc(psState, psFunc->sCfg.uNumBlocks * psCalcState->uStateSize); for (uBlockIdx = 0; uBlockIdx < psFunc->sCfg.uNumBlocks; uBlockIdx++) { IMG_PVOID pvBlockState; pvBlockState = (IMG_PVOID)((IMG_PCHAR)asBlockEnds + uBlockIdx * psCalcState->uStateSize); psCalcState->pfSetDefault(pvBlockState); } psCalcState->psGIState = psGIState; psCalcState->pvInitial = pvInitial; /* First pass: only compute the MOE state (don't insert any instructions), iterating until a fixpoint is reached. (The existing GroupInstructions etc. code breaks if passed a block which it's already *modified*; since iterating a dataflow function to a fixpoint may process some blocks multiple times, setting bInsert to FALSE forces GroupInstructions not to modify any blocks) */ psCalcState->bInsert = IMG_FALSE; DoDataflow(psState, psFunc, IMG_TRUE /*forwards*/, psCalcState->uStateSize, asBlockEnds, GroupInstsDF, psCalcState); /* Second pass: actually insert/modify the blocks according to the states computed by the first pass. (Thus, on each block the dataflow function should always return the same state as it did in the final iteration of the first pass, i.e. such that the first pass correctly predicted the outcome of the second; hence no block should have to be processed more than once, avoiding the problem with GroupInstructions above. TODO, if GroupInstructions etc. were reimplemented to be able to process blocks it had already modified, we could do everything in one pass and remove the bInsert distinction.) */ psCalcState->bInsert = IMG_TRUE; DoDataflow(psState, psFunc, IMG_TRUE /*forwards*/, psCalcState->uStateSize, asBlockEnds, GroupInstsDF, psCalcState); //desired result is state at end of fn. However, to avoid a copy, we'll return the whole lot. return asBlockEnds; } static IMG_VOID DoMOEPass(PINTERMEDIATE_STATE psState, PGROUPINST_STATE psGIState, PCALC_STATE psCalcState, IMG_PVOID pvMainInitialState) /***************************************************************************** FUNCTION : CheckFeaturesUsedBP PURPOSE : BLOCK_PROC to check which MOE features could be used. PARAMETERS : psState - Compiler state. pvGIState - PGROUPINST_STATE to Instruction grouping data. RETURNS : Nothing, but may set the element of pvGIState->abCallUsesSetFc and abCallUsesBaseOffset for the function containing the current block. *****************************************************************************/ { PGROUPINST_FUNCSTATE psMainFuncState; PFUNC psFunc; IMG_UINT32 uLabel; /* For each function allocate memory to hold the MOE state before the start of the function. */ for (uLabel = 0; uLabel < psState->uMaxLabel; uLabel++) { PGROUPINST_FUNCSTATE psFuncState; psFuncState = &psGIState->asFunc[uLabel]; psFuncState->pvInitialState = UscAlloc(psState, psCalcState->uStateSize); psFuncState->bUsed = IMG_FALSE; } /* Initialize the MOE state before the main function. */ psMainFuncState = &psGIState->asFunc[psState->psMainProg->uLabel]; if (pvMainInitialState != NULL) { memcpy(psMainFuncState->pvInitialState, pvMainInitialState, psCalcState->uStateSize); } else { psCalcState->pfSetDefault(psMainFuncState->pvInitialState); } psMainFuncState->bUsed = IMG_TRUE; /* Initialize the MOE state before the secondary update program. */ if (psState->psSecAttrProg) { PGROUPINST_FUNCSTATE psSecAttrProgFuncState; psSecAttrProgFuncState = &psGIState->asFunc[psState->psSecAttrProg->uLabel]; psCalcState->pfSetDefault(psSecAttrProgFuncState->pvInitialState); psSecAttrProgFuncState->bUsed = IMG_TRUE; } /* Do the MOE pass for all functions. */ for (psFunc = psState->psFnOutermost; psFunc; psFunc = psFunc->psFnNestInner) { IMG_PVOID asAll; PGROUPINST_FUNCSTATE psFuncState = &psGIState->asFunc[psFunc->uLabel]; ASSERT (psFuncState->bUsed); /* Do the MOE pass for this function returning the MOE state after each block. */ asAll = DoGroupInsts(psState, psFunc, psFuncState->pvInitialState, psGIState, psCalcState); /* Do any work needed based on the MOE state at the end of the function. */ if (psCalcState->pfProcessFuncEnd != NULL) { psCalcState->pfProcessFuncEnd(psState, psFunc, psCalcState, asAll); } /* Free block end states. */ UscFree(psState, asAll); } /* Free memory allocated for the initial MOE state for each function. */ for (uLabel = 0; uLabel < psState->uMaxLabel; uLabel++) { PGROUPINST_FUNCSTATE psFuncState; psFuncState = &psGIState->asFunc[uLabel]; UscFree(psState, psFuncState->pvInitialState); } } static IMG_VOID SMLSI_ProcessFuncEnd(PINTERMEDIATE_STATE psState, PFUNC psFunc, PCALC_STATE psCalcState, IMG_PVOID pvAll) /***************************************************************************** FUNCTION : SMLSI_ProcessFuncEnd PURPOSE : Do any work needed after generating repeating instructions in a function. PARAMETERS : psState - Compiler state. psFunc - Function that was just processed. pvAll - MOE state after each block in the function. RETURNS : Nothing. *****************************************************************************/ { PSMLSI_STATE asAll = (PSMLSI_STATE)pvAll; PCODEBLOCK psResetBlock; PSMLSI_STATE psEndState; IMG_UINT32 uArg; PVR_UNREFERENCED_PARAMETER(psCalcState); if (psFunc == psState->psMainProg) { /* If this flag is set then the MOE state after the program can be anything. */ if (psState->uCompilerFlags & UF_DONTRESETMOEAFTERPROGRAM) { return; } /* Insert instructions to restore a default state at the end of the program. If splitting for feedback is on then the end of the program (for this purpose) is the point where feedback is done. */ if (psState->uFlags & USC_FLAGS_SPLITFEEDBACKCALC) { psResetBlock = psState->psPreFeedbackBlock; } else { psResetBlock = psState->psMainProg->sCfg.psExit; } } else { /* Reset the MOE state at the function exit. */ psResetBlock = psFunc->sCfg.psExit; } /* Get the MOE state at the end of the function. */ psEndState = &asAll[psResetBlock->uIdx]; /* Check for needing to reset the MOE state. */ for (uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { PMOE_DATA psMoeData; psMoeData = &psEndState->psMoeData[uArg]; if (psFunc == psState->psMainProg) { /* Check for swizzle mode with the first channel selection non-zero. */ if ( psMoeData->eOperandMode == MOE_SWIZZLE && psMoeData->u.s.auSwizzle[0] != 0 ) { break; } } else { /* Check for multiple possible MOE states. */ if (psEndState->pbInvalid[uArg]) { break; } /* Check for the MOE state different to the default state. */ if (!EqualMoeData(psMoeData, &sDefaultSmsliState.psMoeData[uArg], 1)) { break; } } } if (uArg < USC_MAX_MOE_OPERANDS) { /* Insert an instruction to reset the increments back to their defaults. */ PINST psSmlsiInst; ResetMoeOpState(psEndState); /* Make the reset instruction */ psSmlsiInst = AllocateInst(psState, IMG_NULL); MoeToInst(psState,psEndState, psSmlsiInst); /* Add it to the epilogue */ AppendInst(psState, psResetBlock, psSmlsiInst); } } static IMG_VOID SMLSI_Merge(IMG_PVOID pvDest, IMG_PVOID pvSrc) /***************************************************************************** FUNCTION : SMLSI_Merge PURPOSE : Merge two possible MOE states together. PARAMETERS : pvDest - On entry: the first state to merge. On exit: the merged states. pvSrc - The second state to merge. RETURNS : Nothing. *****************************************************************************/ { IMG_UINT32 i; PSMLSI_STATE psDest = (PSMLSI_STATE)pvDest; PSMLSI_STATE psSrc = (PSMLSI_STATE)pvSrc; for (i = 0; i < USC_MAX_MOE_OPERANDS; i++) { if (!EqualMoeData(&psDest->psMoeData[i], &psSrc->psMoeData[i], 1) || psSrc->pbInvalid[i]) { /* If the states don't match then mark the destination as invalid. */ psDest->pbInvalid[i] = IMG_TRUE; } } } static IMG_VOID SMLSI_SetDefault(IMG_PVOID pvState) /***************************************************************************** FUNCTION : SMLSI_SetDefault PURPOSE : Copy the default MOE state. PARAMETERS : pvState - Updated with the default MOE state. RETURNS : Nothing. *****************************************************************************/ { ResetMoeOpState((PSMLSI_STATE)pvState); } static IMG_VOID InsertSmlsi(PINTERMEDIATE_STATE psState, PGROUPINST_STATE psGIState) /***************************************************************************** FUNCTION : InsertSmlsi PURPOSE : Generate repeating instructions. PARAMETERS : psState - Compiler state. psGIState - Module state. RETURNS : Nothing. *****************************************************************************/ { CALC_STATE sCalcState; sCalcState.psGIState = psGIState; sCalcState.uStateSize = sizeof(SMLSI_STATE); sCalcState.pvInitial = NULL; sCalcState.pvPostFuncState = NULL; sCalcState.pfProcessBasicBlock = GroupInstructionsBasicBlock; sCalcState.pfSetDefault = SMLSI_SetDefault; sCalcState.pfMerge = SMLSI_Merge; sCalcState.pfProcessFuncEnd = SMLSI_ProcessFuncEnd; DoMOEPass(psState, psGIState, &sCalcState, NULL); } static IMG_VOID SMBO_SetDefault(IMG_PVOID pvState) /***************************************************************************** FUNCTION : SMBO_SetDefault PURPOSE : Copy the default MOE state. PARAMETERS : pvState - Updated with the default MOE state. RETURNS : Nothing. *****************************************************************************/ { PSMBO_STATE psState = (PSMBO_STATE)pvState; IMG_UINT32 uArg; for (uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { psState->pbInvalidBaseOffsets[uArg] = IMG_FALSE; psState->puBaseOffsets[uArg] = 0; } } static IMG_VOID SMBO_Merge(IMG_PVOID pvDest, IMG_PVOID pvSrc) /***************************************************************************** FUNCTION : SMBO_Merge PURPOSE : Merge two possible MOE states together. PARAMETERS : pvDest - On entry: the first state to merge. On exit: the merged states. pvSrc - The second state to merge. RETURNS : Nothing. *****************************************************************************/ { PSMBO_STATE psDest = (PSMBO_STATE)pvDest; PSMBO_STATE psSrc = (PSMBO_STATE)pvSrc; IMG_UINT32 uArg; for (uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { if (psDest->puBaseOffsets[uArg] != psSrc->puBaseOffsets[uArg] || psSrc->pbInvalidBaseOffsets[uArg]) { psDest->pbInvalidBaseOffsets[uArg] = IMG_TRUE; } } } static IMG_VOID SMBO_ProcessFuncEnd(PINTERMEDIATE_STATE psState, PFUNC psFunc, PCALC_STATE psCalcState, IMG_PVOID pvAll) /***************************************************************************** FUNCTION : SMBO_ProcessFuncEnd PURPOSE : Do any work needed after inserting SMBO instructions in a function. PARAMETERS : psState - Compiler state. psFunc - Function that was just processed. pvAll - MOE state after each block in the function. RETURNS : Nothing. *****************************************************************************/ { PSMBO_STATE asAll = (PSMBO_STATE)pvAll; IMG_UINT32 uArg; PCODEBLOCK psResetBlock; PSMBO_STATE psEndState; IMG_BOOL bResetBaseOffset; PVR_UNREFERENCED_PARAMETER(psCalcState); if (psFunc == psState->psMainProg) { /* If this flag is set then the base offset at the end of the program can have any value. */ if (psState->uCompilerFlags & UF_DONTRESETMOEAFTERPROGRAM) { return; } /* Insert instructions to restore a default state at the end of the program. If splitting for feedback is on then the end of the program is the point where feedback is done. */ if (psState->uFlags & USC_FLAGS_SPLITFEEDBACKCALC) { psResetBlock = psState->psPreFeedbackBlock; } else { psResetBlock = psState->psMainProg->sCfg.psExit; } } else if (psFunc == psState->psSecAttrProg) { /* The base offsets at the end of the secondary update program can have any value. */ return; } else { /* Reset the MOE state at the function exit. */ psResetBlock = psFunc->sCfg.psExit; } psEndState = &asAll[psResetBlock->uIdx]; /* Check for invalid values in the MOE state. */ bResetBaseOffset = IMG_FALSE; for (uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { if (psEndState->pbInvalidBaseOffsets[uArg] || psEndState->puBaseOffsets[uArg] != 0) { bResetBaseOffset = IMG_TRUE; } } if (bResetBaseOffset) { /* Insert an instruction to reset the base offsets back to their default value. */ PINST psSmboInst; psSmboInst = AllocateInst(psState, IMG_NULL); SetOpcodeAndDestCount(psState, psSmboInst, ISMBO, 0 /* uDestCount */); for (uArg = 0; uArg < USC_MAX_MOE_OPERANDS; uArg++) { psSmboInst->asArg[uArg].uType = USEASM_REGTYPE_IMMEDIATE; psSmboInst->asArg[uArg].uNumber = 0; } AppendInst(psState, psResetBlock, psSmboInst); } } static IMG_VOID InsertSmbo(PINTERMEDIATE_STATE psState, PGROUPINST_STATE psGIState) /***************************************************************************** FUNCTION : InsertSmbo PURPOSE : Insert SMBO instructions where instructions are using registers numbers larger than directly addressable by the hardware. PARAMETERS : psState - Compiler state. psGIState - Modulate state. RETURNS : Nothing. *****************************************************************************/ { CALC_STATE sCalcState; sCalcState.psGIState = psGIState; sCalcState.uStateSize = sizeof(SMBO_STATE); sCalcState.pvInitial = NULL; sCalcState.pvPostFuncState = NULL; sCalcState.pfProcessBasicBlock = CheckBaseOffsetBasicBlock; sCalcState.pfSetDefault = SMBO_SetDefault; sCalcState.pfMerge = SMBO_Merge; sCalcState.pfProcessFuncEnd = SMBO_ProcessFuncEnd; DoMOEPass(psState, psGIState, &sCalcState, NULL); } static IMG_VOID SETFC_SetDefault(IMG_PVOID pvState) /***************************************************************************** FUNCTION : SETFC_SetDefault PURPOSE : Copy the default MOE state. PARAMETERS : pvState - Updated with the default MOE state. RETURNS : Nothing. *****************************************************************************/ { PSETFC_STATE psState = (PSETFC_STATE)pvState; /* Set the initial value of the format control for EFO instructions. */ #if EURASIA_USE_MOE_INITIAL_EFO_FORMAT_CONTROL psState->aeFlag[FORMAT_CONTROL_FLAG_TYPE_EFO] = FORMAT_CONTROL_FLAG_ON; #else /* EURASIA_USE_MOE_INITIAL_EFO_FORMAT_CONTROL */ psState->aeFlag[FORMAT_CONTROL_FLAG_TYPE_EFO] = FORMAT_CONTROL_FLAG_OFF; #endif /* EURASIA_USE_MOE_INITIAL_EFO_FORMAT_CONTROL */ /* Set the initial value of the format control for U8/C10 instructions. */ #if EURASIA_USE_MOE_INITIAL_COLOUR_FORMAT_CONTROL psState->aeFlag[FORMAT_CONTROL_FLAG_TYPE_COLOUR] = FORMAT_CONTROL_FLAG_ON; #else /* EURASIA_USE_MOE_INITIAL_COLOUR_FORMAT_CONTROL */ psState->aeFlag[FORMAT_CONTROL_FLAG_TYPE_COLOUR] = FORMAT_CONTROL_FLAG_OFF; #endif /* EURASIA_USE_MOE_INITIAL_COLOUR_FORMAT_CONTROL */ } static IMG_VOID SETFC_Merge(IMG_PVOID pvDest, IMG_PVOID pvSrc) /***************************************************************************** FUNCTION : SETFC_Merge PURPOSE : Merge two possible MOE states together. PARAMETERS : pvDest - On entry: the first state to merge. On exit: the merged states. pvSrc - The second state to merge. RETURNS : Nothing. *****************************************************************************/ { PSETFC_STATE psDest = (PSETFC_STATE)pvDest; PSETFC_STATE psSrc = (PSETFC_STATE)pvSrc; IMG_UINT32 uArg; /* Set the format control flags to invalid if their value in the two states differs. */ for (uArg = 0; uArg < FORMAT_CONTROL_FLAG_TYPE_COUNT; uArg++) { if (psDest->aeFlag[uArg] != psSrc->aeFlag[uArg]) { psDest->aeFlag[uArg] = FORMAT_CONTROL_FLAG_UNDEFINED; } } } static IMG_VOID SETFC_ProcessFuncEnd(PINTERMEDIATE_STATE psState, PFUNC psFunc, PCALC_STATE psCalcState, IMG_PVOID pvAll) /***************************************************************************** FUNCTION : SETFC_ProcessFuncEnd PURPOSE : Do any work needed after inserting SETFC instructions in a function. PARAMETERS : psState - Compiler state. psFunc - Function that was just processed. pvAll - MOE state after each block in the function. RETURNS : Nothing. *****************************************************************************/ { PSETFC_STATE asAll = (PSETFC_STATE)pvAll; PCODEBLOCK psResetBlock; PSETFC_STATE psEndState; PSETFC_STATE psDefaultState; IMG_BOOL bResetSetfcState; IMG_UINT32 uArg; if (psFunc == psState->psMainProg || psFunc == psState->psSecAttrProg) { /* Code executing after the main function or the secondary update program won't assume anything about the MOE format control state. */ return; } else { /* Reset the MOE state at the function exit. */ psResetBlock = psFunc->sCfg.psExit; } /* Get the MOE state at the end of the function. */ psEndState = &asAll[psResetBlock->uIdx]; /* Check if the MOE differs from the default. */ bResetSetfcState = IMG_FALSE; psDefaultState = (PSETFC_STATE)psCalcState->pvPostFuncState; for (uArg = 0; uArg < FORMAT_CONTROL_FLAG_TYPE_COUNT; uArg++) { if (psEndState->aeFlag[uArg] != psDefaultState->aeFlag[uArg]) { bResetSetfcState = IMG_TRUE; } } /* If the MOE state differs from the default then insert an instruction at the end of the block to reset it. */ if (bResetSetfcState) { InsertSetfcInstruction(psState, psResetBlock, NULL, psDefaultState); } } static IMG_VOID InsertSetfc(PINTERMEDIATE_STATE psState, PGROUPINST_STATE psGIState) /***************************************************************************** FUNCTION : InsertSetfc PURPOSE : Insert SETFC instructions where required. PARAMETERS : psState - Compiler state. psGIState - Module state. RETURNS : Nothing. *****************************************************************************/ { CALC_STATE sCalcState; IMG_BOOL bInsertInitialSETFC = IMG_FALSE; /* Check what states of the format control are required by the program. */ FMT_CTRL_EVER sFmtCtrl = { IMG_FALSE, IMG_FALSE, IMG_FALSE, IMG_FALSE, IMG_FALSE }; SETFC_STATE sInitialState; DoOnAllBasicBlocks(psState, ANY_ORDER, SearchFormatControlBP, IMG_FALSE, &sFmtCtrl); /* Get the initial state of the two format control bits set up by the hardware at the start of the program. */ SETFC_SetDefault(&sInitialState); /* Check if only one setting of the EFO format control is used in the program. */ if ( !(sFmtCtrl.bEfoFmtCtrlEverOn && sFmtCtrl.bEfoFmtCtrlEverOff) && (sFmtCtrl.bEfoFmtCtrlEverOn || sFmtCtrl.bEfoFmtCtrlEverOff) && !sFmtCtrl.bFormatChangeAfterFeedback ) { FORMAT_CONTROL_FLAG eEfoFmtCtrlSetting; if (sFmtCtrl.bEfoFmtCtrlEverOn) { eEfoFmtCtrlSetting = FORMAT_CONTROL_FLAG_ON; } else { eEfoFmtCtrlSetting = FORMAT_CONTROL_FLAG_OFF; } /* If the required setting doesn't match the default set by the hardware then insert an initial SETFC instruction. */ if (sInitialState.aeFlag[FORMAT_CONTROL_FLAG_TYPE_EFO] != eEfoFmtCtrlSetting) { bInsertInitialSETFC = IMG_TRUE; sInitialState.aeFlag[FORMAT_CONTROL_FLAG_TYPE_EFO] = eEfoFmtCtrlSetting; } } /* Check if only one setting of the colour format control is used in the program. */ if ( !(sFmtCtrl.bColFmtCtrlEverOn && sFmtCtrl.bColFmtCtrlEverOff) && (sFmtCtrl.bColFmtCtrlEverOn || sFmtCtrl.bColFmtCtrlEverOff) && !sFmtCtrl.bFormatChangeAfterFeedback ) { FORMAT_CONTROL_FLAG eColFmtCtrlSetting; if (sFmtCtrl.bColFmtCtrlEverOn) { eColFmtCtrlSetting = FORMAT_CONTROL_FLAG_ON; } else { eColFmtCtrlSetting = FORMAT_CONTROL_FLAG_OFF; } /* If the required setting doesn't match the default set by the hardware then insert an initial SETFC instruction. */ if (sInitialState.aeFlag[FORMAT_CONTROL_FLAG_TYPE_COLOUR] != eColFmtCtrlSetting) { bInsertInitialSETFC = IMG_TRUE; sInitialState.aeFlag[FORMAT_CONTROL_FLAG_TYPE_COLOUR] = eColFmtCtrlSetting; } } /* Insert SETFC instructions. */ sCalcState.psGIState = psGIState; sCalcState.uStateSize = sizeof(SETFC_STATE); sCalcState.pvInitial = NULL; sCalcState.pvPostFuncState = &sInitialState; sCalcState.pfProcessBasicBlock = CheckFormatControlBasicBlock; sCalcState.pfSetDefault = SETFC_SetDefault; sCalcState.pfMerge = SETFC_Merge; sCalcState.pfProcessFuncEnd = SETFC_ProcessFuncEnd; DoMOEPass(psState, psGIState, &sCalcState, &sInitialState); /* Insert an instruction at the program entrypoint to establish the initial format control state. */ if (bInsertInitialSETFC) { InsertSetfcInstruction(psState, psState->psMainProg->sCfg.psEntry, psState->psMainProg->sCfg.psEntry->psBody, &sInitialState); } } IMG_INTERNAL IMG_VOID GroupInstructionsProgram(PINTERMEDIATE_STATE psState) /***************************************************************************** FUNCTION : GroupInstructionsProgram PURPOSE : Generate repeating instructions for a program. PARAMETERS : psState - Compiler state. RETURNS : Nothing. *****************************************************************************/ { PGROUPINST_STATE psGIState = NULL; /* Allocate the groupinst state. */ InitGroupInstState(psState, &psGIState); DoOnAllBasicBlocks(psState, ANY_ORDER, GenerateDotProdBP, IMG_FALSE, NULL); TESTONLY_PRINT_INTERMEDIATE("Generate DP/DDP", "gen_ddp", IMG_FALSE); /* Flag that the interpretation of register number changes once the MOE state is applied. */ psState->uFlags |= USC_FLAGS_MOESTAGE; /* Copy ARG.uNumber to ARG.uNumberPreMoe for each instruction source and destination. After this point ARG.uNumber is the register to encode directly in the instruction, which will be equal to ARG.uNumberPreMoe after the hardware applies the MOE state. */ DoOnAllBasicBlocks(psState, ANY_ORDER, SaveRegNumsBP, IMG_FALSE/*CALLs*/, NULL); /* Change register numbers to be in the same units as the MOE increments/base offset/etc. */ DoOnAllBasicBlocks(psState, ANY_ORDER, AdjustToMOEUnitsBP, IMG_FALSE, NULL); /* Generate repeated instructions. */ InsertSmlsi(psState, psGIState); TESTONLY_PRINT_INTERMEDIATE("Generate Repeats", "generate_repeats", IMG_FALSE); /* Insert SMBO instructions where the register numbers used in instructions are larger than that directly supported by the hardware. */ InsertSmbo(psState, psGIState); TESTONLY_PRINT_INTERMEDIATE("Insert SMBO", "insert_smbo", IMG_FALSE); /* Insert SETFC instructions where instructions require them. */ InsertSetfc(psState, psGIState); TESTONLY_PRINT_INTERMEDIATE("Insert SETFC", "insert_setfc", IMG_FALSE); /* Free the allocated memory */ FreeGroupInstState(psState, psGIState); }
27.698607
140
0.66064
[ "vector", "model" ]
70e1a024eab1b93bf51f1a2eda088f64da70af46
1,622
c
C
obj_process_face_get_type.c
tac4ttack/simpleOBJ
7aaaa2424ca04d5cf8502cb849392fb7ddff2659
[ "Unlicense" ]
null
null
null
obj_process_face_get_type.c
tac4ttack/simpleOBJ
7aaaa2424ca04d5cf8502cb849392fb7ddff2659
[ "Unlicense" ]
1
2019-11-01T09:10:33.000Z
2019-11-01T09:10:33.000Z
obj_process_face_get_type.c
tac4ttack/simpleOBJ
7aaaa2424ca04d5cf8502cb849392fb7ddff2659
[ "Unlicense" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* obj_process_face_get_type.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fmessina <fmessina@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/28 15:59:07 by fmessina #+# #+# */ /* Updated: 2019/07/01 15:34:27 by fmessina ### ########.fr */ /* */ /* ************************************************************************** */ #include "simple_obj.h" /* ** obj_process_face_type_get(): ** Analyze the "sample" string which should be a face element definition line ** as specified by the Wavefront OBJ mesh file format ** Possible results are: ** -1 = unknown ** 0 = Vn ** 1 = Vn/VTn ** 2 = Vn/VTn/VNn ** 3 = Vn//VNn */ int obj_process_face_type_get(char *sample) { char **split; size_t len; if (sample) { if (strstr(sample, "//")) return (3); else { if (!(split = obj_strsplit(sample, '/'))) return (-1); len = obj_strsplit_len(split); obj_strsplit_destroy(split); if (len == 1) return (0); else if (len == 2) return (1); else if (len == 3) return (2); else return (-1); } } return (-1); }
30.037037
80
0.339088
[ "mesh" ]
70e53df6de7b31b42e84b4daf0c1ef5d4726549a
18,388
c
C
hw/mcu/nxp/mcux-sdk/components/slcd_engine/GDH-1247WP/GDH-1247WP.c
bm16ton/portenta-tinyusb
472ccb5bd6da5c3cf55210c28df72667c825152a
[ "MIT" ]
175
2021-01-19T17:11:01.000Z
2022-03-31T06:04:43.000Z
components/slcd_engine/GDH-1247WP/GDH-1247WP.c
tannewt/mcux-sdk
1f15787b0abb7886f24434297cd293cf16ad04ab
[ "Apache-2.0" ]
69
2021-01-27T08:18:51.000Z
2022-03-29T12:16:57.000Z
components/slcd_engine/GDH-1247WP/GDH-1247WP.c
tannewt/mcux-sdk
1f15787b0abb7886f24434297cd293cf16ad04ab
[ "Apache-2.0" ]
72
2021-01-19T14:34:20.000Z
2022-03-21T09:02:18.000Z
/* * Copyright 2019-2020 NXP * * SPDX-License-Identifier: BSD-3-Clause */ /* printed number only for pin map id01: xx 14D 14E 14C 14G 14F 14B 14A id02: xx 13D 13E 13C 13G 13F 13B 13A id03: xx 12D 12E 12C 12G 12F 12B 12A id04: xx 11D 11E 11C 11G 11F 11B 11A id05: xx 10D 10E 10C 10G 10F 10B 10A id06: 15D 15E 15C 15G 15F 15B 15A xx id07: xx xx xx xx xx xx xx xx id08: xx xx xx xx xx xx xx xx id09: xx xx xx xx xx xx xx xx id10: xx 1A 1F 1B 1G 1E 1C 1D id11: xx 2A 2F 2B 2G 2E 2C 2D id12: xx 3A 3F 3B 3G 3E 3C 3D id13: xx 4A 4F 4B 4G 4E 4C 4D id14: xx 5A 5F 5B 5G 5E 5C 5D id15: xx 6A 6F 6B 6G 6E 6C 6D id16: xx 7A 7F 7B 7G 7E 7C 7D id17: xx 8A 8F 8B 8G 8E 8C 8D id18: xx 9A 9F 9B 9G 9E 9C 9D id19: xx xx xx xx xx xx xx xx id20: xx xx xx xx xx xx xx xx */ #include <stdint.h> #include "GDH-1247WP.h" static const uint16_t SLCD_NumPos1_Num0[] = { 0xaee, 0x0, }; static const uint16_t SLCD_NumPos1_Num1[] = { 0xa48, 0x0, }; static const uint16_t SLCD_NumPos1_Num2[] = { 0xaba, 0x0, }; static const uint16_t SLCD_NumPos1_Num3[] = { 0xada, 0x0, }; static const uint16_t SLCD_NumPos1_Num4[] = { 0xa5c, 0x0, }; static const uint16_t SLCD_NumPos1_Num5[] = { 0xad6, 0x0, }; static const uint16_t SLCD_NumPos1_Num6[] = { 0xaf6, 0x0, }; static const uint16_t SLCD_NumPos1_Num7[] = { 0xa4a, 0x0, }; static const uint16_t SLCD_NumPos1_Num8[] = { 0xafe, 0x0, }; static const uint16_t SLCD_NumPos1_Num9[] = { 0xade, 0x0, }; static const uint16_t *SLCD_NumPos1[] = { SLCD_NumPos1_Num0, SLCD_NumPos1_Num1, SLCD_NumPos1_Num2, SLCD_NumPos1_Num3, SLCD_NumPos1_Num4, SLCD_NumPos1_Num5, SLCD_NumPos1_Num6, SLCD_NumPos1_Num7, SLCD_NumPos1_Num8, SLCD_NumPos1_Num9, }; static const uint16_t SLCD_NumPos2_Num0[] = { 0xbee, 0x0, }; static const uint16_t SLCD_NumPos2_Num1[] = { 0xb48, 0x0, }; static const uint16_t SLCD_NumPos2_Num2[] = { 0xbba, 0x0, }; static const uint16_t SLCD_NumPos2_Num3[] = { 0xbda, 0x0, }; static const uint16_t SLCD_NumPos2_Num4[] = { 0xb5c, 0x0, }; static const uint16_t SLCD_NumPos2_Num5[] = { 0xbd6, 0x0, }; static const uint16_t SLCD_NumPos2_Num6[] = { 0xbf6, 0x0, }; static const uint16_t SLCD_NumPos2_Num7[] = { 0xb4a, 0x0, }; static const uint16_t SLCD_NumPos2_Num8[] = { 0xbfe, 0x0, }; static const uint16_t SLCD_NumPos2_Num9[] = { 0xbde, 0x0, }; static const uint16_t *SLCD_NumPos2[] = { SLCD_NumPos2_Num0, SLCD_NumPos2_Num1, SLCD_NumPos2_Num2, SLCD_NumPos2_Num3, SLCD_NumPos2_Num4, SLCD_NumPos2_Num5, SLCD_NumPos2_Num6, SLCD_NumPos2_Num7, SLCD_NumPos2_Num8, SLCD_NumPos2_Num9, }; static const uint16_t SLCD_NumPos3_Num0[] = { 0xcee, 0x0, }; static const uint16_t SLCD_NumPos3_Num1[] = { 0xc48, 0x0, }; static const uint16_t SLCD_NumPos3_Num2[] = { 0xcba, 0x0, }; static const uint16_t SLCD_NumPos3_Num3[] = { 0xcda, 0x0, }; static const uint16_t SLCD_NumPos3_Num4[] = { 0xc5c, 0x0, }; static const uint16_t SLCD_NumPos3_Num5[] = { 0xcd6, 0x0, }; static const uint16_t SLCD_NumPos3_Num6[] = { 0xcf6, 0x0, }; static const uint16_t SLCD_NumPos3_Num7[] = { 0xc4a, 0x0, }; static const uint16_t SLCD_NumPos3_Num8[] = { 0xcfe, 0x0, }; static const uint16_t SLCD_NumPos3_Num9[] = { 0xcde, 0x0, }; static const uint16_t *SLCD_NumPos3[] = { SLCD_NumPos3_Num0, SLCD_NumPos3_Num1, SLCD_NumPos3_Num2, SLCD_NumPos3_Num3, SLCD_NumPos3_Num4, SLCD_NumPos3_Num5, SLCD_NumPos3_Num6, SLCD_NumPos3_Num7, SLCD_NumPos3_Num8, SLCD_NumPos3_Num9, }; static const uint16_t SLCD_NumPos4_Num0[] = { 0xdee, 0x0, }; static const uint16_t SLCD_NumPos4_Num1[] = { 0xd48, 0x0, }; static const uint16_t SLCD_NumPos4_Num2[] = { 0xdba, 0x0, }; static const uint16_t SLCD_NumPos4_Num3[] = { 0xdda, 0x0, }; static const uint16_t SLCD_NumPos4_Num4[] = { 0xd5c, 0x0, }; static const uint16_t SLCD_NumPos4_Num5[] = { 0xdd6, 0x0, }; static const uint16_t SLCD_NumPos4_Num6[] = { 0xdf6, 0x0, }; static const uint16_t SLCD_NumPos4_Num7[] = { 0xd4a, 0x0, }; static const uint16_t SLCD_NumPos4_Num8[] = { 0xdfe, 0x0, }; static const uint16_t SLCD_NumPos4_Num9[] = { 0xdde, 0x0, }; static const uint16_t *SLCD_NumPos4[] = { SLCD_NumPos4_Num0, SLCD_NumPos4_Num1, SLCD_NumPos4_Num2, SLCD_NumPos4_Num3, SLCD_NumPos4_Num4, SLCD_NumPos4_Num5, SLCD_NumPos4_Num6, SLCD_NumPos4_Num7, SLCD_NumPos4_Num8, SLCD_NumPos4_Num9, }; static const uint16_t SLCD_NumPos5_Num0[] = { 0xeee, 0x0, }; static const uint16_t SLCD_NumPos5_Num1[] = { 0xe48, 0x0, }; static const uint16_t SLCD_NumPos5_Num2[] = { 0xeba, 0x0, }; static const uint16_t SLCD_NumPos5_Num3[] = { 0xeda, 0x0, }; static const uint16_t SLCD_NumPos5_Num4[] = { 0xe5c, 0x0, }; static const uint16_t SLCD_NumPos5_Num5[] = { 0xed6, 0x0, }; static const uint16_t SLCD_NumPos5_Num6[] = { 0xef6, 0x0, }; static const uint16_t SLCD_NumPos5_Num7[] = { 0xe4a, 0x0, }; static const uint16_t SLCD_NumPos5_Num8[] = { 0xefe, 0x0, }; static const uint16_t SLCD_NumPos5_Num9[] = { 0xede, 0x0, }; static const uint16_t *SLCD_NumPos5[] = { SLCD_NumPos5_Num0, SLCD_NumPos5_Num1, SLCD_NumPos5_Num2, SLCD_NumPos5_Num3, SLCD_NumPos5_Num4, SLCD_NumPos5_Num5, SLCD_NumPos5_Num6, SLCD_NumPos5_Num7, SLCD_NumPos5_Num8, SLCD_NumPos5_Num9, }; static const uint16_t SLCD_NumPos6_Num0[] = { 0xfee, 0x0, }; static const uint16_t SLCD_NumPos6_Num1[] = { 0xf48, 0x0, }; static const uint16_t SLCD_NumPos6_Num2[] = { 0xfba, 0x0, }; static const uint16_t SLCD_NumPos6_Num3[] = { 0xfda, 0x0, }; static const uint16_t SLCD_NumPos6_Num4[] = { 0xf5c, 0x0, }; static const uint16_t SLCD_NumPos6_Num5[] = { 0xfd6, 0x0, }; static const uint16_t SLCD_NumPos6_Num6[] = { 0xff6, 0x0, }; static const uint16_t SLCD_NumPos6_Num7[] = { 0xf4a, 0x0, }; static const uint16_t SLCD_NumPos6_Num8[] = { 0xffe, 0x0, }; static const uint16_t SLCD_NumPos6_Num9[] = { 0xfde, 0x0, }; static const uint16_t *SLCD_NumPos6[] = { SLCD_NumPos6_Num0, SLCD_NumPos6_Num1, SLCD_NumPos6_Num2, SLCD_NumPos6_Num3, SLCD_NumPos6_Num4, SLCD_NumPos6_Num5, SLCD_NumPos6_Num6, SLCD_NumPos6_Num7, SLCD_NumPos6_Num8, SLCD_NumPos6_Num9, }; static const uint16_t SLCD_NumPos7_Num0[] = { 0x10ee, 0x0, }; static const uint16_t SLCD_NumPos7_Num1[] = { 0x1048, 0x0, }; static const uint16_t SLCD_NumPos7_Num2[] = { 0x10ba, 0x0, }; static const uint16_t SLCD_NumPos7_Num3[] = { 0x10da, 0x0, }; static const uint16_t SLCD_NumPos7_Num4[] = { 0x105c, 0x0, }; static const uint16_t SLCD_NumPos7_Num5[] = { 0x10d6, 0x0, }; static const uint16_t SLCD_NumPos7_Num6[] = { 0x10f6, 0x0, }; static const uint16_t SLCD_NumPos7_Num7[] = { 0x104a, 0x0, }; static const uint16_t SLCD_NumPos7_Num8[] = { 0x10fe, 0x0, }; static const uint16_t SLCD_NumPos7_Num9[] = { 0x10de, 0x0, }; static const uint16_t *SLCD_NumPos7[] = { SLCD_NumPos7_Num0, SLCD_NumPos7_Num1, SLCD_NumPos7_Num2, SLCD_NumPos7_Num3, SLCD_NumPos7_Num4, SLCD_NumPos7_Num5, SLCD_NumPos7_Num6, SLCD_NumPos7_Num7, SLCD_NumPos7_Num8, SLCD_NumPos7_Num9, }; static const uint16_t SLCD_NumPos8_Num0[] = { 0x11ee, 0x0, }; static const uint16_t SLCD_NumPos8_Num1[] = { 0x1148, 0x0, }; static const uint16_t SLCD_NumPos8_Num2[] = { 0x11ba, 0x0, }; static const uint16_t SLCD_NumPos8_Num3[] = { 0x11da, 0x0, }; static const uint16_t SLCD_NumPos8_Num4[] = { 0x115c, 0x0, }; static const uint16_t SLCD_NumPos8_Num5[] = { 0x11d6, 0x0, }; static const uint16_t SLCD_NumPos8_Num6[] = { 0x11f6, 0x0, }; static const uint16_t SLCD_NumPos8_Num7[] = { 0x114a, 0x0, }; static const uint16_t SLCD_NumPos8_Num8[] = { 0x11fe, 0x0, }; static const uint16_t SLCD_NumPos8_Num9[] = { 0x11de, 0x0, }; static const uint16_t *SLCD_NumPos8[] = { SLCD_NumPos8_Num0, SLCD_NumPos8_Num1, SLCD_NumPos8_Num2, SLCD_NumPos8_Num3, SLCD_NumPos8_Num4, SLCD_NumPos8_Num5, SLCD_NumPos8_Num6, SLCD_NumPos8_Num7, SLCD_NumPos8_Num8, SLCD_NumPos8_Num9, }; static const uint16_t SLCD_NumPos9_Num0[] = { 0x12ee, 0x0, }; static const uint16_t SLCD_NumPos9_Num1[] = { 0x1248, 0x0, }; static const uint16_t SLCD_NumPos9_Num2[] = { 0x12ba, 0x0, }; static const uint16_t SLCD_NumPos9_Num3[] = { 0x12da, 0x0, }; static const uint16_t SLCD_NumPos9_Num4[] = { 0x125c, 0x0, }; static const uint16_t SLCD_NumPos9_Num5[] = { 0x12d6, 0x0, }; static const uint16_t SLCD_NumPos9_Num6[] = { 0x12f6, 0x0, }; static const uint16_t SLCD_NumPos9_Num7[] = { 0x124a, 0x0, }; static const uint16_t SLCD_NumPos9_Num8[] = { 0x12fe, 0x0, }; static const uint16_t SLCD_NumPos9_Num9[] = { 0x12de, 0x0, }; static const uint16_t *SLCD_NumPos9[] = { SLCD_NumPos9_Num0, SLCD_NumPos9_Num1, SLCD_NumPos9_Num2, SLCD_NumPos9_Num3, SLCD_NumPos9_Num4, SLCD_NumPos9_Num5, SLCD_NumPos9_Num6, SLCD_NumPos9_Num7, SLCD_NumPos9_Num8, SLCD_NumPos9_Num9, }; static const uint16_t SLCD_NumPos10_Num0[] = { 0x5ee, 0x0, }; static const uint16_t SLCD_NumPos10_Num1[] = { 0x548, 0x0, }; static const uint16_t SLCD_NumPos10_Num2[] = { 0x5d6, 0x0, }; static const uint16_t SLCD_NumPos10_Num3[] = { 0x5da, 0x0, }; static const uint16_t SLCD_NumPos10_Num4[] = { 0x578, 0x0, }; static const uint16_t SLCD_NumPos10_Num5[] = { 0x5ba, 0x0, }; static const uint16_t SLCD_NumPos10_Num6[] = { 0x5be, 0x0, }; static const uint16_t SLCD_NumPos10_Num7[] = { 0x5c8, 0x0, }; static const uint16_t SLCD_NumPos10_Num8[] = { 0x5fe, 0x0, }; static const uint16_t SLCD_NumPos10_Num9[] = { 0x5fa, 0x0, }; static const uint16_t *SLCD_NumPos10[] = { SLCD_NumPos10_Num0, SLCD_NumPos10_Num1, SLCD_NumPos10_Num2, SLCD_NumPos10_Num3, SLCD_NumPos10_Num4, SLCD_NumPos10_Num5, SLCD_NumPos10_Num6, SLCD_NumPos10_Num7, SLCD_NumPos10_Num8, SLCD_NumPos10_Num9, }; static const uint16_t SLCD_NumPos11_Num0[] = { 0x4ee, 0x0, }; static const uint16_t SLCD_NumPos11_Num1[] = { 0x448, 0x0, }; static const uint16_t SLCD_NumPos11_Num2[] = { 0x4d6, 0x0, }; static const uint16_t SLCD_NumPos11_Num3[] = { 0x4da, 0x0, }; static const uint16_t SLCD_NumPos11_Num4[] = { 0x478, 0x0, }; static const uint16_t SLCD_NumPos11_Num5[] = { 0x4ba, 0x0, }; static const uint16_t SLCD_NumPos11_Num6[] = { 0x4be, 0x0, }; static const uint16_t SLCD_NumPos11_Num7[] = { 0x4c8, 0x0, }; static const uint16_t SLCD_NumPos11_Num8[] = { 0x4fe, 0x0, }; static const uint16_t SLCD_NumPos11_Num9[] = { 0x4fa, 0x0, }; static const uint16_t *SLCD_NumPos11[] = { SLCD_NumPos11_Num0, SLCD_NumPos11_Num1, SLCD_NumPos11_Num2, SLCD_NumPos11_Num3, SLCD_NumPos11_Num4, SLCD_NumPos11_Num5, SLCD_NumPos11_Num6, SLCD_NumPos11_Num7, SLCD_NumPos11_Num8, SLCD_NumPos11_Num9, }; static const uint16_t SLCD_NumPos12_Num0[] = { 0x3ee, 0x0, }; static const uint16_t SLCD_NumPos12_Num1[] = { 0x348, 0x0, }; static const uint16_t SLCD_NumPos12_Num2[] = { 0x3d6, 0x0, }; static const uint16_t SLCD_NumPos12_Num3[] = { 0x3da, 0x0, }; static const uint16_t SLCD_NumPos12_Num4[] = { 0x378, 0x0, }; static const uint16_t SLCD_NumPos12_Num5[] = { 0x3ba, 0x0, }; static const uint16_t SLCD_NumPos12_Num6[] = { 0x3be, 0x0, }; static const uint16_t SLCD_NumPos12_Num7[] = { 0x3c8, 0x0, }; static const uint16_t SLCD_NumPos12_Num8[] = { 0x3fe, 0x0, }; static const uint16_t SLCD_NumPos12_Num9[] = { 0x3fa, 0x0, }; static const uint16_t *SLCD_NumPos12[] = { SLCD_NumPos12_Num0, SLCD_NumPos12_Num1, SLCD_NumPos12_Num2, SLCD_NumPos12_Num3, SLCD_NumPos12_Num4, SLCD_NumPos12_Num5, SLCD_NumPos12_Num6, SLCD_NumPos12_Num7, SLCD_NumPos12_Num8, SLCD_NumPos12_Num9, }; static const uint16_t SLCD_NumPos13_Num0[] = { 0x2ee, 0x0, }; static const uint16_t SLCD_NumPos13_Num1[] = { 0x248, 0x0, }; static const uint16_t SLCD_NumPos13_Num2[] = { 0x2d6, 0x0, }; static const uint16_t SLCD_NumPos13_Num3[] = { 0x2da, 0x0, }; static const uint16_t SLCD_NumPos13_Num4[] = { 0x278, 0x0, }; static const uint16_t SLCD_NumPos13_Num5[] = { 0x2ba, 0x0, }; static const uint16_t SLCD_NumPos13_Num6[] = { 0x2be, 0x0, }; static const uint16_t SLCD_NumPos13_Num7[] = { 0x2c8, 0x0, }; static const uint16_t SLCD_NumPos13_Num8[] = { 0x2fe, 0x0, }; static const uint16_t SLCD_NumPos13_Num9[] = { 0x2fa, 0x0, }; static const uint16_t *SLCD_NumPos13[] = { SLCD_NumPos13_Num0, SLCD_NumPos13_Num1, SLCD_NumPos13_Num2, SLCD_NumPos13_Num3, SLCD_NumPos13_Num4, SLCD_NumPos13_Num5, SLCD_NumPos13_Num6, SLCD_NumPos13_Num7, SLCD_NumPos13_Num8, SLCD_NumPos13_Num9, }; static const uint16_t SLCD_NumPos14_Num0[] = { 0x1ee, 0x0, }; static const uint16_t SLCD_NumPos14_Num1[] = { 0x148, 0x0, }; static const uint16_t SLCD_NumPos14_Num2[] = { 0x1d6, 0x0, }; static const uint16_t SLCD_NumPos14_Num3[] = { 0x1da, 0x0, }; static const uint16_t SLCD_NumPos14_Num4[] = { 0x178, 0x0, }; static const uint16_t SLCD_NumPos14_Num5[] = { 0x1ba, 0x0, }; static const uint16_t SLCD_NumPos14_Num6[] = { 0x1be, 0x0, }; static const uint16_t SLCD_NumPos14_Num7[] = { 0x1c8, 0x0, }; static const uint16_t SLCD_NumPos14_Num8[] = { 0x1fe, 0x0, }; static const uint16_t SLCD_NumPos14_Num9[] = { 0x1fa, 0x0, }; static const uint16_t *SLCD_NumPos14[] = { SLCD_NumPos14_Num0, SLCD_NumPos14_Num1, SLCD_NumPos14_Num2, SLCD_NumPos14_Num3, SLCD_NumPos14_Num4, SLCD_NumPos14_Num5, SLCD_NumPos14_Num6, SLCD_NumPos14_Num7, SLCD_NumPos14_Num8, SLCD_NumPos14_Num9, }; static const uint16_t SLCD_NumPos15_Num0[] = { 0x677, 0x0, }; static const uint16_t SLCD_NumPos15_Num1[] = { 0x624, 0x0, }; static const uint16_t SLCD_NumPos15_Num2[] = { 0x66b, 0x0, }; static const uint16_t SLCD_NumPos15_Num3[] = { 0x66d, 0x0, }; static const uint16_t SLCD_NumPos15_Num4[] = { 0x63c, 0x0, }; static const uint16_t SLCD_NumPos15_Num5[] = { 0x65d, 0x0, }; static const uint16_t SLCD_NumPos15_Num6[] = { 0x65f, 0x0, }; static const uint16_t SLCD_NumPos15_Num7[] = { 0x664, 0x0, }; static const uint16_t SLCD_NumPos15_Num8[] = { 0x67f, 0x0, }; static const uint16_t SLCD_NumPos15_Num9[] = { 0x67d, 0x0, }; static const uint16_t *SLCD_NumPos15[] = { SLCD_NumPos15_Num0, SLCD_NumPos15_Num1, SLCD_NumPos15_Num2, SLCD_NumPos15_Num3, SLCD_NumPos15_Num4, SLCD_NumPos15_Num5, SLCD_NumPos15_Num6, SLCD_NumPos15_Num7, SLCD_NumPos15_Num8, SLCD_NumPos15_Num9, }; const uint16_t **SLCD_NumPos[] = { SLCD_NumPos1, SLCD_NumPos2, SLCD_NumPos3, SLCD_NumPos4, SLCD_NumPos5, SLCD_NumPos6, SLCD_NumPos7, SLCD_NumPos8, SLCD_NumPos9, SLCD_NumPos10, SLCD_NumPos11, SLCD_NumPos12, SLCD_NumPos13, SLCD_NumPos14, SLCD_NumPos15, }; const uint16_t SLCD_Icon[] = { /* Number part 1*/ 0xa02, 0xa08, 0xa40, 0xa80, 0xa20, 0xa04, 0xa10, /* Number part 2*/ 0xb02, 0xb08, 0xb40, 0xb80, 0xb20, 0xb04, 0xb10, /* Number part 3*/ 0xc02, 0xc08, 0xc40, 0xc80, 0xc20, 0xc04, 0xc10, /* Number part 4*/ 0xd02, 0xd08, 0xd40, 0xd80, 0xd20, 0xd04, 0xd10, /* Number part 5*/ 0xe02, 0xe08, 0xe40, 0xe80, 0xe20, 0xe04, 0xe10, /* Number part 6*/ 0xf02, 0xf08, 0xf40, 0xf80, 0xf20, 0xf04, 0xf10, /* Number part 7*/ 0x1002, 0x1008, 0x1040, 0x1080, 0x1020, 0x1004, 0x1010, /* Number part 8*/ 0x1102, 0x1108, 0x1140, 0x1180, 0x1120, 0x1104, 0x1110, /* Number part 9*/ 0x1202, 0x1208, 0x1240, 0x1280, 0x1220, 0x1204, 0x1210, /* Number part 10*/ 0x580, 0x540, 0x508, 0x502, 0x504, 0x520, 0x510, /* Number part 11*/ 0x480, 0x440, 0x408, 0x402, 0x404, 0x420, 0x410, /* Number part 12*/ 0x380, 0x340, 0x308, 0x302, 0x304, 0x320, 0x310, /* Number part 13*/ 0x280, 0x240, 0x208, 0x202, 0x204, 0x220, 0x210, /* Number part 14*/ 0x180, 0x140, 0x108, 0x102, 0x104, 0x120, 0x110, /* Number part 15*/ 0x640, 0x620, 0x604, 0x601, 0x602, 0x610, 0x608, 0xe01, /* index 15, L1 */ 0xf01, /* index 16, L2 */ 0x1001, /* index 17, L3 */ 0x1404, /* index 18, T1 */ 0x1408, /* index 19, T2 */ 0x1410, /* index 20, T3 */ 0x1420, /* index 21, T4 */ 0x1402, /* index 22, RMS */ 0x1380, /* index 23, P1 */ 0x1340, /* index 24, P2 */ 0x1302, /* index 25, P3 */ 0x401, /* index 26, P4 */ 0x301, /* index 27, P5 */ 0x201, /* index 28, P6 */ 0x101, /* index 29, P7 */ 0x840, /* index 30, S1 */ 0x1301, /* index 31, S2 */ 0x801, /* index 32, S3 */ 0x802, /* index 33, S4 */ 0x808, /* index 34, S5 */ 0x820, /* index 35, S6 */ 0x702, /* index 36, S7 */ 0x804, /* index 37, S8 */ 0x810, /* index 38, S9 */ 0x720, /* index 39, S10 */ 0x710, /* index 40, S11 */ 0x704, /* index 41 , S12 */ 0x708, /* index 42, S13 */ 0x740, /* index 43, S14 */ 0x1401, /* index 44, S15 */ 0x908, /* index 45, S16 */ 0x680, /* index 46, S17 */ 0x501, /* index 47, S18 */ 0x780, /* index 48, S19 */ 0x880, /* index 49, S20 */ 0x940, /* index 50, S21 */ 0x920, /* index 51, S22 */ 0x910, /* index 52, S23 */ 0x904, /* index 53, S24 */ 0x902, /* index 54, S25 */ 0xa01, /* index 55, S26 */ 0xb01, /* index 56, S27 */ 0x901, /* index 57, S28 */ 0x1101, /* index 58, S29 */ 0x1201, /* index 59, S30 */ 0x1304, /* index 60, S31 */ 0x1308, /* index 61 , S32*/ 0x1310, /* index 62, S33 */ 0x1320, /* index 63, S34 */ 0x1480, /* index 64, S35 */ 0xd01, /* index 65, S36 */ 0x1440, /* index 66, S37 */ 0x980, /* index 67, S38 */ 0xc01, /* index 68, S39 */ 0x701 /* index 69, S40 */ };
18.744139
103
0.657548
[ "3d" ]
cb0e49a4104c64216aa6b3337d9293b5de1e2698
9,215
h
C
amd_tressfx_sample/prebuilt/include/ObjectManager/include/SuObjectManager.h
kostenickj/TressFX
9a9a1008fbcc9cc71a6b08331a75bed81c2119ac
[ "MIT" ]
1
2020-07-20T19:07:05.000Z
2020-07-20T19:07:05.000Z
amd_tressfx_sample/prebuilt/include/ObjectManager/include/SuObjectManager.h
kostenickj/TressFX
9a9a1008fbcc9cc71a6b08331a75bed81c2119ac
[ "MIT" ]
null
null
null
amd_tressfx_sample/prebuilt/include/ObjectManager/include/SuObjectManager.h
kostenickj/TressFX
9a9a1008fbcc9cc71a6b08331a75bed81c2119ac
[ "MIT" ]
null
null
null
// // Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. // // 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 _SU_OBJECT_MANAGER_H_ #define _SU_OBJECT_MANAGER_H_ #include "SuCommon.h" #include "SuHashMap.h" #include "SuSearchPath.h" #include "SuEffectReloadListener.h" #include "SuUpdateHandlerFactory.h" #include "SuDefaultParticleBufferManager.h" /// \defgroup ObjectManager Object Manager class SuModelData; class SuModel; class SuCamera; class SuObject; class SuAnimatedModel; class SuAnimationSet; class SuParticleGroup; typedef SuCountedPtr<SuParticleGroup> SuParticleGroupPtr; typedef SuCountedPtr<SuAnimationSet> SuAnimationSetPtr; // tolua_begin /// \ingroup ObjectManager /// \brief This is the object manager class SuObjectManager : public SuUpdateHandlerFactory, public SuEffectReloadListener { public: /// Singleton access: reference static SU_DLL SuObjectManager& GetRef(); /// Singleton access: pointer static SU_DLL SuObjectManager* GetPtr(); /// Performs any one-time initialization work that is needed by the object manager SU_DLL void Initialize(); /// Destroy the object manager singleton, and all objects that it contains. static SU_DLL void ShutDown(); /// Method to find an object with a given name. SU_DLL SuObject* GetObjectByName( const SuString& rName ); /// Creates an animated model SU_DLL SuAnimatedModel* CreateAnimatedModel( const SuString& rObjectName, const SuString& rArchiveFile, const SuString& rAnimationFile ); /// Creates a particle group SU_DLL SuParticleGroup* CreateParticleGroup( const SuString& rGroupName, const SuString& rGroupArchive, const SuString& rAnimationFile, SuParticleBufferManager* pBufferMgr = &SuObjectManager::ms_defaultParticleBufferMgr ); /// Adds a directory to the object file search path SU_DLL void AddSearchPath( const SuString& rSearchPath ); /// Re-loads objects SU_DLL void ReloadObjects( bool bForce ); /// Signals the object manager to begin tracking all objects that are drawn SU_DLL void StartDrawTracking(); /// Signals the object manager to stop tracking objects, and to print a list of drawn objects SU_DLL SuString EndDrawTracking(); /// Performs GPU cache warming for all loaded objects SU_DLL void WarmGPUCaches(); // TODO: Object reloading support for plugin objects /// Registers an object that was created by a sushi plugin, and transfers ownership to the object manager SU_DLL bool RegisterPluginObject( SuObject* pObject ); // Don't expose this to the script // tolua_end /// Method to access the app update handler for the object manager SU_DLL SuCountedPtr<SuUpdateHandler> GetUpdateHandler( const SuString& rAnnotationName, SuEffectParameter::DataType eType, uint32 nArraySize, const SuAnnotationMap* pAnnotations ); /// Notifies the OM that an object is being drawn. SU_DLL void SetObjectBeingDrawn( SuObject* pObject ); /// Returns the object that is currently being drawn. This method is required for use by app-update handlers inline SuObject* GetObjectBeingDrawn() const { return m_pDrawingObject; }; // implementation of the SuEffectReloadListener interface /// Called in the event of an effect reload virtual void OnEffectReload( SuEffectPtr pOldEffect, SuEffectPtr pNewEffect ); /// Looks up a path in the object manager's search path SU_DLL bool LookupObjectPath( const SuString& rPath, SuString* pFullPathOut ); // WARNING: This *should* be private, but then poor tolua gets confused when creating the bindings, so it's public instead. // Don't get any stupid ideas just because of that... static SU_DLL SuDefaultParticleBufferManager ms_defaultParticleBufferMgr; private: /// Constructor. It is private to restrict instantiation to the singleton access methods. SuObjectManager(); /// Destructor. It is private to restrict destruction to the ShutDown method. ~SuObjectManager(); /// Constructs a model object from an archive file. SuModel* CreateModel( const SuString& rArchiveFileName ); /// Construct an animation set from an archive file. SuAnimationSetPtr CreateAnimationSet( const SuString& rArchiveFileName ); /// Constructs an update handler for a particular app-update type SuUpdateHandlerPtr CreateUpdateHandler( const SuString& rAppUpdateName ); /// A mapping of object names to objects typedef SuHashMap< SuString, SuObject*, SuStringHasher, SuHashComparer<SuString> > ObjectMap; ObjectMap m_objects; /// A hashmap identifying the objects in m_objects which are SuAnimatedModels. These get some special treatment typedef SuHashMap< SuObject*, SuAnimatedModel*, SuPointerHasher<SuObject>, SuHashComparer<SuObject*> > AnimatedModelMap; AnimatedModelMap m_animatedModels; struct SuModelInfo { SuModel* pModel; time_t nTimeStamp; }; /// A mapping of model archive names to loaded model objects typedef SuHashMap< SuString, SuModelInfo, SuStringHasher, SuHashComparer<SuString> > ModelMap; ModelMap m_models; /// A struct which holds information about each animation set that the object manager owns struct SuAnimationSetInfo { SuAnimationSetPtr pSet; time_t nTimeStamp; }; /// A mapping of animation set file names to loaded animation sets typedef SuHashMap< SuString, SuAnimationSetInfo, SuStringHasher, SuHashComparer<SuString> > AnimationSetMap; AnimationSetMap m_animationSets; struct SuParticleGroupInfo { SuParticleGroup* pParticleGroup; SuString fullPath; ///< Full path of particle file from whence this group came SuAnimationSetPtr pAnimations; ///< The animation set from which this group pulled its animations. Needed for re-loading to work time_t nTimeStamp; }; /// A mapping of particle group archive names to loaded particle groups typedef SuHashMap< SuString, SuParticleGroupInfo, SuStringHasher, SuHashComparer<SuString> > ParticleMap; ParticleMap m_particleGroups; /// Singleton instance static SuObjectManager* ms_pManager ; /// The object currently being drawn, used to facilitate app updates SuObject* m_pDrawingObject; typedef SuHashMap< SuString, SuUpdateHandlerPtr, SuStringHasher, SuHashComparer<SuString> > UpdateHandlerMap; UpdateHandlerMap m_updateHandlers; ///< Set of cached update handlers for various app-update types /// Search path for object files SuSearchPath m_searchPath; bool m_bTrackDraws; ///< Flag to tell whether or not to track object draws struct ObjectDrawStats { uint32 nDrawIndexed; ///< Total number of draw calls generated uint32 nDrawNonIndexed; ///< Total number of nonindexed draw calls generated uint32 nPoints; ///< Total number of point primitives generated uint32 nLines; ///< Total number of line primitives generated uint32 nTriangles; ///< Total number of triangle primitives generated uint32 nDrawIndexedPrev; ///< Value of draw call counter at the time object drawing began uint32 nDrawNonIndexedPrev;///< Value of draw call counter at the time object drawing began uint32 nPointsPrev; ///< Value of point counter at the time object drawing began uint32 nLinesPrev; ///< Value of point counter at the time object drawing began uint32 nTrianglesPrev; ///< Value of triangles counter at the time object drawing began }; /// Map of every object to its drawing statistics, used to implemented draw call tracking typedef SuHashMap< SuString, ObjectDrawStats, SuStringHasher, SuHashComparer<SuString> > ObjectDrawMap; ObjectDrawMap m_objectDrawMap; // tolua_begin }; //tolua_end #endif
40.955556
141
0.720998
[ "object", "model" ]
cb10fa45d30b02c53e97e25bd446b38685336266
1,191
h
C
Homeworks/2_ImageWarping/project/src/App/ImageWidget.h
Chengyu-Cui/USTC_CG
7320243d0826b7fee16d91ee26bbb1b371652b16
[ "MIT" ]
null
null
null
Homeworks/2_ImageWarping/project/src/App/ImageWidget.h
Chengyu-Cui/USTC_CG
7320243d0826b7fee16d91ee26bbb1b371652b16
[ "MIT" ]
null
null
null
Homeworks/2_ImageWarping/project/src/App/ImageWidget.h
Chengyu-Cui/USTC_CG
7320243d0826b7fee16d91ee26bbb1b371652b16
[ "MIT" ]
null
null
null
#pragma once #include <QWidget> #include<vector> #include"IDW.h" #include"RBF.h" QT_BEGIN_NAMESPACE class QImage; class QPainter; QT_END_NAMESPACE class ImageWidget : public QWidget { Q_OBJECT public: ImageWidget(void); ~ImageWidget(void); protected: void paintEvent(QPaintEvent *paintevent); public slots: // File IO void Open(); // Open an image file, support ".bmp, .png, .jpg" format void Save(); // Save image to current file void SaveAs(); // Save image to another file // Image processing void Invert(); // Invert pixel value in image void Mirror(bool horizontal=false, bool vertical=true); // Mirror image vertically or horizontally void TurnGray(); // Turn image to gray-scale map void Restore(); // Restore image to origin void mousePressEvent(QMouseEvent* event); void mouseReleaseEvent(QMouseEvent* event); void mouseMoveEvent(QMouseEvent* event); void start_RBF(); void start_IDW(); private: QImage* ptr_image_; // image QImage* ptr_image_backup_; std::vector<QPoint> origin_points_; std::vector<QPoint> target_points_; QPoint start_point_, end_point_; bool draw_status_; };
23.82
100
0.702771
[ "vector" ]
cb2d29e22f74c925907bd11417209f7644077f2b
2,605
h
C
xdl/test/data_io/op/feature_op/op_test_tool.h
Ru-Xiang/x-deeplearning
04cc0497150920c64b06bb8c314ef89977a3427a
[ "Apache-2.0" ]
4,071
2018-12-13T04:17:38.000Z
2022-03-30T03:29:35.000Z
xdl/test/data_io/op/feature_op/op_test_tool.h
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
359
2018-12-21T01:14:57.000Z
2022-02-15T07:18:02.000Z
xdl/test/data_io/op/feature_op/op_test_tool.h
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
1,054
2018-12-20T09:57:42.000Z
2022-03-29T07:16:53.000Z
/* Copyright (C) 2016-2018 Alibaba Group Holding Limited 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. ==============================================================================*/ #pragma once #include <stdlib.h> #include <string> #include <time.h> #include <vector> #include "xdl/data_io/op/feature_op/expr/expr_node.h" #include "xdl/proto/sample.pb.h" class OpTestTool { public: static int Rand(int range) { srand((unsigned) time(nullptr)); return rand() / (RAND_MAX / range); } static float Rand(float range) { srand((unsigned) time(nullptr)); return rand() / (RAND_MAX / range); } static void Rand(char str[], int size, int range) { str[--size] = 0; const char c = 'A' + Rand(range); for (int i = 0; i < size; ++i) { str[i] = c; } } static void Rand(std::string &str, int size_range, int range) { if (!str.empty()) str.clear(); int size = Rand(size_range); str.resize(size); for (int i = 0; i < size; ++i) { str[i] = 'A' + Rand(range); } } static double GetTime() { timespec ts; clock_gettime(CLOCK_REALTIME, &ts); return static_cast<double>(ts.tv_sec) + static_cast<double>(ts.tv_nsec) * 1e-9; } static void Transfer(const std::vector<const xdl::io::Feature *> &features, xdl::io::Feature &result_feature, std::vector<xdl::io::ExprNode> &nodes, std::vector<const xdl::io::ExprNode *> &source_nodes, xdl::io::ExprNode &result_node) { for (const xdl::io::Feature *feature : features) { xdl::io::ExprNode node; node.type = xdl::io::FeaOpType::kSourceFeatureOp; xdl::io::Feature *f = new xdl::io::Feature(); f->CopyFrom(*feature); node.result = f; node.InitInternal(); nodes.push_back(std::move(node)); } for (const xdl::io::ExprNode &node : nodes) { source_nodes.push_back(&node); } result_node.type = xdl::io::FeaOpType::kMultiFeatureOp; result_node.output = true; result_node.result = &result_feature; result_node.InitInternal(); } };
31.011905
83
0.618426
[ "vector" ]
cb2fd7ef78b3d9f5f27eaaff964bd9b39eef3c98
33,965
h
C
ObitSystem/Obit/include/ObitSDMDataTypeDef.h
sarrvesh/Obit
e4ce6029e9beb2a8c0316ee81ea710b66b2b7986
[ "Linux-OpenIB" ]
5
2019-08-26T06:53:08.000Z
2020-10-20T01:08:59.000Z
ObitSystem/Obit/include/ObitSDMDataTypeDef.h
sarrvesh/Obit
e4ce6029e9beb2a8c0316ee81ea710b66b2b7986
[ "Linux-OpenIB" ]
null
null
null
ObitSystem/Obit/include/ObitSDMDataTypeDef.h
sarrvesh/Obit
e4ce6029e9beb2a8c0316ee81ea710b66b2b7986
[ "Linux-OpenIB" ]
8
2017-08-29T15:12:32.000Z
2022-03-31T12:16:08.000Z
/* $Id$ */ /*--------------------------------------------------------------------*/ /*; Copyright (C) 2010-2019 */ /*; Associated Universities, Inc. Washington DC, USA. */ /*; 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., 675 Massachusetts Ave, Cambridge, */ /*; MA 02139, USA. */ /*; */ /*;Correspondence about this software should be addressed as follows: */ /*; Internet email: bcotton@nrao.edu. */ /*; Postal address: William Cotton */ /*; National Radio Astronomy Observatory */ /*; 520 Edgemont Road */ /*; Charlottesville, VA 22903-2475 USA */ /*--------------------------------------------------------------------*/ /* Define the basic components of the ObitSDMData structure */ /* This is intended to be included in a class structure definition */ /* This class accesses data in the EVLA SDM format */ /* This file defines ASDM and BDF structures */ /** * \file ObitSDMDataTypeDef.h * ObitSDMData ASDM structures */ /* Structures interpreted from the ASDM */ /* SpectralWindow/Poln array */ typedef struct { /** Spectral window ID */ olong spectralWindowId; /** Selected? */ gboolean selected; /** Baseband number */ olong basebandNum; /** subband number */ olong subbandNum; /** Number of channels */ olong numChan; /** Number of cross poln */ olong nCPoln; /** Number of auto poln */ olong nAPoln; /** net Sideband */ gchar *netSideband; /** bandcode NULL = unknown */ gchar *bandcode; /** reference channel */ ofloat refChan; /** refFreq */ odouble refFreq; /** total Bandwidth (Hz) */ odouble totBandwidth; /** channel Frequency Start (Hz) */ odouble chanFreqStart; /** channel Freq Step (Hz) */ odouble chanFreqStep; /** channel Width (Hz) */ odouble chanWidth; /** effectiveBw */ odouble effectiveBw; /** spectral resolution in Hz */ odouble resolution; } ASDMSpectralWindowArrayEntry; typedef struct { /* Reference Frequency */ odouble refFreq; /* Reference JD */ odouble refJD; /** Number of rows */ olong nwinds; /** Band designation code */ ObitASDMBand band; /** 0-rel order number of Spectral windows in data */ olong *order; /** Array of ASDMSpectralWindowArray rows */ ASDMSpectralWindowArrayEntry **winds; } ASDMSpectralWindowArray; /* Antenna/station array */ typedef struct { /** Antenna ID */ olong antennaId; /** Antenna Number */ olong antennaNo; /** name */ gchar* antName; /** antenna Make enum */ ObitASDMAntennaMake antennaMake; /** antenna Type enum */ ObitASDMAntennaType antennaType; /** dish Diameter (m)*/ odouble dishDiameter; /** position array of doubles */ odouble *antPosition; /** offset array of doubles */ odouble *offset; /** time */ odouble time ; /** station Id */ olong stationId; /** Station name */ gchar *staName; /** position */ odouble *staPosition; /** Feed orientation */ ofloat receptorAngle[2]; /** type */ ObitASDMStationType type; /** Number of polarizations (1 or 2) */ olong numPoln; /** Number of polarization orrelations (1-4) */ olong numPolnCorr; /** Polarization types 'R', 'L', 'X', 'Y' */ gchar polnType[2]; } ASDMAntennaArrayEntry; typedef struct { /** Array Name */ gchar *arrayName; /** Observer Name */ gchar *obsName; /* Reference Frequency */ odouble refFreq; /* Reference JD */ odouble refJD; /** Number of rows */ olong nants; /** Highest antenna number */ olong maxAnt; /** Array of Antenna entries */ ASDMAntennaArrayEntry **ants; } ASDMAntennaArray; /** Source array */ typedef struct { /** source Id */ olong sourceId; /** field Id */ olong fieldId; /** source Number (1-rel) */ olong sourceNo; /** Is this a repeat entry of sourceNo? */ gboolean repeat;; /** source qualifier */ olong sourceQual; /** time Interval as JD */ odouble *timeInterval; /** cal code */ gchar *code; /** direction, array of RA, Dec in rad */ odouble *direction; /** proper Motion, array of RA, Dec in rad */ odouble *properMotion; /** source Name as defined in FieldTab */ gchar *fieldName; /** numLines */ olong numLines; /** rest Frequency, one per line */ odouble *restFrequency; /** systemic Velocity, one per line */ odouble *sysVel; /** spectral Window Id */ olong spectralWindowId; } ASDMSourceArrayEntry; typedef struct { /** Number of rows */ olong nsou; /** Array of Source entries */ ASDMSourceArrayEntry **sou; } ASDMSourceArray; /** EVLA ASDM Tables */ /* ASDM Table */ typedef struct { /** Schema version number */ olong schemaVersion; /** Number of Main rows */ olong MainRows; /** Number of Antenna rows */ olong AntennaRows; /** Number of calAtmosphere rows */ olong calAtmosphereRows; /** Number of calData rows */ olong calDataRows; /** Number of calDevice rows */ olong calDeviceRows; /** Number of calPointing rows */ olong calPointingRows; /** Number of CalReduction rows */ olong CalReductionRows; /** Number of CalWVR rows */ olong CalWVRRows; /** Number of ConfigDescription rows */ olong ConfigDescriptionRows; /** Number of CorrelatorMode rows */ olong CorrelatorModeRows; /** Number of DataDescription rows */ olong DataDescriptionRows; /** Number of Delay model fixed parameter rows */ olong DlyModFixRows; /** Number of Delay model variable parameter rows */ olong DlyModVarRows; /** Number of Doppler rows */ olong DopplerRows; /** Number of Ephemeris rows */ olong EphemerisRows; /** Number of ExecBlock rows */ olong ExecBlockRows; /** Number of Feed rows */ olong FeedRows; /** Number of Field rows */ olong FieldRows; /** Number of Flag rows */ olong FlagRows; /** Number of Pointing rows */ olong PointingRows; /** Number of PointingModel rows */ olong PointingModelRows; /** Number of Polarization rows */ olong PolarizationRows; /** Number of Processor rows */ olong ProcessorRows; /** Number of Receiver rows */ olong ReceiverRows; /** Number of SBSummary rows */ olong SBSummaryRows; /** Number of Scan rows */ olong ScanRows; /** Number of Source rows */ olong SourceRows; /** Number of SpectralWindow rows */ olong SpectralWindowRows; /** Number of State rows */ olong StateRows; /** Number of Station rows */ olong StationRows; /** Number of Subscan rows */ olong SubscanRows; /** Number of SwitchCycle rows */ olong SwitchCycleRows; /** Number of SysCal rows */ olong SysCalRows; /** Number of SysPower rows */ olong SysPowerRows; /** Number of Weather rows */ olong WeatherRows; } ASDMTable; /* Main Table */ typedef struct { odouble time; /** Number of antennas */ olong numAntenna; /** Type of time sampling */ ObitSDMSampleType timeSampling; /** Time interval in days covered */ odouble interval; /** Number of integrations */ olong numIntegration; /** Scan number */ olong scanNumber; /** Subscan number */ olong subscanNumber; /** Number of bytes in the BDF data file 64 bits */ ollong dataSize; /** Name of associated BDF data file (replaced slash with underscore) */ gchar *entityId; /** Is all data with this row flagged? */ gboolean flagRow; /** Configuration description Identifier */ olong configDescriptionId; /** execution block identifier */ olong execBlockId; /** field identifier */ olong fieldId; /** State identifier */ olong *stateId; } ASDMMainRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMMain rows */ ASDMMainRow **rows; } ASDMMainTable; /* Antenna Table */ typedef struct { /** Antenna ID */ olong antennaId; /** Antenna ID */ olong antennaNo; /** name */ gchar* name; /** antenna Make enum */ ObitASDMAntennaMake antennaMake; /** antenna Type enum */ ObitASDMAntennaType antennaType; /** dish Diameter (m)*/ odouble dishDiameter; /** position array of doubles */ odouble *position; /** offset array of doubles */ odouble *offset; /** time */ odouble time ; /** station Id */ olong stationId; } ASDMAntennaRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMAntenna rows */ ASDMAntennaRow **rows; } ASDMAntennaTable; /* ALMA CalAtmosphere Table, ignore spectra for now */ typedef struct { /** receiverBand */ olong receiverBand; /** antenna name */ gchar *antennaName; /** syscalType */ gchar *syscalType; /** baseband Id */ olong basebandId; /** number of frequencies */ olong numFreq; /** number of Loads */ olong numLoad; /** number of Receptors */ olong numReceptor; /** calData Id */ olong calDataId ; /** cal reduction Id */ olong calReductionId ; /** polarization types (1D array of poln enums) */ olong *polarizationTypes; /** start time (days) */ odouble startValidTime; /** end time (days) */ odouble endValidTime; /** Ground pressure */ odouble groundPressure; /** Ground relative humidity */ odouble groundRelHumidity; /** Ground temperature (K) */ odouble groundTemperature; /** Frequency range (Hz) */ odouble *frequencyRange; /** Atm. temp per receptor */ odouble *tAtm; /** Receiver temp. per receptor */ odouble *tRec ; /** System temp. at top of atmosphere per receptor */ odouble *tSys; /** Opacity per receptor */ odouble *tau; /** Water per receptor */ odouble *water; /** Error in water, per receptor */ odouble *waterError; /** forward efficiency, per receptor */ odouble *forwardEfficiency; /** sb(?) gain, per receptor */ odouble *sbGain; } ASDMcalAtmosphereRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMCalAtmosphere rows */ ASDMcalAtmosphereRow **rows; } ASDMcalAtmosphereTable; /* calData Table */ typedef struct { /** place holder */ olong holder; } ASDMcalDataRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMcalData rows */ ASDMcalDataRow **rows; } ASDMcalDataTable; /* calDevice Table */ typedef struct { /** antenna Id */ olong antennaId; /** spectral Window Id */ olong spectralWindowId; /** feedId */ olong feedId; /** number of Cal loads (N_cal) */ olong numCalLoad; /** number of Receptors (N_rec) */ olong numReceptor; /** Names of calibration devices (1D array of strings per cal device) */ gchar **calLoadNames; /** time Interval (days) */ odouble *timeInterval; /** Calibration efficiencies (2D array of double [N_rec][N_cal]) */ odouble *calEff; /** equivalent temp of noise cal (1D array of double, one per load) obsolete */ odouble *noiseCal; /** equivalent temp of noise cal (1D array of double, one per poln (R, L)) */ odouble *coupledNoiseCal; /** Physical temperature of loads (1D array of double, one per load) */ odouble *temperatureLoad; } ASDMcalDeviceRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMcalData rows */ ASDMcalDeviceRow **rows; } ASDMcalDeviceTable; /* calPointing Table */ typedef struct { /** place holder */ olong holder; } ASDMcalPointingRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMcalPointing rows */ ASDMcalPointingRow **rows; } ASDMcalPointingTable; /* CalReduction Table */ typedef struct { /** place holder */ olong holder; } ASDMCalReductionRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMCalReduction rows */ ASDMCalReductionRow **rows; } ASDMCalReductionTable; /* CalWVR Table */ typedef struct { /** start Time JD*/ odouble startValidTime; /** end Time JD */ odouble endValidTime; /** wvr method */ gchar *wvrMethod; /** antenna Name */ gchar *antennaName; /** numChan */ olong numChan; /** Arrays of info - dim numChan channel frequency array */ odouble *chanFreq; /* channel width array */ odouble *chanWidth; /* channel temperatures */ odouble *refTemp; /** number of Polynomials */ olong numPoly; /* path coefficients */ odouble *pathCoeff; /* polyFreqLimits */ odouble *polyFreqLimits; /* wet Path */ odouble wetPath; /* dry Path */ odouble dryPath; /* water */ odouble water; } ASDMCalWVRRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMCalWVR rows */ ASDMCalWVRRow **rows; } ASDMCalWVRTable; /* ConfigDescription Table */ typedef struct { /** Number of antennas */ olong numAntenna; /** Number of Data Descriptions */ olong numDataDescription; /** Number of feeds */ olong numFeed; /** correlation Mode */ ObitASDMCorrMode correlationMode; /** config Description Id */ olong configDescriptionId; /** number of Atm Phase Correction */ olong numAtmPhaseCorrection; /** Atm Phase Correction type enum array */ ObitASDMAtmPhCorr *atmPhaseCorrection; /** processor Type enum */ ObitASDMProcrType processorType; /** spectral Type enum */ ObitASDMSpecRes spectralType; /** antenna Ids in configuration array */ olong *antennaId; /** data Description Id array */ olong *dataDescriptionId; /** feed Id array */ olong *feedId; /** processor Id */ olong processorId; /** switch Cycle Id */ olong *switchCycleId; } ASDMConfigDescriptionRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMConfigDescription rows */ ASDMConfigDescriptionRow **rows; } ASDMConfigDescriptionTable; /* CorrelatorMode Table */ typedef struct { /** correlator Mode Id */ olong correlatorModeId; /** number of Basebands */ olong numBaseband; /** baseband Name enums, per baseband */ ObitASDMBasebandName *basebandNames; /** baseband Config array, per baseband*/ olong *basebandConfig; /** accumMode enum*/ ObitASDMAccumMode accumMode; /** bin Mode */ olong binMode; /** number of Axes */ olong numAxes; /** axes Order Array */ ObitASDMAxisName *axesOrderArray; /** filterMode enum array per baseband */ ObitASDMFilterMode *filterMode; /** correlator Name */ gchar *correlatorName; } ASDMCorrelatorModeRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMCorrelatorMode rows */ ASDMCorrelatorModeRow **rows; } ASDMCorrelatorModeTable; /* DataDescription Table */ typedef struct { /** data Description Id */ olong dataDescriptionId; /** polarization Id */ olong polOrHoloId; /** spectra lWindow Id */ olong spectralWindowId; } ASDMDataDescriptionRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMDataDescription rows */ ASDMDataDescriptionRow **rows; } ASDMDataDescriptionTable; /* Doppler Table */ typedef struct { /** place holder */ olong holder; } ASDMDopplerRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMDoppler rows */ ASDMDopplerRow **rows; } ASDMDopplerTable; /* Delay model fixed parameters Table */ typedef struct { /** model Id */ olong delayModelFixedParametersId; /** execution block identifier */ olong execBlockId; /** version */ gchar *delayModelVersion; /** ephemeris Epoch (e.g. "J2000") */ gchar *ephemerisEpoch; /** delay model switches */ gchar *delayModelFlags; /** Gauss constant (near 1.990983675E-7) */ odouble gaussConstant; /** Newtonian constant (near 6.672E-11) */ odouble newtonianConstant; /** gravity acceleration in m/s^2 */ odouble gravity; /** ratio of equatorial to polar radii */ odouble earthFlattening; /** earth equatorial radius in m */ odouble earthRadius; /** moonEarthMassRatio */ odouble moonEarthMassRatio; /** earthTideLag */ odouble earthTideLag; /** earth gravitation constant */ odouble earthGM; /** moon gravitation constant */ odouble moonGM; /** sun gravitation constant */ odouble sunGM; /** earth global Love number H */ odouble loveNumberH; /** earth global Love number L */ odouble loveNumberL; /** precession Constant asec/s*/ odouble precessionConstant; /** light time for 1 AU in seconds */ odouble lightTime1AU; /** speed Of Light m/s */ odouble speedOfLight; } ASDMDlyModFixRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDM rows */ ASDMDlyModFixRow **rows; } ASDMDlyModFixTable; /* Delay model variable parameters Table */ typedef struct { /** model Id */ olong delayModelVariableParametersId; /** Fixed parameters Id */ olong delayModelFixedParametersId; /** time */ odouble time; /** UT1 - UTC in sec. */ odouble ut1_utc; /** IAT - UTC in sec */ odouble iat_utc; /** GST at UT=0 (radian) 0 => you figure it out */ odouble gstAtUt0; /** Earth rotation rate (rad/s) 0 => you figure it out */ odouble earthRotationRate; /** nutation in longitude in rad (optional) */ odouble nutationInLongitude; /** rate of nutation in longitude rad/s (optional) */ odouble nutationInLongitudeRate; /** nutation in obliquity in rad (optional) */ odouble nutationInObliquity; /** rate of nutation in obliquity rad/s (optional) */ odouble nutationInObliquityRate; /** X, Y polar offsets in arcsec */ odouble *polarOffsets; /** type of time differences: 'PREDICTED', 'PRELIMINARY', 'RAPID', 'FINAL' */ gchar *timeType; /** type of polar offsets: 'PREDICTED', 'PRELIMINARY', 'RAPID', 'FINAL' */ gchar *polarOffsetsType; } ASDMDlyModVarRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDM rows */ ASDMDlyModVarRow **rows; } ASDMDlyModVarTable; /* Ephemeris Table */ typedef struct { /** Ephemeris Id */ olong ephemerisId; /** number of Polynomial coefficients in dir */ olong numPolyDir; /** number of Polynomial coefficients in distance */ olong numPolyDist; /** number of Polynomial coefficients in radVel */ olong numPolyRadVel; /** Time origin JD of the polynomial expansion */ odouble timeOrigin; /** Equinox of positions */ odouble equinoxEquator; /** a triple of double precision values defining the observer location. */ odouble *observerLocation; /** time Interval as JD */ odouble *timeInterval; /** Ephermeris direction, numPolyDir pairs*/ odouble *dir; /** Ephermeris distance, numPolyDist elements */ odouble *distance; /** Ephermeris radial velocity, numPolyRadVel elements */ odouble *radVel; /** Origin of ephemeris information */ gchar *origin; } ASDMEphemerisRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMEphemeris rows */ ASDMEphemerisRow **rows; } ASDMEphemerisTable; /* ExecBlock Table */ typedef struct { /** exec Block Id */ olong execBlockId; /** start Time (JD) */ odouble startTime; /** end Time (JD) */ odouble endTime ; /** exec Block Number */ olong execBlockNum; /** array config Name */ gchar *configName; /** telescope Name */ gchar *telescopeName; /** observer Name */ gchar *observerName ; /** observing Log */ gchar **observingLog ; /** session Reference */ gchar *sessionReference; /** scheduler Mode */ gchar *schedulerMode ; /** Number of observing Log */ olong numObservingLog; /** baseline Range Min */ odouble baseRangeMin; /** baseline Range Max */ odouble baseRangeMax; /** baseline Rms Minor */ odouble baseRmsMinor; /** basline Rms Major */ odouble baseRmsMajor; /** baseline Pa */ odouble basePa; /** site Altitude (m) */ odouble siteAltitude; /** site Longitude (deg) */ odouble siteLongitude; /** site Latitude (deg) */ odouble siteLatitude; /** was scan aborted */ gboolean aborted; /** number of Antenna */ olong numAntenna; /** flag this Row */ gboolean flagRow; /** antenna Id array */ olong *antennaId; /** sbSummary Table ID */ olong sbSummaryId; /** scale Id */ olong ScaleId; } ASDMExecBlockRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMExecBlock rows */ ASDMExecBlockRow **rows; } ASDMExecBlockTable; /* Feed Table */ typedef struct { /** feedId */ olong feedId; /** time Interval (days) */ odouble *timeInterval; /** number of Receptors */ olong numReceptor; /** beam Offset (2D array of double) */ odouble *beamOffset; /** focus Reference (2D array of double) */ odouble *focusReference; /** polarizationTypes (1D array of poln enums) */ olong *polarizationTypes; /** pol Response (2D array of double)*/ odouble *polResponse; /** receptor Angle (1D array of double) */ odouble *receptorAngle; /** antenna Id */ olong antennaId; /** receiver Id (1D array of int) */ olong *receiverId; /** spectral Window Id */ olong spectralWindowId; } ASDMFeedRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMFeed rows */ ASDMFeedRow **rows; } ASDMFeedTable; /* Field Table */ typedef struct { /** field Id */ olong fieldId; /** Ephemeris Id - index in EphemerisTab -1=>no entry*/ olong ephemerisId; /** field qual (AIPSish) */ olong fieldQual; /** field Name */ gchar *fieldName; /** code */ gchar *code; /** number of Polynomials */ olong numPoly; /** delay tracking center (rad) possibly also derivatives */ odouble* delayDir; /** phase tracking center (rad) possibly also derivatives */ odouble *phaseDir; /** reference direction (rad) possibly also derivatives */ odouble *referenceDir; /** time (JD)*/ odouble time; /** source Id */ olong sourceId; /** source Number (1-rel) */ olong sourceNo; } ASDMFieldRow; typedef struct { /** Number of rows */ olong nrows; /** Max qual for curField */ olong maxQual; /** Array of ASDMField rows */ ASDMFieldRow **rows; /** current field name */ gchar *curField; } ASDMFieldTable; /* Flag Table */ typedef struct { /** flag Id */ olong flagId; /** number of antennas */ olong numAntenna; /** number of polarization types, 0=> all */ olong numPolarizationType; /** number of spectral windows, 0=> all */ olong numSpectralWindow; /** antenna Id array */ olong *antennaId; /** Polarization array 1=R, 2=L, 3=X, 4=Y , 0=unknown*/ olong *polarizationType; /** spectral window Id array */ olong *spectralWindowId; /** reason */ gchar *reason; /** start Time (JD) */ odouble startTime; /** end Time (JD) */ odouble endTime; } ASDMFlagRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMFlag rows */ ASDMFlagRow **rows; } ASDMFlagTable; /* Pointing Table */ typedef struct { /** time Interval (JD days) */ odouble *timeInterval; /** number of samples */ olong numSample; /** Encoder values - NOT SURE OF TYPE */ odouble *encoder; /** Was antenna in tracking mode */ gboolean pointingTracking; /** using Polynomials */ gboolean usePolynomials; /** Time origin JD of the polynomial expansion */ odouble timeOrigin; /** number of terms in the polynomial */ olong numTerm; /** SourceOffset Equinox */ odouble SourceEquinoxOffset; /** Commanded pointing direction */ odouble *pointingDirection; /** Direction of target */ odouble *target; /** Field mapping offsets */ odouble *offset; /** SourceOffset offsets */ odouble *SourceOffset; /** Sampled time interval */ odouble *SampledTimeInterval; /** Atmospheric Correction */ odouble *AtmosphericCorrection; /** over the top observing? */ gboolean OverTheTop; /** Source Reference Code Offset not sure what this is, apparently an integer */ olong SourceReferenceCodeOffset; /** antenna Id identifying row in Antenna table */ olong antennaId; /** pointing model Id */ olong PointingModelId; } ASDMPointingRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMPointing rows */ ASDMPointingRow **rows; } ASDMPointingTable; /* PointingModel Table */ typedef struct { /** place holder */ olong holder; } ASDMPointingModelRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMPointingModel rows */ ASDMPointingModelRow **rows; } ASDMPointingModelTable; /* Polarization Table */ typedef struct { /** polarization Id */ olong polarizationId; /** number of Correlations */ olong numCorr; /** correlation polarization Type (1D array of numCorr poln codes) */ gchar **corrType; /** corrProduct (2D array of numCorr x 2 poln codes, R, L, X, Y) */ gchar **corrProduct; /** flagRow */ gboolean flagRow; } ASDMPolarizationRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMPolarization rows */ ASDMPolarizationRow **rows; } ASDMPolarizationTable; /* Processor Table */ typedef struct { /** processor Id */ olong processorId; /** modeId */ olong modeId; /** processorType */ gchar *processorType; /** processorSubType */ gchar *processorSubType; } ASDMProcessorRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMProcessor rows */ ASDMProcessorRow **rows; } ASDMProcessorTable; /* Receiver Table */ typedef struct { /** receiver Id */ olong receiverId; /** spectralWindowId */ olong spectralWindowId; /** number of LOs */ olong numLO; /** time Interval (days) */ odouble *timeInterval; /** LO frequencies */ odouble *freqLO; /** LO sidebands */ gchar **sidebandLO; /** receiver name */ gchar *name; /** receiver sideband */ gchar *receiverSideband; /** receiver band code name */ gchar *frequencyBand; } ASDMReceiverRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMReceiver rows */ ASDMReceiverRow **rows; } ASDMReceiverTable; /* SBSummary Table */ typedef struct { /** place holder */ olong holder; } ASDMSBSummaryRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMSBSummary rows */ ASDMSBSummaryRow **rows; } ASDMSBSummaryTable; /* Scan Table */ typedef struct { /** scan Number */ olong scanNumber; /** start Time JD*/ odouble startTime; /** end Time JD */ odouble endTime; /** numIntent */ olong numIntent; /** numSubscan */ olong numSubscan; /** scan Intent array of strings */ gchar **scanIntent; /** cal Data Type string array, one per subscan[?] */ gchar **calDataType; /** calibration On Line? boolean array */ gboolean *calibrationOnLine; /** source Name */ gchar *sourceName; /** Row flagged */ gboolean flagRow; /** execBlockId */ olong execBlockId; } ASDMScanRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMScan rows */ ASDMScanRow **rows; } ASDMScanTable; /* Source Table */ typedef struct { /** source Id */ olong sourceId; /** source Number (1-rel) */ olong sourceNo; /** time Interval as JD */ odouble *timeInterval; /** code */ gchar *code; /** direction, array of RA, Dec in rad */ odouble *direction; /** proper Motion, array of RA, Dec in rad */ odouble *properMotion; /** sourceName */ gchar *sourceName; /** numLines */ olong numLines; /** rest Frequency, one per line */ odouble *restFrequency; /** systemic Velocity, one per line */ odouble *sysVel; /** spectral Window Id */ olong spectralWindowId; } ASDMSourceRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMSource rows */ ASDMSourceRow **rows; } ASDMSourceTable; /* SpectralWindow Table */ typedef struct { /** spectralWindowId */ olong spectralWindowId; /** basebandName */ gchar *basebandName; /** bandcode NULL = unknown */ gchar *bandcode; /** net Sideband */ gchar *netSideband; /** numChan */ olong numChan; /** numPoln */ olong numPoln; /** refFreq */ odouble refFreq; /** sideband Processing Mode enum */ ObitASDMSideBMode sidebandProcessingMode; /** total Bandwidth (Hz) */ odouble totBandwidth; /** window Function enumeration */ ObitASDMWindowFn windowFunction; /** channel Frequency Start (Hz) */ odouble chanFreqStart; /** channel Freq Step (Hz) */ odouble chanFreqStep; /** channel Width (Hz) */ odouble chanWidth; /** correlationBit */ gchar *correlationBit; /** effectiveBw */ odouble effectiveBw; /** name */ gchar *name; /** oversampling? */ gboolean oversampling ; /** quantization[?] */ gboolean quantization; /** spectral resolution in Hz */ odouble resolution; /** Arrays of info - dim numChan channel frequency array */ odouble *chanFreqArray; /* channel width array */ odouble *chanWidthArray; /* effective bandwidth array */ odouble *effectiveBwArray; /* resolution array */ odouble *resolutionArray; /** Number of associated values */ olong numAssocValues; /** Nature of associated values (ObitASDMSpecRes as olong) */ olong *SpecRes; /** Associated Spectral window IDs */ olong *assocSpectralWindowId; } ASDMSpectralWindowRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMSpectralWindow rows */ ASDMSpectralWindowRow **rows; } ASDMSpectralWindowTable; /* State Table */ typedef struct { /** stateId */ olong stateId; /** calibration Device Name */ gchar *calDeviceName; /** Looking at sky? */ gboolean sig; /** Looking at reference? */ gboolean ref; /** On sky? */ gboolean onSky; } ASDMStateRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMState rows */ ASDMStateRow **rows; } ASDMStateTable; /* Station Table */ typedef struct { /** station Id */ olong stationId; /** name */ gchar *name; /** position */ odouble *position; /** type */ ObitASDMStationType type; } ASDMStationRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMStation rows */ ASDMStationRow **rows; } ASDMStationTable; /* Subscan Table */ typedef struct { /** scanNumber */ olong scanNumber; /** subscanNumber */ olong subscanNumber; /** start Time JD */ odouble startTime; /** end Time JD */ odouble endTime; /** fieldName */ gchar *fieldName; /** subscanIntent */ gchar *subscanIntent; /** number of Integrations */ olong numberIntegration; /** numberSubintegration 1 per integration */ olong *numberSubintegration; /** flagRow */ gboolean flagRow; /** execBlockId */ olong execBlockId; } ASDMSubscanRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMSubscan rows */ ASDMSubscanRow **rows; } ASDMSubscanTable; /* SwitchCycle Table */ typedef struct { /** switch Cycle Id */ olong switchCycleId; /** number of steps Step */ olong numStep; /** weight Array */ odouble *weightArray; /** dir Offset Array */ odouble *dirOffsetArray; /** freq Offset Array */ odouble *freqOffsetArray; /** step Duration Array */ odouble *stepDurationArray; } ASDMSwitchCycleRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMSwitchCycle rows */ ASDMSwitchCycleRow **rows; } ASDMSwitchCycleTable; /* Weather Table */ typedef struct { /** time Interval (days) */ odouble *timeInterval; /** atmospheric pressure (Pascal), fblank = invalid */ ofloat pressure; /** relative humidity, fblank = invalid */ ofloat relHumidity; /** temperature(K), fblank = invalid */ ofloat temperature ; /** wind direction, Azimuth?, radians?, fblank = invalid */ ofloat windDirection ; /** wind speed (m/s), fblank = invalid */ ofloat windSpeed; /** wind max - max gust(?) (m/s), fblank = invalid */ ofloat windMax; /** dew point (K), fblank = invalid */ ofloat dewPoint; /** station Id */ olong stationId; } ASDMWeatherRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMWeather rows */ ASDMWeatherRow **rows; } ASDMWeatherTable; /* SysCal Table */ typedef struct { /** place holder */ olong holder; } ASDMSysCalRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMSysCal rows */ ASDMSysCalRow **rows; } ASDMSysCalTable; /* SysPower Table */ typedef struct { /** antenna Id */ olong antennaId; /** spectral Window Id */ olong spectralWindowId; /** feedId */ olong feedId; /** number of Receptors */ olong numReceptor; /** time Interval (days) */ odouble *timeInterval; /** switched Power Difference (1D array of double) */ ofloat *switchedPowerDifference; /** switched Power Sum (1D array of double) */ ofloat *switchedPowerSum; /** Requantizer gain Sum (1D array of double) */ ofloat *requantizerGain; } ASDMSysPowerRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMSysPower rows */ ASDMSysPowerRow **rows; } ASDMSysPowerTable; /* XXXX Table */ typedef struct { /** place holder */ olong holder; } ASDMXXXXRow; typedef struct { /** Number of rows */ olong nrows; /** Array of ASDMXXXX rows */ ASDMXXXXRow **rows; } ASDMXXXXTable;
26.106841
82
0.651995
[ "model" ]
cb369109ad9cc21d55dbe29f5433fce579916858
805
h
C
Cala/src/Core/Utility/IterableVector.h
dominikcondric/Cala
1393d5266b2d7e709a3a7aa0abcc7c0d86a4a810
[ "Apache-2.0" ]
null
null
null
Cala/src/Core/Utility/IterableVector.h
dominikcondric/Cala
1393d5266b2d7e709a3a7aa0abcc7c0d86a4a810
[ "Apache-2.0" ]
null
null
null
Cala/src/Core/Utility/IterableVector.h
dominikcondric/Cala
1393d5266b2d7e709a3a7aa0abcc7c0d86a4a810
[ "Apache-2.0" ]
null
null
null
#pragma once #include <vector> #include <cassert> namespace Cala { template<typename T> class IterableVector { public: using Iterator = typename std::vector<T>::iterator; using ConstIterator = typename std::vector<T>::const_iterator; public: IterableVector(std::vector<T>& _vector) : vector(_vector) {} ~IterableVector() = default; const T& operator[](uint32_t index) const { assert(index < vector.size()); return vector[index]; } Iterator begin() const { return vector.begin(); } Iterator end() const { return vector.end(); } ConstIterator cbegin() const { return vector.cbegin(); } ConstIterator cend() const { return vector.cend(); } size_t getSize() const { return vector.size(); } private: std::vector<T>& vector; }; }
16.1
64
0.652174
[ "vector" ]
cb4b2d8d125a7e2bd91e5433a2cc61775f20df0e
1,335
h
C
sourcecode/Runtime/Manifest.h
fabianmuehlboeck/monnom
609b307d9fa9e6641443f34dbcc0b035b34d3044
[ "BSD-3-Clause", "MIT" ]
2
2021-11-16T20:58:02.000Z
2021-12-05T18:15:41.000Z
sourcecode/Runtime/Manifest.h
fabianmuehlboeck/monnom
609b307d9fa9e6641443f34dbcc0b035b34d3044
[ "BSD-3-Clause", "MIT" ]
null
null
null
sourcecode/Runtime/Manifest.h
fabianmuehlboeck/monnom
609b307d9fa9e6641443f34dbcc0b035b34d3044
[ "BSD-3-Clause", "MIT" ]
null
null
null
#pragma once #include "VersionNumber.h" #include <string> #include <vector> #include "LibraryDependency.h" namespace Nom { namespace Runtime { struct ClassEntry { const std::string Name; const std::string FileName; ClassEntry(std::string&& name, std::string&& fileName) : Name(name), FileName(fileName) { } }; struct InterfaceEntry { const std::string Name; const std::string FileName; InterfaceEntry(std::string&& name, std::string&& fileName) : Name(name), FileName(fileName) { } }; class Manifest { private: std::string mainClassName; public: const std::string Name; const VersionNumber Version; const VersionNumber CompatibleFrom; const VersionNumber CompatibleTo; const bool IsSecurityRisk; const bool IsDeprecated; std::vector<LibraryDependency> Dependencies; std::vector<ClassEntry> Classes; std::vector<InterfaceEntry> Interfaces; Manifest(std::string name, VersionNumber version, VersionNumber compatibleFrom, VersionNumber compatibleTo, bool isSecurityRisk, bool isDeprecated); ~Manifest(); void SetMainClass(std::string&& mainClassName) { this->mainClassName = mainClassName; } bool HasMainClass() { return mainClassName.length() > 0; } const std::string &MainClassName() { return mainClassName; } }; } }
23.421053
151
0.706367
[ "vector" ]
cb4ea2a2d4f22dd2740fde1ba642c169d4d392cc
5,571
h
C
3fd/rpc/rpc_impl_util.h
faburaya/3fd
2fa0b57b9702902178c878fe3d317d55ec4cdc95
[ "MS-PL" ]
23
2017-04-23T08:32:55.000Z
2022-02-21T00:13:29.000Z
3fd/rpc/rpc_impl_util.h
faburaya/3fd
2fa0b57b9702902178c878fe3d317d55ec4cdc95
[ "MS-PL" ]
3
2018-10-16T23:02:50.000Z
2021-11-17T19:43:21.000Z
3fd/rpc/rpc_impl_util.h
faburaya/3fd
2fa0b57b9702902178c878fe3d317d55ec4cdc95
[ "MS-PL" ]
4
2018-08-01T13:24:41.000Z
2021-06-11T20:59:52.000Z
#ifndef RPC_IMPL_UTIL_H // header guard #define RPC_IMPL_UTIL_H #include "rpc_helpers.h" #include <memory> #include <string> #include <NtDsAPI.h> #include <schannel.h> #include <wincrypt.h> namespace _3fd { using std::string; namespace rpc { void ThrowIfError(RPC_STATUS status, const char *message); void ThrowIfError(RPC_STATUS status, const char *message, const string &details); void LogIfError(RPC_STATUS status, const char *message, core::Logger::Priority prio) noexcept; void LogIfError(RPC_STATUS status, const char *message, const string &details, core::Logger::Priority prio) noexcept; const char *ToString(ProtocolSequence protSeq); const char *ToString(AuthenticationLevel authnLevel); const char *ToString(ImpersonationLevel impersonationLevel); const char *ConvertAuthnSvcOptToString(unsigned long authnService); void AppendSecQosOptsDescription(const RPC_SECURITY_QOS &secQOS, std::ostringstream &oss); /// <summary> /// RAII for RPC lib C-style strings. /// </summary> struct RpcString { RPC_WSTR data; RpcString() : data(nullptr) {} ~RpcString() { if (data != nullptr) { CALL_STACK_TRACE; LogIfError( RpcStringFreeW(&data), "Failed to release resources of string generated by RPC library", core::Logger::PRIO_CRITICAL ); } } }; typedef std::pair<uint32_t, const char*> RpcCodeLabelKVPair; /// <summary> /// Gathers resources and code to assemble exceptions with /// highly detailed information regarding RPC errors. /// </summary> class RpcErrorHelper { private: static const std::array<const char *, 11> componentMap; static const RpcCodeLabelKVPair detectionLocationMap[]; static const char *GetComponentLabel(uint32_t code); static const char *GetDetectionLocationLabel(uint32_t code); public: static core::AppException<std::runtime_error> CreateException(RPC_STATUS errCode, const string &message, const string &details); }; const unsigned long UUID_VECTOR_MAX_SIZE(32); /// <summary> /// This is an improvised fix for UUID_VECTOR, /// that seems to be wrongly defined in RPC API. /// </summary> struct UuidVectorFix { unsigned long size; UUID *data[UUID_VECTOR_MAX_SIZE]; }; /// <summary> /// Simple wrapper for a vector of <see cref="UUID"/> structs. /// It uses RAII to guarantee deallocation upon scope end, /// not having to resort to smart pointers. /// </summary> class VectorOfUuids { private: std::vector<UUID *> m_ptrs2Uuids; public: VectorOfUuids() {} VectorOfUuids(VectorOfUuids &&ob) noexcept : m_ptrs2Uuids(std::move(ob.m_ptrs2Uuids)) {} VectorOfUuids &operator =(VectorOfUuids &&ob) noexcept { if (&ob != this) m_ptrs2Uuids = std::move(ob.m_ptrs2Uuids); return *this; } ~VectorOfUuids(); size_t Size() const { return m_ptrs2Uuids.size(); } void Add(const UUID &uuid); UUID_VECTOR *CopyTo(UuidVectorFix &vec) noexcept; }; /// <summary> /// RAII for Directory Service binding handle. /// </summary> struct DirSvcBinding { HANDLE handle; DirSvcBinding() : handle(nullptr) {} ~DirSvcBinding() { if (handle != nullptr) DsUnBindW(&handle); } }; /// <summary> /// RAII for array of SPN's. /// </summary> struct ArrayOfSpn { DWORD size; LPWSTR *data; ArrayOfSpn() : size(0), data(nullptr) {} ~ArrayOfSpn() { if (data != nullptr) DsFreeSpnArrayW(size, data); } }; bool DetectActiveDirectoryServices(DirSvcBinding &dirSvcBinding, bool isClient); /// <summary> /// Provides access to the system certificate store. /// </summary> class SystemCertificateStore { private: HCERTSTORE m_certStoreHandle; public: SystemCertificateStore(DWORD registryLocation, const string &storeName); SystemCertificateStore(const SystemCertificateStore &) = delete; ~SystemCertificateStore(); PCCERT_CONTEXT FindCertBySubject(const string &certSubject) const; }; /// <summary> /// Wraps a credential for secure channel SSP, containing a X.509 /// certificate from the store and using RAII to control reference /// count for the certificate /// </summary> class SChannelCredWrapper { private: SCHANNEL_CRED m_credStructure; public: SChannelCredWrapper( PCCERT_CONTEXT certCtxtHandle, bool strongerSec = false ); SChannelCredWrapper( HCERTSTORE certStoreHandle, PCCERT_CONTEXT certCtxtHandle, bool strongerSec = false ); ~SChannelCredWrapper(); SCHANNEL_CRED *GetCredential() { return &m_credStructure; } }; }// end of namespace rpc }// end of namespace _3fd #endif // end of header guard
23.2125
94
0.588584
[ "vector" ]
cb5678591a826ad0ec6220aa0f95ae09b8285d44
566
h
C
Clowns' F8/Polarbear.h
cherry-glasses/Project-2-Game
9fcd27c4a0b56718be5fe6bc365299286cbf947b
[ "MIT" ]
1
2021-02-04T13:37:00.000Z
2021-02-04T13:37:00.000Z
Clowns' F8/Polarbear.h
cherry-glasses/Project-2-Game
9fcd27c4a0b56718be5fe6bc365299286cbf947b
[ "MIT" ]
23
2019-04-03T08:49:08.000Z
2019-05-25T14:04:44.000Z
Clowns' F8/Polarbear.h
cherry-glasses/Clowns-F8
9fcd27c4a0b56718be5fe6bc365299286cbf947b
[ "MIT" ]
1
2019-02-25T22:49:46.000Z
2019-02-25T22:49:46.000Z
#ifndef _Polarbear_H__ #define _Polarbear_H__ #include "Enemy.h" #include "Animation.h" class Polarbear : public Enemy { public: Polarbear(ENTITY_TYPE _type, pugi::xml_node _config, int _copy); // Destructor ~Polarbear(); //Move and Attack void SearchWalk(); void Walk(const std::vector<std::pair<int, int>> *_path); void SearchAttack(); void Attack(const std::vector<std::pair<int, int>> *_path); void SearchAbility_1(); void Ability_1(const std::vector<std::pair<int, int>> *_path); void CurrentMovement(MOVEMENT _movement); }; #endif // pawn
18.258065
65
0.717314
[ "vector" ]
cb58a59add24ea15aceff2066b8d2a9e96d2e353
3,042
h
C
include/Red/Threading/Thread.h
OutOfTheVoid/ProjectRed
801327283f5a302be130c90d593b39957c84cce5
[ "MIT" ]
1
2020-06-14T06:14:50.000Z
2020-06-14T06:14:50.000Z
include/Red/Threading/Thread.h
OutOfTheVoid/ProjectRed
801327283f5a302be130c90d593b39957c84cce5
[ "MIT" ]
null
null
null
include/Red/Threading/Thread.h
OutOfTheVoid/ProjectRed
801327283f5a302be130c90d593b39957c84cce5
[ "MIT" ]
null
null
null
#ifndef RED_THREADING_THREAD_H #define RED_THREADING_THREAD_H #include <Red/Threading/Threading.h> #include <Red/Threading/ThreadEvent.h> #include <Red/Util/Function.h> #include <Red/Events/IEventDispatcher.h> #include <Red/Events/EventDispatcher.h> #include <Red/Events/IEvent.h> #include <thread> #include <mutex> namespace Red { namespace Threading { class Thread : public Events :: IEventDispatcher { public: // Thread constructor takes an entry to the thread, IE the function to be called concurrently, and an optional name. // Note: holding a local to a Thread which is running will call Join () when it is destructed, so you don't want a local Thread in most cases. Thread ( Util :: IFunction <void> * Entry, const std :: string & Name = "Nameless" ); ~Thread (); // This is how to delete a dynamically allocated Thread object if you don't want to Join on delete. It works by leaving it up to the wrapper call around Entry to deallocate the thread object. You should drop your reference to the object after calling this. It WILL eventually deallocate storage, and therefore shouldn't be used on a local object. // Think of this: If you had a local to the object, it would be like writing "delete & LocalThread", something you should never try to do. void Delete (); // Start a thread. void Start (); // Is the thread running? bool IsRunning (); // Join with the thread. bool Join (); // Get the name supplied to the constructor. const std :: string & GetName (); // Get the keys for ThreadEvent :: kThreadEvent_Started and ThreadEvent :: kThreadEvent_Finished. EventKey HoldEventKey ( const std :: string & EventID ); EventKey FindHeldEventKey ( const std :: string & EventID ); // Noop. void RetireEventKey ( EventKey Key ); // Add or remove a listener to events with the keys for ThreadEvent :: kThreadEvent_Started and ThreadEvent :: kThreadEvent_Finished. void AddEventListener ( EventKey Target, Util :: IFunction1 <void, Events :: IEvent *> * Listener ); void RemoveEventListener ( EventKey Target, Util :: IFunction1 <void, Events :: IEvent *> * Listener ); // Add or remove events with the ID ThreadEvent :: kThreadEvent_Started and ThreadEvent :: kThreadEvent_Finished. void AddEventListener ( const std :: string & EventID, Util :: IFunction1 <void, Events :: IEvent *> * Listener ); void RemoveEventListener ( const std :: string & EventID, Util :: IFunction1 <void, Events :: IEvent *> * Listener ); private: inline void ThreadRun (); static void InternalThreadEntry ( Thread * ThreadPointer ); Util :: IFunction <void> * Entry; std :: thread * ThreadInstance; std :: mutex Lock; bool Running; Events :: EventDispatcher DispatcherInternal; std :: mutex EventLock; IEventDispatcher :: EventKey StartKey; IEventDispatcher :: EventKey FinishKey; const std :: string Name; bool SelfDelete; }; } } #endif
33.428571
349
0.694609
[ "object" ]
cb5bacafee44ae35af04b57f9267dc637468ad8a
2,893
h
C
lorgnette/sane_client_fake.h
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
null
null
null
lorgnette/sane_client_fake.h
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
null
null
null
lorgnette/sane_client_fake.h
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef LORGNETTE_SANE_CLIENT_FAKE_H_ #define LORGNETTE_SANE_CLIENT_FAKE_H_ #include <cstdint> #include <map> #include <memory> #include <string> #include <vector> #include <base/optional.h> #include <sane/sane.h> #include "lorgnette/sane_client.h" namespace lorgnette { class SaneDeviceFake; class SaneClientFake : public SaneClient { public: bool ListDevices(brillo::ErrorPtr* error, std::vector<ScannerInfo>* scanners_out) override; void SetListDevicesResult(bool value); void AddDevice(const std::string& name, const std::string& manufacturer, const std::string& model, const std::string& type); void RemoveDevice(const std::string& name); void SetDeviceForName(const std::string& device_name, std::unique_ptr<SaneDeviceFake> device); protected: std::unique_ptr<SaneDevice> ConnectToDeviceInternal( brillo::ErrorPtr* error, const std::string& device_name) override; private: std::map<std::string, std::unique_ptr<SaneDeviceFake>> devices_; bool list_devices_result_; std::vector<ScannerInfo> scanners_; }; class SaneDeviceFake : public SaneDevice { public: SaneDeviceFake(); ~SaneDeviceFake(); bool GetValidOptionValues(brillo::ErrorPtr* error, ValidOptionValues* values) override; bool SetScanResolution(brillo::ErrorPtr* error, int resolution) override; bool GetDocumentSource(brillo::ErrorPtr* error, DocumentSource* source_out) override; bool SetDocumentSource(brillo::ErrorPtr* error, const DocumentSource& source) override; bool SetColorMode(brillo::ErrorPtr* error, ColorMode color_mode) override; SANE_Status StartScan(brillo::ErrorPtr* error) override; bool GetScanParameters(brillo::ErrorPtr* error, ScanParameters* parameters) override; bool ReadScanData(brillo::ErrorPtr* error, uint8_t* buf, size_t count, size_t* read_out) override; void SetValidOptionValues(const base::Optional<ValidOptionValues>& values); void SetStartScanResult(SANE_Status status); void SetScanParameters(const base::Optional<ScanParameters>& params); void SetReadScanDataResult(bool result); void SetScanData(const std::vector<uint8_t>& scan_data); private: DocumentSource document_source_; base::Optional<ValidOptionValues> values_; SANE_Status start_scan_result_; bool read_scan_data_result_; bool scan_running_; base::Optional<ScanParameters> params_; std::vector<uint8_t> scan_data_; size_t scan_data_offset_; }; } // namespace lorgnette #endif // LORGNETTE_SANE_CLIENT_FAKE_H_
32.144444
77
0.712064
[ "vector", "model" ]
cb5e3833a81f3b51cdd3797ad7f458c0e0e71f1f
5,930
c
C
mex/include/sisl-4.5.0/src/s1011.c
sangyoonHan/extern
a3c874538a7262b895b60d3c4d493e5b34cf81f8
[ "BSD-2-Clause" ]
null
null
null
mex/include/sisl-4.5.0/src/s1011.c
sangyoonHan/extern
a3c874538a7262b895b60d3c4d493e5b34cf81f8
[ "BSD-2-Clause" ]
null
null
null
mex/include/sisl-4.5.0/src/s1011.c
sangyoonHan/extern
a3c874538a7262b895b60d3c4d493e5b34cf81f8
[ "BSD-2-Clause" ]
null
null
null
//=========================================================================== // SISL - SINTEF Spline Library, version 4.5.0. // Definition and interrogation of NURBS curves and surfaces. // // Copyright (C) 2000-2005, 2010 SINTEF ICT, Applied Mathematics, Norway. // // 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 version 2 of the License. // // 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. // // Contact information: E-mail: tor.dokken@sintef.no // SINTEF ICT, Department of Applied Mathematics, // P.O. Box 124 Blindern, // 0314 Oslo, Norway. // // Other licenses are also available for this software, notably licenses // for: // - Building commercial software. // - Building software whose source code you wish to keep private. //=========================================================================== #include "sisl-copyright.h" /* * * $Id: s1011.c,v 1.3 2001-03-19 15:58:40 afr Exp $ * */ #define S1011 #include "sislP.h" #if defined(SISLNEEDPROTOTYPES) void s1011(double start_pos[], double top_pos[], double end_pos[], double shape, int dim, SISLCurve **arc_seg, int *stat) #else void s1011(start_pos, top_pos, end_pos, shape, dim, arc_seg, stat) double start_pos[]; double top_pos[]; double end_pos[]; double shape; int dim; SISLCurve **arc_seg; int *stat; #endif /* ********************************************************************* * * PURPOSE : To describe a conic arc as a NURBS. The arc is given by * position at start, shoulder point and end, and a shape factor. * * * INPUT : start_pos - Start point of segment * top_pos - Shoulder point of segment. This is the intersection * point of the tangents in start_pos and end_pos * end_pos - End point of segment * shape - Shape factor >= 0 * shape < 0.5 a ellipse * shape = 0.5 a parabola * shape > 0.5 a hyperbola * shape >= 1 The start and end point lies on * different branches of the hyperbola. * We want a single arc segment, therefore * if shape>=1, shape is put to 0.999999. * dim - The dimension of the curve to be produced * * * * * OUTPUT : * stat - status messages * > 0 : warning * = 0 : ok * < 0 : error * arc_seg - Pointer to the curve produced * * METHOD : The conic is made as a rational B-spline curve according * to the following formula: * * p0 (1-t)(1-t) + 2 s/(1-s) t(1-t) pt + tt p1 * p(t) = ------------------------------------------- * (1-t)(1-t) + 2 s/(1-s) t(1-t) + tt * * where p0 is the start point, pt is the shoulder point, p1 is * the end point and s is the shape factor. * * * REFERENCES : * *- * CALLS : * * WRITTEN BY : Johannes Kaasa, SI, Oslo, Norway, Jan. 93 (Based on s1385, * written by Tor Dokken) * Revised by : Paal Fugelli, SINTEF, Oslo, Norway, Nov. 1994. Give error if * shape < zero. ********************************************************************* */ { int kpos = 0; /* Error position. */ int ki; /* Index in for loop. */ int in = 3; /* Number of coefficients. */ int ik = 3; /* Order of the curve. */ int rdim = dim + 1; /* Rational dimension. */ double et[6]; /* Knot vector. */ double rcoef[12]; /* Rational coefficients. */ int kind = 4; /* Rational Bezier curve. */ double weight; /* Rational weight. */ /* Make sure we get a single arc segment and positive weights. */ if ( shape >= (DOUBLE)1.0 ) shape = (DOUBLE)0.9999999; else if ( shape < (DOUBLE)0.0 ) goto err151; /* Make the data needed for curve generation. */ for ( ki=0; ki < ik; ki++ ) { et[ki] = DZERO; et[ik + ki] = (DOUBLE)1.0; } weight = shape/((DOUBLE)1.0 - shape); for ( ki=0; ki < dim; ki++ ) { rcoef[ki] = start_pos[ki]; rcoef[rdim + ki] = weight*top_pos[ki]; rcoef[2*rdim + ki] = end_pos[ki]; } rcoef[dim] = (DOUBLE)1.0; rcoef[dim + rdim] = weight; rcoef[dim + 2*rdim] = (DOUBLE)1.0; (*arc_seg) = newCurve(in, ik, et, rcoef, kind, dim, 1); if ((*arc_seg) == SISL_NULL) goto err101; *stat = 0; goto out; /* Error in curve allocation. */ err101: *stat = -101; s6err("s1011", *stat, kpos); goto out; /* Error in input parameters - shape is negative. */ err151: *stat = -151; s6err("s1011", *stat, kpos); goto out; out: return; }
33.693182
79
0.48398
[ "shape", "vector" ]
3b0c2387f0159daf102667cae67ab2900c068d54
347
h
C
Cron/Source/Store.h
matthin/gemtracker
f1a5a06d58acae0979aab34fca935eee1a67a2ed
[ "MIT" ]
null
null
null
Cron/Source/Store.h
matthin/gemtracker
f1a5a06d58acae0979aab34fca935eee1a67a2ed
[ "MIT" ]
null
null
null
Cron/Source/Store.h
matthin/gemtracker
f1a5a06d58acae0979aab34fca935eee1a67a2ed
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <string> #include <SQLiteCpp/Database.h> #include "Client.h" namespace GemTracker { class Store { public: Store(const std::vector<std::string> gems); private: const std::vector<std::string> gems; Client client; SQLite::Database db; void saveDailies(); }; } // namespace GemTracker
15.086957
47
0.685879
[ "vector" ]
3b10caf3d4a346b166ecac83aa0729748d7e2534
9,858
h
C
src/third_party/mozjs/extract/js/src/vm/SharedArrayObject.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/third_party/mozjs/extract/js/src/vm/SharedArrayObject.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/third_party/mozjs/extract/js/src/vm/SharedArrayObject.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim: set ts=8 sts=2 et sw=2 tw=80: * 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 vm_SharedArrayObject_h #define vm_SharedArrayObject_h #include "mozilla/Atomics.h" #include "jsapi.h" #include "jstypes.h" #include "gc/Barrier.h" #include "gc/Memory.h" #include "vm/ArrayBufferObject.h" #include "vm/JSObject.h" #include "wasm/WasmPages.h" namespace js { class FutexWaiter; /* * SharedArrayRawBuffer * * A bookkeeping object always stored immediately before the raw buffer. * The buffer itself is mmap()'d and refcounted. * SharedArrayBufferObjects and structured clone objects may hold references. * * |<------ sizeof ------>|<- length ->| * * | waste | SharedArrayRawBuffer | data array | waste | * * Observe that if we want to map the data array on a specific address, such * as absolute zero (bug 1056027), then the SharedArrayRawBuffer cannot be * prefixed to the data array, it has to be a separate object, also in * shared memory. (That would get rid of ~4KB of waste, as well.) Very little * else would have to change throughout the engine, the SARB would point to * the data array using a constant pointer, instead of computing its * address. * * If preparedForWasm_ is true then length_ can change following initialization; * it may grow toward maxSize_. See extensive comments above WasmArrayRawBuffer * in ArrayBufferObject.cpp. * * length_ only grows when the lock is held. */ class SharedArrayRawBuffer { private: mozilla::Atomic<uint32_t, mozilla::ReleaseAcquire> refcount_; mozilla::Atomic<size_t, mozilla::SequentiallyConsistent> length_; Mutex growLock_; // The maximum size of this buffer in wasm pages. If this buffer was not // prepared for wasm, then this is zero. wasm::Pages wasmMaxPages_; size_t mappedSize_; // Does not include the page for the header bool preparedForWasm_; // A list of structures representing tasks waiting on some // location within this buffer. FutexWaiter* waiters_; uint8_t* basePointer() { SharedMem<uint8_t*> p = dataPointerShared() - gc::SystemPageSize(); MOZ_ASSERT(p.asValue() % gc::SystemPageSize() == 0); return p.unwrap(/* we trust you won't abuse it */); } protected: SharedArrayRawBuffer(uint8_t* buffer, size_t length, wasm::Pages wasmMaxPages, size_t mappedSize, bool preparedForWasm) : refcount_(1), length_(length), growLock_(mutexid::SharedArrayGrow), wasmMaxPages_(wasmMaxPages), mappedSize_(mappedSize), preparedForWasm_(preparedForWasm), waiters_(nullptr) { MOZ_ASSERT(buffer == dataPointerShared()); } // Allocate a SharedArrayRawBuffer for either Wasm or other users. // `wasmMaxPages` must always be something for wasm and nothing for other // users. static SharedArrayRawBuffer* AllocateInternal( size_t length, const mozilla::Maybe<wasm::Pages>& wasmMaxPages, const mozilla::Maybe<size_t>& wasmMappedSize); public: class Lock; friend class Lock; class MOZ_STACK_CLASS Lock { SharedArrayRawBuffer* buf; public: explicit Lock(SharedArrayRawBuffer* buf) : buf(buf) { buf->growLock_.lock(); } ~Lock() { buf->growLock_.unlock(); } }; static SharedArrayRawBuffer* Allocate(size_t length); static SharedArrayRawBuffer* AllocateWasm( wasm::Pages initialPages, const mozilla::Maybe<wasm::Pages>& maxPages, const mozilla::Maybe<size_t>& mappedSize); // This may be called from multiple threads. The caller must take // care of mutual exclusion. FutexWaiter* waiters() const { return waiters_; } // This may be called from multiple threads. The caller must take // care of mutual exclusion. void setWaiters(FutexWaiter* waiters) { waiters_ = waiters; } SharedMem<uint8_t*> dataPointerShared() const { uint8_t* ptr = reinterpret_cast<uint8_t*>(const_cast<SharedArrayRawBuffer*>(this)); return SharedMem<uint8_t*>::shared(ptr + sizeof(SharedArrayRawBuffer)); } static const SharedArrayRawBuffer* fromDataPtr(const uint8_t* dataPtr) { return reinterpret_cast<const SharedArrayRawBuffer*>( dataPtr - sizeof(SharedArrayRawBuffer)); } size_t volatileByteLength() const { return length_; } wasm::Pages volatileWasmPages() const { return wasm::Pages::fromByteLengthExact(length_); } wasm::Pages wasmMaxPages() const { return wasmMaxPages_; } size_t mappedSize() const { return mappedSize_; } bool isWasm() const { return preparedForWasm_; } void tryGrowMaxPagesInPlace(wasm::Pages deltaMaxPages); bool wasmGrowToPagesInPlace(const Lock&, wasm::Pages newPages); uint32_t refcount() const { return refcount_; } [[nodiscard]] bool addReference(); void dropReference(); static int32_t liveBuffers(); }; /* * SharedArrayBufferObject * * When transferred to a WebWorker, the buffer is not detached on the * parent side, and both child and parent reference the same buffer. * * The underlying memory is memory-mapped and reference counted * (across workers and/or processes). The SharedArrayBuffer object * has a finalizer that decrements the refcount, the last one to leave * (globally) unmaps the memory. The sender ups the refcount before * transmitting the memory to another worker. * * SharedArrayBufferObject (or really the underlying memory) /is * racy/: more than one worker can access the memory at the same time. * * A TypedArrayObject (a view) references a SharedArrayBuffer * and keeps it alive. The SharedArrayBuffer does /not/ reference its * views. */ class SharedArrayBufferObject : public ArrayBufferObjectMaybeShared { static bool byteLengthGetterImpl(JSContext* cx, const CallArgs& args); public: // RAWBUF_SLOT holds a pointer (as "private" data) to the // SharedArrayRawBuffer object, which is manually managed storage. static const uint8_t RAWBUF_SLOT = 0; // LENGTH_SLOT holds the length of the underlying buffer as it was when this // object was created. For JS use cases this is the same length as the // buffer, but for Wasm the buffer can grow, and the buffer's length may be // greater than the object's length. static const uint8_t LENGTH_SLOT = 1; static_assert(LENGTH_SLOT == ArrayBufferObject::BYTE_LENGTH_SLOT, "JIT code assumes the same slot is used for the length"); static const uint8_t RESERVED_SLOTS = 2; static const JSClass class_; static const JSClass protoClass_; static bool byteLengthGetter(JSContext* cx, unsigned argc, Value* vp); static bool class_constructor(JSContext* cx, unsigned argc, Value* vp); static bool isOriginalByteLengthGetter(Native native) { return native == byteLengthGetter; } // Create a SharedArrayBufferObject with a new SharedArrayRawBuffer. static SharedArrayBufferObject* New(JSContext* cx, size_t length, HandleObject proto = nullptr); // Create a SharedArrayBufferObject using an existing SharedArrayRawBuffer, // recording the given length in the SharedArrayBufferObject. static SharedArrayBufferObject* New(JSContext* cx, SharedArrayRawBuffer* buffer, size_t length, HandleObject proto = nullptr); static void Finalize(JSFreeOp* fop, JSObject* obj); static void addSizeOfExcludingThis(JSObject* obj, mozilla::MallocSizeOf mallocSizeOf, JS::ClassInfo* info); static void copyData(Handle<SharedArrayBufferObject*> toBuffer, size_t toIndex, Handle<SharedArrayBufferObject*> fromBuffer, size_t fromIndex, size_t count); SharedArrayRawBuffer* rawBufferObject() const; // Invariant: This method does not cause GC and can be called // without anchoring the object it is called on. uintptr_t globalID() const { // The buffer address is good enough as an ID provided the memory is not // shared between processes or, if it is, it is mapped to the same address // in every process. (At the moment, shared memory cannot be shared between // processes.) return dataPointerShared().asValue(); } size_t byteLength() const { return size_t(getFixedSlot(LENGTH_SLOT).toPrivate()); } bool isWasm() const { return rawBufferObject()->isWasm(); } SharedMem<uint8_t*> dataPointerShared() const { return rawBufferObject()->dataPointerShared(); } // WebAssembly support: // Create a SharedArrayBufferObject using the provided buffer and size. // Assumes ownership of a reference to |buffer| even in case of failure, // i.e. on failure |buffer->dropReference()| is performed. static SharedArrayBufferObject* createFromNewRawBuffer( JSContext* cx, SharedArrayRawBuffer* buffer, size_t initialSize); wasm::Pages volatileWasmPages() const { return rawBufferObject()->volatileWasmPages(); } wasm::Pages wasmMaxPages() const { return rawBufferObject()->wasmMaxPages(); } size_t wasmMappedSize() const { return rawBufferObject()->mappedSize(); } private: [[nodiscard]] bool acceptRawBuffer(SharedArrayRawBuffer* buffer, size_t length); void dropRawBuffer(); }; using RootedSharedArrayBufferObject = Rooted<SharedArrayBufferObject*>; using HandleSharedArrayBufferObject = Handle<SharedArrayBufferObject*>; using MutableHandleSharedArrayBufferObject = MutableHandle<SharedArrayBufferObject*>; } // namespace js #endif // vm_SharedArrayObject_h
35.978102
80
0.709475
[ "object" ]
3b29c5242c210ba72b30ade1b4dabfdc3fd16221
4,449
c
C
src/pdf_parser.c
Masaiki/melon
8ee7132d0decd0ae1596f4ed8eaebe51a1d4b3b3
[ "Apache-2.0" ]
null
null
null
src/pdf_parser.c
Masaiki/melon
8ee7132d0decd0ae1596f4ed8eaebe51a1d4b3b3
[ "Apache-2.0" ]
null
null
null
src/pdf_parser.c
Masaiki/melon
8ee7132d0decd0ae1596f4ed8eaebe51a1d4b3b3
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020-2021, yzrh <yzrh@noema.org> * * SPDX-License-Identifier: Apache-2.0 */ #ifdef __linux__ #define _GNU_SOURCE #endif /* __linux__ */ #include <stdlib.h> #include <string.h> #include "pdf.h" static void * _memmem_whitespace(const void *p0, size_t s0, const void *p1, size_t s1) { const char whitespace[6] = { '\r', '\n', '\f', '\t', '\0', ' ' }; char tmp[s1 + 1]; memcpy(tmp, p1, s1); char *ret; for (int i = 0; i < 6; i++) { tmp[s1] = whitespace[i]; if((ret = memmem(p0, s0, tmp, s1 + 1)) != NULL) return ret; } return NULL; } static int _locate(pdf_object_t **pdf, FILE **fp, int size_buf) { pdf_object_t *ptr = *pdf; while (ptr->next != NULL) ptr = ptr->next; char buf[size_buf]; long cur = ftell(*fp); long end; fseek(*fp, 0, SEEK_END); end = ftell(*fp); fseek(*fp, cur, SEEK_SET); int head = 0; int tail = 0; char *pos; char *tmp; for (;;) { fread(buf, size_buf, 1, *fp); if (head == 0 && (pos = _memmem_whitespace(buf, size_buf, " 0 obj", 6)) != NULL) head = cur + (pos - buf) + 7; if (tail == 0 && (pos = _memmem_whitespace(buf, size_buf, "endobj", 6)) != NULL) { /* We need to check if it is the object stored in stream */ while (memcmp(pos + 7, "\r\nendstream", 11) == 0 && (tmp = _memmem_whitespace(pos + 6, size_buf - (pos - buf) - 6, "endobj", 6)) != NULL) pos = tmp; if (pos - buf < size_buf - 7) tail = cur + (pos - buf); } if (tail > head) { if (ptr->next == NULL) { ptr->next = malloc(sizeof(pdf_object_t)); if (ptr->next == NULL) return 1; ptr->next->id = 0; ptr->next->object_size = 0; ptr->next->object = NULL; ptr->next->dictionary_size = 0; ptr->next->dictionary = NULL; ptr->next->stream_size = 0; ptr->next->stream = NULL; ptr->next->next = NULL; ptr = ptr->next; } ptr->address = head; ptr->size = tail - head; fseek(*fp, tail + 6, SEEK_SET); head = tail = 0; } else { fseek(*fp, -6, SEEK_CUR); } if ((cur = ftell(*fp)) + 6 >= end) break; } return 0; } int pdf_load(pdf_object_t **pdf, FILE **fp, int size_buf) { if (*pdf == NULL || *fp == NULL || size_buf < 7) return 1; if (_locate(pdf, fp, size_buf) != 0) return 1; pdf_object_t *ptr = (*pdf)->next; char *buf; char *head; char *tail; char *tmp; while (ptr != NULL) { buf = malloc(ptr->size); if (buf == NULL) return 1; memset(buf, 0, ptr->size); fseek(*fp, ptr->address - 12, SEEK_SET); fread(buf, 8, 1, *fp); for (int i = 0; i < 8; i++) { if (buf[i] >= '0' && buf[i] <= '9') { ptr->id = atoi(buf + i); break; } } fseek(*fp, ptr->address, SEEK_SET); fread(buf, ptr->size, 1, *fp); if ((head = memmem(buf, ptr->size, "<<", 2)) != NULL && (tail = _memmem_whitespace(buf, ptr->size, ">>", 2)) != NULL) { /* * A dictionary object may have nested dictionary, * but it should not be in a stream */ while ((tmp = _memmem_whitespace(tail + 2, ptr->size - (tail - buf) - 2, ">>", 2)) != NULL && memmem(tail + 2, ptr->size - (tail - buf) - 2, "stream\r\n", 8) == NULL) tail = tmp; ptr->dictionary_size = tail - head + 2; ptr->dictionary = malloc(ptr->dictionary_size + 1); if (ptr->dictionary == NULL) return 1; memset(ptr->dictionary, 0, ptr->dictionary_size + 1); memcpy(ptr->dictionary, head, ptr->dictionary_size); if ((head = memmem(tail, ptr->size - (tail - buf), "stream\r\n", 8)) != NULL && (tail = _memmem_whitespace(head, ptr->size - (head - buf), "endstream", 9)) != NULL) { /* * An object may contain a stream that * contains another object that * contains another stream */ while (_memmem_whitespace(tail, ptr->size - (tail - buf), "endobj", 6) != NULL && (tmp = _memmem_whitespace(tail + 9, ptr->size - (tail - buf) - 9, "endstream", 9)) != NULL) tail = tmp; ptr->stream_size = (tail - head) - 8; ptr->stream = malloc(ptr->stream_size); if (ptr->stream == NULL) return 1; memcpy(ptr->stream, head + 8, ptr->stream_size); } } else { ptr->object_size = ptr->size; ptr->object = malloc(ptr->object_size + 1); if (ptr->object == NULL) return 1; memset(ptr->object, 0, ptr->object_size + 1); memcpy(ptr->object, buf, ptr->object_size); } free(buf); ptr = ptr->next; } return 0; }
19.950673
84
0.552708
[ "object" ]
3b2d9532786cedbb794b1a515fce19115e4280da
34,127
h
C
LavaSDK.framework/Headers/LavaSDK-Swift.h
sharathshenoy/testLava
4082ea9cebe8a719811bcd8b181ef6f6cd45f6e4
[ "MIT" ]
null
null
null
LavaSDK.framework/Headers/LavaSDK-Swift.h
sharathshenoy/testLava
4082ea9cebe8a719811bcd8b181ef6f6cd45f6e4
[ "MIT" ]
null
null
null
LavaSDK.framework/Headers/LavaSDK-Swift.h
sharathshenoy/testLava
4082ea9cebe8a719811bcd8b181ef6f6cd45f6e4
[ "MIT" ]
null
null
null
// Generated by Apple Swift version 2.2 (swiftlang-703.0.18.1 clang-703.0.29) #pragma clang diagnostic push #if defined(__has_include) && __has_include(<swift/objc-prologue.h>) # include <swift/objc-prologue.h> #endif #pragma clang diagnostic ignored "-Wauto-import" #include <objc/NSObject.h> #include <stdint.h> #include <stddef.h> #include <stdbool.h> #if !defined(SWIFT_TYPEDEFS) # define SWIFT_TYPEDEFS 1 # if defined(__has_include) && __has_include(<uchar.h>) # include <uchar.h> # elif !defined(__cplusplus) || __cplusplus < 201103L typedef uint_least16_t char16_t; typedef uint_least32_t char32_t; # endif typedef float swift_float2 __attribute__((__ext_vector_type__(2))); typedef float swift_float3 __attribute__((__ext_vector_type__(3))); typedef float swift_float4 __attribute__((__ext_vector_type__(4))); typedef double swift_double2 __attribute__((__ext_vector_type__(2))); typedef double swift_double3 __attribute__((__ext_vector_type__(3))); typedef double swift_double4 __attribute__((__ext_vector_type__(4))); typedef int swift_int2 __attribute__((__ext_vector_type__(2))); typedef int swift_int3 __attribute__((__ext_vector_type__(3))); typedef int swift_int4 __attribute__((__ext_vector_type__(4))); #endif #if !defined(SWIFT_PASTE) # define SWIFT_PASTE_HELPER(x, y) x##y # define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y) #endif #if !defined(SWIFT_METATYPE) # define SWIFT_METATYPE(X) Class #endif #if defined(__has_attribute) && __has_attribute(objc_runtime_name) # define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X))) #else # define SWIFT_RUNTIME_NAME(X) #endif #if defined(__has_attribute) && __has_attribute(swift_name) # define SWIFT_COMPILE_NAME(X) __attribute__((swift_name(X))) #else # define SWIFT_COMPILE_NAME(X) #endif #if !defined(SWIFT_CLASS_EXTRA) # define SWIFT_CLASS_EXTRA #endif #if !defined(SWIFT_PROTOCOL_EXTRA) # define SWIFT_PROTOCOL_EXTRA #endif #if !defined(SWIFT_ENUM_EXTRA) # define SWIFT_ENUM_EXTRA #endif #if !defined(SWIFT_CLASS) # if defined(__has_attribute) && __has_attribute(objc_subclassing_restricted) # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA # define SWIFT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # else # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # define SWIFT_CLASS_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # endif #endif #if !defined(SWIFT_PROTOCOL) # define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA # define SWIFT_PROTOCOL_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA #endif #if !defined(SWIFT_EXTENSION) # define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__) #endif #if !defined(OBJC_DESIGNATED_INITIALIZER) # if defined(__has_attribute) && __has_attribute(objc_designated_initializer) # define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) # else # define OBJC_DESIGNATED_INITIALIZER # endif #endif #if !defined(SWIFT_ENUM) # define SWIFT_ENUM(_type, _name) enum _name : _type _name; enum SWIFT_ENUM_EXTRA _name : _type # if defined(__has_feature) && __has_feature(generalized_swift_name) # define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME) enum _name : _type _name SWIFT_COMPILE_NAME(SWIFT_NAME); enum SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_ENUM_EXTRA _name : _type # else # define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME) SWIFT_ENUM(_type, _name) # endif #endif #if defined(__has_feature) && __has_feature(modules) @import ObjectiveC; @import Foundation; @import UIKit; @import XMPPFramework; #endif #pragma clang diagnostic ignored "-Wproperty-attribute-mismatch" #pragma clang diagnostic ignored "-Wduplicate-method-arg" @protocol LavaRegionManagerDelegate; @class LavaTracker; @class LavaMessenger; @class NSData; @class LavaUser; @class LavaChatUser; @class NSError; @class UIViewController; @class LavaUserProfile; @class UIImage; @class LavaServer; /// The Lava class. All Lava APIs are available in this class. SWIFT_CLASS("_TtC7LavaSDK4Lava") @interface Lava : NSObject + (void)initialize:(NSString * _Nonnull)apiKey launchOptions:(NSDictionary * _Nullable)launchOptions; /// The API key. @property (nonatomic, readonly, copy) NSString * _Nonnull apiKey; /// Set this to true to enable debug logging. By default set to false. + (BOOL)debuggingEnabled; + (void)setDebuggingEnabled:(BOOL)value; /// Set this to get callabcks of beacon and ciecular region enter/exit/range callbacks. + (id <LavaRegionManagerDelegate> _Nullable)beaconDelegate; + (void)setBeaconDelegate:(id <LavaRegionManagerDelegate> _Nullable)newValue; /// Tracker provides set of APIs for tracking screen and events. + (LavaTracker * _Nonnull)tracker; /// Messenger provides set of APIs for social chat. + (LavaMessenger * _Nonnull)messenger; /// Set the device token information. Used for sending remote notification regarding offers. + (void)setDeviceTokenFromData:(NSData * _Nonnull)tokenData; + (NSString * _Nonnull)apiVersion; /// Returns Login status of the user. /// /// \returns <code>true /// </code> if user is logged in. + (BOOL)isLoggedIn; /// Currently logged in user. /// /// \returns Currently logged in user. <code>nil /// </code> if user is not logged in. + (LavaUser * _Nullable)currentUser; /// An array of users. + (NSArray<LavaChatUser *> * _Nonnull)userList; /// The total count of users. + (NSInteger)totalCount; /// State if the users are being downloaded at the moment. + (BOOL)isDownloadingUsers; /// Request to sign up the user with Email. /// /// \param email The email of the user. /// /// \param password The password of the user. /// /// \param completion The block to execute after the signup success or failure. + (void)signUpWithEmail:(NSString * _Nonnull)email password:(NSString * _Nonnull)password completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to sign up the user with Phone Number. /// /// \param phoneNumber The Phone number of the user. /// /// \param password The password of the user. /// /// \param completion The block to execute after the signup success or failure. + (void)signUpWithPhoneNumber:(NSString * _Nonnull)phoneNumber password:(NSString * _Nonnull)password completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to verify the user phone number using the verification key. /// /// \param phoneNumber The Phone number of the user. /// /// \param verficationKey The verification key or one time password that is sent to user phone number. /// /// \param completion The block to execute after the verification success or failure. + (void)verifyPhoneNumber:(NSString * _Nonnull)phoneNumber verficationKey:(NSString * _Nonnull)verficationKey completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to resend verification key to user phone number. /// /// \param phoneNumber The phone number of the user. /// /// \param completion The block to execute after the request success or failure. + (void)resendVerificationForPhoneNumber:(NSString * _Nonnull)phoneNumber completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to resend verification key to user email. /// /// \param emailAddress The email of the user. /// /// \param completion The block to execute after the request success or failure. + (void)resendVerificationForEmail:(NSString * _Nonnull)emailAddress completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to sign in the user with email. /// /// \param email The email of the user. /// /// \param password The password of the user. /// /// \param completion The block to execute after the sign in success or failure. + (void)signInWithEmail:(NSString * _Nonnull)emailAddress password:(NSString * _Nonnull)password completion:(void (^ _Nonnull)(LavaUser * _Nullable, NSError * _Nullable))completion; /// Request to sign in the user with phone number. /// /// \param phoneNumber The phone number of the user. /// /// \param password The password of the user. /// /// \param completion The block to execute after the sign in success or failure. + (void)signInWithPhoneNumber:(NSString * _Nonnull)phoneNumber password:(NSString * _Nonnull)password completion:(void (^ _Nonnull)(LavaUser * _Nullable, NSError * _Nullable))completion; /// Request to sign in the user with Facebook. /// /// \param fromViewController The view controller over which Facebook login view controller presented. /// /// \param completion The block to execute after the sign in success or failure. + (void)signInWithFacebookFromViewController:(UIViewController * _Nonnull)fromViewController completion:(void (^ _Nonnull)(LavaUser * _Nullable, NSError * _Nullable))completion; /// Request to continue with sign in process. This method can be used to continue sign in in current device ignoring the session in other device. /// /// \param user The current user. /// /// \param completion The block to execute after the sign in success or failure. + (void)continueSignInWithUser:(LavaUser * _Nullable)user completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to retrive the user profile of logged in user. /// /// \param completion The block to execute after the profile fetch success or failure. + (void)getUserProfile:(void (^ _Nonnull)(LavaUser * _Nullable, NSError * _Nullable))completion; /// Request to update the profile information of logged in user. /// /// \param userProfile updates user profile of logged in user. /// /// \param completion The block to execute after the profile update success or failure. + (void)updateUserProfile:(LavaUserProfile * _Nonnull)userProfile completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to update the profile picture of logged in user. /// /// \param user profile picture updates user profile picture of logged in user. /// /// \param completion The block to execute after the profile picture update success or failure. + (void)updateUserProfilePicture:(UIImage * _Nonnull)userProfilePricture completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to upload chat image of logged in user. /// /// \param user chat picture uploads the chat picture of logged in user. /// /// \param caht ID the chat id information of the chat image. /// /// \param metadata metadata for the upload. /// /// \param completion The block to execute after the profile picture update success or failure. + (void)uploadChatPicture:(UIImage * _Nonnull)chatPicture chatId:(NSString * _Nullable)chatId metaData:(NSDictionary<NSString *, NSString *> * _Nullable)metaData completion:(void (^ _Nonnull)(id _Nullable, NSError * _Nullable))completion; /// Request to add new email to the current account. /// /// \param email The email to be added. /// /// \param password The new password for fresh email account. /// /// \param completion The block to execute after the link account success or failure. + (void)linkWithEmail:(NSString * _Nonnull)email password:(NSString * _Nonnull)password completion:(void (^ _Nonnull)(LavaUser * _Nullable, NSError * _Nullable))completion; /// Request to add new phone number to the current account. /// /// \param phoneNumber The phone number to be added. /// /// \param password The new password for fresh phone number account. /// /// \param completion The block to execute after the link account success or failure. + (void)linkWithPhoneNumber:(NSString * _Nonnull)phoneNumber password:(NSString * _Nonnull)password completion:(void (^ _Nonnull)(LavaUser * _Nullable, NSError * _Nullable))completion; /// Request to link Facebook account with the current account. /// /// \param currentViewController The view controller over which Facebook login view controller presented. /// /// \param completion The block to execute after the link account success or failure. + (void)linkWithFacebook:(UIViewController * _Nonnull)currentViewController completion:(void (^ _Nonnull)(LavaUser * _Nullable, NSError * _Nullable))completion; /// Request to link existing email account with the current account. /// /// \param email The email to be linked. /// /// \param password The password of the existing email account. /// /// \param completion The block to execute after the link account success or failure. + (void)linkWithExistingEmail:(NSString * _Nonnull)email password:(NSString * _Nonnull)password completion:(void (^ _Nonnull)(LavaUser * _Nullable, NSError * _Nullable))completion; /// Request to link existing phone number account with the current account. /// /// \param phoneNumber The phone number to be linked. /// /// \param password The password of the existing phone number account. /// /// \param completion The block to execute after the link account success or failure. + (void)linkWithExistingPhoneNumber:(NSString * _Nonnull)phoneNumber password:(NSString * _Nonnull)password completion:(void (^ _Nonnull)(LavaUser * _Nullable, NSError * _Nullable))completion; /// Request to check if account with particular phone number or email exists. /// /// \param externalId The phone number or email. /// /// \param completion The block to execute after the check success or failure. + (void)checkIfAccountExists:(NSString * _Nonnull)externalId completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to check if email or phone number is verified. /// /// \param externalId The phone number or email. /// /// \param completion The block to execute after the check success or failure. + (void)checkVerificationStatus:(NSString * _Nonnull)externalId completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to change password of the user. /// /// \param oldPassword The old password of the user. /// /// \param newPassword The new password of the user. /// /// \param completion The block to execute after the password change success or failure. + (void)changePassword:(NSString * _Nonnull)oldPassword newPassword:(NSString * _Nonnull)newPassword completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to reset password for email account. /// /// \param emailAddress The email address of the user. /// /// \param completion The block to execute after the request success or failure. + (void)forgotPasswordForEmail:(NSString * _Nonnull)emailAddress completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to send verification key in order to reset password for phone number account. /// /// \param phoneNumber The phone number of the user. /// /// \param completion The block to execute after the request success or failure. + (void)forgotPasswordForPhoneNumber:(NSString * _Nonnull)phoneNumber completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to reset password of phone number account using verification key. /// /// \param verificationKey The one time password (OTP) that is sent to the user phone number. /// /// \param newPassword The new password for the phone number account. /// /// \param completion The block to execute after the reset password success or failure. + (void)resetPasswordForPhoneNumberWithVerificationKey:(NSString * _Nonnull)verificationKey phoneNumber:(NSString * _Nonnull)phoneNumber newPassword:(NSString * _Nonnull)newPassword completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to log out the user. /// /// \param completion The block to execute after the log out success or failure. + (void)logOut:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to delete the current user account. /// /// \param completion The block to execute after the account deletion success or failure. + (void)deleteCurrentAccount:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request for content. /// /// \param viewController The view controller that presents the content. + (void)requestContent:(UIViewController * _Nonnull)viewController; /// Handles the push notification received by the application. /// /// \param userInfo The userInfo received with the notification. + (void)handleNotification:(NSDictionary * _Nonnull)userInfo; /// Request to retrive the user list. /// /// \param completion The block to execute after the user list fetch success or failure. + (void)getUserList:(void (^ _Nonnull)(NSError * _Nullable))completion; /// This API is only for testing purpose. + (NSDictionary<NSString *, NSString *> * _Nonnull)getDebugInfo; /// This API is only for testing purpose. + (void)enterVirtualBeaconRegion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// This API is only for testing purpose. + (void)exitVirtualBeaconRegion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// This API is only for testing purpose. + (NSArray<LavaServer *> * _Nonnull)getLavaServers; /// This API is only for testing purpose. + (LavaServer * _Nonnull)getCurrentServer; /// This API is only for testing purpose. + (void)setLavaServer:(LavaServer * _Nonnull)server; @end @class XMPPStream; @class GCDAsyncSocket; @class DDXMLElement; SWIFT_PROTOCOL("_TtP7LavaSDK16LavaChatDelegate_") @protocol LavaChatDelegate @optional - (void)lavaStream:(XMPPStream * _Nullable)sender socketDidConnect:(GCDAsyncSocket * _Nullable)socket; - (void)lavaStreamDidConnect; - (void)lavaStreamConnectionErrorWithConnectionError:(DDXMLElement * _Nonnull)error; - (void)lavaStreamDidAuthenticate:(XMPPStream * _Nonnull)sender; - (void)lavaStream:(XMPPStream * _Nonnull)sender didNotAuthenticate:(DDXMLElement * _Nonnull)error; - (void)lavaStreamDidDisconnect:(XMPPStream * _Nonnull)sender withError:(NSError * _Nonnull)error; @end /// The base class used for all Lava SDK model classes. SDK user need not use this class. SWIFT_CLASS("_TtC7LavaSDK9LavaModel") @interface LavaModel : NSObject - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; @end SWIFT_CLASS("_TtC7LavaSDK17LavaChatImageData") @interface LavaChatImageData : LavaModel @property (nonatomic, copy) NSString * _Nullable imageUrl; @property (nonatomic, copy) NSString * _Nullable imageThumbnailUrl; @property (nonatomic, copy) NSDictionary<NSString *, NSString *> * _Nullable metaData; - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; @end typedef SWIFT_ENUM(NSInteger, LavaChatState) { LavaChatStatecomposing = 0, LavaChatStatepaused = 1, }; @class NSCoder; /// Defines the profile information of the user. SWIFT_CLASS("_TtC7LavaSDK15LavaUserProfile") @interface LavaUserProfile : LavaModel <NSCopying, NSCoding> /// Defines the first name of the user. @property (nonatomic, copy) NSString * _Nullable firstName; /// Defines the last name of the user. @property (nonatomic, copy) NSString * _Nullable lastName; /// Defines the gender of the user. @property (nonatomic, copy) NSString * _Nullable gender; /// Defines the country of the user. @property (nonatomic, copy) NSString * _Nullable country; /// Defines the age of the user. @property (nonatomic) NSInteger age; /// Defines the email of the user. @property (nonatomic, copy) NSString * _Nullable email; /// Defines the tier value of the user. @property (nonatomic, copy) NSString * _Nonnull tier; /// Defines the profile picture url of the user. @property (nonatomic, copy) NSString * _Nullable profilePic; /// Defines the profile picture thumnail url of the user. @property (nonatomic, copy) NSString * _Nullable profileThumbnailPic; - (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; - (id _Nonnull)copyWithZone:(struct _NSZone * _Null_unspecified)zone; - (void)encodeWithCoder:(NSCoder * _Nonnull)aCoder; /// Returns the initials from the user's fist and last name. - (NSString * _Nonnull)getInitials; /// Returns the full name of the user. - (NSString * _Nonnull)getFullName; @end /// The chat user profile. All chat recipient list users are this kind of object where jabber id is used to connect to the chat server. SWIFT_CLASS("_TtC7LavaSDK12LavaChatUser") @interface LavaChatUser : LavaUserProfile @property (nonatomic, copy) NSString * _Nonnull jabberId; @property (nonatomic, readonly, copy) NSString * _Nonnull jabberIdWithoutDomain; - (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; @end SWIFT_CLASS("_TtC7LavaSDK9LavaGroup") @interface LavaGroup : NSObject @property (nonatomic, copy) NSString * _Null_unspecified id; @property (nonatomic, copy) NSString * _Nullable name; - (NSString * _Nonnull)getName; - (NSString * _Nonnull)getInitials; @end @class NSDate; @class XMPPMessage; /// The chat message object. SWIFT_CLASS("_TtC7LavaSDK11LavaMessage") @interface LavaMessage : NSObject @property (nonatomic, copy) NSString * _Nonnull messageId; /// The body string of the message. @property (nonatomic, copy) NSString * _Nonnull body; /// The unique string to identify the sender. @property (nonatomic, copy) NSString * _Nonnull senderId; /// The sender display name. @property (nonatomic, copy) NSString * _Nonnull senderDisplayName; /// The time at which the message has received. @property (nonatomic, strong) NSDate * _Nullable date; /// Returns true if message has media content. @property (nonatomic) BOOL isMedia; /// Returns true if message is of type 'action'. An action message can be a message which tells about user subscription or unsucscription from a group. @property (nonatomic) BOOL isActionMessage; /// The image data will be non-nil if this is a media message and has image URLs to download. @property (nonatomic, strong) LavaChatImageData * _Nullable imageData; @property (nonatomic, readonly) BOOL wasDelayed; @property (nonatomic, readonly, strong) NSDate * _Nullable delayedDeliveryDate; - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; - (nonnull instancetype)initWithXmppMessage:(XMPPMessage * _Nonnull)xmppMessage OBJC_DESIGNATED_INITIALIZER; - (nonnull instancetype)initWithSenderId:(NSString * _Nonnull)senderId senderDisplayName:(NSString * _Nonnull)senderDisplayName date:(NSDate * _Nonnull)date body:(NSString * _Nonnull)body OBJC_DESIGNATED_INITIALIZER; - (nonnull instancetype)initWithItem:(DDXMLElement * _Nonnull)item senderId:(NSString * _Nullable)senderId senderDisplayName:(NSString * _Nullable)senderDisplayName date:(NSDate * _Nullable)date body:(NSString * _Nullable)body OBJC_DESIGNATED_INITIALIZER; @property (nonatomic, readonly, strong) LavaChatUser * _Nullable sender; @end SWIFT_CLASS("_TtC7LavaSDK22LavaMessageHistoryData") @interface LavaMessageHistoryData : NSObject @property (nonatomic, copy) NSArray<LavaMessage *> * _Nonnull messages; - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; - (nonnull instancetype)initWithItem:(DDXMLElement * _Nonnull)item OBJC_DESIGNATED_INITIALIZER; @end @protocol LavaMessengerDelegate; /// Lava Messenger provides set of APIs for social chat. SWIFT_CLASS("_TtC7LavaSDK13LavaMessenger") @interface LavaMessenger : NSObject /// Set this delegate to get callbacks of this messenger class. @property (nonatomic, weak) id <LavaMessengerDelegate> _Nullable delegate; - (void)connectUser:(LavaUser * _Nonnull)user; - (BOOL)isConnected; - (void)disconnect; - (BOOL)isConnecting; - (BOOL)isDisconnected; /// Request to send message to an user. /// /// \param message The message that need to be sent. /// /// \param user The receiver of the message. /// /// \param completion The block to execute after the message sending. - (void)sendMessage:(LavaMessage * _Nonnull)message toUser:(LavaChatUser * _Nonnull)user completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to send image to an user. /// /// \param image The image that need to be sent. /// /// \param user The receiver of the image message. /// /// \param completion The block to execute after the message sending. - (void)sendImage:(UIImage * _Nonnull)image toUser:(LavaChatUser * _Nonnull)user completion:(void (^ _Nonnull)(id _Nullable, NSError * _Nullable))completion; /// Request to fetch conversation list. /// /// \param completion The block to execute after the conversation list fetch success or failure. - (void)getConversationList:(void (^ _Nonnull)(id _Nullable, NSError * _Nullable))completion; /// Check whether the user exists in conversation list. /// /// \param user The user object. /// /// \returns <code>true /// </code> if user exists in conversation list. - (BOOL)isUserExistsInConversationList:(LavaChatUser * _Nonnull)user; /// Add user to the conversation list. /// /// \param user The user object. - (void)addUserToConversationList:(LavaChatUser * _Nonnull)user; /// Check whether the user exists in buddy list. /// /// \param user The user object. /// /// \returns <code>true /// </code> if user exists in buddy list. - (BOOL)isUserExistsInRoster:(LavaChatUser * _Nonnull)user; /// Add user to the buddy list. /// /// \param user The user object. /// /// \returns <code>true /// </code> if user exists in buddy list. - (void)addUserToRoster:(LavaChatUser * _Nonnull)user; /// Request to send 'composing' or 'not composing' message to an user. This is used to show/hide typing indicator when user starts/ends typing. /// /// \param receiver The receiver of the state change notification. - (void)setChatState:(enum LavaChatState)chatState receiver:(LavaChatUser * _Nonnull)receiver; /// Request to create group with a name and participants. /// /// \param name The name for the group. /// /// \param participants The list of users who needs to be added to the group. /// /// \param completion The block to execute after creation of the group with participants. - (void)createGroup:(NSString * _Nonnull)name participants:(NSArray<LavaChatUser *> * _Nonnull)participants completion:(void (^ _Nonnull)(id _Nullable, NSError * _Nullable))completion; /// Request to send message to a group. /// /// \param message The message that needs to be sent. /// /// \param group The group for which message needs to be sent. /// /// \param completion The block to execute after message sending success or failure. - (void)sendMessage:(LavaMessage * _Nonnull)message toGroup:(LavaGroup * _Nonnull)group completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to send image to a group. /// /// \param image The image that needs to be sent. /// /// \param group The group for which image needs to be sent. /// /// \param completion The block to execute after image sending success or failure. - (void)sendImage:(UIImage * _Nonnull)image toGroup:(LavaGroup * _Nonnull)group completion:(void (^ _Nonnull)(id _Nullable, NSError * _Nullable))completion; /// Request to retrive all groups. /// /// \param completion The block to execute after group retrival success or failure. - (void)getGroups:(void (^ _Nonnull)(id _Nullable, NSError * _Nullable))completion; /// Request to retrive users in a group. /// /// \param group The group for which users needs to be retrived. /// /// \param completion The block to execute after users in a group success or failure. - (void)getUsersInGroup:(LavaGroup * _Nonnull)group completion:(void (^ _Nonnull)(id _Nullable, NSError * _Nullable))completion; /// Request to add one or more users to a group. /// /// \param users The list of users that needs to be added to the group. /// /// \param completion The block to execute after user subscription success or failure. - (void)addUsers:(NSArray<LavaChatUser *> * _Nonnull)users toGroup:(LavaGroup * _Nonnull)group completion:(void (^ _Nonnull)(NSError * _Nullable))completion; /// Request to leave a group. /// /// \param group The group that needs to be unsubscribed. /// /// \param completion The block to execute after group unsubscription success or failure. - (void)leaveGroup:(LavaGroup * _Nonnull)group completion:(void (^ _Nonnull)(NSError * _Nullable))completion; - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; @end @interface LavaMessenger (SWIFT_EXTENSION(LavaSDK)) /// Returns the chat recipient list. /// /// \returns The chat recipient list. - (NSArray<LavaChatUser *> * _Nonnull)chatRecipients; @end /// Lava Messenger delegate callbacks. SWIFT_PROTOCOL("_TtP7LavaSDK21LavaMessengerDelegate_") @protocol LavaMessengerDelegate @optional /// Gets called when messenger gets connected. - (void)lavaMessengerDidConnect; /// Gets called when messenger connection is failed. - (void)lavaMessengerConnectionError:(NSError * _Nonnull)error; /// Gets called when a new message is received from a user. - (void)didReceiveMessage:(LavaMessage * _Nonnull)message from:(LavaChatUser * _Nonnull)user; /// Gets called when a new message is received from a user in a group. - (void)didReceiveMessage:(LavaMessage * _Nonnull)message from:(LavaChatUser * _Nonnull)user group:(LavaGroup * _Nonnull)group; /// Gets called when chat state changed for an user. - (void)didChatStateChangedForUser:(LavaChatUser * _Nonnull)user chatState:(enum LavaChatState)chatState; /// Gets called when the user adds another user to his buddy list or when user being added to another user's buddy list. We need to update the conversation list when this happens. - (void)rosterContentChanged; /// Gets called when user is added to a group. We need to update the conversation list when this happens. - (void)didAddedToGroup:(LavaGroup * _Nonnull)group; @end @class CLBeaconRegion; @class CLCircularRegion; @class CLBeacon; /// The protocol that defines callbacks from beacon and circular region. SWIFT_PROTOCOL("_TtP7LavaSDK25LavaRegionManagerDelegate_") @protocol LavaRegionManagerDelegate <NSObject> /// This gets called when a beacon enter event occurs. - (void)didEnterBeaconRegion:(CLBeaconRegion * _Nonnull)region; /// This gets called when a beacon exit event occurs. - (void)didExitBeaconRegion:(CLBeaconRegion * _Nonnull)region; /// This gets called when a circular region enter event occurs. - (void)didEnterCircularRegion:(CLCircularRegion * _Nonnull)region; /// This gets called when a circular region exit event occurs. - (void)didExitCircularRegion:(CLCircularRegion * _Nonnull)region; /// This gets called when user is within the beacon region. - (void)didRangeBeacon:(CLBeacon * _Nonnull)beacon; @end SWIFT_CLASS("_TtC7LavaSDK10LavaServer") @interface LavaServer : NSObject @property (nonatomic, copy) NSString * _Null_unspecified title; - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; @end @interface LavaServer (SWIFT_EXTENSION(LavaSDK)) + (LavaServer * _Nonnull)currentServer; + (LavaServer * _Nonnull)client; + (LavaServer * _Nonnull)production; + (LavaServer * _Nonnull)development; + (LavaServer * _Nonnull)testing; @end SWIFT_CLASS("_TtC7LavaSDK11LavaTracker") @interface LavaTracker : NSObject - (void)trackScreen:(NSString * _Nonnull)screenName; - (void)trackEvent:(NSString * _Nonnull)category action:(NSString * _Nonnull)action; @end @class LavaUserAccount; /// The user object. This class holds user's profile and accounts. SWIFT_CLASS("_TtC7LavaSDK8LavaUser") @interface LavaUser : LavaModel <NSCoding> /// The list of accounts this user holds. This can be Email, Phone number or Facebook account. @property (nonatomic, readonly, copy) NSArray<LavaUserAccount *> * _Nullable accounts; /// The profile of the user. @property (nonatomic, readonly, strong) LavaUserProfile * _Nullable userProfile; /// The jabber id of the user which is used to connect to chat server. This can be nil if chat functionality is not applicable for this account. @property (nonatomic, readonly, copy) NSString * _Nullable jabberId; /// The jabber id of the user without domain which is used to connect to chat server. This can be nil if chat functionality is not applicable for this account. @property (nonatomic, readonly, copy) NSString * _Nullable jabberIdWithoutDomain; - (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; - (void)encodeWithCoder:(NSCoder * _Nonnull)aCoder; @end /// Defines a account of the user. This can be a Email, Phone number or Facebook account. SWIFT_CLASS("_TtC7LavaSDK15LavaUserAccount") @interface LavaUserAccount : LavaModel <NSCoding> /// Represents the email or mobile number or facebook id that user used to logged in. @property (nonatomic, readonly, copy) NSString * _Nullable externalId; /// Represents the login type. @property (nonatomic, readonly, copy) NSString * _Nullable externalSystem; /// Variable used to check the verification status of external id. @property (nonatomic, readonly) BOOL isVerified; - (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; - (void)encodeWithCoder:(NSCoder * _Nonnull)aCoder; @end @interface NSError (SWIFT_EXTENSION(LavaSDK)) @end @interface UIImageView (SWIFT_EXTENSION(LavaSDK)) @end @class NSURL; @interface UIImageView (SWIFT_EXTENSION(LavaSDK)) /// Use this method to download all secured lava images. This method internally uses AlamofireImage to download the image. /// /// \param url The URL for the image. - (void)lava_setImageWithURL:(NSURL * _Nonnull)url; /// Use this method to download all secured lava images. This method internally uses AlamofireImage to download the image. /// /// \param url The URL for the image. /// /// \param placeholderImage The image to be set initially until the image request finished. - (void)lava_setImageWithURL:(NSURL * _Nonnull)url placeholderImage:(UIImage * _Nonnull)placeholderImage; /// Use this method to download all secured lava images and rounds the corners of an image into a circle. This method internally uses AlamofireImage to download the image. /// /// \param url The URL for the image. - (void)lava_setCircleImageWithURL:(NSURL * _Nonnull)url; /// Cancels the active download request. - (void)lava_cancelImageRequest; @end @interface XMPPIQ (SWIFT_EXTENSION(LavaSDK)) @end @interface XMPPPubSub (SWIFT_EXTENSION(LavaSDK)) @end #pragma clang diagnostic pop
40.339243
255
0.769391
[ "object", "model" ]
3b345051d00775752158057b52868b410faed57f
3,356
h
C
RecoTracker/DebugTools/interface/GetTrackTrajInfo.h
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
RecoTracker/DebugTools/interface/GetTrackTrajInfo.h
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
RecoTracker/DebugTools/interface/GetTrackTrajInfo.h
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#ifndef RecoTracker_DebugTools_GetTrackTrajInfo_H #define RecoTracker_DebugTools_GetTrackTrajInfo_H /* * Determine the track trajectory and detLayer at each layer that the track produces a hit in. * This info can then be used to get the coordinates and momentum vector of the track at each of these * layers etc. * * Call function analyze() for each track you are interested in. See comments below for that function. * From the "result" that it returns, you can do things such as result.detTSOS.globalPosition(), * to get the estimated position at which the track intercepts the layer. * * N.B. This information is obtained by extrapolating the track trajectory from its point of closest * approach to the beam-line. It is therefore approximate, and should not be used for hit resolution * studies. * If you are using RECO, you can get more precise results by refitting the track instead of using this * class. However, this class will work even on AOD. * * N.B. Your _cfg.py must load RecoTracker.Configuration.RecoTracker_cff to use this. * * Author: Ian Tomalin * Date: Oct. 2011 */ #include <memory> #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/EventSetup.h" #include "DataFormats/TrackReco/interface/Track.h" #include "TrackingTools/TransientTrack/interface/TransientTrackBuilder.h" #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include <vector> class DetLayer; class GetTrackTrajInfo { public: // Used to return results. struct Result { // If this is false, the information in the struct for this hit is invalid, as the track trajectory // did not cross this layer. (Should only happen in very rare cases). bool valid; // If this is false, then although the track trajectory intercepted the layer, it did not intercept // a sensor inside the layer. (Can happen rarely, if the track scattered, for example). // If it is false, the detTSOS is evaluated at the intercept with the layer, not with the sensor, // so will be slightly less accurate. bool accurate; // This is the DetLayer returned by GeometricSearchTracker. // You can cast it into a specific type, such as BarrelDetLayer, before using it. const DetLayer* detLayer; // This is the track trajectory evaluated at the sensor. You can use it to get the coordinates // where the track crosses the sensor and its momentum vector at that point. TrajectoryStateOnSurface detTSOS; }; GetTrackTrajInfo() {} ~GetTrackTrajInfo() {} // For each hit on the track, return the information listed in the struct Result above. // (See comments for struct Results). // There is a one-to-one correspondence between this vector and the hits returned by track::hitPattern(). // i.e. They are ordered by the order in which the track crossed them. std::vector<Result> analyze(const edm::EventSetup& iSetup, const reco::Track& track); private: // Create map indicating r/z values of all layers/disks. void init (const edm::EventSetup& iSetup); private: // Makes TransientTracks needed for vertex fitting. edm::ESHandle<TransientTrackBuilder> trkTool_; }; #endif
40.926829
107
0.75298
[ "vector" ]
3b38b51d1134e34770e260aa1e001992854d3cbb
3,974
h
C
datapool/PIDReader.h
bl4ckic3/fsfw
c76fc8c703e19d917c45a25710b4642e5923c68a
[ "Apache-2.0" ]
null
null
null
datapool/PIDReader.h
bl4ckic3/fsfw
c76fc8c703e19d917c45a25710b4642e5923c68a
[ "Apache-2.0" ]
null
null
null
datapool/PIDReader.h
bl4ckic3/fsfw
c76fc8c703e19d917c45a25710b4642e5923c68a
[ "Apache-2.0" ]
null
null
null
#ifndef PIDREADER_H_ #define PIDREADER_H_ #include "DataPool.h" #include "DataSetIF.h" #include "PoolEntry.h" #include "PoolVariableIF.h" #include "../serialize/SerializeAdapter.h" #include "../serviceinterface/ServiceInterfaceStream.h" template<typename U, uint8_t n_var> class PIDReaderList; template<typename T> class PIDReader: public PoolVariableIF { template<typename U, uint8_t n_var> friend class PIDReaderList; protected: uint32_t parameterId; uint8_t valid; ReturnValue_t read() { uint8_t arrayIndex = DataPool::PIDToArrayIndex(parameterId); PoolEntry<T> *read_out = ::dataPool.getData<T>( DataPool::PIDToDataPoolId(parameterId), arrayIndex); if (read_out != NULL) { valid = read_out->valid; value = read_out->address[arrayIndex]; return HasReturnvaluesIF::RETURN_OK; } else { value = 0; valid = false; sif::error << "PIDReader: read of PID 0x" << std::hex << parameterId << std::dec << " failed." << std::endl; return HasReturnvaluesIF::RETURN_FAILED; } } /** * Never commit, is read-only. * Reason is the possibility to access a single DP vector element, but if we commit, * we set validity of the whole vector. */ ReturnValue_t commit() { return HasReturnvaluesIF::RETURN_FAILED; } /** * Empty ctor for List initialization */ PIDReader() : parameterId(PoolVariableIF::NO_PARAMETER), valid( PoolVariableIF::INVALID), value(0) { } public: /** * \brief This is the local copy of the data pool entry. */ T value; /** * \brief In the constructor, the variable can register itself in a DataSet (if not NULL is * passed). * \details It DOES NOT fetch the current value from the data pool, but sets the value * attribute to default (0). The value is fetched within the read() operation. * \param set_id This is the id in the global data pool this instance of the access class * corresponds to. * \param dataSet The data set in which the variable shall register itself. If NULL, * the variable is not registered. * \param setWritable If this flag is set to true, changes in the value attribute can be * written back to the data pool, otherwise not. */ PIDReader(uint32_t setParameterId, DataSetIF *dataSet) : parameterId(setParameterId), valid(PoolVariableIF::INVALID), value( 0) { if (dataSet != NULL) { dataSet->registerVariable(this); } } /** * Copy ctor to copy classes containing Pool Variables. */ PIDReader(const PIDReader &rhs) : parameterId(rhs.parameterId), valid(rhs.valid), value(rhs.value) { } /** * \brief The classes destructor is empty. */ ~PIDReader() { } /** * \brief This operation returns the data pool id of the variable. */ uint32_t getDataPoolId() const { return DataPool::PIDToDataPoolId(parameterId); } uint32_t getParameterId() const { return parameterId; } /** * This method returns if the variable is write-only, read-write or read-only. */ ReadWriteMode_t getReadWriteMode() const { return VAR_READ; } /** * \brief With this call, the valid information of the variable is returned. */ bool isValid() const { if (valid) return true; else return false; } uint8_t getValid() { return valid; } void setValid(uint8_t valid) { this->valid = valid; } operator T() { return value; } PIDReader<T>& operator=(T newValue) { value = newValue; return *this; } virtual ReturnValue_t serialize(uint8_t **buffer, size_t *size, size_t maxSize, Endianness streamEndianness) const override { return SerializeAdapter::serialize(&value, buffer, size, maxSize, streamEndianness); } virtual size_t getSerializedSize() const override { return SerializeAdapter::getSerializedSize(&value); } virtual ReturnValue_t deSerialize(const uint8_t **buffer, size_t *size, Endianness streamEndianness) override { return SerializeAdapter::deSerialize(&value, buffer, size, streamEndianness); } }; #endif /* PIDREADER_H_ */
26.851351
92
0.704076
[ "vector" ]
3b3acc9e15739ba1ca0f87972ef08df167f2ba6a
2,934
c
C
Split/Temp/il2cppOutput/il2cppOutput/UnityEngine.AIModule_CodeGen.c
OgiJr/SunBed
ea42007d57affe1421517cff6634e6412943f89f
[ "MIT" ]
null
null
null
Split/Temp/il2cppOutput/il2cppOutput/UnityEngine.AIModule_CodeGen.c
OgiJr/SunBed
ea42007d57affe1421517cff6634e6412943f89f
[ "MIT" ]
null
null
null
Split/Temp/il2cppOutput/il2cppOutput/UnityEngine.AIModule_CodeGen.c
OgiJr/SunBed
ea42007d57affe1421517cff6634e6412943f89f
[ "MIT" ]
null
null
null
#include "pch-c.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include "codegen/il2cpp-codegen-metadata.h" IL2CPP_EXTERN_C_BEGIN IL2CPP_EXTERN_C_END // 0x00000001 System.Boolean UnityEngine.AI.NavMeshAgent::SetDestination(UnityEngine.Vector3) extern void NavMeshAgent_SetDestination_m244EFBCDB717576303DA711EE39572B865F43747 (); // 0x00000002 UnityEngine.Vector3 UnityEngine.AI.NavMeshAgent::get_velocity() extern void NavMeshAgent_get_velocity_mA6F25F6B38D5092BBE6DECD77F8FDB93D5C515C9 (); // 0x00000003 System.Boolean UnityEngine.AI.NavMeshAgent::SetDestination_Injected(UnityEngine.Vector3&) extern void NavMeshAgent_SetDestination_Injected_m41607AA111EE126BBBDCDDF76B7523B0BC369D9A (); // 0x00000004 System.Void UnityEngine.AI.NavMeshAgent::get_velocity_Injected(UnityEngine.Vector3&) extern void NavMeshAgent_get_velocity_Injected_m64CD1C3DAE418314D44A1194F014CEC159CDDAA8 (); // 0x00000005 System.Void UnityEngine.AI.NavMesh::Internal_CallOnNavMeshPreUpdate() extern void NavMesh_Internal_CallOnNavMeshPreUpdate_m5C0CEF0AEF92B6BE0368AA5ABC02B4CCDEFA9AD5 (); // 0x00000006 System.Void UnityEngine.AI.NavMesh_OnNavMeshPreUpdate::.ctor(System.Object,System.IntPtr) extern void OnNavMeshPreUpdate__ctor_mDBB85480C3EA968112EB3B356486B9C9FF387BD4 (); // 0x00000007 System.Void UnityEngine.AI.NavMesh_OnNavMeshPreUpdate::Invoke() extern void OnNavMeshPreUpdate_Invoke_m8950FEDFD3E07B272ED469FD1911AA98C60FC28D (); // 0x00000008 System.IAsyncResult UnityEngine.AI.NavMesh_OnNavMeshPreUpdate::BeginInvoke(System.AsyncCallback,System.Object) extern void OnNavMeshPreUpdate_BeginInvoke_m8B7FF1B745E38190A2B744775602508E77B291FA (); // 0x00000009 System.Void UnityEngine.AI.NavMesh_OnNavMeshPreUpdate::EndInvoke(System.IAsyncResult) extern void OnNavMeshPreUpdate_EndInvoke_mA263F64ADF01540E24327DDB24BD334539B1B4D2 (); static Il2CppMethodPointer s_methodPointers[9] = { NavMeshAgent_SetDestination_m244EFBCDB717576303DA711EE39572B865F43747, NavMeshAgent_get_velocity_mA6F25F6B38D5092BBE6DECD77F8FDB93D5C515C9, NavMeshAgent_SetDestination_Injected_m41607AA111EE126BBBDCDDF76B7523B0BC369D9A, NavMeshAgent_get_velocity_Injected_m64CD1C3DAE418314D44A1194F014CEC159CDDAA8, NavMesh_Internal_CallOnNavMeshPreUpdate_m5C0CEF0AEF92B6BE0368AA5ABC02B4CCDEFA9AD5, OnNavMeshPreUpdate__ctor_mDBB85480C3EA968112EB3B356486B9C9FF387BD4, OnNavMeshPreUpdate_Invoke_m8950FEDFD3E07B272ED469FD1911AA98C60FC28D, OnNavMeshPreUpdate_BeginInvoke_m8B7FF1B745E38190A2B744775602508E77B291FA, OnNavMeshPreUpdate_EndInvoke_mA263F64ADF01540E24327DDB24BD334539B1B4D2, }; static const int32_t s_InvokerIndices[9] = { 1380, 1370, 815, 6, 3, 124, 23, 105, 26, }; extern const Il2CppCodeGenModule g_UnityEngine_AIModuleCodeGenModule; const Il2CppCodeGenModule g_UnityEngine_AIModuleCodeGenModule = { "UnityEngine.AIModule.dll", 9, s_methodPointers, s_InvokerIndices, 0, NULL, 0, NULL, 0, NULL, NULL, };
37.139241
124
0.870825
[ "object" ]
3b4b8f8311e5488c737dd71087f3fb47c6447a38
6,590
h
C
v01/dispatcher.h
mtsp/ferret
1ca08b25e2cfab33fe6a9f210ae8b69c79766254
[ "BSD-3-Clause" ]
1
2017-04-27T13:27:55.000Z
2017-04-27T13:27:55.000Z
v01/dispatcher.h
mtsp/ferret
1ca08b25e2cfab33fe6a9f210ae8b69c79766254
[ "BSD-3-Clause" ]
null
null
null
v01/dispatcher.h
mtsp/ferret
1ca08b25e2cfab33fe6a9f210ae8b69c79766254
[ "BSD-3-Clause" ]
null
null
null
/** * Dispatcher.h * Description: API responsible for dispatching a graph to the MTSP runtime * - Execute the graph structure by dispatching it to the runtime * - Displays an error message if the graph was incorrectly dispatched * */ #include "common.h" #include <kmp.h> #include <unistd.h> #include <iostream> #include <string> #include <thread> /** * Task parameter data structure */ typedef struct task_parameter { uint id; bool** in_var; bool** out_var; uint in_sz; uint out_sz; float load; } tparam_t; /* Dispatcher API */ class Dispatcher { public: /** * Dispatch a graph to the runtime * */ static void dispatch(Graph* g) { graph = g; // Allocate array of variables to be used as dependencies dep_vars = new bool[graph->total_deps]; params = new tparam_t[graph->total_tasks]; // Start execution of a parallel region __kmpc_fork_call(NULL, 0, (kmpc_micro) microtask); // Clean the mess delete dep_vars; delete params; } private: /* Static variables that keep in track with the graph workflow */ static Graph* graph; static bool* dep_vars; static tparam_t* params; /** * Main dispatcher according to runtime signature, manage dependencies * between tasks, set dependency checker and dispatch them. */ static void microtask(int gid, int tid, void* param) { uint cur_task = 0; std::cout << "Start Dispatching tasks!\n"; // Initialize dep_vars with false for (uint i = 0; i < graph->total_deps; i++) dep_vars[i] = false; // Since a task only depends on the previous tasks (in the vector index), a // valid order is to dispatch the tasks in the vector order std::vector<Task>::iterator it; for (it = graph->tasks.begin(); it != graph->tasks.end(); ++it) { kmp_depend_info* dep_list; kmp_task* task; std::list<Dep>::iterator itt; uint cur_out, cur_in; // Counter for in and out dependencies uint n_dep; // First dependency and number of dependencies // Initialize task struckture task = __kmpc_omp_task_alloc(NULL, 0, 0, sizeof(kmp_task) + 8, 0, (kmp_routine_entry)ptask_f); // Compute number of dependencies for current task params[cur_task].in_sz = 0; params[cur_task].out_sz = it->successors.size(); n_dep = params[cur_task].out_sz; for (itt = it->predecessors.begin(); itt != it->predecessors.end(); ++itt) { params[cur_task].in_sz += 1; if (itt->type == INOUT) params[cur_task].out_sz += 1; } n_dep += params[cur_task].in_sz; params[cur_task].id = cur_task; params[cur_task].load = it->load; params[cur_task].in_var = new bool*[params[cur_task].in_sz]; params[cur_task].out_var = new bool*[params[cur_task].out_sz]; dep_list = new kmp_depend_info[n_dep+1]; // Prepare task dependencies cur_in = cur_out = 0; uint i = 1; // Index for dep_list dep_list[0].base_addr = (kmp_intptr) &(params[cur_task]); dep_list[0].len = sizeof(params[cur_task]); dep_list[0].flags.in = false; dep_list[0].flags.out = false; for (itt = it->successors.begin(); itt != it->successors.end(); ++itt) { params[cur_task].out_var[cur_out] = &dep_vars[itt->index]; dep_list[i].base_addr = (kmp_intptr) &dep_vars[itt->index]; dep_list[i].len = sizeof(dep_vars[itt->index]); dep_list[i].flags.in = false; dep_list[i].flags.out = true; i++; cur_out++; } for (itt = it->predecessors.begin(); itt != it->predecessors.end(); ++itt) { params[cur_task].in_var[cur_in] = &dep_vars[itt->index]; dep_list[i].base_addr = (kmp_intptr) &dep_vars[itt->index]; dep_list[i].len = sizeof(dep_vars[itt->index]); dep_list[i].flags.in = true; dep_list[i].flags.out = false; if (itt->type == INOUT) { params[cur_task].out_var[cur_out] = &dep_vars[itt->index]; dep_list[i].flags.out = true; cur_out++; } else { dep_list[i].flags.out = false; } i++; cur_in++; } // Dispatch task std::cout << "\tdispatching task " << cur_task << "\n"; __kmpc_omp_task_with_deps(NULL, 0, task, n_dep + 1, dep_list, 0, NULL); delete dep_list; cur_task++; } std::cout << "Done Dispatching!\n"; // Wait until all tasks have been executed __kmpc_omp_taskwait(NULL, 0); std::cout << "Done executing!\n"; } /** * Function to be executed by each task * */ static void f(tparam_t param) { bool cur = true; // Load time to be executed on the current task int load = (param.load * graph->load_time) + graph->load_time; // Waiting! std::this_thread::sleep_for(std::chrono::milliseconds(load)); // -- Compute if task execution is valid -- // Check if all input dependencies are true (if in_sz is 0, then cur will // be true as expected) for (uint i = 0; cur && i < param.in_sz; i++) cur = cur && *(param.in_var[i]); // Print error message if execution is incorrect if (!cur) { std::string err_str; err_str = "invalid execution of task " + std::to_string(param.id) + "\n"; std::cerr << err_str; } // Propagate whether current task execution is valid for (uint i = 0; i < param.out_sz; i++) *(param.out_var[i]) = cur; } /** * Default function called by each task when executed * */ static void ptask_f(kmp_int32 gtid, void* param) { kmp_task* t = (kmp_task*) param; mtsp_task_metadata* md = t->metadata; tparam_t* p = (tparam_t*) md->dep_list[0].base_addr; f(*p); } }; /* Declare static variables */ Graph* Dispatcher::graph; bool* Dispatcher::dep_vars; tparam_t* Dispatcher::params;
31.380952
88
0.550228
[ "vector" ]
3b60d91f7ecf13fa5765c9e11ca6665eb4e70a36
4,818
c
C
d/antioch/jarmila/mobs/paladin.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
9
2021-07-05T15:24:54.000Z
2022-02-25T19:44:15.000Z
d/antioch/jarmila/mobs/paladin.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/antioch/jarmila/mobs/paladin.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
10
2021-03-13T00:18:03.000Z
2022-03-29T15:02:42.000Z
#include <std.h> #include <security.h> #include "../jarmila.h" inherit MONSTER; void do_greeting(); object bork_control; int talked; void create() { int mylevel = 65; ::create(); talked=0; set_name("Rosalind de Montbard"); set_id(({ "paladin", "guard", "paladin guard", "pguard", "Paladin", "avatar",})); set_short("%^C229%^Ros%^C230%^a%^C229%^lind "+ "de M%^C230%^o%^C229%^ntb%^C230%^a%^C229%^rd, "+ "%^C252%^Paladin%^C229%^ of the %^C197%^Rose%^C229%^"); set_long("%^C229%^Dressed in gleaming heavy armor "+ "and resting a wonderous sword on her lap, this "+ "woman is the very image of a paladin. Her equipment "+ "is immacutely cared for and her clothing cut to a "+ "tailor's eye. She has a powerful frame and strong, "+ "yet her movements are fluid and graceful as a "+ "dancer. Long blonde hair cascades over her shoulderes "+ "and frames an extiquisitely beautiful face.%^C229%^"); set_race("deva"); set_gender("female"); set_body_type("human"); set_overall_ac(-70); set_alignment(1); set("aggressive", 2); set_property("swarm", 0); set_level(mylevel); set_class("paladin"); set_mlevel("paladin", mylevel); set_mlevel("cleric", mylevel); set_property("no hold", 1); set_property("no death", 1); set_max_hp(18 * mylevel + 6000); set_hp(query_max_hp()); set_property("spell damage resistance", 60); set_mob_magic_resistance("high"); set_property("damage resistance", 10); set_new_exp(mylevel, "boss"); set("aggressive", 0); set_stats("strength", 22); set_stats("wisdom", 22); set_stats("intelligence", 12); set_stats("constitution", 22); set_stats("charisma", 26); set_stats("dexterity", 18); set_diety("jarmila"); set("speech string", "intone"); set("describe string", "powerfully"); new("/d/magic/symbols/jarmila_symbol.c")->move(TO); force_me("wear symbol"); set_thief_skill("perception", 55); { object obj; int ench = 7; obj = new("/d/magic/obj/shields/jarmila"); obj->set_property("enchantment", ench); obj->move(TO); obj->set_property("monsterweapon", 1); force_me("wear shield"); obj = new("/d/islands/common/obj/new/gdblade"); obj->set_property("enchantment", ench); obj->move(TO); obj->set_property("monsterweapon", 1); force_me("wield weapon"); } set_monster_feats(({ "reflection", "counter", "deflection", "parry", "shieldbash", "shieldwall", "rush", "smite", })); set_spells(({ "sunbeam", "holy smite", "sunburst", })); set_spell_chance(66); set_funcs(({ "rushit", "bashit", "smiteit" })); set_func_chance(66); set_property("cast and attack", 1); set_property("function and attack", 1); force_me("pose %^ORANGE%^Sitting on a sunstone, a sword across her lap%^RESET%^"); } void rushit(object targ) { TO->force_me("rush " + targ->query_name()); } void smiteit(object targ) { TO->force_me("smite"); } void bashit(object targ) { TO->force_me("shieldbash " + targ->query_name()); } void die(object obj) { bork_control =find_object_or_load(ROOMS"top.c"); tell_room(ETO,"death? not worky",ETO); bork_control->turning(0); return ::die(obj); } void init() { ::init(); if (!interactive(TP)) { return; } call_out("do_greeting", 1, TP); return; } void heart_beat() { object* user; int i, j; ::heart_beat(); if(!this_object()) return; if (sizeof(TO->query_attackers())) { if (!TO->query_property("angelic_aspect")) { new("/cmds/spells/g/_greater_angelic_aspect")->use_spell(TO, TO, 70, 100); } if (TO->query_hp() < TO->query_max_hp() / 2) { if (!random(8)) { new("/cmds/spells/h/_heal")->use_spell(TO, TO, 30, 100); } } } } void speak(string msg) { force_me("say %^YELLOW%^" + msg + "%^RESET%^"); } void do_greeting() { if(talked==1){speak("Lets do this!");return;} else{ speak("I am glad you have came. The view is too beautiful to not share."); tell_room(ETO,"%^C226%^\nThe glow radiates from the paladin%^CRST%^\n"); speak("Am I not what you expected from your climb?"); tell_room(ETO,"%^C100%^\nShe chuckles and looks out on the horizon.%^CRST%^\n"); speak("You may not want to, but we need to fight. My death will bring her power and her love. She will fight you as well. To help your rebirth."); tell_room(ETO,"%^C008%^\nShe tightens the clasps on her armor and waits for your move.%^CRST%^\n%^"); talked = 1; return 1; } }
24.835052
162
0.594022
[ "object" ]
3b693b0ae37f19e8f03abb7946f1906ef05c1678
794
h
C
PhotoRotate/Utilities.h
LoyalMoral/PhotoCropRotate
92d21409972f95214ccf9a5a05998e70792ba495
[ "MIT" ]
null
null
null
PhotoRotate/Utilities.h
LoyalMoral/PhotoCropRotate
92d21409972f95214ccf9a5a05998e70792ba495
[ "MIT" ]
1
2017-04-12T03:11:53.000Z
2017-11-10T03:10:00.000Z
PhotoRotate/Utilities.h
LoyalMoral/PhotoCropRotate
92d21409972f95214ccf9a5a05998e70792ba495
[ "MIT" ]
null
null
null
// // Utilities.h // PhotoRotate // // Created by Luan on 11/7/16. // Copyright © 2016 Shutta. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreGraphics/CoreGraphics.h> #import <UIKit/UIKit.h> @interface Utilities : NSObject + (UIImage *)newTransformedImage:(CGAffineTransform)transform sourceImage:(CGImageRef)sourceImage sourceSize:(CGSize)sourceSize sourceOrientation:(UIImageOrientation)sourceOrientation outputWidth:(CGFloat)outputWidth cropSize:(CGSize)cropSize imageViewSize:(CGSize)imageViewSize; + (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)aperture withOrientation:(UIImageOrientation)orientation; @end
29.407407
123
0.667506
[ "transform" ]
3b822d086f37c9bdb93c17f69f7367fdfc9f7a26
733
h
C
src/Canvas.h
data-bridge/build
1bd37f7061d9bd5caf0c1bd9c5cbbd85c7a45486
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
src/Canvas.h
data-bridge/build
1bd37f7061d9bd5caf0c1bd9c5cbbd85c7a45486
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
src/Canvas.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_CANVAS_H #define BRIDGE_CANVAS_H #include <string> #include <vector> using namespace std; class Canvas { private: vector<string> canvas; unsigned height; unsigned width; public: Canvas(); ~Canvas(); void reset(); void resize( const unsigned height, const unsigned width); void setLine( const string& text, const unsigned lineNo, const unsigned colNo); void setRectangle( const vector<string>& rectangle, const unsigned lineNo, const unsigned colNo); string str(const bool RECflag = false) const; }; #endif
13.574074
49
0.635744
[ "vector" ]