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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7939ff9bb43e8b7186513e74352c6b24aed46349
| 2,145
|
h
|
C
|
command/param_comple/file_behavior.h
|
yohe/CLI-DevTool
|
5a69ba89c0657ccaa7a75d60686465106b1453e7
|
[
"Unlicense"
] | null | null | null |
command/param_comple/file_behavior.h
|
yohe/CLI-DevTool
|
5a69ba89c0657ccaa7a75d60686465106b1453e7
|
[
"Unlicense"
] | null | null | null |
command/param_comple/file_behavior.h
|
yohe/CLI-DevTool
|
5a69ba89c0657ccaa7a75d60686465106b1453e7
|
[
"Unlicense"
] | null | null | null |
#ifndef CLI_DEV_PCB_H
#define CLI_DEV_PCB_H
#include <stdio.h>
#include <sstream>
#include "command/param_comple/behavior_base.h"
namespace clidevt {
class FileListBehavior : public ParameterBehavior {
class SpecialCharEscaper {
public:
std::string operator()(std::string str) {
std::string ret;
std::string::iterator ite = str.begin();
for(; ite != str.end(); ++ite) {
switch(*ite) {
case ' ':
ret += "\\ ";
break;
case '\\':
ret += "\\\\";
break;
case '|':
ret += "\\|";
break;
case '<':
ret += "\\<";
break;
case '>':
ret += "\\>";
break;
case '\"':
ret += "\\\"";
break;
case '\'':
ret += "\\\'";
break;
default:
ret += *ite;
break;
}
}
return ret;
}
};
public:
enum CandidateType {
DIRECTORY = 1,
EXECUTABLE = 2,
NON_EXECUTABLE = 4,
SYMBOLIC_LINK = 8,
ALL = 15
};
FileListBehavior() : candidateType_(ALL) {}
virtual ~FileListBehavior() {}
void setCandidatesType(int type) {
candidateType_ = type;
}
virtual void getParamCandidates(std::vector<std::string>& inputtedList, std::string inputting, std::vector<std::string>& candidates) const;
virtual void afterCompletionHook(std::vector<std::string>& candidates) const {
stripParentPath(candidates);
}
virtual void stripParentPath(std::vector<std::string>& candidates) const;
virtual void stripFile(std::vector<std::string>& candidates) const;
private:
int candidateType_;
};
}
#endif /* end of include guard */
| 26.481481
| 143
| 0.435431
|
[
"vector"
] |
794831b2191242116fb1c1f3dedcd6f1d28d8122
| 13,034
|
h
|
C
|
chrome/browser/sync/profile_sync_service.h
|
rwatson/chromium-capsicum
|
b03da8e897f897c6ad2cda03ceda217b760fd528
|
[
"BSD-3-Clause"
] | 11
|
2015-03-20T04:08:08.000Z
|
2021-11-15T15:51:36.000Z
|
chrome/browser/sync/profile_sync_service.h
|
rwatson/chromium-capsicum
|
b03da8e897f897c6ad2cda03ceda217b760fd528
|
[
"BSD-3-Clause"
] | null | null | null |
chrome/browser/sync/profile_sync_service.h
|
rwatson/chromium-capsicum
|
b03da8e897f897c6ad2cda03ceda217b760fd528
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_
#define CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_
#include <string>
#include <map>
#include <vector>
#include "base/basictypes.h"
#include "base/file_path.h"
#include "base/observer_list.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/google_service_auth_error.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/sync/glue/change_processor.h"
#include "chrome/browser/sync/glue/model_associator.h"
#include "chrome/browser/sync/glue/sync_backend_host.h"
#include "chrome/browser/sync/sync_setup_wizard.h"
#include "chrome/common/notification_registrar.h"
#include "googleurl/src/gurl.h"
class CommandLine;
class MessageLoop;
class Profile;
namespace browser_sync {
class UnrecoverableErrorHandler {
public:
// Call this when normal operation detects that the bookmark model and the
// syncer model are inconsistent, or similar. The ProfileSyncService will
// try to avoid doing any work to avoid crashing or corrupting things
// further, and will report an error status if queried.
virtual void OnUnrecoverableError() = 0;
protected:
virtual ~UnrecoverableErrorHandler() { }
};
}
// Various UI components such as the New Tab page can be driven by observing
// the ProfileSyncService through this interface.
class ProfileSyncServiceObserver {
public:
// When one of the following events occurs, OnStateChanged() is called.
// Observers should query the service to determine what happened.
// - We initialized successfully.
// - There was an authentication error and the user needs to reauthenticate.
// - The sync servers are unavailable at this time.
// - Credentials are now in flight for authentication.
virtual void OnStateChanged() = 0;
protected:
virtual ~ProfileSyncServiceObserver() { }
};
// ProfileSyncService is the layer between browser subsystems like bookmarks,
// and the sync backend.
class ProfileSyncService : public NotificationObserver,
public browser_sync::SyncFrontend,
public browser_sync::UnrecoverableErrorHandler {
public:
typedef ProfileSyncServiceObserver Observer;
typedef browser_sync::SyncBackendHost::Status Status;
enum SyncEventCodes {
MIN_SYNC_EVENT_CODE = 0,
// Events starting the sync service.
START_FROM_NTP = 1, // Sync was started from the ad in NTP
START_FROM_WRENCH = 2, // Sync was started from the Wrench menu.
START_FROM_OPTIONS = 3, // Sync was started from Wrench->Options.
START_FROM_BOOKMARK_MANAGER = 4, // Sync was started from Bookmark manager.
// Events regarding cancelation of the signon process of sync.
CANCEL_FROM_SIGNON_WITHOUT_AUTH = 10, // Cancelled before submitting
// username and password.
CANCEL_DURING_SIGNON = 11, // Cancelled after auth.
CANCEL_DURING_SIGNON_AFTER_MERGE = 12, // Cancelled during merge.
// Events resulting in the stoppage of sync service.
STOP_FROM_OPTIONS = 20, // Sync was stopped from Wrench->Options.
// Miscellaneous events caused by sync service.
MERGE_AND_SYNC_NEEDED = 30,
MAX_SYNC_EVENT_CODE
};
explicit ProfileSyncService(Profile* profile);
virtual ~ProfileSyncService();
// Initializes the object. This should be called every time an object of this
// class is constructed.
void Initialize();
// Enables/disables sync for user.
virtual void EnableForUser();
virtual void DisableForUser();
// Whether sync is enabled by user or not.
bool HasSyncSetupCompleted() const;
void SetSyncSetupCompleted();
// NotificationObserver implementation.
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details);
// SyncFrontend implementation.
virtual void OnBackendInitialized();
virtual void OnSyncCycleCompleted();
virtual void OnAuthError();
// Called when a user enters credentials through UI.
virtual void OnUserSubmittedAuth(const std::string& username,
const std::string& password,
const std::string& captcha);
// Called when a user decides whether to merge and sync or abort.
virtual void OnUserAcceptedMergeAndSync();
// Called when a user cancels any setup dialog (login, merge and sync, etc).
virtual void OnUserCancelledDialog();
// Get various information for displaying in the user interface.
browser_sync::SyncBackendHost::StatusSummary QuerySyncStatusSummary();
browser_sync::SyncBackendHost::Status QueryDetailedSyncStatus();
const GoogleServiceAuthError& GetAuthError() const {
return last_auth_error_;
}
// Displays a dialog for the user to enter GAIA credentials and attempt
// re-authentication, and returns true if it actually opened the dialog.
// Returns false if a dialog is already showing, an auth attempt is in
// progress, the sync system is already authenticated, or some error
// occurred preventing the action. We make it the duty of ProfileSyncService
// to open the dialog to easily ensure only one is ever showing.
bool SetupInProgress() const {
return !HasSyncSetupCompleted() && WizardIsVisible();
}
bool WizardIsVisible() const {
return wizard_.IsVisible();
}
void ShowLoginDialog();
// Pretty-printed strings for a given StatusSummary.
static std::wstring BuildSyncStatusSummaryText(
const browser_sync::SyncBackendHost::StatusSummary& summary);
// Returns true if the SyncBackendHost has told us it's ready to accept
// changes.
// TODO(timsteele): What happens if the bookmark model is loaded, a change
// takes place, and the backend isn't initialized yet?
bool sync_initialized() const { return backend_initialized_; }
bool unrecoverable_error_detected() const {
return unrecoverable_error_detected_;
}
bool UIShouldDepictAuthInProgress() const {
return is_auth_in_progress_;
}
// A timestamp marking the last time the service observed a transition from
// the SYNCING state to the READY state. Note that this does not reflect the
// last time we polled the server to see if there were any changes; the
// timestamp is only snapped when syncing takes place and we download or
// upload some bookmark entity.
const base::Time& last_synced_time() const { return last_synced_time_; }
// Returns a user-friendly string form of last synced time (in minutes).
std::wstring GetLastSyncedTimeString() const;
// Returns the authenticated username of the sync user, or empty if none
// exists. It will only exist if the authentication service provider (e.g
// GAIA) has confirmed the username is authentic.
virtual string16 GetAuthenticatedUsername() const;
const std::string& last_attempted_user_email() const {
return last_attempted_user_email_;
}
// The profile we are syncing for.
Profile* profile() { return profile_; }
// Adds/removes an observer. ProfileSyncService does not take ownership of
// the observer.
void AddObserver(Observer* observer);
void RemoveObserver(Observer* observer);
// Record stats on various events.
static void SyncEvent(SyncEventCodes code);
// Returns whether sync is enabled. Sync can be enabled/disabled both
// at compile time (e.g., on a per-OS basis) or at run time (e.g.,
// command-line switches).
static bool IsSyncEnabled();
// UnrecoverableErrorHandler implementation.
virtual void OnUnrecoverableError();
browser_sync::SyncBackendHost* backend() { return backend_.get(); }
protected:
// Call this after any of the subsystems being synced (the bookmark
// model and the sync backend) finishes its initialization. When everything
// is ready, this function will bootstrap the subsystems so that they are
// initially in sync, and start forwarding changes between the two models.
void StartProcessingChangesIfReady();
// Returns whether processing changes is allowed. Check this before doing
// any model-modifying operations.
bool ShouldPushChanges();
// Starts up the backend sync components.
void StartUp();
// Shuts down the backend sync components.
// |sync_disabled| indicates if syncing is being disabled or not.
void Shutdown(bool sync_disabled);
// Methods to register and remove preferences.
void RegisterPreferences();
void ClearPreferences();
// Tests need to override this.
virtual void InitializeBackend();
template <class AssociatorImpl, class ChangeProcessorImpl>
void InstallGlue() {
model_associator_->CreateAndRegisterPerDataTypeImpl<AssociatorImpl>();
// TODO(tim): Keep a map instead of a set so we can register/unregister
// data type specific ChangeProcessors, once we have more than one.
STLDeleteElements(processors());
ChangeProcessorImpl* processor = new ChangeProcessorImpl(this);
change_processors_.insert(processor);
processor->set_model_associator(
model_associator_->GetImpl<AssociatorImpl>());
}
browser_sync::ModelAssociator* associator() {
return model_associator_.get();
}
std::set<browser_sync::ChangeProcessor*>* processors() {
return &change_processors_;
}
// We keep track of the last auth error observed so we can cover up the first
// "expected" auth failure from observers.
// TODO(timsteele): Same as expecting_first_run_auth_needed_event_. Remove
// this!
GoogleServiceAuthError last_auth_error_;
// Cache of the last name the client attempted to authenticate.
std::string last_attempted_user_email_;
private:
friend class ProfileSyncServiceTest;
friend class ProfileSyncServiceTestHarness;
friend class TestModelAssociator;
FRIEND_TEST(ProfileSyncServiceTest, UnrecoverableErrorSuspendsService);
// Initializes the various settings from the command line.
void InitSettings();
// Whether the sync merge warning should be shown.
bool MergeAndSyncAcceptanceNeeded() const;
// Sets the last synced time to the current time.
void UpdateLastSyncedTime();
// When running inside Chrome OS, extract the LSID cookie from the cookie
// store to bootstrap the authentication process.
std::string GetLsidForAuthBootstraping();
// Time at which we begin an attempt a GAIA authorization.
base::TimeTicks auth_start_time_;
// Time at which error UI is presented for the new tab page.
base::TimeTicks auth_error_time_;
// The profile whose data we are synchronizing.
Profile* profile_;
// TODO(ncarter): Put this in a profile, once there is UI for it.
// This specifies where to find the sync server.
GURL sync_service_url_;
// The last time we detected a successful transition from SYNCING state.
// Our backend notifies us whenever we should take a new snapshot.
base::Time last_synced_time_;
// Our asynchronous backend to communicate with sync components living on
// other threads.
scoped_ptr<browser_sync::SyncBackendHost> backend_;
// Model association manager instance.
scoped_ptr<browser_sync::ModelAssociator> model_associator_;
// The change processors that handle the different data types.
std::set<browser_sync::ChangeProcessor*> change_processors_;
NotificationRegistrar registrar_;
// Whether the SyncBackendHost has been initialized.
bool backend_initialized_;
// Set to true when the user first enables sync, and we are waiting for
// syncapi to give us the green light on providing credentials for the first
// time. It is set back to false as soon as we get this message, and is
// false all other times so we don't have to persist this value as it will
// get initialized to false.
// TODO(timsteele): Remove this by way of starting the wizard when enabling
// sync *before* initializing the backend. syncapi will need to change, but
// it means we don't have to wait for the first AuthError; if we ever get
// one, it is actually an error and this bool isn't needed.
bool expecting_first_run_auth_needed_event_;
// Various pieces of UI query this value to determine if they should show
// an "Authenticating.." type of message. We are the only central place
// all auth attempts funnel through, so it makes sense to provide this.
// As its name suggests, this should NOT be used for anything other than UI.
bool is_auth_in_progress_;
SyncSetupWizard wizard_;
// True if an unrecoverable error (e.g. violation of an assumed invariant)
// occurred during syncer operation. This value should be checked before
// doing any work that might corrupt things further.
bool unrecoverable_error_detected_;
ObserverList<Observer> observers_;
DISALLOW_COPY_AND_ASSIGN(ProfileSyncService);
};
#endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_
| 38.222874
| 80
| 0.745205
|
[
"object",
"vector",
"model"
] |
79534425d7ce3d80cc77ed972c5ef225d985bd04
| 1,197
|
h
|
C
|
Service/IMicroService.h
|
ttppren-github/MicroServiceContainer
|
78d2c7e848413fcc7d5f8ae42d18835e74c06bef
|
[
"MIT"
] | null | null | null |
Service/IMicroService.h
|
ttppren-github/MicroServiceContainer
|
78d2c7e848413fcc7d5f8ae42d18835e74c06bef
|
[
"MIT"
] | 2
|
2019-11-21T01:28:24.000Z
|
2019-11-26T01:58:55.000Z
|
Service/IMicroService.h
|
ttppren-github/MicroServiceContainer
|
78d2c7e848413fcc7d5f8ae42d18835e74c06bef
|
[
"MIT"
] | 4
|
2019-11-13T09:21:10.000Z
|
2019-11-22T05:51:47.000Z
|
#ifndef __ELASTOS_IMICROSERVICE_H__
#define __ELASTOS_IMICROSERVICE_H__
#include <string>
#include <vector>
#include <memory>
namespace elastos {
class IMicroService {
public:
enum OperationType {
OperationType_Encrypt = 0,
OperationType_Decrypt,
OperationType_Sign,
OperationType_Verify
};
class DataHandler {
public:
virtual std::shared_ptr<std::vector<uint8_t>> EncryptData(const std::vector<uint8_t>& data) = 0;
virtual std::shared_ptr<std::vector<uint8_t>> DecryptData(const std::vector<uint8_t>& cipherData) = 0;
virtual std::shared_ptr<std::vector<uint8_t>> SignData(const std::vector<uint8_t>& data) = 0;
virtual bool VerifyData(const std::vector<uint8_t>& data, const std::vector<uint8_t>& signedData) = 0;
};
public:
virtual int Start() = 0;
virtual int Stop() = 0;
virtual int HandleMessage(const std::string& did, const std::string& msg) = 0;
virtual std::shared_ptr<std::vector<uint8_t>> HandleData(int type, const std::vector<uint8_t>& data) = 0;
virtual void SetDataHandler(std::shared_ptr<DataHandler>& handler) = 0;
};
}
#endif //__ELASTOS_IMICROSERVICE_H__
| 24.428571
| 110
| 0.691729
|
[
"vector"
] |
79652ffea7c23660381aaa34a653ba8dfeb3d63c
| 1,240
|
h
|
C
|
include/geometrycentral/pointcloud/point_cloud_io.h
|
softwarecapital/geometry-central
|
b4743b4662018d8fa483b31ff4a3af5699db3e93
|
[
"MIT"
] | 539
|
2018-02-19T16:38:26.000Z
|
2022-03-31T06:56:22.000Z
|
include/geometrycentral/pointcloud/point_cloud_io.h
|
softwarecapital/geometry-central
|
b4743b4662018d8fa483b31ff4a3af5699db3e93
|
[
"MIT"
] | 88
|
2018-11-30T13:19:35.000Z
|
2022-03-23T18:40:33.000Z
|
include/geometrycentral/pointcloud/point_cloud_io.h
|
softwarecapital/geometry-central
|
b4743b4662018d8fa483b31ff4a3af5699db3e93
|
[
"MIT"
] | 74
|
2018-05-12T17:57:04.000Z
|
2022-03-21T15:01:26.000Z
|
#pragma once
#include "geometrycentral/pointcloud/point_cloud.h"
#include "geometrycentral/pointcloud/point_position_geometry.h"
namespace geometrycentral {
namespace pointcloud {
// === Readers ===
// Read from a file by name. Type can be optionally inferred from filename.
std::tuple<std::unique_ptr<PointCloud>, std::unique_ptr<PointPositionGeometry>> readPointCloud(std::string filename,
std::string type = "");
// Same as above, but from an istream. Must specify type.
std::tuple<std::unique_ptr<PointCloud>, std::unique_ptr<PointPositionGeometry>> readPointCloud(std::istream& in,
std::string type);
// === Writers ===
// Write to file by name. Type can be optionally inferred from filename.
void writePointCloud(PointCloud& cloud, PointPositionGeometry& geometry, std::string filename, std::string type = "");
// Same as above, to to an ostream. Must specify type.
void writePointCloud(PointCloud& cloud, PointPositionGeometry& geometry, std::ostream& out, std::string type);
} // namespace pointcloud
} // namespace geometrycentral
| 41.333333
| 118
| 0.645161
|
[
"geometry"
] |
79695b32f0fb2efc208791365718832ec2f58062
| 28,375
|
c
|
C
|
3rdparty/experimental/gui/littlevGL/lvgl/lv_objx/lv_tabview.c
|
jinlongliu/AliOS-Things
|
ce051172a775f987183e7aca88bb6f3b809ea7b0
|
[
"Apache-2.0"
] | 19
|
2019-03-25T15:12:48.000Z
|
2022-03-09T08:32:06.000Z
|
3rdparty/experimental/gui/littlevGL/lvgl/lv_objx/lv_tabview.c
|
IamBaoMouMou/AliOS-Things
|
195a9160b871b3d78de6f8cf6c2ab09a71977527
|
[
"Apache-2.0"
] | 3
|
2018-12-17T13:06:46.000Z
|
2018-12-28T01:40:59.000Z
|
3rdparty/experimental/gui/littlevGL/lvgl/lv_objx/lv_tabview.c
|
IamBaoMouMou/AliOS-Things
|
195a9160b871b3d78de6f8cf6c2ab09a71977527
|
[
"Apache-2.0"
] | 9
|
2019-07-12T02:50:10.000Z
|
2021-08-20T17:24:36.000Z
|
/**
* @file lv_tab.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../../lv_conf.h"
#if USE_LV_TABVIEW != 0
#include "lv_tabview.h"
#include "lv_btnm.h"
#include "../lv_themes/lv_theme.h"
#include "../lv_misc/lv_anim.h"
/*********************
* DEFINES
*********************/
#if USE_LV_ANIMATION
#ifndef LV_TABVIEW_ANIM_TIME
#define LV_TABVIEW_ANIM_TIME \
300 /*Animation time of focusing to the a list element [ms] (0: no \
animation) */
#endif
#else
#undef LV_TABVIEW_ANIM_TIME
#define LV_TABVIEW_ANIM_TIME 0 /*No animations*/
#endif
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static lv_res_t lv_tabview_signal(lv_obj_t *tabview, lv_signal_t sign,
void *param);
static lv_res_t tabpage_signal(lv_obj_t *tab_page, lv_signal_t sign,
void *param);
static lv_res_t tabpage_scrl_signal(lv_obj_t *tab_scrl, lv_signal_t sign,
void *param);
static void tabpage_pressed_handler(lv_obj_t *tabview, lv_obj_t *tabpage);
static void tabpage_pressing_handler(lv_obj_t *tabview, lv_obj_t *tabpage);
static void tabpage_press_lost_handler(lv_obj_t *tabview, lv_obj_t *tabpage);
static lv_res_t tab_btnm_action(lv_obj_t *tab_btnm, const char *tab_name);
static void tabview_realign(lv_obj_t *tabview);
/**********************
* STATIC VARIABLES
**********************/
static lv_signal_func_t ancestor_signal;
static lv_signal_func_t page_signal;
static lv_signal_func_t page_scrl_signal;
static const char *tab_def[] = { "" };
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Create a Tab view object
* @param par pointer to an object, it will be the parent of the new tab
* @param copy pointer to a tab object, if not NULL then the new object will be
* copied from it
* @return pointer to the created tab
*/
lv_obj_t *lv_tabview_create(lv_obj_t *par, lv_obj_t *copy)
{
/*Create the ancestor of tab*/
lv_obj_t *new_tabview = lv_obj_create(par, copy);
lv_mem_assert(new_tabview);
if (ancestor_signal == NULL)
ancestor_signal = lv_obj_get_signal_func(new_tabview);
/*Allocate the tab type specific extended data*/
lv_tabview_ext_t *ext =
lv_obj_allocate_ext_attr(new_tabview, sizeof(lv_tabview_ext_t));
lv_mem_assert(ext);
/*Initialize the allocated 'ext' */
ext->drag_hor = 0;
ext->draging = 0;
ext->slide_enable = 1;
ext->tab_cur = 0;
ext->point_last.x = 0;
ext->point_last.y = 0;
ext->content = NULL;
ext->indic = NULL;
ext->btns = NULL;
ext->tab_load_action = NULL;
ext->anim_time = LV_TABVIEW_ANIM_TIME;
ext->tab_name_ptr = lv_mem_alloc(sizeof(char *));
ext->tab_name_ptr[0] = "";
ext->tab_cnt = 0;
/*The signal and design functions are not copied so set them here*/
lv_obj_set_signal_func(new_tabview, lv_tabview_signal);
/*Init the new tab tab*/
if (copy == NULL) {
lv_obj_set_size(new_tabview, LV_HOR_RES, LV_VER_RES);
ext->btns = lv_btnm_create(new_tabview, NULL);
lv_obj_set_height(ext->btns, 3 * LV_DPI / 4);
lv_btnm_set_map(ext->btns, tab_def);
lv_btnm_set_action(ext->btns, tab_btnm_action);
lv_btnm_set_toggle(ext->btns, true, 0);
ext->indic = lv_obj_create(ext->btns, NULL);
lv_obj_set_width(ext->indic, LV_DPI);
lv_obj_align(ext->indic, ext->btns, LV_ALIGN_IN_BOTTOM_LEFT, 0, 0);
lv_obj_set_click(ext->indic, false);
ext->content = lv_cont_create(new_tabview, NULL);
lv_cont_set_fit(ext->content, true, false);
lv_cont_set_layout(ext->content, LV_LAYOUT_ROW_T);
lv_cont_set_style(ext->content, &lv_style_transp_tight);
lv_obj_set_height(ext->content,
LV_VER_RES - lv_obj_get_height(ext->btns));
lv_obj_align(ext->content, ext->btns, LV_ALIGN_OUT_BOTTOM_LEFT, 0, 0);
/*Set the default styles*/
lv_theme_t *th = lv_theme_get_current();
if (th) {
lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_BG,
th->tabview.bg);
lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_INDIC,
th->tabview.indic);
lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_BTN_BG,
th->tabview.btn.bg);
lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_BTN_REL,
th->tabview.btn.rel);
lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_BTN_PR,
th->tabview.btn.pr);
lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_BTN_TGL_REL,
th->tabview.btn.tgl_rel);
lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_BTN_TGL_PR,
th->tabview.btn.tgl_pr);
} else {
lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_BG,
&lv_style_plain);
lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_BTN_BG,
&lv_style_transp);
lv_tabview_set_style(new_tabview, LV_TABVIEW_STYLE_INDIC,
&lv_style_plain_color);
}
}
/*Copy an existing tab view*/
else {
lv_tabview_ext_t *copy_ext = lv_obj_get_ext_attr(copy);
ext->point_last.x = 0;
ext->point_last.y = 0;
ext->btns = lv_btnm_create(new_tabview, copy_ext->btns);
ext->indic = lv_obj_create(ext->btns, copy_ext->indic);
ext->content = lv_cont_create(new_tabview, copy_ext->content);
ext->anim_time = copy_ext->anim_time;
ext->tab_load_action = copy_ext->tab_load_action;
ext->tab_name_ptr = lv_mem_alloc(sizeof(char *));
ext->tab_name_ptr[0] = "";
lv_btnm_set_map(ext->btns, ext->tab_name_ptr);
uint16_t i;
lv_obj_t *new_tab;
lv_obj_t *copy_tab;
for (i = 0; i < copy_ext->tab_cnt; i++) {
new_tab =
lv_tabview_add_tab(new_tabview, copy_ext->tab_name_ptr[i]);
copy_tab = lv_tabview_get_tab(copy, i);
lv_page_set_style(new_tab, LV_PAGE_STYLE_BG,
lv_page_get_style(copy_tab, LV_PAGE_STYLE_BG));
lv_page_set_style(new_tab, LV_PAGE_STYLE_SCRL,
lv_page_get_style(copy_tab, LV_PAGE_STYLE_SCRL));
lv_page_set_style(new_tab, LV_PAGE_STYLE_SB,
lv_page_get_style(copy_tab, LV_PAGE_STYLE_SB));
}
/*Refresh the style with new signal function*/
lv_obj_refresh_style(new_tabview);
}
return new_tabview;
}
/*======================
* Add/remove functions
*=====================*/
/**
* Add a new tab with the given name
* @param tabview pointer to Tab view object where to ass the new tab
* @param name the text on the tab button
* @return pointer to the created page object (lv_page). You can create your
* content here
*/
lv_obj_t *lv_tabview_add_tab(lv_obj_t *tabview, const char *name)
{
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
/*Create the container page*/
lv_obj_t *h = lv_page_create(ext->content, NULL);
lv_obj_set_size(h, lv_obj_get_width(tabview),
lv_obj_get_height(ext->content));
lv_page_set_sb_mode(h, LV_SB_MODE_AUTO);
lv_page_set_style(h, LV_PAGE_STYLE_BG, &lv_style_transp);
lv_page_set_style(h, LV_PAGE_STYLE_SCRL, &lv_style_transp);
if (page_signal == NULL)
page_signal = lv_obj_get_signal_func(h);
if (page_scrl_signal == NULL)
page_scrl_signal = lv_obj_get_signal_func(lv_page_get_scrl(h));
lv_obj_set_signal_func(h, tabpage_signal);
lv_obj_set_signal_func(lv_page_get_scrl(h), tabpage_scrl_signal);
/*Extend the button matrix map with the new name*/
char *name_dm;
if ((name[0] & LV_BTNM_CTRL_MASK) ==
LV_BTNM_CTRL_CODE) { /*If control byte presented let is*/
name_dm =
lv_mem_alloc(strlen(name) + 1); /*+1 for the the closing '\0' */
strcpy(name_dm, name);
} else { /*Set a no long press control byte is not presented*/
name_dm = lv_mem_alloc(
strlen(name) +
2); /*+1 for the the closing '\0' and +1 for the control byte */
name_dm[0] = '\221';
strcpy(&name_dm[1], name);
}
ext->tab_cnt++;
ext->tab_name_ptr =
lv_mem_realloc(ext->tab_name_ptr, sizeof(char *) * (ext->tab_cnt + 1));
ext->tab_name_ptr[ext->tab_cnt - 1] = name_dm;
ext->tab_name_ptr[ext->tab_cnt] = "";
lv_btnm_set_map(ext->btns, ext->tab_name_ptr);
/*Modify the indicator size*/
lv_style_t *style_tabs = lv_obj_get_style(ext->btns);
lv_coord_t indic_width =
(lv_obj_get_width(tabview) -
style_tabs->body.padding.inner * (ext->tab_cnt - 1) -
2 * style_tabs->body.padding.hor) /
ext->tab_cnt;
lv_obj_set_width(ext->indic, indic_width);
lv_obj_set_x(ext->indic, indic_width * ext->tab_cur +
style_tabs->body.padding.inner * ext->tab_cur +
style_tabs->body.padding.hor);
/*Set the first btn as active*/
if (ext->tab_cnt == 1) {
ext->tab_cur = 0;
lv_tabview_set_tab_act(tabview, 0, false);
tabview_realign(tabview); /*To set the proper btns height*/
}
return h;
}
/*=====================
* Setter functions
*====================*/
/**
* Set a new tab
* @param tabview pointer to Tab view object
* @param id index of a tab to load
* @param anim_en true: set with sliding animation; false: set immediately
*/
void lv_tabview_set_tab_act(lv_obj_t *tabview, uint16_t id, bool anim_en)
{
#if USE_LV_ANIMATION == 0
anim_en = false;
#endif
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
lv_style_t *style = lv_obj_get_style(ext->content);
if (id >= ext->tab_cnt)
id = ext->tab_cnt - 1;
if (ext->tab_load_action)
ext->tab_load_action(tabview, id);
ext->tab_cur = id;
lv_coord_t cont_x =
-(lv_obj_get_width(tabview) * id + style->body.padding.inner * id +
style->body.padding.hor);
if (ext->anim_time == 0 || anim_en == false) {
lv_obj_set_x(ext->content, cont_x);
} else {
#if USE_LV_ANIMATION
lv_anim_t a;
a.var = ext->content;
a.start = lv_obj_get_x(ext->content);
a.end = cont_x;
a.fp = (lv_anim_fp_t)lv_obj_set_x;
a.path = lv_anim_path_linear;
a.end_cb = NULL;
a.act_time = 0;
a.time = ext->anim_time;
a.playback = 0;
a.playback_pause = 0;
a.repeat = 0;
a.repeat_pause = 0;
lv_anim_create(&a);
#endif
}
/*Move the indicator*/
lv_coord_t indic_width = lv_obj_get_width(ext->indic);
lv_style_t *tabs_style = lv_obj_get_style(ext->btns);
lv_coord_t indic_x = indic_width * id +
tabs_style->body.padding.inner * id +
tabs_style->body.padding.hor;
if (ext->anim_time == 0 || anim_en == false) {
lv_obj_set_x(ext->indic, indic_x);
} else {
#if USE_LV_ANIMATION
lv_anim_t a;
a.var = ext->indic;
a.start = lv_obj_get_x(ext->indic);
a.end = indic_x;
a.fp = (lv_anim_fp_t)lv_obj_set_x;
a.path = lv_anim_path_linear;
a.end_cb = NULL;
a.act_time = 0;
a.time = ext->anim_time;
a.playback = 0;
a.playback_pause = 0;
a.repeat = 0;
a.repeat_pause = 0;
lv_anim_create(&a);
#endif
}
lv_btnm_set_toggle(ext->btns, true, ext->tab_cur);
}
/**
* Set an action to call when a tab is loaded (Good to create content only if
* required) lv_tabview_get_act() still gives the current (old) tab (to remove
* content from here)
* @param tabview pointer to a tabview object
* @param action pointer to a function to call when a btn is loaded
*/
void lv_tabview_set_tab_load_action(lv_obj_t *tabview,
lv_tabview_action_t action)
{
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
ext->tab_load_action = action;
}
/**
* Enable horizontal sliding with touch pad
* @param tabview pointer to Tab view object
* @param en true: enable sliding; false: disable sliding
*/
void lv_tabview_set_sliding(lv_obj_t *tabview, bool en)
{
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
ext->slide_enable = en == false ? 0 : 1;
}
/**
* Set the animation time of tab view when a new tab is loaded
* @param tabview pointer to Tab view object
* @param anim_time_ms time of animation in milliseconds
*/
void lv_tabview_set_anim_time(lv_obj_t *tabview, uint16_t anim_time)
{
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
#if USE_LV_ANIMATION == 0
anim_time = 0;
#endif
ext->anim_time = anim_time;
}
/**
* Set the style of a tab view
* @param tabview pointer to a tan view object
* @param type which style should be set
* @param style pointer to the new style
*/
void lv_tabview_set_style(lv_obj_t *tabview, lv_tabview_style_t type,
lv_style_t *style)
{
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
switch (type) {
case LV_TABVIEW_STYLE_BG:
lv_obj_set_style(tabview, style);
break;
case LV_TABVIEW_STYLE_BTN_BG:
lv_btnm_set_style(ext->btns, LV_BTNM_STYLE_BG, style);
tabview_realign(tabview);
break;
case LV_TABVIEW_STYLE_BTN_REL:
lv_btnm_set_style(ext->btns, LV_BTNM_STYLE_BTN_REL, style);
tabview_realign(tabview);
break;
case LV_TABVIEW_STYLE_BTN_PR:
lv_btnm_set_style(ext->btns, LV_BTNM_STYLE_BTN_PR, style);
break;
case LV_TABVIEW_STYLE_BTN_TGL_REL:
lv_btnm_set_style(ext->btns, LV_BTNM_STYLE_BTN_TGL_REL, style);
break;
case LV_TABVIEW_STYLE_BTN_TGL_PR:
lv_btnm_set_style(ext->btns, LV_BTNM_STYLE_BTN_TGL_PR, style);
break;
case LV_TABVIEW_STYLE_INDIC:
lv_obj_set_style(ext->indic, style);
lv_obj_set_height(ext->indic, style->body.padding.inner);
tabview_realign(tabview);
break;
}
}
/*=====================
* Getter functions
*====================*/
/**
* Get the index of the currently active tab
* @param tabview pointer to Tab view object
* @return the active btn index
*/
uint16_t lv_tabview_get_tab_act(lv_obj_t *tabview)
{
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
return ext->tab_cur;
}
/**
* Get the number of tabs
* @param tabview pointer to Tab view object
* @return btn count
*/
uint16_t lv_tabview_get_tab_count(lv_obj_t *tabview)
{
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
return ext->tab_cnt;
}
/**
* Get the page (content area) of a tab
* @param tabview pointer to Tab view object
* @param id index of the btn (>= 0)
* @return pointer to page (lv_page) object
*/
lv_obj_t *lv_tabview_get_tab(lv_obj_t *tabview, uint16_t id)
{
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
uint16_t i = 0;
lv_obj_t *page = lv_obj_get_child_back(ext->content, NULL);
while (page != NULL && i != id) {
i++;
page = lv_obj_get_child_back(ext->content, page);
}
if (i == id)
return page;
return NULL;
}
/**
* Get the tab load action
* @param tabview pointer to a tabview object
* @param return the current btn load action
*/
lv_tabview_action_t lv_tabview_get_tab_load_action(lv_obj_t *tabview)
{
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
return ext->tab_load_action;
}
/**
* Get horizontal sliding is enabled or not
* @param tabview pointer to Tab view object
* @return true: enable sliding; false: disable sliding
*/
bool lv_tabview_get_sliding(lv_obj_t *tabview)
{
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
return ext->slide_enable ? true : false;
}
/**
* Get the animation time of tab view when a new tab is loaded
* @param tabview pointer to Tab view object
* @return time of animation in milliseconds
*/
uint16_t lv_tabview_get_anim_time(lv_obj_t *tabview)
{
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
return ext->anim_time;
}
/**
* Get a style of a tab view
* @param tabview pointer to a ab view object
* @param type which style should be get
* @return style pointer to a style
*/
lv_style_t *lv_tabview_get_style(lv_obj_t *tabview, lv_tabview_style_t type)
{
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
switch (type) {
case LV_TABVIEW_STYLE_BG:
return lv_obj_get_style(tabview);
case LV_TABVIEW_STYLE_BTN_BG:
return lv_btnm_get_style(ext->btns, LV_BTNM_STYLE_BG);
case LV_TABVIEW_STYLE_BTN_REL:
return lv_btnm_get_style(ext->btns, LV_BTNM_STYLE_BTN_REL);
case LV_TABVIEW_STYLE_BTN_PR:
return lv_btnm_get_style(ext->btns, LV_BTNM_STYLE_BTN_PR);
case LV_TABVIEW_STYLE_BTN_TGL_REL:
return lv_btnm_get_style(ext->btns, LV_BTNM_STYLE_BTN_TGL_REL);
case LV_TABVIEW_STYLE_BTN_TGL_PR:
return lv_btnm_get_style(ext->btns, LV_BTNM_STYLE_BTN_TGL_PR);
default:
return NULL;
}
/*To avoid warning*/
return NULL;
}
/**********************
* STATIC FUNCTIONS
**********************/
/**
* Signal function of the Tab view
* @param tabview pointer to a Tab view object
* @param sign a signal type from lv_signal_t enum
* @param param pointer to a signal specific variable
* @return LV_RES_OK: the object is not deleted in the function; LV_RES_INV: the
* object is deleted
*/
static lv_res_t lv_tabview_signal(lv_obj_t *tabview, lv_signal_t sign,
void *param)
{
lv_res_t res;
/* Include the ancient signal function */
res = ancestor_signal(tabview, sign, param);
if (res != LV_RES_OK)
return res;
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
if (sign == LV_SIGNAL_CLEANUP) {
uint8_t i;
for (i = 0; ext->tab_name_ptr[i][0] != '\0'; i++)
lv_mem_free(ext->tab_name_ptr[i]);
lv_mem_free(ext->tab_name_ptr);
ext->tab_name_ptr = NULL;
ext->btns =
NULL; /*These objects were children so they are already invalid*/
ext->content = NULL;
} else if (sign == LV_SIGNAL_CORD_CHG) {
if (ext->content != NULL &&
(lv_obj_get_width(tabview) != lv_area_get_width(param) ||
lv_obj_get_height(tabview) != lv_area_get_height(param))) {
tabview_realign(tabview);
}
} else if (sign == LV_SIGNAL_FOCUS || sign == LV_SIGNAL_DEFOCUS ||
sign == LV_SIGNAL_CONTROLL) {
if (ext->btns) {
ext->btns->signal_func(ext->btns, sign, param);
}
} else if (sign == LV_SIGNAL_GET_TYPE) {
lv_obj_type_t *buf = param;
uint8_t i;
for (i = 0; i < LV_MAX_ANCESTOR_NUM - 1;
i++) { /*Find the last set data*/
if (buf->type[i] == NULL)
break;
}
buf->type[i] = "lv_tabview";
}
return res;
}
/**
* Signal function of a tab's page
* @param tab pointer to a tab page object
* @param sign a signal type from lv_signal_t enum
* @param param pointer to a signal specific variable
* @return LV_RES_OK: the object is not deleted in the function; LV_RES_INV: the
* object is deleted
*/
static lv_res_t tabpage_signal(lv_obj_t *tab_page, lv_signal_t sign,
void *param)
{
lv_res_t res;
/* Include the ancient signal function */
res = page_signal(tab_page, sign, param);
if (res != LV_RES_OK)
return res;
lv_obj_t *cont = lv_obj_get_parent(tab_page);
lv_obj_t *tabview = lv_obj_get_parent(cont);
if (lv_tabview_get_sliding(tabview) == false)
return res;
if (sign == LV_SIGNAL_PRESSED) {
tabpage_pressed_handler(tabview, tab_page);
} else if (sign == LV_SIGNAL_PRESSING) {
tabpage_pressing_handler(tabview, tab_page);
} else if (sign == LV_SIGNAL_RELEASED || sign == LV_SIGNAL_PRESS_LOST) {
tabpage_press_lost_handler(tabview, tab_page);
}
return res;
}
/**
* Signal function of the tab page's scrollable object
* @param tab_scrl pointer to a tab page's scrollable object
* @param sign a signal type from lv_signal_t enum
* @param param pointer to a signal specific variable
* @return LV_RES_OK: the object is not deleted in the function; LV_RES_INV: the
* object is deleted
*/
static lv_res_t tabpage_scrl_signal(lv_obj_t *tab_scrl, lv_signal_t sign,
void *param)
{
lv_res_t res;
/* Include the ancient signal function */
res = page_scrl_signal(tab_scrl, sign, param);
if (res != LV_RES_OK)
return res;
lv_obj_t *tab_page = lv_obj_get_parent(tab_scrl);
lv_obj_t *cont = lv_obj_get_parent(tab_page);
lv_obj_t *tabview = lv_obj_get_parent(cont);
if (lv_tabview_get_sliding(tabview) == false)
return res;
if (sign == LV_SIGNAL_PRESSED) {
tabpage_pressed_handler(tabview, tab_page);
} else if (sign == LV_SIGNAL_PRESSING) {
tabpage_pressing_handler(tabview, tab_page);
} else if (sign == LV_SIGNAL_RELEASED || sign == LV_SIGNAL_PRESS_LOST) {
tabpage_press_lost_handler(tabview, tab_page);
}
return res;
}
/**
* Called when a tab's page or scrollable object is pressed
* @param tabview pointer to the btn view object
* @param tabpage pointer to the page of a btn
*/
static void tabpage_pressed_handler(lv_obj_t *tabview, lv_obj_t *tabpage)
{
(void)tabpage;
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
lv_indev_t *indev = lv_indev_get_act();
lv_indev_get_point(indev, &ext->point_last);
}
/**
* Called when a tab's page or scrollable object is being pressed
* @param tabview pointer to the btn view object
* @param tabpage pointer to the page of a btn
*/
static void tabpage_pressing_handler(lv_obj_t *tabview, lv_obj_t *tabpage)
{
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
lv_indev_t *indev = lv_indev_get_act();
lv_point_t point_act;
lv_indev_get_point(indev, &point_act);
lv_coord_t x_diff = point_act.x - ext->point_last.x;
lv_coord_t y_diff = point_act.y - ext->point_last.y;
if (ext->draging == 0) {
if (x_diff >= LV_INDEV_DRAG_LIMIT || x_diff <= -LV_INDEV_DRAG_LIMIT) {
ext->drag_hor = 1;
ext->draging = 1;
lv_obj_set_drag(lv_page_get_scrl(tabpage), false);
} else if (y_diff >= LV_INDEV_DRAG_LIMIT ||
y_diff <= -LV_INDEV_DRAG_LIMIT) {
ext->drag_hor = 0;
ext->draging = 1;
}
}
if (ext->drag_hor) {
lv_obj_set_x(ext->content, lv_obj_get_x(ext->content) + point_act.x -
ext->point_last.x);
ext->point_last.x = point_act.x;
ext->point_last.y = point_act.y;
/*Move the indicator*/
lv_coord_t indic_width = lv_obj_get_width(ext->indic);
lv_style_t *tabs_style = lv_obj_get_style(ext->btns);
lv_style_t *indic_style = lv_obj_get_style(ext->indic);
lv_coord_t p = ((tabpage->coords.x1 - tabview->coords.x1) *
(indic_width + tabs_style->body.padding.inner)) /
lv_obj_get_width(tabview);
lv_obj_set_x(ext->indic,
indic_width * ext->tab_cur +
tabs_style->body.padding.inner * ext->tab_cur +
indic_style->body.padding.hor - p);
}
}
/**
* Called when a tab's page or scrollable object is released or the press id
* lost
* @param tabview pointer to the btn view object
* @param tabpage pointer to the page of a btn
*/
static void tabpage_press_lost_handler(lv_obj_t *tabview, lv_obj_t *tabpage)
{
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
ext->drag_hor = 0;
ext->draging = 0;
lv_obj_set_drag(lv_page_get_scrl(tabpage), true);
lv_indev_t *indev = lv_indev_get_act();
lv_point_t point_act;
lv_indev_get_point(indev, &point_act);
lv_point_t vect;
lv_indev_get_vect(indev, &vect);
lv_coord_t x_predict = 0;
while (vect.x != 0) {
x_predict += vect.x;
vect.x = vect.x * (100 - LV_INDEV_DRAG_THROW) / 100;
}
lv_coord_t page_x1 = tabpage->coords.x1 - tabview->coords.x1 + x_predict;
lv_coord_t page_x2 = page_x1 + lv_obj_get_width(tabpage);
lv_coord_t treshold = lv_obj_get_width(tabview) / 2;
uint16_t tab_cur = ext->tab_cur;
if (page_x1 > treshold) {
if (tab_cur != 0)
tab_cur--;
} else if (page_x2 < treshold) {
if (tab_cur < ext->tab_cnt - 1)
tab_cur++;
}
lv_tabview_set_tab_act(tabview, tab_cur, true);
}
/**
* Called when a tab button is released
* @param tab_btnm pointer to the tab's button matrix object
* @param id the id of the tab (>= 0)
* @return LV_ACTION_RES_OK because the button matrix in not deleted in the
* function
*/
static lv_res_t tab_btnm_action(lv_obj_t *tab_btnm, const char *tab_name)
{
lv_obj_t *tab = lv_obj_get_parent(tab_btnm);
const char **tabs_map = lv_btnm_get_map(tab_btnm);
uint8_t i = 0;
while (tabs_map[i][0] != '\0') {
if (strcmp(&tabs_map[i][1], tab_name) == 0)
break; /*[1] to skip the control byte*/
i++;
}
lv_tabview_set_tab_act(tab, i, true);
return LV_RES_OK;
}
/**
* Realign and resize the elements of Tab view
* @param tabview pointer to a Tab view object
*/
static void tabview_realign(lv_obj_t *tabview)
{
lv_tabview_ext_t *ext = lv_obj_get_ext_attr(tabview);
lv_obj_set_width(ext->btns, lv_obj_get_width(tabview));
if (ext->tab_cnt != 0) {
lv_style_t *style_btn_bg =
lv_tabview_get_style(tabview, LV_TABVIEW_STYLE_BTN_BG);
lv_style_t *style_btn_rel =
lv_tabview_get_style(tabview, LV_TABVIEW_STYLE_BTN_REL);
/*Set the indicator widths*/
lv_coord_t indic_width =
(lv_obj_get_width(tabview) -
style_btn_bg->body.padding.inner * (ext->tab_cnt - 1) -
2 * style_btn_bg->body.padding.hor) /
ext->tab_cnt;
lv_obj_set_width(ext->indic, indic_width);
/*Set the tabs height*/
lv_coord_t btns_height = lv_font_get_height(style_btn_rel->text.font) +
2 * style_btn_rel->body.padding.ver +
2 * style_btn_bg->body.padding.ver;
lv_obj_set_height(ext->btns, btns_height);
}
lv_obj_set_height(ext->content, lv_obj_get_height(tabview) -
lv_obj_get_height(ext->btns));
lv_obj_align(ext->content, ext->btns, LV_ALIGN_OUT_BOTTOM_LEFT, 0, 0);
lv_obj_t *pages = lv_obj_get_child(ext->content, NULL);
while (pages != NULL) {
if (lv_obj_get_signal_func(pages) ==
tabpage_signal) { /*Be sure adjust only the pages (user can other
things)*/
lv_obj_set_size(pages, lv_obj_get_width(tabview),
lv_obj_get_height(ext->content));
}
pages = lv_obj_get_child(ext->content, pages);
}
lv_obj_align(ext->indic, ext->btns, LV_ALIGN_IN_BOTTOM_LEFT, 0, 0);
lv_tabview_set_tab_act(tabview, ext->tab_cur, false);
}
#endif
| 33.50059
| 80
| 0.618044
|
[
"object"
] |
79843bac816985867c589d6e5c5ba0f33e25efcb
| 2,090
|
h
|
C
|
source/ResourceAspect/include/vxResourceAspect/MaterialFactory.h
|
DennisWandschura/vxEngine
|
1396a65f7328aaed50dd34634c65cac561271b9e
|
[
"MIT"
] | 1
|
2015-11-29T11:38:04.000Z
|
2015-11-29T11:38:04.000Z
|
source/ResourceAspect/include/vxResourceAspect/MaterialFactory.h
|
DennisWandschura/vxEngine
|
1396a65f7328aaed50dd34634c65cac561271b9e
|
[
"MIT"
] | null | null | null |
source/ResourceAspect/include/vxResourceAspect/MaterialFactory.h
|
DennisWandschura/vxEngine
|
1396a65f7328aaed50dd34634c65cac561271b9e
|
[
"MIT"
] | null | null | null |
#pragma once
/*
The MIT License (MIT)
Copyright (c) 2015 Dennis Wandschura
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <vxLib/types.h>
class Material;
namespace Graphics
{
class Texture;
}
template<typename T>
class ResourceManager;
namespace vx
{
template<typename K, typename T,typename C>
class sorted_array;
struct StringID;
class FileEntry;
}
#include <vxEngineLib/FileEntry.h>
#include <vector>
struct MaterialFactoryLoadDescription
{
const char *fileNameWithPath;
const vx::sorted_array<vx::StringID, const Graphics::Texture*, std::less<vx::StringID>>* textureFiles;
std::vector<vx::FileEntry>* missingFiles;
Material* material;
};
struct MissingTextureFile
{
vx::FileEntry fileEntry;
bool srgb;
};
struct MaterialFactoryLoadDescNew
{
const char *fileNameWithPath;
const ResourceManager<Graphics::Texture>* m_textureManager;
MissingTextureFile* missingFiles;
u32* missingFilesCount;
Material* material;
};
class MaterialFactory
{
public:
static bool load(const MaterialFactoryLoadDescription &desc);
static bool load(const MaterialFactoryLoadDescNew &desc);
};
| 26.455696
| 103
| 0.790431
|
[
"vector"
] |
79870dbecbfc209586a1d2209a87b14afee21fa7
| 566
|
h
|
C
|
include/filehandler.h
|
yishihara/Social-Network
|
505c08f544a03bbd32ea1c48a437f5de63c51523
|
[
"MIT"
] | null | null | null |
include/filehandler.h
|
yishihara/Social-Network
|
505c08f544a03bbd32ea1c48a437f5de63c51523
|
[
"MIT"
] | null | null | null |
include/filehandler.h
|
yishihara/Social-Network
|
505c08f544a03bbd32ea1c48a437f5de63c51523
|
[
"MIT"
] | null | null | null |
#ifndef FILEHANDLER_H
#define FILEHANDLER_H
#include <vector>
#include <string>
#include <fstream>
#include <boost/bimap/bimap.hpp>
#include "graph.h"
namespace facebook{
typedef std::vector<std::vector<std::string> > Data;
typedef std::map<std::string, int> ID2INT;
typedef boost::bimaps::bimap<int, std::string> Map;
typedef std::vector<std::string> Name;
Data readFile(std::ifstream &fin, Name &name);
Map createMap(Data data);
socialgraph::Edges createEdges(Data data, Map map);
socialgraph::Graph createGraph(Data data, Map map);
}
#endif
| 18.258065
| 53
| 0.724382
|
[
"vector"
] |
7988250b3cdbf9db272eedb51fbc18bcb427de9b
| 2,634
|
h
|
C
|
Source/RuntimeEditor/CBuildingMenu.h
|
shanefarris/CoreGameEngine
|
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
|
[
"MIT"
] | 3
|
2019-04-12T15:22:53.000Z
|
2022-01-05T02:59:56.000Z
|
Source/RuntimeEditor/CBuildingMenu.h
|
shanefarris/CoreGameEngine
|
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
|
[
"MIT"
] | null | null | null |
Source/RuntimeEditor/CBuildingMenu.h
|
shanefarris/CoreGameEngine
|
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
|
[
"MIT"
] | 2
|
2019-04-10T22:46:21.000Z
|
2020-05-27T16:21:37.000Z
|
#ifndef __CBUILDINGMENU_H__
#define __CBUILDINGMENU_H__
#include "Defines.h"
#include "EditorObjects.h"
#include "CInputListener.h"
#include "MyGui/MyGUI.h"
namespace Core
{
class CBuilding;
class CGameObject;
class CInputKeyEvent;
class CInputMouseEvent;
enum MouseButtonID;
namespace GUI
{
class CGuiStrategy_MyGui;
}
namespace Editor
{
class CBuildingMenu : public CInputKeyListener, public CInputMouseListener
{
public:
CBuildingMenu(GUI::CGuiStrategy_MyGui* Strategy);
~CBuildingMenu();
void SetVisible(bool Visible);
void SetVisible(bool Visible, const SELECTED& Selected, CBuilding* Building = nullptr);
MyGUI::Widget* GetForm() { return frmBuilding; }
private:
bool MouseMoved(const CInputMouseEvent &arg);
bool MousePressed(const CInputMouseEvent &arg, MouseButtonID id);
bool MouseReleased(const CInputMouseEvent &arg, MouseButtonID id);
bool KeyPressed(const CInputKeyEvent &arg);
bool KeyReleased(const CInputKeyEvent &arg);
void cmbBuildingList_ComboAccept(MyGUI::ComboBox* _sender, size_t _index);
void rdoBuildingSphereObstacle_Click(MyGUI::WidgetPtr _sender);
void rdoBuildingBoxObstacle_Click(MyGUI::WidgetPtr _sender);
void btnBuildingPlace_Click(MyGUI::WidgetPtr _sender);
void btnBuildingClose_Click(MyGUI::WidgetPtr _sender);
void cmbBuildingType_ComboAccept(MyGUI::ComboBox* _sender, size_t _index);
void btnBuildingCancel_Click(MyGUI::WidgetPtr _sender);
void btnBuildingSave_Click(MyGUI::WidgetPtr _sender);
void cmbBuildingTeam_ComboAccept(MyGUI::ComboBox* _sender, size_t _index);
void Close();
void Save();
void PopulateMeshList();
void PopulateTypeList();
void PlaceMesh(f32 Width, f32 Height);
void ResetControls();
bool isPlaceMesh; // Is the place mesh btn pressed and shift held down
CBuilding* m_Building; // Currently selected object
SELECTED m_Selected; // The selected object type
GUI::CGuiStrategy_MyGui* m_Strategy;
MyGUI::Widget* frmBuilding;
MyGUI::ComboBoxPtr cmbBuildingList;
MyGUI::ButtonPtr rdoBuildingSphereObstacle;
MyGUI::ButtonPtr rdoBuildingBoxObstacle;
MyGUI::ButtonPtr btnBuildingPlace;
MyGUI::ButtonPtr btnBuildingClose;
MyGUI::ComboBoxPtr cmbBuildingType;
MyGUI::EditPtr txtBuildingName;
MyGUI::ButtonPtr btnBuildingCancel;
MyGUI::ButtonPtr btnBuildingSave;
MyGUI::EditPtr txtBuildingPosX;
MyGUI::EditPtr txtBuildingPosY;
MyGUI::EditPtr txtBuildingPosZ;
MyGUI::EditPtr txtBuildingScaleX;
MyGUI::EditPtr txtBuildingScaleY;
MyGUI::EditPtr txtBuildingScaleZ;
MyGUI::ComboBoxPtr cmbBuildingTeam;
};
}
}
#endif // __CBUILDINGMENU_H__
| 30.275862
| 89
| 0.777525
|
[
"mesh",
"object"
] |
7989643675c6a80d9d7d0d74a36e1e5c83aa9851
| 2,200
|
h
|
C
|
wrappers/wrapper_sdk/sample_typedefs.h
|
adrianmahjour/db2-samples
|
ff984aec81c5c08ce28443d896c0818cfae4f789
|
[
"Apache-2.0"
] | 54
|
2019-08-02T13:15:07.000Z
|
2022-03-21T17:36:48.000Z
|
wrappers/wrapper_sdk/sample_typedefs.h
|
junsulee75/db2-samples
|
d9ee03101cad1f9167eebc1609b4151559124017
|
[
"Apache-2.0"
] | 13
|
2019-07-26T13:51:16.000Z
|
2022-03-25T21:43:52.000Z
|
wrappers/wrapper_sdk/sample_typedefs.h
|
junsulee75/db2-samples
|
d9ee03101cad1f9167eebc1609b4151559124017
|
[
"Apache-2.0"
] | 75
|
2019-07-20T04:53:24.000Z
|
2022-03-23T20:56:55.000Z
|
/**********************************************************************
*
* Source File Name = sample_typedef.h
*
* (C) COPYRIGHT International Business Machines Corp. 2003,2004
* All Rights Reserved
* Licensed Materials - Property of IBM
*
* US Government Users Restricted Rights - Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
* Function = Include File defining:Structures and macros used in sample wrapper
*
* Operating System = All
*
***********************************************************************/
#ifndef __SAMPLE_TYPEDEFS_H__
#define __SAMPLE_TYPEDEFS_H__
#include "sqlcli.h"
// Wrapper Defines
#define SAMPLE_WRAPPER_TYPE 'N' // 'N' For Non-Relational (Generic)
#define SAMPLE_WRAPPER_VERSION 1
// Nickname Defines
#define FILE_PATH_OPTION "FILE_PATH"
// Misc. Defines
#define NULL_WRAPPER "Cannot get wrapper object"
#define NULL_PATH "Data source path is NULL"
#define LSTAT_ERROR "STAT Failed on data source"
#define COLUMN_ERROR "No column info found"
#define ACCESS_ERROR "Unable to read file"
#define DATA_ERROR "Data Error"
#define NOT_FILE_ERROR "Data source is a non-standard file"
#define OPEN_ERROR "File open error"
#define BAD_PRED_OP "Unsupported operator"
#define BAD_COLUMN "Column not found"
#define KEY_EXCEEDS_SIZE "Key exceeds definition size"
#define FILE_SIZE_ERROR "Line in data file exceeds 32k"
// Constants
#define MAX_DECIMAL_SIZE 34
#define MAX_VARCHAR_LENGTH 32672
// enums and structs needed by the different classes.
enum myboolean {NO,YES};
struct columnData
{
sqlint32 type; // This structure is used to
sqluint8 *name; // contain the information about
void *data; // a data element
sqlint32 len;
int precision; // Used with decimal data type
int scale; // Used with decimal data type
};
enum relOperator
{
SQL_EQ,
ALL_ROWS
};
// This is a subset of Sample_Query that is generated by plan_request()
struct Sample_Exec_Descriptor
{
relOperator mPredOperator;
int mNumColumns;
int mKeyVector;
int mBindIndex;
};
#endif
| 27.848101
| 80
| 0.664545
|
[
"object"
] |
798d02695c4994bb328a5f2352d353cf9319ef27
| 2,677
|
h
|
C
|
include/benderrmq.h
|
QwantResearch/auto-complete
|
4dde2380e3a89b2d816529a7add5aebbff9c18be
|
[
"Apache-2.0"
] | 1
|
2019-12-10T10:14:04.000Z
|
2019-12-10T10:14:04.000Z
|
include/benderrmq.h
|
QwantResearch/auto-complete
|
4dde2380e3a89b2d816529a7add5aebbff9c18be
|
[
"Apache-2.0"
] | 1
|
2019-11-27T16:59:47.000Z
|
2019-11-27T16:59:47.000Z
|
include/benderrmq.h
|
QwantResearch/auto-complete
|
4dde2380e3a89b2d816529a7add5aebbff9c18be
|
[
"Apache-2.0"
] | 1
|
2019-12-02T11:32:38.000Z
|
2019-12-02T11:32:38.000Z
|
// -*- mode:c++; c-basic-offset:4 -*-
#if !defined __BENDERRMQ_H
#define __BENDERRMQ_H
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <stack>
#include <stdio.h>
#include <sstream>
#include <assert.h>
#include "types.h"
#include "utils.h"
#include "sparsetable.h"
#include "lookuptables.h"
#include "simplefixedobjectallocator.h"
using namespace std;
#define MIN_SIZE_FOR_BENDER_RMQ 16
class BenderRMQ {
/* For inputs < MIN_SIZE_FOR_BENDER_RMQ in size, we use just the
* sparse table.
*
* For inputs > MIN_SIZE_FOR_BENDER_RMQ in size, we use perform a
* Euler Tour of the input and potentially blow it up to 2x. Let
* the size of the blown up input be 'n' elements. We use 'st' for
* 2n/lg n of the elements and for each block of size (1/2)lg n,
* we use 'lt'. Since 'n' can be at most 2^32, (1/2)lg n can be at
* most 16.
*
*/
SparseTable st;
LookupTables lt;
/* The data after euler tour computation (for +-RMQ) */
vui_t euler;
/* mapping stores the mapping of original indexes to indexes
* within our re-written (using euler tour) structure).
*/
vui_t mapping;
/* Stores the bitmask corresponding to a block of size (1/2)(lg n) */
vui_t table_map;
/* Stores the mapping from +-RMQ indexes to actual indexes */
vui_t rev_mapping;
/* The real length of input that the user gave us */
uint_t len;
int lgn_by_2;
int _2n_lgn;
public:
std::string toGraphViz(BinaryTreeNode* par, BinaryTreeNode *n);
/* This is a destructive function - one which deletes the tree rooted
* at node n
*/
void euler_tour(BinaryTreeNode *n,
vui_t &output, /* Where the output is written. Should be empty */
vui_t &levels, /* Where the level for each node is written. Should be empty */
vui_t &mapping /* mapping stores representative
indexes which maps from the original index to the index
into the euler tour array, which is a +- RMQ */,
vui_t &rev_mapping /* Reverse mapping to go from +-RMQ
indexes to user provided indexes */,
int level = 1);
BinaryTreeNode* make_cartesian_tree(vui_t const &input, SimpleFixedObjectAllocator<BinaryTreeNode> &alloc);
void initialize(vui_t const& elems);
// qf & ql are indexes; both inclusive.
// Return: first -> value, second -> index
pui_t query_max(uint_t qf, uint_t ql);
pui_t naive_query_max(vui_t const& v, int i, int j);
};
#endif // __BENDERRMQ_H
| 30.078652
| 111
| 0.635413
|
[
"vector"
] |
799576ffeeb85323903c0a0f1195442fc3cb74ad
| 1,139
|
h
|
C
|
src/include/lwm2mObjects/3358.h
|
henris42/wakaamaNode
|
0b0200c43528483f709b427466638c9ea1a32cd5
|
[
"MIT"
] | 10
|
2016-05-16T07:48:21.000Z
|
2018-04-27T05:57:32.000Z
|
src/include/lwm2mObjects/3358.h
|
taubel/libWakaamaEmb
|
88758d64e30e8f0044fbf3b4e32731ac994c5731
|
[
"MIT"
] | 13
|
2018-06-12T08:43:17.000Z
|
2019-06-10T11:05:13.000Z
|
src/include/lwm2mObjects/3358.h
|
taubel/libWakaamaEmb
|
88758d64e30e8f0044fbf3b4e32731ac994c5731
|
[
"MIT"
] | 9
|
2019-11-17T01:54:07.000Z
|
2020-12-20T14:05:57.000Z
|
#pragma once
// Automatically generated header file
#include "lwm2m/objects.h"
namespace KnownObjects {
namespace id3358 {
// Custom, overrideable types for Opaque and String resources
/* \brief Class for object 3358 - rrcTimerExpiryEvent
* RRC timer expiry event information
*/
class instance : public Lwm2mObjectInstance {
public:
// 0 - 1 = t3002 = t3013 = t3024 = t3035 = t3046 = t3057 = t3118 = t3209 = t32110 = other
int RrcTimerExpiryEvent;
};
enum class RESID {
RrcTimerExpiryEvent = 0,
};
/* \brief Class for object 3358 - rrcTimerExpiryEvent
* RRC timer expiry event information
*/
class object : public Lwm2mObject<3358, object, instance> {
public:
// 0 - 1 = t3002 = t3013 = t3024 = t3035 = t3046 = t3057 = t3118 = t3209 = t32110 = other
Resource(0, &instance::RrcTimerExpiryEvent, O_RES_R) RrcTimerExpiryEvent;
};
} // end of id namespace
} // end of KnownObjects namespace
inline bool operator== (KnownObjects::id3358::RESID c1, uint16_t c2) { return (uint16_t) c1 == c2; }
inline bool operator== (uint16_t c2, KnownObjects::id3358::RESID c1) { return (uint16_t) c1 == c2; }
| 27.780488
| 100
| 0.698859
|
[
"object"
] |
b2a64d86dd4eb535abcdbb909adc5fdeb642d1eb
| 27,638
|
h
|
C
|
src/utilities/json_JsonUtilities.h
|
mutgos/mutgos_server
|
115270d07db22d320e0b51095e9219f0a0e15ddb
|
[
"MIT"
] | 5
|
2019-02-24T06:42:52.000Z
|
2021-04-09T19:16:24.000Z
|
src/utilities/json_JsonUtilities.h
|
mutgos/mutgos_server
|
115270d07db22d320e0b51095e9219f0a0e15ddb
|
[
"MIT"
] | 40
|
2019-02-24T15:25:54.000Z
|
2021-05-17T04:22:43.000Z
|
src/utilities/json_JsonUtilities.h
|
mutgos/mutgos_server
|
115270d07db22d320e0b51095e9219f0a0e15ddb
|
[
"MIT"
] | 2
|
2019-02-23T22:58:36.000Z
|
2019-02-27T01:27:42.000Z
|
/*
* json_JsonUtilities.h
*/
#ifndef MUTGOS_JSON_JSONUTILITIES_H
#define MUTGOS_JSON_JSONUTILITIES_H
#include <unistd.h>
#include <string>
#include <string.h>
#include <rapidjson/document.h>
#include "osinterface/osinterface_OsTypes.h"
/**
* Creates a JSON array root node, named varname.
* Example: JSON_MAKE_ARRAY_ROOT(my_array);
*/
#ifndef JSON_MAKE_ARRAY_ROOT
#define JSON_MAKE_ARRAY_ROOT(varname) \
mutgos::json::JSONRoot varname(rapidjson::kArrayType)
#endif
/**
* Creates a JSON array root node pointer.
* Example: JSON_MAKE_ARRAY_ROOT_PTR();
*/
#ifndef JSON_MAKE_ARRAY_ROOT_PTR
#define JSON_MAKE_ARRAY_ROOT_PTR() \
new mutgos::json::JSONRoot(rapidjson::kArrayType)
#endif
/**
* Creates a JSON array node, named varname.
* Example: JSON_MAKE_ARRAY_NODE(my_array);
*/
#ifndef JSON_MAKE_ARRAY_NODE
#define JSON_MAKE_ARRAY_NODE(varname) \
mutgos::json::JSONNode varname(rapidjson::kArrayType)
#endif
/**
* Creates a JSON array node pointer.
* Example: JSON_MAKE_ARRAY_NODE();
*/
#ifndef JSON_MAKE_ARRAY_NODE_PTR
#define JSON_MAKE_ARRAY_NODE_PTR() \
new mutgos::json::JSONNode(rapidjson::kArrayType)
#endif
/**
* Creates a JSON map (object) node, named varname.
* Example: JSON_MAKE_MAP_NODE(my_object);
*/
#ifndef JSON_MAKE_MAP_NODE
#define JSON_MAKE_MAP_NODE(varname) \
mutgos::json::JSONNode varname(rapidjson::kObjectType)
#endif
/**
* Creates a JSON map (object) node pointer.
* Example: JSON_MAKE_MAP_NODE();
*/
#ifndef JSON_MAKE_MAP_NODE_PTR
#define JSON_MAKE_MAP_NODE_PTR() \
new mutgos::json::JSONNode(rapidjson::kObjectType)
#endif
/**
* Creates a JSON map (object) root node, named varname.
* Example: JSON_MAKE_MAP_ROOT(my_object);
*/
#ifndef JSON_MAKE_MAP_ROOT
#define JSON_MAKE_MAP_ROOT(varname) \
mutgos::json::JSONRoot varname(rapidjson::kObjectType)
#endif
/**
* Creates a JSON map (object) root node pointer.
* Example: JSON_MAKE_MAP_NODE();
*/
#ifndef JSON_MAKE_MAP_ROOT_PTR
#define JSON_MAKE_MAP_ROOT_PTR() \
new mutgos::json::JSONRoot(rapidjson::kObjectType)
#endif
/**
* Creates a standard JSON node (non-array, non-map), named varname.
* This is not normally needed, since the add_* methods auto-create these.
* Example: JSON_MAKE_NODE(my_node);
*/
#ifndef JSON_MAKE_NODE
#define JSON_MAKE_NODE(varname) \
mutgos::json::JSONNode varname
#endif
// TODO Nulls in strings are not well supported when parsing. Will need to add new methods here, and modify any callers of existing, affected methods.
namespace mutgos
{
namespace json
{
// Forward declarations
//
class JsonParsedObject;
//
// Use these typedefs when referring to any JSON object; never refer to
// the underlying JSON parser library directly to maintain portability.
//
/** A JSON Node, which could be any type */
typedef rapidjson::Value JSONNode;
/** The root of the JSON document tree */
typedef rapidjson::Document JSONRoot;
//
// Static methods to make working with the JSON library easier and portable.
//
/**
* Parses the provided string as JSON.
* @param data_ptr[in] Pointer to the JSON data as a string. Ownership
* of the pointer will pass to this method. The data will be modified.
* @return A pointer to the parsed JSON, or null if error or invalid JSON
* string. Caller must manage the pointer.
*/
JsonParsedObject *parse_json(char * const data_ptr);
/**
* Converts the document into a JSON string.
* @param root[in] The document root to convert to a JSON string.
* @return The document as a JSON string.
*/
std::string write_json(JSONRoot &root);
/**
* Clears an array or map of all contents.
* @param array[out] The array or map to clear.
*/
static void json_clear(JSONNode &json)
{
if (json.IsObject())
{
json.RemoveAllMembers();
}
else if (json.IsArray())
{
json.Clear();
}
}
/**
* Adds key value pair to json. The value must be static and never
* modified (in other words, a program constant).
* @param key[in] The key. Must be const static.
* @param value[in] The const static value.
* @param json[out] The section of JSON being added to.
* @param root[in] The document root.
* @return True if success, false if json isn't a map/object type
* or key is empty.
*/
static bool add_static_key_static_value(
const std::string &key,
const std::string &value,
JSONNode &json,
JSONRoot &root)
{
const bool success = json.IsObject() and (not key.empty());
if (success)
{
json.AddMember(
rapidjson::StringRef(key.c_str(), key.size()),
rapidjson::StringRef(value.c_str(), value.size()),
root.GetAllocator());
}
return success;
}
/**
* Adds key value pair to json.
* @param key[in] The key. Must be const static.
* @param value[in] The value (will be copied).
* @param json[out] The section of JSON being added to.
* @param root[in] The document root.
* @return True if success, false if json isn't a map/object type
* or key is empty.
*/
static bool add_static_key_value(
const std::string &key,
const std::string &value,
JSONNode &json,
JSONRoot &root)
{
const bool success = json.IsObject() and (not key.empty());
if (success)
{
rapidjson::Value val;
val.SetString(value.c_str(), value.size(), root.GetAllocator());
json.AddMember(
rapidjson::StringRef(key.c_str(), key.size()),
val,
root.GetAllocator());
}
return success;
}
/**
* Adds key value pair to json.
* @param key[in] The key (will be copied).
* @param value[in] The value (will be copied).
* @param json[out] The section of JSON being added to.
* @param root[in] The document root.
* @return True if success, false if json isn't a map/object type
* or key is empty.
*/
static bool add_key_value(
const std::string &key,
const std::string &value,
JSONNode &json,
JSONRoot &root)
{
const bool success = json.IsObject() and (not key.empty());
if (success)
{
rapidjson::Value keyVal;
rapidjson::Value val;
keyVal.SetString(key.c_str(), key.size());
val.SetString(value.c_str(), value.size());
json.AddMember(keyVal, val, root.GetAllocator());
}
return success;
}
/**
* Adds key value pair to json.
* @param key[in] The key (will be copied).
* @param value[in,out] The value (will be moved into json). When done,
* this will be empty/unset.
* @param json[out] The section of JSON being added to.
* @param root[in] The document root.
* @return True if success, false if json isn't a map/object type or value
* is unset, or key is empty.
*/
static bool add_key_value(
const std::string &key,
JSONNode &value,
JSONNode &json,
JSONRoot &root)
{
const bool success = json.IsObject() and (not key.empty())
and (not value.IsNull());
if (success)
{
rapidjson::Value keyVal;
keyVal.SetString(key.c_str(), key.size());
json.AddMember(keyVal, value, root.GetAllocator());
}
return success;
}
/**
* Adds key value pair to json.
* @param key[in] The key (will be copied).
* @param value[in,out] The value (will be moved into json). When done,
* this will be empty/unset.
* @param json[out] The section of JSON being added to.
* @param root[in] The document root.
* @return True if success, false if json isn't a map/object type or value
* is unset, or key is empty.
*/
static bool add_static_key_value(
const std::string &key,
JSONNode &value,
JSONNode &json,
JSONRoot &root)
{
const bool success = json.IsObject() and (not key.empty())
and (not value.IsNull());
if (success)
{
json.AddMember(
rapidjson::StringRef(key.c_str(), key.size()),
value,
root.GetAllocator());
}
return success;
}
/**
* Adds key value pair to json.
* @param key[in] The key. Must be const static.
* @param value[in] The value (will be copied).
* @param json[out] The section of JSON being added to.
* @param root[in] The document root.
* @return True if success, false if json isn't a map/object type
* or key is empty.
*/
static bool add_static_key_value(
const std::string &key,
const bool value,
JSONNode &json,
JSONRoot &root)
{
const bool success = json.IsObject() and (not key.empty());
if (success)
{
rapidjson::Value val;
val.SetBool(value);
json.AddMember(
rapidjson::StringRef(key.c_str(), key.size()),
val,
root.GetAllocator());
}
return success;
}
/**
* Adds key value pair to json.
* @param key[in] The key. Must be const static.
* @param value[in] The value (will be copied).
* @param json[out] The section of JSON being added to.
* @param root[in] The document root.
* @return True if success, false if json isn't a map/object type
* or key is empty.
*/
static bool add_static_key_value(
const std::string &key,
const MG_UnsignedInt value,
JSONNode &json,
JSONRoot &root)
{
const bool success = json.IsObject() and (not key.empty());
if (success)
{
rapidjson::Value val;
val.SetUint(value);
json.AddMember(
rapidjson::StringRef(key.c_str(), key.size()),
val,
root.GetAllocator());
}
return success;
}
/**
* Adds key value pair to json.
* @param key[in] The key. Must be const static.
* @param value[in] The value (will be copied).
* @param json[out] The section of JSON being added to.
* @param root[in] The document root.
* @return True if success, false if json isn't a map/object type
* or key is empty.
*/
static bool add_static_key_value(
const std::string &key,
const MG_VeryLongUnsignedInt value,
JSONNode &json,
JSONRoot &root)
{
const bool success = json.IsObject() and (not key.empty());
if (success)
{
rapidjson::Value val;
val.SetInt64(value);
json.AddMember(
rapidjson::StringRef(key.c_str(), key.size()),
val,
root.GetAllocator());
}
return success;
}
/**
* Adds key value pair to json.
* @param key[in] The key. Must be const static.
* @param value[in] The value (will be copied).
* @param json[out] The section of JSON being added to.
* @param root[in] The document root.
* @return True if success, false if json isn't a map/object type
* or key is empty.
*/
static bool add_static_key_value(
const std::string &key,
const MG_SignedInt value,
JSONNode &json,
JSONRoot &root)
{
const bool success = json.IsObject() and (not key.empty());
if (success)
{
rapidjson::Value val;
val.SetInt(value);
json.AddMember(
rapidjson::StringRef(key.c_str(), key.size()),
val,
root.GetAllocator());
}
return success;
}
/**
* Gets a string from json.
* @param key[in] The key to retrieve.
* @param json[in] The JSON the key is retrieved from.
* @param value[out] The value associated with the key. It will
* be empty if the return value is false.
* @return True if found and able to retrieve the value, false if
* not found or of the wrong type.
*/
static bool get_key_value(
const std::string &key,
const JSONNode &json,
std::string &value)
{
bool success = false;
value.clear();
if (json.IsObject())
{
rapidjson::Value::ConstMemberIterator iter =
json.FindMember(key.c_str());
if ((iter != json.MemberEnd()) and iter->value.IsString())
{
value.assign(
iter->value.GetString(),
iter->value.GetStringLength());
success = true;
}
}
return success;
}
/**
* Gets an unsigned int from json.
* @param key[in] The key to retrieve.
* @param json[in] The JSON the key is retrieved from.
* @param value[out] The value associated with the key. It will
* be 0 if the return value is false.
* @return True if found and able to retrieve the value, false if
* not found or of the wrong type.
*/
static bool get_key_value(
const std::string &key,
const JSONNode &json,
MG_UnsignedInt &value)
{
bool success = false;
value = 0;
if (json.IsObject())
{
rapidjson::Value::ConstMemberIterator iter =
json.FindMember(key.c_str());
if ((iter != json.MemberEnd()) and iter->value.IsUint())
{
value = iter->value.GetUint();
success = true;
}
}
return success;
}
/**
* Gets a very long unsigned int from json.
* @param key[in] The key to retrieve.
* @param json[in] The JSON the key is retrieved from.
* @param value[out] The value associated with the key. It will
* be 0 if the return value is false.
* @return True if found and able to retrieve the value, false if
* not found or of the wrong type.
*/
static bool get_key_value(
const std::string &key,
const JSONNode &json,
MG_VeryLongUnsignedInt &value)
{
bool success = false;
value = 0;
if (json.IsObject())
{
rapidjson::Value::ConstMemberIterator iter =
json.FindMember(key.c_str());
if ((iter != json.MemberEnd()) and iter->value.IsUint64())
{
value = iter->value.GetUint64();
success = true;
}
}
return success;
}
/**
* Gets an int from a json.
* @param key[in] The key to retrieve.
* @param json[in] The JSON the key is retrieved from.
* @param value[out] The value associated with the key. It will
* be 0 if the return value is false.
* @return True if found and able to retrieve the value, false if
* not found or of the wrong type.
*/
static bool get_key_value(
const std::string &key,
const JSONNode &json,
MG_SignedInt &value)
{
bool success = false;
value = 0;
if (json.IsObject())
{
rapidjson::Value::ConstMemberIterator iter =
json.FindMember(key.c_str());
if ((iter != json.MemberEnd()) and iter->value.IsInt())
{
value = iter->value.GetInt();
success = true;
}
}
return success;
}
/**
* Gets a bool from json.
* @param key[in] The key to retrieve.
* @param json[in] The JSON the key is retrieved from.
* @param value[out] The value associated with the key. It will
* be false if the return value is false.
* @return True if found and able to retrieve the value, false if
* not found or of the wrong type.
*/
static bool get_key_value(
const std::string &key,
const JSONNode &json,
bool &value)
{
bool success = false;
value = false;
if (json.IsObject())
{
rapidjson::Value::ConstMemberIterator iter =
json.FindMember(key.c_str());
if ((iter != json.MemberEnd()) and iter->value.IsBool())
{
value = iter->value.GetBool();
success = true;
}
}
return success;
}
/**
* Gets a node from json. This is generally used to retrieve arrays
* or objects/maps.
* @param key[in] The key to retrieve.
* @param json[in] The JSON the key is retrieved from.
* @param value[out] The pointer to the node. Ownership of the pointer
* does NOT transfer to the caller (do not delete it). It will be set
* to null if this method returns null.
* @return True if found and able to retrieve the value, false if
* not found or of the wrong type.
*/
static bool get_key_value(
const std::string &key,
const JSONNode &json,
const JSONNode *&value)
{
bool success = false;
value = 0;
if (json.IsObject())
{
rapidjson::Value::ConstMemberIterator iter =
json.FindMember(key.c_str());
if (iter != json.MemberEnd())
{
value = &(iter->value);
success = true;
}
}
return success;
}
/**
* @param json[in] The JSON node to check.
* @return True if node is a map.
*/
static bool is_map(const JSONNode &json)
{
return json.IsObject();
}
/**
* @param json[in] The JSON node to check.
* @return True if node is an array.
*/
static bool is_array(const JSONNode &json)
{
return json.IsArray();
}
/**
* @param array[in] The array to check.
* @return True if JSON array is empty.
*/
static bool array_empty(const JSONNode &array)
{
bool empty = true;
if (is_array(array))
{
empty = array.Empty();
}
return empty;
}
/**
* @param array[in] The array to check.
* @return The size of the JSON array.
*/
static MG_UnsignedInt array_size(const JSONNode &array)
{
MG_UnsignedInt size = 0;
if (is_array(array))
{
size = array.Size();
}
return size;
}
/**
* Adds non-static string value to an array.
* @param value[in] The value to add.
* @param array[out] The JSON Array to add the value to.
* @param root[in] The document root.
* @return True if success, or false if not an array.
*/
static bool array_add_value(
const std::string &value,
JSONNode &array,
JSONRoot &root)
{
const bool success = array.IsArray();
if (success)
{
rapidjson::Value val;
val.SetString(value.c_str(), value.size());
array.PushBack(val, root.GetAllocator());
}
return success;
}
/**
* Adds non-static string values to an array.
* @tparam Container std::list of std::string, std::set, and the like.
* @param values[in] The string values to add.
* @param array[out] The JSON Array to add the values to.
* @param root[in] The document root.
* @return True if success, or false if not an array.
*/
template <typename Container>
static bool array_add_value(
const Container &values,
JSONNode &array,
JSONRoot &root)
{
const bool success = array.IsArray();
if (success)
{
rapidjson::Value val;
for (typename Container::const_iterator iter = values.begin();
iter != values.end();
++iter)
{
val.SetString(iter->c_str(), iter->size());
array.PushBack(val, root.GetAllocator());
}
}
return success;
}
/**
* Adds a non-static JSON node to the array.
* @param value[in,out] The value to add. The value itself will be cleared.
* @param array[out] The array to add the value to.
* @param root[in] The document root.
* @return True if success, or false if not an array or unable to add value.
*/
static bool array_add_node(
JSONNode &value,
JSONNode &array,
JSONRoot &root)
{
const bool success = array.IsArray() and not value.IsNull();
if (success)
{
array.PushBack(value, root.GetAllocator());
}
return success;
}
/**
* Adds static (never changes, program constant) string value to an array.
* @param value[in] The value to add.
* @param array[out] The JSON Array to add the value to.
* @param root[in] The document root.
* @return True if success, or false if not an array.
*/
static bool array_add_static_value(
const std::string &value,
JSONNode &array,
JSONRoot &root)
{
const bool success = array.IsArray();
if (success)
{
array.PushBack(
rapidjson::StringRef(value.c_str(), value.size()),
root.GetAllocator());
}
return success;
}
/**
* Adds const static string values to an array.
* @tparam Container std::list of std::string *, std::set, and the like.
* @param values[in] The pointers to const static string values to add.
* Pointer ownership does NOT transfer to this method.
* @param array[out] The JSON Array to add the values to.
* @param root[in] The document root.
* @return True if success, or false if not an array.
*/
template <typename Container>
static bool array_add_static_value(
const Container &values,
JSONNode &array,
JSONRoot &root)
{
const bool success = array.IsArray();
if (success)
{
for (typename Container::const_iterator iter = values.begin();
iter != values.end();
++iter)
{
array.PushBack(
rapidjson::StringRef((*iter)->c_str(), (*iter)->size()),
root.GetAllocator());
}
}
return success;
}
/**
* Gets an array of strings from a JSON array. The strings will be copied.
* Non-string elements will be filtered out.
* @tparam Container std::list of std::string, std::set, and the like.
* @param array[in] The array to retrieve the strings from.
* @param value[out] Where to place the strings retrieved from array.
* The contents will NOT be cleared success or fail.
* @return True if an array and able to retrieve values. Note this will
* return true even if the array is empty.
*/
template <typename Container>
static bool array_get_value(
const JSONNode &array,
Container &value)
{
const bool success = array.IsArray();
if (success)
{
for (JSONNode::ConstValueIterator iter = array.Begin();
iter != array.End();
++iter)
{
if (iter->IsString())
{
value.push_back(std::string(
iter->GetString(),
iter->GetStringLength()));
}
}
}
return success;
}
/**
* Gets a string from a specific location in an array. The string will
* be copied.
* @param array[in] The array to retrieve the string from.
* @param index[in] The index of the string in the array to retrieve.
* @param value[out] The value of the array element. The value will be
* cleared before populating, success or fail.
* @return True if an array, the index is within range, the value is
* of type string, and able to retrieve the value. False otherwise.
*/
static bool array_get_value(
const JSONNode &array,
const ssize_t index,
std::string &value)
{
bool success = array.IsArray() and (array.Size() > index);
value.clear();
if (success)
{
const JSONNode &element = array[index];
if (element.IsString())
{
value.assign(element.GetString(), element.GetStringLength());
}
else
{
success = false;
}
}
return success;
}
/**
* Gets a string from a specific location in an array. The string will
* be copied.
* Note this method is generally used for specific performance reasons;
* the standard std::string variant is preferred for most use cases.
* @param array[in] The array to retrieve the string from.
* @param index[in] The index of the string in the array to retrieve.
* @param value_ptr[out] If returning true, this will contain a pointer
* to the string data. Caller must manage the pointer! If false is
* returned, this will be null.
* @param value_size[out] The length of value, excluding the final null.
* As strings are permitted to contain nulls, this is the most accurate
* size of the string.
* @return True if an array, the index is within range, the value is
* of type string, and able to retrieve the value. False otherwise.
*/
static bool array_get_value(
const JSONNode &array,
const ssize_t index,
char *&value_ptr,
size_t &value_size)
{
bool success = array.IsArray() and (array.Size() > index);
value_ptr = 0;
if (success)
{
const JSONNode &element = array[index];
if (element.IsString())
{
value_size = element.GetStringLength();
value_ptr = new char[value_size + 1];
memcpy(value_ptr, element.GetString(), value_size);
value_ptr[value_size] = 0;
}
else
{
success = false;
}
}
return success;
}
/**
* Gets a JSON node from a specific location in an array.
* @param array[in] The array to retrieve the node from.
* @param index[in] The index of the node in the array to retrieve.
* @param value[out] The pointer to the node. Ownership of the pointer
* does NOT transfer to the caller (do not delete it). It will be set
* to null if this method returns null.
* @return True if an array and the index is within range, and able to
* retrieve the value. False otherwise.
*/
static bool array_get_node(
const JSONNode &array,
const ssize_t index,
const JSONNode *&value)
{
const bool success = array.IsArray() and (array.Size() > index);
value = 0;
if (success)
{
value = &array[index];
}
return success;
}
// TODO array get/add bool, uint, int, ID
// TODO array helpers for list/set of IDs
}
}
#endif //MUTGOS_JSON_JSONUTILITIES_H
| 28.434156
| 151
| 0.56918
|
[
"object"
] |
b2af45033f4867c7f821f25962d4e509c9ae9826
| 7,936
|
c
|
C
|
c/day13/main.c
|
Phytolizer/AOC-2015
|
81e66f9535de097c49939f316c292fdfd0258009
|
[
"MIT"
] | null | null | null |
c/day13/main.c
|
Phytolizer/AOC-2015
|
81e66f9535de097c49939f316c292fdfd0258009
|
[
"MIT"
] | null | null | null |
c/day13/main.c
|
Phytolizer/AOC-2015
|
81e66f9535de097c49939f316c292fdfd0258009
|
[
"MIT"
] | null | null | null |
#include <advent.h>
#include <advent/map.h>
#include <advent/pcre.h>
#include <advent/set.h>
#include <advent/vector.h>
#include <assert.h>
#include <config.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "advent/permute.h"
typedef struct {
char* s;
size_t l;
} string_t;
string_t string_from_cstr(char* s) {
return (string_t){
.s = s,
.l = strlen(s),
};
}
void string_free(string_t s) {
free(s.s);
}
DECLARE_MAP(happiness_catalog_entry_t, long);
DEFINE_MAP(happiness_catalog_entry_t, long);
DECLARE_MAP(happiness_catalog_t, happiness_catalog_entry_t);
DEFINE_MAP(happiness_catalog_t, happiness_catalog_entry_t);
typedef struct {
string_t a;
string_t b;
long happiness;
} happiness_catalog_pair_t;
DECLARE_VECTOR(happiness_catalog_pair_vec_t, happiness_catalog_pair_t);
DEFINE_VECTOR(happiness_catalog_pair_vec_t, happiness_catalog_pair_t);
DECLARE_VECTOR(string_vec_t, string_t);
DEFINE_VECTOR(string_vec_t, string_t);
int main(void) {
FILE* fp = fopen(ADVENT_INPUT, "r");
if (fp == NULL) {
fprintf(stderr, "Failed to open %s\n", ADVENT_INPUT);
return 1;
}
int err;
size_t errofs;
pcre2_code* code =
pcre2_compile((PCRE2_SPTR) "(\\w+) would (gain|lose) (\\d+) happiness "
"units by sitting next to (\\w+)\\.",
PCRE2_ZERO_TERMINATED, 0, &err, &errofs, NULL);
if (code == NULL) {
PCRE2_UCHAR buffer[256];
pcre2_get_error_message(err, buffer, sizeof(buffer));
fprintf(stderr, "PCRE2 compilation failed at offset %d: %s\n",
(int)errofs, buffer);
return 1;
}
pcre2_match_data* match_data =
pcre2_match_data_create_from_pattern(code, NULL);
if (match_data == NULL) {
fprintf(stderr, "Failed to create match data\n");
return 1;
}
char* line = NULL;
size_t line_length = 0;
Set names;
Set_init(&names);
happiness_catalog_pair_vec_t pairs;
happiness_catalog_pair_vec_t_init(&pairs);
while (getline(&line, &line_length, fp) != -1) {
line_length = strlen(line);
if (line[line_length - 1] == '\n') {
--line_length;
line[line_length] = '\0';
}
int ret = pcre2_match(code, (PCRE2_SPTR)line, line_length, 0, 0,
match_data, NULL);
if (ret < 0) {
fprintf(stderr, "Failed to match line: %s\n", line);
return 1;
}
PCRE2_SIZE* ovector = pcre2_get_ovector_pointer(match_data);
Set_insert(&names, line + ovector[2], ovector[3] - ovector[2]);
long happiness = strtol(line + ovector[6], NULL, 10);
if (strncmp(line + ovector[4], "lose", ovector[5] - ovector[4]) == 0) {
happiness = -happiness;
}
happiness_catalog_pair_t pair = {
.a = string_from_cstr(
advent_strndup(line + ovector[2], ovector[3] - ovector[2])),
.b = string_from_cstr(
advent_strndup(line + ovector[8], ovector[9] - ovector[8])),
.happiness = happiness,
};
happiness_catalog_pair_vec_t_push(&pairs, pair);
free(line);
line = NULL;
}
happiness_catalog_t catalog;
happiness_catalog_t_init(&catalog);
for (size_t i = 0; i < names.capacity; ++i) {
if (names.data[i].value == NULL) {
continue;
}
happiness_catalog_entry_t entry;
happiness_catalog_entry_t_init(&entry);
happiness_catalog_t_insert(&catalog, names.data[i].value,
names.data[i].valueLength, entry);
}
for (size_t i = 0; i < pairs.length; ++i) {
happiness_catalog_entry_t* entry;
assert(happiness_catalog_t_get(&catalog, pairs.data[i].a.s,
pairs.data[i].a.l, &entry) &&
"faulty logic");
happiness_catalog_entry_t_insert(entry, pairs.data[i].b.s,
pairs.data[i].b.l,
pairs.data[i].happiness);
}
string_vec_t names_vec;
string_vec_t_init(&names_vec);
for (size_t i = 0; i < names.capacity; ++i) {
if (names.data[i].value == NULL) {
continue;
}
string_vec_t_push(&names_vec,
string_from_cstr(advent_strndup(
names.data[i].value, names.data[i].valueLength)));
}
happiness_catalog_entry_t entry;
happiness_catalog_entry_t_init(&entry);
for (size_t i = 0; i < names_vec.length; ++i) {
happiness_catalog_entry_t_insert(&entry, names_vec.data[i].s,
names_vec.data[i].l, 0);
}
for (size_t i = 0; i < catalog.bucketCount; ++i) {
if (catalog.buckets[i].key == NULL) {
continue;
}
happiness_catalog_entry_t* entry;
assert(happiness_catalog_t_get(&catalog, catalog.buckets[i].key,
catalog.buckets[i].keyLen, &entry) &&
"faulty logic");
happiness_catalog_entry_t_insert(entry, "Me", 2, 0);
}
happiness_catalog_t_insert(&catalog, "Me", 2, entry);
string_vec_t_push(&names_vec, string_from_cstr(advent_strdup("Me")));
permutation_t perm = first_permutation(names_vec.length);
permutation_t optimal_permutation = perm;
long optimal_happiness = 0;
bool first = true;
do {
long total_happiness = 0;
for (size_t i = 0; i < perm.length; ++i) {
string_t name = names_vec.data[perm.data[i].index];
happiness_catalog_entry_t* entry;
assert(happiness_catalog_t_get(&catalog, name.s, name.l, &entry) &&
"faulty logic");
string_t name2;
if (i == 0) {
name2 = names_vec.data[perm.data[perm.length - 1].index];
} else {
name2 = names_vec.data[perm.data[i - 1].index];
}
long* happiness;
assert(happiness_catalog_entry_t_get(entry, name2.s, name2.l,
&happiness) &&
"faulty logic");
total_happiness += *happiness;
if (i == perm.length - 1) {
name2 = names_vec.data[perm.data[0].index];
} else {
name2 = names_vec.data[perm.data[i + 1].index];
}
assert(happiness_catalog_entry_t_get(entry, name2.s, name2.l,
&happiness) &&
"faulty logic");
total_happiness += *happiness;
}
if (first || total_happiness > optimal_happiness) {
first = false;
optimal_happiness = total_happiness;
optimal_permutation = perm;
}
} while (next_permutation(&perm));
for (size_t i = 0; i < optimal_permutation.length; ++i) {
string_t name = names_vec.data[optimal_permutation.data[i].index];
printf("%s%s", i == 0 ? "" : " - ", name.s);
}
printf(" (happiness : %ld)\n", optimal_happiness);
for (size_t i = 0; i < names_vec.length; ++i) {
string_free(names_vec.data[i]);
}
string_vec_t_deinit(&names_vec);
free(line);
for (size_t i = 0; i < catalog.bucketCount; ++i) {
if (catalog.buckets[i].key == NULL) {
continue;
}
happiness_catalog_entry_t_deinit(&catalog.buckets[i].value);
}
happiness_catalog_t_deinit(&catalog);
for (size_t i = 0; i < pairs.length; ++i) {
string_free(pairs.data[i].a);
string_free(pairs.data[i].b);
}
happiness_catalog_pair_vec_t_deinit(&pairs);
fclose(fp);
pcre2_match_data_free(match_data);
pcre2_code_free(code);
return 0;
}
| 33.627119
| 80
| 0.567162
|
[
"vector"
] |
b2bf72beb93dd0d3755537d366b38f22b14d1aa0
| 4,743
|
h
|
C
|
src/graphics/Graphics.h
|
cubeman99/SEAL
|
7003c6fee26493e9b89ea1d34460877d6dc85894
|
[
"MIT"
] | 4
|
2017-01-30T19:44:16.000Z
|
2017-12-18T04:41:32.000Z
|
src/graphics/Graphics.h
|
cubeman99/SEAL
|
7003c6fee26493e9b89ea1d34460877d6dc85894
|
[
"MIT"
] | null | null | null |
src/graphics/Graphics.h
|
cubeman99/SEAL
|
7003c6fee26493e9b89ea1d34460877d6dc85894
|
[
"MIT"
] | null | null | null |
#ifndef _GRAPHICS_H_
#define _GRAPHICS_H_
#include <math/Matrix4f.h>
#include <math/Rect2i.h>
#include <math/Vector2f.h>
#include <math/Vector3f.h>
#include <math/Vector4f.h>
#include <math/Quaternion.h>
#include <math/Rect2f.h>
#include "Color.h"
#include "SpriteFont.h"
#include <assert.h>
#include <string>
//-------------------------------------------------------------------------
// Viewport - integer rectangle class.
//-------------------------------------------------------------------------
struct Viewport
{
int x;
int y;
int width;
int height;
Viewport()
{}
Viewport(int x, int y, int width, int height) :
x(x), y(y), width(width), height(height)
{}
float GetAspectRatio() const
{
assert(height != 0);
return ((float) width / (float) height);
}
void Inset(int amount)
{
x += amount;
y += amount;
width -= amount * 2;
height -= amount * 2;
}
void Inset(int left, int top, int right, int bottom)
{
x += left;
y += top;
width -= left + right;
height -= top + bottom;
}
bool Contains(int x, int y)
{
return (x >= this->x && y >= this->y &&
x < this->x + this->width &&
y < this->y + this->height);
}
};
//-------------------------------------------------------------------------
// TextAlign - bit flags for text alignment.
//-------------------------------------------------------------------------
struct TextAlign
{
enum
{
CENTER = 0x0,
MIDDLE = 0x0,
TOP = 0x1,
BOTTOM = 0x2,
LEFT = 0x4,
RIGHT = 0x8,
TOP_LEFT = TOP | LEFT,
TOP_RIGHT = TOP | RIGHT,
TOP_CENTER = TOP | CENTER,
BOTTOM_LEFT = BOTTOM | LEFT,
BOTTOM_RIGHT = BOTTOM | RIGHT,
BOTTOM_CENTER = BOTTOM | CENTER,
MIDDLE_LEFT = MIDDLE | LEFT,
MIDDLE_RIGHT = MIDDLE | RIGHT,
CENTERED = MIDDLE | CENTER,
};
};
//-------------------------------------------------------------------------
// Graphics - Used for drawing 2D graphics.
//-------------------------------------------------------------------------
class Graphics
{
public:
Graphics();
//---------------------------------------------------------------------
// General
void Clear(const Color& color);
void SetupCanvas2D(int width, int height);
void SetCanvasSize(int width, int height);
void SetViewportToCanvas();
void SetViewport(const Rect2i& viewport, bool scissor);
void SetViewport(const Viewport& viewport, bool scissor);
//---------------------------------------------------------------------
// Lines
void DrawLine(float x1, float y1, float x2, float y2, const Color& color);
void DrawLine(const Vector2f& from, const Vector2f& to, const Color& color);
//---------------------------------------------------------------------
// Rectangles
void DrawRect(const Rect2f& rect, const Color& color);
void DrawRect(const Viewport& rect, const Color& color);
void DrawRect(const Vector2f& pos, const Vector2f& size, const Color& color);
void DrawRect(float x, float y, float width, float height, const Color& color);
void FillRect(const Rect2f& rect, const Color& color);
void FillRect(const Viewport& rect, const Color& color);
void FillRect(const Vector2f& pos, const Vector2f& size, const Color& color);
void FillRect(float x, float y, float width, float height, const Color& color);
//---------------------------------------------------------------------
// Circles
void DrawCircle(const Vector2f& pos, float radius, const Color& color, int numEdges = 20);
void FillCircle(const Vector2f& pos, float radius, const Color& color, int numEdges = 20);
//---------------------------------------------------------------------
// Text
void DrawString(const Font* font, const std::string& text, float x, float y, const Color& color, int align = TextAlign::TOP_LEFT);
void DrawString(const Font* font, const std::string& text, const Vector2f& position, const Color& color, int align = TextAlign::TOP_LEFT);
Vector2f MeasureString(const Font* font, const std::string& text);
//---------------------------------------------------------------------
// Transformations
void SetProjection(const Matrix4f& projection);
void SetCanvasProjection();
void ResetTransform();
void SetTransform(const Matrix4f& transform);
void Transform(const Matrix4f& transform);
void Rotate(const Vector3f& axis, float angle);
void Rotate(const Quaternion& rotation);
void Translate(const Vector2f& translation);
void Translate(const Vector3f& translation);
void Scale(float scale);
void Scale(const Vector3f& scale);
void EnableCull(bool cull);
void EnableDepthTest(bool depthTest);
private:
void gl_Vertex(const Vector2f& v);
void gl_Vertex(const Vector3f& v);
void gl_Color(const Color& color);
int m_canvasWidth;
int m_canvasHeight;
};
#endif // _GRAPHICS_H_
| 26.948864
| 139
| 0.566519
|
[
"transform"
] |
b2bfbe6f6bacbafa118d0b3507a2b09b1f2181c9
| 4,251
|
h
|
C
|
slackerz/string.h
|
Coderz75/Slackerz-Compiler
|
99340059592a874ddb6f08c5f3a9845ab1137e90
|
[
"MIT"
] | null | null | null |
slackerz/string.h
|
Coderz75/Slackerz-Compiler
|
99340059592a874ddb6f08c5f3a9845ab1137e90
|
[
"MIT"
] | null | null | null |
slackerz/string.h
|
Coderz75/Slackerz-Compiler
|
99340059592a874ddb6f08c5f3a9845ab1137e90
|
[
"MIT"
] | null | null | null |
#ifndef STRING_H
#define STRING_H
#include <vector>
#include <string>
#include <algorithm>
#include <cstring>
#include "default.h"
using namespace std;
namespace slackerz{
class str{
public:
string v;
str(string s){
v = s;
}
string upper(){
string data = v;
std::for_each(data.begin(), data.end(), [](char & c){
c = ::toupper(c);
});
return data;
}
string lower(){
string data = v;
std::for_each(data.begin(), data.end(), [](char & c){
c = ::tolower(c);
});
return data;
}
operator std::string () const { // C++ verison of __repr__
return v;
}
std::vector<std::string> split(string x = " "){
std::vector<std::string> so {};
string s = v;
string delim = x;
auto start = 0U;
auto end = s.find(delim);
while (end != std::string::npos)
{
string m = s.substr(start, end - start);
so.push_back(m);
start = end + delim.length();
end = s.find(delim, start);
}
so.push_back(s.substr(start, end));
return so;
}
string capitilize(){
string a = v;
a[0] = toupper(a[0]);
return a;
}
bool isupper(){
string m = v;
for (int i = 0; i < m.length(); i++) {
if(::isupper(m[i])){
}else{
return false;
}
}
return true;
}
bool islower(){
string m = v;
for (int i = 0; i < m.length(); i++) {
if(::islower(m[i])){
}else{
return false;
}
}
return true;
}
string convstr(){
return v;
}
string center(int s, string a = " "){
int spaces = s - v.length() ;
spaces = spaces/2;
string returnval = v;
for(int i = 0; i<spaces; i++){
returnval = a + returnval;
}
for(int i = 0; i<spaces; i++){
returnval = returnval+a;
}
return returnval;
}
string zfill(int length){
string l = v;
int zeros = length - v.length();
for(int i = 0; i< zeros; i++){
l = "0" + l;
}
return l;
}
string swapcase(){
string a = v;
for(int i = 0; i < a.length(); i++){
if(::islower(a[i])){
a[i] = toupper(a[i]);
}else{
a[i] = tolower(a[i]);
}
}
return a;
}
bool startswith(string a, int b = 0, int c = 0){
string l = v;
int x = c;
if (x== 0){
x = a.length();
}
for (int i = 0; i< a.length(); i++){
if (a[i+b] != l[i+b]){
return false;
}
}
return true;
}
};
}
#endif
| 33.210938
| 73
| 0.285109
|
[
"vector"
] |
b2d54e976a74ad54d3d734db559f5c0d19b1ec61
| 706
|
c
|
C
|
Data/My_C_Stuff.c
|
Japhiolite/JuliaTutorial
|
3222ce1b55361c43a25ea76bb01990d0723a9adf
|
[
"MIT"
] | 86
|
2017-05-03T06:12:57.000Z
|
2022-03-25T19:55:15.000Z
|
Data/My_C_Stuff.c
|
Japhiolite/JuliaTutorial
|
3222ce1b55361c43a25ea76bb01990d0723a9adf
|
[
"MIT"
] | 2
|
2018-03-01T12:26:58.000Z
|
2021-08-09T18:20:07.000Z
|
Data/My_C_Stuff.c
|
Japhiolite/JuliaTutorial
|
3222ce1b55361c43a25ea76bb01990d0723a9adf
|
[
"MIT"
] | 54
|
2017-05-03T06:12:58.000Z
|
2021-10-15T07:49:55.000Z
|
#include <stddef.h>
// calculate the inner (dot) product of vectors Y and Y, returns the result (Sxy)
double c_dot(size_t n, double *Y, double *X) {
double Sxy = 0.0;
for (size_t i = 0; i < n; ++i) {
Sxy += X[i]*Y[i];
}
return Sxy;
}
// calculate a simple regression, Y = a + b*X + u, puts (a,b) in vector ab, returns nothing
void c_ols(size_t n, double *Y, double *X, double *ab) {
double Sx = 0.0, Sy = 0.0, Sxx = 0.0, Sxy = 0.0;
for (size_t i = 0; i < n; ++i) {
Sx += X[i];
Sy += Y[i];
Sxx += X[i]*X[i];
Sxy += X[i]*Y[i];
}
ab[1] = (Sxy-Sx*Sy/n)/(Sxx-Sx*Sx/n); //slope
ab[0] = (Sy - ab[1]*Sx)/n; //intercept
}
| 30.695652
| 91
| 0.495751
|
[
"vector"
] |
b2d7adc20be15cb851e1c1b33cea2954fbd793a7
| 2,751
|
h
|
C
|
004_motion_detector/include/MotionDetector_GMM2.h
|
DreamWaterFound/Codes
|
e7d80eb8bfd7d6f104abd18724cb4bface419233
|
[
"WTFPL"
] | 13
|
2019-02-28T14:28:23.000Z
|
2021-12-04T04:55:19.000Z
|
004_motion_detector/include/MotionDetector_GMM2.h
|
DreamWaterFound/Codes
|
e7d80eb8bfd7d6f104abd18724cb4bface419233
|
[
"WTFPL"
] | 1
|
2019-09-07T09:00:50.000Z
|
2019-12-04T02:13:25.000Z
|
004_motion_detector/include/MotionDetector_GMM2.h
|
DreamWaterFound/Codes
|
e7d80eb8bfd7d6f104abd18724cb4bface419233
|
[
"WTFPL"
] | 1
|
2020-03-11T16:47:31.000Z
|
2020-03-11T16:47:31.000Z
|
/**
* @file MotionDetector_GMM2.h
* @author guoqing ([email protected])
* @brief 通过自己的方式来实现的GMM
* @details 也是用这种方式来实现前景检测
* @version 0.1
* @date 2019-01-08
*
* @copyright Copyright (c) 2019
*
*/
#ifndef __MOTION_DETETCTOR_GMM_2_H__
#define __MOTION_DETETCTOR_GMM_2_H__
#include "common.h"
#include "MotionDetector_DiffBase.h"
using namespace std;
using namespace cv;
/** @brief GMM模型的最多数目,这个数值是定死的,不能够在运行时改变 */
#define GMM_MAX_COMPONT 2
//学习速率
#define DEFAULT_GMM_LEARN_ALPHA 0.005 //该学习率越大的话,学习速度太快,效果不好
//阈值
#define DEFALUT_GMM_THRESHOD_SUMW 0.7 //如果取值太大了的话,则更多部分都被检测出来了
//学习帧数
#define DEFAULT_END_FRAME 20
//几个用来加速操作的宏
#define W(index,x,y) (mmWeight[index].at<float>(x,y))
#define U(index,x,y) (mmU[index].at<unsigned char>(x,y))
#define Sigma(index,x,y) (mmSigma[index].at<float>(x,y))
#define IMG(x,y) (img.at<unsigned char>(x,y))
class MotionDetector_GMM2 : public MotionDetector_DiffBase
{
public:
/**
* @brief Construct a new MotionDetector_GMM2 object
*
*/
MotionDetector_GMM2();
/**
* @brief Destroy the MotionDetector_GMM2 object
*
*/
~MotionDetector_GMM2();
public:
/**
* @brief 使用高斯混合模型的方式来的到差分图像
*
* @param[in] frame 当前时刻的帧
* @return cv::Mat 计算得到的差分图像
*/
cv::Mat calcuDiffImg(cv::Mat frame);
/**
* @brief 重设本基类所有参数、清空所有图像缓存
* @details 清空图像缓存不是删除图片而是设置全黑的图片
*/
void resetDetector(void);
private:
//私有函数
/**
* @brief 初始化高斯模型的所有参数
*
* @param img 第一帧图像
*/
void gmmInit(cv::Mat img);
/**
* @brief 处理第一帧的函数
*
* @param img 第一帧图像
*/
void gmmDealFirstFrame(cv::Mat img);
/**
* @brief 对GMM模型进行训练的函数
*
* @param img 当前帧图像
*/
void gmmTrain(cv::Mat img);
/**
* @brief 根据当前帧确定每个像素最适合使用的高斯模型是多少个
*
* @param img 当前帧图像
*/
void gmmCalFitNum(cv::Mat img);
/**
* @brief 使用GMM来进行前景检测
*
* @param img 当前帧图像
*/
void gmmTest(cv::Mat img);
public:
//参数设置函数,现在先不写
//TODO
private:
private:
/**
* @name 高斯模型参数
* @{
*/
//私有变量
/** 每个像素的每个高斯模型的权值 */
cv::Mat mmWeight[GMM_MAX_COMPONT];
/** 每个像素的每个高斯模型的均值 */
cv::Mat mmU[GMM_MAX_COMPONT];
/** 每个像素的每个高斯模型的 协方差矩阵 */
cv::Mat mmSigma[GMM_MAX_COMPONT];
/** @} */
/**
* @brief 其他
* @{
*/
/** 表示某个像素最实用的高斯模型的数目 */
cv::Mat mmFitNum;
/** 学习率 */
float mfLearnRate;
/** 判断 fitNum 时的权重累加和阈值 */
float mfThreshod;
/** 学习帧数 */
int mnLearnFrameNumber;
/** 当前视频帧数 */
int mnFrameCnt;
/** @} */
/** 最后生成的掩摸图像 */
cv::Mat mmGMMMask;
};
#endif //__MOTION_DETETCTOR_GMM_2_H__
| 16.877301
| 65
| 0.587423
|
[
"object"
] |
b2db6db446b5ef3e6050bdb17dff5425a1da4477
| 11,318
|
c
|
C
|
library/+spx/+fast/private/gomp_mmv.c
|
santoshmore85/sparse-plex
|
1cb2b9f3051d6284adbe195abdc1a36c4541bdeb
|
[
"Apache-2.0"
] | 64
|
2016-09-09T09:27:43.000Z
|
2022-02-24T05:49:37.000Z
|
library/+spx/+fast/private/gomp_mmv.c
|
indigits/sparse-plex
|
1cb2b9f3051d6284adbe195abdc1a36c4541bdeb
|
[
"Apache-2.0"
] | null | null | null |
library/+spx/+fast/private/gomp_mmv.c
|
indigits/sparse-plex
|
1cb2b9f3051d6284adbe195abdc1a36c4541bdeb
|
[
"Apache-2.0"
] | 34
|
2015-07-05T12:09:56.000Z
|
2022-03-21T02:31:58.000Z
|
/*************************************************
*
* GOMP Implementation for multiple measurement vectors
*
*************************************************/
#include <mex.h>
#include <math.h>
#include "omp.h"
#include "omp_profile.h"
#include "spxblas.h"
#include "spxalg.h"
#include "spxla.h"
#include "argcheck.h"
#define MAX_M 4096
mxArray* gomp_mmv_chol(const double m_dict[],
const double m_x[],
mwSize M,
mwSize N,
mwSize S,
mwSize K,
mwSize L,
mwSize T,
double res_norm_bnd,
int sparse_output,
int verbose){
// List of indices of selected atoms
mwIndex *selected_atoms = 0;
// Atom indices needed during selection
mwIndex* atom_indices = 0;
// Storage for the Cholesky decomposition of D_I' D_I
double *m_lt = 0;
// The submatrix of selected atoms
double* m_subdict = 0;
// The proxy D' x
double* m_proxy = 0;
// The inner product of residual with atoms H = D' * R
double* m_h = 0;
// Absolute sum of inner products in each column
double* v_h = 0;
// The residual
double* m_r = 0;
// b = D_I' d_k in the Cholesky decomposition updates
double* v_b = 0;
// New vector in the Cholesky decomposition updates
double* v_w = 0;
// Result of orthogonal projection LL' c = p_I
double* m_c = 0;
// Pointer to new atom
const double* wv_new_atom;
// residual norm squared
double res_norm_sqr = 1;
// square of upper bound on residual norm
double res_norm_bnd_sqr = SQR(res_norm_bnd);
// Expected sparsity of signal
mwSize sparsity = K;
/// Output array
mxArray* p_alpha;
double* m_alpha;
// row indices for non-zero entries in Alpha
mwIndex *ir_alpha;
// indices for first non-zero entry in column
mwIndex *jc_alpha;
/// Index for non-zero entries in alpha
mwIndex nz_index;
// counters
int i, j , k, s;
// index of new atom
mwIndex new_atom_index;
// Maximum number of columns to be used in representations
mwSize max_atoms;
if(verbose > 1){
mexPrintf("M: %d, N:%d, S: %d, K: %d, L: %d, T: %d, eps: %e, sparse: %d, verbose: %d\n",
M, N, S, K, L, T, res_norm_bnd, sparse_output, verbose);
}
// structure for tracking time spent.
omp_profile profile;
// K is now the iteration count.
// If it is larger than acceptable, we will cut it down here.
if (K < 0 || K * L > M) {
// K cannot be greater than M / L.
K = M / L;
}
max_atoms = K*L;
// Memory allocations
// Number of selected atoms cannot exceed M
selected_atoms = (mwIndex*) mxMalloc(M*sizeof(mwIndex));
// Total number of atoms is N
atom_indices = (mwIndex*) mxMalloc(N*sizeof(mwIndex));
// Number of rows and columns in L cannot exceed max_atoms.
// We still allocate M elements per column as
// this is what the chol update function assumes
m_lt = (double*) mxMalloc(M*max_atoms*sizeof (double));
// Number of entries in new line for L cannot exceed N.
v_b = (double*)mxMalloc(N*sizeof(double));
v_w = (double*)mxMalloc(N*sizeof(double));
// h is in R^N. We need to store it separately for each vector in MMV set
m_h = (double*)mxMalloc(T*N*sizeof(double));
v_h = (double*)mxMalloc(N*sizeof(double));
// Residual is in signal space R^M. We need to store it separately for each vector in MMV set
m_r = (double*)mxMalloc(T*M*sizeof(double));
// The non-zero approximation coefficients. We need to store it separately for each vector in MMV set
m_c = (double*)mxMalloc(T*M*sizeof(double));
// Proxy vector is in R^N. We need to store it separately for each vector in MMV set
m_proxy = (double*)mxMalloc(T*N*sizeof(double));
// Keeping max_atoms space for subdictionary.
m_subdict = (double*)mxMalloc(max_atoms*M*sizeof(double));
// Allocation of space for the result vector
if (sparse_output == 0){
p_alpha = mxCreateDoubleMatrix(N, S, mxREAL);
m_alpha = mxGetPr(p_alpha);
ir_alpha = 0;
jc_alpha = 0;
}else{
p_alpha = mxCreateSparse(N, S, max_atoms*S, mxREAL);
m_alpha = mxGetPr(p_alpha);
ir_alpha = mxGetIr(p_alpha);
jc_alpha = mxGetJc(p_alpha);
nz_index = 0;
jc_alpha[0] = 0;
}
if (M > MAX_M){
error_msg("gomp_mmv", "Too large M.");
return p_alpha;
}
omp_profile_init(&profile);
// We process one MMV set in each iteration.
// Each MMV set contains at most T vectors
// All except last set contain T vectors
// Last set may contain less vectors
// s indicates the index of first vector in the MMV set
for(s=0; s<S; s+= T){
// Pointer to current MMV set
const double *wm_x = m_x + M*s;
int dummy;
// Counter for selected atoms
int kk = 0;
// Number of atoms in next MMV set
mwSize tt = T;
if (S -s < T){
tt = S - s;
}
if (verbose > 1){
mexPrintf("Processing %d vectors \n", tt);
}
// Initialization
if (res_norm_bnd_sqr > 0){
// Cool trick to compute Frobenius norm of residual
res_norm_sqr = inner_product(wm_x, wm_x, M*tt);
}
//Compute proxy P = D' * X for the MMV set
mult_mat_t_mat(1, m_dict, wm_x, m_proxy, N, tt, M);
omp_profile_toctic(&profile, TIME_DtR);
// h = p = D' * r
copy_vec_vec(m_proxy, m_h, N*tt);
// Iteration counter for selecting bunch of atoms in each iteration.
k = 0;
// In each iteration we select up to L atoms
while (k < K && res_norm_sqr > res_norm_bnd_sqr){
// Number of atoms added during this cycle.
int added_atoms = 0;
if (verbose > 1){
mexPrintf("k: %d :: ", k+1);
}
omp_profile_tic(&profile);
// Sum of absolute correlations in each row (i.e. for all vectors in MMV set)
mat_row_asum(m_h, v_h, N, tt);
// Remove the entries for already selected atoms
for(i=0; i < kk; ++i){
v_h[selected_atoms[i]] = 0;
}
//Assign atom indices
for (i=0; i<N; ++i){
// Assign indices to atoms
atom_indices[i] = i;
}
// Search for L largest atoms
quickselect_desc(v_h, atom_indices, N, L);
omp_profile_toctic(&profile, TIME_MaxAbs);
// Store the indices and update Cholesky decomposition
for (i=0; i < L; ++i){
if (v_h[i] < 1e-6*tt){
// The contribution of atom is too small to consider
continue;
}
new_atom_index = atom_indices[i];
selected_atoms[kk] = new_atom_index;
// One more atom was added
++added_atoms;
// Copy the new atom to the sub-dictionary
wv_new_atom = m_dict + new_atom_index*M;
copy_vec_vec(wv_new_atom, m_subdict+kk*M, M);
if (verbose > 1){
mexPrintf("%d ", new_atom_index+1);
}
// Cholesky update
if (kk == 0){
// Simply initialize the L matrix
*m_lt = 1;
}else{
wv_new_atom = m_subdict+kk*M;
// Incremental Cholesky decomposition
if (chol_update(m_subdict, wv_new_atom, m_lt,
v_b, v_w, M, kk) != 0){
// We will ignore this atom
// as it is linearly dependent on previous atoms
continue;
}
}
++kk;
}
if(0 == added_atoms){
if (verbose > 1){
mexPrintf("No new atoms were added. Stopping.\n");
break;
}
}
omp_profile_toctic(&profile, TIME_LCholUpdate);
// We can increase the iteration count
++k;
// We will now solve the equation L L' alpha_I = p_I
mat_row_extract(m_proxy, selected_atoms, m_c, N, tt, kk);
spd_lt_trtrs_multi(m_lt, m_c, M, kk, tt);
if (verbose > 2){
print_matrix(m_c, kk, tt, "c");
}
omp_profile_toctic(&profile, TIME_LLtSolve);
// Compute residual
// r = x - D_I c
mult_mat_mat(-1, m_subdict, m_c, m_r, M, tt, kk);
sum_vec_vec(1, wm_x, m_r, M*tt);
omp_profile_toctic(&profile, TIME_RUpdate);
// Update h = D' r
mult_mat_t_mat(1, m_dict, m_r, m_h, N, tt, M);
if (res_norm_bnd_sqr > 0){
// Update residual norm squared
res_norm_sqr = inner_product(m_r, m_r, M*tt);
if(verbose > 1){
mexPrintf(" \\| r \\|_2^2 : %.4f.\n", res_norm_sqr);
}
}else{
if (verbose > 1){
mexPrintf("\n");
}
}
omp_profile_toctic(&profile, TIME_DtR);
}
// Write the output vector
if(sparse_output == 0){
// Iterate over MMV set
for (int j=0; j < tt; ++j){
double* wv_alpha = m_alpha + N*(s + j);
double* wv_c = m_c + kk*j;
// Write the output vector
fill_vec_sparse_vals(wv_c, selected_atoms, wv_alpha, N, kk);
}
}
else{
// First sort the indices
mwIndex indices1[MAX_M];
double indices2[MAX_M];
for (int j=0; j < kk; ++j){
indices2[j] = j;
}
// Sort the row indices
quicksort_indices(selected_atoms, indices2, kk);
for (int j=0; j < kk; ++j){
indices1[j] = (mwIndex) indices2[j];
}
// Iterate over MMV set
for(int i=0; i < tt; ++i){
// Coefficients for current vector in MMV set
double* wv_c = m_c + kk*i;
// add the non-zero entries for this column
for(j=0; j <kk; ++j){
m_alpha[nz_index] = wv_c[indices1[j]];
ir_alpha[nz_index] = selected_atoms[j];
++nz_index;
}
// fill in the total number of nonzero entries in the end.
jc_alpha[s+i+1] = jc_alpha[s+i] + kk;
}
}
}
if(verbose){
omp_profile_print(&profile);
}
if (sparse_output && verbose > 2){
mexPrintf("nnz : %d\n", nz_index);
// print_index_vector(jc_alpha, S, "jc_alpha");
// print_vector(m_alpha, nz_index, "pr_alpha");
}
// Memory cleanup
mxFree(selected_atoms);
mxFree(atom_indices);
mxFree(m_lt);
mxFree(v_b);
mxFree(v_w);
mxFree(m_c);
mxFree(m_subdict);
mxFree(m_proxy);
mxFree(m_h);
mxFree(v_h);
mxFree(m_r);
// Return the result
return p_alpha;
}
| 34.717791
| 105
| 0.528362
|
[
"vector"
] |
b2e1079a9bcd91300ad930482013323cafab241b
| 6,018
|
h
|
C
|
src_main/game/client/particle_iterators.h
|
ArcadiusGFN/SourceEngine2007
|
51cd6d4f0f9ed901cb9b61456eb621a50ce44f55
|
[
"bzip2-1.0.6"
] | 25
|
2018-02-28T15:04:42.000Z
|
2021-08-16T03:49:00.000Z
|
src_main/game/client/particle_iterators.h
|
ArcadiusGFN/SourceEngine2007
|
51cd6d4f0f9ed901cb9b61456eb621a50ce44f55
|
[
"bzip2-1.0.6"
] | 1
|
2019-09-20T11:06:03.000Z
|
2019-09-20T11:06:03.000Z
|
src_main/game/client/particle_iterators.h
|
ArcadiusGFN/SourceEngine2007
|
51cd6d4f0f9ed901cb9b61456eb621a50ce44f55
|
[
"bzip2-1.0.6"
] | 9
|
2019-07-31T11:58:20.000Z
|
2021-08-31T11:18:15.000Z
|
// Copyright © 1996-2018, Valve Corporation, All rights reserved.
//
// Purpose: Client side CTFTeam class
#ifndef PARTICLE_ITERATORS_H
#define PARTICLE_ITERATORS_H
#include "materialsystem/imesh.h"
#include "particledraw.h"
#define NUM_PARTICLES_PER_BATCH 200
#define MAX_TOTAL_PARTICLES 4096 // Max particles in the world
//
// Iterate the particles like this:
//
// Particle *pCur = pIterator->GetFirst();
// while ( pCur )
// {
// ... render the particle here and figure out the sort key and position
// pCur = pIterator->GetNext( sortKey, pCur->m_Pos );
// }
//
class CParticleRenderIterator {
friend class CParticleMgr;
friend class CParticleEffectBinding;
public:
CParticleRenderIterator();
// The sort key is used to sort the particles incrementally as they're
// rendered. They only get sorted in the main rendered view (ie: not in
// reflections or monitors). These return const because you should only modify
// particles during their simulation.
const Particle *GetFirst();
const Particle *GetNext(float sortKey);
// Use this to render. This can return NULL, in which case you shouldn't
// render. This being NULL is a carryover from when particles rendered and
// simulated together and it should GO AWAY SOON!
ParticleDraw *GetParticleDraw() const;
private:
void TestFlushBatch();
private:
// Set by CParticleMgr.
CParticleEffectBinding *m_pEffectBinding;
CEffectMaterial *m_pMaterial;
ParticleDraw *m_pParticleDraw;
CMeshBuilder *m_pMeshBuilder;
IMesh *m_pMesh;
bool m_bBucketSort;
// Output after rendering.
float m_MinZ;
float m_MaxZ;
float m_zCoords[MAX_TOTAL_PARTICLES];
int m_nZCoords;
Particle *m_pCur;
bool m_bGotFirst;
float m_flPrevZ;
int m_nParticlesInCurrentBatch;
};
//
// Iterate the particles like this:
//
// Particle *pCur = pIterator->GetFirst();
// while ( pCur )
// {
// ... simulate here.. call pIterator->RemoveParticle if you want the
// particle to go away pCur = pIterator->GetNext();
// }
//
class CParticleSimulateIterator {
friend class CParticleMgr;
friend class CParticleEffectBinding;
public:
CParticleSimulateIterator();
// Iterate through the particles, simulate them, and remove them if necessary.
Particle *GetFirst();
Particle *GetNext();
float GetTimeDelta() const;
void RemoveParticle(Particle *pParticle);
void RemoveAllParticles();
private:
CParticleEffectBinding *m_pEffectBinding;
CEffectMaterial *m_pMaterial;
float m_flTimeDelta;
bool m_bGotFirst;
Particle *m_pNextParticle;
};
// --------------------------------------------------------------------------------------------------------
// // CParticleRenderIterator inlines
// --------------------------------------------------------------------------------------------------------
// //
inline CParticleRenderIterator::CParticleRenderIterator() {
m_pCur = NULL;
m_bGotFirst = false;
m_flPrevZ = 0;
m_nParticlesInCurrentBatch = 0;
m_MinZ = 1e24f;
m_MaxZ = -1e24f;
m_nZCoords = 0;
}
inline const Particle *CParticleRenderIterator::GetFirst() {
Assert(!m_bGotFirst);
m_bGotFirst = true;
m_pCur = m_pMaterial->m_Particles.m_pNext;
if (m_pCur == &m_pMaterial->m_Particles) return NULL;
m_pParticleDraw->m_pSubTexture = m_pCur->m_pSubTexture;
return m_pCur;
}
inline void CParticleRenderIterator::TestFlushBatch() {
++m_nParticlesInCurrentBatch;
if (m_nParticlesInCurrentBatch >= NUM_PARTICLES_PER_BATCH) {
m_pMeshBuilder->End(false, true);
m_pMeshBuilder->Begin(m_pMesh, MATERIAL_QUADS, NUM_PARTICLES_PER_BATCH * 4);
m_nParticlesInCurrentBatch = 0;
}
}
inline const Particle *CParticleRenderIterator::GetNext(float sortKey) {
Assert(m_bGotFirst);
Assert(m_pCur);
TestFlushBatch();
Particle *pNext = m_pCur->m_pNext;
// Update the incremental sort.
if (m_bBucketSort) {
m_MinZ = std::min(sortKey, m_MinZ);
m_MaxZ = std::max(sortKey, m_MaxZ);
m_zCoords[m_nZCoords] = sortKey;
++m_nZCoords;
} else {
// Swap with the previous particle (incremental sort)?
if (m_pCur != m_pMaterial->m_Particles.m_pNext && m_flPrevZ > sortKey) {
SwapParticles(m_pCur->m_pPrev, m_pCur);
} else {
m_flPrevZ = sortKey;
}
}
m_pCur = pNext;
if (m_pCur == &m_pMaterial->m_Particles) return NULL;
m_pParticleDraw->m_pSubTexture = m_pCur->m_pSubTexture;
return m_pCur;
}
inline ParticleDraw *CParticleRenderIterator::GetParticleDraw() const {
return m_pParticleDraw;
}
// --------------------------------------------------------------------------------------------------------
// // CParticleSimulateIterator inlines
// --------------------------------------------------------------------------------------------------------
// //
inline CParticleSimulateIterator::CParticleSimulateIterator() {
m_pNextParticle = NULL;
#ifdef _DEBUG
m_bGotFirst = false;
#endif
}
inline Particle *CParticleSimulateIterator::GetFirst() {
#ifdef _DEBUG
// Make sure they're either starting out fresh or that the previous guy
// iterated through all the particles.
if (m_bGotFirst) {
Assert(m_pNextParticle == &m_pMaterial->m_Particles);
}
#endif
Particle *pRet = m_pMaterial->m_Particles.m_pNext;
if (pRet == &m_pMaterial->m_Particles) return NULL;
#ifdef _DEBUG
m_bGotFirst = true;
#endif
m_pNextParticle = pRet->m_pNext;
return pRet;
}
inline Particle *CParticleSimulateIterator::GetNext() {
Particle *pRet = m_pNextParticle;
if (pRet == &m_pMaterial->m_Particles) return NULL;
m_pNextParticle = pRet->m_pNext;
return pRet;
}
inline void CParticleSimulateIterator::RemoveParticle(Particle *pParticle) {
m_pEffectBinding->RemoveParticle(pParticle);
}
inline void CParticleSimulateIterator::RemoveAllParticles() {
Particle *pParticle = GetFirst();
while (pParticle) {
RemoveParticle(pParticle);
pParticle = GetNext();
}
}
inline float CParticleSimulateIterator::GetTimeDelta() const {
return m_flTimeDelta;
}
#endif // PARTICLE_ITERATORS_H
| 26.165217
| 107
| 0.67996
|
[
"render"
] |
b2e26d28013ee04d00426249083f3fc617015db1
| 1,442
|
h
|
C
|
Backdoor.Win32.Aryan/Client/upnpnat.h
|
010001111/Vx-Suites
|
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
|
[
"MIT"
] | 2
|
2021-02-04T06:47:45.000Z
|
2021-07-28T10:02:10.000Z
|
Backdoor.Win32.Aryan/Client/upnpnat.h
|
010001111/Vx-Suites
|
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
|
[
"MIT"
] | null | null | null |
Backdoor.Win32.Aryan/Client/upnpnat.h
|
010001111/Vx-Suites
|
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
|
[
"MIT"
] | null | null | null |
#ifndef UPNPNAT_H
#define UPNPNAT_H
#include <string>
#include <vector>
#pragma warning(disable: 4251)
#define DefaultTimeOut 10
#define DefaultInterval 200
class __declspec (dllexport) UPNPNAT
{
public:
bool init(int time_out=DefaultTimeOut,int interval=DefaultInterval); //init
bool discovery();//find router
/****
**** _description: port mapping name
**** _destination_ip: internal ip address
**** _port_ex:external: external listen port
**** _destination_port: internal port
**** _protocal: TCP or UDP
***/
bool add_port_mapping(char * _description, char * _destination_ip, unsigned short int _port_ex, unsigned short int _destination_port, char * _protocal);//add port mapping
const char * get_last_error(){ return last_error.c_str();}//get last error
private:
bool get_description(); //
bool parser_description(); //
bool tcp_connect(const char * _addr,unsigned short int _port);
bool parse_mapping_info();
int udp_socket_fd;
int tcp_socket_fd;
typedef enum
{
NAT_INIT=0,
NAT_FOUND,
NAT_TCP_CONNECTED,
NAT_GETDESCRIPTION,
NAT_GETCONTROL,
NAT_ADD,
NAT_DEL,
NAT_GET,
NAT_ERROR
} NAT_STAT;
NAT_STAT status;
int time_out;
int interval;
std::string service_type;
std::string describe_url;
std::string control_url;
std::string base_url;
std::string service_describe_url;
std::string description_info;
std::string last_error;
std::string mapping_info;
};
#endif
| 22.888889
| 171
| 0.738558
|
[
"vector"
] |
b2e7dbda66fcec6428d39eae29c7d9b4d8db69d7
| 3,338
|
h
|
C
|
heligym/envs/renderer/src/py_api.h
|
ugurcanozalp/heli-gym
|
78d754f63f9d0bbc606da760bfff9218c84d8be3
|
[
"MIT"
] | 8
|
2021-04-21T06:38:44.000Z
|
2021-08-16T00:21:57.000Z
|
heligym/envs/renderer/src/py_api.h
|
ugurcanozalp/heli-gym
|
78d754f63f9d0bbc606da760bfff9218c84d8be3
|
[
"MIT"
] | null | null | null |
heligym/envs/renderer/src/py_api.h
|
ugurcanozalp/heli-gym
|
78d754f63f9d0bbc606da760bfff9218c84d8be3
|
[
"MIT"
] | null | null | null |
#ifdef _WIN32
#define BUILDING_DLL
#ifdef BUILD_RENDERER
#define RENDERER_API __declspec(dllexport)
#else
#define RENDERER_API __declspec(dllimport)
#endif
#elif linux
#define RENDERER_API
#endif
#include "gWindow.h"
// RENDERER API for creating shared libraries to call methods from Python.
// Creating window.
extern "C" RENDERER_API Window* create_window(const unsigned int WIDTH,
const unsigned int HEIGHT,
const char* title);
// Close window.
extern "C" RENDERER_API void close(Window* window);
// Check the window is closed or not.
extern "C" RENDERER_API bool is_close(Window* window);
// Render the window.
extern "C" RENDERER_API void render(Window* window);
// Terminate the OpenGL.
extern "C" RENDERER_API void terminate();
// Create model with its shaders.
extern "C" RENDERER_API Model* create_model(char* model_path, char* vertex_shader_file_path, char* fragment_shader_file_path);
// Add model as permanent drawables object to window.
extern "C" RENDERER_API void add_permanent_to_window(Window* window, Model* model);
// Add model as instantaneous drawables object to window.
extern "C" RENDERER_API void add_instantaneous_to_window(Window* window, Model* model);
// Translate model to locations. Locations will be in OpenGL coordinates.
extern "C" RENDERER_API void translate_model(Model* model, float x, float y, float z);
// Rotate model to angle. From will be an rotation around arbitrary angle.
extern "C" RENDERER_API void rotate_model(Model* model, float angle, float x, float y, float z);
// Scale model to the ratios for each axis.
extern "C" RENDERER_API void scale_model(Model* model, float x, float y, float z);
// Get FPS from the window.
extern "C" RENDERER_API float get_fps(Window* window);
// Set FPS of the window.
extern "C" RENDERER_API void set_fps(Window* window, float fps);
// Get Camera pointer of the window.
extern "C" RENDERER_API Camera* get_camera(Window* window);
// Set Camera position of each axis.
extern "C" RENDERER_API void set_camera_pos(Camera* camera, float x, float y, float z);
// Get camera position as float array.
extern "C" RENDERER_API float* get_camera_pos(Camera * camera);
// Check whether the window is visible or not.
extern "C" RENDERER_API bool is_visible(Window* window);
// Hide the window.
extern "C" RENDERER_API void hide_window(Window* window);
// Show the window.
extern "C" RENDERER_API void show_window(Window* window);
// Create guiText vector.
extern "C" RENDERER_API int create_guiTextVector(Window * window, const char* title,
float pos_x, float pos_y,
float size_x, float size_y);
// Add the str and val to guiText vector.
extern "C" RENDERER_API void add_guiText(Window* window, int v_guiText_ind, int size, char** _str, float* _val);
// Set the guiText of vector.
extern "C" RENDERER_API void set_guiText(Window* window, int v_guiText_ind, float* _val);
// Rotate the model Main Rotor with each angle which are in radians.
extern "C" RENDERER_API void rotate_MR(Model* model, float phi, float theta, float psi);
// Rotate the model Tail Rotor with each angle which are in radians.
extern "C" RENDERER_API void rotate_TR(Model* model, float phi, float theta, float psi);
| 37.088889
| 127
| 0.729778
|
[
"render",
"object",
"vector",
"model"
] |
b2f173b3f1847601b102ce09193dc69165eb8089
| 703
|
h
|
C
|
node.h
|
osklunds/skip-list
|
7e8666f16b655b6cb1ce3b7f7f08190d5ee0d0d1
|
[
"BSL-1.0"
] | null | null | null |
node.h
|
osklunds/skip-list
|
7e8666f16b655b6cb1ce3b7f7f08190d5ee0d0d1
|
[
"BSL-1.0"
] | null | null | null |
node.h
|
osklunds/skip-list
|
7e8666f16b655b6cb1ce3b7f7f08190d5ee0d0d1
|
[
"BSL-1.0"
] | null | null | null |
#pragma once
#include <memory>
#include <vector>
#include <random>
using namespace std;
class Node {
//public:
private:
static mt19937 generator;
static uniform_real_distribution<> distribution;
static int get_a_height(double probability);
vector<shared_ptr<Node>> next_nodes;
int value;
public:
static void initialize_randomness();
Node(double probability);
Node(int height);
void initialize_next_nodes(int height);
int height();
void increase_height_to(int new_height);
shared_ptr<Node> get_next_node_at_index(int index);
void set_next_node_at_index(int index, shared_ptr<Node> node);
int get_value();
void set_value(int value);
};
| 20.085714
| 66
| 0.721195
|
[
"vector"
] |
b2f2c521eaed43003b61557ae877c510301b38d4
| 844
|
h
|
C
|
Lib/OakModel/NodeSettings.h
|
MNL82/oakmodelview
|
916f271dbca26f774828ad0fc512d260f14bfb04
|
[
"MIT"
] | 2
|
2018-09-26T08:28:48.000Z
|
2019-04-28T06:35:35.000Z
|
Lib/OakModel/NodeSettings.h
|
MNL82/oakmodelview
|
916f271dbca26f774828ad0fc512d260f14bfb04
|
[
"MIT"
] | 1
|
2019-04-28T06:49:17.000Z
|
2019-05-01T06:59:25.000Z
|
Lib/OakModel/NodeSettings.h
|
MNL82/oakmodelview
|
916f271dbca26f774828ad0fc512d260f14bfb04
|
[
"MIT"
] | null | null | null |
/**
* oakmodelview - version 0.1.0
* --------------------------------------------------------
* Copyright (C) 2017, by Mikkel Nøhr Løvgreen ([email protected])
* Report bugs and download new versions at http://oakmodelview.com/
*
* This library is distributed under the MIT License.
* See accompanying file LICENSE in the root folder.
*/
#pragma once
namespace Oak::Model {
// =============================================================================
// Class definition
// =============================================================================
class NodeSettings
{
public:
NodeSettings();
NodeSettings& operator=(const NodeSettings& copy);
bool hideVariantInstance() const;
void sethideVariantInstance(bool value);
private:
bool m_hideVariantInstance = false;
};
} // namespace Oak::Model
| 24.114286
| 80
| 0.530806
|
[
"model"
] |
b2f30c3ad7db7258d377519d21c7821fc8b93f28
| 18,627
|
c
|
C
|
hips/sources/ahc3.c
|
mikelandy/HIPS
|
fb5440573848cd22d55771484e3c036b6007f780
|
[
"MIT"
] | null | null | null |
hips/sources/ahc3.c
|
mikelandy/HIPS
|
fb5440573848cd22d55771484e3c036b6007f780
|
[
"MIT"
] | null | null | null |
hips/sources/ahc3.c
|
mikelandy/HIPS
|
fb5440573848cd22d55771484e3c036b6007f780
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 1991 Michael Landy
*
* Disclaimer: No guarantees of performance accompany this software,
* nor is any responsibility assumed on the part of the authors. All the
* software has been tested extensively and every effort has been made to
* insure its reliability.
*/
/*
* ahc3.c - 3D adaptive hierarchical coding into binary trees of binary images
*
* usage: ahc3 [-t stackrow stackcol] [-f stackdepth]
* [-d] [-s] [-v] [-g | -a > outseq] < inseq
*
* stackrow, stackcol and stackdepth determine the size of the area
* which is ahc3-encoded as a tree in the forest. All must be powers of
* 2, stackrow and stackcol must be divisors of their corresponding
* spatial dimensions. Stackdepth defaults to the largest power of 2
* divisor of the number of frames, and stackrow and stackcol default to
* the largest power of 2 which is a divisor of the number of rows and
* the number of columns, respectively.
*
* -g indicates that actual code should be generated. The full code
* is: {W,B,V,H,D}-->{10,11,00,010,011}. (If only two cuts are possible
* they are encoded by {00,01}; if one only, by {0}.) The output is in a
* special format: PFAHC3, each frame is bit-packed, with the last word
* of the tree padded with zeroes to the right. The number of output
* bytes is reported on "stderr". -a specifies that actual code be generated
* in ASCII. Only one of -g and -a may be specified. if -a is specified the
* output is not in HIPS format (there is no header). Specification of -s
* produces statistics for each frame in addition to totals. -v (verbose)
* is useful only for debugging purposes, and prints messages about the
* program's progress. -d (debug) is another debugging flag, which outputs
* the entire stored tree structure.
*
* The input must be in byte-unpacked-format with 1 bit per pixel (in other
* words, ahc3 only codes nonzero vs zero pixels). The coding
* assumptions are 2 bits per black or white node, 2 or 3 bits per meta
* symbol. Except at the lowest level where the two pixels are coded as a
* "nibble" in 1 bit. Also if an area is divided into two homogenous
* areas, the second area is coded in 1 bit (0) , since it must be of
* color different from that of the first area. (If -g is specified, the actual
* code is generated. It is left shifted and packed, with the last word of
* each tree padded with 1's to the right.) Compression statistics are
* given on "stderr". The program computes the number of input bits,
* output bits and compression ratio.
*
* to load: cc -o ahc3 ahc3.c -lhips
*
* Yoav Cohen - 4/10/83
* modified by Mike Landy - 6/21/83
* HIPS 2 - msl - 7/22/91
*/
#include <stdio.h>
#include <hipl_format.h>
static Flag_Format flagfmt[] = {
{"t",{LASTFLAG},1,{{PTINT,"-1","stackrow"},{PTINT,"-1","stackcol"},
LASTPARAMETER}},
{"f",{LASTFLAG},1,{{PTINT,"-1","stackdepth"},LASTPARAMETER}},
{"s",{LASTFLAG},0,{{PTBOOLEAN,"FALSE"},LASTPARAMETER}},
{"d",{LASTFLAG},0,{{PTBOOLEAN,"FALSE"},LASTPARAMETER}},
{"v",{LASTFLAG},0,{{PTBOOLEAN,"FALSE"},LASTPARAMETER}},
{"g",{"a",LASTFLAG},0,{{PTBOOLEAN,"FALSE"},LASTPARAMETER}},
{"a",{"g",LASTFLAG},0,{{PTBOOLEAN,"FALSE"},LASTPARAMETER}},
LASTFLAG};
int types[] = {PFBYTE,LASTTYPE};
#define AHCNULL 0
#define B 1
#define W 2
#define V 3
#define H 4
#define D 5
byte *inpic;
struct node {
int len;
char sym;
union {
struct node *pt;
char ch;
} lch;
union {
struct node *pt;
char ch;
} rch;
};
struct node ******p;
int nnr,nnc,nnd;
char *obuf;
int bufindex,bitindex,bytesout=0;
h_boolean gsw,asw,vsw,dsw;
int nr,nc,nrc,stackrow,stackcol,stackdepth,enc2(),encode();
int outbit(),flushbuf(),acode(),asons(),aprint(),lenprint();
int main(argc,argv)
int argc;
char **argv;
{
struct header hd,hdp,hdo;
Filename filename;
FILE *fp;
h_boolean ssw;
byte *in;
struct node *****p1,****p2,***p3,**p4,*p5;
struct node *****tp1,****tp2,***tp3,**tp4,*tp5,*pt;
int f,ifr,i,j,k,l,m,n,sumlen,len,v,h,d,s,ofr,it1,it2,r,c,low;
int method;
Progname = strsave(*argv);
parseargs(argc,argv,flagfmt,&stackrow,&stackcol,&stackdepth,&ssw,
&dsw,&vsw,&gsw,&asw,FFONE,&filename);
fp = hfopenr(filename);
fread_header(fp,&hd,filename);
nr = hd.orows;
nc = hd.ocols;
f = hd.num_frame;
if (nr<=0 || nc<=0 || f<=0)
perr(HE_MSG,"input image dimensions must be greater than zero");
if (stackrow < 0) {
for (i=1;nr%(1<<i)==0;i++);
stackrow = 1 << (i-1);
}
if (stackcol < 0) {
for (i=1;nc%(1<<i)==0;i++);
stackcol = 1 << (i-1);
}
if (stackdepth < 0) {
for (i=1;f%(1<<i)==0;i++);
stackdepth = 1 << (i-1);
}
if (stackrow<1 || stackcol<1 || stackdepth<1)
perr(HE_MSG,"stack args must be >= 1");
for (nnr=0;(1<<nnr)<stackrow;nnr++);
for (nnc=0;(1<<nnc)<stackcol;nnc++);
for (nnd=0;(1<<nnd)<stackdepth;nnd++);
fprintf(stderr,"%s: stacksize is %d x %d x %d\n",Progname,stackrow,
stackcol,stackdepth);
if ((1<<nnr)!=stackrow || (1<<nnc)!=stackcol || (1<<nnd)!=stackdepth)
perr(HE_MSG,"stack dimensions must be powers of 2");
if ((nr % stackrow) != 0 || (nc % stackcol) != 0)
perr(HE_MSG,
"stack sizes must divide the number of rows and columns");
if (f < stackdepth)
perr(HE_MSG,"stackdepth is too large");
if (nnr==0 && nnc==0 && nnd==0)
perr(HE_MSG,"stack size must be bigger than 1 x 1 x 1");
nrc = nr*nc;
ofr = f - (f%stackdepth);
if (ofr!=f)
fprintf(stderr,"%s: only %d frames are encoded\n",Progname,ofr);
/* alloc several frames (stackdepth, to be precise) */
setsize(&hd,nr*stackdepth,nc);
alloc_image(&hd);
method = fset_conversion(&hd,&hdp,types,filename);
if (hdp.numcolor > 1 && stackdepth > 1)
perr(HE_MSG,"can't handle color images with stackdepth > 1");
if (hdp.numcolor > 1)
f = ofr = hdp.num_frame;
inpic = hdp.image;
if (gsw)
obuf=(char *)halloc(512,sizeof(char));
p = (struct node ******) halloc(nnr+1,sizeof(struct node *****));
p1 = (struct node *****)
halloc((nnr+1)*(nnc+1),sizeof(struct node ****));
p2 = (struct node ****)
halloc((nnr+1)*(nnc+1)*(nnd+1),sizeof(struct node ***));
p3 = (struct node ***)
halloc(((nnc+1)*(nnd+1)*((1<<(nnr+1))-1)) - (1<<nnr),
sizeof(struct node **));
p4 = (struct node **)
halloc(((nnd+1)*((1<<(nnr+1))-1)*((1<<(nnc+1))-1)) -
((1<<nnr)*(1<<nnc)),
sizeof(struct node *));
p5 = (struct node *)
halloc((((1<<(nnr+1))-1)*((1<<(nnc+1))-1)*((1<<(nnd+1))-1)) -
((1<<nnr)*(1<<nnc)*(1<<nnd)),
sizeof(struct node));
/* internal allocation */
tp1=p1; tp2=p2; tp3=p3; tp4=p4; tp5=p5;
for (i=0;i<=nnr;i++) {
p[i]=tp1; tp1 += (nnc+1);
r=1<<(nnr-i);
for (j=0;j<=nnc;j++) {
p[i][j]=tp2; tp2 += (nnd+1);
c=1<<(nnc-j);
for (k=0;k<=nnd;k++) {
if (i==0 && j==0 && k==0) continue;
p[i][j][k]=tp3; tp3 += r;
s=1<<(nnd-k);
for (l=0;l<r;l++) {
p[i][j][k][l]=tp4; tp4 += c;
for (m=0;m<c;m++) {
p[i][j][k][l][m]=tp5; tp5 += s;
}
}
}
}
}
if (vsw)
fprintf(stderr,"%s: done allocation\n",Progname);
if (gsw) {
setsize(&hdp,nr,nc);
dup_headern(&hdp,&hdo);
hdo.pixel_format=PFAHC3;
hdo.num_frame=ofr;
setparam(&hdo,"stackrow",PFINT,1,stackrow);
setparam(&hdo,"stackcol",PFINT,1,stackcol);
setparam(&hdo,"stackdepth",PFINT,1,stackdepth);
write_headeru(&hdo,argc,argv);
setsize(&hdp,nr*stackdepth,nc);
}
sumlen=0;
for (ifr=0;ifr<ofr/stackdepth;ifr++) {
fread_imagec(fp,&hd,&hdp,method,ifr,filename);
in = inpic;
for (i=0;i<nrc*stackdepth;i++,in++)
*in = (*in==0) ? B : W;
if (vsw)
fprintf(stderr,"%s: done initialization\n",Progname);
for (it1=0;it1<nr/stackrow;it1++)
for (it2=0;it2<nc/stackcol;it2++) {
if (vsw)
fprintf(stderr,"%s: it1=%d, it2=%d\n",
Progname,it1,it2);
enc2(inpic+it1*nc*stackrow+it2*stackcol);
if (vsw)
fprintf(stderr,"%s: done enc2()\n",Progname);
for (m=2;m<=nnr+nnc+nnd;m++)
for (v=0;v<=nnr && v<=m;v++)
for (h=0;h<=nnc && h<=m;h++) {
d=m-v-h;
if (d<0||d>nnd)continue;
if (vsw)
fprintf(stderr,"%s: calling encode(%d,%d,%d) ",
Progname,v,h,d);
encode(v,h,d);
if (vsw)
fprintf(stderr,"...done\n");
}
len=p[nnr][nnc][nnd][0][0][0].len;
sumlen+=len;
if (ssw&&f>1)
fprintf(stderr,"%s: frame #%d, CR=%5.3f\n",Progname,
ifr,(double)len/(stackrow*stackcol*stackdepth));
if (dsw) {
for (i=0;i<=nnr;i++) {
r=1<<(nnr-i);
for (j=0;j<=nnc;j++) {
c=1<<(nnc-j);
for (k=0;k<=nnd;k++) {
if (i==0 && j==0 && k==0)
continue;
if ((i+j+k)==1)
low=1;
else
low=0;
s=1<<(nnd-k);
for (l=0;l<r;l++)
for (m=0;m<c;m++)
for (n=0;n<s;n++) {
pt= &p[i][j][k][l][m][n];
printf("%p ",(void *) pt);
printf("p[%d][%d][%d][%d][%d][%d] ",i,j,k,l,m,n);
printf("sym=%d, len=%d, ",pt->sym,pt->len);
if (!low)
printf("pointers: %p %p",pt->lch.pt,pt->rch.pt);
printf("\n");
}
}
}
}
}
if (asw||gsw)
acode(ifr);
}
}
i=ofr*nrc;
j=sumlen;
fprintf(stderr,"%s: Total Compression Ratio = %5.4f\n",Progname,
(double) sumlen/(ofr*nrc));
if (gsw)
fprintf(stderr," %d bytes written out\n",bytesout);
return(0);
}
/**************************************************************************/
int enc2(pic)
char *pic;
{
struct node *pt;
char *in1,*in2,*in11,*in22,*in111,*in222,p1,p2;
int ir,ic,il;
/* To encode the m=1 diagonal */
/* vertical pairs */
in1=pic; in2=pic+nc;
for (il=0;il<stackdepth;il++,in1+=nrc,in2+=nrc)
for (ir=0,in11=in1,in22=in2;ir<stackrow/2;
ir++,in11+=(nc+nc),in22+=(nc+nc))
for (ic=0,in111=in11,in222=in22;ic<stackcol;ic++) {
p1= *in111++; p2= *in222++;
pt= &p[1][0][0][ir][ic][il];
pt->len = 2;
if (p1==p2)
pt->sym = p1;
else {
pt->sym = H;
pt->lch.ch = p1; pt->rch.ch = p2;
}
}
/* horizontal pairs */
in1=pic; in2=pic+1;
for (il=0;il<stackdepth;il++,in1+=nrc,in2+=nrc)
for (ir=0,in11=in1,in22=in2;ir<stackrow;ir++,in11+=nc,in22+=nc)
for (ic=0,in111=in11,in222=in22;ic<stackcol/2;ic++,in111+=2,in222+=2) {
p1= *in111; p2= *in222;
pt= &p[0][1][0][ir][ic][il];
pt->len = 2;
if (p1==p2)
pt->sym = p1;
else {
pt->sym = V;
pt->lch.ch = p1; pt->rch.ch = p2;
}
}
/* pairs across layers */
in1=pic; in2=pic+nrc;
for (il=0;il<stackdepth/2;il++,in1+=(nrc+nrc),in2+=(nrc+nrc))
for (ir=0,in11=in1,in22=in2;ir<stackrow;ir++,in11+=nc,in22+=nc)
for (ic=0,in111=in11,in222=in22;ic<stackcol;ic++) {
p1= *in111++; p2= *in222++;
pt= &p[0][0][1][ir][ic][il];
pt->len = 2;
if (p1==p2)
pt->sym = p1;
else {
pt->sym = D;
pt->lch.ch = p1; pt->rch.ch = p2;
}
}
return(0);
}
int encode(v,h,d)
int v,h,d;
{
struct node *pt,*hch1,*hch2,*vch1,*vch2,*dch1,*dch2;
char hsym,vsym,dsym,hsym1,hsym2,vsym1,vsym2,dsym1,dsym2;
int ir,ic,il,hlen,vlen,dlen;
int nbits,max;
nbits=0; if (v>0) nbits++; if (h>0) nbits++; if (d>0) nbits++;
if (nbits<=0||nbits>3)
perr(HE_MSG,"error1 in encode()");
for (il=0;il<(1<<(nnd-d));il++)
for (ir=0;ir<(1<<(nnr-v));ir++)
for (ic=0;ic<(1<<(nnc-h));ic++) {
pt= &p[v][h][d][ir][ic][il];
/* is a h-cut possible ? */
if (v==0) hlen=0; /* no */
else { /* yes */
hch1 = &p[v-1][h][d][ir+ir][ic][il];
hch2 = &p[v-1][h][d][ir+ir+1][ic][il];
hsym1 = hch1->sym;
hsym2 = hch2->sym;
/* is it uniform ? */
if ((hsym1==B && hsym2==B) || (hsym1==W && hsym2==W)) {
/* yes */
hsym=hsym1;
hlen=2;
}
else { /* non-uniform */
hlen = hch1->len + hch2->len + nbits;
hsym = H;
if ((hsym1==B||hsym1==W) &&
(hsym2==B||hsym2==W))
--hlen;
}
}
/* is a v-cut possible ? */
if (h==0)
vlen=0; /* no */
else { /* yes */
vch1 = &p[v][h-1][d][ir][ic+ic][il];
vch2 = &p[v][h-1][d][ir][ic+ic+1][il];
vsym1 = vch1->sym;
vsym2 = vch2->sym;
/* is it uniform ? */
if ((vsym1==B && vsym2==B)
|| (vsym1==W && vsym2==W)) { /* yes */
vsym=vsym1;
vlen=2;
}
else { /* non-uniform */
vlen = vch1->len + vch2->len +
((nbits==3)?2:nbits);
vsym = V;
if ((vsym1==B||vsym1==W) &&
(vsym2==B||vsym2==W))
--vlen;
}
}
/* is a d-cut possible ? */
if (d==0) dlen=0; /* no */
else { /* yes */
dch1 = &p[v][h][d-1][ir][ic][il+il];
dch2 = &p[v][h][d-1][ir][ic][il+il+1];
dsym1 = dch1->sym;
dsym2 = dch2->sym;
/* is it uniform ? */
if ((dsym1==B && dsym2==B)
||(dsym1==W && dsym2==W)) { /* yes */
dsym=dsym1;
dlen=2;
}
else { /* non-uniform */
dlen = dch1->len + dch2->len + nbits;
dsym = D;
if ((dsym1==B||dsym1==W) &&
(dsym2==B||dsym2==W))
--dlen;
}
}
max=hlen; if (vlen>max)max=vlen; if (dlen>max)max=dlen; max++;
if (hlen==0)hlen=max;
if (vlen==0)vlen=max;
if (dlen==0)dlen=max;
if (hlen<= vlen && hlen<= dlen) {
pt->sym = hsym; pt->len = hlen;
if (hsym==H)
{ pt->rch.pt = hch2; pt->lch.pt = hch1; }
else
{ pt->rch.pt = AHCNULL; pt->lch.pt = AHCNULL; }
}
else if (vlen <= dlen) {
pt->sym = vsym;
pt->len = vlen;
if (vsym==V)
{ pt->rch.pt = vch2; pt->lch.pt = vch1; }
else
{ pt->rch.pt = AHCNULL; pt->lch.pt = AHCNULL; }
}
else {
pt->sym = dsym;
pt->len = dlen;
if (dsym==D)
{ pt->rch.pt = dch2; pt->lch.pt = dch1; }
else
{ pt->rch.pt = AHCNULL; pt->lch.pt = AHCNULL; }
}
}
return(0);
}
int outbit(bit)
int bit;
{
/* on entry bufindex and bitindex point to the new available location */
if (gsw) {
if (bit<0 || bit>1)
perr(HE_MSG,"error in outbit()");
obuf[bufindex] += bit;
bitindex++;
if (bitindex<8)
obuf[bufindex] = obuf[bufindex]<<1;
else {
bufindex++; bitindex=0;
if (bufindex>511) {
fwrite(obuf,512,1,stdout);
bytesout+=512; bufindex=0;
}
obuf[bufindex]=0;
}
}
return(0);
}
int flushbuf()
{
if (bufindex==0 && bitindex==0)
return(0);
if (bitindex>0) {
obuf[bufindex]=obuf[bufindex]<<(7-bitindex);
bufindex++;
}
fwrite(obuf,bufindex,1,stdout);
bytesout += (bufindex);
return(0);
}
int acode(frame)
int frame;
{
struct node *pt;
char sym;
if (gsw)
{bufindex=bitindex=0;obuf[0]=0;}
else
printf("\n\nAHC: Code for batch # %d\n\n",frame);
pt = &p[nnr][nnc][nnd][0][0][0];
sym=pt->sym;
switch(sym) {
case W: aprint(0,'W','2');outbit(1);outbit(0);
break;
case B: aprint(0,'B','2');outbit(1);outbit(1);
break;
case V: if (nnr==0&&nnd==0)
{ aprint(0,'V','1');outbit(0); }
else { aprint(0,'V','2');outbit(0);outbit(0); }
break;
case H: if (nnc==0&&nnd==0)
{ aprint(0,'H','1');outbit(0); }
else if (nnd==0)
{ aprint(0,'H','2');outbit(0);outbit(1); }
else if (nnc==0)
{ aprint(0,'H','2');outbit(0);outbit(0); }
else { aprint(0,'H','3');outbit(0);outbit(1);outbit(0); }
break;
case D: if (nnr==0&&nnc==0)
{ aprint(0,'D','1');outbit(0); }
else if (nnr==0||nnc==0)
{ aprint(0,'D','2');outbit(0);outbit(1); }
else { aprint(0,'D','3');outbit(0);outbit(1);outbit(1); }
break;
default: perr(HE_MSG,"error in acode()");
}
lenprint(pt->len);
if (sym==H||sym==V||sym==D)
asons(pt,nnc,nnr,nnd,0);
if (gsw)
flushbuf();
else
putchar('\n');
return(0);
}
int asons(pt,h,v,d,level)
struct node *pt;
int h,v,d,level;
{
char sym,sym1,sym2;
int level1,hh,vv,dd;
sym=pt->sym;
if (sym==W||sym==B)
perr(HE_MSG,"error 0 in asons()");
level1=level+1;
/* sons are single pixels: */
if (h+v+d==1) {
if (pt->lch.ch==W)
{ aprint(level1,'W','1');outbit(0); }
else
{ aprint(level1,'B','1');outbit(1); }
return(0);
}
/* other cases */
hh=h;vv=v;dd=d;
if (sym==D)
dd--;
else if (sym==H)
vv--;
else if (sym==V)
hh--;
sym1=pt->lch.pt->sym; sym2=pt->rch.pt->sym;
switch(sym1) {
case W: aprint(level1,'W','2');outbit(1);outbit(0);
lenprint(pt->lch.pt->len);
break;
case B: aprint(level1,'B','2');outbit(1);outbit(1);
lenprint(pt->lch.pt->len);
break;
case V: if (vv==0&&dd==0)
{ aprint(level1,'V','1');outbit(0); }
else { aprint(level1,'V','2');outbit(0);outbit(0); }
lenprint(pt->lch.pt->len);
asons(pt->lch.pt,hh,vv,dd,level1);
break;
case H: if (hh==0&&dd==0)
{ aprint(level1,'H','1');outbit(0); }
else if (dd==0)
{ aprint(level1,'H','2');outbit(0);outbit(1); }
else if (hh==0)
{ aprint(level1,'H','2');outbit(0);outbit(0); }
else { aprint(level1,'H','3');outbit(0);outbit(1);outbit(0); }
lenprint(pt->lch.pt->len);
asons(pt->lch.pt,hh,vv,dd,level1);
break;
case D: if (vv==0&&hh==0)
{ aprint(level1,'D','1');outbit(0); }
else if (vv==0||hh==0)
{ aprint(level1,'D','2');outbit(0);outbit(1); }
else { aprint(level1,'D','3');outbit(0);outbit(1);outbit(1); }
lenprint(pt->lch.pt->len);
asons(pt->lch.pt,hh,vv,dd,level1);
break;
default: fprintf(stderr,"%s: funny character: %d-%c-\n",
Progname,(unsigned int)sym1,sym1);
perr(HE_MSG,"error 1 in asons");
}
switch(sym2) {
case W: if (sym1==B || sym1==W)
{aprint(level1,'U','1');outbit(1);
(pt->rch.pt->len)--;}
else
{aprint(level1,'W','2');outbit(1);outbit(0);}
lenprint(pt->rch.pt->len);
break;
case B: if (sym1==B || sym1==W)
{aprint(level1,'U','1');outbit(1);
(pt->rch.pt->len)--;}
else
{aprint(level1,'B','2');outbit(1);outbit(1);}
lenprint(pt->rch.pt->len);
break;
case V: if (vv==0&&dd==0)
{ aprint(level1,'V','1');outbit(0); }
else { aprint(level1,'V','2');outbit(0);outbit(0); }
lenprint(pt->rch.pt->len);
asons(pt->rch.pt,hh,vv,dd,level1);
break;
case H: if (hh==0&&dd==0)
{ aprint(level1,'H','1');outbit(0); }
else if (dd==0)
{ aprint(level1,'H','2');outbit(0);outbit(1); }
else if (hh==0)
{ aprint(level1,'H','2');outbit(0);outbit(0); }
else { aprint(level1,'H','3');outbit(0);outbit(1);outbit(0); }
lenprint(pt->rch.pt->len);
asons(pt->rch.pt,hh,vv,dd,level1);
break;
case D: if (vv==0&&hh==0)
{ aprint(level1,'D','1');outbit(0); }
else if (vv==0||hh==0)
{ aprint(level1,'D','2');outbit(0);outbit(1); }
else { aprint(level1,'D','3');outbit(0);outbit(1);outbit(1); }
lenprint(pt->rch.pt->len);
asons(pt->rch.pt,hh,vv,dd,level1);
break;
default: fprintf(stderr,"%s: funny character: %d -%c-\n",
Progname,(unsigned int) sym2,sym2);
perr(HE_MSG,"error 2 in asons");
}
return(0);
}
int aprint(level,ch1,ch2)
int level;
char ch1,ch2;
{
int i;
if (asw) {
putchar('\n');
while(level-- >0) { for (i=0;i<7;i++)putchar(' ');}
putchar(ch1);putchar(ch2);
}
return(0);
}
int lenprint(len)
int len;
{
if (asw)
printf(" (%d)",len);
return(0);
}
| 26.61
| 80
| 0.564718
|
[
"3d"
] |
b2f48a35a4d2081c9885ecb7f72d2918a8204b42
| 507
|
h
|
C
|
src/Shapes/Shape.h
|
rbetik12/raytracer
|
a9a23739011104d18bf683c0d8e9e6ebcc6a3947
|
[
"MIT"
] | null | null | null |
src/Shapes/Shape.h
|
rbetik12/raytracer
|
a9a23739011104d18bf683c0d8e9e6ebcc6a3947
|
[
"MIT"
] | null | null | null |
src/Shapes/Shape.h
|
rbetik12/raytracer
|
a9a23739011104d18bf683c0d8e9e6ebcc6a3947
|
[
"MIT"
] | null | null | null |
#pragma once
#include <geometry.h>
#include "../Material.h"
namespace RayTracer {
enum ShapeType {
ESphere,
EPlane
};
class Shape {
public:
const Vec3f position;
const Material material;
const ShapeType type;
Shape(const Vec3f& position, const Material& material, const ShapeType type) : position(position), material(material), type(type) {}
virtual bool RayIntersect(const Vec3f& orig, const Vec3f& dir, float& t0) = 0;
};
}
| 22.043478
| 140
| 0.629191
|
[
"geometry",
"shape"
] |
b2f4bcbd440d57e8e89324406c6e54bfd0f6c410
| 31,252
|
c
|
C
|
expr.c
|
Jamboii/b-minor-compiler
|
a489e1627b1d504ec68f8447255ddc01cc73897a
|
[
"CC0-1.0"
] | null | null | null |
expr.c
|
Jamboii/b-minor-compiler
|
a489e1627b1d504ec68f8447255ddc01cc73897a
|
[
"CC0-1.0"
] | null | null | null |
expr.c
|
Jamboii/b-minor-compiler
|
a489e1627b1d504ec68f8447255ddc01cc73897a
|
[
"CC0-1.0"
] | null | null | null |
#include "expr.h"
#include "scope.h"
#include "scratch.h"
#include "label.h"
#include "library.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
extern int type_val;
extern int resolve_val;
extern int yylineno;
extern int reg_table[6];
/* create an expression*/
/*
inputs
- kind: expression type
- L: sitting to the left of the expression
- R: sitting to the right of the expression
output
- e: expr struct
*/
struct expr * expr_create( expr_t kind,
struct expr *L,
struct expr *R )
{
struct expr *e = calloc(1, sizeof(*e));
e->kind = kind;
e->left = L;
e->right = R;
return e;
}
/* create a name for an expression */
struct expr * expr_create_name(const char *name)
{
struct expr *e = expr_create(EXPR_NAME, 0, 0);
e->name = name;
return e;
}
/* create an integer literal for an expression */
struct expr * expr_create_integer_literal(int int_val)
{
struct expr *e = expr_create(EXPR_INT_LITERAL, 0, 0);
e->literal_value = int_val;
return e;
}
/* create a boolean for an expression */
struct expr * expr_create_boolean_literal(int bool_val)
{
struct expr *e = expr_create(EXPR_BOOLEAN_LITERAL, 0, 0);
e->literal_value = bool_val;
return e;
}
/* create a char for an expression */
struct expr * expr_create_char_literal(char char_val)
{
struct expr *e = expr_create(EXPR_CHAR_LITERAL, 0, 0);
e->literal_value = char_val;
return e;
}
/* create a string for an expression */
struct expr * expr_create_string_literal(const char *str_val)
{
struct expr *e = expr_create(EXPR_STRING_LITERAL, 0, 0);
// printf("Adding string %s\n",str_val);
e->string_literal = str_val;
return e;
}
/* expr_resolve - resolve the current expression by looking it up in the scope */
/*
inputs
- e: expr struct
*/
void expr_resolve(struct expr *e)
{
// resolve nothing if it doesn't exist
if (!e) return;
// check if the kind of expression is an identifier
if (e->kind == EXPR_NAME)
{
// printf("assigning a symbol to %s\n",e->name);
// try to link a symbol from the existing scope to the variable name
e->symbol = scope_lookup(e->name);
// scope_bind(e->name,e->symbol);
// if we can't actually link any sorta symbol name to our identifier theres a resolution error
if (!e->symbol)
{
printf("resolve error: %s is not defined\n",e->name);
resolve_val++;
}
// printf("COMPLETED assigning a symbol to %s\n",e->name);
}
// if we don't have an identifier just look at every other expression linked to this one until we do
expr_resolve(e->next); // resolve the "next" expression, which will be some new array element
expr_resolve(e->left); // resolve the left expression
expr_resolve(e->right); // resolve the right expression
}
/* exprs_resolve - resolve multiple expressions joined together by some linked list, for function parameter lists or array elements */
/*
inputs
- e: expr struct, has a next attribute associated
*/
void exprs_resolve(struct expr *e)
{
// resolve nothing if it doesn't exist
if (!e) return;
// resolve our current expression
expr_resolve(e);
// but also resolve the next expression, doesn't matter if it exists or not
exprs_resolve(e->next);
}
/* expression type checker */
/*
- computes the type of an expression recursively and return a new type object to represent it
- should check for errors within the expresision
- the result of this typecheck method should be used to compare against expectations in stmt_typecheck and decl_typecheck
*/
struct type * expr_typecheck(struct expr *e)
{
// if expression doesn't exist we gotta go
if (!e) return 0;
// fflush(stdout);
struct type *l = expr_typecheck(e->left);
struct type *r = expr_typecheck(e->right);
struct type *res;
// printf("expr typecheck ");
// expr_print(e);
// printf("\n");
// if (e->name) printf("expr name: %s\n",e->name);
// if (e->literal_value)
// {
// if (e->kind == EXPR_CHAR_LITERAL) printf("expr literal value: %c\n",e->literal_value);
// else printf("expr literal value: %i\n",e->literal_value);
// }
// if (e->string_literal)printf("expr string literal: %s\n",e->string_literal);
switch (e->kind)
{
case EXPR_ASSIGN: // 0
// if the left expression exists
if (l)
{
if (l->kind == TYPE_AUTO) // type auto must be reassigned to a new type
{
l = type_copy(r); // just copy the type of the RHS of the assignment
printf("notice: type of %s is ",e->left->name);
type_print(r);
printf("\n");
}
else if (!type_compare(l,r)) // if the types of the exprs on the left and the right side don't match at all
{
printf("type error: you can't assign a variable %s with a value of a different type silly\n", e->left->name);
type_val++;
}
else if (l->kind == TYPE_ARRAY && r->kind == TYPE_ARRAY) // do we have arrays on the left and right sides
{
if (!type_compare(l->subtype,r->subtype))
{
printf("type error: cannot assign two arrays %s and %s of different subtypes\n", e->left->name, e->right->name);
}
}
res = type_copy(l);
}
break;
case EXPR_ADD: // 1
case EXPR_SUB: // 2
case EXPR_MUL: // 3
case EXPR_DIV: // 4
case EXPR_MOD: // 5
case EXPR_EXP: // 6
// check to see if either side of the epxression is a non-integer
if (l->kind != TYPE_INTEGER || r->kind != TYPE_INTEGER)
{
// printf("type error: cannot perform a binary operation on a non-integer type\n");
printf("type error: cannot perform a binary operation between ");
type_print(r);
printf(" (");
expr_print(e->right);
printf(") and");
type_print(l);
printf(" (");
expr_print(e->left);
printf(")\n");
type_val++;
}
// create an integer type for this expression
res = type_create(TYPE_INTEGER, 0, 0, 0);
break;
case EXPR_LE: // 7
case EXPR_LT: // 8
case EXPR_GE: // 9
case EXPR_GT: // 10
// check to see if either operation of the comparison is a non-integer
if (l->kind != TYPE_INTEGER || r->kind != TYPE_INTEGER)
{
printf("type error: cannot perform a logical operation on non-integer type ");
// print an error message for an invalid left hand side
if (l->kind != TYPE_INTEGER)
{
type_print(l);
printf(" (");
expr_print(e->left);
printf(")\n");
type_val++;
}
// print an error message for an invalid right hand side
if (r->kind != TYPE_INTEGER)
{
type_print(r);
printf(" (");
expr_print(e->right);
printf(")\n");
type_val++;
}
// type_val++;
}
// create a boolean type for this expression
res = type_create(TYPE_BOOLEAN, 0, 0, 0);
break;
case EXPR_EQ: // 11
case EXPR_NEQ: // 12
// the types on both sides of this comparison need to be the same, check to see if this is true
if (!type_compare(l,r))
{
printf("type error: ");
type_print(l);
expr_print(e->left);
printf(" and ");
type_print(r);
expr_print(e->right);
printf("are of different types\n");
type_val++;
}
if (l->kind == TYPE_FUNCTION ||
l->kind == TYPE_ARRAY ||
l->kind == TYPE_VOID )
{
printf("type error: cannot compare equality for ");
type_print(l);
printf("\n");
type_val++;
}
// create a boolean type for this expression
res = type_create(TYPE_BOOLEAN, 0, 0, 0);
break;
case EXPR_AND: // 13
case EXPR_OR: // 14
// may only be applied to boolean values nice
if (l->kind != TYPE_BOOLEAN || r->kind != TYPE_BOOLEAN)
{
printf("type error: cannot perform logical operation on non-boolean ");
// print an error message for an invalid left hand side
if (l->kind != TYPE_BOOLEAN)
{
type_print(l);
printf("(");
expr_print(e->left);
printf(")");
type_val++;
}
// print an error message for an invalid right hand side
if (r->kind != TYPE_BOOLEAN)
{
if (l->kind != TYPE_BOOLEAN) printf(" and ");
type_print(r);
printf("(");
expr_print(e->right);
printf(") ");
type_val++;
}
printf("\n");
}
// create a boolean type for this expression
res = type_create(TYPE_BOOLEAN, 0, 0, 0);
break;
case EXPR_NOT: // 15
// may only be applied to boolean values nice
if (r->kind != TYPE_BOOLEAN)
{
printf("type error: cannot negate a non-boolean ");
type_print(r);
printf("(");
expr_print(e->right);
printf(")\n");
type_val++;
}
// create a boolean type for this expression
res = type_create(TYPE_BOOLEAN, 0, 0, 0);
break;
case EXPR_NEG: // 16
if (r->kind != TYPE_INTEGER)
{
printf("type error: cannot negate non-integer ");
type_print(r);
printf(" (");
expr_print(e->right);
printf(")\n");
type_val++;
}
res = type_create(TYPE_INTEGER, 0, 0, 0);
break;
case EXPR_INCR: // 17
case EXPR_DECR: // 18
if (l->kind != TYPE_INTEGER)
{
printf("type error: cannot perform a postfix operation on non-integer ");
type_print(l);
printf(" (");
expr_print(e->left);
printf(")\n");
type_val++;
}
res = type_create(TYPE_INTEGER, 0, 0, 0);
break;
case EXPR_GROUP: // 19
// printf("GROUP ");
// type_print(expr_typecheck(e->right));
// printf("\n");
// copy the type
res = type_copy(expr_typecheck(e->right));
break;
case EXPR_ARRELEM: // 20
// are we looking at an array's elements here
if (l->kind == TYPE_ARRAY)
{
// are we trying to get into a non-integer access
if (r->kind != TYPE_INTEGER)
{
printf("type error: cannot access %s array with non-integer \n", e->left->name);
type_val++;
}
// if the array multi-dimensional
if (e->right->right)
{
struct expr *r_expr = e->right;
while (r_expr)
{
// constantly look at each consecutive array access
if (expr_typecheck(r_expr)->kind != TYPE_INTEGER)
{
printf("type error: cannot access %s array with non-integer \n", e->left->name);
type_val++;
}
if (r_expr->right) r_expr = r_expr->right;
else r_expr = 0;
}
}
// add multiple array accesses
res = type_copy(l->subtype);
}
else // hey we got an error, this ain't an array
{
printf("type error: cannot index string %s with non-integer\n", e->left->name);
res = type_copy(l);
type_val++;
}
break;
case EXPR_INT_LITERAL: // 21
res = type_create(TYPE_INTEGER, 0, 0, 0); // create a new integer type
break;
case EXPR_BOOLEAN_LITERAL: // 22
res = type_create(TYPE_BOOLEAN, 0, 0, 0); // create a new boolean type
break;
case EXPR_CHAR_LITERAL: // 23
res = type_create(TYPE_CHARACTER, 0, 0, 0); // create a new character type
break;
case EXPR_STRING_LITERAL: // 24
res = type_create(TYPE_STRING, 0, 0, 0); // create a new string type
break;
case EXPR_NAME: // 25
// printf("copying identifier %s\n",e->name);
// printf("kind %i\n",e->symbol->type->kind);
// if (e->symbol)
// {
// printf("theres a symbol here\n");
// }
// else
// {
// printf("there's no symbol here\n");
// }
res = type_copy(e->symbol->type); // copy the symbol type
break;
case EXPR_FUNCCALL: // 26
// printf("Function call has been MADE\n");
if (l->kind == TYPE_FUNCTION)
{
struct param_list *p = e->left->symbol->type->params; // pointer to param list of actual function decl
struct expr *er = e->right; // pointer to the first param of a linked list for the function call
// make sure the types of the vars used in the function call are the same as the types of the variables in the declaration
if (!param_list_compare_call(p, er))
{
printf("type error: parameters not matching in function call of %s\n", e->left->name);
type_val++;
}
res = type_copy(l->subtype); // this is the return type of the function call
}
else // you're making a call to a non-function, stop that
{
printf("type error: cannot call non-function %s\n", e->left->name);
res = type_copy(l); // create a type copy to return anyway
type_val++;
}
break;
}
type_delete(l);
type_delete(r);
return res;
}
/*
- recursively calls itself for its left and right children
- each child will generate code such that the result will be left in the reg num noted in the reg field
- current node generates code using those registers
- current node frees the registers it no longer needs
extra stuff
- not all symbols are simple global vars
- when a symbol forms part of an instruction, symbol_codegen needs to return the string that gives the specific address for that symbol
*/
/* expression code generation */
void expr_codegen(struct expr *e, FILE *outfil)
{
// if there's no expression to generate code for then leave
if (!e) return;
// generate code based on type of expression
switch (e->kind)
{
// Interior node: generate children, then add them
case EXPR_ASSIGN: // 0
printf("assignment time\n");
// generate code for both sides of the assignment
expr_codegen(e->left, outfil);
expr_codegen(e->right, outfil);
// store the resulting register (left) onto the stack
// fprintf(outfil, "\tmov\t%s, %s\n", scratch_name(e->left->reg), symbol_codegen(e->right->symbol));
if (e->left->kind == EXPR_ARRELEM)
{
int idx = e->left->right->literal_value;
printf("array elem: index %i\n",idx*8);
// load the array again cause I'm lazy
fprintf(outfil, "\tadrp\t%s, %s\n", scratch_name(e->left->reg), e->left->left->name);
fprintf(outfil, "\tadd\t%s, %s, :lo12:%s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), e->left->left->name);
fprintf(outfil, "\tstr\t%s, [%s, %i]\n", scratch_name(e->right->reg), scratch_name(e->left->reg), idx*8);
}
else if (e->left->symbol->kind == SYMBOL_LOCAL)
{
printf("not an array element\n");
// fprintf(outfil, "\tmov\t%s, %s\n", scratch_name(e->left->reg), symbol_codegen(e->right->symbol));
fprintf(outfil, "\tstr\t%s, [sp, %s]\n", scratch_name(e->right->reg), symbol_codegen(e->left->symbol));
}
else // TODO check to see if global variable editing even works
{
printf("global variable storage: %s\n",e->left->name);
fprintf(outfil, "\tadrp\t%s, %s\n", scratch_name(e->left->reg), symbol_codegen(e->left->symbol));
fprintf(outfil, "\tadd\t%s, %s, :lo12:%s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), symbol_codegen(e->left->symbol));
fprintf(outfil, "\tstr\t%s, [%s]\n", scratch_name(e->right->reg), scratch_name(e->left->reg));
}
e->reg = e->left->reg;
break;
case EXPR_ADD: // 1
expr_codegen(e->left, outfil);
expr_codegen(e->right, outfil);
fprintf(outfil, "\tadd\t%s, %s, %s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), scratch_name(e->right->reg));
e->reg = e->left->reg;
scratch_free(e->right->reg);
break;
case EXPR_SUB: // 2
expr_codegen(e->left, outfil);
/*
int leftreg_ptr = e->left->reg;
if (e->right->kind == EXPR_FUNCCALL)
{
e->left->reg = 19;
}
*/
expr_codegen(e->right, outfil);
fprintf(outfil, "\tsub\t%s, %s, %s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), scratch_name(e->right->reg));
/*
if (e->right->kind == EXPR_FUNCCALL)
{
fprintf(outfil, "\tmov\t%s, %s\n", scratch_name(leftreg_ptr), scratch_name(e->left->reg));
e->left->reg = leftreg_ptr;
}
*/
e->reg = e->left->reg;
scratch_free(e->right->reg);
break;
case EXPR_MUL: // 3
expr_codegen(e->left, outfil);
expr_codegen(e->right, outfil);
fprintf(outfil, "\tmul\t%s, %s, %s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), scratch_name(e->right->reg));
e->reg = e->left->reg;
scratch_free(e->right->reg);
break;
case EXPR_DIV: // 4
expr_codegen(e->left, outfil);
expr_codegen(e->right, outfil);
fprintf(outfil, "\tsdiv\t%s, %s, %s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), scratch_name(e->right->reg));
e->reg = e->left->reg;
scratch_free(e->right->reg);
break;
case EXPR_MOD: // 5
expr_codegen(e->left, outfil); // left side of modulo operator (a)
expr_codegen(e->right, outfil); // right side of modulo operator (n)
// perform modulus operation - a mod n = a - [n * int(a/n)]
int div_reg = scratch_alloc();
fprintf(outfil, "\tsdiv\t%s, %s, %s\n", scratch_name(div_reg), scratch_name(e->left->reg), scratch_name(e->right->reg));
fprintf(outfil, "\tmul\t%s, %s, %s\n", scratch_name(e->right->reg), scratch_name(div_reg), scratch_name(e->right->reg));
fprintf(outfil, "\tsub\t%s, %s, %s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), scratch_name(e->right->reg));
// free left and right registers
e->reg = e->left->reg;
scratch_free(div_reg);
scratch_free(e->right->reg);
break;
case EXPR_EXP: // 6
expr_codegen(e->left, outfil); // base
expr_codegen(e->right, outfil); // exponent
// let's just hope these registers are in x0 and x1 lol
int base_reg = 0;
int expo_reg = 1;
if (e->left->reg != base_reg)
{
fprintf(outfil, "\tmov\t%s, %s\n", scratch_name(base_reg), scratch_name(e->left->reg));
}
if (e->right->reg != expo_reg)
{
fprintf(outfil, "\tmov\t%s, %s\n", scratch_name(expo_reg), scratch_name(e->right->reg));
}
// branch to our integer power function
fprintf(outfil, "\tbl\tinteger_power\n");
e->reg = e->left->reg;
scratch_free(e->left->reg);
scratch_free(e->right->reg);
break;
case EXPR_LE: // 7
case EXPR_LT: // 8
case EXPR_GE: // 9
case EXPR_GT: // 10
case EXPR_EQ: // 11
case EXPR_NEQ: // 12
expr_codegen(e->left, outfil);
expr_codegen(e->right, outfil);
// compare both sides of the expression
fprintf(outfil, "\tcmp\t%s, %s\n", scratch_name(e->left->reg), scratch_name(e->right->reg));
// conditional set a register based on one of the conditions
switch (e->kind)
{
case EXPR_LE: // 7
fprintf(outfil, "\tcset\t%s, le\n", scratch_name(e->left->reg));
break;
case EXPR_LT: // 8
fprintf(outfil, "\tcset\t%s, lt\n", scratch_name(e->left->reg));
break;
case EXPR_GE: // 9
fprintf(outfil, "\tcset\t%s, ge\n", scratch_name(e->left->reg));
break;
case EXPR_GT: // 10
fprintf(outfil, "\tcset\t%s, gt\n", scratch_name(e->left->reg));
break;
case EXPR_EQ: // 11
fprintf(outfil, "\tcset\t%s, eq\n", scratch_name(e->left->reg));
break;
case EXPR_NEQ: // 12
fprintf(outfil, "\tcset\t%s, ne\n", scratch_name(e->left->reg));
break;
}
// free unnecessary register and assign expression register
e->reg = e->left->reg;
scratch_free(e->right->reg);
break;
case EXPR_AND: // 13
expr_codegen(e->left, outfil);
expr_codegen(e->right, outfil);
// create an AND function
fprintf(outfil, "\tand\t%s, %s, %s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), scratch_name(e->right->reg));
// update expression register, maybe keep the unused register idk
e->reg = e->left->reg;
scratch_free(e->right->reg);
break;
case EXPR_OR: // 14
expr_codegen(e->left, outfil);
expr_codegen(e->right, outfil);
// create an AND function
fprintf(outfil, "\torr\t%s, %s, %s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), scratch_name(e->right->reg));
// update expression register, maybe keep the unused register idk
e->reg = e->left->reg;
scratch_free(e->right->reg);
break;
case EXPR_NOT: // 15
expr_codegen(e->right, outfil);
// do an equals comparison to 0
fprintf(outfil, "\tcmp\t%s, 0\n", scratch_name(e->right->reg));
fprintf(outfil, "\tcset\t%s, eq\n", scratch_name(e->right->reg));
// set new register of the expression
e->reg = e->right->reg;
break;
case EXPR_NEG: // 16
expr_codegen(e->right, outfil);
// use the negative instruction on the register
fprintf(outfil, "\tneg\t%s, %s\n", scratch_name(e->right->reg), scratch_name(e->right->reg));
// set new register of the expression
e->reg = e->right->reg;
break;
case EXPR_INCR: // 17
case EXPR_DECR: // 18
expr_codegen(e->left, outfil);
int temp_reg = scratch_alloc();
if (e->kind == EXPR_INCR)
fprintf(outfil, "\tadd\t%s, %s, 1\n", scratch_name(temp_reg), scratch_name(e->left->reg));
else if (e->kind == EXPR_DECR)
fprintf(outfil, "\tsub\t%s, %s, 1\n", scratch_name(temp_reg), scratch_name(e->left->reg));
else
{
printf("codegen error: how are you here in the incr/decr section.\n");
exit(1);
}
e->reg = e->left->reg;
// gotta also store this register into memory then free it
// check whether we're saving an array element, local, or global variable
if (e->left->kind == EXPR_ARRELEM)
{
int idx = e->left->right->literal_value;
// load the array again cause I'm lazy
fprintf(outfil, "\tadrp\t%s, %s\n", scratch_name(e->left->reg), e->left->left->name);
fprintf(outfil, "\tadd\t%s, %s, :lo12:%s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), e->left->left->name);
fprintf(outfil, "\tstr\t%s, [%s, %i]\n", scratch_name(temp_reg), scratch_name(e->left->reg), idx*8);
}
else if (e->left->symbol->kind == SYMBOL_LOCAL)
{
printf("not an array element\n");
fprintf(outfil, "\tstr\t%s, [sp, %s]\n", scratch_name(temp_reg), symbol_codegen(e->left->symbol));
}
else
{
printf("global variable storage: %s\n",e->left->name);
fprintf(outfil, "\tadrp\t%s, %s\n", scratch_name(e->left->reg), symbol_codegen(e->left->symbol));
fprintf(outfil, "\tadd\t%s, %s, :lo12:%s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), symbol_codegen(e->left->symbol));
fprintf(outfil, "\tstr\t%s, [%s]\n", scratch_name(temp_reg), scratch_name(e->left->reg));
// immediately load the value into x0 in case we wanna use it
fprintf(outfil, "\tldr\t%s, [%s]\n", scratch_name(e->left->reg), scratch_name(e->left->reg));
}
// free the registers afterward
scratch_free(temp_reg);
scratch_free(e->left->reg);
break;
case EXPR_GROUP: // 19
// expression grouping/precedence just doesn't work at all
expr_codegen(e->right,outfil);
e->reg = e->right->reg;
break;
case EXPR_ARRELEM: // 20
// TODO somehow implement the assignment of values to arrays which have not been declared yet
// TODO also assignment of new values to already declared arrays
printf("ARRAY ELEM INDEXING\n");
if (e->left) printf("name: %s\n",e->left->name);
if (e->right) printf("idx: %i\n",e->right->literal_value);
e->reg = scratch_alloc();
// instructions to deal with loading the array up
fprintf(outfil, "\tadrp\t%s, %s\n", scratch_name(e->reg), e->left->name);
fprintf(outfil, "\tadd\t%s, %s, :lo12:%s\n", scratch_name(e->reg), scratch_name(e->reg), e->left->name);
// now we gotta load up the exact element based on where it's located on the stack
// expr_codegen(e->right, outfil);
e->right->reg = scratch_alloc();
int idx = e->right->literal_value;
if (idx == 0)
fprintf(outfil, "\tldr\t%s, [%s]\n",scratch_name(e->right->reg),scratch_name(e->reg));
else
fprintf(outfil, "\tldr\t%s, [%s, %i]\n",scratch_name(e->right->reg),scratch_name(e->reg),idx*8);
// to be annoying and give probably the laziest and probably specific fix ever, just move the right reg into the arrays reg
fprintf(outfil, "\tmov\t%s, %s\n", scratch_name(e->reg), scratch_name(e->right->reg));
// scratch_free(e->right->reg);
scratch_free(e->right->reg);
// e->reg = e->right->reg;
break;
// Leaf node: allocate register and load value
case EXPR_INT_LITERAL: // 21
case EXPR_BOOLEAN_LITERAL: // 22
case EXPR_CHAR_LITERAL: // 23
e->reg = scratch_alloc();
fprintf(outfil, "\tmov\t%s, %d\n", scratch_name(e->reg), e->literal_value);
break;
case EXPR_STRING_LITERAL: // 24
e->reg = scratch_alloc();
// string label stuff here
int str_label = label_create();
// start up the data section once more
fprintf(outfil, "\t.data\n");
fprintf(outfil, "\t.section\t.rodata\n");
// allocate 2^3 = 8 bytes
fprintf(outfil, "\t.align\t3\n");
// string label
fprintf(outfil, "%s:\n", label_name(str_label));
// string value
fprintf(outfil, "\t.string\t%s\n", e->string_literal);
// go back to the text section
fprintf(outfil, "\t.text\n");
// now we need instructions to deal with this string
fprintf(outfil, "\tadrp\t%s, %s\n", scratch_name(e->reg), label_name(str_label));
fprintf(outfil, "\tadd\t%s, %s, :lo12:%s\n", scratch_name(e->reg), scratch_name(e->reg), label_name(str_label));
break;
case EXPR_NAME: // 25
e->reg = scratch_alloc();
if (e->symbol->kind != SYMBOL_GLOBAL)
{
printf("loading local variable/parameter %s\n",e->name);
// code to reference any parameter or local variable for anything
fprintf(outfil, "\tldr\t%s, [sp, %s]\n", scratch_name(e->reg), symbol_codegen(e->symbol));
// TODO maybe remove this line cause it might not be necessary (i think this is only for global vars)
// fprintf(outfil, "\tmov\t%s, %s\n", scratch_name(e->reg), symbol_codegen(e->symbol));
}
else
{
// code to reference a global variable within a function for anything
printf("loading global variable %s\n",e->name);
fprintf(outfil, "\tadrp\t%s, %s\n", scratch_name(e->reg), symbol_codegen(e->symbol));
fprintf(outfil, "\tadd\t%s, %s, :lo12:%s\n", scratch_name(e->reg), scratch_name(e->reg), symbol_codegen(e->symbol));
// TODO figure out if commenting this breaks things
// TODO this breaks only when we gotta store something to the global variable itself aka any assignment
// is there a way to find out if this name comes from an assignment?
fprintf(outfil, "\tldr\t%s, [%s]\n", scratch_name(e->reg), scratch_name(e->reg));
}
break;
case EXPR_FUNCCALL: // 26
{
struct expr *er = e->right; // parameters
struct expr *er_copy = e->right; // parameters copy
struct expr *el = e->left; // function identifier
// int i = 0;
// printf("funccall start\n");
// TODO somehow move other IR values into other registers before calling this
// let's try to at least
/*
int reg_move = 19;
for (int i=0;i<6;i++)
{
if (reg_table[i])
{
}
}
*/
// generate code for loading in those parameters
while (er)
{
// TODO fix this up, we gotta load the parameters into argument registers then branch to the function
// If i hardcode the parameters, have this loop a "mov" command
// generate code for parameter
expr_codegen(er, outfil);
// free register if possible
// scratch_free(er->reg);
// move to next pointer
er = er->next;
}
// scratch_print();
// printf("now we free\n");
// free up the registers we just used
while (er_copy)
{
scratch_free(er_copy->reg);
er_copy = er_copy->next;
}
// scratch_print();
// printf("argument end\n");
// branch to the function
fprintf(outfil, "\tbl\t%s\n",el->name);
/*
// TODO needs local variable storage for any return parameters, probably also needs a lot of fixes
if (expr_typecheck(el) != TYPE_VOID)
{
printf("returning for function %s\n", el->name);
e->reg = scratch_alloc();
fprintf(outfil, "\tstr\t%s, [sp, %i]\n", scratch_name(e->reg), STACK_SIZE-(el->symbol->which*8));
}
*/
// printf("done with return type\n");
/*
int funccall_result = scratch_alloc();
e->reg = funccall_result;
*/
break;
}
}
/*
// I'm just gonna try something
if (e->right)
{
if (e->right->kind == EXPR_FUNCCALL)
{
// save registers
// new register time
e->reg = 19;
}
}
*/
}
/* print an expression */
void expr_print(struct expr *e)
{
// return if the expression just does not exist
if (!e) return;
// print based on the kind of expression
switch (e->kind)
{
case EXPR_ASSIGN:
expr_print(e->left);
printf("=");
expr_print(e->right);
break;
case EXPR_ADD:
// printf("ADDLEFT KIND:%d ",e->left->kind);
expr_print(e->left);
printf("+");
// printf("ADDRIGHT KIND:%d ",e->right->kind);
expr_print(e->right);
break;
case EXPR_SUB:
// printf("SUBLEFT KIND:%d ",e->left->kind);
expr_print(e->left);
printf("-");
// printf("SUBRIGHT KIND:%d ",e->right->kind);
expr_print(e->right);
break;
case EXPR_MUL:
expr_print(e->left);
printf("*");
expr_print(e->right);
break;
case EXPR_DIV:
expr_print(e->left);
printf("/");
expr_print(e->right);
break;
case EXPR_MOD:
expr_print(e->left);
printf("%%");
expr_print(e->right);
break;
case EXPR_EXP:
expr_print(e->left);
printf("^");
expr_print(e->right);
break;
case EXPR_LE:
expr_print(e->left);
printf("<=");
expr_print(e->right);
break;
case EXPR_LT:
expr_print(e->left);
printf("<");
expr_print(e->right);
break;
case EXPR_GE:
expr_print(e->left);
printf(">=");
expr_print(e->right);
break;
case EXPR_GT:
expr_print(e->left);
printf(">");
expr_print(e->right);
break;
case EXPR_EQ:
expr_print(e->left);
printf("==");
expr_print(e->right);
break;
case EXPR_NEQ:
expr_print(e->left);
printf("!=");
expr_print(e->right);
break;
case EXPR_AND:
expr_print(e->left);
printf("&&");
expr_print(e->right);
break;
case EXPR_OR:
expr_print(e->left);
printf("||");
expr_print(e->right);
break;
case EXPR_NOT:
printf("!");
expr_print(e->right);
break;
case EXPR_NEG:
printf("-");
expr_print(e->right);
break;
case EXPR_INCR:
expr_print(e->left);
printf("++");
break;
case EXPR_DECR:
expr_print(e->left);
printf("--");
break;
case EXPR_GROUP:
printf("(");
expr_print(e->right);
printf(")");
break;
case EXPR_ARRELEM:
expr_print(e->left); // expr_create_name(ident) --> expr_create(EXPR_NAME,0,0) --> name
printf("[");
expr_print(e->right); // bracket --> [expr] --> [i] bracket --> expr->right = brackets --> bracket --> expr
printf("]");
e = e->right;
if (e->next)
{
while (e->next)
{
printf("[");
expr_print(e->next);
printf("]");
e = e->next;
}
}
break;
case EXPR_INT_LITERAL:
printf("%d",e->literal_value);
break;
case EXPR_BOOLEAN_LITERAL:
if (e->literal_value) printf("true");
else printf("false");
break;
case EXPR_CHAR_LITERAL:
printf("'%c'",e->literal_value);
break;
case EXPR_STRING_LITERAL:
printf("%s", e->string_literal);
break;
case EXPR_NAME:
printf("%s", e->name);
break;
case EXPR_FUNCCALL:
expr_print(e->left);
printf("(");
exprs_print(e->right);
printf(")");
break;
}
return;
}
/* print multiple expressions, for print, funccalls, arrayelems */
void exprs_print(struct expr *e)
{
/* print nothing if it doesn't exist */
if (!e) return;
expr_print(e);
if (e->next)
{
printf(", ");
}
exprs_print(e->next);
}
| 28.830258
| 138
| 0.624952
|
[
"object"
] |
b2f73e1f89dfa55150ea6c76744facf33e3720db
| 2,641
|
h
|
C
|
src/include/syntax/make_parser/tokenizer.h
|
on-keyday/utils
|
5364370eadfe909407ffded678bebfdd2b0f3995
|
[
"MIT"
] | null | null | null |
src/include/syntax/make_parser/tokenizer.h
|
on-keyday/utils
|
5364370eadfe909407ffded678bebfdd2b0f3995
|
[
"MIT"
] | null | null | null |
src/include/syntax/make_parser/tokenizer.h
|
on-keyday/utils
|
5364370eadfe909407ffded678bebfdd2b0f3995
|
[
"MIT"
] | null | null | null |
/*
utils - utility library
Copyright (c) 2021-2022 on-keyday (https://github.com/on-keyday)
Released under the MIT license
https://opensource.org/licenses/mit-license.php
*/
// tokenizer - custom tokenizer for syntax
#pragma once
#include "../../tokenize/tokenizer.h"
#include "../../tokenize/merge.h"
#include "keyword.h"
#include "attribute.h"
namespace utils {
namespace syntax {
namespace tknz = tokenize;
namespace internal {
template <class String, template <class...> class Vec = wrap::vector>
tknz::Tokenizer<String, Vec> make_internal_tokenizer() {
tknz::Tokenizer<String, Vec> ret;
auto cvt_push = [&](auto base, auto& predef) {
String converted;
utf::convert(base, converted);
predef.push_back(std::move(converted));
};
for (size_t i = 0; i < sizeof(keyword_str) / sizeof(keyword_str[0]); i++) {
cvt_push(keyword_str[i], ret.keyword.predef);
}
cvt_push(":=", ret.symbol.predef);
cvt_push("[", ret.symbol.predef);
cvt_push("]", ret.symbol.predef);
cvt_push("|", ret.symbol.predef);
cvt_push("#", ret.symbol.predef);
cvt_push("\"", ret.symbol.predef);
cvt_push("\\", ret.symbol.predef);
cvt_push(attribute(Attribute::adjacent), ret.symbol.predef);
cvt_push(attribute(Attribute::fatal), ret.symbol.predef);
cvt_push(attribute(Attribute::ifexists), ret.symbol.predef);
cvt_push(attribute(Attribute::repeat), ret.symbol.predef);
return ret;
}
template <class T, class String, template <class...> class Vec = wrap::vector>
bool tokenize_and_merge(Sequencer<T>& input, wrap::shared_ptr<tknz::Token<String>>& output, const char** errmsg = nullptr) {
auto tokenizer = internal::make_internal_tokenizer<String, Vec>();
auto result = tokenizer.tokenize(input, output);
assert(result && "expect true but tokenize failed");
const char* err = nullptr;
auto res = tknz::merge(err, output, tknz::escaped_comment<String>("\"", "\\"),
tknz::line_comment<String>("#"));
if (errmsg) {
*errmsg = err;
}
return res;
}
} // namespace internal
} // namespace syntax
} // namespace utils
| 42.596774
| 136
| 0.540326
|
[
"vector"
] |
b2f88b46b362864d6fc22554ce5593d2d410e8ee
| 4,655
|
h
|
C
|
aws-cpp-sdk-wisdom/include/aws/wisdom/model/Filter.h
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-02-12T08:09:30.000Z
|
2022-02-12T08:09:30.000Z
|
aws-cpp-sdk-wisdom/include/aws/wisdom/model/Filter.h
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-01-03T23:59:37.000Z
|
2022-01-03T23:59:37.000Z
|
aws-cpp-sdk-wisdom/include/aws/wisdom/model/Filter.h
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-11-09T12:02:58.000Z
|
2021-11-09T12:02:58.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/wisdom/ConnectWisdomService_EXPORTS.h>
#include <aws/wisdom/model/FilterField.h>
#include <aws/wisdom/model/FilterOperator.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace ConnectWisdomService
{
namespace Model
{
/**
* <p>A search filter.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/wisdom-2020-10-19/Filter">AWS API
* Reference</a></p>
*/
class AWS_CONNECTWISDOMSERVICE_API Filter
{
public:
Filter();
Filter(Aws::Utils::Json::JsonView jsonValue);
Filter& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The field on which to filter.</p>
*/
inline const FilterField& GetField() const{ return m_field; }
/**
* <p>The field on which to filter.</p>
*/
inline bool FieldHasBeenSet() const { return m_fieldHasBeenSet; }
/**
* <p>The field on which to filter.</p>
*/
inline void SetField(const FilterField& value) { m_fieldHasBeenSet = true; m_field = value; }
/**
* <p>The field on which to filter.</p>
*/
inline void SetField(FilterField&& value) { m_fieldHasBeenSet = true; m_field = std::move(value); }
/**
* <p>The field on which to filter.</p>
*/
inline Filter& WithField(const FilterField& value) { SetField(value); return *this;}
/**
* <p>The field on which to filter.</p>
*/
inline Filter& WithField(FilterField&& value) { SetField(std::move(value)); return *this;}
/**
* <p>The operator to use for comparing the field’s value with the provided
* value.</p>
*/
inline const FilterOperator& GetOperator() const{ return m_operator; }
/**
* <p>The operator to use for comparing the field’s value with the provided
* value.</p>
*/
inline bool OperatorHasBeenSet() const { return m_operatorHasBeenSet; }
/**
* <p>The operator to use for comparing the field’s value with the provided
* value.</p>
*/
inline void SetOperator(const FilterOperator& value) { m_operatorHasBeenSet = true; m_operator = value; }
/**
* <p>The operator to use for comparing the field’s value with the provided
* value.</p>
*/
inline void SetOperator(FilterOperator&& value) { m_operatorHasBeenSet = true; m_operator = std::move(value); }
/**
* <p>The operator to use for comparing the field’s value with the provided
* value.</p>
*/
inline Filter& WithOperator(const FilterOperator& value) { SetOperator(value); return *this;}
/**
* <p>The operator to use for comparing the field’s value with the provided
* value.</p>
*/
inline Filter& WithOperator(FilterOperator&& value) { SetOperator(std::move(value)); return *this;}
/**
* <p>The desired field value on which to filter.</p>
*/
inline const Aws::String& GetValue() const{ return m_value; }
/**
* <p>The desired field value on which to filter.</p>
*/
inline bool ValueHasBeenSet() const { return m_valueHasBeenSet; }
/**
* <p>The desired field value on which to filter.</p>
*/
inline void SetValue(const Aws::String& value) { m_valueHasBeenSet = true; m_value = value; }
/**
* <p>The desired field value on which to filter.</p>
*/
inline void SetValue(Aws::String&& value) { m_valueHasBeenSet = true; m_value = std::move(value); }
/**
* <p>The desired field value on which to filter.</p>
*/
inline void SetValue(const char* value) { m_valueHasBeenSet = true; m_value.assign(value); }
/**
* <p>The desired field value on which to filter.</p>
*/
inline Filter& WithValue(const Aws::String& value) { SetValue(value); return *this;}
/**
* <p>The desired field value on which to filter.</p>
*/
inline Filter& WithValue(Aws::String&& value) { SetValue(std::move(value)); return *this;}
/**
* <p>The desired field value on which to filter.</p>
*/
inline Filter& WithValue(const char* value) { SetValue(value); return *this;}
private:
FilterField m_field;
bool m_fieldHasBeenSet;
FilterOperator m_operator;
bool m_operatorHasBeenSet;
Aws::String m_value;
bool m_valueHasBeenSet;
};
} // namespace Model
} // namespace ConnectWisdomService
} // namespace Aws
| 28.212121
| 115
| 0.641031
|
[
"model"
] |
253e9acf91a6c234f37210d265004a3bfb28a4d7
| 10,237
|
h
|
C
|
src/Moon/240/mask_29_240.h
|
MHotchin/RLEBitmap
|
ebea6f7f032c235ff2301e2aced1e6180b71882e
|
[
"MIT"
] | 8
|
2020-07-05T17:00:15.000Z
|
2022-02-08T04:34:50.000Z
|
src/Moon/240/mask_29_240.h
|
Bodmer/RLEBitmap
|
ed2bf7ec6497371415878a7a5a07b7938294aad6
|
[
"MIT"
] | 2
|
2020-07-04T21:11:49.000Z
|
2020-08-11T20:23:06.000Z
|
src/Moon/240/mask_29_240.h
|
Bodmer/RLEBitmap
|
ed2bf7ec6497371415878a7a5a07b7938294aad6
|
[
"MIT"
] | 3
|
2020-07-05T17:00:22.000Z
|
2020-11-03T11:18:34.000Z
|
//
// This file is AUTOMATICALLY GENERATED, and should not be edited unless you are certain
// that it will not be re-generated anytime in the future. As generated code, the
// copyright owner(s) of the generating program do NOT claim any copyright on the code
// generated.
//
// Run Length Encoded (RLE) bitmaps. Each run is encoded as either one or two bytes,
// with NO PADDING. Thus, the data for each line of the bitmap is VARIABLE LENGTH, and
// there is no way of determining where any line other than the first starts without
// walking though the data.
//
// Note that one byte encoding ONLY occurs if the total number of colors is 16 or less,
// and in that case the 'flags' member of the 'RLEBitmapInfo' will have the first bit
// (0x01) set.
//
// In that case, if the high 4 bits of the first byte are ZERO, then this is a 2 byte
// run. The first byte is the index of the color in the color palette, and the second
// byte is the length.
//
// Else, the lower 4 bits are the color index, and the upper 4 bits are the run length.
//
// If the 'flags' member first bit is zero, then ALL runs are 2 byte runs. The first
// byte is the palette index, and the second is the run length.
//
// In order to save PROGMEM for other uses, the bitmap data is placed in a section that
// occurs near the END of the used FLASH. So, this data should only be accessed using
// the 'far' versions of the progmem functions - the usual versions are limited to the
// first 64K of FLASH.
//
// Data is from file 'images\240\mask_29_240.bmp'.
//
const byte mask_29_240_RLEBM_data[] PROGMEM_LATE =
{
0x00, 0x6d, 0xc1, 0x00, 0x77,
0x00, 0x65, 0xb1, 0x00, 0x80,
0x00, 0x60, 0x91, 0x00, 0x87,
0x00, 0x5b, 0x91, 0x00, 0x8c,
0x00, 0x58, 0x91, 0x00, 0x8f,
0x00, 0x54, 0x91, 0x00, 0x93,
0x00, 0x51, 0xa1, 0x00, 0x95,
0x00, 0x4f, 0x91, 0x00, 0x98,
0x00, 0x4c, 0xa1, 0x00, 0x9a,
0x00, 0x4a, 0x91, 0x00, 0x9d,
0x00, 0x47, 0xa1, 0x00, 0x9f,
0x00, 0x45, 0xa1, 0x00, 0xa1,
0x00, 0x43, 0xb1, 0x00, 0xa2,
0x00, 0x41, 0xb1, 0x00, 0xa4,
0x00, 0x3f, 0xb1, 0x00, 0xa6,
0x00, 0x3d, 0xc1, 0x00, 0xa7,
0x00, 0x3c, 0xb1, 0x00, 0xa9,
0x00, 0x3a, 0xc1, 0x00, 0xaa,
0x00, 0x38, 0xc1, 0x00, 0xac,
0x00, 0x37, 0xc1, 0x00, 0xad,
0x00, 0x35, 0xd1, 0x00, 0xae,
0x00, 0x34, 0xc1, 0x00, 0xb0,
0x00, 0x32, 0xd1, 0x00, 0xb1,
0x00, 0x31, 0xd1, 0x00, 0xb2,
0x00, 0x30, 0xd1, 0x00, 0xb3,
0x00, 0x2e, 0xe1, 0x00, 0xb4,
0x00, 0x2d, 0xe1, 0x00, 0xb5,
0x00, 0x2c, 0xe1, 0x00, 0xb6,
0x00, 0x2b, 0xe1, 0x00, 0xb7,
0x00, 0x2a, 0xe1, 0x00, 0xb8,
0x00, 0x29, 0xe1, 0x00, 0xb9,
0x00, 0x27, 0xf1, 0x00, 0xba,
0x00, 0x26, 0xf1, 0x00, 0xbb,
0x00, 0x25, 0xf1, 0x00, 0xbc,
0x00, 0x24, 0xf1, 0x00, 0xbd,
0x00, 0x23, 0xf1, 0x00, 0xbe,
0x00, 0x22, 0xf1, 0x00, 0xbf,
0x00, 0x21, 0x01, 0x10, 0x00, 0xbf,
0x00, 0x20, 0x01, 0x10, 0x00, 0xc0,
0x00, 0x1f, 0x01, 0x10, 0x00, 0xc1,
0x00, 0x1f, 0xf1, 0x00, 0xc2,
0x00, 0x1e, 0xf1, 0x00, 0xc3,
0x00, 0x1d, 0x01, 0x10, 0x00, 0xc3,
0x00, 0x1c, 0x01, 0x10, 0x00, 0xc4,
0x00, 0x1b, 0x01, 0x10, 0x00, 0xc5,
0x00, 0x1a, 0x01, 0x11, 0x00, 0xc5,
0x00, 0x1a, 0x01, 0x10, 0x00, 0xc6,
0x00, 0x19, 0x01, 0x10, 0x00, 0xc7,
0x00, 0x18, 0x01, 0x11, 0x00, 0xc7,
0x00, 0x17, 0x01, 0x11, 0x00, 0xc8,
0x00, 0x17, 0x01, 0x10, 0x00, 0xc9,
0x00, 0x16, 0x01, 0x11, 0x00, 0xc9,
0x00, 0x15, 0x01, 0x11, 0x00, 0xca,
0x00, 0x15, 0x01, 0x11, 0x00, 0xca,
0x00, 0x14, 0x01, 0x11, 0x00, 0xcb,
0x00, 0x13, 0x01, 0x12, 0x00, 0xcb,
0x00, 0x13, 0x01, 0x11, 0x00, 0xcc,
0x00, 0x12, 0x01, 0x12, 0x00, 0xcc,
0x00, 0x11, 0x01, 0x12, 0x00, 0xcd,
0x00, 0x11, 0x01, 0x11, 0x00, 0xce,
0x00, 0x10, 0x01, 0x12, 0x00, 0xce,
0x00, 0x10, 0x01, 0x12, 0x00, 0xce,
0xf0, 0x01, 0x12, 0x00, 0xcf,
0xf0, 0x01, 0x12, 0x00, 0xcf,
0xe0, 0x01, 0x12, 0x00, 0xd0,
0xe0, 0x01, 0x12, 0x00, 0xd0,
0xd0, 0x01, 0x12, 0x00, 0xd1,
0xd0, 0x01, 0x12, 0x00, 0xd1,
0xc0, 0x01, 0x12, 0x00, 0xd2,
0xc0, 0x01, 0x12, 0x00, 0xd2,
0xb0, 0x01, 0x13, 0x00, 0xd2,
0xb0, 0x01, 0x12, 0x00, 0xd3,
0xa0, 0x01, 0x13, 0x00, 0xd3,
0xa0, 0x01, 0x13, 0x00, 0xd3,
0x90, 0x01, 0x13, 0x00, 0xd4,
0x90, 0x01, 0x13, 0x00, 0xd4,
0x90, 0x01, 0x13, 0x00, 0xd4,
0x80, 0x01, 0x13, 0x00, 0xd5,
0x80, 0x01, 0x13, 0x00, 0xd5,
0x70, 0x01, 0x14, 0x00, 0xd5,
0x70, 0x01, 0x13, 0x00, 0xd6,
0x70, 0x01, 0x13, 0x00, 0xd6,
0x60, 0x01, 0x14, 0x00, 0xd6,
0x60, 0x01, 0x13, 0x00, 0xd7,
0x60, 0x01, 0x13, 0x00, 0xd7,
0x50, 0x01, 0x14, 0x00, 0xd7,
0x50, 0x01, 0x14, 0x00, 0xd7,
0x50, 0x01, 0x13, 0x00, 0xd8,
0x50, 0x01, 0x13, 0x00, 0xd8,
0x40, 0x01, 0x14, 0x00, 0xd8,
0x40, 0x01, 0x14, 0x00, 0xd8,
0x40, 0x01, 0x14, 0x00, 0xd8,
0x40, 0x01, 0x13, 0x00, 0xd9,
0x30, 0x01, 0x14, 0x00, 0xd9,
0x30, 0x01, 0x14, 0x00, 0xd9,
0x30, 0x01, 0x14, 0x00, 0xd9,
0x30, 0x01, 0x14, 0x00, 0xd9,
0x30, 0x01, 0x13, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x01, 0x15, 0x00, 0xdb,
0x01, 0x15, 0x00, 0xdb,
0x01, 0x15, 0x00, 0xdb,
0x01, 0x15, 0x00, 0xdb,
0x01, 0x15, 0x00, 0xdb,
0x01, 0x15, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x30, 0x01, 0x13, 0x00, 0xda,
0x30, 0x01, 0x14, 0x00, 0xd9,
0x30, 0x01, 0x14, 0x00, 0xd9,
0x30, 0x01, 0x14, 0x00, 0xd9,
0x30, 0x01, 0x14, 0x00, 0xd9,
0x40, 0x01, 0x13, 0x00, 0xd9,
0x40, 0x01, 0x14, 0x00, 0xd8,
0x40, 0x01, 0x14, 0x00, 0xd8,
0x40, 0x01, 0x14, 0x00, 0xd8,
0x50, 0x01, 0x13, 0x00, 0xd8,
0x50, 0x01, 0x13, 0x00, 0xd8,
0x50, 0x01, 0x14, 0x00, 0xd7,
0x50, 0x01, 0x14, 0x00, 0xd7,
0x60, 0x01, 0x13, 0x00, 0xd7,
0x60, 0x01, 0x13, 0x00, 0xd7,
0x60, 0x01, 0x14, 0x00, 0xd6,
0x70, 0x01, 0x13, 0x00, 0xd6,
0x70, 0x01, 0x13, 0x00, 0xd6,
0x70, 0x01, 0x14, 0x00, 0xd5,
0x80, 0x01, 0x13, 0x00, 0xd5,
0x80, 0x01, 0x13, 0x00, 0xd5,
0x90, 0x01, 0x13, 0x00, 0xd4,
0x90, 0x01, 0x13, 0x00, 0xd4,
0x90, 0x01, 0x13, 0x00, 0xd4,
0xa0, 0x01, 0x13, 0x00, 0xd3,
0xa0, 0x01, 0x13, 0x00, 0xd3,
0xb0, 0x01, 0x12, 0x00, 0xd3,
0xb0, 0x01, 0x13, 0x00, 0xd2,
0xc0, 0x01, 0x12, 0x00, 0xd2,
0xc0, 0x01, 0x12, 0x00, 0xd2,
0xd0, 0x01, 0x12, 0x00, 0xd1,
0xd0, 0x01, 0x12, 0x00, 0xd1,
0xe0, 0x01, 0x12, 0x00, 0xd0,
0xe0, 0x01, 0x12, 0x00, 0xd0,
0xf0, 0x01, 0x12, 0x00, 0xcf,
0xf0, 0x01, 0x12, 0x00, 0xcf,
0x00, 0x10, 0x01, 0x12, 0x00, 0xce,
0x00, 0x10, 0x01, 0x12, 0x00, 0xce,
0x00, 0x11, 0x01, 0x11, 0x00, 0xce,
0x00, 0x11, 0x01, 0x12, 0x00, 0xcd,
0x00, 0x12, 0x01, 0x12, 0x00, 0xcc,
0x00, 0x13, 0x01, 0x11, 0x00, 0xcc,
0x00, 0x13, 0x01, 0x12, 0x00, 0xcb,
0x00, 0x14, 0x01, 0x11, 0x00, 0xcb,
0x00, 0x15, 0x01, 0x11, 0x00, 0xca,
0x00, 0x15, 0x01, 0x11, 0x00, 0xca,
0x00, 0x16, 0x01, 0x11, 0x00, 0xc9,
0x00, 0x17, 0x01, 0x10, 0x00, 0xc9,
0x00, 0x17, 0x01, 0x11, 0x00, 0xc8,
0x00, 0x18, 0x01, 0x11, 0x00, 0xc7,
0x00, 0x19, 0x01, 0x10, 0x00, 0xc7,
0x00, 0x1a, 0x01, 0x10, 0x00, 0xc6,
0x00, 0x1a, 0x01, 0x11, 0x00, 0xc5,
0x00, 0x1b, 0x01, 0x10, 0x00, 0xc5,
0x00, 0x1c, 0x01, 0x10, 0x00, 0xc4,
0x00, 0x1d, 0x01, 0x10, 0x00, 0xc3,
0x00, 0x1e, 0xf1, 0x00, 0xc3,
0x00, 0x1f, 0xf1, 0x00, 0xc2,
0x00, 0x1f, 0x01, 0x10, 0x00, 0xc1,
0x00, 0x20, 0x01, 0x10, 0x00, 0xc0,
0x00, 0x21, 0x01, 0x10, 0x00, 0xbf,
0x00, 0x22, 0xf1, 0x00, 0xbf,
0x00, 0x23, 0xf1, 0x00, 0xbe,
0x00, 0x24, 0xf1, 0x00, 0xbd,
0x00, 0x25, 0xf1, 0x00, 0xbc,
0x00, 0x26, 0xf1, 0x00, 0xbb,
0x00, 0x27, 0xf1, 0x00, 0xba,
0x00, 0x29, 0xe1, 0x00, 0xb9,
0x00, 0x2a, 0xe1, 0x00, 0xb8,
0x00, 0x2b, 0xe1, 0x00, 0xb7,
0x00, 0x2c, 0xe1, 0x00, 0xb6,
0x00, 0x2d, 0xe1, 0x00, 0xb5,
0x00, 0x2e, 0xe1, 0x00, 0xb4,
0x00, 0x30, 0xd1, 0x00, 0xb3,
0x00, 0x31, 0xd1, 0x00, 0xb2,
0x00, 0x32, 0xd1, 0x00, 0xb1,
0x00, 0x34, 0xc1, 0x00, 0xb0,
0x00, 0x35, 0xd1, 0x00, 0xae,
0x00, 0x37, 0xc1, 0x00, 0xad,
0x00, 0x38, 0xc1, 0x00, 0xac,
0x00, 0x3a, 0xc1, 0x00, 0xaa,
0x00, 0x3c, 0xb1, 0x00, 0xa9,
0x00, 0x3d, 0xc1, 0x00, 0xa7,
0x00, 0x3f, 0xb1, 0x00, 0xa6,
0x00, 0x41, 0xb1, 0x00, 0xa4,
0x00, 0x43, 0xb1, 0x00, 0xa2,
0x00, 0x45, 0xa1, 0x00, 0xa1,
0x00, 0x47, 0xa1, 0x00, 0x9f,
0x00, 0x4a, 0x91, 0x00, 0x9d,
0x00, 0x4c, 0xa1, 0x00, 0x9a,
0x00, 0x4f, 0x91, 0x00, 0x98,
0x00, 0x51, 0xa1, 0x00, 0x95,
0x00, 0x54, 0x91, 0x00, 0x93,
0x00, 0x58, 0x91, 0x00, 0x8f,
0x00, 0x5b, 0x91, 0x00, 0x8c,
0x00, 0x60, 0x91, 0x00, 0x87,
0x00, 0x65, 0xb1, 0x00, 0x80,
0x00, 0x6d, 0xc1, 0x00, 0x77,
}; // 240x240 Bitmap (57600 pixels) in 1240 bytes
const uint16_t mask_29_240_RLEBM_palette[] PROGMEM_LATE =
{
// Palette has 2 entries
0x0000, 0xffff,
};
// Some platforms don't fully implement the pgmspace.h interface. Assume ordinary
// addresses will do.
#if not defined pgm_get_far_address
#define pgm_get_far_address(x) ((uint32_t)(&(x)))
#endif
// Returns the info needed to render the bitmap.
inline void get_mask_29_240_RLEBM(
RLEBitmapInfo &bmInfo)
{
bmInfo.pRLEBM_data_far = pgm_get_far_address(mask_29_240_RLEBM_data);
bmInfo.pRLEBM_palette_far = pgm_get_far_address(mask_29_240_RLEBM_palette);
bmInfo.width = 240;
bmInfo.height = 240;
bmInfo.flags = 0x01;
}
| 33.785479
| 89
| 0.65019
|
[
"render"
] |
2549d09bfb1554a9779f3244d67b8b621e0267b6
| 6,047
|
h
|
C
|
Co-Simulation/Sumo/sumo-1.7.0/src/microsim/devices/MSTransportableDevice_Routing.h
|
uruzahe/carla
|
940c2ab23cce1eda1ef66de35f66b42d40865fb1
|
[
"MIT"
] | null | null | null |
Co-Simulation/Sumo/sumo-1.7.0/src/microsim/devices/MSTransportableDevice_Routing.h
|
uruzahe/carla
|
940c2ab23cce1eda1ef66de35f66b42d40865fb1
|
[
"MIT"
] | null | null | null |
Co-Simulation/Sumo/sumo-1.7.0/src/microsim/devices/MSTransportableDevice_Routing.h
|
uruzahe/carla
|
940c2ab23cce1eda1ef66de35f66b42d40865fb1
|
[
"MIT"
] | null | null | null |
/****************************************************************************/
// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
// Copyright (C) 2007-2020 German Aerospace Center (DLR) and others.
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0/
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License 2.0 are satisfied: GNU General Public License, version 2
// or later which is available at
// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
/****************************************************************************/
/// @file MSTransportableDevice_Routing.h
/// @author Michael Behrisch
/// @author Daniel Krajzewicz
/// @author Jakob Erdmann
/// @date Tue, 04 Dec 2007
///
// A device that performs vehicle rerouting based on current edge speeds
/****************************************************************************/
#pragma once
#include <config.h>
#include "MSTransportableDevice.h"
// ===========================================================================
// class declarations
// ===========================================================================
class MSLane;
// ===========================================================================
// class definitions
// ===========================================================================
/**
* @class MSTransportableDevice_Routing
* @brief A device that performs person rerouting based on current edge speeds
*
* The routing-device system consists of in-vehicle devices that perform the routing
* and simulation-wide static methods for collecting edge weights and
* parallelizing in MSRoutingEngine.
*
* A device is assigned using the common explicit/probability - procedure.
*
* A device computes a new route for a person as soon as a personTrip appears in the plan.
*/
class MSTransportableDevice_Routing : public MSTransportableDevice {
public:
/** @brief Inserts MSTransportableDevice_Routing-options
* @param[filled] oc The options container to add the options to
*/
static void insertOptions(OptionsCont& oc);
/** @brief checks MSTransportableDevice_Routing-options
* @param[filled] oc The options container with the user-defined options
*/
static bool checkOptions(OptionsCont& oc);
/** @brief Build devices for the given person, if needed
*
* The options are read and evaluated whether rerouting-devices shall be built
* for the given person.
*
* When the first device is built, the static container of edge weights
* used for routing is initialised with the mean speed the edges allow.
* In addition, an event is generated which updates these weights is
* built and added to the list of events to execute at a simulation end.
*
* The built device is stored in the given vector.
*
* @param[in] p The person for which a device may be built
* @param[filled] into The vector to store the built device in
*/
static void buildDevices(MSTransportable& p, std::vector<MSTransportableDevice*>& into);
/// @brief Destructor.
~MSTransportableDevice_Routing();
/// @brief return the name for this type of device
const std::string deviceName() const {
return "rerouting";
}
/** @brief Saves the state of the device
*
* @param[in] out The OutputDevice to write the information into
*/
void saveState(OutputDevice& out) const;
/** @brief Loads the state of the device from the given description
*
* @param[in] attrs XML attributes describing the current state
*/
void loadState(const SUMOSAXAttributes& attrs);
/// @brief initiate the rerouting, create router / thread pool on first use
void reroute(const SUMOTime currentTime, const bool onInit = false);
/// @brief try to retrieve the given parameter from this device. Throw exception for unsupported key
std::string getParameter(const std::string& key) const;
/// @brief try to set the given parameter for this device. Throw exception for unsupported key
void setParameter(const std::string& key, const std::string& value);
private:
/** @brief Constructor
*
* @param[in] holder The vehicle that holds this device
* @param[in] id The ID of the device
* @param[in] period The period with which a new route shall be searched
*/
MSTransportableDevice_Routing(MSTransportable& holder, const std::string& id, SUMOTime period);
/** @brief Performs rerouting after a period
*
* A new route is computed by calling the vehicle's "reroute" method, supplying
* "getEffort" as the edge effort retrieval method.
*
* This method is called from the event handler at the begin of a simulation
* step after the rerouting period is over. The reroute period is returned.
*
* @param[in] currentTime The current simulation time
* @return The offset to the next call (the rerouting period "myPeriod")
* @see MSVehicle::reroute
* @see MSEventHandler
* @see WrappingCommand
*/
SUMOTime wrappedRerouteCommandExecute(SUMOTime currentTime);
private:
/// @brief The period with which a vehicle shall be rerouted
SUMOTime myPeriod;
/// @brief The last time a routing took place
SUMOTime myLastRouting;
/// @brief The (optional) command responsible for rerouting
WrappingCommand< MSTransportableDevice_Routing >* myRerouteCommand;
private:
/// @brief Invalidated copy constructor.
MSTransportableDevice_Routing(const MSTransportableDevice_Routing&);
/// @brief Invalidated assignment operator.
MSTransportableDevice_Routing& operator=(const MSTransportableDevice_Routing&);
};
| 38.515924
| 104
| 0.651232
|
[
"vector"
] |
25573ffa2ec4326c53132a73aed247c833347785
| 1,317
|
h
|
C
|
aws-cpp-sdk-rekognition/include/aws/rekognition/model/DeleteCollectionResult.h
|
Neusoft-Technology-Solutions/aws-sdk-cpp
|
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
|
[
"Apache-2.0"
] | 1
|
2022-02-12T08:09:30.000Z
|
2022-02-12T08:09:30.000Z
|
aws-cpp-sdk-rekognition/include/aws/rekognition/model/DeleteCollectionResult.h
|
Neusoft-Technology-Solutions/aws-sdk-cpp
|
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
|
[
"Apache-2.0"
] | 1
|
2022-01-03T23:59:37.000Z
|
2022-01-03T23:59:37.000Z
|
aws-cpp-sdk-rekognition/include/aws/rekognition/model/DeleteCollectionResult.h
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-11-09T11:58:03.000Z
|
2021-11-09T11:58:03.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/rekognition/Rekognition_EXPORTS.h>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace Rekognition
{
namespace Model
{
class AWS_REKOGNITION_API DeleteCollectionResult
{
public:
DeleteCollectionResult();
DeleteCollectionResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
DeleteCollectionResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>HTTP status code that indicates the result of the operation.</p>
*/
inline int GetStatusCode() const{ return m_statusCode; }
/**
* <p>HTTP status code that indicates the result of the operation.</p>
*/
inline void SetStatusCode(int value) { m_statusCode = value; }
/**
* <p>HTTP status code that indicates the result of the operation.</p>
*/
inline DeleteCollectionResult& WithStatusCode(int value) { SetStatusCode(value); return *this;}
private:
int m_statusCode;
};
} // namespace Model
} // namespace Rekognition
} // namespace Aws
| 23.517857
| 110
| 0.710706
|
[
"model"
] |
25650823b53e5c706ee7a16271bd390145bcf248
| 8,368
|
h
|
C
|
src/DpaParser/JsDriverStandardFrcSolver.h
|
iqrfsdk/iqrf-gateway-daemon
|
8875a9a0bf67003fc7115a59af12ab12d591b487
|
[
"Apache-2.0"
] | 1
|
2021-04-28T07:34:14.000Z
|
2021-04-28T07:34:14.000Z
|
src/DpaParser/JsDriverStandardFrcSolver.h
|
iqrf/iqrf-gateway-daemon
|
adf8585749afefb01f274d5b70959d500d35bd6c
|
[
"Apache-2.0"
] | 1
|
2019-10-31T13:29:55.000Z
|
2019-10-31T13:29:55.000Z
|
src/DpaParser/JsDriverStandardFrcSolver.h
|
iqrf/iqrf-gateway-daemon
|
adf8585749afefb01f274d5b70959d500d35bd6c
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright 2015-2021 IQRF Tech s.r.o.
* Copyright 2019-2021 MICRORISC s.r.o.
*
* 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 "IDpaTransactionResult2.h"
#include "JsDriverSolver.h"
#include "Dali.h"
#include "JsonUtils.h"
#include <vector>
namespace iqrf
{
// use as common functionality predecessor for JsDriverDali, JsDriverSensor
class JsDriverStandardFrcSolver : public JsDriverSolver
{
private:
std::string m_functionName;
DpaMessage m_frcRequest;
uint16_t m_hwpid;
DpaMessage m_frcExtraRequest;
DpaMessage m_frcResponse;
DpaMessage m_frcExtraResponse;
std::unique_ptr<IDpaTransactionResult2> m_frcDpaTransactionResult;
std::unique_ptr<IDpaTransactionResult2> m_frcExtraDpaTransactionResult;
rapidjson::Document m_frcRequestResult0Doc;
rapidjson::Document m_frcResponseResultDoc;
protected:
// used by sensor::JsDriverFrc, dali::JsDriverFrc
JsDriverStandardFrcSolver(IJsRenderService* iJsRenderService)
:JsDriverSolver(iJsRenderService)
, m_hwpid(0xFFFF)
{}
public:
JsDriverStandardFrcSolver(IJsRenderService* iJsRenderService, const std::string & functionName, const rapidjson::Value & val, uint16_t hwpid)
:JsDriverSolver(iJsRenderService)
, m_functionName(functionName)
, m_hwpid(hwpid)
{
setRequestParamDoc(val);
}
virtual ~JsDriverStandardFrcSolver() {}
const DpaMessage & getFrcRequest() const { return m_frcRequest; }
const DpaMessage & getFrcExtraRequest() const { return m_frcExtraRequest; }
const rapidjson::Document & getRequestResult0Doc() const { return m_frcRequestResult0Doc; }
const rapidjson::Document & getResponseResultDoc() const { return m_frcResponseResultDoc; }
void setFrcDpaTransactionResult(std::unique_ptr<IDpaTransactionResult2> res)
{
m_frcDpaTransactionResult = std::move(res);
if (!m_frcDpaTransactionResult->isResponded()) {
THROW_EXC_TRC_WAR(std::logic_error, "No Frc response");
}
m_frcResponse = m_frcDpaTransactionResult->getResponse();
}
void setFrcExtraDpaTransactionResult(std::unique_ptr<IDpaTransactionResult2> res)
{
m_frcExtraDpaTransactionResult = std::move(res);
if (!m_frcExtraDpaTransactionResult->isResponded()) {
THROW_EXC_TRC_WAR(std::logic_error, "No Frc Extra response");
}
m_frcExtraResponse = m_frcExtraDpaTransactionResult->getResponse();
}
std::unique_ptr<IDpaTransactionResult2> moveFrcDpaTransactionResult()
{
return std::move(m_frcDpaTransactionResult);
}
std::unique_ptr<IDpaTransactionResult2> moveFrcExtraDpaTransactionResult()
{
return std::move(m_frcExtraDpaTransactionResult);
}
const rapidjson::Document & getResponseResultDoc() { return m_responseResultDoc; }
// partial JSON parse to get nadrs of returned results
rapidjson::Document getExtFormat(const std::string & resultArrayKey, const std::string & resultItemKey)
{
using namespace rapidjson;
Document doc;
doc.SetArray();
// get nadrs from selectedNodes if applied
std::set<int> selectedNodesSet;
const Value *selectedNodesVal = Pointer("/selectedNodes").Get(getRequestParamDoc());
if (selectedNodesVal && selectedNodesVal->IsArray()) {
for (const Value *nadrVal = selectedNodesVal->Begin(); nadrVal != selectedNodesVal->End(); nadrVal++) {
if (nadrVal->IsInt()) {
selectedNodesSet.insert(nadrVal->GetInt());
}
else {
THROW_EXC_TRC_WAR(std::logic_error, "Expected: Json Array of Int .../selectedNodes[]");
}
}
}
Value *arrayVal = Pointer(resultArrayKey).Get(m_frcResponseResultDoc);
if (!(arrayVal && arrayVal->IsArray())) {
THROW_EXC_TRC_WAR(std::logic_error, "Expected: Json Array ..." << resultArrayKey << "[]");
}
if (arrayVal->Size() > 0) { // is there something in the array?
if (selectedNodesSet.size() > 0) {
// selective FRC
// check size
if ((selectedNodesSet.size() + 1) > arrayVal->Size()) {
THROW_EXC_TRC_WAR(std::logic_error, "Inconsistent .../selectedNodes[] and ..." << resultArrayKey << "[]");
}
// iterate via selected nodes
const Value *itemVal = arrayVal->Begin() + 1; //skip index 0 as driver returns first null as a result of general FRC
for (auto nadr : selectedNodesSet) {
Value sensorVal;
Pointer("/nAdr").Set(sensorVal, nadr, doc.GetAllocator());
Pointer(resultItemKey).Set(sensorVal, *itemVal++, doc.GetAllocator());
doc.PushBack(sensorVal, doc.GetAllocator());
}
}
else {
// non-selective FRC //TODO does FRC always starts from nadr=0?
int nadr = 0;
for (Value *itemVal = arrayVal->Begin(); itemVal != arrayVal->End(); itemVal++) {
Value sensorVal;
Pointer("/nAdr").Set(sensorVal, nadr++, doc.GetAllocator());
Pointer(resultItemKey).Set(sensorVal, *itemVal, doc.GetAllocator());
doc.PushBack(sensorVal, doc.GetAllocator());
}
}
}
return doc;
}
protected:
uint16_t getNadrDrv() const override
{
return (uint16_t)0; // coordinator
}
uint16_t getHwpidDrv() const
{
return m_hwpid;
}
std::string functionName() const override
{
return m_functionName;
}
void preRequest(rapidjson::Document& requestResultDoc) override
{
// set in ctor by setRequestParamDoc(val);
(void)requestResultDoc; //silence -Wunused-parameter
}
void postRequest(const rapidjson::Document& requestResultDoc) override
{
using namespace rapidjson;
if (const Value *val0 = Pointer("/retpars/0").Get(requestResultDoc)) {
uint8_t pnum, pcmd;
rawHdp2dpaRequest(m_frcRequest, getNadrDrv(), pnum, pcmd, getHwpidDrv(), *val0);
m_frcRequestResult0Doc.CopyFrom(*val0, m_frcRequestResult0Doc.GetAllocator());
}
else {
THROW_EXC_TRC_WAR(std::logic_error, "Expected: Json Array .../retpars[0]");
}
if (const Value *val1 = Pointer("/retpars/1").Get(requestResultDoc)) {
uint8_t pnum, pcmd;
rawHdp2dpaRequest(m_frcExtraRequest, getNadrDrv(), pnum, pcmd, getHwpidDrv(), *val1);
}
else {
THROW_EXC_TRC_WAR(std::logic_error, "Expected: Json Array .../retpars[1]");
}
}
void preResponse(rapidjson::Document& responseParamDoc) override
{
using namespace rapidjson;
// some std FRC needs requestParam to parse response
responseParamDoc.CopyFrom(getRequestParamDoc(), responseParamDoc.GetAllocator());
if (!m_frcDpaTransactionResult->isResponded()) {
THROW_EXC_TRC_WAR(std::logic_error, "No Frc response");
}
{
Value val;
dpa2rawHdpResponse(m_frcResponse, val, responseParamDoc.GetAllocator());
Pointer("/responseFrcSend").Set(responseParamDoc, val);
}
if (m_frcExtraDpaTransactionResult) {
// optional extra result
if (!m_frcExtraDpaTransactionResult->isResponded()) {
THROW_EXC_TRC_WAR(std::logic_error, "No Frc response");
}
{
Value val;
dpa2rawHdpResponse(m_frcExtraResponse, val, responseParamDoc.GetAllocator());
Pointer("/responseFrcExtraResult").Set(responseParamDoc, val);
}
}
Pointer("/frcSendRequest").Set(responseParamDoc, m_frcRequestResult0Doc);
}
void postResponse(const rapidjson::Document& responseResultDoc) override
{
m_frcResponseResultDoc.CopyFrom(responseResultDoc, m_frcResponseResultDoc.GetAllocator());
}
};
} //namespace iqrf
| 34.436214
| 145
| 0.667663
|
[
"vector"
] |
2565a67fa44f404f98c5f801b2b9e44a56519ea2
| 5,245
|
h
|
C
|
server/include/thread/ThreadPool.h
|
SiskonEmilia/lightweight-web-server
|
5d55b2f3344a65178d255a5ddb91adb684e843b0
|
[
"MIT"
] | 6
|
2021-02-13T14:40:35.000Z
|
2021-11-15T08:47:24.000Z
|
server/include/thread/ThreadPool.h
|
SiskonEmilia/lightweight-web-server
|
5d55b2f3344a65178d255a5ddb91adb684e843b0
|
[
"MIT"
] | null | null | null |
server/include/thread/ThreadPool.h
|
SiskonEmilia/lightweight-web-server
|
5d55b2f3344a65178d255a5ddb91adb684e843b0
|
[
"MIT"
] | 2
|
2021-11-15T08:34:49.000Z
|
2021-11-15T08:47:27.000Z
|
#pragma once
#include <vector>
#include <list>
#include <functional>
#include <pthread.h>
#include <memory>
#include <iostream>
#include <pthread.h>
#include <sys/prctl.h>
#include <csignal>
#include "utils/Uncopyable.h"
#include "thread/MutexLock.h"
#include "thread/Condition.h"
template<typename T>
struct ThreadTask {
std::function<void(std::shared_ptr<T>)> process; // 线程接受的函数
std::shared_ptr<T> arg; // 该函数接受的参数表指针(若为单参数,则可为参数指针)
ThreadTask() {}
ThreadTask(std::shared_ptr<T>& arg, std::function<void(std::shared_ptr<T>)>& process):
process(process), arg(arg) { }
};
template<typename T>
class ThreadPool {
// 互斥锁
MutexLock mutex;
Condition condition;
// 线程池属性
int thread_num;
int max_queue_size;
// 状态信息
int started;
int shutdown_;
// 资源池与请求队列
std::vector<pthread_t> threads;
std::list<ThreadTask<T>> request_queue;
static void *worker(void *args);
/**
* @brief EventLoop:执行执行等待队列内的任务。
*/
void run();
public:
enum {
Default_Thread_Num = 8,
Max_Thread_Num = 1024,
Max_Queue_Size = 16384
};
typedef enum {
immediate_mode = 1,
graceful_mode = 2
} ShutdownMode;
ThreadPool(int thread_num, int max_queue_size);
~ThreadPool();
bool append(std::shared_ptr<T> arg, std::function<void(std::shared_ptr<T>)> fun);
void shutdown(bool graceful);
};
using std::cout;
using std::cerr;
using std::endl;
template<typename T>
ThreadPool<T>::ThreadPool(int thread_num, int max_queue_size) :
thread_num(thread_num), max_queue_size(max_queue_size),
started(0), shutdown_(0) {
if (thread_num <= 0 || thread_num > Max_Thread_Num) {
// 不合法的线程数量
cout << "Invalid thread size: " << thread_num << ", " << endl
<< "will be set to default value: " << Default_Thread_Num << endl;
thread_num = Default_Thread_Num;
}
if (max_queue_size <= 0 || max_queue_size > Max_Queue_Size) {
// 不合法的最大任务数量
cout << "Invalid waiting queue size: " << max_queue_size << ", " << endl
<< "will be set to default value: " << Max_Queue_Size << "." << endl;
max_queue_size = Max_Queue_Size;
}
// 创建线程,并保存线程的 tid
threads.resize(thread_num);
for (int i = 0; i < thread_num; i++) {
if (pthread_create(&threads[i], NULL, worker, this) != 0) {
cerr << "Failed to create thread#" << i << "." << endl;
abort();
}
started++;
}
}
template<typename T>
ThreadPool<T>::~ThreadPool() {
if (!shutdown_)
shutdown(true);
}
template<typename T>
bool ThreadPool<T>::append(std::shared_ptr<T> arg, std::function<void(std::shared_ptr<T>)> fun) {
// 如果已经停机,则不接受更多的链接
if (shutdown_) {
cout << "Failed to append task: ThreadPool has been shutdown." << endl;
return false;
}
MutexLockGuard guard(this->mutex);
if (request_queue.size() >= max_queue_size) {
cout << "Failed to append task: waiting queue is full." << endl;
return false;
}
// 向等待队列添加新的任务
request_queue.push_back({arg, fun});
// 通知空闲的线程处理任务队列
condition.notify();
return true;
}
template<typename T>
void ThreadPool<T>::shutdown(bool graceful) {
{
MutexLockGuard guard(this->mutex);
// 如果已经在停机状态,不需额外操作
if (shutdown_) {
cout << "Fail to shutdown: server has been shutdown." << endl;
// 进程退出时自动释放持有的文件符,无需手动释放
return;
}
shutdown_ = graceful ? graceful_mode : immediate_mode;
condition.notifyAll();
}
// 等待所有 thread 执行完毕
for (int i = 0; i < thread_num; i++) {
if (pthread_join(threads[i], NULL) != 0) {
cerr << "Fail to end thread: pthread_join error for thread#" << i << endl
<< "-- TID: " << threads[i] << endl;
}
}
}
template<typename T>
void *ThreadPool<T>::worker(void *args) {
ThreadPool *pool = static_cast<ThreadPool *>(args);
// 若线程池指针无效,则立即停止执行
if (pool == nullptr)
return NULL;
// 设置线程名
prctl(PR_SET_NAME,"EventLoopThread");
sigset_t cur_set;
sigaddset(&cur_set, SIGPIPE);
sigaddset(&cur_set, SIGINT);
pthread_sigmask(SIG_BLOCK, &cur_set, nullptr);
// 执行 EventLoop
pool->run();
return NULL;
}
template<typename T>
void ThreadPool<T>::run() {
// EventLoop
while (true) {
ThreadTask<T> requestTask;
{
// 此作用域用来约束互斥锁范围
MutexLockGuard guard(this->mutex);
// 没有任务且没有停机的情况下,不断通过条件变量进行等待(自旋锁会不会更快?)
while (request_queue.empty() && !shutdown_) {
// 此处条件变量会解锁互斥锁,因而不会死锁
condition.wait(this->mutex);
}
// 处理停机的情况:如果立即停机,则不处理剩下任务
// 如果为优雅关闭模式,则继续处理剩下的任务,直到处理完停机
if ((shutdown_ == immediate_mode) || (shutdown_ == graceful_mode && request_queue.empty())) {
break;
}
// 处理等待队列中的任务
requestTask = request_queue.front();
request_queue.pop_front();
}
// 此时互斥锁已经释放,因而执行过程不会阻塞线程池
requestTask.process(requestTask.arg);
}
}
| 25.965347
| 105
| 0.586463
|
[
"vector"
] |
25726aa159a4c1fabe7adcee2d726d867084ab88
| 11,828
|
h
|
C
|
simple_blas/tensor_arithmetic_operations.h
|
BalderOdinson/Transprecision-Floating-Point
|
98ece279c6dc891cb719ebaabadcc223e3838b24
|
[
"MIT"
] | null | null | null |
simple_blas/tensor_arithmetic_operations.h
|
BalderOdinson/Transprecision-Floating-Point
|
98ece279c6dc891cb719ebaabadcc223e3838b24
|
[
"MIT"
] | null | null | null |
simple_blas/tensor_arithmetic_operations.h
|
BalderOdinson/Transprecision-Floating-Point
|
98ece279c6dc891cb719ebaabadcc223e3838b24
|
[
"MIT"
] | 1
|
2021-04-14T18:20:28.000Z
|
2021-04-14T18:20:28.000Z
|
#pragma once
template <typename Type>
tensor<Type>& tensor<Type>::transpose()
{
auto const copy = *this;
for (int64_t n = 0; n < shape_.first * shape_.second; ++n)
{
auto i = n / shape_.first;
auto j = n % shape_.first;
data_[n] = copy.data_[j * shape_.second + i];
}
std::swap(shape_.first, shape_.second);
return *this;
}
template <typename Type>
tensor<Type> transpose(tensor<Type> tensor)
{
return tensor.transpose();
}
template <typename Type>
tensor<Type>& tensor<Type>::dot(tensor<Type> const& other)
{
if (shape_.second != other.shape_.first)
throw std::runtime_error("Invalid shapes - " + to_string(shape_) + " and " + to_string(other.shape_) + "!");
auto const n = shape_.first;
auto const m = shape_.second;
auto const p = other.shape_.second;
auto const other_transposed = std::move(simple_blas::transpose(other));
tensor<Type> result;
result.shape_ = { n, p };
result.data_ = std::make_unique<Type[]>(n * p);
#pragma omp parallel for
for (int64_t i = 0; i < n; ++i)
{
for (int64_t j = 0; j < p; ++j)
{
Type dot = 0;
for (int64_t k = 0; k < m; ++k)
dot += data_[i * m + k] * other_transposed.data_[j * m + k];
result.data_[i * p + j] = dot;
}
}
return (*this = std::move(result));
}
template <typename Type>
tensor<Type> dot(tensor<Type> lhs, tensor<Type> const& rhs)
{
auto result = lhs.dot(rhs);
return result;
}
template <typename Type>
template<uint_fast8_t Axis>
tensor<Type> tensor<Type>::sum() const
{
if constexpr (Axis == 0)
{
tensor<Type> result({ 1, shape_.second });
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
result.data_[j] += data_[i * shape_.second + j];
return result;
}
if constexpr (Axis == 1)
{
tensor<Type> result({ shape_.first, 1 });
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
result.data_[i] += data_[i * shape_.second + j];
return result;
}
throw std::runtime_error("Invalid axis template parameter!");
}
template <typename Type>
Type tensor<Type>::sum() const
{
Type sum = 0;
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
sum += data_[i * shape_.second + j];
return sum;
}
template <typename Type>
template <uint_fast8_t Axis>
tensor<Type> tensor<Type>::max() const
{
if constexpr (Axis == 0)
{
tensor<Type> result({ 1, shape_.second });
for (int64_t j = 0; j < shape_.second; ++j)
{
result.data_[j] = data_[j];
for (int64_t i = 0; i < shape_.first; ++i)
result.data_[j] = std::max(data_[i * shape_.second + j], result.data_[j]);
}
return result;
}
if constexpr (Axis == 1)
{
tensor<Type> result({ shape_.first, 1 });
for (int64_t i = 0; i < shape_.first; ++i)
{
result.data_[i] = data_[i];
for (int64_t j = 0; j < shape_.second; ++j)
result.data_[i] = std::max(data_[i * shape_.second + j], result.data_[i]);
}
return result;
}
throw std::runtime_error("Invalid axis template parameter!");
}
template <typename Type>
Type tensor<Type>::max() const
{
Type max = data_[0];
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
max = std::max(data_[i * shape_.second + j], max);
return max;
}
template <typename Type>
template <uint_fast8_t Axis>
tensor<Type> tensor<Type>::min() const
{
if constexpr (Axis == 0)
{
tensor<Type> result({ 1, shape_.second });
for (int64_t j = 0; j < shape_.second; ++j)
{
result.data_[j] = data_[j];
for (int64_t i = 0; i < shape_.first; ++i)
result.data_[j] = std::min(data_[i * shape_.second + j], result.data_[j]);
}
return result;
}
if constexpr (Axis == 1)
{
tensor<Type> result({ shape_.first, 1 });
for (int64_t i = 0; i < shape_.first; ++i)
{
result.data_[i] = data_[i];
for (int64_t j = 0; j < shape_.second; ++j)
result.data_[i] = std::min(data_[i * shape_.second + j], result.data_[i]);
}
return result;
}
throw std::runtime_error("Invalid axis template parameter!");
}
template <typename Type>
Type tensor<Type>::min() const
{
Type min = data_[0];
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
min = std::min(data_[i * shape_.second + j], min);
return min;
}
template <typename Type>
template <uint_fast8_t Axis>
tensor<size_t> tensor<Type>::argmax() const
{
if constexpr (Axis == 0)
{
tensor<size_t> result({ 1, shape_.second });
for (int64_t j = 0; j < shape_.second; ++j)
{
result[{0, j}] = 0;
for (int64_t i = 0; i < shape_.first; ++i)
{
auto const current = result[{0, j}];
result[{0, j}] = data_[i * shape_.second + j] > data_[current * shape_.second + j] ? i : current;
}
}
return result;
}
if constexpr (Axis == 1)
{
tensor<size_t> result({ shape_.first, 1 });
for (int64_t i = 0; i < shape_.first; ++i)
{
result[{i, 0}] = 0;
for (int64_t j = 0; j < shape_.second; ++j)
{
auto const current = result[{i, 0}];
result[{i, 0}] = data_[i * shape_.second + j] > data_[i * shape_.second + current] ? j : current;
}
}
return result;
}
throw std::runtime_error("Invalid axis template parameter!");
}
template <typename Type>
tensor_index tensor<Type>::argmax() const
{
tensor_index max = { 0,0 };
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
if ((data_[i * shape_.second + j] > data_[max.first * shape_.second + max.second])) max = tensor_index{ i, j };
return max;
}
template <typename Type>
template <uint_fast8_t Axis>
tensor<size_t> tensor<Type>::argmin() const
{
if constexpr (Axis == 0)
{
tensor<size_t> result({ 1, shape_.second });
for (int64_t j = 0; j < shape_.second; ++j)
{
result[{0, j}] = 0;
for (int64_t i = 0; i < shape_.first; ++i)
{
auto const current = result[{0, j}];
result[{0, j}] = data_[i * shape_.second + j] < data_[current * shape_.second + j] ? i : current;
}
}
return result;
}
if constexpr (Axis == 1)
{
tensor<size_t> result({ shape_.first, 1 });
for (int64_t i = 0; i < shape_.first; ++i)
{
result[{i, 0}] = data_[i];
for (int64_t j = 0; j < shape_.second; ++j)
{
auto const current = result[{i, 0}];
result[{i, 0}] = data_[i * shape_.second + j] < data_[i * shape_.second + current] ? j : current;
}
}
return result;
}
throw std::runtime_error("Invalid axis template parameter!");
}
template <typename Type>
tensor_index tensor<Type>::argmin() const
{
tensor_index min = { 0,0 };
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
if ((data_[i * shape_.second + j] < data_[min.first * shape_.second + min.second])) min = tensor_index{ i, j };
return min;
}
template <typename Type>
template <typename Reduction, uint_fast8_t Axis>
tensor<Type> tensor<Type>::reduce(Reduction reduction) const
{
if constexpr (Axis == 0)
{
tensor<Type> result({ 1, shape_.second });
for (int64_t j = 0; j < shape_.second; ++j)
{
result.data_[j] = data_[j];
for (int64_t i = 1; i < shape_.first; ++i)
result.data_[j] = reduction(data_[i * shape_.second + j], result.data_[j]);
}
return result;
}
if constexpr (Axis == 1)
{
tensor<Type> result({ shape_.first, 1 });
for (int64_t i = 0; i < shape_.first; ++i)
{
result.data_[i] = data_[i * shape_.second];
for (int64_t j = 1; j < shape_.second; ++j)
result.data_[i] = reduction(data_[i * shape_.second + j], result.data_[i]);
}
return result;
}
throw std::runtime_error("Invalid axis template parameter!");
}
template <typename Type>
template <typename Reduction>
Type tensor<Type>::reduce(Reduction reduction) const
{
Type r = data_[0];
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = i == 0 ? 1 : 0; j < shape_.second; ++j)
r = reduction(data_[i * shape_.second + j], r);
return r;
}
template <typename Type>
tensor<Type>& tensor<Type>::log()
{
#pragma omp parallel for
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
data_[i * shape_.second + j] = std::log(static_cast<double>(data_[i * shape_.second + j]));
return *this;
}
template <typename Type>
tensor<Type> log(tensor<Type> tensor)
{
return tensor.log();
}
template <typename Type>
tensor<Type>& tensor<Type>::exp()
{
#pragma omp parallel for
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
data_[i * shape_.second + j] = std::exp(static_cast<double>(data_[i * shape_.second + j]));
return *this;
}
template <typename Type>
tensor<Type> exp(tensor<Type> tensor)
{
return tensor.exp();
}
template <typename Type>
tensor<Type>& tensor<Type>::abs()
{
#pragma omp parallel for
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
data_[i * shape_.second + j] = std::fabs(static_cast<double>(data_[i * shape_.second + j]));
return *this;
}
template <typename Type>
tensor<Type> abs(tensor<Type> tensor)
{
return tensor.abs();
}
template <typename Type>
tensor<Type>& tensor<Type>::sqrt()
{
#pragma omp parallel for
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
data_[i * shape_.second + j] = std::sqrt(static_cast<double>(data_[i * shape_.second + j]));
return *this;
}
template <typename Type>
tensor<Type> sqrt(tensor<Type> tensor)
{
return tensor.sqrt();
}
template <typename Type>
tensor<Type>& tensor<Type>::maximum(Type max)
{
#pragma omp parallel for
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
data_[i * shape_.second + j] = std::max(data_[i * shape_.second + j], max);
return *this;
}
template <typename Type>
tensor<Type> maximum(tensor<Type> tensor, Type max)
{
return tensor.maximum(max);
}
template <typename Type>
tensor<Type>& tensor<Type>::minimum(Type max)
{
#pragma omp parallel for
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
data_[i * shape_.second + j] = std::min(data_[i * shape_.second + j], max);
return *this;
}
template <typename Type>
tensor<Type> minimum(tensor<Type> tensor, Type max)
{
return tensor.minimum(max);
}
template <typename Type>
template <typename Function>
tensor<Type> tensor<Type>::apply(Function func)
{
#pragma omp parallel for
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
data_[i * shape_.second + j] = func(data_[i * shape_.second + j]);
return *this;
}
template <typename Type, typename Function>
tensor<Type> apply(tensor<Type> tensor, Function func)
{
return tensor.apply(func);
}
template<typename Type, typename Function>
tensor<Type> produce(tensor<Type> lhs, tensor<Type> const& rhs, Function function)
{
if (lhs.shape().first == rhs.shape().first && rhs.shape().second == 1)
{
#pragma omp parallel for
for (int64_t i = 0; i < lhs.shape().first; ++i)
{
auto const elem = rhs[{i, 0}];
for (int64_t j = 0; j < lhs.shape().second; ++j)
lhs[{ i, j }] = Type(function(lhs[{ i, j }], elem));
}
}
else if (lhs.shape().second == rhs.shape().second && rhs.shape().first == 1)
{
#pragma omp parallel for
for (int64_t j = 0; j < lhs.shape().second; ++j)
{
auto const elem = rhs[{0, j}];
for (int64_t i = 0; i < lhs.shape().first; ++i)
lhs[{ i, j }] = Type(function(lhs[{ i, j }], elem));
}
}
else if (lhs.shape().first == rhs.shape().first && lhs.shape().second == rhs.shape().second)
{
#pragma omp parallel for
for (int64_t i = 0; i < lhs.shape().first; ++i)
for (int64_t j = 0; j < lhs.shape().second; ++j)
lhs[{ i, j }] = Type(function(lhs[{ i, j }], rhs[{i, j}]));
}
else
throw std::runtime_error("Invalid shapes - " + to_string(lhs.shape()) + " and " + to_string(rhs.shape()) + "!");
return lhs;
}
| 23.751004
| 114
| 0.620984
|
[
"shape"
] |
257636febd6bd9ade52255789c01fe8f0b9b09d8
| 1,710
|
h
|
C
|
components/DynamicIndication/DataPolycy/ic74141ParralelPolcy.h
|
ololoshka2871/NixieClock-ESP32-idf
|
1505f801ca6f5ff36d2648805b20dab5d1326c12
|
[
"Apache-2.0"
] | null | null | null |
components/DynamicIndication/DataPolycy/ic74141ParralelPolcy.h
|
ololoshka2871/NixieClock-ESP32-idf
|
1505f801ca6f5ff36d2648805b20dab5d1326c12
|
[
"Apache-2.0"
] | null | null | null |
components/DynamicIndication/DataPolycy/ic74141ParralelPolcy.h
|
ololoshka2871/NixieClock-ESP32-idf
|
1505f801ca6f5ff36d2648805b20dab5d1326c12
|
[
"Apache-2.0"
] | null | null | null |
#ifndef _ID1_PARRALEL_POLICY_H_
#define _ID1_PARRALEL_POLICY_H_
#include <memory>
#include <vector>
#include "esp_log.h"
#include "../typed"
namespace DynamicIndication {
namespace DataPolicy {
template <typename T> struct ic7414ParralelPolicy {
using bus_type = T;
using data_type = typename bus_type::data_type;
static constexpr char TAG[] = "ic7414ParralelPolicy";
static constexpr uint32_t bits_pre_channel = 4;
using framebuffer_element_type = typename typed<bits_pre_channel>::type;
ic7414ParralelPolicy(bus_type &databus, const uint32_t group_count = 1)
: databus{databus}, channels_pre_data_bus{databus.width() /
bits_pre_channel},
group_count{group_count} {}
ic7414ParralelPolicy(const ic7414ParralelPolicy &) = delete;
void setData(const std::vector<data_type> &dataSrc, uint8_t group) {
uint32_t bus_val = 0;
for (uint ch = 0; ch < channels_pre_data_bus; ++ch) {
if (dataSrc.size() <= group + ch * group_count) {
ESP_LOGW(TAG,
"dataSrc.size()[%d] <= group[%d] + "
"ch[%d] * group_count[%d]",
dataSrc.size(), group, ch, group_count);
return;
}
auto d = dataSrc.at(group + ch * group_count);
bus_val |= d << (bits_pre_channel * ch);
}
databus.setData(bus_val);
}
size_t framebufferSize() const { return channels_pre_data_bus * group_count; }
private:
bus_type &databus;
const uint32_t channels_pre_data_bus;
const uint32_t group_count;
};
} // namespace DataPolicy
} // namespace DynamicIndication
#endif /* _ID1_PARRALEL_POLICY_H_ */
| 29.482759
| 81
| 0.644444
|
[
"vector"
] |
257c24ef4aca40e597471db7bdf4109d04210664
| 5,549
|
h
|
C
|
MMOCoreORB/src/server/zone/objects/creature/commands/TransferItemArmorCommand.h
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 18
|
2017-02-09T15:36:05.000Z
|
2021-12-21T04:22:15.000Z
|
MMOCoreORB/src/server/zone/objects/creature/commands/TransferItemArmorCommand.h
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 61
|
2016-12-30T21:51:10.000Z
|
2021-12-10T20:25:56.000Z
|
MMOCoreORB/src/server/zone/objects/creature/commands/TransferItemArmorCommand.h
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 71
|
2017-01-01T05:34:38.000Z
|
2022-03-29T01:04:00.000Z
|
/*
Copyright <SWGEmu>
See file COPYING for copying conditions.*/
#ifndef TRANSFERITEMARMORCOMMAND_H_
#define TRANSFERITEMARMORCOMMAND_H_
#include "server/zone/objects/scene/SceneObject.h"
#include "server/zone/managers/objectcontroller/ObjectController.h"
#include "server/zone/managers/player/PlayerManager.h"
#include "server/zone/objects/player/sessions/TradeSession.h"
class TransferItemArmorCommand : public QueueCommand {
public:
TransferItemArmorCommand(const String& name, ZoneProcessServer* server)
: QueueCommand(name, server) {
}
int doQueueCommand(CreatureObject* creature, const uint64& target, const UnicodeString& arguments) const {
if (!checkStateMask(creature))
return INVALIDSTATE;
if (!checkInvalidLocomotions(creature))
return INVALIDLOCOMOTION;
/*
creature->info("transfer item armor");
StringBuffer infoMsg;
infoMsg << "target: 0x" << hex << target << " arguments" << arguments.toString();
creature->info(infoMsg.toString());
*/
StringTokenizer tokenizer(arguments.toString());
uint64 destinationID = tokenizer.getLongToken();
int transferType = tokenizer.getIntToken(); // I've seen -1 usually.. 4 when equipping most clothes (I think -1 is remove)
float unknown1 = tokenizer.getFloatToken();
float unknown2 = tokenizer.getFloatToken();
float unknown3 = tokenizer.getFloatToken();
ManagedReference<TradeSession*> tradeContainer = creature->getActiveSession(SessionFacadeType::TRADE).castTo<TradeSession*>();
if (tradeContainer != nullptr) {
server->getZoneServer()->getPlayerManager()->handleAbortTradeMessage(creature);
}
ManagedReference<SceneObject*> objectToTransfer = server->getZoneServer()->getObject(target);
if (objectToTransfer == nullptr) {
creature->error("objectToTransfer nullptr in transferitemarmor command");
return GENERALERROR;
}
if (!objectToTransfer->checkContainerPermission(creature, ContainerPermissions::MOVECONTAINER))
return GENERALERROR;
ManagedReference<SceneObject*> objectsParent = objectToTransfer->getParent().get();
if (objectsParent == nullptr)
return GENERALERROR;
if (!objectsParent->checkContainerPermission(creature, ContainerPermissions::MOVEOUT))
return GENERALERROR;
if (!objectToTransfer->isWearableObject()) {
creature->error("objectToTransfer is not an armor object in transferitemarmor");
return GENERALERROR;
}
if (!objectToTransfer->isASubChildOf(creature))
return GENERALERROR;
ManagedReference<SceneObject*> destinationObject = server->getZoneServer()->getObject(destinationID);
if (destinationObject == nullptr) {
creature->error("destinationObject nullptr in transferitemarmor command");
return GENERALERROR;
}
if (destinationObject != creature) {
creature->error("destinationObject is not player in transferitemarmor command");
return GENERALERROR;
}
if (transferType == 4) {
ManagedReference<SceneObject*> parent = objectToTransfer->getParent().get();
if (parent == nullptr) {
creature->error("objectToTransfer parent is nullptr in transferitemarmor command");
return GENERALERROR;
}
ZoneServer* zoneServer = server->getZoneServer();
ObjectController* objectController = zoneServer->getObjectController();
String errorDescription;
int transferPreProcess = destinationObject->canAddObject(objectToTransfer, transferType, errorDescription);
if (transferPreProcess == TransferErrorCode::SLOTOCCUPIED) {
int arrangementSize = objectToTransfer->getArrangementDescriptorSize();
if (arrangementSize > 0) {
int arrangementGroupToUse = -1;
for (int i = 0; i < arrangementSize && arrangementGroupToUse == -1; ++i) {
const Vector<String>* descriptors = objectToTransfer->getArrangementDescriptor(i);
for (int j = 0; j < descriptors->size(); ++j) {
const String& descriptor = descriptors->get(j);
if (destinationObject->getSlottedObject(descriptor) == nullptr && arrangementGroupToUse == -1) {
arrangementGroupToUse = i;
} else if (arrangementGroupToUse != -1) {
arrangementGroupToUse = -1;
break;
}
}
}
if (arrangementGroupToUse != -1) {
transferType += arrangementGroupToUse;
} else {
const String& childArrangement = objectToTransfer->getArrangementDescriptor(0)->get(0);
ManagedReference<SceneObject*> objectToRemove = destinationObject->getSlottedObject(childArrangement);
if (objectToRemove == nullptr)
return GENERALERROR;
if (!objectController->transferObject(objectToRemove, parent, 0xFFFFFFFF, true))
return GENERALERROR;
}
}
} else if (transferPreProcess != 0) {
if (errorDescription.length() > 1)
creature->sendSystemMessage(errorDescription);
return GENERALERROR;
}
if (!objectController->transferObject(objectToTransfer, destinationObject, transferType, true))
return GENERALERROR;
} /*else if (transferType == 4) {
}*/ else {
creature->error("unknown transferType in transferitemarmor command");
}
/*
uint64 target = packet->parseLong();
TangibleObject* targetTanoObject;
targetTanoObject = cast<TangibleObject*>( player->getInventoryItem(target));
if (targetTanoObject != nullptr) {
Inventory* inventory = player->getInventory();
if (inventory != nullptr)
inventory->moveObjectToTopLevel(player, targetTanoObject);
player->changeArmor(target, false);
}*/
return SUCCESS;
}
};
#endif //TRANSFERITEMARMORCOMMAND_H_
| 31.350282
| 128
| 0.725716
|
[
"object",
"vector"
] |
257f00462e5cca2062f164b46d5c2f0c0dc23f57
| 6,609
|
h
|
C
|
view/QOptionPropertyBrowser.h
|
ipantao/AutoPilot-Tool
|
4418fa4fce09ae373c2437398997d1fec53bf3e8
|
[
"Apache-2.0"
] | 1
|
2021-01-20T02:12:05.000Z
|
2021-01-20T02:12:05.000Z
|
view/QOptionPropertyBrowser.h
|
ipantao/AutoPilot-Tool
|
4418fa4fce09ae373c2437398997d1fec53bf3e8
|
[
"Apache-2.0"
] | null | null | null |
view/QOptionPropertyBrowser.h
|
ipantao/AutoPilot-Tool
|
4418fa4fce09ae373c2437398997d1fec53bf3e8
|
[
"Apache-2.0"
] | null | null | null |
/******************************************************************************
* IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. *
* *
* By downloading, copying, installing or using the software you agree to *
* this license.If you do not agree to this license, do not download, *
* install,copy or use the software. *
* *
* License Agreement *
* For AutoPilot-tool *
* *
* Copyright (C) 2020, Huang Jianyu, all rights reserved. *
* Third party copyrights are property of their respective owners. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification,are permitted provided that the following conditions are met: *
* *
* * Redistribution's of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* *
* * Redistribution's in binary form must reproduce the above copyright *
* notice,this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* * The name of the copyright holders may not be used to endorse or promote *
* productsderived 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 Intel Corporation or contributors be *
* liable for any direct,indirect, incidental, special, exemplary, or *
* consequential damages(including, but not limited to, procurement of *
* substitute goods or services;loss of use, data, or profits; or business *
* interruption) however caused and on any theory of liability, whether in *
* contract, strict liability,or tort (including negligence or otherwise) *
* arising in any way out of the use of this software, even if advised of *
* the possibility of such damage. *
* *
*******************************************************************************
* Author: Huang Jianyu **
* Website: https://github.com/HjyTiger/AutoPilot-Tool **
* Date: 2020.12.24 **
* Version: 1.0.0 **
******************************************************************************/
#pragma once
#include "Model/Model_Config.h"
#include <string>
#include <atomic>
#include <QObject>
#include "qtpropertymanager.h"
#include "qteditorfactory.h"
#include "qttreepropertybrowser.h"
#include "qtbuttonpropertybrowser.h"
#include "qtgroupboxpropertybrowser.h"
enum PropertyOperation{
//common
THEME_CHANGE,
VIEW_CHANGE,
ENABLE_MOUSE,
ENABLE_KEYBOARD,
MOUSE_SENSITIVITY_CHANGE,
MOUSEWHEEL_SENSITIVITY_CHANGE,
KEYBOARD_SENSITIVITY_CHANGE,
//logger
CHANGE_PROJECT_NAME,
CHANGE_SW_VERSION,
CHANGE_VEHICLE_NO,
CHANGE_TESTER_NAME,
CHANGE_DATA_DISK,
CHANGE_LOG_CONS_TYPE,
CHANGE_LOG_CONS_VALUE,
CHANGE_RECORD_MODE,
CHANGE_RECORD_VALUE,
//player
ENABLE_PUBLISH_LCM,
CHANGE_PLAY_SPEED
};
struct PropertyOperationValue{
bool value_flag;
int value_enum;
int value_int;
float value_float;
double value_double;
std::string value_string;
};
Q_DECLARE_METATYPE(PropertyOperationValue)
enum LogConstrainType{
LOG_TIME_DURATION,
LOG_FILE_SIZE,
LOG_MESSAGE_COUNT
};
enum RecordMode{
RECORD_TIME_DURATION,
RECORD_FILE_SIZE,
RECORD_MESSAGE_COUNT
};
///
/// \brief The QTagTableWidget class
///
class QOptionPropertyBrowser: public QtTreePropertyBrowser
{
Q_OBJECT
public:
explicit QOptionPropertyBrowser(QWidget *parent = 0);
virtual ~QOptionPropertyBrowser();
public:
void Init();
void InitSignalAndSlot();
void InitCommonProperty();
void InitLoggerProperty();
void InitPlayerProperty();
void set_Config(tool::Option_Config * option_config);
void save_Config();
tool::Option_Config * get_Config(){
return config_;
}
private:
tool::Option_Config * config_;
QtStringPropertyManager * m_stringManager;
QtBoolPropertyManager * m_boolManager;
QtEnumPropertyManager * m_enumManager;
QtIntPropertyManager * m_intManager;
QtIntPropertyManager * m_intManager_slider;
QtDoublePropertyManager * m_doubleManager;
QtCheckBoxFactory * m_checkBoxFactory;
QtSpinBoxFactory * m_spinBoxFactory;
QtLineEditFactory * m_lineEditFactory;
QtEnumEditorFactory * m_comboBoxFactory;
QtDoubleSpinBoxFactory * m_doubleSpinBoxFactory;
QtSliderFactory * m_sliderFactory;
QtGroupPropertyManager * m_groupManager;
std::map<std::string,QtProperty *> m_Property_Map;
signals:
void updatePropertyOperation(int operation,PropertyOperationValue operValue);
void operationInformation(QString msgInfo,QColor strcolor);
public slots:
void OnStringChanged(QtProperty * property, QString val);
void OnBoolChanged(QtProperty * property, bool val);
void OnEnumChanged(QtProperty * property, int val);
void OnIntChanged(QtProperty * property, int val);
void OnIntSliderChanged(QtProperty * property, int val);
void OnDoubleChanged(QtProperty * property, double val);
};
| 41.829114
| 81
| 0.563323
|
[
"model"
] |
25982e0cfa321224d6ebd12b675dc07b52cb08be
| 4,623
|
h
|
C
|
NkEngine/include/GameLoop.h
|
dandov/NoKarma
|
e87eaf49e6980f6f31849aaa9d09889b206be609
|
[
"Apache-2.0"
] | null | null | null |
NkEngine/include/GameLoop.h
|
dandov/NoKarma
|
e87eaf49e6980f6f31849aaa9d09889b206be609
|
[
"Apache-2.0"
] | null | null | null |
NkEngine/include/GameLoop.h
|
dandov/NoKarma
|
e87eaf49e6980f6f31849aaa9d09889b206be609
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2015 Alvaro Herrasti and Daniel Dovali
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 GAME_LOOP_H
#define GAME_LOOP_H
#pragma once
#include <iostream>
#include <map>
#include <unordered_map>
#include <functional>
#include <cstdarg>
#include "GameSystem.h"
#include "SystemMessageSender.h"
template <typename KeyType>
class GameLoop
{
public:
// Constructs gameloop, recieves comparator function to order templated GameLoops, systemManager owning this gameloop,
// maxSubSteps maximum number of steps for simulation clamps when time since last render is big and loop runs multiple times with each fixed step,
// fixedTimeStep discrete timestep that will be passed to each system's update, if zero it passes delta time since last render
// priority of this gameloop with respect to others in SystemManager to which this is added
GameLoop(std::function<bool(const KeyType&, const KeyType&)> comparator, SystemMessageSender* sysManager,
double maxSubSteps = 1.0, double fixedTimeStep = 0.0, int priority = 0) :
mMaxSubSteps(maxSubSteps),
mFixedTimeStep(fixedTimeStep),
mSystemMap(comparator),
mComparator(comparator),
mSysManager(sysManager),
mTimeAccumulator(0.0),
mPriority(priority)
{
}
// lvalue copy constructor
GameLoop(GameLoop&& other) :
mMaxSubSteps(other.mMaxSubSteps),
mFixedTimeStep(other.mFixedTimeStep),
mSystemMap(std::move(other.mSystemMap)),
mComparator(other.mComparator),
mSysManager(other.mSysManager),
mTimeAccumulator(other.mTimeAccumulator),
mPriority(other.mPriority)
{
}
GameLoop() :
mMaxSubSteps(0),
mFixedTimeStep(0),
mSysManager(nullptr),
mTimeAccumulator(0.0),
mPriority(0)
{
}
// Adds new system to run, recieves priority key and object to copy
template <class T>
std::shared_ptr<GameSystem> addNewSystem(const KeyType& priorityKey, T&& newSystem) {
std::shared_ptr<GameSystem> system = std::shared_ptr<GameSystem>(new T(std::move(newSystem)));
this->mSystemMap[priorityKey] = system;
const std::type_info* type = &typeid(T);
mSysManager->addSystem(type, system);
return system;
}
// Adds new system to run, recieves priority and initializes new object with default constructor
template <class T>
std::shared_ptr<GameSystem> addNewSystem(const KeyType& priorityKey) {
std::shared_ptr<GameSystem> system = std::shared_ptr<GameSystem>(new T());
this->mSystemMap[priorityKey] = system;
const std::type_info* type = &typeid(T);
mSysManager->addSystem(type, system);
return system;
}
// removes system based on priority key
template <class T>
bool removeSystem(const KeyType& priorityKey) {
auto sysIt = this->ms
this->mSystemMap[priorityKey] = system;
const std::type_info* type = &typeid(T);
mSysManager->removeSystem(type);
return system;
}
// recieves deltaTime since last render
void run(double deltaTimeStep, SystemMessageSender* msgSender)
{
int loops = 0;
mTimeAccumulator += deltaTimeStep;
// runs systems in discrete fixed timesteps for deterministic behavior
// and clamps to max number of steps if simulation is runing too slow
while (mTimeAccumulator >= mFixedTimeStep && loops < mMaxSubSteps) {
// if mFixedTimeStep
double deltaTimeUpdate = mFixedTimeStep != 0.0 ? mFixedTimeStep : deltaTimeStep;
for (auto it = this->mSystemMap.begin(); it != this->mSystemMap.end(); it++)
{
it->second->update(deltaTimeUpdate, msgSender);
}
mTimeAccumulator -= deltaTimeUpdate;
loops++;
}
}
// Sets priority of this gameloop
void setPriority(int priority) {
this->mPriority = priority;
}
// gets priority of this gameloop, reference value used to look for inside a SystemManager
int getPriority() {
return this->mPriority;
}
~GameLoop()
{
}
private:
double mMaxSubSteps;
double mFixedTimeStep;
typedef std::map < KeyType, std::shared_ptr<GameSystem>, std::function<bool(const KeyType&, const KeyType&)> > SystemMap;
SystemMap mSystemMap;
typedef std::function<bool(const KeyType&, const KeyType&)> CompareFunc;
CompareFunc mComparator;
SystemMessageSender* mSysManager;
double mTimeAccumulator;
int mPriority;
};
#endif
| 30.615894
| 147
| 0.750811
|
[
"render",
"object"
] |
055c969148e2e10bc6bd42c93591bbd75aad8b8f
| 3,089
|
h
|
C
|
engine/neural/phenome.h
|
SirBob01/BraniacEngine
|
d8f4977a81da6b635399b908ddf52655f82b26eb
|
[
"MIT"
] | null | null | null |
engine/neural/phenome.h
|
SirBob01/BraniacEngine
|
d8f4977a81da6b635399b908ddf52655f82b26eb
|
[
"MIT"
] | null | null | null |
engine/neural/phenome.h
|
SirBob01/BraniacEngine
|
d8f4977a81da6b635399b908ddf52655f82b26eb
|
[
"MIT"
] | null | null | null |
#ifndef CHESS_NEURAL_PHENOME_H_
#define CHESS_NEURAL_PHENOME_H_
#include <unordered_set>
#include <queue>
#include <algorithm>
#include <cassert>
#include "genome.h"
#include "quadtree.h"
namespace chess::neural {
struct NodePhenotype {
double bias;
NodeType type;
activation_t function;
double activation = 0;
};
class Phenome {
Genome &_genome;
PhenomeParameters _params;
int _node_count;
std::vector<Point> &_inputs;
std::vector<Point> &_outputs;
// Map 3D substrate points to node indexes
std::unordered_map<Point, int, PointHash> _pointset;
std::unordered_map<int, NodePhenotype> _nodes;
std::unordered_map<Edge, double, EdgeHash> _edges;
std::unordered_map<int, std::vector<int>> _adjacency;
std::vector<int> _sorted;
/**
* Checks if adding a new edge will create a cycle
*/
bool creates_cycle(Edge edge);
/**
* Query the CPPN (genome) to generate weight and bias values
*/
double calculate_weight(Point p0, Point p1);
/**
* Perform the division and initialization step of the evolving substrate
*/
Quadtree *division_initialization(Point point, bool outgoing);
/**
* Perform the prune and extract algorithm of the evolving substrate
*/
void prune_extract(Point point, Quadtree *quadtree, bool outgoing,
std::unordered_map<Edge, double, EdgeHash> &connections);
/**
* Check if a path exists between two nodes using BFS
*/
bool path_exists(int start, int end);
/**
* Remove nodes and connections that do not have a path to inputs or outputs
*/
void cleanup();
/**
* Generate the adjacency list
*/
void generate_adjacency();
/**
* Topologically sort the nodes for feed-forward evaluation
*/
void topological_sort(int node, std::unordered_set<int> &visited);
/**
* Update the internal graph structure of the neural network for evaluation
*/
void update_structure();
/**
* Check if all the output nodes are active
*/
bool active_output();
public:
/**
* A phenome is defined by the genome CPPN
*/
Phenome(Genome &genome, std::vector<Point> &inputs, std::vector<Point> &outputs, PhenomeParameters params);
Phenome &operator=(const Phenome &rhs);
/**
* Evaluate the neural network
*/
std::vector<double> forward(std::vector<double> input);
/**
* Get the fitness of this phenome's genome
*/
double get_fitness();
/**
* Set the fitness of this phenome's genome
*/
void set_fitness(double fitness);
/**
* Get this phenome's genome
*/
Genome &get_genome();
};
}
#endif
| 26.177966
| 115
| 0.574296
|
[
"vector",
"3d"
] |
0567cc3546ac4d2db9ee624479903a2b628cbd36
| 726
|
c
|
C
|
trunk/freertos/app/mesh/gatt/mesh_gatt_cfg.c
|
HESUPING/JmeshBLE-StaticLib
|
cf0900f004026c7e2e3448ffde07e21d4af8e387
|
[
"Apache-2.0"
] | null | null | null |
trunk/freertos/app/mesh/gatt/mesh_gatt_cfg.c
|
HESUPING/JmeshBLE-StaticLib
|
cf0900f004026c7e2e3448ffde07e21d4af8e387
|
[
"Apache-2.0"
] | null | null | null |
trunk/freertos/app/mesh/gatt/mesh_gatt_cfg.c
|
HESUPING/JmeshBLE-StaticLib
|
cf0900f004026c7e2e3448ffde07e21d4af8e387
|
[
"Apache-2.0"
] | 3
|
2019-08-27T17:11:42.000Z
|
2021-02-04T06:38:35.000Z
|
/*
* mesh_gatt_cfg.c
*
* Created on: 2018��8��2��
* Author: huichen
*/
/*
* INCLUDE FILES
****************************************************************************************
*/
#include "osapp_config.h"
#ifdef OSAPP_MESH
#include "mesh_gatt_cfg.h"
///**
// ****************************************************************************************
// * @brief The Mesh Gatt att_mtu max size to peer device.
// *
// * @param[in] conn_index gatt connect index.
// *
// * @return The max gatt mtu size.
// *
// ****************************************************************************************
// */
//uint16_t mesh_gatt_get_att_mtu_size(uint16_t conn_index)
//{
//
//}
//
//
#endif /* OSAPP_MESH */
| 20.166667
| 91
| 0.378788
|
[
"mesh"
] |
056cfa89280f252bfc356d97fab7df0678bdd2e9
| 2,108
|
h
|
C
|
Cortex/MedableCortex.framework/Headers/MDNotification.h
|
Medable/iOS-SDK
|
af1839129bcaa470ef4f247de325c64de52eac2e
|
[
"0BSD"
] | 7
|
2015-04-23T02:38:52.000Z
|
2021-05-05T03:29:27.000Z
|
Cortex/MedableCortex.framework/Headers/MDNotification.h
|
Medable/iOS-SDK
|
af1839129bcaa470ef4f247de325c64de52eac2e
|
[
"0BSD"
] | 6
|
2015-04-24T20:21:51.000Z
|
2018-10-07T20:54:39.000Z
|
Cortex/MedableCortex.framework/Headers/MDNotification.h
|
Medable/iOS-SDK
|
af1839129bcaa470ef4f247de325c64de52eac2e
|
[
"0BSD"
] | 4
|
2015-07-07T06:17:40.000Z
|
2018-05-28T14:12:43.000Z
|
//
// MDNotification.h
// Medable
//
// Copyright (c) 2014 Medable. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "MDNotificationManager.h"
#import "MDBaseInstance.h"
@class MDObjectId;
@class MDReference;
NS_ASSUME_NONNULL_BEGIN
/**
* Notifications are created as a result of modifications to contexts, posts and comment begin created or edited,
* invitations to connect and context ownership transfer requests.
* An Organization can setup an app for Apple Push Notification Service (APNs), and users can set preferences for
* how to receive notifications, through APNs or via email.
*
* Notifications are automatically cleared for posts and comments when they are retrieved using the API. Otherwise,
* clients should manually clear them using the notifications API.
*/
@interface MDNotification : MDBaseInstance
/**
* The context for which the notification was created.
*/
@property (nonatomic, readonly) MDReference* context;
/**
* Enumeration of the context the notification belongs to. Should only be used for default classes and not custom ones.
*/
@property (nonatomic, readonly) MDNotificationContext contextEnumerated;
/**
* Type-specific metadata
*/
@property (nonatomic, readonly) NSDictionary* meta;
/**
* Notification Type.
*/
@property (nonatomic, readonly) MDObjectId* type;
/**
* Type enumeration.
*
* @see MDNotificationType
*/
@property (nonatomic, readonly) MDNotificationType typeEnumerated;
/**
* Returns the ObjectId representing the type of notification.
*
* @param type type of notification
*
* @return MDObjectId representing the type of notification.
*/
+ (MDObjectId*)typeIdWithType:(MDNotificationType)type;
// unavailable
+ (instancetype)new NS_UNAVAILABLE;
// unavailable init
- (instancetype)init NS_UNAVAILABLE;
/**
* Create a new notification object from a received notification.
*
* @param attributes Notification information, as received.
*
* @return Instance representing the received notification.
*/
- (instancetype)initWithAttributes:(nonnull NSDictionary*)attributes;
@end
NS_ASSUME_NONNULL_END
| 25.39759
| 119
| 0.760911
|
[
"object"
] |
05768cebd4e5dfeca0dc24cc75803edaff00d190
| 9,668
|
h
|
C
|
modules/flowcontrol/plugin/PiiPisoOperation.h
|
topiolli/into
|
f0a47736f5c93dd32e89e7aad34152ae1afc5583
|
[
"BSD-3-Clause"
] | 14
|
2015-01-19T22:14:18.000Z
|
2020-04-13T23:27:20.000Z
|
modules/flowcontrol/plugin/PiiPisoOperation.h
|
topiolli/into
|
f0a47736f5c93dd32e89e7aad34152ae1afc5583
|
[
"BSD-3-Clause"
] | null | null | null |
modules/flowcontrol/plugin/PiiPisoOperation.h
|
topiolli/into
|
f0a47736f5c93dd32e89e7aad34152ae1afc5583
|
[
"BSD-3-Clause"
] | 14
|
2015-01-16T05:43:15.000Z
|
2019-01-29T07:57:11.000Z
|
/* This file is part of Into.
* Copyright (C) Intopii 2013.
* All rights reserved.
*
* Licensees holding a commercial Into license may use this file in
* accordance with the commercial license agreement. Please see
* LICENSE.commercial for commercial licensing terms.
*
* Alternatively, this file may be used under the terms of the GNU
* Affero General Public License version 3 as published by the Free
* Software Foundation. In addition, Intopii gives you special rights
* to use Into as a part of open source software projects. Please
* refer to LICENSE.AGPL3 for details.
*/
#ifndef _PIIPISOOPERATION_H
#define _PIIPISOOPERATION_H
#include <PiiDefaultOperation.h>
#include <QVector>
/**
* A parallel-to-serial converter. In the default non-grouped state,
* PiiPisoOperation outputs whatever it receives in any of its inputs
* to its single output. If [groupSize] is one, a PISO works like a
* multiplexer. A PISO is commonly useful in situations where multiple
* data sources feed data into one processing pipeline. The operation
* allows flexible control of input groups to redirect many
* synchronized input streams at once.
*
* If [groupSize] is greater than one, inputs are divided into
* synchronized groups. Input sockets from zero to `groupSize` - 1
* will form the first group, sockets from `groupSize` to 2 *
* `groupSize` - 1 the second one and so on. Every socket in a group
* must contain an object before it is processed. Whenever this
* happens, all objects will be simultaneously sent to the
* corresponding outputs. The first input in a group will be sent to
* `output0` and so on. If an input socket in a group has not been
* connected, there must be a [default value](defaultValues) for
* it.
*
*
* Configuring default values
* --------------------------
*
* A list of PiiVariant objects that will be used if a socket in a
* group is not connected. The first element in the list is the
* default value for the first input, or the first input in each
* group, depending on the value of [defaultValueMode]. The second
* element is the value for the second input and so on. An invalid
* PiiVariant means no default value. Input sockets with a valid
* default value will be marked optional. Default values have no
* effect if [groupSize] is one.
*
* ~~~(c++)
* PiiOperation* op = engine.createOperation("PiiPisoOperation");
* op->setProperty("groupSize", 2);
* op->setProperty("inputCount", 4);
* // No default value for first input in each group.
* // The default value for the second input is int(0)
* op->setProperty("defaultValues", PiiVariantList() << PiiVariant() << PiiVariant(0));
* ~~~
*
* You can configure also the one default value with property map
* (QVariantMap). Recognized property values are:
*
* - `index` - the index of the input to configure. (int, default
* value 0)
*
* - `defaultValue` - a PiiVariant object that will be used if the
* corresponding input is not connected.
*
* ~~~(c++)
* // Create a new piso
* PiiOperation* piso = engine.createOperation("PiiPisoOperation");
* piso->setProperty("groupSize", 2);
* piso->setProperty("dynamicInputCount", 4);
*
* QVariantMap props;
* props["index"] = 1;
* props["defaultValue"] = Pii::createQVariant(0);
* piso->setProperty("defaultValue", props);
* ~~~
*
* The default number of inputs is two.
*
* Inputs
* ------
*
* @in inputX - any number of input sockets that accept any object
* type. X ranges from 0 to `inputCount` - 1.
*
* @in groupX inputY - alias for input number X * [groupSize] + Y. If
* [groupSize] is 3, `group1` `input1` is an alias for `input4`.
*
* At least one of the inputs must be connected. If any of the inputs
* in a synchronous input group are connected, then all of them must
* either be connected or have a default value assigned.
*
* Outputs
* -------
*
* @out index - the index of the input group the object was or objects
* were received in. If [groupSize] is one (the default), the group
* index equals the index of the input socket.
*
* @out output - alias for output0. Emits the object received from any
* of the inputs. Objects are emitted in the order they are received.
*
* @out outputX - synchronous outputs, if [groupSize] is greater than
* one. X ranges from 0 to [groupSize]-1. Whenever all sockets in a
* synchronous group contain an object, the objects will be
* simultaneously sent to the corresponding outputs. That is,
* `groupX` `input0` will be redirected to `output0`, `groupX`
* `input1` to `input` 1 etc.
*
*/
class PiiPisoOperation : public PiiDefaultOperation
{
Q_OBJECT
/**
* The number of input sockets. Default is 2.
*/
Q_PROPERTY(int dynamicInputCount READ dynamicInputCount WRITE setDynamicInputCount);
/**
* The number of sockets in each synchronized group. It is usually a
* clever idea to make [dynamicInputCount] divisible by this value. If it is
* not, the last group will not have corresponding inputs for all
* outputs. In such a case there must be a [defaultValues]
* "default value" for each orphaned output. The default value is
* one.
*/
Q_PROPERTY(int groupSize READ groupSize WRITE setGroupSize);
/**
* A list of PiiVariant objects that will be used if a socket in
* a group is not connected. The first element in the list is the
* default value for the first input, or the first input in each
* group, depending on the value of [defaultValueMode]. The second
* element is the value for the second input and so on. An invalid
* PiiVariant means no default value. Input sockets with a valid
* default value will be marked optional. Default values have no
* effect if [groupSize] is one.
*
* ~~~(c++)
* PiiOperation* op = engine.createOperation("PiiPisoOperation");
* op->setProperty("groupSize", 2);
* op->setProperty("dynamicInputCount", 4);
* // No default value for first input in each group.
* // The default value for the second input is int(0)
* op->setProperty("defaultValues", PiiVariantList() << PiiVariant() << PiiVariant(0));
* ~~~
*/
Q_PROPERTY(PiiVariantList defaultValues READ defaultValues WRITE setDefaultValues);
/**
* Configure a single input. The `index` property in the
* `defaultValue` map specifies the input to configure.
*
* ~~~(c++)
* QVariantMap props;
* props["defaultValue"] = Pii::createQVariant("name");
* props["index"] = 0;
* piso->setProperty("defaultValue", props);
* ~~~
*/
Q_PROPERTY(QVariantMap defaultValue WRITE setDefaultValue STORED false);
/**
* Treatment of the [defaultValues] list. The default value is
* `SameDefaultsForAllGroups`.
*/
Q_PROPERTY(DefaultValueMode defaultValueMode READ defaultValueMode WRITE setDefaultValueMode);
Q_ENUMS(DefaultValueMode);
/**
* Operation mode. Default is `AsynchronousMode`.
*/
Q_PROPERTY(OperationMode operationMode READ operationMode WRITE setOperationMode);
Q_ENUMS(OperationMode);
PII_OPERATION_SERIALIZATION_FUNCTION
public:
/**
* Default value handling.
*
* - `SameDefaultsForAllGroups` - the [defaultValues] list is
* repeated for each group of synchronized inputs. The same default
* value applies to the corresponding sockets in each group. If the
* length of the [defaultValues] list is larger than [groupSize], the
* extra entries will be ignored.
*
* - `IndividualDefaults` - each input socket has its own default
* value. If the length of the [defaultValues] list is smaller than
* the number of input sockets, the rest of the input sockets will
* not have default values. If the length of the [defaultValues] list
* is larger than [dynamicInputCount], the extra entries will be ignored.
*/
enum DefaultValueMode { SameDefaultsForAllGroups, IndividualDefaults };
/**
* Operation modes.
*
* - `AsynchronousMode` - the operation passed data from any input
* group as soon as the group is full. Some groups may be handled
* more often than others. Synchronization information will be
* passed only once it is received in all groups.
*
* - `SynchronousMode` - the operation waits until all input groups
* are full before passing data. Input objects will then be emitted
* serially starting from group zero. The objects are sent between
* synchronization tags. (See PiiOutputSocket::startMany() and
* PiiOutputSocket::endMany().)
*/
enum OperationMode { AsynchronousMode, SynchronousMode };
PiiPisoOperation();
PiiInputSocket* input(const QString& name) const;
PiiOutputSocket* output(const QString& name) const;
void check(bool reset);
void setDefaultValue(const QVariantMap& defaultValue);
void setGroupSize(int groupSize);
int groupSize() const;
void setDefaultValues(const PiiVariantList& defaultValues);
PiiVariantList defaultValues() const;
void setDefaultValueMode(const DefaultValueMode& defaultValueMode);
DefaultValueMode defaultValueMode() const;
void setDynamicInputCount(int count);
int dynamicInputCount() const;
void setOperationMode(const OperationMode& operationMode);
OperationMode operationMode() const;
protected:
void process();
PiiFlowController* createFlowController();
private:
bool hasDefaultValue(int inputIndex);
void passObjectsInGroup(int groupId);
/// @internal
class Data : public PiiDefaultOperation::Data
{
public:
Data();
int iGroupSize;
int iGroupCount;
PiiVariantList lstDefaultValues;
QVector<bool> vecConnectedInputs;
DefaultValueMode defaultValueMode;
OperationMode operationMode;
};
PII_D_FUNC;
};
#endif //_PIIPISOOPERATION_H
| 36.760456
| 96
| 0.71959
|
[
"object"
] |
0577c422051398cfcab50f3ac4f0f8d83f8e502c
| 689
|
h
|
C
|
source/laplace/engine/basic_impact.predef.h
|
ogryzko/laplace
|
be63caa0c6d1c4fceab02ab5b41b6d307ef7baaf
|
[
"MIT"
] | null | null | null |
source/laplace/engine/basic_impact.predef.h
|
ogryzko/laplace
|
be63caa0c6d1c4fceab02ab5b41b6d307ef7baaf
|
[
"MIT"
] | null | null | null |
source/laplace/engine/basic_impact.predef.h
|
ogryzko/laplace
|
be63caa0c6d1c4fceab02ab5b41b6d307ef7baaf
|
[
"MIT"
] | null | null | null |
/* laplace/engine/basic_impact.predef.h
*
* Impact declarations.
*
* Copyright (c) 2021 Mitya Selivanov
*
* This file is part of the Laplace project.
*
* Laplace 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 MIT License for more details.
*/
#ifndef laplace_engine_basic_impact_predef_h
#define laplace_engine_basic_impact_predef_h
#include <memory>
#include <vector>
namespace laplace::engine {
class basic_impact;
using ptr_impact = std::shared_ptr<basic_impact>;
using vptr_impact = std::vector<ptr_impact>;
}
#endif
| 24.607143
| 63
| 0.746009
|
[
"vector"
] |
058a60daa50b222bd9c34e202dbc99dd9a0406fa
| 9,397
|
h
|
C
|
include/FlowNetworks/include/FlowNetwork.h
|
nicholas-gs/DataStructsAndAlgos
|
2d999db6758619782fbb9cf38360746dbb653024
|
[
"MIT"
] | null | null | null |
include/FlowNetworks/include/FlowNetwork.h
|
nicholas-gs/DataStructsAndAlgos
|
2d999db6758619782fbb9cf38360746dbb653024
|
[
"MIT"
] | null | null | null |
include/FlowNetworks/include/FlowNetwork.h
|
nicholas-gs/DataStructsAndAlgos
|
2d999db6758619782fbb9cf38360746dbb653024
|
[
"MIT"
] | null | null | null |
//
// Created by Nicholas on 7 Jan 2021.
//
#pragma once
#include <cstddef>
#include <stdexcept>
#include <forward_list>
#include <memory>
#include <type_traits>
#include <vector>
#include <optional>
namespace wtl {
/**
* A directed edge in a flow network.
* @tparam CapacityType
*/
template<typename CapacityType>
struct FlowEdge {
std::size_t m_Source;
std::size_t m_Dest;
CapacityType m_Capacity;
CapacityType m_Flow = 0;
FlowEdge(std::size_t source, std::size_t dest, CapacityType capacity)
: m_Source(source), m_Dest(dest), m_Capacity(capacity) {}
[[nodiscard]] std::size_t source() const noexcept {
return m_Source;
}
[[nodiscard]] std::size_t dest() const noexcept {
return m_Dest;
}
[[nodiscard]] CapacityType getFlow() const noexcept {
return m_Flow;
}
[[nodiscard]] CapacityType getCapacity() const noexcept {
return m_Capacity;
}
[[nodiscard]] std::size_t other(std::size_t v) const {
if (v == m_Source)
return m_Dest;
else if (v == m_Dest) {
return m_Source;
} else {
throw std::invalid_argument("Invalid vertex");
}
}
/**
* Retrieve the residual capacity of the flow edge. Note that the residual capacity depends on
* which direction of the directed flow edge we are traversing.
* @param v
* @return
*/
[[nodiscard]] CapacityType getResidualCapacity(std::size_t v) const {
if (v == m_Dest) {
return m_Capacity - m_Flow;
} else if (v == m_Source) {
return m_Flow;
} else {
throw std::invalid_argument("Invalid vertex");
}
}
/**
* Add flow to the flow edge. If the flow is in the same direction as the directed edge,
* then the flow is added to the current flow, else it is subtracted.
* @param flow
* @param v
*/
void addFlowTo(std::size_t v, CapacityType flow) {
if (flow < 0 || getResidualCapacity(v) < flow) {
throw std::invalid_argument("Flow cannot be negative");
}
if (v == m_Dest) {
m_Flow += flow;
} else if (v == m_Source) {
m_Flow -= flow;
}
}
};
namespace impl {
template<typename CapacityType>
struct FlowNetwork_FlowEdge_Compare {
private:
using FlowEdge = FlowEdge<CapacityType>;
public:
bool operator()(const FlowEdge& lhs, const FlowEdge& rhs) const {
return (lhs.m_Source == rhs.m_Source && lhs.m_Dest == rhs.m_Dest)
|| (lhs.m_Source == rhs.m_Dest && lhs.m_Dest == rhs.m_Source);
}
};
}
/**
* A flow network is a directed graph where each edge has a capacity and flow value.
* The amount of flow on an edge cannot exceed the capacity of the edge.
* The vertices of the flow network are labelled from [0, number of vertices - 1].
* Flow Network does not allow for more than 1 edge between 2 vertices, regardless of edge direction.
* @tparam CapacityType
*/
template<typename CapacityType>
class FlowNetwork {
private:
using Edge = FlowEdge<CapacityType>;
using Edge_Ptr = Edge*;
using Compare = impl::FlowNetwork_FlowEdge_Compare<CapacityType>;
using Edges = std::forward_list<Edge>;
using Bucket = std::vector<Edge_Ptr>;
using AdjList = std::unique_ptr<Bucket[]>;
template<typename T>
friend
class FordFulkerson;
template<typename T>
friend
class EdmondsKarp;
template<typename T>
friend
class Dinic;
/// Number of vertices in the graph
const std::size_t m_VertexCount;
/// Keep track of number of edges.
std::size_t m_EdgeCount = 0;
/// Store all the edge objects
Edges m_Edges;
/// Graph represented as an adjacency list, which stores pointers to edges
AdjList m_Network;
/**
* Check if an vertex is invalid
* @param v
* @return True if invalid, false if valid
*/
[[nodiscard]] inline bool outOfBounds(std::size_t v) const noexcept {
return v < 0 || v >= m_VertexCount;
}
public:
/**
* Constructor
* @param vertexCount
*/
explicit FlowNetwork(std::size_t vertexCount)
: m_VertexCount(vertexCount) {
static_assert(std::is_arithmetic_v<CapacityType>, "CapacityType must be arithmetic type");
if (m_VertexCount < 1) {
throw std::invalid_argument("Flow network cannot have less than 1 vertex");
}
m_Network = std::make_unique<Bucket[]>(m_VertexCount);
}
/**
* Copy constructor
* @param other
* @return
*/
FlowNetwork(const FlowNetwork& other) = delete;
/**
* Copy assignment
* @param other
* @return
*/
FlowNetwork& operator=(const FlowNetwork& other) = delete;
/**
* Get the number of vertices in the flow network.
* @return
*/
[[nodiscard]] std::size_t vertex() const noexcept {
return m_VertexCount;
}
/**
* Get the number of edges in the flow network.
* @return
*/
[[nodiscard]] std::size_t edge() const noexcept {
return m_EdgeCount;
}
/**
* Get all edges adjacent to the specified vertex, which includes all edges pointing away
* and pointing towards the specified vertex.
* @param v
* @return vector of edge objects
*/
[[nodiscard]] std::vector<Edge> adjacent(std::size_t v) const {
if (outOfBounds(v)) {
throw std::invalid_argument("Invalid vertex");
}
std::vector<Edge> result;
for (const Edge_Ptr edgePtr : m_Network[v]) {
result.push_back(*edgePtr);
}
return result;
}
/**
* Get all edges in the flow network.
* @return vector of edge objects
*/
[[nodiscard]] std::vector<Edge> allEdges() const noexcept {
std::vector<Edge> result;
result.reserve(m_EdgeCount);
for (std::size_t i = 0; i < m_VertexCount; i++) {
for (const Edge_Ptr edgePtr : m_Network[i]) {
if (edgePtr->m_Source == i) {
result.push_back(*edgePtr);
}
}
}
return result;
}
/**
* Check there is an edge between vertex v and vertex w, regardless of the edge direction.
* @param v
* @param w
* @return true if there is an edge, false if not.
*/
[[nodiscard]] bool hasEdge(std::size_t v, std::size_t w) const {
if (outOfBounds(v) || outOfBounds(w)) {
throw std::invalid_argument("Invalid vertex");
}
Edge e(v, w, 1);
Compare compare;
for (const Edge_Ptr edgePtr : m_Network[v]) {
if (compare(e, *edgePtr)) {
return true;
}
}
return false;
}
/**
* Get the edge between vertex v and vertex w, regardless of the edge direction.
* @param v
* @param w
* @return const reference to the edge.
*/
[[nodiscard]] const Edge& getEdge(std::size_t v, std::size_t w) const {
if (outOfBounds(v) || outOfBounds(w)) {
throw std::invalid_argument("Invalid vertex");
}
Edge e(v, w, 1);
Compare compare;
for (const Edge_Ptr edgePtr : m_Network[v]) {
if (compare(e, *edgePtr)) {
return *edgePtr;
}
}
throw std::runtime_error("Edge does not exist");
}
/**
* Add an edge to the flow network. Since more than 1 edge cannot exist between 2 vertices, duplicate edges
* are not inserted.
* @param source
* @param dest
* @param capacity
* @return True if edge was inserted, false if not
*/
bool addEdge(std::size_t source, std::size_t dest, CapacityType capacity) {
if (outOfBounds(source) || outOfBounds(dest)) {
throw std::invalid_argument("Invalid vertices");
}
if (capacity < 0) {
throw std::invalid_argument("Capacity cannot be less than 0");
}
if (hasEdge(source, dest)) {
return false;
}
m_Edges.emplace_front(source, dest, capacity);
m_Network[source].push_back(&(*m_Edges.begin()));
m_Network[dest].push_back(&(*m_Edges.begin()));
return true;
}
};
}
| 30.609121
| 115
| 0.525061
|
[
"vector"
] |
058f0462021358d37f25e025f25b3a6d851d58fe
| 101,641
|
c
|
C
|
setup/xen-with-blktap/src/tools/libxl/libxl.c
|
manabu-hirano/logdrive
|
2921b5de9d4c52645778bcdcf0df5338e823fed8
|
[
"Unlicense"
] | null | null | null |
setup/xen-with-blktap/src/tools/libxl/libxl.c
|
manabu-hirano/logdrive
|
2921b5de9d4c52645778bcdcf0df5338e823fed8
|
[
"Unlicense"
] | null | null | null |
setup/xen-with-blktap/src/tools/libxl/libxl.c
|
manabu-hirano/logdrive
|
2921b5de9d4c52645778bcdcf0df5338e823fed8
|
[
"Unlicense"
] | null | null | null |
/*
* Copyright (C) 2009 Citrix Ltd.
* Author Vincent Hanquez <[email protected]>
* Author Stefano Stabellini <[email protected]>
*
* 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; version 2.1 only. with the special
* exception on linking described in file 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 Lesser General Public License for more details.
*/
#include "libxl_osdeps.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h> /* for write, unlink and close */
#include <stdint.h>
#include <inttypes.h>
#include <assert.h>
#include "libxl.h"
#include "libxl_utils.h"
#include "libxl_internal.h"
#include "flexarray.h"
#define PAGE_TO_MEMKB(pages) ((pages) * 4)
#define BACKEND_STRING_SIZE 5
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
int libxl_ctx_init(libxl_ctx *ctx, int version, xentoollog_logger *lg)
{
struct stat stat_buf;
if (version != LIBXL_VERSION)
return ERROR_VERSION;
memset(ctx, 0, sizeof(libxl_ctx));
ctx->lg = lg;
memset(&ctx->version_info, 0, sizeof(libxl_version_info));
if ( stat(XENSTORE_PID_FILE, &stat_buf) != 0 ) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "Is xenstore daemon running?\n"
"failed to stat %s", XENSTORE_PID_FILE);
return ERROR_FAIL;
}
ctx->xch = xc_interface_open(lg,lg,0);
if (!ctx->xch) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, errno,
"cannot open libxc handle");
return ERROR_FAIL;
}
ctx->xsh = xs_daemon_open();
if (!ctx->xsh)
ctx->xsh = xs_domain_open();
if (!ctx->xsh) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, errno,
"cannot connect to xenstore");
xc_interface_close(ctx->xch);
return ERROR_FAIL;
}
return 0;
}
int libxl_ctx_free(libxl_ctx *ctx)
{
if (ctx->xch) xc_interface_close(ctx->xch);
libxl_version_info_destroy(&ctx->version_info);
if (ctx->xsh) xs_daemon_close(ctx->xsh);
return 0;
}
void libxl_string_list_destroy(libxl_string_list *psl)
{
int i;
libxl_string_list sl = *psl;
if (!sl)
return;
for (i = 0; sl[i] != NULL; i++)
free(sl[i]);
free(sl);
}
void libxl_key_value_list_destroy(libxl_key_value_list *pkvl)
{
int i;
libxl_key_value_list kvl = *pkvl;
if (!kvl)
return;
for (i = 0; kvl[i] != NULL; i += 2) {
free(kvl[i]);
if (kvl[i + 1])
free(kvl[i + 1]);
}
free(kvl);
}
/******************************************************************************/
int libxl_domain_rename(libxl_ctx *ctx, uint32_t domid,
const char *old_name, const char *new_name,
xs_transaction_t trans)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *dom_path = 0;
const char *name_path;
char *got_old_name;
unsigned int got_old_len;
xs_transaction_t our_trans = 0;
int rc;
dom_path = libxl__xs_get_dompath(&gc, domid);
if (!dom_path) goto x_nomem;
name_path= libxl__sprintf(&gc, "%s/name", dom_path);
if (!name_path) goto x_nomem;
retry_transaction:
if (!trans) {
trans = our_trans = xs_transaction_start(ctx->xsh);
if (!our_trans) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, errno,
"create xs transaction for domain (re)name");
goto x_fail;
}
}
if (new_name[0]) {
/* nonempty names must be unique */
uint32_t domid_e;
rc = libxl_name_to_domid(ctx, new_name, &domid_e);
if (rc == ERROR_INVAL) {
/* no such domain, good */
} else if (rc != 0) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "unexpected error"
"checking for existing domain");
goto x_rc;
} else if (domid_e == domid) {
/* domain already has this name, ok (but we do still
* need the rest of the code as we may need to check
* old_name, for example). */
} else {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "domain with name \"%s\""
" already exists.", new_name);
rc = ERROR_INVAL;
goto x_rc;
}
}
if (old_name) {
got_old_name = xs_read(ctx->xsh, trans, name_path, &got_old_len);
if (!got_old_name) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, errno, "check old name"
" for domain %"PRIu32" allegedly named `%s'",
domid, old_name);
goto x_fail;
}
if (strcmp(old_name, got_old_name)) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "domain %"PRIu32" allegedly named "
"`%s' is actually named `%s' - racing ?",
domid, old_name, got_old_name);
free(got_old_name);
goto x_fail;
}
free(got_old_name);
}
if (!xs_write(ctx->xsh, trans, name_path,
new_name, strlen(new_name))) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "failed to write new name `%s'"
" for domain %"PRIu32" previously named `%s'",
new_name, domid, old_name);
goto x_fail;
}
if (our_trans) {
if (!xs_transaction_end(ctx->xsh, our_trans, 0)) {
trans = our_trans = 0;
if (errno != EAGAIN) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "failed to commit new name `%s'"
" for domain %"PRIu32" previously named `%s'",
new_name, domid, old_name);
goto x_fail;
}
LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "need to retry rename transaction"
" for domain %"PRIu32" (name_path=\"%s\", new_name=\"%s\")",
domid, name_path, new_name);
goto retry_transaction;
}
our_trans = 0;
}
rc = 0;
x_rc:
if (our_trans) xs_transaction_end(ctx->xsh, our_trans, 1);
libxl__free_all(&gc);
return rc;
x_fail: rc = ERROR_FAIL; goto x_rc;
x_nomem: rc = ERROR_NOMEM; goto x_rc;
}
int libxl_domain_resume(libxl_ctx *ctx, uint32_t domid)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
int rc = 0;
if (libxl__domain_is_hvm(ctx, domid)) {
LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "Called domain_resume on "
"non-cooperative hvm domain %u", domid);
rc = ERROR_NI;
goto out;
}
if (xc_domain_resume(ctx->xch, domid, 0)) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"xc_domain_resume failed for domain %u",
domid);
rc = ERROR_FAIL;
goto out;
}
if (!xs_resume_domain(ctx->xsh, domid)) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"xs_resume_domain failed for domain %u",
domid);
rc = ERROR_FAIL;
}
out:
libxl__free_all(&gc);
return 0;
}
/*
* Preserves a domain but rewrites xenstore etc to make it unique so
* that the domain can be restarted.
*
* Does not modify info so that it may be reused.
*/
int libxl_domain_preserve(libxl_ctx *ctx, uint32_t domid,
libxl_domain_create_info *info, const char *name_suffix, libxl_uuid new_uuid)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
struct xs_permissions roperm[2];
xs_transaction_t t;
char *preserved_name;
char *uuid_string;
char *vm_path;
char *dom_path;
int rc;
preserved_name = libxl__sprintf(&gc, "%s%s", info->name, name_suffix);
if (!preserved_name) {
libxl__free_all(&gc);
return ERROR_NOMEM;
}
uuid_string = libxl__uuid2string(&gc, new_uuid);
if (!uuid_string) {
libxl__free_all(&gc);
return ERROR_NOMEM;
}
dom_path = libxl__xs_get_dompath(&gc, domid);
if (!dom_path) {
libxl__free_all(&gc);
return ERROR_FAIL;
}
vm_path = libxl__sprintf(&gc, "/vm/%s", uuid_string);
if (!vm_path) {
libxl__free_all(&gc);
return ERROR_FAIL;
}
roperm[0].id = 0;
roperm[0].perms = XS_PERM_NONE;
roperm[1].id = domid;
roperm[1].perms = XS_PERM_READ;
retry_transaction:
t = xs_transaction_start(ctx->xsh);
xs_rm(ctx->xsh, t, vm_path);
xs_mkdir(ctx->xsh, t, vm_path);
xs_set_permissions(ctx->xsh, t, vm_path, roperm, ARRAY_SIZE(roperm));
xs_write(ctx->xsh, t, libxl__sprintf(&gc, "%s/vm", dom_path), vm_path, strlen(vm_path));
rc = libxl_domain_rename(ctx, domid, info->name, preserved_name, t);
if (rc) {
libxl__free_all(&gc);
return rc;
}
xs_write(ctx->xsh, t, libxl__sprintf(&gc, "%s/uuid", vm_path), uuid_string, strlen(uuid_string));
if (!xs_transaction_end(ctx->xsh, t, 0))
if (errno == EAGAIN)
goto retry_transaction;
libxl__free_all(&gc);
return 0;
}
static void xcinfo2xlinfo(const xc_domaininfo_t *xcinfo,
libxl_dominfo *xlinfo)
{
memcpy(&(xlinfo->uuid), xcinfo->handle, sizeof(xen_domain_handle_t));
xlinfo->domid = xcinfo->domain;
xlinfo->dying = !!(xcinfo->flags&XEN_DOMINF_dying);
xlinfo->shutdown = !!(xcinfo->flags&XEN_DOMINF_shutdown);
xlinfo->paused = !!(xcinfo->flags&XEN_DOMINF_paused);
xlinfo->blocked = !!(xcinfo->flags&XEN_DOMINF_blocked);
xlinfo->running = !!(xcinfo->flags&XEN_DOMINF_running);
if (xlinfo->shutdown || xlinfo->dying)
xlinfo->shutdown_reason = (xcinfo->flags>>XEN_DOMINF_shutdownshift) & XEN_DOMINF_shutdownmask;
else
xlinfo->shutdown_reason = ~0;
xlinfo->current_memkb = PAGE_TO_MEMKB(xcinfo->tot_pages);
xlinfo->max_memkb = PAGE_TO_MEMKB(xcinfo->max_pages);
xlinfo->cpu_time = xcinfo->cpu_time;
xlinfo->vcpu_max_id = xcinfo->max_vcpu_id;
xlinfo->vcpu_online = xcinfo->nr_online_vcpus;
}
libxl_dominfo * libxl_list_domain(libxl_ctx *ctx, int *nb_domain)
{
libxl_dominfo *ptr;
int i, ret;
xc_domaininfo_t info[1024];
int size = 1024;
ptr = calloc(size, sizeof(libxl_dominfo));
if (!ptr) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "allocating domain info");
return NULL;
}
ret = xc_domain_getinfolist(ctx->xch, 0, 1024, info);
if (ret<0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "geting domain info list");
return NULL;
}
for (i = 0; i < ret; i++) {
xcinfo2xlinfo(&info[i], &ptr[i]);
}
*nb_domain = ret;
return ptr;
}
int libxl_domain_info(libxl_ctx *ctx, libxl_dominfo *info_r,
uint32_t domid) {
xc_domaininfo_t xcinfo;
int ret;
ret = xc_domain_getinfolist(ctx->xch, domid, 1, &xcinfo);
if (ret<0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "geting domain info list");
return ERROR_FAIL;
}
if (ret==0 || xcinfo.domain != domid) return ERROR_INVAL;
xcinfo2xlinfo(&xcinfo, info_r);
return 0;
}
libxl_cpupoolinfo * libxl_list_cpupool(libxl_ctx *ctx, int *nb_pool)
{
libxl_cpupoolinfo *ptr, *tmp;
int i;
xc_cpupoolinfo_t *info;
uint32_t poolid;
ptr = NULL;
poolid = 0;
for (i = 0;; i++) {
info = xc_cpupool_getinfo(ctx->xch, poolid);
if (info == NULL)
break;
tmp = realloc(ptr, (i + 1) * sizeof(libxl_cpupoolinfo));
if (!tmp) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "allocating cpupool info");
free(ptr);
xc_cpupool_infofree(ctx->xch, info);
return NULL;
}
ptr = tmp;
ptr[i].poolid = info->cpupool_id;
ptr[i].sched_id = info->sched_id;
ptr[i].n_dom = info->n_dom;
if (libxl_cpumap_alloc(ctx, &ptr[i].cpumap)) {
xc_cpupool_infofree(ctx->xch, info);
break;
}
memcpy(ptr[i].cpumap.map, info->cpumap, ptr[i].cpumap.size);
poolid = info->cpupool_id + 1;
xc_cpupool_infofree(ctx->xch, info);
}
*nb_pool = i;
return ptr;
}
/* this API call only list VM running on this host. a VM can be an aggregate of multiple domains. */
libxl_vminfo * libxl_list_vm(libxl_ctx *ctx, int *nb_vm)
{
libxl_vminfo *ptr;
int index, i, ret;
xc_domaininfo_t info[1024];
int size = 1024;
ptr = calloc(size, sizeof(libxl_dominfo));
if (!ptr)
return NULL;
ret = xc_domain_getinfolist(ctx->xch, 1, 1024, info);
if (ret<0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "geting domain info list");
return NULL;
}
for (index = i = 0; i < ret; i++) {
if (libxl_is_stubdom(ctx, info[i].domain, NULL))
continue;
memcpy(&(ptr[index].uuid), info[i].handle, sizeof(xen_domain_handle_t));
ptr[index].domid = info[i].domain;
index++;
}
*nb_vm = index;
return ptr;
}
int libxl_domain_suspend(libxl_ctx *ctx, libxl_domain_suspend_info *info,
uint32_t domid, int fd)
{
int hvm = libxl__domain_is_hvm(ctx, domid);
int live = info != NULL && info->flags & XL_SUSPEND_LIVE;
int debug = info != NULL && info->flags & XL_SUSPEND_DEBUG;
int rc = 0;
rc = libxl__domain_suspend_common(ctx, domid, fd, hvm, live, debug);
if (!rc && hvm)
rc = libxl__domain_save_device_model(ctx, domid, fd);
return rc;
}
int libxl_domain_pause(libxl_ctx *ctx, uint32_t domid)
{
int ret;
ret = xc_domain_pause(ctx->xch, domid);
if (ret<0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "pausing domain %d", domid);
return ERROR_FAIL;
}
return 0;
}
int libxl_domain_core_dump(libxl_ctx *ctx, uint32_t domid,
const char *filename)
{
int ret;
ret = xc_domain_dumpcore(ctx->xch, domid, filename);
if (ret<0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "core dumping domain %d to %s",
domid, filename);
return ERROR_FAIL;
}
return 0;
}
int libxl_domain_unpause(libxl_ctx *ctx, uint32_t domid)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *path;
char *state;
int ret, rc = 0;
if (libxl__domain_is_hvm(ctx, domid)) {
path = libxl__sprintf(&gc, "/local/domain/0/device-model/%d/state", domid);
state = libxl__xs_read(&gc, XBT_NULL, path);
if (state != NULL && !strcmp(state, "paused")) {
libxl__xs_write(&gc, XBT_NULL, libxl__sprintf(&gc, "/local/domain/0/device-model/%d/command", domid), "continue");
libxl__wait_for_device_model(ctx, domid, "running", NULL, NULL);
}
}
ret = xc_domain_unpause(ctx->xch, domid);
if (ret<0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "unpausing domain %d", domid);
rc = ERROR_FAIL;
}
libxl__free_all(&gc);
return rc;
}
static char *req_table[] = {
[0] = "poweroff",
[1] = "reboot",
[2] = "suspend",
[3] = "crash",
[4] = "halt",
};
int libxl_domain_shutdown(libxl_ctx *ctx, uint32_t domid, int req)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *shutdown_path;
char *dom_path;
if (req > ARRAY_SIZE(req_table)) {
libxl__free_all(&gc);
return ERROR_INVAL;
}
dom_path = libxl__xs_get_dompath(&gc, domid);
if (!dom_path) {
libxl__free_all(&gc);
return ERROR_FAIL;
}
if (libxl__domain_is_hvm(ctx,domid)) {
unsigned long pvdriver = 0;
int ret;
ret = xc_get_hvm_param(ctx->xch, domid, HVM_PARAM_CALLBACK_IRQ, &pvdriver);
if (ret<0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "getting HVM callback IRQ");
libxl__free_all(&gc);
return ERROR_FAIL;
}
if (!pvdriver) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "HVM domain without PV drivers:"
" graceful shutdown not possible, use destroy");
libxl__free_all(&gc);
return ERROR_FAIL;
}
}
shutdown_path = libxl__sprintf(&gc, "%s/control/shutdown", dom_path);
xs_write(ctx->xsh, XBT_NULL, shutdown_path, req_table[req], strlen(req_table[req]));
libxl__free_all(&gc);
return 0;
}
int libxl_get_wait_fd(libxl_ctx *ctx, int *fd)
{
*fd = xs_fileno(ctx->xsh);
return 0;
}
int libxl_wait_for_domain_death(libxl_ctx *ctx, uint32_t domid, libxl_waiter *waiter)
{
waiter->path = strdup("@releaseDomain");
if (asprintf(&(waiter->token), "%d", LIBXL_EVENT_DOMAIN_DEATH) < 0)
return -1;
if (!xs_watch(ctx->xsh, waiter->path, waiter->token))
return -1;
return 0;
}
int libxl_wait_for_disk_ejects(libxl_ctx *ctx, uint32_t guest_domid, libxl_device_disk *disks, int num_disks, libxl_waiter *waiter)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
int i, rc = -1;
uint32_t domid = libxl_get_stubdom_id(ctx, guest_domid);
if (!domid)
domid = guest_domid;
for (i = 0; i < num_disks; i++) {
if (asprintf(&(waiter[i].path), "%s/device/vbd/%d/eject",
libxl__xs_get_dompath(&gc, domid),
libxl__device_disk_dev_number(disks[i].vdev)) < 0)
goto out;
if (asprintf(&(waiter[i].token), "%d", LIBXL_EVENT_DISK_EJECT) < 0)
goto out;
xs_watch(ctx->xsh, waiter[i].path, waiter[i].token);
}
rc = 0;
out:
libxl__free_all(&gc);
return rc;
}
int libxl_get_event(libxl_ctx *ctx, libxl_event *event)
{
unsigned int num;
char **events = xs_read_watch(ctx->xsh, &num);
if (num != 2) {
free(events);
return ERROR_FAIL;
}
event->path = strdup(events[XS_WATCH_PATH]);
event->token = strdup(events[XS_WATCH_TOKEN]);
event->type = atoi(event->token);
free(events);
return 0;
}
int libxl_stop_waiting(libxl_ctx *ctx, libxl_waiter *waiter)
{
if (!xs_unwatch(ctx->xsh, waiter->path, waiter->token))
return ERROR_FAIL;
else
return 0;
}
int libxl_free_event(libxl_event *event)
{
free(event->path);
free(event->token);
return 0;
}
int libxl_free_waiter(libxl_waiter *waiter)
{
free(waiter->path);
free(waiter->token);
return 0;
}
int libxl_event_get_domain_death_info(libxl_ctx *ctx, uint32_t domid, libxl_event *event, libxl_dominfo *info)
{
if (libxl_domain_info(ctx, info, domid) < 0)
return 0;
if (info->running || (!info->shutdown && !info->dying))
return ERROR_INVAL;
return 1;
}
int libxl_event_get_disk_eject_info(libxl_ctx *ctx, uint32_t domid, libxl_event *event, libxl_device_disk *disk)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *path;
char *backend;
char *value;
char backend_type[BACKEND_STRING_SIZE+1];
value = libxl__xs_read(&gc, XBT_NULL, event->path);
if (!value || strcmp(value, "eject")) {
libxl__free_all(&gc);
return 0;
}
path = strdup(event->path);
path[strlen(path) - 6] = '\0';
backend = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/backend", path));
sscanf(backend,
"/local/domain/%d/backend/%" TOSTRING(BACKEND_STRING_SIZE) "[a-z]/%*d/%*d",
&disk->backend_domid, backend_type);
if (!strcmp(backend_type, "tap") || !strcmp(backend_type, "vbd")) {
disk->backend = DISK_BACKEND_TAP;
} else if (!strcmp(backend_type, "qdisk")) {
disk->backend = DISK_BACKEND_QDISK;
} else {
disk->backend = DISK_BACKEND_UNKNOWN;
}
disk->domid = domid;
disk->pdev_path = strdup("");
disk->format = DISK_FORMAT_EMPTY;
/* this value is returned to the user: do not free right away */
disk->vdev = xs_read(ctx->xsh, XBT_NULL, libxl__sprintf(&gc, "%s/dev", backend), NULL);
disk->unpluggable = 1;
disk->readwrite = 0;
disk->is_cdrom = 1;
free(path);
libxl__free_all(&gc);
return 1;
}
int libxl_domain_destroy(libxl_ctx *ctx, uint32_t domid, int force)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
libxl_dominfo dominfo;
char *dom_path;
char *vm_path;
int rc, dm_present;
rc = libxl_domain_info(ctx, &dominfo, domid);
switch(rc) {
case 0:
break;
case ERROR_INVAL:
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "non-existant domain %d", domid);
default:
return rc;
}
if (libxl__domain_is_hvm(ctx, domid)) {
dm_present = 1;
} else {
char *pid;
pid = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "/local/domain/%d/image/device-model-pid", domid));
dm_present = (pid != NULL);
}
dom_path = libxl__xs_get_dompath(&gc, domid);
if (!dom_path) {
rc = ERROR_FAIL;
goto out;
}
if (libxl_device_pci_shutdown(ctx, domid) < 0)
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "pci shutdown failed for domid %d", domid);
rc = xc_domain_pause(ctx->xch, domid);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc, "xc_domain_pause failed for %d", domid);
}
if (dm_present) {
if (libxl__destroy_device_model(ctx, domid) < 0)
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "libxl__destroy_device_model failed for %d", domid);
}
if (libxl__devices_destroy(ctx, domid, force) < 0)
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "libxl_destroy_devices failed for %d", domid);
vm_path = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/vm", dom_path));
if (vm_path)
if (!xs_rm(ctx->xsh, XBT_NULL, vm_path))
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "xs_rm failed for %s", vm_path);
if (!xs_rm(ctx->xsh, XBT_NULL, dom_path))
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "xs_rm failed for %s", dom_path);
libxl__userdata_destroyall(ctx, domid);
rc = xc_domain_destroy(ctx->xch, domid);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc, "xc_domain_destroy failed for %d", domid);
rc = ERROR_FAIL;
goto out;
}
rc = 0;
out:
libxl__free_all(&gc);
return 0;
}
int libxl_console_exec(libxl_ctx *ctx, uint32_t domid, int cons_num, libxl_console_constype type)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *p = libxl__sprintf(&gc, "%s/xenconsole", libxl_private_bindir_path());
char *domid_s = libxl__sprintf(&gc, "%d", domid);
char *cons_num_s = libxl__sprintf(&gc, "%d", cons_num);
char *cons_type_s;
switch (type) {
case LIBXL_CONSTYPE_PV:
cons_type_s = "pv";
break;
case LIBXL_CONSTYPE_SERIAL:
cons_type_s = "serial";
break;
default:
goto out;
}
execl(p, p, domid_s, "--num", cons_num_s, "--type", cons_type_s, (void *)NULL);
out:
libxl__free_all(&gc);
return ERROR_FAIL;
}
int libxl_primary_console_exec(libxl_ctx *ctx, uint32_t domid_vm)
{
uint32_t stubdomid = libxl_get_stubdom_id(ctx, domid_vm);
if (stubdomid)
return libxl_console_exec(ctx, stubdomid,
STUBDOM_CONSOLE_SERIAL, LIBXL_CONSTYPE_PV);
else {
if (libxl__domain_is_hvm(ctx, domid_vm))
return libxl_console_exec(ctx, domid_vm, 0, LIBXL_CONSTYPE_SERIAL);
else
return libxl_console_exec(ctx, domid_vm, 0, LIBXL_CONSTYPE_PV);
}
}
int libxl_vncviewer_exec(libxl_ctx *ctx, uint32_t domid, int autopass)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
const char *vnc_port;
const char *vnc_listen = NULL, *vnc_pass = NULL;
int port = 0, autopass_fd = -1;
char *vnc_bin, *args[] = {
"vncviewer",
NULL, /* hostname:display */
NULL, /* -autopass */
NULL,
};
vnc_port = libxl__xs_read(&gc, XBT_NULL,
libxl__sprintf(&gc,
"/local/domain/%d/console/vnc-port", domid));
if ( vnc_port )
port = atoi(vnc_port) - 5900;
vnc_listen = libxl__xs_read(&gc, XBT_NULL,
libxl__sprintf(&gc,
"/local/domain/%d/console/vnc-listen", domid));
if ( autopass )
vnc_pass = libxl__xs_read(&gc, XBT_NULL,
libxl__sprintf(&gc,
"/local/domain/%d/console/vnc-pass", domid));
if ( NULL == vnc_listen )
vnc_listen = "localhost";
if ( (vnc_bin = getenv("VNCVIEWER")) )
args[0] = vnc_bin;
args[1] = libxl__sprintf(&gc, "%s:%d", vnc_listen, port);
if ( vnc_pass ) {
char tmpname[] = "/tmp/vncautopass.XXXXXX";
autopass_fd = mkstemp(tmpname);
if ( autopass_fd < 0 ) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"mkstemp %s failed", tmpname);
goto x_fail;
}
if ( unlink(tmpname) ) {
/* should never happen */
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"unlink %s failed", tmpname);
goto x_fail;
}
if ( libxl_write_exactly(ctx, autopass_fd, vnc_pass, strlen(vnc_pass),
tmpname, "vnc password") )
goto x_fail;
if ( lseek(autopass_fd, SEEK_SET, 0) ) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"rewind %s (autopass) failed", tmpname);
goto x_fail;
}
args[2] = "-autopass";
}
libxl__exec(autopass_fd, -1, -1, args[0], args);
abort();
x_fail:
libxl__free_all(&gc);
return ERROR_FAIL;
}
/******************************************************************************/
static int validate_virtual_disk(libxl_ctx *ctx, char *file_name,
libxl_device_disk *disk)
{
struct stat stat_buf;
char *delimiter;
if (disk->format == DISK_FORMAT_EMPTY)
return 0;
if (disk->format == DISK_FORMAT_PRESERVATION)
return 0;
if (disk->format == DISK_FORMAT_RAW) {
delimiter = strchr(file_name, ':');
if (delimiter) {
if (!strncmp(file_name, "vhd:", sizeof("vhd:")-1)) {
disk->format = DISK_FORMAT_VHD;
file_name = ++delimiter;
}
}
}
if ( stat(file_name, &stat_buf) != 0 ) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "failed to stat %s", file_name);
return ERROR_INVAL;
}
if (disk->backend == DISK_BACKEND_PHY) {
if ( !(S_ISBLK(stat_buf.st_mode)) ) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "Virtual disk %s is not a block device!\n",
file_name);
return ERROR_INVAL;
}
} else if ( S_ISREG(stat_buf.st_mode) && stat_buf.st_size == 0 ) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "Virtual disk %s size is 0!\n", file_name);
return ERROR_INVAL;
}
return 0;
}
int libxl_device_disk_add(libxl_ctx *ctx, uint32_t domid, libxl_device_disk *disk)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
flexarray_t *front;
flexarray_t *back;
char *backend_type;
int devid;
libxl__device device;
int major, minor, rc;
rc = validate_virtual_disk(ctx, disk->pdev_path, disk);
if (rc)
return rc;
front = flexarray_make(16, 1);
if (!front) {
rc = ERROR_NOMEM;
goto out;
}
back = flexarray_make(16, 1);
if (!back) {
rc = ERROR_NOMEM;
goto out_free;
}
backend_type = libxl__device_disk_string_of_backend(disk->backend);
devid = libxl__device_disk_dev_number(disk->vdev);
if (devid==-1) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "Invalid or unsupported"
" virtual disk identifier %s", disk->vdev);
rc = ERROR_INVAL;
goto out_free;
}
device.backend_devid = devid;
device.backend_domid = disk->backend_domid;
device.devid = devid;
device.domid = disk->domid;
device.kind = DEVICE_VBD;
switch (disk->backend) {
case DISK_BACKEND_PHY:
libxl__device_physdisk_major_minor(disk->pdev_path, &major, &minor);
flexarray_append(back, "physical-device");
flexarray_append(back, libxl__sprintf(&gc, "%x:%x", major, minor));
flexarray_append(back, "params");
flexarray_append(back, disk->pdev_path);
device.backend_kind = DEVICE_VBD;
break;
case DISK_BACKEND_TAP:
if (libxl__blktap_enabled(&gc) && disk->format != DISK_FORMAT_EMPTY) {
const char *dev = libxl__blktap_devpath(&gc,
disk->pdev_path, disk->format);
if (!dev) {
rc = ERROR_FAIL;
goto out_free;
}
flexarray_append(back, "tapdisk-params");
flexarray_append(back, libxl__sprintf(&gc, "%s:%s",
libxl__device_disk_string_of_format(disk->format),
disk->pdev_path));
flexarray_append(back, "params");
flexarray_append(back, libxl__strdup(&gc, dev));
backend_type = "phy";
libxl__device_physdisk_major_minor(dev, &major, &minor);
flexarray_append(back, "physical-device");
flexarray_append(back, libxl__sprintf(&gc, "%x:%x", major, minor));
device.backend_kind = DEVICE_VBD;
break;
}
case DISK_BACKEND_QDISK:
flexarray_append(back, "params");
flexarray_append(back, libxl__sprintf(&gc, "%s:%s",
libxl__device_disk_string_of_format(disk->format), disk->pdev_path));
if (libxl__blktap_enabled(&gc) &&
disk->backend != DISK_BACKEND_QDISK)
device.backend_kind = DEVICE_TAP;
else
device.backend_kind = DEVICE_QDISK;
break;
default:
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "unrecognized disk backend type: %d\n", disk->backend);
rc = ERROR_INVAL;
goto out_free;
}
flexarray_append(back, "frontend-id");
flexarray_append(back, libxl__sprintf(&gc, "%d", disk->domid));
flexarray_append(back, "online");
flexarray_append(back, "1");
flexarray_append(back, "removable");
flexarray_append(back, libxl__sprintf(&gc, "%d", (disk->unpluggable) ? 1 : 0));
flexarray_append(back, "bootable");
flexarray_append(back, libxl__sprintf(&gc, "%d", 1));
flexarray_append(back, "state");
flexarray_append(back, libxl__sprintf(&gc, "%d", 1));
flexarray_append(back, "dev");
flexarray_append(back, disk->vdev);
flexarray_append(back, "type");
flexarray_append(back, backend_type);
flexarray_append(back, "mode");
flexarray_append(back, disk->readwrite ? "w" : "r");
flexarray_append(front, "backend-id");
flexarray_append(front, libxl__sprintf(&gc, "%d", disk->backend_domid));
flexarray_append(front, "state");
flexarray_append(front, libxl__sprintf(&gc, "%d", 1));
flexarray_append(front, "virtual-device");
flexarray_append(front, libxl__sprintf(&gc, "%d", devid));
flexarray_append(front, "device-type");
flexarray_append(front, disk->is_cdrom ? "cdrom" : "disk");
if (0 /* protocol != native*/) {
flexarray_append(front, "protocol");
flexarray_append(front, "x86_32-abi"); /* hardcoded ! */
}
libxl__device_generic_add(ctx, &device,
libxl__xs_kvs_of_flexarray(&gc, back, back->count),
libxl__xs_kvs_of_flexarray(&gc, front, front->count));
rc = 0;
out_free:
flexarray_free(back);
flexarray_free(front);
out:
libxl__free_all(&gc);
return rc;
}
int libxl_device_disk_del(libxl_ctx *ctx,
libxl_device_disk *disk, int wait)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
libxl__device device;
int devid, rc;
devid = libxl__device_disk_dev_number(disk->vdev);
device.backend_domid = disk->backend_domid;
device.backend_devid = devid;
device.backend_kind =
(disk->backend == DISK_BACKEND_PHY) ? DEVICE_VBD : DEVICE_TAP;
device.domid = disk->domid;
device.devid = devid;
device.kind = DEVICE_VBD;
rc = libxl__device_del(ctx, &device, wait);
xs_rm(ctx->xsh, XBT_NULL, libxl__device_backend_path(&gc, &device));
xs_rm(ctx->xsh, XBT_NULL, libxl__device_frontend_path(&gc, &device));
libxl__free_all(&gc);
return rc;
}
char * libxl_device_disk_local_attach(libxl_ctx *ctx, libxl_device_disk *disk)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
const char *dev = NULL;
char *ret = NULL;
switch (disk->backend) {
case DISK_BACKEND_PHY:
if (disk->format != DISK_FORMAT_RAW) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "physical block device must"
" be raw");
break;
}
LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "attaching PHY disk %s to domain 0",
disk->pdev_path);
dev = disk->pdev_path;
break;
case DISK_BACKEND_TAP:
if (disk->format == DISK_FORMAT_VHD || disk->format == DISK_FORMAT_RAW)
{
if (libxl__blktap_enabled(&gc))
dev = libxl__blktap_devpath(&gc, disk->pdev_path, disk->format);
else {
if (disk->format != DISK_FORMAT_RAW) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "tapdisk2 is required"
" to open a vhd disk");
break;
} else {
LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "attaching tap disk %s to domain 0",
disk->pdev_path);
dev = disk->pdev_path;
break;
}
}
break;
} else if (disk->format == DISK_FORMAT_QCOW ||
disk->format == DISK_FORMAT_QCOW2) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "cannot locally attach a qcow or qcow2 disk image");
break;
} else {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "unrecognized disk backend "
"type: %d", disk->backend);
break;
}
case DISK_BACKEND_QDISK:
if (disk->format != DISK_FORMAT_RAW) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "cannot locally attach a qdisk "
"image if the format is not raw");
break;
}
LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "attaching qdisk %s to domain 0\n",
disk->pdev_path);
dev = disk->pdev_path;
break;
case DISK_BACKEND_UNKNOWN:
default:
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "unrecognized disk backend "
"type: %d", disk->backend);
break;
}
if (dev != NULL)
ret = strdup(dev);
libxl__free_all(&gc);
return ret;
}
int libxl_device_disk_local_detach(libxl_ctx *ctx, libxl_device_disk *disk)
{
/* Nothing to do for PHYSTYPE_PHY. */
/*
* For other device types assume that the blktap2 process is
* needed by the soon to be started domain and do nothing.
*/
return 0;
}
/******************************************************************************/
int libxl_device_nic_init(libxl_device_nic *nic_info, int devnum)
{
const uint8_t *r;
libxl_uuid uuid;
libxl_uuid_generate(&uuid);
r = libxl_uuid_bytearray(&uuid);
memset(nic_info, '\0', sizeof(*nic_info));
nic_info->backend_domid = 0;
nic_info->domid = 0;
nic_info->devid = devnum;
nic_info->mtu = 1492;
nic_info->model = strdup("rtl8139");
nic_info->mac[0] = 0x00;
nic_info->mac[1] = 0x16;
nic_info->mac[2] = 0x3e;
nic_info->mac[3] = r[0] & 0x7f;
nic_info->mac[4] = r[1];
nic_info->mac[5] = r[2];
nic_info->ifname = NULL;
nic_info->bridge = strdup("xenbr0");
nic_info->ip = NULL;
if ( asprintf(&nic_info->script, "%s/vif-bridge",
libxl_xen_script_dir_path()) < 0 )
return ERROR_FAIL;
nic_info->nictype = NICTYPE_IOEMU;
return 0;
}
int libxl_device_nic_add(libxl_ctx *ctx, uint32_t domid, libxl_device_nic *nic)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
flexarray_t *front;
flexarray_t *back;
libxl__device device;
char *dompath, **l;
unsigned int nb, rc;
front = flexarray_make(16, 1);
if (!front) {
rc = ERROR_NOMEM;
goto out;
}
back = flexarray_make(16, 1);
if (!back) {
rc = ERROR_NOMEM;
goto out_free;
}
if (nic->devid == -1) {
if (!(dompath = libxl__xs_get_dompath(&gc, domid))) {
rc = ERROR_FAIL;
goto out_free;
}
if (!(l = libxl__xs_directory(&gc, XBT_NULL,
libxl__sprintf(&gc, "%s/device/vif", dompath), &nb))) {
nic->devid = 0;
} else {
nic->devid = strtoul(l[nb - 1], NULL, 10) + 1;
}
}
device.backend_devid = nic->devid;
device.backend_domid = nic->backend_domid;
device.backend_kind = DEVICE_VIF;
device.devid = nic->devid;
device.domid = nic->domid;
device.kind = DEVICE_VIF;
flexarray_append(back, "frontend-id");
flexarray_append(back, libxl__sprintf(&gc, "%d", nic->domid));
flexarray_append(back, "online");
flexarray_append(back, "1");
flexarray_append(back, "state");
flexarray_append(back, libxl__sprintf(&gc, "%d", 1));
flexarray_append(back, "script");
flexarray_append(back, nic->script);
flexarray_append(back, "mac");
flexarray_append(back, libxl__sprintf(&gc, "%02x:%02x:%02x:%02x:%02x:%02x",
nic->mac[0], nic->mac[1], nic->mac[2],
nic->mac[3], nic->mac[4], nic->mac[5]));
if (nic->ip) {
flexarray_append(back, "ip");
flexarray_append(back, libxl__strdup(&gc, nic->ip));
}
flexarray_append(back, "bridge");
flexarray_append(back, libxl__strdup(&gc, nic->bridge));
flexarray_append(back, "handle");
flexarray_append(back, libxl__sprintf(&gc, "%d", nic->devid));
flexarray_append(front, "backend-id");
flexarray_append(front, libxl__sprintf(&gc, "%d", nic->backend_domid));
flexarray_append(front, "state");
flexarray_append(front, libxl__sprintf(&gc, "%d", 1));
flexarray_append(front, "handle");
flexarray_append(front, libxl__sprintf(&gc, "%d", nic->devid));
flexarray_append(front, "mac");
flexarray_append(front, libxl__sprintf(&gc, "%02x:%02x:%02x:%02x:%02x:%02x",
nic->mac[0], nic->mac[1], nic->mac[2],
nic->mac[3], nic->mac[4], nic->mac[5]));
if (0 /* protocol != native*/) {
flexarray_append(front, "protocol");
flexarray_append(front, "x86_32-abi"); /* hardcoded ! */
}
libxl__device_generic_add(ctx, &device,
libxl__xs_kvs_of_flexarray(&gc, back, back->count),
libxl__xs_kvs_of_flexarray(&gc, front, front->count));
/* FIXME: wait for plug */
rc = 0;
out_free:
flexarray_free(back);
flexarray_free(front);
out:
libxl__free_all(&gc);
return rc;
}
int libxl_device_nic_del(libxl_ctx *ctx,
libxl_device_nic *nic, int wait)
{
libxl__device device;
device.backend_devid = nic->devid;
device.backend_domid = nic->backend_domid;
device.backend_kind = DEVICE_VIF;
device.devid = nic->devid;
device.domid = nic->domid;
device.kind = DEVICE_VIF;
return libxl__device_del(ctx, &device, wait);
}
libxl_nicinfo *libxl_list_nics(libxl_ctx *ctx, uint32_t domid, unsigned int *nb)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *dompath, *nic_path_fe;
char **l, **list;
char *val, *tok;
unsigned int nb_nics, i;
libxl_nicinfo *res, *nics;
dompath = libxl__xs_get_dompath(&gc, domid);
if (!dompath)
goto err;
list = l = libxl__xs_directory(&gc, XBT_NULL,
libxl__sprintf(&gc, "%s/device/vif", dompath), &nb_nics);
if (!l)
goto err;
nics = res = calloc(nb_nics, sizeof (libxl_device_nic));
if (!res)
goto err;
for (*nb = nb_nics; nb_nics > 0; --nb_nics, ++l, ++nics) {
nic_path_fe = libxl__sprintf(&gc, "%s/device/vif/%s", dompath, *l);
nics->backend = xs_read(ctx->xsh, XBT_NULL,
libxl__sprintf(&gc, "%s/backend", nic_path_fe), NULL);
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/backend-id", nic_path_fe));
nics->backend_id = val ? strtoul(val, NULL, 10) : -1;
nics->devid = strtoul(*l, NULL, 10);
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/state", nic_path_fe));
nics->state = val ? strtoul(val, NULL, 10) : -1;
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/mac", nic_path_fe));
for (i = 0, tok = strtok(val, ":"); tok && (i < 6);
++i, tok = strtok(NULL, ":")) {
nics->mac[i] = strtoul(tok, NULL, 16);
}
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/event-channel", nic_path_fe));
nics->evtch = val ? strtol(val, NULL, 10) : -1;
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/tx-ring-ref", nic_path_fe));
nics->rref_tx = val ? strtol(val, NULL, 10) : -1;
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/rx-ring-ref", nic_path_fe));
nics->rref_rx = val ? strtol(val, NULL, 10) : -1;
nics->frontend = xs_read(ctx->xsh, XBT_NULL,
libxl__sprintf(&gc, "%s/frontend", nics->backend), NULL);
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/frontend-id", nics->backend));
nics->frontend_id = val ? strtoul(val, NULL, 10) : -1;
nics->script = xs_read(ctx->xsh, XBT_NULL,
libxl__sprintf(&gc, "%s/script", nics->backend), NULL);
}
libxl__free_all(&gc);
return res;
err:
libxl__free_all(&gc);
return NULL;
}
/******************************************************************************/
void libxl_device_net2_init(libxl_device_net2 *net2_info, int devnum)
{
const uint8_t *r;
libxl_uuid uuid;
libxl_uuid_generate(&uuid);
r = libxl_uuid_bytearray(&uuid);
memset(net2_info, '\0', sizeof(*net2_info));
net2_info->devid = devnum;
net2_info->front_mac[0] = 0x00;
net2_info->front_mac[1] = 0x16;
net2_info->front_mac[2] = 0x3e;;
net2_info->front_mac[3] = 0x7f & r[0];
net2_info->front_mac[4] = r[1];
net2_info->front_mac[5] = r[2];
net2_info->back_mac[0] = 0x00;
net2_info->back_mac[1] = 0x16;
net2_info->back_mac[2] = 0x3e;
net2_info->back_mac[3] = 0x7f & r[3];
net2_info->back_mac[4] = r[4];
net2_info->back_mac[5] = r[5];
net2_info->back_trusted = 1;
net2_info->filter_mac = 1;
net2_info->max_bypasses = 5;
net2_info->bridge = strdup("xenbr0");
}
int libxl_device_net2_add(libxl_ctx *ctx, uint32_t domid, libxl_device_net2 *net2)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
flexarray_t *front, *back;
libxl__device device;
char *dompath, *dom, **l;
unsigned int nb;
int rc;
front = flexarray_make(16, 1);
if (!front) {
rc = ERROR_NOMEM;
goto err;
}
back = flexarray_make(16, 1);
if (!back) {
rc = ERROR_NOMEM;
goto err_free;
}
if (!(dompath = libxl__xs_get_dompath(&gc, domid))) {
rc = ERROR_FAIL;
goto err_free;
}
dom = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/name", dompath));
if (net2->devid == -1) {
if (!(l = libxl__xs_directory(&gc, XBT_NULL,
libxl__sprintf(&gc, "%s/device/vif2", dompath), &nb))) {
net2->devid = 0;
} else {
net2->devid = strtoul(l[nb - 1], NULL, 10) + 1;
}
}
device.backend_devid = net2->devid;
device.backend_domid = net2->backend_domid;
device.backend_kind = DEVICE_VIF2;
device.devid = net2->devid;
device.domid = net2->domid;
device.kind = DEVICE_VIF2;
flexarray_append(back, "domain");
flexarray_append(back, dom);
flexarray_append(back, "frontend-id");
flexarray_append(back, libxl__sprintf(&gc, "%d", net2->domid));
flexarray_append(back, "local-trusted");
flexarray_append(back, libxl__sprintf(&gc, "%d", net2->back_trusted));
flexarray_append(back, "mac");
flexarray_append(back, libxl__sprintf(&gc, "%02x:%02x:%02x:%02x:%02x:%02x",
net2->back_mac[0], net2->back_mac[1],
net2->back_mac[2], net2->back_mac[3],
net2->back_mac[4], net2->back_mac[5]));
flexarray_append(back, "remote-trusted");
flexarray_append(back, libxl__sprintf(&gc, "%d", net2->trusted));
flexarray_append(back, "remote-mac");
flexarray_append(back, libxl__sprintf(&gc, "%02x:%02x:%02x:%02x:%02x:%02x",
net2->front_mac[0], net2->front_mac[1],
net2->front_mac[2], net2->front_mac[3],
net2->front_mac[4], net2->front_mac[5]));
flexarray_append(back, "max-bypasses");
flexarray_append(back, libxl__sprintf(&gc, "%d", net2->max_bypasses));
flexarray_append(back, "filter-mac");
flexarray_append(back, libxl__sprintf(&gc, "%d", !!(net2->filter_mac)));
flexarray_append(back, "handle");
flexarray_append(back, libxl__sprintf(&gc, "%d", net2->devid));
flexarray_append(back, "online");
flexarray_append(back, "1");
flexarray_append(back, "state");
flexarray_append(back, "1");
flexarray_append(front, "backend-id");
flexarray_append(front, libxl__sprintf(&gc, "%d", net2->backend_domid));
flexarray_append(front, "local-trusted");
flexarray_append(front, libxl__sprintf(&gc, "%d", net2->trusted));
flexarray_append(front, "mac");
flexarray_append(front, libxl__sprintf(&gc, "%02x:%02x:%02x:%02x:%02x:%02x",
net2->front_mac[0], net2->front_mac[1],
net2->front_mac[2], net2->front_mac[3],
net2->front_mac[4], net2->front_mac[5]));
flexarray_append(front, "remote-trusted");
flexarray_append(front, libxl__sprintf(&gc, "%d", net2->back_trusted));
flexarray_append(front, "remote-mac");
flexarray_append(front, libxl__sprintf(&gc, "%02x:%02x:%02x:%02x:%02x:%02x",
net2->back_mac[0], net2->back_mac[1],
net2->back_mac[2], net2->back_mac[3],
net2->back_mac[4], net2->back_mac[5]));
flexarray_append(front, "filter-mac");
flexarray_append(front, libxl__sprintf(&gc, "%d", !!(net2->filter_mac)));
flexarray_append(front, "state");
flexarray_append(front, "1");
libxl__device_generic_add(ctx, &device,
libxl__xs_kvs_of_flexarray(&gc, back, back->count),
libxl__xs_kvs_of_flexarray(&gc, front, front->count));
/* FIXME: wait for plug */
rc = 0;
err_free:
flexarray_free(back);
flexarray_free(front);
err:
libxl__free_all(&gc);
return rc;
}
libxl_net2info *libxl_device_net2_list(libxl_ctx *ctx, uint32_t domid, unsigned int *nb)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *dompath, *net2_path_fe;
char **l;
char *val, *tok;
unsigned int nb_net2s, i;
libxl_net2info *res, *net2s;
dompath = libxl__xs_get_dompath(&gc, domid);
if (!dompath)
goto err;
l = libxl__xs_directory(&gc, XBT_NULL,
libxl__sprintf(&gc, "%s/device/vif2", dompath), &nb_net2s);
if (!l)
goto err;
res = calloc(nb_net2s, sizeof (libxl_net2info));
if (!res)
goto err;
net2s = res;
for (*nb = nb_net2s; nb_net2s > 0; --nb_net2s, ++l, ++net2s) {
net2_path_fe = libxl__sprintf(&gc, "%s/device/vif2/%s", dompath, *l);
net2s->backend = libxl__xs_read(&gc, XBT_NULL,
libxl__sprintf(&gc, "%s/backend", net2_path_fe));
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/backend-id", net2_path_fe));
net2s->backend_id = val ? strtoul(val, NULL, 10) : -1;
net2s->devid = strtoul(*l, NULL, 10);
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/state", net2_path_fe));
net2s->state = val ? strtoul(val, NULL, 10) : -1;
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/mac", net2_path_fe));
for (i = 0, tok = strtok(val, ":"); tok && (i < 6);
++i, tok = strtok(NULL, ":")) {
net2s->mac[i] = strtoul(tok, NULL, 16);
}
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/remote-trusted", net2_path_fe));
net2s->trusted = val ? strtoul(val, NULL, 10) : -1;
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/remote-mac", net2_path_fe));
for (i = 0, tok = strtok(val, ":"); tok && (i < 6);
++i, tok = strtok(NULL, ":")) {
net2s->back_mac[i] = strtoul(tok, NULL, 16);
}
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/filter-mac", net2_path_fe));
net2s->filter_mac = val ? strtoul(val, NULL, 10) : -1;
net2s->frontend = libxl__xs_read(&gc, XBT_NULL,
libxl__sprintf(&gc, "%s/frontend", net2s->backend));
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/frontend-id", net2s->backend));
net2s->frontend_id = val ? strtoul(val, NULL, 10) : -1;
}
libxl__free_all(&gc);
return res;
err:
libxl__free_all(&gc);
return NULL;
}
int libxl_device_net2_del(libxl_ctx *ctx, libxl_device_net2 *net2, int wait)
{
libxl__device device;
device.backend_devid = net2->devid;
device.backend_domid = net2->backend_domid;
device.backend_kind = DEVICE_VIF2;
device.devid = net2->devid;
device.domid = net2->domid;
device.kind = DEVICE_VIF2;
return libxl__device_del(ctx, &device, wait);
}
/******************************************************************************/
int libxl_device_console_add(libxl_ctx *ctx, uint32_t domid, libxl_device_console *console)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
flexarray_t *front;
flexarray_t *back;
libxl__device device;
int rc;
front = flexarray_make(16, 1);
if (!front) {
rc = ERROR_NOMEM;
goto out;
}
back = flexarray_make(16, 1);
if (!back) {
rc = ERROR_NOMEM;
goto out_free;
}
device.backend_devid = console->devid;
device.backend_domid = console->backend_domid;
device.backend_kind = DEVICE_CONSOLE;
device.devid = console->devid;
device.domid = console->domid;
device.kind = DEVICE_CONSOLE;
flexarray_append(back, "frontend-id");
flexarray_append(back, libxl__sprintf(&gc, "%d", console->domid));
flexarray_append(back, "online");
flexarray_append(back, "1");
flexarray_append(back, "state");
flexarray_append(back, libxl__sprintf(&gc, "%d", 1));
flexarray_append(back, "domain");
flexarray_append(back, libxl__domid_to_name(&gc, domid));
flexarray_append(back, "protocol");
flexarray_append(back, LIBXL_XENCONSOLE_PROTOCOL);
flexarray_append(front, "backend-id");
flexarray_append(front, libxl__sprintf(&gc, "%d", console->backend_domid));
flexarray_append(front, "limit");
flexarray_append(front, libxl__sprintf(&gc, "%d", LIBXL_XENCONSOLE_LIMIT));
flexarray_append(front, "type");
if (console->consback == LIBXL_CONSBACK_XENCONSOLED)
flexarray_append(front, "xenconsoled");
else
flexarray_append(front, "ioemu");
flexarray_append(front, "output");
flexarray_append(front, console->output);
if (device.devid == 0) {
if (console->build_state == NULL) {
rc = ERROR_INVAL;
goto out_free;
}
flexarray_append(front, "port");
flexarray_append(front, libxl__sprintf(&gc, "%"PRIu32, console->build_state->console_port));
flexarray_append(front, "ring-ref");
flexarray_append(front, libxl__sprintf(&gc, "%lu", console->build_state->console_mfn));
} else {
flexarray_append(front, "state");
flexarray_append(front, libxl__sprintf(&gc, "%d", 1));
flexarray_append(front, "protocol");
flexarray_append(front, LIBXL_XENCONSOLE_PROTOCOL);
}
libxl__device_generic_add(ctx, &device,
libxl__xs_kvs_of_flexarray(&gc, back, back->count),
libxl__xs_kvs_of_flexarray(&gc, front, front->count));
rc = 0;
out_free:
flexarray_free(back);
flexarray_free(front);
out:
libxl__free_all(&gc);
return rc;
}
/******************************************************************************/
void libxl_device_vkb_init(libxl_device_vkb *vkb, int dev_num)
{
memset(vkb, 0x00, sizeof(libxl_device_vkb));
vkb->devid = dev_num;
}
int libxl_device_vkb_add(libxl_ctx *ctx, uint32_t domid, libxl_device_vkb *vkb)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
flexarray_t *front;
flexarray_t *back;
libxl__device device;
int rc;
front = flexarray_make(16, 1);
if (!front) {
rc = ERROR_NOMEM;
goto out;
}
back = flexarray_make(16, 1);
if (!back) {
rc = ERROR_NOMEM;
goto out_free;
}
device.backend_devid = vkb->devid;
device.backend_domid = vkb->backend_domid;
device.backend_kind = DEVICE_VKBD;
device.devid = vkb->devid;
device.domid = vkb->domid;
device.kind = DEVICE_VKBD;
flexarray_append(back, "frontend-id");
flexarray_append(back, libxl__sprintf(&gc, "%d", vkb->domid));
flexarray_append(back, "online");
flexarray_append(back, "1");
flexarray_append(back, "state");
flexarray_append(back, libxl__sprintf(&gc, "%d", 1));
flexarray_append(back, "domain");
flexarray_append(back, libxl__domid_to_name(&gc, domid));
flexarray_append(front, "backend-id");
flexarray_append(front, libxl__sprintf(&gc, "%d", vkb->backend_domid));
flexarray_append(front, "state");
flexarray_append(front, libxl__sprintf(&gc, "%d", 1));
libxl__device_generic_add(ctx, &device,
libxl__xs_kvs_of_flexarray(&gc, back, back->count),
libxl__xs_kvs_of_flexarray(&gc, front, front->count));
rc = 0;
out_free:
flexarray_free(back);
flexarray_free(front);
out:
libxl__free_all(&gc);
return rc;
}
int libxl_device_vkb_clean_shutdown(libxl_ctx *ctx, uint32_t domid)
{
return ERROR_NI;
}
int libxl_device_vkb_hard_shutdown(libxl_ctx *ctx, uint32_t domid)
{
return ERROR_NI;
}
static unsigned int libxl_append_disk_list_of_type(libxl_ctx *ctx,
uint32_t domid,
const char *type,
libxl_device_disk **disks,
unsigned int *ndisks)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *be_path = NULL;
char **dir = NULL;
unsigned int n = 0, len = 0;
libxl_device_disk *pdisk = NULL, *pdisk_end = NULL;
char *physpath_tmp = NULL;
be_path = libxl__sprintf(&gc, "%s/backend/%s/%d",
libxl__xs_get_dompath(&gc, 0), type, domid);
dir = libxl__xs_directory(&gc, XBT_NULL, be_path, &n);
if (dir) {
char *removable;
*disks = realloc(*disks, sizeof (libxl_device_disk) * (*ndisks + n));
pdisk = *disks + *ndisks;
*ndisks += n;
pdisk_end = *disks + *ndisks;
for (; pdisk < pdisk_end; pdisk++, dir++) {
pdisk->backend_domid = 0;
pdisk->domid = domid;
physpath_tmp = xs_read(ctx->xsh, XBT_NULL, libxl__sprintf(&gc, "%s/%s/params", be_path, *dir), &len);
if (physpath_tmp && strchr(physpath_tmp, ':')) {
pdisk->pdev_path = strdup(strchr(physpath_tmp, ':') + 1);
free(physpath_tmp);
} else {
pdisk->pdev_path = physpath_tmp;
}
libxl_string_to_backend(ctx, libxl__xs_read(&gc, XBT_NULL,
libxl__sprintf(&gc, "%s/%s/type", be_path, *dir)),
&(pdisk->backend));
pdisk->vdev = xs_read(ctx->xsh, XBT_NULL, libxl__sprintf(&gc, "%s/%s/dev", be_path, *dir), &len);
removable = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/%s/removable", be_path, *dir));
if (removable)
pdisk->unpluggable = atoi(removable);
else
pdisk->unpluggable = 0;
if (!strcmp(libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/%s/mode", be_path, *dir)), "w"))
pdisk->readwrite = 1;
else
pdisk->readwrite = 0;
type = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/device-type", libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/%s/frontend", be_path, *dir))));
pdisk->is_cdrom = !strcmp(type, "cdrom");
}
}
libxl__free_all(&gc);
return n;
}
libxl_device_disk *libxl_device_disk_list(libxl_ctx *ctx, uint32_t domid, int *num)
{
libxl_device_disk *disks = NULL;
unsigned int ndisks = 0;
*num = libxl_append_disk_list_of_type(ctx, domid, "vbd", &disks, &ndisks);
*num += libxl_append_disk_list_of_type(ctx, domid, "tap", &disks, &ndisks);
*num += libxl_append_disk_list_of_type(ctx, domid, "qdisk", &disks, &ndisks);
return disks;
}
int libxl_device_disk_getinfo(libxl_ctx *ctx, uint32_t domid,
libxl_device_disk *disk, libxl_diskinfo *diskinfo)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *dompath, *diskpath;
char *val;
dompath = libxl__xs_get_dompath(&gc, domid);
diskinfo->devid = libxl__device_disk_dev_number(disk->vdev);
/* tap devices entries in xenstore are written as vbd devices. */
diskpath = libxl__sprintf(&gc, "%s/device/vbd/%d", dompath, diskinfo->devid);
diskinfo->backend = xs_read(ctx->xsh, XBT_NULL,
libxl__sprintf(&gc, "%s/backend", diskpath), NULL);
if (!diskinfo->backend) {
libxl__free_all(&gc);
return ERROR_FAIL;
}
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/backend-id", diskpath));
diskinfo->backend_id = val ? strtoul(val, NULL, 10) : -1;
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/state", diskpath));
diskinfo->state = val ? strtoul(val, NULL, 10) : -1;
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/event-channel", diskpath));
diskinfo->evtch = val ? strtoul(val, NULL, 10) : -1;
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/ring-ref", diskpath));
diskinfo->rref = val ? strtoul(val, NULL, 10) : -1;
diskinfo->frontend = xs_read(ctx->xsh, XBT_NULL,
libxl__sprintf(&gc, "%s/frontend", diskinfo->backend), NULL);
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/frontend-id", diskinfo->backend));
diskinfo->frontend_id = val ? strtoul(val, NULL, 10) : -1;
libxl__free_all(&gc);
return 0;
}
int libxl_cdrom_insert(libxl_ctx *ctx, uint32_t domid, libxl_device_disk *disk)
{
int num, i;
uint32_t stubdomid;
libxl_device_disk *disks;
int ret = ERROR_FAIL;
if (!disk->pdev_path) {
disk->pdev_path = strdup("");
disk->format = DISK_FORMAT_EMPTY;
}
disks = libxl_device_disk_list(ctx, domid, &num);
for (i = 0; i < num; i++) {
if (disks[i].is_cdrom && !strcmp(disk->vdev, disks[i].vdev))
/* found */
break;
}
if (i == num) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "Virtual device not found");
goto out;
}
ret = 0;
libxl_device_disk_del(ctx, disks + i, 1);
libxl_device_disk_add(ctx, domid, disk);
stubdomid = libxl_get_stubdom_id(ctx, domid);
if (stubdomid) {
disks[i].domid = stubdomid;
libxl_device_disk_del(ctx, disks + i, 1);
disk->domid = stubdomid;
libxl_device_disk_add(ctx, stubdomid, disk);
disk->domid = domid;
}
out:
for (i = 0; i < num; i++)
libxl_device_disk_destroy(&disks[i]);
free(disks);
return ret;
}
/******************************************************************************/
void libxl_device_vfb_init(libxl_device_vfb *vfb, int dev_num)
{
memset(vfb, 0x00, sizeof(libxl_device_vfb));
vfb->devid = dev_num;
vfb->display = NULL;
vfb->xauthority = NULL;
vfb->vnc = 1;
vfb->vncpasswd = NULL;
vfb->vnclisten = strdup("127.0.0.1");
vfb->vncdisplay = 0;
vfb->vncunused = 1;
vfb->keymap = NULL;
vfb->sdl = 0;
vfb->opengl = 0;
}
int libxl_device_vfb_add(libxl_ctx *ctx, uint32_t domid, libxl_device_vfb *vfb)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
flexarray_t *front;
flexarray_t *back;
libxl__device device;
int rc;
front = flexarray_make(16, 1);
if (!front) {
rc = ERROR_NOMEM;
goto out;
}
back = flexarray_make(16, 1);
if (!back) {
rc = ERROR_NOMEM;
goto out_free;
}
device.backend_devid = vfb->devid;
device.backend_domid = vfb->backend_domid;
device.backend_kind = DEVICE_VFB;
device.devid = vfb->devid;
device.domid = vfb->domid;
device.kind = DEVICE_VFB;
flexarray_append_pair(back, "frontend-id", libxl__sprintf(&gc, "%d", vfb->domid));
flexarray_append_pair(back, "online", "1");
flexarray_append_pair(back, "state", libxl__sprintf(&gc, "%d", 1));
flexarray_append_pair(back, "domain", libxl__domid_to_name(&gc, domid));
flexarray_append_pair(back, "vnc", libxl__sprintf(&gc, "%d", vfb->vnc));
flexarray_append_pair(back, "vnclisten", vfb->vnclisten);
flexarray_append_pair(back, "vncpasswd", vfb->vncpasswd);
flexarray_append_pair(back, "vncdisplay", libxl__sprintf(&gc, "%d", vfb->vncdisplay));
flexarray_append_pair(back, "vncunused", libxl__sprintf(&gc, "%d", vfb->vncunused));
flexarray_append_pair(back, "sdl", libxl__sprintf(&gc, "%d", vfb->sdl));
flexarray_append_pair(back, "opengl", libxl__sprintf(&gc, "%d", vfb->opengl));
if (vfb->xauthority) {
flexarray_append_pair(back, "xauthority", vfb->xauthority);
}
if (vfb->display) {
flexarray_append_pair(back, "display", vfb->display);
}
flexarray_append_pair(front, "backend-id", libxl__sprintf(&gc, "%d", vfb->backend_domid));
flexarray_append_pair(front, "state", libxl__sprintf(&gc, "%d", 1));
libxl__device_generic_add(ctx, &device,
libxl__xs_kvs_of_flexarray(&gc, back, back->count),
libxl__xs_kvs_of_flexarray(&gc, front, front->count));
rc = 0;
out_free:
flexarray_free(front);
flexarray_free(back);
out:
libxl__free_all(&gc);
return rc;
}
int libxl_device_vfb_clean_shutdown(libxl_ctx *ctx, uint32_t domid)
{
return ERROR_NI;
}
int libxl_device_vfb_hard_shutdown(libxl_ctx *ctx, uint32_t domid)
{
return ERROR_NI;
}
/******************************************************************************/
int libxl_domain_setmaxmem(libxl_ctx *ctx, uint32_t domid, uint32_t max_memkb)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *mem, *endptr;
uint32_t memorykb;
char *dompath = libxl__xs_get_dompath(&gc, domid);
int rc = 1;
mem = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/memory/target", dompath));
if (!mem) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "cannot get memory info from %s/memory/target\n", dompath);
goto out;
}
memorykb = strtoul(mem, &endptr, 10);
if (*endptr != '\0') {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "invalid memory %s from %s/memory/target\n", mem, dompath);
goto out;
}
if (max_memkb < memorykb) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "memory_static_max must be greater than or or equal to memory_dynamic_max\n");
goto out;
}
rc = 0;
out:
libxl__free_all(&gc);
return rc;
}
static int libxl__fill_dom0_memory_info(libxl__gc *gc, uint32_t *target_memkb)
{
int rc;
libxl_dominfo info;
libxl_physinfo physinfo;
char *target = NULL, *staticmax = NULL, *freememslack = NULL, *endptr = NULL;
char *target_path = "/local/domain/0/memory/target";
char *max_path = "/local/domain/0/memory/static-max";
char *free_mem_slack_path = "/local/domain/0/memory/freemem-slack";
xs_transaction_t t;
libxl_ctx *ctx = libxl__gc_owner(gc);
uint32_t free_mem_slack_kb = 0;
retry_transaction:
t = xs_transaction_start(ctx->xsh);
target = libxl__xs_read(gc, t, target_path);
staticmax = libxl__xs_read(gc, t, max_path);
freememslack = libxl__xs_read(gc, t, free_mem_slack_path);
if (target && staticmax && freememslack) {
rc = 0;
goto out;
}
if (target) {
*target_memkb = strtoul(target, &endptr, 10);
if (*endptr != '\0') {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"invalid memory target %s from %s\n", target, target_path);
rc = ERROR_FAIL;
goto out;
}
}
rc = libxl_domain_info(ctx, &info, 0);
if (rc < 0)
goto out;
rc = libxl_get_physinfo(ctx, &physinfo);
if (rc < 0)
goto out;
if (target == NULL) {
libxl__xs_write(gc, t, target_path, "%"PRIu32,
(uint32_t) info.current_memkb);
*target_memkb = (uint32_t) info.current_memkb;
}
if (staticmax == NULL)
libxl__xs_write(gc, t, max_path, "%"PRIu32,
(uint32_t) info.max_memkb);
if (freememslack == NULL) {
free_mem_slack_kb = (uint32_t) (PAGE_TO_MEMKB(physinfo.total_pages) -
info.current_memkb);
/* From empirical measurements the free_mem_slack shouldn't be more
* than 15% of the total memory present on the system. */
if (free_mem_slack_kb > PAGE_TO_MEMKB(physinfo.total_pages) * 0.15)
free_mem_slack_kb = PAGE_TO_MEMKB(physinfo.total_pages) * 0.15;
libxl__xs_write(gc, t, free_mem_slack_path, "%"PRIu32, free_mem_slack_kb);
}
rc = 0;
out:
if (!xs_transaction_end(ctx->xsh, t, 0)) {
if (errno == EAGAIN)
goto retry_transaction;
else
rc = ERROR_FAIL;
}
return rc;
}
/* returns how much memory should be left free in the system */
static int libxl__get_free_memory_slack(libxl__gc *gc, uint32_t *free_mem_slack)
{
int rc;
char *free_mem_slack_path = "/local/domain/0/memory/freemem-slack";
char *free_mem_slack_s, *endptr;
uint32_t target_memkb;
retry:
free_mem_slack_s = libxl__xs_read(gc, XBT_NULL, free_mem_slack_path);
if (!free_mem_slack_s) {
rc = libxl__fill_dom0_memory_info(gc, &target_memkb);
if (rc < 0)
return rc;
goto retry;
} else {
*free_mem_slack = strtoul(free_mem_slack_s, &endptr, 10);
if (*endptr != '\0') {
LIBXL__LOG_ERRNO(gc->owner, LIBXL__LOG_ERROR,
"invalid free_mem_slack %s from %s\n",
free_mem_slack_s, free_mem_slack_path);
return ERROR_FAIL;
}
}
return 0;
}
int libxl_set_memory_target(libxl_ctx *ctx, uint32_t domid,
int32_t target_memkb, int relative, int enforce)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
int rc = 1, abort = 0;
uint32_t memorykb = 0, videoram = 0;
uint32_t current_target_memkb = 0, new_target_memkb = 0;
char *memmax, *endptr, *videoram_s = NULL, *target = NULL;
char *dompath = libxl__xs_get_dompath(&gc, domid);
xc_domaininfo_t info;
libxl_dominfo ptr;
char *uuid;
xs_transaction_t t;
retry_transaction:
t = xs_transaction_start(ctx->xsh);
target = libxl__xs_read(&gc, t, libxl__sprintf(&gc,
"%s/memory/target", dompath));
if (!target && !domid) {
xs_transaction_end(ctx->xsh, t, 1);
rc = libxl__fill_dom0_memory_info(&gc, ¤t_target_memkb);
if (rc < 0) {
abort = 1;
goto out;
}
goto retry_transaction;
} else if (!target) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"cannot get target memory info from %s/memory/target\n",
dompath);
abort = 1;
goto out;
} else {
current_target_memkb = strtoul(target, &endptr, 10);
if (*endptr != '\0') {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"invalid memory target %s from %s/memory/target\n",
target, dompath);
abort = 1;
goto out;
}
}
memmax = libxl__xs_read(&gc, t, libxl__sprintf(&gc,
"%s/memory/static-max", dompath));
if (!memmax) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"cannot get memory info from %s/memory/static-max\n",
dompath);
abort = 1;
goto out;
}
memorykb = strtoul(memmax, &endptr, 10);
if (*endptr != '\0') {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"invalid max memory %s from %s/memory/static-max\n",
memmax, dompath);
abort = 1;
goto out;
}
if (relative) {
if (target_memkb < 0 && abs(target_memkb) > current_target_memkb)
new_target_memkb = 0;
else
new_target_memkb = current_target_memkb + target_memkb;
} else
new_target_memkb = target_memkb;
if (new_target_memkb > memorykb) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR,
"memory_dynamic_max must be less than or equal to"
" memory_static_max\n");
abort = 1;
goto out;
}
if (!domid && new_target_memkb < LIBXL_MIN_DOM0_MEM) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR,
"new target %d for dom0 is below the minimum threshold\n",
new_target_memkb);
abort = 1;
goto out;
}
videoram_s = libxl__xs_read(&gc, t, libxl__sprintf(&gc,
"%s/memory/videoram", dompath));
videoram = videoram_s ? atoi(videoram_s) : 0;
if (enforce) {
memorykb = new_target_memkb;
rc = xc_domain_setmaxmem(ctx->xch, domid, memorykb +
LIBXL_MAXMEM_CONSTANT);
if (rc != 0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"xc_domain_setmaxmem domid=%d memkb=%d failed "
"rc=%d\n", domid, memorykb + LIBXL_MAXMEM_CONSTANT, rc);
abort = 1;
goto out;
}
}
new_target_memkb -= videoram;
rc = xc_domain_set_pod_target(ctx->xch, domid,
new_target_memkb / 4, NULL, NULL, NULL);
if (rc != 0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"xc_domain_set_pod_target domid=%d, memkb=%d "
"failed rc=%d\n", domid, new_target_memkb / 4,
rc);
abort = 1;
goto out;
}
libxl__xs_write(&gc, t, libxl__sprintf(&gc, "%s/memory/target",
dompath), "%"PRIu32, new_target_memkb);
rc = xc_domain_getinfolist(ctx->xch, domid, 1, &info);
if (rc != 1 || info.domain != domid) {
abort = 1;
goto out;
}
xcinfo2xlinfo(&info, &ptr);
uuid = libxl__uuid2string(&gc, ptr.uuid);
libxl__xs_write(&gc, t, libxl__sprintf(&gc, "/vm/%s/memory", uuid),
"%"PRIu32, new_target_memkb / 1024);
out:
if (!xs_transaction_end(ctx->xsh, t, abort) && !abort)
if (errno == EAGAIN)
goto retry_transaction;
libxl__free_all(&gc);
return rc;
}
int libxl_get_memory_target(libxl_ctx *ctx, uint32_t domid, uint32_t *out_target)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
int rc = 1;
char *target = NULL, *endptr = NULL;
char *dompath = libxl__xs_get_dompath(&gc, domid);
uint32_t target_memkb;
target = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc,
"%s/memory/target", dompath));
if (!target && !domid) {
rc = libxl__fill_dom0_memory_info(&gc, &target_memkb);
if (rc < 0)
goto out;
} else if (!target) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"cannot get target memory info from %s/memory/target\n",
dompath);
goto out;
} else {
target_memkb = strtoul(target, &endptr, 10);
if (*endptr != '\0') {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"invalid memory target %s from %s/memory/target\n",
target, dompath);
goto out;
}
}
*out_target = target_memkb;
rc = 0;
out:
libxl__free_all(&gc);
return rc;
}
int libxl_domain_need_memory(libxl_ctx *ctx, libxl_domain_build_info *b_info,
libxl_device_model_info *dm_info, uint32_t *need_memkb)
{
*need_memkb = b_info->target_memkb;
if (b_info->hvm) {
*need_memkb += b_info->shadow_memkb + LIBXL_HVM_EXTRA_MEMORY;
if (strstr(dm_info->device_model, "stubdom-dm"))
*need_memkb += 32 * 1024;
} else
*need_memkb += b_info->shadow_memkb + LIBXL_PV_EXTRA_MEMORY;
if (*need_memkb % (2 * 1024))
*need_memkb += (2 * 1024) - (*need_memkb % (2 * 1024));
return 0;
}
int libxl_get_free_memory(libxl_ctx *ctx, uint32_t *memkb)
{
int rc = 0;
libxl_physinfo info;
uint32_t freemem_slack;
libxl__gc gc = LIBXL_INIT_GC(ctx);
rc = libxl_get_physinfo(ctx, &info);
if (rc < 0)
goto out;
rc = libxl__get_free_memory_slack(&gc, &freemem_slack);
if (rc < 0)
goto out;
if ((info.free_pages + info.scrub_pages) * 4 > freemem_slack)
*memkb = (info.free_pages + info.scrub_pages) * 4 - freemem_slack;
else
*memkb = 0;
out:
libxl__free_all(&gc);
return rc;
}
int libxl_wait_for_free_memory(libxl_ctx *ctx, uint32_t domid, uint32_t
memory_kb, int wait_secs)
{
int rc = 0;
libxl_physinfo info;
uint32_t freemem_slack;
libxl__gc gc = LIBXL_INIT_GC(ctx);
rc = libxl__get_free_memory_slack(&gc, &freemem_slack);
if (rc < 0)
goto out;
while (wait_secs > 0) {
rc = libxl_get_physinfo(ctx, &info);
if (rc < 0)
goto out;
if (info.free_pages * 4 - freemem_slack >= memory_kb) {
rc = 0;
goto out;
}
wait_secs--;
sleep(1);
}
rc = ERROR_NOMEM;
out:
libxl__free_all(&gc);
return rc;
}
int libxl_wait_for_memory_target(libxl_ctx *ctx, uint32_t domid, int wait_secs)
{
int rc = 0;
uint32_t target_memkb = 0;
libxl_dominfo info;
do {
wait_secs--;
sleep(1);
rc = libxl_get_memory_target(ctx, domid, &target_memkb);
if (rc < 0)
goto out;
rc = libxl_domain_info(ctx, &info, domid);
if (rc < 0)
return rc;
} while (wait_secs > 0 && info.current_memkb > target_memkb);
if (info.current_memkb <= target_memkb)
rc = 0;
else
rc = ERROR_FAIL;
out:
return 0;
}
int libxl_button_press(libxl_ctx *ctx, uint32_t domid, libxl_button button)
{
int rc = -1;
switch (button) {
case POWER_BUTTON:
rc = xc_domain_send_trigger(ctx->xch, domid, XEN_DOMCTL_SENDTRIGGER_POWER, 0);
break;
case SLEEP_BUTTON:
rc = xc_domain_send_trigger(ctx->xch, domid, XEN_DOMCTL_SENDTRIGGER_SLEEP, 0);
break;
default:
break;
}
return rc;
}
int libxl_get_physinfo(libxl_ctx *ctx, libxl_physinfo *physinfo)
{
xc_physinfo_t xcphysinfo = { 0 };
int rc;
rc = xc_physinfo(ctx->xch, &xcphysinfo);
if (rc != 0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "getting physinfo");
return ERROR_FAIL;
}
physinfo->threads_per_core = xcphysinfo.threads_per_core;
physinfo->cores_per_socket = xcphysinfo.cores_per_socket;
physinfo->max_cpu_id = xcphysinfo.max_cpu_id;
physinfo->nr_cpus = xcphysinfo.nr_cpus;
physinfo->cpu_khz = xcphysinfo.cpu_khz;
physinfo->total_pages = xcphysinfo.total_pages;
physinfo->free_pages = xcphysinfo.free_pages;
physinfo->scrub_pages = xcphysinfo.scrub_pages;
physinfo->nr_nodes = xcphysinfo.nr_nodes;
memcpy(physinfo->hw_cap,xcphysinfo.hw_cap, sizeof(physinfo->hw_cap));
physinfo->phys_cap = xcphysinfo.capabilities;
return 0;
}
int libxl_get_topologyinfo(libxl_ctx *ctx, libxl_topologyinfo *info)
{
xc_topologyinfo_t tinfo;
DECLARE_HYPERCALL_BUFFER(xc_cpu_to_core_t, coremap);
DECLARE_HYPERCALL_BUFFER(xc_cpu_to_socket_t, socketmap);
DECLARE_HYPERCALL_BUFFER(xc_cpu_to_node_t, nodemap);
int i;
int rc = 0;
rc += libxl_cpuarray_alloc(ctx, &info->coremap);
rc += libxl_cpuarray_alloc(ctx, &info->socketmap);
rc += libxl_cpuarray_alloc(ctx, &info->nodemap);
if (rc)
goto fail;
coremap = xc_hypercall_buffer_alloc(ctx->xch, coremap, sizeof(*coremap) * info->coremap.entries);
socketmap = xc_hypercall_buffer_alloc(ctx->xch, socketmap, sizeof(*socketmap) * info->socketmap.entries);
nodemap = xc_hypercall_buffer_alloc(ctx->xch, nodemap, sizeof(*nodemap) * info->nodemap.entries);
if ((coremap == NULL) || (socketmap == NULL) || (nodemap == NULL))
goto fail;
set_xen_guest_handle(tinfo.cpu_to_core, coremap);
set_xen_guest_handle(tinfo.cpu_to_socket, socketmap);
set_xen_guest_handle(tinfo.cpu_to_node, nodemap);
tinfo.max_cpu_index = info->coremap.entries - 1;
if (xc_topologyinfo(ctx->xch, &tinfo) != 0)
goto fail;
for (i = 0; i <= tinfo.max_cpu_index; i++) {
if (i < info->coremap.entries)
info->coremap.array[i] = (coremap[i] == INVALID_TOPOLOGY_ID) ?
LIBXL_CPUARRAY_INVALID_ENTRY : coremap[i];
if (i < info->socketmap.entries)
info->socketmap.array[i] = (socketmap[i] == INVALID_TOPOLOGY_ID) ?
LIBXL_CPUARRAY_INVALID_ENTRY : socketmap[i];
if (i < info->nodemap.entries)
info->nodemap.array[i] = (nodemap[i] == INVALID_TOPOLOGY_ID) ?
LIBXL_CPUARRAY_INVALID_ENTRY : nodemap[i];
}
xc_hypercall_buffer_free(ctx->xch, coremap);
xc_hypercall_buffer_free(ctx->xch, socketmap);
xc_hypercall_buffer_free(ctx->xch, nodemap);
return 0;
fail:
xc_hypercall_buffer_free(ctx->xch, coremap);
xc_hypercall_buffer_free(ctx->xch, socketmap);
xc_hypercall_buffer_free(ctx->xch, nodemap);
libxl_topologyinfo_destroy(info);
return ERROR_FAIL;
}
const libxl_version_info* libxl_get_version_info(libxl_ctx *ctx)
{
union {
xen_extraversion_t xen_extra;
xen_compile_info_t xen_cc;
xen_changeset_info_t xen_chgset;
xen_capabilities_info_t xen_caps;
xen_platform_parameters_t p_parms;
xen_commandline_t xen_commandline;
} u;
long xen_version;
libxl_version_info *info = &ctx->version_info;
if (info->xen_version_extra != NULL)
return info;
xen_version = xc_version(ctx->xch, XENVER_version, NULL);
info->xen_version_major = xen_version >> 16;
info->xen_version_minor = xen_version & 0xFF;
xc_version(ctx->xch, XENVER_extraversion, &u.xen_extra);
info->xen_version_extra = strdup(u.xen_extra);
xc_version(ctx->xch, XENVER_compile_info, &u.xen_cc);
info->compiler = strdup(u.xen_cc.compiler);
info->compile_by = strdup(u.xen_cc.compile_by);
info->compile_domain = strdup(u.xen_cc.compile_domain);
info->compile_date = strdup(u.xen_cc.compile_date);
xc_version(ctx->xch, XENVER_capabilities, &u.xen_caps);
info->capabilities = strdup(u.xen_caps);
xc_version(ctx->xch, XENVER_changeset, &u.xen_chgset);
info->changeset = strdup(u.xen_chgset);
xc_version(ctx->xch, XENVER_platform_parameters, &u.p_parms);
info->virt_start = u.p_parms.virt_start;
info->pagesize = xc_version(ctx->xch, XENVER_pagesize, NULL);
xc_version(ctx->xch, XENVER_commandline, &u.xen_commandline);
info->commandline = strdup(u.xen_commandline);
return info;
}
libxl_vcpuinfo *libxl_list_vcpu(libxl_ctx *ctx, uint32_t domid,
int *nb_vcpu, int *nrcpus)
{
libxl_vcpuinfo *ptr, *ret;
xc_domaininfo_t domaininfo;
xc_vcpuinfo_t vcpuinfo;
if (xc_domain_getinfolist(ctx->xch, domid, 1, &domaininfo) != 1) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "getting infolist");
return NULL;
}
*nrcpus = libxl_get_max_cpus(ctx);
ret = ptr = calloc(domaininfo.max_vcpu_id + 1, sizeof (libxl_vcpuinfo));
if (!ptr) {
return NULL;
}
for (*nb_vcpu = 0; *nb_vcpu <= domaininfo.max_vcpu_id; ++*nb_vcpu, ++ptr) {
if (libxl_cpumap_alloc(ctx, &ptr->cpumap)) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "allocating cpumap");
return NULL;
}
if (xc_vcpu_getinfo(ctx->xch, domid, *nb_vcpu, &vcpuinfo) == -1) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "getting vcpu info");
return NULL;
}
if (xc_vcpu_getaffinity(ctx->xch, domid, *nb_vcpu, ptr->cpumap.map) == -1) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "getting vcpu affinity");
return NULL;
}
ptr->vcpuid = *nb_vcpu;
ptr->cpu = vcpuinfo.cpu;
ptr->online = !!vcpuinfo.online;
ptr->blocked = !!vcpuinfo.blocked;
ptr->running = !!vcpuinfo.running;
ptr->vcpu_time = vcpuinfo.cpu_time;
}
return ret;
}
int libxl_set_vcpuaffinity(libxl_ctx *ctx, uint32_t domid, uint32_t vcpuid,
libxl_cpumap *cpumap)
{
if (xc_vcpu_setaffinity(ctx->xch, domid, vcpuid, cpumap->map)) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "setting vcpu affinity");
return ERROR_FAIL;
}
return 0;
}
int libxl_set_vcpuonline(libxl_ctx *ctx, uint32_t domid, libxl_cpumap *cpumap)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
libxl_dominfo info;
char *dompath;
xs_transaction_t t;
int i, rc = ERROR_FAIL;
if (libxl_domain_info(ctx, &info, domid) < 0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "getting domain info list");
goto out;
}
if (!(dompath = libxl__xs_get_dompath(&gc, domid)))
goto out;
retry_transaction:
t = xs_transaction_start(ctx->xsh);
for (i = 0; i <= info.vcpu_max_id; i++)
libxl__xs_write(&gc, t,
libxl__sprintf(&gc, "%s/cpu/%u/availability", dompath, i),
"%s", libxl_cpumap_test(cpumap, i) ? "online" : "offline");
if (!xs_transaction_end(ctx->xsh, t, 0)) {
if (errno == EAGAIN)
goto retry_transaction;
} else
rc = 0;
out:
libxl__free_all(&gc);
return rc;
}
/*
* returns one of the XEN_SCHEDULER_* constants from public/domctl.h
*/
int libxl_get_sched_id(libxl_ctx *ctx)
{
int sched, ret;
if ((ret = xc_sched_id(ctx->xch, &sched)) != 0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "getting domain info list");
return ERROR_FAIL;
}
return sched;
}
int libxl_sched_credit_domain_get(libxl_ctx *ctx, uint32_t domid, libxl_sched_credit *scinfo)
{
struct xen_domctl_sched_credit sdom;
int rc;
rc = xc_sched_credit_domain_get(ctx->xch, domid, &sdom);
if (rc != 0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "setting domain sched credit");
return ERROR_FAIL;
}
scinfo->weight = sdom.weight;
scinfo->cap = sdom.cap;
return 0;
}
int libxl_sched_credit_domain_set(libxl_ctx *ctx, uint32_t domid, libxl_sched_credit *scinfo)
{
struct xen_domctl_sched_credit sdom;
xc_domaininfo_t domaininfo;
int rc;
rc = xc_domain_getinfolist(ctx->xch, domid, 1, &domaininfo);
if (rc < 0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "getting domain info list");
return ERROR_FAIL;
}
if (rc != 1 || domaininfo.domain != domid)
return ERROR_INVAL;
if (scinfo->weight < 1 || scinfo->weight > 65535) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Cpu weight out of range, valid values are within range from 1 to 65535");
return ERROR_INVAL;
}
if (scinfo->cap < 0 || scinfo->cap > (domaininfo.max_vcpu_id + 1) * 100) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Cpu cap out of range, valid range is from 0 to %d for specified number of vcpus",
((domaininfo.max_vcpu_id + 1) * 100));
return ERROR_INVAL;
}
sdom.weight = scinfo->weight;
sdom.cap = scinfo->cap;
rc = xc_sched_credit_domain_set(ctx->xch, domid, &sdom);
if ( rc < 0 ) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "setting domain sched credit");
return ERROR_FAIL;
}
return 0;
}
static int trigger_type_from_string(char *trigger_name)
{
if (!strcmp(trigger_name, "nmi"))
return XEN_DOMCTL_SENDTRIGGER_NMI;
else if (!strcmp(trigger_name, "reset"))
return XEN_DOMCTL_SENDTRIGGER_RESET;
else if (!strcmp(trigger_name, "init"))
return XEN_DOMCTL_SENDTRIGGER_INIT;
else if (!strcmp(trigger_name, "power"))
return XEN_DOMCTL_SENDTRIGGER_POWER;
else if (!strcmp(trigger_name, "sleep"))
return XEN_DOMCTL_SENDTRIGGER_SLEEP;
else
return -1;
}
int libxl_send_trigger(libxl_ctx *ctx, uint32_t domid, char *trigger_name, uint32_t vcpuid)
{
int rc = -1;
int trigger_type = -1;
if (!strcmp(trigger_name, "s3resume")) {
xc_set_hvm_param(ctx->xch, domid, HVM_PARAM_ACPI_S_STATE, 0);
return 0;
}
trigger_type = trigger_type_from_string(trigger_name);
if (trigger_type == -1) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, -1,
"Invalid trigger, valid triggers are <nmi|reset|init|power|sleep>");
return ERROR_INVAL;
}
rc = xc_domain_send_trigger(ctx->xch, domid, trigger_type, vcpuid);
if (rc != 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Send trigger '%s' failed", trigger_name);
return ERROR_FAIL;
}
return 0;
}
int libxl_send_sysrq(libxl_ctx *ctx, uint32_t domid, char sysrq)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *dompath = libxl__xs_get_dompath(&gc, domid);
libxl__xs_write(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/control/sysrq", dompath), "%c", sysrq);
libxl__free_all(&gc);
return 0;
}
int libxl_send_debug_keys(libxl_ctx *ctx, char *keys)
{
int ret;
ret = xc_send_debug_keys(ctx->xch, keys);
if ( ret < 0 ) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "sending debug keys");
return ERROR_FAIL;
}
return 0;
}
libxl_xen_console_reader *
libxl_xen_console_read_start(libxl_ctx *ctx, int clear)
{
libxl_xen_console_reader *cr;
unsigned int size = 16384;
char *buf = malloc(size);
if (!buf) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "cannot malloc buffer for libxl_xen_console_reader,"
" size is %u", size);
return NULL;
}
cr = malloc(sizeof(libxl_xen_console_reader));
if (!cr) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "cannot malloc libxl_xen_console_reader");
return NULL;
}
memset(cr, 0, sizeof(libxl_xen_console_reader));
cr->buffer = buf;
cr->size = size;
cr->count = size;
cr->clear = clear;
cr->incremental = 1;
return cr;
}
/* return values: *line_r
* 1 success, whole line obtained from buffer non-0
* 0 no more lines available right now 0
* negative error code ERROR_* 0
* On success *line_r is updated to point to a nul-terminated
* string which is valid until the next call on the same console
* reader. The libxl caller may overwrite parts of the string
* if it wishes. */
int libxl_xen_console_read_line(libxl_ctx *ctx,
libxl_xen_console_reader *cr,
char **line_r)
{
int ret;
memset(cr->buffer, 0, cr->size);
ret = xc_readconsolering(ctx->xch, cr->buffer, &cr->count,
cr->clear, cr->incremental, &cr->index);
if (ret < 0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "reading console ring buffer");
return ERROR_FAIL;
}
if (!ret) {
if (cr->count) {
*line_r = cr->buffer;
ret = 1;
} else {
*line_r = NULL;
ret = 0;
}
}
return ret;
}
void libxl_xen_console_read_finish(libxl_ctx *ctx,
libxl_xen_console_reader *cr)
{
free(cr->buffer);
free(cr);
}
uint32_t libxl_vm_get_start_time(libxl_ctx *ctx, uint32_t domid)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *dompath = libxl__xs_get_dompath(&gc, domid);
char *vm_path, *start_time;
uint32_t ret;
vm_path = libxl__xs_read(
&gc, XBT_NULL, libxl__sprintf(&gc, "%s/vm", dompath));
start_time = libxl__xs_read(
&gc, XBT_NULL, libxl__sprintf(&gc, "%s/start_time", vm_path));
if (start_time == NULL) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, -1,
"Can't get start time of domain '%d'", domid);
ret = -1;
}else{
ret = strtoul(start_time, NULL, 10);
}
libxl__free_all(&gc);
return ret;
}
char *libxl_tmem_list(libxl_ctx *ctx, uint32_t domid, int use_long)
{
int rc;
char _buf[32768];
rc = xc_tmem_control(ctx->xch, -1, TMEMC_LIST, domid, 32768, use_long,
0, _buf);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Can not get tmem list");
return NULL;
}
return strdup(_buf);
}
int libxl_tmem_freeze(libxl_ctx *ctx, uint32_t domid)
{
int rc;
rc = xc_tmem_control(ctx->xch, -1, TMEMC_FREEZE, domid, 0, 0,
0, NULL);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Can not freeze tmem pools");
return ERROR_FAIL;
}
return rc;
}
int libxl_tmem_destroy(libxl_ctx *ctx, uint32_t domid)
{
int rc;
rc = xc_tmem_control(ctx->xch, -1, TMEMC_DESTROY, domid, 0, 0,
0, NULL);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Can not destroy tmem pools");
return ERROR_FAIL;
}
return rc;
}
int libxl_tmem_thaw(libxl_ctx *ctx, uint32_t domid)
{
int rc;
rc = xc_tmem_control(ctx->xch, -1, TMEMC_THAW, domid, 0, 0,
0, NULL);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Can not thaw tmem pools");
return ERROR_FAIL;
}
return rc;
}
static int32_t tmem_setop_from_string(char *set_name)
{
if (!strcmp(set_name, "weight"))
return TMEMC_SET_WEIGHT;
else if (!strcmp(set_name, "cap"))
return TMEMC_SET_CAP;
else if (!strcmp(set_name, "compress"))
return TMEMC_SET_COMPRESS;
else
return -1;
}
int libxl_tmem_set(libxl_ctx *ctx, uint32_t domid, char* name, uint32_t set)
{
int rc;
int32_t subop = tmem_setop_from_string(name);
if (subop == -1) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, -1,
"Invalid set, valid sets are <weight|cap|compress>");
return ERROR_INVAL;
}
rc = xc_tmem_control(ctx->xch, -1, subop, domid, set, 0, 0, NULL);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Can not set tmem %s", name);
return ERROR_FAIL;
}
return rc;
}
int libxl_tmem_shared_auth(libxl_ctx *ctx, uint32_t domid,
char* uuid, int auth)
{
int rc;
rc = xc_tmem_auth(ctx->xch, domid, uuid, auth);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Can not set tmem shared auth");
return ERROR_FAIL;
}
return rc;
}
int libxl_tmem_freeable(libxl_ctx *ctx)
{
int rc;
rc = xc_tmem_control(ctx->xch, -1, TMEMC_QUERY_FREEABLE_MB, -1, 0, 0, 0, 0);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Can not get tmem freeable memory");
return ERROR_FAIL;
}
return rc;
}
void libxl_file_reference_destroy(libxl_file_reference *f)
{
libxl__file_reference_unmap(f);
free(f->path);
}
int libxl_get_freecpus(libxl_ctx *ctx, libxl_cpumap *cpumap)
{
int ncpus;
ncpus = libxl_get_max_cpus(ctx);
if (ncpus == 0)
return ERROR_FAIL;
cpumap->map = xc_cpupool_freeinfo(ctx->xch);
if (cpumap->map == NULL)
return ERROR_FAIL;
cpumap->size = (ncpus + 7) / 8;
return 0;
}
int libxl_create_cpupool(libxl_ctx *ctx, const char *name, int schedid,
libxl_cpumap cpumap, libxl_uuid *uuid,
uint32_t *poolid)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
int rc;
int i;
xs_transaction_t t;
char *uuid_string;
uuid_string = libxl__uuid2string(&gc, *uuid);
if (!uuid_string) {
libxl__free_all(&gc);
return ERROR_NOMEM;
}
rc = xc_cpupool_create(ctx->xch, poolid, schedid);
if (rc) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Could not create cpupool");
libxl__free_all(&gc);
return ERROR_FAIL;
}
libxl_for_each_cpu(i, cpumap)
if (libxl_cpumap_test(&cpumap, i)) {
rc = xc_cpupool_addcpu(ctx->xch, *poolid, i);
if (rc) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Error moving cpu to cpupool");
libxl_destroy_cpupool(ctx, *poolid);
libxl__free_all(&gc);
return ERROR_FAIL;
}
}
for (;;) {
t = xs_transaction_start(ctx->xsh);
xs_mkdir(ctx->xsh, t, libxl__sprintf(&gc, "/local/pool/%d", *poolid));
libxl__xs_write(&gc, t,
libxl__sprintf(&gc, "/local/pool/%d/uuid", *poolid),
"%s", uuid_string);
libxl__xs_write(&gc, t,
libxl__sprintf(&gc, "/local/pool/%d/name", *poolid),
"%s", name);
if (xs_transaction_end(ctx->xsh, t, 0) || (errno != EAGAIN)) {
libxl__free_all(&gc);
return 0;
}
}
}
int libxl_destroy_cpupool(libxl_ctx *ctx, uint32_t poolid)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
int rc, i;
xc_cpupoolinfo_t *info;
xs_transaction_t t;
libxl_cpumap cpumap;
info = xc_cpupool_getinfo(ctx->xch, poolid);
if (info == NULL) {
libxl__free_all(&gc);
return ERROR_NOMEM;
}
rc = ERROR_INVAL;
if ((info->cpupool_id != poolid) || (info->n_dom))
goto out;
rc = ERROR_NOMEM;
if (libxl_cpumap_alloc(ctx, &cpumap))
goto out;
memcpy(cpumap.map, info->cpumap, cpumap.size);
libxl_for_each_cpu(i, cpumap)
if (libxl_cpumap_test(&cpumap, i)) {
rc = xc_cpupool_removecpu(ctx->xch, poolid, i);
if (rc) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Error removing cpu from cpupool");
rc = ERROR_FAIL;
goto out1;
}
}
rc = xc_cpupool_destroy(ctx->xch, poolid);
if (rc) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc, "Could not destroy cpupool");
rc = ERROR_FAIL;
goto out1;
}
for (;;) {
t = xs_transaction_start(ctx->xsh);
xs_rm(ctx->xsh, XBT_NULL, libxl__sprintf(&gc, "/local/pool/%d", poolid));
if (xs_transaction_end(ctx->xsh, t, 0) || (errno != EAGAIN))
break;
}
rc = 0;
out1:
libxl_cpumap_destroy(&cpumap);
out:
xc_cpupool_infofree(ctx->xch, info);
libxl__free_all(&gc);
return rc;
}
int libxl_cpupool_rename(libxl_ctx *ctx, const char *name, uint32_t poolid)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
xs_transaction_t t;
xc_cpupoolinfo_t *info;
int rc;
info = xc_cpupool_getinfo(ctx->xch, poolid);
if (info == NULL) {
libxl__free_all(&gc);
return ERROR_NOMEM;
}
rc = ERROR_INVAL;
if (info->cpupool_id != poolid)
goto out;
rc = 0;
for (;;) {
t = xs_transaction_start(ctx->xsh);
libxl__xs_write(&gc, t,
libxl__sprintf(&gc, "/local/pool/%d/name", poolid),
"%s", name);
if (xs_transaction_end(ctx->xsh, t, 0))
break;
if (errno == EAGAIN)
continue;
rc = ERROR_FAIL;
break;
}
out:
xc_cpupool_infofree(ctx->xch, info);
libxl__free_all(&gc);
return rc;
}
int libxl_cpupool_cpuadd(libxl_ctx *ctx, uint32_t poolid, int cpu)
{
int rc;
rc = xc_cpupool_addcpu(ctx->xch, poolid, cpu);
if (rc) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Error moving cpu to cpupool");
return ERROR_FAIL;
}
return 0;
}
int libxl_cpupool_cpuadd_node(libxl_ctx *ctx, uint32_t poolid, int node, int *cpus)
{
int rc = 0;
int cpu;
libxl_cpumap freemap;
libxl_topologyinfo topology;
if (libxl_get_freecpus(ctx, &freemap)) {
return ERROR_FAIL;
}
if (libxl_get_topologyinfo(ctx, &topology)) {
rc = ERROR_FAIL;
goto out;
}
*cpus = 0;
for (cpu = 0; cpu < topology.nodemap.entries; cpu++) {
if (libxl_cpumap_test(&freemap, cpu) &&
(topology.nodemap.array[cpu] == node) &&
!libxl_cpupool_cpuadd(ctx, poolid, cpu)) {
(*cpus)++;
}
}
libxl_topologyinfo_destroy(&topology);
out:
libxl_cpumap_destroy(&freemap);
return rc;
}
int libxl_cpupool_cpuremove(libxl_ctx *ctx, uint32_t poolid, int cpu)
{
int rc;
rc = xc_cpupool_removecpu(ctx->xch, poolid, cpu);
if (rc) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Error removing cpu from cpupool");
return ERROR_FAIL;
}
return 0;
}
int libxl_cpupool_cpuremove_node(libxl_ctx *ctx, uint32_t poolid, int node, int *cpus)
{
int ret = 0;
int n_pools;
int p;
int cpu;
libxl_topologyinfo topology;
libxl_cpupoolinfo *poolinfo;
poolinfo = libxl_list_cpupool(ctx, &n_pools);
if (!poolinfo) {
return ERROR_NOMEM;
}
if (libxl_get_topologyinfo(ctx, &topology)) {
ret = ERROR_FAIL;
goto out;
}
*cpus = 0;
for (p = 0; p < n_pools; p++) {
if (poolinfo[p].poolid == poolid) {
for (cpu = 0; cpu < topology.nodemap.entries; cpu++) {
if ((topology.nodemap.array[cpu] == node) &&
libxl_cpumap_test(&poolinfo[p].cpumap, cpu) &&
!libxl_cpupool_cpuremove(ctx, poolid, cpu)) {
(*cpus)++;
}
}
}
}
libxl_topologyinfo_destroy(&topology);
out:
for (p = 0; p < n_pools; p++) {
libxl_cpupoolinfo_destroy(poolinfo + p);
}
return ret;
}
int libxl_cpupool_movedomain(libxl_ctx *ctx, uint32_t poolid, uint32_t domid)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
int rc;
char *dom_path;
char *vm_path;
char *poolname;
xs_transaction_t t;
dom_path = libxl__xs_get_dompath(&gc, domid);
if (!dom_path) {
libxl__free_all(&gc);
return ERROR_FAIL;
}
rc = xc_cpupool_movedomain(ctx->xch, poolid, domid);
if (rc) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Error moving domain to cpupool");
libxl__free_all(&gc);
return ERROR_FAIL;
}
for (;;) {
t = xs_transaction_start(ctx->xsh);
poolname = libxl__cpupoolid_to_name(&gc, poolid);
vm_path = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/vm", dom_path));
if (!vm_path)
break;
libxl__xs_write(&gc, t, libxl__sprintf(&gc, "%s/pool_name", vm_path),
"%s", poolname);
if (xs_transaction_end(ctx->xsh, t, 0) || (errno != EAGAIN))
break;
}
libxl__free_all(&gc);
return 0;
}
| 31.428881
| 173
| 0.59292
|
[
"model"
] |
05a0c9c2175063b523c3b007541dbdfd73a7d544
| 4,282
|
h
|
C
|
src/extern/inventor/apps/tools/ivfix/IfFlattener.h
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | 2
|
2020-05-21T07:06:07.000Z
|
2021-06-28T02:14:34.000Z
|
src/extern/inventor/apps/tools/ivfix/IfFlattener.h
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | null | null | null |
src/extern/inventor/apps/tools/ivfix/IfFlattener.h
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | 6
|
2016-03-21T19:53:18.000Z
|
2021-06-08T18:06:03.000Z
|
/*
*
* Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
/////////////////////////////////////////////////////////////////////////////
//
// IfFlattener class: takes all the shapes in the scene graph
// represented by a IfHolder and flattens it into a bunch of
// triangles. The coordinates, normals, texture coordinates, and
// material indices are stored in the SoIndexedTriangleStripSet in the
// IfHolder.
//
/////////////////////////////////////////////////////////////////////////////
#ifndef _IF_FLATTENER_
#define _IF_FLATTENER_
#include <Inventor/SbLinear.h>
#include <Inventor/actions/SoCallbackAction.h>
class IfHolder;
class SoNode;
class SoShape;
class IfFlattener {
public:
IfFlattener();
~IfFlattener();
void flatten(IfHolder *_holder);
private:
IfHolder *holder; // Holds most important stuff
int numVerts; // Number of vertices stored
SbMatrix pointMatrix; // For transforming points
SbMatrix normalMatrix; // For transforming normals
SbMatrix textureMatrix; // For transforming texture coords
int numMtlIndices; // Number of material indices stored
int fieldSize; // Number of entries allocated for fields
// These hold pointers to the field value arrays (returned by
// startEditing()) to make additions much faster:
SbVec3f *coordVals;
SbVec3f *normalVals;
SbVec2f *texCoordVals;
int32_t *mtlIndexVals;
void expandFields();
void prepareForShape(SoCallbackAction *cba, const SoShape *shape);
void addTriangle(SoCallbackAction *cba,
const SoPrimitiveVertex *verts[3]);
void finishShape(SoCallbackAction *cba, const SoShape *shape);
void addCoordinate(const SbVec3f &point);
void addNormal(const SbVec3f &normal);
void addMaterialIndex(int materialIndex);
void addTextureCoordinate(const SbVec4f &texCoord);
void createGraph();
//////////////////////////////////////////////////////////////////
//
// Callbacks
static SoCallbackAction::Response preShapeCB(void *userData,
SoCallbackAction *cba,
const SoNode *shape)
{
((IfFlattener *) userData)->
prepareForShape(cba, (const SoShape *) shape);
return SoCallbackAction::CONTINUE;
}
static SoCallbackAction::Response postShapeCB(void *userData,
SoCallbackAction *cba,
const SoNode *shape)
{
((IfFlattener *) userData)->
finishShape(cba, (const SoShape *) shape);
return SoCallbackAction::CONTINUE;
}
static void triangleCB(void *userData, SoCallbackAction *cba,
const SoPrimitiveVertex *v1,
const SoPrimitiveVertex *v2,
const SoPrimitiveVertex *v3)
{
const SoPrimitiveVertex *v[3];
v[0] = v1;
v[1] = v2;
v[2] = v3;
((IfFlattener *) userData)->addTriangle(cba, v);
}
};
#endif /* _IF_FLATTENER_ */
| 32.687023
| 77
| 0.671882
|
[
"shape"
] |
05a3ad017e26543388aebe07d9a2301f84aecf8f
| 14,257
|
h
|
C
|
pkgs/tools/cmake/src/Utilities/cmxmlrpc/XmlRpcCpp.h
|
manggoguy/parsec-modified
|
d14edfb62795805c84a4280d67b50cca175b95af
|
[
"BSD-3-Clause"
] | 64
|
2015-03-06T00:30:56.000Z
|
2022-03-24T13:26:53.000Z
|
pkgs/tools/cmake/src/Utilities/cmxmlrpc/XmlRpcCpp.h
|
manggoguy/parsec-modified
|
d14edfb62795805c84a4280d67b50cca175b95af
|
[
"BSD-3-Clause"
] | 12
|
2020-12-15T08:30:19.000Z
|
2022-03-13T03:54:24.000Z
|
pkgs/tools/cmake/src/Utilities/cmxmlrpc/XmlRpcCpp.h
|
manggoguy/parsec-modified
|
d14edfb62795805c84a4280d67b50cca175b95af
|
[
"BSD-3-Clause"
] | 40
|
2015-02-26T15:31:16.000Z
|
2022-03-03T23:23:37.000Z
|
// -*- C++ -*- <-- an Emacs control
// Copyright information is at the bottom of the file.
//=========================================================================
// XML-RPC C++ API
//=========================================================================
#ifndef _XMLRPCCPP_H_
#define _XMLRPCCPP_H_ 1
// The C++ standard says we should either include <string.h> (which gets
// us the wrong header), or say 'using namespace std;' (which doesn't
// work with our version of g++). So this header name is technically wrong.
// Tell me what your compiler does; I can provide some autoconf magic to the
// Right Thing on most platforms.
//
// 2004.12.22 Bryan: This looks like a problem with whatever g++ he was
// using, so if anything, the special case should be for that. In any case,
// we've already added using namespace std to other files, without knowing
// there was an issue, so I'm just going to do the "using namespace"
// unconditionally and see who complains. If there are complaints, we can
// improve the documentation here.
//
// Formerly, the "using namespace std" was under
// "#if defined(__GNUC__) && (__GNUC__ >= 3)".
#include <string>
using namespace std;
#include <xmlrpc_config.h>
#include <xmlrpc.h>
#include <xmlrpc_client.h>
#include <xmlrpc_server.h>
#define XMLRPC_NO_ASSIGNMENT \
XMLRPC_FATAL_ERROR("Assignment operator not available"); return *this;
//=========================================================================
// XmlRpcFault
//=========================================================================
// A C++ exception class representing an XML-RPC fault.
class XmlRpcFault {
private:
xmlrpc_env mFault;
XmlRpcFault& operator= (const XmlRpcFault& f)
{ (void) f; XMLRPC_NO_ASSIGNMENT }
public:
XmlRpcFault (const XmlRpcFault &fault);
XmlRpcFault (const int faultCode, const string faultString);
XmlRpcFault (const xmlrpc_env *env);
~XmlRpcFault (void);
int getFaultCode (void) const;
string getFaultString (void) const;
xmlrpc_env *getFaultEnv (void);
};
inline int XmlRpcFault::getFaultCode (void) const {
return mFault.fault_code;
}
inline xmlrpc_env *XmlRpcFault::getFaultEnv (void) {
return &mFault;
}
//=========================================================================
// XmlRpcEnv
//=========================================================================
// This class can be used to wrap xmlrpc_env object. Use it as follows:
//
// XmlRpcEnv env;
// xmlrpc_parse_value(env, v, "(i)", &i);
// env.throwIfFaultOccurred();
class XmlRpcEnv {
private:
xmlrpc_env mEnv;
void throwMe (void) const;
XmlRpcEnv& operator= (const XmlRpcEnv& e)
{ (void) e; XMLRPC_NO_ASSIGNMENT }
public:
XmlRpcEnv (const XmlRpcEnv &env);
XmlRpcEnv (void) { xmlrpc_env_init(&mEnv); }
~XmlRpcEnv (void) { xmlrpc_env_clean(&mEnv); }
bool faultOccurred (void) const { return mEnv.fault_occurred; };
bool hasFaultOccurred (void) const { return faultOccurred(); };
/* hasFaultOccurred() is for backward compatibility.
faultOccurred() is a superior name for this.
*/
XmlRpcFault getFault (void) const;
void throwIfFaultOccurred (void) const;
operator xmlrpc_env * (void) { return &mEnv; }
};
inline void XmlRpcEnv::throwIfFaultOccurred (void) const {
if (faultOccurred())
throwMe();
}
//=========================================================================
// XmlRpcValue
//=========================================================================
// An object in this class is an XML-RPC value.
//
// We have a complex structure to allow C code mixed in with C++ code
// which uses this class to refer to the same XML-RPC value object.
// This is especially important because there aren't proper C++ facilities
// for much of Xmlrpc-c; you have to use the C facilities even if you'd
// rather use proper C++.
//
// The XmlRpcValue object internally represents the value as an
// xmlrpc_value. It hold one reference to the xmlrpc_value. Users
// of XmlRpcValue never see that xmlrpc_value, but C code can. the
// C code might create the xmlrpc_value and then bind it to an XmlRpcValue,
// or it might get the xmlrpc_value handle from the XmlRpcValue. Finally,
// C code can simply use the XmlRpcValue where an xmlrpc_value handle is
// required and it gets converted automatically.
//
// So reference counting for the xmlrpc_value is quite a nightmare.
class XmlRpcValue {
private:
xmlrpc_value *mValue;
public:
enum ReferenceBehavior {
MAKE_REFERENCE,
CONSUME_REFERENCE
};
typedef xmlrpc_int32 int32;
XmlRpcValue (void);
XmlRpcValue (xmlrpc_value *value,
ReferenceBehavior behavior = MAKE_REFERENCE);
XmlRpcValue (const XmlRpcValue& value);
~XmlRpcValue (void);
XmlRpcValue& operator= (const XmlRpcValue& value);
// Accessing the value's type (think of this as lightweight RTTI).
xmlrpc_type getType(void) const;
// We don't supply an automatic conversion operator--you need to say
// whether you want to make or borrow this object's reference.
// XXX - Is it really OK for these to be const?
xmlrpc_value *makeReference (void) const;
xmlrpc_value *borrowReference (void) const;
// Some static "constructor" functions.
static XmlRpcValue makeInt (const XmlRpcValue::int32 i);
static XmlRpcValue makeBool (const bool b);
static XmlRpcValue makeDouble (const double d);
static XmlRpcValue makeDateTime (const string& dateTime);
static XmlRpcValue makeString (const string& str);
static XmlRpcValue makeString (const char *const str);
static XmlRpcValue makeString (const char *const str, size_t len);
static XmlRpcValue makeArray (void);
static XmlRpcValue makeStruct (void);
static XmlRpcValue makeBase64 (const unsigned char *const data,
size_t len);
/*
// An interface to xmlrpc_build_value.
static XmlRpcValue buildValue (const char *const format, ...);
*/
// Some functions to get the underlying data.
// These will throw an XmlRpcFault if the data is the wrong type.
XmlRpcValue::int32 getInt (void) const;
bool getBool (void) const;
double getDouble (void) const;
string getRawDateTime (void) const;
string getString (void) const;
XmlRpcValue getArray (void) const;
XmlRpcValue getStruct (void) const;
// This returns an internal pointer which will become invalid when
// all references to the underlying value are destroyed.
void getBase64 (const unsigned char *& out_data,
size_t& out_len) const;
/*
// An interface to xmlrpc_parse_value.
void parseValue (const char *const format, ...);
*/
// Array functions. These will throw an XmlRpcFault if the value
// isn't an array.
size_t arraySize (void) const;
void arrayAppendItem (const XmlRpcValue& value);
XmlRpcValue arrayGetItem (int index) const;
// Struct functions. These will throw an XmlRpcFault if the value
// isn't a struct.
size_t structSize (void) const;
bool structHasKey (const string& key) const;
XmlRpcValue structGetValue (const string& key) const;
void structSetValue (const string& key, const XmlRpcValue& value);
void structGetKeyAndValue (const int index,
string& out_key,
XmlRpcValue& out_value) const;
};
inline XmlRpcValue::XmlRpcValue (xmlrpc_value *value,
ReferenceBehavior behavior)
{
mValue = value;
if (behavior == MAKE_REFERENCE)
xmlrpc_INCREF(value);
}
inline XmlRpcValue::XmlRpcValue (const XmlRpcValue& value) {
mValue = value.mValue;
xmlrpc_INCREF(mValue);
}
inline XmlRpcValue::~XmlRpcValue (void) {
xmlrpc_DECREF(mValue);
}
inline XmlRpcValue& XmlRpcValue::operator= (const XmlRpcValue& value) {
// Must increment before we decrement, in case of assignment to self.
xmlrpc_INCREF(value.mValue);
xmlrpc_DECREF(mValue);
mValue = value.mValue;
return *this;
}
inline xmlrpc_type XmlRpcValue::getType (void) const {
return xmlrpc_value_type(mValue);
}
inline xmlrpc_value *XmlRpcValue::makeReference (void) const {
xmlrpc_INCREF(mValue);
return mValue;
}
inline xmlrpc_value *XmlRpcValue::borrowReference (void) const {
return mValue;
}
//=========================================================================
// XmlRpcClient
//=========================================================================
class XmlRpcClient {
private:
string mServerUrl;
public:
static void Initialize (string appname, string appversion);
static void Terminate (void);
XmlRpcClient (const string& server_url) : mServerUrl(server_url) {}
~XmlRpcClient (void) {}
XmlRpcClient (const XmlRpcClient& client);
XmlRpcClient& operator= (const XmlRpcClient& client);
XmlRpcValue call (string method_name, XmlRpcValue param_array);
void call_asynch (string method_name,
XmlRpcValue param_array,
xmlrpc_response_handler callback,
void* user_data);
void event_loop_asynch (unsigned long milliseconds);
};
inline void XmlRpcClient::call_asynch(string method_name,
XmlRpcValue param_array,
xmlrpc_response_handler callback,
void* user_data)
{
xmlrpc_client_call_asynch_params(
mServerUrl.c_str(),
method_name.c_str(),
callback,
user_data,
param_array.borrowReference());
}
inline void XmlRpcClient::event_loop_asynch(unsigned long milliseconds)
{
xmlrpc_client_event_loop_finish_asynch_timeout(milliseconds);
}
//=========================================================================
// XmlRpcClient Methods
//=========================================================================
// These are inline for now, so we don't need to screw with linker issues
// and build a separate client library.
inline XmlRpcClient::XmlRpcClient (const XmlRpcClient& client)
: mServerUrl(client.mServerUrl)
{
}
inline XmlRpcClient& XmlRpcClient::operator= (const XmlRpcClient& client) {
if (this != &client)
mServerUrl = client.mServerUrl;
return *this;
}
inline void XmlRpcClient::Initialize (string appname, string appversion) {
xmlrpc_client_init(XMLRPC_CLIENT_NO_FLAGS,
appname.c_str(),
appversion.c_str());
}
inline void XmlRpcClient::Terminate (void) {
xmlrpc_client_cleanup();
}
inline XmlRpcValue XmlRpcClient::call (string method_name,
XmlRpcValue param_array)
{
XmlRpcEnv env;
xmlrpc_value *result =
xmlrpc_client_call_params(env,
mServerUrl.c_str(),
method_name.c_str(),
param_array.borrowReference());
env.throwIfFaultOccurred();
return XmlRpcValue(result, XmlRpcValue::CONSUME_REFERENCE);
}
//=========================================================================
// XmlRpcGenSrv
//=========================================================================
class XmlRpcGenSrv {
private:
xmlrpc_registry* mRegistry;
xmlrpc_mem_block* alloc (XmlRpcEnv& env, const string& body) const;
public:
XmlRpcGenSrv (int flags);
~XmlRpcGenSrv (void);
xmlrpc_registry* getRegistry (void) const;
XmlRpcGenSrv& addMethod (const string& name,
xmlrpc_method method,
void *data);
XmlRpcGenSrv& addMethod (const string& name,
xmlrpc_method method,
void* data,
const string& signature,
const string& help);
string handle (const string& body) const;
};
inline XmlRpcGenSrv::XmlRpcGenSrv (int flags) {
XmlRpcEnv env;
if (flags == flags){};
mRegistry = xmlrpc_registry_new (env);
env.throwIfFaultOccurred();
}
inline XmlRpcGenSrv::~XmlRpcGenSrv (void) {
xmlrpc_registry_free (mRegistry);
}
inline xmlrpc_registry* XmlRpcGenSrv::getRegistry () const {
return mRegistry;
}
#undef XMLRPC_NO_ASSIGNMENT
// Copyright (C) 2001 by Eric Kidd. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
#endif /* _XMLRPCCPP_H_ */
| 33.2331
| 78
| 0.619696
|
[
"object"
] |
05a9137594bfe3ba2859f400a616efad6e0f7b90
| 2,617
|
h
|
C
|
FormMain.h
|
gcardi/Tabellone
|
c204dd20c6bb59601cca1ebc197690c411b2a0fe
|
[
"MIT"
] | 2
|
2022-01-03T23:40:19.000Z
|
2022-02-18T08:07:22.000Z
|
FormMain.h
|
gcardi/Tabellone
|
c204dd20c6bb59601cca1ebc197690c411b2a0fe
|
[
"MIT"
] | null | null | null |
FormMain.h
|
gcardi/Tabellone
|
c204dd20c6bb59601cca1ebc197690c411b2a0fe
|
[
"MIT"
] | 1
|
2022-01-03T23:40:08.000Z
|
2022-01-03T23:40:08.000Z
|
//---------------------------------------------------------------------------
#ifndef FormMainH
#define FormMainH
//---------------------------------------------------------------------------
#include <FMX.ActnList.hpp>
#include <FMX.Controls.hpp>
#include <FMX.Controls.Presentation.hpp>
#include <FMX.Edit.hpp>
#include <FMX.Layouts.hpp>
#include <FMX.ListBox.hpp>
#include <FMX.Menus.hpp>
#include <FMX.Objects.hpp>
#include <FMX.StdCtrls.hpp>
#include <FMX.Types.hpp>
#include <System.Actions.hpp>
#include <System.Classes.hpp>
#include "FMXFormAppMain.h"
#include <vector>
#include "FormPanel.h"
//---------------------------------------------------------------------------
class TfrmMain : public TfrmPanelAppMain
{
__published: // IDE-managed Components
TTimer *tmrPolling;
TMenuItem *MenuItem1;
TMenuItem *MenuItem2;
TMenuItem *MenuItem3;
TMenuItem *MenuItem4;
TMenuItem *MenuItem5;
TMenuItem *MenuItem6;
TMenuItem *MenuItem7;
TMenuItem *MenuItem9;
TMenuItem *MenuItem10;
TMenuItem *MenuItem11;
TMenuItem *MenuItem12;
TMenuItem *MenuItem13;
TMenuItem *MenuItem16;
TMenuItem *MenuItem17;
TMenuItem *MenuItem18;
TMenuItem *MenuItem19;
TMenuItem *MenuItem34;
TLine *Line1;
TGridLayout *GridLayout1;
TAction *actPanelClear;
TButton *Button4;
TMenuBar *MenuBar1;
void __fastcall FormCloseQuery(TObject *Sender, bool &CanClose);
void __fastcall actPanelClearExecute(TObject *Sender);
void __fastcall actPanelClearUpdate(TObject *Sender);
private: // User declarations
using PanelType = TfrmPanel;
std::unique_ptr<TfrmPanel> panel_;
std::vector<std::unique_ptr<TButton>> btns_;
void BuildButtons();
void DestroyButtons();
void CreatePanel( FMXWinDisplayDev const * Display, bool Clipping,
bool Scaling, bool KeepAspectRatio );
void DestroyPanel();
void __fastcall NumButtonClick( TObject *Sender );
void __fastcall NumberChanged( TObject* Sender, int Num, bool Val );
protected:
virtual void RestoreProperties();
virtual void SaveProperties() const;
virtual void Start();
virtual void Stop();
virtual TfrmPanelBase* GetPanel() { return panel_.get(); }
virtual void Config();
public: // User declarations
using inherited = TfrmPanelAppMain;
__fastcall TfrmMain(TComponent* Owner);
__fastcall ~TfrmMain();
};
//---------------------------------------------------------------------------
extern PACKAGE TfrmMain *frmMain;
//---------------------------------------------------------------------------
#endif
| 29.077778
| 77
| 0.608712
|
[
"vector"
] |
05c65bd84f849fc34f8c3f076c6a24c3798a3971
| 906
|
h
|
C
|
SDLSnake/Snake.h
|
Nismirno/SDLSnake
|
36e4e148ead546aac34e85ccc17fc8ebb735b8c7
|
[
"MIT"
] | null | null | null |
SDLSnake/Snake.h
|
Nismirno/SDLSnake
|
36e4e148ead546aac34e85ccc17fc8ebb735b8c7
|
[
"MIT"
] | null | null | null |
SDLSnake/Snake.h
|
Nismirno/SDLSnake
|
36e4e148ead546aac34e85ccc17fc8ebb735b8c7
|
[
"MIT"
] | null | null | null |
#pragma once
#ifndef _SNAKE_H
#define _SNAKE_H
#include <vector>
#include "Texture.h"
#include "Globals.h"
#include "Timer.h"
#include "SnakePart.h"
class Snake {
public:
// Initialize snake
Snake();
// Deallocate memory
~Snake();
// Handle key presses
void handleEvent(const SDL_Event &e);
// Load texture
void loadHeadTexture(std::string path, SDL_Renderer *renderer);
void loadBodyTexture(std::string path, SDL_Renderer *renderer);
// Render snake
void render(SDL_Renderer *renderer) const;
// Move snake
bool move();
// Spawn head
void spawn(Loc spawnLoc);
// Snake's growth
void growth();
// Get entities
std::vector<SnakePart *> &getEntities();
private:
// Snake textures
Texture m_headTexture;
Texture m_bodyTexture;
// Snake parts
std::vector<SnakePart *> m_parts;
// Movement timer
Timer m_timer;
// Size of snake
int m_size;
};
#endif // !_SNAKE_H
| 14.612903
| 64
| 0.701987
|
[
"render",
"vector"
] |
397e4ea923f3aa8ede166faec5bc50cf07489b63
| 58,112
|
h
|
C
|
FK/Model.h
|
rita0222/FK
|
bc5786a5da0dd732e2f411c1a953b331323ee432
|
[
"BSD-3-Clause"
] | 4
|
2020-05-15T03:43:53.000Z
|
2021-06-05T16:21:31.000Z
|
FK/Model.h
|
rita0222/FK
|
bc5786a5da0dd732e2f411c1a953b331323ee432
|
[
"BSD-3-Clause"
] | 1
|
2020-05-19T09:27:16.000Z
|
2020-05-21T02:12:54.000Z
|
FK/Model.h
|
rita0222/FK
|
bc5786a5da0dd732e2f411c1a953b331323ee432
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef __FK_MODEL_HEADER__
#define __FK_MODEL_HEADER__
#ifndef FK_OLD_NONSUPPORT
//#define FK_OLD_NONSUPPORT
#endif
#include <FK/Boundary.h>
#include <FK/Palette.h>
#include <FK/RenderState.h>
#include <FK/Angle.h>
#include <FK/IndexFace.h>
#include <FK/Texture.h>
#include <FK/Tree.h>
#include <memory>
#include <functional>
namespace FK {
class fk_Material;
class fk_Shape;
class fk_TreeData;
class fk_Color;
class fk_ShaderBinder;
using fk_funcSet = std::tuple<unsigned int, std::function<void(void)> >;
//! 描画優先モードを表す列挙型
enum class fk_ElementMode {
NONE, //!< 描画しない
MODEL, //!< モデル設定優先
ELEMENT //!< 形状個別要素設定優先
};
//! シェーディングモードを表す列挙型
enum class fk_ShadingMode {
GOURAUD = 0, //!< グーローシェーディング
PHONG, //!< フォンシェーディング
NUM //!< シェーディングモード種類数
};
//! モデルを生成、管理するクラス
/*!
* このクラスは、「モデル」を制御する機能を提供します。
* FK における「モデル」とは、位置や方向を持ったオブジェクトのことを指します。
* 利用者は、
* このクラスを通じてカメラを含むオブジェクトの位置や姿勢を制御していきます。
* 従って、このクラスは FK システムにおいて最も中心的な存在であると言えます。
* 位置や姿勢を制御するための関数の多くは、
* fk_MatrixAdmin クラスから継承しています。
* (ただし、後述する「親子関係」に関連する機能は本クラス自体が持っています。)
* fk_MatrixAdmin クラスの説明も合わせて参照して下さい。
*
* FK において、モデルと形状は別の存在として扱います。
* 形状は別のクラスで作成しておき、
* モデルに対して形状をリンクするという考え方です。
* このような設計になっている利点は、
* まず第1に1つのモデルが複数の形状を使い分けられるということがあります。
* 第2に、1つの形状を複数のモデルで共有することでメモリ利用量を削減できます。
* 形状については fk_Shape クラスおよびその派生クラスを参照して下さい。
*
* 位置や姿勢の制御と共に、このクラスの重要な機能の1つが「親子関係」です。
* あるモデルを別のモデルに「子モデル」として登録したとします。
* 親モデルの位置や姿勢を制御すると、
* 子モデルの形状は親モデル内の形状と同じように追従するようになります。
* 例えば、車を車体モデルとタイヤモデルで別々に作成し、
* タイヤモデルを車体モデルの子モデルとして登録しておけば、
* 車体モデルの位置移動にあわせてタイヤモデルも位置関係を維持しながら
* 一緒に移動します。
* マテリアルや頂点色、稜線色については、
* 何も設定しない場合は親モデルの設定が用いられます。
* それぞれのモデルにマテリアルや色属性を設定した場合、
* そのモデルについては個々の設定が利用されるようになります。
*
* また、モデル同士の干渉判定や衝突判定を検出することができます。
* 干渉・衝突判定を行うには、
* まず「境界ボリューム」と呼ばれるモデルを覆う領域を設定します。
* その後、その境界ボリューム同士が干渉部分や衝突時間の検出を行うことで実現します。
* 本マニュアルにおいて、「干渉判定」と「衝突判定」は以下のような意味を持ちます。
* - 干渉判定: \n
* ある時点において、モデル同士に干渉部分があるかどうかを判定すること。
* - 衝突判定: \n
* 2つのモデルが時刻 t0 から t1 まで等速度直線運動をしていたと仮定した場合に、
* 途中で衝突が起こったかどうかを判定すること。
*
* 本クラスのメンバ関数では、以下のような機能を提供します。
* - setShape() にて形状を設定した後に自動的に境界ボリュームのサイズを設定する機能。
* - 干渉判定や衝突判定を行う機能。
* - 登録しておいたモデルと干渉した場合に自動的に停止する機能。
*
* 干渉判定は現在すべての種類の境界ボリュームで対応していますが、
* 同じ種類同士である必要があります。
* 衝突判定については、現在は境界球のみで対応しています。
* 境界ボリュームの種類に関する解説や、適用する境界ボリュームの選択については
* fk_Boundary クラスのリファレンスを参照して下さい。
*
* \sa fk_MatrixAdmin, fk_Boundary, fk_Shape, fk_Scene, fk_DisplayLink
*/
class fk_Model : public fk_Boundary {
#ifndef FK_DOXYGEN_USER_PROCESS
class Member {
public:
fk_Material material;
fk_Color pointColor;
fk_Color lineColor;
fk_Color curveColor;
fk_Shape *shape;
fk_Model *parentModel;
fk_TreeData *treeData;
fk_Draw drawMode;
fk_ElementMode elemMode;
fk_BlendMode blendMode;
fk_BlendFactor srcFactor;
fk_BlendFactor dstFactor;
fk_DepthMode depthMode;
double pointSize;
bool smoothFlag;
bool reverseFlag;
bool treeFlag;
unsigned int modelID;
bool treeDelMode;
fk_TexMode texMode;
fk_ShadingMode shadingMode;
std::unique_ptr<fk_HVector> snapPos;
std::unique_ptr<fk_HVector> snapInhPos;
std::unique_ptr<fk_Angle> snapAngle;
bool snapFlag;
bool interMode;
bool interStatus;
bool interStopMode;
std::list<fk_Model *> interList;
fk_ShaderBinder *shader;
bool shadowEffectMode;
bool shadowDrawMode;
bool fogMode;
Member(void);
};
#endif
public:
//! コンストラクタ
/*!
* \param[in] shape
* 形状インスタンスのポインタ。
* nullptr を代入した場合や引数を省略した場合は、
* 初期形状が無い状態になります。
*/
fk_Model(fk_Shape *shape = nullptr);
//! デストラクタ
virtual ~fk_Model();
//! ID参照関数
/*!
* モデルの固有IDを取得します。
* IDの最小値は 1 で、
* 同一プロセス中では同じ ID が別のモデルに割り振られることはありません。
*
* \return 固有モデルID
*/
unsigned int getID(void) const;
//! \name 回転制御関数
///@{
//! グローバル座標系座標軸回転関数1
/*!
* モデルの位置を、グローバル座標系によって回転した場所に移動します。
* 回転軸は、origin を通り、
* axis で指定した座標軸に平行な直線となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は位置のみを回転させるもので、姿勢は回転しません。
* 姿勢の回転も伴いたい場合は glRotateWithVec() を利用して下さい。
* ローカル座標系で回転移動を行いたい場合は loRotate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ fk_MatrixAdmin::glRotate_(fk_Vector &, fk_Axis, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] origin
* グローバル座標系での回転軸上の点
*
* \param[in] axis
* 回転軸に平行な軸。fk_X, fk_Y, fk_Z のいずれかになります。
*
* \param[in] theta
* 回転角度(ラジアン)
*
* \return この関数は常に true を返します。
*
* \sa glRotateWithVec(fk_Vector, fk_Axis, double),
* loRotate(fk_Vector, fk_Axis, double),
* fk_MatrixAdmin::glRotate_(fk_Vector &, fk_Axis, double)
*/
bool glRotate(fk_Vector origin, fk_Axis axis, double theta);
//! グローバル座標系座標軸回転関数2
/*!
* モデルの位置を、グローバル座標系によって回転した場所に移動します。
* 回転軸は、(orgX, orgY, orgZ) を通り、
* axis で指定した座標軸に平行な直線となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は位置のみを回転させるもので、姿勢は回転しません。
* 姿勢の回転も伴いたい場合は glRotateWithVec() を利用して下さい。
* ローカル座標系で回転移動を行いたい場合は loRotate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glRotate_(double, double, double, fk_Axis, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] orgX グローバル座標系での回転軸上の点のx成分
* \param[in] orgY グローバル座標系での回転軸上の点のy成分
* \param[in] orgZ グローバル座標系での回転軸上の点のz成分
*
* \param[in] axis
* 回転軸に平行な軸。fk_X, fk_Y, fk_Z のいずれかになります。
*
* \param[in] theta 回転角度(ラジアン)
*
* \return この関数は常に true を返します。
*
* \sa glRotateWithVec(double, double, double, fk_Axis, double),
* loRotate(double, double, double, fk_Axis, double),
* fk_MatrixAdmin::glRotate_(double, double, double, fk_Axis, double)
*/
bool glRotate(double orgX, double orgY, double orgZ, fk_Axis axis, double theta);
//! グローバル座標系任意軸回転関数1
/*!
* モデルの位置を、グローバル座標系によって回転した場所に移動します。
* 回転軸は、A と B を通る軸となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は位置のみを回転させるもので、姿勢は回転しません。
* 姿勢の回転も伴いたい場合は glRotateWithVec() を利用して下さい。
* ローカル座標系で回転移動を行いたい場合は loRotate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glRotate_(fk_Vector &, fk_Vector &, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] A 回転軸上の1点。B と一致してはいけません。
* \param[in] B 回転軸上の1点。A と一致してはいけません。
* \param[in] theta 回転角度(ラジアン)
*
* \return
* 回転が成功した場合 true を返します。
* A と B が同一位置ベクトルであった場合、
* 回転せずに false を返します。
*
* \sa glRotateWithVec(fk_Vector, fk_Vector, double),
* loRotate(fk_Vector, fk_Vector, double),
* fk_MatrixAdmin::glRotate_(fk_Vector &, fk_Vector &, double)
*/
bool glRotate(fk_Vector A, fk_Vector B, double theta);
//! グローバル座標系任意軸回転関数2
/*!
* モデルの位置を、グローバル座標系によって回転した場所に移動します。
* 回転軸は、(Ax, Ay, Az) と (Bx, By, Bz) を通る軸となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は位置のみを回転させるもので、姿勢は回転しません。
* 姿勢の回転も伴いたい場合は glRotateWithVec() を利用して下さい。
* ローカル座標系で回転移動を行いたい場合は loRotate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glRotate_(double, double, double, double, double, double, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] Ax 回転軸上の1点 A の x 成分
* \param[in] Ay 回転軸上の1点 A の y 成分
* \param[in] Az 回転軸上の1点 A の z 成分
* \param[in] Bx 回転軸上の1点 B の x 成分
* \param[in] By 回転軸上の1点 B の y 成分
* \param[in] Bz 回転軸上の1点 B の z 成分
* \param[in] theta 回転角度(ラジアン)
*
* \return
* 回転が成功した場合 true を返します。
* A と B が同一位置ベクトルであった場合、
* 回転せずに false を返します。
*
* \sa glRotateWithVec(double, double, double, double, double, double, double),
* loRotate(double, double, double, double, double, double, double),
* fk_MatrixAdmin::glRotate_(double, double, double, double, double, double, double)
*/
bool glRotate(double Ax, double Ay, double Az,
double Bx, double By, double Bz, double theta);
//! ローカル座標系座標軸回転関数1
/*!
* モデルの位置を、ローカル座標系によって回転した場所に移動します。
* 回転軸は(ローカル座標系における) origin を通り、
* axis で指定した (ローカル座標系における) 座標軸に平行な直線となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は位置のみを回転させるもので、姿勢は回転しません。
* 姿勢の回転も伴いたい場合は loRotateWithVec() を利用して下さい。
* グローバル座標系で回転移動を行いたい場合は glRotate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loRotate_(fk_Vector &, fk_Axis, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] origin
* ローカル座標系での回転軸上の点
*
* \param[in] axis
* 回転軸に平行なローカル座標系上の軸。
* fk_X, fk_Y, fk_Z のいずれかになります。
*
* \param[in] theta
* 回転角度(ラジアン)
*
* \return この関数は常に true を返します。
*
* \sa glRotate(fk_Vector, fk_Axis, double),
* loRotateWithVec(fk_Vector, fk_Axis, double),
* fk_MatrixAdmin::loRotate_(fk_Vector &, fk_Axis, double)
*/
bool loRotate(fk_Vector origin, fk_Axis axis, double theta);
//! ローカル座標系座標軸回転関数2
/*!
* モデルの位置を、ローカル座標系によって回転した場所に移動します。
* 回転軸は(ローカル座標系における) (orgX, orgY, orgZ) を通り、
* axis で指定した (ローカル座標系における) 座標軸に平行な直線となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は位置のみを回転させるもので、姿勢は回転しません。
* 姿勢の回転も伴いたい場合は loRotateWithVec() を利用して下さい。
* グローバル座標系で回転移動を行いたい場合は glRotate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loRotate_(double, double, double, fk_Axis, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] orgX ローカル座標系での回転軸上の点のx成分
* \param[in] orgY ローカル座標系での回転軸上の点のy成分
* \param[in] orgZ ローカル座標系での回転軸上の点のz成分
*
* \param[in] axis
* 回転軸に平行なローカル座標系上の軸。
* fk_X, fk_Y, fk_Z のいずれかになります。
*
* \param[in] theta 回転角度(ラジアン)
*
* \return この関数は常に true を返します。
*
* \sa glRotate(double, double, double, fk_Axis, double),
* loRotateWithVec(double, double, double, fk_Axis, double),
* fk_MatrixAdmin::loRotate_(double, double, double, fk_Axis, double)
*/
bool loRotate(double orgX, double orgY, double orgZ, fk_Axis axis, double theta);
//! ローカル座標系任意軸回転関数1
/*!
* モデルの位置を、ローカル座標系によって回転した場所に移動します。
* 回転軸は、(ローカル座標系における) A と B を通る軸となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は位置のみを回転させるもので、姿勢は回転しません。
* 姿勢の回転も伴いたい場合は loRotateWithVec() を利用して下さい。
* グローバル座標系で回転移動を行いたい場合は glRotate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loRotate_(fk_Vector &, fk_Vector &, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] A
* ローカル座標系における回転軸上の1点。B と一致してはいけません。
*
* \param[in] B
* ローカル座標系における回転軸上の1点。A と一致してはいけません。
*
* \param[in] theta 回転角度(ラジアン)
*
* \return
* 回転が成功した場合 true を返します。
* A と B が同一位置ベクトルであった場合、
* 回転せずに false を返します。
*
* \sa glRotateWithVec(fk_Vector, fk_Vector, double),
* loRotate(fk_Vector, fk_Vector, double),
* fk_MatrixAdmin::loRotate_(fk_Vector &, fk_Vector &, double)
*/
bool loRotate(fk_Vector A, fk_Vector B, double theta);
//! ローカル座標系任意軸回転関数2
/*!
* モデルの位置を、ローカル座標系によって回転した場所に移動します。
* 回転軸は、(ローカル座標系における)
* (Ax, Ay, Az) と (Bx, By, Bz) を通る軸となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は位置のみを回転させるもので、姿勢は回転しません。
* 姿勢の回転も伴いたい場合は loRotateWithVec() を利用して下さい。
* グローバル座標系で回転移動を行いたい場合は glRotate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loRotate_(double, double, double, double, double, double, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] Ax
* ローカル座標系における回転軸上の1点 A の x 成分
*
* \param[in] Ay
* ローカル座標系における回転軸上の1点 A の y 成分
*
* \param[in] Az
* ローカル座標系における回転軸上の1点 A の z 成分
*
* \param[in] Bx
* ローカル座標系における回転軸上の1点 B の x 成分
*
* \param[in] By
* ローカル座標系における回転軸上の1点 B の y 成分
*
* \param[in] Bz
* ローカル座標系における回転軸上の1点 B の z 成分
*
* \param[in] theta 回転角度(ラジアン)
*
* \return
* 回転が成功した場合 true を返します。
* A と B が同一位置ベクトルであった場合、
* 回転せずに false を返します。
*
* \sa glRotateWithVec(double, double, double, double, double, double, double),
* loRotate(double, double, double, double, double, double, double),
* fk_MatrixAdmin::loRotate_(double, double, double, double, double, double, double)
*/
bool loRotate(double Ax, double Ay, double Az,
double Bx, double By, double Bz, double theta);
//! グローバル座標系座標軸回転(姿勢付き)関数1
/*!
* モデルの位置を、グローバル座標系によって回転した場所に移動します。
* 回転軸は、origin を通り、
* axis で指定した座標軸に平行な直線となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は、回転の際に姿勢も回転していきます。
* 位置のみの回転を行いたい場合は glRotate() を利用して下さい。
* ローカル座標系で回転移動(姿勢付き)を行いたい場合は、
* loRotateWithVec() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glRotateWithVec_(fk_Vector &, fk_Axis, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] origin グローバル座標系での回転軸上の点
*
* \param[in] axis
* 回転軸に平行な軸。fk_X, fk_Y, fk_Z のいずれかになります。
*
* \param[in] theta 回転角度(ラジアン)
*
* \return この関数は常に true を返します。
*
* \sa glRotate(fk_Vector, fk_Axis, double),
* loRotateWithVec(fk_Vector, fk_Axis, double),
* fk_MatrixAdmin::glRotateWithVec_(fk_Vector &, fk_Axis, double)
*/
bool glRotateWithVec(fk_Vector origin, fk_Axis axis, double theta);
//! グローバル座標系座標軸回転(姿勢付き)関数2
/*!
* モデルの位置を、グローバル座標系によって回転した場所に移動します。
* 回転軸は、(orgX, orgY, orgZ) を通り、
* axis で指定した座標軸に平行な直線となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は、回転の際に姿勢も回転していきます。
* 位置のみの回転を行いたい場合は glRotate() を利用して下さい。
* ローカル座標系で回転移動(姿勢付き)を行いたい場合は、
* loRotateWithVec() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glRotateWithVec_(double, double, double, fk_Axis, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] orgX グローバル座標系での回転軸上の点のx成分
* \param[in] orgY グローバル座標系での回転軸上の点のy成分
* \param[in] orgZ グローバル座標系での回転軸上の点のz成分
*
* \param[in] axis
* 回転軸に平行な軸。fk_X, fk_Y, fk_Z のいずれかになります。
*
* \param[in] theta 回転角度(ラジアン)
*
* \return この関数は常に true を返します。
*
* \sa glRotate(double, double, double, fk_Axis, double),
* loRotateWithVec(double, double, double, fk_Axis, double),
* fk_MatrixAdmin::glRotateWithVec_(double, double, double, fk_Axis, double)
*/
bool glRotateWithVec(double orgX, double orgY, double orgZ,
fk_Axis axis, double theta);
//! グローバル座標系任意軸回転(姿勢付き)関数1
/*!
* モデルの位置を、グローバル座標系によって回転した場所に移動します。
* 回転軸は、A と B を通る軸となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は、回転の際に姿勢も回転していきます。
* 位置のみの回転を行いたい場合は glRotate() を利用して下さい。
* ローカル座標系で回転移動(姿勢付き)を行いたい場合は、
* loRotateWithVec() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glRotateWithVec_(fk_Vector &, fk_Vector &, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] A 回転軸上の1点。B と一致してはいけません。
* \param[in] B 回転軸上の1点。A と一致してはいけません。
* \param[in] theta 回転角度(ラジアン)
*
* \return
* 回転が成功した場合 true を返します。
* A と B が同一位置ベクトルであった場合、
* 回転せずに false を返します。
*
* \sa glRotate(fk_Vector, fk_Vector, double),
* loRotateWithVec(fk_Vector, fk_Vector, double),
* fk_MatrixAdmin::glRotateWithVec_(fk_Vector &, fk_Vector &, double)
*/
bool glRotateWithVec(fk_Vector A, fk_Vector B, double theta);
//! グローバル座標系任意軸回転(姿勢付き)関数2
/*!
* モデルの位置を、グローバル座標系によって回転した場所に移動します。
* 回転軸は、(Ax, Ay, Az) と (Bx, By, Bz) を通る軸となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は、回転の際に姿勢も回転していきます。
* 位置のみの回転を行いたい場合は glRotate() を利用して下さい。
* ローカル座標系で回転移動(姿勢付き)を行いたい場合は、
* loRotateWithVec() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、同機能を持つ
* fk_MatrixAdmin::glRotateWithVec_(double, double, double, double, double, double, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] Ax 回転軸上の1点 A の x 成分
* \param[in] Ay 回転軸上の1点 A の y 成分
* \param[in] Az 回転軸上の1点 A の z 成分
* \param[in] Bx 回転軸上の1点 B の x 成分
* \param[in] By 回転軸上の1点 B の y 成分
* \param[in] Bz 回転軸上の1点 B の z 成分
* \param[in] theta 回転角度(ラジアン)
*
* \return
* 回転が成功した場合 true を返します。
* A と B が同一位置ベクトルであった場合、
* 回転せずに false を返します。
*
* \sa glRotate(double, double, double, double, double, double, double),
* loRotateWithVec(double, double, double, double, double, double, double),
* fk_MatrixAdmin::glRotateWithVec_(double, double, double, double, double, double, double)
*/
bool glRotateWithVec(double Ax, double Ay, double Az,
double Bx, double By, double Bz, double theta);
//! ローカル座標系座標軸回転(姿勢付き)関数1
/*!
* モデルの位置を、ローカル座標系によって回転した場所に移動します。
* 回転軸は(ローカル座標系における) origin を通り、
* axis で指定した (ローカル座標系における) 座標軸に平行な直線となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は、回転の際に姿勢も回転していきます。
* 位置のみの回転を行いたい場合は loRotate() を利用して下さい。
* グローバル座標系で回転移動(姿勢付き)を行いたい場合は、
* glRotateWithVec() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loRotateWithVec_(fk_Vector &, fk_Axis, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] origin ローカル座標系での回転軸上の点
*
* \param[in] axis
* 回転軸に平行なローカル座標系上の軸。
* fk_X, fk_Y, fk_Z のいずれかになります。
*
* \param[in] theta 回転角度(ラジアン)
*
* \return この関数は常に true を返します。
*
* \sa loRotate(fk_Vector, fk_Axis, double),
* glRotateWithVec(fk_Vector, fk_Axis, double),
* fk_MatrixAdmin::loRotateWithVec_(fk_Vector &, fk_Axis, double)
*/
bool loRotateWithVec(fk_Vector origin, fk_Axis axis, double theta);
//! ローカル座標系座標軸回転(姿勢付き)関数2
/*!
* モデルの位置を、ローカル座標系によって回転した場所に移動します。
* 回転軸は(ローカル座標系における) (orgX, orgY, orgZ) を通り、
* axis で指定した (ローカル座標系における) 座標軸に平行な直線となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は、回転の際に姿勢も回転していきます。
* 位置のみの回転を行いたい場合は loRotate() を利用して下さい。
* グローバル座標系で回転移動(姿勢付き)を行いたい場合は、
* glRotateWithVec() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loRotateWithVec_(double, double, double, fk_Axis, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] orgX ローカル座標系での回転軸上の点のx成分
* \param[in] orgY ローカル座標系での回転軸上の点のy成分
* \param[in] orgZ ローカル座標系での回転軸上の点のz成分
*
* \param[in] axis
* 回転軸に平行なローカル座標系上の軸。
* fk_X, fk_Y, fk_Z のいずれかになります。
*
* \param[in] theta 回転角度(ラジアン)
*
* \return この関数は常に true を返します。
*
* \sa loRotate(double, double, double, fk_Axis, double),
* glRotateWithVec(double, double, double, fk_Axis, double),
* fk_MatrixAdmin::loRotateWithVec_(double, double, double, fk_Axis, double)
*/
bool loRotateWithVec(double orgX, double orgY, double orgZ,
fk_Axis axis, double theta);
//! ローカル座標系任意軸回転(姿勢付き)関数1
/*!
* モデルの位置を、ローカル座標系によって回転した場所に移動します。
* 回転軸は、(ローカル座標系における) A と B を通る軸となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は、回転の際に姿勢も回転していきます。
* 位置のみの回転を行いたい場合は loRotate() を利用して下さい。
* グローバル座標系で回転移動(姿勢付き)を行いたい場合は、
* glRotateWithVec() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loRotateWithVec_(fk_Vector &, fk_Vector &, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] A
* ローカル座標系における回転軸上の1点。B と一致してはいけません。
*
* \param[in] B
* ローカル座標系における回転軸上の1点。A と一致してはいけません。
*
* \param[in] theta 回転角度(ラジアン)
*
* \return
* 回転が成功した場合 true を返します。
* A と B が同一位置ベクトルであった場合、
* 回転せずに false を返します。
*
* \sa glRotateWithVec(fk_Vector, fk_Vector, double)
* loRotate(fk_Vector, fk_Vector, double),
* fk_MatrixAdmin::loRotateWithVec_(fk_Vector &, fk_Vector &, double)
*/
bool loRotateWithVec(fk_Vector A, fk_Vector B, double theta);
//! ローカル座標系任意軸回転(姿勢付き)関数2
/*!
* モデルの位置を、ローカル座標系によって回転した場所に移動します。
* 回転軸は、(ローカル座標系における)
* (Ax, Ay, Az) と (Bx, By, Bz) を通る軸となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は、回転の際に姿勢も回転していきます。
* 位置のみの回転を行いたい場合は loRotate() を利用して下さい。
* グローバル座標系で回転移動(姿勢付き)を行いたい場合は、
* glRotateWithVec() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、同機能を持つ
* fk_MatrixAdmin::loRotateWithVec_(double, double, double, double, double, double, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] Ax
* ローカル座標系における回転軸上の1点 A の x 成分
*
* \param[in] Ay
* ローカル座標系における回転軸上の1点 A の y 成分
*
* \param[in] Az
* ローカル座標系における回転軸上の1点 A の z 成分
*
* \param[in] Bx
* ローカル座標系における回転軸上の1点 B の x 成分
*
* \param[in] By
* ローカル座標系における回転軸上の1点 B の y 成分
*
* \param[in] Bz
* ローカル座標系における回転軸上の1点 B の z 成分
*
* \param[in] theta 回転角度(ラジアン)
*
* \return
* 回転が成功した場合 true を返します。
* A と B が同一位置ベクトルであった場合、
* 回転せずに false を返します。
*
* \sa glRotateWithVec(double, double, double, double, double, double, double),
* loRotate(double, double, double, double, double, double, double),
* fk_MatrixAdmin::loRotateWithVec_(double, double, double, double, double, double, double)
*/
bool loRotateWithVec(double Ax, double Ay, double Az,
double Bx, double By, double Bz, double theta);
///@}
//! \name 位置制御関数
///@{
//! グローバル座標系平行移動関数1
/*!
* モデルを、クローバル座標系によって平行移動した位置に移動します。
* 平行移動量はベクトルで指定します。
*
* ローカル座標系による平行移動量の指定を行いたい場合は、
* loTranslate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glTranslate_(fk_Vector &)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] v 平行移動量ベクトル
*
* \return この関数は常に true を返します。
*
* \sa loTranslate(fk_Vector), fk_MatrixAdmin::glTranslate_(fk_Vector &)
*/
bool glTranslate(fk_Vector v);
//! グローバル座標系平行移動関数2
/*!
* モデルを、クローバル座標系によって平行移動した位置に移動します。
* 平行移動量はベクトルの成分を意味する3個の実数で指定します。
*
* ローカル座標系による平行移動量の指定を行いたい場合は、
* loTranslate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glTranslate_(double, double, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] x 平行移動量ベクトルのx成分
* \param[in] y 平行移動量ベクトルのy成分
* \param[in] z 平行移動量ベクトルのz成分
*
* \return この関数は常に true を返します。
*
* \sa loTranslate(double, double, double),
* fk_MatrixAdmin::glTranslate_(double, double, double)
*/
bool glTranslate(double x, double y, double z);
//! ローカル座標系平行移動関数1
/*!
* モデルを、ローカル座標系によって平行移動した位置に移動します。
* 平行移動量はベクトルで指定します。
*
* グローバル座標系による平行移動量の指定を行いたい場合は、
* glTranslate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loTranslate_(fk_Vector &)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] v 平行移動量ベクトル
*
* \return この関数は常に true を返します。
*
* \sa glTranslate(fk_Vector), glMoveTo(fk_Vector),
* fk_MatrixAdmin::loTranslate_(fk_Vector &)
*/
bool loTranslate(fk_Vector v);
//! ローカル座標系平行移動関数2
/*!
* モデルを、ローカル座標系によって平行移動した位置に移動します。
* 平行移動量はベクトルの成分を意味する3個の実数で指定します。
*
* グローバル座標系による平行移動量の指定を行いたい場合は、
* glTranslate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loTranslate_(double, double, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] x 平行移動量ベクトルのx成分
* \param[in] y 平行移動量ベクトルのy成分
* \param[in] z 平行移動量ベクトルのz成分
*
* \return この関数は常に true を返します。
*
* \sa glTranslate(double, double, double), glMoveTo(double, double, double),
* fk_MatrixAdmin::loTranslate_(double, double, double)
*/
bool loTranslate(double x, double y, double z);
//! グローバル座標系位置指定関数1
/*!
* モデルの位置を、指定した位置ベクトルに移動します。
* 位置はベクトルで指定します。
*
* glMoveTo() 関数に対応するローカル座標系関数
* 「loMoveTo()」関数は存在しません。
* これは、loMoveTo() 関数はその意味的に
* loTranslate() とまったく同一の挙動となるためです。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glMoveTo_(fk_Vector &)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] p 移動先位置ベクトル
*
* \return この関数は常に true を返します。
*
* \sa glTranslate(fk_Vector), loTranslate(fk_Vector),
* fk_MatrixAdmin::glMoveTo_(fk_Vector &)
*/
bool glMoveTo(fk_Vector p);
//! グローバル座標系位置指定関数2
/*!
* モデルの位置を、指定した位置ベクトルに移動します。
* 位置はベクトルの成分を意味する3個の実数で指定します。
*
* glMoveTo() 関数に対応するローカル座標系関数
* 「loMoveTo()」関数は存在しません。
* これは、loMoveTo() 関数はその意味的に
* loTranslate() とまったく同一の挙動となるためです。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glMoveTo_(double, double, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] x 移動先位置ベクトルのx成分
* \param[in] y 移動先位置ベクトルのy成分
* \param[in] z 移動先位置ベクトルのz成分
*
* \return この関数は常に true を返します。
*
* \sa glTranslate(double, double, double), loTranslate(double, double, double),
* fk_MatrixAdmin::glMoveTo_(double, double, double)
*/
bool glMoveTo(double x, double y, double z);
///@}
//! \name 形状データ制御関数
///@{
//! 形状設定関数
/*!
* モデルの形状を設定します。
* 形状は、 fk_Shape クラスの派生クラスであれば設定可能です。
* なお、呼ぶ前に形状が設定されていた場合、前の設定は破棄されます。
*
* 設定した形状インスタンスは、モデルに設定した状態で解放しないようにしてください。
* もし解放された場合、プログラムが誤動作を起こします。
*
* \param[in] shape 形状インスタンスのポインタ
*/
void setShape(fk_Shape *shape);
//! 形状参照関数
/*!
* 現在設定されている形状を取得します。
* 形状が設定されていない場合は nullptr を返します。
*
* \return 形状インスタンスのポインタ
*/
fk_Shape * getShape(void) const;
///@}
//! \name マテリアル属性設定関数
///@{
//! マテリアル設定関数
/*!
* モデルの基本マテリアルを設定します。
* マテリアルに関しての詳細は、
* fk_Material の説明およびユーザーズマニュアルを参照して下さい。
*
* \note
* 稜線の色は setLineColor(),
* 頂点の色は setPointColor(),
* 曲線の色は setCurveColor() を利用して設定して下さい。
* 個別位相要素のマテリアルとの制御については、
* setMaterialMode() を参照して下さい。
* テクスチャを描画する際には、テクスチャモードによって混合の仕方が異なりますので、
* fk_Texture::setTextureMode() を参照して下さい。
*
* \param[in] mat マテリアル
*
* \sa fk_Material, setLineColor(), setPointColor(), fk_Texture::setTextureMode()
*/
void setMaterial(const fk_Material &mat);
//! 頂点色設定関数1
/*!
* モデルの頂点色を設定します。
* 頂点は、光源による陰影の影響はなく、常に設定色で表示されます。
*
* \param[in] col 頂点色のポインタ
*
* \sa fk_Color
*/
void setPointColor(fk_Color *col);
//! 頂点色設定関数2
/*!
* モデルの頂点色を設定します。
* 頂点は、光源による陰影の影響はなく、常に設定色で表示されます。
* 各色要素は 0 から 1 までの値を取ります。
* それ以外の値が与えられた場合、0 以下なら 0 に、1 以上なら 1 に丸められます。
*
* \param[in] r 頂点色の赤要素
* \param[in] g 頂点色の緑要素
* \param[in] b 頂点色の青要素
*/
void setPointColor(float r, float g, float b);
//! 稜線色設定関数1
/*!
* モデルの稜線色を設定します。
* 稜線は、光源による陰影の影響はなく、常に設定色で表示されます。
*
* \param[in] col 稜線色のポインタ
*
* \sa fk_Color
*/
void setLineColor(fk_Color *col);
//! 稜線色設定関数2
/*!
* モデルの稜線色を設定します。
* 稜線は、光源による陰影の影響はなく、常に設定色で表示されます。
* 各色要素は 0 から 1 までの値を取ります。
* それ以外の値が与えられた場合、0 以下なら 0 に、1 以上なら 1 に丸められます。
*
* \param[in] r 稜線色の赤要素
* \param[in] g 稜線色の緑要素
* \param[in] b 稜線色の青要素
*/
void setLineColor(float r, float g, float b);
//! 曲線色設定関数1
/*!
* モデルの曲線色を設定します。
* 曲線は、光源による陰影の影響はなく、常に設定色で表示されます。
*
* \param[in] col 曲線色のポインタ
*
* \sa fk_Color
*/
void setCurveColor(fk_Color *col);
//! 曲線色設定関数2
/*!
* モデルの曲線色を設定します。
* 曲線は、光源による陰影の影響はなく、常に設定色で表示されます。
* 各色要素は 0 から 1 までの値を取ります。
* それ以外の値が与えられた場合、0 以下なら 0 に、1 以上なら 1 に丸められます。
*
* \param[in] r 曲線色の赤要素
* \param[in] g 曲線色の緑要素
* \param[in] b 曲線色の青要素
*/
void setCurveColor(float r, float g, float b);
///@}
//! \name マテリアル属性参照関数
///@{
//! マテリアル参照関数
/*!
* 現在モデルに設定されている基本マテリアルを参照します。
*
* \return 基本マテリアルのポインタ
*
* \sa fk_Material, setMaterial()
*/
fk_Material * getMaterial(void);
//! 頂点色参照関数
/*!
* 現在モデルに設定されている頂点色を参照します。
*
* \return 頂点色のポインタ
*
* \sa fk_Color, setPointColor()
*/
fk_Color * getPointColor(void);
//! 稜線色参照関数
/*!
* 現在モデルに設定されている稜線色を参照します。
*
* \return 稜線色のポインタ
*
* \sa fk_Color, setLineColor()
*/
fk_Color * getLineColor(void);
//! 曲線色参照関数
/*!
* 現在モデルに設定されている曲線色を参照します。
*
* \return 曲線色のポインタ
*
* \sa fk_Color, setCurveColor()
*/
fk_Color * getCurveColor(void);
///@}
//! \name 描画属性制御関数
///@{
//! 描画モード設定関数
/*!
* モデルの描画モードを設定します。
* 描画モードとは、
* 面、稜線、頂点のそれぞれを描画するかどうかを制御するものです。
* 描画モード種類は以下のとおりです。
* - fk_Draw::NONE: 何も描画しません。
* - fk_Draw::POINT: 頂点を描画します。
* 曲線・曲面の場合は制御点を描画します。
* - fk_Draw::LINE: 稜線を描画します。
* 曲線・曲面の場合は制御点を結ぶポリラインを描画します。
* - fk_Draw::FACE: 面の表を描画します。
* - fk_Draw::BACK_FACE: 面の裏を描画します。
* - fk_Draw::FRONTBACK_FACE: 面の表と裏を描画します。
* - fk_Draw::TEXTURE: テクスチャを描画します。
* - fk_Draw::GEOM_LINE: 曲線や、曲面グリッド線を描画します。
* - fk_Draw::GEOM_POINT: 曲線上や曲面上の分割点を描画します。
* - fk_Draw::GEOM_FACE: 曲面を描画します。
* .
* これらの描画モードは、
* ビット論理和を用いて複数のものを同時に指定することが可能です。
* 以下のコードは、頂点、稜線、面の表をすべて描画するように設定します。
*
* fk_Model model;
*
* model.setDrawMode(fk_Draw::POINT | fk_Draw::LINE | fk_Draw::FACE);
*
* \param[in] mode 描画モード
*/
void setDrawMode(const fk_Draw mode);
//! 描画モード参照関数
/*!
* 現在の描画モードを参照します。
*
* \return 描画モード
*
* \sa setDrawMode()
*/
fk_Draw getDrawMode(void) const;
//! 要素モード設定関数
/*!
* 形状表示の際、モデル設定と形状個別要素設定のどちらを採用するかを設定します。
* モードには以下のものがあります。
* - fk_ElementMode::NONE: 何も描画しません。
* - fk_ElementMode::MODEL: モデル設定を優先します。
* - fk_ElementMode::ELEMENT: 形状内の個別要素設定を優先します。
* .
*
* \param[in] mode 設定モード
*/
void setElementMode(const fk_ElementMode mode);
//! 要素モード設定関数
/*!
* 表示の際の優先モードを取得します。
*
* \return 設定モード
*
* \sa setElementMode()
*/
fk_ElementMode getElementMode(void) const;
//! シェーディングモード設定関数
/*!
* 面描画またはテクスチャ描画の際の、
* シェーディングアルゴリズムを設定します。
* グーローシェーディングは、各頂点ごとに発色輝度を計算し、
* 頂点以外の面内部は色値の線形補間によって発色輝度を決定します。
* フォンシェーディングでは、色値ではなく法線ベクトルを補間決定し、
* 面内部の発色は補間法線ベクトルに対し発色輝度を計算します。
* 一般的には、速度重視の場合はグーロー、質重視の場合はフォンを選択します。
* なお、本館数は面またはテクスチャの描画の際のみに関与するものであり、
* 線や点の描画の際には影響を及ぼしません。
*
* \param[in] mode モード
*/
void setShadingMode(fk_ShadingMode mode);
//! シェーディングモード取得関数
/*!
* 表示の差異のシェーディングモードを取得します。
*
* \return モード
*
* \sa setShadingMode()
*/
fk_ShadingMode getShadingMode(void) const;
//! ブレンドモード設定関数
/*!
* テクスチャ画像を伴うモデルを表示する場合、
* 表示色はテクスチャ画像の各画素色と、
* モデルに設定されているマテリアルの両方が関与します。
* この関数は、テクスチャ画像の画素色とモデルのマテリアル色に対し、
* どのような計算式で双方を混合(ブレンド)するかを設定します。
* ここでブレンドモードを設定しても、fk_Scene:setBlendStatus() で
* ブレンドを有効にしていないと実際の描画で有効になりません。
* ブレンドモードの設定は、一般的な設定をプリセットの中から選択するか、
* カスタムモードを選択した上で、入力ピクセルと出力ピクセルに対する係数を
* 個別に指定するかのどちらかによって行います。
*
* \param[in] mode
* ブレンドモードを設定します。与えられる値は以下の8種類です。
* - fk_BlendMode::ALPHA: 通常のアルファブレンドです。初期値です。
* - fk_BlendMode::NEGATIVE: 反転ブレンドです。
* - fk_BlendMode::ADDITION: 加算ブレンドです。
* - fk_BlendMode::SCREEN: アルファ付き加算ブレンドです。
* - fk_BlendMode::LIGHTEN: 入出力ピクセルのうち明るい方を採用するブレンドです。
* - fk_BlendMode::MULTIPLY: 乗算ブレンドです。
* - fk_BlendMode::NONE: ブレンドを行いません。
* fk_Scene 側の設定によらずブレンドを無効にします。
* - fk_BlendMode::CUSTOM: カスタムモードです。第 2,3 引数にて指定した
* 係数を用いた計算式でブレンドします。
*
* \param[in] srcFactor
* 入力ピクセルに対する係数を設定します。
* mode に fk_BlendMode::CUSTOM を指定した場合のみ有効です。
* それ以外のモードでは省略可能です。
* 本関数の仕様は OpenGL 関数の glBlendFunc() に準拠します。
* 詳細は glBlendFunc() の情報を参照して下さい。
* 与えられる値は以下の10種類で、
* それぞれの値に「GL」に置き換えた GLenum 型の値に対応します。
* - fk_BlendFactor::ZERO
* - fk_BlendFactor::ONE
* - fk_BlendFactor::SRC_COLOR
* - fk_BlendFactor::ONE_MINUS_SRC_COLOR
* - fk_BlendFactor::DST_COLOR
* - fk_BlendFactor::ONE_MINUS_DST_COLOR
* - fk_BlendFactor::SRC_ALPHA
* - fk_BlendFactor::ONE_MINUS_SRC_ALPHA
* - fk_BlendFactor::DST_ALPHA
* - fk_BlendFactor::ONE_MINUS_DST_ALPHA
*
* \param[in] dstFactor
* 出力ピクセルに対する係数を設定します。
* mode に fk_BlendFactor::CUSTOM を指定した場合のみ有効です。
* それ以外のモードでは省略可能です。与えられる値は srcFactor と同様です。
*
* \sa getBlendMode(), fk_Scene::setBlendStatus(), fk_Scene::getBlendStatus()
*/
void setBlendMode(const fk_BlendMode mode,
const fk_BlendFactor srcFactor = fk_BlendFactor::SRC_ALPHA,
const fk_BlendFactor dstFactor = fk_BlendFactor::ONE_MINUS_SRC_ALPHA);
//! ブレンドモード参照関数
/*!
* モデルのブレンドモードを取得します。
*
* \param[out] outSrc
* 入力ピクセルにかかる係数の種類を取得します。省略可能です。
* \param[out] outDst
* 出力ピクセルにかかる係数の種類を取得します。省略可能です。
* \return ブレンドモード
*
* \sa setBlendMode()
*/
fk_BlendMode getBlendMode(fk_BlendFactor *outSrc = nullptr,
fk_BlendFactor *outDst = nullptr) const;
//! スムースモード設定関数
/*!
* モデルのスムースモードを設定します。
* スムースモードを有効にすると、
* 形状の隣り合う面同士の法線ベクトルが補間され、
* 擬似的に滑らかな曲面として表示を行うようになります。
*
* \param[in] mode true である場合、スムースモードを有効とします。
* false である場合無効とします。
*/
void setSmoothMode(const bool mode);
//! スムースモード参照関数
/*!
* 現在のモデルのスムースモードを取得します。
*
* \return 有効である場合 true を、無効である場合 false を返します。
*
* \sa setSmoothMode()
*/
bool getSmoothMode(void) const;
//! 描画順序制御関数
/*!
* この関数では、モデルの持つ位相要素の描画順序を制御します。
* モデルの各位相要素が同一平面上にあり、描画順序を逆にしたい場合に用います。
*
* \param[in] mode
* true の場合、モデル内の描画が通常と逆順になります。
* false の場合、順序を通常の状態に戻します。
*/
void setReverseDrawMode(const bool mode);
//! 描画順序参照関数
/*!
* setReverseDrawMode() で設定した描画順序を取得します。
*
* \return 逆順である場合 true を、正順である場合 false を返します。
*
* \sa setReverseDrawMode()
*/
bool getReverseDrawMode(void) const;
//! 前後関係制御関数
/*!
* この関数では、モデルを描画する際の前後関係に関する設定を制御します。
* fk_Scene::entryOverlayModel()でも前後関係を無視した描画はできますが、
* 通常の描画中に前後関係を無視したり、
* 半透明物体が後続の描画の前後関係に作用しないようにするなど、
* 細かな調整を行いたい場合に用います。
*
* \param[in] mode
* 前後関係の処理モードを設定します。与えられる値は以下の4種類です。
* - fk_DepthMode::NO_USE: 前後関係の参照も更新も行わず、常に上書きします。
* - fk_DepthMode::READ: 前後関係を参照してチェックします。
* - fk_DepthMode::WRITE: 前後関係を更新して後続の描画に影響するようにします。
* - fk_DepthMode::READ_AND_WRITE: 前後関係を参照しつつ更新します。
* fk_DepthMode::READ | fk_DepthMode::WRITE と等価です。初期値です。
*/
void setDepthMode(const fk_DepthMode mode);
//! 前後関係参照関数
/*!
* setDepthMode() で設定した前後関係の設定を取得します。
*
* \return 前後関係処理モード
*
* \sa setDepthMode()
*/
fk_DepthMode getDepthMode(void) const;
//! テクスチャモード設定関数
/*!
* テクスチャの描画時における描画色処理モードを設定します。
* これは、ポリゴンに設定されているマテリアルによる発色と、
* テクスチャ画像の色をどのように混成するかを制御するものです。
* それぞれのモードの概要と厳密な計算式を以下に記載します。
* なお、数式中の \f$ C_f \f$ はポリゴン色、
* \f$ C_\alpha \f$ ポリゴンの透明度、
* \f$ T_f \f$ はテクスチャピクセル色、
* \f$ T_\alpha \f$ はテクスチャの透明度を表します。
*
* - fk_TexMode::MODULATE \n
* この設定では、ポリゴンの色とテクスチャの色を積算します。
* そのため、光源による陰影効果が生じます。
* 透明度に関しても積算となります。
* 数式として表すと、色と透明度はそれぞれ
* \f[
* (C_f T_f, \; C_\alpha T_\alpha)
* \f]
* となります。
*
* - fk_TexMode::REPLACE \n
* この設定では、ポリゴンの色は完全に無視され、
* テクスチャのピクセル色がそのまま表示されます。
* そのため、光源による陰影効果が生じません。
* また、テクスチャ画像の透明度はそのまま描画に反映されます。
* 数式として表すと、色と透明度はそれぞれ
* \f[
* (T_f, \; T_\alpha)
* \f]
* となります。
*
* - fk_TexMode::DECAL \n
* この設定では、各ピクセルの透明度に応じて、
* ポリゴン色とピクセル色の混合が行われます。
* 光源による陰影効果は、ピクセルの透明度が低い場合に強くなります。
* 透明度は、ポリゴンの透明度がそのまま適用されます。
* これを数式として表すと、色と透明度はそれぞれ
* \f[
* (C_f (1-T_\alpha) + T_f T_\alpha, \; C_\alpha)
* \f]
* となります。
*
* - fk_TexMode::NONE \n
* この設定では、 fk_Model での設定は無視し、
* fk_Texture::setTextureMode() での設定に従います。
* .
* デフォルトでは fk_TexMode::NONE が設定されています。
* なお、同様の設定は fk_Texture::setTextureMode() でも行うことが可能で、
* fk_Model 側で fk_TexMode::NONE 以外が設定されている場合は
* fk_Model 側の設定が優先されます。
* fk_Model 側で fk_TexMode::NONE が設定されている場合のみ、
* fk_Texture 側での設定が有効となります。
*
* \param[in] mode モード
*
* \sa getTextureMode(), fk_Texture::setTextureMode()
*/
void setTextureMode(fk_TexMode mode);
//! テクスチャモード取得関数
/*!
* 現在のテクスチャモードを取得します。
*
* \return テクスチャモード
*
* \sa setTextureMode()
*/
fk_TexMode getTextureMode(void);
//! 頂点描画サイズ設定関数
/*!
* 頂点の描画サイズを設定します。
* 単位はピクセルです。整数以外も設定可能です。
*
* \param[in] size 頂点描画サイズ
*
* \sa getPointSize(), setLineWidth()
*/
void setPointSize(const double size);
//! 頂点描画サイズ参照関数
/*!
* 頂点の描画サイズを取得します。
*
* \return 頂点描画サイズ
*
* \sa setPointSize()
*/
double getPointSize(void) const;
//! 影投影設定関数
/*!
* このモデルが別モデル(やこのモデル自身)へ影を投影するかどうかの設定を行います。
* この設定を false にすると、シーン全体で影効果が有効であっても、
* 当モデルの影は別モデル(やこのモデル自身)に投影されなくなります。
* デフォルトは true です。
*
* 他モデルの影をこのモデルに投影するかどうかを制御する場合は、
* setShadowDraw() を用いてください。
*
* \param[in] mode true で有効、false で無効となります。
*
* \sa
* setShadowDraw(), getShadowEffect(),
* fk_Scene::setShadowMode(), fk_AppWindow::setShadowMode()
*/
void setShadowEffect(bool mode);
//! 影投影設定参照関数
/*!
* このモデルの影投影設定を参照します。
* 詳細は setShadowEffect() のマニュアルを参照して下さい。
*
* \return 影投影設定。true で有効、false で無効を意味します。
*
* \sa
* setShadowEffect(), getShadowDraw(),
* fk_Scene::setShadowMode(), fk_AppWindow::setShadowMode()
*/
bool getShadowEffect(void);
//! 影表示設定関数
/*!
* 別モデルやこのモデル自身の影を、このモデルに投影するかどうかの設定を行います。
*
* このモデルの影を別のモデル(や自分自身)に投影するかどうかの制御は、
* setShadowEffect() を用いて下さい。
*
* \param[in] mode true で有効、false で無効となります。
*
* \sa
* setShadowEffect(), getShadowDraw(),
* fk_Scene::setShadowMode(), fk_AppWindow::setShadowMode()
*/
void setShadowDraw(bool mode);
//! 影表示設定参照関数
/*!
* このモデルの影表示設定を参照します。
* 詳細は setShadowDraw() のマニュアルを参照して下さい。
*
* \return 影表示設定。true で有効、false で無効を意味します。
*
* \sa
* setShadowDraw(), getShadowEffect(),
* fk_Scene::setShadowMode(), fk_AppWindow::setShadowMode()
*/
bool getShadowDraw(void);
//! 霧効果設定関数
/*!
* このモデルの表示に対し霧効果の有効とするかどうかを設定します。
* デフォルトでは有効となっています。
*
* \param[in] mode true で有効、false で無効となります。
*/
void setFogMode(bool mode);
//! 霧効果設定参照関数
/*!
* 霧効果が有効かどうかを参照します。
*
* \return 有効なら true、無効なら false を返します。
*/
bool getFogMode(void);
///@}
//! \name 座標系情報参照関数
///@{
//! 継承変換行列取得関数
/*!
* モデルの位置と姿勢を表す変換行列を取得します。
* 当モデルに親モデルがあった場合、
* その親モデルの変換行列と当モデルの変換行列の積が返されます。
* 結果として、この関数を用いることでグローバル座標系における
* 当モデルの変換行列を得ることができます。
* 親モデルが設定されていない場合は、
* fk_MatrixAdmin::getMatrix() と結果が同じとなります。
*
* \return モデルの継承変換行列
*
* \sa fk_MatrixAdmin::getMatrix(), getInhInvMatrix()
*/
fk_Matrix getInhMatrix(void) const;
//! 継承逆変換行列取得関数
/*!
* モデルの位置と姿勢を表す変換行列の、逆行列を取得します。
* これは、 getInhMatrix() で得られる行列の逆行列となります。
* 当モデルに親モデルがあった場合、
* その親モデルの逆変換行列と当モデルの逆変換行列の積が返されます。
* 結果として、この関数を用いることでグローバル座標系における
* 当モデルの逆変換行列を得ることができます。
* 親モデルが設定されていない場合は、
* fk_MatrixAdmin::getInvMatrix() と結果が同じとなります。
*
* \return モデルの継承逆変換行列
*
* \sa fk_MatrixAdmin::getInvMatrix(), getInhMatrix()
*/
fk_Matrix getInhInvMatrix(void) const;
//! 継承移動・回転要素変換行列取得関数
/*!
* モデルの持つ変換要素のうち、
* 位置と姿勢のみを反映した、
* すなわち拡大縮小の要素を省いた変換行列を取得します。
* 当モデルに親モデルがあった場合、
* その親モデルの変換行列と当モデルの変換行列の積が返されます。
* その結果として、この関数を用いることでグローバル座標系における
* 当モデルの変換行列を得ることができます。
* 親モデルが設定されていない場合は、
* fk_MatrixAdmin::getBaseMatrix() と結果が同じとなります。
*
* \return モデルの継承移動・回転要素変換行列
*
* \sa fk_MatrixAdmin::getBaseMatrix(), getInhMatrix(), getInhInvBaseMatrix()
*/
fk_OrthoMatrix getInhBaseMatrix(void) const;
//! 継承移動・回転要素逆変換行列取得関数
/*!
* モデルの持つ変換要素のうち、
* 位置と姿勢のみを反映した、
* すなわち拡大縮小の要素を省いた変換行列の逆行列を取得します。
* 当モデルに親モデルがあった場合、
* その親モデルの逆変換行列と当モデルの逆変換行列の積が返されます。
* その結果として、この関数を用いることでグローバル座標系における
* 当モデルの逆変換行列を得ることができます。
* 親モデルが設定されていない場合は、
* fk_MatrixAdmin::getInvBaseMatrix() と結果が同じとなります。
*
* \return モデルの継承移動・回転要素逆変換行列
*
* \sa fk_MatrixAdmin::getInvBaseMatrix(), getInhInvMatrix(), getInhBaseMatrix()
*/
fk_OrthoMatrix getInhInvBaseMatrix(void) const;
//! 継承位置ベクトル参照関数
/*!
* モデルの位置ベクトルを取得します。
* 本関数は、親モデルの有無にかかわらず、グローバル座標系での実際の位置ベクトルを返します。
*
* \return グローバル座標系での位置ベクトル
*
* \sa getInhVec(), getInhUpvec(), getInhAngle(), fk_MatrixAdmin::getPosition()
*/
fk_Vector getInhPosition(void) const;
//! 継承方向ベクトル参照関数
/*!
* モデルの方向ベクトルを取得します。
* 本関数は、親モデルの有無にかかわらず、グローバル座標系での実際の方向ベクトルを返します。
*
* \return グローバル座標系での方向ベクトル
*
* \sa getInhPosition(), getInhUpvec(), getInhAngle(), fk_MatrixAdmin::getVec()
*/
fk_Vector getInhVec(void) const;
//! 継承アップベクトル参照関数
/*!
* モデルのアップベクトルを取得します。
* 本関数は、親モデルの有無にかかわらず、
* グローバル座標系での実際のアップベクトルを返します。
*
* \return グローバル座標系でのアップベクトル
*
* \sa getInhPosition(), getInhVec(), getInhAngle(), fk_MatrixAdmin::getUpvec()
*/
fk_Vector getInhUpvec(void) const;
#ifndef FK_DOXYGEN_USER_PROCESS
fk_Vector getInhUpVec(void) const;
void setPickMode(const bool);
bool getPickMode(void) const;
void setMaterialMode(const fk_MaterialMode mode);
fk_MaterialMode getMaterialMode(void) const;
#endif
//! 継承オイラー角参照関数
/*!
* モデルのオイラー角を取得します。
* 本関数は、親モデルの有無にかかわらず、グローバル座標系での実際のオイラー角を返します。
* オイラー角の詳細については、 fk_Angle の説明を参照して下さい。
*
* \return
*
* \sa getInhPosition(), getInhVec(), getInhUpvec(), fk_MatrixAdmin::getAngle(), fk_Angle
*/
fk_Angle getInhAngle(void) const;
//! 継承全体倍率取得関数
/*!
* モデルの全体拡大・縮小倍率を取得します。
* 親子関係の小モデルの場合、親モデルでの倍率も反映されます。
*
* \return 継承全体拡大・縮小倍率
*
* \sa getInhPosition(), getInhVec(), getInhUpvec(),
* getInhAngle(), fk_MatrixAdmin::getScale()
*/
double getInhScale(void) const;
///@}
//! \name 親子関係制御関数
///@{
//! 親モデル設定関数
/*!
* 親モデルを設定します。
* 親モデルは 1 個しか設定できません。
* 前に設定されていた場合は、前のモデル設定は破棄されます。
*
* \param[in] model 親モデルインスタンスのポインタ
*
* \param[in] setMode
* true の場合、現在のグローバル座標系の位置と姿勢を、
* 親モデル設定後も保持します。
* false の場合は、当モデルでの位置と姿勢を親モデルからの
* 相対的な位置、姿勢として扱います。
* そのため、設定後にグローバル座標系での位置や姿勢は変化することになります。
* この引数を省略した場合は false と同様の挙動となります。
*
* \return 設定に成功すれば true を、失敗すれば false を返します。
*
* \sa deleteParent(), getParent(), entryChild()
*/
bool setParent(fk_Model *model, bool setMode = false);
//! 親モデル解除関数
/*!
* 親モデルの設定を解除します。
*
* \param[in] setMode
* true の場合、現在のグローバル座標系の位置と姿勢を、
* 親モデル解除後も保持します。
* false の場合は、親モデルからの相対的な位置と姿勢を、
* 解除後のグローバル座標系に設定します。
* この引数を省略した場合は false と同様の挙動となります。
*
* \sa setParent(), getParent(), deleteChild()
*/
void deleteParent(bool setMode = false);
//! 親モデル参照関数
/*!
* 親モデルを取得します。
*
* \return 親モデルインスタンスのポインタ。
* 親モデルが設定されていない場合は nullptr を返します。
*
* \sa setParent(), deleteParent()
*/
fk_Model * getParent(void) const;
//! 子モデル設定関数
/*!
* 子モデルを設定します。
* 子モデルは複数持つことが可能なので、
* 既に子モデルが登録されている場合でも、その設定は破棄されません。
*
* \param[in] model 子モデルインスタンスのポインタ
*
* \param[in] setMode
* true の場合、子モデルの現在のグローバル座標系の位置と姿勢を、
* 設定後も保持します。
* false の場合は、子モデルでの位置と姿勢を当モデルからの
* 相対的な位置、姿勢として扱います。
* そのため、設定後にグローバル座標系での位置や姿勢は変化することになります。
* この引数を省略した場合は false と同様の挙動となります。
*
* \return 設定に成功すれば true を、失敗すれば false を返します。
*
* \sa setParent(), deleteChild(), deleteChildren(), foreachChild()
*/
bool entryChild(fk_Model *model, bool setMode = false);
//! 子モデル解除関数
/*!
* 子モデルの設定を解除します。
*
* \param[in] model
* 子モデルインスタンスのポインタ。
* もし model が子モデルの中に存在しない場合は、false を返します。
*
* \param[in] setMode
* true の場合、子モデルのグローバル座標系の位置と姿勢を、
* 解除後も保持します。
* false の場合は、親モデルからの相対的な位置と姿勢を、
* 解除後のグローバル座標系に設定します。
* この引数を省略した場合は false と同様の挙動となります。
*
* \return 解除に成功すれば true を、失敗すれば false を返します。
*
* \sa entryChild(), deleteChildren(), foreachChild()
*/
bool deleteChild(fk_Model *model, bool setMode = false);
//! 全子モデル解除関数
/*!
* 当モデルの全ての子モデルの設定を解除します。
*
* \param[in] setMode
* true の場合、子モデルのグローバル座標系の位置と姿勢を、
* 解除後も保持します。
* false の場合は、親モデルからの相対的な位置と姿勢を、
* 解除後のグローバル座標系に設定します。
* この引数を省略した場合は false と同様の挙動となります。
*
* \sa entryChild(), deleteChild(), foreachChild()
*/
void deleteChildren(bool setMode = false);
//! 子モデル逐次参照関数
/*!
* 当モデルに設定されている子モデルを順番に帰します。
* まず、引数に nullptr を渡したとき、1番目の子モデルを返します。
* 子モデルが存在しない場合は、その時点で nullptr を返します。
* 次に、1番目に帰ってきたモデルを引数として渡したとき、
* 2番目の子モデルを返します。
* このように、設定されている子モデルを順番に参照することができます。
* 最後の子モデルが引数として渡されたとき、nullptr を返します。
*
* 以下のコードは、「parent」の全ての子モデルに対し、
* 描画モードを fk_Draw::LINE に設定する例です。
*
* fk_Model parentModel, *childModel;
*
* for(childModel = parentModel.foreachChild(nullptr);
* childModel != nullptr;
* childModel = parentModel.foreachChild(childModel)) {
*
* childModel->setDrawMode(fk_Draw::LINE);
* }
*
* \param[in] model 順番に渡す子モデルインスタンスのポインタ
*
* \return 次にあたる子モデルインスタンスのポインタ。
* 引数に最後の子モデルが渡された場合、nullptr を返します。
*
* \sa entryChild(), deleteChild(), deleteChildren()
*/
fk_Model * foreachChild(fk_Model *model);
///@}
//! \name 状態保存制御関数
///@{
//! 位置・姿勢保存関数
/*!
* 現時点でのモデルの位置と姿勢を保存します。
* restore() 関数を用いることで復元します。
*
* \sa restore(void), restore(double), setInterStopMode()
*/
void snapShot(void);
//! 位置・姿勢復元関数
/*!
* snapShot() 関数によって保存した位置・姿勢を復元します。
*
* \return 復元に成功すれば true を、失敗すれば false を返します。
*
* \sa restore(double), snapShot(), setInterStopMode()
*/
bool restore(void);
//! 位置・姿勢途中復元関数
/*!
* snapShot() 関数によって保存した位置・姿勢に対し、
* 現在の位置・姿勢と線形補間した状態にします。
*
* \param[in] t
* 線形補間パラメータ。
* 0 を snapShot() 関数による保存時、
* 1 を現時点とし、
* 与えられた実数によって線形補間した位置と姿勢に設定します。
*
* \return 設定に成功すれば true を、失敗すれば false を返します。
*
* \sa snapShot(), restore(void), isCollision()
*/
bool restore(double t);
///@}
//! \name 描画制御用関数
///@{
//! シェーダー設定関数
/*!
* この関数は、モデル描画の際のシェーダーを設定するものです。
* fk_ShaderBinder::bindModel() による設定とまったく同じ挙動となります。
*
* \param[in] shader シェーダープログラム
*
* \note
* シェーダーを未設定にし、デフォルトのシェーダーで描画したい場合は、
* 引数に nullptr を入力して下さい。
*/
void setShader(fk_ShaderBinder *shader);
//! シェーダー取得関数
/*!
* setShader() (または fk_ShaderBinder::bindModel())
* によって設定されたシェーダーを返します。
*
* \return シェーダーを返します。
* シェーダーが設定されていない場合は nullptr を返します。
*/
fk_ShaderBinder * getShader(void);
#ifndef FK_DOXYGEN_USER_PROCESS
//! 描画処理事前関数
/*!
* この関数は、
* 描画エンジン内部でモデルが実際に描画される前に自動的に呼び出されます。
* デフォルトの状態では中身は空ですが、
* 関数オブジェクトまたはラムダ式で上書きすることにより、
* 描画処理前の時点の処理を記述することが可能です。
* 主な利用用途はシェーダプログラミングやデバッグ、
* あるいは独自形状描画などが考えられます。
*
* 本関数を利用するには、FK の描画エンジン内部に精通している必要があります。
* ソースコードを解析し、内部処理を理解した上で利用することを推奨します。
*/
//std::function<void(void)> preShader;
//! 描画処理事後関数
/*!
* この関数は、
* 描画エンジン内部でモデルが実際に描画された後に自動的に呼び出されます。
* デフォルトの状態では中身は空ですが、
* 関数オブジェクトまたはラムダ式で上書きすることにより、
* 描画処理後の時点の処理を記述することが可能です。
* 主な利用用途はシェーダプログラミングやデバッグ、
* あるいは独自形状描画などが考えられます。
*
* 本関数を利用するには、FK の描画エンジン内部に精通している必要があります。
* ソースコードを解析し、内部処理を理解した上で利用することを推奨します。
*/
//std::function<void(void)> postShader;
#endif
///@}
//! \name 境界ボリューム自動設定関数
///@{
//! 境界球自動設定関数
/*!
* この関数は、
* 境界ボリュームである境界球の半径を自動的に設定するものです。
* 具体的には、モデルの中心から形状の最遠点となる点と中心との距離を半径とします。
* その結果、すべての形状上の点は境界球の内側に入ることになります。
* 境界球に関する詳細は fk_Boundary クラスを参照して下さい。
*
* \note
* setShape() で別形状を設定した場合や、設定した形状を
* fk_IndexFaceSet::moveVPosition() などの関数によって変形した場合でも、
* 境界球半径は自動的に変化しません。
* 形状の全ての部分が境界球内部に入ることを保証するためには、
* 形状変化後に本関数を呼ぶ必要があります。
*
* \sa adjustAABB(), adjustOBB(), adjustCapsule(), isInter(), isCollision(),
* fk_Boundary::setBMode(),
* fk_Boundary::setSphere(), fk_Boundary::getSphere()
*/
void adjustSphere(void);
//! AABB 自動設定関数
/*!
* この関数は、
* 境界ボリュームである AABB (軸平行境界ボックス) の大きさを自動的に設定するものです。
* すべての頂点が AABB の内部と入る条件を満たす最小の大きさが設定されます。
* AABB に関する詳細は fk_Boundary クラスを参照して下さい。
*
* \note
* setShape() で別形状を設定した場合や、設定した形状を
* fk_IndexFaceSet::moveVPosition() などの関数によって変形した場合でも、
* AABB の大きさは自動的に変化しません。
* 形状の全ての部分が AABB 内部に入ることを保証するためには、
* 形状変化後に本関数を呼ぶ必要があります。
* また、AABB はその性質上、
* モデルが回転した場合には形状が AABB の外側にはみ出る可能性がありますので、
* モデルが回転した後も形状が AABB 内部にあることを保証するには、
* 回転した後に本関数を呼ぶ必要があります。
*
* \sa adjustSphere(), adjustOBB(), adjustCapsule(), isInter(), isCollision(),
* fk_Boundary::setBMode(),
* fk_Boundary::setAABBSize(double, double, double),
* fk_Boundary::setAABBSize(fk_Vector), fk_Boundary::getAABBSize()
*/
void adjustAABB(void);
//! OBB 自動設定関数
/*!
* この関数は、
* 境界ボリュームである OBB (有向境界ボックス) の大きさを自動的に設定するものです。
* すべての頂点が OBB の内部と入る条件を満たす最小の大きさが設定されます。
* OBB に関する詳細は fk_Boundary クラスを参照して下さい。
*
* \note
* setShape() で別形状を設定した場合や、設定した形状を
* fk_IndexFaceSet::moveVPosition() などの関数によって変形した場合でも、
* OBB の大きさは自動的に変化しません。
* 形状の全ての部分が OBB 内部に入ることを保証するためには、
* 形状変化後に本関数を呼ぶ必要があります。
*
* \sa adjustSphere(), adjustAABB(), adjustCapsule(), isInter(), isCollision(),
* fk_Boundary::setBMode(),
* fk_Boundary::setOBBSize(double, double, double),
* fk_Boundary::setOBBSize(fk_Vector), fk_Boundary::getOBBSize()
*/
void adjustOBB(void);
//! 境界カプセル自動設定関数
/*!
* この関数は、
* 境界ボリュームである境界カプセルの大きさを自動的に設定するものです。
* すべての頂点が境界カプセルの内部と入る条件を満たす最小の大きさが設定されます。
* 境界カプセルに関する詳細は fk_Boundary クラスを参照して下さい。
*
* \note
* setShape() で別形状を設定した場合や、設定した形状を
* fk_IndexFaceSet::moveVPosition() などの関数によって変形した場合でも、
* 境界カプセルの大きさは自動的に変化しません。
* 形状の全ての部分が境界カプセル内部に入ることを保証するためには、
* 形状変化後に本関数を呼ぶ必要があります。
*
* \param[in] S 中心軸始点位置ベクトル
* \param[in] E 中心軸終点位置ベクトル
*
* \sa adjustSphere(), adjustAABB(), adjustOBB(), isInter(), isCollision(),
* fk_Boundary::setBMode(),
* fk_Boundary::setCapsule(), fk_Boundary::getCapsuleRadius(),
* fk_Boundary::getCapsuleLength(), fk_Boundary::getCapsuleStartPos(),
* fk_Boundary::getCapsuleEndPos()
*/
void adjustCapsule(fk_Vector S, fk_Vector E);
///@}
//! \name 干渉判定・衝突判定関数
///@{
//! モデル間干渉判定関数
/*!
* この関数は、別モデルとの干渉判定を行います。
* 干渉判定に用いられる境界ボリュームの種類は、
* fk_Boundary::setBMode() で設定されたものが用いられます。
* 相手モデル側で別の種類が設定されていた場合でも、
* この関数を呼び出しているインスタンス側の設定が優先されます。
* 従って、相手モデル側の境界ボリュームも適切に設定しておく必要があります。
*
* \note
* 「干渉判定」と「衝突判定」の違いに関しては、
* 本クラスの概要を参照して下さい。
*
* \param[in] model
* 干渉判定を行うモデル
*
* \return 干渉している場合 true を、していない場合 false を返します。
*
* \sa adjustSphere(), adjustAABB(), adjustOBB(), adjustCapsule(), isCollision(),
* snapShot(), restore(void), setInterStopMode(), entryInterModel(),
* fk_Boundary::setBMode(),
* fk_Boundary::setCapsule(), fk_Boundary::getCapsuleRadius(),
* fk_Boundary::getCapsuleLength(), fk_Boundary::getCapsuleStartPos(),
* fk_Boundary::getCapsuleEndPos()
*/
bool isInter(fk_Model *model);
//! モデル間衝突判定関数
/*!
* この関数は、別モデルとの衝突判定を行います。
* 衝突判定を行うには、まずそれぞれのモデルにおいて
* snapShot() 関数によって衝突判定を行う初期状態を設定しておく必要があります。
* その状態から現在の位置まで、両モデルが等速度直線運動していると想定し、
* その間に衝突が発生したかどうかを検出します。
*
* なお、本関数を利用する際には事前に境界球の半径を適切に設定しておく必要があります。
* 現在この関数は境界球による判定のみが有効となります。
* fk_Boundary::setBMode() によって境界ボリュームが別の種類に設定されていた場合でも、
* 境界球の情報のみが用いられます。
*
* なお、衝突判定は snapShot() を呼ぶ以前や現時点以降を含めての検出となるので、
* snapShot() を呼んだ時点から現時点までの間に衝突が起こったかどうかを判定するには、
* 返値第2引数の衝突時間を考慮する必要があります。
*
* \note
* 「干渉判定」と「衝突判定」の違いに関しては、
* 本クラスの概要を参照して下さい。
*
* \param[in] model
* 衝突判定を行うモデル
*
* \return
* 第1要素は、両モデルが等速度直線運動をすると想定した場合に、
* いずれかの時刻で衝突が起きる場合 true が、衝突しない場合は false が入ります。
*
* 第2要素は,snapShot() が呼ばれた時刻を 0、
* 現時点の時刻を 1 とした場合の衝突時間が入ります。
* 第1要素が true であった場合でも、
* この値が 0 から 1 の間にないときは、
* 衝突が起こっていないことになりますので、注意して下さい。
*
* \sa adjustSphere(), adjustAABB(), adjustOBB(), adjustCapsule(), isInter(),
* snapShot(), restore(double),
* fk_Boundary::setBMode(),
* fk_Boundary::setCapsule(), fk_Boundary::getCapsuleRadius(),
* fk_Boundary::getCapsuleLength(), fk_Boundary::getCapsuleStartPos(),
* fk_Boundary::getCapsuleEndPos()
*/
std::tuple<bool, double> isCollision(fk_Model *model);
#ifndef FK_OLD_NONSUPPORT
#ifndef FK_DOXYGEN_USER_PROCESS
bool isCollision(fk_Model *model, double *time);
#endif
#endif
//! 干渉継続モード設定関数
/*!
* 干渉継続モードを有効にしておくと、
* 本モデルが isInter() 関数で他のモデルと干渉状態が検出された場合、
* resetInter() が呼ばれるまでは true を返すようになります。
*
* \param[in] mode
* true である場合、干渉継続モードが有効となります。
* false の場合無効にします。
*
* \sa isInter(), getInterMode(), getInterStatus(), resetInter(),
* setInterStopMode(), entryInterModel()
*/
void setInterMode(bool mode);
//! 干渉継続モード取得関数
/*!
* 現在の干渉継続モード状態を取得します。
*
* \return
* 干渉継続モードが有効である場合 true を、無効である場合 false を返します。
*
* \sa setInterMode()
*/
bool getInterMode(void);
//! 干渉継続状態取得関数
/*!
* 本関数は、干渉継続モードが有効である場合で、
* 前に resetInter() が呼ばれた以降で、
* isInter() によって干渉が検出されたことがあるかを検出します。
*
* \return
* 干渉検出があった場合 true を、なかった場合 false を返します。
*
* \sa isInter(), setInterMode(), resetInterStatus()
*/
bool getInterStatus(void);
//! 干渉継続状態初期化関数
/*!
* 干渉継続モードによる干渉検出状態を初期化します。
* この関数が呼ばれた以降、再び isInter() による干渉が検出されるまでは、
* getInterStatus() 関数は false を返します。
*
* \sa isInter(), setInterMode(), getInterStatus()
*/
void resetInter(void);
///@}
//! \name 干渉自動停止制御関数
///@{
//! 干渉自動停止モード設定関数
/*!
* この関数は、干渉自動停止モードの有無効を設定します。
* 「干渉自動停止モード」とは、以下のような処理を行う機能のことです。
* -# 干渉チェック対象となるモデルを事前に登録しておく。
* -# モデル移動の前に snapShot() をしておく。
* -# モデルの移動を行った際に、
* もし干渉チェック対象モデルのいずれかと干渉していた場合は、
* restore() を実行し移動前の状態に戻る。
*
* この機能を用いることで、移動後で干渉が起きてしまう移動が無効となります。
* 壁などにモデルが入らないように処理するような場面で有効となります。
*
* このモードの対象となる移動関数は以下のとおりです。
* - glRotate()
* - loRotate()
* - glRotateWithVec()
* - loRotateWithVec()
* - glTranslate()
* - loTranslate()
* - glMoveTo()
*
* これらの関数は、モデルの位置ベクトルが変化する可能性があるからです。
* その他の姿勢制御関数については停止の対象とはなりません。
*
* なお、このモードを利用する場合、 restore() した後にも干渉状態となっている場合、
* 適用モデルがまったく動かなくなるという問題が生じます。
* そのため本機能を用いたい場合は、
* 干渉チェック対象となるモデルは全て静止した状態であることを推奨します。
* また、位置のかわらない姿勢制御関数は干渉状態であっても動作しますが、
* その際に物体の回転によって非干渉状態から干渉状態となることがありえますので、
* これも注意が必要です。
*
* \note
* 干渉判定を行う際の境界ボリュームに関する設定は、
* 事前に行っておく必要があります。
*
* \note
* このモードを利用する場合、副作用として自前で管理していた
* snapShot() の情報が破棄されてしまうという問題がありますので、
* snapShot() や restore() を利用する場合はこのモードは用いないようにして下さい。
*
* \param[in] mode true の場合有効とし、 false の場合無効とします。
*
* \sa getInterStopMode(), entryInterModel(), deleteInterModel(), clearInterModel(),
* isInter(), snapShot(), restore()
*/
void setInterStopMode(bool mode);
//! 干渉自動停止モード取得関数
/*!
* 干渉自動停止モードの有無効を取得します。
*
* \return 有効である場合 true を、無効である場合 false を返します。
*
* \sa setInterStopMode()
*/
bool getInterStopMode(void);
//! 干渉自動停止モデル登録関数
/*!
* 干渉自動停止モードの対象となるモデルを登録します。
*
* \note
* 本関数で登録したモデルのインスタンスを、
* deleteInterModel() や clearInterModel() で解除する前に消去した場合、
* 動作は保証されません。
*
* \param[in] model 登録モデルインスタンス
*
* \sa setInterStopMode(), deleteInterModel(), clearInterModel()
*/
void entryInterModel(fk_Model *model);
//! 干渉自動停止モデル解除関数
/*!
* 干渉自動停止モードの対象となっていたモデルの解除を行います。
* もし入力モデルが登録されていなかった場合は、なにも起こりません。
*
* \param[in] model 解除モデルインスタンス
*
* \sa setInterStopMode(), entryInterModel(), clearInterModel()
*/
void deleteInterModel(fk_Model *model);
//! 干渉自動停止モデル初期化関数
/*!
* 干渉自動停止モード用に登録されていた全てのモデルを解除します。
*
* \sa setInterStopMode(), entryInterModel(), deleteInterModel()
*/
void clearInterModel(void);
///@}
#ifndef FK_DOXYGEN_USER_PROCESS
// カスタムテクスチャ描画用エントリポイント
virtual void connectShader(unsigned int) {};
void SetTreeDelMode(bool);
void TreePrint(void);
void setSize(double);
double getSize(void) const;
void setWidth(double);
double getWidth(void) const;
#endif
private:
std::unique_ptr<Member> _m;
void EntryTree(void);
void DeleteTree(void);
fk_TreeData * GetTreeData(fk_Model *);
bool IsBSInter(fk_Model *);
bool IsAABBInter(fk_Model *);
bool IsOBBInter(fk_Model *);
bool IsCapsuleInter(fk_Model *);
void PreMove(void);
void PostMove(void);
static std::unique_ptr<fk_Tree> modelTree;
static unsigned int globalModelID;
};
}
#endif // !__FK_MODEL_HEADER__
/****************************************************************************
*
* Copyright (c) 1999-2020, Fine Kernel Project, 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 copyright holders 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.
*
****************************************************************************/
/****************************************************************************
*
* Copyright (c) 1999-2020, Fine Kernel Project, All rights reserved.
*
* 本ソフトウェアおよびソースコードのライセンスは、基本的に
* 「修正 BSD ライセンス」に従います。以下にその詳細を記します。
*
* ソースコード形式かバイナリ形式か、変更するかしないかを問わず、
* 以下の条件を満たす場合に限り、再頒布および使用が許可されます。
*
* - ソースコードを再頒布する場合、上記の著作権表示、本条件一覧、
* および下記免責条項を含めること。
*
* - バイナリ形式で再頒布する場合、頒布物に付属のドキュメント等の
* 資料に、上記の著作権表示、本条件一覧、および下記免責条項を
* 含めること。
*
* - 書面による特別の許可なしに、本ソフトウェアから派生した製品の
* 宣伝または販売促進に、本ソフトウェアの著作権者の名前または
* コントリビューターの名前を使用してはならない。
*
* 本ソフトウェアは、著作権者およびコントリビューターによって「現
* 状のまま」提供されており、明示黙示を問わず、商業的な使用可能性、
* および特定の目的に対する適合性に関す暗黙の保証も含め、またそれ
* に限定されない、いかなる保証もないものとします。著作権者もコン
* トリビューターも、事由のいかんを問わず、損害発生の原因いかんを
* 問わず、かつ責任の根拠が契約であるか厳格責任であるか(過失その
* 他の)不法行為であるかを問わず、仮にそのような損害が発生する可
* 能性を知らされていたとしても、本ソフトウェアの使用によって発生
* した(代替品または代用サービスの調達、使用の喪失、データの喪失、
* 利益の喪失、業務の中断も含め、またそれに限定されない)直接損害、
* 間接損害、偶発的な損害、特別損害、懲罰的損害、または結果損害に
* ついて、一切責任を負わないものとします。
*
****************************************************************************/
| 25.266087
| 94
| 0.658762
|
[
"shape",
"model"
] |
399003e5fc2f86371be1beabc0864482e62f31e3
| 4,128
|
h
|
C
|
abscommon/abscommon/Subsystems.h
|
pablokawan/ABx
|
064d6df265c48c667ce81b0a83f84e5e22a7ff53
|
[
"MIT"
] | null | null | null |
abscommon/abscommon/Subsystems.h
|
pablokawan/ABx
|
064d6df265c48c667ce81b0a83f84e5e22a7ff53
|
[
"MIT"
] | null | null | null |
abscommon/abscommon/Subsystems.h
|
pablokawan/ABx
|
064d6df265c48c667ce81b0a83f84e5e22a7ff53
|
[
"MIT"
] | null | null | null |
/**
* Copyright 2017-2020 Stefan Ascher
*
* 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 <unordered_map>
#include <vector>
#include <sa/Assert.h>
#include <sa/TypeName.h>
#include <sa/StringHash.h>
class Subsystems
{
private:
class _Subsystem
{ };
template<typename T>
class _SubystemWrapper : public _Subsystem
{
public:
std::unique_ptr<T> object_;
explicit _SubystemWrapper(T* object) :
object_(std::move(object))
{ }
};
std::unordered_map<size_t, std::unique_ptr<_Subsystem>> systems_;
/// The creation order of the systems
std::vector<size_t> order_;
public:
Subsystems() = default;
~Subsystems() noexcept
{
Clear();
}
void Clear() noexcept
{
// Reverse delete subsystems
std::vector<size_t>::reverse_iterator itr;
for (itr = order_.rbegin(); itr != order_.rend(); ++itr)
{
auto sit = systems_.find(*itr);
ASSERT(sit != systems_.end());
(*sit).second.reset();
}
systems_.clear();
order_.clear();
}
template<typename T, typename... _CArgs>
bool CreateSubsystem(_CArgs&&... _Args)
{
static constexpr size_t key = sa::StringHash(sa::TypeName<T>::Get());
const auto i = systems_.find(key);
if (i != systems_.end())
return false;
T* system = new T(std::forward<_CArgs>(_Args)...);
if (system)
{
if (RegisterSubsystem<T>(system))
return true;
delete system;
}
return false;
}
/// Takes ownership of the object
template<typename T>
bool RegisterSubsystem(T* system)
{
static constexpr size_t key = sa::StringHash(sa::TypeName<T>::Get());
const auto i = systems_.find(key);
if (i == systems_.end())
{
systems_[key] = std::make_unique<_SubystemWrapper<T>>(system);
order_.push_back(key);
return true;
}
return false;
}
template<typename T>
void RemoveSubsystem()
{
static constexpr size_t key = sa::StringHash(sa::TypeName<T>::Get());
const auto i = systems_.find(key);
if (i != systems_.end())
{
auto it = std::find_if(order_.begin(), order_.end(), [&](size_t current) -> bool {
return current == key;
});
ASSERT(it != order_.end());
order_.erase(it);
systems_.erase(i);
}
}
template<typename T>
T* GetSubsystem()
{
static constexpr size_t key = sa::StringHash(sa::TypeName<T>::Get());
const auto i = systems_.find(key);
if (i != systems_.end())
{
const auto wrapper = static_cast<_SubystemWrapper<T>*>((*i).second.get());
return wrapper->object_.get();
}
return nullptr;
}
static Subsystems Instance;
};
template<typename T>
inline T* GetSubsystem()
{
return Subsystems::Instance.GetSubsystem<T>();
}
| 29.697842
| 94
| 0.607316
|
[
"object",
"vector"
] |
39bdea7c63d2c89873e5a99489f83f314ba2f66a
| 3,199
|
h
|
C
|
RxData/cache/subject/SelectionSubject.h
|
intact-software-systems/cpp-software-patterns
|
e463fc7eeba4946b365b5f0b2eecf3da0f4c895b
|
[
"MIT"
] | 1
|
2020-09-03T07:23:11.000Z
|
2020-09-03T07:23:11.000Z
|
RxData/cache/subject/SelectionSubject.h
|
intact-software-systems/cpp-software-patterns
|
e463fc7eeba4946b365b5f0b2eecf3da0f4c895b
|
[
"MIT"
] | null | null | null |
RxData/cache/subject/SelectionSubject.h
|
intact-software-systems/cpp-software-patterns
|
e463fc7eeba4946b365b5f0b2eecf3da0f4c895b
|
[
"MIT"
] | null | null | null |
#ifndef RxData_Cache_SelectionSubject_h_IsIncluded
#define RxData_Cache_SelectionSubject_h_IsIncluded
#include"RxData/CommonDefines.h"
#include"RxData/cache/observer/SelectionListener.h"
namespace RxData
{
template <typename DATA>
class SelectionSubject
: public SelectionObserver<DATA>
, public BaseLib::Concurrent::Observable<SelectionObserver<DATA> >
{
public:
SelectionSubject()
: selectionObserverSignaller_(new Signaller1<void, DATA>())
{}
virtual ~SelectionSubject()
{}
/**
* Called when an object enters the Selection.
*
* @param data
*/
virtual void OnObjectIn(DATA data)
{
selectionObserverSignaller_->template Signal<SelectionObserver<DATA> >(data, &SelectionObserver<DATA>::OnObjectIn);
}
/**
* Called when an object exits the Selection.
*
* @param data
*/
virtual void OnObjectOut(DATA data)
{
selectionObserverSignaller_->template Signal<SelectionObserver<DATA> >(data, &SelectionObserver<DATA>::OnObjectOut);
}
/**
* Called when the contents of an object belonging to the Selection changes
*
* @param data
*/
virtual void OnObjectModified(DATA data)
{
selectionObserverSignaller_->template Signal<SelectionObserver<DATA> >(data, &SelectionObserver<DATA>::OnObjectModified);
}
/**
* Set the SelectionListener (set_listener), that will be triggered when the composition of the
* selection changes, as well as if the members are modified. set_listener returns the
* previously set listener if any; set_listener called with a NULL parameter discards the current
* listener.
*/
virtual SlotHolder::Ptr Connect(SelectionObserver<DATA> *observer)
{
selectionObserverSignaller_->template Connect<SelectionObserver<DATA> >(observer, &SelectionObserver<DATA>::OnObjectIn);
selectionObserverSignaller_->template Connect<SelectionObserver<DATA> >(observer, &SelectionObserver<DATA>::OnObjectOut);
return selectionObserverSignaller_->template Connect<SelectionObserver<DATA> >(observer, &SelectionObserver<DATA>::OnObjectModified);
}
virtual bool Disconnect(SelectionObserver<DATA> *observer)
{
return selectionObserverSignaller_->template Disconnect<SelectionObserver<DATA> >(observer);
}
virtual void DisconnectAll()
{
selectionObserverSignaller_->DisconnectAll();
}
private:
/**
* The SelectionListener is activated when the composition of the Selection is modified as well
* as when one of its members is modified. A member can be considered as modified, either
* when the member is modified or when that member or one of its contained objects is modified
* (depending on the value of concerns_contained). Modifications in the Selection are considered
* with respect to the state of the Selection last time is was examined, for instance:
*
* - at each incoming updates processing, if auto_refresh is TRUE.
* - at each explicit call to refresh, if auto_refresh is FALSE.
*/
typename Signaller1<void, DATA>::Ptr selectionObserverSignaller_;
};
}
#endif
| 34.771739
| 141
| 0.714911
|
[
"object"
] |
39ca575ab533298368f34ce736e19c687906eef2
| 676
|
h
|
C
|
chaps/slot_policy.h
|
Toromino/chromiumos-platform2
|
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
|
[
"BSD-3-Clause"
] | null | null | null |
chaps/slot_policy.h
|
Toromino/chromiumos-platform2
|
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
|
[
"BSD-3-Clause"
] | null | null | null |
chaps/slot_policy.h
|
Toromino/chromiumos-platform2
|
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2021 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 CHAPS_SLOT_POLICY_H_
#define CHAPS_SLOT_POLICY_H_
#include <string>
#include "pkcs11/cryptoki.h"
namespace chaps {
class Object;
// SlotPolicy encapsulates policies for a PKCS #11 token.
class SlotPolicy {
public:
virtual ~SlotPolicy() = default;
virtual bool IsObjectClassAllowedForNewObject(
CK_OBJECT_CLASS object_class) = 0;
virtual bool IsObjectClassAllowedForImportedObject(
CK_OBJECT_CLASS object_class) = 0;
};
} // namespace chaps
#endif // CHAPS_SLOT_POLICY_H_
| 23.310345
| 73
| 0.761834
|
[
"object"
] |
5ea3ff548103b793358b9c177bcc227382c42315
| 12,281
|
c
|
C
|
ssd1327zb.c
|
warcomeb/SSD1327ZB
|
1cdeb75ab3ed9025c734e62878c32de15690831e
|
[
"MIT"
] | 2
|
2018-10-08T23:17:46.000Z
|
2020-02-29T06:22:08.000Z
|
ssd1327zb.c
|
warcomeb/SSD1327ZB
|
1cdeb75ab3ed9025c734e62878c32de15690831e
|
[
"MIT"
] | null | null | null |
ssd1327zb.c
|
warcomeb/SSD1327ZB
|
1cdeb75ab3ed9025c734e62878c32de15690831e
|
[
"MIT"
] | 1
|
2018-10-08T23:17:55.000Z
|
2018-10-08T23:17:55.000Z
|
/******************************************************************************
* SSD1327ZB - Library for SSD1327ZB OLed Driver based on libohiboard
* Copyright (C) 2018 Alessio Socci & Marco Giammarini
*
* Authors:
* Alessio Socci <[email protected]>
* Marco Giammarini <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
******************************************************************************/
#include "ssd1327zb.h"
#include <string.h>
#define SSD1327ZB_CMD_SETCOLUMNADDR 0x15
#define SSD1327ZB_CMD_SETROWADDR 0x75
#define SSD1327ZB_CMD_SETCONTRAST 0x81
#define SSD1327ZB_CMD_SEGMENTREMAP 0xA0 /**< Set Display remap */
#define SSD1327ZB_CMD_STARTLINE 0xA1 /**< Set start line */
#define SSD1327ZB_CMD_DISPLAYNORMAL 0xA4
#define SSD1327ZB_CMD_DISPLAYALLON 0xA5 /**< Entire Display is ON with gray scale level to GS15 */
#define SSD1327ZB_CMD_DISPLAYALLOFF 0xA6 /**< Entire Display is OFF with gray scale level to GS0 */
#define SSD1327ZB_CMD_DISPLAYINVERSE 0xA7
#define SSD1327ZB_CMD_DISPLAYOFF 0xAE
#define SSD1327ZB_CMD_DISPLAYON 0xAF
#define SSD1327ZB_REMAP_COLUMN 0x01 /**< Enable column address remap */
#define SSD1327ZB_REMAP_NIBBLE 0x02 /**< Enable nibble remap */
#define SSD1327ZB_REMAP_ADDR_INCREMENT 0x04 /**< Enable vertical address increment */
#define SSD1327ZB_REMAP_COM 0x10 /**< Enable COM remap */
#define SSD1327ZB_REMAP_ODDEVEN_COM 0x40 /**< Enable COM split odd/even */
#define SSD1327ZB_write(value) do { \
((value & 0x01) > 0) ? Gpio_set(dev->gdl.d0) : Gpio_clear(dev->gdl.d0); \
((value & 0x02) > 0) ? Gpio_set(dev->gdl.d1) : Gpio_clear(dev->gdl.d1); \
((value & 0x04) > 0) ? Gpio_set(dev->gdl.d2) : Gpio_clear(dev->gdl.d2); \
((value & 0x08) > 0) ? Gpio_set(dev->gdl.d3) : Gpio_clear(dev->gdl.d3); \
((value & 0x10) > 0) ? Gpio_set(dev->gdl.d4) : Gpio_clear(dev->gdl.d4); \
((value & 0x20) > 0) ? Gpio_set(dev->gdl.d5) : Gpio_clear(dev->gdl.d5); \
((value & 0x40) > 0) ? Gpio_set(dev->gdl.d6) : Gpio_clear(dev->gdl.d6); \
((value & 0x80) > 0) ? Gpio_set(dev->gdl.d7) : Gpio_clear(dev->gdl.d7); \
} while (0)
static void SSD1327ZB_sendCommand (SSD1327ZB_Device* dev, uint8_t command)
{
#if defined WARCOMEB_GDL_PARALLEL
Gpio_set(dev->gdl.rd);
Gpio_clear(dev->gdl.cs);
Gpio_set(dev->gdl.wr);
// Is command message
Gpio_clear(dev->gdl.dc);
// Enable writing
Gpio_clear(dev->gdl.wr);
SSD1327ZB_write(command);
// Restore write pin
Gpio_set(dev->gdl.wr);
// Disable device
Gpio_set(dev->gdl.cs);
#elif defined WARCOMEB_GDL_I2C
#elif defined WARCOMEB_GDL_SPI
#endif
}
static void SSD1327ZB_sendData (SSD1327ZB_Device* dev, uint8_t value)
{
#if defined WARCOMEB_GDL_PARALLEL
Gpio_set(dev->gdl.rd);
Gpio_clear(dev->gdl.cs);
Gpio_set(dev->gdl.wr);
// is data message
Gpio_set(dev->gdl.dc);
// Enable writing
Gpio_clear(dev->gdl.wr);
SSD1327ZB_write(value);
// Restore write pin
Gpio_set(dev->gdl.wr);
// Disable device
Gpio_set(dev->gdl.cs);
#elif defined WARCOMEB_GDL_I2C
#elif defined WARCOMEB_GDL_SPI
#endif
}
/**
* The function set the current position into the display. The values are related to
* the internal buffer of the display.
*
* @param[in] dev The handle of the device
* @param[in] xStart The x start position into the buffer
* @param[in] xStop The x stop position into the buffer
* @param[in] yStart The y start position into the buffer
* @param[in] yStop The y stop position into the buffer
* @return Return an error if the requested position is wrong,
* GDL_ERRORS_OK otherwise.
*/
static GDL_Errors SSD1327ZB_setBufferPosition (SSD1327ZB_Device* dev,
uint8_t xStart,
uint8_t xStop,
uint8_t yStart,
uint8_t yStop)
{
if ((xStart >= dev->gdl.width) || (yStart >= dev->gdl.height))
return GDL_ERRORS_WRONG_POSITION;
if ((xStop >= dev->gdl.width) || (yStop >= dev->gdl.height))
return GDL_ERRORS_WRONG_POSITION;
// Set column address
SSD1327ZB_sendCommand(dev,SSD1327ZB_CMD_SETCOLUMNADDR);
SSD1327ZB_sendCommand(dev,xStart/2);
SSD1327ZB_sendCommand(dev,xStop/2);
// Set row address
SSD1327ZB_sendCommand(dev,SSD1327ZB_CMD_SETROWADDR);
SSD1327ZB_sendCommand(dev,yStart);
SSD1327ZB_sendCommand(dev,yStop);
return GDL_ERRORS_OK;
}
void SSD1327ZB_init (SSD1327ZB_Device* dev)
{
// Set the device model
dev->gdl.model = GDL_MODELTYPE_SSD1327ZB;
// Save display size
dev->gdl.height = WARCOMEB_SSD1327ZB_HEIGHT;
dev->gdl.width = WARCOMEB_SSD1327ZB_WIDTH;
// Save default font size
dev->gdl.fontSize = 1;
dev->gdl.useCustomFont = FALSE;
// Save callback for drawing pixel
dev->gdl.drawPixel = SSD1327ZB_drawPixel;
// memset(dev->buffer, 0x00, WARCOMEB_SSD1327ZB_BUFFERDIMENSION);
#if defined WARCOMEB_GDL_PARALLEL
Gpio_config(dev->gdl.d0,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.d1,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.d2,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.d3,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.d4,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.d5,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.d6,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.d7,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.rd,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.dc,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.rs,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.cs,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.wr,GPIO_PINS_OUTPUT);
Gpio_set(dev->gdl.dc);
Gpio_set(dev->gdl.rd);
Gpio_set(dev->gdl.wr);
Gpio_set(dev->gdl.cs);
Gpio_set(dev->gdl.rs);
#elif defined WARCOMEB_GDL_I2C
#elif defined WARCOMEB_GDL_SPI
#endif
SSD1327ZB_sendCommand(dev,SSD1327ZB_CMD_DISPLAYON);
// Wait 100ms after on
dev->gdl.delayTime(100);
// Set display to normal
SSD1327ZB_sendCommand(dev,SSD1327ZB_CMD_DISPLAYNORMAL);
// Select segment re-map, COM scan direction, COM hardware configuration and
// de-select level
// They depend on producer choice
switch (dev->gdl.product)
{
case SSD1327ZB_PRODUCT_RAYSTAR_REX128128B:
SSD1327ZB_sendCommand(dev,SSD1327ZB_CMD_SEGMENTREMAP);
SSD1327ZB_sendCommand(dev,SSD1327ZB_REMAP_ODDEVEN_COM);
SSD1327ZB_sendCommand(dev,SSD1327ZB_CMD_STARTLINE);
SSD1327ZB_sendCommand(dev,0);
break;
}
}
GDL_Errors SSD1327ZB_drawPixel (SSD1327ZB_Device* dev,
uint8_t xPos,
uint8_t yPos,
SSD1327ZB_GrayScale color)
{
if ((xPos >= dev->gdl.width) || (yPos >= dev->gdl.height))
return GDL_ERRORS_WRONG_POSITION;
uint16_t pos = ((uint16_t) xPos/2) + ((uint16_t) yPos*(dev->gdl.width/2));
if (xPos%2)
dev->buffer[pos] = (((color << 4) & 0xF0) | (dev->buffer[pos] & 0x0F));
else
dev->buffer[pos] = ((color & 0x0F) | (dev->buffer[pos] & 0xF0));
return GDL_ERRORS_OK;
}
void SSD1327ZB_setContrast (SSD1327ZB_Device* dev, uint8_t value)
{
SSD1327ZB_sendCommand(dev,SSD1327ZB_CMD_SETCONTRAST);
SSD1327ZB_sendCommand(dev,value);
}
void SSD1327ZB_flush (SSD1327ZB_Device* dev)
{
// Set the cursor to the starting point of the display
// Print all the buffer
SSD1327ZB_setBufferPosition(dev,0,dev->gdl.width-1,0,dev->gdl.height-1);
for (uint16_t i = 0; i < WARCOMEB_SSD1327ZB_BUFFERDIMENSION; i++)
{
SSD1327ZB_sendData(dev,dev->buffer[i]);
}
}
void SSD1327ZB_flushPart (SSD1327ZB_Device* dev,
uint8_t xStart,
uint8_t xStop,
uint8_t yStart,
uint8_t yStop)
{
// Set the part of the display where change the pixels
GDL_Errors error = SSD1327ZB_setBufferPosition(dev,xStart,xStop,yStart,yStop);
if (error != GDL_ERRORS_OK) return;
uint8_t xStartHalf = xStart/2;
uint8_t xStopHalf = xStop/2;
uint8_t widthHalf = dev->gdl.width/2;
for (uint8_t i = yStart; i <= yStop; i++)
{
for (uint8_t j = xStartHalf; j <= xStopHalf; j++)
{
SSD1327ZB_sendData(dev,dev->buffer[j + (i * widthHalf)]);
}
}
}
void SSD1327ZB_clear (SSD1327ZB_Device* dev)
{
// Reset memory buffer
memset(dev->buffer, 0x00, WARCOMEB_SSD1327ZB_BUFFERDIMENSION);
// Flush the new buffer
SSD1327ZB_flush(dev);
}
void SSD1327ZB_drawLine (SSD1327ZB_Device* dev,
uint8_t xStart,
uint8_t yStart,
uint8_t xStop,
uint8_t yStop,
SSD1327ZB_GrayScale color)
{
GDL_drawLine(&(dev->gdl),xStart,yStart,xStop,yStop,(uint8_t)color);
}
void SSD1327ZB_drawHLine (SSD1327ZB_Device* dev,
uint8_t xStart,
uint8_t yStart,
uint8_t width,
SSD1327ZB_GrayScale color)
{
SSD1327ZB_drawLine(dev,xStart,yStart,xStart+width,yStart,color);
}
void SSD1327ZB_drawVLine (SSD1327ZB_Device* dev,
uint8_t xStart,
uint8_t yStart,
uint8_t height,
SSD1327ZB_GrayScale color)
{
SSD1327ZB_drawLine(dev,xStart,yStart,xStart,yStart+height,color);
}
void SSD1327ZB_drawRectangle (SSD1327ZB_Device* dev,
uint16_t xStart,
uint16_t yStart,
uint16_t width,
uint16_t height,
SSD1327ZB_GrayScale color,
bool isFill)
{
GDL_drawRectangle(&(dev->gdl),xStart,yStart,width,height,(uint8_t)color,isFill);
}
GDL_Errors SSD1327ZB_drawChar (SSD1327ZB_Device* dev,
uint16_t xPos,
uint16_t yPos,
uint8_t c,
SSD1327ZB_GrayScale color,
SSD1327ZB_GrayScale background,
uint8_t size)
{
return GDL_drawChar(&(dev->gdl),xPos,yPos,c,(uint8_t)color,(uint8_t)background,size);
}
GDL_Errors SSD1327ZB_drawPicture (SSD1327ZB_Device* dev,
uint16_t xPos,
uint16_t yPos,
uint16_t width,
uint16_t height,
const uint8_t* picture,
GDL_PictureType pixelType)
{
if ((pixelType != GDL_PICTURETYPE_1BIT) && (pixelType != GDL_PICTURETYPE_4BIT))
return GDL_ERRORS_WRONG_VALUE;
return GDL_drawPicture(&(dev->gdl),xPos,yPos,width,height,picture,pixelType);
}
| 35.49422
| 112
| 0.620715
|
[
"model"
] |
5ea6f61136f93fbc35474359538b86413dee4642
| 2,941
|
h
|
C
|
pxr/imaging/lib/hdSt/shader.h
|
dalgos-adsk/USD
|
65320d266057ae0a68626217f54a0298ac092799
|
[
"AML"
] | 18
|
2017-10-28T22:37:48.000Z
|
2022-01-26T12:00:24.000Z
|
pxr/imaging/lib/hdSt/shader.h
|
piscees/USD
|
65320d266057ae0a68626217f54a0298ac092799
|
[
"AML"
] | null | null | null |
pxr/imaging/lib/hdSt/shader.h
|
piscees/USD
|
65320d266057ae0a68626217f54a0298ac092799
|
[
"AML"
] | 3
|
2019-12-03T16:46:14.000Z
|
2021-08-23T14:56:21.000Z
|
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef HDST_SHADER_H
#define HDST_SHADER_H
#include "pxr/pxr.h"
#include "pxr/imaging/hdSt/api.h"
#include "pxr/imaging/hf/perfLog.h"
#include "pxr/imaging/hd/shader.h"
#include <boost/shared_ptr.hpp>
PXR_NAMESPACE_OPEN_SCOPE
typedef boost::shared_ptr<class HdSurfaceShader> HdSurfaceShaderSharedPtr;
class HdStShader final: public HdShader {
public:
HF_MALLOC_TAG_NEW("new HdStShader");
HDST_API
HdStShader(SdfPath const& id);
HDST_API
virtual ~HdStShader();
/// Synchronizes state from the delegate to this object.
HDST_API
virtual void Sync(HdSceneDelegate *sceneDelegate,
HdRenderParam *renderParam,
HdDirtyBits *dirtyBits) override;
/// Accessor for tasks to get the parameter cached in this sprim object.
/// Don't communicate back to scene delegate within this function.
HDST_API
virtual VtValue Get(TfToken const &token) const override;
/// Returns the minimal set of dirty bits to place in the
/// change tracker for use in the first sync of this prim.
/// Typically this would be all dirty bits.
HDST_API
virtual HdDirtyBits GetInitialDirtyBitsMask() const override;
/// Causes the shader to be reloaded.
HDST_API
virtual void Reload() override;
/// Obtains the render delegate specific representation of the shader.
/// XXX: Should not be virtual.
HDST_API
virtual HdShaderCodeSharedPtr GetShaderCode() const override;
/// Replaces the shader code object with an externally created one
/// Used to set the fallback shader for prim.
/// This class takes ownership of the passed in object.
HDST_API
void SetSurfaceShader(HdSurfaceShaderSharedPtr &shaderCode);
private:
HdSurfaceShaderSharedPtr _surfaceShader;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // HDST_SHADER_H
| 33.804598
| 76
| 0.731044
|
[
"render",
"object"
] |
5eb79005f0fbe8ace1042a0878e6a0d51031e094
| 2,883
|
h
|
C
|
eb/include/tencentcloud/eb/v20210416/model/ListEventBusesResponse.h
|
TencentCloud/tencentcloud-sdk-cpp-intl-en
|
752c031f5ad2c96868183c5931eae3a42dd5ae6c
|
[
"Apache-2.0"
] | 1
|
2022-01-27T09:27:34.000Z
|
2022-01-27T09:27:34.000Z
|
eb/include/tencentcloud/eb/v20210416/model/ListEventBusesResponse.h
|
TencentCloud/tencentcloud-sdk-cpp-intl-en
|
752c031f5ad2c96868183c5931eae3a42dd5ae6c
|
[
"Apache-2.0"
] | null | null | null |
eb/include/tencentcloud/eb/v20210416/model/ListEventBusesResponse.h
|
TencentCloud/tencentcloud-sdk-cpp-intl-en
|
752c031f5ad2c96868183c5931eae3a42dd5ae6c
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_EB_V20210416_MODEL_LISTEVENTBUSESRESPONSE_H_
#define TENCENTCLOUD_EB_V20210416_MODEL_LISTEVENTBUSESRESPONSE_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/eb/v20210416/model/EventBus.h>
namespace TencentCloud
{
namespace Eb
{
namespace V20210416
{
namespace Model
{
/**
* ListEventBuses response structure.
*/
class ListEventBusesResponse : public AbstractModel
{
public:
ListEventBusesResponse();
~ListEventBusesResponse() = default;
CoreInternalOutcome Deserialize(const std::string &payload);
std::string ToJsonString() const;
/**
* 获取Event bus information
* @return EventBuses Event bus information
*/
std::vector<EventBus> GetEventBuses() const;
/**
* 判断参数 EventBuses 是否已赋值
* @return EventBuses 是否已赋值
*/
bool EventBusesHasBeenSet() const;
/**
* 获取Total number of event buses
* @return TotalCount Total number of event buses
*/
int64_t GetTotalCount() const;
/**
* 判断参数 TotalCount 是否已赋值
* @return TotalCount 是否已赋值
*/
bool TotalCountHasBeenSet() const;
private:
/**
* Event bus information
*/
std::vector<EventBus> m_eventBuses;
bool m_eventBusesHasBeenSet;
/**
* Total number of event buses
*/
int64_t m_totalCount;
bool m_totalCountHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_EB_V20210416_MODEL_LISTEVENTBUSESRESPONSE_H_
| 31.336957
| 83
| 0.52931
|
[
"vector",
"model"
] |
5eb864125bc1df08a3a7437ca0e6729fcb0ba149
| 708
|
h
|
C
|
src/gradient/gradient.h
|
Toxe/mandelbrot-sfml-imgui
|
e9375290a475a264c5b57e7678851ffae752d3b0
|
[
"MIT"
] | 6
|
2021-04-14T15:49:46.000Z
|
2022-03-05T12:39:31.000Z
|
src/gradient/gradient.h
|
Toxe/mandelbrot-sfml-imgui
|
e9375290a475a264c5b57e7678851ffae752d3b0
|
[
"MIT"
] | null | null | null |
src/gradient/gradient.h
|
Toxe/mandelbrot-sfml-imgui
|
e9375290a475a264c5b57e7678851ffae752d3b0
|
[
"MIT"
] | null | null | null |
#pragma once
#include <string>
#include <vector>
namespace sf {
class Color;
}
bool equal_enough(float a, float b) noexcept;
struct GradientColor {
float pos;
float r, g, b;
bool operator==(const float p) const noexcept { return equal_enough(p, pos); }
bool operator<(const GradientColor& col) const noexcept { return pos < col.pos; }
};
struct Gradient {
std::string name_;
std::vector<GradientColor> colors;
Gradient() : name_{""} {}
Gradient(std::string name) : name_{name} {}
};
Gradient load_gradient(const std::string& name);
sf::Color color_from_gradient(const Gradient& gradient, const float pos) noexcept;
std::vector<Gradient> load_available_gradients();
| 23.6
| 85
| 0.69774
|
[
"vector"
] |
5ec39d478a14f1d34083c8c0ee6662fc72886ef6
| 11,969
|
h
|
C
|
plugins/unifiedvideoinertialtracker/ConfigParams.h
|
ethanpeng/OSVR-Core
|
59405fc1b1a25aea051dfbba0be5171fa19b8b30
|
[
"Apache-2.0"
] | 369
|
2015-03-08T03:12:41.000Z
|
2022-02-08T22:15:39.000Z
|
plugins/unifiedvideoinertialtracker/ConfigParams.h
|
ethanpeng/OSVR-Core
|
59405fc1b1a25aea051dfbba0be5171fa19b8b30
|
[
"Apache-2.0"
] | 486
|
2015-03-09T13:29:00.000Z
|
2020-10-16T00:41:26.000Z
|
plugins/unifiedvideoinertialtracker/ConfigParams.h
|
ethanpeng/OSVR-Core
|
59405fc1b1a25aea051dfbba0be5171fa19b8b30
|
[
"Apache-2.0"
] | 166
|
2015-03-08T12:03:56.000Z
|
2021-12-03T13:56:21.000Z
|
/** @file
@brief Header
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef INCLUDED_ConfigParams_h_GUID_22101CEF_879B_4781_2733_F5F7AE4E3633
#define INCLUDED_ConfigParams_h_GUID_22101CEF_879B_4781_2733_F5F7AE4E3633
// Internal Includes
#include "BlobParams.h"
// Library/third-party includes
// - none
// Standard includes
#include <cstdint>
#include <string>
namespace osvr {
namespace vbtracker {
static const double BaseMeasurementVariance = 3.0;
struct IMUInputParams {
std::string path =
"/com_osvr_Multiserver/OSVRHackerDevKit0/semantic/hmd";
/// Should we use the IMU orientation data for calibration even if
/// useOrientation is false?
bool calibrateAnyway = false;
/// Should orientation reports be used once calibration completes?
bool useOrientation = true;
/// units: rad^2
double orientationVariance = 1.0e-7;
std::int32_t orientationMicrosecondsOffset = 0;
/// Should angular velocity reports be used once calibration completes?
bool useAngularVelocity = true;
/// units: (rad/sec)^2
double angularVelocityVariance = 1.0e-1;
std::int32_t angularVelocityMicrosecondsOffset = 0;
};
struct TuningParams {
TuningParams();
double noveltyPenaltyBase;
double distanceMeasVarianceBase;
double distanceMeasVarianceIntercept;
};
/// If you add an entry here, must also update both
/// getConfigStringForTargetSet and AllBuiltInTargetSets in
/// ConfigurationParser.h
enum class BuiltInTargetSets { HDK1xChassis, HDK2Chassis };
/// General configuration parameters
struct ConfigParams {
/// Not intended to be manually configurable - enabled when doing things
/// like running an optimization algorithm so some things like a debug
/// view might need to change.
bool performingOptimization = false;
/// For optimization usage.
bool silent = false;
/// For recording tuning data - whether we should record the raw blob
/// data.
bool logRawBlobs = false;
/// For recording tuning data - whether we should record the data from
/// just the usable LEDs each frame after they're associated.
bool logUsableLeds = false;
TuningParams tuning;
/// Parameters specific to the blob-detection step of the algorithm
BlobParams blobParams;
/// Parameters specific to the edge hole based LED extraction algorithm.
EdgeHoleParams extractParams;
/// When using hard-coded target sets, which one to use.
BuiltInTargetSets targetSet = BuiltInTargetSets::HDK1xChassis;
/// Should we have the tracking thread update the reporting vector for
/// every (IMU) message, instead of waiting/buffering for a few
/// milliseconds between updates?
bool continuousReporting = true;
/// Should we open the camera in high-gain mode?
bool highGain = true;
/// Seconds beyond the current time to predict, using the Kalman state.
double additionalPrediction = 0.;
/// Max residual, in meters at the expected XY plane of the beacon in
/// space, for a beacon before applying a variance penalty.
double maxResidual = 0.03631354168383816;
/// Initial beacon error for autocalibration (units: m^2).
/// 0 effectively turns off beacon auto-calib.
/// This is a variance number, so std deviation squared, but it's
/// pretty likely to be between 0 and 1, so the variance will be smaller
/// than the standard deviation.
double initialBeaconError = 1e-7; // 0.001;
/// Maximum distance a blob can move, in multiples of its previous
/// "keypoint diameter", and still be considered the same blob.
double blobMoveThreshold = 3.5;
/// Whether to show the debug windows and debug messages.
bool debug = false;
/// How many threads to let OpenCV use. Set to 0 or less to let OpenCV
/// decide (that is, not set an explicit preference)
int numThreads = 1;
/// This is the autocorrelation kernel of the process noise. The first
/// three elements correspond to position, the second three to
/// incremental rotation.
double processNoiseAutocorrelation[6];
/// The value used in exponential decay of linear velocity: it's the
/// proportion of that velocity remaining at the end of 1 second. Thus,
/// smaller = faster decay/higher damping. In range [0, 1]
double linearVelocityDecayCoefficient = 0.9040551503451977;
/// The value used in exponential decay of angular velocity: it's the
/// proportion of that velocity remaining at the end of 1 second. Thus,
/// smaller = faster decay/higher damping. In range [0, 1]
double angularVelocityDecayCoefficient = 0.8945437897688864;
/// The value used in an additional exponential decay of linear velocity
/// when we've lost sight of all beacons, to quickly attenuate coasting.
/// it's the proportion of that velocity remaining at the end of 1
/// second. Thus, smaller = faster decay/higher damping. In range [0, 1]
double noBeaconLinearVelocityDecayCoefficient = 0.005878868009089861;
/// The measurement variance (units: m^2) is included in the plugin
/// along with the coordinates of the beacons. Some beacons are
/// observed with higher variance than others, due to known difficulties
/// in tracking them, etc. However, for testing you may fine-tine the
/// measurement variances globally by scaling them here.
double measurementVarianceScaleFactor = 1.5;
/// Whether the tracking algorithm internally adjusts beacon positions
/// based on the centroid of the input beacon positions.
bool offsetToCentroid = false;
/// Manual beacon offset (in m) - only really sensible if you only have
/// one target, only used if offsetToCentroid is false.
double manualBeaconOffset[3];
/// If true, this will replace the two sensors with just a single one,
/// including the beacons at the back of the head "rigidly" as a part of
/// it. If true, recommend offsetToCentroid = false, and
/// manualBeaconOffset to be 0, 0, -75.
bool includeRearPanel = true;
/// Head circumference at the head strap, in cm - 55.75 is our estimate
/// for an average based on some hat sizing guidelines. Only matters if
/// includeRearPanel is true.
double headCircumference = 55.75;
/// This is the distance fron the front of the head to the origin of the
/// front sensor coordinate system in the Z axis, in mm.
/// This is a rough estimate - the origin of the coordinate system is
/// roughly the flat part of the hard plastic.
double headToFrontBeaconOriginDistance = 0;
/// This used to be different than the other beacons, but now it's
/// mostly the same.
double backPanelMeasurementError = BaseMeasurementVariance;
/// This is the process-model noise in the beacon-auto-calibration, in
/// mm^2/s. Not fully accurate, since it only gets applied when a beacon
/// gets used for a measurement, but it should be enough to keep beacons
/// from converging in a bad local minimum.
double beaconProcessNoise = 1.e-19;
/// This is the multiplicative penalty applied to the variance of
/// measurements with a "bad" residual
double highResidualVariancePenalty = 7.513691210865344;
/// When true, will stream debug info (variance, pixel measurement,
/// pixel residual) on up to the first 34 beacons of your first sensor
/// as analogs.
bool streamBeaconDebugInfo = false;
/// This should be the ratio of lengths of sides that you'll permit to
/// be filtered in. Larger side first, please.
///
/// Not currently being used.
float boundingBoxFilterRatio = 5.f / 4.f;
/// This should be a negative number - it's the largest the z component
/// of the camera-space LED emission vector is permitted to be and still
/// be used in estimation. acos(this number) is the maximum angle away
/// from pointing at the camera that we'll accept an LED pointing.
double maxZComponent = -0.3;
/// Should we attempt to skip bright-mode LEDs? The alternative is to
/// just give them slightly higher variance.
bool shouldSkipBrightLeds = false;
/// If shouldSkipBrightLeds is false, we use this value as a factor to
/// increase the measurement variance of bright LEDs, to account for the
/// fact that they are less accurate because they tend to refract
/// through surrounding materials, etc.
double brightLedVariancePenalty = 28.32749811268542;
/// If this option is set to true, then while some of the pattern
/// identifier is run each frame, an "early-out" will be taken if the
/// blob/LED already has a valid (non-negative) ID assigned to it. This
/// can help keep IDs on hard to identify blobs, but it can also persist
/// errors longer. That's why it's an option.
///
/// Defaulting to off because it adds some jitter for some reason.
bool blobsKeepIdentity = false;
/// Extra verbose developer debugging messages
bool extraVerbose = false;
/// If non-empty, the file to load (or save to) for calibration data.
/// Only make sense for a single target.
std::string calibrationFile = "";
/// IMU input-related parameters.
IMUInputParams imu;
/// x, y, z, with y up, all in meters.
double cameraPosition[3];
/// Whether we should adjust transforms to assume the camera looks along
/// the YZ plane in the +Z direction.
bool cameraIsForward = true;
/// Should we permit the whole system to enter Kalman mode? Not doing so
/// is usually a bad idea, unless you're doing something special like
/// development on the tracker itself...
bool permitKalman = true;
/// Time offset for the camera timestamp, in microseconds.
/// Default is measured on Windows 10 version 1511.
std::int32_t cameraMicrosecondsOffset = -27000;
/// Should we permit a reset to be "soft" (blended by a Kalman) rather
/// than a hard state setting, in certain conditions? Only available in
/// the Unified tracker.
bool softResets = false;
/// Soft reset data incorporation parameter: Positional variance scale -
/// multiplied by the square of the distance from the camera.
double softResetPositionVarianceScale = 1.e-1;
/// Soft reset data incorporation parameter: Orientation variance
double softResetOrientationVariance = 1.e0;
ConfigParams();
};
} // namespace vbtracker
} // namespace osvr
#endif // INCLUDED_ConfigParams_h_GUID_22101CEF_879B_4781_2733_F5F7AE4E3633
| 41.415225
| 80
| 0.66572
|
[
"vector",
"model"
] |
5ecf84a6cca35dd93593d017d3cdbebd15bd8ab7
| 10,114
|
h
|
C
|
Sources/Elastos/Frameworks/Droid/Base/Packages/SystemUI/inc/elastos/droid/systemui/recents/model/RecentsTaskLoader.h
|
jingcao80/Elastos
|
d0f39852356bdaf3a1234743b86364493a0441bc
|
[
"Apache-2.0"
] | 7
|
2017-07-13T10:34:54.000Z
|
2021-04-16T05:40:35.000Z
|
Sources/Elastos/Frameworks/Droid/Base/Packages/SystemUI/inc/elastos/droid/systemui/recents/model/RecentsTaskLoader.h
|
jingcao80/Elastos
|
d0f39852356bdaf3a1234743b86364493a0441bc
|
[
"Apache-2.0"
] | null | null | null |
Sources/Elastos/Frameworks/Droid/Base/Packages/SystemUI/inc/elastos/droid/systemui/recents/model/RecentsTaskLoader.h
|
jingcao80/Elastos
|
d0f39852356bdaf3a1234743b86364493a0441bc
|
[
"Apache-2.0"
] | 9
|
2017-07-13T12:33:20.000Z
|
2021-06-19T02:46:48.000Z
|
//=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#ifndef __ELASTOS_DROID_SYSTEMUI_RECENTS_MODEL_RECENTSTASKLOADER_H__
#define __ELASTOS_DROID_SYSTEMUI_RECENTS_MODEL_RECENTSTASKLOADER_H__
#include "_Elastos.Droid.SystemUI.h"
#include "Elastos.Droid.App.h"
#include "Elastos.Droid.Content.h"
#include "Elastos.Droid.Graphics.h"
#include "Elastos.Droid.Os.h"
#include "Elastos.CoreLibrary.Utility.h"
#include "Elastos.CoreLibrary.Utility.Concurrent.h"
#include <elastos/core/Runnable.h>
#include "elastos/droid/systemui/recents/RecentsConfiguration.h"
#include "elastos/droid/systemui/recents/misc/SystemServicesProxy.h"
#include "elastos/droid/systemui/recents/model/BitmapLruCache.h"
#include "elastos/droid/systemui/recents/model/DrawableLruCache.h"
#include "elastos/droid/systemui/recents/model/RecentsPackageMonitor.h"
#include "elastos/droid/systemui/recents/model/StringLruCache.h"
using Elastos::Droid::App::IActivityManagerTaskDescription;
using Elastos::Droid::Content::IContext;
using Elastos::Droid::Content::Res::IResources;
using Elastos::Droid::Content::Pm::IActivityInfo;
using Elastos::Droid::Graphics::IBitmap;
using Elastos::Droid::Graphics::Drawable::IBitmapDrawable;
using Elastos::Droid::Os::IHandler;
using Elastos::Droid::Os::IHandlerThread;
using Elastos::Core::Runnable;
using Elastos::Droid::SystemUI::Recents::Misc::SystemServicesProxy;
using Elastos::Droid::SystemUI::Recents::Model::BitmapLruCache;
using Elastos::Droid::SystemUI::Recents::Model::DrawableLruCache;
using Elastos::Droid::SystemUI::Recents::Model::IPackageCallbacks;
using Elastos::Droid::SystemUI::Recents::Model::ITask;
using Elastos::Droid::SystemUI::Recents::Model::ITaskKey;
using Elastos::Droid::SystemUI::Recents::Model::RecentsPackageMonitor;
using Elastos::Droid::SystemUI::Recents::Model::StringLruCache;
using Elastos::Utility::ICollection;
using Elastos::Utility::Concurrent::IConcurrentLinkedQueue;
namespace Elastos {
namespace Droid {
namespace SystemUI {
namespace Recents {
namespace Model {
/* Recents task loader
* NOTE: We should not hold any references to a Context from a static instance */
class RecentsTaskLoader
: public Object
{
private:
/** Handle to an ActivityInfo */
class ActivityInfoHandle
: public Object
{
public:
AutoPtr<IActivityInfo> mInfo;
};
/** A bitmap load queue */
class TaskResourceLoadQueue
: public Object
{
public:
AutoPtr<IConcurrentLinkedQueue> mQueue;
public:
TaskResourceLoadQueue();
/** Adds a new task to the load queue */
CARAPI_(void) AddTasks(
/* [in] */ ICollection* tasks);
/** Adds a new task to the load queue */
CARAPI_(void) AddTask(
/* [in] */ ITask* t);
/**
* Retrieves the next task from the load queue, as well as whether we want that task to be
* force reloaded.
*/
CARAPI_(AutoPtr<ITask>) NextTask();
/** Removes a task from the load queue */
CARAPI_(void) RemoveTask(
/* [in] */ ITask* t);
/** Clears all the tasks from the load queue */
CARAPI_(void) ClearTasks();
/** Returns whether the load queue is empty */
CARAPI_(Boolean) IsEmpty();
};
/* Task resource loader */
class TaskResourceLoader
: public Runnable
{
public:
/** Constructor, creates a new loading thread that loads task resources in the background */
TaskResourceLoader(
/* [in] */ TaskResourceLoadQueue* loadQueue,
/* [in] */ DrawableLruCache* applicationIconCache,
/* [in] */ BitmapLruCache* thumbnailCache,
/* [in] */ IBitmap* defaultThumbnail,
/* [in] */ IBitmapDrawable* defaultApplicationIcon);
/** Restarts the loader thread */
CARAPI_(void) Start(
/* [in] */ IContext* context);
/** Requests the loader thread to stop after the current iteration */
CARAPI_(void) Stop();
// @Override
CARAPI Run();
CARAPI_(AutoPtr<IDrawable>) GetTaskDescriptionIcon(
/* [in] */ ITaskKey* taskKey,
/* [in] */ IBitmap* iconBitmap,
/* [in] */ const String& iconFilename,
/* [in] */ SystemServicesProxy* ssp,
/* [in] */ IResources* res);
public:
AutoPtr<IContext> mContext;
AutoPtr<IHandlerThread> mLoadThread;
AutoPtr<IHandler> mLoadThreadHandler;
AutoPtr<IHandler> mMainThreadHandler;
AutoPtr<SystemServicesProxy> mSystemServicesProxy;
AutoPtr<TaskResourceLoadQueue> mLoadQueue;
AutoPtr<DrawableLruCache> mApplicationIconCache;
AutoPtr<BitmapLruCache> mThumbnailCache;
AutoPtr<IBitmap> mDefaultThumbnail;
AutoPtr<IBitmapDrawable> mDefaultApplicationIcon;
Boolean mCancelled;
Boolean mWaitingOnLoadQueue;
};
class MyRunnable
: public Runnable
{
public:
MyRunnable(
/* [in] */ ITask* t,
/* [in] */ IDrawable* d,
/* [in] */ IBitmap* b);
//@Override
CARAPI Run();
private:
AutoPtr<ITask> mTask;
AutoPtr<IDrawable> mNewIcon;
AutoPtr<IBitmap> mNewThumbnail;
};
private:
/** Private Constructor */
RecentsTaskLoader(
/* [in] */ IContext* context);
public:
/** Initializes the recents task loader */
static CARAPI_(AutoPtr<RecentsTaskLoader>) Initialize(
/* [in] */ IContext* context);
/** Returns the current recents task loader */
static CARAPI_(AutoPtr<RecentsTaskLoader>) GetInstance();
/** Returns the system services proxy */
CARAPI GetSystemServicesProxy(
/* [out] */ SystemServicesProxy** ssp);
private:
/** Gets the list of recent tasks, ordered from back to front. */
static CARAPI_(AutoPtr<IList>) GetRecentTasks(
/* [in] */ SystemServicesProxy* ssp,
/* [in] */ Boolean isTopTaskHome);
public:
/** Returns the activity icon using as many cached values as we can. */
CARAPI_(AutoPtr<IDrawable>) GetAndUpdateActivityIcon(
/* [in] */ ITaskKey* taskKey,
/* [in] */ IActivityManagerTaskDescription* td,
/* [in] */ SystemServicesProxy* ssp,
/* [in] */ IResources* res,
/* [in] */ ActivityInfoHandle* infoHandle,
/* [in] */ Boolean preloadTask);
/** Returns the activity label using as many cached values as we can. */
CARAPI_(String) GetAndUpdateActivityLabel(
/* [in] */ ITaskKey* taskKey,
/* [in] */ IActivityManagerTaskDescription* td,
/* [in] */ SystemServicesProxy* ssp,
/* [in] */ ActivityInfoHandle* infoHandle);
/** Returns the activity's primary color. */
CARAPI_(Int32) GetActivityPrimaryColor(
/* [in] */ IActivityManagerTaskDescription* td,
/* [in] */ RecentsConfiguration* config);
/** Reload the set of recent tasks */
CARAPI_(AutoPtr<ISpaceNode>) Reload(
/* [in] */ IContext* context,
/* [in] */ Int32 preloadCount,
/* [in] */ Boolean isTopTaskHome);
/** Creates a lightweight stack of the current recent tasks, without thumbnails and icons. */
CARAPI_(AutoPtr<ITaskStack>) GetTaskStack(
/* [in] */ SystemServicesProxy* ssp,
/* [in] */ IResources* res,
/* [in] */ Int32 preloadTaskId,
/* [in] */ Int32 preloadTaskCount,
/* [in] */ Boolean loadTaskThumbnails,
/* [in] */ Boolean isTopTaskHome,
/* [in] */ IList* taskKeysOut,
/* [in] */ IList* tasksToLoadOut);
/** Acquires the task resource data directly from the pool. */
CARAPI_(void) LoadTaskData(
/* [in] */ ITask* t);
/** Releases the task resource data back into the pool. */
CARAPI_(void) UnloadTaskData(
/* [in] */ ITask* t);
/** Completely removes the resource data from the pool. */
CARAPI_(void) DeleteTaskData(
/* [in] */ ITask* t,
/* [in] */ Boolean notifyTaskDataUnloaded);
/** Stops the task loader and clears all pending tasks */
CARAPI_(void) StopLoader();
/** Registers any broadcast receivers. */
CARAPI_(void) RegisterReceivers(
/* [in] */ IContext* context,
/* [in] */ IPackageCallbacks* cb);
/** Unregisters any broadcast receivers. */
CARAPI_(void) UnregisterReceivers();
/**
* Handles signals from the system, trimming memory when requested to prevent us from running
* out of memory.
*/
CARAPI_(void) OnTrimMemory(
/* [in] */ Int32 level);
private:
static const String TAG;
public:
static AutoPtr<RecentsTaskLoader> sInstance;
AutoPtr<SystemServicesProxy> mSystemServicesProxy;
AutoPtr<DrawableLruCache> mApplicationIconCache;
AutoPtr<BitmapLruCache> mThumbnailCache;
AutoPtr<StringLruCache> mActivityLabelCache;
AutoPtr<TaskResourceLoadQueue> mLoadQueue;
AutoPtr<TaskResourceLoader> mLoader;
AutoPtr<RecentsPackageMonitor> mPackageMonitor;
Int32 mMaxThumbnailCacheSize;
Int32 mMaxIconCacheSize;
AutoPtr<IBitmapDrawable> mDefaultApplicationIcon;
AutoPtr<IBitmap> mDefaultThumbnail;
};
} // namespace Model
} // namespace Recents
} // namespace SystemUI
} // namespace Droid
} // namespace Elastos
#endif // __ELASTOS_DROID_SYSTEMUI_RECENTS_MODEL_RECENTSTASKLOADER_H__
| 34.053872
| 100
| 0.651572
|
[
"object",
"model"
] |
5eef6787995ec8f9d975336e0847ba9435231795
| 5,656
|
h
|
C
|
quill/quill/include/quill/Logger.h
|
iSLC/quill
|
7d2d85e1afc871a863d05f144e91bf673105bb52
|
[
"MIT"
] | null | null | null |
quill/quill/include/quill/Logger.h
|
iSLC/quill
|
7d2d85e1afc871a863d05f144e91bf673105bb52
|
[
"MIT"
] | null | null | null |
quill/quill/include/quill/Logger.h
|
iSLC/quill
|
7d2d85e1afc871a863d05f144e91bf673105bb52
|
[
"MIT"
] | 1
|
2020-04-10T12:35:50.000Z
|
2020-04-10T12:35:50.000Z
|
/**
* Copyright(c) 2020-present, Odysseas Georgoudis & quill contributors.
* Distributed under the MIT License (http://opensource.org/licenses/MIT)
*/
#pragma once
#include "quill/LogLevel.h"
#include "quill/detail/LoggerDetails.h"
#include "quill/detail/ThreadContextCollection.h"
#include "quill/detail/misc/Macros.h"
#include "quill/detail/misc/Utilities.h"
#include "quill/detail/record/LogRecord.h"
#include <atomic>
#include <cstdint>
#include <vector>
namespace quill
{
namespace detail
{
class LoggerCollection;
}
/**
* Thread safe logger.
* Logger must be obtained from LoggerCollection get_logger(), therefore constructors are private
*/
class alignas(detail::CACHELINE_SIZE) Logger
{
public:
/**
* Deleted
*/
Logger(Logger const&) = delete;
Logger& operator=(Logger const&) = delete;
/**
* We align the logger object to it's own cache line. It shouldn't make much difference as the
* logger object size is exactly 1 cache line
* @param i
* @return
*/
void* operator new(size_t i) { return detail::aligned_alloc(detail::CACHELINE_SIZE, i); }
void operator delete(void* p) { detail::aligned_free(p); }
/**
* @return The log level of the logger
*/
QUILL_NODISCARD LogLevel log_level() const noexcept
{
return _log_level.load(std::memory_order_relaxed);
}
/**
* Set the log level of the logger
* @param log_level The new log level
*/
void set_log_level(LogLevel log_level) noexcept
{
_log_level.store(log_level, std::memory_order_relaxed);
}
/**
* Checks if the given log_statement_level can be logged by this logger
* @param log_statement_level The log level of the log statement to be logged
* @return
*/
QUILL_NODISCARD bool should_log(LogLevel log_statement_level) const noexcept
{
return log_statement_level >= log_level();
}
/**
* Checks if the given log_statement_level can be logged by this logger
* @tparam log_statement_level
* @return
*/
template <LogLevel log_statement_level>
QUILL_NODISCARD_ALWAYS_INLINE_HOT bool should_log() const noexcept
{
return log_statement_level >= log_level();
}
/**
* Push a log record to the spsc queue to be logged by the backend thread.
* One queue per caller thread.
* We have this enable_if to use unlikely since no if constexpr in C++14
* @note This function is thread-safe.
*/
template <LogLevel log_statement_level, typename... FmtArgs>
QUILL_ALWAYS_INLINE_HOT
typename std::enable_if_t<(log_statement_level == LogLevel::TraceL3 || log_statement_level == LogLevel::TraceL2 ||
log_statement_level == LogLevel::TraceL1 || log_statement_level == LogLevel::Debug),
void>
log(detail::StaticLogRecordInfo const* log_line_info, FmtArgs&&... fmt_args)
{
// it is usually likely we will not log those levels
if (QUILL_LIKELY(!should_log<log_statement_level>()))
{
return;
}
// Resolve the type of the record first
using log_record_t = quill::detail::LogRecord<FmtArgs...>;
// emplace to the spsc queue owned by the ctx
_thread_context_collection.local_thread_context()->spsc_queue().emplace<log_record_t>(
log_line_info, std::addressof(_logger_details), std::forward<FmtArgs>(fmt_args)...);
}
/**
* Push a log record to the spsc queue to be logged by the backend thread.
* One queue per caller thread.
* We have this enable_if to use unlikely since no if constexpr in C++14
* @note This function is thread-safe.
*/
template <LogLevel log_statement_level, typename... FmtArgs>
QUILL_ALWAYS_INLINE_HOT
typename std::enable_if_t<(log_statement_level == LogLevel::Info || log_statement_level == LogLevel::Warning ||
log_statement_level == LogLevel::Error || log_statement_level == LogLevel::Critical),
void>
log(detail::StaticLogRecordInfo const* log_line_info, FmtArgs&&... fmt_args)
{
// it is usually unlikely we will not log those levels
if (QUILL_UNLIKELY(!should_log<log_statement_level>()))
{
return;
}
// Resolve the type of the record first
using log_record_t = quill::detail::LogRecord<FmtArgs...>;
// emplace to the spsc queue owned by the ctx
_thread_context_collection.local_thread_context()->spsc_queue().emplace<log_record_t>(
log_line_info, std::addressof(_logger_details), std::forward<FmtArgs>(fmt_args)...);
}
private:
friend class detail::LoggerCollection;
/**
* Constructs new logger object
* @param logger_id A unique id per logger
* @param log_level The log level of the logger
*/
Logger(char const* name, Handler* handler, detail::ThreadContextCollection& thread_context_collection)
: _logger_details(name, handler), _thread_context_collection(thread_context_collection)
{
}
/**
* Constructs a new logger object with multiple handlers
* @param name
* @param handlers
* @param thread_context_collection
*/
Logger(char const* name, std::vector<Handler*> handlers, detail::ThreadContextCollection& thread_context_collection)
: _logger_details(name, std::move(handlers)), _thread_context_collection(thread_context_collection)
{
}
private:
detail::LoggerDetails _logger_details;
detail::ThreadContextCollection& _thread_context_collection;
std::atomic<LogLevel> _log_level{LogLevel::Info};
};
#if !(defined(_WIN32) && defined(_DEBUG))
// In MSVC debug mode the class has increased size
static_assert(sizeof(Logger) <= detail::CACHELINE_SIZE, "Logger needs to fit in 1 cache line");
#endif
} // namespace quill
| 32.32
| 118
| 0.70686
|
[
"object",
"vector"
] |
5ef11cd198acea51608bec01efafd8e8f4cb3759
| 5,120
|
h
|
C
|
src/types.h
|
dorodnic/playground
|
1c64aa0ce4a5697a33cac19896705ec7de430952
|
[
"Unlicense"
] | null | null | null |
src/types.h
|
dorodnic/playground
|
1c64aa0ce4a5697a33cac19896705ec7de430952
|
[
"Unlicense"
] | null | null | null |
src/types.h
|
dorodnic/playground
|
1c64aa0ce4a5697a33cac19896705ec7de430952
|
[
"Unlicense"
] | null | null | null |
#pragma once
#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <string>
#include <sstream>
#include <fstream>
#ifdef WIN32
#undef min
#undef max
#endif
enum class Orientation
{
vertical,
horizontal
};
template<typename T>
inline T clamp(T val, T from, T to) { return std::max(from, std::min(to, val)); }
inline float mix(float a, float b, float t)
{
return a * (1 - t) + b * t;
}
typedef std::unordered_map<std::string, std::string> PropertyBag;
struct str
{
operator std::string() const
{
return _ss.str();
}
template<class T>
str& operator<<(T&& t)
{
_ss << t;
return *this;
}
std::ostringstream _ss;
};
struct Color3 {
float r, g, b;
Color3 brighten(float f) const
{
return { clamp(r * f, 0.0f, 1.0f),
clamp(g * f, 0.0f, 1.0f),
clamp(b * f, 0.0f, 1.0f) };
}
Color3 operator-() const
{
return { 1.0f - r, 1.0f - g, 1.0f - b };
}
Color3 to_grayscale() const
{
auto avg = (r + g + b) / 3;
return { avg, avg, avg };
}
Color3 mix_with(const Color3& other, float t) const
{
return { mix(r, other.r, t),
mix(g, other.b, t),
mix(b, other.b, t) };
}
};
inline std::ostream & operator << (std::ostream & o, const Color3& c)
{
o << (int)(255 * c.r) << ","
<< (int)(255 * c.g) << ","
<< (int)(255 * c.b);
return o;
}
inline std::string read_all_text(const std::string& filename)
{
std::ifstream stream(filename, std::ios::in);
if(!stream.is_open())
{
throw std::runtime_error(str() << "File '" << filename << "' not found!");
}
auto buffer = std::vector<char>((std::istreambuf_iterator<char>(stream)),
std::istreambuf_iterator<char>());
buffer.push_back('\0');
return std::string(buffer.data());
}
class Size
{
public:
Size() : _pixels(0), _is_pixels(true) {} // Default is Auto
Size(int pixels) : _pixels(pixels) {}
Size(float percents)
: _percents(percents), _is_pixels(false) {}
static Size All() { return Size(1.0f); }
static Size Nth(int n) { return Size(1.0f / n); }
static Size Auto() { return Size(0); }
int to_pixels(int base_pixels) const
{
if (_is_pixels) return _pixels;
else return (int) (_percents * base_pixels);
}
bool is_const() const { return _is_pixels; }
float get_percents() const { return _percents; }
int get_pixels() const { return _pixels; }
bool is_auto() const { return _pixels == 0 && _is_pixels; }
Size add_pixels(int px) const
{
if (_is_pixels && _pixels != 0) return Size(_pixels + px);
else return *this;
}
private:
int _pixels;
float _percents;
bool _is_pixels = true;
};
struct Size2
{
Size x, y;
};
inline std::ostream & operator << (std::ostream & o, const Size& r)
{
if (r.is_auto()) o << "auto";
else if (r.is_const()) o << r.get_pixels() << "px";
else o << (int)(r.get_percents() * 100) << "%";
return o;
}
inline Size2 Auto() { return { Size::Auto(), Size::Auto() }; }
inline std::ostream & operator << (std::ostream & o, const Size2& r)
{
return o << r.x << ", " << r.y;
}
struct Int2 {
int x, y;
};
inline bool operator==(const Int2& a, const Int2& b) {
return (a.x == b.x) && (a.y == b.y);
}
inline std::ostream & operator << (std::ostream & o, const Int2& r)
{
return o << "(" << r.x << ", " << r.y << ")";
}
struct Rect
{
Int2 position, size;
};
inline bool operator==(const Rect& a, const Rect& b)
{
return (a.position == b.position) && (a.size == b.size);
}
inline std::ostream & operator << (std::ostream & o, const Rect& r)
{
return o << "[" << r.position << ", " << r.size << "]";
}
inline bool contains(const Rect& rect, const Int2& v)
{
return (rect.position.x <= v.x && rect.position.x + rect.size.x >= v.x) &&
(rect.position.y <= v.y && rect.position.y + rect.size.y >= v.y);
}
struct Margin
{
int left, right, top, bottom;
Margin(int v) : left(v), right(v), top(v), bottom(v) {}
Margin(int x, int y) : left(x), right(x), top(y), bottom(y) {}
Margin(int left, int top, int right, int bottom)
: left(left), right(right), top(top), bottom(bottom) {}
operator bool() const {
return left != 0 || right != 0 || top != 0 || bottom != 0;
}
Margin operator-()
{
return { -left, -right, -top, -bottom };
}
Rect apply(const Rect& r) const
{
return { { r.position.x - left, r.position.y - top },
{ r.size.x + left + right, r.size.y + top + bottom } };
}
Size2 apply(const Size2 s) const
{
return { s.x.add_pixels(left + right), s.y.add_pixels(top + bottom) };
}
};
enum class MouseButton
{
left,
middle,
right
};
enum class MouseState
{
down,
up
};
enum class Alignment
{
left,
center,
right
};
| 22.068966
| 82
| 0.538281
|
[
"vector"
] |
5ef4298e46ce94a153c296b4b00f307bec1853f7
| 22,709
|
h
|
C
|
toolkit/toolkit.h
|
barbalet/nobleape
|
fb118007ba83b7b24734e2bc2a1e37fd889c4e53
|
[
"Unlicense"
] | 28
|
2015-01-17T15:18:42.000Z
|
2019-12-04T23:02:30.000Z
|
toolkit/toolkit.h
|
barbalet/apesdk
|
fb118007ba83b7b24734e2bc2a1e37fd889c4e53
|
[
"Unlicense"
] | 18
|
2020-02-27T22:59:18.000Z
|
2020-03-03T11:16:07.000Z
|
toolkit/toolkit.h
|
barbalet/apesdk
|
fb118007ba83b7b24734e2bc2a1e37fd889c4e53
|
[
"Unlicense"
] | null | null | null |
/****************************************************************
toolkit.h
=============================================================
Copyright 1996-2020 Tom Barbalet. 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.
This software is a continuing work of Tom Barbalet, begun on
13 June 1996. No apes or cats were harmed in the writing of
this software.
****************************************************************/
/*! \file toolkit.h
* \brief This is the interface between the ApeSDK toolkit and what consumes
the ApeSDK toolkit.
*/
#ifndef _TOOLKIT_H_
#define _TOOLKIT_H_
/* Variable Definitions */
#include <signal.h> // for SIMULATED_APE_ASSERT
#undef COMMAND_LINE_DEBUG /* Sends the debug output as printf output - added through command line build */
#define CHAR_SPACE (32)
#define IS_RETURN(val) (((val) == 10) || ((val) == 13))
#define IS_SPACE(val) ((val) == CHAR_SPACE)
#undef SIMULATED_APE_ASSERT
#define PACKED_DATA_BLOCK (32*32*32*2)
typedef double n_double;
#define TWO_PI ((n_double)(6.2831853071795864769252867665590057683943))
#define SINE_MAXIMUM (26880)
#define BIG_INTEGER (2147483647)
#define BIG_NEGATIVE_INTEGER (0-2147483648)
#define NOTHING (0L)
typedef char n_char;
/*! @typedef n_string
@discussion This is the string format for the Simulated Ape development */
typedef n_char * n_string;
typedef const n_char * n_constant_string;
#define STRING_BLOCK_SIZE (2048)
typedef n_char n_string_block[STRING_BLOCK_SIZE];
/*! @typedef n_byte
@discussion This is a single byte data unit. */
typedef unsigned char n_byte;
/*! @typedef n_byte2
@discussion This is a two byte data unit. There is no
expectations on the byte ordering. */
typedef unsigned short n_byte2;
typedef unsigned int n_byte4;
typedef int n_c_int;
#ifndef _WIN64
/*! @typedef n_uint
@discussion This is a four byte data unit. Please note that
this form may be shown as unsigned int on some 64-bit
implementations. */
typedef unsigned long n_uint;
/*! @typedef n_int
@discussion This is the native integer data unit. It can be
whatever length is specified by the implementation. */
typedef long n_int;
#else
typedef unsigned long long n_uint;
typedef long long n_int;
#endif
typedef enum
{
FILE_TYPE_BYTE = 0x01,
FILE_TYPE_BYTE2 = 0x02,
FILE_TYPE_BYTE_EXT = 0x03,
FILE_TYPE_PACKED = 0x05,
FILE_TYPE_BYTE4 = 0x06
} file_element_type;
#ifdef SIMULATED_APE_ASSERT
#define NA_ASSERT(test, message) if(!(test)){io_assert(message, __FILE__, __LINE__); raise(SIGINT);}
void io_assert(n_string message, n_string file_loc, n_int line);
#else
#define NA_ASSERT(test, message) /* test message */
#endif
typedef union
{
struct
{
n_int x;
n_int y;
};
n_int data[2];
}n_vect2;
typedef union
{
struct
{
n_vect2 top_left;
n_vect2 bottom_right;
};
n_int data[4];
} n_area2;
typedef union
{
struct
{
n_double x;
n_double y;
n_double z;
};
n_double data[3];
} n_vect3;
typedef struct {
n_byte r;
n_byte g;
n_byte b;
n_byte a;
}n_rgba;
typedef union
{
n_rgba rgba;
n_byte4 thirtytwo;
}n_rgba32;
typedef struct {
n_vect2 * points;
n_int no_of_points;
n_int max_points;
}n_points;
typedef struct
{
n_byte4 date;
n_byte2 location[2];
n_byte4 time;
}
n_spacetime;
/*! @struct
@field characters Characters that represent these values in the file.
@field incl_kind Included type and the kind of value combined together.
@field number Number of these values.
@field location Byte location of the start of these values within the struct.
@field what_is_it Provides a string output for HTML documentation for the user.
@discussion This is the line by line definition of the Simulated Ape file types.
*/
typedef struct
{
n_byte characters[7];
n_byte incl_kind;
n_uint number_entries;
n_uint start_location;
const n_string what_is_it;
} simulated_file_entry;
#define POPULATED(ch) ((ch[0] != 0) || (ch[1] != 0) || (ch[2] != 0) || (ch[3] != 0) || (ch[4] != 0) || (ch[5] != 0))
/* include externally, if needed */
#define FILE_COPYRIGHT 0x00
#define FILE_INCL(num) ((num) & 0xf0)
#define FILE_KIND(num) ((num) & 0x0f)
#define FILE_EOF 0x0100
#define ASCII_NUMBER(val) (((val) >= '0') && ((val) <= '9'))
#define ASCII_LOWERCASE(val) (((val) >= 'a') && ((val) <= 'z'))
#define ASCII_UPPERCASE(val) (((val) >= 'A') && ((val) <= 'Z'))
#define FILE_OKAY 0x0000
#define FILE_ERROR (-1)
typedef n_byte (n_pixel)(n_int px, n_int py, n_int dx, n_int dy, void * information);
typedef n_int (n_memory_location)(n_int px, n_int py);
typedef n_byte2 (n_patch)(n_byte2 * local);
typedef n_int (n_file_in)(n_byte * buff, n_uint len);
typedef n_byte * (n_file_out)(n_uint * len);
/*! @struct
@field pixel_draw The n_pixel function used to draw pixels into
the window buffer.
@field information This is the pointer information passed into
the pixel_draw function.
@discussion This drawing interface was designed to write to
window buffer information where the window buffer could be
either color or monochrome. The interface needed to be relatively
independent to allow for text to be written into either a color
window or a monochrome window or a line to be drawn through
either window buffer without there being any difference in the
implementation algorithm. Think of this method as a way of
translating high-level drawing and low-level drawing.
*/
typedef struct
{
n_pixel * pixel_draw;
void * information;
} n_join;
typedef struct
{
n_byte * screen;
n_byte * background;
} n_background8;
typedef struct
{
n_byte * screen;
n_byte color;
} n_color8;
/*! @struct
@field size The size of the file in bytes.
@field location The location of the accessing pointer within the
file. This is useful for both input and output files.
@field data The data stored in bytes.
@discussion This is the primary file handling structure in the ApeSDK. It is used for both input and output files. It is the method
used to pass file information from the platform layer into the
platform independent layers of Simulated Ape.
*/
typedef struct
{
n_uint size;
n_uint location;
n_byte *data;
} n_file;
typedef void (n_file_specific)(n_string string, n_byte * reference);
typedef struct
{
void * data;
n_uint expected_bytes;
n_uint hash;
void * next;
} n_file_chain;
typedef enum
{
OBJECT_EMPTY = 0,
OBJECT_STRING,
OBJECT_NUMBER,
OBJECT_OBJECT,
OBJECT_ARRAY = 4,
}n_object_type;
typedef enum
{
OBJ_TYPE_EMPTY = 0,
OBJ_TYPE_STRING_NOTATION,
OBJ_TYPE_NUMBER,
OBJ_TYPE_COLON,
OBJ_TYPE_COMMA,
OBJ_TYPE_OBJECT_OPEN,
OBJ_TYPE_OBJECT_CLOSE,
OBJ_TYPE_ARRAY_OPEN,
OBJ_TYPE_ARRAY_CLOSE
}n_object_stream_type;
typedef struct
{
n_string data;
void* next;
n_object_type type;
}n_array;
typedef struct
{
n_array primitive;
n_string name;
n_uint name_hash;
}n_object;
n_file * obj_json(n_object * object);
n_array * array_number(n_int set_number);
n_array * array_string(n_string set_string);
n_array * array_object(n_object * set_object);
n_array * array_array(n_array * set_array);
n_array * array_add(n_array * array, n_array * element);
n_object * object_number(n_object * obj, n_string name, n_int number);
n_object * object_string(n_object * obj, n_string name, n_string string);
n_object * object_object(n_object * obj, n_string name, n_object * object);
n_object * object_array(n_object * obj, n_string name, n_array * array);
void object_top_object(n_file * file, n_object * top_level);
n_object * object_file_to_tree(n_file * file);
void obj_free(n_object ** object);
n_string obj_contains(n_object* base, n_string name, n_object_type type);
n_int obj_contains_number(n_object* base, n_string name, n_int *number);
n_int obj_contains_array_numbers(n_object* base, n_string name, n_int *array_numbers, n_int size);
n_int obj_contains_array_nbyte2(n_object* base, n_string name, n_byte2 *array_numbers, n_int size);
n_array * obj_get_array(n_string array);
n_object * obj_get_object(n_string object);
n_int obj_get_number(n_string object);
n_array * obj_array_next(n_array * array, n_array * element);
n_int obj_array_count(n_array * array_obj);
/** \brief sine and cosine conversation */
#define NEW_SD_MULTIPLE 26880
extern n_int draw_error(n_constant_string error_text, n_constant_string location, n_int line_number);
#define SHOW_ERROR(val) (draw_error(val, __FILE__, __LINE__))
#define IO_LOWER_CHAR(value) if(ASCII_UPPERCASE(value)) (value) += 'a' - 'A'
typedef n_int (execute_function)(void * general_data, void * read_data, void * write_data);
typedef void (execute_thread_stub)(execute_function function, void * general_data, void * read_data, void * write_data);
void execute_group(execute_function * function, void * general_data, void * read_data, n_int count, n_int size);
void area2_add(n_area2 * area, n_vect2 * vect, n_byte first);
n_int vect2_distance_under(n_vect2 * first, n_vect2 * second, n_int distance);
void vect2_byte2(n_vect2 * converter, n_byte2 * input);
void vect2_add(n_vect2 * equals, n_vect2 * initial, n_vect2 * second);
void vect2_center(n_vect2 * center, n_vect2 * initial, n_vect2 * second);
void vect2_subtract(n_vect2 * equals, n_vect2 * initial, n_vect2 * second);
void vect2_divide(n_vect2 * equals, n_vect2 * initial, n_vect2 * second, n_int divisor);
void vect2_multiplier(
n_vect2 * equals, n_vect2 * initial,
n_vect2 * second, n_int multiplier, n_int divisor);
void vect2_d(
n_vect2 * initial, n_vect2 * second,
n_int multiplier, n_int divisor);
n_int vect2_dot(
n_vect2 * initial, n_vect2 * second,
n_int multiplier, n_int divisor);
void vect2_rotate90(n_vect2 * rotation);
void vect2_direction(n_vect2 * initial, n_int direction, n_int divisor);
void vect2_delta(n_vect2 * initial, n_vect2 * delta);
void vect2_offset(n_vect2 * initial, n_int dx, n_int dy);
void vect2_back_byte2(n_vect2 * converter, n_byte2 * output);
void vect2_copy(n_vect2 * to, n_vect2 * from);
void vect2_populate(n_vect2 * value, n_int x, n_int y);
void vect2_rotation(n_vect2 * location, n_vect2 * rotation);
void vect2_rotation_bitshift(n_vect2 * location, n_vect2 * rotation);
n_int vect2_nonzero(n_vect2 * nonzero);
n_vect2 * vect2_min_max_init(void);
void vect2_min_max(n_vect2 * points, n_int number, n_vect2 * maxmin);
void vect2_scalar_multiply(n_vect2 * value, n_int multiplier);
void vect2_scalar_divide(n_vect2 * value, n_int divisor);
void vect2_scalar_bitshiftdown(n_vect2 * value, n_int bitshiftdown);
void vect3_double(n_vect3 * converter, n_double * input);
void vect3_add(n_vect3 * equals, n_vect3 * initial, n_vect3 * second);
void vect3_center(n_vect3 * center, n_vect3 * initial, n_vect3 * second);
void vect3_subtract(n_vect3 * equals, n_vect3 * initial, n_vect3 * second);
void vect3_divide(n_vect3 * equals, n_vect3 * initial, n_vect3 * second, n_double divisor);
void vect3_multiplier(n_vect3 * equals, n_vect3 * initial, n_vect3 * second,
n_double multiplier, n_double divisor);
void vect3_d(n_vect3 * initial, n_vect3 * second, n_double multiplier, n_double divisor);
n_double vect3_dot(n_vect3 * initial, n_vect3 * second, n_double multiplier, n_double divisor);
void vect3_delta(n_vect3 * initial, n_vect3 * delta);
void vect3_offset(n_vect3 * initial, n_double dx, n_double dy, n_double dz);
void vect3_back_double(n_vect3 * converter, n_double * output);
void vect3_copy(n_vect3 * to, n_vect3 * from);
void vect3_populate(n_vect3 * value, n_double x, n_double y, n_double z);
n_int vect3_nonzero(n_vect3 * nonzero);
n_byte * math_general_allocation(n_byte * bc0, n_byte * bc1, n_int i);
void math_general_execution(n_int instruction, n_int is_constant0, n_int is_constant1,
n_byte * addr0, n_byte * addr1, n_int value0, n_int * i,
n_int is_const0, n_int is_const1,
n_byte * pspace,
n_byte *bc0, n_byte *bc1,
n_int braincode_min_loop);
n_byte4 math_hash_fnv1(n_constant_string key);
n_uint math_hash(n_byte * values, n_uint length);
void math_bilinear_8_times(n_byte * side512, n_byte * data, n_byte double_spread);
n_uint math_root(n_uint squ);
n_byte math_turn_towards(n_vect2 * p, n_byte fac, n_byte turn);
#undef DEBUG_RANDOM
#undef VERBOSE_DEBUG_RANDOM
#ifdef DEBUG_RANDOM
#include <stdio.h>
#define math_random(num) math_random_debug(num, __FILE__, __LINE__)
#define math_random3(num) math_random_debug(num, __FILE__, __LINE__)
#define mrdc(string) math_random_debug_count(string)
n_byte2 math_random_debug(n_byte2 * local, n_string file_string, n_int line_number);
void math_random_debug_count(n_string place);
#else
#define mrdc(string) /* math_random_debug_count(string) */
n_byte2 math_random(n_byte2 * local);
void math_random3(n_byte2 * local);
#endif
n_byte math_join(n_int sx, n_int sy, n_int dx, n_int dy, n_join * draw);
n_int math_spread_byte(n_byte val);
n_int math_sine(n_int direction, n_int divisor);
n_byte math_join_vect2(n_int sx, n_int sy, n_vect2 * vect, n_join * draw);
n_byte math_line_vect(n_vect2 * point1, n_vect2 * point2, n_join * draw);
n_byte math_line(n_int x1, n_int y1, n_int x2, n_int y2, n_join * draw);
n_int math_seg14(n_int character);
n_byte math_do_intersect(n_vect2 * p1, n_vect2 * q1, n_vect2 * p2, n_vect2 * q2);
void io_number_to_string(n_string value, n_uint number);
void io_string_number(n_string output_string, n_string input_string, n_uint number);
void io_three_strings(n_string output_string, n_string first_string, n_string second_string, n_string third_string, n_byte new_line);
void io_entry_execution(n_int argc, n_string * argv);
void io_command_line_execution_set(void);
n_int io_command_line_execution(void);
void io_lower(n_string value, n_int length);
void io_whitespace(n_file * input);
void io_whitespace_json(n_file * input);
void io_audit_file(const simulated_file_entry * format, n_byte section_to_audit);
void io_search_file_format(const simulated_file_entry * format, n_string compare);
void io_string_write(n_string dest, n_string insert, n_int * pos);
n_int io_read_bin(n_file * fil, n_byte * local_byte);
n_int io_file_write(n_file * fil, n_byte byte);
void io_file_reused(n_file * fil);
n_int io_write(n_file * fil, n_constant_string ch, n_byte new_line);
n_int io_writenumber(n_file * fil, n_int loc_val, n_uint numer, n_uint denom);
n_int io_length(n_string value, n_int max);
n_int io_find(n_string check, n_int from, n_int max, n_string value_find, n_int value_find_length);
n_int io_read_buff(n_file * fil, n_byte * data, const simulated_file_entry * commands);
n_int io_write_buff(n_file * fil, void * data, const simulated_file_entry * commands, n_byte command_num, n_file_specific * func);
n_int io_write_csv(n_file * fil, n_byte * data, const simulated_file_entry * commands, n_byte command_num, n_byte initial) ;
void memory_copy(n_byte * from, n_byte * to, n_uint number);
void * memory_new(n_uint bytes);
void memory_free(void ** ptr);
void * memory_new_range(n_uint memory_min, n_uint *memory_allocated);
n_file * io_file_new(void);
void io_file_free(n_file ** file);
void io_file_debug(n_file * file);
n_int io_number(n_string number_string, n_int * actual_value, n_int * decimal_divisor);
void memory_erase(n_byte * buf_offscr, n_uint nestop);
n_int io_disk_read(n_file * local_file, n_string file_name);
n_int io_disk_read_no_error(n_file * local_file, n_string file_name);
n_int io_disk_write(n_file * local_file, n_constant_string file_name);
n_int io_disk_check(n_constant_string file_name);
n_string * io_tab_delimit_to_n_string_ptr(n_file * tab_file, n_int * size_value, n_int * row_value);
void io_three_string_combination(n_string output, n_string first, n_string second, n_string third, n_int count);
void io_time_to_string(n_string value);
n_string io_string_copy(n_string string);
n_int io_read_byte4(n_file * fil, n_uint * actual_value, n_byte * final_char);
n_int io_writenum(n_file * fil, n_int loc_val, n_byte ekind, n_byte new_line);
n_int io_command(n_file * fil, const simulated_file_entry * commands);
n_int io_read_data(n_file * fil, n_byte2 command, n_byte * data_read);
void io_output_contents(n_file * file);
n_uint io_file_hash(n_file * file);
n_file * io_file_ready(n_int entry, n_file * file);
void io_file_cleanup(n_int * entry, n_file ** file);
void io_file_writeon(n_int * entry, n_file ** file, n_byte blocked_write);
void io_file_writeoff(n_int * entry, n_file * file);
void io_file_string(n_int entry, n_file * file, n_constant_string string);
n_uint io_find_size_data(simulated_file_entry * commands);
#define ASCII_QUOTE(num) ((num) == '"')
#define ASCII_TEXT(num) ((ASCII_UPPERCASE(num) || ASCII_LOWERCASE(num)) || ((num) == '_'))
#define ASCII_SEMICOLON(num) ((num) == ';')
#define ASCII_COLON(num) ((num) == ':')
#define ASCII_COMMA(num) ((num) == ',')
#define ASCII_EQUAL(num) ((num) == '=')
#define ASCII_BRACKET(num) (((num) == '(')||((num) == ')'))
#define ASCII_BRACES(num) (((num) == '{')||((num) == '}'))
#define ASCII_LOGICAL(num) ((((num) == '&')||((num) == '|'))||(((num) == '^')||((num) == '!')))
#define ASCII_ARITHMETIC(num) ((((num) == '+')||((num) == '-'))||(((num) == '*')||((num) == '/')))
#define ASCII_DIRECTIONAL(num) (((num)=='<')||((num)=='>'))
#define CODE_VALUE_REQUIRED(num) (((num) == APESCRIPT_OPERATOR || (num) == APESCRIPT_NUMBER) || ((num) == APESCRIPT_TEXT))
#define SIZEOF_NUMBER_WRITE (sizeof(n_int))
void io_int_to_bytes(n_int value, n_byte * bytes);
n_int io_bytes_to_int(n_byte * bytes);
#ifndef ABS
#define ABS(a) (((a) < 0) ? -(a) : (a))
#endif
typedef short n_audio;
#define AUDIO_FFT_MAX_BITS (15)
#define AUDIO_FFT_MAX_BUFFER (1<<AUDIO_FFT_MAX_BITS)
void audio_fft(n_byte inverse, n_uint power_sample);
void audio_new_fft(n_uint power_sample,
n_int InverseTransform,
n_double *RealIn,
n_double *ImagIn,
n_double *RealOut,
n_double *ImagOut );
void audio_clear_buffers(n_uint length);
void audio_clear_output(n_audio * audio, n_uint length);
void audio_equal_output(n_audio * audio, n_uint length);
void audio_multiply_output(n_audio * audio, n_uint length);
void audio_set_frequency(n_uint entry, n_uint value);
void audio_low_frequency(n_audio * buffer, n_int number_freq, n_int debug);
void audio_buffer_clear(n_audio * buffer, n_int size);
void audio_buffer_double_clear(n_double * buffer, n_int size);
void audio_buffer_copy_to_audio(n_double * buffer_double, n_audio * buffer_audio, n_int size);
void audio_buffer_copy_to_double(n_audio * buffer_audio, n_double * buffer_double, n_int size);
void audio_buffer_copy_to_double_double(n_double * buffer_double1, n_double * buffer_double2, n_int size);
void audio_buffer_copy_to_double_double(n_double * buffer_double_to, n_double * buffer_double_from, n_int size);
void graph_init(n_int four_byte_factory);
void graph_erase(n_byte * buffer, n_vect2 * img, n_rgba32 * color);
/* draws a line */
void graph_line(n_byte * buffer,
n_vect2 * img,
n_vect2 * previous,
n_vect2 * current,
n_rgba32 * color,
n_byte thickness);
void graph_curve(n_byte * buffer,
n_vect2 * img,
n_vect2 * pt0,
n_vect2 * pt1,
n_vect2 * pt2,
n_rgba32 * color,
n_byte radius_percent,
n_uint start_thickness,
n_uint end_thickness);
void graph_fill_polygon(n_vect2 * points, n_int no_of_points,
n_rgba32 * color, n_byte transparency,
n_byte * buffer, n_vect2 * img);
typedef n_string (n_console_input)(n_string value, n_int length);
typedef void (n_console_output)(n_constant_string value);
typedef n_int (n_console)(void * ptr, n_string response, n_console_output output_function);
typedef struct
{
n_console * function;
n_string command;
n_string addition;
n_string help_information;
} simulated_console_command;
void audio_aiff_header(void * fptr, n_uint total_samples);
n_int audio_aiff_is_header(void * fptr, n_uint *samples);
void audio_aiff_body(void * fptr, n_audio *samples, n_uint number_samples);
n_int io_quit(void * ptr, n_string response, n_console_output output_function);
n_int io_help(void * ptr, n_string response, n_console_output output_function);
n_string io_console_entry_clean(n_string string, n_int length);
n_string io_console_entry(n_string string, n_int length);
void io_console_out(n_constant_string value);
n_int io_console(void * ptr, simulated_console_command * commands, n_console_input input_function, n_console_output output_function);
void io_help_line(simulated_console_command * specific, n_console_output output_function);
void io_console_quit(void);
#endif /* _TOOLKIT_H_ */
| 33.248902
| 139
| 0.710775
|
[
"object"
] |
5efda3e24ce4a11824982a15fc91ebd78b1cd8d2
| 278
|
h
|
C
|
src/ltable.h
|
Agathon1/lemon
|
aceae9987b427c5321d73b5f6c210354b0e7a385
|
[
"MIT"
] | 566
|
2017-10-08T08:01:23.000Z
|
2022-02-11T14:21:50.000Z
|
src/ltable.h
|
Agathon1/lemon
|
aceae9987b427c5321d73b5f6c210354b0e7a385
|
[
"MIT"
] | 25
|
2017-10-25T10:45:15.000Z
|
2018-09-03T07:05:34.000Z
|
src/ltable.h
|
Agathon1/lemon
|
aceae9987b427c5321d73b5f6c210354b0e7a385
|
[
"MIT"
] | 53
|
2017-10-09T09:15:53.000Z
|
2022-02-06T14:12:17.000Z
|
#ifndef LEMON_LTABLE_H
#define LEMON_LTABLE_H
struct lobject;
struct ltable {
struct lobject object;
int count;
int length;
void *items;
};
void *
ltable_create(struct lemon *lemon);
struct ltype *
ltable_type_create(struct lemon *lemon);
#endif /* LEMON_LTABLE_H */
| 12.636364
| 40
| 0.744604
|
[
"object"
] |
e80dace891938c5ac5277ecec27e76279e94e0fa
| 6,166
|
h
|
C
|
dev/floyd_speak/parts/file_handling.h
|
lemonad/floyd
|
736d21f20d1bdab7082b4461d7b6330cb4b10224
|
[
"MIT"
] | null | null | null |
dev/floyd_speak/parts/file_handling.h
|
lemonad/floyd
|
736d21f20d1bdab7082b4461d7b6330cb4b10224
|
[
"MIT"
] | null | null | null |
dev/floyd_speak/parts/file_handling.h
|
lemonad/floyd
|
736d21f20d1bdab7082b4461d7b6330cb4b10224
|
[
"MIT"
] | null | null | null |
#pragma once
/*
Simple library for access the local file system.
*/
#include <vector>
#include <string>
#include <cstdint>
#include <map>
struct VRelativePath {
std::string fRelativePath;
};
struct VAbsolutePath {
std::string fAbsolutePath;
};
// Path is absolute and with native path separators.
std::vector<std::uint8_t> LoadFile(const std::string& completePath);
// Path is absolute and with native path separators.
std::string LoadTextFile(const std::string& completePath);
// Path is absolute and with native path separators.
bool DoesEntryExist(const std::string& completePath);
/////////////////////////////////////////////////// DIRECTOR ROOTS
//??? Add help creating the directory with the correct name.
struct directories_t {
//??? add app resource root.
// Directory where your executable or bundle lives.
std::string process_dir;
// Current logged-in user's home directory. Ex: "/Users/marcus"
// User-visible files.
std::string home_dir;
// Current logged-in user's documents directory. Ex: "/Users/marcus/Documents"
// User-visible files.
std::string documents_dir;
// Current logged-in user's desktop directory. Ex: "/Users/marcus/Desktop"
// User-visible files.
std::string desktop_dir;
// Current logged-in user's preference directory. Ex: "/Users/marcus/Library/Preferences"
// Notice that this points to a directory shared by many applications: store your data in a sub directory!
// User don't see these files.
std::string preferences_dir;
// Current logged-in user's cache directory. Ex: "/Users/marcus/Library/Caches"
// Notice that this points to a directory shared by many applications: store your data in a sub directory!
// User don't see these files.
std::string cache_dir;
// Temporary directory. Will be erased soon.
// Notice that this points to a directory shared by many applications: store your data in a sub directory!
// User don't see these files.
std::string temp_dir;
// Current logged-in user's Application Support directory. Ex: "/Users/marcus/Library/Application Support"
// Notice that this points to a directory shared by many applications: store your data in a sub directory!
// App creates and manages on behalf of the user and can include files that contain user data.
// User don't see these files.
std::string application_support;
};
directories_t GetDirectories();
struct process_info_t {
std::string process_path;
};
process_info_t get_process_info();
std::string get_working_dir();
/////////////////////////////////////////////////// ADVANCED
// Path is absolute and with native path separators.
// Will _create_ any needed directories in the save-path.
void SaveFile(const std::string& completePath, const std::uint8_t data[], std::size_t byteCount);
/*
dir_a
dir_b
file_5
dir_d
file_4
file_2
dir_e
file_1
file_2
file_3
dir_c
DeleteDeep("dir_b") will delete file_5, file_4, file_2, file_1, file_2, file_3, dir_e, dir_d, dir_b
*/
void DeleteDeep(const std::string& path);
void RenameEntry(const std::string& path, const std::string& n);
void MakeDirectoriesDeep(const std::string& nativePath);
std::string UpDir(const std::string& path);
std::pair<std::string, std::string> UpDir2(const std::string& path);
struct TFileInfo {
bool fDirFlag;
// Dates are undefined unit, but can be compared.
std::uint64_t fCreationDate;
std::uint64_t fModificationDate;
std::uint64_t fFileSize;
};
bool GetFileInfo(const std::string& completePath, TFileInfo& outInfo);
struct TDirEntry {
enum EType {
kFile = 200,
kDir = 201
};
EType fType;
// Name of file or dir.
std::string fNameOnly;
// Parent path.
std::string fParent;
};
// Never includes "." or "..".
std::vector<TDirEntry> GetDirItems(const std::string& dir);
// Returns a entiry directory tree deeply.
// Each TDirEntry name will be prefixed by _prefix_.
// Contents of sub-directories will be also be prefixed by the sub-directory names.
// All path names are relative to the input directory - not absolute to file system.
// Never includes "." or "..".
std::vector<TDirEntry> GetDirItemsDeep(const std::string& dir);
// Converts all forward slashes "/" to the path separator of the current operating system:
// Windows is "\"
// Unix is "/"
// Mac OS 9 is ":"
std::string ToNativePath(const std::string& path);
std::string FromNativePath(const std::string& path);
std::string RemoveExtension(const std::string& s);
// Returns "" when there is no extension.
// Returned extension includes the leading ".".
// Examples:
// ".wav"
// ""
// ".doc"
// ".AIFF"
std::string GetExtension(const std::string& s);
std::pair<std::string, std::string> SplitExtension(const std::string& s);
struct TPathParts {
public: TPathParts();
public: TPathParts(const std::string& path, const std::string& name, const std::string& extension);
// "/Volumes/MyHD/SomeDir/"
std::string fPath;
// "MyFileName"
std::string fName;
// ".txt"
std::string fExtension;
};
TPathParts SplitPath(const std::string& path);
std::vector<std::string> SplitPath2(const std::string& path);
/*
base relativePath
"/users/marcus/" "resources/hello.jpg" "/users/marcus/resources/hello.jpg"
*/
std::string MakeAbsolutePath(const std::string& base, const std::string& relativePath);
//////////////////////////// COMMAND LINE ARGUMENTS
std::vector<std::string> args_to_vector(int argc, const char * argv[]);
// Flags: x: means x supports parameter.
struct command_line_args_t {
std::string command;
std::string subcommand;
// Key: flag character, value: parameter or ""
std::map<std::string, std::string> flags;
// Extra arguments, after the flags have been parsed.
std::vector<std::string> extra_arguments;
};
command_line_args_t parse_command_line_args(const std::vector<std::string>& args, const std::string& flags);
/*
git commit -m "Commit message"
command: "git"
subcommand: "commit"
flags
m: ""
extra_arguments
"Commit message"
*/
command_line_args_t parse_command_line_args_subcommands(const std::vector<std::string>& args, const std::string& flags);
std::string read_text_file(const std::string& abs_path);
| 26.127119
| 120
| 0.709861
|
[
"vector"
] |
e8181aaa936b962a8d2450cf54a5740c34de7ecf
| 3,485
|
h
|
C
|
contrib/gnu/gcc/dist/libstdc++-v3/config/locale/gnu/c++locale_internal.h
|
TheSledgeHammer/2.11BSD
|
fe61f0b9aaa273783cd027c7b5ec77e95ead2153
|
[
"BSD-3-Clause"
] | 3
|
2021-05-04T17:09:06.000Z
|
2021-10-04T07:19:26.000Z
|
contrib/gnu/gcc/dist/libstdc++-v3/config/locale/gnu/c++locale_internal.h
|
TheSledgeHammer/2.11BSD
|
fe61f0b9aaa273783cd027c7b5ec77e95ead2153
|
[
"BSD-3-Clause"
] | null | null | null |
contrib/gnu/gcc/dist/libstdc++-v3/config/locale/gnu/c++locale_internal.h
|
TheSledgeHammer/2.11BSD
|
fe61f0b9aaa273783cd027c7b5ec77e95ead2153
|
[
"BSD-3-Clause"
] | null | null | null |
// Prototypes for GLIBC thread locale __-prefixed functions -*- C++ -*-
// Copyright (C) 2002-2020 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, 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 General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file bits/c++locale_internal.h
* This is an internal header file, included by other library headers.
* Do not attempt to use it directly. @headername{locale}
*/
// Written by Jakub Jelinek <[email protected]>
#include <bits/c++config.h>
#include <clocale>
#include <cstdlib>
#include <cstring>
#include <cstddef>
#include <langinfo.h>
#include <vector>
#include <string.h> // ::strdup
#include <ext/concurrence.h>
#if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2)
extern "C" __typeof(nl_langinfo_l) __nl_langinfo_l;
extern "C" __typeof(strcoll_l) __strcoll_l;
extern "C" __typeof(strftime_l) __strftime_l;
extern "C" __typeof(strtod_l) __strtod_l;
extern "C" __typeof(strtof_l) __strtof_l;
extern "C" __typeof(strtold_l) __strtold_l;
extern "C" __typeof(strxfrm_l) __strxfrm_l;
extern "C" __typeof(newlocale) __newlocale;
extern "C" __typeof(freelocale) __freelocale;
extern "C" __typeof(duplocale) __duplocale;
extern "C" __typeof(uselocale) __uselocale;
#ifdef _GLIBCXX_USE_WCHAR_T
extern "C" __typeof(iswctype_l) __iswctype_l;
extern "C" __typeof(towlower_l) __towlower_l;
extern "C" __typeof(towupper_l) __towupper_l;
extern "C" __typeof(wcscoll_l) __wcscoll_l;
extern "C" __typeof(wcsftime_l) __wcsftime_l;
extern "C" __typeof(wcsxfrm_l) __wcsxfrm_l;
extern "C" __typeof(wctype_l) __wctype_l;
#endif
#endif // GLIBC 2.3 and later
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
struct Catalog_info
{
Catalog_info(messages_base::catalog __id, const char* __domain,
locale __loc)
: _M_id(__id), _M_domain(strdup(__domain)), _M_locale(__loc)
{ }
~Catalog_info()
{ free(_M_domain); }
messages_base::catalog _M_id;
char* _M_domain;
locale _M_locale;
private:
Catalog_info(const Catalog_info&);
Catalog_info&
operator=(const Catalog_info&);
};
class Catalogs
{
public:
Catalogs() : _M_catalog_counter(0) { }
~Catalogs();
messages_base::catalog
_M_add(const char* __domain, locale __l);
void
_M_erase(messages_base::catalog __c);
const Catalog_info*
_M_get(messages_base::catalog __c) const;
private:
mutable __gnu_cxx::__mutex _M_mutex;
messages_base::catalog _M_catalog_counter;
vector<Catalog_info*> _M_infos;
};
Catalogs&
get_catalogs();
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace
| 28.801653
| 72
| 0.73802
|
[
"vector"
] |
e8185a9945f88683c0a6aa5a982e2d4b70e1375f
| 3,297
|
h
|
C
|
src/Modules/RemoteTool/ToolBalancer.h
|
mapron/Wuild
|
5701ed6ecf60fd4959c69cde0d87b7121d6479c2
|
[
"Apache-2.0"
] | 44
|
2017-01-06T16:48:24.000Z
|
2022-03-02T17:06:34.000Z
|
src/Modules/RemoteTool/ToolBalancer.h
|
mapron/Wuild
|
5701ed6ecf60fd4959c69cde0d87b7121d6479c2
|
[
"Apache-2.0"
] | 14
|
2017-01-13T11:38:26.000Z
|
2021-05-30T14:09:11.000Z
|
src/Modules/RemoteTool/ToolBalancer.h
|
mapron/Wuild
|
5701ed6ecf60fd4959c69cde0d87b7121d6479c2
|
[
"Apache-2.0"
] | 9
|
2017-11-08T14:30:37.000Z
|
2021-10-06T06:32:18.000Z
|
/*
* Copyright (C) 2017-2021 Smirnov Vladimir [email protected]
* Source code 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 or in file COPYING-APACHE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.h
*/
#pragma once
#include <CoordinatorTypes.h>
#include <mutex>
#include <atomic>
namespace Wuild {
/**
* Balancer used to split request between several tool servers.
* Main goal: the request should gone to server with least load at this moment.
*
* To update client information, UpdateClient and SetClientActive is used.
*
* To recieve balancer most suitable client, call FindFreeClient.
* StartTask and FinishTask updates load cache.
* Get*Threads funcation used for overall statistics.
*/
class ToolBalancer {
public:
enum class ClientStatus
{
Added,
Skipped,
Updated
};
public:
ToolBalancer();
~ToolBalancer();
void SetRequiredTools(const StringVector& requiredToolIds);
void SetSessionId(int64_t sessionId);
ClientStatus UpdateClient(const ToolServerInfo& toolServer, size_t& index);
void SetClientActive(size_t index, bool isActive);
void SetClientCompatible(size_t index, bool isCompatible);
void SetServerSideLoad(size_t index, uint16_t load);
size_t FindFreeClient(const std::string& toolId) const;
void StartTask(size_t index);
void FinishTask(size_t index);
uint16_t GetTotalThreads() const { return m_totalRemoteThreads; }
uint16_t GetFreeThreads() const { return m_freeRemoteThreads; }
uint16_t GetUsedThreads() const { return m_usedThreads; }
bool IsAllChecked() const;
/// Used for tests.
std::vector<uint16_t> TestGetBusy() const;
protected:
struct ClientInfo {
ToolServerInfo m_toolServer;
bool m_checked = false;
bool m_active = false;
bool m_compatible = false;
uint16_t m_serverSideQueue = 0;
uint16_t m_serverSideQueuePrev = 0;
uint16_t m_serverSideQueueAvg = 0;
uint16_t m_busyMine = 0;
uint16_t m_busyOthers = 0;
uint16_t m_busyTotal = 0;
uint16_t m_busyByNetworkLoad = 0;
int64_t m_clientLoad = 0;
int m_eachTaskWeight = 32768; //TODO: priority? configaration?
void UpdateLoad(int64_t mySessionId);
};
protected:
void RecalcAvailable();
std::atomic<uint16_t> m_totalRemoteThreads{ 0 };
std::atomic<uint16_t> m_freeRemoteThreads{ 0 };
std::atomic<uint16_t> m_usedThreads{ 0 };
int64_t m_sessionId = 0;
std::deque<ClientInfo> m_clients;
StringVector m_requiredToolIds;
mutable std::mutex m_clientsMutex;
};
}
| 33.30303
| 119
| 0.663937
|
[
"vector"
] |
e81a098c3ba4b6af38682a8d27aa5722546b3bf6
| 28,804
|
h
|
C
|
Common/Geometry/GeometryFactory.h
|
achilex/MgDev
|
f7baf680a88d37659af32ee72b9a2046910b00d8
|
[
"PHP-3.0"
] | 2
|
2017-04-19T01:38:30.000Z
|
2020-07-31T03:05:32.000Z
|
Common/Geometry/GeometryFactory.h
|
achilex/MgDev
|
f7baf680a88d37659af32ee72b9a2046910b00d8
|
[
"PHP-3.0"
] | null | null | null |
Common/Geometry/GeometryFactory.h
|
achilex/MgDev
|
f7baf680a88d37659af32ee72b9a2046910b00d8
|
[
"PHP-3.0"
] | 1
|
2021-12-29T10:46:12.000Z
|
2021-12-29T10:46:12.000Z
|
//
// Copyright (C) 2004-2011 by Autodesk, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of version 2.1 of the GNU Lesser
// General Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
#ifndef _MGGEOMETRYFACTORY_H_
#define _MGGEOMETRYFACTORY_H_
class MgGeometryFactory;
template class MG_GEOMETRY_API Ptr<MgGeometryFactory>;
/// \defgroup MgGeometryFactory MgGeometryFactory
/// \ingroup Geometry_Module_classes
/// \{
/////////////////////////////////////////////////////////////////////
/// \brief
/// The MgGeometryFactory class is used to construct objects
/// whose classes are derived from MgGeometry.
///
/// \remarks
/// The starting point for the construction of the MgGeometry
/// objects is user-supplied numbers of type double or integer.
/// The lexical analyzer converts integers to doubles. The
/// numbers are passed to one of the CreateCoordinate????()
/// methods where ???? is one of XY, XYM, XYZ, or XYZM.
/// \n
/// The MgGeometryFactory methods do no spatial analysis. Errors
/// in the construction of the geometry objects are not detected
/// until some operation in the datastore requiring spatial
/// analysis is performed.
/// \n
/// The general rules for constructing geometry objects are as
/// follows:
/// <ul>
/// <li>add coordinates to a coordinate collection which defines
/// an MgLinearRing so that the first and last coordinates are
/// identical,</li>
/// <li>add coordinates to a coordinate collection which defines
/// an MgLinearRing to be used as an <b>exterior</b> ring in an
/// MgPolygon so that the direction of traversal is
/// counterclockwise,</li>
/// <li>add coordinates to a coordinate collection which defines
/// an MgLinearRing to be used as an <b>interior</b> ring in an
/// MgPolygon so that the direction of traversal is clockwise,</li>
/// <li>add MgCurveSegment objects (either MgArcSegment objects
/// or MgLinearSegment objects) to an MgCurveSegmentCollection
/// so that they are contiguous in the order added and so that
/// the last coordinate in an MgCurveSegment object is identical
/// to the first coordinate in the succeeding MgCurveSegment
/// object,</li>
/// <li>add MgCurveSegment objects (either MgArcSegment objects
/// or MgLinearSegment objects) to an MgCurveSegmentCollection
/// which defines an MgCurveRing to be used as an <b>exterior</b>
/// ring in an MgCurvePolygon so that the direction of traversal
/// is counterclockwise,</li>
/// <li>add MgCurveSegment objects (either MgArcSegment objects
/// or MgLinearSegment objects) to an MgCurveSegmentCollection
/// which defines an MgCurveRing to be used as an <b>interior</b>
/// ring in an MgCurvePolygon so that the direction of traversal
/// is clockwise.</li>
/// </ul>
/// With respect to the construction of linear and curve
/// polygons, the Autodesk Geometry Format (AGF) Binary
/// specification does not stipulate the direction of traversal
/// in a ring. However, some providers, for example, Oracle,
/// require that the direction of traversal be counterclockwise
/// in an exterior ring and clockwise in an interior ring.
/// \n
/// The following statements are represented in the graphic at
/// the bottom of this pane.
/// \n
/// MgCoordinate objects are used directly to create MgPoint
/// geometries and MgArcSegment geometry components.
/// \n
/// MgCoordinateCollection objects are used to create
/// MgLineString geometries, MgLinearRing geometry components and
/// MgLinearSegment geometry components.
/// \n
/// An MgPolygon geometry is constructed from an MgLinearRing
/// geometry component, which defines the polygon's external
/// boundary, and an optional MgLinearRingCollection of
/// MgLinearRing geometry components, which define "holes' in the
/// containing ring.
/// \n
/// An MgCurveSegmentCollection of MgLinearSegment objects and
/// MgArcSegment objects are used to create MgCurveString
/// geometries and MgCurveRing geometry components.
/// \n
/// An MgCurvePolygon geometry is constructed from an MgCurveRing
/// geometry component, which defines the curve polygon's
/// external boundary, and an optional MgCurveRingCollection of
/// MgCurveRing geometries, which define "holes" in the
/// containing ring.
/// \n
/// Each single geometry (point, line string, polygon, curve
/// string, and curve polygon) has a homogeneous multi-version.
/// For example, an MgMultiPoint geometry is composed of MgPoint
/// geometries. For each geometry type there is a helper
/// collection class used to construct the multi-version object.
/// \n
/// Finally an MgMultiGeometry object, which consists of a
/// heterogeneous collection of geometries, is constructed by
/// adding geometries to a helper collection class object and
/// passing that collection object to a constructor.
/// \n
/// \image html GeometryFactory.png
///
class MG_GEOMETRY_API MgGeometryFactory : public MgGuardDisposable
{
DECLARE_CLASSNAME(MgGeometryFactory)
PUBLISHED_API:
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates an MgGeometryFactory object
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// MgGeometryFactory();
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// MgGeometryFactory();
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// MgGeometryFactory();
/// \htmlinclude SyntaxBottom.html
///
MgGeometryFactory();
////////////////////////////////////////////////////////////////
/// \brief
/// Creates an MgCoordinate object with Dimension = XY, X = x, Y
/// = y.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXY(double x, double y);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXY(double x, double y);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXY(double x, double y);
/// \htmlinclude SyntaxBottom.html
///
/// \param x (double)
/// X value for the coordinate.
/// \param y (double)
/// Y value for the coordinate.
///
/// \return
/// An initialized MgCoordinate instance.
///
virtual MgCoordinate* CreateCoordinateXY(double x, double y);
/////////////////////////////////////////////////////////////////
/// \brief
/// Creates an MgCoordinate object with Dimension = XYM, X = x, Y
/// = y, M = m.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYM(double x, double y, double m);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYM(double x, double y, double m);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYM(double x, double y, double m);
/// \htmlinclude SyntaxBottom.html
///
/// \param x (double)
/// X value for the coordinate.
/// \param y (double)
/// Y value for the coordinate.
/// \param m (double)
/// M value for the coordinate.
///
/// \return
/// An initialized MgCoordinate instance.
///
virtual MgCoordinate* CreateCoordinateXYM(double x, double y, double m);
/////////////////////////////////////////////////////////////////
/// \brief
/// Creates an MgCoordinate object with Dimension = XYZ, X = x, Y
/// = y, Z = z.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYZ(double x, double y, double z);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYZ(double x, double y, double z);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYZ(double x, double y, double z);
/// \htmlinclude SyntaxBottom.html
///
/// \param x (double)
/// X value for the coordinate.
/// \param y (double)
/// Y value for the coordinate.
/// \param z (double)
/// Z value for the coordinate.
///
/// \return
/// An initialized MgCoordinate instance.
///
virtual MgCoordinate* CreateCoordinateXYZ(double x, double y, double z);
////////////////////////////////////////////////////////////////
/// \brief
/// Creates an MgCoordinate object with Dimension = XYZM, X = x,
/// Y = y, Z = z, M = m.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYZM(double x, double y, double z, double m);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYZM(double x, double y, double z, double m);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYZM(double x, double y, double z, double m);
/// \htmlinclude SyntaxBottom.html
///
/// \param x (double)
/// X value for the coordinate.
/// \param y (double)
/// Y value for the coordinate.
/// \param z (double)
/// Z value for the coordinate.
/// \param m (double)
/// M value for the coordinate.
///
/// \return
/// An initialized MgCoordinate instance.
///
virtual MgCoordinate* CreateCoordinateXYZM(double x, double y, double z, double m);
///////////////////////////////////////////////////////////////////////
/// \brief
/// Creates an arc segment from start, end, and control
/// coordinates.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgArcSegment CreateArcSegment(MgCoordinate start, MgCoordinate end, MgCoordinate control);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgArcSegment CreateArcSegment(MgCoordinate start, MgCoordinate end, MgCoordinate control);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgArcSegment CreateArcSegment(MgCoordinate start, MgCoordinate end, MgCoordinate control);
/// \htmlinclude SyntaxBottom.html
///
/// \param start (MgCoordinate)
/// The MgCoordinate that specifies the start point
/// of the arc.
/// \param end (MgCoordinate)
/// The MgCoordinate that specifies the end point
/// of the arc.
/// \param control (MgCoordinate)
/// The MgCoordinate that specifies the control
/// point of the arc.
///
/// \return
/// An instance of MgArcSegment.
///
virtual MgArcSegment* CreateArcSegment(MgCoordinate* start, MgCoordinate* end, MgCoordinate* control);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a linear segment from a collection of coordinates.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgLinearSegment CreateLinearSegment(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgLinearSegment CreateLinearSegment(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgLinearSegment CreateLinearSegment(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
///
/// \param coordinates (MgCoordinateCollection)
/// An MgCoordinateCollection that specifies the coordinates of the linear
/// segment. The collection must contain at least two coordinates.
///
/// \return
/// An instance of MgLinearSegment.
///
virtual MgLinearSegment* CreateLinearSegment(MgCoordinateCollection* coordinates);
/////////////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a linear ring from a collection of coordinates.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgLinearRing CreateLinearRing(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgLinearRing CreateLinearRing(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgLinearRing CreateLinearRing(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
///
/// \param coordinates (MgCoordinateCollection)
/// An MgCoordinateCollection that specifies the coordinates of the linear
/// ring. The collection must contain at least three coordinates.
///
/// \return
/// An instance of MgLinearRing.
///
virtual MgLinearRing* CreateLinearRing(MgCoordinateCollection* coordinates);
///////////////////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a curve ring from a collection of curve segments.
/// \remarks
/// The use of this method is illustrated in the MgCurvePolygon example code.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgCurveRing CreateCurveRing(MgCurveSegmentCollection curveSegments);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgCurveRing CreateCurveRing(MgCurveSegmentCollection curveSegments);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgCurveRing CreateCurveRing(MgCurveSegmentCollection curveSegments);
/// \htmlinclude SyntaxBottom.html
///
/// \param curveSegments (MgCurveSegmentCollection)
/// An MgCurveSegmentCollection that specifies the segments
/// of the curve ring. The segments in the collection must
/// form a closed shape. See the example php code for
/// details about the construction of the segments so that
/// the resulting shape is closed.
///
/// \return
/// An instance of MgCurveRing.
///
virtual MgCurveRing* CreateCurveRing(MgCurveSegmentCollection* curveSegments);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a point from a coordinate.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgPoint CreatePoint(MgCoordinate coordinate);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgPoint CreatePoint(MgCoordinate coordinate);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgPoint CreatePoint(MgCoordinate coordinate);
/// \htmlinclude SyntaxBottom.html
///
/// \param coordinate (MgCoordinate)
/// An MgCoordinate that specifies the location of this point.
///
/// \return
/// An instance of MgPoint.
///
virtual MgPoint* CreatePoint(MgCoordinate* coordinate);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a line string from a collection of coordinates.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgLineString CreateLineString(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgLineString CreateLineString(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgLineString CreateLineString(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
///
/// \param coordinates (MgCoordinateCollection)
/// An MgCoordinateCollection that specifies the coordinates of the line
/// string. The collection must contain at least two coordinates.
///
/// \return
/// An instance of MgLineString.
///
virtual MgLineString* CreateLineString(MgCoordinateCollection* coordinates);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a curve string from a collection of curve segments.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgCurveString CreateCurveString(MgCurveSegmentCollection curveSegments);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgCurveString CreateCurveString(MgCurveSegmentCollection curveSegments);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgCurveString CreateCurveString(MgCurveSegmentCollection curveSegments);
/// \htmlinclude SyntaxBottom.html
///
/// \param curveSegments (MgCurveSegmentCollection)
/// An MgCurveSegmentCollection that specifies the segments of the
/// curve string. The collection must contain at least one segment.
///
/// \return
/// An instance of MgCurveString.
///
virtual MgCurveString* CreateCurveString(MgCurveSegmentCollection* curveSegments);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a polygon from an outer ring and a collection of inner rings.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgPolygon CreatePolygon(MgLinearRing outerRing, MgLinearRingCollection innerRings);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgPolygon CreatePolygon(MgLinearRing outerRing, MgLinearRingCollection innerRings);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgPolygon CreatePolygon(MgLinearRing outerRing, MgLinearRingCollection innerRings);
/// \htmlinclude SyntaxBottom.html
///
/// \param outerRing (MgLinearRing)
/// An MgLinearRing that specifies the polygons outer boundary.
/// \param innerRings (MgLinearRingCollection)
/// An MgLinearRingCollection that specifies the polygons holes.
/// This parameter may be null.
///
/// \return
/// An instance of MgPolygon.
///
virtual MgPolygon* CreatePolygon(MgLinearRing* outerRing, MgLinearRingCollection* innerRings);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a curve polygon from an outer ring and a collection of inner
/// rings.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgCurvePolygon CreateCurvePolygon(MgCurveRing outerRing, MgCurveRingCollection innerRings);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgCurvePolygon CreateCurvePolygon(MgCurveRing outerRing, MgCurveRingCollection innerRings);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgCurvePolygon CreateCurvePolygon(MgCurveRing outerRing, MgCurveRingCollection innerRings);
/// \htmlinclude SyntaxBottom.html
///
/// \param outerRing (MgCurveRing)
/// An MgCurveRing that specifies the polygons outer boundary.
/// \param innerRings (MgCurveRingCollection)
/// An MgCurveRingCollection that specifies the polygons holes.
/// This parameter may be null.
///
/// \return
/// An instance of MgCurvePolygon.
///
virtual MgCurvePolygon* CreateCurvePolygon(MgCurveRing* outerRing, MgCurveRingCollection* innerRings);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a multi point aggregate geometry from a collection of points.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgMultiPoint CreateMultiPoint(MgPointCollection points);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgMultiPoint CreateMultiPoint(MgPointCollection points);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgMultiPoint CreateMultiPoint(MgPointCollection points);
/// \htmlinclude SyntaxBottom.html
///
/// \param points (MgPointCollection)
/// An MgGeometryCollection that specifies the points. All geometry
/// objects in this collection must be of type MgPoint.
///
/// \return
/// An instance of MgMultiPoint.
///
virtual MgMultiPoint* CreateMultiPoint(MgPointCollection* points);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a multi line string aggregate geometry from a collection of
/// line strings.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgMultiLineString CreateMultiLineString(MgLineStringCollection lineStrings);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgMultiLineString CreateMultiLineString(MgLineStringCollection lineStrings);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgMultiLineString CreateMultiLineString(MgLineStringCollection lineStrings);
/// \htmlinclude SyntaxBottom.html
///
/// \param lineStrings (MgLineStringCollection)
/// An MgGeometryCollection that specifies the line strings. All geometry
/// objects in this collection must be of type MgLineString.
///
/// \return
/// An instance of MgMultiLineString.
///
virtual MgMultiLineString* CreateMultiLineString(MgLineStringCollection* lineStrings);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a multi curve string aggregate geometry from a collection of
/// curve strings.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgMultiCurveString CreateMultiCurveString(MgCurveStringCollection curveStrings);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgMultiCurveString CreateMultiCurveString(MgCurveStringCollection curveStrings);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgMultiCurveString CreateMultiCurveString(MgCurveStringCollection curveStrings);
/// \htmlinclude SyntaxBottom.html
///
/// \param curveStrings (MgCurveStringCollection)
/// An MgGeometryCollection that specifies the curve strings. All geometry
/// objects in this collection must be of type MgCurveString.
///
/// \return
/// An instance of MgMultiCurveString.
///
virtual MgMultiCurveString* CreateMultiCurveString(MgCurveStringCollection* curveStrings);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a multi polygon aggregate geometry from a collection of
/// polygons.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgMultiPolygon CreateMultiPolygon(MgPolygonCollection polygons);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgMultiPolygon CreateMultiPolygon(MgPolygonCollection polygons);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgMultiPolygon CreateMultiPolygon(MgPolygonCollection polygons);
/// \htmlinclude SyntaxBottom.html
///
/// \param polygons (MgPolygonCollection)
/// An MgGeometryCollection that specifies the polygons. All geometry
/// objects in this collection must be of type MgPolygon.
///
/// \return
/// An instance of MgMultiPolygon.
///
virtual MgMultiPolygon* CreateMultiPolygon(MgPolygonCollection* polygons);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a multi curve polygon aggregate geometry from a collection of
/// curve polygons.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgMultiCurvePolygon CreateMultiCurvePolygon(MgCurvePolygonCollection polygons);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgMultiCurvePolygon CreateMultiCurvePolygon(MgCurvePolygonCollection polygons);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgMultiCurvePolygon CreateMultiCurvePolygon(MgCurvePolygonCollection polygons);
/// \htmlinclude SyntaxBottom.html
///
/// \param polygons (MgCurvePolygonCollection)
/// An MgGeometryCollection that specifies the curve polygons. All geometry
/// objects in this collection must be of type MgCurvePolygon.
///
/// \return
/// An instance of MgMultiCurvePolygon.
///
virtual MgMultiCurvePolygon* CreateMultiCurvePolygon(MgCurvePolygonCollection* polygons);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates an aggregate geometry from a collection of geometry objects.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgMultiGeometry CreateMultiGeometry(MgGeometryCollection geometries);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgMultiGeometry CreateMultiGeometry(MgGeometryCollection geometries);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgMultiGeometry CreateMultiGeometry(MgGeometryCollection geometries);
/// \htmlinclude SyntaxBottom.html
///
/// \param geometries (MgGeometryCollection)
/// An MgGeometryCollection that specifies the geometries.
///
/// \return
/// An instance of MgMultiGeometry.
///
virtual MgMultiGeometry* CreateMultiGeometry(MgGeometryCollection* geometries);
INTERNAL_API:
//////////////////////////////////////////////////////////////////
/// \brief
/// Get the unique identifier for the class
///
/// \return
/// Class Identifider.
///
virtual INT32 GetClassId();
//////////////////////////////////////////////////////////////////
/// \brief
/// Creates an empty geometry from its type identifier
///
/// \return
/// Geometry.
///
static MgGeometry* CreateGeometry(INT32 geomId);
protected:
//////////////////////////////////////////////
/// \brief
/// Dispose this object.
///
virtual void Dispose();
//////////////////////////////////////////////////////////////////
/// \brief
/// Initializes the factory
///
static bool InitializeGeometryFactory();
//////////////////////////////////////////////////////////////////
/// \brief
/// Empty geometry creation functions
///
static MgPoint* CreateEmptyPoint();
static MgLineString* CreateEmptyLineString();
static MgCurveString* CreateEmptyCurveString();
static MgPolygon* CreateEmptyPolygon();
static MgCurvePolygon* CreateEmptyCurvePolygon();
static MgMultiPoint* CreateEmptyMultiPoint();
static MgMultiLineString* CreateEmptyMultiLineString();
static MgMultiCurveString* CreateEmptyMultiCurveString();
static MgMultiPolygon* CreateEmptyMultiPolygon();
static MgMultiCurvePolygon* CreateEmptyMultiCurvePolygon();
static MgMultiGeometry* CreateEmptyMultiGeometry();
CLASS_ID:
static const INT32 m_cls_id = Geometry_GeometryFactory;
private:
static bool m_factoryInitialized;
};
/// \}
#endif //_MGGEOMETRYFACTORY_H_
| 41.564214
| 107
| 0.648868
|
[
"geometry",
"object",
"shape"
] |
e81b26c8f1500ec882b361e8b860b43dc2845f06
| 792
|
h
|
C
|
Engine/Mesh_RenderInfo.h
|
SergiPC/ParticleSystem_Engine
|
ba9a3045b042a81a8173e7b775f068fd69de5966
|
[
"Apache-2.0"
] | 1
|
2017-09-14T08:21:07.000Z
|
2017-09-14T08:21:07.000Z
|
Engine/Mesh_RenderInfo.h
|
Vulpem/V_Engine
|
d5d2a582e28b29c9eea87897d6be03387b150369
|
[
"Apache-2.0"
] | null | null | null |
Engine/Mesh_RenderInfo.h
|
Vulpem/V_Engine
|
d5d2a582e28b29c9eea87897d6be03387b150369
|
[
"Apache-2.0"
] | null | null | null |
#ifndef ___MESH_RENDERINFO__
#define ___MESH_RENDERINFO__
#include "Math.h"
class R_mesh;
enum AlphaTestTypes
{
ALPHA_OPAQUE = 0,
ALPHA_DISCARD,
ALPHA_BLEND
};
struct Mesh_RenderInfo
{
const R_mesh* origin = nullptr;
bool wired = false;
bool filled = false;
bool doubleSidedFaces = false;
bool renderNormals = false;
bool hasNormals = false;
bool hasUVs = false;
float4 meshColor = float4::zero;
float4 wiresColor = float4::zero;
unsigned int num_indices = 0;
unsigned int num_vertices = 0;
unsigned int indicesBuffer = 0;
unsigned int dataBuffer = 0;
unsigned int textureBuffer = 0;
AlphaTestTypes alphaType = AlphaTestTypes::ALPHA_OPAQUE;
int blendType = 0;
float alphaTest = 0.2f;
uint shader = 0;
float4x4 transform;
};
#endif // !___MESH_RENDERINFO__
| 16.5
| 57
| 0.741162
|
[
"transform"
] |
e81bddfc1d39624bfdce1a022d69dc59583ebe67
| 8,387
|
h
|
C
|
camera/hal/intel/ipu6/modules/algowrapper/IntelPGParam.h
|
dgreid/platform2
|
9b8b30df70623c94f1c8aa634dba94195343f37b
|
[
"BSD-3-Clause"
] | 4
|
2020-07-24T06:54:16.000Z
|
2021-06-16T17:13:53.000Z
|
camera/hal/intel/ipu6/modules/algowrapper/IntelPGParam.h
|
dgreid/platform2
|
9b8b30df70623c94f1c8aa634dba94195343f37b
|
[
"BSD-3-Clause"
] | 1
|
2021-04-02T17:35:07.000Z
|
2021-04-02T17:35:07.000Z
|
camera/hal/intel/ipu6/modules/algowrapper/IntelPGParam.h
|
dgreid/platform2
|
9b8b30df70623c94f1c8aa634dba94195343f37b
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (C) 2018-2020 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
extern "C" {
#include <ia_css_program_group_data.h>
#include <ia_css_program_group_param.h>
#include <ia_css_psys_process_group.h>
#include <ia_css_psys_program_group_manifest.h>
#include <ia_css_psys_terminal.h>
#include <ia_css_psys_terminal_manifest.h>
#include <ia_css_terminal_manifest_types.h>
#include <ia_css_terminal_types.h>
#include <ia_isp_bxt.h>
#include <ia_isp_types.h>
#include <ia_p2p.h>
#include <ia_p2p_types.h>
#include <ia_pal_types_isp_ids_autogen.h>
#include <pg_control_init_framework.h>
}
#include <map>
#include <memory>
#include <vector>
#include "ia_tools/css_types.h"
#include "iutils/Errors.h"
#include "iutils/Utils.h"
#include "modules/ia_cipr/include/Utils.h"
#include "src/core/psysprocessor/PGUtils.h"
namespace icamera {
#define PSYS_MAX_KERNELS_PER_PG IA_CSS_KERNEL_BITMAP_BITS
/**
* \class IntelPGParam
*
* \brief This is a version P2P implementation which is used to encode parameter terminal
* and decode statistic terminal for PSYS pipeline.
*
* The call sequence as follows:
* 1. init();
* 2. prepare();
* 3. allocatePGBuffer() (optional);
* 4. setPGAndPrepareProgram();
* 5. getPayloadSizes(), and allocate payload buffers,
* allocatePayloads() is provided for that;
* 6. getFragmentDescriptors();
* 7. loop frame {
* updatePALAndEncode();
* decode();
* }
* 8. deinit();
*/
class IntelPGParam {
public:
explicit IntelPGParam(int pgId);
~IntelPGParam();
/**
* Use to init and config P2P handle.
*/
int init(ia_p2p_platform_t platform, const PgConfiguration& Pgconfiguration);
/**
* Query and save the requirement for each terminal, calculate the final kernel bitmap.
*/
int prepare(const ia_binary_data* ipuParameters, const ia_css_rbm_t* rbm,
ia_css_kernel_bitmap_t* bitmap, uint32_t* maxStatsSize = nullptr);
/**
* Allocate PG buffer for caller
*/
void* allocatePGBuffer(int pgSize);
/**
* Accept pg outside and init program_control_init terminal.
*/
int setPGAndPrepareProgram(ia_css_process_group_t* pg);
/**
* Allocate payload memory for terminals.
*/
int allocatePayloads(int payloadCount, ia_binary_data* payloads);
/**
* Update PAL and encode payload data for all terminals. Will skip inactive terminals.
*/
int updatePALAndEncode(const ia_binary_data* ipuParams, int payloadCount,
ia_binary_data* payloads);
/**
* Decode payload data for all related terminals.
*/
int decode(int payloadCount, ia_binary_data* payload, ia_binary_data* statistics);
/**
* Use to deinit P2P handle.
*/
void deinit();
/**
* Get fragment descriptors calculated according to PAL data
* Called after prepare().
*/
int getFragmentDescriptors(int descCount, ia_p2p_fragment_desc* descs);
/**
* Get payload size for all terminals, and return valid payloads number.
*/
int getPayloadSizes(int payloadCount, ia_binary_data* payloads);
private:
enum FragmentDataTerminalType {
FRAG_TERM_TYPE_INPUT = 0,
FRAG_TERM_TYPE_OUTPUT_START, // Mapping to data out terminal in order for all postgdc pgs.
FRAG_TERM_TYPE_DISPALY_OUTPUT = FRAG_TERM_TYPE_OUTPUT_START,
FRAG_TERM_TYPE_MAIN_OUTPUT,
FRAG_TERM_TYPE_PP_OUTPUT,
FRAG_TERM_TYPE_COUNT,
};
int mPgId;
int mTerminalCount;
PgFrameDesc mInputMainFrame;
PgFrameDesc mOutputMainFrame;
uint8_t mFragmentCount;
ia_p2p_fragment_desc* mFragmentDesc;
ia_p2p_fragment_configuration_t* mFragmentConfig;
// for pg fragment with new api:
// ia_p2p_calculate_fragments_rbm
// Instead of mFragmentDesc
ia_p2p_handle mP2pHandle;
ia_binary_data mP2pCacheBuffer;
ia_css_program_group_manifest_t* mPgManifest;
std::vector<int> mDisableDataTermials;
ia_css_process_group_t* mProcessGroup;
int mProgramControlInitTerminalIndex;
struct IpuPgTerminalKernelInfo {
IpuPgTerminalKernelInfo() {}
uint8_t id = 0;
uint8_t sections = 0;
uint32_t size = 0;
bool initialize = false;
};
struct IpuPgTerminaRequirements {
IpuPgTerminaRequirements() { kernelBitmap = ia_css_kernel_bitmap_clear(); }
ia_css_terminal_type_t type = IA_CSS_N_TERMINAL_TYPES;
uint32_t payloadSize = 0;
ia_css_kernel_bitmap_t kernelBitmap;
uint32_t sectionCount = 0;
IpuPgTerminalKernelInfo* kernelOrder = nullptr;
ia_p2p_fragment_desc* fragment_descs = nullptr;
// Use for program_control_init
uint32_t userParamSize;
std::unique_ptr<uint8_t[]> userParamAddress;
};
struct IpuPgRequirements {
IpuPgRequirements() { CLEAR(terminals); }
uint32_t terminalCount = 0;
IpuPgTerminaRequirements terminals[IPU_MAX_TERMINAL_COUNT];
};
struct KernelRequirement {
KernelRequirement() { mKernelBitmap = ia_css_kernel_bitmap_clear(); }
ia_p2p_terminal_requirements_t mSections[PSYS_MAX_KERNELS_PER_PG];
ia_p2p_payload_desc mPayloads[PSYS_MAX_KERNELS_PER_PG];
int mPayloadSize = 0;
ia_css_kernel_bitmap_t mKernelBitmap;
};
KernelRequirement mKernel;
IpuPgRequirements mPgReqs;
// Allocate them here, for sandboxing case (shared memory)
std::vector<ia_binary_data> mAllocatedPayloads;
void* mProcessGroupMemory;
private:
int getKernelIdByBitmap(ia_css_kernel_bitmap_t bitmap);
ia_css_kernel_bitmap_t getCachedTerminalKernelBitmap(
ia_css_param_terminal_manifest_t* manifest);
ia_css_kernel_bitmap_t getProgramTerminalKernelBitmap(
ia_css_program_terminal_manifest_t* manifest);
int disableZeroSizedTerminals(ia_css_kernel_bitmap_t* kernelBitmap);
css_err_t getKernelOrderForProgramTerm(ia_css_program_terminal_manifest_t* terminalManifest,
IpuPgTerminalKernelInfo* kernelOrder);
css_err_t getKernelOrderForParamCachedInTerm(ia_css_param_terminal_manifest_t* terminalManifest,
IpuPgTerminalKernelInfo* kernelOrder);
int8_t terminalEnumerateByType(IpuPgRequirements* reqs, ia_css_terminal_type_t terminalType,
uint8_t num);
int8_t terminalEnumerateByBitmap(IpuPgRequirements* reqs, ia_css_terminal_type_t terminal_type,
ia_css_kernel_bitmap_t bitmap);
bool isKernelIdInKernelOrder(IpuPgRequirements* reqs, int8_t termIndex, int kernelId,
uint8_t* orderedIndex);
uint32_t getKernelCountFromKernelOrder(IpuPgRequirements* reqs, int8_t termIndex, int kernelId);
void processTerminalKernelRequirements(IpuPgRequirements* reqs, int8_t termIndex,
ia_css_terminal_type_t terminalType, int kernelId);
css_err_t payloadSectionSizeSanityTest(ia_p2p_payload_desc* current, uint16_t kernelId,
uint8_t terminalIndex, uint32_t currentOffset,
size_t payloadSize);
int calcFragmentDescriptors(int fragmentCount, const PgFrameDesc& inputMainFrame,
const PgFrameDesc& outputMainFrame, const ia_css_rbm_t* rbm);
void dumpFragmentDesc(int fragmentCount);
int encodeTerminal(ia_css_terminal_t* terminal, ia_binary_data payload);
int decodeTerminal(ia_css_terminal_t* terminal, ia_binary_data payload);
int serializeDecodeCache(ia_binary_data* result);
void destroyPayloads();
void destroyPGBuffer();
DISALLOW_COPY_AND_ASSIGN(IntelPGParam);
};
} // namespace icamera
| 35.09205
| 100
| 0.707047
|
[
"vector"
] |
e81d761240269b901d83a69bbfdb9eae9835cf79
| 1,460
|
h
|
C
|
src/tools/hpca-master/src/redsvd/util.h
|
Jie317/WordEmbeddingsAnalysis
|
e412782aa135a452894b0ab1f0cc4e5df037a0d8
|
[
"Apache-2.0"
] | 1
|
2017-08-11T13:23:08.000Z
|
2017-08-11T13:23:08.000Z
|
src/tools/hpca-master/src/redsvd/util.h
|
Jie317/WordEmbeddingsEvaluation
|
e412782aa135a452894b0ab1f0cc4e5df037a0d8
|
[
"Apache-2.0"
] | null | null | null |
src/tools/hpca-master/src/redsvd/util.h
|
Jie317/WordEmbeddingsEvaluation
|
e412782aa135a452894b0ab1f0cc4e5df037a0d8
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2011 Daisuke Okanohara
*
* 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 authors nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*/
#ifndef REDSVD_UTIL_HPP__
#define REDSVD_UTIL_HPP__
#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET
#include <vector>
#include "Eigen/Sparse"
#include "Eigen/Dense"
#include "Eigen/Eigenvalues"
namespace REDSVD {
typedef Eigen::SparseMatrix<float, Eigen::RowMajor> SMatrixXf;
typedef std::vector<std::pair<int, float> > fv_t;
class Util{
public:
static void convertFV2Mat(const std::vector<fv_t>& fvs, SMatrixXf& A);
static void sampleGaussianMat(Eigen::MatrixXf& x);
static void processGramSchmidt(Eigen::MatrixXf& mat);
static double getSec();
private:
static void sampleTwoGaussian(float& f1, float& f2);
};
}
#endif // REDSVD_UTIL_HPP_
| 29.795918
| 76
| 0.74726
|
[
"vector"
] |
e81ed119175f749e1b1b3a2994047ed0c5591693
| 1,186
|
c
|
C
|
src/deathball.c
|
kpw6/Vulkan
|
d9049e4d87c910032d0a770ee2be7ca42feeb004
|
[
"MIT"
] | null | null | null |
src/deathball.c
|
kpw6/Vulkan
|
d9049e4d87c910032d0a770ee2be7ca42feeb004
|
[
"MIT"
] | null | null | null |
src/deathball.c
|
kpw6/Vulkan
|
d9049e4d87c910032d0a770ee2be7ca42feeb004
|
[
"MIT"
] | null | null | null |
#include "SDL_Timer.h"
#include "simple_logger.h"
#include "spikes.h"
#include "entity.h"
int p = 0;
void deathball_think(Entity* self);
void deathball_ontouch(Entity* self, Entity* other);
Entity* deathball_new(Vector3D position)
{
Entity* ent = NULL;
ent = entity_new();
if (!ent)
{
slog("UGH OHHHH, no player for you!");
return NULL;
}
ent->model = gf3d_model_load("cube");
ent->scale = vector3d(0.1, 0.1, 0.1);
ent->position = position;
ent->touch = deathball_ontouch;
ent->think = deathball_think;
gfc_matrix_scale(ent->modelMat, ent->scale);
ent->radius = 0.05;
return ent;
}
void deathball_think(Entity* self) {
{
switch (p) {
case 0:
if (self->position.x > .9) {
p = 1;
break;
}
self->position.x += .01;
break;
case 1:
if (self->position.x < -.9) {
p = 0;
break;
}
self->position.x -= .01;
break;
}
}
}
void deathball_ontouch(Entity* self, Entity* other) {
other->health -= 1;
slog("healthy");
}
| 21.178571
| 53
| 0.516863
|
[
"model"
] |
e8214921b374d12180bb8cbcdd71dd3768810d50
| 655
|
h
|
C
|
source/common/CmdLineArgs.h
|
dexter3k/Stranded2pp
|
022df9becf9931f8437e81bb405bacf168884c8d
|
[
"MIT"
] | 1
|
2021-04-13T18:18:34.000Z
|
2021-04-13T18:18:34.000Z
|
source/common/CmdLineArgs.h
|
SMemsky/Stranded2pp
|
022df9becf9931f8437e81bb405bacf168884c8d
|
[
"MIT"
] | 2
|
2021-04-03T15:02:22.000Z
|
2021-04-13T18:16:39.000Z
|
source/common/CmdLineArgs.h
|
SMemsky/Stranded2pp
|
022df9becf9931f8437e81bb405bacf168884c8d
|
[
"MIT"
] | null | null | null |
#pragma once
#include <string>
#include <vector>
namespace common
{
class CmdLineArgs
{
public:
CmdLineArgs(std::vector<std::string> const & arguments);
bool shouldForceWindowedMode() const { return forceWindowedMode; };
bool shouldUseDebugMode() const { return debugMode; };
std::string modificationName() const;
private:
void parseArguments(std::vector<std::string> const & arguments);
std::string parseStringParameter(std::vector<std::string> const & arguments, unsigned & i) const;
private:
static std::string const defaultModification;
bool forceWindowedMode;
bool debugMode;
std::string customModification;
};
} // namespace common
| 21.833333
| 98
| 0.758779
|
[
"vector"
] |
e8298db38fce13634d8eb9f6e842dd9c4a3a82a5
| 1,029
|
h
|
C
|
third_party/GsTL/include/GsTL/sampler/updater_sampler.h
|
hiteshbedre/movetk
|
8d261f19538e28ff36cac98a89ef067f8c26f978
|
[
"Apache-2.0"
] | 70
|
2015-01-21T12:24:50.000Z
|
2022-03-16T02:10:45.000Z
|
third_party/GsTL/include/GsTL/sampler/updater_sampler.h
|
bacusters/movetk
|
acbc9c5acb69dd3eb23aa7d2156ede02ed468eae
|
[
"Apache-2.0"
] | 44
|
2020-09-11T17:40:30.000Z
|
2021-04-08T23:56:19.000Z
|
third_party/GsTL/include/GsTL/sampler/updater_sampler.h
|
aniketmitra001/movetk
|
cdf0c98121da6df4cadbd715fba02b05be724218
|
[
"Apache-2.0"
] | 18
|
2015-02-15T18:04:31.000Z
|
2021-01-16T08:54:32.000Z
|
#ifndef __GSTL_SAMPLER_UPDATER_SAMPLER_H__
#define __GSTL_SAMPLER_UPDATER_SAMPLER_H__
/** Updater_sampler is a model of concept Sampler.
* An Updater_sampler first updates the ccdf before sampling it.
* The update can be local, ie dependent on the geovalue where
* the sampling is performed.
* \c local_cdf_updater is a model of BinaryFunction that has the
* following signature:
* cdf_type binary_function( const geovalue&, const cdf_type& ).
* \c sampler is a model of concept Sampler.
*/
template <class BinaryFunction, class Sampler_>
class Updater_sampler {
public:
Updater_sampler( BinaryFunction local_cdf_updater,
Sampler_& sampler )
: local_cdf_updater_( local_cdf_updater ),
sampler_( sampler ) {
}
int operator() ( typename BinaryFunction::first_argument& g,
const typename BinaryFunction::second_argument& cdf ) {
return sampler_( g, local_cdf_updater_( g, cdf ) );
}
private:
BinaryFunction local_cdf_updater_;
Sampler_ sampler_;
};
#endif
| 29.4
| 74
| 0.737609
|
[
"model"
] |
e82d63c2d880225308b5e4b5cdc50f22f46bbc83
| 5,384
|
h
|
C
|
aws-cpp-sdk-imagebuilder/include/aws/imagebuilder/model/LaunchTemplateConfiguration.h
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-02-10T08:06:54.000Z
|
2022-02-10T08:06:54.000Z
|
aws-cpp-sdk-imagebuilder/include/aws/imagebuilder/model/LaunchTemplateConfiguration.h
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2021-10-14T16:57:00.000Z
|
2021-10-18T10:47:24.000Z
|
aws-cpp-sdk-imagebuilder/include/aws/imagebuilder/model/LaunchTemplateConfiguration.h
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-12-30T04:25:33.000Z
|
2021-12-30T04:25:33.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/imagebuilder/Imagebuilder_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace imagebuilder
{
namespace Model
{
/**
* <p>Identifies an Amazon EC2 launch template to use for a specific
* account.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/LaunchTemplateConfiguration">AWS
* API Reference</a></p>
*/
class AWS_IMAGEBUILDER_API LaunchTemplateConfiguration
{
public:
LaunchTemplateConfiguration();
LaunchTemplateConfiguration(Aws::Utils::Json::JsonView jsonValue);
LaunchTemplateConfiguration& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>Identifies the Amazon EC2 launch template to use.</p>
*/
inline const Aws::String& GetLaunchTemplateId() const{ return m_launchTemplateId; }
/**
* <p>Identifies the Amazon EC2 launch template to use.</p>
*/
inline bool LaunchTemplateIdHasBeenSet() const { return m_launchTemplateIdHasBeenSet; }
/**
* <p>Identifies the Amazon EC2 launch template to use.</p>
*/
inline void SetLaunchTemplateId(const Aws::String& value) { m_launchTemplateIdHasBeenSet = true; m_launchTemplateId = value; }
/**
* <p>Identifies the Amazon EC2 launch template to use.</p>
*/
inline void SetLaunchTemplateId(Aws::String&& value) { m_launchTemplateIdHasBeenSet = true; m_launchTemplateId = std::move(value); }
/**
* <p>Identifies the Amazon EC2 launch template to use.</p>
*/
inline void SetLaunchTemplateId(const char* value) { m_launchTemplateIdHasBeenSet = true; m_launchTemplateId.assign(value); }
/**
* <p>Identifies the Amazon EC2 launch template to use.</p>
*/
inline LaunchTemplateConfiguration& WithLaunchTemplateId(const Aws::String& value) { SetLaunchTemplateId(value); return *this;}
/**
* <p>Identifies the Amazon EC2 launch template to use.</p>
*/
inline LaunchTemplateConfiguration& WithLaunchTemplateId(Aws::String&& value) { SetLaunchTemplateId(std::move(value)); return *this;}
/**
* <p>Identifies the Amazon EC2 launch template to use.</p>
*/
inline LaunchTemplateConfiguration& WithLaunchTemplateId(const char* value) { SetLaunchTemplateId(value); return *this;}
/**
* <p>The account ID that this configuration applies to.</p>
*/
inline const Aws::String& GetAccountId() const{ return m_accountId; }
/**
* <p>The account ID that this configuration applies to.</p>
*/
inline bool AccountIdHasBeenSet() const { return m_accountIdHasBeenSet; }
/**
* <p>The account ID that this configuration applies to.</p>
*/
inline void SetAccountId(const Aws::String& value) { m_accountIdHasBeenSet = true; m_accountId = value; }
/**
* <p>The account ID that this configuration applies to.</p>
*/
inline void SetAccountId(Aws::String&& value) { m_accountIdHasBeenSet = true; m_accountId = std::move(value); }
/**
* <p>The account ID that this configuration applies to.</p>
*/
inline void SetAccountId(const char* value) { m_accountIdHasBeenSet = true; m_accountId.assign(value); }
/**
* <p>The account ID that this configuration applies to.</p>
*/
inline LaunchTemplateConfiguration& WithAccountId(const Aws::String& value) { SetAccountId(value); return *this;}
/**
* <p>The account ID that this configuration applies to.</p>
*/
inline LaunchTemplateConfiguration& WithAccountId(Aws::String&& value) { SetAccountId(std::move(value)); return *this;}
/**
* <p>The account ID that this configuration applies to.</p>
*/
inline LaunchTemplateConfiguration& WithAccountId(const char* value) { SetAccountId(value); return *this;}
/**
* <p>Set the specified Amazon EC2 launch template as the default launch template
* for the specified account.</p>
*/
inline bool GetSetDefaultVersion() const{ return m_setDefaultVersion; }
/**
* <p>Set the specified Amazon EC2 launch template as the default launch template
* for the specified account.</p>
*/
inline bool SetDefaultVersionHasBeenSet() const { return m_setDefaultVersionHasBeenSet; }
/**
* <p>Set the specified Amazon EC2 launch template as the default launch template
* for the specified account.</p>
*/
inline void SetSetDefaultVersion(bool value) { m_setDefaultVersionHasBeenSet = true; m_setDefaultVersion = value; }
/**
* <p>Set the specified Amazon EC2 launch template as the default launch template
* for the specified account.</p>
*/
inline LaunchTemplateConfiguration& WithSetDefaultVersion(bool value) { SetSetDefaultVersion(value); return *this;}
private:
Aws::String m_launchTemplateId;
bool m_launchTemplateIdHasBeenSet;
Aws::String m_accountId;
bool m_accountIdHasBeenSet;
bool m_setDefaultVersion;
bool m_setDefaultVersionHasBeenSet;
};
} // namespace Model
} // namespace imagebuilder
} // namespace Aws
| 33.234568
| 137
| 0.691865
|
[
"model"
] |
e8322127974b10684a93fd3378643f8112d6a9c7
| 1,750
|
h
|
C
|
cc/modules/features2d/descriptorMatching.h
|
luciany/opencv4nodejs
|
502b4a2ef303e805a4da1d6b79f4d3d01707eb6e
|
[
"MIT"
] | 1
|
2018-03-20T02:01:40.000Z
|
2018-03-20T02:01:40.000Z
|
cc/modules/features2d/descriptorMatching.h
|
goldyraj/facerecognition
|
9b0820135eb8cdaf783b3d560695bfb324083270
|
[
"MIT"
] | null | null | null |
cc/modules/features2d/descriptorMatching.h
|
goldyraj/facerecognition
|
9b0820135eb8cdaf783b3d560695bfb324083270
|
[
"MIT"
] | 1
|
2018-05-31T19:19:19.000Z
|
2018-05-31T19:19:19.000Z
|
#include "macros.h"
#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>
#include "Mat.h"
#include "KeyPoint.h"
#include "DescriptorMatch.h"
#ifndef __FF_DESCRIPTORMATCHING_H__
#define __FF_DESCRIPTORMATCHING_H__
class DescriptorMatching : public Nan::ObjectWrap {
public:
static NAN_MODULE_INIT(Init);
static NAN_METHOD(MatchFlannBased);
static NAN_METHOD(MatchBruteForce);
static NAN_METHOD(MatchBruteForceL1);
static NAN_METHOD(MatchBruteForceHamming);
static NAN_METHOD(MatchBruteForceHammingLut);
static NAN_METHOD(MatchBruteForceSL2);
static NAN_METHOD(MatchFlannBasedAsync);
static NAN_METHOD(MatchBruteForceAsync);
static NAN_METHOD(MatchBruteForceL1Async);
static NAN_METHOD(MatchBruteForceHammingAsync);
static NAN_METHOD(MatchBruteForceHammingLutAsync);
static NAN_METHOD(MatchBruteForceSL2Async);
#if CV_VERSION_MINOR < 2
static void match(Nan::NAN_METHOD_ARGS_TYPE info, std::string matcherType);
static void matchAsync(Nan::NAN_METHOD_ARGS_TYPE info, std::string matcherType);
#else
static void match(Nan::NAN_METHOD_ARGS_TYPE info, int matcherType);
static void matchAsync(Nan::NAN_METHOD_ARGS_TYPE info, int matcherType);
#endif
struct MatchContext {
public:
cv::Ptr<cv::DescriptorMatcher> matcher;
cv::Mat descFrom;
cv::Mat descTo;
std::vector<cv::DMatch> dmatches;
const char* execute() {
matcher->match(descFrom, descTo, dmatches);
return "";
}
FF_VAL getReturnValue() {
FF_ARR jsMatches = FF_NEW_ARRAY(dmatches.size());
uint i = 0;
for (auto dmatch : dmatches) {
FF_OBJ jsMatch = FF_NEW_INSTANCE(DescriptorMatch::constructor);
FF_UNWRAP(jsMatch, DescriptorMatch)->dmatch = dmatch;
jsMatches->Set(i++, jsMatch);
}
return jsMatches;
}
};
};
#endif
| 29.166667
| 81
| 0.773714
|
[
"vector"
] |
e84676c682aa099951a1726ad8800dcf21418935
| 903
|
h
|
C
|
src/core/archive/IArchive.h
|
PearCoding/PearRay
|
8654a7dcd55cc67859c7c057c7af64901bf97c35
|
[
"MIT"
] | 19
|
2016-11-07T00:01:19.000Z
|
2021-12-29T05:35:14.000Z
|
src/core/archive/IArchive.h
|
PearCoding/PearRay
|
8654a7dcd55cc67859c7c057c7af64901bf97c35
|
[
"MIT"
] | 33
|
2016-07-06T21:58:05.000Z
|
2020-08-01T18:18:24.000Z
|
src/core/archive/IArchive.h
|
PearCoding/PearRay
|
8654a7dcd55cc67859c7c057c7af64901bf97c35
|
[
"MIT"
] | null | null | null |
#pragma once
#include "PR_Config.h"
namespace PR {
class RayStream;
class HitStream;
class BoundingBox;
struct Ray;
struct HitEntry;
/// An archive is a containerlike object with a bounding box. A scene is a special case of an archive
class PR_LIB_CORE IArchive {
public:
/// Traces a stream of rays and produces a stream of hits
virtual void traceRays(RayStream& rays, HitStream& hits) const = 0;
/// Traces a single ray and returns true if something was hit. Information about the hit are updated if a hit was found
virtual bool traceSingleRay(const Ray& ray, HitEntry& entry) const = 0;
/// Traces a single ray and returns true if something lays within the given distance
virtual bool traceShadowRay(const Ray& ray, float distance = PR_INF) const = 0;
/// Bounding box containing all elements inside in world coordinates.
virtual BoundingBox boundingBox() const = 0;
};
} // namespace PR
| 34.730769
| 120
| 0.75969
|
[
"object"
] |
e85f3ed2f779d02c512b859b040654f80631fd32
| 2,389
|
h
|
C
|
src/SparseVector.h
|
rumkex/IonTools
|
e4c80a6385fa41fd7dd3721636a1a4b177839625
|
[
"BSD-3-Clause"
] | 3
|
2018-08-09T08:49:40.000Z
|
2019-07-24T02:48:55.000Z
|
src/SparseVector.h
|
rumkex/IonTools
|
e4c80a6385fa41fd7dd3721636a1a4b177839625
|
[
"BSD-3-Clause"
] | null | null | null |
src/SparseVector.h
|
rumkex/IonTools
|
e4c80a6385fa41fd7dd3721636a1a4b177839625
|
[
"BSD-3-Clause"
] | 1
|
2019-05-22T12:22:45.000Z
|
2019-05-22T12:22:45.000Z
|
#pragma once
#include <unordered_map>
#include <ostream>
#include <vector>
using namespace std;
class SparseVector
{
private:
unordered_map<int, double> values;
public:
SparseVector(void)
{}
SparseVector(unordered_map<int, double> val): values(val)
{}
unordered_map<int, double>::iterator begin()
{
return values.begin();
}
unordered_map<int, double>::iterator end()
{
return values.end();
}
unordered_map<int, double>::const_iterator cbegin() const
{
return values.cbegin();
}
unordered_map<int, double>::const_iterator cend() const
{
return values.cend();
}
int size()
{
return values.size();
}
double& operator[](int key)
{
return values[key];
}
double operator[](int key) const
{
return values.count(key) ? values.at(key): 0;
}
const SparseVector& operator*= (double other)
{
for(auto it = values.begin(); it != values.end(); it++)
values[(*it).first] = other * (*it).second;
return *this;
}
const SparseVector& operator+= (const SparseVector& other)
{
for(auto it = other.values.begin(); it != other.values.end(); it++)
values[(*it).first] += (*it).second;
return *this;
}
const SparseVector& operator-= (const SparseVector& other)
{
for(auto it = other.values.begin(); it != other.values.end(); it++)
values[(*it).first] -= (*it).second;
return *this;
}
SparseVector operator* (double other) const
{
SparseVector result(values);
return result *= other;
}
SparseVector operator+ (const SparseVector& other) const
{
SparseVector result(values);
return (result += other);
}
SparseVector operator- (const SparseVector& other) const
{
SparseVector result(values);
return (result -= other);
}
template <class TVector>
double dot(const TVector& other) const
{
double sum = 0.0;
for(auto it = values.begin(); it != this->values.end(); it++)
{
int key = (*it).first;
sum += other[key] * (*it).second;
}
return sum;
}
double sum() const
{
double sum = 0.0;
for(auto it = values.begin(); it != this->values.end(); it++)
sum += (*it).second;
return sum;
}
void clear()
{
values.clear();
}
double lengthSquared() const
{
double sum = 0.0;
for(auto it = values.begin(); it != this->values.end(); it++)
sum += (*it).second * (*it).second;
return sum;
}
~SparseVector(void)
{
}
};
ostream& operator<<(ostream& out, SparseVector &v);
| 17.962406
| 69
| 0.640854
|
[
"vector"
] |
e8690d5dcdb723b097d54760ef42985626ffab24
| 7,322
|
h
|
C
|
PlatformServices/MediaGateWayServer/MediaGateWayServer/Protocol/HttpProtocol.h
|
github188/MediaResolution
|
6ada78d907eba4da5ede7e9eba939fd4957492d4
|
[
"Apache-2.0"
] | null | null | null |
PlatformServices/MediaGateWayServer/MediaGateWayServer/Protocol/HttpProtocol.h
|
github188/MediaResolution
|
6ada78d907eba4da5ede7e9eba939fd4957492d4
|
[
"Apache-2.0"
] | null | null | null |
PlatformServices/MediaGateWayServer/MediaGateWayServer/Protocol/HttpProtocol.h
|
github188/MediaResolution
|
6ada78d907eba4da5ede7e9eba939fd4957492d4
|
[
"Apache-2.0"
] | 1
|
2022-02-15T06:32:42.000Z
|
2022-02-15T06:32:42.000Z
|
#ifndef HTTP_PROTOCOL__H
#define HTTP_PROTOCOL__H
#include <vector>
#include "Markup.h"
#include "Poco/HashMap.h"
#include <algorithm>
#include "Poco/Mutex.h"
#include "Poco/ScopedLock.h"
#include "Poco/HashMap.h"
#include "VDeviceConfig.h"
#include "Markup.h"
using Poco::FastMutex;
using Poco::ScopedLock;
class CHttpDevInfoProtocol
{
public:
std::vector<int> m_FaultChannelVec;
std::vector<int> m_RealChannelVec;
std::string m_strDevId;
std::string Serialize()
{
CMarkup xml;
xml.SetDoc("<?xml version=\"1.0\" encoding=\"gb2312\"?>");
xml.AddElem("Message");
xml.IntoElem();
xml.AddElem("Dev");
xml.AddAttrib("Id",m_strDevId);
xml.IntoElem();
if (m_FaultChannelVec.size()!=0)
{
xml.AddElem("FaultChannel");
xml.IntoElem();
for (int j=0;j< m_FaultChannelVec.size();j++)
{
int nChannel =m_FaultChannelVec[j];
xml.AddElem("Channel",nChannel+1);
}
xml.OutOfElem();
}
//ptr->second.m_FaultChannelVec.clear();
if (m_RealChannelVec.size()!=0)
{
xml.AddElem("RealChannel");
xml.IntoElem();
for (int j=0;j< m_RealChannelVec.size();j++)
{
int nChannel = m_RealChannelVec[j];
xml.AddElem("Channel",nChannel+1);
}
xml.OutOfElem();
}
xml.OutOfElem();
xml.OutOfElem();
return xml.GetDoc();
}
};
class HttpServerInfoProtocol
{
public:
HttpServerInfoProtocol()
{
}
~HttpServerInfoProtocol()
{
}
void AddFaultChannel(std::string strDevId,int nChannel)
{
ScopedLock<FastMutex> lock(m_Mutex);
Poco::HashMap<std::string, CHttpDevInfoProtocol>::Iterator ptr = m_devVec.find(strDevId);
if (ptr==m_devVec.end())
{
CHttpDevInfoProtocol dev;
dev.m_strDevId=strDevId;
dev.m_FaultChannelVec.push_back(nChannel);
m_devVec[strDevId]=dev;
return;
}
std::vector<int>::iterator itrChannel = find(ptr->second.m_FaultChannelVec.begin(),ptr->second.m_FaultChannelVec.end(),nChannel);
if (itrChannel!=ptr->second.m_FaultChannelVec.end())
{
return;
}
ptr->second.m_FaultChannelVec.push_back(nChannel);
}
void AddRealChannel(std::string strDevId,int nChannel)
{
ScopedLock<FastMutex> lock(m_Mutex);
Poco::HashMap<std::string,CHttpDevInfoProtocol>::Iterator ptr = m_devVec.find(strDevId);
if (ptr==m_devVec.end())
{
CHttpDevInfoProtocol dev;
dev.m_strDevId=strDevId;
dev.m_RealChannelVec.push_back(nChannel);
m_devVec[strDevId]=dev;
return;
}
std::vector<int>::iterator itrChannel = find(ptr->second.m_RealChannelVec.begin(),ptr->second.m_RealChannelVec.end(),nChannel);
if (itrChannel!=ptr->second.m_RealChannelVec.end())
{
return;
}
ptr->second.m_RealChannelVec.push_back(nChannel);
}
void RemoveRealChannel(std::string strDevId,int nChannel)
{
ScopedLock<FastMutex> lock(m_Mutex);
Poco::HashMap<std::string,CHttpDevInfoProtocol>::Iterator ptr = m_devVec.find(strDevId);
if (ptr==m_devVec.end())
{
return;
}
std::vector<int>::iterator itrChannel = find(ptr->second.m_RealChannelVec.begin(),ptr->second.m_RealChannelVec.end(),nChannel);
if (itrChannel!=ptr->second.m_RealChannelVec.end())
{
ptr->second.m_RealChannelVec.erase(itrChannel);
if (ptr->second.m_RealChannelVec.size()==0&&ptr->second.m_FaultChannelVec.size()==0)
{
m_devVec.erase(ptr);
}
}
}
void RemoveFaultChannel()
{
for (Poco::HashMap<std::string,CHttpDevInfoProtocol>::Iterator ptr=m_devVec.begin();ptr!=m_devVec.end();ptr++)
{
ptr->second.m_FaultChannelVec.clear();
}
}
bool GetDevInfo(const std::string& strDevId,CHttpDevInfoProtocol& devInfo)
{
ScopedLock<FastMutex> lock(m_Mutex);
Poco::HashMap<std::string, CHttpDevInfoProtocol>::Iterator ptr = m_devVec.find(strDevId);
if (ptr==m_devVec.end())
{
return false;
}
devInfo = ptr->second;
return true;
}
public:
std::string Serialize()
{
CMarkup xml;
xml.SetDoc("<?xml version=\"1.0\" encoding=\"gb2312\"?>");
xml.AddElem("Message");
xml.IntoElem();
xml.AddElem("CPU");
xml.AddAttrib("CpuType",m_strCPUType);
xml.AddAttrib("UseRatio",m_strCPUUseRatio);
xml.AddElem("Memory");
xml.AddAttrib("Size",m_fMemorySize);
xml.AddAttrib("UseRatio",m_strMmoryUseRatio);
ScopedLock<FastMutex> lock(m_Mutex);
for (Poco::HashMap<std::string,CHttpDevInfoProtocol>::Iterator ptr = m_devVec.begin();ptr!=m_devVec.end();ptr++)
{
xml.AddElem("Dev");
xml.AddAttrib("Id",ptr->first);
xml.IntoElem();
if (ptr->second.m_FaultChannelVec.size()!=0)
{
xml.AddElem("FaultChannel");
xml.IntoElem();
for (int j=0;j< ptr->second.m_FaultChannelVec.size();j++)
{
int nChannel =ptr->second.m_FaultChannelVec[j];
xml.AddElem("Channel",nChannel+1);
}
xml.OutOfElem();
}
//ptr->second.m_FaultChannelVec.clear();
if ( ptr->second.m_RealChannelVec.size()!=0)
{
xml.AddElem("RealChannel");
xml.IntoElem();
for (int j=0;j< ptr->second.m_RealChannelVec.size();j++)
{
int nChannel = ptr->second.m_RealChannelVec[j];
xml.AddElem("Channel",nChannel+1);
}
xml.OutOfElem();
}
xml.OutOfElem();
}
return xml.GetDoc();
}
public:
std::string strDevId;
std::string m_strCPUType;
std::string m_strCPUUseRatio;
double m_fMemorySize;
std::string m_strMmoryUseRatio;
Poco::HashMap<std::string, CHttpDevInfoProtocol> m_devVec;
FastMutex m_Mutex;
};
class CHttpAddVPlatform
{
public:
CHttpAddVPlatform()
{
}
~CHttpAddVPlatform()
{
}
void UnSerialize(std::string& strMsg)
{
CMarkup xml;
xml.SetDoc(strMsg);
if(xml.FindElem("Message")==false)
{
return ;
}
xml.IntoElem();
if (xml.FindElem("VPlatforms")==false)
{
return ;
}
xml.IntoElem();
while(xml.FindElem("VirtualDevice"))
{
VDeviceConfig vplatform;
vplatform.m_sDeviceId=xml.GetAttrib("DeviceID");
vplatform.m_sExtendPara1=xml.GetAttrib("ExtendPara1");
vplatform.m_sPasswd=xml.GetAttrib("Passwd");
vplatform.m_sPlatformName=xml.GetAttrib("PlatformName");
vplatform.m_sPtzParam=xml.GetAttrib("PtzParam");
vplatform.m_sServerIP=xml.GetAttrib("IP");
vplatform.m_sUser=xml.GetAttrib("User");
vplatform.m_lPort=atol(xml.GetAttrib("Port").c_str());
vplatform.m_lSupportNM=atol(xml.GetAttrib("SupportNM").c_str());
vplatform.m_lSupportMutiStream=atol(xml.GetAttrib("SupportMutiStream").c_str());
vplatform.m_lPtzType=atol(xml.GetAttrib("PtzType").c_str());
vplatform.m_lMaxConnect=atol(xml.GetAttrib("DeviceMaxConnect").c_str());
m_VPlatformVec.push_back(vplatform);
}
}
public:
std::vector<VDeviceConfig> m_VPlatformVec;
};
class CHttpRemoveVPlatorm
{
public:
CHttpRemoveVPlatorm()
{
}
~CHttpRemoveVPlatorm()
{
}
void UnSerialize(std::string& strMsg)
{
CMarkup xml;
xml.SetDoc(strMsg);
//if(xml.FindElem("Message")==false)
//{
// return ;
//}
//xml.IntoElem();
if (xml.FindElem("VPlatforms")==false)
{
return ;
}
xml.IntoElem();
while(xml.FindElem("VirtualDevice"))
{
std::string strDevId=xml.GetAttrib("DeviceID");
m_VPlatformVec.push_back(strDevId);
}
}
public:
std::vector<std::string> m_VPlatformVec;
};
#endif
| 25.423611
| 132
| 0.665802
|
[
"vector"
] |
e879d3cd37da60575bb62dfce85030a07cf0c112
| 4,540
|
h
|
C
|
benchmarks/sto/OutputDataSerializer.h
|
shenweihai1/rolis-eurosys2022
|
59b3fd58144496a9b13415e30b41617b34924323
|
[
"MIT"
] | 1
|
2022-03-08T00:36:10.000Z
|
2022-03-08T00:36:10.000Z
|
benchmarks/sto/OutputDataSerializer.h
|
shenweihai1/rolis-eurosys2022
|
59b3fd58144496a9b13415e30b41617b34924323
|
[
"MIT"
] | null | null | null |
benchmarks/sto/OutputDataSerializer.h
|
shenweihai1/rolis-eurosys2022
|
59b3fd58144496a9b13415e30b41617b34924323
|
[
"MIT"
] | null | null | null |
//
// Created by mrityunjay kumar on 2019-07-02.
//
#pragma once
#include <vector>
#include <algorithm>
#include <functional>
#include <memory>
#include <map>
#include <unordered_map>
#include <type_traits>
#include <unistd.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iostream>
#include <cstdarg>
#include <string>
//#ifdef TEST_REPLAY_SPEED_FEAT
// #ifndef LOG_FOLDER
// #define LOG_FOLDER "/home/jay/prev_logs/"
// #endif
//#elif TEST_WRITE_SPEED_FEAT
// #ifndef LOG_FOLDER
// #define LOG_FOLDER "/home/jay/prev_logs/"
// #endif
//#else
// #ifndef LOG_FOLDER
// #define LOG_FOLDER "/home/AzureUser/prev_logs/"
// #endif
//#endif
#ifndef LOG_FOLDER
#define LOG_FOLDER "/home/AzureUser/prev_logs/"
#endif
#ifdef LOG_FOLDER
#define LOG_FOLDER_NAME LOG_FOLDER
#endif
#define INFO_SUFFIX "info/"
#define R_SUFFIX "replay_logs/"
#define W_SUFFIX "write_logs/"
#define STR3(STR1) STR1 INFO_SUFFIX
#define STR2(STR1) STR1 R_SUFFIX
#define STR4(STR1) STR1 W_SUFFIX
#define INFO_LOG_FOLDER_NAME STR3(LOG_FOLDER)
#define REPLAY_SAVER_PATH STR2(LOG_FOLDER)
#define WRITE_STATS_SAVER_PATH STR4(LOG_FOLDER)
struct LOGGING_CONST {
static std::string WHOLE_LOG_STRING;
static std::string WHOLE_INFO_STRING;
static void setlog(int threads, int runTime){
std::string SUFFIX_STRING = "GenLogThd"+std::to_string(threads)+".Time."+std::to_string(runTime)+"/";
WHOLE_LOG_STRING = LOG_FOLDER + SUFFIX_STRING;
WHOLE_INFO_STRING = LOG_FOLDER + SUFFIX_STRING + "info/";
}
};
bool util_mkpath( const std::string& path );
/**
* Singleton Logger Class.
*/
class OutputDataSerializer
{
public:
uint64_t UUID();
/**
* Logs a message
* @param _oss message to be logged.
*/
// void Log(std::ostream& _oss);
/**
* Logs a message
* @param sMessage message to be logged.
*/
void TimedLog (const char* sMessage,size_t len,size_t count);
void Log(const char* sMessage,size_t len);
void LLog(const char* sMessage,size_t len);
void Log(const std::string& sMessage);
void Log(const std::vector<long long unsigned int>* str);
void BloopLog();
void MapWriter(const std::map<std::string,long>& fileMap);
void MapWriter(const std::unordered_map<std::string,long>& fileMap);
/**
* Variable Length Logger function
* @param format string for the message to be logged.
*/
// void Log(const char * format);
/**
* << overloaded function to Logs a message
* @param sMessage message to be logged.
*/
OutputDataSerializer& operator<<(const std::string& sMessage);
/**
* Funtion to create the instance of logger class.
* @return singleton object of Clogger class..
*/
static OutputDataSerializer* GetLogger(int thread_id,const std::string& parent_folder_name);
public:
static void flush_all();
static void close_all();
OutputDataSerializer(int thread_id, const std::string& parent_folder_name,bool bloop=false);
~OutputDataSerializer(){
if(awesome_ostream.is_open()){
// gmtx.lock ();
std::cout << "Flushing for thread_id:" << thread_id << " Skip Close";
awesome_ostream << std::flush;
// awesome_ostream.close ();
// gmtx.unlock ();
}
}
void flush(bool bloop= false);
// static uint64_t _UUID;
private:
size_t wpos{0};
bool is_bloop_act;
int thread_id;
// size_t nBufSize;
// char *buffer;
static size_t BUFSIZE;
static constexpr uint64_t increment_value = uint64_t(0x1000);
/**
* Default constructor for the Logger class.
*/
OutputDataSerializer(int thread_id);
/**
* copy constructor for the Logger class.
*/
OutputDataSerializer(const OutputDataSerializer&){}; // copy constructor is private
/**
* assignment operator for the Logger class.
*/
OutputDataSerializer& operator=(const OutputDataSerializer&){ return *this; }; // assignment operator is private
/**
* Singleton logger class object pointer.
**/
static std::unordered_map<int, OutputDataSerializer*> m_pThis;
//static OutputDataSerializer* m_pThis;
/**
* Log file stream object.
**/
std::ofstream awesome_ostream;
static std::unordered_map<int,std::ofstream> m_FileStream;
static std::unordered_map<int,std::stringstream> m_Logfile;
static std::unordered_map<int,std::ofstream> m_FileStreamTimedLog;
static std::unordered_map<int,std::FILE *> m_FileStream3;
};
| 25.795455
| 117
| 0.680396
|
[
"object",
"vector"
] |
e87cd4e67fa3005fb917210e6ceded94cc914b33
| 3,316
|
h
|
C
|
MUKArrayDelta.h
|
muccy/MUKArrayDelta
|
3260fe6a4a4dc14b42cb87bec3c666cad5818350
|
[
"MIT"
] | 2
|
2015-04-27T12:47:13.000Z
|
2015-11-26T14:28:26.000Z
|
Example/Pods/MUKArrayDelta/MUKArrayDelta.h
|
muccy/MUKDataSource
|
3cb7dedcfcac610294e1b2a4eb20f864f064005e
|
[
"MIT"
] | null | null | null |
Example/Pods/MUKArrayDelta/MUKArrayDelta.h
|
muccy/MUKDataSource
|
3cb7dedcfcac610294e1b2a4eb20f864f064005e
|
[
"MIT"
] | null | null | null |
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Type of match between two items
*/
typedef NS_ENUM(NSInteger, MUKArrayDeltaMatchType) {
/**
No match: items are different
*/
MUKArrayDeltaMatchTypeNone,
/**
Partial match: items are not equal because they change from source array
to destination array
*/
MUKArrayDeltaMatchTypeChange,
/**
Complete match
*/
MUKArrayDeltaMatchTypeEqual
};
/**
A match between two items in source array and destination array
*/
@interface MUKArrayDeltaMatch : NSObject
/**
Index of matched item in source array
*/
@property (nonatomic, readonly) NSUInteger sourceIndex;
/**
Index of matched item in destination array
*/
@property (nonatomic, readonly) NSUInteger destinationIndex;
/**
Type of match
*/
@property (nonatomic, readonly) MUKArrayDeltaMatchType type;
/**
Designated initializer
*/
- (instancetype)initWithType:(MUKArrayDeltaMatchType)type sourceIndex:(NSUInteger)sourceIndex destinationIndex:(NSUInteger)destinationIndex NS_DESIGNATED_INITIALIZER;
/**
@returns YES when two movements are equal
*/
- (BOOL)isEqualToArrayDeltaMatch:(MUKArrayDeltaMatch *)match;
@end
/**
Comparator which takes two items and returns match type
*/
typedef MUKArrayDeltaMatchType (^MUKArrayDeltaMatchTest)(id object1, id object2);
/**
An object which tells you diffs between two arrays
*/
@interface MUKArrayDelta : NSObject
/**
Source array
*/
@property (nonatomic, copy, readonly, nullable) NSArray *sourceArray;
/**
Destination array
*/
@property (nonatomic, copy, readonly, nullable) NSArray *destinationArray;
/**
Inserted indexes. Indexes refer to destinationArray.
*/
@property (nonatomic, readonly) NSIndexSet *insertedIndexes;
/**
Deleted indexes. Indexes refer to sourceArray.
*/
@property (nonatomic, readonly) NSIndexSet *deletedIndexes;
/**
Set of MUKArrayDeltaMatch objects which represent equal matches
*/
@property (nonatomic, readonly) NSSet<MUKArrayDeltaMatch *> *equalMatches;
/**
Set of MUKArrayDeltaMatch objects which represent partial matches
*/
@property (nonatomic, readonly) NSSet<MUKArrayDeltaMatch *> *changes;
/**
Set of MUKArrayDeltaMatch objects which represent movements.
A match contained in movements set is contained inside equalMatches or
changes set, too.
*/
@property (nonatomic, readonly) NSSet<MUKArrayDeltaMatch *> *movements;
/**
Designated initializer.
@param sourceArray Source array
@param destinationArray Destination array
@param matchTest A block to compare source and destination items.
It may be nil but you lose changes detection.
@returns A fully initialized delta between sourceArray and destinationArray
*/
- (instancetype)initWithSourceArray:(nullable NSArray *)sourceArray destinationArray:(nullable NSArray *)destinationArray matchTest:(nullable MUKArrayDeltaMatchTest)matchTest NS_DESIGNATED_INITIALIZER;
/**
@returns YES when two deltas are equal
*/
- (BOOL)isEqualToArrayDelta:(MUKArrayDelta *)arrayDelta;
/**
@returns Projected source index to destination taking into account only insertions
before, deletions before and movements happened so far
*/
- (NSUInteger)intermediateDestinationIndexForMovement:(MUKArrayDeltaMatch *)movement;
@end
NS_ASSUME_NONNULL_END
| 29.873874
| 201
| 0.76146
|
[
"object"
] |
e88034dee4e2a35b870ea2b79cd5ad59cba5c974
| 1,395
|
h
|
C
|
testu01/src/lizardpwlcm/LizardPwlcm.h
|
vestincloud/LizardPwlcm
|
1166d2d4c3dfa1bc5b2977c15b673d0ac5794607
|
[
"Apache-2.0"
] | null | null | null |
testu01/src/lizardpwlcm/LizardPwlcm.h
|
vestincloud/LizardPwlcm
|
1166d2d4c3dfa1bc5b2977c15b673d0ac5794607
|
[
"Apache-2.0"
] | null | null | null |
testu01/src/lizardpwlcm/LizardPwlcm.h
|
vestincloud/LizardPwlcm
|
1166d2d4c3dfa1bc5b2977c15b673d0ac5794607
|
[
"Apache-2.0"
] | null | null | null |
/***
* Created by Zhang Ti-kui
*
*/
#ifndef __LIZARD_PWLCM__H
#define __LIZARD_PWLCM__H
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include "lizard.h"
#include "toolex.h"
#include "pwlcm.h"
/*-- States and control parameters for PWLCM1 and PWLCM2 --*/
static uint32_t P1 = 0;
static uint32_t P2 = 0;
static uint32_t X0 = 0;
static uint32_t X1 = 0;
/* -- Seed key and initial vector for LIZARD-PWLCM ---*/
static char *Kstr="f2942e83948d92f948b938a3913493";
static char *IVstr="8f918e48d93f3016";
uint8_t Kbin[122];
uint8_t IVbin[66];
uint32_t low_mask=0x0000ffff;
/***
*Initialize an interger by mostleft_bit in left and random bits generated by LIZARD for the others
*/
static inline void init_integer(uint32_t *data, uint32_t mostleft_bit, int length){
*data =mostleft_bit;
for(int i=0; i<length; i++){
*data <<=1;
*data |= (uint32_t)(step());
}
}
static inline void lizard_pwlcm_init(){
_construct(Kbin,IVbin);
init_integer(&X0, 0,NN);
init_integer(&X1, 0,NN);
init_integer(&P1,3, NN-3);
init_integer(&P2,2, NN-3);
init(X0,P1,X1,P2);
}
static inline void LizardPwlcm_seed(uint64_t IV){
hex2binArray(Kstr,Kbin);
hex2binArray(IVstr,IVbin);
lizard_pwlcm_init();
}
static inline uint32_t LizardPwlcm(){
return (pwlcm_cross(step()) << 16) | (pwlcm_cross(step()) & low_mask);
//return (uint64)pwlcm_cross(step());
}
#endif
| 21.136364
| 99
| 0.706093
|
[
"vector"
] |
e8819fd7138b383064ce5c1a2008d7277441ceac
| 469
|
h
|
C
|
REALSPACE/Include/rquaternion.h
|
WhyWolfie/source2007
|
324257e9c69bbaec872ebb7ae4f96ab2ce98f520
|
[
"FSFAP"
] | null | null | null |
REALSPACE/Include/rquaternion.h
|
WhyWolfie/source2007
|
324257e9c69bbaec872ebb7ae4f96ab2ce98f520
|
[
"FSFAP"
] | null | null | null |
REALSPACE/Include/rquaternion.h
|
WhyWolfie/source2007
|
324257e9c69bbaec872ebb7ae4f96ab2ce98f520
|
[
"FSFAP"
] | null | null | null |
#ifndef __RQUATERNION_H
#define __RQUATERNION_H
#include "rutils.h"
struct rquaternion {
public:
float x,y,z,w;
rquaternion(float _x,float _y,float _z,float _w) { x=_x;y=_y;z=_z;w=_w;}
rquaternion(const rquaternion &q) { x=q.x;y=q.y;z=q.z;w=q.w; }
rquaternion(rvector &axis,float angle);
rquaternion() {};
rquaternion operator * (rquaternion& p);
rvector v() { return rvector(x,y,z); }
rquaternion Conjugate();
rvector Transform(rvector& v);
};
#endif
| 18.76
| 73
| 0.695096
|
[
"transform"
] |
e89008b890d70835482159ae6c231e5c063f268e
| 509
|
h
|
C
|
apps/calculator/include/compile/MathCompiler.h
|
mcfongtw/LostInCompilation
|
ca6a61f7a4fa6f215207a5ab8970471ef2568fd6
|
[
"MIT"
] | 1
|
2016-11-29T13:41:28.000Z
|
2016-11-29T13:41:28.000Z
|
apps/calculator/include/compile/MathCompiler.h
|
mcfongtw/LostInCompilation
|
ca6a61f7a4fa6f215207a5ab8970471ef2568fd6
|
[
"MIT"
] | null | null | null |
apps/calculator/include/compile/MathCompiler.h
|
mcfongtw/LostInCompilation
|
ca6a61f7a4fa6f215207a5ab8970471ef2568fd6
|
[
"MIT"
] | null | null | null |
//
// Created by Michael Fong on 2016/11/12.
//
#ifndef LOSTINCOMPILATION_MATHCOMPILER_H
#define LOSTINCOMPILATION_MATHCOMPILER_H
#include "compile/Compilable.h"
/**
* MathCompiler compiles a given math equations from soure input
*
* @since 0.1
*/
class MathCompiler : public Compilable {
public:
MathCompiler();
virtual ~MathCompiler();
virtual bool compile(std::string& fname);
virtual bool compile(std::vector<std::string> content);
};
#endif //LOSTINCOMPILATION_MATHCOMPILER_H
| 18.178571
| 64
| 0.732809
|
[
"vector"
] |
95570fbdc7ad11aaf637a6e4bbd86fb88f5ac0de
| 15,156
|
h
|
C
|
src/utils/geometry.h
|
ZJUSSL/Autoref
|
e67587b782636031a079d43930cb1d2551b3fc7b
|
[
"MIT"
] | 1
|
2021-03-08T15:53:40.000Z
|
2021-03-08T15:53:40.000Z
|
src/utils/geometry.h
|
ZJUSSL/Autoref
|
e67587b782636031a079d43930cb1d2551b3fc7b
|
[
"MIT"
] | null | null | null |
src/utils/geometry.h
|
ZJUSSL/Autoref
|
e67587b782636031a079d43930cb1d2551b3fc7b
|
[
"MIT"
] | null | null | null |
#ifndef _GEOMETRY_H_
#define _GEOMETRY_H_
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
/************************************************************************/
/* CVector */
/************************************************************************/
double CNormalize(double angle);
class CVector {
public:
CVector() : _x(0), _y(0) {}
CVector(double x, double y) : _x(x), _y(y) {}
CVector(const CVector& v) : _x(v.x()), _y(v.y()) {}
bool setVector(double x, double y) {
_x = x;
_y = y;
return true;
}
double mod() const {
return std::sqrt(_x * _x + _y * _y);
}
double mod2() const {
return (_x * _x + _y * _y);
}
double dir() const {
return std::atan2(y(), x());
}
double theta(const CVector& v) {
//计算自身到v的夹角
double _theta;
_theta = std::atan2(_y, _x) - std::atan2(v.y(), v.x());
if (_theta > 3.14159265358979323846) return _theta - 2 * 3.14159265358979323846 ;
if (_theta < -3.14159265358979323846) return _theta + 2 * 3.14159265358979323846;
return _theta;
}
CVector rotate(double angle) const;
CVector unit() const {
CVector vector(_x, _y);
if (vector.mod() < 1e-8) {
std::cout << "WARNING Vector too small to have unit vector!\n";
return CVector(1, 0);
}
return CVector(vector.x() / vector.mod(),
vector.y() / vector.mod());
}
double x() const {
return _x;
}
double y() const {
return _y;
}
double value(double angle) const {
return mod() * std::cos(dir() - angle);
}
CVector operator +(const CVector& v) const {
return CVector(_x + v.x(), _y + v.y());
}
CVector operator -(const CVector& v) const {
return CVector(_x - v.x(), _y - v.y());
}
CVector operator *(double a) const {
return CVector(_x * a, _y * a);
}
double operator *(CVector b) const {
return double(_x * b.x() + _y * b.y()); //向量点乘
}
CVector operator /(double a) const {
return CVector(_x / a, _y / a);
}
CVector operator -() const {
return CVector(-1 * _x, -1 * _y);
}
friend std::ostream& operator <<(std::ostream& os, const CVector& v) {
return os << "(" << v.x() << ":" << v.y() << ")";
}
private:
double _x, _y;
};
/************************************************************************/
/* CGeoPoint */
/************************************************************************/
class CGeoPoint {
public:
CGeoPoint() : _x(0), _y(0) {}
~CGeoPoint() {}
CGeoPoint(double x, double y) : _x(x), _y(y) {}
CGeoPoint(const CGeoPoint& p) : _x(p.x()), _y(p.y()) {}
bool operator==(const CGeoPoint& rhs) {
return ((this->x() == rhs.x()) && (this->y() == rhs.y()));
}
double x() const {
return _x;
}
double y() const {
return _y;
}
void setX(double x) {
_x = x; // 2014/2/28 新增 设置x坐标 yys
}
void setY(double y) {
_y = y; // 2014/2/28 新增 设置y坐标 yys
}
bool fill(double x, double y) {
_x = x; //2018/4/14 新增 同时设置 wayne
_y = y;
return true;
}
double dist(const CGeoPoint& p) const {
return CVector(p - CGeoPoint(_x, _y)).mod();
}
double dist2(const CGeoPoint& p) const {
return CVector(p - CGeoPoint(_x, _y)).mod2();
}
CGeoPoint operator+(const CVector& v) const {
return CGeoPoint(_x + v.x(), _y + v.y());
}
CGeoPoint operator*(const double& a) const {
return CGeoPoint(_x * a, _y * a);
}
CVector operator-(const CGeoPoint& p) const {
return CVector(_x - p.x(), _y - p.y());
}
CGeoPoint midPoint(const CGeoPoint& p) const {
return CGeoPoint((_x + p.x()) / 2, (_y + p.y()) / 2);
}
friend std::ostream& operator <<(std::ostream& os, const CGeoPoint& v) {
return os << "(" << v.x() << ":" << v.y() << ")";
}
private:
double _x, _y;
};
/************************************************************************/
/* CGeoLine */
/************************************************************************/
class CGeoLine {
public:
CGeoLine() {}
CGeoLine(const CGeoPoint& p1, const CGeoPoint& p2) : _p1(p1), _p2(p2) {
calABC();
}
CGeoLine(const CGeoPoint& p, double angle) : _p1(p), _p2(p.x() + std::cos(angle), p.y() + std::sin(angle)) {
calABC();
}
void calABC() {
if(_p1.y() == _p2.y()) {
_a = 0;
_b = 1;
_c = -1.0 * _p1.y();
} else {
_a = 1;
_b = -1.0 * (_p1.x() - _p2.x()) / (_p1.y() - _p2.y());
_c = (_p1.x() * _p2.y() - _p1.y() * _p2.x()) / (_p1.y() - _p2.y());
}
}
//投影点
CGeoPoint projection(const CGeoPoint& p) const {
if (_p2.x() == _p1.x()) {
return CGeoPoint(_p1.x(), p.y());
} else {
// 如果该线段不平行于X轴也不平行于Y轴,则斜率存在且不为0。设线段的两端点为pt1和pt2,斜率为:
double k = (_p2.y() - _p1.y()) / (_p2.x() - _p1.x());
// 该直线方程为: y = k* ( x - pt1.x) + pt1.y
// 其垂线的斜率为 -1/k,垂线方程为: y = (-1/k) * (x - point.x) + point.y
// 联立两直线方程解得:
double x = (k * k * _p1.x() + k * (p.y() - _p1.y()) + p.x()) / (k * k + 1);
double y = k * (x - _p1.x()) + _p1.y();
return CGeoPoint(x, y);
}
}
CGeoPoint point1() const {
return _p1;
}
CGeoPoint point2() const {
return _p2;
}
bool operator==(const CGeoLine& rhs) {
return ((this->point1().x() == rhs.point1().x()) && (this->point1().y() == rhs.point1().y())
&& (this->point2().x() == rhs.point2().x()) && (this->point2().y() == rhs.point2().y()));
}
const double& a() const {
return _a;
}
const double& b() const {
return _b;
}
const double& c() const {
return _c;
}
private:
CGeoPoint _p1;
CGeoPoint _p2;
// 直线的解析方程 a*x+b*y+c=0 为统一表示,约定 a>= 0
double _a;
double _b;
double _c;
};
class CGeoLineLineIntersection {
public:
CGeoLineLineIntersection(const CGeoLine& line_1, const CGeoLine& line_2);
bool Intersectant() const {
return _intersectant;
}
const CGeoPoint& IntersectPoint() const {
return _point;
}
private:
bool _intersectant;
CGeoPoint _point;
};
/************************************************************************/
/* CGeoSegment / 线段 */
/************************************************************************/
class CGeoSegment: public CGeoLine {
public:
CGeoSegment() {}
CGeoSegment(const CGeoPoint& p1, const CGeoPoint& p2) : CGeoLine(p1, p2), _start(p1), _end(p2) {
_compareX = std::abs(p1.x() - p2.x()) > std::abs(p1.y() - p2.y());
_center = CGeoPoint((p1.x() + p2.x()) / 2, (p1.y() + p2.y()) / 2);
}
bool IsPointOnLineOnSegment(const CGeoPoint& p) const { // 直线上的点是否在线段上
if(_compareX) {
return p.x() > (std::min)(_start.x(), _end.x()) && p.x() < (std::max)(_start.x(), _end.x());
}
return p.y() > (std::min)(_start.y(), _end.y()) && p.y() < (std::max)(_start.y(), _end.y());
}
bool IsSegmentsIntersect(const CGeoSegment& p) const {
CGeoLineLineIntersection tmpInter(*this, p);
CGeoPoint interPoint = tmpInter.IntersectPoint();
return (IsPointOnLineOnSegment(interPoint) && p.IsPointOnLineOnSegment(interPoint));
}
CGeoPoint segmentsIntersectPoint(const CGeoSegment& p) const {
CGeoLineLineIntersection tmpInter(*this, p);
CGeoPoint interPoint = tmpInter.IntersectPoint();
if (IsPointOnLineOnSegment(interPoint) && p.IsPointOnLineOnSegment(interPoint))
return interPoint;
else return CGeoPoint(9999, 9999);
}
double dist2Point(const CGeoPoint& p) {
CGeoPoint tmpProj = projection(p);
if (IsPointOnLineOnSegment(tmpProj)) return p.dist(tmpProj);
else return std::min(_start.dist(p), _end.dist(p));
}
double dist2Segment(const CGeoSegment& s) {
if (IsSegmentsIntersect(s)) return 0;
else return std::min(dist2Point(s.point1()), dist2Point(s.point2()));
}
const CGeoPoint& start() const {
return _start;
}
const CGeoPoint& end() const {
return _end;
}
const CGeoPoint& center() {
return _center;
}
private:
CGeoPoint _start;
CGeoPoint _end;
CGeoPoint _center;
bool _compareX;
};
/************************************************************************/
/* CGeoShape */
/************************************************************************/
class CGeoShape {
public:
virtual ~CGeoShape() { }
virtual bool HasPoint( const CGeoPoint& p) const = 0;
};
/************************************************************************/
/* CGeoRectangle */
/************************************************************************/
class CGeoRectangle : public CGeoShape {
public:
CGeoRectangle() {
calPoint(0, 0, 0, 0);
}
CGeoRectangle( const CGeoPoint& leftTop, const CGeoPoint& rightDown) {
calPoint(leftTop.x(), leftTop.y(), rightDown.x(), rightDown.y());
}
CGeoRectangle( double x1, double y1, double x2, double y2) {
calPoint(x1, y1, x2, y2);
}
void calPoint(double x1, double y1, double x2, double y2) {
_point[0] = CGeoPoint(x1, y1);
_point[1] = CGeoPoint(x1, y2);
_point[2] = CGeoPoint(x2, y2);
_point[3] = CGeoPoint(x2, y1);
}
double dist2Point(const CGeoPoint& p) {
// std::cout << "GEO COMPUTE IS " <<fabs(p.x() - _point[0].x()) << " " << fabs(p.x() - _point[2].x()) << " " << fabs(_point[0].x() - _point[2].x()) << " " <<
// fabs(p.y() - _point[0].y()) << " " << fabs(p.y() - _point[2].y()) << " " << fabs(_point[0].x() - _point[2].y()) << std::endl;
if (fabs(p.x() - _point[0].x()) + fabs(p.x() - _point[2].x()) - fabs(_point[0].x() - _point[2].x()) < 1.0e-5 &&
fabs(p.y() - _point[0].y()) + fabs(p.y() - _point[2].y()) - fabs(_point[0].y() - _point[2].y()) < 1.0e-5) {
return 0; // the point is inside the rectangle
} else {
CGeoSegment s1(_point[0], _point[1]);
CGeoSegment s2(_point[1], _point[2]);
CGeoSegment s3(_point[2], _point[3]);
CGeoSegment s4(_point[3], _point[0]);
return std::min(s1.dist2Point(p), std::min(s2.dist2Point(p), std::min(s3.dist2Point(p), s4.dist2Point(p))));
}
}
virtual bool HasPoint(const CGeoPoint& p) const;
CGeoPoint _point[4];
};
/************************************************************************/
/* CGeoLineRectangleIntersection */
/************************************************************************/
class CGeoLineRectangleIntersection {
public:
CGeoLineRectangleIntersection(const CGeoLine& line, const CGeoRectangle& rect);
bool intersectant() const {
return _intersectant;
}
const CGeoPoint& point1() const {
return _point[0];
}
const CGeoPoint& point2() const {
return _point[1];
}
private:
bool _intersectant;
CGeoPoint _point[2];
};
/************************************************************************/
/* CGeoCircle */
/************************************************************************/
class CGeoCirlce : public CGeoShape {
public:
CGeoCirlce() { }
CGeoCirlce(const CGeoPoint& c, double r) : _radius(r), _center(c) { }
virtual bool HasPoint(const CGeoPoint& p) const ;
CGeoPoint Center() const {
return _center;
}
double Radius() const {
return _radius;
}
double Radius2() const {
return _radius * _radius;
}
private:
double _radius;
CGeoPoint _center;
};
/************************************************************************/
/* CGeoLineCircleIntersection */
/************************************************************************/
class CGeoLineCircleIntersection {
public:
CGeoLineCircleIntersection(const CGeoLine& line, const CGeoCirlce& circle);
bool intersectant() const {
return _intersectant;
}
const CGeoPoint& point1() const {
return _point1;
}
const CGeoPoint& point2() const {
return _point2;
}
private:
bool _intersectant;
CGeoPoint _point1;
CGeoPoint _point2;
};
/************************************************************************/
/* CGeoEllipse,此椭圆的轴与坐标轴垂直 ,方程为(x-c.x())^2/m^2+(y-c.y())^2/n^2 =1 */
/************************************************************************/
class CGeoEllipse: CGeoShape {
public:
CGeoEllipse() { }
CGeoEllipse(CGeoPoint c, double m, double n) : _xaxis(m), _yaxis(n), _center(c) { }
CGeoPoint Center() const {
return _center;
}
virtual bool HasPoint(const CGeoPoint& p) const ;
double Xaxis()const {
return _xaxis;
}
double Yaxis()const {
return _yaxis;
}
private:
double _xaxis;
double _yaxis;
CGeoPoint _center;
};
/************************************************************************/
/* CGeoLineCircleIntersection */
/************************************************************************/
class CGeoLineEllipseIntersection {
public:
CGeoLineEllipseIntersection(const CGeoLine& line, const CGeoEllipse& circle);
bool intersectant() const {
return _intersectant;
}
const CGeoPoint& point1() const {
return _point1;
}
const CGeoPoint& point2() const {
return _point2;
}
private:
bool _intersectant;
CGeoPoint _point1;
CGeoPoint _point2;
};
/*********************************************************************/
/* CGeoSegmentCircleIntersection */
/********************************************************************/
class CGeoSegmentCircleIntersection {
public:
CGeoSegmentCircleIntersection(const CGeoSegment& line, const CGeoCirlce& circle);
bool intersectant() const {
return _intersectant;
}
const CGeoPoint& point1() const {
return _point1;
}
const CGeoPoint& point2() const {
return _point2;
}
int size() {
return intersection_size;
}
private:
bool _intersectant;
int intersection_size;
CGeoPoint _point1;
CGeoPoint _point2;
};
#endif
| 33.30989
| 164
| 0.466746
|
[
"vector"
] |
956669fa4e5bc499a640107bdc3e4d3ca08de522
| 510
|
h
|
C
|
0589-N-ary-Tree-Preorder-Traversal/cpp_0589/Solution1.h
|
ooooo-youwillsee/leetcode
|
07b273f133c8cf755ea40b3ae9df242ce044823c
|
[
"MIT"
] | 12
|
2020-03-18T14:36:23.000Z
|
2021-12-19T02:24:33.000Z
|
0589-N-ary-Tree-Preorder-Traversal/cpp_0589/Solution1.h
|
ooooo-youwillsee/leetcode
|
07b273f133c8cf755ea40b3ae9df242ce044823c
|
[
"MIT"
] | null | null | null |
0589-N-ary-Tree-Preorder-Traversal/cpp_0589/Solution1.h
|
ooooo-youwillsee/leetcode
|
07b273f133c8cf755ea40b3ae9df242ce044823c
|
[
"MIT"
] | null | null | null |
//
// Created by ooooo on 2020/1/3.
//
#ifndef CPP_0589_SOLUTION1_H
#define CPP_0589_SOLUTION1_H
#include "Node.h"
/**
* recursion
*/
class Solution {
public:
void help(Node *node, vector<int> &vec) {
if (!node) return;
vec.push_back(node->val);
for (auto child: node->children) {
help(child, vec);
}
}
vector<int> preorder(Node *root) {
vector<int> vec;
help(root, vec);
return vec;
}
};
#endif //CPP_0589_SOLUTION1_H
| 16.451613
| 45
| 0.570588
|
[
"vector"
] |
9568d8c04b66b60a0ecf24e092102b1c4adfa238
| 190
|
h
|
C
|
src/include/inference.h
|
joshuaroll/plmc
|
1a9a1e9228a2177c618c69040ea8cfc2d902d9df
|
[
"MIT"
] | 72
|
2016-04-19T00:52:12.000Z
|
2022-02-08T20:02:54.000Z
|
src/include/inference.h
|
joshuaroll/plmc
|
1a9a1e9228a2177c618c69040ea8cfc2d902d9df
|
[
"MIT"
] | 8
|
2016-12-22T06:25:38.000Z
|
2020-08-18T19:48:28.000Z
|
src/include/inference.h
|
joshuaroll/plmc
|
1a9a1e9228a2177c618c69040ea8cfc2d902d9df
|
[
"MIT"
] | 29
|
2016-02-17T20:31:49.000Z
|
2021-12-03T07:09:47.000Z
|
#ifndef INFERENCE_H
#define INFERENCE_H
/* Estimates parameters of maximum entropy model */
lbfgsfloatval_t *InferPairModel(alignment_t *ali, options_t *options);
#endif /* INFERENCE_H */
| 23.75
| 70
| 0.784211
|
[
"model"
] |
957aa6267bf3f3175d4d30cce6f6d8ad2d3f33f2
| 15,624
|
h
|
C
|
admin/pchealth/sr/inc/srapi.h
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
admin/pchealth/sr/inc/srapi.h
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
admin/pchealth/sr/inc/srapi.h
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
/*++
Copyright (c) 1999-2000 Microsoft Corporation
Module Name:
srapi.h
Abstract:
This module defines the public System Restore interface for nt.
Author:
Paul McDaniel (paulmcd) 24-Feb-2000
Revision History:
Paul McDaniel (paulmcd) 18-Apr-2000 completely new version
--*/
#ifndef _SRAPI_H_
#define _SRAPI_H_
#ifdef __cplusplus
extern "C" {
#endif
/***************************************************************************++
Routine Description:
SrCreateControlHandle is used to retrieve a HANDLE that can be used
to perform control operations on the driver.
Arguments:
pControlHandle - receives the newly created HANDLE. The controlling
application must call CloseHandle when it is done.
Options - one of the below options.
Return Value:
ULONG - Completion status.
--***************************************************************************/
#define SR_OPTION_OVERLAPPED 0x00000001 // for async
#define SR_OPTION_VALID 0x00000001 //
ULONG
WINAPI
SrCreateControlHandle (
IN ULONG Options,
OUT PHANDLE pControlHandle
);
/***************************************************************************++
Routine Description:
SrCreateRestorePoint is called by the controlling application to declare
a new restore point. The driver will create a local restore directory
and then return a unique sequence number to the controlling app.
Arguments:
ControlHandle - the control HANDLE.
pNewRestoreNumber - holds the new restore number on return. example: if
the new restore point directory is \_restore\rp5 this will return
the number 5
Return Value:
ULONG - Completion status.
--***************************************************************************/
ULONG
WINAPI
SrCreateRestorePoint (
IN HANDLE ControlHandle,
OUT PULONG pNewRestoreNumber
);
/***************************************************************************++
Routine Description:
SrGetNextSequenceNum is called by the application to get the next
available sequence number from the driver.
Arguments:
ControlHandle - the control HANDLE.
pNewSequenceNumber - holds the new sequnce number on return.
Return Value:
ULONG - Completion status.
--***************************************************************************/
ULONG
WINAPI
SrGetNextSequenceNum(
IN HANDLE ControlHandle,
OUT PINT64 pNextSequenceNum
);
/***************************************************************************++
Routine Description:
SrReloadConfiguration causes the driver to reload it's configuration
from it's configuration file that resides in a preassigned location.
A controlling service can update this file, then alert the driver to
reload it.
this file is %systemdrive%\_restore\_exclude.cfg .
Arguments:
ControlHandle - the control HANDLE.
Return Value:
ULONG - Completion status.
--***************************************************************************/
ULONG
WINAPI
SrReloadConfiguration (
IN HANDLE ControlHandle
);
/***************************************************************************++
Routine Description:
SrStopMonitoring will cause the driver to stop monitoring file changes.
The default state of the driver on startup is to monitor file changes.
Arguments:
ControlHandle - the control HANDLE.
Return Value:
ULONG - Completion status.
--***************************************************************************/
ULONG
WINAPI
SrStopMonitoring (
IN HANDLE ControlHandle
);
/***************************************************************************++
Routine Description:
SrStartMonitoring will cause the driver to start monitoring file changes.
The default state of the driver on startup is to monitor file changes.
This api is only needed in the case that the controlling application has
called SrStopMonitoring and wishes to restart it.
Arguments:
ControlHandle - the control HANDLE.
Return Value:
ULONG - Completion status.
--***************************************************************************/
ULONG
WINAPI
SrStartMonitoring (
IN HANDLE ControlHandle
);
//
// these are the interesting types of events that can happen.
//
typedef enum _SR_EVENT_TYPE
{
SrEventInvalid = 0, // no action has been set
SrEventStreamChange = 0x01, // data is being changed in a stream
SrEventAclChange = 0x02, // an acl on a file or directory is changing
SrEventAttribChange = 0x04, // an attribute on a file or directory is changing
SrEventStreamOverwrite = 0x08, // a stream is being opened for overwrite
SrEventFileDelete = 0x10, // a file is being opened for delete
SrEventFileCreate = 0x20, // a file is newly created, not overwriting anything
SrEventFileRename = 0x40, // a file is renamed (within monitored space)
SrEventDirectoryCreate = 0x80, // a dir is created
SrEventDirectoryRename = 0x100, // a dir is renamed (within monitored space)
SrEventDirectoryDelete = 0x200, // an empty dir is deleted
SrEventMountCreate = 0x400, // a mount point was created
SrEventMountDelete = 0x800, // a mount point was deleted
SrEventVolumeError = 0x1000, // a non-recoverable error occurred on the volume
SrEventMaximum = 0x1000,
SrEventStreamCreate = 0x2000, // a stream has been created. This will never
// be logged, but is used to make sure that
// we handle stream creations correctly.
SrEventLogMask = 0xffff,
//
// flags
//
SrEventNoOptimization = 0x00010000, // this flag on means no optimizations are to be performed
SrEventIsDirectory = 0x00020000, // this event happened on a directory
SrEventIsNotDirectory = 0x00040000, // this event happened on a non-directory (file)
SrEventSimulatedDelete = 0x00080000, // when set this is a simulated DELETE operation --
// the file is not really being deleted, but to
// SR it looks like a delete.
SrEventInPreCreate = 0x00100000, // when set, the create has not yet been succeeded by the filesystem
SrEventOpenById = 0x00200000 // when set, the create has not yet been succeeded by the filesystem
// and this file is being opened by ID.
} SR_EVENT_TYPE;
//
// this structure represents a notification from kernel mode
// to user mode. This is because of interesting volume activity
//
typedef enum _SR_NOTIFICATION_TYPE
{
SrNotificationInvalid = 0, // no action has been set
SrNotificationVolumeFirstWrite, // The first write on a volume occured
SrNotificationVolume25MbWritten,// 25 meg has been written the the volume
SrNotificationVolumeError, // A backup just failed, Context holds the win32 code.
SrNotificationMaximum
} SR_NOTIFICATION_TYPE, * PSR_NOTIFICATION_TYPE;
#define SR_NOTIFY_BYTE_COUNT 25 * (1024 * 1024)
//
// this the largest nt path the sr chooses to monitor. paths larger than
// this will be silently ignored and passed down to the file system
// unmonitored.
//
// NOTE: This lenght INCLUDES the terminating NULL at the end of the
// filename string.
//
#define SR_MAX_FILENAME_LENGTH 1000
//
// Restore needs to prepend the volume guid in addition to the filepath --
// so the maximum filepath length relative to the volume that can be supported
// is 1000 - strlen(guid) = 952 characters
// restore also appends suffixes like (2) to these names in cases of locked or
// conflicting files, so to be really safe, we choose an even smaller number
//
#define SR_MAX_FILENAME_PATH 940
#define MAKE_TAG(tag) ( (ULONG)(tag) )
#define SR_NOTIFICATION_RECORD_TAG MAKE_TAG( 'RNrS' )
#define IS_VALID_NOTIFICATION_RECORD(pObject) \
(((pObject) != NULL) && ((pObject)->Signature == SR_NOTIFICATION_RECORD_TAG))
typedef struct _SR_NOTIFICATION_RECORD
{
//
// SR_NOTIFICATION_RECORD_TAG
//
ULONG Signature;
//
// reserved
//
LIST_ENTRY ListEntry;
//
// the type of notification
//
SR_NOTIFICATION_TYPE NotificationType;
//
// the name of the volume being notified for
//
UNICODE_STRING VolumeName;
//
// a context/parameter
//
ULONG Context;
} SR_NOTIFICATION_RECORD, * PSR_NOTIFICATION_RECORD;
/***************************************************************************++
Routine Description:
SrWaitForNotificaiton is used to receive volume activity notifications
from the driver. This includes new volume, delete volume, and out of disk
space for a volume.
Arguments:
ControlHandle - the HANDLE from SrCreateControlHandle.
pNotification - the buffer to hold the NOTIFICATION_RECORD.
NotificationLength - the length in bytes of pNotification
pOverlapped - an OVERLAPPED structure if async io is enabled on the
HANDLE.
Return Value:
ULONG - Completion status.
--***************************************************************************/
ULONG
WINAPI
SrWaitForNotification (
IN HANDLE ControlHandle,
OUT PSR_NOTIFICATION_RECORD pNotification,
IN ULONG NotificationLength,
IN LPOVERLAPPED pOverlapped OPTIONAL
);
/***************************************************************************++
Routine Description:
SrSwitchAllLogs is used to cause the filter to close all of the open
log files on all volumes, and use new log files. this is used so that
another process can parse these files without worrying about the filter
writing to them. use this to get a consistent view of the restore point.
Arguments:
ControlHandle - the HANDLE from SrCreateControlHandle.
Return Value:
ULONG - Completion status.
--***************************************************************************/
ULONG
WINAPI
SrSwitchAllLogs (
IN HANDLE ControlHandle
);
/***************************************************************************++
Routine Description:
SrDisableVolume is used to temporarily disable monitoring on the
specified volume. this is reset by a call to SrReloadConfiguration.
There is no EnableVolume.
Arguments:
ControlHandle - the HANDLE from SrCreateControlHandle.
pVolumeName - the name of the volume to disable, in the nt format of
\Device\HarddiskDmVolumes\PhysicalDmVolumes\BlockVolume3.
Return Value:
ULONG - Completion status.
--***************************************************************************/
ULONG
WINAPI
SrDisableVolume (
IN HANDLE ControlHandle,
IN PWSTR pVolumeName
);
#define _SR_REQUEST(ioctl) \
((((ULONG)(ioctl)) >> 2) & 0x03FF)
#define SR_CREATE_RESTORE_POINT 0
#define SR_RELOAD_CONFIG 1
#define SR_START_MONITORING 2
#define SR_STOP_MONITORING 3
#define SR_WAIT_FOR_NOTIFICATION 4
#define SR_SWITCH_LOG 5
#define SR_DISABLE_VOLUME 6
#define SR_GET_NEXT_SEQUENCE_NUM 7
#define SR_NUM_IOCTLS 8
#define IOCTL_SR_CREATE_RESTORE_POINT CTL_CODE( FILE_DEVICE_UNKNOWN, SR_CREATE_RESTORE_POINT, METHOD_BUFFERED, FILE_WRITE_ACCESS )
#define IOCTL_SR_RELOAD_CONFIG CTL_CODE( FILE_DEVICE_UNKNOWN, SR_RELOAD_CONFIG, METHOD_NEITHER, FILE_WRITE_ACCESS )
#define IOCTL_SR_START_MONITORING CTL_CODE( FILE_DEVICE_UNKNOWN, SR_START_MONITORING, METHOD_NEITHER, FILE_WRITE_ACCESS )
#define IOCTL_SR_STOP_MONITORING CTL_CODE( FILE_DEVICE_UNKNOWN, SR_STOP_MONITORING, METHOD_NEITHER, FILE_WRITE_ACCESS )
#define IOCTL_SR_WAIT_FOR_NOTIFICATION CTL_CODE( FILE_DEVICE_UNKNOWN, SR_WAIT_FOR_NOTIFICATION, METHOD_OUT_DIRECT, FILE_READ_ACCESS )
#define IOCTL_SR_SWITCH_LOG CTL_CODE( FILE_DEVICE_UNKNOWN, SR_SWITCH_LOG, METHOD_NEITHER, FILE_WRITE_ACCESS )
#define IOCTL_SR_DISABLE_VOLUME CTL_CODE( FILE_DEVICE_UNKNOWN, SR_DISABLE_VOLUME, METHOD_BUFFERED, FILE_WRITE_ACCESS )
#define IOCTL_SR_GET_NEXT_SEQUENCE_NUM CTL_CODE( FILE_DEVICE_UNKNOWN, SR_GET_NEXT_SEQUENCE_NUM,METHOD_BUFFERED, FILE_WRITE_ACCESS )
//
// Names of the object directory, devices, driver, and service.
//
#define SR_CONTROL_DEVICE_NAME L"\\FileSystem\\Filters\\SystemRestore"
#define SR_DRIVER_NAME L"SR.SYS"
#define SR_SERVICE_NAME L"SR"
//
// The current interface version number. This version number must be
// updated after any significant changes to the interface (especially
// structure changes).
//
#define SR_INTERFACE_VERSION_MAJOR 0x0000
#define SR_INTERFACE_VERSION_MINOR 0x0005
//
// The name of the EA (Extended Attribute) passed to NtCreateFile(). This
// allows us to pass version information at the time the driver is opened,
// allowing SR.SYS to immediately fail open requests with invalid version
// numbers.
//
// N.B. The EA name (including the terminator) must be a multiple of eight
// to ensure natural alignment of the SR_OPEN_PACKET structure used as
// the EA value.
//
// 7654321076543210
#define SR_OPEN_PACKET_NAME "SrOpenPacket000"
#define SR_OPEN_PACKET_NAME_LENGTH (sizeof(SR_OPEN_PACKET_NAME) - 1)
C_ASSERT( ((SR_OPEN_PACKET_NAME_LENGTH + 1) & 7) == 0 );
//
// The following structure is used as the value for the EA named above.
//
typedef struct SR_OPEN_PACKET
{
USHORT MajorVersion;
USHORT MinorVersion;
} SR_OPEN_PACKET, *PSR_OPEN_PACKET;
//
// Registry paths.
//
#define REGISTRY_PARAMETERS L"\\Parameters"
#define REGISTRY_DEBUG_CONTROL L"DebugControl"
#define REGISTRY_PROCNAME_OFFSET L"ProcessNameOffset"
#define REGISTRY_STARTDISABLED L"FirstRun"
#define REGISTRY_DONTBACKUP L"DontBackup"
#define REGISTRY_MACHINE_GUID L"MachineGuid"
#define REGISTRY_SRSERVICE L"\\SRService"
#define REGISTRY_SRSERVICE_START L"Start"
//
// directory and file paths
//
#define SYSTEM_VOLUME_INFORMATION L"\\System Volume Information"
#define RESTORE_LOCATION SYSTEM_VOLUME_INFORMATION L"\\_restore%ws"
#define GENERAL_RESTORE_LOCATION SYSTEM_VOLUME_INFORMATION L"\\_restore"
#define RESTORE_FILELIST_LOCATION RESTORE_LOCATION L"\\_filelst.cfg"
//
// used as a prefix for restore point subdirs (e.g. \_restore\rp5)
//
#define RESTORE_POINT_PREFIX L"RP"
//
// used as a prefix for the backup files in a restore point subdir
// (e.g. \_restore\rp5\A0000025.dll)
//
#define RESTORE_FILE_PREFIX L"A"
#ifdef __cplusplus
}
#endif
#endif // _SRAPI_H_
| 29.590909
| 139
| 0.613479
|
[
"object"
] |
957b3423f2d78317e214fe70ad8c3b8fff26c029
| 2,842
|
h
|
C
|
Source/Common/FileRegistered.h
|
g-maxime/MediaConch_SourceCode
|
54208791ca0b6eb3f7bffd17f67e236777f69d89
|
[
"BSD-2-Clause"
] | 29
|
2016-01-28T08:58:54.000Z
|
2021-12-19T16:49:58.000Z
|
Source/Common/FileRegistered.h
|
g-maxime/MediaConch_SourceCode
|
54208791ca0b6eb3f7bffd17f67e236777f69d89
|
[
"BSD-2-Clause"
] | 218
|
2015-07-07T09:49:17.000Z
|
2022-03-21T06:18:37.000Z
|
Source/Common/FileRegistered.h
|
g-maxime/MediaConch_SourceCode
|
54208791ca0b6eb3f7bffd17f67e236777f69d89
|
[
"BSD-2-Clause"
] | 18
|
2015-06-19T17:58:34.000Z
|
2021-12-08T15:02:26.000Z
|
/* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// Core functions
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//---------------------------------------------------------------------------
#ifndef FileRegisteredH
#define FileRegisteredH
//---------------------------------------------------------------------------
#include <string>
namespace MediaConch {
//***************************************************************************
// Struct FileRegistered
//***************************************************************************
class FileRegistered
{
public:
FileRegistered() : analyze_percent(0), file_id(-1), policy(-1), display(-1), verbosity(-1), report_kind(0),
analyzed(false), implementation_valid(false), policy_valid(false), create_policy(false), need_update(true)
{
}
FileRegistered(const FileRegistered& f)
{
if (&f == this)
return;
this->filename = f.filename;
this->filepath = f.filepath;
this->file_id = f.file_id;
this->policy = f.policy;
this->display = f.display;
this->verbosity = f.verbosity;
this->analyze_percent = f.analyze_percent;
this->analyzed = f.analyzed;
this->implementation_valid = f.implementation_valid;
this->policy_valid = f.policy_valid;
this->create_policy = f.create_policy;
this->index = f.index;
this->report_kind = f.report_kind;
this->need_update = f.need_update;
for (size_t x = 0; x < f.generated_id.size(); ++x)
this->generated_id.push_back(f.generated_id[x]);
for (size_t x = 0; x < f.options.size(); ++x)
{
if (f.options[x] != "File_TryToFix")
this->options.push_back(f.options[x]);
}
}
std::string filename;
std::string filepath;
std::vector<long> generated_id;
std::vector<std::string> options;
double analyze_percent;
long file_id;
int policy;
int display;
int verbosity;
int report_kind;
unsigned int index;
bool analyzed;
bool implementation_valid;
bool policy_valid;
bool create_policy;
bool need_update;
};
}
#endif
| 32.295455
| 115
| 0.440887
|
[
"vector"
] |
9584f5223087300464a8bbc4ef8b3878d471eac3
| 27,521
|
c
|
C
|
src/libs/pdflib/libs/pdflib/p_annots.c
|
deep-1/haiku
|
b273e9733d25babe5e6702dc1e24f3dff1ffd6dc
|
[
"MIT"
] | 4
|
2016-03-29T21:45:21.000Z
|
2016-12-20T00:50:38.000Z
|
src/libs/pdflib/libs/pdflib/p_annots.c
|
jessicah/haiku
|
c337460525c39e870d31221d205a299d9cd79c6a
|
[
"MIT"
] | null | null | null |
src/libs/pdflib/libs/pdflib/p_annots.c
|
jessicah/haiku
|
c337460525c39e870d31221d205a299d9cd79c6a
|
[
"MIT"
] | 1
|
2020-05-08T04:02:02.000Z
|
2020-05-08T04:02:02.000Z
|
/*---------------------------------------------------------------------------*
| PDFlib - A library for generating PDF on the fly |
+---------------------------------------------------------------------------+
| Copyright (c) 1997-2004 Thomas Merz and PDFlib GmbH. All rights reserved. |
+---------------------------------------------------------------------------+
| |
| This software is subject to the PDFlib license. It is NOT in the |
| public domain. Extended versions and commercial licenses are |
| available, please check http://www.pdflib.com. |
| |
*---------------------------------------------------------------------------*/
/* $Id: p_annots.c 14574 2005-10-29 16:27:43Z bonefish $
*
* PDFlib routines for annnotations
*
*/
#include "p_intern.h"
/* Annotation types */
typedef enum {
ann_text, ann_locallink,
ann_pdflink, ann_weblink,
ann_launchlink, ann_attach
} pdf_annot_type;
/* icons for file attachments and text annotations */
typedef enum {
icon_file_graph, icon_file_paperclip,
icon_file_pushpin, icon_file_tag,
icon_text_comment, icon_text_insert,
icon_text_note, icon_text_paragraph,
icon_text_newparagraph, icon_text_key,
icon_text_help
} pdf_icon;
/* Annotations */
struct pdf_annot_s {
pdf_annot_type type; /* used for all annotation types */
pdc_rectangle rect; /* used for all annotation types */
pdc_id obj_id; /* used for all annotation types */
pdf_annot *next; /* used for all annotation types */
pdf_icon icon; /* attach and text */
char *filename; /* attach, launchlink, pdflink,weblink*/
char *contents; /* text, attach, pdflink */
char *mimetype; /* attach */
char *parameters; /* launchlink */
char *operation; /* launchlink */
char *defaultdir; /* launchlink */
char *title; /* text */
int open; /* text */
pdf_dest dest; /* locallink, pdflink */
/* -------------- annotation border style and color -------------- */
pdf_border_style border_style;
float border_width;
float border_red;
float border_green;
float border_blue;
float border_dash1;
float border_dash2;
};
static const char *pdf_border_style_names[] = {
"S", /* solid border */
"D", /* dashed border */
"B", /* beveled (three-dimensional) border */
"I", /* inset border */
"U" /* underlined border */
};
static const char *pdf_icon_names[] = {
/* embedded file icon names */
"Graph", "Paperclip", "Pushpin", "Tag",
/* text annotation icon names */
"Comment", "Insert", "Note", "Paragraph", "NewParagraph", "Key", "Help"
};
/* flags for annotation properties */
typedef enum {
pdf_ann_flag_invisible = 1,
pdf_ann_flag_hidden = 2,
pdf_ann_flag_print = 4,
pdf_ann_flag_nozoom = 8,
pdf_ann_flag_norotate = 16,
pdf_ann_flag_noview = 32,
pdf_ann_flag_readonly = 64
} pdf_ann_flag;
void
pdf_init_annots(PDF *p)
{
/* annotation border style defaults */
p->border_style = border_solid;
p->border_width = (float) 1.0;
p->border_red = (float) 0.0;
p->border_green = (float) 0.0;
p->border_blue = (float) 0.0;
p->border_dash1 = (float) 3.0;
p->border_dash2 = (float) 3.0;
/* auxiliary function parameters */
p->launchlink_parameters = NULL;
p->launchlink_operation = NULL;
p->launchlink_defaultdir = NULL;
}
void
pdf_cleanup_annots(PDF *p)
{
if (p->launchlink_parameters) {
pdc_free(p->pdc, p->launchlink_parameters);
p->launchlink_parameters = NULL;
}
if (p->launchlink_operation) {
pdc_free(p->pdc, p->launchlink_operation);
p->launchlink_operation = NULL;
}
if (p->launchlink_defaultdir) {
pdc_free(p->pdc, p->launchlink_defaultdir);
p->launchlink_defaultdir = NULL;
}
}
static void
pdf_init_annot(PDF *p, pdf_annot *ann)
{
(void) p;
ann->next = NULL;
ann->filename = NULL;
ann->mimetype = NULL;
ann->contents = NULL;
ann->mimetype = NULL;
ann->parameters = NULL;
ann->operation = NULL;
ann->defaultdir = NULL;
ann->title = NULL;
}
/* Write annotation border style and color */
static void
pdf_write_border_style(PDF *p, pdf_annot *ann)
{
/* don't write the default values */
if (ann->border_style == border_solid &&
ann->border_width == (float) 1.0 &&
ann->border_red == (float) 0.0 &&
ann->border_green == (float) 0.0 &&
ann->border_blue == (float) 0.0 &&
ann->border_dash1 == (float) 3.0 &&
ann->border_dash2 == (float) 3.0)
return;
if (ann->type != ann_attach) {
pdc_puts(p->out, "/BS");
pdc_begin_dict(p->out); /* BS dict */
pdc_puts(p->out, "/Type/Border\n");
/* Acrobat 6 requires this entry, and does not use /S/S as default */
pdc_printf(p->out, "/S/%s\n",
pdf_border_style_names[ann->border_style]);
/* Acrobat 6 requires this entry */
pdc_printf(p->out, "/W %f\n", ann->border_width);
if (ann->border_style == border_dashed)
pdc_printf(p->out, "/D[%f %f]\n",
ann->border_dash1, ann->border_dash2);
pdc_end_dict(p->out); /* BS dict */
/* Write the Border key in old-style PDF 1.1 format */
pdc_printf(p->out, "/Border[0 0 %f", ann->border_width);
if (ann->border_style == border_dashed &&
(ann->border_dash1 != (float) 0.0 || ann->border_dash2 !=
(float) 0.0))
/* set dashed border */
pdc_printf(p->out, "[%f %f]", ann->border_dash1, ann->border_dash2);
pdc_puts(p->out, "]\n");
}
/* write annotation color */
pdc_printf(p->out, "/C[%f %f %f]\n",
ann->border_red, ann->border_green, ann->border_blue);
}
void
pdf_write_annots_root(PDF *p)
{
pdf_annot *ann;
/* Annotations array */
if (p->annots) {
pdc_puts(p->out, "/Annots[");
for (ann = p->annots; ann != NULL; ann = ann->next) {
ann->obj_id = pdc_alloc_id(p->out);
pdc_printf(p->out, "%ld 0 R ", ann->obj_id);
}
pdc_puts(p->out, "]\n");
}
}
void
pdf_write_page_annots(PDF *p)
{
pdf_annot *ann;
for (ann = p->annots; ann != NULL; ann = ann->next) {
pdc_begin_obj(p->out, ann->obj_id); /* Annotation object */
pdc_begin_dict(p->out); /* Annotation dict */
pdc_puts(p->out, "/Type/Annot\n");
switch (ann->type) {
case ann_text:
pdc_puts(p->out, "/Subtype/Text\n");
pdc_printf(p->out, "/Rect[%f %f %f %f]\n",
ann->rect.llx, ann->rect.lly, ann->rect.urx, ann->rect.ury);
pdf_write_border_style(p, ann);
if (ann->open)
pdc_puts(p->out, "/Open true\n");
if (ann->icon != icon_text_note) /* note is default */
pdc_printf(p->out, "/Name/%s\n", pdf_icon_names[ann->icon]);
/* Contents key is required, but may be empty */
pdc_puts(p->out, "/Contents");
if (ann->contents) {
pdc_put_pdfunistring(p->out, ann->contents);
pdc_puts(p->out, "\n");
} else
pdc_puts(p->out, "()\n"); /* empty contents is OK */
/* title is optional */
if (ann->title) {
pdc_puts(p->out, "/T");
pdc_put_pdfunistring(p->out, ann->title);
pdc_puts(p->out, "\n");
}
break;
case ann_locallink:
pdc_puts(p->out, "/Subtype/Link\n");
pdc_printf(p->out, "/Rect[%f %f %f %f]\n",
ann->rect.llx, ann->rect.lly, ann->rect.urx, ann->rect.ury);
pdf_write_border_style(p, ann);
/* preallocate page object id for a later page */
if (ann->dest.page > p->current_page) {
while (ann->dest.page >= p->pages_capacity)
pdf_grow_pages(p);
/* if this page has already been used as a link target
* it will already have an object id.
*/
if (p->pages[ann->dest.page] == PDC_BAD_ID)
p->pages[ann->dest.page] = pdc_alloc_id(p->out);
}
pdc_puts(p->out, "/Dest");
pdf_write_destination(p, &ann->dest);
pdc_puts(p->out, "\n");
break;
case ann_pdflink:
pdc_puts(p->out, "/Subtype/Link\n");
pdc_printf(p->out, "/Rect[%f %f %f %f]\n",
ann->rect.llx, ann->rect.lly, ann->rect.urx, ann->rect.ury);
pdf_write_border_style(p, ann);
pdc_puts(p->out, "/A");
pdc_begin_dict(p->out); /* A dict */
pdc_puts(p->out, "/Type/Action/S/GoToR\n");
pdc_puts(p->out, "/D");
pdf_write_destination(p, &ann->dest);
pdc_puts(p->out, "\n");
pdc_puts(p->out, "/F");
pdc_begin_dict(p->out); /* F dict */
pdc_puts(p->out, "/Type/Filespec\n");
pdc_puts(p->out, "/F");
pdc_put_pdfstring(p->out, ann->filename,
(int)strlen(ann->filename));
pdc_puts(p->out, "\n");
pdc_end_dict(p->out); /* F dict */
pdc_end_dict(p->out); /* A dict */
break;
case ann_launchlink:
pdc_puts(p->out, "/Subtype/Link\n");
pdc_printf(p->out, "/Rect[%f %f %f %f]\n",
ann->rect.llx, ann->rect.lly, ann->rect.urx, ann->rect.ury);
pdf_write_border_style(p, ann);
pdc_puts(p->out, "/A");
pdc_begin_dict(p->out); /* A dict */
pdc_puts(p->out, "/Type/Action/S/Launch\n");
if (ann->parameters || ann->operation || ann->defaultdir) {
pdc_puts(p->out, "/Win");
pdc_begin_dict(p->out); /* Win dict */
pdc_printf(p->out, "/F");
pdc_put_pdfstring(p->out, ann->filename,
(int)strlen(ann->filename));
pdc_puts(p->out, "\n");
if (ann->parameters) {
pdc_printf(p->out, "/P");
pdc_put_pdfstring(p->out, ann->parameters,
(int)strlen(ann->parameters));
pdc_puts(p->out, "\n");
pdc_free(p->pdc, ann->parameters);
ann->parameters = NULL;
}
if (ann->operation) {
pdc_printf(p->out, "/O");
pdc_put_pdfstring(p->out, ann->operation,
(int)strlen(ann->operation));
pdc_puts(p->out, "\n");
pdc_free(p->pdc, ann->operation);
ann->operation = NULL;
}
if (ann->defaultdir) {
pdc_printf(p->out, "/D");
pdc_put_pdfstring(p->out, ann->defaultdir,
(int)strlen(ann->defaultdir));
pdc_puts(p->out, "\n");
pdc_free(p->pdc, ann->defaultdir);
ann->defaultdir = NULL;
}
pdc_end_dict(p->out); /* Win dict */
} else {
pdc_puts(p->out, "/F");
pdc_begin_dict(p->out); /* F dict */
pdc_puts(p->out, "/Type/Filespec\n");
pdc_printf(p->out, "/F");
pdc_put_pdfstring(p->out, ann->filename,
(int)strlen(ann->filename));
pdc_puts(p->out, "\n");
pdc_end_dict(p->out); /* F dict */
}
pdc_end_dict(p->out); /* A dict */
break;
case ann_weblink:
pdc_puts(p->out, "/Subtype/Link\n");
pdc_printf(p->out, "/Rect[%f %f %f %f]\n",
ann->rect.llx, ann->rect.lly, ann->rect.urx, ann->rect.ury);
pdf_write_border_style(p, ann);
pdc_puts(p->out, "/A<</S/URI/URI");
pdc_put_pdfstring(p->out, ann->filename,
(int)strlen(ann->filename));
pdc_puts(p->out, ">>\n");
break;
case ann_attach:
pdc_puts(p->out, "/Subtype/FileAttachment\n");
pdc_printf(p->out, "/Rect[%f %f %f %f]\n",
ann->rect.llx, ann->rect.lly, ann->rect.urx, ann->rect.ury);
pdf_write_border_style(p, ann);
if (ann->icon != icon_file_pushpin) /* pushpin is default */
pdc_printf(p->out, "/Name/%s\n",
pdf_icon_names[ann->icon]);
if (ann->title) {
pdc_puts(p->out, "/T");
pdc_put_pdfunistring(p->out, ann->title);
pdc_puts(p->out, "\n");
}
if (ann->contents) {
pdc_puts(p->out, "/Contents");
pdc_put_pdfunistring(p->out, ann->contents);
pdc_puts(p->out, "\n");
}
/* the icon is too small without these flags (=28) */
pdc_printf(p->out, "/F %d\n",
pdf_ann_flag_print |
pdf_ann_flag_nozoom |
pdf_ann_flag_norotate);
pdc_puts(p->out, "/FS");
pdc_begin_dict(p->out); /* FS dict */
pdc_puts(p->out, "/Type/Filespec\n");
pdc_puts(p->out, "/F");
pdc_put_pdfstring(p->out, ann->filename,
(int)strlen(ann->filename));
pdc_puts(p->out, "\n");
/* alloc id for the actual embedded file stream */
ann->obj_id = pdc_alloc_id(p->out);
pdc_printf(p->out, "/EF<</F %ld 0 R>>\n", ann->obj_id);
pdc_end_dict(p->out); /* FS dict */
break;
default:
pdc_error(p->pdc, PDF_E_INT_BADANNOT,
pdc_errprintf(p->pdc, "%d", ann->type), 0, 0, 0);
}
pdc_end_dict(p->out); /* Annotation dict */
pdc_end_obj(p->out); /* Annotation object */
}
/* Write the actual embedded files with preallocated ids */
for (ann = p->annots; ann != NULL; ann = ann->next) {
pdc_id length_id;
PDF_data_source src;
if (ann->type != ann_attach)
continue;
pdc_begin_obj(p->out, ann->obj_id); /* EmbeddedFile */
pdc_puts(p->out, "<</Type/EmbeddedFile\n");
if (ann->mimetype) {
pdc_puts(p->out, "/Subtype");
pdc_put_pdfname(p->out, ann->mimetype, strlen(ann->mimetype));
pdc_puts(p->out, "\n");
}
if (pdc_get_compresslevel(p->out))
pdc_puts(p->out, "/Filter/FlateDecode\n");
length_id = pdc_alloc_id(p->out);
pdc_printf(p->out, "/Length %ld 0 R\n", length_id);
pdc_end_dict(p->out); /* F dict */
/* write the file in the PDF */
src.private_data = (void *) ann->filename;
src.init = pdf_data_source_file_init;
src.fill = pdf_data_source_file_fill;
src.terminate = pdf_data_source_file_terminate;
src.length = (long) 0;
src.offset = (long) 0;
pdf_copy_stream(p, &src, pdc_true); /* embedded file stream */
pdc_end_obj(p->out); /* EmbeddedFile object */
pdc_put_pdfstreamlength(p->out, length_id);
if (p->flush & pdf_flush_content)
pdc_flush_stream(p->out);
}
}
void
pdf_init_page_annots(PDF *p)
{
p->annots = NULL;
}
void
pdf_cleanup_page_annots(PDF *p)
{
pdf_annot *ann, *old;
for (ann = p->annots; ann != (pdf_annot *) NULL; /* */ ) {
switch (ann->type) {
case ann_text:
if (ann->contents)
pdc_free(p->pdc, ann->contents);
if (ann->title)
pdc_free(p->pdc, ann->title);
break;
case ann_locallink:
pdf_cleanup_destination(p, &ann->dest);
break;
case ann_launchlink:
pdc_free(p->pdc, ann->filename);
break;
case ann_pdflink:
pdf_cleanup_destination(p, &ann->dest);
pdc_free(p->pdc, ann->filename);
break;
case ann_weblink:
pdc_free(p->pdc, ann->filename);
break;
case ann_attach:
pdf_unlock_pvf(p, ann->filename);
pdc_free(p->pdc, ann->filename);
if (ann->contents)
pdc_free(p->pdc, ann->contents);
if (ann->title)
pdc_free(p->pdc, ann->title);
if (ann->mimetype)
pdc_free(p->pdc, ann->mimetype);
break;
default:
pdc_error(p->pdc, PDF_E_INT_BADANNOT,
pdc_errprintf(p->pdc, "%d", ann->type), 0, 0, 0);
}
old = ann;
ann = old->next;
pdc_free(p->pdc, old);
}
p->annots = NULL;
}
/* Insert new annotation at the end of the annots chain */
static void
pdf_add_annot(PDF *p, pdf_annot *ann)
{
pdf_annot *last;
/* fetch current border state from p */
ann->border_style = p->border_style;
ann->border_width = p->border_width;
ann->border_red = p->border_red;
ann->border_green = p->border_green;
ann->border_blue = p->border_blue;
ann->border_dash1 = p->border_dash1;
ann->border_dash2 = p->border_dash2;
ann->next = NULL;
if (p->annots == NULL)
p->annots = ann;
else {
for (last = p->annots; last->next != NULL; /* */ )
last = last->next;
last->next = ann;
}
}
static void
pdf_init_rectangle(PDF *p, pdf_annot *ann,
float llx, float lly, float urx, float ury)
{
pdc_rect_init(&ann->rect, llx, lly, urx, ury);
if (p->usercoordinates == pdc_true)
pdc_rect_transform(&p->gstate[p->sl].ctm, &ann->rect, &ann->rect);
}
/* Attach an arbitrary file to the PDF. Note that the actual
* embedding takes place in PDF_end_page().
* description, author, and mimetype may be NULL.
*/
static const pdc_keyconn pdf_icon_attach_keylist[] =
{
{"graph", icon_file_graph},
{"paperclip", icon_file_paperclip},
{"pushpin", icon_file_pushpin},
{"tag", icon_file_tag},
{NULL, 0}
};
static void
pdf__attach_file(
PDF *p,
float llx,
float lly,
float urx,
float ury,
const char *filename,
const char *description,
int len_descr,
const char *author,
int len_auth,
const char *mimetype,
const char *icon)
{
static const char fn[] = "pdf__attach_file";
pdf_annot *ann;
pdc_file *attfile;
if (filename == NULL || *filename == '\0')
pdc_error(p->pdc, PDC_E_ILLARG_EMPTY, "filename", 0, 0, 0);
if ((attfile = pdf_fopen(p, filename, "attachment ", 0)) == NULL)
pdc_error(p->pdc, -1, 0, 0, 0, 0);
pdf_lock_pvf(p, filename);
pdc_fclose(attfile);
ann = (pdf_annot *) pdc_malloc(p->pdc, sizeof(pdf_annot), fn);
pdf_init_annot(p, ann);
ann->type = ann_attach;
pdf_init_rectangle(p, ann, llx, lly, urx, ury);
if (icon == NULL || !*icon)
icon = "pushpin";
ann->icon = (pdf_icon) pdc_get_keycode(icon, pdf_icon_attach_keylist);
if (ann->icon == PDC_KEY_NOTFOUND)
pdc_error(p->pdc, PDC_E_ILLARG_STRING, "icon", icon, 0, 0);
ann->filename = (char *) pdc_strdup(p->pdc, filename);
ann->contents = pdf_convert_hypertext(p, description, len_descr);
ann->title = pdf_convert_hypertext(p, author, len_auth);
if (mimetype != NULL) {
ann->mimetype = (char *) pdc_strdup(p->pdc, mimetype);
}
pdf_add_annot(p, ann);
}
PDFLIB_API void PDFLIB_CALL
PDF_attach_file(
PDF *p,
float llx,
float lly,
float urx,
float ury,
const char *filename,
const char *description,
const char *author,
const char *mimetype,
const char *icon)
{
static const char fn[] = "PDF_attach_file";
if (pdf_enter_api(p, fn, pdf_state_page,
"(p[%p], %g, %g, %g, %g, \"%s\", \"%s\", \"%s\", \"%s\", \"%s\")\n",
(void *) p, llx, lly, urx, ury, filename,
pdc_strprint(p->pdc, description, 0),
pdc_strprint(p->pdc, author, 0), mimetype, icon))
{
int len_descr = description ? (int) pdc_strlen(description) : 0;
int len_auth = author ? (int) pdc_strlen(author) : 0;
pdf__attach_file(p, llx, lly, urx, ury, filename,
description, len_descr, author, len_auth, mimetype, icon) ;
}
}
PDFLIB_API void PDFLIB_CALL
PDF_attach_file2(
PDF *p,
float llx,
float lly,
float urx,
float ury,
const char *filename,
int reserved,
const char *description,
int len_descr,
const char *author,
int len_auth,
const char *mimetype,
const char *icon)
{
static const char fn[] = "PDF_attach_file2";
if (pdf_enter_api(p, fn, pdf_state_page,
"(p[%p], %g, %g, %g, %g, \"%s\", %d, \"%s\", %d, "
"\"%s\", %d, \"%s\", \"%s\")\n",
(void *) p, llx, lly, urx, ury, filename, reserved,
pdc_strprint(p->pdc, description, len_descr), len_descr,
pdc_strprint(p->pdc, author, len_auth), len_auth, mimetype, icon))
{
pdf__attach_file(p, llx, lly, urx, ury, filename,
description, len_descr, author, len_auth, mimetype, icon) ;
}
}
static const pdc_keyconn pdf_icon_note_keylist[] =
{
{"comment", icon_text_comment},
{"insert", icon_text_insert},
{"note", icon_text_note},
{"paragraph", icon_text_paragraph},
{"newparagraph", icon_text_newparagraph},
{"key", icon_text_key},
{"help", icon_text_help},
{NULL, 0}
};
static void
pdf__add_note(
PDF *p,
float llx,
float lly,
float urx,
float ury,
const char *contents,
int len_cont,
const char *title,
int len_title,
const char *icon,
int open)
{
static const char fn[] = "pdf__add_note";
pdf_annot *ann;
ann = (pdf_annot *) pdc_malloc(p->pdc, sizeof(pdf_annot), fn);
pdf_init_annot(p, ann);
ann->type = ann_text;
ann->open = open;
pdf_init_rectangle(p, ann, llx, lly, urx, ury);
if (icon == NULL || !*icon)
icon = "note";
ann->icon = (pdf_icon) pdc_get_keycode(icon, pdf_icon_note_keylist);
if (ann->icon == PDC_KEY_NOTFOUND)
pdc_error(p->pdc, PDC_E_ILLARG_STRING, "icon", icon, 0, 0);
/* title may be NULL */
ann->title = pdf_convert_hypertext(p, title, len_title);
/* It is legal to create an empty text annnotation */
ann->contents = pdf_convert_hypertext(p, contents, len_cont);
pdf_add_annot(p, ann);
}
PDFLIB_API void PDFLIB_CALL
PDF_add_note(
PDF *p,
float llx,
float lly,
float urx,
float ury,
const char *contents,
const char *title,
const char *icon,
int open)
{
static const char fn[] = "PDF_add_note";
if (pdf_enter_api(p, fn, pdf_state_page,
"(p[%p], %g, %g, %g, %g, \"%s\", \"%s\", \"%s\", %d)\n",
(void *) p, llx, lly, urx, ury,
pdc_strprint(p->pdc, contents, 0),
pdc_strprint(p->pdc, title, 0), icon, open))
{
int len_cont = contents ? (int) pdc_strlen(contents) : 0;
int len_title = title ? (int) pdc_strlen(title) : 0;
pdf__add_note(p, llx, lly, urx, ury, contents, len_cont,
title, len_title, icon, open);
}
}
PDFLIB_API void PDFLIB_CALL
PDF_add_note2(
PDF *p,
float llx,
float lly,
float urx,
float ury,
const char *contents,
int len_cont,
const char *title,
int len_title,
const char *icon,
int open)
{
static const char fn[] = "PDF_add_note2";
if (pdf_enter_api(p, fn, pdf_state_page,
"(p[%p], %g, %g, %g, %g, \"%s\", %d, \"%s\", %d, \"%s\", %d)\n",
(void *) p, llx, lly, urx, ury,
pdc_strprint(p->pdc, contents, len_cont), len_cont,
pdc_strprint(p->pdc, title, len_title), len_title,
icon, open))
{
pdf__add_note(p, llx, lly, urx, ury, contents, len_cont,
title, len_title, icon, open);
}
}
/* Add a link to another PDF file */
PDFLIB_API void PDFLIB_CALL
PDF_add_pdflink(
PDF *p,
float llx,
float lly,
float urx,
float ury,
const char *filename,
int page,
const char *optlist)
{
static const char fn[] = "PDF_add_pdflink";
pdf_annot *ann;
if (!pdf_enter_api(p, fn, pdf_state_page,
"(p[%p], %g, %g, %g, %g, \"%s\", %d, \"%s\")\n",
(void *) p, llx, lly, urx, ury, filename, page, optlist))
{
return;
}
if (filename == NULL)
pdc_error(p->pdc, PDC_E_ILLARG_EMPTY, "filename", 0, 0, 0);
ann = (pdf_annot *) pdc_malloc(p->pdc, sizeof(pdf_annot), fn);
pdf_init_annot(p, ann);
ann->filename = pdc_strdup(p->pdc, filename);
ann->type = ann_pdflink;
pdf_parse_destination_optlist(p, optlist, &ann->dest, page, pdf_remotelink);
pdf_init_rectangle(p, ann, llx, lly, urx, ury);
pdf_add_annot(p, ann);
}
/* Add a link to another file of an arbitrary type */
PDFLIB_API void PDFLIB_CALL
PDF_add_launchlink(
PDF *p,
float llx,
float lly,
float urx,
float ury,
const char *filename)
{
static const char fn[] = "PDF_add_launchlink";
pdf_annot *ann;
if (!pdf_enter_api(p, fn, pdf_state_page,
"(p[%p], %g, %g, %g, %g, \"%s\")\n",
(void *)p, llx, lly, urx, ury, filename))
{
return;
}
if (filename == NULL)
pdc_error(p->pdc, PDC_E_ILLARG_EMPTY, "filename", 0, 0, 0);
ann = (pdf_annot *) pdc_malloc(p->pdc, sizeof(pdf_annot), fn);
pdf_init_annot(p, ann);
ann->filename = pdc_strdup(p->pdc, filename);
ann->type = ann_launchlink;
if (p->launchlink_parameters) {
ann->parameters = p->launchlink_parameters;
p->launchlink_parameters = NULL;
}
if (p->launchlink_operation) {
ann->operation = p->launchlink_operation;
p->launchlink_operation = NULL;
}
if (p->launchlink_defaultdir) {
ann->defaultdir = p->launchlink_defaultdir;
p->launchlink_defaultdir = NULL;
}
pdf_init_rectangle(p, ann, llx, lly, urx, ury);
pdf_add_annot(p, ann);
}
/* Add a link to a destination in the current PDF file */
PDFLIB_API void PDFLIB_CALL
PDF_add_locallink(
PDF *p,
float llx,
float lly,
float urx,
float ury,
int page,
const char *optlist)
{
static const char fn[] = "PDF_add_locallink";
pdf_annot *ann;
if (!pdf_enter_api(p, fn, pdf_state_page,
"(p[%p], %g, %g, %g, %g, %d, \"%s\")\n",
(void *) p, llx, lly, urx, ury, page, optlist))
{
return;
}
ann = (pdf_annot *) pdc_malloc(p->pdc, sizeof(pdf_annot), fn);
pdf_init_annot(p, ann);
ann->type = ann_locallink;
pdf_parse_destination_optlist(p, optlist, &ann->dest, page, pdf_locallink);
pdf_init_rectangle(p, ann, llx, lly, urx, ury);
pdf_add_annot(p, ann);
}
/* Add a link to an arbitrary Internet resource (URL) */
PDFLIB_API void PDFLIB_CALL
PDF_add_weblink(
PDF *p,
float llx,
float lly,
float urx,
float ury,
const char *url)
{
static const char fn[] = "PDF_add_weblink";
pdf_annot *ann;
if (!pdf_enter_api(p, fn, pdf_state_page,
"(p[%p], %g, %g, %g, %g, \"%s\")\n",
(void *) p, llx, lly, urx, ury, url))
{
return;
}
if (url == NULL || *url == '\0')
pdc_error(p->pdc, PDC_E_ILLARG_EMPTY, "url", 0, 0, 0);
ann = (pdf_annot *) pdc_malloc(p->pdc, sizeof(pdf_annot), fn);
pdf_init_annot(p, ann);
ann->filename = pdc_strdup(p->pdc, url);
ann->type = ann_weblink;
pdf_init_rectangle(p, ann, llx, lly, urx, ury);
pdf_add_annot(p, ann);
}
PDFLIB_API void PDFLIB_CALL
PDF_set_border_style(PDF *p, const char *style, float width)
{
static const char fn[] = "PDF_set_border_style";
if (!pdf_enter_api(p, fn,
(pdf_state) (pdf_state_document | pdf_state_page),
"(p[%p], \"%s\", %g)\n", (void *) p, style, width))
{
return;
}
if (style == NULL)
p->border_style = border_solid;
else if (!strcmp(style, "solid"))
p->border_style = border_solid;
else if (!strcmp(style, "dashed"))
p->border_style = border_dashed;
else
pdc_error(p->pdc, PDC_E_ILLARG_STRING, "style", style, 0, 0);
if (width < 0.0)
pdc_error(p->pdc, PDC_E_ILLARG_FLOAT,
"width", pdc_errprintf(p->pdc, "%f", width), 0, 0);
p->border_width = width;
}
PDFLIB_API void PDFLIB_CALL
PDF_set_border_color(PDF *p, float red, float green, float blue)
{
static const char fn[] = "PDF_set_border_color";
if (!pdf_enter_api(p, fn,
(pdf_state) (pdf_state_document | pdf_state_page),
"(p[%p], %g, %g, %g)\n", (void *) p, red, green, blue))
{
return;
}
if (red < 0.0 || red > 1.0)
pdc_error(p->pdc, PDC_E_ILLARG_FLOAT,
"red", pdc_errprintf(p->pdc, "%f", red), 0, 0);
if (green < 0.0 || green > 1.0)
pdc_error(p->pdc, PDC_E_ILLARG_FLOAT,
"green", pdc_errprintf(p->pdc, "%f", green), 0, 0);
if (blue < 0.0 || blue > 1.0)
pdc_error(p->pdc, PDC_E_ILLARG_FLOAT,
"blue", pdc_errprintf(p->pdc, "%f", blue), 0, 0);
p->border_red = red;
p->border_green = green;
p->border_blue = blue;
}
PDFLIB_API void PDFLIB_CALL
PDF_set_border_dash(PDF *p, float b, float w)
{
static const char fn[] = "PDF_set_border_dash";
if (!pdf_enter_api(p, fn,
(pdf_state) (pdf_state_document | pdf_state_page),
"(p[%p], %g, %g)\n", (void *) p, b, w))
{
return;
}
if (b < 0.0)
pdc_error(p->pdc, PDC_E_ILLARG_FLOAT,
"b", pdc_errprintf(p->pdc, "%f", b), 0, 0);
if (w < 0.0)
pdc_error(p->pdc, PDC_E_ILLARG_FLOAT,
"w", pdc_errprintf(p->pdc, "%f", w), 0, 0);
p->border_dash1 = b;
p->border_dash2 = w;
}
| 26.210476
| 80
| 0.592965
|
[
"object",
"solid"
] |
958d1435c13dc39bb1700b51a6a2880e55ca7daf
| 1,388
|
h
|
C
|
code/toolkit/toolkitutil/fbx/attic/fbxskinparser.h
|
gscept/nebula-trifid
|
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
|
[
"BSD-2-Clause"
] | 67
|
2015-03-30T19:56:16.000Z
|
2022-03-11T13:52:17.000Z
|
code/toolkit/toolkitutil/fbx/attic/fbxskinparser.h
|
gscept/nebula-trifid
|
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
|
[
"BSD-2-Clause"
] | 5
|
2015-04-15T17:17:33.000Z
|
2016-02-11T00:40:17.000Z
|
code/toolkit/toolkitutil/fbx/attic/fbxskinparser.h
|
gscept/nebula-trifid
|
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
|
[
"BSD-2-Clause"
] | 34
|
2015-03-30T15:08:00.000Z
|
2021-09-23T05:55:10.000Z
|
#pragma once
//------------------------------------------------------------------------------
/**
@class ToolkitUtil::FBXSkinParser
Searches an FBX scene and extracts skins
(C) 2012 gscept
*/
#include "fbxparserbase.h"
#include "fbxtypes.h"
//------------------------------------------------------------------------------
namespace ToolkitUtil
{
class FBXSkinParser : public FBXParserBase
{
__DeclareClass(FBXSkinParser);
public:
/// constructor
FBXSkinParser();
/// destructor
virtual ~FBXSkinParser();
/// parses a scene in search of skins
void Parse(KFbxScene* scene, ToolkitUtil::AnimBuilder* animBuilder = 0);
/// sets a list of skeletons to be used for skin->skeleton connections
void SetSkeletonList(SkeletonList skeletons);
/// sets the mesh which should get skinned
void SetMesh(ShapeNode* mesh);
private:
ShapeNode* mesh;
SkeletonList skeletons;
};
//------------------------------------------------------------------------------
/**
*/
inline void
FBXSkinParser::SetSkeletonList( SkeletonList skeletons )
{
this->skeletons = skeletons;
}
//------------------------------------------------------------------------------
/**
*/
inline void
FBXSkinParser::SetMesh( ShapeNode* mesh )
{
n_assert(mesh);
this->mesh = mesh;
}
} // namespace ToolkitUtil
//------------------------------------------------------------------------------
| 22.754098
| 80
| 0.510086
|
[
"mesh"
] |
9594ff1c2fff056c5e0a9cd29d5fc934ecab62d5
| 14,798
|
c
|
C
|
lib/driverkit/hwmodel.c
|
lambdaxymox/barrelfish
|
06a9f54721a8d96874a8939d8973178a562c342f
|
[
"MIT"
] | 111
|
2015-02-03T02:57:27.000Z
|
2022-03-01T23:57:09.000Z
|
lib/driverkit/hwmodel.c
|
lambdaxymox/barrelfish
|
06a9f54721a8d96874a8939d8973178a562c342f
|
[
"MIT"
] | 12
|
2016-03-22T14:44:32.000Z
|
2020-03-18T13:30:29.000Z
|
lib/driverkit/hwmodel.c
|
lambdaxymox/barrelfish
|
06a9f54721a8d96874a8939d8973178a562c342f
|
[
"MIT"
] | 55
|
2015-02-03T05:28:12.000Z
|
2022-03-31T05:00:03.000Z
|
/**
* \file
* \brief Driverkit module implementation.
*
* Contians helper functions to iterate over driver modules in a domain
* and create driver instances from driver modules.
*/
/*
* Copyright (c) 2016, ETH Zurich.
* All rights reserved.
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group.
*/
#include <stdlib.h>
#include <barrelfish/barrelfish.h>
#include <driverkit/driverkit.h>
#include <driverkit/iommu.h>
#include <driverkit/hwmodel.h>
#include <collections/hash_table.h>
#include <skb/skb.h>
#include <if/mem_defs.h>
#include "debug.h"
#include "../libc/include/namespace.h"
__attribute__((unused))
static void format_nodelist(int32_t *nodes, char *out){
*out = '\0';
sprintf(out + strlen(out), "[");
int first = 1;
while(*nodes != 0){
if(!first) sprintf(out + strlen(out), ",");
sprintf(out + strlen(out), "%" PRIi32, *nodes);
nodes++;
first = 0;
}
sprintf(out + strlen(out), "]");
}
void driverkit_parse_namelist(char *in, struct hwmodel_name *names, int *conversions){
assert(in);
*conversions = 0;
struct list_parser_status status;
skb_read_list_init_offset(&status, in, 0);
while(skb_read_list(&status, "name(%"SCNu64", %"SCNi32")",
&names->address, &names->nodeid)) {
debug_printf("parse_namelist: %lx\n", names->address);
names++;
*conversions += 1;
}
}
#define ALLOC_WRAP_Q "state_get(S)," \
"alloc_wrap(S, %zu, %d, %"PRIi32",%s, NewS)," \
"state_set(NewS)."
errval_t
driverkit_hwmodel_allocate(size_t bytes, int32_t dstnode, int32_t * nodes,
uint8_t alloc_bits, genpaddr_t *retaddr) {
errval_t err;
char nodes_str[128];
format_nodelist(nodes, nodes_str);
HWMODEL_QUERY_DEBUG(ALLOC_WRAP_Q, bytes, alloc_bits, dstnode, nodes_str);
err = skb_execute_query(ALLOC_WRAP_Q, bytes, alloc_bits, dstnode, nodes_str);
if (err_is_fail(err)) {
DEBUG_SKB_ERR(err, "failed to query\n");
return err;
}
struct hwmodel_name names[1];
int num_conversions = 0;
driverkit_parse_namelist(skb_get_output(), names, &num_conversions);
assert(num_conversions == 1);
if (retaddr) {
*retaddr = names[0].address;
}
return SYS_ERR_OK;
}
errval_t driverkit_hwmodel_ram_alloc(struct capref *dst,
size_t bytes, int32_t dstnode,
int32_t *nodes)
{
if (bytes < (LARGE_PAGE_SIZE)) {
bytes = LARGE_PAGE_SIZE;
}
int bits = log2ceil(bytes);
bytes = 1 << bits;
assert(bits >= 21);
// The PT configuration in the SKB is currently using 2M pages.
#ifdef DISABLE_MODEL
if (dstnode != driverkit_hwmodel_lookup_dram_node_id()) {
return LIB_ERR_RAM_ALLOC_MS_CONSTRAINTS;
}
return ram_alloc(dst, bits);
#else
errval_t err;
errval_t msgerr;
genpaddr_t addr;
err = driverkit_hwmodel_allocate(bytes, dstnode, nodes, bits, &addr);
if(err_is_fail(err)) {
return err;
}
// Alloc cap slot
err = slot_alloc(dst);
if (err_is_fail(err)) {
return err_push(err, LIB_ERR_SLOT_ALLOC);
}
struct mem_binding * b = get_mem_client();
debug_printf("Determined addr=0x%"PRIx64" as address for (nodeid=%d, size=%zu) request\n",
addr, dstnode, bytes);
err = b->rpc_tx_vtbl.allocate(b, bits, addr, addr + bytes,
&msgerr, dst);
if(err_is_fail(err)){
DEBUG_ERR(err, "allocate RPC");
return err;
}
if(err_is_fail(msgerr)){
DEBUG_ERR(msgerr, "allocate");
return msgerr;
}
return SYS_ERR_OK;
#endif
}
errval_t driverkit_hwmodel_frame_alloc(struct capref *dst,
size_t bytes, int32_t dstnode,
int32_t *nodes)
{
#ifdef DISABLE_MODEL
if (dstnode != driverkit_hwmodel_lookup_dram_node_id()) {
return LIB_ERR_RAM_ALLOC_MS_CONSTRAINTS;
}
return frame_alloc(dst, bytes, NULL);
#else
errval_t err;
struct capref ram_cap;
if(bytes < LARGE_PAGE_SIZE) bytes = LARGE_PAGE_SIZE;
// Allocate RAM cap
err = driverkit_hwmodel_ram_alloc(&ram_cap, bytes, dstnode, nodes);
if(err_is_fail(err)){
return err;
}
// Alloc cap slot
err = slot_alloc(dst);
if (err_is_fail(err)) {
return err_push(err, LIB_ERR_SLOT_ALLOC);
}
// Get bits
assert(bytes > 0);
uint8_t bits = log2ceil(bytes);
assert((1UL << bits) >= bytes);
// This is doing what "create_ram_descendant" in
// lib/barrelfish/capabilities.c is doing.
err = cap_retype(*dst, ram_cap, 0, ObjType_Frame, (1UL << bits), 1);
if (err_is_fail(err)) {
return err_push(err, LIB_ERR_CAP_RETYPE);
}
err = cap_destroy(ram_cap);
if (err_is_fail(err)) {
return err_push(err, LIB_ERR_CAP_DESTROY);
}
return SYS_ERR_OK;
#endif
}
/**
* fills in dmem->vbase + maps frame
*/
errval_t driverkit_hwmodel_vspace_map(int32_t nodeid, struct capref frame,
vregion_flags_t flags, struct dmem *dmem)
{
#ifdef DISABLE_MODEL
return SYS_ERR_OK;
#else
errval_t err;
struct frame_identity id;
err = frame_identify(frame, &id);
if (err_is_fail(err)) {
return err;
}
char conf_buf[512];
dmem->mem = frame;
dmem->size = id.bytes;
dmem->devaddr = id.base;
// Alloc space in my vspace
assert(nodeid == driverkit_hwmodel_get_my_node_id());
err = driverkit_hwmodel_get_map_conf(frame, nodeid, conf_buf, sizeof(conf_buf),
&dmem->vbase);
if(err_is_fail(err)) {
DEBUG_ERR(err, "vspace_map local");
return err;
}
uint64_t inaddr, outaddr;
int32_t conf_nodeid;
struct list_parser_status status;
skb_read_list_init_offset(&status, conf_buf, 0);
while(skb_read_list(&status, "c(%"SCNi32", %"SCNu64", %"SCNu64")",
&conf_nodeid, &inaddr, &outaddr)) {
debug_printf("%s:%u %i, %i, inaddr=%lx, vbase=%lx\n", __FUNCTION__, __LINE__,
nodeid, conf_nodeid, inaddr, dmem->vbase);
err = driverkit_hwmodel_vspace_map_fixed(nodeid, dmem->vbase, frame,
flags, dmem);
if (err_is_fail(err)) {
DEBUG_ERR(err, "TODO CLEANUP!");
return err;
}
}
return SYS_ERR_OK;
#endif
}
errval_t driverkit_hwmodel_vspace_map_fixed(int32_t nodeid,
genvaddr_t addr,
struct capref frame,
vregion_flags_t flags,
struct dmem *dmem)
{
errval_t err;
if(nodeid != driverkit_hwmodel_get_my_node_id()){
return LIB_ERR_NOT_IMPLEMENTED;
}
struct frame_identity id;
err = frame_identify(frame, &id);
if (err_is_fail(err)) {
return err;
}
dmem->vbase = addr;
return vspace_map_one_frame_fixed_attr(addr, id.bytes, frame, flags, NULL, NULL);
}
#define MAP_WRAP_Q "state_get(S)," \
"map_wrap(S, %zu, 21, %"PRIi32", %"PRIu64", %s, NewS)," \
"state_set(NewS)."
errval_t driverkit_hwmodel_vspace_alloc(struct capref frame,
int32_t nodeid, genvaddr_t *addr)
{
errval_t err;
struct frame_identity id;
err = frame_identify(frame, &id);
if (err_is_fail(err)) {
return err;
}
int32_t src_nodeid[2];
char src_nodeid_str[128];
src_nodeid[0] = nodeid;
src_nodeid[1] = 0;
format_nodelist(src_nodeid, src_nodeid_str);
//int32_t mem_nodeid = id.pasid;
int32_t mem_nodeid = driverkit_hwmodel_lookup_dram_node_id();
uint64_t mem_addr = id.base;
HWMODEL_QUERY_DEBUG(MAP_WRAP_Q,
id.bytes, mem_nodeid, mem_addr, src_nodeid_str);
err = skb_execute_query(MAP_WRAP_Q,
id.bytes, mem_nodeid, mem_addr, src_nodeid_str);
if(err_is_fail(err)){
DEBUG_SKB_ERR(err, "map_wrap");
return err;
}
struct hwmodel_name names[2];
int num_conversions = 0;
driverkit_parse_namelist(skb_get_output(), names, &num_conversions);
assert(num_conversions == 2);
//ignore, names[0] it is the resolved name as stored in frame
*addr = names[1].address;
debug_printf("Determined addr=0x%"PRIx64" as vbase for (nodeid=%d, size=%zu) request\n",
*addr, nodeid, id.bytes);
return SYS_ERR_OK;
}
/*
* Returns this process nodeid. It lazily adds the process' model node
* and returns it's identifier.
*/
int32_t driverkit_hwmodel_get_my_node_id(void)
{
errval_t err;
err = skb_client_connect();
if (err_is_fail(err)) {
return -1;
}
/*
* XXX: this assumes the domain only runs on a single core!
*/
static int32_t nodeid = -1;
if(nodeid == -1){
HWMODEL_QUERY_DEBUG(
"state_get(S), "
"add_process(S, E, NewS), writeln(E), "
"state_set(NewS)");
err = skb_execute_query(
"state_get(S), "
"add_process(S, E, NewS), writeln(E), "
"state_set(NewS)");
if (err_is_fail(err)) {
DEBUG_SKB_ERR(err, "add_process");
return -1;
}
err = skb_read_output("%d", &nodeid);
assert(err_is_ok(err));
DRIVERKIT_DEBUG("Instantiated new process model node, nodeid=%"PRIi32"\n",
nodeid);
}
return nodeid;
}
int32_t driverkit_hwmodel_lookup_dram_node_id(void)
{
#ifdef DISABLE_MODEL
return 1;
#else
return driverkit_hwmodel_lookup_node_id("[\"DRAM\"]");
#endif
}
int32_t driverkit_hwmodel_lookup_pcibus_node_id(void)
{
return driverkit_hwmodel_lookup_node_id("[\"PCIBUS\"]");
}
int32_t driverkit_hwmodel_lookup_node_id(const char *path)
{
debug_printf("%s:%u with path='%s'\n", __FUNCTION__, __LINE__, path);
errval_t err;
HWMODEL_QUERY_DEBUG(
"node_enum(%s, E), writeln(E)",
path);
err = skb_execute_query(
"node_enum(%s, E), writeln(E)",
path);
if (err_is_fail(err)) {
DEBUG_SKB_ERR(err, "query node_enum");
}
int32_t nodeid;
err = skb_read_output("%d", &nodeid);
assert(err_is_ok(err));
return nodeid;
}
#define REVERSE_RESOLVE_Q "state_get(S)," \
"reverse_resolve_wrap(S, %"PRIi32", %"PRIu64", %zu, %"PRIi32")."
#define FORMAT "[\"KNC_SOCKET\", \"PCI0\", %d]"
// Without reconfiguration, under what ret_addr can you reach dst
// from nodeid?
errval_t driverkit_hwmodel_reverse_resolve(struct capref dst, int32_t nodeid,
genpaddr_t *ret_addr)
{
errval_t err;
struct frame_identity id;
err = frame_identify(dst, &id);
if (err_is_fail(err)) {
return err;
}
assert(ret_addr);
#ifdef DISABLE_MODEL
*ret_addr = id.base;
return SYS_ERR_OK;
#else
int dst_enum = id.pasid;
dst_enum = driverkit_hwmodel_lookup_pcibus_node_id();
assert(nodeid < 100);
char buf[sizeof(FORMAT)];
snprintf(buf, sizeof(buf), FORMAT, nodeid);
nodeid = driverkit_hwmodel_lookup_node_id(buf);
HWMODEL_QUERY_DEBUG(REVERSE_RESOLVE_Q, dst_enum, id.base, id.bytes, nodeid);
err = skb_execute_query(REVERSE_RESOLVE_Q, dst_enum, id.base, id.bytes, nodeid);
DEBUG_SKB_ERR(err, "reverse_resolve");
if(err_is_fail(err)){
DEBUG_SKB_ERR(err, "reverse_resolve");
return err;
}
struct hwmodel_name names[1];
int num_conversions = 0;
driverkit_parse_namelist(skb_get_output(), names, &num_conversions);
assert(num_conversions == 1);
*ret_addr = names[0].address;
debug_printf("Determined (0x%"PRIx64", %d) is alias of (0x%"PRIx64", %d)\n",
names[0].address, nodeid, id.base, dst_enum);
return SYS_ERR_OK;
#endif
}
#define MAP_WRAP_Q "state_get(S)," \
"map_wrap(S, %zu, 21, %"PRIi32", %"PRIu64", %s, NewS)," \
"state_set(NewS)."
errval_t driverkit_hwmodel_get_map_conf_addr(int32_t mem_nodeid, genpaddr_t addr,
gensize_t size, int32_t nodeid,
char *ret_conf, size_t ret_conf_size,
lvaddr_t *ret_addr)
{
errval_t err;
#ifdef DISABLE_MODEL
return SYS_ERR_OK;
#endif
debug_printf("%s:%d: alias_conf request addr=0x%"PRIx64", size=%"PRIuGENSIZE"\n",
__FUNCTION__, __LINE__, addr, size);
int32_t src_nodeid[2];
char src_nodeid_str[128];
src_nodeid[0] = nodeid;
src_nodeid[1] = 0;
format_nodelist(src_nodeid, src_nodeid_str);
for(int tries=0; tries<3; tries++){
HWMODEL_QUERY_DEBUG(MAP_WRAP_Q, size, mem_nodeid, addr, src_nodeid_str);
err = skb_execute_query(MAP_WRAP_Q, size, mem_nodeid, addr, src_nodeid_str);
if(err_is_ok(err)) break;
}
if (err_is_fail(err)) {
DEBUG_SKB_ERR(err, "alias_conf \n");
return err;
}
// Determine and copy conf line (second output line)
char * confline = strstr(skb_get_output(), "\n");
assert(confline);
if(ret_conf){
strncpy(ret_conf, confline + 1, ret_conf_size);
}
debug_printf("retbuf=%p, %s\n", ret_conf, confline);
// Parse names
*confline = 0;
struct hwmodel_name names[2];
int conversions;
driverkit_parse_namelist(skb_get_output(), names, &conversions);
debug_printf("Conversions = %d\n", conversions);
if(ret_addr) *ret_addr = names[1].address;
return SYS_ERR_OK;
}
/**
* Makes dst visible to nodeid, assuming the configuration returned
* in ret_conf will be installed.
*/
errval_t driverkit_hwmodel_get_map_conf(struct capref dst,
int32_t nodeid,
char *ret_conf, size_t ret_conf_size,
lvaddr_t *ret_addr)
{
#ifdef DISABLE_MODEL
return SYS_ERR_OK;
#else
struct frame_identity id;
errval_t err;
err = frame_identify(dst, &id);
if (err_is_fail(err)) {
return err;
}
int32_t mem_nodeid = driverkit_hwmodel_lookup_pcibus_node_id();
return driverkit_hwmodel_get_map_conf_addr(mem_nodeid, id.base, id.bytes,
nodeid, ret_conf, ret_conf_size, ret_addr);
#endif
}
| 28.13308
| 94
| 0.608461
|
[
"model"
] |
9f2b6655feca086db3508d59d650513317c23774
| 12,064
|
h
|
C
|
camera/hal/intel/ipu3/psl/ipu3/GraphConfig.h
|
strassek/chromiumos-platform2
|
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
|
[
"BSD-3-Clause"
] | 4
|
2020-07-24T06:54:16.000Z
|
2021-06-16T17:13:53.000Z
|
camera/hal/intel/ipu3/psl/ipu3/GraphConfig.h
|
strassek/chromiumos-platform2
|
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
|
[
"BSD-3-Clause"
] | 1
|
2021-04-02T17:35:07.000Z
|
2021-04-02T17:35:07.000Z
|
camera/hal/intel/ipu3/psl/ipu3/GraphConfig.h
|
strassek/chromiumos-platform2
|
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
|
[
"BSD-3-Clause"
] | 1
|
2020-11-04T22:31:45.000Z
|
2020-11-04T22:31:45.000Z
|
/*
* Copyright (C) 2015-2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _CAMERA3_GRAPHCONFIG_H_
#define _CAMERA3_GRAPHCONFIG_H_
#include <string>
#include <memory>
#include <vector>
#include <set>
#include <utils/Errors.h>
#include <hardware/camera3.h>
#include <gcss.h>
#include <ia_aiq.h>
#include <linux/media.h>
#include "MediaCtlPipeConfig.h"
#include "LogHelper.h"
#include "MediaController.h"
#include "IPU3CameraCapInfo.h"
namespace GCSS {
class GraphConfigNode;
}
#define NODE_NAME(x) (getNodeName(x).c_str())
namespace cros {
namespace intel {
class GraphConfigManager;
#define MAX_OUTPUT_NUM_IN_PIPE 2
#define CSI_BE_OUTPUT "csi_be:output"
const int32_t ACTIVE_ISA_OUTPUT_BUFFER = 2;
const int32_t MAX_STREAMS = 4; // max number of streams
const uint32_t MAX_KERNEL_COUNT = 30; // max number of kernels in the kernel list
// Declare string consts
const std::string CSI_BE = "ipu3-cio2 ";
const std::string GC_INPUT = "input";
const std::string GC_MAIN = "main";
const std::string GC_VF = "vf";
const std::string GC_RAW = "raw";
// pipe index, video pipe: "ipu3-imgu 0", still pipe: "ipu3-imgu 1"
#define VIDEO_PIPE_INDEX 0
#define STILL_PIPE_INDEX 1
/**
* Stream id associated with the ISA PG that runs on Psys.
*/
static const int32_t PSYS_ISA_STREAM_ID = 60002;
/**
* Stream id associated with the ISA PG that runs on Isys.
*/
static const int32_t ISYS_ISA_STREAM_ID = 0;
/**
* \struct SinkDependency
*
* This structure stores dependency information for each virtual sink.
* This information is useful to determine the connections that preceded the
* virtual sink.
* We do not go all the way up to the sensor (we could), we just store the
* terminal id of the input port of the pipeline that serves a particular sink
* (i.e. the input port of the video pipe or still pipe)
*/
struct SinkDependency {
uid_t sinkGCKey; /**< GCSS_KEY that represents a sink, like GCSS_KEY_VIDEO1 */
int32_t streamId; /**< (a.k.a pipeline id) linked to this sink (ex 60000) */
uid_t streamInputPortId; /**< 4CC code of that terminal */
SinkDependency():
sinkGCKey(0),
streamId(-1),
streamInputPortId(0) {};
};
/**
* \class GraphConfig
*
* Reference and accessor to pipe configuration for specific request.
*
* In general case, at sream-config time there are multiple possible graphs.
* Per each request there is additional intent that can narrow down the
* possibilities to single graph settings: the GraphConfig object.
*
* This class is instantiated by \class GraphConfigManager for each request,
* and passed around HAL (control unit, capture unit, processing unit) via
* shared pointers. The objects are read-only and owned by GCM.
*/
class GraphConfig {
public:
typedef GCSS::GraphConfigNode Node;
typedef std::vector<Node*> NodesPtrVector;
typedef std::vector<int32_t> StreamsVector;
typedef std::map<camera3_stream_t*, uid_t> StreamToSinkMap;
static const int32_t PORT_DIRECTION_INPUT = 0;
static const int32_t PORT_DIRECTION_OUTPUT = 1;
public:
GraphConfig();
~GraphConfig();
/*
* Convert Node to GraphConfig interface
*/
const GCSS::IGraphConfig* getInterface(Node *node) const;
const GCSS::IGraphConfig* getInterface() const;
/*
* Graph Interrogation methods
*/
status_t graphGetSinksByName(const std::string &name, NodesPtrVector &sinks);
status_t graphGetDimensionsByName(const std::string &name,
int &widht, int &height);
status_t graphGetDimensionsByName(const std::string &name,
unsigned short &widht, unsigned short &height);
/*
* Find distinct stream ids from the graph
*/
status_t graphGetStreamIds(std::vector<int32_t> &streamIds);
/*
* Sink Interrogation methods
*/
int32_t sinkGetStreamId(Node *sink);
/*
* Stream Interrogation methods
*/
status_t streamGetInputPort(int32_t streamId, Node **port);
/*
* Port Interrogation methods
*/
status_t portGetFullName(Node *port, std::string &fullName);
status_t portGetPeer(Node *port, Node **peer);
int32_t portGetDirection(Node *port);
bool portIsVirtual(Node *port);
status_t portGetPeerIdByName(std::string name,
uid_t &terminalId);
status_t getDimensions(const Node *node, int &w, int &h) const;
status_t getDimensions(const Node *node, int &w, int &h, int &l,int &t) const;
/*
* re-cycler static method
*/
static void reset(GraphConfig *me);
void fullReset();
/*
* Debugging support
*/
std::string getNodeName(Node *node);
status_t getValue(string &nodeName, uint32_t id, int &value);
bool doesNodeExist(string nodeName);
enum PipeType {
PIPE_STILL = 0,
PIPE_VIDEO,
PIPE_MAX
};
PipeType getPipeType() const { return mPipeType; }
void setPipeType(PipeType type) { mPipeType = type; }
bool isStillPipe() { return mPipeType == PIPE_STILL; }
public:
void setMediaCtlConfig(std::shared_ptr<MediaController> mediaCtl,
bool enableStill);
private:
/* Helper structures to access Sensor Node information easily */
class Rectangle {
public:
Rectangle();
int32_t w; /*<! width */
int32_t h; /*<! height */
int32_t t; /*<! top */
int32_t l; /*<! left */
};
struct MediaCtlLut {
string uidStr;
uint32_t uid;
int pad;
string nodeName;
int ipuNodeName;
};
class SubdevPad: public Rectangle {
public:
SubdevPad();
int32_t mbusFormat;
};
struct BinFactor {
int32_t h;
int32_t v;
};
struct ScaleFactor {
int32_t num;
int32_t denom;
};
union RcFactor { // Resolution Changing factor
BinFactor bin;
ScaleFactor scale;
};
struct SubdevInfo {
string name;
SubdevPad in;
SubdevPad out;
RcFactor factor;
};
class SourceNodeInfo {
public:
SourceNodeInfo();
string name;
string i2cAddress;
string modeId;
bool metadataEnabled;
string csiPort;
string nativeBayer;
SubdevInfo tpg;
SubdevInfo pa;
SubdevPad output;
int32_t interlaced;
string verticalFlip;
string horizontalFlip;
string link_freq;
};
friend class GraphConfigManager;
// Private initializer: only used by our friend GraphConfigManager.
void init(int32_t reqId);
status_t prepare(Node *settings,
StreamToSinkMap &streamToSinkIdMap);
status_t analyzeSourceType();
void calculateSinkDependencies();
void storeTuningModes();
/*
* Helpers for constructing mediaCtlConfigs from graph config
*/
status_t parseSensorNodeInfo(Node* sensorNode, SourceNodeInfo &info);
status_t getCio2MediaCtlData(int *cio2Format, MediaCtlConfig* mediaCtlConfig);
status_t getImguMediaCtlData(int32_t cameraId,
int cio2Format,
int32_t testPatternMode,
bool enableStill,
MediaCtlConfig* mediaCtlConfig);
status_t addControls(const Node *sensorNode,
const SourceNodeInfo &sensorInfo,
MediaCtlConfig* config);
void addVideoNodes(MediaCtlConfig *config);
void addImguVideoNode(int ipuNodeName, const string& nodeName, MediaCtlConfig* config);
status_t getBinningFactor(const Node *node,
int32_t &hBin, int32_t &vBin) const;
status_t getScalingFactor(const Node *node,
int32_t &scalingNum,
int32_t &scalingDenom) const;
void addCtlParams(const string &entityName,
uint32_t controlName,
int controlId,
const string &strValue,
MediaCtlConfig* config);
void addFormatParams(const string &entityName,
int width,
int height,
int pad,
int formatCode,
int field,
MediaCtlConfig* config);
void addLinkParams(const string &srcName,
int srcPad,
const string &sinkName,
int sinkPad,
int enable,
int flags,
MediaCtlConfig* config);
void addSelectionParams(const string &entityName,
int width,
int height,
int left,
int top,
int target,
int pad,
MediaCtlConfig* config);
void addSelectionVideoParams(const string &entityName,
const struct v4l2_subdev_selection &select,
MediaCtlConfig* config);
status_t getNodeInfo(const ia_uid uid, const Node &parent, int *width, int *height);
void dumpMediaCtlConfig(const MediaCtlConfig &config) const;
// Private helpers for port nodes
status_t portGetFourCCInfo(Node &portNode,
uint32_t &stageId, uint32_t &terminalId);
// Format options methods
status_t getActiveOutputPorts(
const StreamToSinkMap &streamToSinkIdMap);
Node *getOutputPortForSink(const std::string &sinkName);
public:
// Imgu used from ParameterWorker
status_t getSensorFrameParams(ia_aiq_frame_params &sensorFrameParams);
private:
// Disable copy constructor and assignment operator
GraphConfig(const GraphConfig &);
GraphConfig& operator=(const GraphConfig &);
private:
GCSS::GraphConfigNode *mSettings;
int32_t mReqId;
std::map<int32_t, size_t> mKernelCountsMap; // key is stream id
PipeType mPipeType;
enum SourceType {
SRC_NONE = 0,
SRC_SENSOR,
SRC_TPG,
};
SourceType mSourceType;
/**
* pre-computed state done *per request*.
* This map holds the terminal id's of the ISA's peer ports (this is
* the terminal id's of the input port of the video or still pipe)
* that are required to fulfill a request.
* Ideally this gets initialized during init() call.
* But for now the GcManager will set it via a private method.
* we use a map so that we can handle the case when a request has 2 buffers
* that are generated from the same pipe.
*/
std::map<uid_t, uid_t> mIsaActiveDestinations;
/**
* vector holding the peers to the sink nodes. Map contains pairs of
* {sink, peer}.
* This map is filled at stream config time.
*/
std::map<Node*, Node*> mSinkPeerPort;
/**
*copy of the map provided from GraphConfigManager to be used internally.
*/
StreamToSinkMap mStreamToSinkIdMap;
/**
* Map of tuning modes per stream id
* Key: stream id
* Value: tuning mode
*/
std::map<int32_t, int32_t> mStream2TuningMap;
std::string mCSIBE;
std::shared_ptr<MediaController> mMediaCtl;
std::vector<MediaCtlLut> mLut;
};
} // namespace intel
} // namespace cros
#endif
| 32.782609
| 93
| 0.631134
|
[
"object",
"vector"
] |
9f39b976691ed4b580f770fabfc23744f9fd97d6
| 1,201
|
h
|
C
|
src/Zombies/Human.h
|
ndongmo/Zombies-Game
|
739a0b759c36ab6974af2e50db99c2b736e00964
|
[
"MIT"
] | 13
|
2019-02-21T09:05:11.000Z
|
2021-12-03T09:11:00.000Z
|
src/Zombies/Human.h
|
ndongmo/Zombies-Game
|
739a0b759c36ab6974af2e50db99c2b736e00964
|
[
"MIT"
] | null | null | null |
src/Zombies/Human.h
|
ndongmo/Zombies-Game
|
739a0b759c36ab6974af2e50db99c2b736e00964
|
[
"MIT"
] | 2
|
2019-09-03T05:45:40.000Z
|
2020-03-25T06:10:37.000Z
|
#pragma once
#include "Agent.h"
#include "Gun.h"
#include "Bag.h"
class Human : public Agent
{
friend class PathFollowingAI;
public:
Human();
virtual void init(float x, float y, float radius, NS2::GLTexture& texture, glm::ivec2& texDims, AI* ai);
virtual void init(float x, float y, float radius, NS2::GLTexture& texture, glm::ivec2& texDims, NS2::ColorRGBA8& color,
glm::vec2& direction, std::string name, float animSpeed, AI* ai, float speed, float health);
virtual void draw(NS2::SpriteBatch& spriteBatch) override;
virtual void draw(NS2::DebugRenderer& debugRender, NS2::ColorRGBA8& color) override;
virtual void update(Level& level, float deltaTime) override;
virtual void applyDamage(Level& level, float damage) override;
void setEquipWeapon(Gun* gun){ m_weapon = gun; }
void setEquipAmmo(Ammo* ammo){ m_ammo = ammo; }
void setEquipObject(Object* object){ m_object = object; }
Gun* getEquipWeapon(){ return m_weapon; }
Ammo* geEquipAmmo(){ return m_ammo; }
Object* getEquipObject(){ return m_object; }
protected:
float m_invTime; // Invincible time
float m_invCurrentTime;
NS2::ColorRGBA8 m_invColor;
Bag m_bag;
Gun* m_weapon;
Ammo* m_ammo;
Object* m_object;
};
| 28.595238
| 120
| 0.734388
|
[
"object"
] |
9f3a0d9a0908c33391c159718b2ac54bd8f7f5c1
| 3,306
|
h
|
C
|
src/mymodel/Increment/Increment.h
|
travissluka/JEDI-modeltemplate
|
958da1cae23b99f4deff72273960e3b4b4bf14f5
|
[
"Apache-2.0"
] | null | null | null |
src/mymodel/Increment/Increment.h
|
travissluka/JEDI-modeltemplate
|
958da1cae23b99f4deff72273960e3b4b4bf14f5
|
[
"Apache-2.0"
] | null | null | null |
src/mymodel/Increment/Increment.h
|
travissluka/JEDI-modeltemplate
|
958da1cae23b99f4deff72273960e3b4b4bf14f5
|
[
"Apache-2.0"
] | null | null | null |
/*
* (C) Copyright 2019-2020 UCAR.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
#ifndef MYMODEL_INCREMENT_INCREMENT_H_
#define MYMODEL_INCREMENT_INCREMENT_H_
#include <memory>
#include <ostream>
#include <string>
#include <vector>
#include "oops/base/GeneralizedDepartures.h"
#include "oops/base/Variables.h"
#include "oops/util/DateTime.h"
#include "oops/util/Printable.h"
#include "oops/util/Serializable.h"
// forward declarations
namespace oops {
class LocalIncrement;
class Variables;
}
namespace ufo {
class GeoVaLs;
class Locations;
}
namespace mymodel {
class Geometry;
class GeometryIterator;
class State;
}
// ----------------------------------------------------------------------------
namespace mymodel {
// Increment class
class Increment : public oops::GeneralizedDepartures,
public util::Printable,
public util::Serializable,
private util::ObjectCounter<Increment> {
public:
static const std::string classname() {return "mymodel::Increment";}
// Constructor, destructor
Increment(const Geometry &, const oops::Variables &,
const util::DateTime &);
Increment(const Geometry &, const Increment &);
Increment(const Increment &, const bool);
Increment(const Increment &);
~Increment();
// Math operators
Increment & operator =(const Increment &);
Increment & operator-=(const Increment &);
Increment & operator+=(const Increment &);
Increment & operator*=(const double &);
void accumul(const double &, const State &);
void axpy(const double &, const Increment &, const bool check = true);
void diff(const State &, const State &);
double dot_product_with(const Increment &) const;
double norm() const;
void random();
void schur_product_with(const Increment &);
void zero();
void zero(const util::DateTime &);
void ones();
// time manipulation
void updateTime(const util::Duration & dt) { time_ += dt; }
const util::DateTime & validTime() const { return time_; }
util::DateTime & validTime() { return time_; }
// dirac
void dirac(const eckit::Configuration &);
// Iterator access
oops::LocalIncrement getLocal(const GeometryIterator &) const;
void setLocal(const oops::LocalIncrement &, const GeometryIterator &);
// serialize (only needed for EDA?)
size_t serialSize() const override;
void serialize(std::vector<double> &) const override;
void deserialize(const std::vector<double> &, size_t &) override;
// other accessors
std::shared_ptr<const Geometry> geometry() const { return geom_; }
// I/O
void read(const eckit::Configuration &);
void write(const eckit::Configuration &) const;
private:
void print(std::ostream &) const;
std::shared_ptr<const Geometry> geom_;
util::DateTime time_;
oops::Variables vars_;
};
} // namespace mymodel
#endif // MYMODEL_INCREMENT_INCREMENT_H_
| 30.054545
| 81
| 0.668482
|
[
"geometry",
"vector"
] |
9f440d3b0fa1adf0b3c91d0c244bc6cd555cf1ee
| 197
|
h
|
C
|
src/HPMeshGen2/TriangleCluster.h
|
DanielZint/hpmeshgen
|
cdfb9163ed92523fcf41a127c8173097e935c0a3
|
[
"MIT"
] | 2
|
2022-02-09T08:51:16.000Z
|
2022-02-09T08:51:27.000Z
|
src/HPMeshGen2/TriangleCluster.h
|
DanielZint/hpmeshgen
|
cdfb9163ed92523fcf41a127c8173097e935c0a3
|
[
"MIT"
] | null | null | null |
src/HPMeshGen2/TriangleCluster.h
|
DanielZint/hpmeshgen
|
cdfb9163ed92523fcf41a127c8173097e935c0a3
|
[
"MIT"
] | null | null | null |
#pragma once
#include "MeshHeader.h"
#include <experimental/filesystem>
#include <vector>
class TriangleCluster
{
public:
TriangleCluster( TriMesh& fragMesh, TriMesh& fineMesh );
private:
};
| 12.3125
| 57
| 0.751269
|
[
"vector"
] |
9f44adb92859126dbf0496b711a71c29e931cdf3
| 4,317
|
h
|
C
|
BoyerMoore.h
|
akhileshzmishra/DataStructure
|
111dccb23243700caf3a01a1ae7c87ae880a89d3
|
[
"CECILL-B"
] | null | null | null |
BoyerMoore.h
|
akhileshzmishra/DataStructure
|
111dccb23243700caf3a01a1ae7c87ae880a89d3
|
[
"CECILL-B"
] | null | null | null |
BoyerMoore.h
|
akhileshzmishra/DataStructure
|
111dccb23243700caf3a01a1ae7c87ae880a89d3
|
[
"CECILL-B"
] | null | null | null |
#ifndef __BOYER_MOORE__H__
#define __BOYER_MOORE__H__
#include <vector>
#pragma once
template<class T>
class BoyerMoore
{
typedef std::vector<int> List;
List m_Table1;
List m_Table2;
const T* m_Sub;
const T* m_Src;
int m_LengthSrc;
int m_LengthSub;
bool m_bTable1Prepared;
bool m_bTable2Prepared;
int m_index;
public:
static const int No_Index = -1;
BoyerMoore(void):
m_Sub(0),
m_Src(0),
m_LengthSrc(0),
m_LengthSub(0),
m_bTable1Prepared(false),
m_bTable2Prepared(false),
m_index(0)
{
}
~BoyerMoore(void)
{
}
int FindIndex(T* src, int srclen, T* sub, int sublen)
{
Reset();
if(!src || !sub)
{
return No_Index;
}
m_LengthSrc = srclen;
m_LengthSub = sublen;
m_Src = src;
m_Sub = sub;
return t_FindIndex(true);
}
int FindIndex(const T* src, int srclen) //sub has already been given
{
if(!src || !m_Sub || (srclen <= 0) || (m_LengthSub <= 0))
{
return No_Index;
}
m_LengthSrc = srclen;
m_Src = src;
return t_FindIndex(false);
}
void SetSubString(const T* sub, int sublen)
{
Reset();
CreateTables(sub, sublen);
}
void Reset();
private:
void CreateTables(const T* sub, int sublen)
{
if(!sub || (sublen <= 0))
{
return;
}
m_LengthSub = sublen;
m_Sub = sub;
t_CreateTableOne();
t_CreateTableTwo();
}
void t_CreateTableOne();
void t_CreateTableTwo();
bool t_AreTablePrepared()
{
return (m_bTable1Prepared & m_bTable2Prepared);
}
int t_FindIndex(bool createtable = true);
};
template<class T>
void BoyerMoore<T>::t_CreateTableOne()
{
if(t_AreTablePrepared())
{
return;
}
m_Table1.clear();
int length = m_LengthSub;
if(length <= 0)
{
return;
}
m_Table1.resize(length, 0);
for(int i = length - 1; i > 0; i--)
{
for(int j = i - 1; j >= 0; j--)
{
if(m_Sub[i] == m_Sub[j])
{
m_Table1[i - 1] = i - j;
break;
}
}
}
for(int i = 0; i < length; i++)
{
if(m_Table1[i] == 0)
m_Table1[i] = length - i;
}
m_bTable1Prepared = true;
}
template<class T>
void BoyerMoore<T>::t_CreateTableTwo()
{
if(t_AreTablePrepared())
{
return;
}
m_Table2.clear();
int length = m_LengthSub;
if(length <= 0)
{
return;
}
m_Table2.resize(length, 0);
std::vector<int> EndTable;
for(int i = 0; i < length; i++)
{
if(m_Sub[i] == m_Sub[length - 1])
{
EndTable.push_back(i);
}
}
for(int i = (int)((int)EndTable.size() - 1); i > 0; i--)
{
for(int j = i - 1; j >= 0; j--)
{
int x = EndTable[i];
int y = EndTable[j];
while((m_Sub[x] == m_Sub[y]) && (y >= 0))
{
if(m_Table2[x - 1] == 0)
{
m_Table2[x - 1] = x - y;
}
x--;
y--;
}
}
}
for(int i = 0; i < length; i++)
{
if(m_Table2[i] == 0)
{
m_Table2[i] = length - i - 1;
}
}
m_Table2[length - 1] = 1;
m_bTable2Prepared = true;
}
template<class T>
void BoyerMoore<T>::Reset()
{
m_Sub = 0;
m_Src = 0;
m_bTable1Prepared = false;
m_bTable2Prepared = false;
m_Table1.clear();
m_Table2.clear();
}
template<class T>
int BoyerMoore<T>::t_FindIndex(bool createtable)
{
int currIndex = No_Index;
int srclen = m_LengthSrc;
int sublen = m_LengthSub;
if(sublen > srclen)
{
m_index = No_Index;
return currIndex;
}
if(createtable)
{
t_CreateTableOne();
t_CreateTableTwo();
}
if(!t_AreTablePrepared())
{
return No_Index;
}
int i = sublen - 1 + m_index;
int j = sublen - 1;
int curr = i;
while(i < srclen)
{
while(j >= 0)
{
if(m_Src[i] == m_Sub[j])
{
i--;
j--;
}
else
{
break;
}
}
if(j >= 0)
{
int tab1 = m_Table1[j];
int tab2 = m_Table2[j];
int max = tab2;
if(tab1 > tab2)
max = tab1;
if(max == 0)
max = 1;
//cout<<"jumps "<<max<<endl;
curr += max;
i = curr;
j = sublen - 1;
}
else
{
break;
}
}
if(j < 0)
{
currIndex = i + 1;
m_index = currIndex;
}
else
{
m_index = No_Index;
}
return m_index;
}
#endif
| 15.755474
| 72
| 0.529534
|
[
"vector"
] |
9f49d36586b4ba9b4099eb693b0c6410bc84b9d1
| 2,777
|
h
|
C
|
hbase-native-client/src/core/compare_filter.h
|
vergilchiu/hdp-hbase
|
f03369b38225317f8f2fdae30ff9ab66c70ec010
|
[
"Apache-2.0"
] | null | null | null |
hbase-native-client/src/core/compare_filter.h
|
vergilchiu/hdp-hbase
|
f03369b38225317f8f2fdae30ff9ab66c70ec010
|
[
"Apache-2.0"
] | null | null | null |
hbase-native-client/src/core/compare_filter.h
|
vergilchiu/hdp-hbase
|
f03369b38225317f8f2fdae30ff9ab66c70ec010
|
[
"Apache-2.0"
] | null | null | null |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#pragma once
#include "byte_array_comparable.h"
#include "cell.h"
#include "filter_base.h"
class CompareFilter : public FilterBase {
public:
enum class CompareOp{
/** less than */
LESS,
/** less than or equal to */
LESS_OR_EQUAL,
/** equals */
EQUAL,
/** not equal */
NOT_EQUAL,
/** greater than or equal to */
GREATER_OR_EQUAL,
/** greater than */
GREATER,
/** no operation */
NO_OP
};
CompareFilter();
CompareFilter(const CompareOp &compare_op, const ByteArrayComparable *comparator);
const CompareFilter::CompareOp & GetOperator();
const ByteArrayComparable *GetComparator();
virtual ~CompareFilter();
bool FilterRowKey(const Cell &first_row_cell);
// TODO
// public static ArrayList<Object> extractArguments(ArrayList<byte []> filterArguments)
// FilterProtos.CompareFilter convert()
// boolean areSerializedFieldsEqual(Filter o)
// public String toString()
std::unique_ptr<google::protobuf::Message> Convert();
const std::string &GetCompareOpName();
const hbase::pb::CompareType &GetPbCompareOp();
virtual const char *GetName() = 0;
virtual bool ToByteArray(hbase::pb::Filter &filter) = 0;
protected:
bool CompareRow(const CompareOp &compare_op, const ByteArrayComparable *comparator, const Cell &cell);
bool compareFamily(const CompareOp &compare_op, const ByteArrayComparable *comparator, const Cell &cell);
bool compareQualifier(const CompareOp &compare_op, const ByteArrayComparable *comparator, const Cell &cell);
bool compareValue(const CompareOp &compare_op, const ByteArrayComparable *comparator, const Cell &cell);
CompareOp compare_op_;
ByteArrayComparable *comparator_;
private:
bool Compare(const CompareOp &compare_op, const int &compare_result);
void SetCompareOpName(const CompareOp &compare_op);
void SetPbCompareOp(const CompareOp &compare_op);
std::string compare_op_name_;
hbase::pb::CompareType pb_compare_op_;
};
| 35.602564
| 110
| 0.737847
|
[
"object"
] |
9f5a8937d7e255a9c54b29dcbd5f6e36bf6d9176
| 23,158
|
h
|
C
|
BAPSPresenter/RecordLibrarySearch.h
|
UniversityRadioYork/BAPS2
|
af80b66cdd7a980cf34714bef7b5260167714ca5
|
[
"BSD-3-Clause"
] | 4
|
2018-12-20T20:58:46.000Z
|
2019-05-22T21:32:43.000Z
|
BAPSPresenter/RecordLibrarySearch.h
|
UniversityRadioYork/BAPS2
|
af80b66cdd7a980cf34714bef7b5260167714ca5
|
[
"BSD-3-Clause"
] | 9
|
2018-12-22T00:55:13.000Z
|
2019-01-21T10:08:30.000Z
|
BAPSPresenter/RecordLibrarySearch.h
|
UniversityRadioYork/BAPS2
|
af80b66cdd7a980cf34714bef7b5260167714ca5
|
[
"BSD-3-Clause"
] | 1
|
2018-12-21T19:32:48.000Z
|
2018-12-21T19:32:48.000Z
|
#pragma once
#include "BAPSButton.h"
#include "BAPSListBox.h"
#include "BAPSPresenterMain.h"
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
namespace BAPSPresenter {
/** We need a pre-declaration of the Main form so that we can define a handle to it here **/
ref class BAPSPresenterMain;
/// <summary>
/// Summary for RecordLibrarySearch
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
/// </summary>
public ref class RecordLibrarySearch : public System::Windows::Forms::Form
{
public:
RecordLibrarySearch(BAPSPresenterMain^ _bapsPresenterMain, System::Collections::Queue^ _queue)
: bapsPresenterMain(_bapsPresenterMain), msgQueue(_queue)
{
InitializeComponent();
System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(RecordLibrarySearch::typeid));
//this->connectionStatus->BackgroundImage = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"$this.BackgroundImage")));
//this->resultsInfo->BackgroundImage = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"$this.BackgroundImage")));
//this->statusStrip->BackgroundImage = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"$this.BackgroundImage")));
/** Tag objects for the 3 buttons to find out at runtime what they are **/
System::Object ^number0 = safe_cast<System::Object^>(0);
System::Object ^number1 = 1;
System::Object ^number2 = 2;
/** Set the tags correctly **/
AddToChannel0->Tag = number0;
AddToChannel1->Tag = number1;
AddToChannel2->Tag = number2;
/** Disable all the buttons **/
AddToChannel0->Enabled = false;
AddToChannel1->Enabled = false;
AddToChannel2->Enabled = false;
/** Disable the listbox **/
ResultsBox->Enabled = false;
/** We don't want to be tabbing onto the labels! **/
ArtistBoxLabel->TabStop = false;
TitleBoxLabel->TabStop = false;
/** Set result count to be 0 **/
numberOfResults = 0;
/** Set to first result page **/
pageNum = 0;
}
void setResultCount(System::Object^ _count);
void add(System::Object^ _index, System::Object^ _dirtyStatus, System::String^ string);
void handleError(System::Object^ _errorcode, System::String^ description);
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~RecordLibrarySearch()
{
/** The fastest method turned out to be when we load the results
into a temporary array and then add them to the listbox
**/
ResultsBox->Items->Clear();
if (components)
{
delete components;
}
}
private:
/** The page of results to view **/
int pageNum;
/** Placeholder for result count **/
int numberOfResults;
/** A handle to the main window **/
BAPSPresenterMain^ bapsPresenterMain;
private: System::Windows::Forms::RadioButton^ dateReleasedRadioButton;
private: System::Windows::Forms::CheckBox^ noncleanCheckbox;
private: System::Windows::Forms::Button^ closeButton;
private: System::Windows::Forms::Button^ SearchButton;
private: System::Windows::Forms::ListBox^ ResultsBox;
/** handle to the global message queue **/
System::Collections::Queue^ msgQueue;
System::Void RadioButton_CheckedChanged(System::Object^ sender, System::EventArgs^ e);
System::Void AddToChannel_Click(System::Object ^ sender, System::EventArgs ^ e);
System::Void SearchButton_Click(System::Object ^ sender, System::EventArgs ^ e);
System::Void Text_Enter(System::Object ^ sender, System::EventArgs ^ e);
System::Void Artist_Leave(System::Object ^ sender, System::EventArgs ^ e);
System::Void Title_Leave(System::Object ^ sender, System::EventArgs ^ e);
System::Void closeButton_Click(System::Object^ sender, System::EventArgs^ e);
System::Void RecordLibrarySearch_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e);
System::Void Some_TextChanged(System::Object^ sender, System::EventArgs^ e);
private: System::Windows::Forms::Button^ AddToChannel0;
private: System::Windows::Forms::Button^ AddToChannel1;
private: System::Windows::Forms::Button^ AddToChannel2;
private: System::Windows::Forms::RadioButton^ titleRadioButton;
private: System::Windows::Forms::RadioButton^ artistRadioButton;
private: System::Windows::Forms::RadioButton^ dateAddedRadioButton;
private: System::Windows::Forms::CheckBox^ reverseOrderCheckBox;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::ToolStripStatusLabel^ connectionStatus;
private: System::Windows::Forms::StatusStrip^ statusStrip;
private: System::Windows::Forms::ToolStripProgressBar^ progressBar;
private: System::Windows::Forms::ToolStripStatusLabel^ resultsInfo;
private: System::Windows::Forms::Label^ TitleBoxLabel;
private: System::Windows::Forms::Label^ ArtistBoxLabel;
private: System::Windows::Forms::TextBox^ Title;
private: System::Windows::Forms::TextBox^ Artist;
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(RecordLibrarySearch::typeid));
this->connectionStatus = (gcnew System::Windows::Forms::ToolStripStatusLabel());
this->statusStrip = (gcnew System::Windows::Forms::StatusStrip());
this->progressBar = (gcnew System::Windows::Forms::ToolStripProgressBar());
this->resultsInfo = (gcnew System::Windows::Forms::ToolStripStatusLabel());
this->TitleBoxLabel = (gcnew System::Windows::Forms::Label());
this->ArtistBoxLabel = (gcnew System::Windows::Forms::Label());
this->Title = (gcnew System::Windows::Forms::TextBox());
this->Artist = (gcnew System::Windows::Forms::TextBox());
this->artistRadioButton = (gcnew System::Windows::Forms::RadioButton());
this->titleRadioButton = (gcnew System::Windows::Forms::RadioButton());
this->dateAddedRadioButton = (gcnew System::Windows::Forms::RadioButton());
this->label1 = (gcnew System::Windows::Forms::Label());
this->reverseOrderCheckBox = (gcnew System::Windows::Forms::CheckBox());
this->dateReleasedRadioButton = (gcnew System::Windows::Forms::RadioButton());
this->noncleanCheckbox = (gcnew System::Windows::Forms::CheckBox());
this->closeButton = (gcnew System::Windows::Forms::Button());
this->SearchButton = (gcnew System::Windows::Forms::Button());
this->AddToChannel0 = (gcnew System::Windows::Forms::Button());
this->AddToChannel1 = (gcnew System::Windows::Forms::Button());
this->AddToChannel2 = (gcnew System::Windows::Forms::Button());
this->ResultsBox = (gcnew System::Windows::Forms::ListBox());
this->statusStrip->SuspendLayout();
this->SuspendLayout();
//
// connectionStatus
//
this->connectionStatus->Name = L"connectionStatus";
this->connectionStatus->Size = System::Drawing::Size(145, 17);
this->connectionStatus->Spring = true;
this->connectionStatus->Text = L"Connection: stable";
//
// statusStrip
//
this->statusStrip->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(3) {this->connectionStatus,
this->progressBar, this->resultsInfo});
this->statusStrip->Location = System::Drawing::Point(0, 492);
this->statusStrip->Name = L"statusStrip";
this->statusStrip->Size = System::Drawing::Size(508, 22);
this->statusStrip->SizingGrip = false;
this->statusStrip->TabIndex = 11;
this->statusStrip->Text = L"statusStrip1";
//
// progressBar
//
this->progressBar->Name = L"progressBar";
this->progressBar->Size = System::Drawing::Size(200, 16);
//
// resultsInfo
//
this->resultsInfo->Name = L"resultsInfo";
this->resultsInfo->RightToLeft = System::Windows::Forms::RightToLeft::No;
this->resultsInfo->Size = System::Drawing::Size(145, 17);
this->resultsInfo->Spring = true;
this->resultsInfo->Text = L"No Results";
//
// TitleBoxLabel
//
this->TitleBoxLabel->BackColor = System::Drawing::Color::Transparent;
this->TitleBoxLabel->Location = System::Drawing::Point(22, 13);
this->TitleBoxLabel->Name = L"TitleBoxLabel";
this->TitleBoxLabel->Size = System::Drawing::Size(40, 20);
this->TitleBoxLabel->TabIndex = 18;
this->TitleBoxLabel->Text = L"Title:";
this->TitleBoxLabel->TextAlign = System::Drawing::ContentAlignment::MiddleLeft;
//
// ArtistBoxLabel
//
this->ArtistBoxLabel->BackColor = System::Drawing::Color::Transparent;
this->ArtistBoxLabel->Location = System::Drawing::Point(20, 41);
this->ArtistBoxLabel->Name = L"ArtistBoxLabel";
this->ArtistBoxLabel->Size = System::Drawing::Size(40, 20);
this->ArtistBoxLabel->TabIndex = 17;
this->ArtistBoxLabel->Text = L"Artist:";
this->ArtistBoxLabel->TextAlign = System::Drawing::ContentAlignment::MiddleLeft;
//
// Title
//
this->Title->Anchor = static_cast<System::Windows::Forms::AnchorStyles>(((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Left)
| System::Windows::Forms::AnchorStyles::Right));
this->Title->BackColor = System::Drawing::SystemColors::Window;
this->Title->BorderStyle = System::Windows::Forms::BorderStyle::FixedSingle;
this->Title->Location = System::Drawing::Point(68, 12);
this->Title->Name = L"Title";
this->Title->Size = System::Drawing::Size(347, 21);
this->Title->TabIndex = 0;
this->Title->Text = L"<Enter the Title to search for>";
this->Title->TextChanged += gcnew System::EventHandler(this, &RecordLibrarySearch::Some_TextChanged);
this->Title->Leave += gcnew System::EventHandler(this, &RecordLibrarySearch::Title_Leave);
this->Title->Enter += gcnew System::EventHandler(this, &RecordLibrarySearch::Text_Enter);
//
// Artist
//
this->Artist->Anchor = static_cast<System::Windows::Forms::AnchorStyles>(((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Left)
| System::Windows::Forms::AnchorStyles::Right));
this->Artist->BackColor = System::Drawing::SystemColors::Window;
this->Artist->BorderStyle = System::Windows::Forms::BorderStyle::FixedSingle;
this->Artist->Location = System::Drawing::Point(68, 40);
this->Artist->Name = L"Artist";
this->Artist->Size = System::Drawing::Size(347, 21);
this->Artist->TabIndex = 1;
this->Artist->Text = L"<Enter the Artist to search for>";
this->Artist->TextChanged += gcnew System::EventHandler(this, &RecordLibrarySearch::Some_TextChanged);
this->Artist->Leave += gcnew System::EventHandler(this, &RecordLibrarySearch::Artist_Leave);
this->Artist->Enter += gcnew System::EventHandler(this, &RecordLibrarySearch::Text_Enter);
//
// artistRadioButton
//
this->artistRadioButton->AutoSize = true;
this->artistRadioButton->BackColor = System::Drawing::Color::Transparent;
this->artistRadioButton->Location = System::Drawing::Point(117, 66);
this->artistRadioButton->Name = L"artistRadioButton";
this->artistRadioButton->Size = System::Drawing::Size(51, 17);
this->artistRadioButton->TabIndex = 6;
this->artistRadioButton->Text = L"Artist";
this->artistRadioButton->UseVisualStyleBackColor = false;
this->artistRadioButton->CheckedChanged += gcnew System::EventHandler(this, &RecordLibrarySearch::RadioButton_CheckedChanged);
//
// titleRadioButton
//
this->titleRadioButton->AutoSize = true;
this->titleRadioButton->BackColor = System::Drawing::Color::Transparent;
this->titleRadioButton->Checked = true;
this->titleRadioButton->Location = System::Drawing::Point(68, 66);
this->titleRadioButton->Name = L"titleRadioButton";
this->titleRadioButton->Size = System::Drawing::Size(45, 17);
this->titleRadioButton->TabIndex = 5;
this->titleRadioButton->TabStop = true;
this->titleRadioButton->Text = L"Title";
this->titleRadioButton->UseVisualStyleBackColor = false;
this->titleRadioButton->CheckedChanged += gcnew System::EventHandler(this, &RecordLibrarySearch::RadioButton_CheckedChanged);
//
// dateAddedRadioButton
//
this->dateAddedRadioButton->AutoSize = true;
this->dateAddedRadioButton->BackColor = System::Drawing::Color::Transparent;
this->dateAddedRadioButton->Location = System::Drawing::Point(168, 66);
this->dateAddedRadioButton->Name = L"dateAddedRadioButton";
this->dateAddedRadioButton->Size = System::Drawing::Size(82, 17);
this->dateAddedRadioButton->TabIndex = 7;
this->dateAddedRadioButton->Text = L"Date Added";
this->dateAddedRadioButton->UseVisualStyleBackColor = false;
this->dateAddedRadioButton->CheckedChanged += gcnew System::EventHandler(this, &RecordLibrarySearch::RadioButton_CheckedChanged);
//
// label1
//
this->label1->BackColor = System::Drawing::Color::Transparent;
this->label1->Location = System::Drawing::Point(15, 66);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(62, 17);
this->label1->TabIndex = 4;
this->label1->Text = L"Order By:";
this->label1->TextAlign = System::Drawing::ContentAlignment::MiddleLeft;
//
// reverseOrderCheckBox
//
this->reverseOrderCheckBox->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
this->reverseOrderCheckBox->AutoSize = true;
this->reverseOrderCheckBox->BackColor = System::Drawing::Color::Transparent;
this->reverseOrderCheckBox->Location = System::Drawing::Point(283, 89);
this->reverseOrderCheckBox->Name = L"reverseOrderCheckBox";
this->reverseOrderCheckBox->Size = System::Drawing::Size(97, 17);
this->reverseOrderCheckBox->TabIndex = 9;
this->reverseOrderCheckBox->Text = L"Reverse Order";
this->reverseOrderCheckBox->UseVisualStyleBackColor = false;
this->reverseOrderCheckBox->CheckedChanged += gcnew System::EventHandler(this, &RecordLibrarySearch::Some_TextChanged);
//
// dateReleasedRadioButton
//
this->dateReleasedRadioButton->AutoSize = true;
this->dateReleasedRadioButton->BackColor = System::Drawing::Color::Transparent;
this->dateReleasedRadioButton->Location = System::Drawing::Point(254, 66);
this->dateReleasedRadioButton->Name = L"dateReleasedRadioButton";
this->dateReleasedRadioButton->Size = System::Drawing::Size(95, 17);
this->dateReleasedRadioButton->TabIndex = 8;
this->dateReleasedRadioButton->Text = L"Date Released";
this->dateReleasedRadioButton->UseVisualStyleBackColor = false;
this->dateReleasedRadioButton->CheckedChanged += gcnew System::EventHandler(this, &RecordLibrarySearch::RadioButton_CheckedChanged);
//
// noncleanCheckbox
//
this->noncleanCheckbox->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
this->noncleanCheckbox->AutoSize = true;
this->noncleanCheckbox->BackColor = System::Drawing::Color::Transparent;
this->noncleanCheckbox->Location = System::Drawing::Point(383, 89);
this->noncleanCheckbox->Name = L"noncleanCheckbox";
this->noncleanCheckbox->Size = System::Drawing::Size(110, 17);
this->noncleanCheckbox->TabIndex = 10;
this->noncleanCheckbox->Text = L"Non-Clean Tracks";
this->noncleanCheckbox->UseVisualStyleBackColor = false;
this->noncleanCheckbox->CheckedChanged += gcnew System::EventHandler(this, &RecordLibrarySearch::Some_TextChanged);
//
// closeButton
//
this->closeButton->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
this->closeButton->DialogResult = System::Windows::Forms::DialogResult::Cancel;
this->closeButton->FlatStyle = System::Windows::Forms::FlatStyle::Flat;
this->closeButton->Location = System::Drawing::Point(421, 40);
this->closeButton->Name = L"closeButton";
this->closeButton->Size = System::Drawing::Size(75, 23);
this->closeButton->TabIndex = 3;
this->closeButton->Text = L"Close";
this->closeButton->Click += gcnew System::EventHandler(this, &RecordLibrarySearch::closeButton_Click);
//
// SearchButton
//
this->SearchButton->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
this->SearchButton->FlatStyle = System::Windows::Forms::FlatStyle::Flat;
this->SearchButton->Location = System::Drawing::Point(421, 12);
this->SearchButton->Name = L"SearchButton";
this->SearchButton->Size = System::Drawing::Size(75, 23);
this->SearchButton->TabIndex = 2;
this->SearchButton->Text = L"Search";
this->SearchButton->Click += gcnew System::EventHandler(this, &RecordLibrarySearch::SearchButton_Click);
//
// AddToChannel0
//
this->AddToChannel0->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Left));
this->AddToChannel0->BackColor = System::Drawing::Color::Transparent;
this->AddToChannel0->FlatStyle = System::Windows::Forms::FlatStyle::Flat;
this->AddToChannel0->Font = (gcnew System::Drawing::Font(L"Tahoma", 9.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->AddToChannel0->Location = System::Drawing::Point(12, 447);
this->AddToChannel0->Name = L"AddToChannel0";
this->AddToChannel0->Size = System::Drawing::Size(156, 36);
this->AddToChannel0->TabIndex = 12;
this->AddToChannel0->Text = L"Add to Channel 1";
this->AddToChannel0->UseVisualStyleBackColor = false;
this->AddToChannel0->Click += gcnew System::EventHandler(this, &RecordLibrarySearch::AddToChannel_Click);
//
// AddToChannel1
//
this->AddToChannel1->Anchor = System::Windows::Forms::AnchorStyles::Bottom;
this->AddToChannel1->BackColor = System::Drawing::Color::Transparent;
this->AddToChannel1->FlatStyle = System::Windows::Forms::FlatStyle::Flat;
this->AddToChannel1->Font = (gcnew System::Drawing::Font(L"Tahoma", 9.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->AddToChannel1->Location = System::Drawing::Point(177, 447);
this->AddToChannel1->Name = L"AddToChannel1";
this->AddToChannel1->Size = System::Drawing::Size(156, 36);
this->AddToChannel1->TabIndex = 13;
this->AddToChannel1->Text = L"Add to Channel 2";
this->AddToChannel1->UseVisualStyleBackColor = false;
this->AddToChannel1->Click += gcnew System::EventHandler(this, &RecordLibrarySearch::AddToChannel_Click);
//
// AddToChannel2
//
this->AddToChannel2->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Right));
this->AddToChannel2->BackColor = System::Drawing::Color::Transparent;
this->AddToChannel2->FlatStyle = System::Windows::Forms::FlatStyle::Flat;
this->AddToChannel2->Font = (gcnew System::Drawing::Font(L"Tahoma", 9.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->AddToChannel2->Location = System::Drawing::Point(340, 447);
this->AddToChannel2->Name = L"AddToChannel2";
this->AddToChannel2->Size = System::Drawing::Size(156, 36);
this->AddToChannel2->TabIndex = 14;
this->AddToChannel2->Text = L"Add to Channel 3";
this->AddToChannel2->UseVisualStyleBackColor = false;
this->AddToChannel2->Click += gcnew System::EventHandler(this, &RecordLibrarySearch::AddToChannel_Click);
//
// ResultsBox
//
this->ResultsBox->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom)
| System::Windows::Forms::AnchorStyles::Left)
| System::Windows::Forms::AnchorStyles::Right));
this->ResultsBox->Location = System::Drawing::Point(12, 112);
this->ResultsBox->Name = L"ResultsBox";
this->ResultsBox->Size = System::Drawing::Size(484, 329);
this->ResultsBox->TabIndex = 11;
//
// RecordLibrarySearch
//
this->AcceptButton = this->SearchButton;
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->CancelButton = this->closeButton;
this->ClientSize = System::Drawing::Size(508, 514);
this->ControlBox = false;
this->StartPosition = System::Windows::Forms::FormStartPosition::CenterParent;
this->Controls->Add(this->ResultsBox);
this->Controls->Add(this->SearchButton);
this->Controls->Add(this->closeButton);
this->Controls->Add(this->titleRadioButton);
this->Controls->Add(this->AddToChannel2);
this->Controls->Add(this->AddToChannel1);
this->Controls->Add(this->AddToChannel0);
this->Controls->Add(this->statusStrip);
this->Controls->Add(this->TitleBoxLabel);
this->Controls->Add(this->ArtistBoxLabel);
this->Controls->Add(this->Title);
this->Controls->Add(this->Artist);
this->Controls->Add(this->label1);
this->Controls->Add(this->noncleanCheckbox);
this->Controls->Add(this->reverseOrderCheckBox);
this->Controls->Add(this->dateReleasedRadioButton);
this->Controls->Add(this->dateAddedRadioButton);
this->Controls->Add(this->artistRadioButton);
this->Font = (gcnew System::Drawing::Font(L"Tahoma", 8.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->Icon = (cli::safe_cast<System::Drawing::Icon^ >(resources->GetObject(L"$this.Icon")));
this->KeyPreview = true;
this->MaximizeBox = false;
this->MinimizeBox = false;
this->MinimumSize = System::Drawing::Size(516, 309);
this->Name = L"RecordLibrarySearch";
this->ShowInTaskbar = false;
this->SizeGripStyle = System::Windows::Forms::SizeGripStyle::Hide;
this->StartPosition = System::Windows::Forms::FormStartPosition::CenterParent;
this->Text = L"Record Library Search";
this->KeyDown += gcnew System::Windows::Forms::KeyEventHandler(this, &RecordLibrarySearch::RecordLibrarySearch_KeyDown);
this->statusStrip->ResumeLayout(false);
this->statusStrip->PerformLayout();
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
};
}
| 49.802151
| 181
| 0.715433
|
[
"object"
] |
9f64124a8526edb8698cd9a9dac24b98f9d68e5f
| 1,421
|
h
|
C
|
src/operator/contrib/farthest_point_sampling-inl.h
|
xudong-sun/mxnet
|
fe42d30d5885dd576cb871fd70594c53efce9b42
|
[
"Apache-2.0"
] | 31
|
2016-04-29T09:13:44.000Z
|
2021-02-16T21:27:00.000Z
|
src/operator/contrib/farthest_point_sampling-inl.h
|
xudong-sun/mxnet
|
fe42d30d5885dd576cb871fd70594c53efce9b42
|
[
"Apache-2.0"
] | 4
|
2016-04-25T13:01:30.000Z
|
2017-07-31T10:18:17.000Z
|
src/operator/contrib/farthest_point_sampling-inl.h
|
xudong-sun/mxnet
|
fe42d30d5885dd576cb871fd70594c53efce9b42
|
[
"Apache-2.0"
] | 47
|
2016-04-19T22:46:09.000Z
|
2020-09-30T08:09:16.000Z
|
/*!
* Copyright (c) 2017 by Contributors
* \file point_pooling-inl.h
* \brief farthest point sampling
* \author Feng Wang
*/
#ifndef MXNET_OPERATOR_CONTRIB_FARTHEST_POINT_SAMPLING_INL_H_
#define MXNET_OPERATOR_CONTRIB_FARTHEST_POINT_SAMPLING_INL_H_
#include <vector>
#include <utility>
#include "../mshadow_op.h"
#include "../tensor/init_op.h"
#include "../operator_common.h"
namespace mxnet {
typedef std::vector<mxnet::TShape> ShapeVector;
namespace op {
// Declare enumeration of input order to make code more intuitive.
// These enums are only visible within this header
namespace farthest_point_sampling {
enum FarthestPointSamplingOpInputs { kData };
enum FarthestPointSamplingOpOutputs { kOut, kMinDist };
} // namespace farthest_point_sampling
struct FarthestPointSamplingParam
: public dmlc::Parameter<FarthestPointSamplingParam> {
int npoints;
DMLC_DECLARE_PARAMETER(FarthestPointSamplingParam) {
DMLC_DECLARE_FIELD(npoints).describe("Number of keypoints.");
}
};
template <typename xpu>
void FarthestPointSamplingForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& in_data,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& out_data);
}
}
#endif // MXNET_OPERATOR_CONTRIB_FARTHEST_POINT_SAMPLING_INL_H_
| 31.577778
| 70
| 0.712878
|
[
"vector"
] |
9f6c4362e79d10a757109935eea7671e2781798e
| 11,859
|
c
|
C
|
src/CaSearch2.c
|
noboruatkek/SAD
|
3881a190af8903537774c57b56963ffc94cfc039
|
[
"BSD-3-Clause"
] | 11
|
2019-04-01T15:54:57.000Z
|
2022-03-09T16:47:20.000Z
|
src/CaSearch2.c
|
noboruatkek/SAD
|
3881a190af8903537774c57b56963ffc94cfc039
|
[
"BSD-3-Clause"
] | null | null | null |
src/CaSearch2.c
|
noboruatkek/SAD
|
3881a190af8903537774c57b56963ffc94cfc039
|
[
"BSD-3-Clause"
] | 9
|
2017-03-15T08:52:45.000Z
|
2021-07-19T08:06:40.000Z
|
#include <sim/sad_tcltk.h>
#include <sim/sad_api.h>
#include <sim/TFCODE.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <inttypes.h>
#include <cadef.h>
#define MAXCOMLEN 1024
#define CA_PEND_IO_TIME 0.0001
static int bDebug = 0;
static int bInCaPend = 0;
static real8 *cavalue_buffer = NULL;
static size_t cavalue_bufsz = 0;
static void cavalue_alloc(size_t n0) {
const size_t page_size = 4096 / sizeof(real8);
real8 *ptr;
size_t n;
if(n0 > cavalue_bufsz) {
if(n0 > page_size) {
n = page_size * ((n0 + 2048) / page_size + 1);
} else {
n = 1;
while(n0 > n) n *= 2;
}
ptr = realloc(cavalue_buffer, sizeof(real8) * n);
if(ptr == NULL) {
fprintf(stderr, "cavalue: Cannot allocate memory(cavalue_buffer)\n");
exit(1);
}
cavalue_buffer = ptr;
cavalue_bufsz = n;
}
}
void cavalue(struct event_handler_args arg)
{
struct dbr_time_double *p = (struct dbr_time_double *)arg.dbr;
int n = arg.count;
real8 chid = pointer2double(arg.chid);
integer4 st = p->status, sev = p->severity;
integer4 type = arg.type - DBR_TIME_STRING;
real8 x,t = p->stamp.secPastEpoch + p->stamp.nsec * 1e-9;
integer4 length, mode = -1;
integer8 *i8ptr = NULL;
int i;
dbr_string_t *sv;
dbr_char_t *cv;
dbr_short_t *shv;
dbr_long_t *lv;
dbr_float_t *fv;
if(bDebug) {
printf("cavalue[%s,%d]: %d\n", ca_name(arg.chid), n, ca_state(arg.chid));
fflush(stdout);
}
switch(arg.type) {
case DBR_TIME_STRING:
if(bDebug) printf("string[%s]\n",
((struct dbr_time_string *)arg.dbr)->value);
sv = &(((struct dbr_time_string *)arg.dbr)->value);
cavalue_alloc(n);
i8ptr = (integer8 *)cavalue_buffer;
for(i = 0; i < n; i++) {
length = 0;
while(length < sizeof(dbr_string_t) && sv[i][length] != '\0')
length += 1;
i8ptr[i] = ktfstring + ktsalocb_(&mode, sv[i], &length, length);
}
break;
case DBR_TIME_CHAR:
if(bDebug) printf("char[%c]\n",
((struct dbr_time_char *)arg.dbr)->value);
cv = &(((struct dbr_time_char *)(arg.dbr))->value);
cavalue_alloc(n); i8ptr = (integer8 *)cavalue_buffer;
for(i = 0; i < n; i++) {x=(real8) cv[i];i8ptr[i] = kfromr(x);}
break;
case DBR_TIME_SHORT:
if(bDebug) printf("short[%" PRId16 "]\n",
((struct dbr_time_short *)arg.dbr)->value);
shv = &(((struct dbr_time_short *)(arg.dbr))->value);
cavalue_alloc(n); i8ptr = (integer8 *)cavalue_buffer;
for(i = 0; i < n; i++) {x=(real8) shv[i];i8ptr[i] = kfromr(x);}
break;
case DBR_TIME_LONG:
if(bDebug) printf("long[%" PRId32 "]\n",
((struct dbr_time_long *)arg.dbr)->value);
lv = &(((struct dbr_time_long *)(arg.dbr))->value);
cavalue_alloc(n); i8ptr = (integer8 *)cavalue_buffer;
for(i = 0; i < n; i++) {x=(real8) lv[i];i8ptr[i] = kfromr(x);}
break;
case DBR_TIME_FLOAT:
if(bDebug) printf("float[%f]\n",
((struct dbr_time_float *)arg.dbr)->value);
fv = &(((struct dbr_time_float *)(arg.dbr))->value);
cavalue_alloc(n); i8ptr = (integer8 *)cavalue_buffer;
for(i = 0; i < n; i++) {x=(real8)fv[i];i8ptr[i] = kfromr(x);}
break;
case DBR_TIME_DOUBLE:
if(bDebug) printf("double[%22.16le]\n",
((struct dbr_time_double *)arg.dbr)->value);
i8ptr = &kfromr(((struct dbr_time_double *)(arg.dbr))->value);
break;
default:
printf("cavalue: unknown type: %ld\n", arg.type);
return;
}
tfepicsvaluecb_(&chid, &st, &sev, &t, &type, &n, i8ptr);
/* tfcavaluecb_(&chid, &st, &sev, &t, &type, &n, i4prt, r8ptr); */
}
void cachange(struct connection_handler_args arg)
{
real8 chan_id;
integer4 status;
chan_id = pointer2double(arg.chid);
status = ca_state(arg.chid);
if(bDebug) printf("cachange: ID=%p[%s] %d\n",
(void*)arg.chid, ca_name(arg.chid), status);
tfepicsconstatcb_(&chan_id, &status);
}
/* Oide Change 5/8/1999
void cachange(struct connection_handler_args arg)
{
integer4 len, itx, iax, irtc;
real8 vx;
int status = ca_state(arg.chid);
char str[MAXCOMLEN];
size_t full_len;
if(bDebug) printf("cachange: ID=%p[%s]: %d\n",
arg.chid, ca_name(arg.chid), status);
full_len = snprintf(str, MAXCOMLEN, "EPICS$ConStatCB[%td,%d]",
(ptrdiff_t)arg.chid, status);
len = strlen(str);
if(full_len > len) {
fprintf(stderr, "cachange[%s]: "
"SAD evaluation buffer overflowed by %dbytes. "
"Change event is discarded\n",
ca_name(arg.chid), full_len - len);
fflush(stderr);
} else
tfevalb_(str, &len, &itx, &iax, &vx, &irtc, MAXCOMLEN);
}
*/
void caputcb(struct event_handler_args arg)
{
integer8 kx;
integer4 len, irtc;
char str[MAXCOMLEN];
size_t full_len;
if(bDebug) printf("caputcb: ID=%p[%s]\n",
(void*)arg.chid, ca_name(arg.chid));
full_len = snprintf(str, MAXCOMLEN, "EPICS$PutCB[%td]", (ptrdiff_t)arg.chid);
len = strlen(str);
if(full_len > len) {
fprintf(stderr, "caputcb[%s]: "
"SAD evaluation buffer overflowed by %zubytes. "
"Callback event is discarded\n",
ca_name(arg.chid), full_len - len);
fflush(stderr);
} else
tfevalb_(str, len, &kx, &irtc);
}
integer ecaaddarrayevent_(real8 *chd,
real8 *evd, integer4 *vtype, integer4 *evt)
{
int status,vt;
chid chan_id = (chid)double2pointer(*chd);
evid event_id;
chtype cht;
if (*vtype>=0)
vt = *vtype;
else
vt = ca_field_type(chan_id);
#ifndef NDEBUG
/* fprintf(stderr, "%s : field type id %d",,vt);*/
#endif
switch(vt) {
case DBF_STRING:
cht = DBR_TIME_STRING;
break;
case DBF_CHAR:
cht = DBR_TIME_CHAR;
break;
case DBF_SHORT:
cht = DBR_TIME_SHORT;
break;
case DBF_LONG:
case DBF_ENUM:
cht = DBR_TIME_LONG;
break;
case DBF_FLOAT:
cht = DBR_TIME_FLOAT;
break;
case DBF_DOUBLE:
cht = DBR_TIME_DOUBLE;
break;
default:
printf("ecaaddarrayevent: unknown ca field type: %d\n",ca_field_type(chan_id));
/*cht = DBR_TIME_DOUBLE;*/
return -1;
}
status = ca_add_masked_array_event(cht, 0, chan_id, cavalue, NULL,
0, 0, 0, &event_id, *evt);
SEVCHK(status, "error in ca_add_masked_array_event");
*evd = pointer2double(event_id);
return status;
}
integer ecasearchandconnect_(const char *chname, real8 *chd, void *pilist)
{
chid chan_id;
int status;
if (bDebug)
printf("casearch: [%s]\n", chname);
status = ca_search_and_connect(chname, &chan_id, cachange, pilist);
SEVCHK(status,"error in ca_search");
if (status!=ECA_NORMAL) {
*chd = 0;
return status;
}
*chd = pointer2double(chan_id);
return status;
}
void ecaclearchannel_(real8 *chd)
{
chid chan_id = (chid)double2pointer(*chd);
int status;
status = ca_clear_channel(chan_id);
SEVCHK(status, "ca_clear_channel");
}
void ecaclearevent_(real8 *evd)
{
evid event_id = (evid)double2pointer(*evd);
int status;
status = ca_clear_event(event_id);
SEVCHK(status, "ca_clear_event");
}
void ecaput_(real8 *ch_id, logical4 *cb,
integer4 *mode, integer4 *nc, void *val, integer4 *irtc)
{
chid chan_id = (chid)double2pointer(*ch_id);
integer8 kx, *ia;
integer4 i, len;
void *ptr = NULL;
dbr_string_t *sv = NULL;
dbr_double_t *dv = NULL;
int type, status, size = *nc > 0 ? *nc : 1;
switch(*mode) {
case 0: /* STRING */
type = DBR_STRING;
break;
case 1: /* DOUBLE */
type = DBR_DOUBLE;
break;
default:
type = DBR_DOUBLE;
break;
}
switch(type) {
case DBR_DOUBLE:
if(*nc > 0) { /* Vector API */
dv = malloc(sizeof(dbr_double_t) * *nc);
if(dv != NULL) {
*irtc = 0;
ia = (integer8 *)val;
for(i = 1; i <= *nc; i++) {
kx = klist(*ia + i);
if(ktfnonrealq(kx)) {
*irtc = -1;
break;
}
dv[i - 1] = rfromk(kx);
}
}
} else { /* Scalar API */
dv = malloc(sizeof(dbr_double_t));
if(dv != NULL) {
*irtc = 0;
*dv = *((real8 *)val);
}
}
ptr = dv;
break;
case DBR_STRING:
if(*nc > 0) { /* Vector API */
sv = malloc(sizeof(dbr_string_t) * *nc + 1);
if(sv != NULL) {
*irtc = 0;
ia = (integer8 *)val;
for(i = 1; i <= *nc; i++) {
kx = klist(*ia + i);
if(ktfnonstringq(kx)) {
*irtc = -1;
break;
}
tfgetstr_((character)sv[i - 1], sizeof(dbr_string_t), &kx, &len);
((char *)sv[i - 1])[len] = '\0';
}
}
} else { /* Scalar API */
sv = malloc(sizeof(dbr_string_t) + 1);
if(sv != NULL) {
*irtc = 0;
ia = (integer8 *)val;
tfgetstr_((character)sv[0], sizeof(dbr_string_t), ia, &len);
((char *)sv[0])[len] = '\0';
}
}
ptr = sv;
break;
default:
ptr = NULL;
*irtc = -1;
}
/* Check channel connection if without callback mode */
if(*irtc == 0 && !(*cb) && ca_state(chan_id) != cs_conn) *irtc = 1;
if(*irtc == 0) {
if(bDebug) {
printf("ecaput%s[%d]: ", *cb ? "cb" : "", size);
switch(type) {
case DBR_DOUBLE:
printf("%lf\n", dv[0]); break;
case DBR_STRING:
printf("%s\n", sv[0]); break;
default:
printf("Unkown type[%d]\n", type);
}
}
if(*cb)
status = ca_array_put_callback(type, size, chan_id, ptr, caputcb, NULL);
else
status = ca_array_put(type, size, chan_id, ptr);
SEVCHK(status, "error in ca_array_put");
status = ca_flush_io();
SEVCHK(status, "ca_flush_io");
}
if(ptr != NULL) free(ptr);
}
integer ecapendio_(real4 *timeout)
{
int status;
if (bDebug)
printf("pend_io\n");
if (bInCaPend) {
fprintf(stderr, "CaSad: try to call ca_pend_io in ca_pend_* !!");
return 0;
}
bInCaPend = 1;
status = ca_pend_io(*timeout);
bInCaPend = 0;
SEVCHK(status,"ca_pend_io");
return status;
}
integer ecapendevent_(real4 *timeout)
{
int status;
if (bDebug)
printf("pend_event\n");
if (bInCaPend) {
fprintf(stderr, "CaSad: try to call ca_pend_event in ca_pend_* !!");
return 0;
}
bInCaPend = 1;
status = ca_pend_event(*timeout);
bInCaPend = 0;
SEVCHK(status,"ca_pend_event");
return status;
}
integer ecaflushio_()
{
int status;
status = ca_flush_io();
SEVCHK(status,"ca_flush_io");
return status;
}
static void ecafdcallback(void *clientData, int mask)
{
if (bDebug)
printf("pend_event_callback 1\n");
if (bInCaPend) {
fprintf(stderr, "CaSad: try to call ca_pend_event in ca_pend_* !!");
return;
}
bInCaPend = 1;
ca_pend_event(CA_PEND_IO_TIME);
bInCaPend = 0;
if (bDebug)
printf("pend_event_callback 2\n");
}
static void ecafdregister(userarg, fd, opened)
void *userarg;
int fd,opened;
{
if (bDebug)
printf("ecafdregister %d %d %p\n",fd,opened,userarg);
if(opened)
sadTk_CreateFileHandler(fd, SAD_TK_READABLE | SAD_TK_EXCEPTION,
ecafdcallback, userarg);
else
sadTk_DeleteFileHandler(fd);
}
integer ecainit_()
{
int status;
if (bDebug)
printf("ecainit\n");
status = ca_task_initialize();
SEVCHK(status,"ca_task_initialize");
status = ca_add_fd_registration(ecafdregister, NULL);
SEVCHK(status,"ca_add_fd_registration");
return status;
}
void ecahostname_(integer8 *kx)
{
chid chan_id = (chid)double2pointer(*kx);
integer4 length, mode = -1;
char *hostname;
hostname = (char *)ca_host_name(chan_id);
if(hostname != NULL) {
*kx = ktfstring + ktsalocb_(&mode, hostname, &length, length);
} else {
*kx = ktfoper + mtfnull;
}
}
integer ecafieldtype_(real8 *chd, integer4 *type)
{
chid chan_id = (chid)double2pointer(*chd);
*type = ca_field_type(chan_id);
return 0;
}
integer ecaelementcount_(real8 *chd, integer4 *count)
{
chid chan_id = (chid)double2pointer(*chd);
*count = ca_element_count(chan_id);
return 0;
}
integer4 ecadebugprint_(integer4 *bNewDebug)
{
integer4 bOldDebug = bDebug;
bDebug = *bNewDebug;
return bOldDebug;
}
| 23.116959
| 83
| 0.616915
|
[
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.