Dataset Viewer (First 5GB)
Auto-converted to Parquet
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" ]
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
17